Files
cbsnexora/src/app/deposits/recurring-deposits/edit-recurring-deposit-account/edit-recurring-deposit-account.component.ts
T

362 lines
16 KiB
TypeScript

/**
* 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, ViewChild, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
/** Custom Services */
import { RecurringDepositsService } from '../recurring-deposits.service';
import { ClientsService } from 'app/clients/clients.service';
import { SettingsService } from 'app/settings/settings.service';
import { ProductsService } from 'app/products/products.service';
import { AlertService } from 'app/core/alert/alert.service';
/** Step Components */
import { RecurringDepositsAccountDetailsStepComponent } from '../recurring-deposits-account-stepper/recurring-deposits-account-details-step/recurring-deposits-account-details-step.component';
import { Dates } from 'app/core/utils/dates';
import { MatTabsModule } from '@angular/material/tabs';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { RecurringDepositsAccountCurrencyStepComponent } from '../recurring-deposits-account-stepper/recurring-deposits-account-currency-step/recurring-deposits-account-currency-step.component';
import { RecurringDepositsAccountInterestRateChartStepComponent } from '../recurring-deposits-account-stepper/recurring-deposits-account-interest-rate-chart-step/recurring-deposits-account-interest-rate-chart-step.component';
import { RecurringDepositsAccountPreviewStepComponent } from '../recurring-deposits-account-stepper/recurring-deposits-account-preview-step/recurring-deposits-account-preview-step.component';
import { RecurringDepositsAccountMaturityTermsStepComponent } from '../recurring-deposits-account-stepper/recurring-deposits-account-maturity-terms-step/recurring-deposits-account-maturity-terms-step.component';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/**
* Edit Recurring Deposit Account Component — same tab UI as Create, pre-populated with existing data.
*/
@Component({
selector: 'mifosx-edit-recurring-deposit-account',
templateUrl: './edit-recurring-deposit-account.component.html',
styleUrls: ['./edit-recurring-deposit-account.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatTabsModule,
FaIconComponent,
RecurringDepositsAccountDetailsStepComponent,
RecurringDepositsAccountCurrencyStepComponent,
RecurringDepositsAccountInterestRateChartStepComponent,
RecurringDepositsAccountMaturityTermsStepComponent,
RecurringDepositsAccountPreviewStepComponent
]
})
export class EditRecurringDepositAccountComponent {
private route = inject(ActivatedRoute);
private router = inject(Router);
private dateUtils = inject(Dates);
private recurringDepositsService = inject(RecurringDepositsService);
private settingsService = inject(SettingsService);
private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private clientsService = inject(ClientsService);
@ViewChild(RecurringDepositsAccountDetailsStepComponent, { static: true })
recurringDepositsAccountDetailsStep: RecurringDepositsAccountDetailsStepComponent;
@ViewChild(RecurringDepositsAccountCurrencyStepComponent)
recurringDepositsAccountCurrencyStep: RecurringDepositsAccountCurrencyStepComponent;
@ViewChild(RecurringDepositsAccountInterestRateChartStepComponent)
recurringDepositsAccountChartStep: RecurringDepositsAccountInterestRateChartStepComponent;
@ViewChild(RecurringDepositsAccountPreviewStepComponent)
recurringDepositsAccountPreviewStep: RecurringDepositsAccountPreviewStepComponent;
@ViewChild(RecurringDepositsAccountMaturityTermsStepComponent)
recurringDepositsAccountMaturityTermsStep: RecurringDepositsAccountMaturityTermsStepComponent;
/** Full account data + template from resolver */
recurringDepositsAccountAndTemplate: any;
/** Product template emitted by details step */
recurringDepositsAccountProductTemplate: any;
/** Currently visible wizard tab (0-indexed). */
selectedTabIndex = 0;
private readonly totalTabs = 5;
/** Active CBS base interest rate versions */
cbsBaseRates: any[] = [];
/** Selected tenure value and frequency from calculator */
selectedTenureValue: number | null = null;
selectedTenureFrequencyId: number | null = null;
selectedDepositAmount: number | null = null;
rdAppliedRate: number | null = null;
rdIsSeniorCitizen = false;
constructor() {
this.route.data.subscribe((data: { recurringDepositsAccountAndTemplate: any }) => {
const account = data.recurringDepositsAccountAndTemplate;
this.recurringDepositsAccountAndTemplate = account;
// Pre-populate tenure from existing account
if (account?.depositPeriod) {
this.selectedTenureValue = account.depositPeriod;
this.selectedTenureFrequencyId = account.depositPeriodFrequency?.id ?? 2;
}
if (account?.mandatoryRecommendedDepositAmount) {
this.selectedDepositAmount = account.mandatoryRecommendedDepositAmount;
}
if (account?.clientId && account?.accountNo) {
this.clientsService
.getClientNominees(String(account.clientId), account.accountNo, 'RD')
.subscribe((nominees: any[]) => {
if (Array.isArray(nominees) && nominees.length > 0) {
this.recurringDepositsAccountAndTemplate = { ...this.recurringDepositsAccountAndTemplate, nominees };
}
});
}
});
}
get initialTenure(): {
depositPeriod: number;
depositPeriodFrequencyId: number;
depositAmount?: number;
isSeniorCitizen?: boolean;
appliedRate?: number;
} | null {
if (!this.selectedTenureValue) {
return null;
}
return {
depositPeriod: this.selectedTenureValue,
depositPeriodFrequencyId: this.selectedTenureFrequencyId ?? 2,
depositAmount: this.selectedDepositAmount ?? undefined,
isSeniorCitizen: !!this.recurringDepositsAccountAndTemplate?.isSeniorCitizen,
appliedRate: this.recurringDepositsAccountAndTemplate?.seniorCitizenInterestRate ?? undefined
};
}
next(): void {
if (this.selectedTabIndex < this.totalTabs - 1) {
this.selectedTabIndex += 1;
}
}
prev(): void {
if (this.selectedTabIndex > 0) {
this.selectedTabIndex -= 1;
}
}
setTemplate($event: any) {
this.recurringDepositsAccountProductTemplate = $event;
this.productsService.getRdBaseInterestRates().subscribe({
next: (rates: any) => (this.cbsBaseRates = Array.isArray(rates) ? rates : rates ? [rates] : []),
error: () => (this.cbsBaseRates = [])
});
}
handleTenureSelected($event: any) {
this.selectedTenureValue = $event.depositPeriod;
this.selectedTenureFrequencyId = $event.depositPeriodFrequencyId;
this.selectedDepositAmount = $event.depositAmount;
this.rdAppliedRate = $event.appliedRate ?? null;
this.rdIsSeniorCitizen = $event.isSeniorCitizen ?? false;
}
get recurringDepositAccountDetailsForm() {
return this.recurringDepositsAccountDetailsStep.recurringDepositAccountDetailsForm;
}
get recurringDepositAccountData() {
return { ...this.recurringDepositsAccountDetailsStep.recurringDepositAccountDetails };
}
get recurringDepositAccount() {
return { ...this.recurringDepositsAccountDetailsStep.recurringDepositAccountDetails };
}
get rdTenureDays(): number | null {
return this.recurringDepositsAccountChartStep?.matchResult?.tenureDays ?? null;
}
get rdApplicableSlab(): any | null {
return this.recurringDepositsAccountChartStep?.matchResult?.slab ?? null;
}
get rdMaturityAmount(): number | null {
return this.recurringDepositsAccountChartStep?.matchResult?.maturityAmount ?? null;
}
get rdInterestEarned(): number | null {
return this.recurringDepositsAccountChartStep?.matchResult?.interestEarned ?? null;
}
get rdDaysInYear(): number | null {
return this.recurringDepositsAccountChartStep?.matchResult?.daysInYear ?? null;
}
get submittedOnDate(): Date | null {
return this.recurringDepositAccountDetailsForm?.value?.submittedOnDate ?? null;
}
get rdCurrencyFlags() {
return {
autoDebitFacility: this.recurringDepositsAccountCurrencyStep?.autoDebitFacility ?? false
};
}
submit() {
const detailsStep = this.recurringDepositsAccountDetailsStep;
if (detailsStep.selectedAccountStatus === 'JOINT' && detailsStep.totalJointSharePercentage !== 100) {
this.alertService.alert({
type: 'Error',
message: `Total ownership is ${detailsStep.totalJointSharePercentage}%. It must equal 100% before submitting.`
});
return;
}
if (
this.recurringDepositsAccountProductTemplate?.nominationFacility &&
(this.recurringDepositsAccountCurrencyStep?.nominees ?? []).length === 0
) {
this.alertService.alert({
type: 'Error',
message: 'Nomination Facility is enabled for this product. Please add at least one nominee before submitting.'
});
return;
}
if (!this.selectedTenureValue || this.selectedTenureFrequencyId === null) {
this.alertService.alert({
type: 'Error',
message: 'Please enter the Deposit Tenure and click "Find Rate" before submitting.'
});
return;
}
if (!this.selectedDepositAmount || this.selectedDepositAmount <= 0) {
this.alertService.alert({
type: 'Error',
message: 'Please enter the Monthly Installment amount and click "Find Rate" before submitting.'
});
return;
}
const lienError = this.recurringDepositsAccountCurrencyStep?.lienPercentageError;
if (lienError) {
this.alertService.alert({ type: 'Error', message: `Loan against this RD: ${lienError}` });
return;
}
if (!detailsStep?.selectedCustomerSegment) {
this.alertService.alert({ type: 'Error', message: 'Please select a Customer Segment before submitting.' });
return;
}
const locale = this.settingsService.language.code;
const dateFormat = this.settingsService.dateFormat;
const monthDayFormat = 'dd MMMM';
const pt = this.recurringDepositsAccountProductTemplate;
const details = this.recurringDepositAccount;
const currencyStep = this.recurringDepositsAccountCurrencyStep;
const terms: any = {};
if (pt?.nominalAnnualInterestRate != null) terms.nominalAnnualInterestRate = pt.nominalAnnualInterestRate;
if (pt?.interestCompoundingPeriodType?.id != null)
terms.interestCompoundingPeriodType = pt.interestCompoundingPeriodType.id;
if (pt?.interestPostingPeriodType?.id != null) terms.interestPostingPeriodType = pt.interestPostingPeriodType.id;
if (pt?.interestCalculationType?.id != null) terms.interestCalculationType = pt.interestCalculationType.id;
if (pt?.interestCalculationDaysInYearType?.id != null)
terms.interestCalculationDaysInYearType = pt.interestCalculationDaysInYearType.id;
const settings: any = {};
if (pt?.lockinPeriodFrequency != null) settings.lockinPeriodFrequency = pt.lockinPeriodFrequency;
if (pt?.lockinPeriodFrequencyType?.id != null) settings.lockinPeriodFrequencyType = pt.lockinPeriodFrequencyType.id;
if (pt?.minDepositTerm != null) settings.minDepositTerm = pt.minDepositTerm;
if (pt?.minDepositTermType?.id != null) settings.minDepositTermTypeId = pt.minDepositTermType.id;
if (pt?.inMultiplesOfDepositTerm != null) settings.inMultiplesOfDepositTerm = pt.inMultiplesOfDepositTerm;
if (pt?.inMultiplesOfDepositTermType?.id != null)
settings.inMultiplesOfDepositTermTypeId = pt.inMultiplesOfDepositTermType.id;
if (pt?.maxDepositTerm != null) settings.maxDepositTerm = pt.maxDepositTerm;
if (pt?.maxDepositTermType?.id != null) settings.maxDepositTermTypeId = pt.maxDepositTermType.id;
if (pt?.preClosurePenalApplicable != null) settings.preClosurePenalApplicable = pt.preClosurePenalApplicable;
if (pt?.preClosurePenalInterest != null) settings.preClosurePenalInterest = pt.preClosurePenalInterest;
if (pt?.preClosurePenalInterestOnType?.id != null)
settings.preClosurePenalInterestOnTypeId = pt.preClosurePenalInterestOnType.id;
if (pt?.maturityInstructionId != null) settings.maturityInstructionId = pt.maturityInstructionId;
if (pt?.transferInterestToSavings != null) settings.transferInterestToSavings = pt.transferInterestToSavings;
if (pt?.withHoldTax != null) settings.withHoldTax = pt.withHoldTax;
const productDefaults: any = {
isCalendarInherited: pt?.isCalendarInherited ?? false,
isMandatoryDeposit: pt?.isMandatoryDeposit ?? false,
allowWithdrawal: pt?.allowWithdrawal ?? false,
// See create-recurring-deposits-account: advance payments must count towards the next installments.
adjustAdvanceTowardsFuturePayments: true,
autoDebitFacility: currencyStep?.autoDebitFacility ?? pt?.autoDebitFacility ?? false,
// Lien Marked products only - the server ignores it otherwise and caps it at the product's limit.
...(currencyStep?.lienAllowed && currencyStep?.lienPercentage != null
? { lienPercentage: Number(currencyStep.lienPercentage) }
: {})
};
const rawCharges: any[] = pt?.charges ?? [];
const recurringDepositAccount: any = {
...details,
...terms,
...settings,
...(this.recurringDepositsAccountMaturityTermsStep?.closureSettings ?? {}),
...productDefaults,
clientId: this.recurringDepositsAccountAndTemplate.clientId,
mandatoryRecommendedDepositAmount: pt?.minDepositAmount ?? 0,
recurringFrequency: pt?.recurringFrequency ?? 1,
recurringFrequencyType: pt?.recurringFrequencyType ?? 2,
submittedOnDate: this.dateUtils.formatDate(details.submittedOnDate, dateFormat),
expectedFirstDepositOnDate: this.dateUtils.formatDate(details.expectedFirstDepositOnDate, dateFormat),
dateFormat,
monthDayFormat,
locale,
charts: [
{
chartSlabs:
pt?.accountChart?.chartSlabs ?? pt?.activeChart?.chartSlabs ?? pt?.interestRateCharts?.[0]?.chartSlabs ?? []
}
],
charges: rawCharges.map((charge: any) => ({
chargeId: charge.chargeId ?? charge.id,
amount: charge.amount,
dueDate: charge.dueDate && this.dateUtils.formatDate(charge.dueDate, dateFormat),
feeOnMonthDay: charge.feeOnMonthDay,
feeInterval: charge.feeInterval
}))
};
if (this.selectedTenureValue && this.selectedTenureFrequencyId !== null) {
recurringDepositAccount.depositPeriod = this.selectedTenureValue;
recurringDepositAccount.depositPeriodFrequencyId = this.selectedTenureFrequencyId;
} else if (this.rdTenureDays) {
recurringDepositAccount.depositPeriod = this.rdTenureDays;
recurringDepositAccount.depositPeriodFrequencyId = 0;
}
if (this.selectedDepositAmount) {
recurringDepositAccount.mandatoryRecommendedDepositAmount = this.selectedDepositAmount;
}
if (this.rdIsSeniorCitizen && this.rdAppliedRate != null && this.rdAppliedRate > 0) {
recurringDepositAccount.isSeniorCitizen = true;
recurringDepositAccount.seniorCitizenInterestRate = this.rdAppliedRate;
recurringDepositAccount.nominalAnnualInterestRate = this.rdAppliedRate;
}
const nominees = this.recurringDepositsAccountCurrencyStep?.nominees ?? [];
if (nominees.length > 0) {
recurringDepositAccount.nominees = nominees.map((n: any) => ({
nomineeClientId: n.nomineeClientId,
nominationType: n.nominationType,
relationshipId: n.relationshipId,
percentageShare: n.percentageShare,
nomineeIsMinor: n.nomineeIsMinor,
...(n.guardianClientId ? { guardianClientId: n.guardianClientId } : {}),
remarks: n.remarks
}));
}
this.recurringDepositsService
.updateRecurringDepositAccount(this.recurringDepositsAccountAndTemplate.id, recurringDepositAccount)
.subscribe((response: any) => {
this.router.navigate(['../'], { relativeTo: this.route });
});
}
}