Files
cbsnexora/src/app/current-accounts/current-account-stepper/current-account-details-step/current-account-details-step.component.ts
T
niteshandClaude Sonnet 5 395fb8ace8
Tests / testRigor (push) Canceled after 0s
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
feat(clients,deposits): auto-derive senior-citizen/customer-segment, fix disbursement display and reversed-transaction balances
Four independent, self-contained changes bundled from this session's work:

1. Auto-derive Senior Citizen / Minor / Customer Segment instead of manual entry

   Senior Citizen was a manual, staff-editable checkbox on FD/RD account
   creation with no validation against the client's actual age -- this let
   non-senior clients get the senior-citizen interest rate by mistake (found
   twice on live test accounts, where m_savings_account.is_senior_citizen
   was true despite the client being confirmed non-senior at the client
   record level). Likewise "minor" client classification was hardcoded to
   the age-18 threshold with no single source of truth, and FD/RD account
   creation's "Customer Segment" (Individual / Non-Individual) had no
   connection to the Individual/Non-Individual Legal Form already captured
   at client creation.

   - New src/app/clients/shared/client-age.util.ts centralises age/DOB
     derivation: MINOR_AGE_THRESHOLD (now 10, was 18), SENIOR_CITIZEN_AGE_
     THRESHOLD (60), AGE_OF_MAJORITY (18, kept separate from the minor
     threshold -- majority date math is unrelated to the minor/adult
     classification threshold), calculateAge/isMinorAge/isSeniorCitizenAge/
     isIndividualClient/deriveSeniorCitizenStatus.
   - FD/RD interest-rate-chart steps: Senior Citizen checkbox is now derived
     from the client's DOB (age >= 60, individual clients only) and
     disabled for manual editing; a hint explains why it is checked/
     unchecked.
   - Client general step and all four account-details-steps (savings,
     current, FD, RD): replaced hardcoded 18/60 literals with the shared
     helpers; "Must be below 18" hints now read the actual threshold.
   - FD/RD account-details-steps: Customer Segment auto-selects to match
     the client's Legal Form (exact match, not substring -- a substring
     match would misclassify "Individual" as matching "Non-Individual").
   - RD preview step: fixed a pre-existing display bug that always showed
     the product's default Customer Segment instead of what was actually
     selected on the account.

2. Fix wrong Account Name / Account Type on Disbursement Review screens

   Clerk disbursement review and "My Disbursement Requests" showed the
   account NUMBER instead of the holder's name, and always labelled the
   account type "SAVINGS" regardless of the real account type (FD/RD/
   Share/Loan), because transaction-entry.component.ts's account-type
   mapping only checked for CA/CB and its account-name fallback chain
   never tried clientName. Added creditEntryAccountType() covering
   GL/CA/CB/FD/RD/SHR/LA, and accountTypeLabel() display helpers on both
   review screens.

3. Stop reversed transactions from distorting displayed running balances

   Passbook and Transactions tabs were including reversed transactions in
   their client-side running-balance recalculation, so a reversed posting
   (visible struck-through) still shifted the balance shown for every
   transaction after it. Both now filter out txn.reversed before computing
   running balances; Transactions tab also defaults "Hide Reversed" to on.

4. New Interest Schedule dialog on the FD account view

   Added custom-dialogs/interest-schedule-dialog, opened from the FD
   General tab, showing the account's period-by-period interest schedule.

Excludes src/environments/.env.ts (auto-generated build version/hash
stamp, regenerated on every build -- not meaningful to hand-commit).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 18:58:20 +05:30

753 lines
29 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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, OnInit, Input, Output, EventEmitter, inject, ChangeDetectorRef } from '@angular/core';
import { UntypedFormGroup, UntypedFormBuilder, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms';
import { Dates } from 'app/core/utils/dates';
/** Custom Services */
import { CurrentAccountsService } from 'app/current-accounts/current-accounts.service';
import { SettingsService } from 'app/settings/settings.service';
import { ClientsService } from 'app/clients/clients.service';
import {
AGE_OF_MAJORITY,
MINOR_AGE_THRESHOLD,
isMinorAge,
isSeniorCitizenAge
} from 'app/clients/shared/client-age.util';
import { MatDialog } from '@angular/material/dialog';
import { MatStepperPrevious, MatStepperNext } from '@angular/material/stepper';
import { MatIcon } from '@angular/material/icon';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { IntroducerSearchComponent } from 'app/shared/introducer-search/introducer-search.component';
import { AddRelatedClientDialogComponent } from './add-related-client-dialog/add-related-client-dialog.component';
import { AlertService } from 'app/core/alert/alert.service';
/**
* Current Account Details Step
*/
@Component({
selector: 'mifosx-current-account-details-step',
templateUrl: './current-account-details-step.component.html',
styleUrls: ['./current-account-details-step.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatStepperPrevious,
FaIconComponent,
MatStepperNext,
IntroducerSearchComponent,
MatIcon,
FormsModule
]
})
export class CurrentAccountDetailsStepComponent implements OnInit {
private formBuilder = inject(UntypedFormBuilder);
private currentAccountsService = inject(CurrentAccountsService);
private settingsService = inject(SettingsService);
private clientsService = inject(ClientsService);
private dialog = inject(MatDialog);
private alertService = inject(AlertService);
private dateUtils = inject(Dates);
private cdr = inject(ChangeDetectorRef);
@Input() currentAccountTemplate: any;
@Input() hideButtons = false;
@Input() readOnly = false;
minDate = new Date(2000, 0, 1);
maxDate = new Date();
productData: any;
fieldOfficerData: any;
isFieldOfficerPatched = false;
currentAccountDetailsForm: UntypedFormGroup;
currentAccountProductSelected = false;
introducerId: number | null = null;
introducerName: string | null = null;
introducerCif: string | null = null;
private isEditMode = false;
shareLinkingEnabled = false;
// ── Non-Individual (existing) ──────────────────────────────────────────
isNonIndividualClient = false;
relatedClients: Array<{
clientId: number;
clientName: string;
clientCif: string;
sharePercentage: number;
isMandatory: boolean;
}> = [];
signatoryRights = '';
readonly signatoryRightsOptions = [
{ value: 'ANYONE', label: 'E or S', sublabel: 'Either or Survivor', icon: 'how_to_vote' },
{ value: 'ONE_MANDATORY', label: 'J/One', sublabel: 'Joint – One Mandatory', icon: 'group' },
{ value: 'TWO_MANDATORY', label: 'J/Two', sublabel: 'Joint – Two Mandatory', icon: 'groups' },
{ value: 'ONLY_ONE', label: 'Single', sublabel: 'Only 1 Person', icon: 'person' }
];
@Output() currentAccountProductTemplate = new EventEmitter();
productTemplate: any = null;
accountTypeOptions: string[] = [];
customerSegmentOptions: string[] = [];
selectedAccountType: string | null = null;
selectedCustomerSegment: string | null = null;
// ── Client info (auto-fetched) ─────────────────────────────────────────
clientDob: Date | null = null;
clientAge: number | null = null;
/** Exposed for tooltips so the displayed rule can never drift from the applied rule. */
readonly minorAgeThreshold = MINOR_AGE_THRESHOLD;
clientGender: string | null = null;
primaryClientName = '';
primaryClientCif = '';
primaryClientId: number | null = null;
primaryHolderShare = 50;
// ── Status of Account (RBI) ────────────────────────────────────────────
readonly accountStatusOptions = [
{ value: 'INDIVIDUAL_MALE', label: 'Individual (Male)', icon: 'person', color: '#3b82f6' },
{ value: 'INDIVIDUAL_FEMALE', label: 'Individual (Female)', icon: 'person_outline', color: '#ec4899' },
{ value: 'SINGLE', label: 'Single Account', icon: 'account_circle', color: '#0891b2' },
{ value: 'JOINT', label: 'Joint Account', icon: 'group', color: '#8b5cf6' },
{ value: 'MINOR', label: 'Minor Account', icon: 'child_care', color: '#f59e0b' },
{ value: 'SENIOR_CITIZEN', label: 'Senior Citizen', icon: 'elderly', color: '#10b981' }
];
selectedAccountStatus = '';
// ── Joint Account (Status of Account) ─────────────────────────────────
jointHolders: Array<{
clientId: number;
clientName: string;
clientCif: string;
sharePercentage: number;
isMandatory: boolean;
signingAuthority?: string;
role?: string;
}> = [];
modeOfOperation = '';
readonly modeOfOperationOptions = [
{ value: 'EITHER_OR_SURVIVOR', label: 'E or S', sublabel: 'Either or Survivor', icon: 'how_to_vote' },
{ value: 'FORMER_OR_SURVIVOR', label: 'F or S', sublabel: 'Former or Survivor', icon: 'person' },
{ value: 'JOINTLY', label: 'Jointly', sublabel: 'All Must Sign', icon: 'groups' },
{ value: 'ANYONE_OR_SURVIVOR', label: 'Anyone', sublabel: 'Anyone or Survivor', icon: 'group' }
];
// ── Individual Male — Special Category ────────────────────────────────
selectedSpecialCategory = '';
readonly specialCategoryOptions = [
{ value: 'DEFENCE', label: 'Defence Personnel', icon: 'military_tech' },
{ value: 'EX_SERVICEMAN', label: 'Ex-Serviceman', icon: 'shield' },
{ value: 'GOVT_EMPLOYEE', label: 'Government Employee', icon: 'account_balance' },
{ value: 'PHYSICALLY_CHALLENGED', label: 'Physically Challenged', icon: 'accessible' },
{ value: 'NRI', label: 'NRI (Non-Resident Indian)', icon: 'flight' },
{ value: 'NONE', label: 'None / General', icon: 'person' }
];
// ── Individual Female — Weaker Section ────────────────────────────────
selectedWeakerSection = '';
readonly weakerSectionOptions = [
{ value: 'BPL', label: 'BPL (Below Poverty Line)', icon: 'volunteer_activism' },
{ value: 'SC_ST', label: 'SC / ST Category', icon: 'groups' },
{ value: 'MINORITY', label: 'Minority Community', icon: 'diversity_3' },
{ value: 'SHG', label: 'Self Help Group Member', icon: 'handshake' },
{ value: 'PMJDY', label: 'PMJDY Beneficiary', icon: 'savings' },
{ value: 'NONE', label: 'None / General', icon: 'person_outline' }
];
// ── Minor Account ──────────────────────────────────────────────────────
guardianClientId: number | null = null;
guardianName = '';
guardianCif = '';
guardianRelationship = '';
minorDob: Date | null = null;
readonly guardianRelationshipOptions = [
'Father',
'Mother',
'Legal Guardian',
'Court Appointed Guardian'
];
constructor() {
this.createCurrentAccountDetailsForm();
}
ngOnInit() {
this.maxDate = this.settingsService.businessDate;
this.buildDependencies();
const clientId = this.currentAccountTemplate?.clientId;
if (clientId) {
this.primaryClientId = clientId;
this.clientsService.getClientData(String(clientId)).subscribe((client: any) => {
this.isNonIndividualClient = client?.legalForm?.id === 2;
this.primaryClientName = client?.displayName ?? client?.fullname ?? '';
this.primaryClientCif = client?.cifNumber ?? client?.cifNo ?? '';
if (client?.dateOfBirth) {
const dob = this.parseClientDob(client.dateOfBirth);
if (dob) {
this.clientDob = dob;
this.clientAge = this.calculateAge(dob);
this.clientGender = client.gender?.name?.toLowerCase() ?? null;
this.autoDetectAccountStatus();
}
}
this.cdr.detectChanges();
});
}
if (this.currentAccountTemplate) {
this.productData = this.currentAccountTemplate.productOptions;
const existingProductId =
this.currentAccountTemplate.currentAccountProductId ?? this.currentAccountTemplate.productId;
// Edit mode: account response always has accountNo; pure template has previewAccountNo only
if (this.currentAccountTemplate.accountNo) {
this.isEditMode = true;
}
if ((!this.productData || this.productData.length === 0) && existingProductId) {
this.isEditMode = true;
this.productData = [
{
id: existingProductId,
name:
this.currentAccountTemplate.productName ??
this.currentAccountTemplate.currentAccountProductName ??
'Product'
}
];
}
if (existingProductId) {
this.currentAccountDetailsForm.patchValue({
productId: existingProductId,
submittedOnDate:
this.currentAccountTemplate.timeline?.submittedOnDate &&
new Date(this.currentAccountTemplate.timeline.submittedOnDate),
externalId: this.currentAccountTemplate.externalId
});
} else {
this.currentAccountDetailsForm.patchValue({
submittedOnDate: this.settingsService.businessDate
});
}
}
if (this.readOnly) {
this.currentAccountDetailsForm.disable();
}
}
createCurrentAccountDetailsForm() {
this.currentAccountDetailsForm = this.formBuilder.group({
productId: [
'',
Validators.required
],
submittedOnDate: [
'',
Validators.required
],
fieldOfficerId: [''],
externalId: [''],
balanceSwapOption: [false],
msme: [false],
autoDebitFacility: [false],
establishmentDate: [''],
startOperationDate: ['']
});
}
buildDependencies() {
const entityId = this.currentAccountTemplate.groupId || this.currentAccountTemplate.clientId;
this.currentAccountDetailsForm.get('productId').valueChanges.subscribe((productId: string) => {
this.currentAccountsService
.getCurrentAccountTemplate(entityId, productId, this.currentAccountTemplate.groupId ? true : false)
.subscribe((response: any) => {
if (!response.currency) {
const selectedProduct = this.currentAccountTemplate.productOptions?.find(
(product: any) => product.id == productId
);
if (selectedProduct?.currency) {
response.currency = selectedProduct.currency;
} else if (this.currentAccountTemplate.currency) {
response.currency = this.currentAccountTemplate.currency;
}
}
this.productTemplate = response;
this.accountTypeOptions = this.extractOptions(response.accountTypeOptions, response.accountType);
this.customerSegmentOptions = this.extractOptions(response.customerSegmentOptions, response.customerSegment);
this.selectedAccountType = response.accountType ?? null;
this.selectedCustomerSegment = response.customerSegment ?? null;
this.currentAccountProductTemplate.emit(response);
this.fieldOfficerData = response.fieldOfficerOptions;
this.currentAccountProductSelected = true;
this.shareLinkingEnabled = !!response.shareLinkingEnabled;
this.currentAccountDetailsForm.patchValue({
balanceSwapOption: !!response.balanceSwapOption,
msme: !!response.msme,
autoDebitFacility: !!response.autoDebitFacility
});
this.cdr.detectChanges();
if (!this.isFieldOfficerPatched && this.currentAccountTemplate.fieldOfficerId) {
this.currentAccountDetailsForm.get('fieldOfficerId').patchValue(this.currentAccountTemplate.fieldOfficerId);
this.isFieldOfficerPatched = true;
} else {
this.currentAccountDetailsForm.get('fieldOfficerId').patchValue('');
}
// === Restore existing account values when in edit/modify mode ===
this.restoreExistingAccountValues();
});
});
}
private restoreExistingAccountValues(): void {
const ea = this.currentAccountTemplate;
// Edit mode: API returns `productId`, create template uses `currentAccountProductId`
if (!ea?.currentAccountProductId && !ea?.productId) {
return;
}
const strVal = (v: any): string => (typeof v === 'object' && v !== null ? (v.value ?? '') : (v ?? ''));
const accountStatus = strVal(ea.accountStatus);
if (accountStatus) {
this.selectedAccountStatus = accountStatus;
}
const customerSegment = strVal(ea.customerSegment);
if (customerSegment) {
this.selectedCustomerSegment = customerSegment;
}
// cbsAccountType is the CBS descriptive type ("Standard Account", etc.)
// ea.accountType is Fineract's enum-based type ({id,value:"Individual"}) — do NOT use as fallback
const accountType = ea.cbsAccountType ? strVal(ea.cbsAccountType) : null;
if (accountType) {
this.selectedAccountType = accountType;
}
if (accountStatus === 'JOINT') {
const modeOfOp = strVal(ea.modeOfOperation);
if (modeOfOp) {
this.modeOfOperation = modeOfOp;
}
// jointHolders may not be returned by backend — skip if absent
if (Array.isArray(ea.jointHolders) && ea.jointHolders.length > 0) {
// Support both camelCase and lowercase keys (MySQL queryForList returns lowercase)
const isPH = (h: any) => h.isPrimary ?? h.isprimary ?? false;
const primary = ea.jointHolders.find((h: any) => isPH(h));
const ps = primary?.sharePercentage ?? primary?.sharepercentage;
if (ps) {
this.primaryHolderShare = +ps;
}
this.jointHolders = ea.jointHolders
.filter((h: any) => !isPH(h))
.map((h: any) => ({
clientId: h.clientId ?? h.clientid,
clientName: h.displayName ?? h.displayname ?? h.clientName ?? '',
clientCif: h.cifNumber ?? h.cifnumber ?? h.clientCif ?? '',
sharePercentage: +(h.sharePercentage ?? h.sharepercentage ?? 0),
isMandatory: !!(h.isMandatory ?? h.ismandatory)
}));
}
}
if (accountStatus === 'INDIVIDUAL_MALE' && ea.specialCategory) {
this.selectedSpecialCategory = ea.specialCategory;
}
if (accountStatus === 'INDIVIDUAL_FEMALE' && ea.weakerSection) {
this.selectedWeakerSection = ea.weakerSection;
}
if (accountStatus === 'MINOR') {
if (ea.guardianClientId) {
this.guardianClientId = ea.guardianClientId;
}
if (ea.guardianName) {
this.guardianName = ea.guardianName;
}
if (ea.guardianCifNumber) {
this.guardianCif = ea.guardianCifNumber;
}
if (ea.guardianRelationship) {
this.guardianRelationship = ea.guardianRelationship;
}
if (ea.minorDateOfBirth) {
const d = new Date(ea.minorDateOfBirth);
if (!isNaN(d.getTime())) {
this.minorDob = d;
}
}
}
// API returns introducerClientId, not introducerId
const introId = ea.introducerId ?? ea.introducerClientId;
if (introId) {
this.introducerId = introId;
this.introducerName = ea.introducerName ?? null;
this.introducerCif = ea.introducerCifNumber ?? null;
}
this.shareLinkingEnabled = ea.shareLinkingEnabled !== undefined ? !!ea.shareLinkingEnabled : !!ea.isLinkingEnable;
this.currentAccountDetailsForm.patchValue({
balanceSwapOption: !!ea.balanceSwapOption,
msme: !!ea.msme,
autoDebitFacility: !!ea.autoDebitFacility,
...(ea.establishmentDate ? { establishmentDate: new Date(ea.establishmentDate) } : {}),
...(ea.startOperationDate ? { startOperationDate: new Date(ea.startOperationDate) } : {})
});
this.cdr.detectChanges();
}
private extractOptions(options: any[], fallback?: string): string[] {
if (Array.isArray(options) && options.length > 0) {
return options.map((o: any) => o.value ?? o.name ?? o);
}
return fallback ? [fallback] : [];
}
formatTemplateDate(value: any): string {
if (!value) return '';
let dateValue: Date | null = null;
if (value instanceof Date) {
dateValue = value;
} else if (Array.isArray(value) && value.length >= 3) {
dateValue = new Date(value[0], value[1] - 1, value[2]);
} else {
dateValue = new Date(value);
}
if (!dateValue || Number.isNaN(dateValue.getTime())) {
return Array.isArray(value) ? value.join('/') : String(value);
}
return this.dateUtils.formatDate(dateValue, 'M/d/yyyy') || '';
}
// ── Client DOB helpers ─────────────────────────────────────────────────
private parseClientDob(dob: any): Date | null {
if (!dob) return null;
if (Array.isArray(dob) && dob.length >= 3) return new Date(dob[0], dob[1] - 1, dob[2]);
const d = new Date(dob);
return isNaN(d.getTime()) ? null : d;
}
private calculateAge(dob: Date): number {
const today = this.settingsService.businessDate ?? new Date();
let age = today.getFullYear() - dob.getFullYear();
const m = today.getMonth() - dob.getMonth();
if (m < 0 || (m === 0 && today.getDate() < dob.getDate())) age--;
return age;
}
private autoDetectAccountStatus(): void {
if (this.isEditMode) {
return;
}
if (this.clientAge === null) return;
if (isMinorAge(this.clientAge)) {
this.selectedAccountStatus = 'MINOR';
this.minorDob = this.clientDob;
} else if (isSeniorCitizenAge(this.clientAge)) {
this.selectedAccountStatus = 'SENIOR_CITIZEN';
} else if (this.clientGender === 'female') {
this.selectedAccountStatus = 'INDIVIDUAL_FEMALE';
} else {
this.selectedAccountStatus = 'INDIVIDUAL_MALE';
}
}
isTileDisabled(value: string): boolean {
if (this.readOnly) return true;
if (value === 'MINOR') return !isMinorAge(this.clientAge);
if (value === 'SENIOR_CITIZEN') return !isSeniorCitizenAge(this.clientAge);
return false;
}
getTileTooltip(value: string): string {
if (value === 'MINOR' && !isMinorAge(this.clientAge))
return `Age ${this.clientAge} yrs — Minor only allowed below years`;
if (value === 'SENIOR_CITIZEN' && !isSeniorCitizenAge(this.clientAge))
return `Age ${this.clientAge} yrs — Senior Citizen only allowed at 60+ years`;
if (value === 'MINOR' && this.clientAge === null) return 'DOB not available — cannot verify age';
if (value === 'SENIOR_CITIZEN' && this.clientAge === null) return 'DOB not available — cannot verify age';
return '';
}
// ── Introducer ─────────────────────────────────────────────────────────
onIntroducerChange(event: { clientId: number; displayName: string; cifNumber?: string } | null): void {
this.introducerId = event?.clientId ?? null;
this.introducerName = event?.displayName ?? null;
this.introducerCif = event?.cifNumber ?? null;
}
onGuardianChange(event: { clientId: number; displayName: string; cifNumber?: string } | null): void {
this.guardianClientId = event?.clientId ?? null;
this.guardianName = event?.displayName ?? '';
this.guardianCif = event?.cifNumber ?? '';
}
// ── Joint Account (Status of Account) ─────────────────────────────────
openAddJointHolderDialog(): void {
const excludedClientIds = [
...(this.primaryClientId ? [this.primaryClientId] : []),
...this.jointHolders.map((h: any) => h.clientId).filter(Boolean)
];
const maxSharePercentage = Math.max(0, 100 - this.totalJointSharePercentage);
const ref = this.dialog.open(AddRelatedClientDialogComponent, {
width: '500px',
panelClass: 'arc-dialog-panel',
disableClose: true,
data: { excludedClientIds, maxSharePercentage }
});
ref.afterClosed().subscribe((result) => {
if (result) {
const isPrimary = this.primaryClientCif && this.primaryClientCif === result.clientCif;
const duplicate = isPrimary || this.jointHolders.some((h) => h.clientCif && h.clientCif === result.clientCif);
if (duplicate) {
this.alertService.alert({
type: 'Error',
message: `Account holder with CIF ${result.clientCif} is already added.`
});
return;
}
this.jointHolders = [
...this.jointHolders,
{ ...result, isMandatory: false }];
this.autoSetModeOfOperation();
}
});
}
removeJointHolder(index: number): void {
this.jointHolders = this.jointHolders.filter((_, i) => i !== index);
this.autoSetModeOfOperation();
}
toggleJointHolderMandatory(holder: any): void {
holder.isMandatory = !holder.isMandatory;
this.autoSetModeOfOperation();
}
autoSetModeOfOperation(): void {
const mandatory = this.jointHolders.filter((h) => h.isMandatory).length;
if (mandatory === 0) this.modeOfOperation = 'EITHER_OR_SURVIVOR';
else if (mandatory === 1) this.modeOfOperation = 'FORMER_OR_SURVIVOR';
else this.modeOfOperation = 'JOINTLY';
}
get totalJointSharePercentage(): number {
return (this.primaryHolderShare || 0) + this.jointHolders.reduce((sum, h) => sum + (h.sharePercentage || 0), 0);
}
onPrimaryShareInput(event: Event): void {
const input = event.target as HTMLInputElement;
let val = +input.value;
if (val > 100) {
val = 100;
input.value = '100';
}
this.primaryHolderShare = val;
if (val >= 1) this.redistributeCoHolders();
}
onPrimaryShareBlur(event: Event): void {
const input = event.target as HTMLInputElement;
let val = +input.value;
if (!val || val < 1) {
val = 1;
input.value = '1';
this.primaryHolderShare = 1;
this.redistributeCoHolders();
}
}
private redistributeCoHolders(): void {
if (this.jointHolders.length === 0) return;
const remaining = 100 - this.primaryHolderShare;
const totalCo = this.jointHolders.reduce((sum, h) => sum + (h.sharePercentage || 0), 0);
if (totalCo === 0) return;
let allocated = 0;
this.jointHolders.forEach((h, i) => {
if (i === this.jointHolders.length - 1) {
h.sharePercentage = Math.max(0, remaining - allocated);
} else {
const share = Math.round((h.sharePercentage / totalCo) * remaining);
h.sharePercentage = Math.max(0, share);
allocated += h.sharePercentage;
}
});
}
get isJointOwnershipValid(): boolean {
return (
this.totalJointSharePercentage === 100 &&
this.primaryHolderShare >= 1 &&
this.jointHolders.every((h) => h.sharePercentage >= 1)
);
}
get mandatoryJointCount(): number {
return this.jointHolders.filter((h) => h.isMandatory).length;
}
get selectedModeLabel(): string {
return this.modeOfOperationOptions.find((o) => o.value === this.modeOfOperation)?.sublabel ?? '';
}
get today(): Date {
const d = new Date();
d.setHours(0, 0, 0, 0);
return d;
}
get minStartOperationDate(): Date | null {
const val = this.currentAccountDetailsForm?.get('establishmentDate')?.value;
return val ? new Date(val) : null;
}
get majorityDate(): string {
const dob = this.minorDob ?? this.clientDob;
if (!dob) return '';
const d = new Date(dob);
d.setFullYear(d.getFullYear() + AGE_OF_MAJORITY);
return this.dateUtils.formatDate(d, 'M/d/yyyy') || '';
}
// ── Non-Individual (existing) helpers ──────────────────────────────────
openAddRelatedClientDialog(): void {
const excludedClientIds = [
...(this.primaryClientId ? [this.primaryClientId] : []),
...this.relatedClients.map((c: any) => c.clientId).filter(Boolean)
];
const maxSharePercentage = Math.max(0, 100 - this.totalSharePercentage);
const ref = this.dialog.open(AddRelatedClientDialogComponent, {
width: '500px',
panelClass: 'arc-dialog-panel',
disableClose: true,
data: { excludedClientIds, maxSharePercentage }
});
ref.afterClosed().subscribe((result) => {
if (result) {
const duplicate = this.relatedClients.some((c) => c.clientCif && c.clientCif === result.clientCif);
if (duplicate) {
this.alertService.alert({ type: 'Error', message: `Partner with CIF ${result.clientCif} is already added.` });
return;
}
this.relatedClients = [
...this.relatedClients,
{ ...result, isMandatory: false }];
this.autoSetSignatoryRights();
}
});
}
removeRelatedClient(index: number): void {
this.relatedClients = this.relatedClients.filter((_, i) => i !== index);
this.autoSetSignatoryRights();
}
toggleMandatory(client: any): void {
client.isMandatory = !client.isMandatory;
this.autoSetSignatoryRights();
}
autoSetSignatoryRights(): void {
const mandatory = this.relatedClients.filter((c) => c.isMandatory).length;
if (mandatory === 0) this.signatoryRights = 'ANYONE';
else if (mandatory === 1) this.signatoryRights = 'ONE_MANDATORY';
else this.signatoryRights = 'TWO_MANDATORY';
}
get totalSharePercentage(): number {
return this.relatedClients.reduce((sum, c) => sum + (c.sharePercentage || 0), 0);
}
get mandatoryCount(): number {
return this.relatedClients.filter((c) => c.isMandatory).length;
}
get selectedSignatoryLabel(): string {
const opt = this.signatoryRightsOptions.find((x) => x.value === this.signatoryRights);
return opt ? opt.sublabel : '';
}
get currentAccountDetails() {
const value = this.currentAccountDetailsForm.getRawValue();
value.shareLinkingEnabled = this.shareLinkingEnabled;
if (this.introducerId) {
value.introducerId = this.introducerId;
value.introducerName = this.introducerName;
value.introducerCifNumber = this.introducerCif;
}
value.isNonIndividualClient = this.isNonIndividualClient;
// Product classification fields
if (this.selectedAccountType) {
value.accountType = this.selectedAccountType;
}
if (this.selectedCustomerSegment) {
value.customerSegment = this.selectedCustomerSegment;
}
// accountStatus applies to all client types
value.accountStatus = this.selectedAccountStatus || null;
if (this.selectedAccountStatus === 'INDIVIDUAL_MALE' && this.selectedSpecialCategory)
value.specialCategory = this.selectedSpecialCategory;
if (this.selectedAccountStatus === 'INDIVIDUAL_FEMALE' && this.selectedWeakerSection)
value.weakerSection = this.selectedWeakerSection;
if (this.selectedAccountStatus === 'JOINT') {
value.modeOfOperation = this.modeOfOperation || null;
value.jointHolders = [
{
clientId: this.primaryClientId,
displayName: this.primaryClientName,
cifNumber: this.primaryClientCif,
sharePercentage: this.primaryHolderShare,
isMandatory: true,
isPrimary: true,
signingAuthority: 'Mandatory',
role: 'Primary Account Holder'
},
...this.jointHolders.map((h) => ({
clientId: h.clientId,
displayName: h.clientName,
cifNumber: h.clientCif,
sharePercentage: h.sharePercentage,
isMandatory: h.isMandatory,
isPrimary: false,
signingAuthority: h.signingAuthority || (h.isMandatory ? 'Mandatory' : 'Optional'),
role: h.role || 'Co-Holder'
}))
];
}
if (this.selectedAccountStatus === 'MINOR') {
value.guardianClientId = this.guardianClientId;
value.guardianName = this.guardianName;
value.guardianCifNumber = this.guardianCif;
value.guardianRelationship = this.guardianRelationship;
value.minorDateOfBirth = this.minorDob ? this.dateUtils.formatDate(this.minorDob, 'dd MMMM yyyy') : null;
}
// non-individual: partners are a separate dataset
if (this.isNonIndividualClient) {
value.signatoryRights = this.signatoryRights || null;
value.partners = this.relatedClients.map((c) => ({
clientId: c.clientId,
clientName: c.clientName,
clientCif: c.clientCif,
sharePercentage: c.sharePercentage,
isMandatory: c.isMandatory
}));
}
return value;
}
}