/** * 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, Input, OnInit, inject } from '@angular/core'; import { UntypedFormGroup, UntypedFormBuilder, Validators, UntypedFormControl, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; /** Custom Services */ import { RecurringDepositsService } from '../../recurring-deposits.service'; import { DenominationMasterService } from 'app/system/denomination-master/denomination-master.service'; import { ClientsService } from 'app/clients/clients.service'; import { SettingsService } from 'app/settings/settings.service'; import { Dates } from 'app/core/utils/dates'; import { Currency } from 'app/shared/models/general.model'; import { TransactionCommand, TransactionTypeFlags } from '../../../transaction.model'; import { InputAmountComponent } from '../../../../shared/input-amount/input-amount.component'; import { MatSlideToggle } from '@angular/material/slide-toggle'; import { CdkTextareaAutosize } from '@angular/cdk/text-field'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { MatDialog } from '@angular/material/dialog'; import { TransactionConfirmDialogComponent } from '../../../../savings/saving-account-actions/savings-account-transactions/transaction-confirm-dialog/transaction-confirm-dialog.component'; import { IdentityVerifyDialogComponent } from '../../../../savings/saving-account-actions/savings-account-transactions/identity-verify-dialog/identity-verify-dialog.component'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; interface Denomination { value: number; kind: 'note' | 'coin'; label: string; active: boolean; } /** * Deposits Recurring Deposits Account Component */ @Component({ selector: 'mifosx-deposit-recurring-deposits-account', templateUrl: './deposit-recurring-deposits-account.component.html', styleUrls: ['./deposit-recurring-deposits-account.component.scss'], imports: [ ...STANDALONE_SHARED_IMPORTS, InputAmountComponent, MatSlideToggle, CdkTextareaAutosize, FaIconComponent ] }) export class DepositRecurringDepositsAccountComponent implements OnInit { private formBuilder = inject(UntypedFormBuilder); private route = inject(ActivatedRoute); private router = inject(Router); private dateUtils = inject(Dates); private recurringDepositsService = inject(RecurringDepositsService); private clientsService = inject(ClientsService); private settingsService = inject(SettingsService); private dialog = inject(MatDialog); private denominationMasterService = inject(DenominationMasterService); @Input() currency: Currency; transactionAmount: any; outstandingChargeAmount: any; paymentTypes: any; accountId: string; showPaymentDetails = false; minDate = new Date(2000, 0, 1); maxDate = new Date(); depositRecurringDepositForm: UntypedFormGroup; action: string; actionName: string; transactionCommand: TransactionCommand; transactionType: TransactionTypeFlags = { deposit: false, withdrawal: false }; notes: Denomination[] = []; coins: Denomination[] = []; /** When false, discontinued (inactive) denominations stay hidden in the grid. */ showInactive = false; denominationCounts: Record = {}; accountNo: string | null = null; clientName: string | null = null; clientId: number | null = null; kycStatus: 'Verified' | 'Partial' | 'Pending' = 'Pending'; availableBalance = 0; identityVerified = false; constructor() { this.route.data.subscribe((data: { recurringDepositsAccountActionData: any }) => { this.transactionAmount = data.recurringDepositsAccountActionData.amount; this.paymentTypes = data.recurringDepositsAccountActionData.paymentTypeOptions; if ( data.recurringDepositsAccountActionData.outstandingChargeAmount && data.recurringDepositsAccountActionData.outstandingChargeAmount > 0 ) { this.outstandingChargeAmount = data.recurringDepositsAccountActionData.outstandingChargeAmount; this.transactionAmount += this.outstandingChargeAmount; } }); this.actionName = this.route.snapshot.params['name']; this.action = this.actionName.toLowerCase(); if (this.action === 'deposit' || this.action === 'withdrawal') { this.transactionCommand = this.action; this.transactionType[this.transactionCommand] = true; } else { throw new Error(`Invalid transaction action: ${this.actionName}`); } this.accountId = this.route.parent.snapshot.params['recurringDepositAccountId']; } ngOnInit() { this.maxDate = this.settingsService.businessDate; this.createdepositRecurringDepositForm(); this.loadDenominations(); this.loadContextStrip(); } /** Load active denominations from the Denomination Master so the cash * breakdown grid reflects the bank's current configuration. */ private loadDenominations(): void { this.denominationMasterService.getAll().subscribe({ next: (list: any[]) => { const rows: Denomination[] = (list || []).map((d) => ({ value: d.denomination, kind: d.kind as 'note' | 'coin', label: '₹' + d.denomination, active: !!d.isActive })); const order = (a: Denomination, b: Denomination) => b.value - a.value; this.notes = rows.filter((r) => r.kind === 'note').sort(order); this.coins = rows.filter((r) => r.kind === 'coin').sort(order); }, error: () => { this.notes = []; this.coins = []; } }); } /** True when at least one discontinued denomination exists. */ get hasInactive(): boolean { return [ ...this.notes, ...this.coins ].some((d) => !d.active); } private loadContextStrip(): void { if (!this.accountId) return; this.recurringDepositsService.getRecurringDepositsAccountData(this.accountId).subscribe({ next: (account: any) => { this.accountNo = account?.accountNo ?? null; this.clientName = account?.clientName ?? account?.groupName ?? null; this.clientId = account?.clientId ?? null; if (!this.currency && account?.currency) this.currency = account.currency; this.availableBalance = Number(account?.summary?.accountBalance ?? account?.summary?.availableBalance ?? 0); if (account?.clientId) { this.fetchClientKyc(String(account.clientId)); } }, error: () => {} }); } private fetchClientKyc(clientId: string): void { this.clientsService.getClientKyc(clientId).subscribe({ next: (kyc: any) => { const pan = !!kyc?.panVerified; const aadhaar = !!kyc?.aadhaarVerified; this.kycStatus = pan && aadhaar ? 'Verified' : pan || aadhaar ? 'Partial' : 'Pending'; }, error: () => {} }); } createdepositRecurringDepositForm() { this.depositRecurringDepositForm = this.formBuilder.group({ transactionDate: [ new Date(), Validators.required ], transactionAmount: [ 0.0, Validators.required ], paymentTypeId: [ '', Validators.required ], note: '' }); } // ── Denomination helpers ──────────────────────────────────────────── denomKey(d: Denomination): string { return `${d.kind}:${d.value}`; } countFor(d: Denomination): number { return this.denominationCounts[this.denomKey(d)] || 0; } subtotalFor(d: Denomination): number { return this.countFor(d) * d.value; } onDenomChange(d: Denomination, raw: any): void { const n = Math.max(0, Math.floor(Number(raw) || 0)); this.denominationCounts[this.denomKey(d)] = n; } bumpDenom(d: Denomination, delta: number): void { const next = Math.max(0, this.countFor(d) + delta); this.denominationCounts[this.denomKey(d)] = next; } get notesTotal(): number { return this.notes.reduce((s, d) => s + this.subtotalFor(d), 0); } get coinsTotal(): number { return this.coins.reduce((s, d) => s + this.subtotalFor(d), 0); } get denominationTotal(): number { return this.notesTotal + this.coinsTotal; } get totalPieces(): number { return Object.values(this.denominationCounts).reduce((s, n) => s + (n || 0), 0); } get denominationMatchesForm(): boolean { const formAmt = Number(this.depositRecurringDepositForm?.controls?.['transactionAmount']?.value || 0); return this.denominationTotal > 0 && formAmt === this.denominationTotal; } applyDenominationTotal(): void { this.depositRecurringDepositForm.controls['transactionAmount'].setValue(this.denominationTotal); this.depositRecurringDepositForm.controls['transactionAmount'].markAsDirty(); } clearDenominations(): void { this.denominationCounts = {}; } openIdentityVerify(): void { if (!this.clientId) return; this.identityVerified = true; this.dialog.open(IdentityVerifyDialogComponent, { width: '500px', maxWidth: '92vw', panelClass: 'idv-panel', autoFocus: false, data: { clientId: this.clientId, clientName: this.clientName, accountNo: this.accountNo } }); } addPaymentDetails() { this.showPaymentDetails = !this.showPaymentDetails; if (this.showPaymentDetails) { this.depositRecurringDepositForm.addControl('accountNumber', new UntypedFormControl('')); this.depositRecurringDepositForm.addControl('checkNumber', new UntypedFormControl('')); this.depositRecurringDepositForm.addControl('routingCode', new UntypedFormControl('')); this.depositRecurringDepositForm.addControl('receiptNumber', new UntypedFormControl('')); this.depositRecurringDepositForm.addControl('bankNumber', new UntypedFormControl('')); } else { this.depositRecurringDepositForm.removeControl('accountNumber'); this.depositRecurringDepositForm.removeControl('checkNumber'); this.depositRecurringDepositForm.removeControl('routingCode'); this.depositRecurringDepositForm.removeControl('receiptNumber'); this.depositRecurringDepositForm.removeControl('bankNumber'); } } submit() { const formAmount = Number(this.depositRecurringDepositForm.value.transactionAmount) || 0; const paymentTypeId = this.depositRecurringDepositForm.value.paymentTypeId; const paymentTypeLabel = this.paymentTypes?.find((p: any) => p.id === paymentTypeId)?.name ?? null; const ref = this.dialog.open(TransactionConfirmDialogComponent, { width: '480px', maxWidth: '92vw', panelClass: 'tcd-panel', autoFocus: false, data: { kind: this.transactionType.deposit ? 'deposit' : 'withdrawal', clientName: this.clientName, accountNo: this.accountNo, currentBalance: this.availableBalance, transactionAmount: formAmount, paymentTypeLabel } }); ref.afterClosed().subscribe((result: any) => { if (result?.confirm) { this.postTransaction(); } }); } private postTransaction(): void { const formData = this.depositRecurringDepositForm.value; const dateFormat = this.settingsService.dateFormat; const locale = this.settingsService.language.code; const prevDate = this.depositRecurringDepositForm.value.transactionDate; if (formData.transactionDate instanceof Date) { formData.transactionDate = this.dateUtils.formatDate(prevDate, dateFormat); } const data = { ...formData, dateFormat, locale }; delete data['note']; data['transactionAmount'] = data['transactionAmount'] * 1; if (this.denominationTotal > 0) { data['denominationBreakdown'] = [ ...this.notes, ...this.coins ] .map((d) => ({ denomination: d.value, kind: d.kind, count: this.countFor(d), subtotal: this.subtotalFor(d) })) .filter((row) => row.count > 0); } this.recurringDepositsService .executeRecurringDepositsAccountCommand(this.accountId, this.action, data) .subscribe(() => { this.router.navigate(['../../'], { relativeTo: this.route }); }); } }