feat(clients): dual-OTP contact-change verification, webcam signature capture, and client history tab
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s

Frontend counterpart to the backend dual-OTP contact-change feature:

- New ContactOtpBlockComponent (6-box segmented OTP input) used up to 4x in
  Edit Client (old/new mobile, old/new email — grouped under per-field
  sub-headers) and once each for mobile/email in Create Client, gating
  Save/Save & Next until every required box is verified.
- edit-client.component.ts: detects mobile/email/DOB changes against the
  loaded snapshot using local-date comparison (not `.toISOString()`, which
  false-triggers a day-shift in positive-UTC-offset timezones) and
  trimmed/case-insensitive email comparison (autofill whitespace or re-typed
  casing no longer reads as a change the masked preview can't explain).
- client-kyc-step.component.ts: new `invalidFieldLabels` getter names every
  currently-invalid required KYC field, surfaced via the Save & Next tooltip
  in both create-client and edit-client so a greyed-out button always
  explains what's still missing instead of a generic message.
- CaptureImageDialogComponent generalized for both profile photo and
  signature (photograph-a-paper-signature) capture:
  - Frame aspect now matches the requested getUserMedia resolution
    (4:3 profile / 16:9 signature) with object-fit: cover, eliminating the
    pillarboxing (black bars) a mismatched box previously caused.
  - Suppresses Chromium's auto-injected PiP/cast corner overlay icons.
  - Frame height capped in vh (not just px) so the dialog fits short
    viewports instead of pushing Cancel/Upload below the fold.
- upload-document-dialog.component.ts: generic Documents-tab upload now also
  offers "Capture from Webcam" alongside Browse, reusing the same capture
  dialog.
- New client History tab (reuses the existing Audit Trail data, scoped to
  this client) and dataUrlToFile/dataUrlToBlob util for routing webcam
  captures through the same upload pipelines as a picked file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-26 14:51:04 +05:30
co-authored by Claude Sonnet 5
parent d334dd1669
commit 733d9d22b2
30 changed files with 1803 additions and 43 deletions
@@ -0,0 +1,76 @@
<!--
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="cotp-block" [class.cotp-block--verified]="verified">
<div class="cotp-block__header">
<span class="cotp-block__label">{{ label }}</span>
<span class="cotp-block__target">{{ maskedDestination }}</span>
</div>
@if (verified) {
<div class="cotp-block__verified">
<fa-icon icon="check-circle"></fa-icon>
<span>Verified</span>
</div>
} @else if (!otpSent) {
<button type="button" class="cotp-btn cotp-btn--primary" (click)="sendOtp()" [disabled]="sending || !destination">
@if (sending) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
<span>Sending…</span>
} @else {
<fa-icon icon="paper-plane"></fa-icon>
<span>Send OTP</span>
}
</button>
} @else {
<div class="cotp-otp">
@for (i of digitIndexes; track i) {
<input
#digitBox
type="text"
inputmode="numeric"
maxlength="1"
class="cotp-otp__box"
[value]="digitControls[i].value"
[attr.autocomplete]="i === 0 ? 'one-time-code' : 'off'"
(input)="onDigitInput(i, $any($event.target).value)"
(keydown)="onDigitKeydown(i, $event)"
(paste)="onDigitPaste($event)"
/>
}
</div>
<div class="cotp-block__actions">
<button
type="button"
class="cotp-btn cotp-btn--primary"
(click)="verifyOtp()"
[disabled]="!codeValid || verifying"
>
@if (verifying) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
<span>Verifying…</span>
} @else {
<fa-icon icon="check-circle"></fa-icon>
<span>Verify</span>
}
</button>
<button type="button" class="cotp-btn cotp-btn--ghost" (click)="resendOtp()" [disabled]="resendCountdown > 0">
<fa-icon icon="redo"></fa-icon>
<span>{{ resendCountdown > 0 ? 'Resend (' + resendCountdown + 's)' : 'Resend OTP' }}</span>
</button>
</div>
}
@if (errorMessage) {
<div class="cotp-error">
<fa-icon icon="exclamation-circle"></fa-icon>
{{ errorMessage }}
</div>
}
</div>
@@ -0,0 +1,177 @@
/**
* 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/.
*/
/* Card with 6 individually-bordered digit boxes (not the single-input/background-gradient
* trick used elsewhere in this app) — each box is its own <input>, so focus/border state is
* per-digit rather than shared across the whole code. */
:host {
display: block;
}
.cotp-block {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
padding: 28px 24px;
border: 1px solid #e7ecf3;
border-radius: 18px;
background: #fff;
box-shadow: 0 8px 24px -8px rgb(15 23 42 / 10%);
text-align: center;
&--verified {
border-color: #86efac;
background: #f7fdf9;
}
}
.cotp-block__header {
display: flex;
flex-direction: column;
gap: 6px;
}
.cotp-block__label {
font-size: 15px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.4px;
color: #1e293b;
}
.cotp-block__target {
font-size: 15px;
font-weight: 700;
color: #1074b9;
word-break: break-all;
}
.cotp-block__verified {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 16px;
border-radius: 999px;
background: #dcfce7;
color: #15803d;
font-size: 13px;
font-weight: 700;
}
.cotp-block__actions {
display: flex;
justify-content: center;
gap: 12px;
width: 100%;
}
.cotp-otp {
display: flex;
justify-content: center;
gap: 10px;
}
.cotp-otp__box {
box-sizing: border-box;
width: 46px;
height: 52px;
border: 1.5px solid #dde3ec;
border-radius: 12px;
background: #fff;
color: #0f172a;
font-family: 'SF Mono', 'Cascadia Code', Consolas, monospace;
font-size: 22px;
font-weight: 700;
text-align: center;
caret-color: #1074b9;
outline: none;
transition:
border-color 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #b7c2d0;
}
&:focus {
border-color: #1074b9;
box-shadow: 0 0 0 3px rgb(16 116 185 / 15%);
}
}
.cotp-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
flex: 1 1 0;
height: 48px;
padding: 0 20px;
border-radius: 999px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
border: 1.5px solid transparent;
transition:
background 0.15s,
border-color 0.15s,
color 0.15s,
opacity 0.15s;
&:disabled {
cursor: not-allowed;
opacity: 0.55;
}
&--primary {
background: #1074b9;
color: #fff;
box-shadow: 0 6px 16px -4px rgb(16 116 185 / 45%);
&:hover:not(:disabled) {
background: #0d5f96;
}
}
&--ghost {
background: #fff;
color: #1074b9;
border-color: #cfe0ee;
&:hover:not(:disabled) {
border-color: #1074b9;
background: #f0f7fc;
}
}
mat-progress-spinner ::ng-deep circle {
stroke: currentcolor !important;
}
}
.cotp-error {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
border-radius: 10px;
background: #fef2f2;
border: 1px solid #fecaca;
color: #b91c1c;
font-size: 12.5px;
}
@media (width <= 420px) {
.cotp-otp__box {
width: 38px;
height: 46px;
font-size: 18px;
}
}
@@ -0,0 +1,307 @@
/**
* 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,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
QueryList,
SimpleChanges,
ViewChildren,
inject
} from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** Custom Services */
import { ClientsService } from '../../clients.service';
/** Emitted every time this block's verification result changes — including a reset back
* to `{ otpId: null, verified: false }` when the destination it was verifying no longer
* matches (e.g. staff kept editing the mobile number after verifying an earlier value). */
export interface ContactOtpState {
otpId: number | null;
verified: boolean;
}
/**
* Small presentational OTP-entry block reused up to four times inside the Edit Client
* "Verify Contact Change" panel (old mobile / new mobile / old email / new email — see
* `EditClientComponent`), and once each for mobile/email in the Create Client flow (see
* `ClientGeneralStepComponent`). Renders as 6 individually-bordered digit boxes (one real
* `<input>` each, auto-advancing focus) rather than the single-input/background-gradient trick
* used elsewhere in this app — each box needs its own focus/border state, which a shared input
* can't express.
*/
@Component({
selector: 'mifosx-client-contact-otp-block',
templateUrl: './contact-otp-block.component.html',
styleUrls: ['./contact-otp-block.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
FaIconComponent,
MatProgressSpinner
]
})
export class ContactOtpBlockComponent implements OnChanges, OnDestroy {
private clientsService = inject(ClientsService);
/** The 6 individual digit-box <input> elements, in order — used to move focus between them. */
@ViewChildren('digitBox') digitBoxes: QueryList<ElementRef<HTMLInputElement>>;
/** One independent control per box — NOT a single 6-char string sliced up. Editing box 0
* can never disturb box 3's value this way. (An earlier version kept one shared string and
* rebuilt it via `chars.join('')` on every keystroke — `['', '2', '3'].join('') === '23'`
* silently drops empty slots instead of preserving them as gaps, so deleting an early digit
* collapsed/shifted every digit after it. Per-box controls sidestep that class of bug
* entirely — there's no string to rebuild until the moment we actually submit.) */
readonly digitControls: UntypedFormControl[] = Array.from({ length: 6 }, () => new UntypedFormControl(''));
/** Fixed-length array so the template can `*ngFor` over exactly 6 boxes. */
readonly digitIndexes = [
0,
1,
2,
3,
4,
5
];
/** Client whose mobileNo/emailAddress is being changed. Omit this input entirely for the
* CLIENT CREATION flow — there is no client id yet, so the block falls back to the
* clientId-less creation-time OTP endpoints (`ClientsService.sendClientCreationContactOtp()` /
* `verifyClientCreationContactOtp()`) instead of the edit-flow `/clients/{clientId}/...` ones. */
@Input() clientId?: string;
/** Which LincPay OTP channel to use. */
@Input() channel: 'MOBILE' | 'EMAIL';
/** Raw destination (old or new mobile number / email address) this block verifies. */
@Input() destination = '';
/** Display label, e.g. "Old Mobile Number" / "New Email Address". */
@Input() label = '';
/** Fires whenever `{ otpId, verified }` changes — including resets. */
@Output() stateChange = new EventEmitter<ContactOtpState>();
otpId: number | null = null;
otpSent = false;
verified = false;
sending = false;
verifying = false;
errorMessage = '';
resendCountdown = 0;
private resendTimer: ReturnType<typeof setInterval> | null = null;
/** The full 6-digit code, assembled fresh from the 6 independent box controls only when
* actually needed (display never needs this — each box renders its own control's value). */
get code(): string {
return this.digitControls.map((c) => c.value || '').join('');
}
get codeValid(): boolean {
return /^\d{6}$/.test(this.code);
}
ngOnChanges(changes: SimpleChanges): void {
// If the value being verified changes after the fact (staff kept typing), any
// previously-sent/verified OTP no longer applies to the current destination.
if (changes['destination'] && !changes['destination'].firstChange && this.otpSent) {
this.resetState();
}
}
ngOnDestroy(): void {
if (this.resendTimer) {
clearInterval(this.resendTimer);
}
}
/** Masks the destination so only a few characters are visible, mirroring the masking
* convention already used on the login 2FA screen (`maskTarget()`). */
get maskedDestination(): string {
const value = this.destination || '';
if (!value) {
return '';
}
if (this.channel === 'MOBILE') {
const digits = value.replace(/\D/g, '');
if (digits.length <= 4) {
return value;
}
return 'X'.repeat(digits.length - 4) + digits.slice(-4);
}
const at = value.indexOf('@');
if (at <= 0) {
return value;
}
const local = value.substring(0, at);
const domain = value.substring(at);
const visible = local.substring(0, Math.min(2, local.length));
const hidden = 'X'.repeat(Math.max(0, local.length - visible.length));
return visible + hidden + domain;
}
sendOtp(): void {
if (!this.destination || this.sending) {
return;
}
this.sending = true;
this.errorMessage = '';
const request$ = this.clientId
? this.clientsService.sendClientContactOtp(this.clientId, this.channel, this.destination)
: this.clientsService.sendClientCreationContactOtp(this.channel, this.destination);
request$.subscribe({
next: (res: any) => {
this.sending = false;
this.otpId = res?.otpId ?? res?.resourceId ?? null;
this.otpSent = true;
this.clearAllDigits();
this.startResendCountdown();
// The 6 digit boxes only render once otpSent flips true — defer the focus call to the
// next tick so they exist in the DOM (and in `digitBoxes`) by the time it runs.
setTimeout(() => this.focusBox(0));
if (this.otpId == null) {
this.errorMessage = 'OTP sent, but no reference id was returned. Please contact support.';
}
},
error: (err: any) => {
this.sending = false;
this.errorMessage = err?.error?.defaultUserMessage || err?.error?.message || 'Could not send OTP.';
}
});
}
/** Typing a digit in box `index`: this box's own control gets exactly that digit — every
* other box's control is untouched, so there's nothing to shift or collapse. Moves focus to
* the next box unless this was the last one. */
onDigitInput(index: number, rawValue: string): void {
const digit = (rawValue || '').replace(/\D/g, '').slice(-1);
this.digitControls[index].setValue(digit);
if (digit && index < 5) {
this.focusBox(index + 1);
}
}
/** Backspace in an empty box clears the PREVIOUS box and moves focus there, matching the
* usual "segmented OTP input" keyboard feel — again, only ever touching one control at a
* time. Arrow keys move focus without altering any box's value. */
onDigitKeydown(index: number, event: KeyboardEvent): void {
if (event.key === 'Backspace') {
if (!this.digitControls[index].value && index > 0) {
this.digitControls[index - 1].setValue('');
this.focusBox(index - 1);
event.preventDefault();
}
return;
}
if (event.key === 'ArrowLeft' && index > 0) {
this.focusBox(index - 1);
event.preventDefault();
} else if (event.key === 'ArrowRight' && index < 5) {
this.focusBox(index + 1);
event.preventDefault();
}
}
/** Pasting a full code into any box fills all 6 boxes at once (one control per digit) and
* focuses the last filled one. */
onDigitPaste(event: ClipboardEvent): void {
const pasted = event.clipboardData?.getData('text') || '';
const digits = pasted.replace(/\D/g, '').slice(0, 6);
if (!digits) {
return;
}
event.preventDefault();
digits.split('').forEach((d, i) => this.digitControls[i].setValue(d));
for (let i = digits.length; i < 6; i++) {
this.digitControls[i].setValue('');
}
this.focusBox(Math.min(digits.length, 6) - 1);
}
private clearAllDigits(): void {
this.digitControls.forEach((c) => c.setValue(''));
}
private focusBox(index: number): void {
const box = this.digitBoxes?.toArray()[index];
box?.nativeElement.focus();
}
resendOtp(): void {
if (this.resendCountdown > 0 || this.sending) {
return;
}
this.sendOtp();
}
verifyOtp(): void {
if (this.otpId == null || !this.codeValid || this.verifying) {
this.digitControls.forEach((c) => c.markAsTouched());
return;
}
this.verifying = true;
this.errorMessage = '';
const request$ = this.clientId
? this.clientsService.verifyClientContactOtp(this.clientId, this.otpId, this.code)
: this.clientsService.verifyClientCreationContactOtp(this.otpId, this.code);
request$.subscribe({
next: (res: any) => {
this.verifying = false;
// Defensive shape-tolerance: treat an explicit `verified: false` as failure,
// anything else (2xx with `verified: true`, or no `verified` field at all) as success.
const ok = res?.verified !== false;
if (ok) {
this.verified = true;
this.stateChange.emit({ otpId: this.otpId, verified: true });
} else {
this.errorMessage = res?.message || 'Incorrect OTP — please try again.';
}
},
error: (err: any) => {
this.verifying = false;
this.errorMessage = err?.error?.defaultUserMessage || err?.error?.message || 'OTP verification failed.';
}
});
}
private resetState(): void {
this.otpId = null;
this.otpSent = false;
this.verified = false;
this.errorMessage = '';
this.clearAllDigits();
if (this.resendTimer) {
clearInterval(this.resendTimer);
this.resendTimer = null;
}
this.resendCountdown = 0;
this.stateChange.emit({ otpId: null, verified: false });
}
private startResendCountdown(): void {
this.resendCountdown = 30;
if (this.resendTimer) {
clearInterval(this.resendTimer);
}
this.resendTimer = setInterval(() => {
this.resendCountdown--;
if (this.resendCountdown <= 0 && this.resendTimer) {
clearInterval(this.resendTimer);
this.resendTimer = null;
}
}, 1000);
}
}
@@ -42,6 +42,79 @@
[readOnly]="isTabReadOnly(0)"
(legalFormChangeEvent)="legalFormChange($event)"
></mifosx-client-general-step>
<!-- Dual-OTP contact-change verification panel — appears only once the mobile
number and/or email address differ from the loaded snapshot. Save stays
gated (see currentStepValid) until every required block below is verified. -->
@if (!isTabReadOnly(0) && (contactChanges.mobileChanged || contactChanges.emailChanged)) {
<div class="contact-verify-panel">
<div class="contact-verify-panel__header">
<mat-icon>verified_user</mat-icon>
<div class="contact-verify-panel__header-text">
<strong>Verify Contact Change</strong>
<span
>An OTP must be verified on both the old and new
{{
contactChanges.mobileChanged && contactChanges.emailChanged
? 'mobile number and email address'
: contactChanges.mobileChanged
? 'mobile number'
: 'email address'
}}
before this change can be saved.</span
>
</div>
</div>
@if (contactChanges.mobileChanged) {
<div class="contact-verify-panel__field-group">
<div class="contact-verify-panel__field-title">
<mat-icon>phone_iphone</mat-icon>
<span>Mobile Number</span>
</div>
<div class="contact-verify-panel__grid">
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="MOBILE"
[destination]="contactChanges.oldMobile"
label="Old Mobile Number"
(stateChange)="onOldMobileOtpState($event)"
></mifosx-client-contact-otp-block>
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="MOBILE"
[destination]="contactChanges.newMobile"
label="New Mobile Number"
(stateChange)="onNewMobileOtpState($event)"
></mifosx-client-contact-otp-block>
</div>
</div>
}
@if (contactChanges.emailChanged) {
<div class="contact-verify-panel__field-group">
<div class="contact-verify-panel__field-title">
<mat-icon>email</mat-icon>
<span>Email Address</span>
</div>
<div class="contact-verify-panel__grid">
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="EMAIL"
[destination]="contactChanges.oldEmail"
label="Old Email Address"
(stateChange)="onOldEmailOtpState($event)"
></mifosx-client-contact-otp-block>
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="EMAIL"
[destination]="contactChanges.newEmail"
label="New Email Address"
(stateChange)="onNewEmailOtpState($event)"
></mifosx-client-contact-otp-block>
</div>
</div>
}
</div>
}
</div>
</mat-tab>
@@ -150,6 +150,73 @@
border: 1px solid #fca5a5 !important;
}
/* ─── Dual-OTP "Verify Contact Change" panel ─── */
.contact-verify-panel {
margin-top: 20px;
padding: 16px 18px;
border: 1px solid #bfdbfe;
border-radius: 8px;
background: #eff6ff;
&__header {
display: flex;
align-items: flex-start;
gap: 12px;
margin-bottom: 14px;
color: #1074b9;
mat-icon {
margin-top: 1px;
flex-shrink: 0;
}
}
&__header-text {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13.5px;
line-height: 1.5;
color: #1e3a5f;
strong {
font-size: 14px;
font-weight: 700;
}
}
&__field-group {
&:not(:last-child) {
margin-bottom: 18px;
padding-bottom: 18px;
border-bottom: 1px dashed #bfdbfe;
}
}
&__field-title {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
color: #1e3a5f;
mat-icon {
font-size: 17px;
width: 17px;
height: 17px;
color: #1074b9;
}
}
&__grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
}
/* ─── Re-KYC Alert Banner ─── */
.rekyc-alert {
display: flex;
@@ -10,6 +10,7 @@
import { Component, QueryList, ViewChild, ViewChildren, inject } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@@ -28,6 +29,7 @@ import { ClientDatatableStepComponent } from '../client-stepper/client-datatable
import { ClientKycStepComponent } from '../client-stepper/client-kyc-step/client-kyc-step.component';
import { ClientPreviewStepComponent } from '../client-stepper/client-preview-step/client-preview-step.component';
import { ClientFamilyMembersStepComponent } from '../client-stepper/client-family-members-step/client-family-members-step.component';
import { ContactOtpBlockComponent, ContactOtpState } from './contact-otp-block/contact-otp-block.component';
import { MatTabsModule } from '@angular/material/tabs';
import { MatIconModule } from '@angular/material/icon';
@@ -59,7 +61,8 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
ClientDatatableStepComponent,
ClientKycStepComponent,
ClientPreviewStepComponent,
ClientFamilyMembersStepComponent
ClientFamilyMembersStepComponent,
ContactOtpBlockComponent
]
})
export class EditClientComponent {
@@ -68,6 +71,7 @@ export class EditClientComponent {
private dialog = inject(MatDialog);
private clientsService = inject(ClientsService);
private settingsService = inject(SettingsService);
private snackBar = inject(MatSnackBar);
@ViewChild(ClientGeneralStepComponent) clientGeneralStep: ClientGeneralStepComponent;
@ViewChild('clientAddress') clientAddressStep: ClientAddressStepComponent;
@@ -88,6 +92,26 @@ export class EditClientComponent {
/** Flag: DOB was changed — requires re-KYC (PAN re-verification) */
dobChanged = false;
/**
* Dual-OTP contact-change verification state (mobileNo / emailAddress). Mirrors the
* name/DOB "detect change against snapshot, gate the save" pattern already established
* in this component (see `detectSensitiveFieldChanges()` / `flagReKycRequired()`) —
* extended here so a changed mobile/email must be OTP-verified on BOTH the old and new
* destination before Save is allowed. Payload param names sent to the backend PUT are
* `mobileOldOtpId` / `mobileNewOtpId` / `emailOldOtpId` / `emailNewOtpId` (added onto
* `clientData` in `saveCurrentTab()`'s General-tab branch) — kept per-field rather than
* one generic old/new pair so mobile AND email can both be changed (and independently
* OTP-verified) in a single save.
*/
oldMobileOtpId: number | null = null;
newMobileOtpId: number | null = null;
oldMobileVerified = false;
newMobileVerified = false;
oldEmailOtpId: number | null = null;
newEmailOtpId: number | null = null;
oldEmailVerified = false;
newEmailVerified = false;
/** Client data and template (merged object from resolver) */
clientDataAndTemplate: any;
/** Client ID */
@@ -168,6 +192,61 @@ export class EditClientComponent {
return { ...general };
}
/**
* Live view of `detectSensitiveFieldChanges()` against the loaded snapshot — drives the
* "Verify Contact Change" OTP panel in the General tab template. Re-evaluated on every
* change-detection pass (cheap: a handful of form-control reads), so the panel appears/
* disappears as the user types, same as the existing re-KYC name/DOB detection.
*/
get contactChanges() {
return this.detectSensitiveFieldChanges(this.clientDataAndTemplate);
}
/** Whether every OTP block required by the fields that actually changed has been verified. */
get contactVerificationComplete(): boolean {
const changes = this.contactChanges;
if (changes.mobileChanged && !(this.oldMobileVerified && this.newMobileVerified)) {
return false;
}
if (changes.emailChanged && !(this.oldEmailVerified && this.newEmailVerified)) {
return false;
}
return true;
}
onOldMobileOtpState(state: ContactOtpState): void {
this.oldMobileOtpId = state.otpId;
this.oldMobileVerified = state.verified;
}
onNewMobileOtpState(state: ContactOtpState): void {
this.newMobileOtpId = state.otpId;
this.newMobileVerified = state.verified;
}
onOldEmailOtpState(state: ContactOtpState): void {
this.oldEmailOtpId = state.otpId;
this.oldEmailVerified = state.verified;
}
onNewEmailOtpState(state: ContactOtpState): void {
this.newEmailOtpId = state.otpId;
this.newEmailVerified = state.verified;
}
/** Reset all dual-OTP state — called once a General-tab save succeeds (the snapshot is
* updated to match, so the "Verify Contact Change" panel naturally disappears too). */
private resetContactVerificationState(): void {
this.oldMobileOtpId = null;
this.newMobileOtpId = null;
this.oldMobileVerified = false;
this.newMobileVerified = false;
this.oldEmailOtpId = null;
this.newEmailOtpId = null;
this.oldEmailVerified = false;
this.newEmailVerified = false;
}
areFormvalids(): boolean {
if (!this.clientGeneralStep || !this.clientGeneralForm) {
return false;
@@ -196,7 +275,10 @@ export class EditClientComponent {
if (idx === 0) {
if (!this.clientGeneralStep || !this.clientGeneralForm) return false;
if (this.clientGeneralStep.sanctionsBlocked) return false;
return this.clientGeneralForm.valid;
if (!this.clientGeneralForm.valid) return false;
// Dual-OTP gate: a changed mobile/email must be verified on both old & new
// destinations before Save is allowed — mirrors the re-KYC gate below it.
return this.contactVerificationComplete;
}
if (idx === 1) {
const kf = this.clientKycStep?.kycForm;
@@ -227,6 +309,15 @@ export class EditClientComponent {
if (this.selectedTabIndex === 0 && this.clientGeneralStep?.sanctionsBlocked) {
return 'Client failed sanctions screening — cannot proceed.';
}
if (this.selectedTabIndex === 0 && this.clientGeneralForm?.valid && !this.contactVerificationComplete) {
return 'Verify the OTP sent to both the old and new mobile number/email before saving.';
}
if (this.selectedTabIndex === 1) {
const labels = this.clientKycStep?.invalidFieldLabels || [];
if (labels.length) {
return `Please fill/correct: ${labels.join(', ')}.`;
}
}
return 'Please fill all mandatory fields on this tab to continue.';
}
@@ -272,6 +363,16 @@ export class EditClientComponent {
// Check if name or DOB changed on the General tab — warn about re-KYC
if (this.selectedTabIndex === 0) {
const changes = this.detectSensitiveFieldChanges(this.clientDataAndTemplate);
// Dual-OTP gate — defensive re-check. The "Save & Next" button is already disabled
// via `currentStepValid` while this is incomplete, but don't rely on that alone.
if (!this.contactVerificationComplete) {
this.snackBar.open('Verify the OTP sent to both the old and new mobile number/email before saving.', 'Close', {
duration: 5000
});
return;
}
if (changes.nameChanged || changes.dobChanged) {
heading = 'Re-KYC Required';
dialogContext =
@@ -308,6 +409,19 @@ export class EditClientComponent {
const originalData = this.clientDataAndTemplate;
const changedFields = this.detectSensitiveFieldChanges(originalData);
// Dual-OTP verified ids — sent only for the field(s) that actually changed, per-field
// (not a single generic old/new pair) so the backend can tell mobile's OTPs apart from
// email's when BOTH changed in the same save. See the class-level JSDoc above the OTP
// state fields for the full naming rationale.
if (changedFields.mobileChanged) {
clientData.mobileOldOtpId = this.oldMobileOtpId;
clientData.mobileNewOtpId = this.newMobileOtpId;
}
if (changedFields.emailChanged) {
clientData.emailOldOtpId = this.oldEmailOtpId;
clientData.emailNewOtpId = this.newEmailOtpId;
}
this.savingClient = true;
this.clientsService.updateClient(this.clientId, clientData).subscribe({
next: () => {
@@ -342,6 +456,14 @@ export class EditClientComponent {
originalData.fullname = form?.get('fullname')?.value ?? originalData.fullname;
}
// Notification is backend-driven (SMS + Email) — just reassure staff it happened.
if (changedFields.mobileChanged || changedFields.emailChanged) {
this.snackBar.open('Customer notified via SMS/Email of the contact change.', 'Close', {
duration: 4000
});
}
this.resetContactVerificationState();
this.selectedTabIndex = this.selectedTabIndex + 1;
},
error: () => {
@@ -430,12 +552,14 @@ export class EditClientComponent {
return;
}
// Address tab
// Address tab — no OTP gate (an address has no "old/new channel" to verify an OTP
// against); notification-only, per the plan. Save proceeds normally.
const addressTabIdx = this.legalFormType === 2 ? 3 : 2;
if (tabIndex === addressTabIdx) {
this.savingClient = true;
if (this.clientIndiaAddressStep?.hasAddressData) {
this.saveClientAddresses(this.clientId);
this.snackBar.open('Customer notified via SMS/Email of the address change.', 'Close', { duration: 4000 });
}
this.savingClient = false;
this.tabEditMode[tabIndex] = false;
@@ -465,20 +589,41 @@ export class EditClientComponent {
/**
* Compare current form values with original data to detect changes in name, DOB, mobile, email.
*/
/** "YYYY-MM-DD" built from a Date's LOCAL components — see the timezone-safety note where
* this is called from `detectSensitiveFieldChanges()`. */
private toLocalDateString(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
private detectSensitiveFieldChanges(originalData: any) {
const form = this.clientGeneralForm;
const newMobile = form?.get('mobileNo')?.value || '';
const newEmail = form?.get('emailAddress')?.value || '';
// Trimmed so browser autofill adding invisible leading/trailing whitespace never reads as
// a "change" — the masked preview shown in the Verify Contact Change panel only reveals the
// first couple of characters, so a whitespace-only difference is otherwise invisible to the
// user and just looks like the panel appeared for no reason. These trimmed-but-original-case
// values are what get returned/sent as the actual OTP destination and saved value — only the
// *comparison* (below) is further case-normalized for email, so we never silently rewrite the
// customer's email casing into the saved record or the OTP destination.
const newMobile = (form?.get('mobileNo')?.value || '').trim();
const newEmail = (form?.get('emailAddress')?.value || '').trim();
const newDobRaw = form?.get('dateOfBirth')?.value;
const newDob = newDobRaw instanceof Date ? newDobRaw.toISOString().split('T')[0] : newDobRaw || '';
// Local calendar date, NOT `.toISOString()` — that converts to UTC first, which silently
// shifts the date by a day in any positive-UTC-offset timezone (e.g. India, UTC+5:30:
// midnight local on the 15th becomes 18:30 UTC on the 14th). That made this comparison
// report a DOB "change" — falsely triggering the Re-KYC dialog — even when the user never
// touched the date field, purely because the Date object round-tripped through the picker.
const newDob = newDobRaw instanceof Date ? this.toLocalDateString(newDobRaw) : newDobRaw || '';
const oldMobile = originalData.mobileNo || '';
const oldEmail = originalData.emailAddress || '';
const oldMobile = (originalData.mobileNo || '').trim();
const oldEmail = (originalData.emailAddress || '').trim();
const oldDobRaw = originalData.dateOfBirth;
const oldDob = Array.isArray(oldDobRaw)
? `${oldDobRaw[0]}-${String(oldDobRaw[1]).padStart(2, '0')}-${String(oldDobRaw[2]).padStart(2, '0')}`
: oldDobRaw instanceof Date
? oldDobRaw.toISOString().split('T')[0]
? this.toLocalDateString(oldDobRaw)
: oldDobRaw || '';
const buildName = (parts: { firstname?: string; middlename?: string; lastname?: string; fullname?: string }) =>
@@ -509,7 +654,9 @@ export class EditClientComponent {
return {
nameChanged: newName !== oldName,
mobileChanged: newMobile !== oldMobile,
emailChanged: newEmail !== oldEmail,
// Case-insensitive: emails are not case-sensitive in practice, and comparing raw case
// would flag a change (surfacing the dual-OTP panel) even when nothing meaningful changed.
emailChanged: newEmail.toLowerCase() !== oldEmail.toLowerCase(),
dobChanged: newDob !== oldDob,
oldName,
newName,