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

406 lines
18 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 { 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';
/**
* Create new recurring deposit account
*/
@Component({
selector: 'mifosx-create-recurring-deposits-account',
templateUrl: './create-recurring-deposits-account.component.html',
styleUrls: ['./create-recurring-deposits-account.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatTabsModule,
FaIconComponent,
RecurringDepositsAccountDetailsStepComponent,
RecurringDepositsAccountCurrencyStepComponent,
RecurringDepositsAccountInterestRateChartStepComponent,
RecurringDepositsAccountMaturityTermsStepComponent,
RecurringDepositsAccountPreviewStepComponent
]
})
export class CreateRecurringDepositsAccountComponent {
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);
@ViewChild(RecurringDepositsAccountDetailsStepComponent, { static: true })
recurringDepositsAccountDetailsStep: RecurringDepositsAccountDetailsStepComponent;
@ViewChild(RecurringDepositsAccountCurrencyStepComponent)
recurringDepositsAccountCurrencyStep: RecurringDepositsAccountCurrencyStepComponent;
@ViewChild(RecurringDepositsAccountInterestRateChartStepComponent)
recurringDepositsAccountChartStep: RecurringDepositsAccountInterestRateChartStepComponent;
@ViewChild(RecurringDepositsAccountPreviewStepComponent)
recurringDepositsAccountPreviewStep: RecurringDepositsAccountPreviewStepComponent;
@ViewChild(RecurringDepositsAccountMaturityTermsStepComponent)
recurringDepositsAccountMaturityTermsStep: RecurringDepositsAccountMaturityTermsStepComponent;
/** Recurring Deposits Account Template */
recurringDepositsAccountTemplate: any;
/** Recurring Deposit Account Product Template */
recurringDepositsAccountProductTemplate: any;
/** Currently visible wizard tab (0-indexed). */
selectedTabIndex = 0;
/** Total wizard tabs — Product, Currency, Chart, Preview. */
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: { recurringDepositsAccountTemplate: any }) => {
this.recurringDepositsAccountTemplate = data.recurringDepositsAccountTemplate;
});
}
next(): void {
if (this.selectedTabIndex < this.totalTabs - 1) {
this.selectedTabIndex += 1;
}
}
prev(): void {
if (this.selectedTabIndex > 0) {
this.selectedTabIndex -= 1;
}
}
/**
* Sets recurring deposits account product template.
* Also fetches the active CBS base interest rate chart.
*/
setTemplate($event: any) {
this.recurringDepositsAccountProductTemplate = $event;
this.productsService.getFdBaseInterestRates().subscribe({
next: (rates: any[]) => (this.cbsBaseRates = rates || []),
error: () => (this.cbsBaseRates = [])
});
}
/** Captures tenure selection from calculator */
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 Recurring Deposit Account Details Form Data */
get recurringDepositAccountDetailsForm() {
return this.recurringDepositsAccountDetailsStep.recurringDepositAccountDetailsForm;
}
/** Retrieves Data of all forms */
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
};
}
/**
* Submits the recurring deposit form to create a new recurring deposit account
*/
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.recurringDepositsAccountProductTemplate?.introducerRequired && !detailsStep?.introducerId) {
this.alertService.alert({
type: 'Error',
message: 'This product requires an introducer. Please choose an existing customer as introducer 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;
}
// Same limits the server enforces - checked here so the message names the numbers before anything is sent.
const minInstallment = Number(this.recurringDepositsAccountProductTemplate?.minDepositAmount) || 0;
const maxInstallment = Number(this.recurringDepositsAccountProductTemplate?.maxDepositAmount) || 0;
if (minInstallment > 0 && this.selectedDepositAmount < minInstallment) {
this.alertService.alert({
type: 'Error',
message: `Installment ${this.selectedDepositAmount} is below this product's minimum of ${minInstallment}.`
});
return;
}
if (maxInstallment > 0 && this.selectedDepositAmount > maxInstallment) {
this.alertService.alert({
type: 'Error',
message: `Installment ${this.selectedDepositAmount} is above this product's maximum of ${maxInstallment}.`
});
return;
}
if (
this.recurringDepositsAccountCurrencyStep?.autoDebitFacility &&
detailsStep?.selectedLinkedAccount?.accountType !== 'SAVINGS'
) {
this.alertService.alert({
type: 'Error',
message:
'Auto Debit collects each installment from the linked account. Link a Savings account under Deposit Account Link, or turn Auto Debit off.'
});
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;
// Terms — pulled from product template
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;
// Settings — pulled from product template
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;
// Flags and other product defaults
const productDefaults: any = {
isCalendarInherited: pt?.isCalendarInherited ?? false,
isMandatoryDeposit: pt?.isMandatoryDeposit ?? false,
allowWithdrawal: pt?.allowWithdrawal ?? false,
// Money paid ahead of a due date counts towards the next installments. Without this an advance cash
// payment stayed unallocated: the schedule kept showing the installment unpaid, so Auto Debit collected it
// a second time and the missed-installment penalty charged it. The RD product form has no such option, so
// the product's value was always false.
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) }
: {})
};
// Charges from product template
const rawCharges: any[] = pt?.charges ?? [];
const recurringDepositAccount: any = {
...details,
...terms,
...settings,
...(this.recurringDepositsAccountMaturityTermsStep?.closureSettings ?? {}),
...productDefaults,
clientId: this.recurringDepositsAccountTemplate.clientId,
mandatoryRecommendedDepositAmount: pt?.minDepositAmount ?? 0,
recurringFrequency: pt?.recurringFrequency ?? 1,
recurringFrequencyType: pt?.recurringFrequencyType ?? 2, // Monthly
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
}))
};
// Tenure override from interest rate chart calculator
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; // Days
}
// Amount override from calculator if provided
if (this.selectedDepositAmount) {
recurringDepositAccount.mandatoryRecommendedDepositAmount = this.selectedDepositAmount;
}
// Senior citizen rate override
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.createRecurringDepositAccount(recurringDepositAccount).subscribe({
next: (response: any) => {
this.router.navigate(
[
'../',
response.resourceId
],
{ relativeTo: this.route }
);
},
error: (error: any) => {
const errorCode =
error?.error?.errors?.[0]?.userMessageGlobalisationCode ?? error?.error?.userMessageGlobalisationCode;
if (errorCode === 'error.msg.savings.account.duplicate.product.for.client') {
this.alertService.alert({
type: 'Error',
message:
'This client already has an active Recurring Deposit account with the selected product. Please choose a different product.'
});
} else if (errorCode === 'error.msg.savingsaccount.duplicate.externalId') {
this.alertService.alert({
type: 'Error',
message: 'An account with this External ID already exists. Please use a unique External ID.'
});
}
}
});
}
}