Merge branch 'dev' into feature/bugfix

Conflicts resolved in:
- src/app/clients/clients-view/ckyc-tab/ckyc-tab.component.html
- src/app/clients/clients-view/ckyc-tab/ckyc-tab.component.ts

Kept dev's CKYC architecture (upload dialog, real per-artefact endpoints)
and layered feature/bugfix's fixes on top: upload file validation,
missing-file badge, silent preview download, and image/PDF view button.
Also includes the CKYC "Image of Client" upload-state fix and the
client-change state-leak fix in the same component.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-16 16:55:32 +05:30
co-authored by Claude Sonnet 5
105 changed files with 7140 additions and 1902 deletions
@@ -969,6 +969,11 @@
createClientForm.get('alternateMobileNo')?.touched
) {
<mat-error>Enter valid 10-digit number (starts with 6-9)</mat-error>
} @else if (
createClientForm.get('alternateMobileNo')?.hasError('sameAsMobile') &&
createClientForm.get('alternateMobileNo')?.touched
) {
<mat-error>Alternate number can't be the same as Mobile No</mat-error>
}
</mat-form-field>
@@ -979,7 +984,11 @@
color="primary"
type="button"
class="verify-btn"
[disabled]="readOnly || createClientForm.get('alternateMobileNo')?.value?.length !== 10"
[disabled]="
readOnly ||
createClientForm.get('alternateMobileNo')?.value?.length !== 10 ||
createClientForm.get('alternateMobileNo')?.hasError('sameAsMobile')
"
(click)="verifyAlternateDIP()"
>
<fa-icon icon="shield-alt" class="m-r-10"></fa-icon>
@@ -25,7 +25,10 @@ import {
UntypedFormGroup,
Validators,
UntypedFormControl,
ReactiveFormsModule
ReactiveFormsModule,
ValidatorFn,
AbstractControl,
ValidationErrors
} from '@angular/forms';
import { Subject, Subscription, merge } from 'rxjs';
import { filter, switchMap, takeUntil } from 'rxjs/operators';
@@ -922,6 +925,16 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
}
}
/** Alternate Mobile No must differ from Mobile No — the same number saved in both fields is
* meaningless (there's no second contact route) and the DIP checks would just repeat. */
private notSameAsMobileNoValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
const mobileNo = control.parent?.get('mobileNo')?.value;
return value && mobileNo && value === mobileNo ? { sameAsMobile: true } : null;
};
}
/**
* Creates the client form.
*/
@@ -961,7 +974,8 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
'',
[
Validators.pattern(/^[6-9]\d{9}$/),
Validators.maxLength(10)
Validators.maxLength(10),
this.notSameAsMobileNoValidator()
]
],
emailAddress: [
@@ -1334,6 +1348,10 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
// invalid) and its own reset never had a chance to run.
this.mobileOtpVerified = false;
this.mobileNewOtpId = null;
// Alternate Mobile No's "not same as Mobile No" validator reads mobileNo's current
// value, so re-run it here too — otherwise fixing mobileNo away from a clash leaves
// the alternate field's error stuck until the user also edits that field.
this.createClientForm.get('alternateMobileNo')?.updateValueAndValidity({ emitEvent: false });
});
this.createClientForm
@@ -221,6 +221,22 @@
<mat-datepicker #addrIssueDatePicker></mat-datepicker>
</mat-form-field>
}
<mat-form-field appearance="outline" class="addr-ff">
<mat-label>Expiry date (optional)</mat-label>
<span matPrefix class="addr-prefix"><mat-icon>event_busy</mat-icon></span>
<input
matInput
[matDatepicker]="addrExpiryDatePicker"
formControlName="expiryDate"
[readonly]="readOnly || isAddressProofLinkedToKyc"
/>
<mat-datepicker-toggle
matSuffix
[for]="addrExpiryDatePicker"
[disabled]="readOnly || isAddressProofLinkedToKyc"
></mat-datepicker-toggle>
<mat-datepicker #addrExpiryDatePicker></mat-datepicker>
</mat-form-field>
</div>
<div class="addr-upload-grid" [class.addr-upload-grid--two]="selectedAddrProof.sides === 2">
@@ -238,14 +254,18 @@
@if (existingAddressProofDocuments.length > 0 && !addrFiles.front && readOnly) {
<div class="addr-dropzone addr-dropzone--has addr-dropzone--locked">
<div class="addr-dropzone__existing">
@if (addrMergedPreview) {
<img [src]="addrMergedPreview" alt="Saved address proof" class="addr-dropzone__thumb" />
@if (existingAddrFrontSlotPreview) {
<img
[src]="existingAddrFrontSlotPreview"
alt="Saved address proof"
class="addr-dropzone__thumb"
/>
} @else {
<mat-icon class="addr-dropzone__doc-ic">description</mat-icon>
}
<div class="addr-dropzone__existing-meta">
<span class="addr-dropzone__existing-name">
{{ existingAddressProofDocuments[0].fileName || existingAddressProofDocuments[0].name }}
{{ existingAddrFrontSlotName }}
</span>
<button type="button" class="addr-dropzone__view" (click)="viewExistingAddressProof()">
<mat-icon>visibility</mat-icon>
@@ -278,14 +298,18 @@
<!-- Edit mode WITH existing doc — let the user view it OR
click anywhere to replace. -->
<div class="addr-dropzone__existing">
@if (addrMergedPreview) {
<img [src]="addrMergedPreview" alt="Saved address proof" class="addr-dropzone__thumb" />
@if (existingAddrFrontSlotPreview) {
<img
[src]="existingAddrFrontSlotPreview"
alt="Saved address proof"
class="addr-dropzone__thumb"
/>
} @else {
<mat-icon class="addr-dropzone__doc-ic">description</mat-icon>
}
<div class="addr-dropzone__existing-meta">
<span class="addr-dropzone__existing-name">
{{ existingAddressProofDocuments[0].fileName || existingAddressProofDocuments[0].name }}
{{ existingAddrFrontSlotName }}
</span>
<div class="addr-dropzone__existing-actions">
<button
@@ -327,14 +351,18 @@
@if (existingAddressProofDocuments.length > 0 && !addrFiles.back && readOnly) {
<div class="addr-dropzone addr-dropzone--has addr-dropzone--locked">
<div class="addr-dropzone__existing">
@if (addrMergedPreview) {
<img [src]="addrMergedPreview" alt="Saved address proof" class="addr-dropzone__thumb" />
@if (existingAddrBackSlotPreview) {
<img
[src]="existingAddrBackSlotPreview"
alt="Saved address proof"
class="addr-dropzone__thumb"
/>
} @else {
<mat-icon class="addr-dropzone__doc-ic">description</mat-icon>
}
<div class="addr-dropzone__existing-meta">
<span class="addr-dropzone__existing-name">
{{ existingAddressProofDocuments[0].fileName || existingAddressProofDocuments[0].name }}
{{ existingAddrBackSlotName }}
</span>
<button type="button" class="addr-dropzone__view" (click)="viewExistingAddressProof()">
<mat-icon>visibility</mat-icon>
@@ -367,14 +395,18 @@
<!-- Edit mode WITH existing combined doc — same view + replace
pattern as the front slot, anchored to the saved file. -->
<div class="addr-dropzone__existing">
@if (addrMergedPreview) {
<img [src]="addrMergedPreview" alt="Saved address proof" class="addr-dropzone__thumb" />
@if (existingAddrBackSlotPreview) {
<img
[src]="existingAddrBackSlotPreview"
alt="Saved address proof"
class="addr-dropzone__thumb"
/>
} @else {
<mat-icon class="addr-dropzone__doc-ic">description</mat-icon>
}
<div class="addr-dropzone__existing-meta">
<span class="addr-dropzone__existing-name">
{{ existingAddressProofDocuments[0].fileName || existingAddressProofDocuments[0].name }}
{{ existingAddrBackSlotName }}
</span>
<div class="addr-dropzone__existing-actions">
<button
@@ -102,7 +102,8 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
Validators.required
],
documentKey: [''],
issueDate: ['']
issueDate: [''],
expiryDate: ['']
});
currentForm: UntypedFormGroup = this.fb.group({
@@ -222,6 +223,12 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
size: number;
previewUrl: string | null;
}[] = [];
/** Set only when the saved documents are separately-uploaded "<Proof> — Front"/"— Back"
* files (the CKYC tab / client-kyc-step convention) rather than this component's own single
* merged-PNG upload — lets the two slots show their own file instead of both showing
* whichever one happened to be first. */
private existingAddrFrontPreview: string | null = null;
private existingAddrBackPreview: string | null = null;
residenceTypes = [
'Owned',
@@ -307,11 +314,10 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
this.existingAddressProofDocuments = [];
if (this.existingKycDocSides.front) this.existingAddressProofDocuments.push(this.existingKycDocSides.front);
if (this.existingKycDocSides.back) this.existingAddressProofDocuments.push(this.existingKycDocSides.back);
if (this.existingKycDocSides.front?.previewUrl) {
this.addrMergedPreview = this.existingKycDocSides.front.previewUrl;
} else if (this.existingKycDocSides.back?.previewUrl) {
this.addrMergedPreview = this.existingKycDocSides.back.previewUrl;
}
// These already carry their own per-side preview from the KYC step's own mapping —
// keep the two slots distinct rather than collapsing them into one shared preview.
this.existingAddrFrontPreview = this.existingKycDocSides.front?.previewUrl || null;
this.existingAddrBackPreview = this.existingKycDocSides.back?.previewUrl || null;
this.existingAddressProofIdentifierId = this.existingKycIdentifierId;
}
} else if (this.isAddressProofLinkedToKyc) {
@@ -327,6 +333,8 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
this.currentForm.patchValue({ documentKey: '', issueDate: null });
this.addrFiles = { front: null, back: null };
this.addrMergedPreview = null;
this.existingAddrFrontPreview = null;
this.existingAddrBackPreview = null;
}
/**
@@ -356,6 +364,8 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
this.addrFiles = { front: null, back: null };
this.addrMergedFile = null;
this.addrMergedPreview = null;
this.existingAddrFrontPreview = null;
this.existingAddrBackPreview = null;
this.existingAddressProofIdentifierId = null;
this.existingAddressProofDocuments = [];
this.addressLoaded = false;
@@ -488,6 +498,7 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
proofId: any;
documentKey: string;
issueDate: string;
expiryDate: string;
files: { slot: string; file: File }[];
} {
const files: { slot: string; file: File }[] = [];
@@ -500,11 +511,13 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
}
}
const rawIssueDate = this.permanentForm.get('issueDate')?.value;
const rawExpiryDate = this.permanentForm.get('expiryDate')?.value;
return {
proof: this.selectedAddrProof,
proofId: this.permanentForm.get('proofId')?.value || '',
documentKey: this.permanentForm.get('documentKey')?.value || '',
issueDate: rawIssueDate ? this.dates.getDate(rawIssueDate) : '',
expiryDate: rawExpiryDate ? this.dates.getDate(rawExpiryDate) : '',
files
};
}
@@ -644,7 +657,14 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
this.tryLinkKycData();
return;
}
const identifier = identifiers.find((i: any) => this.findMatchingProof(i?.documentType?.name));
// Aadhaar, Passport, Voter ID and Driving Licence are valid OVDs for both this slot and
// the separate identity-proof one (client-kyc-step) — when a client has two such
// dual-purpose identifiers, that step always runs first and picks the OLDEST match (the
// one on file first, historically the identity proof), so picking the NEWEST match here
// lands this step on the other row without the two steps needing to coordinate.
const identifier = [...identifiers]
.sort((a: any, b: any) => (b?.id ?? 0) - (a?.id ?? 0))
.find((i: any) => this.findMatchingProof(i?.documentType?.name));
if (!identifier?.id) {
this.existingAddressProofCheckComplete = true;
this.tryLinkKycData();
@@ -664,14 +684,19 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
proofId: matchedProof.id,
documentKey: identifier.documentKey || ''
});
// The description carries `Issue date: yyyy-MM-dd` when set on create (see
// create-client.saveAddressProof) — pull it out so the form's issueDate field
// shows what was previously entered.
// The description carries "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" when set on
// create (see create-client.saveAddressProof / CkycTabComponent) — pull both out so the
// form's date fields show what was previously entered. Each match stops at the next
// comma so adding expiry after issue doesn't get swallowed into the issue-date capture.
const desc: string = identifier.description || '';
const issueMatch = desc.match(/Issue date:\s*(.+)$/i);
const issueMatch = desc.match(/Issue date:\s*([^,|]+)/i);
const expiryMatch = desc.match(/Expiry date:\s*([^,|]+)/i);
if (issueMatch) {
this.permanentForm.patchValue({ issueDate: this.dates.parseDate(issueMatch[1].trim()) });
}
if (expiryMatch) {
this.permanentForm.patchValue({ expiryDate: this.dates.parseDate(expiryMatch[1].trim()) });
}
}
this.clientsService.getClientIdentificationDocuments(this.existingAddressProofIdentifierId).subscribe({
@@ -685,6 +710,29 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
size: d.size || 0,
previewUrl: null as string | null
}));
const sideOf = (d: { name: string; fileName: string }): 'front' | 'back' | null => {
const text = `${d.name || ''} ${d.fileName || ''}`.toLowerCase();
if (text.includes('back')) return 'back';
if (text.includes('front')) return 'front';
return null;
};
// Changing the document type (e.g. Aadhaar -> Passport) keeps the old front/back
// files attached to this same identifier rather than removing them, so there can be
// more than one "— Front"/"— Back" pair on file — sort newest-first before matching
// or this would keep showing the very first scan ever uploaded here.
const byNewest = [...this.existingAddressProofDocuments].sort((a, b) => Number(b.id) - Number(a.id));
const frontDoc = byNewest.find((d) => sideOf(d) === 'front');
const backDoc = byNewest.find((d) => sideOf(d) === 'back');
if (frontDoc || backDoc) {
// Separately-uploaded front/back — each side gets its own preview.
if (frontDoc) this.downloadAddrSidePreview(frontDoc, 'front');
if (backDoc) this.downloadAddrSidePreview(backDoc, 'back');
return;
}
// Legacy/single-file case: one combined (or unlabelled) document covers both slots.
const firstImage = this.existingAddressProofDocuments.find((d) =>
(d.type || '').toLowerCase().startsWith('image/')
);
@@ -715,6 +763,50 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
});
}
private downloadAddrSidePreview(doc: { id: string; fileName: string; name: string }, slot: 'front' | 'back'): void {
this.clientsService.downloadClientIdentificationDocument(this.existingAddressProofIdentifierId!, doc.id).subscribe({
next: async (blob: any) => {
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const url = 'data:' + blob.type + ';base64,' + btoa(binary);
if (slot === 'front') this.existingAddrFrontPreview = url;
else this.existingAddrBackPreview = url;
},
error: () => {}
});
}
/** What the Front slot should show: its own saved file when front/back were uploaded
* separately, falling back to the single combined preview for legacy/merged uploads. */
get existingAddrFrontSlotPreview(): string | null {
return this.existingAddrFrontPreview || this.addrMergedPreview;
}
get existingAddrFrontSlotName(): string {
const front = this.existingAddressProofDocuments.find((d) =>
`${d.name} ${d.fileName}`.toLowerCase().includes('front')
);
const doc = front || this.existingAddressProofDocuments[0];
return doc?.fileName || doc?.name || '';
}
/** Same as above, for the Back slot. */
get existingAddrBackSlotPreview(): string | null {
return this.existingAddrBackPreview || this.addrMergedPreview;
}
get existingAddrBackSlotName(): string {
const back = this.existingAddressProofDocuments.find((d) =>
`${d.name} ${d.fileName}`.toLowerCase().includes('back')
);
const doc = back || this.existingAddressProofDocuments[0];
return doc?.fileName || doc?.name || '';
}
onPinInput(tab: string) {
const form = this.getForm(tab);
const pin = form.get('pinCode')?.value?.replace(/\D/g, '') || '';
@@ -7,6 +7,7 @@
*/
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges, inject } from '@angular/core';
import { forkJoin, catchError, of } from 'rxjs';
import { UntypedFormBuilder, UntypedFormGroup, Validators, FormsModule } from '@angular/forms';
import {
MatDialog,
@@ -1266,8 +1267,14 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
this.loadExistingKycIdentifier(data?.kycDocumentName);
},
error: () => {
// No existing KYC — that's fine for new clients
// No m_client_kyc row yet (e.g. CERSAI sync hasn't run) — that's fine, but the client
// can still have a KYC-type identifier already on file (uploaded via the CKYC tab,
// which writes straight to client_identifier and never touches this record). Look it
// up the same way the success branch does, just without a document-name hint.
this.kycLoaded = true;
this.loadExistingPhoto();
this.loadExistingSignature();
this.loadExistingKycIdentifier(undefined);
}
});
}
@@ -1283,8 +1290,13 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
*/
private loadExistingKycIdentifier(kycDocumentName: string | undefined): void {
if (!this.clientId) return;
this.clientsService.getClientIdentifiers(this.clientId).subscribe({
next: (identifiers: any[]) => {
forkJoin({
identifiers: this.clientsService.getClientIdentifiers(this.clientId),
// Only needed to spot the dual-purpose OVD types (Aadhaar/Passport/Voter ID/Driving
// Licence) below — a failure here just means that disambiguation step is skipped.
proofTypes: this.clientsService.getKycProofTypes().pipe(catchError(() => of({ addressProofs: [] })))
}).subscribe({
next: ({ identifiers, proofTypes }: { identifiers: any[]; proofTypes: any }) => {
if (!identifiers || identifiers.length === 0) return;
const cleanStr = (s: string) => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '');
const isKycType = (i: any) => {
@@ -1297,6 +1309,13 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
})
);
};
// Aadhaar, Passport, Voter ID and Driving Licence are valid OVDs for BOTH this slot and
// the separate address-proof one (client-india-address-step) — a client with, say, a PAN
// identity proof and an Aadhaar address proof has two client_identifier rows that both
// pass isKycType. Without a name to go on, prefer whichever candidate is NOT also an
// address-proof type, so this slot doesn't grab the other step's file.
const addressTypeNames = new Set<string>((proofTypes?.addressProofs || []).map((p: any) => cleanStr(p?.name)));
const isAddressType = (i: any) => addressTypeNames.has(cleanStr(i?.documentType?.name));
// Re-uploading a KYC document creates a new identifier row rather than updating the
// old one in place (same pattern as OVD identifiers), so sort newest-first before
// picking — otherwise a repeat upload of the same document type would keep showing
@@ -1311,7 +1330,15 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
return name === kName || name.includes(kName) || kName.includes(name);
})
: null;
const identifier = match || sorted.find(isKycType);
// Last resort, when EVERY kyc-type candidate is also address-eligible (e.g. a client
// whose identity proof and address proof are both Aadhaar/Passport/Voter ID/Driving
// Licence): this stepper always runs before the address step in both the create and
// edit wizards, so the identity proof is the one that was on file first — pick the
// OLDEST match here, and the address step (client-india-address-step) picks the NEWEST
// among ITS own address-eligible candidates, so the two steps land on different rows
// without needing to coordinate at runtime.
const identifier =
match || sorted.find((i) => isKycType(i) && !isAddressType(i)) || [...sorted].reverse().find(isKycType);
if (!identifier?.id) return;
this.existingKycIdentifierId = identifier.id.toString();
@@ -1327,6 +1354,19 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
kycDocumentNumber: identifier.documentKey || ''
});
}
// Same for issue/expiry date — the CKYC tab (and client-india-address-step, for address
// proof) write "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" into the identifier's
// description; read it back here only to fill in whatever the KYC record itself doesn't
// already have, same as the documentKey backfill above.
const desc: string = identifier?.description || '';
const issueMatch = desc.match(/Issue date:\s*([^,|]+)/i);
const expiryMatch = desc.match(/Expiry date:\s*([^,|]+)/i);
if (issueMatch && !this.kycForm.get('kycDocIssueDate')?.value) {
this.kycForm.patchValue({ kycDocIssueDate: this.parseApiDate(issueMatch[1].trim()) });
}
if (expiryMatch && !this.kycForm.get('kycDocExpiryDate')?.value) {
this.kycForm.patchValue({ kycDocExpiryDate: this.parseApiDate(expiryMatch[1].trim()) });
}
this.clientsService.getClientIdentificationDocuments(this.existingKycIdentifierId).subscribe({
next: (docs: any[]) => {
@@ -187,124 +187,6 @@
}
<div class="ckyc-upload-grid">
<!-- ID Proof Document -->
<mat-card class="ckyc-upload-card">
<mat-card-content>
<div class="ckyc-upload-header">
<mat-icon class="ckyc-upload-icon">badge</mat-icon>
<span>{{ 'labels.inputs.ID Proof Document' | translate }}</span>
</div>
@if (existing.ID_PROOF.present) {
<div class="ckyc-existing">
<div class="ckyc-existing__head">
<fa-icon icon="check-circle" class="ckyc-existing__ok"></fa-icon>
<div>
<strong>Already available</strong>
<span class="ckyc-existing__source">from {{ existing.ID_PROOF.source }}</span>
@if (existing.ID_PROOF.previewUnavailable) {
<span class="ckyc-existing__warn">stored file unavailable</span>
}
</div>
</div>
@if (existing.ID_PROOF.previewUrl && isImage('ID_PROOF')) {
<img [src]="existing.ID_PROOF.previewUrl" alt="ID proof" class="ckyc-existing__thumb" />
}
@if (existing.ID_PROOF.previewUrl) {
<button mat-stroked-button type="button" class="ckyc-existing__view" (click)="openDocument('ID_PROOF')">
<fa-icon icon="eye"></fa-icon>
&nbsp;View document
</button>
}
<div class="ckyc-existing__meta">
<fa-icon icon="file-alt"></fa-icon>
<span>{{ existing.ID_PROOF.name }}</span>
@if (existing.ID_PROOF.documentKey) {
<span class="ckyc-existing__key">{{ existing.ID_PROOF.documentKey }}</span>
}
@if (existing.ID_PROOF.fileCount && existing.ID_PROOF.fileCount > 0) {
<span class="ckyc-existing__count">
{{ existing.ID_PROOF.fileCount }}
{{ existing.ID_PROOF.fileCount === 1 ? 'file' : 'files' }}
</span>
}
</div>
<button
mat-stroked-button
type="button"
class="ckyc-existing__replace"
(click)="toggleReplace('ID_PROOF')"
>
<fa-icon [icon]="existing.ID_PROOF.expanded ? 'times' : 'upload'"></fa-icon>
{{ existing.ID_PROOF.expanded ? 'Cancel replace' : 'Upload new version' }}
</button>
</div>
}
@if (!existing.ID_PROOF.present || existing.ID_PROOF.expanded) {
<p class="ckyc-upload-hint">{{ 'labels.inputs.Accepted formats' | translate }}: PNG, JPEG, JPG, PDF</p>
<div class="ckyc-file-row">
<input
type="file"
#idProofInput
accept=".png,.jpeg,.jpg,.pdf"
(change)="onFileSelect($event, 'ID_PROOF')"
[style.display]="'none'"
/>
<mat-form-field appearance="outline" class="ckyc-file-name-field">
<input
matInput
[readonly]="true"
[value]="idProofFile?.name || ''"
[placeholder]="'labels.text.NoFileSelected' | translate"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="idProofInput.click()">
<fa-icon icon="folder-open" size="lg"></fa-icon>
&nbsp;{{ 'labels.buttons.Browse' | translate }}
</button>
</div>
<button
mat-raised-button
color="primary"
type="button"
[disabled]="!idProofFile || uploading['ID_PROOF']"
(click)="uploadDocument('ID_PROOF')"
>
@if (uploading['ID_PROOF']) {
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
} @else {
{{ 'labels.buttons.Upload' | translate }}
}
</button>
@if (uploadErrors['ID_PROOF']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['ID_PROOF'] }}</span>
</div>
}
@if (uploadResponses['ID_PROOF']) {
<div class="ckyc-upload-response">
<p>
<b>{{ 'labels.inputs.Status' | translate }}:</b> {{ uploadResponses['ID_PROOF'].status }}
</p>
<p>
<b>{{ 'labels.inputs.Request ID' | translate }}:</b> {{ uploadResponses['ID_PROOF'].requestId }}
</p>
<p>
<b>{{ 'labels.inputs.Acknowledgement Number' | translate }}:</b>
{{ uploadResponses['ID_PROOF'].acknowledgementNumber }}
</p>
<p>
<b>{{ 'labels.inputs.Processing Status' | translate }}:</b>
{{ uploadResponses['ID_PROOF'].processingStatus }}
</p>
</div>
}
}
</mat-card-content>
</mat-card>
<!-- Address Proof Document -->
<mat-card class="ckyc-upload-card">
<mat-card-content>
@@ -325,8 +207,25 @@
}
</div>
</div>
@if (existing.ADDRESS_PROOF.previewUrl && isImage('ADDRESS_PROOF')) {
<img [src]="existing.ADDRESS_PROOF.previewUrl" alt="Address proof" class="ckyc-existing__thumb" />
@if (
(existing.ADDRESS_PROOF.previewUrl || existing.ADDRESS_PROOF.previewUrlBack) && isImage('ADDRESS_PROOF')
) {
<div class="ckyc-existing__thumbs">
@if (existing.ADDRESS_PROOF.previewUrl) {
<img
[src]="existing.ADDRESS_PROOF.previewUrl"
alt="Address proof scan - front"
class="ckyc-existing__thumb"
/>
}
@if (existing.ADDRESS_PROOF.previewUrlBack) {
<img
[src]="existing.ADDRESS_PROOF.previewUrlBack"
alt="Address proof scan - back"
class="ckyc-existing__thumb"
/>
}
</div>
}
@if (existing.ADDRESS_PROOF.previewUrl) {
<button
@@ -352,78 +251,51 @@
</span>
}
</div>
@if (cardDate('ADDRESS_PROOF', 'issue') || cardDate('ADDRESS_PROOF', 'expiry')) {
<div class="ckyc-existing__dates">
@if (cardDate('ADDRESS_PROOF', 'issue')) {
<span
><fa-icon icon="calendar-check"></fa-icon> Issued {{ cardDate('ADDRESS_PROOF', 'issue') }}</span
>
}
@if (cardDate('ADDRESS_PROOF', 'expiry')) {
<span
><fa-icon icon="calendar-check"></fa-icon> Expires {{ cardDate('ADDRESS_PROOF', 'expiry') }}</span
>
}
</div>
}
<button
mat-stroked-button
type="button"
class="ckyc-existing__replace"
(click)="toggleReplace('ADDRESS_PROOF')"
(click)="openUploadDialog('ADDRESS_PROOF')"
>
<fa-icon [icon]="existing.ADDRESS_PROOF.expanded ? 'times' : 'upload'"></fa-icon>
{{ existing.ADDRESS_PROOF.expanded ? 'Cancel replace' : 'Upload new version' }}
<fa-icon icon="upload"></fa-icon>
Upload new version
</button>
</div>
} @else {
<div class="ckyc-missing">
<p class="ckyc-upload-hint">Not uploaded yet. Accepted formats: PNG, JPEG, JPG, PDF</p>
<button mat-raised-button color="primary" type="button" (click)="openUploadDialog('ADDRESS_PROOF')">
<fa-icon icon="upload"></fa-icon>
&nbsp;{{ 'labels.buttons.Upload' | translate }}
</button>
</div>
}
@if (!existing.ADDRESS_PROOF.present || existing.ADDRESS_PROOF.expanded) {
<p class="ckyc-upload-hint">{{ 'labels.inputs.Accepted formats' | translate }}: PNG, JPEG, JPG, PDF</p>
<div class="ckyc-file-row">
<input
type="file"
#addressProofInput
accept=".png,.jpeg,.jpg,.pdf"
(change)="onFileSelect($event, 'ADDRESS_PROOF')"
[style.display]="'none'"
/>
<mat-form-field appearance="outline" class="ckyc-file-name-field">
<input
matInput
[readonly]="true"
[value]="addressProofFile?.name || ''"
[placeholder]="'labels.text.NoFileSelected' | translate"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="addressProofInput.click()">
<fa-icon icon="folder-open" size="lg"></fa-icon>
&nbsp;{{ 'labels.buttons.Browse' | translate }}
</button>
@if (uploading['ADDRESS_PROOF']) {
<div class="ckyc-uploading">
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
<span>Uploading…</span>
</div>
}
@if (uploadErrors['ADDRESS_PROOF']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['ADDRESS_PROOF'] }}</span>
</div>
<button
mat-raised-button
color="primary"
type="button"
[disabled]="!addressProofFile || uploading['ADDRESS_PROOF']"
(click)="uploadDocument('ADDRESS_PROOF')"
>
@if (uploading['ADDRESS_PROOF']) {
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
} @else {
{{ 'labels.buttons.Upload' | translate }}
}
</button>
@if (uploadErrors['ADDRESS_PROOF']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['ADDRESS_PROOF'] }}</span>
</div>
}
@if (uploadResponses['ADDRESS_PROOF']) {
<div class="ckyc-upload-response">
<p>
<b>{{ 'labels.inputs.Status' | translate }}:</b> {{ uploadResponses['ADDRESS_PROOF'].status }}
</p>
<p>
<b>{{ 'labels.inputs.Request ID' | translate }}:</b> {{ uploadResponses['ADDRESS_PROOF'].requestId }}
</p>
<p>
<b>{{ 'labels.inputs.Acknowledgement Number' | translate }}:</b>
{{ uploadResponses['ADDRESS_PROOF'].acknowledgementNumber }}
</p>
<p>
<b>{{ 'labels.inputs.Processing Status' | translate }}:</b>
{{ uploadResponses['ADDRESS_PROOF'].processingStatus }}
</p>
</div>
}
}
</mat-card-content>
</mat-card>
@@ -448,8 +320,23 @@
}
</div>
</div>
@if (existing.PHOTO_PROOF.previewUrl && isImage('PHOTO_PROOF')) {
<img [src]="existing.PHOTO_PROOF.previewUrl" alt="Photo proof" class="ckyc-existing__thumb" />
@if ((existing.PHOTO_PROOF.previewUrl || existing.PHOTO_PROOF.previewUrlBack) && isImage('PHOTO_PROOF')) {
<div class="ckyc-existing__thumbs">
@if (existing.PHOTO_PROOF.previewUrl) {
<img
[src]="existing.PHOTO_PROOF.previewUrl"
alt="ID proof scan - front"
class="ckyc-existing__thumb"
/>
}
@if (existing.PHOTO_PROOF.previewUrlBack) {
<img
[src]="existing.PHOTO_PROOF.previewUrlBack"
alt="ID proof scan - back"
class="ckyc-existing__thumb"
/>
}
</div>
}
@if (existing.PHOTO_PROOF.previewUrl) {
<button
@@ -474,78 +361,49 @@
</span>
}
</div>
@if (cardDate('PHOTO_PROOF', 'issue') || cardDate('PHOTO_PROOF', 'expiry')) {
<div class="ckyc-existing__dates">
@if (cardDate('PHOTO_PROOF', 'issue')) {
<span><fa-icon icon="calendar-check"></fa-icon> Issued {{ cardDate('PHOTO_PROOF', 'issue') }}</span>
}
@if (cardDate('PHOTO_PROOF', 'expiry')) {
<span
><fa-icon icon="calendar-check"></fa-icon> Expires {{ cardDate('PHOTO_PROOF', 'expiry') }}</span
>
}
</div>
}
<button
mat-stroked-button
type="button"
class="ckyc-existing__replace"
(click)="toggleReplace('PHOTO_PROOF')"
(click)="openUploadDialog('PHOTO_PROOF')"
>
<fa-icon [icon]="existing.PHOTO_PROOF.expanded ? 'times' : 'upload'"></fa-icon>
{{ existing.PHOTO_PROOF.expanded ? 'Cancel replace' : 'Upload new version' }}
<fa-icon icon="upload"></fa-icon>
Upload new version
</button>
</div>
} @else {
<div class="ckyc-missing">
<p class="ckyc-upload-hint">Not uploaded yet. Accepted formats: PNG, JPEG, JPG, PDF</p>
<button mat-raised-button color="primary" type="button" (click)="openUploadDialog('PHOTO_PROOF')">
<fa-icon icon="upload"></fa-icon>
&nbsp;{{ 'labels.buttons.Upload' | translate }}
</button>
</div>
}
@if (!existing.PHOTO_PROOF.present || existing.PHOTO_PROOF.expanded) {
<p class="ckyc-upload-hint">{{ 'labels.inputs.Accepted formats' | translate }}: PNG, JPEG, JPG, PDF</p>
<div class="ckyc-file-row">
<input
type="file"
#photoProofInput
accept=".png,.jpeg,.jpg,.pdf"
(change)="onFileSelect($event, 'PHOTO_PROOF')"
[style.display]="'none'"
/>
<mat-form-field appearance="outline" class="ckyc-file-name-field">
<input
matInput
[readonly]="true"
[value]="photoProofFile?.name || ''"
[placeholder]="'labels.text.NoFileSelected' | translate"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="photoProofInput.click()">
<fa-icon icon="folder-open" size="lg"></fa-icon>
&nbsp;{{ 'labels.buttons.Browse' | translate }}
</button>
@if (uploading['PHOTO_PROOF']) {
<div class="ckyc-uploading">
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
<span>Uploading…</span>
</div>
}
@if (uploadErrors['PHOTO_PROOF']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['PHOTO_PROOF'] }}</span>
</div>
<button
mat-raised-button
color="primary"
type="button"
[disabled]="!photoProofFile || uploading['PHOTO_PROOF']"
(click)="uploadDocument('PHOTO_PROOF')"
>
@if (uploading['PHOTO_PROOF']) {
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
} @else {
{{ 'labels.buttons.Upload' | translate }}
}
</button>
@if (uploadErrors['PHOTO_PROOF']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['PHOTO_PROOF'] }}</span>
</div>
}
@if (uploadResponses['PHOTO_PROOF']) {
<div class="ckyc-upload-response">
<p>
<b>{{ 'labels.inputs.Status' | translate }}:</b> {{ uploadResponses['PHOTO_PROOF'].status }}
</p>
<p>
<b>{{ 'labels.inputs.Request ID' | translate }}:</b> {{ uploadResponses['PHOTO_PROOF'].requestId }}
</p>
<p>
<b>{{ 'labels.inputs.Acknowledgement Number' | translate }}:</b>
{{ uploadResponses['PHOTO_PROOF'].acknowledgementNumber }}
</p>
<p>
<b>{{ 'labels.inputs.Processing Status' | translate }}:</b>
{{ uploadResponses['PHOTO_PROOF'].processingStatus }}
</p>
</div>
}
}
</mat-card-content>
</mat-card>
@@ -570,8 +428,10 @@
}
</div>
</div>
@if (existing.CLIENT_IMAGE.previewUrl) {
@if (existing.CLIENT_IMAGE.previewUrl && isImage('CLIENT_IMAGE')) {
<img [src]="existing.CLIENT_IMAGE.previewUrl" alt="Client photo" class="ckyc-existing__thumb" />
}
@if (existing.CLIENT_IMAGE.previewUrl) {
<button
mat-stroked-button
type="button"
@@ -586,74 +446,33 @@
mat-stroked-button
type="button"
class="ckyc-existing__replace"
(click)="toggleReplace('CLIENT_IMAGE')"
(click)="openUploadDialog('CLIENT_IMAGE')"
>
<fa-icon [icon]="existing.CLIENT_IMAGE.expanded ? 'times' : 'upload'"></fa-icon>
{{ existing.CLIENT_IMAGE.expanded ? 'Cancel replace' : 'Upload new version' }}
<fa-icon icon="upload"></fa-icon>
Upload new version
</button>
</div>
} @else {
<div class="ckyc-missing">
<p class="ckyc-upload-hint">Not uploaded yet. Accepted formats: PNG, JPEG, JPG</p>
<button mat-raised-button color="primary" type="button" (click)="openUploadDialog('CLIENT_IMAGE')">
<fa-icon icon="upload"></fa-icon>
&nbsp;{{ 'labels.buttons.Upload' | translate }}
</button>
</div>
}
@if (!existing.CLIENT_IMAGE.present || existing.CLIENT_IMAGE.expanded) {
<p class="ckyc-upload-hint">{{ 'labels.inputs.Accepted formats' | translate }}: PNG, JPEG, JPG</p>
<div class="ckyc-file-row">
<input
type="file"
#clientImageInput
accept=".png,.jpeg,.jpg"
(change)="onFileSelect($event, 'CLIENT_IMAGE')"
[style.display]="'none'"
/>
<mat-form-field appearance="outline" class="ckyc-file-name-field">
<input
matInput
[readonly]="true"
[value]="clientImageFile?.name || ''"
[placeholder]="'labels.text.NoFileSelected' | translate"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="clientImageInput.click()">
<fa-icon icon="folder-open" size="lg"></fa-icon>
&nbsp;{{ 'labels.buttons.Browse' | translate }}
</button>
@if (uploading['CLIENT_IMAGE']) {
<div class="ckyc-uploading">
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
<span>Uploading…</span>
</div>
}
@if (uploadErrors['CLIENT_IMAGE']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['CLIENT_IMAGE'] }}</span>
</div>
<button
mat-raised-button
color="primary"
type="button"
[disabled]="!clientImageFile || uploading['CLIENT_IMAGE']"
(click)="uploadDocument('CLIENT_IMAGE')"
>
@if (uploading['CLIENT_IMAGE']) {
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
} @else {
{{ 'labels.buttons.Upload' | translate }}
}
</button>
@if (uploadErrors['CLIENT_IMAGE']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['CLIENT_IMAGE'] }}</span>
</div>
}
@if (uploadResponses['CLIENT_IMAGE']) {
<div class="ckyc-upload-response">
<p>
<b>{{ 'labels.inputs.Status' | translate }}:</b> {{ uploadResponses['CLIENT_IMAGE'].status }}
</p>
<p>
<b>{{ 'labels.inputs.Request ID' | translate }}:</b> {{ uploadResponses['CLIENT_IMAGE'].requestId }}
</p>
<p>
<b>{{ 'labels.inputs.Acknowledgement Number' | translate }}:</b>
{{ uploadResponses['CLIENT_IMAGE'].acknowledgementNumber }}
</p>
<p>
<b>{{ 'labels.inputs.Processing Status' | translate }}:</b>
{{ uploadResponses['CLIENT_IMAGE'].processingStatus }}
</p>
</div>
}
}
</mat-card-content>
</mat-card>
@@ -678,7 +497,7 @@
}
</div>
</div>
@if (existing.CLIENT_SIGNATURE.previewUrl) {
@if (existing.CLIENT_SIGNATURE.previewUrl && isImage('CLIENT_SIGNATURE')) {
<img
[src]="existing.CLIENT_SIGNATURE.previewUrl"
alt="Client signature"
@@ -704,75 +523,33 @@
mat-stroked-button
type="button"
class="ckyc-existing__replace"
(click)="toggleReplace('CLIENT_SIGNATURE')"
(click)="openUploadDialog('CLIENT_SIGNATURE')"
>
<fa-icon [icon]="existing.CLIENT_SIGNATURE.expanded ? 'times' : 'upload'"></fa-icon>
{{ existing.CLIENT_SIGNATURE.expanded ? 'Cancel replace' : 'Upload new version' }}
<fa-icon icon="upload"></fa-icon>
Upload new version
</button>
</div>
} @else {
<div class="ckyc-missing">
<p class="ckyc-upload-hint">Not uploaded yet. Accepted formats: PNG, JPEG, JPG</p>
<button mat-raised-button color="primary" type="button" (click)="openUploadDialog('CLIENT_SIGNATURE')">
<fa-icon icon="upload"></fa-icon>
&nbsp;{{ 'labels.buttons.Upload' | translate }}
</button>
</div>
}
@if (!existing.CLIENT_SIGNATURE.present || existing.CLIENT_SIGNATURE.expanded) {
<p class="ckyc-upload-hint">{{ 'labels.inputs.Accepted formats' | translate }}: PNG, JPEG, JPG</p>
<div class="ckyc-file-row">
<input
type="file"
#clientSignatureInput
accept=".png,.jpeg,.jpg"
(change)="onFileSelect($event, 'CLIENT_SIGNATURE')"
[style.display]="'none'"
/>
<mat-form-field appearance="outline" class="ckyc-file-name-field">
<input
matInput
[readonly]="true"
[value]="clientSignatureFile?.name || ''"
[placeholder]="'labels.text.NoFileSelected' | translate"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="clientSignatureInput.click()">
<fa-icon icon="folder-open" size="lg"></fa-icon>
&nbsp;{{ 'labels.buttons.Browse' | translate }}
</button>
@if (uploading['CLIENT_SIGNATURE']) {
<div class="ckyc-uploading">
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
<span>Uploading…</span>
</div>
}
@if (uploadErrors['CLIENT_SIGNATURE']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['CLIENT_SIGNATURE'] }}</span>
</div>
<button
mat-raised-button
color="primary"
type="button"
[disabled]="!clientSignatureFile || uploading['CLIENT_SIGNATURE']"
(click)="uploadDocument('CLIENT_SIGNATURE')"
>
@if (uploading['CLIENT_SIGNATURE']) {
<mat-progress-spinner diameter="18" mode="indeterminate"></mat-progress-spinner>
} @else {
{{ 'labels.buttons.Upload' | translate }}
}
</button>
@if (uploadErrors['CLIENT_SIGNATURE']) {
<div class="ckyc-upload-error">
<mat-icon>error_outline</mat-icon>
<span>{{ uploadErrors['CLIENT_SIGNATURE'] }}</span>
</div>
}
@if (uploadResponses['CLIENT_SIGNATURE']) {
<div class="ckyc-upload-response">
<p>
<b>{{ 'labels.inputs.Status' | translate }}:</b> {{ uploadResponses['CLIENT_SIGNATURE'].status }}
</p>
<p>
<b>{{ 'labels.inputs.Request ID' | translate }}:</b>
{{ uploadResponses['CLIENT_SIGNATURE'].requestId }}
</p>
<p>
<b>{{ 'labels.inputs.Acknowledgement Number' | translate }}:</b>
{{ uploadResponses['CLIENT_SIGNATURE'].acknowledgementNumber }}
</p>
<p>
<b>{{ 'labels.inputs.Processing Status' | translate }}:</b>
{{ uploadResponses['CLIENT_SIGNATURE'].processingStatus }}
</p>
</div>
}
}
</mat-card-content>
</mat-card>
@@ -553,15 +553,21 @@
margin: 0 0 12px;
}
.ckyc-file-row {
.ckyc-missing {
margin-top: 14px;
display: flex;
flex-direction: column;
gap: 10px;
align-items: flex-start;
gap: 8px;
margin-bottom: 12px;
}
.ckyc-file-name-field {
flex: 1;
.ckyc-uploading {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
font-size: 12px;
color: #5f6368;
}
.ckyc-upload-error {
@@ -583,19 +589,6 @@
}
}
.ckyc-upload-response {
margin-top: 12px;
padding: 10px 14px;
background-color: #e8f5e9;
border: 1px solid #a5d6a7;
border-radius: 8px;
font-size: 12px;
p {
margin: 4px 0;
}
}
@media (width <= 900px) {
.ckyc-upload-grid {
grid-template-columns: 1fr;
@@ -610,14 +603,6 @@
.ckyc-upload-grid {
grid-template-columns: 1fr;
}
.ckyc-file-row {
flex-direction: column;
}
.ckyc-file-name-field {
width: 100%;
}
}
/* ===================== Already-available banners ===================== */
@@ -760,6 +745,34 @@
letter-spacing: 0.3px;
}
&__thumbs {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
}
&__dates {
display: flex;
align-items: center;
gap: 10px;
font-size: 11px;
color: #0f6e56;
flex-wrap: wrap;
span {
display: inline-flex;
align-items: center;
gap: 5px;
}
fa-icon {
color: #1d9e75;
font-size: 11px;
}
}
&__thumb {
width: 100px;
height: 100px;
@@ -9,52 +9,41 @@
/** Angular Imports */
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subject, takeUntil, catchError, of } from 'rxjs';
import { Subject, Observable, takeUntil, catchError, of, forkJoin } from 'rxjs';
/** Custom Services */
import { ClientsService } from '../../clients.service';
import { AlertService } from 'app/core/alert/alert.service';
import { MatIcon } from '@angular/material/icon';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { MatDialog } from '@angular/material/dialog';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { Dates } from 'app/core/utils/dates';
import { ProofType, normalizeProofType } from '../../shared/kyc-proof-types';
import { CkycUploadDialogComponent, CkycUploadDialogResult } from './ckyc-upload-dialog/ckyc-upload-dialog.component';
interface ExistingArtefact {
present: boolean;
name?: string;
source?: string;
previewUrl?: string;
previewUrlBack?: string;
documentId?: string;
documentTypeId?: string;
documentKey?: string;
/** "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" — same convention client-india-address-step
* already writes/reads for address proof; now shared by the photo/identity proof too. */
description?: string;
fileCount?: number;
expanded?: boolean;
/** Set when the stored file could not be fetched - the row exists but its content is gone. */
previewUnavailable?: boolean;
/** Stored MIME type, so the card knows whether it can render an inline thumbnail. */
mimeType?: string;
}
/**
* Multipart `name` / `description` sent for each CKYC artefact type.
*
* The platform has no CKYC-specific document API; these are stored through the generic
* DocumentApiResource, whose contract carries no document-type field. The artefact type therefore
* travels in `name`, which is the same mechanism the client signature already uses - so
* `CLIENT_SIGNATURE` deliberately reuses the existing `clientSignature` value that
* loadExistingArtefacts() (and uploadClientSignatureImage()) match on. Changing that string would
* orphan every previously uploaded signature.
*/
export type CkycDocumentType = 'ID_PROOF' | 'ADDRESS_PROOF' | 'PHOTO_PROOF' | 'CLIENT_IMAGE' | 'CLIENT_SIGNATURE';
const CKYC_DOCUMENT_META: Record<CkycDocumentType, { name: string; description: string }> = {
ID_PROOF: { name: 'ckycIdProof', description: 'CKYC ID proof' },
ADDRESS_PROOF: { name: 'ckycAddressProof', description: 'CKYC address proof' },
PHOTO_PROOF: { name: 'ckycPhotoProof', description: 'CKYC photo proof' },
CLIENT_IMAGE: { name: 'ckycClientImage', description: 'CKYC client photograph' },
CLIENT_SIGNATURE: { name: 'clientSignature', description: 'Client signature' }
};
const CKYC_DOCUMENT_TYPES = Object.keys(CKYC_DOCUMENT_META) as CkycDocumentType[];
type ProofKind = 'ADDRESS_PROOF' | 'PHOTO_PROOF';
type CkycDocKind = ProofKind | 'CLIENT_IMAGE' | 'CLIENT_SIGNATURE';
/**
* Client-side upload guards, kept deliberately in step with the backend so a file that passes here
@@ -62,8 +51,8 @@ const CKYC_DOCUMENT_TYPES = Object.keys(CKYC_DOCUMENT_META) as CkycDocumentType[
* - 5 MB matches `spring.servlet.multipart.max-file-size`
* - the extension list is the intersection of the backend `fineract.content.regex-whitelist`
* with what these cards can actually render.
* `accept=` on the input is only a file-picker hint and is trivially bypassed, so the real check
* lives in onFileSelect().
* The dialog's `accept=` is only a file-picker hint and is trivially bypassed, so the real check
* runs here, on the file the dialog hands back, before anything is sent.
*/
const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
const IMAGE_EXTENSIONS = [
@@ -76,8 +65,8 @@ const DOCUMENT_EXTENSIONS = [
'pdf'
];
/** Types whose card renders an inline <img> preview, so a PDF would not display. */
const IMAGE_ONLY_TYPES: CkycDocumentType[] = [
/** Cards that render an inline <img>, so a PDF would not display in them. */
const IMAGE_ONLY_KINDS: CkycDocKind[] = [
'CLIENT_IMAGE',
'CLIENT_SIGNATURE'
];
@@ -98,6 +87,8 @@ export class CkycTabComponent implements OnInit, OnDestroy {
private route = inject(ActivatedRoute);
private clientsService = inject(ClientsService);
private alertService = inject(AlertService);
private dialog = inject(MatDialog);
private dates = inject(Dates);
private destroy$ = new Subject<void>();
@@ -131,37 +122,55 @@ export class CkycTabComponent implements OnInit, OnDestroy {
return this.panVerified && this.aadhaarVerified;
}
/** CKYC artefacts already uploaded for this client, keyed by artefact type. */
existing: Record<CkycDocumentType, ExistingArtefact> = {
ID_PROOF: { present: false },
/** Pre-existing artefacts detected from client data */
existing: Record<CkycDocKind, ExistingArtefact> = {
ADDRESS_PROOF: { present: false },
PHOTO_PROOF: { present: false },
CLIENT_IMAGE: { present: false },
CLIENT_SIGNATURE: { present: false }
};
/** Document-type options for the proof pickers, fetched once from /kyc/proof-types */
addressProofOptions: ProofType[] = [];
idProofOptions: ProofType[] = [];
/** Document type currently selected in each proof card's picker */
selectedProofType: Record<ProofKind, ProofType | null> = {
ADDRESS_PROOF: null,
PHOTO_PROOF: null
};
/** Front/back files staged for the two proof cards; other cards keep a single file each */
docFiles: Record<ProofKind, { front: File | null; back: File | null }> = {
ADDRESS_PROOF: { front: null, back: null },
PHOTO_PROOF: { front: null, back: null }
};
/** Document number + issue/expiry dates staged from the upload dialog, same fields client
* creation collects for a KYC/address proof — persisted onto the identifier's documentKey
* and description ("Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd"). */
private documentDetails: Record<
ProofKind,
{ documentKey: string; issueDate: string | null; expiryDate: string | null }
> = {
ADDRESS_PROOF: { documentKey: '', issueDate: null, expiryDate: null },
PHOTO_PROOF: { documentKey: '', issueDate: null, expiryDate: null }
};
/** File references */
idProofFile: File | null = null;
addressProofFile: File | null = null;
photoProofFile: File | null = null;
clientImageFile: File | null = null;
clientSignatureFile: File | null = null;
/** Per-document upload state */
uploading: { [key: string]: boolean } = {
ID_PROOF: false,
ADDRESS_PROOF: false,
PHOTO_PROOF: false,
CLIENT_IMAGE: false,
CLIENT_SIGNATURE: false
};
/** Per-document upload response */
uploadResponses: { [key: string]: any } = {};
/** Per-document error messages */
uploadErrors: { [key: string]: string | null } = {
ID_PROOF: null,
ADDRESS_PROOF: null,
PHOTO_PROOF: null,
CLIENT_IMAGE: null,
@@ -171,6 +180,11 @@ export class CkycTabComponent implements OnInit, OnDestroy {
ngOnInit(): void {
this.route.parent.params.subscribe((params: any) => {
this.clientId = params['clientId'];
// Angular reuses this component when only the clientId in the route changes, and
// loadExistingArtefacts() only ever *assigns* what it finds - it has no "not found" branch.
// Without clearing first, a client with no photo (or no signature, or no proof) keeps showing
// the previous client's card.
this.resetArtefactState();
this.loadClientInfo();
this.loadAccounts();
this.loadCkycData();
@@ -178,6 +192,46 @@ export class CkycTabComponent implements OnInit, OnDestroy {
});
}
/**
* Returns every per-client card to its empty state, so nothing from the client just viewed can
* survive into the next one. Covers all four cards plus the details staged for an upload - a file
* or document number left over from another client must never be submitted against this one.
*/
private resetArtefactState(): void {
this.revokePreviewUrls();
this.existing = {
ADDRESS_PROOF: { present: false },
PHOTO_PROOF: { present: false },
CLIENT_IMAGE: { present: false },
CLIENT_SIGNATURE: { present: false }
};
this.selectedProofType = { ADDRESS_PROOF: null, PHOTO_PROOF: null };
this.docFiles = {
ADDRESS_PROOF: { front: null, back: null },
PHOTO_PROOF: { front: null, back: null }
};
this.documentDetails = {
ADDRESS_PROOF: { documentKey: '', issueDate: null, expiryDate: null },
PHOTO_PROOF: { documentKey: '', issueDate: null, expiryDate: null }
};
this.clientImageFile = null;
this.clientSignatureFile = null;
this.uploadErrors = {
ADDRESS_PROOF: null,
PHOTO_PROOF: null,
CLIENT_IMAGE: null,
CLIENT_SIGNATURE: null
};
}
/** Frees the blob URLs held by the current cards before their references are dropped. */
private revokePreviewUrls(): void {
Object.values(this.existing).forEach((e) => {
if (e.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(e.previewUrl);
if (e.previewUrlBack?.startsWith('blob:')) URL.revokeObjectURL(e.previewUrlBack);
});
}
private loadClientInfo(): void {
this.route.parent.data.subscribe((data: any) => {
const cv = data?.clientViewData;
@@ -263,123 +317,270 @@ export class CkycTabComponent implements OnInit, OnDestroy {
}
/**
* Loads every CKYC artefact from the client's documents (`m_document`), which is the single
* source of truth for this screen: each card matches the `name` its own upload writes, so what
* the checker sees is exactly what CKYC stored.
*
* Deliberately does NOT read the profile image or client identifiers any more. Those belong to
* client registration and the Identities section; reading them here showed artefacts this screen
* had never uploaded, and hid the ones it had. Those other screens are untouched.
*
* A client can accumulate several rows for one artefact (older uploads pre-date replacement, and
* the signature is also written by client registration), so the newest row - highest `id` - wins.
* Fetch photo (profile image), signature (client document),
* ID proof and address proof (client identifiers) so already-uploaded
* artefacts are shown here instead of forcing re-upload.
*/
private loadExistingArtefacts(): void {
this.checkingExisting = true;
forkJoin({
photo: this.clientsService.getClientProfileImage(this.clientId).pipe(catchError(() => of(null))),
documents: this.clientsService.getClientDocuments(this.clientId).pipe(catchError(() => of([]))),
identifiers: this.clientsService.getClientIdentifiers(this.clientId).pipe(catchError(() => of([]))),
proofTypes: this.clientsService.getKycProofTypes().pipe(catchError(() => of({ idProofs: [], addressProofs: [] })))
})
.pipe(takeUntil(this.destroy$))
.subscribe(({ photo, documents, identifiers, proofTypes }) => {
this.checkingExisting = false;
// 1. Photo / image of client — from m_client.image_id
if (photo && typeof photo === 'string' && photo.length > 0) {
this.existing.CLIENT_IMAGE = {
present: true,
source: 'Client registration',
previewUrl: photo,
name: 'Profile photo'
};
}
// 2. Signature — client document with name='clientSignature'. Multiple rows can exist
// for clients who re-cropped/replaced their signature before uploads became single-slot,
// so pick the highest id (latest) rather than the first unordered match.
const signatureDoc = (documents as any[])
?.filter((d: any) => d?.name === 'clientSignature')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (signatureDoc) {
this.existing.CLIENT_SIGNATURE = {
present: true,
source: 'Client registration',
name: signatureDoc.fileName || 'Client signature',
documentId: signatureDoc.id,
mimeType: signatureDoc.type
};
// Same endpoint getClientSignatureImage() uses, but opted out of the global error alert:
// a m_document row whose file is no longer in the content store returns 500, and the card
// below reports that itself. Without `silent` the interceptor pops an "Internal Server
// Error" modal on every page load, for a failure the user cannot act on.
this.clientsService
.downloadClientDocument(this.clientId, String(signatureDoc.id), true)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (blob: any) => {
if (blob && blob.size > 0) {
this.existing.CLIENT_SIGNATURE.previewUrl = URL.createObjectURL(blob);
} else {
// A 200 with an empty body still means there is nothing to show. Without this the
// card would claim "Already available" with no thumbnail and no explanation.
this.existing.CLIENT_SIGNATURE.previewUnavailable = true;
}
},
error: () => {
this.existing.CLIENT_SIGNATURE.previewUnavailable = true;
}
});
}
// 3 & 4. ID proof + Address proof — client identifiers classified via proof-types
this.idProofOptions = (proofTypes?.idProofs || []).map((p: any) => normalizeProofType(p));
this.addressProofOptions = (proofTypes?.addressProofs || []).map((p: any) => normalizeProofType(p));
const idProofIds = new Set<string>((proofTypes?.idProofs || []).map((p: any) => String(p.id)));
const addressProofIds = new Set<string>((proofTypes?.addressProofs || []).map((p: any) => String(p.id)));
const idList = Array.isArray(identifiers) ? identifiers : (identifiers as any)?.pageItems || [];
for (const identity of idList) {
const docTypeId = String(identity?.documentType?.id ?? '');
const isActive =
!identity?.status ||
identity?.status?.code === 'clientIdentifierStatusType.active' ||
identity?.status === 'clientIdentifierStatusType.active' ||
identity?.status === 'Active';
if (!isActive) continue;
const proofName = identity?.documentType?.name || 'Identifier';
// Address proof documentKey is auto-generated as "<ProofName> - <clientId>"
// in identities-tab; hide it when it's just that synthetic key.
const rawKey = identity?.documentKey || '';
const isSyntheticKey = rawKey.startsWith(`${proofName} - `);
const common = {
present: true,
source: 'Identities section',
name: proofName,
documentKey: isSyntheticKey ? '' : rawKey,
documentId: identity?.id,
documentTypeId: docTypeId,
description: identity?.description || '',
fileCount: (identity?.documents || []).length
};
if (idProofIds.has(docTypeId) && !this.existing.PHOTO_PROOF.present) {
this.existing.PHOTO_PROOF = common;
this.selectedProofType.PHOTO_PROOF = this.idProofOptions.find((p) => String(p.id) === docTypeId) || null;
this.loadIdentifierDocPreview('PHOTO_PROOF', identity.id);
} else if (addressProofIds.has(docTypeId) && !this.existing.ADDRESS_PROOF.present) {
this.existing.ADDRESS_PROOF = common;
this.selectedProofType.ADDRESS_PROOF =
this.addressProofOptions.find((p) => String(p.id) === docTypeId) || null;
this.loadIdentifierDocPreview('ADDRESS_PROOF', identity.id);
}
}
});
}
/**
* The scanned ID/address-proof card only showed its file name and key — never the scan
* itself, unlike the photo and signature cards right beside it. Mirrors those two: fetch
* the identifier's own attached document(s) (m_client_identifier -> m_document, the same
* chain the Identities tab and the create-client stepper read) and download the latest for
* an inline preview. Two-sided proof types (Aadhaar, Passport, Voter ID, Driving Licence)
* store front/back as two separate documents named "<Proof> — Front"/"— Back" (the same
* convention the create-client stepper writes), so both are matched and previewed here;
* a legacy single upload with no such marker just shows as the one preview.
*/
private loadIdentifierDocPreview(kind: ProofKind, identifierId: string): void {
this.clientsService
.getClientDocuments(this.clientId)
.getClientIdentificationDocuments(identifierId)
.pipe(
takeUntil(this.destroy$),
catchError(() => of([]))
)
.subscribe((documents: any) => {
this.checkingExisting = false;
.subscribe((docs: any) => {
const list = Array.isArray(docs) ? docs : [];
if (!list.length) return;
this.existing[kind].fileCount = list.length;
this.existing[kind].previewUnavailable = false;
const list: any[] = Array.isArray(documents) ? documents : (documents?.pageItems ?? []);
const byNewest = (a: any, b: any) => b.id - a.id;
const label = (d: any) => (d?.name || d?.fileName || '').toString();
const back = [...list].filter((d: any) => /back/i.test(label(d))).sort(byNewest)[0];
const front =
[...list].filter((d: any) => /front/i.test(label(d))).sort(byNewest)[0] ||
[...list].filter((d: any) => d.id !== back?.id).sort(byNewest)[0];
for (const type of CKYC_DOCUMENT_TYPES) {
const expectedName = CKYC_DOCUMENT_META[type].name;
const doc = list
.filter((d: any) => d?.name === expectedName)
.sort((a: any, b: any) => (b?.id ?? 0) - (a?.id ?? 0))[0];
if (!doc) {
// No upload yet for this artefact - leave the card in its empty state.
this.existing[type] = { present: false };
continue;
}
this.existing[type] = {
present: true,
source: 'CKYC upload',
name: doc.fileName || expectedName,
documentId: doc.id,
mimeType: doc.type
};
this.loadPreview(type, doc.id);
}
// A proof can be scanned to PDF, which no <img> can render - remember what was stored so the
// card offers "View document" instead of a broken thumbnail.
if (front) this.existing[kind].mimeType = front.type;
if (front) this.downloadIdentifierDocPreview(identifierId, front.id, kind, 'front');
if (back && back.id !== front?.id) this.downloadIdentifierDocPreview(identifierId, back.id, kind, 'back');
});
}
/**
* Fetches the stored file so the card can show a thumbnail. A failure here is reported on the
* card rather than swallowed: the usual cause is a `m_document` row whose file is no longer in
* the content store, and silently showing "Already available" with no image hides that.
*/
private loadPreview(type: CkycDocumentType, documentId: string | number): void {
private downloadIdentifierDocPreview(
identifierId: string,
documentId: string,
kind: ProofKind,
slot: 'front' | 'back'
): void {
this.clientsService
// silent: a missing stored file returns 500, and the card below already reports that. Without
// this the global error interceptor pops an "Internal Server Error" modal on every page load
// and after every upload, for a failure the user cannot act on.
.downloadClientDocument(this.clientId, String(documentId), true)
.downloadClientIdentificationDocument(identifierId, documentId)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (blob: any) => {
if (blob && blob.size > 0) {
this.existing[type].previewUrl = URL.createObjectURL(blob);
} else {
// A 200 with an empty body still means there is nothing to show. Without this the card
// would sit there claiming "Already available" with no thumbnail and no explanation.
this.existing[type].previewUnavailable = true;
if (!blob || blob.size === 0) {
this.existing[kind].previewUnavailable = true;
return;
}
const url = URL.createObjectURL(blob);
if (slot === 'front') this.existing[kind].previewUrl = url;
else this.existing[kind].previewUrlBack = url;
},
// The row exists but its file is gone from the content store. Saying so on the card beats
// showing "Already available" next to a blank space.
error: () => {
this.existing[type].previewUnavailable = true;
this.existing[kind].previewUnavailable = true;
}
});
}
/**
* True when the stored file can be shown as an inline thumbnail. A PDF cannot, so its card falls
* back to the "View document" button alone rather than rendering a broken image.
*/
isImage(documentType: CkycDocumentType): boolean {
const entry = this.existing[documentType];
if (entry?.mimeType) {
return entry.mimeType.startsWith('image/');
}
// Older rows can have no stored MIME type - fall back to the file extension.
const extension = (entry?.name?.split('.').pop() || '').toLowerCase();
return IMAGE_EXTENSIONS.includes(extension);
}
/**
* Opens the uploaded document full size in a new tab. Uses the blob already fetched for the
* thumbnail, so it works for PDFs too and costs no extra request.
*/
openDocument(documentType: CkycDocumentType): void {
const url = this.existing[documentType]?.previewUrl;
if (url) {
window.open(url, '_blank', 'noopener');
}
}
toggleReplace(documentType: string): void {
const entry = (this.existing as any)[documentType];
if (entry) entry.expanded = !entry.expanded;
}
onAccountSelect(accountNo: string): void {
this.selectedAccount = this.allAccounts.find((a) => a.accountNo === accountNo) || null;
this.selectedAccountType = this.selectedAccount?.accountType || '';
}
getFile(documentType: string): File | null {
switch (documentType) {
case 'CLIENT_IMAGE':
return this.clientImageFile;
case 'CLIENT_SIGNATURE':
return this.clientSignatureFile;
default:
return null;
}
}
private static readonly CARD_TITLES: Record<CkycDocKind, string> = {
ADDRESS_PROOF: 'Address Proof Document',
PHOTO_PROOF: 'Photo Proof Document',
CLIENT_IMAGE: 'Image of Client',
CLIENT_SIGNATURE: 'Signature of Client'
};
/** Opens the picker/preview popup for one card and, once the user confirms a file there, feeds
* the picked type/file(s) into the same upload path the card always used. Picking and preview
* now live entirely in the dialog — this screen only stages the result and re-runs upload. */
openUploadDialog(kind: CkycDocKind): void {
const isProofKind = kind === 'ADDRESS_PROOF' || kind === 'PHOTO_PROOF';
const action = this.existing[kind].present ? 'Replace' : 'Upload';
const existingDates = isProofKind
? this.parseDescriptionDates(this.existing[kind].description)
: { issueDate: null, expiryDate: null };
const ref = this.dialog.open(CkycUploadDialogComponent, {
width: '480px',
maxWidth: '95vw',
data: {
title: `${action} ${CkycTabComponent.CARD_TITLES[kind]}`,
isProofKind,
accept: isProofKind ? '.png,.jpeg,.jpg,.pdf' : '.png,.jpeg,.jpg',
proofOptions:
kind === 'PHOTO_PROOF'
? this.idProofOptions
: kind === 'ADDRESS_PROOF'
? this.addressProofOptions
: undefined,
initialProofType: isProofKind ? this.selectedProofType[kind as ProofKind] : undefined,
initialDocumentKey: isProofKind ? this.existing[kind].documentKey || '' : undefined,
initialIssueDate: existingDates.issueDate,
initialExpiryDate: existingDates.expiryDate
}
});
ref.afterClosed().subscribe((result: CkycUploadDialogResult | null) => {
if (!result) return;
// The dialog's `accept=` filter is only a hint to the file picker and is trivially bypassed,
// so the size/type guard runs here on what actually came back. Catching it now turns a raw
// server rejection into a message on the card.
const rejection =
this.validationError(result.front, kind) ?? (result.back ? this.validationError(result.back, kind) : null);
if (rejection) {
this.uploadErrors[kind] = rejection;
return;
}
this.uploadErrors[kind] = null;
if (isProofKind) {
const proofKind = kind as ProofKind;
this.selectedProofType[proofKind] = result.proofType || null;
this.docFiles[proofKind] = { front: result.front, back: result.back || null };
this.documentDetails[proofKind] = {
documentKey: result.documentKey || '',
issueDate: result.issueDate || null,
expiryDate: result.expiryDate || null
};
} else if (kind === 'CLIENT_IMAGE') {
this.clientImageFile = result.front;
} else {
this.clientSignatureFile = result.front;
}
this.uploadDocument(kind);
});
}
/** Extensions a given card can both store and render. */
private allowedExtensions(documentType: string): string[] {
return IMAGE_ONLY_TYPES.includes(documentType as CkycDocumentType) ? IMAGE_EXTENSIONS : DOCUMENT_EXTENSIONS;
private allowedExtensions(kind: CkycDocKind): string[] {
return IMAGE_ONLY_KINDS.includes(kind) ? IMAGE_EXTENSIONS : DOCUMENT_EXTENSIONS;
}
/**
@@ -387,8 +588,11 @@ export class CkycTabComponent implements OnInit, OnDestroy {
* so the user gets a clear message instead of a raw server error. Returns null when the file is
* acceptable.
*/
private validationError(file: File, documentType: string): string | null {
const allowed = this.allowedExtensions(documentType);
private validationError(file: File | null | undefined, kind: CkycDocKind): string | null {
if (!file) {
return null;
}
const allowed = this.allowedExtensions(kind);
const extension = (file.name.split('.').pop() || '').toLowerCase();
if (!allowed.includes(extension)) {
@@ -404,125 +608,279 @@ export class CkycTabComponent implements OnInit, OnDestroy {
return null;
}
private setFile(documentType: string, file: File | null): void {
switch (documentType) {
case 'ID_PROOF':
this.idProofFile = file;
break;
case 'ADDRESS_PROOF':
this.addressProofFile = file;
break;
case 'PHOTO_PROOF':
this.photoProofFile = file;
break;
case 'CLIENT_IMAGE':
this.clientImageFile = file;
break;
case 'CLIENT_SIGNATURE':
this.clientSignatureFile = file;
break;
/**
* True when the stored file can be shown as an inline thumbnail. A PDF cannot, so its card falls
* back to the "View document" button alone rather than rendering a broken image.
*/
isImage(kind: CkycDocKind): boolean {
const entry = this.existing[kind];
// The profile image arrives as a `data:image/...;base64,` URL, which declares its own type -
// it has neither a stored MIME type nor a file extension for the checks below to read.
if (entry?.previewUrl?.startsWith('data:')) {
return entry.previewUrl.startsWith('data:image/');
}
if (entry?.mimeType) {
return entry.mimeType.startsWith('image/');
}
// Older rows can have no stored MIME type - fall back to the file extension.
const extension = (entry?.name?.split('.').pop() || '').toLowerCase();
return IMAGE_EXTENSIONS.includes(extension);
}
/**
* Opens the uploaded document full size in a new tab. Uses the blob already fetched for the
* thumbnail, so it works for PDFs too and costs no extra request.
*/
openDocument(kind: CkycDocKind): void {
const url = this.existing[kind]?.previewUrl;
if (url) {
window.open(url, '_blank', 'noopener');
}
}
onFileSelect(event: any, documentType: string): void {
const file = event.target?.files?.[0];
if (!file) return;
/** Reads back the "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" convention this tab (and
* client-india-address-step, for address proof) writes into the identifier's description. */
private parseDescriptionDates(description: string | undefined): { issueDate: Date | null; expiryDate: Date | null } {
const issueMatch = (description || '').match(/Issue date:\s*([^,|]+)/i);
const expiryMatch = (description || '').match(/Expiry date:\s*([^,|]+)/i);
return {
issueDate: issueMatch ? this.dates.parseDate(issueMatch[1].trim()) : null,
expiryDate: expiryMatch ? this.dates.parseDate(expiryMatch[1].trim()) : null
};
}
const error = this.validationError(file, documentType);
if (error) {
this.setFile(documentType, null);
this.uploadErrors[documentType] = error;
event.target.value = '';
private buildDescription(issueDate: string | null, expiryDate: string | null): string {
const parts: string[] = [];
if (issueDate) parts.push(`Issue date: ${issueDate}`);
if (expiryDate) parts.push(`Expiry date: ${expiryDate}`);
return parts.join(', ');
}
/** Issue/expiry date for display on the card, formatted dd-MM-yyyy — parsed from the same
* description text the upload dialog writes. */
cardDate(kind: ProofKind, which: 'issue' | 'expiry'): string {
const parsed = this.parseDescriptionDates(this.existing[kind].description);
const value = which === 'issue' ? parsed.issueDate : parsed.expiryDate;
return value ? this.dates.formatDate(value, 'dd-MM-yyyy') : '';
}
/**
* Routes each card to whichever real endpoint that artefact is actually stored through — there
* is no single "/clients/{id}/ckyc/documents" resource on the backend, so posting every card to
* one made-up URL 404'd for all four. A photo goes to the image endpoint, a signature to the
* client's own documents, and an ID/address proof to the m_client_identifier it already belongs
* to (the same one the Identities tab and create-client stepper post to) — never a fresh,
* type-less upload, since which identifier a proof belongs to is exactly what makes it that
* proof rather than some other file on the client's record.
*/
uploadDocument(documentType: string): void {
if (documentType === 'PHOTO_PROOF' || documentType === 'ADDRESS_PROOF') {
this.uploadProofDocument(documentType);
return;
}
this.setFile(documentType, file);
this.uploadErrors[documentType] = null;
}
getFile(documentType: string): File | null {
switch (documentType) {
case 'ID_PROOF':
return this.idProofFile;
case 'ADDRESS_PROOF':
return this.addressProofFile;
case 'PHOTO_PROOF':
return this.photoProofFile;
case 'CLIENT_IMAGE':
return this.clientImageFile;
case 'CLIENT_SIGNATURE':
return this.clientSignatureFile;
default:
return null;
}
}
uploadDocument(documentType: CkycDocumentType): void {
const file = this.getFile(documentType);
if (!file) return;
this.uploading[documentType] = true;
this.uploadErrors[documentType] = null;
const key = documentType as keyof typeof this.existing;
// DocumentApiResource consumes multipart/form-data with body parts `file`, `name` and
// `description` (file + description mandatory). There is no document-type field in that
// contract, so the artefact type is carried in `name` - which is also the key
// loadExistingArtefacts() matches on when reading the document back.
const meta = CKYC_DOCUMENT_META[documentType];
const formData = new FormData();
formData.append('file', file);
formData.append('name', meta.name);
formData.append('description', meta.description);
// Replace in place when this artefact already has a usable document, so a re-upload updates the
// existing row (same document id, same content-store location) instead of stacking up another
// copy. Falls back to create for the first upload of an artefact.
//
// Deliberately create instead of replace when the stored file is missing: the backend's update
// path writes the new content relative to the row's existing `location` and never calls
// setLocation(), so replacing a row whose file is already gone writes the upload to a fresh
// folder while the row keeps pointing at the missing one - the artefact would stay broken and
// the user would get a success message. Creating a new row repairs the card instead.
const entry = this.existing[documentType];
const replacing = !!entry?.documentId && !entry?.previewUnavailable;
const existingId = entry?.documentId;
const request$ = replacing
? this.clientsService.replaceClientDocument(this.clientId, String(existingId), formData)
: this.clientsService.uploadCkycDocument(this.clientId, formData);
let request$: Observable<any>;
switch (documentType) {
case 'CLIENT_IMAGE':
request$ = this.clientsService.uploadClientProfileImage(this.clientId, file);
break;
case 'CLIENT_SIGNATURE':
request$ = this.clientsService.uploadClientSignatureImage(this.clientId, file);
break;
default:
return;
}
request$.pipe(takeUntil(this.destroy$)).subscribe({
next: (response: any) => {
next: () => {
this.uploading[documentType] = false;
this.uploadResponses[documentType] = response;
this.setFile(documentType, null);
this.alertService.alert({
type: 'success',
message:
response?.message || (replacing ? 'Document replaced successfully.' : 'Document uploaded successfully.')
});
// Re-read from m_document so the card reflects what was actually stored, rather than
// assuming the write succeeded exactly as sent.
this.loadExistingArtefacts();
// The card is gated on `present`; without this a successful upload left it reading
// "Not uploaded yet". uploadProofDocument() sets the same flag for the proof cards.
this.existing[key].present = true;
this.existing[key].source = this.existing[key].source || 'CKYC upload';
this.alertService.alert({ type: 'success', message: 'Document uploaded successfully.' });
this.refreshPreview(documentType);
},
error: (err: any) => {
this.uploading[documentType] = false;
this.uploadErrors[documentType] =
err?.error?.developerMessage ||
err?.error?.defaultUserMessage ||
err?.message ||
'Failed to upload document.';
this.uploadErrors[documentType] = this.extractErrorMessage(err);
}
});
}
/**
* Proof cards work like the create-client KYC step: pick a document type first (its `sides`
* decides whether one image or a front+back pair is required), then upload. Reuses the same
* identifier the Identities tab manages — updates its documentTypeId if the picked type
* changed, or creates a fresh identifier when none exists yet, so this card never depends on
* a separate trip to the Identities tab.
*/
private uploadProofDocument(kind: ProofKind): void {
const proof = this.selectedProofType[kind];
if (!proof) {
this.uploadErrors[kind] = 'Select a document type first.';
return;
}
const files = this.docFiles[kind];
if (!files.front || (proof.sides === 2 && !files.back)) {
this.uploadErrors[kind] =
proof.sides === 2
? 'Both front and back images are required for this document type.'
: 'Select a file to upload.';
return;
}
this.uploading[kind] = true;
this.uploadErrors[kind] = null;
const existingId = this.existing[kind].documentId;
const details = this.documentDetails[kind];
const documentKey = details.documentKey || `${proof.name} - ${this.clientId}`;
const description = this.buildDescription(details.issueDate, details.expiryDate);
const identifier$: Observable<any> = !existingId
? this.clientsService.addClientIdentifier(this.clientId, {
documentTypeId: proof.id,
status: 'ACTIVE',
documentKey,
description: description || 'KYC document'
})
: this.clientsService.updateClientIdentifier(this.clientId, existingId, {
documentTypeId: proof.id,
status: 'ACTIVE',
documentKey,
description
});
identifier$.pipe(takeUntil(this.destroy$)).subscribe({
next: (res: any) => {
const identifierId = existingId || res?.resourceId;
const uploads: Observable<any>[] = [];
const front = new FormData();
front.append('name', proof.sides === 2 ? `${proof.name} — Front` : proof.name);
front.append('file', files.front!);
uploads.push(this.clientsService.uploadClientIdentifierDocument(identifierId, front));
if (proof.sides === 2 && files.back) {
const back = new FormData();
back.append('name', `${proof.name} — Back`);
back.append('file', files.back);
uploads.push(this.clientsService.uploadClientIdentifierDocument(identifierId, back));
}
forkJoin(uploads)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: () => {
this.uploading[kind] = false;
this.existing[kind].present = true;
this.existing[kind].documentId = identifierId;
this.existing[kind].documentTypeId = String(proof.id);
this.existing[kind].documentKey = details.documentKey || '';
this.existing[kind].description = description;
this.existing[kind].name = proof.name;
this.existing[kind].source = this.existing[kind].source || 'Identities section';
this.docFiles[kind] = { front: null, back: null };
this.alertService.alert({ type: 'success', message: 'Document uploaded successfully.' });
this.refreshPreview(kind);
},
error: (err: any) => {
this.uploading[kind] = false;
this.uploadErrors[kind] = this.extractErrorMessage(err);
}
});
},
error: (err: any) => {
this.uploading[kind] = false;
this.uploadErrors[kind] = this.extractErrorMessage(err);
}
});
}
private extractErrorMessage(err: any): string {
return (
err?.error?.errors?.[0]?.defaultUserMessage ||
err?.error?.developerMessage ||
err?.error?.defaultUserMessage ||
err?.message ||
'Failed to upload document.'
);
}
/** Re-fetches whichever artefact was just replaced, so its preview reflects the new file
* immediately instead of the one this screen loaded on entry. */
private refreshPreview(documentType: string): void {
const staleKey = documentType as keyof typeof this.existing;
if (this.existing[staleKey].previewUrl?.startsWith('blob:')) {
URL.revokeObjectURL(this.existing[staleKey].previewUrl!);
}
if (this.existing[staleKey].previewUrlBack?.startsWith('blob:')) {
URL.revokeObjectURL(this.existing[staleKey].previewUrlBack!);
}
// The upload that triggered this refresh is what repairs a previously missing file, so the
// warning has to be cleared before the re-read - otherwise a fixed card keeps the old badge.
this.existing[staleKey].previewUrl = undefined;
this.existing[staleKey].previewUrlBack = undefined;
this.existing[staleKey].previewUnavailable = false;
switch (documentType) {
case 'CLIENT_IMAGE':
this.clientsService
.getClientProfileImage(this.clientId)
.pipe(takeUntil(this.destroy$))
.subscribe((photo: any) => {
if (photo) {
this.existing.CLIENT_IMAGE.previewUrl = photo;
} else {
this.existing.CLIENT_IMAGE.previewUnavailable = true;
}
});
break;
case 'CLIENT_SIGNATURE':
this.clientsService
.getClientDocuments(this.clientId)
.pipe(takeUntil(this.destroy$))
.subscribe((documents: any) => {
const doc = (documents as any[])
?.filter((d: any) => d?.name === 'clientSignature')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (!doc) return;
this.existing.CLIENT_SIGNATURE.documentId = doc.id;
this.existing.CLIENT_SIGNATURE.mimeType = doc.type;
this.clientsService
.downloadClientDocument(this.clientId, String(doc.id), true)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (blob: any) => {
if (blob && blob.size > 0) {
this.existing.CLIENT_SIGNATURE.previewUrl = URL.createObjectURL(blob);
} else {
this.existing.CLIENT_SIGNATURE.previewUnavailable = true;
}
},
error: () => {
this.existing.CLIENT_SIGNATURE.previewUnavailable = true;
}
});
});
break;
case 'PHOTO_PROOF':
case 'ADDRESS_PROOF':
this.loadIdentifierDocPreview(documentType, this.existing[documentType].documentId!);
break;
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
// Release object URLs
Object.values(this.existing).forEach((e) => {
if (e.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(e.previewUrl);
});
this.revokePreviewUrls();
}
}
@@ -0,0 +1,167 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="cud-header">
<div class="cud-header__badge">
<fa-icon icon="folder-open"></fa-icon>
</div>
<div class="cud-header__text">
<h2 mat-dialog-title class="cud-title">{{ data.title }}</h2>
<p class="cud-subtitle">Fill in the document details, then attach the scan.</p>
</div>
<button mat-icon-button mat-dialog-close class="cud-close" aria-label="Close">
<fa-icon icon="times"></fa-icon>
</button>
</div>
<mat-dialog-content class="cud-body">
@if (data.isProofKind) {
<div class="cud-section">
<span class="cud-section__label"><fa-icon icon="id-card"></fa-icon> Document type</span>
<mat-form-field appearance="outline" class="cud-field" subscriptSizing="dynamic">
<mat-select
[value]="selectedProofType"
[compareWith]="compareProofType"
placeholder="Select document type"
(selectionChange)="onProofTypeChange($event.value)"
>
@for (p of data.proofOptions; track p.id) {
<mat-option [value]="p">{{ p.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<p class="cud-hint">Upload requirements will update automatically based on the type you pick.</p>
</div>
@if (selectedProofType) {
@if (selectedProofType.info) {
<div class="cud-banner">
<fa-icon icon="check-circle"></fa-icon>
<span>{{ selectedProofType.info }}</span>
</div>
}
<div class="cud-section">
<span class="cud-section__label">
<fa-icon icon="hashtag"></fa-icon>
{{ selectedProofType.documentKeyLabel || 'Document number' }}
</span>
<mat-form-field appearance="outline" class="cud-field" subscriptSizing="dynamic">
<input
matInput
[(ngModel)]="documentKey"
[ngModelOptions]="{ standalone: true }"
[placeholder]="selectedProofType.documentKeyPlaceholder || 'Enter document number'"
/>
</mat-form-field>
</div>
<div class="cud-section cud-section--dates">
<div class="cud-date-field">
<span class="cud-section__label"><fa-icon icon="calendar-check"></fa-icon> Issue date</span>
<mat-form-field appearance="outline" class="cud-field" subscriptSizing="dynamic">
<input
matInput
readonly
[matDatepicker]="issuePicker"
[(ngModel)]="issueDate"
[ngModelOptions]="{ standalone: true }"
placeholder="Optional"
(click)="issuePicker.open()"
/>
<mat-datepicker-toggle matSuffix [for]="issuePicker"></mat-datepicker-toggle>
<mat-datepicker #issuePicker></mat-datepicker>
</mat-form-field>
</div>
<div class="cud-date-field">
<span class="cud-section__label"><fa-icon icon="calendar-check"></fa-icon> Expiry date</span>
<mat-form-field appearance="outline" class="cud-field" subscriptSizing="dynamic">
<input
matInput
readonly
[matDatepicker]="expiryPicker"
[(ngModel)]="expiryDate"
[ngModelOptions]="{ standalone: true }"
placeholder="Optional"
(click)="expiryPicker.open()"
/>
<mat-datepicker-toggle matSuffix [for]="expiryPicker"></mat-datepicker-toggle>
<mat-datepicker #expiryPicker></mat-datepicker>
</mat-form-field>
</div>
</div>
<div class="cud-divider"><span>Scan</span></div>
<div class="cud-grid" [class.cud-grid--two]="sides === 2">
<div class="cud-slot">
<span class="cud-slot__label">{{ sides === 2 ? 'Front side' : 'Document' }}</span>
<label class="cud-dropzone" [class.cud-dropzone--has]="front">
<input type="file" [attr.accept]="data.accept" hidden (change)="onFilePick('front', $event)" />
@if (frontPreview) {
<img [src]="frontPreview" alt="Front side preview" class="cud-dropzone__img" />
} @else if (front) {
<fa-icon icon="file-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__name">{{ front.name }}</p>
} @else {
<fa-icon icon="cloud-upload-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__text">Click to choose file</p>
}
</label>
</div>
@if (sides === 2) {
<div class="cud-slot">
<span class="cud-slot__label">Back side</span>
<label class="cud-dropzone" [class.cud-dropzone--has]="back">
<input type="file" [attr.accept]="data.accept" hidden (change)="onFilePick('back', $event)" />
@if (backPreview) {
<img [src]="backPreview" alt="Back side preview" class="cud-dropzone__img" />
} @else if (back) {
<fa-icon icon="file-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__name">{{ back.name }}</p>
} @else {
<fa-icon icon="cloud-upload-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__text">Click to choose file</p>
}
</label>
</div>
}
</div>
}
} @else {
<div class="cud-grid">
<div class="cud-slot">
<span class="cud-slot__label">Document</span>
<label class="cud-dropzone" [class.cud-dropzone--has]="front">
<input type="file" [attr.accept]="data.accept" hidden (change)="onFilePick('front', $event)" />
@if (frontPreview) {
<img [src]="frontPreview" alt="Preview" class="cud-dropzone__img" />
} @else if (front) {
<fa-icon icon="file-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__name">{{ front.name }}</p>
} @else {
<fa-icon icon="cloud-upload-alt" class="cud-dropzone__icon"></fa-icon>
<p class="cud-dropzone__text">Click to choose file</p>
}
</label>
</div>
</div>
}
</mat-dialog-content>
<mat-dialog-actions class="cud-actions" align="end">
<button mat-stroked-button type="button" (click)="cancel()">
<fa-icon icon="times"></fa-icon>
&nbsp;Cancel
</button>
<button mat-flat-button color="primary" type="button" [disabled]="!canSubmit" (click)="submit()">
<fa-icon icon="upload"></fa-icon>
&nbsp;Upload
</button>
</mat-dialog-actions>
@@ -0,0 +1,270 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
:host {
display: block;
max-width: 100%;
}
/* ===================== Header ===================== */
.cud-header {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 20px 24px 16px;
border-bottom: 1px solid #eef1f4;
&__badge {
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
font-size: 15px;
color: #fff;
background: linear-gradient(135deg, #1a73e8, #4285f4);
box-shadow: 0 3px 10px rgb(26 115 232 / 28%);
}
&__text {
flex: 1;
min-width: 0;
}
}
.cud-title {
margin: 0 !important;
padding: 0;
font-size: 16px;
font-weight: 700;
color: #1a1d21;
line-height: 1.3;
}
.cud-subtitle {
margin: 2px 0 0;
font-size: 12px;
color: #6b7280;
}
.cud-close {
flex-shrink: 0;
width: 32px;
height: 32px;
margin: -4px -4px 0 0;
color: #9aa0a6;
&:hover {
color: #3c4043;
}
}
/* ===================== Body / sections ===================== */
.cud-body.mat-mdc-dialog-content {
padding: 18px 24px !important;
max-height: 70vh;
}
.cud-section {
margin-bottom: 14px;
&--dates {
display: flex;
gap: 14px;
.cud-date-field {
flex: 1;
min-width: 0;
}
}
&__label {
display: flex;
align-items: center;
gap: 7px;
font-size: 11px;
font-weight: 700;
color: #475569;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 6px;
fa-icon {
color: #1a73e8;
font-size: 10.5px;
}
}
}
.cud-field {
width: 100%;
}
.cud-hint {
font-size: 12px;
color: #6b7280;
margin: 6px 0 0;
line-height: 1.4;
}
.cud-banner {
display: flex;
align-items: flex-start;
gap: 9px;
padding: 10px 14px;
margin-bottom: 14px;
background: #f0fbf6;
border: 1px solid #cfecdd;
border-radius: 10px;
font-size: 12.5px;
color: #085041;
line-height: 1.45;
fa-icon {
margin-top: 2px;
color: #1d9e75;
flex-shrink: 0;
}
}
.cud-divider {
display: flex;
align-items: center;
gap: 10px;
margin: 16px 0 12px;
font-size: 10.5px;
font-weight: 700;
color: #9aa0a6;
text-transform: uppercase;
letter-spacing: 0.08em;
&::before,
&::after {
content: '';
flex: 1;
height: 1px;
background: #eef1f4;
}
}
/* ===================== Front/back scan grid ===================== */
.cud-grid {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
&--two {
grid-template-columns: repeat(2, 1fr);
}
}
.cud-slot {
display: flex;
flex-direction: column;
gap: 6px;
&__label {
font-size: 10.5px;
font-weight: 700;
color: #5f6368;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
.cud-dropzone {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 130px;
padding: 16px;
border: 2px dashed #cbd5e1;
border-radius: 12px;
cursor: pointer;
text-align: center;
background: #fafbfc;
transition:
border-color 0.15s,
background 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #1a73e8;
background: #f5f9ff;
box-shadow: 0 2px 10px rgb(26 115 232 / 10%);
}
&--has {
border-style: solid;
border-color: #1d9e75;
background: #f0fbf6;
}
&__icon {
font-size: 22px;
color: #9aa5b1;
}
&--has &__icon {
color: #1d9e75;
}
&__text {
font-size: 12px;
color: #64748b;
margin: 0;
font-weight: 500;
}
&__name {
font-size: 11.5px;
color: #085041;
font-weight: 600;
margin: 0;
word-break: break-all;
padding: 0 8px;
}
&__img {
max-width: 100%;
max-height: 150px;
border-radius: 8px;
object-fit: contain;
box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
}
}
/* ===================== Actions ===================== */
.cud-actions {
padding: 12px 24px !important;
margin: 0 !important;
border-top: 1px solid #eef1f4;
fa-icon {
font-size: 12px;
}
}
@media (width <= 560px) {
:host {
width: 100%;
}
.cud-section--dates {
flex-direction: column;
gap: 14px;
}
.cud-grid--two {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,155 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, OnDestroy, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
MatDialogRef,
MAT_DIALOG_DATA,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose
} from '@angular/material/dialog';
import { MatIconButton } from '@angular/material/button';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { Dates } from 'app/core/utils/dates';
import { ProofType } from '../../../shared/kyc-proof-types';
export interface CkycUploadDialogData {
title: string;
isProofKind: boolean;
accept: string;
proofOptions?: ProofType[];
initialProofType?: ProofType | null;
initialDocumentKey?: string;
initialIssueDate?: Date | null;
initialExpiryDate?: Date | null;
}
export interface CkycUploadDialogResult {
proofType?: ProofType | null;
front: File;
back?: File;
/** Document number (Aadhaar/PAN/Passport number, etc.) — same field client creation collects. */
documentKey?: string;
/** 'yyyy-MM-dd', same as the rest of this app's date fields. */
issueDate?: string | null;
expiryDate?: string | null;
}
/**
* A focused popup for replacing/uploading one CKYC artefact at a time — opened from each card on
* the CKYC tab instead of expanding a form inline underneath it. Collects the same details
* client creation does for an identity/address proof (document type, number, issue + expiry
* date) and shows a client-side preview of whatever image is picked before it's ever sent to the
* server; the actual upload still happens back in CkycTabComponent (this dialog only collects
* the type, number, dates and file(s), then hands them back).
*/
@Component({
selector: 'mifosx-ckyc-upload-dialog',
templateUrl: './ckyc-upload-dialog.component.html',
styleUrls: ['./ckyc-upload-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
FormsModule,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose,
MatIconButton,
FaIconComponent
]
})
export class CkycUploadDialogComponent implements OnDestroy {
private dates = inject(Dates);
dialogRef = inject<MatDialogRef<CkycUploadDialogComponent, CkycUploadDialogResult | null>>(MatDialogRef);
data = inject<CkycUploadDialogData>(MAT_DIALOG_DATA);
selectedProofType: ProofType | null = this.data.initialProofType || null;
documentKey = this.data.initialDocumentKey || '';
issueDate: Date | null = this.data.initialIssueDate || null;
expiryDate: Date | null = this.data.initialExpiryDate || null;
front: File | null = null;
back: File | null = null;
frontPreview: string | null = null;
backPreview: string | null = null;
get sides(): number {
return this.data.isProofKind ? (this.selectedProofType?.sides ?? 1) : 1;
}
get canSubmit(): boolean {
if (this.data.isProofKind) {
if (!this.selectedProofType) return false;
if (!this.documentKey.trim()) return false;
}
if (!this.front) return false;
if (this.sides === 2 && !this.back) return false;
return true;
}
compareProofType = (a: ProofType | null, b: ProofType | null): boolean => (a?.id ?? null) === (b?.id ?? null);
onProofTypeChange(proof: ProofType | null): void {
this.selectedProofType = proof;
this.clearSlot('front');
this.clearSlot('back');
}
onFilePick(slot: 'front' | 'back', event: any): void {
const file = event?.target?.files?.[0];
if (event?.target) event.target.value = '';
if (!file) return;
this.clearSlot(slot);
const preview = file.type?.startsWith('image/') ? URL.createObjectURL(file) : null;
if (slot === 'front') {
this.front = file;
this.frontPreview = preview;
} else {
this.back = file;
this.backPreview = preview;
}
}
private clearSlot(slot: 'front' | 'back'): void {
if (slot === 'front') {
if (this.frontPreview) URL.revokeObjectURL(this.frontPreview);
this.front = null;
this.frontPreview = null;
} else {
if (this.backPreview) URL.revokeObjectURL(this.backPreview);
this.back = null;
this.backPreview = null;
}
}
submit(): void {
if (!this.canSubmit) return;
this.dialogRef.close({
proofType: this.selectedProofType,
front: this.front!,
back: this.sides === 2 ? this.back! : undefined,
documentKey: this.data.isProofKind ? this.documentKey.trim() : undefined,
issueDate: this.issueDate ? this.dates.getDate(this.issueDate) : null,
expiryDate: this.expiryDate ? this.dates.getDate(this.expiryDate) : null
});
}
cancel(): void {
this.dialogRef.close(null);
}
ngOnDestroy(): void {
if (this.frontPreview) URL.revokeObjectURL(this.frontPreview);
if (this.backPreview) URL.revokeObjectURL(this.backPreview);
}
}
@@ -229,7 +229,7 @@ export class IdentitiesTabComponent implements OnDestroy {
}
const identifierData = {
documentTypeId,
status: 'Active',
status: 'ACTIVE',
documentKey: kind === 'id' ? section.documentKey : `${proofName} - ${this.clientId}`,
description: kind === 'address' && section.address ? section.address : description
};
@@ -82,12 +82,13 @@
<strong class="kyc-doc-alert__title">{{ kycDocumentAlertTitle }}</strong>
<p class="kyc-doc-alert__text">{{ kycDocumentAlertMessage }}</p>
</div>
<!-- Same dialog as the document's own row: the banner is asking for exactly that. -->
<button
mat-flat-button
color="primary"
type="button"
class="kyc-doc-alert__action"
(click)="toggleEditMode()"
(click)="updateKycDocument()"
>
Update Document
</button>
@@ -470,7 +471,11 @@
}
</span>
<span class="kv-table__col kv-table__col--action">
<button mat-stroked-button class="kv-action-btn" type="button" (click)="toggleEditMode()">Update</button>
<!-- The document is re-collected in its own dialog, the way PAN and Aadhaar are dealt
with on their rows, rather than by opening the whole KYC form for editing. -->
<button mat-stroked-button class="kv-action-btn" type="button" (click)="updateKycDocument()">
Update
</button>
</span>
</div>
}
@@ -1188,15 +1193,81 @@
</mat-form-field>
</div>
<!-- The scans live with the document itself, on the identifier the customer's
original was attached to. Re-scanning is done there rather than duplicated
here, so both sides, the cropper and the replace-in-place all behave the
same way they did when the document was first collected. -->
<a class="kyc-doc-scans-link" [routerLink]="['/clients', clientId, 'edit']">
<mat-icon>photo_library</mat-icon>
<span>Replace the scanned front / back of this document</span>
<mat-icon class="kyc-doc-scans-link__go">chevron_right</mat-icon>
</a>
<!-- The scan, where the document it belongs to is. Re-collecting an expiring
document is what this panel is for, so sending the officer to the client
edit screen to change the image made them leave the record they were
working on and find the same document again. -->
<div class="kyc-doc-scans">
<div class="kyc-doc-scans__head">
<mat-icon>photo_library</mat-icon>
<span>Scanned document</span>
@if (docScansLoading) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
}
</div>
@if (!docScansLoading && !docScans.front && !docScans.back) {
<div class="kyc-doc-scans__empty">No scan is on file for this document. Upload one below.</div>
}
<div class="kyc-doc-scans__sides">
@for (slot of docScanSlots; track slot) {
<div class="kyc-doc-side">
<div class="kyc-doc-side__label">{{ slot === 'front' ? 'Front' : 'Back' }}</div>
<div class="kyc-doc-side__frame">
@if (docScanOf(slot)?.previewUrl) {
<img
[src]="docScanOf(slot)!.previewUrl"
[alt]="slot === 'front' ? 'Front of document' : 'Back of document'"
/>
} @else if (docScanOf(slot)) {
<!-- On file but not an image (a PDF, say) — named rather than shown. -->
<div class="kyc-doc-side__file">
<mat-icon>description</mat-icon>
<span>{{ docScanOf(slot)!.fileName }}</span>
</div>
} @else {
<div class="kyc-doc-side__none">Not on file</div>
}
</div>
<button
type="button"
mat-stroked-button
class="kyc-doc-side__btn"
[disabled]="!!docScanUploading || docScansLoading"
(click)="scanInput.click()"
>
@if (docScanUploading === slot) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
Uploading…
} @else {
{{ docScanOf(slot) ? 'Replace' : 'Upload' }}
}
</button>
<input
#scanInput
type="file"
hidden
accept="image/*,application/pdf"
(change)="onDocScanSelected($event, slot)"
/>
</div>
}
</div>
@if (docScanError) {
<div class="kyc-doc-scans__msg kyc-doc-scans__msg--err">
<mat-icon>error_outline</mat-icon><span>{{ docScanError }}</span>
</div>
}
@if (docScanSuccess) {
<div class="kyc-doc-scans__msg kyc-doc-scans__msg--ok">
<mat-icon>check_circle</mat-icon><span>{{ docScanSuccess }}</span>
</div>
}
</div>
</div>
}
@@ -1681,3 +1681,129 @@
.kyc-doc-scans-link__go {
margin-left: auto;
}
/* The scan itself, beside the number and dates it belongs to. */
.kyc-doc-scans {
margin-top: 10px;
padding: 12px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #fff;
}
.kyc-doc-scans__head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.03em;
text-transform: uppercase;
color: #475569;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: #64748b;
}
}
.kyc-doc-scans__empty {
margin-bottom: 10px;
font-size: 12.5px;
color: #64748b;
}
.kyc-doc-scans__sides {
display: flex;
flex-wrap: wrap;
gap: 14px;
}
.kyc-doc-side {
display: flex;
flex-direction: column;
gap: 6px;
width: 190px;
}
.kyc-doc-side__label {
font-size: 11.5px;
font-weight: 700;
color: #334155;
}
/* Fixed height so front and back line up whatever the scan's aspect ratio is. */
.kyc-doc-side__frame {
display: flex;
align-items: center;
justify-content: center;
height: 118px;
padding: 6px;
border: 1px solid #e2e8f0;
border-radius: 6px;
background: #f8fafc;
overflow: hidden;
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 3px;
}
}
.kyc-doc-side__none {
font-size: 12px;
color: #94a3b8;
}
.kyc-doc-side__file {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 0 6px;
font-size: 11px;
color: #475569;
text-align: center;
word-break: break-word;
mat-icon {
color: #64748b;
}
}
.kyc-doc-side__btn {
font-size: 12px;
mat-progress-spinner {
display: inline-block;
margin-right: 6px;
vertical-align: middle;
}
}
.kyc-doc-scans__msg {
display: flex;
align-items: center;
gap: 6px;
margin-top: 10px;
font-size: 12.5px;
mat-icon {
font-size: 17px;
width: 17px;
height: 17px;
}
&--err {
color: #b91c1c;
}
&--ok {
color: #15803d;
}
}
@@ -11,7 +11,7 @@ import { Component, OnInit, OnDestroy, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UntypedFormBuilder, UntypedFormGroup, Validators, FormsModule } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { catchError, of, Subject, takeUntil } from 'rxjs';
import { catchError, forkJoin, map, of, Subject, takeUntil } from 'rxjs';
/** Custom Services */
import { ClientsService } from '../../clients.service';
@@ -30,6 +30,11 @@ import {
AadhaarReceiptDialogComponent,
AadhaarReceiptResult
} from '../../shared/aadhaar-receipt-dialog/aadhaar-receipt-dialog.component';
import {
KycDocumentUpdateDialogComponent,
KycDocumentUpdateData,
KycDocumentUpdateResult
} from '../../shared/kyc-document-update-dialog/kyc-document-update-dialog.component';
import { Dates } from 'app/core/utils/dates';
import { jsPDF } from 'jspdf';
import { MatIcon } from '@angular/material/icon';
@@ -38,6 +43,15 @@ import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** One side of the scanned KYC document, with the preview once it has been fetched. */
interface DocScanSide {
documentId: string;
/** The identifier row this scan hangs off; the two sides can sit on different rows. */
identifierId: string;
fileName: string;
previewUrl: string | null;
}
/**
* KYC Tab Component.
* Displays and manages KYC (Know Your Customer) details for an existing client.
@@ -149,9 +163,42 @@ export class KycTabComponent implements OnInit, OnDestroy {
exceptionReason: [[]]
});
// ── Officially valid document scans ────────────────────────────────────────
/**
* The scans of the document named above, by side.
*
* The screen used to show the document's number and dates but not the image behind them, and
* sent the officer to the client edit screen to change it. Re-collecting an expiring document is
* the one thing this panel exists for, so the scan is shown and replaced here.
*/
docScans: { front: DocScanSide | null; back: DocScanSide | null } = { front: null, back: null };
/** The two sides, in display order, so the template loops rather than repeating itself. */
readonly docScanSlots: ('front' | 'back')[] = [
'front',
'back'
];
docScanOf(slot: 'front' | 'back') {
return this.docScans[slot];
}
/** Identifier row replacements are filed against. Null when the document has no identifier. */
private docIdentifierId: string | null = null;
/** Every identifier row carrying this document, since the sides can be split across them. */
private docIdentifierIds: string[] = [];
docScansLoading = false;
/** Which side is mid-upload, so only that button shows a spinner. */
docScanUploading: 'front' | 'back' | null = null;
docScanError: string | null = null;
docScanSuccess: string | null = null;
ngOnInit(): void {
this.route.parent.params.subscribe((params: any) => {
this.clientId = params['clientId'];
// Scans are matched against the document number on the KYC record, so they are loaded once
// that record has arrived rather than alongside it.
this.loadKycData();
this.loadClientDateOfBirth();
});
@@ -190,6 +237,8 @@ export class KycTabComponent implements OnInit, OnDestroy {
isException: data.isException || false,
exceptionReason: data.exceptionReason ? data.exceptionReason.split(', ') : []
});
// Now that the document number is known, the scans filed under it can be found.
this.loadDocumentScans();
}
});
}
@@ -1307,6 +1356,305 @@ I further confirm that:
doc.save(`Self_Declaration_${cifNumber}_${clientName.replace(/\s/g, '_')}.pdf`);
}
// ── Document scans ─────────────────────────────────────────────────────────
/**
* Finds the identifier the KYC document was filed under and loads its scans.
*
* The KYC record keeps the document's name and number but not the identifier id, so the two are
* matched on the number — that is what makes them the same document, and it survives the client
* holding several identifiers of the same type.
*/
private loadDocumentScans(): void {
if (!this.clientId) {
return;
}
this.docScansLoading = true;
this.clientsService
.getClientIdentifiers(this.clientId)
.pipe(catchError(() => of([] as any[])))
.subscribe((identifiers: any[]) => {
const wantedKey = (this.kycData?.kycDocumentNumber || '').toString().trim();
const wantedName = (this.kycData?.kycDocumentName || '').toString().trim().toLowerCase();
const norm = (s: any) => (s || '').toString().trim().toLowerCase();
// Every identifier carrying this document number, not just the first. The onboarding step
// files each side against its own identifier row, so this client's Aadhaar front sits on
// one row and the back on another under the same number - taking only the first match
// showed the front and reported the back as missing.
let matches = (identifiers || []).filter((i) => wantedKey && norm(i.documentKey) === norm(wantedKey));
if (!matches.length) {
matches = (identifiers || []).filter((i) => wantedName && norm(i.documentType?.name) === wantedName);
}
if (!matches.length) {
this.docScansLoading = false;
this.docIdentifierId = null;
this.docIdentifierIds = [];
this.docScans = { front: null, back: null };
return;
}
// Replacements are filed against the first row, so the sides stay together from here on.
this.docIdentifierId = String(matches[0].id);
this.docIdentifierIds = matches.map((m: any) => String(m.id));
this.fetchScansFor(this.docIdentifierIds);
});
}
/**
* Sides are read off the document name, which is how they were written at upload
* ("<Proof> — Front" / "— Back"). Where the name says nothing, upload order stands in, front
* first, rather than leaving a scan the officer cannot see.
*/
private fetchScansFor(identifierIds: string[]): void {
forkJoin(
identifierIds.map((id) =>
this.clientsService.getClientIdentificationDocuments(id).pipe(
// Tagged with the row it came from, because the download call needs the parent id and
// the sides can be spread across more than one.
map((docs: any) => ((docs as any[]) || []).map((d) => ({ ...d, identifierId: id }))),
catchError(() => of([] as any[]))
)
)
).subscribe((perIdentifier: any[][]) => {
this.docScansLoading = false;
// This runs again after every replace, so the previews being thrown away are revoked
// rather than left holding their blobs.
for (const old of [
this.docScans.front,
this.docScans.back
]) {
if (old?.previewUrl) {
URL.revokeObjectURL(old.previewUrl);
}
}
// Oldest first by document id, so the newest upload for a side is the last one written and
// therefore the one that stands. Identifier order cannot do this job: a replacement is filed
// against the first row while the original sits on the second, so reading the rows in order
// let a document uploaded months ago overwrite the scan collected a moment ago - the officer
// pressed Replace, saw "replaced", and the old image came straight back.
const docs = perIdentifier.flat().sort((a, b) => Number(a.id) - Number(b.id));
const sides: typeof this.docScans = { front: null, back: null };
const unlabelled: any[] = [];
const entryOf = (d: any): DocScanSide => ({
documentId: String(d.id),
identifierId: String(d.identifierId),
fileName: d.fileName || d.name,
previewUrl: null
});
for (const d of docs) {
const text = `${d.name || ''} ${d.fileName || ''}`.toLowerCase();
// Later uploads win, so a replaced side shows the new scan rather than the original.
if (text.includes('back')) {
sides.back = entryOf(d);
} else if (text.includes('front')) {
sides.front = entryOf(d);
} else {
unlabelled.push(d);
}
}
for (const d of unlabelled) {
if (!sides.front) {
sides.front = entryOf(d);
} else if (!sides.back) {
sides.back = entryOf(d);
}
}
this.docScans = sides;
for (const key of [
'front',
'back'
] as const) {
if (sides[key]) {
this.loadScanPreview(sides[key]!);
}
}
});
}
private loadScanPreview(side: DocScanSide): void {
this.clientsService
.downloadClientIdentificationDocument(side.identifierId, side.documentId)
.pipe(catchError(() => of(null)))
.subscribe((blob: Blob | null) => {
if (!blob || !blob.type?.startsWith('image/')) {
return;
}
// Revoked in ngOnDestroy; a preview left behind holds the blob in memory for the life of
// the tab.
side.previewUrl = URL.createObjectURL(blob);
});
}
/**
* Replaces one side with a freshly collected scan.
*
* The new file is uploaded under the same side name, which is what the readers here and on the
* client screen key on, so the latest upload becomes the scan on show. The old file is left in
* place deliberately: a KYC document that has been re-collected is a record of what was held
* before and when it changed, and destroying it would leave the audit trail with a gap.
*/
onDocScanSelected(event: Event, slot: 'front' | 'back'): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
// Cleared so choosing the same filename twice still fires a change event.
input.value = '';
if (!file || !this.docIdentifierId) {
return;
}
this.docScanError = null;
this.docScanSuccess = null;
this.docScanUploading = slot;
const label = slot === 'front' ? 'Front' : 'Back';
const docName = this.kycForm.get('kycDocumentName')?.value || this.kycData?.kycDocumentName || 'KYC document';
const formData = new FormData();
formData.append('file', file);
formData.append('name', `${docName} — ${label}`);
formData.append('description', `Re-collected on ${new Date().toLocaleDateString('en-IN')}`);
this.clientsService.uploadClientIdentifierDocument(this.docIdentifierId, formData).subscribe({
next: () => {
this.docScanUploading = null;
this.docScanSuccess = `${label} side replaced.`;
// Re-read every row, not just the one written to: the other side still lives on its own.
this.fetchScansFor(this.docIdentifierIds);
},
error: (err: any) => {
this.docScanUploading = null;
this.docScanError =
err?.error?.defaultUserMessage ||
err?.error?.developerMessage ||
`Could not replace the ${label.toLowerCase()} side.`;
}
});
}
/**
* A verified record only accepts an amendment with a reason on it, so the dialog has to ask for
* one. 300 is VERIFIED; the code form is checked too, since either can arrive on the payload.
*/
private get isKycVerified(): boolean {
return this.kycData?.kycStatus === 300 || this.kycData?.kycStatusCode === 'clientKycStatus.verified';
}
/**
* Re-collects the officially valid document from its own row.
*
* PAN and Aadhaar are each handled on their row; this one sent the officer into edit mode on the
* whole KYC form to do the same job. The dialog asks for the number, the dates and each side of
* the scan together, which is what re-collecting a document actually is.
*/
updateKycDocument(): void {
if (!this.kycId) {
this.docScanError = 'KYC record not found. Save KYC details first.';
return;
}
this.dialog
.open(KycDocumentUpdateDialogComponent, {
width: '640px',
maxWidth: '95vw',
disableClose: true,
data: {
documentName: this.kycData?.kycDocumentName || 'KYC document',
documentNumber: this.kycData?.kycDocumentNumber || '',
issueDate: this.parseApiDate(this.kycData?.kycDocIssueDate),
expiryDate: this.parseApiDate(this.kycData?.kycDocExpiryDate),
reason: this.showKycDocumentAlert ? this.kycDocumentAlertMessage : '',
currentFront: this.docScans.front?.previewUrl || null,
currentBack: this.docScans.back?.previewUrl || null,
requiresRemarks: this.isKycVerified
} as KycDocumentUpdateData
})
.afterClosed()
.subscribe((result: KycDocumentUpdateResult | undefined) => {
if (result) {
this.persistKycDocument(result);
}
});
}
/**
* Saves the corrected details, then uploads whichever sides were re-scanned.
*
* The details go first: they are the record, and a scan attached to a document whose number was
* never corrected would file the new image under the old identity.
*/
private persistKycDocument(result: KycDocumentUpdateResult): void {
this.saving = true;
this.docScanError = null;
this.docScanSuccess = null;
const dateFormat = 'dd MMMM yyyy';
const payload: any = {
locale: 'en',
dateFormat,
kycDocumentName: this.kycData?.kycDocumentName || null,
kycDocumentNumber: result.documentNumber || null,
kycDocIssueDate: result.issueDate ? this.dateUtils.formatDate(result.issueDate, dateFormat) : null,
kycDocExpiryDate: result.expiryDate ? this.dateUtils.formatDate(result.expiryDate, dateFormat) : null
};
// The server refuses an amendment to a verified record without one, and records it as the
// reason the document changed.
if (result.remarks) {
payload.remarks = result.remarks;
}
this.clientsService.updateClientKyc(this.clientId, this.kycId!, payload).subscribe({
next: () => {
this.saving = false;
this.docScanSuccess = 'Document updated.';
this.loadKycData();
this.uploadReplacedSides(result);
},
error: (err: any) => {
this.saving = false;
this.docScanError =
err?.error?.defaultUserMessage || err?.error?.developerMessage || 'Could not update the document.';
}
});
}
/** Sends each re-scanned side through the same upload path the panel below uses. */
private uploadReplacedSides(result: KycDocumentUpdateResult): void {
if (!this.docIdentifierId) {
return;
}
const sides: { slot: 'front' | 'back'; file: File }[] = [];
if (result.front) {
sides.push({ slot: 'front', file: result.front });
}
if (result.back) {
sides.push({ slot: 'back', file: result.back });
}
if (!sides.length) {
return;
}
const docName = this.kycData?.kycDocumentName || 'KYC document';
forkJoin(
sides.map(({ slot, file }) => {
const formData = new FormData();
formData.append('file', file);
formData.append('name', `${docName} — ${slot === 'front' ? 'Front' : 'Back'}`);
formData.append('description', `Re-collected on ${new Date().toLocaleDateString('en-IN')}`);
return this.clientsService
.uploadClientIdentifierDocument(this.docIdentifierId!, formData)
.pipe(catchError(() => of(null)));
})
).subscribe(() => {
this.docScanSuccess = 'Document and scan updated.';
this.fetchScansFor(this.docIdentifierIds);
});
}
/** Handle file selection for signed declaration upload */
onDeclarationFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
@@ -1365,5 +1713,14 @@ I further confirm that:
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
// Object URLs are held by the browser until revoked, so the scan blobs would outlive the tab.
for (const side of [
this.docScans.front,
this.docScans.back
]) {
if (side?.previewUrl) {
URL.revokeObjectURL(side.previewUrl);
}
}
}
}
@@ -840,6 +840,15 @@ export class CreateClientComponent {
this.saveAddressProof(clientId);
}
/** "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" — same convention the CKYC tab and
* client-india-address-step's own "load existing" parsing both read back. */
private buildProofDescription(issueDate: string | null | undefined, expiryDate: string | null | undefined): string {
const parts: string[] = [];
if (issueDate) parts.push(`Issue date: ${issueDate}`);
if (expiryDate) parts.push(`Expiry date: ${expiryDate}`);
return parts.join(', ');
}
/**
* Save the address-proof picked on the permanent tab as a client identifier
* + upload each selected file as a document attached to that identifier.
@@ -855,9 +864,9 @@ export class CreateClientComponent {
const proofName = payload.proof?.name || 'Address Proof';
const identifierData: any = {
documentTypeId: payload.proofId,
status: 'Active',
status: 'ACTIVE',
documentKey: payload.documentKey || `${proofName} - ${clientId}`,
description: payload.issueDate ? `Issue date: ${payload.issueDate}` : ''
description: this.buildProofDescription(payload.issueDate, payload.expiryDate)
};
this.clientsService.addClientIdentifier(clientId, identifierData).subscribe({
@@ -904,7 +913,7 @@ export class CreateClientComponent {
}
const identifierData: any = {
documentTypeId,
status: 'Active',
status: 'ACTIVE',
documentKey: payload.documentKey || `${proofName} - ${clientId}`,
description: 'KYC document'
};
@@ -164,6 +164,13 @@ export class ContactOtpBlockComponent implements OnChanges, OnDestroy {
request$.subscribe({
next: (res: any) => {
this.sending = false;
// The backend reports failure to actually dispatch the OTP (gateway error, flagged
// number, SMTP failure...) as a 200 response with success:false and a real reason in
// `message` — never a thrown error. Surface that reason instead of treating it as sent.
if (res?.success === false) {
this.errorMessage = res?.message || 'Could not send OTP.';
return;
}
this.otpId = res?.otpId ?? res?.resourceId ?? null;
this.otpSent = true;
this.clearAllDigits();
@@ -1035,6 +1035,15 @@ export class EditClientComponent {
this.saveAddressProof(clientId);
}
/** "Issue date: yyyy-MM-dd, Expiry date: yyyy-MM-dd" — same convention the CKYC tab and
* client-india-address-step's own "load existing" parsing both read back. */
private buildProofDescription(issueDate: string | null | undefined, expiryDate: string | null | undefined): string {
const parts: string[] = [];
if (issueDate) parts.push(`Issue date: ${issueDate}`);
if (expiryDate) parts.push(`Expiry date: ${expiryDate}`);
return parts.join(', ');
}
/**
* Save the address-proof picked on the permanent tab as a client identifier
* + upload each selected file as a document attached to that identifier.
@@ -1050,9 +1059,9 @@ export class EditClientComponent {
const proofName = payload.proof?.name || 'Address Proof';
const identifierData: any = {
documentTypeId: payload.proofId,
status: 'Active',
status: 'ACTIVE',
documentKey: payload.documentKey || `${proofName} - ${clientId}`,
description: payload.issueDate ? `Issue date: ${payload.issueDate}` : ''
description: this.buildProofDescription(payload.issueDate, payload.expiryDate)
};
this.clientsService.addClientIdentifier(clientId, identifierData).subscribe({
@@ -1105,7 +1114,7 @@ export class EditClientComponent {
const existingId = this.clientKycStep?.existingKycIdentifierId;
if (existingId) {
this.resolveDocumentTypeId(payload.proofId, proofName).subscribe((documentTypeId: number | null) => {
const update: any = { documentKey: payload.documentKey || `${proofName} - ${clientId}`, status: 'Active' };
const update: any = { documentKey: payload.documentKey || `${proofName} - ${clientId}`, status: 'ACTIVE' };
if (documentTypeId != null) {
update.documentTypeId = documentTypeId;
}
@@ -1128,7 +1137,7 @@ export class EditClientComponent {
}
const identifierData: any = {
documentTypeId,
status: 'Active',
status: 'ACTIVE',
documentKey: payload.documentKey || `${proofName} - ${clientId}`,
description: 'KYC document'
};
@@ -0,0 +1,131 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<h2 mat-dialog-title class="kdu-title">
<mat-icon>description</mat-icon>
Update {{ data.documentName }}
</h2>
<mat-dialog-content class="kdu-body">
<!-- Why this is being asked for, in the words the alert used. -->
@if (data.reason) {
<div class="kdu-reason">
<mat-icon>schedule</mat-icon>
<span>{{ data.reason }}</span>
</div>
}
<form [formGroup]="form" class="kdu-form">
<mat-form-field appearance="outline" class="kdu-field kdu-field--wide">
<mat-label>Document Number</mat-label>
<input matInput formControlName="documentNumber" autocomplete="off" />
@if (form.get('documentNumber')?.hasError('required') && form.get('documentNumber')?.touched) {
<mat-error>Document number is required</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline" class="kdu-field">
<mat-label>Issued On</mat-label>
<input matInput [matDatepicker]="issuePicker" formControlName="issueDate" />
<mat-datepicker-toggle matSuffix [for]="issuePicker"></mat-datepicker-toggle>
<mat-datepicker #issuePicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline" class="kdu-field">
<mat-label>Valid Till</mat-label>
<input matInput [matDatepicker]="expiryPicker" formControlName="expiryDate" />
<mat-datepicker-toggle matSuffix [for]="expiryPicker"></mat-datepicker-toggle>
<mat-datepicker #expiryPicker></mat-datepicker>
<mat-hint>Blank if it does not expire</mat-hint>
</mat-form-field>
<!-- Only where the KYC record is already verified. Changing what a verified record holds is an
amendment, and the reason goes on the record with it. -->
@if (data.requiresRemarks) {
<mat-form-field appearance="outline" class="kdu-field kdu-field--wide">
<mat-label>Reason for update</mat-label>
<textarea
matInput
formControlName="remarks"
rows="2"
placeholder="e.g. Document expired — fresh copy collected from the customer"
></textarea>
<mat-hint>Recorded against the verified KYC record</mat-hint>
@if (form.get('remarks')?.hasError('required') && form.get('remarks')?.touched) {
<mat-error>A reason is required to change a verified KYC record</mat-error>
}
</mat-form-field>
}
</form>
<div class="kdu-scans">
<div class="kdu-scans__head">Scanned copy</div>
<p class="kdu-scans__hint">
Leave a side untouched to keep the scan already on file. The previous copy is kept either way.
</p>
<div class="kdu-sides">
@for (slot of slots; track slot) {
<div class="kdu-side">
<div class="kdu-side__label">
{{ slot === 'front' ? 'Front' : 'Back' }}
@if (isReplaced(slot)) {
<span class="kdu-side__new">New</span>
}
</div>
<div class="kdu-side__frame" [class.kdu-side__frame--new]="isReplaced(slot)">
@if (previewOf(slot)) {
<img [src]="previewOf(slot)" [alt]="slot === 'front' ? 'Front of document' : 'Back of document'" />
} @else if (isReplaced(slot)) {
<!-- Picked, but not an image (a PDF, say) — named rather than shown. -->
<div class="kdu-side__file">
<mat-icon>insert_drive_file</mat-icon>
<span>{{ pickedName(slot) }}</span>
</div>
} @else {
<div class="kdu-side__none">Not on file</div>
}
</div>
<div class="kdu-side__actions">
<button type="button" mat-stroked-button class="kdu-side__btn" (click)="sideInput.click()">
{{ previewOf(slot) || isReplaced(slot) ? 'Choose new scan' : 'Upload scan' }}
</button>
@if (isReplaced(slot)) {
<button
type="button"
mat-icon-button
class="kdu-side__undo"
matTooltip="Keep the scan already on file"
(click)="clearPick(slot)"
>
<mat-icon>undo</mat-icon>
</button>
}
</div>
<input #sideInput type="file" hidden accept="image/*,application/pdf" (change)="onFilePicked($event, slot)" />
</div>
}
</div>
</div>
</mat-dialog-content>
<mat-dialog-actions align="end" class="kdu-actions">
<button mat-stroked-button type="button" (click)="cancel()">Cancel</button>
<button
mat-flat-button
color="primary"
type="button"
[disabled]="form.invalid || !hasChanges"
[matTooltip]="!hasChanges ? 'Change a detail or add a scan first' : ''"
(click)="submit()"
>
Save Document
</button>
</mat-dialog-actions>
@@ -0,0 +1,172 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.kdu-title {
display: flex;
align-items: center;
gap: 8px;
mat-icon {
color: #64748b;
}
}
.kdu-body {
padding-top: 4px;
}
.kdu-reason {
display: flex;
align-items: flex-start;
gap: 8px;
margin-bottom: 16px;
padding: 10px 12px;
border: 1px solid #fde68a;
border-radius: 6px;
background: #fffbeb;
color: #92400e;
font-size: 13px;
line-height: 1.5;
mat-icon {
flex: 0 0 auto;
font-size: 18px;
width: 18px;
height: 18px;
color: #d97706;
}
}
.kdu-form {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.kdu-field {
flex: 1 1 180px;
}
.kdu-field--wide {
flex: 1 1 100%;
}
.kdu-scans {
margin-top: 8px;
padding: 12px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #f8fafc;
}
.kdu-scans__head {
font-size: 12px;
font-weight: 700;
letter-spacing: 0.03em;
text-transform: uppercase;
color: #475569;
}
.kdu-scans__hint {
margin: 4px 0 12px;
font-size: 12px;
color: #64748b;
}
.kdu-sides {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.kdu-side {
display: flex;
flex-direction: column;
gap: 6px;
width: 210px;
}
.kdu-side__label {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 700;
color: #334155;
}
/* Marks the side the officer has just re-scanned, so it is obvious what will change on save. */
.kdu-side__new {
padding: 1px 7px;
border-radius: 999px;
background: #dcfce7;
color: #15803d;
font-size: 10.5px;
font-weight: 700;
}
.kdu-side__frame {
display: flex;
align-items: center;
justify-content: center;
height: 132px;
padding: 6px;
border: 1px solid #e2e8f0;
border-radius: 6px;
background: #fff;
overflow: hidden;
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 3px;
}
&--new {
border-color: #86efac;
box-shadow: 0 0 0 1px #86efac;
}
}
.kdu-side__none {
font-size: 12px;
color: #94a3b8;
}
.kdu-side__file {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 0 6px;
font-size: 11px;
color: #475569;
text-align: center;
word-break: break-word;
mat-icon {
color: #64748b;
}
}
.kdu-side__actions {
display: flex;
align-items: center;
gap: 4px;
}
.kdu-side__btn {
flex: 1;
font-size: 12px;
}
.kdu-actions {
padding: 8px 24px 20px;
gap: 8px;
}
@@ -0,0 +1,215 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/** Angular Imports */
import { Component, OnDestroy, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UntypedFormBuilder, UntypedFormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** What the caller hands in: the document as it stands, and the scans already on file. */
export interface KycDocumentUpdateData {
documentName: string;
documentNumber: string;
issueDate: Date | string | null;
expiryDate: Date | string | null;
/** Why the document is being asked for, shown at the top so the officer sees the reason. */
reason: string;
/** Previews of what is currently held, so the officer can see what they are replacing. */
currentFront: string | null;
currentBack: string | null;
/**
* True when the KYC record is already verified. Changing data on one of those needs a reason on
* the record, which the server enforces - so the dialog asks for it rather than letting the
* officer fill the whole form in and be refused on submit.
*/
requiresRemarks: boolean;
}
/** What the caller gets back: the corrected details, plus whichever sides were re-scanned. */
export interface KycDocumentUpdateResult {
documentNumber: string;
issueDate: Date | null;
expiryDate: Date | null;
front: File | null;
back: File | null;
/** Why the document was re-collected. Blank unless the record was already verified. */
remarks: string;
}
/**
* Re-collects an officially valid document without leaving the KYC record.
*
* PAN and Aadhaar are each dealt with on their own row of the verification table. The OVD was the
* exception: its Update button put the whole KYC form into edit mode, so re-collecting one expiring
* document meant scrolling a form of unrelated fields and finding the same document again. The work
* is the same either way - a new number, new dates, a fresh scan of each side - so it is asked for
* in one place.
*/
@Component({
selector: 'mifosx-kyc-document-update-dialog',
templateUrl: './kyc-document-update-dialog.component.html',
styleUrls: ['./kyc-document-update-dialog.component.scss'],
standalone: true,
// The shared set carries the date adapter the two datepickers below need; the sibling dialogs
// pull it in the same way.
imports: [
...STANDALONE_SHARED_IMPORTS,
CommonModule,
ReactiveFormsModule,
MatDialogModule,
MatButtonModule,
MatDatepickerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressSpinnerModule,
MatTooltipModule
]
})
export class KycDocumentUpdateDialogComponent implements OnDestroy {
private formBuilder = inject(UntypedFormBuilder);
private dialogRef = inject<MatDialogRef<KycDocumentUpdateDialogComponent>>(MatDialogRef);
data = inject<KycDocumentUpdateData>(MAT_DIALOG_DATA);
form: UntypedFormGroup;
/** Newly chosen files, with a local preview so the officer sees what they picked. */
picked: { front: File | null; back: File | null } = { front: null, back: null };
pickedPreview: { front: string | null; back: string | null } = { front: null, back: null };
readonly slots: ('front' | 'back')[] = [
'front',
'back'
];
constructor() {
this.form = this.formBuilder.group({
documentNumber: [
this.data.documentNumber || '',
[Validators.required]
],
issueDate: [this.toDate(this.data.issueDate)],
// Left free rather than required: a passport expires, a PAN card does not.
expiryDate: [this.toDate(this.data.expiryDate)],
// Required only where the server requires it, so completing a record that was never verified
// does not demand a justification for filling in blanks.
remarks: [
'',
this.data.requiresRemarks ? [Validators.required] : []
]
});
}
private toDate(value: Date | string | null): Date | null {
if (!value) {
return null;
}
const d = value instanceof Date ? value : new Date(value);
return isNaN(d.getTime()) ? null : d;
}
previewOf(slot: 'front' | 'back'): string | null {
return this.pickedPreview[slot] || (slot === 'front' ? this.data.currentFront : this.data.currentBack);
}
/** True once this side has been re-scanned in this dialog, so the label can say so. */
isReplaced(slot: 'front' | 'back'): boolean {
return !!this.picked[slot];
}
pickedName(slot: 'front' | 'back'): string {
return this.picked[slot]?.name || '';
}
onFilePicked(event: Event, slot: 'front' | 'back'): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0] || null;
// Cleared so re-picking the same filename still fires a change event.
input.value = '';
if (!file) {
return;
}
if (this.pickedPreview[slot]) {
URL.revokeObjectURL(this.pickedPreview[slot]!);
}
this.picked[slot] = file;
this.pickedPreview[slot] = file.type.startsWith('image/') ? URL.createObjectURL(file) : null;
}
clearPick(slot: 'front' | 'back'): void {
if (this.pickedPreview[slot]) {
URL.revokeObjectURL(this.pickedPreview[slot]!);
}
this.picked[slot] = null;
this.pickedPreview[slot] = null;
}
/**
* Something has to change for the update to mean anything - either a corrected detail or a fresh
* scan. Submitting an untouched form would reopen a verified KYC record for no reason.
*/
get hasChanges(): boolean {
if (this.picked.front || this.picked.back) {
return true;
}
const v = this.form.value;
const sameNumber = (v.documentNumber || '').trim() === (this.data.documentNumber || '').trim();
const sameIssue = this.sameDay(v.issueDate, this.toDate(this.data.issueDate));
const sameExpiry = this.sameDay(v.expiryDate, this.toDate(this.data.expiryDate));
return !(sameNumber && sameIssue && sameExpiry);
}
private sameDay(a: Date | null, b: Date | null): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}
submit(): void {
if (this.form.invalid || !this.hasChanges) {
this.form.markAllAsTouched();
return;
}
const v = this.form.value;
const result: KycDocumentUpdateResult = {
documentNumber: (v.documentNumber || '').trim(),
issueDate: v.issueDate || null,
expiryDate: v.expiryDate || null,
front: this.picked.front,
back: this.picked.back,
remarks: (v.remarks || '').trim()
};
this.dialogRef.close(result);
}
cancel(): void {
this.dialogRef.close();
}
ngOnDestroy(): void {
// Only the previews this dialog created; the caller owns the ones it passed in.
for (const slot of this.slots) {
if (this.pickedPreview[slot]) {
URL.revokeObjectURL(this.pickedPreview[slot]!);
}
}
}
}