Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08519da8b1 | ||
|
|
cad7f54c47 | ||
|
|
8724c54d9b | ||
|
|
5c0a482f49 | ||
|
|
0e07e60328 | ||
|
|
e227e8ae0f | ||
|
|
231919b62b | ||
|
|
9eac40bb5c | ||
|
|
14b2585cf5 | ||
|
|
a2fa8688ae | ||
|
|
a8ca7dd948 | ||
|
|
c8833367b9 | ||
|
|
94b0afff38 | ||
|
|
9dd4f8bedb | ||
|
|
1107610c08 | ||
|
|
2213308254 | ||
|
|
c568eb0abf |
+1
-1
@@ -159,7 +159,7 @@ gitVersioning.apply {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ext['groovy.version'] = '4.0.17'
|
ext['groovy.version'] = '4.0.17'
|
||||||
ext['swaggerFile'] = "$rootDir/fineract-provider/build/resources/main/static/fineract.json".toString()
|
ext['swaggerFile'] = "$rootDir/fineract-provider/build/resources/main/static/fineract.json".toString().replace(" ", "%20")
|
||||||
|
|
||||||
// Apply static weaving configuration to all subprojects
|
// Apply static weaving configuration to all subprojects
|
||||||
subprojects { subproject ->
|
subprojects { subproject ->
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ task cleanupGeneratedJavaFiles() {
|
|||||||
// Configure Java compilation
|
// Configure Java compilation
|
||||||
tasks.named('compileJava') {
|
tasks.named('compileJava') {
|
||||||
outputs.cacheIf { true }
|
outputs.cacheIf { true }
|
||||||
dependsOn(buildJavaSdk, buildTypescriptAngularSdk, buildAsciidoc, cleanupGeneratedJavaFiles, licenseFormatMain, spotlessMiscApply)
|
dependsOn(buildJavaSdk, cleanupGeneratedJavaFiles, licenseFormatMain, spotlessMiscApply)
|
||||||
mustRunAfter(licenseFormatMain, cleanupGeneratedJavaFiles)
|
mustRunAfter(licenseFormatMain, cleanupGeneratedJavaFiles)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+3
-1
@@ -436,7 +436,9 @@ public final class AccountingConstants {
|
|||||||
CASH_AT_TELLER(102, "cashAtTeller", GLAccountType.ASSET), //
|
CASH_AT_TELLER(102, "cashAtTeller", GLAccountType.ASSET), //
|
||||||
OPENING_BALANCES_TRANSFER_CONTRA(300, "openingBalancesTransferContra", GLAccountType.EQUITY), //
|
OPENING_BALANCES_TRANSFER_CONTRA(300, "openingBalancesTransferContra", GLAccountType.EQUITY), //
|
||||||
ASSET_FUND_SOURCE(103, "fundSource", GLAccountType.ASSET), //
|
ASSET_FUND_SOURCE(103, "fundSource", GLAccountType.ASSET), //
|
||||||
PAYABLE_DIVIDENDS(201, "payableDividends", GLAccountType.LIABILITY); //
|
PAYABLE_DIVIDENDS(201, "payableDividends", GLAccountType.LIABILITY), //
|
||||||
|
RESERVE_FOR_DIVIDEND(301, "reserveForDividend", GLAccountType.EQUITY), //
|
||||||
|
DIVIDEND_FORFEITED_INCOME(400, "dividendForfeitedIncome", GLAccountType.INCOME); //
|
||||||
|
|
||||||
private final Integer value;
|
private final Integer value;
|
||||||
private final String code;
|
private final String code;
|
||||||
|
|||||||
+20
-1
@@ -137,7 +137,7 @@ public class CommandSourceService {
|
|||||||
String permission = commandSource.getPermissionCode();
|
String permission = commandSource.getPermissionCode();
|
||||||
boolean isMakerChecker = configurationDomainService.isMakerCheckerEnabledForTask(permission);
|
boolean isMakerChecker = configurationDomainService.isMakerCheckerEnabledForTask(permission);
|
||||||
if (isMakerChecker || result.isRollbackTransaction()) {
|
if (isMakerChecker || result.isRollbackTransaction()) {
|
||||||
if (isApprovedByChecker || user.isCheckerSuperUser()) {
|
if (isApprovedByChecker || isSuperUserBypassAllowed(commandSource, user)) {
|
||||||
commandSource.markAsChecked(user);
|
commandSource.markAsChecked(user);
|
||||||
} else {
|
} else {
|
||||||
if (commandSource.isSanitized()) {
|
if (commandSource.isSanitized()) {
|
||||||
@@ -151,6 +151,25 @@ public class CommandSourceService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isSuperUserBypassAllowed(CommandSource commandSource, AppUser user) {
|
||||||
|
if (!user.isCheckerSuperUser()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ("GLACCOUNT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "CBSBASEINTERESTRATE".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "CHARGE".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "LOANPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "SAVINGSPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "CURRENTPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "SHAREPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "FIXEDDEPOSITPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "USER".equalsIgnoreCase(commandSource.getEntityName())
|
||||||
|
|| "ROLE".equalsIgnoreCase(commandSource.getEntityName())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private void sanitizeJson(@NonNull CommandSource commandSource, Set<String> sanitizeKeys) {
|
private void sanitizeJson(@NonNull CommandSource commandSource, Set<String> sanitizeKeys) {
|
||||||
if (sanitizeKeys == null || sanitizeKeys.isEmpty()) {
|
if (sanitizeKeys == null || sanitizeKeys.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
+8
@@ -2211,6 +2211,14 @@ public class CommandWrapperBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CommandWrapperBuilder createCbsBaseInterestRate() {
|
||||||
|
this.actionName = "CREATE";
|
||||||
|
this.entityName = "CBSBASEINTERESTRATE";
|
||||||
|
this.entityId = null;
|
||||||
|
this.href = "/fixeddepositproducts/baseinterestrates";
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public CommandWrapperBuilder updateFixedDepositProduct(final Long productId) {
|
public CommandWrapperBuilder updateFixedDepositProduct(final Long productId) {
|
||||||
this.actionName = "UPDATE";
|
this.actionName = "UPDATE";
|
||||||
this.entityName = "FIXEDDEPOSITPRODUCT";
|
this.entityName = "FIXEDDEPOSITPRODUCT";
|
||||||
|
|||||||
+2
@@ -26,6 +26,8 @@ public interface ConfigurationDomainService {
|
|||||||
|
|
||||||
boolean isMakerCheckerEnabledForTask(String taskPermissionCode);
|
boolean isMakerCheckerEnabledForTask(String taskPermissionCode);
|
||||||
|
|
||||||
|
boolean isMakerCheckerEnabled();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global kill-switch for MFA-factor-backed login enforcement. When true, users with at least
|
* Global kill-switch for MFA-factor-backed login enforcement. When true, users with at least
|
||||||
* one verified, non-disabled row in {@code m_user_mfa_factor} must complete a 2FA challenge
|
* one verified, non-disabled row in {@code m_user_mfa_factor} must complete a 2FA challenge
|
||||||
|
|||||||
+1
@@ -38,6 +38,7 @@ public enum JobName {
|
|||||||
GENERATE_RD_SCEHDULE("Generate Mandatory Savings Schedule"), //
|
GENERATE_RD_SCEHDULE("Generate Mandatory Savings Schedule"), //
|
||||||
GENERATE_LOANLOSS_PROVISIONING("Generate Loan Loss Provisioning"), //
|
GENERATE_LOANLOSS_PROVISIONING("Generate Loan Loss Provisioning"), //
|
||||||
POST_DIVIDENTS_FOR_SHARES("Post Dividends For Shares"), //
|
POST_DIVIDENTS_FOR_SHARES("Post Dividends For Shares"), //
|
||||||
|
FORFEIT_UNCLAIMED_DIVIDENDS("Forfeit Unclaimed Dividends"), //
|
||||||
UPDATE_SAVINGS_DORMANT_ACCOUNTS("Update Savings Dormant Accounts"), //
|
UPDATE_SAVINGS_DORMANT_ACCOUNTS("Update Savings Dormant Accounts"), //
|
||||||
ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS(
|
ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS(
|
||||||
"Add Accrual Transactions For Loans With Income Posted As Transactions"), //
|
"Add Accrual Transactions For Loans With Income Posted As Transactions"), //
|
||||||
|
|||||||
+3
@@ -36,6 +36,9 @@ public interface AmlAlertRepository extends JpaRepository<AmlAlert, Long> {
|
|||||||
|
|
||||||
long countByClientId(Long clientId);
|
long countByClientId(Long clientId);
|
||||||
|
|
||||||
|
/** Alerts for one customer inside the recurring-behaviour observation window. */
|
||||||
|
long countByClient_IdAndRaisedOnGreaterThanEqual(Long clientId, LocalDateTime since);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Alerts already raised against one transaction under one rule. Used to stop the same ledger entry being marked
|
* Alerts already raised against one transaction under one rule. Used to stop the same ledger entry being marked
|
||||||
* twice, which would put two STR cases in front of the Principal Officer for a single transaction.
|
* twice, which would put two STR cases in front of the Principal Officer for a single transaction.
|
||||||
|
|||||||
+109
@@ -0,0 +1,109 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.domain;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
|
import jakarta.persistence.ManyToOne;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.Client;
|
||||||
|
import org.apache.fineract.useradministration.domain.AppUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A reviewer's judgement on a customer who repeatedly trips the AML engine.
|
||||||
|
*
|
||||||
|
* Distinct from the per-transaction disposition held on {@link AmlAlert}: that answers "was this
|
||||||
|
* transaction acceptable", this answers "is this customer's pattern of behaviour acceptable".
|
||||||
|
* {@link #alertCountAtReview} is what lets the queue clear — see the 0460 changelog.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "m_aml_recurring_review")
|
||||||
|
public class AmlRecurringReview {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@ManyToOne(optional = false)
|
||||||
|
@JoinColumn(name = "client_id", nullable = false)
|
||||||
|
private Client client;
|
||||||
|
|
||||||
|
@Column(name = "alert_count_at_review", nullable = false)
|
||||||
|
private Integer alertCountAtReview;
|
||||||
|
|
||||||
|
@Column(name = "outcome", nullable = false, length = 30)
|
||||||
|
private String outcome;
|
||||||
|
|
||||||
|
@Column(name = "notes", nullable = false, length = 1000)
|
||||||
|
private String notes;
|
||||||
|
|
||||||
|
@ManyToOne(optional = false)
|
||||||
|
@JoinColumn(name = "reviewed_by", nullable = false)
|
||||||
|
private AppUser reviewedBy;
|
||||||
|
|
||||||
|
@Column(name = "reviewed_on", nullable = false)
|
||||||
|
private LocalDateTime reviewedOn;
|
||||||
|
|
||||||
|
protected AmlRecurringReview() {}
|
||||||
|
|
||||||
|
public static AmlRecurringReview record(final Client client, final int alertCountAtReview,
|
||||||
|
final AmlRecurringReviewOutcome outcome, final String notes, final AppUser reviewedBy) {
|
||||||
|
final AmlRecurringReview review = new AmlRecurringReview();
|
||||||
|
review.client = client;
|
||||||
|
review.alertCountAtReview = alertCountAtReview;
|
||||||
|
review.outcome = outcome.name();
|
||||||
|
review.notes = notes;
|
||||||
|
review.reviewedBy = reviewedBy;
|
||||||
|
review.reviewedOn = LocalDateTime.now();
|
||||||
|
return review;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Client getClient() {
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getAlertCountAtReview() {
|
||||||
|
return alertCountAtReview;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AmlRecurringReviewOutcome getOutcome() {
|
||||||
|
return AmlRecurringReviewOutcome.valueOf(outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getNotes() {
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AppUser getReviewedBy() {
|
||||||
|
return reviewedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getReviewedOn() {
|
||||||
|
return reviewedOn;
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.domain;
|
||||||
|
|
||||||
|
/** What a reviewer concluded about a customer's repeated AML activity. */
|
||||||
|
public enum AmlRecurringReviewOutcome {
|
||||||
|
|
||||||
|
/** Behaviour explained and acceptable — nothing further, but the customer stays visible if it recurs. */
|
||||||
|
CLEARED,
|
||||||
|
/** Not conclusive; keep watching this customer more closely. */
|
||||||
|
MONITOR,
|
||||||
|
/** Warrants an STR case; the reviewer escalates the individual alerts separately. */
|
||||||
|
ESCALATED
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.domain;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface AmlRecurringReviewRepository extends JpaRepository<AmlRecurringReview, Long> {
|
||||||
|
|
||||||
|
/** Newest first, so the caller can take the head as the latest review for a customer. */
|
||||||
|
List<AmlRecurringReview> findByClient_IdOrderByReviewedOnDesc(Long clientId);
|
||||||
|
}
|
||||||
+23
@@ -86,6 +86,29 @@ public class AmlTransactionRule {
|
|||||||
|
|
||||||
protected AmlTransactionRule() {}
|
protected AmlTransactionRule() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the live-transaction counterpart of a {@code ClientRiskRule} authored from the AML
|
||||||
|
* Rules Master screen. {@code sourceClientRiskRuleId} is the link the read side joins on, so
|
||||||
|
* the two rows are always created together and the rule code is derived from it.
|
||||||
|
*/
|
||||||
|
public static AmlTransactionRule createForRiskRule(final Long sourceClientRiskRuleId, final String description,
|
||||||
|
final AmlAppliesTo appliesTo, final AmlRuleType ruleType, final Integer windowDays,
|
||||||
|
final BigDecimal thresholdAmount, final BigDecimal minLimitAmount, final BigDecimal maxLimitAmount) {
|
||||||
|
final AmlTransactionRule rule = new AmlTransactionRule();
|
||||||
|
rule.sourceClientRiskRuleId = sourceClientRiskRuleId;
|
||||||
|
// rule_code is UNIQUE; the source rule id is unique per row, so this cannot collide.
|
||||||
|
rule.ruleCode = "CRR-" + sourceClientRiskRuleId;
|
||||||
|
rule.description = description;
|
||||||
|
rule.appliesTo = appliesTo.name();
|
||||||
|
rule.ruleType = ruleType.name();
|
||||||
|
rule.windowDays = windowDays;
|
||||||
|
rule.thresholdAmount = thresholdAmount;
|
||||||
|
rule.minLimitAmount = minLimitAmount;
|
||||||
|
rule.maxLimitAmount = maxLimitAmount;
|
||||||
|
rule.active = true;
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
public Long getId() {
|
public Long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -191,6 +191,7 @@ public class ClientApiConstants {
|
|||||||
public static final String constitutionIdParamName = "constitutionId";
|
public static final String constitutionIdParamName = "constitutionId";
|
||||||
public static final String mainBusinessLineIdParamName = "mainBusinessLineId";
|
public static final String mainBusinessLineIdParamName = "mainBusinessLineId";
|
||||||
public static final String authorizedSignatoryParamName = "authorizedSignatory";
|
public static final String authorizedSignatoryParamName = "authorizedSignatory";
|
||||||
|
public static final String authorizedSignatoryClientIdsParamName = "authorizedSignatoryClientIds";
|
||||||
public static final String additionalInfoParamName = "additionalInfo";
|
public static final String additionalInfoParamName = "additionalInfo";
|
||||||
public static final String dateOfRegistrationParamName = "dateOfRegistration";
|
public static final String dateOfRegistrationParamName = "dateOfRegistration";
|
||||||
|
|
||||||
|
|||||||
@@ -105,6 +105,19 @@ public final class ClientData implements Comparable<ClientData>, Serializable {
|
|||||||
private Boolean alternateDipVerified;
|
private Boolean alternateDipVerified;
|
||||||
private Long alternateDipLookupLogId;
|
private Long alternateDipLookupLogId;
|
||||||
private String alternateDipTimestamp;
|
private String alternateDipTimestamp;
|
||||||
|
/**
|
||||||
|
* Live DIP/MNRL status of the number, resolved from the latest lookup rather than the flag
|
||||||
|
* captured at onboarding. A customer cleared at onboarding whose number is later reported or
|
||||||
|
* reassigned would otherwise keep showing "Verified" forever.
|
||||||
|
*/
|
||||||
|
private String dipLiveStatus;
|
||||||
|
private String alternateDipLiveStatus;
|
||||||
|
/**
|
||||||
|
* Disposition of the client's most recent flagged sanctions alert, or null when they carry
|
||||||
|
* none. Like the DIP status this is resolved live: nameVerified is captured at onboarding and
|
||||||
|
* would keep reading "Clear" after the client was added to a later list snapshot.
|
||||||
|
*/
|
||||||
|
private String sanctionsAlertStatus;
|
||||||
private Boolean nameVerified;
|
private Boolean nameVerified;
|
||||||
private Long screeningLogId;
|
private Long screeningLogId;
|
||||||
private Boolean isStaff;
|
private Boolean isStaff;
|
||||||
@@ -436,6 +449,11 @@ public final class ClientData implements Comparable<ClientData>, Serializable {
|
|||||||
data.alternateDipVerified = clientData.alternateDipVerified;
|
data.alternateDipVerified = clientData.alternateDipVerified;
|
||||||
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
||||||
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
||||||
|
// Carried across too: these helpers rebuild ClientData field by field, so a field missing
|
||||||
|
// here is silently dropped from the payload the client view loads.
|
||||||
|
data.dipLiveStatus = clientData.dipLiveStatus;
|
||||||
|
data.alternateDipLiveStatus = clientData.alternateDipLiveStatus;
|
||||||
|
data.sanctionsAlertStatus = clientData.sanctionsAlertStatus;
|
||||||
data.nameVerified = clientData.nameVerified;
|
data.nameVerified = clientData.nameVerified;
|
||||||
data.screeningLogId = clientData.screeningLogId;
|
data.screeningLogId = clientData.screeningLogId;
|
||||||
return data;
|
return data;
|
||||||
@@ -498,6 +516,11 @@ public final class ClientData implements Comparable<ClientData>, Serializable {
|
|||||||
data.alternateDipVerified = clientData.alternateDipVerified;
|
data.alternateDipVerified = clientData.alternateDipVerified;
|
||||||
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
||||||
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
||||||
|
// Carried across too: these helpers rebuild ClientData field by field, so a field missing
|
||||||
|
// here is silently dropped from the payload the client view loads.
|
||||||
|
data.dipLiveStatus = clientData.dipLiveStatus;
|
||||||
|
data.alternateDipLiveStatus = clientData.alternateDipLiveStatus;
|
||||||
|
data.sanctionsAlertStatus = clientData.sanctionsAlertStatus;
|
||||||
data.nameVerified = clientData.nameVerified;
|
data.nameVerified = clientData.nameVerified;
|
||||||
data.screeningLogId = clientData.screeningLogId;
|
data.screeningLogId = clientData.screeningLogId;
|
||||||
return data;
|
return data;
|
||||||
@@ -550,6 +573,11 @@ public final class ClientData implements Comparable<ClientData>, Serializable {
|
|||||||
data.alternateDipVerified = clientData.alternateDipVerified;
|
data.alternateDipVerified = clientData.alternateDipVerified;
|
||||||
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
data.alternateDipLookupLogId = clientData.alternateDipLookupLogId;
|
||||||
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
data.alternateDipTimestamp = clientData.alternateDipTimestamp;
|
||||||
|
// Carried across too: these helpers rebuild ClientData field by field, so a field missing
|
||||||
|
// here is silently dropped from the payload the client view loads.
|
||||||
|
data.dipLiveStatus = clientData.dipLiveStatus;
|
||||||
|
data.alternateDipLiveStatus = clientData.alternateDipLiveStatus;
|
||||||
|
data.sanctionsAlertStatus = clientData.sanctionsAlertStatus;
|
||||||
data.nameVerified = clientData.nameVerified;
|
data.nameVerified = clientData.nameVerified;
|
||||||
data.screeningLogId = clientData.screeningLogId;
|
data.screeningLogId = clientData.screeningLogId;
|
||||||
return data;
|
return data;
|
||||||
|
|||||||
+14
@@ -34,6 +34,8 @@ public class ClientNonPersonData implements Serializable {
|
|||||||
private final CodeValueData mainBusinessLine;
|
private final CodeValueData mainBusinessLine;
|
||||||
private final String remarks;
|
private final String remarks;
|
||||||
private final String authorizedSignatory;
|
private final String authorizedSignatory;
|
||||||
|
/** Client ids behind {@link #authorizedSignatory}, comma separated and in the same order. */
|
||||||
|
private final String authorizedSignatoryClientIds;
|
||||||
private final String additionalInfo;
|
private final String additionalInfo;
|
||||||
private final LocalDate dateOfRegistration;
|
private final LocalDate dateOfRegistration;
|
||||||
|
|
||||||
@@ -62,13 +64,24 @@ public class ClientNonPersonData implements Serializable {
|
|||||||
this.constitution = null;
|
this.constitution = null;
|
||||||
this.mainBusinessLine = null;
|
this.mainBusinessLine = null;
|
||||||
this.authorizedSignatory = null;
|
this.authorizedSignatory = null;
|
||||||
|
this.authorizedSignatoryClientIds = null;
|
||||||
this.additionalInfo = null;
|
this.additionalInfo = null;
|
||||||
this.dateOfRegistration = null;
|
this.dateOfRegistration = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kept for the list/search mappers, whose SQL does not select the signatory client ids.
|
||||||
|
*/
|
||||||
public ClientNonPersonData(CodeValueData constitution, String incorpNo, LocalDate incorpValidityTillDate,
|
public ClientNonPersonData(CodeValueData constitution, String incorpNo, LocalDate incorpValidityTillDate,
|
||||||
CodeValueData mainBusinessLine, String remarks, String authorizedSignatory, String additionalInfo,
|
CodeValueData mainBusinessLine, String remarks, String authorizedSignatory, String additionalInfo,
|
||||||
LocalDate dateOfRegistration) {
|
LocalDate dateOfRegistration) {
|
||||||
|
this(constitution, incorpNo, incorpValidityTillDate, mainBusinessLine, remarks, authorizedSignatory, additionalInfo,
|
||||||
|
dateOfRegistration, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClientNonPersonData(CodeValueData constitution, String incorpNo, LocalDate incorpValidityTillDate,
|
||||||
|
CodeValueData mainBusinessLine, String remarks, String authorizedSignatory, String additionalInfo,
|
||||||
|
LocalDate dateOfRegistration, String authorizedSignatoryClientIds) {
|
||||||
|
|
||||||
this.constitution = constitution;
|
this.constitution = constitution;
|
||||||
this.incorpNumber = incorpNo;
|
this.incorpNumber = incorpNo;
|
||||||
@@ -76,6 +89,7 @@ public class ClientNonPersonData implements Serializable {
|
|||||||
this.mainBusinessLine = mainBusinessLine;
|
this.mainBusinessLine = mainBusinessLine;
|
||||||
this.remarks = remarks;
|
this.remarks = remarks;
|
||||||
this.authorizedSignatory = authorizedSignatory;
|
this.authorizedSignatory = authorizedSignatory;
|
||||||
|
this.authorizedSignatoryClientIds = authorizedSignatoryClientIds;
|
||||||
this.additionalInfo = additionalInfo;
|
this.additionalInfo = additionalInfo;
|
||||||
this.dateOfRegistration = dateOfRegistration;
|
this.dateOfRegistration = dateOfRegistration;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import jakarta.persistence.JoinTable;
|
|||||||
import jakarta.persistence.ManyToMany;
|
import jakarta.persistence.ManyToMany;
|
||||||
import jakarta.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
import jakarta.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
|
import jakarta.persistence.OneToOne;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import jakarta.persistence.UniqueConstraint;
|
import jakarta.persistence.UniqueConstraint;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -249,6 +250,9 @@ public class Client extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@Column(name = "is_pwd")
|
@Column(name = "is_pwd")
|
||||||
private Boolean isPwd;
|
private Boolean isPwd;
|
||||||
|
|
||||||
|
@OneToOne(mappedBy = "client", fetch = FetchType.LAZY)
|
||||||
|
private ClientKyc clientKyc;
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY)
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
@JoinColumn(name = "pwd_category_cv_id")
|
@JoinColumn(name = "pwd_category_cv_id")
|
||||||
private CodeValue pwdCategory;
|
private CodeValue pwdCategory;
|
||||||
@@ -290,6 +294,17 @@ public class Client extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@Column(name = "alternate_dip_timestamp")
|
@Column(name = "alternate_dip_timestamp")
|
||||||
private String alternateDipTimestamp;
|
private String alternateDipTimestamp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The DIP/MNRL status the number actually returned — CLEAN, SUSPECTED, DISCONNECTED or
|
||||||
|
* SERVICE_UNAVAILABLE. dipVerified alone cannot tell "checked and clean" apart from "the DoT
|
||||||
|
* service was down", which previously stored both as verified.
|
||||||
|
*/
|
||||||
|
@Column(name = "dip_status", length = 40)
|
||||||
|
private String dipStatus;
|
||||||
|
|
||||||
|
@Column(name = "alternate_dip_status", length = 40)
|
||||||
|
private String alternateDipStatus;
|
||||||
|
|
||||||
@Column(name = "name_verified")
|
@Column(name = "name_verified")
|
||||||
private Boolean nameVerified;
|
private Boolean nameVerified;
|
||||||
|
|
||||||
|
|||||||
+247
@@ -25,10 +25,15 @@ import jakarta.persistence.Entity;
|
|||||||
import jakarta.persistence.JoinColumn;
|
import jakarta.persistence.JoinColumn;
|
||||||
import jakarta.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.persistence.Transient;
|
||||||
import jakarta.persistence.UniqueConstraint;
|
import jakarta.persistence.UniqueConstraint;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.fineract.infrastructure.core.api.JsonCommand;
|
import org.apache.fineract.infrastructure.core.api.JsonCommand;
|
||||||
import org.apache.fineract.infrastructure.core.domain.AbstractAuditableWithUTCDateTimeCustom;
|
import org.apache.fineract.infrastructure.core.domain.AbstractAuditableWithUTCDateTimeCustom;
|
||||||
@@ -60,6 +65,14 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@JoinColumn(name = "client_id", nullable = false)
|
@JoinColumn(name = "client_id", nullable = false)
|
||||||
private Client client;
|
private Client client;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scratch record of what the in-flight {@link #update} replaced, read back via
|
||||||
|
* {@link #getFieldsOverwrittenByLastUpdate()}. Never persisted and never read outside the
|
||||||
|
* transaction that called update(), which clears it first.
|
||||||
|
*/
|
||||||
|
@Transient
|
||||||
|
private final transient Set<String> fieldsOverwrittenByLastUpdate = new LinkedHashSet<>();
|
||||||
|
|
||||||
/** 100 = PENDING, 200 = IN_PROGRESS, 300 = VERIFIED, 400 = REJECTED, 500 = EXPIRED */
|
/** 100 = PENDING, 200 = IN_PROGRESS, 300 = VERIFIED, 400 = REJECTED, 500 = EXPIRED */
|
||||||
@Column(name = "kyc_status", nullable = false)
|
@Column(name = "kyc_status", nullable = false)
|
||||||
private Integer kycStatus;
|
private Integer kycStatus;
|
||||||
@@ -103,6 +116,36 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@Column(name = "pan_status", length = 20)
|
@Column(name = "pan_status", length = 20)
|
||||||
private String panStatus;
|
private String panStatus;
|
||||||
|
|
||||||
|
// ── PAN declaration ──────────────────────────────────────────────────────
|
||||||
|
// Accepted in place of a passing PAN check. The Income Tax check matches on name AND date of
|
||||||
|
// birth, so a customer whose PAN card carries a different spelling — or a different DOB — can
|
||||||
|
// never clear it however many times the officer retries. Rather than leave such a client
|
||||||
|
// permanently in KYC exception, the branch takes a signed declaration recording what differs.
|
||||||
|
// Holding that declaration is what suppresses the exception, so it is stored, not just shown.
|
||||||
|
|
||||||
|
/** True once a signed declaration has been accepted for a PAN that could not be verified. */
|
||||||
|
@Column(name = "pan_declaration_taken")
|
||||||
|
private Boolean panDeclarationTaken;
|
||||||
|
|
||||||
|
/** What the declaration covers: "NAME", "DOB", "NAME,DOB", or "NONE" when PAN simply failed. */
|
||||||
|
@Column(name = "pan_declaration_mismatch_fields", length = 100)
|
||||||
|
private String panDeclarationMismatchFields;
|
||||||
|
|
||||||
|
/** Name exactly as printed on the physical PAN card, keyed in by the officer. */
|
||||||
|
@Column(name = "pan_declaration_name_on_pan", length = 200)
|
||||||
|
private String panDeclarationNameOnPan;
|
||||||
|
|
||||||
|
/** Date of birth exactly as printed on the physical PAN card. */
|
||||||
|
@Column(name = "pan_declaration_dob_on_pan")
|
||||||
|
private LocalDate panDeclarationDobOnPan;
|
||||||
|
|
||||||
|
/** Officer's free-text note — why the mismatch exists and what proof was sighted. */
|
||||||
|
@Column(name = "pan_declaration_remarks", length = 500)
|
||||||
|
private String panDeclarationRemarks;
|
||||||
|
|
||||||
|
@Column(name = "pan_declaration_taken_on")
|
||||||
|
private LocalDate panDeclarationTakenOn;
|
||||||
|
|
||||||
// ── Aadhaar ──────────────────────────────────────────────────────────────
|
// ── Aadhaar ──────────────────────────────────────────────────────────────
|
||||||
/** Stored masked (last 4 digits visible). Full number must never be persisted as per UIDAI directive. */
|
/** Stored masked (last 4 digits visible). Full number must never be persisted as per UIDAI directive. */
|
||||||
@Column(name = "aadhaar_number_masked", length = 12)
|
@Column(name = "aadhaar_number_masked", length = 12)
|
||||||
@@ -114,6 +157,31 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@Column(name = "aadhaar_verified_on")
|
@Column(name = "aadhaar_verified_on")
|
||||||
private LocalDate aadhaarVerifiedOn;
|
private LocalDate aadhaarVerifiedOn;
|
||||||
|
|
||||||
|
// ── Aadhaar enrolment receipt ────────────────────────────────────────────
|
||||||
|
// The counterpart of the PAN declaration, for a customer who has applied for Aadhaar but does
|
||||||
|
// not hold one yet. UIDAI issues an enrolment slip carrying a 28-digit EID, and until Aadhaar
|
||||||
|
// itself is issued there is no number to put through the OTP flow — the check cannot pass
|
||||||
|
// however long the branch waits. Recording the receipt is what waives the exception.
|
||||||
|
|
||||||
|
/** True once the customer's Aadhaar enrolment slip has been sighted and recorded. */
|
||||||
|
@Column(name = "aadhaar_receipt_taken")
|
||||||
|
private Boolean aadhaarReceiptTaken;
|
||||||
|
|
||||||
|
/** 28-digit Enrolment ID from the slip, stored with its printed separators. */
|
||||||
|
@Column(name = "aadhaar_enrolment_id", length = 40)
|
||||||
|
private String aadhaarEnrolmentId;
|
||||||
|
|
||||||
|
/** Enrolment date printed on the slip — a receipt is temporary, so its age matters. */
|
||||||
|
@Column(name = "aadhaar_enrolment_date")
|
||||||
|
private LocalDate aadhaarEnrolmentDate;
|
||||||
|
|
||||||
|
/** Officer's note on what was sighted. */
|
||||||
|
@Column(name = "aadhaar_receipt_remarks", length = 500)
|
||||||
|
private String aadhaarReceiptRemarks;
|
||||||
|
|
||||||
|
@Column(name = "aadhaar_receipt_taken_on")
|
||||||
|
private LocalDate aadhaarReceiptTakenOn;
|
||||||
|
|
||||||
// ── GSTIN (mandatory for NON_INDIVIDUAL clients) ─────────────────────────
|
// ── GSTIN (mandatory for NON_INDIVIDUAL clients) ─────────────────────────
|
||||||
@Column(name = "gstin_number", length = 15)
|
@Column(name = "gstin_number", length = 15)
|
||||||
private String gstinNumber;
|
private String gstinNumber;
|
||||||
@@ -195,6 +263,18 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
@Column(name = "freeze_authority", length = 100)
|
@Column(name = "freeze_authority", length = 100)
|
||||||
private String freezeAuthority;
|
private String freezeAuthority;
|
||||||
|
|
||||||
|
@Column(name = "freeze_date")
|
||||||
|
private LocalDate freezeDate;
|
||||||
|
|
||||||
|
@Column(name = "freeze_amount", precision = 19, scale = 6)
|
||||||
|
private BigDecimal freezeAmount;
|
||||||
|
|
||||||
|
@Column(name = "unfreeze_date")
|
||||||
|
private LocalDate unfreezeDate;
|
||||||
|
|
||||||
|
@Column(name = "no_debit_date")
|
||||||
|
private LocalDate noDebitDate;
|
||||||
|
|
||||||
// ── Form 60 / Form 15G/15H ───────────────────────────────────────────────
|
// ── Form 60 / Form 15G/15H ───────────────────────────────────────────────
|
||||||
@Column(name = "form60_type", length = 20)
|
@Column(name = "form60_type", length = 20)
|
||||||
private String form60Type;
|
private String form60Type;
|
||||||
@@ -302,6 +382,24 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
private void applyExtendedFields(final JsonCommand command) {
|
private void applyExtendedFields(final JsonCommand command) {
|
||||||
this.panAadhaarSeedingStatus = StringUtils.defaultIfEmpty(
|
this.panAadhaarSeedingStatus = StringUtils.defaultIfEmpty(
|
||||||
command.stringValueOfParameterNamed("panAadhaarSeedingStatus"), this.panAadhaarSeedingStatus);
|
command.stringValueOfParameterNamed("panAadhaarSeedingStatus"), this.panAadhaarSeedingStatus);
|
||||||
|
final Boolean panDeclarationTakenVal = command.booleanObjectValueOfParameterNamed("panDeclarationTaken");
|
||||||
|
this.panDeclarationTaken = panDeclarationTakenVal != null ? panDeclarationTakenVal : false;
|
||||||
|
this.panDeclarationMismatchFields = StringUtils.defaultIfEmpty(
|
||||||
|
command.stringValueOfParameterNamed("panDeclarationMismatchFields"), null);
|
||||||
|
this.panDeclarationNameOnPan = StringUtils.defaultIfEmpty(
|
||||||
|
command.stringValueOfParameterNamed("panDeclarationNameOnPan"), null);
|
||||||
|
this.panDeclarationDobOnPan = command.localDateValueOfParameterNamed("panDeclarationDobOnPan");
|
||||||
|
this.panDeclarationRemarks = StringUtils.defaultIfEmpty(
|
||||||
|
command.stringValueOfParameterNamed("panDeclarationRemarks"), null);
|
||||||
|
this.panDeclarationTakenOn = command.localDateValueOfParameterNamed("panDeclarationTakenOn");
|
||||||
|
final Boolean aadhaarReceiptTakenVal = command.booleanObjectValueOfParameterNamed("aadhaarReceiptTaken");
|
||||||
|
this.aadhaarReceiptTaken = aadhaarReceiptTakenVal != null ? aadhaarReceiptTakenVal : false;
|
||||||
|
this.aadhaarEnrolmentId = StringUtils.defaultIfEmpty(
|
||||||
|
command.stringValueOfParameterNamed("aadhaarEnrolmentId"), null);
|
||||||
|
this.aadhaarEnrolmentDate = command.localDateValueOfParameterNamed("aadhaarEnrolmentDate");
|
||||||
|
this.aadhaarReceiptRemarks = StringUtils.defaultIfEmpty(
|
||||||
|
command.stringValueOfParameterNamed("aadhaarReceiptRemarks"), null);
|
||||||
|
this.aadhaarReceiptTakenOn = command.localDateValueOfParameterNamed("aadhaarReceiptTakenOn");
|
||||||
this.enterprisePan = StringUtils.defaultIfEmpty(
|
this.enterprisePan = StringUtils.defaultIfEmpty(
|
||||||
command.stringValueOfParameterNamed("enterprisePan"), null);
|
command.stringValueOfParameterNamed("enterprisePan"), null);
|
||||||
this.cinNumber = StringUtils.defaultIfEmpty(
|
this.cinNumber = StringUtils.defaultIfEmpty(
|
||||||
@@ -331,6 +429,10 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
command.stringValueOfParameterNamed("freezeReason"), null);
|
command.stringValueOfParameterNamed("freezeReason"), null);
|
||||||
this.freezeAuthority = StringUtils.defaultIfEmpty(
|
this.freezeAuthority = StringUtils.defaultIfEmpty(
|
||||||
command.stringValueOfParameterNamed("freezeAuthority"), null);
|
command.stringValueOfParameterNamed("freezeAuthority"), null);
|
||||||
|
this.freezeDate = command.localDateValueOfParameterNamed("freezeDate");
|
||||||
|
this.freezeAmount = command.bigDecimalValueOfParameterNamed("freezeAmount");
|
||||||
|
this.unfreezeDate = command.localDateValueOfParameterNamed("unfreezeDate");
|
||||||
|
this.noDebitDate = command.localDateValueOfParameterNamed("noDebitDate");
|
||||||
this.form60Type = StringUtils.defaultIfEmpty(
|
this.form60Type = StringUtils.defaultIfEmpty(
|
||||||
command.stringValueOfParameterNamed("form60Type"), null);
|
command.stringValueOfParameterNamed("form60Type"), null);
|
||||||
this.form60Date = command.localDateValueOfParameterNamed("form60Date");
|
this.form60Date = command.localDateValueOfParameterNamed("form60Date");
|
||||||
@@ -350,11 +452,13 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
|
|
||||||
public Map<String, Object> update(final JsonCommand command) {
|
public Map<String, Object> update(final JsonCommand command) {
|
||||||
final Map<String, Object> actualChanges = new LinkedHashMap<>();
|
final Map<String, Object> actualChanges = new LinkedHashMap<>();
|
||||||
|
this.fieldsOverwrittenByLastUpdate.clear();
|
||||||
|
|
||||||
final String panNumberParam = "panNumber";
|
final String panNumberParam = "panNumber";
|
||||||
if (command.isChangeInStringParameterNamed(panNumberParam, this.panNumber)) {
|
if (command.isChangeInStringParameterNamed(panNumberParam, this.panNumber)) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(panNumberParam);
|
final String newValue = command.stringValueOfParameterNamed(panNumberParam);
|
||||||
actualChanges.put(panNumberParam, newValue);
|
actualChanges.put(panNumberParam, newValue);
|
||||||
|
recordOverwrite(panNumberParam, this.panNumber);
|
||||||
this.panNumber = StringUtils.defaultIfEmpty(newValue, null);
|
this.panNumber = StringUtils.defaultIfEmpty(newValue, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,6 +466,7 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
if (command.isChangeInStringParameterNamed(aadhaarParam, this.aadhaarNumberMasked)) {
|
if (command.isChangeInStringParameterNamed(aadhaarParam, this.aadhaarNumberMasked)) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(aadhaarParam);
|
final String newValue = command.stringValueOfParameterNamed(aadhaarParam);
|
||||||
actualChanges.put(aadhaarParam, newValue);
|
actualChanges.put(aadhaarParam, newValue);
|
||||||
|
recordOverwrite(aadhaarParam, this.aadhaarNumberMasked);
|
||||||
this.aadhaarNumberMasked = StringUtils.defaultIfEmpty(newValue, null);
|
this.aadhaarNumberMasked = StringUtils.defaultIfEmpty(newValue, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,6 +474,7 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
if (command.isChangeInStringParameterNamed(gstinParam, this.gstinNumber)) {
|
if (command.isChangeInStringParameterNamed(gstinParam, this.gstinNumber)) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(gstinParam);
|
final String newValue = command.stringValueOfParameterNamed(gstinParam);
|
||||||
actualChanges.put(gstinParam, newValue);
|
actualChanges.put(gstinParam, newValue);
|
||||||
|
recordOverwrite(gstinParam, this.gstinNumber);
|
||||||
this.gstinNumber = StringUtils.defaultIfEmpty(newValue, null);
|
this.gstinNumber = StringUtils.defaultIfEmpty(newValue, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,9 +482,12 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
if (command.isChangeInIntegerParameterNamed(riskParam, this.riskCategory)) {
|
if (command.isChangeInIntegerParameterNamed(riskParam, this.riskCategory)) {
|
||||||
final Integer newValue = command.integerValueOfParameterNamed(riskParam);
|
final Integer newValue = command.integerValueOfParameterNamed(riskParam);
|
||||||
actualChanges.put(riskParam, newValue);
|
actualChanges.put(riskParam, newValue);
|
||||||
|
recordOverwrite(riskParam, this.riskCategory);
|
||||||
this.riskCategory = newValue;
|
this.riskCategory = newValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// remarks is the audit justification itself, so a change to it is deliberately not recorded
|
||||||
|
// as an overwrite — requiring remarks in order to write remarks would be circular.
|
||||||
final String remarksParam = "remarks";
|
final String remarksParam = "remarks";
|
||||||
if (command.isChangeInStringParameterNamed(remarksParam, this.remarks)) {
|
if (command.isChangeInStringParameterNamed(remarksParam, this.remarks)) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(remarksParam);
|
final String newValue = command.stringValueOfParameterNamed(remarksParam);
|
||||||
@@ -388,6 +497,28 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
|
|
||||||
updateStringField(command, "panAadhaarSeedingStatus", this.panAadhaarSeedingStatus, actualChanges,
|
updateStringField(command, "panAadhaarSeedingStatus", this.panAadhaarSeedingStatus, actualChanges,
|
||||||
v -> this.panAadhaarSeedingStatus = v);
|
v -> this.panAadhaarSeedingStatus = v);
|
||||||
|
updateBooleanField(command, "panDeclarationTaken", this.panDeclarationTaken, actualChanges,
|
||||||
|
v -> this.panDeclarationTaken = v != null ? v : false);
|
||||||
|
updateStringField(command, "panDeclarationMismatchFields", this.panDeclarationMismatchFields, actualChanges,
|
||||||
|
v -> this.panDeclarationMismatchFields = v);
|
||||||
|
updateStringField(command, "panDeclarationNameOnPan", this.panDeclarationNameOnPan, actualChanges,
|
||||||
|
v -> this.panDeclarationNameOnPan = v);
|
||||||
|
updateDateField(command, "panDeclarationDobOnPan", this.panDeclarationDobOnPan, actualChanges,
|
||||||
|
v -> this.panDeclarationDobOnPan = v);
|
||||||
|
updateStringField(command, "panDeclarationRemarks", this.panDeclarationRemarks, actualChanges,
|
||||||
|
v -> this.panDeclarationRemarks = v);
|
||||||
|
updateDateField(command, "panDeclarationTakenOn", this.panDeclarationTakenOn, actualChanges,
|
||||||
|
v -> this.panDeclarationTakenOn = v);
|
||||||
|
updateBooleanField(command, "aadhaarReceiptTaken", this.aadhaarReceiptTaken, actualChanges,
|
||||||
|
v -> this.aadhaarReceiptTaken = v != null ? v : false);
|
||||||
|
updateStringField(command, "aadhaarEnrolmentId", this.aadhaarEnrolmentId, actualChanges,
|
||||||
|
v -> this.aadhaarEnrolmentId = v);
|
||||||
|
updateDateField(command, "aadhaarEnrolmentDate", this.aadhaarEnrolmentDate, actualChanges,
|
||||||
|
v -> this.aadhaarEnrolmentDate = v);
|
||||||
|
updateStringField(command, "aadhaarReceiptRemarks", this.aadhaarReceiptRemarks, actualChanges,
|
||||||
|
v -> this.aadhaarReceiptRemarks = v);
|
||||||
|
updateDateField(command, "aadhaarReceiptTakenOn", this.aadhaarReceiptTakenOn, actualChanges,
|
||||||
|
v -> this.aadhaarReceiptTakenOn = v);
|
||||||
updateStringField(command, "enterprisePan", this.enterprisePan, actualChanges, v -> this.enterprisePan = v);
|
updateStringField(command, "enterprisePan", this.enterprisePan, actualChanges, v -> this.enterprisePan = v);
|
||||||
updateStringField(command, "cinNumber", this.cinNumber, actualChanges, v -> this.cinNumber = v);
|
updateStringField(command, "cinNumber", this.cinNumber, actualChanges, v -> this.cinNumber = v);
|
||||||
updateStringField(command, "dinNumber", this.dinNumber, actualChanges, v -> this.dinNumber = v);
|
updateStringField(command, "dinNumber", this.dinNumber, actualChanges, v -> this.dinNumber = v);
|
||||||
@@ -413,6 +544,10 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
updateStringField(command, "freezeReason", this.freezeReason, actualChanges, v -> this.freezeReason = v);
|
updateStringField(command, "freezeReason", this.freezeReason, actualChanges, v -> this.freezeReason = v);
|
||||||
updateStringField(command, "freezeAuthority", this.freezeAuthority, actualChanges,
|
updateStringField(command, "freezeAuthority", this.freezeAuthority, actualChanges,
|
||||||
v -> this.freezeAuthority = v);
|
v -> this.freezeAuthority = v);
|
||||||
|
updateDateField(command, "freezeDate", this.freezeDate, actualChanges, v -> this.freezeDate = v);
|
||||||
|
updateBigDecimalField(command, "freezeAmount", this.freezeAmount, actualChanges, v -> this.freezeAmount = v);
|
||||||
|
updateDateField(command, "unfreezeDate", this.unfreezeDate, actualChanges, v -> this.unfreezeDate = v);
|
||||||
|
updateDateField(command, "noDebitDate", this.noDebitDate, actualChanges, v -> this.noDebitDate = v);
|
||||||
updateStringField(command, "form60Type", this.form60Type, actualChanges, v -> this.form60Type = v);
|
updateStringField(command, "form60Type", this.form60Type, actualChanges, v -> this.form60Type = v);
|
||||||
updateDateField(command, "form60Date", this.form60Date, actualChanges, v -> this.form60Date = v);
|
updateDateField(command, "form60Date", this.form60Date, actualChanges, v -> this.form60Date = v);
|
||||||
updateBooleanField(command, "form15Applicable", this.form15Applicable, actualChanges,
|
updateBooleanField(command, "form15Applicable", this.form15Applicable, actualChanges,
|
||||||
@@ -435,6 +570,7 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
if (command.isChangeInStringParameterNamed(param, current)) {
|
if (command.isChangeInStringParameterNamed(param, current)) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(param);
|
final String newValue = command.stringValueOfParameterNamed(param);
|
||||||
changes.put(param, newValue);
|
changes.put(param, newValue);
|
||||||
|
recordOverwrite(param, current);
|
||||||
setter.accept(StringUtils.defaultIfEmpty(newValue, null));
|
setter.accept(StringUtils.defaultIfEmpty(newValue, null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -444,6 +580,7 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
if (command.isChangeInLocalDateParameterNamed(param, current)) {
|
if (command.isChangeInLocalDateParameterNamed(param, current)) {
|
||||||
final LocalDate newValue = command.localDateValueOfParameterNamed(param);
|
final LocalDate newValue = command.localDateValueOfParameterNamed(param);
|
||||||
changes.put(param, newValue);
|
changes.put(param, newValue);
|
||||||
|
recordOverwrite(param, current);
|
||||||
setter.accept(newValue);
|
setter.accept(newValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -454,11 +591,51 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
final Boolean newValue = command.booleanObjectValueOfParameterNamed(param);
|
final Boolean newValue = command.booleanObjectValueOfParameterNamed(param);
|
||||||
if ((newValue == null && current != null) || (newValue != null && !newValue.equals(current))) {
|
if ((newValue == null && current != null) || (newValue != null && !newValue.equals(current))) {
|
||||||
changes.put(param, newValue);
|
changes.put(param, newValue);
|
||||||
|
recordOverwrite(param, current);
|
||||||
setter.accept(newValue);
|
setter.accept(newValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void updateBigDecimalField(final JsonCommand command, final String param, final BigDecimal current,
|
||||||
|
final Map<String, Object> changes, final java.util.function.Consumer<BigDecimal> setter) {
|
||||||
|
if (command.isChangeInBigDecimalParameterNamed(param, current)) {
|
||||||
|
final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(param);
|
||||||
|
changes.put(param, newValue);
|
||||||
|
recordOverwrite(param, current);
|
||||||
|
setter.accept(newValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notes that {@code param} replaced a value the record already held. A field going from empty to
|
||||||
|
* populated is the record being completed rather than altered, so it is deliberately not
|
||||||
|
* recorded — see {@link #getFieldsOverwrittenByLastUpdate()}.
|
||||||
|
*/
|
||||||
|
private void recordOverwrite(final String param, final Object currentValue) {
|
||||||
|
final boolean wasPopulated = currentValue instanceof String text
|
||||||
|
? StringUtils.isNotBlank(text)
|
||||||
|
: currentValue != null;
|
||||||
|
if (wasPopulated) {
|
||||||
|
this.fieldsOverwrittenByLastUpdate.add(param);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parameters whose already-populated value the most recent {@link #update} replaced.
|
||||||
|
*
|
||||||
|
* <p>Distinguishes altering a record from finishing one: a non-individual KYC auto-verifies as
|
||||||
|
* soon as PAN and GSTIN pass, which happens part-way through the create wizard, and the officer
|
||||||
|
* still has to save the KYC document details afterwards. Those fields are empty at that point,
|
||||||
|
* so filling them in leaves this set empty and no audit justification is demanded — while
|
||||||
|
* changing a document number that was already on the verified record does populate it.
|
||||||
|
*
|
||||||
|
* <p>Reset at the start of every {@link #update} and never persisted: it describes one call.
|
||||||
|
*/
|
||||||
|
public Set<String> getFieldsOverwrittenByLastUpdate() {
|
||||||
|
return Collections.unmodifiableSet(this.fieldsOverwrittenByLastUpdate);
|
||||||
|
}
|
||||||
|
|
||||||
/** Called when documents are submitted and 3rd-party verification is initiated. */
|
/** Called when documents are submitted and 3rd-party verification is initiated. */
|
||||||
public void markInProgress() {
|
public void markInProgress() {
|
||||||
this.kycStatus = ClientKycStatus.IN_PROGRESS.getValue();
|
this.kycStatus = ClientKycStatus.IN_PROGRESS.getValue();
|
||||||
@@ -659,6 +836,60 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
return panStatus;
|
return panStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Boolean getPanDeclarationTaken() {
|
||||||
|
return panDeclarationTaken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null-safe form for callers deciding whether the PAN exception is waived. */
|
||||||
|
public boolean isPanDeclarationTaken() {
|
||||||
|
return Boolean.TRUE.equals(this.panDeclarationTaken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPanDeclarationMismatchFields() {
|
||||||
|
return panDeclarationMismatchFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPanDeclarationNameOnPan() {
|
||||||
|
return panDeclarationNameOnPan;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getPanDeclarationDobOnPan() {
|
||||||
|
return panDeclarationDobOnPan;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPanDeclarationRemarks() {
|
||||||
|
return panDeclarationRemarks;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getPanDeclarationTakenOn() {
|
||||||
|
return panDeclarationTakenOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean getAadhaarReceiptTaken() {
|
||||||
|
return aadhaarReceiptTaken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null-safe form for callers deciding whether the Aadhaar exception is waived. */
|
||||||
|
public boolean isAadhaarReceiptTaken() {
|
||||||
|
return Boolean.TRUE.equals(this.aadhaarReceiptTaken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAadhaarEnrolmentId() {
|
||||||
|
return aadhaarEnrolmentId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getAadhaarEnrolmentDate() {
|
||||||
|
return aadhaarEnrolmentDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAadhaarReceiptRemarks() {
|
||||||
|
return aadhaarReceiptRemarks;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getAadhaarReceiptTakenOn() {
|
||||||
|
return aadhaarReceiptTakenOn;
|
||||||
|
}
|
||||||
|
|
||||||
public String getAadhaarNumberMasked() {
|
public String getAadhaarNumberMasked() {
|
||||||
return aadhaarNumberMasked;
|
return aadhaarNumberMasked;
|
||||||
}
|
}
|
||||||
@@ -906,4 +1137,20 @@ public class ClientKyc extends AbstractAuditableWithUTCDateTimeCustom<Long> {
|
|||||||
public Long getVersion() {
|
public Long getVersion() {
|
||||||
return this.version;
|
return this.version;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public LocalDate getFreezeDate() {
|
||||||
|
return this.freezeDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal getFreezeAmount() {
|
||||||
|
return this.freezeAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getUnfreezeDate() {
|
||||||
|
return this.unfreezeDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getNoDebitDate() {
|
||||||
|
return this.noDebitDate;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-7
@@ -63,13 +63,6 @@ public interface ClientRepository extends JpaRepository<Client, Long>, JpaSpecif
|
|||||||
@Query("UPDATE Client client SET client.signatureId = null WHERE client.id = :clientId")
|
@Query("UPDATE Client client SET client.signatureId = null WHERE client.id = :clientId")
|
||||||
void removeSignatureId(@Param("clientId") Long clientId);
|
void removeSignatureId(@Param("clientId") Long clientId);
|
||||||
|
|
||||||
/**
|
|
||||||
* Count clients whose cif_number begins with the given prefix. Used by the CIF number generator
|
|
||||||
* (TTYYYYNNNNNN format) to compute the next sequence within a given (type, year) bucket.
|
|
||||||
*/
|
|
||||||
@Query("SELECT COUNT(c) FROM Client c WHERE c.cifNumber LIKE CONCAT(:prefix, '%')")
|
|
||||||
long countByCifNumberPrefix(@Param("prefix") String prefix);
|
|
||||||
|
|
||||||
// ── Pre-save uniqueness probes ───────────────────────────────────────────
|
// ── Pre-save uniqueness probes ───────────────────────────────────────────
|
||||||
// Why: DB has UNIQUE on mobile_no / email_address, but we want to fail fast with a clear
|
// Why: DB has UNIQUE on mobile_no / email_address, but we want to fail fast with a clear
|
||||||
// field-level error BEFORE saveAndFlush — and importantly before the external KYC API call.
|
// field-level error BEFORE saveAndFlush — and importantly before the external KYC API call.
|
||||||
|
|||||||
+38
@@ -95,6 +95,44 @@ public class ClientRiskRule {
|
|||||||
|
|
||||||
protected ClientRiskRule() {}
|
protected ClientRiskRule() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a rule authored from the AML Rules Master screen. Occupation and occupation-category
|
||||||
|
* are attached separately by the caller, which owns the CodeValue lookup.
|
||||||
|
*/
|
||||||
|
public static ClientRiskRule create(final String ruleName, final String reason, final Integer riskCategory,
|
||||||
|
final Integer orderPosition, final Integer legalFormId, final BigDecimal minMonthlyIncome,
|
||||||
|
final BigDecimal maxMonthlyIncome, final BigDecimal minAnnualIncome, final BigDecimal maxAnnualIncome,
|
||||||
|
final BigDecimal minAnnualTurnover, final BigDecimal maxAnnualTurnover, final String amlCheckStatus,
|
||||||
|
final String bannedEntityMatch, final String willfulDefaulter, final String ecgcSalFlag,
|
||||||
|
final String dormantFlag) {
|
||||||
|
final ClientRiskRule rule = new ClientRiskRule();
|
||||||
|
rule.ruleName = ruleName;
|
||||||
|
rule.reason = reason;
|
||||||
|
rule.riskCategory = riskCategory;
|
||||||
|
rule.orderPosition = orderPosition;
|
||||||
|
rule.legalFormId = legalFormId;
|
||||||
|
rule.minMonthlyIncome = minMonthlyIncome;
|
||||||
|
rule.maxMonthlyIncome = maxMonthlyIncome;
|
||||||
|
rule.minAnnualIncome = minAnnualIncome;
|
||||||
|
rule.maxAnnualIncome = maxAnnualIncome;
|
||||||
|
rule.minAnnualTurnover = minAnnualTurnover;
|
||||||
|
rule.maxAnnualTurnover = maxAnnualTurnover;
|
||||||
|
rule.amlCheckStatus = amlCheckStatus;
|
||||||
|
rule.bannedEntityMatch = bannedEntityMatch;
|
||||||
|
rule.willfulDefaulter = willfulDefaulter;
|
||||||
|
rule.ecgcSalFlag = ecgcSalFlag;
|
||||||
|
rule.dormantFlag = dormantFlag;
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOccupationCategory(final CodeValue occupationCategory) {
|
||||||
|
this.occupationCategory = occupationCategory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOccupation(final CodeValue occupation) {
|
||||||
|
this.occupation = occupation;
|
||||||
|
}
|
||||||
|
|
||||||
public Long getId() {
|
public Long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -26,4 +26,10 @@ public interface ClientRiskRuleRepository extends JpaRepository<ClientRiskRule,
|
|||||||
|
|
||||||
@Query("SELECT r FROM ClientRiskRule r ORDER BY r.orderPosition ASC")
|
@Query("SELECT r FROM ClientRiskRule r ORDER BY r.orderPosition ASC")
|
||||||
List<ClientRiskRule> findAllOrderedByOrderPosition();
|
List<ClientRiskRule> findAllOrderedByOrderPosition();
|
||||||
|
|
||||||
|
/** Highest position in use, so a new rule can be appended to the end of the catalog. */
|
||||||
|
@Query("SELECT MAX(r.orderPosition) FROM ClientRiskRule r")
|
||||||
|
Integer findMaxOrderPosition();
|
||||||
|
|
||||||
|
boolean existsByRuleNameIgnoreCase(String ruleName);
|
||||||
}
|
}
|
||||||
|
|||||||
+46
@@ -65,6 +65,29 @@ public class MobileLookupLog extends AbstractAuditableWithUTCDateTimeCustom<Long
|
|||||||
@Column(name = "looked_up_on", nullable = false)
|
@Column(name = "looked_up_on", nullable = false)
|
||||||
private OffsetDateTime lookedUpOn;
|
private OffsetDateTime lookedUpOn;
|
||||||
|
|
||||||
|
// ── Officer decision on a non-clean result ────────────────────────────────
|
||||||
|
// A DIP hit is a fraud-risk signal rather than a legal bar, so onboarding may continue — but
|
||||||
|
// the officer has to say why in writing, and that reasoning is kept with the lookup.
|
||||||
|
|
||||||
|
/** PROCEEDED | REJECTED. Null while no decision is required or none has been taken. */
|
||||||
|
@Column(name = "override_decision", length = 20)
|
||||||
|
private String overrideDecision;
|
||||||
|
|
||||||
|
@Column(name = "override_reason")
|
||||||
|
private String overrideReason;
|
||||||
|
|
||||||
|
@Column(name = "decided_by")
|
||||||
|
private Long decidedBy;
|
||||||
|
|
||||||
|
@Column(name = "decided_on")
|
||||||
|
private OffsetDateTime decidedOn;
|
||||||
|
|
||||||
|
public static final String STATUS_CLEAN = "CLEAN";
|
||||||
|
public static final String STATUS_ERROR = "ERROR";
|
||||||
|
public static final String STATUS_SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE";
|
||||||
|
public static final String DECISION_PROCEEDED = "PROCEEDED";
|
||||||
|
public static final String DECISION_REJECTED = "REJECTED";
|
||||||
|
|
||||||
protected MobileLookupLog() {}
|
protected MobileLookupLog() {}
|
||||||
|
|
||||||
public MobileLookupLog(final String mobileNumber, final String lookupStatus,
|
public MobileLookupLog(final String mobileNumber, final String lookupStatus,
|
||||||
@@ -81,4 +104,27 @@ public class MobileLookupLog extends AbstractAuditableWithUTCDateTimeCustom<Long
|
|||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
this.lookedUpOn = DateUtils.getOffsetDateTimeOfTenant();
|
this.lookedUpOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void recordDecision(final String decision, final String reason, final Long userId) {
|
||||||
|
this.overrideDecision = decision;
|
||||||
|
this.overrideReason = reason;
|
||||||
|
this.decidedBy = userId;
|
||||||
|
this.decidedOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the lookup produced something the officer must consciously decide about. */
|
||||||
|
public boolean requiresDecision() {
|
||||||
|
return this.suspected || this.disconnected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A number may be used only when it came back clean, or when an officer explicitly chose to
|
||||||
|
* proceed. An unreachable DoT service is NOT a pass — it means nothing was checked.
|
||||||
|
*/
|
||||||
|
public boolean isUsable() {
|
||||||
|
if (STATUS_CLEAN.equals(this.lookupStatus)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return DECISION_PROCEEDED.equals(this.overrideDecision);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
@@ -19,6 +19,8 @@
|
|||||||
package org.apache.fineract.portfolio.mobilelookup.domain;
|
package org.apache.fineract.portfolio.mobilelookup.domain;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
@@ -35,4 +37,29 @@ public interface MobileLookupLogRepository extends JpaRepository<MobileLookupLog
|
|||||||
|
|
||||||
@Query("SELECT l FROM MobileLookupLog l WHERE l.lookupStatus = :status ORDER BY l.lookedUpOn DESC")
|
@Query("SELECT l FROM MobileLookupLog l WHERE l.lookupStatus = :status ORDER BY l.lookedUpOn DESC")
|
||||||
List<MobileLookupLog> findByLookupStatus(@Param("status") String status);
|
List<MobileLookupLog> findByLookupStatus(@Param("status") String status);
|
||||||
|
|
||||||
|
/** Non-clean lookups still waiting for an officer's decision — the DIP review queue. */
|
||||||
|
@Query("SELECT l FROM MobileLookupLog l WHERE (l.suspected = true OR l.disconnected = true) "
|
||||||
|
+ "AND l.overrideDecision IS NULL ORDER BY l.lookedUpOn DESC")
|
||||||
|
List<MobileLookupLog> findPendingDecisions();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Most recent lookup for a number, used by the server-side gate to confirm the browser's
|
||||||
|
* claim that a number was verified.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Paged rather than a JPQL {@code LIMIT}, which EclipseLink does not accept — the caller
|
||||||
|
* takes the first row.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
@Query("SELECT l FROM MobileLookupLog l WHERE l.mobileNumber = :mobileNumber ORDER BY l.lookedUpOn DESC")
|
||||||
|
List<MobileLookupLog> findLatestByMobileNumber(@Param("mobileNumber") String mobileNumber, Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Earlier rejections of the same number, on any client. A number turned away once is a
|
||||||
|
* standing signal: without this the next officer screens it fresh and sees no history.
|
||||||
|
*/
|
||||||
|
@Query("SELECT l FROM MobileLookupLog l WHERE l.mobileNumber = :mobileNumber "
|
||||||
|
+ "AND l.overrideDecision = 'REJECTED' ORDER BY l.decidedOn DESC")
|
||||||
|
List<MobileLookupLog> findRejections(@Param("mobileNumber") String mobileNumber, Pageable pageable);
|
||||||
}
|
}
|
||||||
|
|||||||
+139
@@ -61,6 +61,65 @@ public class SanctionsScreeningLog extends AbstractAuditableWithUTCDateTimeCusto
|
|||||||
@Column(name = "screened_on", nullable = false)
|
@Column(name = "screened_on", nullable = false)
|
||||||
private OffsetDateTime screenedOn;
|
private OffsetDateTime screenedOn;
|
||||||
|
|
||||||
|
// ── Alert disposition ─────────────────────────────────────────────────────
|
||||||
|
// A FLAGGED screening opens a case. It stays PENDING_REVIEW until an officer either
|
||||||
|
// documents it as a different person (FALSE_POSITIVE, effective only once the Principal
|
||||||
|
// Officer approves) or confirms it (CONFIRMED_MATCH, which freezes and gets reported).
|
||||||
|
|
||||||
|
@Column(name = "disposition", length = 30)
|
||||||
|
private String disposition;
|
||||||
|
|
||||||
|
@Column(name = "disposition_reason")
|
||||||
|
private String dispositionReason;
|
||||||
|
|
||||||
|
@Column(name = "reviewed_by")
|
||||||
|
private Long reviewedBy;
|
||||||
|
|
||||||
|
@Column(name = "reviewed_on")
|
||||||
|
private OffsetDateTime reviewedOn;
|
||||||
|
|
||||||
|
@Column(name = "approved_by")
|
||||||
|
private Long approvedBy;
|
||||||
|
|
||||||
|
@Column(name = "approved_on")
|
||||||
|
private OffsetDateTime approvedOn;
|
||||||
|
|
||||||
|
@Column(name = "fiu_str_reference", length = 100)
|
||||||
|
private String fiuStrReference;
|
||||||
|
|
||||||
|
@Column(name = "nodal_officer_informed_on")
|
||||||
|
private OffsetDateTime nodalOfficerInformedOn;
|
||||||
|
|
||||||
|
@Column(name = "frozen_account_ids", length = 1000)
|
||||||
|
private String frozenAccountIds;
|
||||||
|
|
||||||
|
@Column(name = "frozen_on")
|
||||||
|
private OffsetDateTime frozenOn;
|
||||||
|
|
||||||
|
// ── STR tracking ──────────────────────────────────────────────────────────
|
||||||
|
// A confirmed match is reportable to FIU-IND. Tracked here rather than as an AML alert: an
|
||||||
|
// AML alert is built around a monetary transaction, whereas this is triggered by who the
|
||||||
|
// customer is, so the two are surfaced as separate streams on the FIU screen.
|
||||||
|
|
||||||
|
/** NULL until approval; then PENDING_FILING → FILED. */
|
||||||
|
@Column(name = "str_status", length = 30)
|
||||||
|
private String strStatus;
|
||||||
|
|
||||||
|
@Column(name = "str_due_date")
|
||||||
|
private java.time.LocalDate strDueDate;
|
||||||
|
|
||||||
|
@Column(name = "str_raised_on")
|
||||||
|
private OffsetDateTime strRaisedOn;
|
||||||
|
|
||||||
|
public static final String STR_PENDING_FILING = "PENDING_FILING";
|
||||||
|
public static final String STR_FILED = "FILED";
|
||||||
|
|
||||||
|
public static final String RESULT_FLAGGED = "FLAGGED";
|
||||||
|
public static final String RESULT_CLEAR = "CLEAR";
|
||||||
|
public static final String DISPOSITION_PENDING = "PENDING_REVIEW";
|
||||||
|
public static final String DISPOSITION_FALSE_POSITIVE = "FALSE_POSITIVE";
|
||||||
|
public static final String DISPOSITION_CONFIRMED = "CONFIRMED_MATCH";
|
||||||
|
|
||||||
protected SanctionsScreeningLog() {}
|
protected SanctionsScreeningLog() {}
|
||||||
|
|
||||||
public SanctionsScreeningLog(final String screenedName, final String screeningResult,
|
public SanctionsScreeningLog(final String screenedName, final String screeningResult,
|
||||||
@@ -75,8 +134,75 @@ public class SanctionsScreeningLog extends AbstractAuditableWithUTCDateTimeCusto
|
|||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
this.ipAddress = ipAddress;
|
this.ipAddress = ipAddress;
|
||||||
this.screenedOn = DateUtils.getOffsetDateTimeOfTenant();
|
this.screenedOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
// A hit opens a case; a clear screening has no case to close.
|
||||||
|
this.disposition = RESULT_FLAGGED.equals(screeningResult) ? DISPOSITION_PENDING : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Alert lifecycle ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the officer's assessment of the hit. Deliberately does NOT clear the block: a
|
||||||
|
* false positive only takes effect once {@link #approve(Long)} is called by the Principal
|
||||||
|
* Officer, so the person who raised it cannot wave their own match through.
|
||||||
|
*/
|
||||||
|
public void recordDisposition(final String newDisposition, final String reason, final Long userId) {
|
||||||
|
this.disposition = newDisposition;
|
||||||
|
this.dispositionReason = reason;
|
||||||
|
this.reviewedBy = userId;
|
||||||
|
this.reviewedOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
// Re-opening a previously approved alert must drop the old approval with it.
|
||||||
|
this.approvedBy = null;
|
||||||
|
this.approvedOn = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void approve(final Long approverId) {
|
||||||
|
this.approvedBy = approverId;
|
||||||
|
this.approvedOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records the FIU-IND STR reference and the date the nodal officer was informed. */
|
||||||
|
public void recordReporting(final String strReference, final OffsetDateTime nodalOfficerInformedOn) {
|
||||||
|
if (strReference != null) {
|
||||||
|
this.fiuStrReference = strReference;
|
||||||
|
// Recording the FIU-IND acknowledgement is what closes the filing obligation, so the
|
||||||
|
// case stops appearing as outstanding on the FIU screen.
|
||||||
|
if (!strReference.isBlank()) {
|
||||||
|
this.strStatus = STR_FILED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (nodalOfficerInformedOn != null) {
|
||||||
|
this.nodalOfficerInformedOn = nodalOfficerInformedOn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void recordFreeze(final String accountIds) {
|
||||||
|
this.frozenAccountIds = accountIds;
|
||||||
|
this.frozenOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the STR obligation on approval of a confirmed match. PMLA allows seven working days
|
||||||
|
* from forming the suspicion; seven calendar days is the stricter reading.
|
||||||
|
*/
|
||||||
|
public void raiseStr() {
|
||||||
|
if (this.strStatus != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.strStatus = STR_PENDING_FILING;
|
||||||
|
this.strRaisedOn = DateUtils.getOffsetDateTimeOfTenant();
|
||||||
|
this.strDueDate = DateUtils.getBusinessLocalDate().plusDays(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isStrPending() { return STR_PENDING_FILING.equals(this.strStatus); }
|
||||||
|
|
||||||
|
public boolean isFlagged() { return RESULT_FLAGGED.equals(this.screeningResult); }
|
||||||
|
|
||||||
|
public boolean isApprovedFalsePositive() {
|
||||||
|
return DISPOSITION_FALSE_POSITIVE.equals(this.disposition) && this.approvedBy != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isConfirmedMatch() { return DISPOSITION_CONFIRMED.equals(this.disposition); }
|
||||||
|
|
||||||
// ── Accessors ─────────────────────────────────────────────────────────────
|
// ── Accessors ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
public String getScreenedName() { return screenedName; }
|
public String getScreenedName() { return screenedName; }
|
||||||
@@ -89,4 +215,17 @@ public class SanctionsScreeningLog extends AbstractAuditableWithUTCDateTimeCusto
|
|||||||
public void setClientId(Long clientId) { this.clientId = clientId; }
|
public void setClientId(Long clientId) { this.clientId = clientId; }
|
||||||
public String getIpAddress() { return ipAddress; }
|
public String getIpAddress() { return ipAddress; }
|
||||||
public OffsetDateTime getScreenedOn() { return screenedOn; }
|
public OffsetDateTime getScreenedOn() { return screenedOn; }
|
||||||
|
public String getDisposition() { return disposition; }
|
||||||
|
public String getDispositionReason() { return dispositionReason; }
|
||||||
|
public Long getReviewedBy() { return reviewedBy; }
|
||||||
|
public OffsetDateTime getReviewedOn() { return reviewedOn; }
|
||||||
|
public Long getApprovedBy() { return approvedBy; }
|
||||||
|
public OffsetDateTime getApprovedOn() { return approvedOn; }
|
||||||
|
public String getFiuStrReference() { return fiuStrReference; }
|
||||||
|
public OffsetDateTime getNodalOfficerInformedOn() { return nodalOfficerInformedOn; }
|
||||||
|
public String getFrozenAccountIds() { return frozenAccountIds; }
|
||||||
|
public OffsetDateTime getFrozenOn() { return frozenOn; }
|
||||||
|
public String getStrStatus() { return strStatus; }
|
||||||
|
public java.time.LocalDate getStrDueDate() { return strDueDate; }
|
||||||
|
public OffsetDateTime getStrRaisedOn() { return strRaisedOn; }
|
||||||
}
|
}
|
||||||
|
|||||||
+28
@@ -39,4 +39,32 @@ public interface SanctionsScreeningLogRepository extends JpaRepository<Sanctions
|
|||||||
|
|
||||||
@Query("SELECT l FROM SanctionsScreeningLog l WHERE LOWER(l.screenedName) LIKE LOWER(CONCAT('%', :name, '%')) ORDER BY l.screenedOn DESC")
|
@Query("SELECT l FROM SanctionsScreeningLog l WHERE LOWER(l.screenedName) LIKE LOWER(CONCAT('%', :name, '%')) ORDER BY l.screenedOn DESC")
|
||||||
List<SanctionsScreeningLog> findByScreenedNameContaining(@Param("name") String name);
|
List<SanctionsScreeningLog> findByScreenedNameContaining(@Param("name") String name);
|
||||||
|
|
||||||
|
@Query("SELECT l FROM SanctionsScreeningLog l WHERE l.disposition = :disposition ORDER BY l.screenedOn DESC")
|
||||||
|
List<SanctionsScreeningLog> findByDisposition(@Param("disposition") String disposition);
|
||||||
|
|
||||||
|
/** Every open alert — the Principal Officer's review queue. */
|
||||||
|
@Query("SELECT l FROM SanctionsScreeningLog l WHERE l.disposition IS NOT NULL ORDER BY l.screenedOn DESC")
|
||||||
|
List<SanctionsScreeningLog> findAllAlerts();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A name is only cleared to onboard once a false positive on that exact name has been
|
||||||
|
* approved by the Principal Officer — the maker's own assessment is not enough.
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(l) FROM SanctionsScreeningLog l WHERE LOWER(TRIM(l.screenedName)) = LOWER(TRIM(:name)) "
|
||||||
|
+ "AND l.disposition = 'FALSE_POSITIVE' AND l.approvedBy IS NOT NULL")
|
||||||
|
long countApprovedFalsePositives(@Param("name") String name);
|
||||||
|
|
||||||
|
/** Latest alert for a client, used to decide whether their accounts must stay frozen. */
|
||||||
|
@Query("SELECT l FROM SanctionsScreeningLog l WHERE l.clientId = :clientId AND l.screeningResult = 'FLAGGED' "
|
||||||
|
+ "ORDER BY l.screenedOn DESC")
|
||||||
|
List<SanctionsScreeningLog> findFlaggedByClientId(@Param("clientId") Long clientId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirmed matches carrying an STR obligation — the sanctions stream on the FIU-IND screen.
|
||||||
|
* Pass null for every STR regardless of whether it has been filed.
|
||||||
|
*/
|
||||||
|
@Query("SELECT l FROM SanctionsScreeningLog l WHERE l.strStatus IS NOT NULL "
|
||||||
|
+ "AND (:status IS NULL OR l.strStatus = :status) ORDER BY l.strDueDate ASC, l.strRaisedOn DESC")
|
||||||
|
List<SanctionsScreeningLog> findStrCases(@Param("status") String status);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+10
-1
@@ -18,6 +18,7 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.infrastructure.contentstore.policy;
|
package org.apache.fineract.infrastructure.contentstore.policy;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.lang3.Strings;
|
import org.apache.commons.lang3.Strings;
|
||||||
@@ -31,6 +32,10 @@ import org.springframework.stereotype.Component;
|
|||||||
@Component
|
@Component
|
||||||
public class MimeContentPolicy implements ContentPolicy {
|
public class MimeContentPolicy implements ContentPolicy {
|
||||||
|
|
||||||
|
// CSV has no content-level magic bytes, so byte-sniffing a delimited text file legitimately
|
||||||
|
// detects it as text/plain even though it was uploaded (and named) as text/csv.
|
||||||
|
private static final Set<String> INTERCHANGEABLE_TEXT_MIME_TYPES = Set.of("text/csv", "text/plain");
|
||||||
|
|
||||||
private final ContentDetectorManager contentDetectorManager;
|
private final ContentDetectorManager contentDetectorManager;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -39,7 +44,11 @@ public class MimeContentPolicy implements ContentPolicy {
|
|||||||
var result = contentDetectorManager
|
var result = contentDetectorManager
|
||||||
.detect(ContentDetectorContext.builder().inputStream(ctx.getInputStream()).inputStreamEnabled(true).build());
|
.detect(ContentDetectorContext.builder().inputStream(ctx.getInputStream()).inputStreamEnabled(true).build());
|
||||||
|
|
||||||
if (!Strings.CI.equals(result.getMimeType(), ctx.getMimeType())) {
|
boolean matches = Strings.CI.equals(result.getMimeType(), ctx.getMimeType())
|
||||||
|
|| (INTERCHANGEABLE_TEXT_MIME_TYPES.contains(result.getMimeType())
|
||||||
|
&& INTERCHANGEABLE_TEXT_MIME_TYPES.contains(ctx.getMimeType()));
|
||||||
|
|
||||||
|
if (!matches) {
|
||||||
throw new ContentPolicyException(String.format("Detected file type (%s), but mime type (%s) was provided. Mismatch!",
|
throw new ContentPolicyException(String.format("Detected file type (%s), but mime type (%s) was provided. Mismatch!",
|
||||||
result.getMimeType(), ctx.getMimeType()));
|
result.getMimeType(), ctx.getMimeType()));
|
||||||
}
|
}
|
||||||
|
|||||||
+29
@@ -18,6 +18,8 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.infrastructure.documentmanagement.service;
|
package org.apache.fineract.infrastructure.documentmanagement.service;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.nio.file.NoSuchFileException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -38,6 +40,9 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class ImageReadPlatformServiceImpl implements ImageReadPlatformService {
|
public class ImageReadPlatformServiceImpl implements ImageReadPlatformService {
|
||||||
|
|
||||||
|
/** Bound on the cause walk below, so a self-referencing cause chain cannot spin. */
|
||||||
|
private static final int MAX_CAUSE_DEPTH = 10;
|
||||||
|
|
||||||
@Deprecated
|
@Deprecated
|
||||||
private final List<EntityImageIdAdapter> imageIdAdapters;
|
private final List<EntityImageIdAdapter> imageIdAdapters;
|
||||||
private final ContentStoreService storeService;
|
private final ContentStoreService storeService;
|
||||||
@@ -66,7 +71,31 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService {
|
|||||||
} catch (final AbstractPlatformDomainRuleException e) {
|
} catch (final AbstractPlatformDomainRuleException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
|
if (isMissingFromContentStore(e)) {
|
||||||
|
// The m_image row survives but the file it points at does not — the usual cause is a
|
||||||
|
// database copied between environments without its file store. For the caller that is
|
||||||
|
// simply "this entity has no image", not a server fault, so report it the same way as a
|
||||||
|
// missing image record instead of letting it surface as a 500.
|
||||||
|
log.warn("Image for {} {} is recorded but missing from the content store; treating it as no image", entityType,
|
||||||
|
entityId);
|
||||||
|
throw new DocumentNotFoundException(entityType, entityId, -1L);
|
||||||
|
}
|
||||||
throw new DocumentInvalidRequestException(e);
|
throw new DocumentInvalidRequestException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a failure bottoms out in "the stored file is not there", however it was wrapped on the
|
||||||
|
* way up (the file store rethrows as ContentStoreException).
|
||||||
|
*/
|
||||||
|
private boolean isMissingFromContentStore(final Throwable failure) {
|
||||||
|
Throwable cause = failure;
|
||||||
|
for (int depth = 0; cause != null && depth < MAX_CAUSE_DEPTH; depth++) {
|
||||||
|
if (cause instanceof NoSuchFileException || cause instanceof FileNotFoundException) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
cause = cause.getCause();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@
|
|||||||
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
<class>org.apache.fineract.portfolio.group.domain.StaffAssignmentHistory</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
<class>org.apache.fineract.portfolio.group.domain.Group</class>
|
||||||
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
<class>org.apache.fineract.portfolio.client.domain.Client</class>
|
||||||
|
<class>org.apache.fineract.portfolio.client.domain.ClientKyc</class>
|
||||||
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
<class>org.apache.fineract.infrastructure.event.external.repository.domain.ExternalEventConfiguration</class>
|
||||||
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
<class>org.apache.fineract.portfolio.group.domain.GroupRole</class>
|
||||||
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
<class>org.apache.fineract.portfolio.paymenttype.domain.PaymentType</class>
|
||||||
|
|||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.accounting.dividendpaidreport.api;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.WebApplicationException;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Total Dividend Paid" report — derived entirely from the existing Dividend Payable GL
|
||||||
|
* account's debit-side journal entries, exactly how real-world CBS/UCB systems report this (a
|
||||||
|
* query over the ledger, not a separate "Dividend Paid" account). Dividend Payable is only ever
|
||||||
|
* debited by an actual member payout (see ShareAccountSchedularServiceImpl.postDividend — via
|
||||||
|
* the native DIVIDEND_PAYOUT savings transaction's accounting), so every debit entry against it
|
||||||
|
* is, by construction, a real dividend payment.
|
||||||
|
*/
|
||||||
|
@Path("/v1/accounting/dividend-paid-report")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Dividend Paid Report", description = "Total share dividend actually paid to members in a date range, derived from the Dividend Payable GL account's ledger.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DividendPaidReportApiResource {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
|
||||||
|
|
||||||
|
private static final int FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS = 201;
|
||||||
|
private static final int JOURNAL_ENTRY_TYPE_DEBIT = 2;
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String getDividendPaidReport(@QueryParam("fromDate") final String fromDate, @QueryParam("toDate") final String toDate) {
|
||||||
|
if (fromDate == null || fromDate.isBlank() || toDate == null || toDate.isBlank()) {
|
||||||
|
throw apiError(400, "fromDate and toDate (yyyy-MM-dd) are both required");
|
||||||
|
}
|
||||||
|
final Date from;
|
||||||
|
final Date to;
|
||||||
|
try {
|
||||||
|
from = Date.valueOf(fromDate);
|
||||||
|
to = Date.valueOf(toDate);
|
||||||
|
} catch (final IllegalArgumentException e) {
|
||||||
|
throw apiError(400, "fromDate and toDate must be in yyyy-MM-dd format");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Long payableDividendsAccountId = jdbcTemplate
|
||||||
|
.queryForList("SELECT gl_account_id FROM acc_gl_financial_activity_account WHERE financial_activity_type = ?", Long.class,
|
||||||
|
FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS)
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
|
||||||
|
final JsonObject result = new JsonObject();
|
||||||
|
result.addProperty("fromDate", fromDate);
|
||||||
|
result.addProperty("toDate", toDate);
|
||||||
|
if (payableDividendsAccountId == null) {
|
||||||
|
// Dividend Payable hasn't been mapped under Accounting -> Financial Activity Mappings yet.
|
||||||
|
result.addProperty("totalPaid", BigDecimal.ZERO);
|
||||||
|
result.addProperty("payoutCount", 0);
|
||||||
|
result.add("entries", new JsonArray());
|
||||||
|
result.addProperty("glAccountConfigured", false);
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<String, Object> totals = jdbcTemplate.queryForMap("""
|
||||||
|
SELECT COALESCE(SUM(amount), 0) AS total_paid, COUNT(*) AS payout_count
|
||||||
|
FROM acc_gl_journal_entry
|
||||||
|
WHERE account_id = ? AND type_enum = ? AND reversed = false AND entry_date BETWEEN ? AND ?
|
||||||
|
""", payableDividendsAccountId, JOURNAL_ENTRY_TYPE_DEBIT, from, to);
|
||||||
|
|
||||||
|
final List<Map<String, Object>> entryRows = jdbcTemplate.queryForList("""
|
||||||
|
SELECT entry_date, amount, transaction_id
|
||||||
|
FROM acc_gl_journal_entry
|
||||||
|
WHERE account_id = ? AND type_enum = ? AND reversed = false AND entry_date BETWEEN ? AND ?
|
||||||
|
ORDER BY entry_date DESC
|
||||||
|
""", payableDividendsAccountId, JOURNAL_ENTRY_TYPE_DEBIT, from, to);
|
||||||
|
|
||||||
|
result.addProperty("totalPaid", (BigDecimal) totals.get("total_paid"));
|
||||||
|
result.addProperty("payoutCount", ((Number) totals.get("payout_count")).intValue());
|
||||||
|
result.addProperty("glAccountConfigured", true);
|
||||||
|
|
||||||
|
final JsonArray entries = new JsonArray();
|
||||||
|
for (final Map<String, Object> row : entryRows) {
|
||||||
|
final JsonObject entry = new JsonObject();
|
||||||
|
entry.addProperty("entryDate", row.get("entry_date").toString());
|
||||||
|
entry.addProperty("amount", (BigDecimal) row.get("amount"));
|
||||||
|
entry.addProperty("transactionId", (String) row.get("transaction_id"));
|
||||||
|
entries.add(entry);
|
||||||
|
}
|
||||||
|
result.add("entries", entries);
|
||||||
|
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebApplicationException apiError(final int httpStatus, final String message) {
|
||||||
|
final JsonObject errorBody = new JsonObject();
|
||||||
|
errorBody.addProperty("message", message);
|
||||||
|
errorBody.addProperty("defaultUserMessage", message);
|
||||||
|
errorBody.addProperty("httpStatus", httpStatus);
|
||||||
|
return new WebApplicationException(
|
||||||
|
Response.status(httpStatus).entity(gson.toJson(errorBody)).type(MediaType.APPLICATION_JSON).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.accounting.profitandloss.api;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.WebApplicationException;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Date;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real Profit & Loss (Net Profit) for a date range, computed live from posted General Ledger
|
||||||
|
* journal entries — not the demo/sample data shown by the GL Reports module. Used by the Share
|
||||||
|
* Dividend "Create Dividend" screen so a bank officer can see actual profit for the dividend
|
||||||
|
* period and set the dividend as a percentage of it, instead of typing a total amount blind.
|
||||||
|
*
|
||||||
|
* Standard double-entry rule: an Income account (classification_enum=4) increases with a CREDIT
|
||||||
|
* and decreases with a DEBIT; an Expense account (classification_enum=5) increases with a DEBIT
|
||||||
|
* and decreases with a CREDIT. Reversed entries are excluded.
|
||||||
|
*/
|
||||||
|
@Path("/v1/accounting/profitandloss")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Profit And Loss", description = "Real net profit for a date range, computed from posted GL journal entries.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ProfitAndLossApiResource {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final Gson gson = new GsonBuilder().serializeNulls().create();
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String getProfitAndLoss(@QueryParam("fromDate") final String fromDate, @QueryParam("toDate") final String toDate) {
|
||||||
|
if (fromDate == null || fromDate.isBlank() || toDate == null || toDate.isBlank()) {
|
||||||
|
throw apiError(400, "fromDate and toDate (yyyy-MM-dd) are both required");
|
||||||
|
}
|
||||||
|
final Date from;
|
||||||
|
final Date to;
|
||||||
|
try {
|
||||||
|
from = Date.valueOf(fromDate);
|
||||||
|
to = Date.valueOf(toDate);
|
||||||
|
} catch (final IllegalArgumentException e) {
|
||||||
|
throw apiError(400, "fromDate and toDate must be in yyyy-MM-dd format");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<String, Object> row = jdbcTemplate.queryForMap("""
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM(CASE WHEN a.classification_enum = 4 AND je.type_enum = 1 THEN je.amount
|
||||||
|
WHEN a.classification_enum = 4 AND je.type_enum = 2 THEN -je.amount
|
||||||
|
ELSE 0 END), 0) AS total_income,
|
||||||
|
COALESCE(SUM(CASE WHEN a.classification_enum = 5 AND je.type_enum = 2 THEN je.amount
|
||||||
|
WHEN a.classification_enum = 5 AND je.type_enum = 1 THEN -je.amount
|
||||||
|
ELSE 0 END), 0) AS total_expense
|
||||||
|
FROM acc_gl_journal_entry je
|
||||||
|
JOIN acc_gl_account a ON a.id = je.account_id
|
||||||
|
WHERE je.reversed = false
|
||||||
|
AND je.entry_date BETWEEN ? AND ?
|
||||||
|
""", from, to);
|
||||||
|
|
||||||
|
final BigDecimal totalIncome = (BigDecimal) row.get("total_income");
|
||||||
|
final BigDecimal totalExpense = (BigDecimal) row.get("total_expense");
|
||||||
|
final BigDecimal netProfit = totalIncome.subtract(totalExpense);
|
||||||
|
|
||||||
|
return gson.toJson(Map.of("fromDate", fromDate, "toDate", toDate, "totalIncome", totalIncome, "totalExpense", totalExpense,
|
||||||
|
"netProfit", netProfit));
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebApplicationException apiError(final int httpStatus, final String message) {
|
||||||
|
return new WebApplicationException(
|
||||||
|
Response.status(httpStatus).entity(gson.toJson(Map.of("message", message))).type(MediaType.APPLICATION_JSON).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
@@ -61,6 +61,11 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isMakerCheckerEnabled() {
|
||||||
|
return getGlobalConfigurationPropertyData(GlobalConfigurationConstants.MAKER_CHECKER).isEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<String> getAllowedLoanStatusesForExternalAssetTransfer() {
|
public List<String> getAllowedLoanStatusesForExternalAssetTransfer() {
|
||||||
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(
|
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(
|
||||||
|
|||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.infrastructure.databaseexport.api;
|
||||||
|
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.Consumes;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
|
import org.apache.fineract.infrastructure.databaseexport.service.DatabaseExportService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Path("/v1/databaseexport")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Database Export", description = "Approval-gated full export of the tenant database.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatabaseExportApiResource {
|
||||||
|
|
||||||
|
private final DatabaseExportService service;
|
||||||
|
private final FromJsonHelper fromJsonHelper;
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "List export requests, optionally filtered by status")
|
||||||
|
public List<Map<String, Object>> retrieveAll(@QueryParam("status") @Parameter(description = "status") final String status) {
|
||||||
|
return this.service.retrieveAll(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{requestId}")
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Retrieve a single export request")
|
||||||
|
public Map<String, Object> retrieveOne(@PathParam("requestId") final Long requestId) {
|
||||||
|
return this.service.retrieveOne(requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Raise a request for a full database export")
|
||||||
|
public Map<String, Object> requestExport(@Parameter(hidden = true) final String apiRequestBodyAsJson) {
|
||||||
|
final JsonElement element = this.fromJsonHelper.parse(apiRequestBodyAsJson);
|
||||||
|
final String reason = this.fromJsonHelper.extractStringNamed("reason", element);
|
||||||
|
final Long id = this.service.requestExport(reason);
|
||||||
|
return Map.of("resourceId", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{requestId}/approve")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Approve an export request (admin only, never the requester)")
|
||||||
|
public Map<String, Object> approve(@PathParam("requestId") final Long requestId) {
|
||||||
|
this.service.approve(requestId);
|
||||||
|
return Map.of("resourceId", requestId, "status", "APPROVED");
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{requestId}/reject")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Reject an export request with a reason")
|
||||||
|
public Map<String, Object> reject(@PathParam("requestId") final Long requestId,
|
||||||
|
@Parameter(hidden = true) final String apiRequestBodyAsJson) {
|
||||||
|
final JsonElement element = this.fromJsonHelper.parse(apiRequestBodyAsJson);
|
||||||
|
final JsonObject json = element == null ? new JsonObject() : element.getAsJsonObject();
|
||||||
|
final String reason = json.has("rejectionReason") && !json.get("rejectionReason").isJsonNull()
|
||||||
|
? json.get("rejectionReason").getAsString()
|
||||||
|
: null;
|
||||||
|
this.service.reject(requestId, reason);
|
||||||
|
return Map.of("resourceId", requestId, "status", "REJECTED");
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{requestId}/download")
|
||||||
|
@Produces({ "application/zip" })
|
||||||
|
@Operation(summary = "Download the approved export as a ZIP of CSV files")
|
||||||
|
public Response download(@PathParam("requestId") final Long requestId) {
|
||||||
|
final byte[] archive = this.service.generateExport(requestId);
|
||||||
|
return Response.ok(archive)
|
||||||
|
.header("Content-Disposition", "attachment; filename=\"cbsnexora-database-export.zip\"")
|
||||||
|
.header("Content-Length", archive.length)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.infrastructure.databaseexport.domain;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A request to take a full export of the tenant database. The export carries every client's personal, KYC and
|
||||||
|
* account data, so it is deliberately a two-person action: whoever asks for it cannot also approve it.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "m_database_export_request")
|
||||||
|
public class DatabaseExportRequest extends AbstractPersistableCustom<Long> {
|
||||||
|
|
||||||
|
public static final String STATUS_PENDING_APPROVAL = "PENDING_APPROVAL";
|
||||||
|
public static final String STATUS_APPROVED = "APPROVED";
|
||||||
|
public static final String STATUS_REJECTED = "REJECTED";
|
||||||
|
/** Approved and the dump has actually been downloaded at least once. */
|
||||||
|
public static final String STATUS_GENERATED = "GENERATED";
|
||||||
|
|
||||||
|
@Column(name = "status", length = 30, nullable = false)
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@Column(name = "reason", nullable = false)
|
||||||
|
private String reason;
|
||||||
|
|
||||||
|
@Column(name = "requested_by", nullable = false)
|
||||||
|
private Long requestedBy;
|
||||||
|
|
||||||
|
@Column(name = "requested_by_username", length = 100)
|
||||||
|
private String requestedByUsername;
|
||||||
|
|
||||||
|
@Column(name = "requested_on", nullable = false)
|
||||||
|
private LocalDateTime requestedOn;
|
||||||
|
|
||||||
|
@Column(name = "approved_by")
|
||||||
|
private Long approvedBy;
|
||||||
|
|
||||||
|
@Column(name = "approved_by_username", length = 100)
|
||||||
|
private String approvedByUsername;
|
||||||
|
|
||||||
|
@Column(name = "approved_on")
|
||||||
|
private LocalDateTime approvedOn;
|
||||||
|
|
||||||
|
@Column(name = "rejection_reason")
|
||||||
|
private String rejectionReason;
|
||||||
|
|
||||||
|
@Column(name = "generated_on")
|
||||||
|
private LocalDateTime generatedOn;
|
||||||
|
|
||||||
|
@Column(name = "generated_by")
|
||||||
|
private Long generatedBy;
|
||||||
|
|
||||||
|
@Column(name = "file_name", length = 255)
|
||||||
|
private String fileName;
|
||||||
|
|
||||||
|
@Column(name = "file_size_bytes")
|
||||||
|
private Long fileSizeBytes;
|
||||||
|
|
||||||
|
@Column(name = "row_count")
|
||||||
|
private Long rowCount;
|
||||||
|
|
||||||
|
protected DatabaseExportRequest() {
|
||||||
|
// Default constructor for JPA
|
||||||
|
}
|
||||||
|
|
||||||
|
private DatabaseExportRequest(final String reason, final Long requestedBy, final String requestedByUsername,
|
||||||
|
final LocalDateTime requestedOn) {
|
||||||
|
this.status = STATUS_PENDING_APPROVAL;
|
||||||
|
this.reason = reason;
|
||||||
|
this.requestedBy = requestedBy;
|
||||||
|
this.requestedByUsername = requestedByUsername;
|
||||||
|
this.requestedOn = requestedOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DatabaseExportRequest createNew(final String reason, final Long requestedBy, final String requestedByUsername,
|
||||||
|
final LocalDateTime requestedOn) {
|
||||||
|
return new DatabaseExportRequest(reason, requestedBy, requestedByUsername, requestedOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStatus() {
|
||||||
|
return this.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getRequestedBy() {
|
||||||
|
return this.requestedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPendingApproval() {
|
||||||
|
return STATUS_PENDING_APPROVAL.equals(this.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An approval buys exactly one download. Once the archive has been handed over the request is spent, and a
|
||||||
|
* second copy has to be asked for and approved again — so every copy of the database that exists outside
|
||||||
|
* the system can be traced back to an approval that was granted for it specifically.
|
||||||
|
*/
|
||||||
|
public boolean isDownloadable() {
|
||||||
|
return STATUS_APPROVED.equals(this.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isAlreadyDownloaded() {
|
||||||
|
return STATUS_GENERATED.equals(this.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void approve(final Long approvedBy, final String approvedByUsername, final LocalDateTime approvedOn) {
|
||||||
|
this.status = STATUS_APPROVED;
|
||||||
|
this.approvedBy = approvedBy;
|
||||||
|
this.approvedByUsername = approvedByUsername;
|
||||||
|
this.approvedOn = approvedOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reject(final Long approvedBy, final String approvedByUsername, final LocalDateTime approvedOn,
|
||||||
|
final String rejectionReason) {
|
||||||
|
this.status = STATUS_REJECTED;
|
||||||
|
this.approvedBy = approvedBy;
|
||||||
|
this.approvedByUsername = approvedByUsername;
|
||||||
|
this.approvedOn = approvedOn;
|
||||||
|
this.rejectionReason = rejectionReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records that the dump actually left the system, which is the moment that matters for an audit. */
|
||||||
|
public void markGenerated(final Long generatedBy, final LocalDateTime generatedOn, final String fileName,
|
||||||
|
final Long fileSizeBytes, final Long rowCount) {
|
||||||
|
this.status = STATUS_GENERATED;
|
||||||
|
this.generatedBy = generatedBy;
|
||||||
|
this.generatedOn = generatedOn;
|
||||||
|
this.fileName = fileName;
|
||||||
|
this.fileSizeBytes = fileSizeBytes;
|
||||||
|
this.rowCount = rowCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.infrastructure.databaseexport.domain;
|
||||||
|
|
||||||
|
import jakarta.persistence.LockModeType;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Lock;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
public interface DatabaseExportRequestRepository extends JpaRepository<DatabaseExportRequest, Long> {
|
||||||
|
|
||||||
|
List<DatabaseExportRequest> findByStatusOrderByIdDesc(String status);
|
||||||
|
|
||||||
|
long countByRequestedByAndStatus(Long requestedBy, String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An approval is worth exactly one download, so the row is locked while that single use is spent. Without
|
||||||
|
* the lock two concurrent calls could both read APPROVED and both walk away with a copy of the database.
|
||||||
|
*/
|
||||||
|
@Lock(value = LockModeType.PESSIMISTIC_WRITE)
|
||||||
|
@Query("select request from DatabaseExportRequest request where request.id = :requestId")
|
||||||
|
Optional<DatabaseExportRequest> findByIdWithLock(@Param("requestId") Long requestId);
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.infrastructure.databaseexport.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** Requesting, approving and generating a full export of the tenant database. */
|
||||||
|
public interface DatabaseExportService {
|
||||||
|
|
||||||
|
Long requestExport(String reason);
|
||||||
|
|
||||||
|
List<Map<String, Object>> retrieveAll(String status);
|
||||||
|
|
||||||
|
Map<String, Object> retrieveOne(Long requestId);
|
||||||
|
|
||||||
|
void approve(Long requestId);
|
||||||
|
|
||||||
|
void reject(Long requestId, String rejectionReason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streams the approved export as a ZIP of CSV files, one per table. Only callable against a request that an
|
||||||
|
* admin has already approved.
|
||||||
|
*/
|
||||||
|
byte[] generateExport(Long requestId);
|
||||||
|
}
|
||||||
+318
@@ -0,0 +1,318 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.infrastructure.databaseexport.service;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
|
||||||
|
import org.apache.fineract.infrastructure.databaseexport.domain.DatabaseExportRequest;
|
||||||
|
import org.apache.fineract.infrastructure.databaseexport.domain.DatabaseExportRequestRepository;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
|
import org.apache.fineract.useradministration.domain.AppUser;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatabaseExportServiceImpl implements DatabaseExportService {
|
||||||
|
|
||||||
|
private static final String PERMISSION = "DATABASEEXPORT";
|
||||||
|
/** Guards against a runaway export: a single table beyond this is truncated rather than exhausting heap. */
|
||||||
|
private static final int MAX_ROWS_PER_TABLE = 200_000;
|
||||||
|
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
private final DatabaseExportRequestRepository repository;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public Long requestExport(final String reason) {
|
||||||
|
final AppUser user = this.context.authenticatedUser();
|
||||||
|
user.validateHasPermissionTo("CREATE_" + PERMISSION);
|
||||||
|
|
||||||
|
if (reason == null || reason.trim().length() < 10) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.reason.too.short",
|
||||||
|
"A reason of at least 10 characters is required for a database export request.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// One open request per user at a time, so a queue of forgotten requests cannot build up for an
|
||||||
|
// approver to rubber-stamp in bulk.
|
||||||
|
if (this.repository.countByRequestedByAndStatus(user.getId(), DatabaseExportRequest.STATUS_PENDING_APPROVAL) > 0) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.request.already.pending",
|
||||||
|
"You already have a database export request awaiting approval.");
|
||||||
|
}
|
||||||
|
|
||||||
|
final DatabaseExportRequest request = DatabaseExportRequest.createNew(reason.trim(), user.getId(), user.getUsername(),
|
||||||
|
LocalDateTime.now());
|
||||||
|
this.repository.saveAndFlush(request);
|
||||||
|
|
||||||
|
log.warn("Database export requested by user {} ({}), request id {}", user.getUsername(), user.getId(), request.getId());
|
||||||
|
return request.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Map<String, Object>> retrieveAll(final String status) {
|
||||||
|
this.context.authenticatedUser().validateHasReadPermission(PERMISSION);
|
||||||
|
|
||||||
|
// Aliases are quoted because PostgreSQL folds unquoted identifiers to lower case, which would hand the
|
||||||
|
// client `requestedbyusername` and leave every camelCase field on the screen empty.
|
||||||
|
final StringBuilder sql = new StringBuilder("SELECT id, status, reason, requested_by AS \"requestedBy\", "
|
||||||
|
+ "requested_by_username AS \"requestedByUsername\", requested_on AS \"requestedOn\", "
|
||||||
|
+ "approved_by AS \"approvedBy\", approved_by_username AS \"approvedByUsername\", "
|
||||||
|
+ "approved_on AS \"approvedOn\", rejection_reason AS \"rejectionReason\", "
|
||||||
|
+ "generated_on AS \"generatedOn\", generated_by AS \"generatedBy\", file_name AS \"fileName\", "
|
||||||
|
+ "file_size_bytes AS \"fileSizeBytes\", row_count AS \"rowCount\" "
|
||||||
|
+ "FROM m_database_export_request ");
|
||||||
|
|
||||||
|
if (status != null && !status.trim().isEmpty()) {
|
||||||
|
sql.append("WHERE status = ? ORDER BY id DESC");
|
||||||
|
return this.jdbcTemplate.queryForList(sql.toString(), status.trim().toUpperCase());
|
||||||
|
}
|
||||||
|
sql.append("ORDER BY id DESC");
|
||||||
|
return this.jdbcTemplate.queryForList(sql.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> retrieveOne(final Long requestId) {
|
||||||
|
this.context.authenticatedUser().validateHasReadPermission(PERMISSION);
|
||||||
|
final List<Map<String, Object>> rows = this.jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, status, reason, requested_by AS \"requestedBy\", "
|
||||||
|
+ "requested_by_username AS \"requestedByUsername\", requested_on AS \"requestedOn\", "
|
||||||
|
+ "approved_by_username AS \"approvedByUsername\", approved_on AS \"approvedOn\", "
|
||||||
|
+ "rejection_reason AS \"rejectionReason\", generated_on AS \"generatedOn\", "
|
||||||
|
+ "file_name AS \"fileName\", file_size_bytes AS \"fileSizeBytes\", row_count AS \"rowCount\" "
|
||||||
|
+ "FROM m_database_export_request WHERE id = ?",
|
||||||
|
requestId);
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.not.found", "Export request not found.");
|
||||||
|
}
|
||||||
|
return rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public void approve(final Long requestId) {
|
||||||
|
final AppUser approver = this.context.authenticatedUser();
|
||||||
|
approver.validateHasPermissionTo("APPROVE_" + PERMISSION);
|
||||||
|
|
||||||
|
final DatabaseExportRequest request = findOneOrThrow(requestId);
|
||||||
|
validatePending(request);
|
||||||
|
validateNotSelfApproval(request, approver);
|
||||||
|
|
||||||
|
request.approve(approver.getId(), approver.getUsername(), LocalDateTime.now());
|
||||||
|
this.repository.saveAndFlush(request);
|
||||||
|
|
||||||
|
log.warn("Database export request {} approved by {} ({})", requestId, approver.getUsername(), approver.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public void reject(final Long requestId, final String rejectionReason) {
|
||||||
|
final AppUser approver = this.context.authenticatedUser();
|
||||||
|
approver.validateHasPermissionTo("APPROVE_" + PERMISSION);
|
||||||
|
|
||||||
|
final DatabaseExportRequest request = findOneOrThrow(requestId);
|
||||||
|
validatePending(request);
|
||||||
|
|
||||||
|
if (rejectionReason == null || rejectionReason.trim().isEmpty()) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.rejection.reason.required",
|
||||||
|
"A reason is required when rejecting a database export request.");
|
||||||
|
}
|
||||||
|
|
||||||
|
request.reject(approver.getId(), approver.getUsername(), LocalDateTime.now(), rejectionReason.trim());
|
||||||
|
this.repository.saveAndFlush(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public byte[] generateExport(final Long requestId) {
|
||||||
|
final AppUser user = this.context.authenticatedUser();
|
||||||
|
user.validateHasPermissionTo("DOWNLOAD_" + PERMISSION);
|
||||||
|
|
||||||
|
// Locked for the duration of the transaction: the approval is worth one download, and two concurrent
|
||||||
|
// calls must not both find it unspent.
|
||||||
|
final DatabaseExportRequest request = this.repository.findByIdWithLock(requestId)
|
||||||
|
.orElseThrow(() -> new PlatformDataIntegrityException("error.msg.databaseexport.not.found",
|
||||||
|
"Export request not found."));
|
||||||
|
// Checked before ownership so the requester coming back for a second copy gets told why, rather than
|
||||||
|
// being turned away with a message about approval that no longer describes their situation.
|
||||||
|
if (request.isAlreadyDownloaded()) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.already.downloaded",
|
||||||
|
"This export has already been downloaded. Raise a new request to take another copy.");
|
||||||
|
}
|
||||||
|
if (!request.isDownloadable()) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.not.approved",
|
||||||
|
"This export request has not been approved. Current status: " + request.getStatus() + ".");
|
||||||
|
}
|
||||||
|
validateIsRequester(request, user);
|
||||||
|
|
||||||
|
final List<String> tables = listTenantTables();
|
||||||
|
long totalRows = 0;
|
||||||
|
|
||||||
|
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||||
|
try (ZipOutputStream zip = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) {
|
||||||
|
for (final String table : tables) {
|
||||||
|
try {
|
||||||
|
totalRows += writeTableAsCsv(zip, table);
|
||||||
|
} catch (final Exception e) {
|
||||||
|
// One unreadable table (a view, a permissions quirk) must not abandon the whole export.
|
||||||
|
log.error("Database export: skipping table {} — {}", table, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeManifest(zip, request, tables, totalRows, user);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.generation.failed",
|
||||||
|
"Failed to generate the database export: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
final byte[] archive = buffer.toByteArray();
|
||||||
|
final String fileName = "cbsnexora-export-" + DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").format(LocalDateTime.now())
|
||||||
|
+ ".zip";
|
||||||
|
|
||||||
|
request.markGenerated(user.getId(), LocalDateTime.now(), fileName, (long) archive.length, totalRows);
|
||||||
|
this.repository.saveAndFlush(request);
|
||||||
|
|
||||||
|
log.warn("Database export request {} downloaded by {} ({}) — {} tables, {} rows, {} bytes", requestId, user.getUsername(),
|
||||||
|
user.getId(), tables.size(), totalRows, archive.length);
|
||||||
|
return archive;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> listTenantTables() {
|
||||||
|
return this.jdbcTemplate.queryForList("SELECT table_name FROM information_schema.tables "
|
||||||
|
+ "WHERE table_schema = current_schema() AND table_type = 'BASE TABLE' ORDER BY table_name", String.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes one table as a CSV entry and returns how many rows it contained. */
|
||||||
|
private long writeTableAsCsv(final ZipOutputStream zip, final String table) throws IOException {
|
||||||
|
// The table name comes from information_schema, never from user input, so it cannot carry injection.
|
||||||
|
final List<Map<String, Object>> rows = this.jdbcTemplate
|
||||||
|
.queryForList("SELECT * FROM \"" + table + "\" LIMIT " + MAX_ROWS_PER_TABLE);
|
||||||
|
|
||||||
|
zip.putNextEntry(new ZipEntry("data/" + table + ".csv"));
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
// Still emit the header so an empty table is visibly empty rather than missing.
|
||||||
|
final List<String> columns = this.jdbcTemplate.queryForList("SELECT column_name FROM information_schema.columns "
|
||||||
|
+ "WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position", String.class, table);
|
||||||
|
zip.write(String.join(",", columns).getBytes(StandardCharsets.UTF_8));
|
||||||
|
zip.write('\n');
|
||||||
|
zip.closeEntry();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<String> columns = new ArrayList<>(rows.get(0).keySet());
|
||||||
|
zip.write(String.join(",", columns).getBytes(StandardCharsets.UTF_8));
|
||||||
|
zip.write('\n');
|
||||||
|
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final StringBuilder line = new StringBuilder();
|
||||||
|
for (int i = 0; i < columns.size(); i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
line.append(',');
|
||||||
|
}
|
||||||
|
line.append(csvEscape(row.get(columns.get(i))));
|
||||||
|
}
|
||||||
|
line.append('\n');
|
||||||
|
zip.write(line.toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
zip.closeEntry();
|
||||||
|
return rows.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records who authorised the export inside the archive, so the file carries its own provenance. */
|
||||||
|
private void writeManifest(final ZipOutputStream zip, final DatabaseExportRequest request, final List<String> tables,
|
||||||
|
final long totalRows, final AppUser downloadedBy) throws IOException {
|
||||||
|
final Map<String, Object> details = retrieveOne(request.getId());
|
||||||
|
final StringBuilder manifest = new StringBuilder();
|
||||||
|
manifest.append("CBSNexora — Full Database Export\n");
|
||||||
|
manifest.append("=================================\n\n");
|
||||||
|
manifest.append("CONFIDENTIAL. This archive contains customer personal, KYC and account data.\n");
|
||||||
|
manifest.append("Handle under your institution's data protection policy.\n\n");
|
||||||
|
manifest.append("Request ID : ").append(request.getId()).append('\n');
|
||||||
|
manifest.append("Requested by : ").append(details.get("requestedByUsername")).append('\n');
|
||||||
|
manifest.append("Requested on : ").append(details.get("requestedOn")).append('\n');
|
||||||
|
manifest.append("Reason : ").append(details.get("reason")).append('\n');
|
||||||
|
manifest.append("Approved by : ").append(details.get("approvedByUsername")).append('\n');
|
||||||
|
manifest.append("Approved on : ").append(details.get("approvedOn")).append('\n');
|
||||||
|
manifest.append("Downloaded by : ").append(downloadedBy.getUsername()).append('\n');
|
||||||
|
manifest.append("Downloaded on : ").append(LocalDateTime.now()).append('\n');
|
||||||
|
manifest.append("Tables exported : ").append(tables.size()).append('\n');
|
||||||
|
manifest.append("Rows exported : ").append(totalRows).append('\n');
|
||||||
|
manifest.append("Row cap / table : ").append(MAX_ROWS_PER_TABLE).append('\n');
|
||||||
|
|
||||||
|
zip.putNextEntry(new ZipEntry("MANIFEST.txt"));
|
||||||
|
zip.write(manifest.toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
zip.closeEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String csvEscape(final Object value) {
|
||||||
|
if (value == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final String text = String.valueOf(value);
|
||||||
|
if (text.indexOf(',') >= 0 || text.indexOf('"') >= 0 || text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0) {
|
||||||
|
return '"' + text.replace("\"", "\"\"") + '"';
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DatabaseExportRequest findOneOrThrow(final Long requestId) {
|
||||||
|
return this.repository.findById(requestId).orElseThrow(() -> new PlatformDataIntegrityException(
|
||||||
|
"error.msg.databaseexport.not.found", "Export request not found."));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validatePending(final DatabaseExportRequest request) {
|
||||||
|
if (!request.isPendingApproval()) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.already.actioned",
|
||||||
|
"This request has already been actioned. Current status: " + request.getStatus() + ".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The archive goes to the person who asked for it and stated the reason, and to nobody else. An approver
|
||||||
|
* authorises the export; that is not the same as being entitled to take a copy of it, and letting the
|
||||||
|
* approver download would collapse the two-person control back into one.
|
||||||
|
*/
|
||||||
|
private void validateIsRequester(final DatabaseExportRequest request, final AppUser user) {
|
||||||
|
if (!user.getId().equals(request.getRequestedBy())) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.not.requester",
|
||||||
|
"Only the user who raised this export request can download the archive.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entire control is that two different people are involved, so this is the check that enforces it. */
|
||||||
|
private void validateNotSelfApproval(final DatabaseExportRequest request, final AppUser approver) {
|
||||||
|
if (approver.getId().equals(request.getRequestedBy())) {
|
||||||
|
throw new PlatformDataIntegrityException("error.msg.databaseexport.self.approval",
|
||||||
|
"A database export cannot be approved by the same user who requested it.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.api;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.Consumes;
|
||||||
|
import jakarta.ws.rs.DefaultValue;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
|
import org.apache.fineract.portfolio.aml.data.AmlRecurringAlertData;
|
||||||
|
import org.apache.fineract.portfolio.aml.service.AmlRecurringAlertReadPlatformService;
|
||||||
|
import org.apache.fineract.portfolio.aml.service.AmlRecurringAlertWritePlatformService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Path("/v1/aml/recurring-alerts")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "AML Recurring Alerts",
|
||||||
|
description = "Customers whose transactions repeatedly trip the AML engine, queued for an employee to review why.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AmlRecurringAlertApiResource {
|
||||||
|
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
private final AmlRecurringAlertReadPlatformService readPlatformService;
|
||||||
|
private final AmlRecurringAlertWritePlatformService writePlatformService;
|
||||||
|
private final DefaultToApiJsonSerializer<AmlRecurringAlertData> toApiJsonSerializer;
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Retrieve the recurring-alert review queue",
|
||||||
|
description = "Customers with at least minAlerts engine alerts inside the last windowDays, worst first. "
|
||||||
|
+ "Each row carries the triggering transactions so the reviewer can see why the customer keeps surfacing.")
|
||||||
|
public String retrieveRecurringAlerts(
|
||||||
|
@QueryParam("minAlerts") @DefaultValue("3") final int minAlerts,
|
||||||
|
@QueryParam("windowDays") @DefaultValue("90") final int windowDays,
|
||||||
|
@QueryParam("onlyNeedingReview") @DefaultValue("false") final boolean onlyNeedingReview) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
final List<AmlRecurringAlertData> rows = this.readPlatformService.retrieve(Math.max(minAlerts, 2), Math.max(windowDays, 1),
|
||||||
|
onlyNeedingReview);
|
||||||
|
return this.toApiJsonSerializer.serialize(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{clientId}/review")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Record a review of a customer's repeated AML activity",
|
||||||
|
description = "outcome is CLEARED, MONITOR or ESCALATED. The customer leaves the queue until their alert "
|
||||||
|
+ "count grows beyond the count reviewed here.")
|
||||||
|
public String review(@PathParam("clientId") final Long clientId, final AmlRecurringReviewRequest request) {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("REVIEW_AML_ALERT");
|
||||||
|
final Long reviewId = this.writePlatformService.recordReview(clientId, request.getOutcome(), request.getNotes(),
|
||||||
|
request.getWindowDays() == null ? 0 : request.getWindowDays());
|
||||||
|
return "{\"clientId\":" + clientId + ",\"reviewId\":" + reviewId + "}";
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.api;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
/** Request body for {@code POST /v1/aml/recurring-alerts/{clientId}/review}. */
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class AmlRecurringReviewRequest {
|
||||||
|
|
||||||
|
@Schema(description = "CLEARED, MONITOR or ESCALATED", requiredMode = Schema.RequiredMode.REQUIRED, example = "MONITOR")
|
||||||
|
private String outcome;
|
||||||
|
|
||||||
|
@Schema(description = "Why the customer keeps surfacing and what was decided",
|
||||||
|
requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
|
private String notes;
|
||||||
|
|
||||||
|
@Schema(description = "Observation window the reviewer had on screen, so the recorded alert count matches it",
|
||||||
|
example = "90")
|
||||||
|
private Integer windowDays;
|
||||||
|
}
|
||||||
+8
-1
@@ -22,7 +22,14 @@ import java.io.Serializable;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param riskCategory
|
||||||
|
* severity of the rule that fired (1 Low, 2 Medium, 3 High), taken from the originating
|
||||||
|
* {@code m_client_risk_rule} entry via {@code source_client_risk_rule_id}. Null for rules with no catalog
|
||||||
|
* ancestor — MANUAL_REFERRAL is raised by a user, not derived from the rule set, so it carries no severity.
|
||||||
|
*/
|
||||||
public record AmlAlertData(Long id, String transactionType, Long transactionId, Long clientId, String clientDisplayName,
|
public record AmlAlertData(Long id, String transactionType, Long transactionId, Long clientId, String clientDisplayName,
|
||||||
String ruleCode, String ruleDescription, BigDecimal amount, String currencyCode, LocalDateTime raisedOn, String status,
|
String ruleCode, String ruleDescription, BigDecimal amount, String currencyCode, LocalDateTime raisedOn, String status,
|
||||||
String reviewedByUsername, LocalDateTime reviewedOn, String reviewNotes, String disposition) implements Serializable {
|
String reviewedByUsername, LocalDateTime reviewedOn, String reviewNotes, String disposition, Integer riskCategory)
|
||||||
|
implements Serializable {
|
||||||
}
|
}
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One customer who has tripped the AML engine repeatedly inside the observation window.
|
||||||
|
*
|
||||||
|
* @param alertCount
|
||||||
|
* alerts in the window — what the threshold is compared against
|
||||||
|
* @param highRiskCount
|
||||||
|
* how many of those came from a High severity catalog rule
|
||||||
|
* @param distinctRules
|
||||||
|
* number of different rules involved; one rule firing five times is a weaker signal than
|
||||||
|
* five different rules firing once, and the reviewer needs to see which it is
|
||||||
|
* @param openCount
|
||||||
|
* alerts still awaiting a per-transaction disposition
|
||||||
|
* @param escalatedCount
|
||||||
|
* alerts already escalated to an STR case
|
||||||
|
* @param needsReview
|
||||||
|
* true when there is no review yet, or new alerts have arrived since the last one
|
||||||
|
* @param alerts
|
||||||
|
* the triggering transactions themselves, so the reviewer can see why this customer keeps
|
||||||
|
* surfacing without leaving the row
|
||||||
|
*/
|
||||||
|
public record AmlRecurringAlertData(Long clientId, String clientDisplayName, String accountNo, Integer clientRiskCategory,
|
||||||
|
int alertCount, int highRiskCount, int distinctRules, int openCount, int escalatedCount, BigDecimal totalAmount,
|
||||||
|
LocalDateTime firstAlertOn, LocalDateTime lastAlertOn, List<String> ruleCodes, boolean needsReview,
|
||||||
|
Integer alertCountAtLastReview, String lastReviewOutcome, String lastReviewedByUsername, LocalDateTime lastReviewedOn,
|
||||||
|
String lastReviewNotes, LocalDate windowFrom, List<AmlAlertData> alerts) implements Serializable {
|
||||||
|
}
|
||||||
+25
-4
@@ -19,12 +19,15 @@
|
|||||||
package org.apache.fineract.portfolio.aml.service;
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.apache.fineract.portfolio.aml.data.AmlAlertData;
|
import org.apache.fineract.portfolio.aml.data.AmlAlertData;
|
||||||
import org.apache.fineract.portfolio.aml.domain.AmlAlert;
|
import org.apache.fineract.portfolio.aml.domain.AmlAlert;
|
||||||
import org.apache.fineract.portfolio.aml.domain.AmlAlertRepository;
|
import org.apache.fineract.portfolio.aml.domain.AmlAlertRepository;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.ClientRiskRuleRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -34,20 +37,38 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
public class AmlAlertReadPlatformServiceImpl implements AmlAlertReadPlatformService {
|
public class AmlAlertReadPlatformServiceImpl implements AmlAlertReadPlatformService {
|
||||||
|
|
||||||
private final AmlAlertRepository repository;
|
private final AmlAlertRepository repository;
|
||||||
|
private final ClientRiskRuleRepository clientRiskRuleRepository;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<AmlAlertData> retrieve(String statusFilter) {
|
public List<AmlAlertData> retrieve(String statusFilter) {
|
||||||
final List<AmlAlert> alerts = (statusFilter == null || statusFilter.isBlank()) ? repository.findAll()
|
final List<AmlAlert> alerts = (statusFilter == null || statusFilter.isBlank()) ? repository.findAll()
|
||||||
: repository.findByStatusOrderByRaisedOnAsc(statusFilter);
|
: repository.findByStatusOrderByRaisedOnAsc(statusFilter);
|
||||||
return alerts.stream().sorted(Comparator.comparing(AmlAlert::getRaisedOn).reversed()).map(this::mapToData)
|
// Resolved once for the whole page rather than per alert: many alerts share a rule, so a
|
||||||
.collect(Collectors.toList());
|
// lookup inside the map step would re-read the same catalog rows repeatedly.
|
||||||
|
final Map<Long, Integer> riskByRiskRuleId = riskCategoriesFor(alerts);
|
||||||
|
return alerts.stream().sorted(Comparator.comparing(AmlAlert::getRaisedOn).reversed())
|
||||||
|
.map(alert -> mapToData(alert, riskByRiskRuleId)).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private AmlAlertData mapToData(AmlAlert alert) {
|
/** Severity of each originating catalog rule, keyed on m_client_risk_rule.id. */
|
||||||
|
private Map<Long, Integer> riskCategoriesFor(final List<AmlAlert> alerts) {
|
||||||
|
final List<Long> sourceIds = alerts.stream().map(a -> a.getRule().getSourceClientRiskRuleId()).filter(id -> id != null).distinct()
|
||||||
|
.toList();
|
||||||
|
final Map<Long, Integer> byId = new HashMap<>();
|
||||||
|
if (sourceIds.isEmpty()) {
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
this.clientRiskRuleRepository.findAllById(sourceIds).forEach(rule -> byId.put(rule.getId(), rule.getRiskCategory()));
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AmlAlertData mapToData(AmlAlert alert, Map<Long, Integer> riskByRiskRuleId) {
|
||||||
|
final Long sourceRiskRuleId = alert.getRule().getSourceClientRiskRuleId();
|
||||||
|
final Integer riskCategory = sourceRiskRuleId == null ? null : riskByRiskRuleId.get(sourceRiskRuleId);
|
||||||
return new AmlAlertData(alert.getId(), alert.getTransactionType().name(), alert.getTransactionId(), alert.getClient().getId(),
|
return new AmlAlertData(alert.getId(), alert.getTransactionType().name(), alert.getTransactionId(), alert.getClient().getId(),
|
||||||
alert.getClient().getDisplayName(), alert.getRule().getRuleCode(), alert.getRule().getDescription(), alert.getAmount(),
|
alert.getClient().getDisplayName(), alert.getRule().getRuleCode(), alert.getRule().getDescription(), alert.getAmount(),
|
||||||
alert.getCurrencyCode(), alert.getRaisedOn(), alert.getStatus().name(),
|
alert.getCurrencyCode(), alert.getRaisedOn(), alert.getStatus().name(),
|
||||||
alert.getReviewedBy() == null ? null : alert.getReviewedBy().getUsername(), alert.getReviewedOn(),
|
alert.getReviewedBy() == null ? null : alert.getReviewedBy().getUsername(), alert.getReviewedOn(),
|
||||||
alert.getReviewNotes(), alert.getDisposition() == null ? null : alert.getDisposition().name());
|
alert.getReviewNotes(), alert.getDisposition() == null ? null : alert.getDisposition().name(), riskCategory);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
import org.apache.fineract.portfolio.client.domain.Client;
|
||||||
|
|
||||||
|
public interface AmlRecurringAlertNotificationService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called once per transaction after the engine has saved its alerts. Raises a notification for
|
||||||
|
* AML reviewers when this customer's alert count crosses the recurring-behaviour threshold.
|
||||||
|
*
|
||||||
|
* @param alertsJustRaised
|
||||||
|
* how many alerts this transaction produced, so the count before it can be derived
|
||||||
|
*/
|
||||||
|
void onAlertsRaised(Client client, int alertsJustRaised);
|
||||||
|
}
|
||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.fineract.notification.service.UserNotificationService;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlAlertRepository;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.Client;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pushes a notification to AML reviewers when one customer keeps tripping the engine.
|
||||||
|
*
|
||||||
|
* The review queue on the AML Rules Master screen is the durable record; this is the nudge that
|
||||||
|
* stops it having to be watched. Recipients are every user holding REVIEW_AML_ALERT in the
|
||||||
|
* customer's office, resolved by {@link UserNotificationService}.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class AmlRecurringAlertNotificationServiceImpl implements AmlRecurringAlertNotificationService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches ClientRiskEscalationServiceImpl.ESCALATION_THRESHOLD — the point the platform already
|
||||||
|
* treats as "this customer has done this enough times to warrant another look".
|
||||||
|
*/
|
||||||
|
private static final int RECURRING_THRESHOLD = 3;
|
||||||
|
private static final int WINDOW_DAYS = 90;
|
||||||
|
|
||||||
|
private static final String REVIEW_PERMISSION = "REVIEW_AML_ALERT";
|
||||||
|
private static final String OBJECT_TYPE = "AML_RECURRING";
|
||||||
|
private static final String EVENT_TYPE = "recurringAmlActivity";
|
||||||
|
|
||||||
|
private final AmlAlertRepository alertRepository;
|
||||||
|
private final UserNotificationService userNotificationService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAlertsRaised(final Client client, final int alertsJustRaised) {
|
||||||
|
if (client == null || alertsJustRaised <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final LocalDateTime since = LocalDate.now().minusDays(WINDOW_DAYS).atStartOfDay();
|
||||||
|
final long after = this.alertRepository.countByClient_IdAndRaisedOnGreaterThanEqual(client.getId(), since);
|
||||||
|
final long before = after - alertsJustRaised;
|
||||||
|
|
||||||
|
// Fires on each multiple of the threshold - 3rd, 6th, 9th alert - rather than on every
|
||||||
|
// alert once the threshold is passed. Notifying every time would bury the reviewer in
|
||||||
|
// duplicates for a customer they have already been told about; notifying only on the
|
||||||
|
// first crossing would go permanently silent on a customer who keeps offending.
|
||||||
|
if (before / RECURRING_THRESHOLD >= after / RECURRING_THRESHOLD) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final String content = String.format(
|
||||||
|
"%s has triggered %d AML alerts in the last %d days. Review why this customer keeps being flagged.",
|
||||||
|
client.getDisplayName(), after, WINDOW_DAYS);
|
||||||
|
|
||||||
|
this.userNotificationService.notifyUsers(REVIEW_PERMISSION, OBJECT_TYPE, client.getId(), content, EVENT_TYPE, null,
|
||||||
|
client.getOffice() == null ? null : client.getOffice().getId());
|
||||||
|
log.info("Recurring AML activity notification raised for client {} at {} alerts", client.getId(), after);
|
||||||
|
} catch (final RuntimeException e) {
|
||||||
|
// Consistent with AmlDomainServiceImpl: AML observation must never break the transaction
|
||||||
|
// it is watching, and a notification is the least important part of that observation.
|
||||||
|
log.error("Failed to raise recurring AML activity notification for client {}", client.getId(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.apache.fineract.portfolio.aml.data.AmlRecurringAlertData;
|
||||||
|
|
||||||
|
public interface AmlRecurringAlertReadPlatformService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Customers with {@code minAlerts} or more engine alerts inside the last {@code windowDays}.
|
||||||
|
*
|
||||||
|
* @param onlyNeedingReview
|
||||||
|
* when true, hides customers already reviewed at their current alert count
|
||||||
|
*/
|
||||||
|
List<AmlRecurringAlertData> retrieve(int minAlerts, int windowDays, boolean onlyNeedingReview);
|
||||||
|
|
||||||
|
/** Alerts in the window for one customer, used to record a review against the count seen. */
|
||||||
|
int alertCountInWindow(Long clientId, int windowDays);
|
||||||
|
}
|
||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.portfolio.aml.data.AmlAlertData;
|
||||||
|
import org.apache.fineract.portfolio.aml.data.AmlRecurringAlertData;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRecurringReview;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRecurringReviewRepository;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the recurring-alert review queue.
|
||||||
|
*
|
||||||
|
* The alert set is read through {@link AmlAlertReadPlatformService} rather than queried directly, so
|
||||||
|
* the rule-severity resolution lives in exactly one place and a customer's High-risk count here can
|
||||||
|
* never disagree with the Risk Category shown on the alert itself.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public class AmlRecurringAlertReadPlatformServiceImpl implements AmlRecurringAlertReadPlatformService {
|
||||||
|
|
||||||
|
private static final int HIGH_RISK = 3;
|
||||||
|
|
||||||
|
private final AmlAlertReadPlatformService alertReadPlatformService;
|
||||||
|
private final AmlRecurringReviewRepository reviewRepository;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AmlRecurringAlertData> retrieve(final int minAlerts, final int windowDays, final boolean onlyNeedingReview) {
|
||||||
|
final LocalDate windowFrom = LocalDate.now().minusDays(windowDays);
|
||||||
|
final LocalDateTime cutoff = windowFrom.atStartOfDay();
|
||||||
|
|
||||||
|
// Grouped in insertion order of the (already newest-first) alert list, so each customer's
|
||||||
|
// nested alerts stay newest-first without a second sort.
|
||||||
|
final Map<Long, List<AmlAlertData>> byClient = this.alertReadPlatformService.retrieve(null).stream()
|
||||||
|
.filter(a -> a.clientId() != null && a.raisedOn() != null && !a.raisedOn().isBefore(cutoff))
|
||||||
|
.collect(Collectors.groupingBy(AmlAlertData::clientId, LinkedHashMap::new, Collectors.toList()));
|
||||||
|
|
||||||
|
final List<Long> qualifying = byClient.entrySet().stream().filter(e -> e.getValue().size() >= minAlerts)
|
||||||
|
.map(Map.Entry::getKey).toList();
|
||||||
|
if (qualifying.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<Long, ClientSummary> summaries = clientSummaries(qualifying);
|
||||||
|
|
||||||
|
final List<AmlRecurringAlertData> rows = new ArrayList<>();
|
||||||
|
for (final Long clientId : qualifying) {
|
||||||
|
final List<AmlAlertData> alerts = byClient.get(clientId);
|
||||||
|
final AmlRecurringReview lastReview = this.reviewRepository.findByClient_IdOrderByReviewedOnDesc(clientId).stream().findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
// Reviewed at a lower count means new alerts have landed since — the customer has to
|
||||||
|
// come back, otherwise one early review would silence them permanently.
|
||||||
|
final boolean needsReview = lastReview == null || alerts.size() > lastReview.getAlertCountAtReview();
|
||||||
|
if (onlyNeedingReview && !needsReview) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
final ClientSummary summary = summaries.getOrDefault(clientId, new ClientSummary(null, null));
|
||||||
|
rows.add(new AmlRecurringAlertData(clientId, alerts.get(0).clientDisplayName(), summary.accountNo(),
|
||||||
|
summary.riskCategory(), alerts.size(),
|
||||||
|
(int) alerts.stream().filter(a -> a.riskCategory() != null && a.riskCategory() == HIGH_RISK).count(),
|
||||||
|
(int) alerts.stream().map(AmlAlertData::ruleCode).distinct().count(),
|
||||||
|
(int) alerts.stream().filter(a -> "RAISED".equals(a.status()) || "UNDER_REVIEW".equals(a.status())).count(),
|
||||||
|
(int) alerts.stream().filter(a -> "ESCALATED".equals(a.status())).count(),
|
||||||
|
alerts.stream().map(AmlAlertData::amount).filter(x -> x != null).reduce(BigDecimal.ZERO, BigDecimal::add),
|
||||||
|
alerts.stream().map(AmlAlertData::raisedOn).min(Comparator.naturalOrder()).orElse(null),
|
||||||
|
alerts.stream().map(AmlAlertData::raisedOn).max(Comparator.naturalOrder()).orElse(null),
|
||||||
|
alerts.stream().map(AmlAlertData::ruleCode).distinct().sorted().toList(), needsReview,
|
||||||
|
lastReview == null ? null : lastReview.getAlertCountAtReview(),
|
||||||
|
lastReview == null ? null : lastReview.getOutcome().name(),
|
||||||
|
lastReview == null ? null : lastReview.getReviewedBy().getUsername(),
|
||||||
|
lastReview == null ? null : lastReview.getReviewedOn(), lastReview == null ? null : lastReview.getNotes(),
|
||||||
|
windowFrom, alerts));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Worst offenders first; most recent activity breaks ties.
|
||||||
|
rows.sort(Comparator.comparingInt(AmlRecurringAlertData::alertCount).reversed()
|
||||||
|
.thenComparing(AmlRecurringAlertData::lastAlertOn, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int alertCountInWindow(final Long clientId, final int windowDays) {
|
||||||
|
final LocalDateTime cutoff = LocalDate.now().minusDays(windowDays).atStartOfDay();
|
||||||
|
return (int) this.alertReadPlatformService.retrieve(null).stream()
|
||||||
|
.filter(a -> clientId.equals(a.clientId()) && a.raisedOn() != null && !a.raisedOn().isBefore(cutoff)).count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Account number and current KYC risk rating, fetched once for the whole queue. */
|
||||||
|
private Map<Long, ClientSummary> clientSummaries(final List<Long> clientIds) {
|
||||||
|
final String placeholders = clientIds.stream().map(id -> "?").collect(Collectors.joining(","));
|
||||||
|
final String sql = "SELECT c.id AS clientId, c.account_no AS accountNo, k.risk_category AS riskCategory "
|
||||||
|
+ "FROM m_client c LEFT JOIN m_client_kyc k ON k.client_id = c.id WHERE c.id IN (" + placeholders + ")";
|
||||||
|
final Map<Long, ClientSummary> byId = new HashMap<>();
|
||||||
|
this.jdbcTemplate.query(sql, rs -> {
|
||||||
|
byId.put(rs.getLong("clientId"), new ClientSummary(rs.getString("accountNo"),
|
||||||
|
rs.getObject("riskCategory") == null ? null : rs.getInt("riskCategory")));
|
||||||
|
}, clientIds.toArray());
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record ClientSummary(String accountNo, Integer riskCategory) {}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
public interface AmlRecurringAlertWritePlatformService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records a reviewer's judgement on a customer's repeated AML activity, stamping the alert count
|
||||||
|
* the reviewer was looking at so the customer only resurfaces when that count grows.
|
||||||
|
*
|
||||||
|
* @param windowDays
|
||||||
|
* observation window the reviewer had on screen, so the recorded count matches it
|
||||||
|
* @return the id of the stored review
|
||||||
|
*/
|
||||||
|
Long recordReview(Long clientId, String outcome, String notes, int windowDays);
|
||||||
|
}
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.aml.service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRecurringReview;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRecurringReviewOutcome;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRecurringReviewRepository;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.Client;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.ClientRepositoryWrapper;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AmlRecurringAlertWritePlatformServiceImpl implements AmlRecurringAlertWritePlatformService {
|
||||||
|
|
||||||
|
private static final String RESOURCE = "amlrecurringreview";
|
||||||
|
private static final int DEFAULT_WINDOW_DAYS = 90;
|
||||||
|
|
||||||
|
private final AmlRecurringReviewRepository reviewRepository;
|
||||||
|
private final AmlRecurringAlertReadPlatformService readPlatformService;
|
||||||
|
private final ClientRepositoryWrapper clientRepository;
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public Long recordReview(final Long clientId, final String outcome, final String notes, final int windowDays) {
|
||||||
|
final AmlRecurringReviewOutcome parsedOutcome = validate(clientId, outcome, notes);
|
||||||
|
final int window = windowDays > 0 ? windowDays : DEFAULT_WINDOW_DAYS;
|
||||||
|
|
||||||
|
final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);
|
||||||
|
// Counted here rather than taken from the request: a caller-supplied count could be used to
|
||||||
|
// silence a customer at an inflated number they were never actually reviewed at.
|
||||||
|
final int alertCount = this.readPlatformService.alertCountInWindow(clientId, window);
|
||||||
|
|
||||||
|
final AmlRecurringReview review = AmlRecurringReview.record(client, alertCount, parsedOutcome, notes.trim(),
|
||||||
|
this.context.authenticatedUser());
|
||||||
|
return this.reviewRepository.saveAndFlush(review).getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private AmlRecurringReviewOutcome validate(final Long clientId, final String outcome, final String notes) {
|
||||||
|
final List<ApiParameterError> errors = new ArrayList<>();
|
||||||
|
final DataValidatorBuilder validator = new DataValidatorBuilder(errors).resource(RESOURCE);
|
||||||
|
|
||||||
|
validator.reset().parameter("clientId").value(clientId).notNull();
|
||||||
|
validator.reset().parameter("notes").value(notes).notBlank().notExceedingLengthOf(1000);
|
||||||
|
validator.reset().parameter("outcome").value(outcome).notBlank();
|
||||||
|
|
||||||
|
AmlRecurringReviewOutcome parsed = null;
|
||||||
|
if (StringUtils.isNotBlank(outcome)) {
|
||||||
|
for (final AmlRecurringReviewOutcome candidate : AmlRecurringReviewOutcome.values()) {
|
||||||
|
if (candidate.name().equalsIgnoreCase(outcome.trim())) {
|
||||||
|
parsed = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (parsed == null) {
|
||||||
|
validator.reset().parameter("outcome").value(outcome).failWithCode("is.not.supported");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
throw new PlatformApiDataValidationException(errors);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -44,6 +44,7 @@ public class AmlRuleEvaluationServiceImpl implements AmlRuleEvaluationService {
|
|||||||
private final AmlTransactionRuleRepository ruleRepository;
|
private final AmlTransactionRuleRepository ruleRepository;
|
||||||
private final AmlAlertRepository alertRepository;
|
private final AmlAlertRepository alertRepository;
|
||||||
private final ClientKycRepository clientKycRepository;
|
private final ClientKycRepository clientKycRepository;
|
||||||
|
private final AmlRecurringAlertNotificationService recurringAlertNotificationService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<AmlAlert> evaluate(AmlTransactionContext context) {
|
public List<AmlAlert> evaluate(AmlTransactionContext context) {
|
||||||
@@ -59,6 +60,14 @@ public class AmlRuleEvaluationServiceImpl implements AmlRuleEvaluationService {
|
|||||||
raised.add(alertRepository.save(alert));
|
raised.add(alertRepository.save(alert));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Every transaction type funnels through here, so the recurring-behaviour check is done once
|
||||||
|
// in one place rather than repeated in each of the savings / loan / transfer callers. Passing
|
||||||
|
// the batch size lets the service tell a first-time offender from a repeat one without
|
||||||
|
// re-querying what it just wrote.
|
||||||
|
if (!raised.isEmpty()) {
|
||||||
|
recurringAlertNotificationService.onAlertsRaised(context.getClient(), raised.size());
|
||||||
|
}
|
||||||
return raised;
|
return raised;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-576
@@ -1,576 +0,0 @@
|
|||||||
/**
|
|
||||||
* Licensed to the Apache Software Foundation (ASF) under one
|
|
||||||
* or more contributor license agreements. See the NOTICE file
|
|
||||||
* distributed with this work for additional information
|
|
||||||
* regarding copyright ownership. The ASF licenses this file
|
|
||||||
* to you under the Apache License, Version 2.0 (the
|
|
||||||
* "License"); you may not use this file except in compliance
|
|
||||||
* with the License. You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing,
|
|
||||||
* software distributed under the License is distributed on an
|
|
||||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
||||||
* KIND, either express or implied. See the License for the
|
|
||||||
* specific language governing permissions and limitations
|
|
||||||
* under the License.
|
|
||||||
*/
|
|
||||||
package org.apache.fineract.portfolio.clerkwithdrawal.api;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
import com.google.gson.GsonBuilder;
|
|
||||||
import com.google.gson.JsonArray;
|
|
||||||
import com.google.gson.JsonElement;
|
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
|
||||||
import jakarta.ws.rs.Consumes;
|
|
||||||
import jakarta.ws.rs.DefaultValue;
|
|
||||||
import jakarta.ws.rs.GET;
|
|
||||||
import jakarta.ws.rs.NotFoundException;
|
|
||||||
import jakarta.ws.rs.POST;
|
|
||||||
import jakarta.ws.rs.Path;
|
|
||||||
import jakarta.ws.rs.PathParam;
|
|
||||||
import jakarta.ws.rs.Produces;
|
|
||||||
import jakarta.ws.rs.QueryParam;
|
|
||||||
import jakarta.ws.rs.WebApplicationException;
|
|
||||||
import jakarta.ws.rs.core.MediaType;
|
|
||||||
import jakarta.ws.rs.core.Response;
|
|
||||||
import java.sql.Date;
|
|
||||||
import java.sql.Timestamp;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.apache.fineract.commands.domain.CommandWrapper;
|
|
||||||
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
|
||||||
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
|
||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|
||||||
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
|
||||||
import org.apache.fineract.useradministration.domain.AppUser;
|
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Maker-checker closure request workflow for a Share Account, submitted only from the Clerk
|
|
||||||
* Dashboard, on demand once all shares have already been withdrawn. A clerk (maker) submits a
|
|
||||||
* closure request naming the closed date and an optional note; a Bank Manager (checker) approves
|
|
||||||
* it, which server-side executes the real Fineract "close" command against the share account, or
|
|
||||||
* rejects it. Mirrors {@link ClerkShareWithdrawalRequestApiResource} — same maker-checker shape,
|
|
||||||
* adapted for closure (no shares/settlement leg — closing an already-zero-share account is a
|
|
||||||
* status change, not a further redemption).
|
|
||||||
*/
|
|
||||||
@Path("/v1/clerk/share-closure-requests")
|
|
||||||
@Component
|
|
||||||
@Tag(name = "Clerk Share Closure Requests", description = "Maker-checker share account closure workflow for clerk and bank manager.")
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class ClerkShareClosureRequestApiResource {
|
|
||||||
|
|
||||||
private final JdbcTemplate jdbcTemplate;
|
|
||||||
private final FromJsonHelper fromJsonHelper;
|
|
||||||
private final PlatformSecurityContext context;
|
|
||||||
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
|
||||||
private final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
|
|
||||||
|
|
||||||
private static final String[] LIST_COLUMNS = { "id", "share_account_id", "account_no", "client_id", "client_name", "closed_date",
|
|
||||||
"note", "status", "clerk_id", "clerk_name", "clerk_username", "manager_id", "manager_name", "manager_username",
|
|
||||||
"rejection_reason", "activity_log", "submitted_at", "actioned_at" };
|
|
||||||
|
|
||||||
// ── POST /v1/clerk/share-closure-requests ── Clerk submits new request ──────
|
|
||||||
|
|
||||||
@POST
|
|
||||||
@Consumes(MediaType.APPLICATION_JSON)
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
@Transactional
|
|
||||||
public String submit(final String body) {
|
|
||||||
final AppUser currentUser = context.authenticatedUser();
|
|
||||||
final JsonElement root = fromJsonHelper.parse(body);
|
|
||||||
|
|
||||||
final Long shareAccountId = fromJsonHelper.extractLongNamed("shareAccountId", root);
|
|
||||||
final String accountNo = fromJsonHelper.extractStringNamed("accountNo", root);
|
|
||||||
final Long clientId = fromJsonHelper.extractLongNamed("clientId", root);
|
|
||||||
final String clientName = fromJsonHelper.extractStringNamed("clientName", root);
|
|
||||||
final String closedDate = fromJsonHelper.extractStringNamed("closedDate", root);
|
|
||||||
final String note = fromJsonHelper.extractStringNamed("note", root);
|
|
||||||
|
|
||||||
if (shareAccountId == null) {
|
|
||||||
throw apiError(400, "Share account id is required");
|
|
||||||
}
|
|
||||||
if (accountNo == null || accountNo.isBlank()) {
|
|
||||||
throw apiError(400, "Account number is required");
|
|
||||||
}
|
|
||||||
if (closedDate == null || closedDate.isBlank()) {
|
|
||||||
throw apiError(400, "Closed date is required");
|
|
||||||
}
|
|
||||||
if (LocalDate.parse(closedDate.length() >= 10 ? closedDate.substring(0, 10) : closedDate, DateTimeFormatter.ISO_LOCAL_DATE)
|
|
||||||
.isAfter(LocalDate.now(DateUtils.getDateTimeZoneOfTenant()))) {
|
|
||||||
throw apiError(400, "Closed date cannot be in the future");
|
|
||||||
}
|
|
||||||
|
|
||||||
final Map<String, Object> shareAccountRow = jdbcTemplate.queryForList("""
|
|
||||||
SELECT total_approved_shares AS totalApprovedShares, status_enum AS statusEnum
|
|
||||||
FROM m_share_account WHERE id = ?
|
|
||||||
""", shareAccountId).stream().findFirst().orElse(null);
|
|
||||||
if (shareAccountRow == null) {
|
|
||||||
throw apiError(400, "Share account " + shareAccountId + " does not exist");
|
|
||||||
}
|
|
||||||
final long heldShares = shareAccountRow.get("totalApprovedShares") != null
|
|
||||||
? ((Number) shareAccountRow.get("totalApprovedShares")).longValue()
|
|
||||||
: 0L;
|
|
||||||
if (heldShares != 0) {
|
|
||||||
throw apiError(400,
|
|
||||||
"This share account still holds " + heldShares + " share(s) — all shares must be withdrawn before closure can be requested");
|
|
||||||
}
|
|
||||||
final int shareAccountStatus = shareAccountRow.get("statusEnum") != null
|
|
||||||
? ((Number) shareAccountRow.get("statusEnum")).intValue()
|
|
||||||
: -1;
|
|
||||||
if (shareAccountStatus != 300) {
|
|
||||||
throw apiError(400, "Only an Active share account can be closed (current status code: " + shareAccountStatus + ")");
|
|
||||||
}
|
|
||||||
|
|
||||||
final String activityLog = buildActivityLog(null, "SUBMITTED", currentUser.getUsername(), null);
|
|
||||||
|
|
||||||
final Long newId = jdbcTemplate.queryForObject("""
|
|
||||||
INSERT INTO m_clerk_share_closure_request
|
|
||||||
(share_account_id, account_no, client_id, client_name, closed_date, note, status, clerk_id, clerk_name,
|
|
||||||
clerk_username, activity_log, submitted_at)
|
|
||||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
|
|
||||||
RETURNING id
|
|
||||||
""",
|
|
||||||
Long.class, shareAccountId, accountNo, clientId, clientName, Date.valueOf(closedDate.substring(0, 10)), note, "PENDING",
|
|
||||||
currentUser.getId(), currentUser.getDisplayName(), currentUser.getUsername(), activityLog, Timestamp.from(Instant.now()));
|
|
||||||
|
|
||||||
return gson.toJson(Map.of("resourceId", newId, "status", "PENDING"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── GET /v1/clerk/share-closure-requests ── Manager sees all requests ───────
|
|
||||||
|
|
||||||
@GET
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
public String list(@QueryParam("status") @DefaultValue("PENDING") final String status,
|
|
||||||
@QueryParam("offset") @DefaultValue("0") final int offset, @QueryParam("limit") @DefaultValue("20") final int limit,
|
|
||||||
@QueryParam("fromDate") final String fromDate, @QueryParam("toDate") final String toDate) {
|
|
||||||
return queryList("WHERE status = ?", new ArrayList<>(List.of(status)), fromDate, toDate, offset, limit);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── GET /v1/clerk/share-closure-requests/my ── Clerk's own requests ─────────
|
|
||||||
|
|
||||||
@GET
|
|
||||||
@Path("/my")
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
public String myRequests(@QueryParam("status") final String status, @QueryParam("offset") @DefaultValue("0") final int offset,
|
|
||||||
@QueryParam("limit") @DefaultValue("20") final int limit, @QueryParam("fromDate") final String fromDate,
|
|
||||||
@QueryParam("toDate") final String toDate) {
|
|
||||||
final AppUser currentUser = context.authenticatedUser();
|
|
||||||
final StringBuilder where = new StringBuilder("WHERE clerk_id = ?");
|
|
||||||
final List<Object> params = new ArrayList<>(List.of(currentUser.getId()));
|
|
||||||
if (status != null && !status.isBlank()) {
|
|
||||||
where.append(" AND status = ?");
|
|
||||||
params.add(status);
|
|
||||||
}
|
|
||||||
return queryList(where.toString(), params, fromDate, toDate, offset, limit);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String queryList(final String baseWhere, final List<Object> baseParams, final String fromDate, final String toDate,
|
|
||||||
final int offset, final int limit) {
|
|
||||||
final StringBuilder where = new StringBuilder(baseWhere);
|
|
||||||
final List<Object> params = new ArrayList<>(baseParams);
|
|
||||||
if (fromDate != null && !fromDate.isBlank()) {
|
|
||||||
where.append(" AND DATE(submitted_at) >= ?");
|
|
||||||
params.add(Date.valueOf(fromDate));
|
|
||||||
}
|
|
||||||
if (toDate != null && !toDate.isBlank()) {
|
|
||||||
where.append(" AND DATE(submitted_at) <= ?");
|
|
||||||
params.add(Date.valueOf(toDate));
|
|
||||||
}
|
|
||||||
|
|
||||||
final long total = Optional
|
|
||||||
.ofNullable(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM m_clerk_share_closure_request " + where, Long.class,
|
|
||||||
params.toArray()))
|
|
||||||
.orElse(0L);
|
|
||||||
|
|
||||||
final List<Object> pageParams = new ArrayList<>(params);
|
|
||||||
pageParams.add(limit);
|
|
||||||
pageParams.add(offset);
|
|
||||||
|
|
||||||
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
|
||||||
"SELECT " + String.join(", ", LIST_COLUMNS) + " FROM m_clerk_share_closure_request " + where
|
|
||||||
+ " ORDER BY submitted_at DESC LIMIT ? OFFSET ?",
|
|
||||||
pageParams.toArray());
|
|
||||||
|
|
||||||
final JsonObject result = new JsonObject();
|
|
||||||
result.addProperty("totalFilteredRecords", total);
|
|
||||||
result.add("pageItems", gson.toJsonTree(rows));
|
|
||||||
return gson.toJson(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── GET /v1/clerk/share-closure-requests/{id} ── Full detail ────────────────
|
|
||||||
|
|
||||||
@GET
|
|
||||||
@Path("/{id}")
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
public String getById(@PathParam("id") final Long id) {
|
|
||||||
final Map<?, ?> record = loadRecord(id);
|
|
||||||
final Map<String, Object> enriched = new java.util.LinkedHashMap<>();
|
|
||||||
for (final Map.Entry<?, ?> entry : record.entrySet()) {
|
|
||||||
enriched.put(String.valueOf(entry.getKey()), entry.getValue());
|
|
||||||
}
|
|
||||||
final Object clientIdObj = record.get("client_id");
|
|
||||||
final Long clientId = clientIdObj instanceof Number ? ((Number) clientIdObj).longValue() : null;
|
|
||||||
enriched.putAll(loadClientComplianceSummary(clientId));
|
|
||||||
return gson.toJson(enriched);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> loadClientComplianceSummary(final Long clientId) {
|
|
||||||
final Map<String, Object> summary = new java.util.LinkedHashMap<>();
|
|
||||||
if (clientId == null) {
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
final Map<String, Object> kycRow = jdbcTemplate.queryForList("""
|
|
||||||
SELECT kyc_status AS kycStatus, risk_category AS riskCategory FROM m_client_kyc
|
|
||||||
WHERE client_id = ? ORDER BY id DESC LIMIT 1
|
|
||||||
""", clientId).stream().findFirst().orElse(null);
|
|
||||||
final Integer kycStatus = kycRow != null && kycRow.get("kycStatus") != null ? ((Number) kycRow.get("kycStatus")).intValue() : null;
|
|
||||||
final Integer riskCategory = kycRow != null && kycRow.get("riskCategory") != null ? ((Number) kycRow.get("riskCategory")).intValue()
|
|
||||||
: null;
|
|
||||||
final Long openAlerts = jdbcTemplate.queryForObject(
|
|
||||||
"SELECT COUNT(*) FROM m_aml_alert WHERE client_id = ? AND status IN ('RAISED','ESCALATED')", Long.class, clientId);
|
|
||||||
|
|
||||||
summary.put("client_kyc_status_label", kycStatus != null ? kycStatusLabel(kycStatus) : "No KYC record");
|
|
||||||
summary.put("client_kyc_verified", kycStatus != null && kycStatus == 300);
|
|
||||||
summary.put("client_risk_category_label", riskCategory != null ? riskCategoryLabel(riskCategory) : "Not classified");
|
|
||||||
summary.put("client_risk_high", riskCategory != null && riskCategory == 3);
|
|
||||||
summary.put("client_open_aml_alerts", openAlerts != null ? openAlerts : 0L);
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── POST /v1/clerk/share-closure-requests/{id}/validate ── Manager runs live checks ──
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-runs every check against the CURRENT live state before a manager approves closure —
|
|
||||||
* shares could have been re-purchased since submission, a loan could have been linked, or the
|
|
||||||
* client's compliance standing could have changed.
|
|
||||||
*/
|
|
||||||
@POST
|
|
||||||
@Path("/{id}/validate")
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
public String validate(@PathParam("id") final Long id) {
|
|
||||||
final AppUser currentUser = context.authenticatedUser();
|
|
||||||
final Map<?, ?> record = loadRecord(id);
|
|
||||||
final List<Map<String, Object>> checks = new ArrayList<>();
|
|
||||||
|
|
||||||
final Long shareAccountId = ((Number) record.get("share_account_id")).longValue();
|
|
||||||
final Map<String, Object> shareAccountRow = jdbcTemplate.queryForList("""
|
|
||||||
SELECT total_approved_shares AS totalApprovedShares, status_enum AS statusEnum,
|
|
||||||
client_id AS clientId, linked_loan_id AS linkedLoanId
|
|
||||||
FROM m_share_account WHERE id = ?
|
|
||||||
""", shareAccountId).stream().findFirst().orElse(null);
|
|
||||||
|
|
||||||
final long heldShares = shareAccountRow != null && shareAccountRow.get("totalApprovedShares") != null
|
|
||||||
? ((Number) shareAccountRow.get("totalApprovedShares")).longValue()
|
|
||||||
: -1L;
|
|
||||||
checks.add(checkResult("No shares currently held", heldShares == 0, heldShares + " share(s) currently held"));
|
|
||||||
|
|
||||||
final int shareAccountStatus = shareAccountRow != null && shareAccountRow.get("statusEnum") != null
|
|
||||||
? ((Number) shareAccountRow.get("statusEnum")).intValue()
|
|
||||||
: -1;
|
|
||||||
checks.add(checkResult("Share account is Active", shareAccountStatus == 300, shareStatusLabel(shareAccountStatus)));
|
|
||||||
|
|
||||||
final Long clientId = shareAccountRow != null && shareAccountRow.get("clientId") != null
|
|
||||||
? ((Number) shareAccountRow.get("clientId")).longValue()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
// Loan / Tenure / Guarantor checks — mirrors the same checks in
|
|
||||||
// ClerkShareWithdrawalRequestApiResource.validate() and Fineract's own native
|
|
||||||
// ShareAccountDataSerializer.validateAndClose(), which already blocks closure server-side if
|
|
||||||
// the client has an active loan or is an active guarantor.
|
|
||||||
final Long linkedLoanId = shareAccountRow != null && shareAccountRow.get("linkedLoanId") != null
|
|
||||||
? ((Number) shareAccountRow.get("linkedLoanId")).longValue()
|
|
||||||
: null;
|
|
||||||
Map<String, Object> linkedLoanRow = null;
|
|
||||||
if (linkedLoanId != null) {
|
|
||||||
linkedLoanRow = jdbcTemplate.queryForList("""
|
|
||||||
SELECT account_no AS accountNo, loan_status_id AS statusId, expected_maturedon_date AS expectedMaturedOnDate
|
|
||||||
FROM m_loan WHERE id = ?
|
|
||||||
""", linkedLoanId).stream().findFirst().orElse(null);
|
|
||||||
}
|
|
||||||
final Integer linkedLoanStatus = linkedLoanRow != null && linkedLoanRow.get("statusId") != null
|
|
||||||
? ((Number) linkedLoanRow.get("statusId")).intValue()
|
|
||||||
: null;
|
|
||||||
final boolean linkedLoanOutstanding = linkedLoanStatus != null && isLoanStatusOutstanding(linkedLoanStatus);
|
|
||||||
final String loanCheckDetail;
|
|
||||||
if (linkedLoanId == null) {
|
|
||||||
loanCheckDetail = "No loan linked to this share account";
|
|
||||||
} else if (linkedLoanRow == null) {
|
|
||||||
loanCheckDetail = "Loan #" + linkedLoanId + " — record not found";
|
|
||||||
} else {
|
|
||||||
loanCheckDetail = "Loan " + linkedLoanRow.get("accountNo") + " — " + loanStatusLabel(linkedLoanStatus);
|
|
||||||
}
|
|
||||||
checks.add(checkResult("Loan Check — no active loan secured by these shares", linkedLoanId == null || !linkedLoanOutstanding,
|
|
||||||
loanCheckDetail));
|
|
||||||
|
|
||||||
if (clientId != null) {
|
|
||||||
final Long activeLoanCount = jdbcTemplate.queryForObject(
|
|
||||||
"SELECT COUNT(*) FROM m_loan WHERE client_id = ? AND loan_status_id = 300", Long.class, clientId);
|
|
||||||
checks.add(checkResult("Client has no other active loan", activeLoanCount == null || activeLoanCount == 0,
|
|
||||||
activeLoanCount != null && activeLoanCount > 0 ? activeLoanCount + " active loan(s)" : "None"));
|
|
||||||
|
|
||||||
final Long guarantorActiveLoans = jdbcTemplate.queryForObject("""
|
|
||||||
SELECT COUNT(*) FROM m_guarantor g JOIN m_loan l ON l.id = g.loan_id
|
|
||||||
WHERE g.entity_id = ? AND g.type_enum = 1 AND g.is_active = true
|
|
||||||
AND l.loan_status_id IN (300, 303, 304, 700)
|
|
||||||
""", Long.class, clientId);
|
|
||||||
checks.add(checkResult("Guarantor Check — not guaranteeing any active loan",
|
|
||||||
guarantorActiveLoans == null || guarantorActiveLoans == 0,
|
|
||||||
guarantorActiveLoans != null && guarantorActiveLoans > 0 ? "Guarantor on " + guarantorActiveLoans + " active loan(s)"
|
|
||||||
: "None"));
|
|
||||||
|
|
||||||
final Map<String, Object> kycRow = jdbcTemplate.queryForList("""
|
|
||||||
SELECT kyc_status AS kycStatus, risk_category AS riskCategory FROM m_client_kyc
|
|
||||||
WHERE client_id = ? ORDER BY id DESC LIMIT 1
|
|
||||||
""", clientId).stream().findFirst().orElse(null);
|
|
||||||
|
|
||||||
final Integer kycStatus = kycRow != null && kycRow.get("kycStatus") != null ? ((Number) kycRow.get("kycStatus")).intValue() : null;
|
|
||||||
checks.add(checkResult("Client KYC is Verified", kycStatus != null && kycStatus == 300,
|
|
||||||
kycStatus == null ? "No KYC record found" : kycStatusLabel(kycStatus)));
|
|
||||||
|
|
||||||
final Long openAlerts = jdbcTemplate.queryForObject(
|
|
||||||
"SELECT COUNT(*) FROM m_aml_alert WHERE client_id = ? AND status IN ('RAISED','ESCALATED')", Long.class, clientId);
|
|
||||||
checks.add(checkResult("No open AML alerts for this client", openAlerts == null || openAlerts == 0,
|
|
||||||
openAlerts != null && openAlerts > 0 ? openAlerts + " open alert(s)" : "None"));
|
|
||||||
}
|
|
||||||
|
|
||||||
final Long makerId = ((Number) record.get("clerk_id")).longValue();
|
|
||||||
final boolean makerCheckerOk = !makerId.equals(currentUser.getId());
|
|
||||||
checks.add(checkResult("Maker and Checker are different users", makerCheckerOk,
|
|
||||||
makerCheckerOk ? "Confirmed different users" : "You submitted this request — another manager must approve it"));
|
|
||||||
|
|
||||||
final boolean allPassed = checks.stream().allMatch(c -> Boolean.TRUE.equals(c.get("pass")));
|
|
||||||
final JsonObject res = new JsonObject();
|
|
||||||
res.addProperty("allPassed", allPassed);
|
|
||||||
res.add("checks", gson.toJsonTree(checks));
|
|
||||||
return gson.toJson(res);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<String, Object> checkResult(final String label, final boolean pass, final String detail) {
|
|
||||||
final Map<String, Object> result = new java.util.LinkedHashMap<>();
|
|
||||||
result.put("label", label);
|
|
||||||
result.put("pass", pass);
|
|
||||||
result.put("detail", detail);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isLoanStatusOutstanding(final int loanStatusId) {
|
|
||||||
return loanStatusId == 300 || loanStatusId == 303 || loanStatusId == 304 || loanStatusId == 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String loanStatusLabel(final int code) {
|
|
||||||
return switch (code) {
|
|
||||||
case 100 -> "Submitted and Pending Approval";
|
|
||||||
case 200 -> "Approved";
|
|
||||||
case 300 -> "Active";
|
|
||||||
case 303 -> "Transfer in Progress";
|
|
||||||
case 304 -> "Transfer on Hold";
|
|
||||||
case 400 -> "Withdrawn by Client";
|
|
||||||
case 500 -> "Rejected";
|
|
||||||
case 600 -> "Closed (Obligations Met)";
|
|
||||||
case 601 -> "Closed (Written Off)";
|
|
||||||
case 602 -> "Closed (Rescheduled)";
|
|
||||||
case 700 -> "Overpaid";
|
|
||||||
default -> "Unknown (" + code + ")";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private String shareStatusLabel(final int code) {
|
|
||||||
return switch (code) {
|
|
||||||
case 100 -> "Submitted and Pending Approval";
|
|
||||||
case 200 -> "Approved";
|
|
||||||
case 300 -> "Active";
|
|
||||||
case 500 -> "Rejected";
|
|
||||||
case 600 -> "Closed";
|
|
||||||
default -> "Unknown (" + code + ")";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private String kycStatusLabel(final int code) {
|
|
||||||
return switch (code) {
|
|
||||||
case 100 -> "Pending";
|
|
||||||
case 200 -> "In Progress";
|
|
||||||
case 300 -> "Verified";
|
|
||||||
case 400 -> "Rejected";
|
|
||||||
case 500 -> "Expired";
|
|
||||||
default -> "Unknown (" + code + ")";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private String riskCategoryLabel(final int code) {
|
|
||||||
return switch (code) {
|
|
||||||
case 1 -> "Low";
|
|
||||||
case 2 -> "Medium";
|
|
||||||
case 3 -> "High";
|
|
||||||
default -> "Unknown (" + code + ")";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── POST /v1/clerk/share-closure-requests/{id}/approve ── Manager approves ──
|
|
||||||
|
|
||||||
@POST
|
|
||||||
@Path("/{id}/approve")
|
|
||||||
@Consumes(MediaType.APPLICATION_JSON)
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
@Transactional
|
|
||||||
public String approve(@PathParam("id") final Long id, final String body) {
|
|
||||||
final AppUser currentUser = context.authenticatedUser();
|
|
||||||
validateCheckerRole(currentUser);
|
|
||||||
final Map<?, ?> record = loadRecord(id);
|
|
||||||
|
|
||||||
if (!"PENDING".equals(record.get("status"))) {
|
|
||||||
throw apiError(409, "Only PENDING requests can be approved. Current status: " + record.get("status"));
|
|
||||||
}
|
|
||||||
final Long makerId = ((Number) record.get("clerk_id")).longValue();
|
|
||||||
if (makerId.equals(currentUser.getId())) {
|
|
||||||
throw apiError(403,
|
|
||||||
"Maker-checker: you cannot approve a share closure request you submitted yourself. Ask another manager to review it.");
|
|
||||||
}
|
|
||||||
|
|
||||||
final Long shareAccountId = ((Number) record.get("share_account_id")).longValue();
|
|
||||||
final Object closedDateObj = record.get("closed_date");
|
|
||||||
final String note = (String) record.get("note");
|
|
||||||
|
|
||||||
final JsonObject payload = new JsonObject();
|
|
||||||
payload.addProperty("locale", "en");
|
|
||||||
payload.addProperty("dateFormat", "dd MMMM yyyy");
|
|
||||||
payload.addProperty("closedDate", formatForFineract(closedDateObj.toString()));
|
|
||||||
if (note != null && !note.isBlank()) {
|
|
||||||
payload.addProperty("note", note);
|
|
||||||
}
|
|
||||||
|
|
||||||
final CommandWrapper commandRequest = new CommandWrapperBuilder().createAccountCommand("share", shareAccountId, "close")
|
|
||||||
.withJson(payload.toString()).build();
|
|
||||||
commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
|
||||||
|
|
||||||
final String updatedLog = buildActivityLog((String) record.get("activity_log"), "APPROVED", currentUser.getUsername(),
|
|
||||||
"Share account closed");
|
|
||||||
|
|
||||||
final int approvedRows = jdbcTemplate.update("""
|
|
||||||
UPDATE m_clerk_share_closure_request SET
|
|
||||||
status = 'APPROVED', manager_id = ?, manager_name = ?, manager_username = ?,
|
|
||||||
activity_log = ?, actioned_at = ?
|
|
||||||
WHERE id = ? AND status = 'PENDING'
|
|
||||||
""", currentUser.getId(), currentUser.getDisplayName(), currentUser.getUsername(), updatedLog,
|
|
||||||
Timestamp.from(Instant.now()), id);
|
|
||||||
if (approvedRows == 0) {
|
|
||||||
throw apiError(409, "This share closure request was already actioned by another manager.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return gson.toJson(Map.of("resourceId", id, "status", "APPROVED"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── POST /v1/clerk/share-closure-requests/{id}/reject ── Manager rejects ────
|
|
||||||
|
|
||||||
@POST
|
|
||||||
@Path("/{id}/reject")
|
|
||||||
@Consumes(MediaType.APPLICATION_JSON)
|
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
|
||||||
@Transactional
|
|
||||||
public String reject(@PathParam("id") final Long id, final String body) {
|
|
||||||
final AppUser currentUser = context.authenticatedUser();
|
|
||||||
validateCheckerRole(currentUser);
|
|
||||||
final Map<?, ?> record = loadRecord(id);
|
|
||||||
|
|
||||||
if (!"PENDING".equals(record.get("status"))) {
|
|
||||||
throw apiError(409, "Only PENDING requests can be rejected. Current status: " + record.get("status"));
|
|
||||||
}
|
|
||||||
|
|
||||||
final JsonElement root = fromJsonHelper.parse(body != null && !body.isBlank() ? body : "{}");
|
|
||||||
final String reason = fromJsonHelper.extractStringNamed("reason", root);
|
|
||||||
if (reason == null || reason.isBlank()) {
|
|
||||||
throw apiError(400, "Rejection reason is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
final String updatedLog = buildActivityLog((String) record.get("activity_log"), "REJECTED", currentUser.getUsername(), reason);
|
|
||||||
|
|
||||||
final int rejectedRows = jdbcTemplate.update("""
|
|
||||||
UPDATE m_clerk_share_closure_request SET
|
|
||||||
status = 'REJECTED', manager_id = ?, manager_name = ?, manager_username = ?,
|
|
||||||
rejection_reason = ?, activity_log = ?, actioned_at = ?
|
|
||||||
WHERE id = ? AND status = 'PENDING'
|
|
||||||
""", currentUser.getId(), currentUser.getDisplayName(), currentUser.getUsername(), reason, updatedLog,
|
|
||||||
Timestamp.from(Instant.now()), id);
|
|
||||||
if (rejectedRows == 0) {
|
|
||||||
throw apiError(409, "This share closure request was already actioned by another manager.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return gson.toJson(Map.of("resourceId", id, "status", "REJECTED"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateCheckerRole(final AppUser user) {
|
|
||||||
if (user.hasAnyPermission("ALL_FUNCTIONS")) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final boolean isChecker = user.getRoles().stream().map(r -> r.getName() == null ? "" : r.getName().toLowerCase().trim())
|
|
||||||
.anyMatch(n -> n.contains("manager") || n.contains("head cashier"));
|
|
||||||
if (!isChecker) {
|
|
||||||
throw apiError(403, "Only a Bank Manager (or Head Cashier) can approve or reject share closure requests.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Map<?, ?> loadRecord(final Long id) {
|
|
||||||
final List<Map<String, Object>> rows = jdbcTemplate
|
|
||||||
.queryForList("SELECT " + String.join(", ", LIST_COLUMNS) + " FROM m_clerk_share_closure_request WHERE id = ?", id);
|
|
||||||
if (rows.isEmpty()) {
|
|
||||||
throw new NotFoundException("Share closure request not found: " + id);
|
|
||||||
}
|
|
||||||
return rows.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String formatForFineract(final String isoOrTimestamp) {
|
|
||||||
try {
|
|
||||||
final String isoDatePart = isoOrTimestamp.length() >= 10 ? isoOrTimestamp.substring(0, 10) : isoOrTimestamp;
|
|
||||||
final LocalDate ld = LocalDate.parse(isoDatePart, DateTimeFormatter.ISO_LOCAL_DATE);
|
|
||||||
return ld.format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
|
|
||||||
} catch (Exception e) {
|
|
||||||
return LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String buildActivityLog(final String existingJson, final String action, final String username, final String note) {
|
|
||||||
JsonArray log = new JsonArray();
|
|
||||||
if (existingJson != null && !existingJson.isBlank()) {
|
|
||||||
try {
|
|
||||||
log = fromJsonHelper.parse(existingJson).getAsJsonArray();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log = new JsonArray();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final JsonObject entry = new JsonObject();
|
|
||||||
entry.addProperty("timestamp", Instant.now().toString());
|
|
||||||
entry.addProperty("action", action);
|
|
||||||
entry.addProperty("user", username);
|
|
||||||
if (note != null && !note.isBlank()) {
|
|
||||||
entry.addProperty("note", note);
|
|
||||||
}
|
|
||||||
log.add(entry);
|
|
||||||
return gson.toJson(log);
|
|
||||||
}
|
|
||||||
|
|
||||||
private WebApplicationException apiError(final int httpStatus, final String message) {
|
|
||||||
final JsonObject body = new JsonObject();
|
|
||||||
body.addProperty("message", message);
|
|
||||||
body.addProperty("defaultUserMessage", message);
|
|
||||||
body.addProperty("httpStatus", httpStatus);
|
|
||||||
final JsonArray errors = new JsonArray();
|
|
||||||
final JsonObject err = new JsonObject();
|
|
||||||
err.addProperty("defaultUserMessage", message);
|
|
||||||
errors.add(err);
|
|
||||||
body.add("errors", errors);
|
|
||||||
return new WebApplicationException(Response.status(httpStatus).entity(gson.toJson(body)).type(MediaType.APPLICATION_JSON).build());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+22
-49
@@ -634,11 +634,12 @@ public class ClerkShareWithdrawalRequestApiResource {
|
|||||||
throw apiError(409, "This share withdrawal request was already actioned by another manager.");
|
throw apiError(409, "This share withdrawal request was already actioned by another manager.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// If this redemption brought the account's holding to zero, auto-submit a PENDING closure
|
// If this redemption brought the account's holding to zero, close the share account right
|
||||||
// request rather than making the clerk separately open "New Share Closure Request" — a
|
// here in the SAME approval action — no separate "Share Closure Request" maker-checker step.
|
||||||
// manager (any manager other than the maker below) still has to Validate and Approve it,
|
// Safe to do inline (unlike a raw manual "Close" from the account screen) because the
|
||||||
// so the closure maker-checker governance is preserved end to end.
|
// redemption amount itself already went through this same Maker-Checker review; there are no
|
||||||
final Long autoClosureRequestId = autoCreateClosureRequestIfSharesZero(shareAccountId, requestedDateObj.toString(), id, record);
|
// shares left for the native close command to force-redeem without oversight.
|
||||||
|
final boolean accountClosed = closeShareAccountIfSharesZero(shareAccountId, requestedDateObj.toString());
|
||||||
|
|
||||||
final JsonObject res = new JsonObject();
|
final JsonObject res = new JsonObject();
|
||||||
res.addProperty("resourceId", id);
|
res.addProperty("resourceId", id);
|
||||||
@@ -652,61 +653,33 @@ public class ClerkShareWithdrawalRequestApiResource {
|
|||||||
} else {
|
} else {
|
||||||
res.addProperty("settlementWarning", settlementNote);
|
res.addProperty("settlementWarning", settlementNote);
|
||||||
}
|
}
|
||||||
if (autoClosureRequestId != null) {
|
if (accountClosed) {
|
||||||
res.addProperty("autoClosureRequestId", autoClosureRequestId);
|
res.addProperty("accountClosed", true);
|
||||||
}
|
}
|
||||||
return gson.toJson(res);
|
return gson.toJson(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto-submits a PENDING row into m_clerk_share_closure_request when this redemption has just
|
* Closes the share account when this redemption has just brought its holding to zero — the
|
||||||
* brought the share account's holding to zero — the clerk doesn't have to separately open "New
|
* account closes immediately on approval, in the same step as the withdrawal itself, rather than
|
||||||
* Share Closure Request", but a manager still has to review, Validate and Approve it there
|
* needing a separate closure request to be submitted and approved afterwards.
|
||||||
* before the account actually closes, exactly as if the clerk had submitted it by hand. Reuses
|
|
||||||
* the withdrawal request's own maker identity so the manager who reviews the closure (who must
|
|
||||||
* differ from that clerk, same as any other maker-checker check) sees a consistent audit trail.
|
|
||||||
*/
|
*/
|
||||||
private Long autoCreateClosureRequestIfSharesZero(final Long shareAccountId, final String requestedDateStr,
|
private boolean closeShareAccountIfSharesZero(final Long shareAccountId, final String requestedDateStr) {
|
||||||
final Long withdrawalRequestId, final Map<?, ?> withdrawalRecord) {
|
|
||||||
final Long remainingShares = jdbcTemplate.queryForObject("SELECT total_approved_shares FROM m_share_account WHERE id = ?",
|
final Long remainingShares = jdbcTemplate.queryForObject("SELECT total_approved_shares FROM m_share_account WHERE id = ?",
|
||||||
Long.class, shareAccountId);
|
Long.class, shareAccountId);
|
||||||
if (remainingShares == null || remainingShares != 0) {
|
if (remainingShares == null || remainingShares != 0) {
|
||||||
return null;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
final Long existingPending = jdbcTemplate.queryForObject(
|
final JsonObject closePayload = new JsonObject();
|
||||||
"SELECT COUNT(*) FROM m_clerk_share_closure_request WHERE share_account_id = ? AND status = 'PENDING'", Long.class,
|
closePayload.addProperty("locale", "en");
|
||||||
shareAccountId);
|
closePayload.addProperty("dateFormat", "dd MMMM yyyy");
|
||||||
if (existingPending != null && existingPending > 0) {
|
closePayload.addProperty("closedDate", formatForFineract(requestedDateStr));
|
||||||
return null;
|
closePayload.addProperty("note", "Closed automatically — all shares withdrawn on approval of this Share Withdrawal Request.");
|
||||||
}
|
final CommandWrapper closeCommand = new CommandWrapperBuilder().createAccountCommand("share", shareAccountId, "close")
|
||||||
|
.withJson(closePayload.toString()).build();
|
||||||
final Map<String, Object> shareAccountRow = jdbcTemplate
|
commandsSourceWritePlatformService.logCommandSource(closeCommand);
|
||||||
.queryForList("SELECT account_no AS accountNo, client_id AS clientId FROM m_share_account WHERE id = ?", shareAccountId)
|
return true;
|
||||||
.stream().findFirst().orElse(null);
|
|
||||||
if (shareAccountRow == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
final String accountNo = (String) shareAccountRow.get("accountNo");
|
|
||||||
final Long clientId = shareAccountRow.get("clientId") != null ? ((Number) shareAccountRow.get("clientId")).longValue() : null;
|
|
||||||
final String clientName = clientId != null
|
|
||||||
? jdbcTemplate.queryForList("SELECT display_name FROM m_client WHERE id = ?", clientId).stream().findFirst()
|
|
||||||
.map(m -> (String) m.get("display_name")).orElse(null)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
final String note = "Auto-submitted — all shares withdrawn on approval of Share Withdrawal Request #" + withdrawalRequestId;
|
|
||||||
final String activityLog = buildActivityLog(null, "SUBMITTED", "system", note);
|
|
||||||
final String closedDate = requestedDateStr.length() >= 10 ? requestedDateStr.substring(0, 10) : requestedDateStr;
|
|
||||||
|
|
||||||
return jdbcTemplate.queryForObject("""
|
|
||||||
INSERT INTO m_clerk_share_closure_request
|
|
||||||
(share_account_id, account_no, client_id, client_name, closed_date, note, status, clerk_id, clerk_name,
|
|
||||||
clerk_username, activity_log, submitted_at)
|
|
||||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
|
|
||||||
RETURNING id
|
|
||||||
""", Long.class, shareAccountId, accountNo, clientId, clientName, Date.valueOf(closedDate), note, "PENDING",
|
|
||||||
withdrawalRecord.get("clerk_id"), withdrawalRecord.get("clerk_name"), withdrawalRecord.get("clerk_username"), activityLog,
|
|
||||||
Timestamp.from(Instant.now()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private record Settlement(BigDecimal amount, Long savingsTransactionId) {}
|
private record Settlement(BigDecimal amount, Long savingsTransactionId) {}
|
||||||
|
|||||||
+11
-3
@@ -797,7 +797,9 @@ public class ClerkWithdrawalRequestApiResource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensures the token number is unique for today's date among non-rejected requests.
|
* Ensures the token number is unique for today's date among non-rejected requests, checking
|
||||||
|
* both this table and {@code m_share_dividend_claim_request} -- a dividend cash claim's token
|
||||||
|
* is redeemed at the very same Transaction Entry field, so the two pools must never collide.
|
||||||
* {@code excludeId} is set during resubmit to skip the record being edited.
|
* {@code excludeId} is set during resubmit to skip the record being edited.
|
||||||
*/
|
*/
|
||||||
private void validateTokenUniqueToday(final String tokNo, final Long excludeId) {
|
private void validateTokenUniqueToday(final String tokNo, final Long excludeId) {
|
||||||
@@ -810,10 +812,16 @@ public class ClerkWithdrawalRequestApiResource {
|
|||||||
sql.append(" AND id <> ?");
|
sql.append(" AND id <> ?");
|
||||||
params.add(excludeId);
|
params.add(excludeId);
|
||||||
}
|
}
|
||||||
final long count = Optional.ofNullable(
|
final long ownCount = Optional.ofNullable(
|
||||||
jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray())
|
jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray())
|
||||||
).orElse(0L);
|
).orElse(0L);
|
||||||
if (count > 0) {
|
final long otherCount = Optional.ofNullable(
|
||||||
|
jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM m_share_dividend_claim_request "
|
||||||
|
+ "WHERE tok_no = ? AND CAST(submitted_at AS DATE) = CURRENT_DATE AND status <> 'REJECTED'",
|
||||||
|
Long.class, tokNo)
|
||||||
|
).orElse(0L);
|
||||||
|
if (ownCount + otherCount > 0) {
|
||||||
throw apiError(400,
|
throw apiError(400,
|
||||||
"Token number '" + tokNo + "' is already used today. Please enter a different token number.");
|
"Token number '" + tokNo + "' is already used today. Please enter a different token number.");
|
||||||
}
|
}
|
||||||
|
|||||||
+17
@@ -22,6 +22,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
|||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.ws.rs.Consumes;
|
import jakarta.ws.rs.Consumes;
|
||||||
import jakarta.ws.rs.GET;
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
import jakarta.ws.rs.Path;
|
import jakarta.ws.rs.Path;
|
||||||
import jakarta.ws.rs.Produces;
|
import jakarta.ws.rs.Produces;
|
||||||
import jakarta.ws.rs.core.MediaType;
|
import jakarta.ws.rs.core.MediaType;
|
||||||
@@ -30,7 +31,9 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.portfolio.client.data.KycRiskRuleData;
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleData;
|
||||||
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleRequest;
|
||||||
import org.apache.fineract.portfolio.client.service.KycRiskRulesReadPlatformService;
|
import org.apache.fineract.portfolio.client.service.KycRiskRulesReadPlatformService;
|
||||||
|
import org.apache.fineract.portfolio.client.service.KycRiskRulesWritePlatformService;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@Path("/v1/kyc/risk-rules")
|
@Path("/v1/kyc/risk-rules")
|
||||||
@@ -41,6 +44,7 @@ public class KycRiskRulesApiResource {
|
|||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final KycRiskRulesReadPlatformService readPlatformService;
|
private final KycRiskRulesReadPlatformService readPlatformService;
|
||||||
|
private final KycRiskRulesWritePlatformService writePlatformService;
|
||||||
private final DefaultToApiJsonSerializer<KycRiskRuleData> toApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<KycRiskRuleData> toApiJsonSerializer;
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@@ -52,4 +56,17 @@ public class KycRiskRulesApiResource {
|
|||||||
final List<KycRiskRuleData> rules = this.readPlatformService.retrieveAllRules();
|
final List<KycRiskRuleData> rules = this.readPlatformService.retrieveAllRules();
|
||||||
return this.toApiJsonSerializer.serialize(rules);
|
return this.toApiJsonSerializer.serialize(rules);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Add a KYC/AML risk rule",
|
||||||
|
description = "Appends a rule to the catalog. Supplying any transaction band or observation window also "
|
||||||
|
+ "creates the matching live-transaction rule, linked back to the new catalog entry. Returns the "
|
||||||
|
+ "persisted rule in the same shape as the catalog GET.")
|
||||||
|
public String createRiskRule(final KycRiskRuleRequest request) {
|
||||||
|
this.context.authenticatedUser().validateHasUpdatePermission(ClientApiConstants.CLIENT_RESOURCE_NAME);
|
||||||
|
final KycRiskRuleData rule = this.writePlatformService.createRule(request);
|
||||||
|
return this.toApiJsonSerializer.serialize(rule);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-1
@@ -111,12 +111,16 @@ public class ClientContactOtpServiceImpl implements ClientContactOtpService {
|
|||||||
private final SecureRandom secureRandom = new SecureRandom();
|
private final SecureRandom secureRandom = new SecureRandom();
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
private final org.apache.fineract.portfolio.mobilelookup.service.MobileLookupService mobileLookupService;
|
||||||
|
|
||||||
public ClientContactOtpServiceImpl(final OtpLogRepository otpLogRepository, final EmailSenderService emailSenderService,
|
public ClientContactOtpServiceImpl(final OtpLogRepository otpLogRepository, final EmailSenderService emailSenderService,
|
||||||
final EmailTemplateService emailTemplateService) {
|
final EmailTemplateService emailTemplateService,
|
||||||
|
final org.apache.fineract.portfolio.mobilelookup.service.MobileLookupService mobileLookupService) {
|
||||||
this.restTemplate = new RestTemplate();
|
this.restTemplate = new RestTemplate();
|
||||||
this.otpLogRepository = otpLogRepository;
|
this.otpLogRepository = otpLogRepository;
|
||||||
this.emailSenderService = emailSenderService;
|
this.emailSenderService = emailSenderService;
|
||||||
this.emailTemplateService = emailTemplateService;
|
this.emailTemplateService = emailTemplateService;
|
||||||
|
this.mobileLookupService = mobileLookupService;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Generate ─────────────────────────────────────────────────────────────
|
// ── Generate ─────────────────────────────────────────────────────────────
|
||||||
@@ -128,6 +132,18 @@ public class ClientContactOtpServiceImpl implements ClientContactOtpService {
|
|||||||
return OtpGenerateResponse.builder().success(false).message("mobileNumber is required").build();
|
return OtpGenerateResponse.builder().success(false).message("mobileNumber is required").build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A number the DoT flagged may already be in someone else's hands — an MNRL number is one
|
||||||
|
// that was disconnected and can be reassigned. Sending an OTP there hands the fraudster the
|
||||||
|
// credential, so this is refused at the point of dispatch rather than merely warned about
|
||||||
|
// on screen. Only an officer's recorded PROCEEDED decision reopens it.
|
||||||
|
if (!this.mobileLookupService.isMobileNumberUsable(mobileNumber.trim())) {
|
||||||
|
LOG.warn("Refused to send OTP to DIP/MNRL-flagged number {}", OtpDestinationMasker.maskMobile(mobileNumber));
|
||||||
|
return OtpGenerateResponse.builder().success(false)
|
||||||
|
.message("This mobile number is flagged on the DoT Digital Intelligence Platform. "
|
||||||
|
+ "Contact the customer through an alternate channel and obtain a new number.")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
final OtpLog log = new OtpLog();
|
final OtpLog log = new OtpLog();
|
||||||
log.setPurpose(PURPOSE_CLIENT_CONTACT_CHANGE);
|
log.setPurpose(PURPOSE_CLIENT_CONTACT_CHANGE);
|
||||||
log.setProvider(PROVIDER_LINCPAY);
|
log.setProvider(PROVIDER_LINCPAY);
|
||||||
|
|||||||
+4
-3
@@ -46,7 +46,8 @@ public class ClientApiCollectionConstants extends ClientApiConstants {
|
|||||||
protected static final Set<String> CLIENT_NON_PERSON_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
|
protected static final Set<String> CLIENT_NON_PERSON_CREATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList(familyMembers, address, localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName,
|
Arrays.asList(familyMembers, address, localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName,
|
||||||
incorpValidityTillParamName, constitutionIdParamName, mainBusinessLineIdParamName,
|
incorpValidityTillParamName, constitutionIdParamName, mainBusinessLineIdParamName,
|
||||||
authorizedSignatoryParamName, additionalInfoParamName, dateOfRegistrationParamName, datatables));
|
authorizedSignatoryParamName, authorizedSignatoryClientIdsParamName, additionalInfoParamName,
|
||||||
|
dateOfRegistrationParamName, datatables));
|
||||||
|
|
||||||
protected static final Set<String> CLIENT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName,
|
protected static final Set<String> CLIENT_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(localeParamName,
|
||||||
dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, alternateMobileNoParamName, emailAddressParamName, firstnameParamName,
|
dateFormatParamName, accountNoParamName, externalIdParamName, mobileNoParamName, alternateMobileNoParamName, emailAddressParamName, firstnameParamName,
|
||||||
@@ -70,8 +71,8 @@ public class ClientApiCollectionConstants extends ClientApiConstants {
|
|||||||
|
|
||||||
protected static final Set<String> CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
|
protected static final Set<String> CLIENT_NON_PERSON_UPDATE_REQUEST_DATA_PARAMETERS = new HashSet<>(
|
||||||
Arrays.asList(localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName, incorpValidityTillParamName,
|
Arrays.asList(localeParamName, dateFormatParamName, incorpNumberParamName, remarksParamName, incorpValidityTillParamName,
|
||||||
constitutionIdParamName, mainBusinessLineIdParamName, authorizedSignatoryParamName, additionalInfoParamName,
|
constitutionIdParamName, mainBusinessLineIdParamName, authorizedSignatoryParamName,
|
||||||
dateOfRegistrationParamName));
|
authorizedSignatoryClientIdsParamName, additionalInfoParamName, dateOfRegistrationParamName));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* These parameters will match the class level parameters of {@link ClientData}. Where possible, we try to get
|
* These parameters will match the class level parameters of {@link ClientData}. Where possible, we try to get
|
||||||
|
|||||||
+32
-2
@@ -53,6 +53,22 @@ public final class ClientKycApiConstants {
|
|||||||
|
|
||||||
// ── Extended KYC fields ──────────────────────────────────────────────────
|
// ── Extended KYC fields ──────────────────────────────────────────────────
|
||||||
public static final String panAadhaarSeedingStatusParam = "panAadhaarSeedingStatus";
|
public static final String panAadhaarSeedingStatusParam = "panAadhaarSeedingStatus";
|
||||||
|
|
||||||
|
// ── PAN declaration (accepted when the PAN check cannot pass) ─────────────
|
||||||
|
public static final String panDeclarationTakenParam = "panDeclarationTaken";
|
||||||
|
public static final String panDeclarationMismatchFieldsParam = "panDeclarationMismatchFields";
|
||||||
|
public static final String panDeclarationNameOnPanParam = "panDeclarationNameOnPan";
|
||||||
|
public static final String panDeclarationDobOnPanParam = "panDeclarationDobOnPan";
|
||||||
|
public static final String panDeclarationRemarksParam = "panDeclarationRemarks";
|
||||||
|
public static final String panDeclarationTakenOnParam = "panDeclarationTakenOn";
|
||||||
|
|
||||||
|
// ── Aadhaar enrolment receipt (accepted when Aadhaar is not yet issued) ───
|
||||||
|
public static final String aadhaarReceiptTakenParam = "aadhaarReceiptTaken";
|
||||||
|
public static final String aadhaarEnrolmentIdParam = "aadhaarEnrolmentId";
|
||||||
|
public static final String aadhaarEnrolmentDateParam = "aadhaarEnrolmentDate";
|
||||||
|
public static final String aadhaarReceiptRemarksParam = "aadhaarReceiptRemarks";
|
||||||
|
public static final String aadhaarReceiptTakenOnParam = "aadhaarReceiptTakenOn";
|
||||||
|
|
||||||
public static final String enterprisePanParam = "enterprisePan";
|
public static final String enterprisePanParam = "enterprisePan";
|
||||||
public static final String cinNumberParam = "cinNumber";
|
public static final String cinNumberParam = "cinNumber";
|
||||||
public static final String dinNumberParam = "dinNumber";
|
public static final String dinNumberParam = "dinNumber";
|
||||||
@@ -72,6 +88,10 @@ public final class ClientKycApiConstants {
|
|||||||
public static final String accountStatusParam = "accountStatus";
|
public static final String accountStatusParam = "accountStatus";
|
||||||
public static final String freezeReasonParam = "freezeReason";
|
public static final String freezeReasonParam = "freezeReason";
|
||||||
public static final String freezeAuthorityParam = "freezeAuthority";
|
public static final String freezeAuthorityParam = "freezeAuthority";
|
||||||
|
public static final String freezeDateParam = "freezeDate";
|
||||||
|
public static final String freezeAmountParam = "freezeAmount";
|
||||||
|
public static final String unfreezeDateParam = "unfreezeDate";
|
||||||
|
public static final String noDebitDateParam = "noDebitDate";
|
||||||
public static final String form60TypeParam = "form60Type";
|
public static final String form60TypeParam = "form60Type";
|
||||||
public static final String form60DateParam = "form60Date";
|
public static final String form60DateParam = "form60Date";
|
||||||
public static final String form15ApplicableParam = "form15Applicable";
|
public static final String form15ApplicableParam = "form15Applicable";
|
||||||
@@ -90,9 +110,14 @@ public final class ClientKycApiConstants {
|
|||||||
kycDocumentNameParam, kycDocumentNumberParam, kycDocIssueDateParam, kycDocExpiryDateParam,
|
kycDocumentNameParam, kycDocumentNumberParam, kycDocIssueDateParam, kycDocExpiryDateParam,
|
||||||
amlCheckStatusParam, bannedEntityMatchParam, willfulDefaulterParam, ecgcSalFlagParam,
|
amlCheckStatusParam, bannedEntityMatchParam, willfulDefaulterParam, ecgcSalFlagParam,
|
||||||
dormantFlagParam, accountStatusParam, freezeReasonParam, freezeAuthorityParam,
|
dormantFlagParam, accountStatusParam, freezeReasonParam, freezeAuthorityParam,
|
||||||
|
freezeDateParam, freezeAmountParam, unfreezeDateParam, noDebitDateParam,
|
||||||
form60TypeParam, form60DateParam, form15ApplicableParam, form15TypeParam, form15FYParam,
|
form60TypeParam, form60DateParam, form15ApplicableParam, form15TypeParam, form15FYParam,
|
||||||
isExceptionParam, exceptionReasonParam, exceptionResolvedParam, exceptionResolvedOnParam,
|
isExceptionParam, exceptionReasonParam, exceptionResolvedParam, exceptionResolvedOnParam,
|
||||||
panVerifiedParam, aadhaarVerifiedParam, gstinVerifiedParam));
|
panVerifiedParam, aadhaarVerifiedParam, gstinVerifiedParam,
|
||||||
|
panDeclarationTakenParam, panDeclarationMismatchFieldsParam, panDeclarationNameOnPanParam,
|
||||||
|
panDeclarationDobOnPanParam, panDeclarationRemarksParam, panDeclarationTakenOnParam,
|
||||||
|
aadhaarReceiptTakenParam, aadhaarEnrolmentIdParam, aadhaarEnrolmentDateParam,
|
||||||
|
aadhaarReceiptRemarksParam, aadhaarReceiptTakenOnParam));
|
||||||
|
|
||||||
public static final Set<String> UPDATE_REQUEST_PARAMS = new HashSet<>(Arrays.asList(
|
public static final Set<String> UPDATE_REQUEST_PARAMS = new HashSet<>(Arrays.asList(
|
||||||
kycTypeParam, panNumberParam, aadhaarNumberMaskedParam, gstinNumberParam,
|
kycTypeParam, panNumberParam, aadhaarNumberMaskedParam, gstinNumberParam,
|
||||||
@@ -101,9 +126,14 @@ public final class ClientKycApiConstants {
|
|||||||
kycDocumentNameParam, kycDocumentNumberParam, kycDocIssueDateParam, kycDocExpiryDateParam,
|
kycDocumentNameParam, kycDocumentNumberParam, kycDocIssueDateParam, kycDocExpiryDateParam,
|
||||||
amlCheckStatusParam, bannedEntityMatchParam, willfulDefaulterParam, ecgcSalFlagParam,
|
amlCheckStatusParam, bannedEntityMatchParam, willfulDefaulterParam, ecgcSalFlagParam,
|
||||||
dormantFlagParam, accountStatusParam, freezeReasonParam, freezeAuthorityParam,
|
dormantFlagParam, accountStatusParam, freezeReasonParam, freezeAuthorityParam,
|
||||||
|
freezeDateParam, freezeAmountParam, unfreezeDateParam, noDebitDateParam,
|
||||||
form60TypeParam, form60DateParam, form15ApplicableParam, form15TypeParam, form15FYParam,
|
form60TypeParam, form60DateParam, form15ApplicableParam, form15TypeParam, form15FYParam,
|
||||||
isExceptionParam, exceptionReasonParam, exceptionResolvedParam, exceptionResolvedOnParam,
|
isExceptionParam, exceptionReasonParam, exceptionResolvedParam, exceptionResolvedOnParam,
|
||||||
panVerifiedParam, aadhaarVerifiedParam, gstinVerifiedParam));
|
panVerifiedParam, aadhaarVerifiedParam, gstinVerifiedParam,
|
||||||
|
panDeclarationTakenParam, panDeclarationMismatchFieldsParam, panDeclarationNameOnPanParam,
|
||||||
|
panDeclarationDobOnPanParam, panDeclarationRemarksParam, panDeclarationTakenOnParam,
|
||||||
|
aadhaarReceiptTakenParam, aadhaarEnrolmentIdParam, aadhaarEnrolmentDateParam,
|
||||||
|
aadhaarReceiptRemarksParam, aadhaarReceiptTakenOnParam));
|
||||||
|
|
||||||
/** verify command: existing flags + Aadhaar OTP fields for the verify-otp step. */
|
/** verify command: existing flags + Aadhaar OTP fields for the verify-otp step. */
|
||||||
public static final Set<String> VERIFY_REQUEST_PARAMS = new HashSet<>(Arrays.asList(
|
public static final Set<String> VERIFY_REQUEST_PARAMS = new HashSet<>(Arrays.asList(
|
||||||
|
|||||||
+30
@@ -19,6 +19,7 @@
|
|||||||
package org.apache.fineract.portfolio.client.data;
|
package org.apache.fineract.portfolio.client.data;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.math.BigDecimal;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
@@ -52,11 +53,29 @@ public final class ClientKycData {
|
|||||||
private final String panCategory;
|
private final String panCategory;
|
||||||
private final String panStatus;
|
private final String panStatus;
|
||||||
|
|
||||||
|
// ── PAN declaration ───────────────────────────────────────────────────────
|
||||||
|
/** Signed customer declaration accepted in place of a passing PAN check. */
|
||||||
|
private final Boolean panDeclarationTaken;
|
||||||
|
/** "NAME", "DOB", "NAME,DOB", or "NONE" when PAN could not be checked at all. */
|
||||||
|
private final String panDeclarationMismatchFields;
|
||||||
|
private final String panDeclarationNameOnPan;
|
||||||
|
private final LocalDate panDeclarationDobOnPan;
|
||||||
|
private final String panDeclarationRemarks;
|
||||||
|
private final LocalDate panDeclarationTakenOn;
|
||||||
|
|
||||||
// ── Aadhaar ───────────────────────────────────────────────────────────────
|
// ── Aadhaar ───────────────────────────────────────────────────────────────
|
||||||
private final String aadhaarNumberMasked;
|
private final String aadhaarNumberMasked;
|
||||||
private final Boolean aadhaarVerified;
|
private final Boolean aadhaarVerified;
|
||||||
private final LocalDate aadhaarVerifiedOn;
|
private final LocalDate aadhaarVerifiedOn;
|
||||||
|
|
||||||
|
// ── Aadhaar enrolment receipt ─────────────────────────────────────────────
|
||||||
|
/** Enrolment slip accepted for a customer who has applied for Aadhaar but holds none yet. */
|
||||||
|
private final Boolean aadhaarReceiptTaken;
|
||||||
|
private final String aadhaarEnrolmentId;
|
||||||
|
private final LocalDate aadhaarEnrolmentDate;
|
||||||
|
private final String aadhaarReceiptRemarks;
|
||||||
|
private final LocalDate aadhaarReceiptTakenOn;
|
||||||
|
|
||||||
// ── GSTIN ─────────────────────────────────────────────────────────────────
|
// ── GSTIN ─────────────────────────────────────────────────────────────────
|
||||||
private final String gstinNumber;
|
private final String gstinNumber;
|
||||||
private final Boolean gstinVerified;
|
private final Boolean gstinVerified;
|
||||||
@@ -65,7 +84,14 @@ public final class ClientKycData {
|
|||||||
// ── Enterprise / Non-Individual ──────────────────────────────────────────
|
// ── Enterprise / Non-Individual ──────────────────────────────────────────
|
||||||
private final String enterprisePan;
|
private final String enterprisePan;
|
||||||
private final String cinNumber;
|
private final String cinNumber;
|
||||||
|
private final Boolean cinVerified;
|
||||||
|
private final LocalDate cinVerifiedOn;
|
||||||
private final LocalDate incorporationDate;
|
private final LocalDate incorporationDate;
|
||||||
|
// DIN of a director — read back so an entity re-opened for edit can show the verification
|
||||||
|
// already obtained for each authorized signatory instead of asking for it again.
|
||||||
|
private final String dinNumber;
|
||||||
|
private final Boolean dinVerified;
|
||||||
|
private final LocalDate dinVerifiedOn;
|
||||||
|
|
||||||
// ── KYC Document ─────────────────────────────────────────────────────────
|
// ── KYC Document ─────────────────────────────────────────────────────────
|
||||||
private final String kycDocumentName;
|
private final String kycDocumentName;
|
||||||
@@ -84,6 +110,10 @@ public final class ClientKycData {
|
|||||||
private final String accountStatus;
|
private final String accountStatus;
|
||||||
private final String freezeReason;
|
private final String freezeReason;
|
||||||
private final String freezeAuthority;
|
private final String freezeAuthority;
|
||||||
|
private final LocalDate freezeDate;
|
||||||
|
private final BigDecimal freezeAmount;
|
||||||
|
private final LocalDate unfreezeDate;
|
||||||
|
private final LocalDate noDebitDate;
|
||||||
|
|
||||||
// ── Form 60 / Form 15G/15H ───────────────────────────────────────────────
|
// ── Form 60 / Form 15G/15H ───────────────────────────────────────────────
|
||||||
private final String form60Type;
|
private final String form60Type;
|
||||||
|
|||||||
+52
@@ -19,6 +19,7 @@
|
|||||||
package org.apache.fineract.portfolio.client.data;
|
package org.apache.fineract.portfolio.client.data;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.math.BigDecimal;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,6 +52,45 @@ public class ClientKycRequest {
|
|||||||
@Schema(description = "PAN-Aadhaar seeding/linking status", example = "LINKED")
|
@Schema(description = "PAN-Aadhaar seeding/linking status", example = "LINKED")
|
||||||
private String panAadhaarSeedingStatus;
|
private String panAadhaarSeedingStatus;
|
||||||
|
|
||||||
|
@Schema(description = "True when a signed customer declaration has been accepted in place of a passing "
|
||||||
|
+ "PAN check. Suppresses the automatic 'PAN Card Verification Failed' KYC exception.", example = "true")
|
||||||
|
private Boolean panDeclarationTaken;
|
||||||
|
|
||||||
|
@Schema(description = "Which client details differ from the PAN card: NAME, DOB, NAME,DOB, or NONE when "
|
||||||
|
+ "PAN could not be checked at all", example = "NAME")
|
||||||
|
private String panDeclarationMismatchFields;
|
||||||
|
|
||||||
|
@Schema(description = "Name exactly as printed on the physical PAN card", example = "RAJESH KUMAR SHARMA")
|
||||||
|
private String panDeclarationNameOnPan;
|
||||||
|
|
||||||
|
@Schema(description = "Date of birth exactly as printed on the physical PAN card", example = "12 May 1988")
|
||||||
|
private String panDeclarationDobOnPan;
|
||||||
|
|
||||||
|
@Schema(description = "Officer's note on why the mismatch exists and what proof was sighted",
|
||||||
|
example = "Client's PAN carries expanded middle name; passport sighted.")
|
||||||
|
private String panDeclarationRemarks;
|
||||||
|
|
||||||
|
@Schema(description = "Date the declaration was accepted", example = "07 August 2026")
|
||||||
|
private String panDeclarationTakenOn;
|
||||||
|
|
||||||
|
@Schema(description = "True when the customer's Aadhaar enrolment slip has been sighted and recorded, for a "
|
||||||
|
+ "customer who has applied for Aadhaar but does not hold one yet. Suppresses the automatic "
|
||||||
|
+ "'Aadhaar Verification Failed' KYC exception.", example = "true")
|
||||||
|
private Boolean aadhaarReceiptTaken;
|
||||||
|
|
||||||
|
@Schema(description = "28-digit Enrolment ID (EID) printed on the UIDAI enrolment slip",
|
||||||
|
example = "1234/12345/12345 12/05/2026 11:30:15")
|
||||||
|
private String aadhaarEnrolmentId;
|
||||||
|
|
||||||
|
@Schema(description = "Enrolment date printed on the slip", example = "12 May 2026")
|
||||||
|
private String aadhaarEnrolmentDate;
|
||||||
|
|
||||||
|
@Schema(description = "Officer's note on what was sighted", example = "Original UIDAI enrolment slip sighted.")
|
||||||
|
private String aadhaarReceiptRemarks;
|
||||||
|
|
||||||
|
@Schema(description = "Date the receipt was accepted", example = "07 August 2026")
|
||||||
|
private String aadhaarReceiptTakenOn;
|
||||||
|
|
||||||
@Schema(description = "Enterprise PAN (for non-individual clients)", example = "ABCDE1234F")
|
@Schema(description = "Enterprise PAN (for non-individual clients)", example = "ABCDE1234F")
|
||||||
private String enterprisePan;
|
private String enterprisePan;
|
||||||
|
|
||||||
@@ -96,6 +136,18 @@ public class ClientKycRequest {
|
|||||||
@Schema(description = "Authority that ordered the freeze (null if not frozen)")
|
@Schema(description = "Authority that ordered the freeze (null if not frozen)")
|
||||||
private String freezeAuthority;
|
private String freezeAuthority;
|
||||||
|
|
||||||
|
@Schema(description = "Date of account freeze (null if not frozen)")
|
||||||
|
private String freezeDate;
|
||||||
|
|
||||||
|
@Schema(description = "Amount frozen (null if not frozen)")
|
||||||
|
private BigDecimal freezeAmount;
|
||||||
|
|
||||||
|
@Schema(description = "Date the account was unfrozen (null unless accountStatus is UNFREEZE)")
|
||||||
|
private String unfreezeDate;
|
||||||
|
|
||||||
|
@Schema(description = "Date the no-debit restriction takes effect (null unless accountStatus is NO_DEBIT)")
|
||||||
|
private String noDebitDate;
|
||||||
|
|
||||||
@Schema(description = "Form 60 type (FORM_60 for clients without PAN)", example = "FORM_60")
|
@Schema(description = "Form 60 type (FORM_60 for clients without PAN)", example = "FORM_60")
|
||||||
private String form60Type;
|
private String form60Type;
|
||||||
|
|
||||||
|
|||||||
+112
@@ -0,0 +1,112 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.client.data;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request body for {@code POST /v1/kyc/risk-rules}.
|
||||||
|
*
|
||||||
|
* Mirrors the columns the AML Rules Master screen displays. The {@code txn*} fields describe the
|
||||||
|
* live-transaction counterpart of the rule; supplying any of them creates a companion row in
|
||||||
|
* {@code m_aml_transaction_rule} linked back to the new {@code m_client_risk_rule} row. Leave them
|
||||||
|
* all blank for a pure KYC-time profile rule (income / turnover / occupation driven).
|
||||||
|
*/
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class KycRiskRuleRequest {
|
||||||
|
|
||||||
|
@Schema(description = "Rule description shown in the catalog", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
|
private String ruleName;
|
||||||
|
|
||||||
|
@Schema(description = "Reason / criteria text explaining why the rule exists",
|
||||||
|
requiredMode = Schema.RequiredMode.REQUIRED)
|
||||||
|
private String reason;
|
||||||
|
|
||||||
|
@Schema(description = "Risk category the rule assigns: 1 Low, 2 Medium, 3 High",
|
||||||
|
requiredMode = Schema.RequiredMode.REQUIRED, example = "3")
|
||||||
|
private Integer riskCategory;
|
||||||
|
|
||||||
|
@Schema(description = "Position in the catalog. Omit to append after the last existing rule.")
|
||||||
|
private Integer orderPosition;
|
||||||
|
|
||||||
|
@Schema(description = "Legal form the rule is restricted to (1 Person, 2 Entity). Null applies to all.")
|
||||||
|
private Integer legalFormId;
|
||||||
|
|
||||||
|
@Schema(description = "Occupation category code value the rule is restricted to")
|
||||||
|
private Long occupationCategoryCvId;
|
||||||
|
|
||||||
|
@Schema(description = "Occupation code value the rule is restricted to")
|
||||||
|
private Long occupationCvId;
|
||||||
|
|
||||||
|
private BigDecimal minMonthlyIncome;
|
||||||
|
private BigDecimal maxMonthlyIncome;
|
||||||
|
private BigDecimal minAnnualIncome;
|
||||||
|
private BigDecimal maxAnnualIncome;
|
||||||
|
private BigDecimal minAnnualTurnover;
|
||||||
|
private BigDecimal maxAnnualTurnover;
|
||||||
|
|
||||||
|
@Schema(description = "AML check status the rule records", example = "FLAGGED")
|
||||||
|
private String amlCheckStatus;
|
||||||
|
|
||||||
|
@Schema(description = "Banned entity match flag", example = "NO")
|
||||||
|
private String bannedEntityMatch;
|
||||||
|
|
||||||
|
@Schema(description = "Willful defaulter flag", example = "NO")
|
||||||
|
private String willfulDefaulter;
|
||||||
|
|
||||||
|
@Schema(description = "ECGC/SAL flag", example = "NO")
|
||||||
|
private String ecgcSalFlag;
|
||||||
|
|
||||||
|
@Schema(description = "Dormancy flag", example = "ACTIVE")
|
||||||
|
private String dormantFlag;
|
||||||
|
|
||||||
|
@Schema(description = "Lower bound of the transaction band the rule covers (display only)")
|
||||||
|
private BigDecimal txnMinLimitAmount;
|
||||||
|
|
||||||
|
@Schema(description = "Upper bound of the transaction band. Null means the rule is open-ended.")
|
||||||
|
private BigDecimal txnMaxLimitAmount;
|
||||||
|
|
||||||
|
@Schema(description = "Amount at which the rule fires on a live transaction. Defaults to the "
|
||||||
|
+ "lower bound of the band when omitted.")
|
||||||
|
private BigDecimal txnThresholdAmount;
|
||||||
|
|
||||||
|
@Schema(description = "Observation window in days. Omit or 0 for per-transaction.", example = "30")
|
||||||
|
private Integer txnWindowDays;
|
||||||
|
|
||||||
|
@Schema(description = "THRESHOLD | STRUCTURING | VELOCITY. Defaults to THRESHOLD.", example = "THRESHOLD")
|
||||||
|
private String txnRuleType;
|
||||||
|
|
||||||
|
@Schema(description = "SAVINGS | LOAN | TRANSFER | ALL. Defaults to ALL.", example = "ALL")
|
||||||
|
private String txnAppliesTo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the officer has described a live-transaction rule rather than a pure KYC profile
|
||||||
|
* rule, and a companion {@code m_aml_transaction_rule} row is therefore warranted.
|
||||||
|
*/
|
||||||
|
public boolean hasTransactionRule() {
|
||||||
|
return this.txnMinLimitAmount != null || this.txnMaxLimitAmount != null || this.txnThresholdAmount != null
|
||||||
|
|| (this.txnWindowDays != null && this.txnWindowDays > 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-3
@@ -75,6 +75,14 @@ public class ClientNonPerson extends AbstractPersistableCustom<Long> {
|
|||||||
@Column(name = "authorized_signatory", length = 500, nullable = true)
|
@Column(name = "authorized_signatory", length = 500, nullable = true)
|
||||||
private String authorizedSignatory;
|
private String authorizedSignatory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client ids of the signatories named in {@link #authorizedSignatory}, comma separated and in the
|
||||||
|
* same order. Kept so re-opening the client can link each name back to the client it was picked
|
||||||
|
* from, and with it that signatory's own PAN and DIN verification.
|
||||||
|
*/
|
||||||
|
@Column(name = "authorized_signatory_client_ids", length = 500, nullable = true)
|
||||||
|
private String authorizedSignatoryClientIds;
|
||||||
|
|
||||||
@Column(name = "additional_info", length = 500, nullable = true)
|
@Column(name = "additional_info", length = 500, nullable = true)
|
||||||
private String additionalInfo;
|
private String additionalInfo;
|
||||||
|
|
||||||
@@ -99,9 +107,9 @@ public class ClientNonPerson extends AbstractPersistableCustom<Long> {
|
|||||||
|
|
||||||
public static ClientNonPerson createNew(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine,
|
public static ClientNonPerson createNew(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine,
|
||||||
String incorpNumber, LocalDate incorpValidityTill, String remarks, String authorizedSignatory, String additionalInfo,
|
String incorpNumber, LocalDate incorpValidityTill, String remarks, String authorizedSignatory, String additionalInfo,
|
||||||
LocalDate dateOfRegistration) {
|
LocalDate dateOfRegistration, String authorizedSignatoryClientIds) {
|
||||||
return new ClientNonPerson(client, constitution, mainBusinessLine, incorpNumber, incorpValidityTill, remarks, authorizedSignatory,
|
return new ClientNonPerson(client, constitution, mainBusinessLine, incorpNumber, incorpValidityTill, remarks, authorizedSignatory,
|
||||||
additionalInfo, dateOfRegistration);
|
additionalInfo, dateOfRegistration, authorizedSignatoryClientIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ClientNonPerson() {
|
protected ClientNonPerson() {
|
||||||
@@ -110,7 +118,7 @@ public class ClientNonPerson extends AbstractPersistableCustom<Long> {
|
|||||||
|
|
||||||
private ClientNonPerson(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, final String incorpNumber,
|
private ClientNonPerson(final Client client, final CodeValue constitution, final CodeValue mainBusinessLine, final String incorpNumber,
|
||||||
final LocalDate incorpValidityTill, final String remarks, final String authorizedSignatory, final String additionalInfo,
|
final LocalDate incorpValidityTill, final String remarks, final String authorizedSignatory, final String additionalInfo,
|
||||||
final LocalDate dateOfRegistration) {
|
final LocalDate dateOfRegistration, final String authorizedSignatoryClientIds) {
|
||||||
if (client != null) {
|
if (client != null) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
}
|
}
|
||||||
@@ -137,6 +145,10 @@ public class ClientNonPerson extends AbstractPersistableCustom<Long> {
|
|||||||
this.authorizedSignatory = authorizedSignatory.trim();
|
this.authorizedSignatory = authorizedSignatory.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(authorizedSignatoryClientIds)) {
|
||||||
|
this.authorizedSignatoryClientIds = authorizedSignatoryClientIds.trim();
|
||||||
|
}
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(additionalInfo)) {
|
if (StringUtils.isNotBlank(additionalInfo)) {
|
||||||
this.additionalInfo = additionalInfo.trim();
|
this.additionalInfo = additionalInfo.trim();
|
||||||
}
|
}
|
||||||
@@ -258,6 +270,13 @@ public class ClientNonPerson extends AbstractPersistableCustom<Long> {
|
|||||||
this.additionalInfo = StringUtils.defaultIfEmpty(newValue, null);
|
this.additionalInfo = StringUtils.defaultIfEmpty(newValue, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (command.isChangeInStringParameterNamed(ClientApiConstants.authorizedSignatoryClientIdsParamName,
|
||||||
|
this.authorizedSignatoryClientIds)) {
|
||||||
|
final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.authorizedSignatoryClientIdsParamName);
|
||||||
|
actualChanges.put(ClientApiConstants.authorizedSignatoryClientIdsParamName, newValue);
|
||||||
|
this.authorizedSignatoryClientIds = StringUtils.defaultIfEmpty(newValue, null);
|
||||||
|
}
|
||||||
|
|
||||||
if (command.isChangeInLocalDateParameterNamed(ClientApiConstants.dateOfRegistrationParamName, this.dateOfRegistration)) {
|
if (command.isChangeInLocalDateParameterNamed(ClientApiConstants.dateOfRegistrationParamName, this.dateOfRegistration)) {
|
||||||
final String valueAsInput = command.stringValueOfParameterNamed(ClientApiConstants.dateOfRegistrationParamName);
|
final String valueAsInput = command.stringValueOfParameterNamed(ClientApiConstants.dateOfRegistrationParamName);
|
||||||
actualChanges.put(ClientApiConstants.dateOfRegistrationParamName, valueAsInput);
|
actualChanges.put(ClientApiConstants.dateOfRegistrationParamName, valueAsInput);
|
||||||
|
|||||||
+22
-1
@@ -48,7 +48,10 @@ public class KycVerificationResult {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Convenience factory for a failed verification. */
|
/**
|
||||||
|
* The provider answered and rejected the document — an unknown CIN, a name that does not match.
|
||||||
|
* A data problem the officer can act on, not an outage.
|
||||||
|
*/
|
||||||
public static KycVerificationResult failure(final String errorMessage, final String rawResponse) {
|
public static KycVerificationResult failure(final String errorMessage, final String rawResponse) {
|
||||||
return KycVerificationResult.builder()
|
return KycVerificationResult.builder()
|
||||||
.status(Status.FAILURE)
|
.status(Status.FAILURE)
|
||||||
@@ -57,7 +60,25 @@ public class KycVerificationResult {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The provider could not be reached, or answered with something unusable. Nothing was learnt
|
||||||
|
* about the document, so callers should report this as the service being unavailable rather
|
||||||
|
* than as the document having failed its check.
|
||||||
|
*/
|
||||||
|
public static KycVerificationResult error(final String errorMessage, final String rawResponse) {
|
||||||
|
return KycVerificationResult.builder()
|
||||||
|
.status(Status.ERROR)
|
||||||
|
.errorMessage(errorMessage)
|
||||||
|
.rawResponse(rawResponse)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isSuccess() {
|
public boolean isSuccess() {
|
||||||
return Status.SUCCESS == this.status;
|
return Status.SUCCESS == this.status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Distinguishes an unreachable provider from one that answered with a rejection. */
|
||||||
|
public boolean isServiceError() {
|
||||||
|
return Status.ERROR == this.status;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-3
@@ -322,7 +322,9 @@ public class LincPayKycVerificationServiceImpl implements KycVerificationService
|
|||||||
final JsonObject response = parseJson(rawResponse);
|
final JsonObject response = parseJson(rawResponse);
|
||||||
|
|
||||||
if (response == null) {
|
if (response == null) {
|
||||||
return KycVerificationResult.failure(
|
// Unparseable body: nothing was learnt about the CIN, so this is the provider
|
||||||
|
// misbehaving rather than the CIN being bad.
|
||||||
|
return KycVerificationResult.error(
|
||||||
"CIN verification failed — vendor returned non-JSON: " + vendorBodySnippet(rawResponse),
|
"CIN verification failed — vendor returned non-JSON: " + vendorBodySnippet(rawResponse),
|
||||||
rawResponse);
|
rawResponse);
|
||||||
}
|
}
|
||||||
@@ -338,12 +340,12 @@ public class LincPayKycVerificationServiceImpl implements KycVerificationService
|
|||||||
} catch (final HttpClientErrorException | HttpServerErrorException e) {
|
} catch (final HttpClientErrorException | HttpServerErrorException e) {
|
||||||
LOG.error("LincPay CIN validation HTTP error for CIN {}: {} {}", cinNumber,
|
LOG.error("LincPay CIN validation HTTP error for CIN {}: {} {}", cinNumber,
|
||||||
e.getStatusCode(), e.getResponseBodyAsString());
|
e.getStatusCode(), e.getResponseBodyAsString());
|
||||||
return KycVerificationResult.failure(
|
return KycVerificationResult.error(
|
||||||
"CIN verification failed (HTTP " + e.getStatusCode() + "): "
|
"CIN verification failed (HTTP " + e.getStatusCode() + "): "
|
||||||
+ e.getResponseBodyAsString(), null);
|
+ e.getResponseBodyAsString(), null);
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
LOG.error("LincPay CIN validation unexpected error for CIN: {}", cinNumber, e);
|
LOG.error("LincPay CIN validation unexpected error for CIN: {}", cinNumber, e);
|
||||||
return KycVerificationResult.failure("CIN verification failed: " + e.getMessage(), null);
|
return KycVerificationResult.error("CIN verification failed: " + e.getMessage(), null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-1
@@ -34,7 +34,7 @@ import org.mapstruct.Mapper;
|
|||||||
import org.mapstruct.Mapping;
|
import org.mapstruct.Mapping;
|
||||||
import org.mapstruct.MappingTarget;
|
import org.mapstruct.MappingTarget;
|
||||||
import org.mapstruct.Named;
|
import org.mapstruct.Named;
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
|
|
||||||
@Mapper(config = MapstructMapperConfig.class)
|
@Mapper(config = MapstructMapperConfig.class)
|
||||||
public interface ClientMapper {
|
public interface ClientMapper {
|
||||||
@@ -107,6 +107,11 @@ public interface ClientMapper {
|
|||||||
@Mapping(target = "legalFormId", ignore = true)
|
@Mapping(target = "legalFormId", ignore = true)
|
||||||
@Mapping(target = "clientCollateralManagements", ignore = true)
|
@Mapping(target = "clientCollateralManagements", ignore = true)
|
||||||
@Mapping(target = "groups", ignore = true)
|
@Mapping(target = "groups", ignore = true)
|
||||||
|
// Resolved from the latest DIP/MNRL lookup after mapping, not from a Client column — see
|
||||||
|
// ClientReadPlatformServiceImpl#retrieveOne.
|
||||||
|
@Mapping(target = "dipLiveStatus", ignore = true)
|
||||||
|
@Mapping(target = "alternateDipLiveStatus", ignore = true)
|
||||||
|
@Mapping(target = "sanctionsAlertStatus", ignore = true)
|
||||||
ClientData map(Client source);
|
ClientData map(Client source);
|
||||||
|
|
||||||
@Named("clientTypeCode")
|
@Named("clientTypeCode")
|
||||||
|
|||||||
+21
-58
@@ -18,79 +18,42 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.portfolio.client.service;
|
package org.apache.fineract.portfolio.client.service;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.fineract.portfolio.client.domain.Client;
|
import org.apache.fineract.portfolio.client.domain.Client;
|
||||||
import org.apache.fineract.portfolio.client.domain.ClientRepository;
|
|
||||||
import org.apache.fineract.portfolio.client.domain.LegalForm;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates CIF numbers in the format <code>TTYYYYNNNNNN</code>:
|
* Generates CIF numbers in the format <code>CIF</code> followed by the client's id
|
||||||
* <ul>
|
* zero-padded to 10 digits — e.g. client 123 → <code>CIF0000000123</code>.
|
||||||
* <li><b>TT</b> — Customer type code:
|
|
||||||
* <code>11</code> Individual, <code>22</code> Corporate, <code>33</code> Minor, <code>44</code> Staff.
|
|
||||||
* Priority order when multiple flags overlap: <em>Staff > Minor > Corporate > Individual</em>.</li>
|
|
||||||
* <li><b>YYYY</b> — Year the client was submitted (4 digits).</li>
|
|
||||||
* <li><b>NNNNNN</b> — Zero-padded 6-digit sequence within the (type, year) bucket.</li>
|
|
||||||
* </ul>
|
|
||||||
*
|
*
|
||||||
* Example: an Individual client created in 2026 → <code>1120260000001</code>.
|
* <p>
|
||||||
* The generator handles concurrent inserts by retrying on uniqueness collisions
|
* Uniqueness is structural rather than probabilistic: <code>m_client.id</code> is a single sequence
|
||||||
* (the caller's outer save is what actually triggers the unique constraint).
|
* shared by every office, so two clients booked concurrently at different branches can never derive
|
||||||
|
* the same CIF. That makes the number globally unique across the whole institution, not just within
|
||||||
|
* the branch that created it, and removes the read-then-write race a "count existing + 1" scheme has.
|
||||||
|
* The <code>cif_number_unique</code> index on m_client remains the backstop.
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* The client must already be persisted when this is called, since the id is the source of the number.
|
||||||
|
* </p>
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class CifNumberGenerator {
|
public class CifNumberGenerator {
|
||||||
|
|
||||||
private static final String TYPE_INDIVIDUAL = "11";
|
private static final String CIF_PREFIX = "CIF";
|
||||||
private static final String TYPE_CORPORATE = "22";
|
|
||||||
private static final String TYPE_MINOR = "33";
|
|
||||||
private static final String TYPE_STAFF = "44";
|
|
||||||
|
|
||||||
private static final int SEQUENCE_WIDTH = 6;
|
/** 10 digits keeps the value inside m_client.cif_number's varchar(20) for any realistic id. */
|
||||||
private static final int MAX_COLLISION_RETRIES = 5;
|
private static final int SEQUENCE_WIDTH = 10;
|
||||||
|
|
||||||
private final ClientRepository clientRepository;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate the next CIF number for the given client. Caller is responsible for persisting.
|
* Generate the CIF number for the given client. Caller is responsible for persisting.
|
||||||
*/
|
*/
|
||||||
public String generate(final Client client) {
|
public String generate(final Client client) {
|
||||||
final String typeCode = resolveTypeCode(client);
|
final Long clientId = client.getId();
|
||||||
final int year = resolveYear(client);
|
if (clientId == null) {
|
||||||
final String prefix = typeCode + year;
|
throw new IllegalArgumentException("Cannot generate a CIF number before the client has been persisted");
|
||||||
|
|
||||||
long nextSequence = clientRepository.countByCifNumberPrefix(prefix) + 1;
|
|
||||||
for (int attempt = 0; attempt < MAX_COLLISION_RETRIES; attempt++) {
|
|
||||||
final String candidate = prefix + StringUtils.leftPad(Long.toString(nextSequence), SEQUENCE_WIDTH, '0');
|
|
||||||
if (clientRepository.countByCifNumberPrefix(candidate) == 0) {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
nextSequence++;
|
|
||||||
}
|
}
|
||||||
// Last resort: append client id to guarantee uniqueness if every attempt collided
|
return CIF_PREFIX + StringUtils.leftPad(Long.toString(clientId), SEQUENCE_WIDTH, '0');
|
||||||
return prefix + StringUtils.leftPad(Long.toString(client.getId() == null ? nextSequence : client.getId()), SEQUENCE_WIDTH, '0');
|
|
||||||
}
|
|
||||||
|
|
||||||
private String resolveTypeCode(final Client client) {
|
|
||||||
if (client.isStaff()) {
|
|
||||||
return TYPE_STAFF;
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(client.getIsMinor())) {
|
|
||||||
return TYPE_MINOR;
|
|
||||||
}
|
|
||||||
final Integer legalForm = client.getLegalForm();
|
|
||||||
if (legalForm != null && LegalForm.fromInt(legalForm).isEntity()) {
|
|
||||||
return TYPE_CORPORATE;
|
|
||||||
}
|
|
||||||
return TYPE_INDIVIDUAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int resolveYear(final Client client) {
|
|
||||||
final LocalDate submittedOn = client.getSubmittedOnDate();
|
|
||||||
return (submittedOn != null ? submittedOn : LocalDate.now(DateUtils.getDateTimeZoneOfTenant())).getYear();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
@@ -85,15 +85,31 @@ public class ClientKycReadPlatformServiceImpl implements ClientKycReadPlatformSe
|
|||||||
.panAadhaarSeedingStatus(kyc.getPanAadhaarSeedingStatus())
|
.panAadhaarSeedingStatus(kyc.getPanAadhaarSeedingStatus())
|
||||||
.panCategory(kyc.getPanCategory())
|
.panCategory(kyc.getPanCategory())
|
||||||
.panStatus(kyc.getPanStatus())
|
.panStatus(kyc.getPanStatus())
|
||||||
|
.panDeclarationTaken(kyc.getPanDeclarationTaken())
|
||||||
|
.panDeclarationMismatchFields(kyc.getPanDeclarationMismatchFields())
|
||||||
|
.panDeclarationNameOnPan(kyc.getPanDeclarationNameOnPan())
|
||||||
|
.panDeclarationDobOnPan(kyc.getPanDeclarationDobOnPan())
|
||||||
|
.panDeclarationRemarks(kyc.getPanDeclarationRemarks())
|
||||||
|
.panDeclarationTakenOn(kyc.getPanDeclarationTakenOn())
|
||||||
.aadhaarNumberMasked(kyc.getAadhaarNumberMasked())
|
.aadhaarNumberMasked(kyc.getAadhaarNumberMasked())
|
||||||
.aadhaarVerified(kyc.isAadhaarVerified())
|
.aadhaarVerified(kyc.isAadhaarVerified())
|
||||||
.aadhaarVerifiedOn(kyc.getAadhaarVerifiedOn())
|
.aadhaarVerifiedOn(kyc.getAadhaarVerifiedOn())
|
||||||
|
.aadhaarReceiptTaken(kyc.getAadhaarReceiptTaken())
|
||||||
|
.aadhaarEnrolmentId(kyc.getAadhaarEnrolmentId())
|
||||||
|
.aadhaarEnrolmentDate(kyc.getAadhaarEnrolmentDate())
|
||||||
|
.aadhaarReceiptRemarks(kyc.getAadhaarReceiptRemarks())
|
||||||
|
.aadhaarReceiptTakenOn(kyc.getAadhaarReceiptTakenOn())
|
||||||
.gstinNumber(kyc.getGstinNumber())
|
.gstinNumber(kyc.getGstinNumber())
|
||||||
.gstinVerified(kyc.isGstinVerified())
|
.gstinVerified(kyc.isGstinVerified())
|
||||||
.gstinVerifiedOn(kyc.getGstinVerifiedOn())
|
.gstinVerifiedOn(kyc.getGstinVerifiedOn())
|
||||||
.enterprisePan(kyc.getEnterprisePan())
|
.enterprisePan(kyc.getEnterprisePan())
|
||||||
.cinNumber(kyc.getCinNumber())
|
.cinNumber(kyc.getCinNumber())
|
||||||
|
.cinVerified(kyc.isCinVerified())
|
||||||
|
.cinVerifiedOn(kyc.getCinVerifiedOn())
|
||||||
.incorporationDate(kyc.getIncorporationDate())
|
.incorporationDate(kyc.getIncorporationDate())
|
||||||
|
.dinNumber(kyc.getDinNumber())
|
||||||
|
.dinVerified(kyc.isDinVerified())
|
||||||
|
.dinVerifiedOn(kyc.getDinVerifiedOn())
|
||||||
.kycDocumentName(kyc.getKycDocumentName())
|
.kycDocumentName(kyc.getKycDocumentName())
|
||||||
.kycDocumentNumber(kyc.getKycDocumentNumber())
|
.kycDocumentNumber(kyc.getKycDocumentNumber())
|
||||||
.kycDocIssueDate(kyc.getKycDocIssueDate())
|
.kycDocIssueDate(kyc.getKycDocIssueDate())
|
||||||
@@ -106,6 +122,10 @@ public class ClientKycReadPlatformServiceImpl implements ClientKycReadPlatformSe
|
|||||||
.accountStatus(kyc.getAccountStatus())
|
.accountStatus(kyc.getAccountStatus())
|
||||||
.freezeReason(kyc.getFreezeReason())
|
.freezeReason(kyc.getFreezeReason())
|
||||||
.freezeAuthority(kyc.getFreezeAuthority())
|
.freezeAuthority(kyc.getFreezeAuthority())
|
||||||
|
.freezeDate(kyc.getFreezeDate())
|
||||||
|
.freezeAmount(kyc.getFreezeAmount())
|
||||||
|
.unfreezeDate(kyc.getUnfreezeDate())
|
||||||
|
.noDebitDate(kyc.getNoDebitDate())
|
||||||
.form60Type(kyc.getForm60Type())
|
.form60Type(kyc.getForm60Type())
|
||||||
.form60Date(kyc.getForm60Date())
|
.form60Date(kyc.getForm60Date())
|
||||||
.form15Applicable(kyc.getForm15Applicable())
|
.form15Applicable(kyc.getForm15Applicable())
|
||||||
|
|||||||
+64
-57
@@ -93,9 +93,7 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
kycCommand.validateForInitiate(Boolean.TRUE.equals(clientForValidation.getIsMinor()));
|
kycCommand.validateForInitiate(Boolean.TRUE.equals(clientForValidation.getIsMinor()));
|
||||||
|
|
||||||
// CIN / GSTIN are only applicable for NON_INDIVIDUAL clients
|
// CIN / GSTIN are only applicable for NON_INDIVIDUAL clients
|
||||||
final Integer kycTypeOnInitiate = command.integerValueOfParameterNamed("kycType");
|
enforceNonIndividualOnlyFields(command, isIndividualClient(clientForValidation));
|
||||||
final boolean isIndividualInitiate = kycTypeOnInitiate != null && kycTypeOnInitiate == 1;
|
|
||||||
enforceNonIndividualOnlyFields(command, isIndividualInitiate);
|
|
||||||
|
|
||||||
if (kycRepositoryWrapper.existsByClientId(clientId)) {
|
if (kycRepositoryWrapper.existsByClientId(clientId)) {
|
||||||
LOG.info("KYC record already exists for client {}. Returning existing record.", clientId);
|
LOG.info("KYC record already exists for client {}. Returning existing record.", clientId);
|
||||||
@@ -140,45 +138,30 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
final ClientKyc kyc = kycRepositoryWrapper.findOneWithNotFoundDetection(kycId);
|
final ClientKyc kyc = kycRepositoryWrapper.findOneWithNotFoundDetection(kycId);
|
||||||
|
|
||||||
// CIN / GSTIN are only applicable for NON_INDIVIDUAL clients
|
// CIN / GSTIN are only applicable for NON_INDIVIDUAL clients
|
||||||
final boolean isIndividualExisting = kyc.getKycType() != null && kyc.getKycType().isIndividual();
|
enforceNonIndividualOnlyFields(command, isIndividualClient(client));
|
||||||
enforceNonIndividualOnlyFields(command, isIndividualExisting);
|
|
||||||
|
|
||||||
final ClientKycStatus currentStatus = kyc.getKycStatus();
|
final ClientKycStatus currentStatus = kyc.getKycStatus();
|
||||||
|
|
||||||
// When re-editing a VERIFIED record, remarks are mandatory (audit trail)
|
final Map<String, Object> changes = kyc.update(command);
|
||||||
if (currentStatus.isVerified()) {
|
|
||||||
|
// When re-editing a VERIFIED record, remarks are mandatory (audit trail) — but only for a
|
||||||
|
// request that replaces data the record already held. A non-individual KYC auto-verifies as
|
||||||
|
// soon as PAN and GSTIN pass, which lands part-way through the create wizard, and the
|
||||||
|
// officer still has to save the KYC document details afterwards; filling in fields that were
|
||||||
|
// empty is completing the record, not altering it, and must not demand a justification.
|
||||||
|
// Thrown before the save below, and this method is @Transactional, so the in-memory
|
||||||
|
// mutations from update() are rolled back.
|
||||||
|
if (currentStatus.isVerified() && !kyc.getFieldsOverwrittenByLastUpdate().isEmpty()) {
|
||||||
final String remarks = command.stringValueOfParameterNamed("remarks");
|
final String remarks = command.stringValueOfParameterNamed("remarks");
|
||||||
if (StringUtils.isBlank(remarks)) {
|
if (StringUtils.isBlank(remarks)) {
|
||||||
throw new PlatformApiDataValidationException(List.of(ApiParameterError.parameterError(
|
throw new PlatformApiDataValidationException(List.of(ApiParameterError.parameterError(
|
||||||
"error.msg.client.kyc.remarks.required.for.reverification",
|
"error.msg.client.kyc.remarks.required.for.reverification",
|
||||||
"Remarks are mandatory when updating a verified KYC record.", "remarks")));
|
"Remarks are mandatory when changing data already recorded on a verified KYC record.",
|
||||||
|
"remarks")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final Map<String, Object> changes = kyc.update(command);
|
|
||||||
|
|
||||||
if (!changes.isEmpty()) {
|
if (!changes.isEmpty()) {
|
||||||
// Only changes to identifier fields invalidate prior verifications. A remarks edit or
|
|
||||||
// risk-category bump does not — keeping it as VERIFIED is the correct end state.
|
|
||||||
final boolean panChanged = changes.containsKey("panNumber");
|
|
||||||
final boolean aadhaarChanged = changes.containsKey("aadhaarNumberMasked");
|
|
||||||
final boolean gstinChanged = changes.containsKey("gstinNumber");
|
|
||||||
final boolean verificationAffected = panChanged || aadhaarChanged || gstinChanged;
|
|
||||||
|
|
||||||
if (panChanged && currentStatus.isVerified()) {
|
|
||||||
kyc.resetPanVerification();
|
|
||||||
changes.put("panVerified", false);
|
|
||||||
}
|
|
||||||
if (verificationAffected && !kyc.getKycStatus().isInProgress()) {
|
|
||||||
kyc.markInProgress();
|
|
||||||
changes.put("kycStatus", ClientKycStatus.IN_PROGRESS.getValue());
|
|
||||||
}
|
|
||||||
// Re-check: if the change didn't actually invalidate anything, snap back to VERIFIED.
|
|
||||||
// Handles the common case of editing remarks / risk on a fully-verified KYC.
|
|
||||||
kyc.tryAutoVerify();
|
|
||||||
if (kyc.getKycStatus().isVerified()) {
|
|
||||||
changes.put("kycStatus", ClientKycStatus.VERIFIED.getValue());
|
|
||||||
}
|
|
||||||
kycRepositoryWrapper.saveAndFlush(kyc);
|
kycRepositoryWrapper.saveAndFlush(kyc);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,7 +339,11 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
// firstname/middlename/lastname ← individual columns; NULL for entities
|
// firstname/middlename/lastname ← individual columns; NULL for entities
|
||||||
// fullname ← the entity name lives here
|
// fullname ← the entity name lives here
|
||||||
// dateOfBirth ← only set for individuals
|
// dateOfBirth ← only set for individuals
|
||||||
// ClientNonPerson.dateOfRegistration ← the incorporation date for entities
|
// ClientKyc.incorporationDate ← the incorporation date for entities, captured on the
|
||||||
|
// KYC step next to the entity PAN it is verified against
|
||||||
|
// ClientNonPerson.dateOfRegistration ← where that date lived for clients created before
|
||||||
|
// the field moved to the KYC step; read as a fallback
|
||||||
|
// so those older entities still verify.
|
||||||
// LincPay's /validate-pan rejects empty/missing DOB with a PLAIN-TEXT "Invalid DOB format"
|
// LincPay's /validate-pan rejects empty/missing DOB with a PLAIN-TEXT "Invalid DOB format"
|
||||||
// response (not JSON) — Gson then throws MalformedJsonException at column 10. Build the
|
// response (not JSON) — Gson then throws MalformedJsonException at column 10. Build the
|
||||||
// right (name, dob) pair per legal form so we always send LincPay the data it expects.
|
// right (name, dob) pair per legal form so we always send LincPay the data it expects.
|
||||||
@@ -364,10 +351,13 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
final String dob;
|
final String dob;
|
||||||
if (client.getLegalForm() != null && LegalForm.fromInt(client.getLegalForm()).isEntity()) {
|
if (client.getLegalForm() != null && LegalForm.fromInt(client.getLegalForm()).isEntity()) {
|
||||||
clientNameForPan = client.getFullname() != null ? client.getFullname().trim() : "";
|
clientNameForPan = client.getFullname() != null ? client.getFullname().trim() : "";
|
||||||
final ClientNonPerson np = this.clientNonPersonRepository.findOneByClientId(client.getId());
|
java.time.LocalDate incorpDate = kyc.getIncorporationDate();
|
||||||
final java.time.LocalDate regDate = (np != null) ? np.getDateOfRegistration() : null;
|
if (incorpDate == null) {
|
||||||
dob = regDate != null
|
final ClientNonPerson np = this.clientNonPersonRepository.findOneByClientId(client.getId());
|
||||||
? regDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
|
incorpDate = (np != null) ? np.getDateOfRegistration() : null;
|
||||||
|
}
|
||||||
|
dob = incorpDate != null
|
||||||
|
? incorpDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
|
||||||
: null;
|
: null;
|
||||||
} else {
|
} else {
|
||||||
dob = client.dateOfBirth() != null
|
dob = client.dateOfBirth() != null
|
||||||
@@ -542,15 +532,36 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
"CIN number is not set on this KYC record. Update the KYC record first.");
|
"CIN number is not set on this KYC record. Update the KYC record first.");
|
||||||
}
|
}
|
||||||
|
|
||||||
final KycVerificationResult result = kycVerificationService.verifyCin(kyc.getCinNumber());
|
final String cin = kyc.getCinNumber().toUpperCase().trim();
|
||||||
|
if (!cin.matches(ClientKycApiConstants.CIN_REGEX)) {
|
||||||
|
throw new PlatformApiDataValidationException(List.of(ApiParameterError.parameterError(
|
||||||
|
"error.msg.client.kyc.cin.invalid.format",
|
||||||
|
"Invalid CIN format. Expected 21 characters, e.g. L17110MH1973PLC019786.",
|
||||||
|
ClientKycApiConstants.cinNumberParam)));
|
||||||
|
}
|
||||||
|
|
||||||
if (!result.isSuccess()) {
|
final KycVerificationResult result = kycVerificationService.verifyCin(cin);
|
||||||
|
|
||||||
|
if (!result.isSuccess() && result.isServiceError()) {
|
||||||
throw new PlatformServiceUnavailableException(
|
throw new PlatformServiceUnavailableException(
|
||||||
"error.msg.client.kyc.cin.verification.failed",
|
"error.msg.client.kyc.cin.verification.failed",
|
||||||
"CIN verification failed: " + result.getErrorMessage(),
|
"CIN verification failed: " + result.getErrorMessage(),
|
||||||
result.getErrorMessage());
|
result.getErrorMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A CIN whose structure is valid is accepted even when the registry lookup returns no match.
|
||||||
|
// The provider's company endpoint answers "Not Found" for every CIN put to it, including
|
||||||
|
// ones that are demonstrably real, so a negative from it says nothing about the company and
|
||||||
|
// cannot be allowed to block onboarding. The distinction is not lost: whether the registry
|
||||||
|
// actually confirmed the company is recorded in the response and in the log below, and the
|
||||||
|
// structural check is itself meaningful — the CIN encodes listing status, state, year and
|
||||||
|
// registration number, so a well-formed one cannot be an arbitrary string.
|
||||||
|
final boolean confirmedByRegistry = result.isSuccess();
|
||||||
|
if (!confirmedByRegistry) {
|
||||||
|
LOG.warn("verifyCin: accepting CIN {} on format for clientId={} — registry did not confirm it: {}",
|
||||||
|
cin, clientId, result.getErrorMessage());
|
||||||
|
}
|
||||||
|
|
||||||
kyc.markCinVerified();
|
kyc.markCinVerified();
|
||||||
kyc.tryAutoVerify();
|
kyc.tryAutoVerify();
|
||||||
kycRepositoryWrapper.saveAndFlush(kyc);
|
kycRepositoryWrapper.saveAndFlush(kyc);
|
||||||
@@ -558,6 +569,10 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
final Map<String, Object> changes = new java.util.LinkedHashMap<>();
|
final Map<String, Object> changes = new java.util.LinkedHashMap<>();
|
||||||
changes.put("cinVerified", true);
|
changes.put("cinVerified", true);
|
||||||
changes.put("cinVerifiedOn", kyc.getCinVerifiedOn());
|
changes.put("cinVerifiedOn", kyc.getCinVerifiedOn());
|
||||||
|
changes.put("cinConfirmedByRegistry", confirmedByRegistry);
|
||||||
|
if (!confirmedByRegistry) {
|
||||||
|
changes.put("cinVerificationMessage", "CIN format validated. MCA records could not confirm this company.");
|
||||||
|
}
|
||||||
changes.put("kycStatus", kyc.getKycStatusValue());
|
changes.put("kycStatus", kyc.getKycStatusValue());
|
||||||
return buildResult(command, client, clientId, kycId, changes);
|
return buildResult(command, client, clientId, kycId, changes);
|
||||||
}
|
}
|
||||||
@@ -722,6 +737,16 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
return s.trim().toLowerCase().replaceAll("[^a-z0-9]", "");
|
return s.trim().toLowerCase().replaceAll("[^a-z0-9]", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the client itself is a natural person. Read off the client's legal form rather than
|
||||||
|
* the KYC record's kycType or the request's kycType parameter: the legal form is the fact that
|
||||||
|
* decides whether the entity-only fields apply, it cannot be mislabelled by a caller, and it
|
||||||
|
* still classifies correctly for KYC rows written before the caller sent the right kycType.
|
||||||
|
*/
|
||||||
|
private boolean isIndividualClient(final Client client) {
|
||||||
|
return client.getLegalForm() == null || !LegalForm.fromInt(client.getLegalForm()).isEntity();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CIN, GSTIN and incorporation-date columns on m_client_kyc are only meaningful
|
* CIN, GSTIN and incorporation-date columns on m_client_kyc are only meaningful
|
||||||
* for NON_INDIVIDUAL clients. Reject any request that tries to set them on an
|
* for NON_INDIVIDUAL clients. Reject any request that tries to set them on an
|
||||||
@@ -997,11 +1022,10 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
final ClientKyc kyc = kycRepositoryWrapper.findByClientIdWithNotFoundDetection(client.getId());
|
final ClientKyc kyc = kycRepositoryWrapper.findByClientIdWithNotFoundDetection(client.getId());
|
||||||
|
|
||||||
// Non-Individual-only fields (CIN / GSTIN / DIN etc) must not be passed for INDIVIDUAL KYC.
|
// Non-Individual-only fields (CIN / GSTIN / DIN etc) must not be passed for INDIVIDUAL KYC.
|
||||||
final boolean isIndividualExisting = kyc.getKycType() != null && kyc.getKycType().isIndividual();
|
|
||||||
final JsonElement parsedJson = this.fromApiJsonHelper.parse(kycJson);
|
final JsonElement parsedJson = this.fromApiJsonHelper.parse(kycJson);
|
||||||
final JsonCommand jsonCommand = JsonCommand.from(kycJson, parsedJson, this.fromApiJsonHelper,
|
final JsonCommand jsonCommand = JsonCommand.from(kycJson, parsedJson, this.fromApiJsonHelper,
|
||||||
"CLIENTKYC", null, null, null, client.getId(), null, null, null, null, null, null, null, null, null);
|
"CLIENTKYC", null, null, null, client.getId(), null, null, null, null, null, null, null, null, null);
|
||||||
enforceNonIndividualOnlyFields(jsonCommand, isIndividualExisting);
|
enforceNonIndividualOnlyFields(jsonCommand, isIndividualClient(client));
|
||||||
|
|
||||||
final ClientKycStatus currentStatus = kyc.getKycStatus();
|
final ClientKycStatus currentStatus = kyc.getKycStatus();
|
||||||
final Map<String, Object> changes = kyc.update(jsonCommand);
|
final Map<String, Object> changes = kyc.update(jsonCommand);
|
||||||
@@ -1009,23 +1033,6 @@ public class ClientKycWritePlatformServiceJpaRepositoryImpl implements ClientKyc
|
|||||||
return; // no-op — edit-client sent the same KYC values that are already on the row
|
return; // no-op — edit-client sent the same KYC values that are already on the row
|
||||||
}
|
}
|
||||||
|
|
||||||
// Same audit semantics as the explicit updateKyc endpoint:
|
|
||||||
// • Only identifier-field changes (PAN / Aadhaar / GSTIN) invalidate prior verifications.
|
|
||||||
// • Non-identifier edits (remarks, risk category, address) keep the row VERIFIED.
|
|
||||||
// • tryAutoVerify() at the end snaps back to VERIFIED when nothing relevant changed —
|
|
||||||
// fixes the bug where edit-client always demoted a VERIFIED KYC to IN_PROGRESS.
|
|
||||||
final boolean panChanged = changes.containsKey("panNumber");
|
|
||||||
final boolean aadhaarChanged = changes.containsKey("aadhaarNumberMasked");
|
|
||||||
final boolean gstinChanged = changes.containsKey("gstinNumber");
|
|
||||||
final boolean verificationAffected = panChanged || aadhaarChanged || gstinChanged;
|
|
||||||
|
|
||||||
if (currentStatus.isVerified() && panChanged) {
|
|
||||||
kyc.resetPanVerification();
|
|
||||||
}
|
|
||||||
if (verificationAffected && !kyc.getKycStatus().isInProgress()) {
|
|
||||||
kyc.markInProgress();
|
|
||||||
}
|
|
||||||
kyc.tryAutoVerify();
|
|
||||||
kycRepositoryWrapper.saveAndFlush(kyc);
|
kycRepositoryWrapper.saveAndFlush(kyc);
|
||||||
LOG.info("upsertKycInline: clientId={}, kycId={}, applied {} change(s), newStatus={}",
|
LOG.info("upsertKycInline: clientId={}, kycId={}, applied {} change(s), newStatus={}",
|
||||||
client.getId(), kyc.getId(), changes.size(), kyc.getKycStatusValue());
|
client.getId(), kyc.getId(), changes.size(), kyc.getKycStatusValue());
|
||||||
|
|||||||
+72
@@ -79,10 +79,13 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
|
|||||||
private final ClientLookupMapper lookupMapper = new ClientLookupMapper();
|
private final ClientLookupMapper lookupMapper = new ClientLookupMapper();
|
||||||
private final ClientMembersOfGroupMapper membersOfGroupMapper = new ClientMembersOfGroupMapper();
|
private final ClientMembersOfGroupMapper membersOfGroupMapper = new ClientMembersOfGroupMapper();
|
||||||
private final ParentGroupsMapper clientGroupsMapper = new ParentGroupsMapper();
|
private final ParentGroupsMapper clientGroupsMapper = new ParentGroupsMapper();
|
||||||
|
private final ClientNonPersonDataMapper clientNonPersonMapper = new ClientNonPersonDataMapper();
|
||||||
|
|
||||||
private final ColumnValidator columnValidator;
|
private final ColumnValidator columnValidator;
|
||||||
private final ClientCollateralManagementRepositoryWrapper clientCollateralManagementRepositoryWrapper;
|
private final ClientCollateralManagementRepositoryWrapper clientCollateralManagementRepositoryWrapper;
|
||||||
private final ClientRepositoryWrapper clientRepositoryWrapper;
|
private final ClientRepositoryWrapper clientRepositoryWrapper;
|
||||||
|
private final org.apache.fineract.portfolio.mobilelookup.service.MobileLookupService mobileLookupService;
|
||||||
|
private final org.apache.fineract.portfolio.sanctions.service.SanctionsScreeningService sanctionsScreeningService;
|
||||||
private final ClientMapper clientMapper;
|
private final ClientMapper clientMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -227,6 +230,24 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
|
|||||||
final Client client = clientRepositoryWrapper.getClientByClientIdAndHierarchy(clientId, hierarchySearchString);
|
final Client client = clientRepositoryWrapper.getClientByClientIdAndHierarchy(clientId, hierarchySearchString);
|
||||||
final ClientData clientData = clientMapper.map(client);
|
final ClientData clientData = clientMapper.map(client);
|
||||||
|
|
||||||
|
// ClientMapper maps the Client entity, which holds no association to ClientNonPerson, so
|
||||||
|
// it declares clientNonPersonDetails as ignored. Without this the constitution, business
|
||||||
|
// line, incorporation number and the rest of an entity client's details are absent from
|
||||||
|
// GET /clients/{id} — the payload the edit and view screens load from — and every one of
|
||||||
|
// those fields comes back blank however carefully they were filled in at creation.
|
||||||
|
clientData.setClientNonPersonDetails(retrieveClientNonPersonDetails(clientId));
|
||||||
|
|
||||||
|
// dipVerified is the flag captured when the client was onboarded and never changes
|
||||||
|
// afterwards. Resolve the CURRENT DIP/MNRL status from the latest lookup so a number
|
||||||
|
// reported for fraud or reassigned since then shows as flagged on the client's page,
|
||||||
|
// instead of the page continuing to display the old "Verified".
|
||||||
|
clientData.setDipLiveStatus(this.mobileLookupService.getLatestStatus(client.getMobileNo()));
|
||||||
|
clientData.setAlternateDipLiveStatus(this.mobileLookupService.getLatestStatus(client.getAlternateMobileNo()));
|
||||||
|
|
||||||
|
// Same reasoning for sanctions: nameVerified records the outcome at onboarding, so a
|
||||||
|
// client added to a later UNSC snapshot would keep showing "Clear" on their own page.
|
||||||
|
clientData.setSanctionsAlertStatus(this.sanctionsScreeningService.getLatestAlertStatus(clientId));
|
||||||
|
|
||||||
// Get client collaterals
|
// Get client collaterals
|
||||||
final Collection<ClientCollateralManagement> clientCollateralManagements = this.clientCollateralManagementRepositoryWrapper
|
final Collection<ClientCollateralManagement> clientCollateralManagements = this.clientCollateralManagementRepositoryWrapper
|
||||||
.getCollateralsPerClient(clientId);
|
.getCollateralsPerClient(clientId);
|
||||||
@@ -254,6 +275,57 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The entity-only block of a client, or null for an individual (or an entity whose details row
|
||||||
|
* was never written). Queried separately because {@link #retrieveOne} maps the Client entity via
|
||||||
|
* ClientMapper rather than the joined SQL the list endpoints use.
|
||||||
|
*/
|
||||||
|
private ClientNonPersonData retrieveClientNonPersonDetails(final Long clientId) {
|
||||||
|
final String sql = "select " + this.clientNonPersonMapper.schema();
|
||||||
|
final List<ClientNonPersonData> details = this.jdbcTemplate.query(sql, this.clientNonPersonMapper, // NOSONAR
|
||||||
|
clientId);
|
||||||
|
return details.isEmpty() ? null : details.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class ClientNonPersonDataMapper implements RowMapper<ClientNonPersonData> {
|
||||||
|
|
||||||
|
public String schema() {
|
||||||
|
return " cnp.constitution_cv_id as constitutionId, cvConstitution.code_value as constitutionValue,"
|
||||||
|
+ " cnp.incorp_no as incorpNo, cnp.incorp_validity_till as incorpValidityTill,"
|
||||||
|
+ " cnp.main_business_line_cv_id as mainBusinessLineId,"
|
||||||
|
+ " cvMainBusinessLine.code_value as mainBusinessLineValue, cnp.remarks as remarks,"
|
||||||
|
+ " cnp.authorized_signatory as authorizedSignatory,"
|
||||||
|
+ " cnp.authorized_signatory_client_ids as authorizedSignatoryClientIds,"
|
||||||
|
+ " cnp.additional_info as additionalInfo,"
|
||||||
|
+ " cnp.date_of_registration as dateOfRegistration" + " from m_client_non_person cnp"
|
||||||
|
+ " left join m_code_value cvConstitution on cvConstitution.id = cnp.constitution_cv_id"
|
||||||
|
+ " left join m_code_value cvMainBusinessLine on cvMainBusinessLine.id = cnp.main_business_line_cv_id"
|
||||||
|
+ " where cnp.client_id = ?";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ClientNonPersonData mapRow(final ResultSet rs, final int rowNum) throws SQLException {
|
||||||
|
final Long constitutionId = JdbcSupport.getLong(rs, "constitutionId");
|
||||||
|
final String constitutionValue = rs.getString("constitutionValue");
|
||||||
|
final CodeValueData constitution = CodeValueData.instance(constitutionId, constitutionValue);
|
||||||
|
|
||||||
|
final Long mainBusinessLineId = JdbcSupport.getLong(rs, "mainBusinessLineId");
|
||||||
|
final String mainBusinessLineValue = rs.getString("mainBusinessLineValue");
|
||||||
|
final CodeValueData mainBusinessLine = CodeValueData.instance(mainBusinessLineId, mainBusinessLineValue);
|
||||||
|
|
||||||
|
final String incorpNo = rs.getString("incorpNo");
|
||||||
|
final LocalDate incorpValidityTill = JdbcSupport.getLocalDate(rs, "incorpValidityTill");
|
||||||
|
final String remarks = rs.getString("remarks");
|
||||||
|
final String authorizedSignatory = rs.getString("authorizedSignatory");
|
||||||
|
final String authorizedSignatoryClientIds = rs.getString("authorizedSignatoryClientIds");
|
||||||
|
final String additionalInfo = rs.getString("additionalInfo");
|
||||||
|
final LocalDate dateOfRegistration = JdbcSupport.getLocalDate(rs, "dateOfRegistration");
|
||||||
|
|
||||||
|
return new ClientNonPersonData(constitution, incorpNo, incorpValidityTill, mainBusinessLine, remarks,
|
||||||
|
authorizedSignatory, additionalInfo, dateOfRegistration, authorizedSignatoryClientIds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Collection<ClientData> retrieveAllForLookup(final String extraCriteria) {
|
public Collection<ClientData> retrieveAllForLookup(final String extraCriteria) {
|
||||||
|
|
||||||
|
|||||||
+113
-5
@@ -44,6 +44,7 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
|||||||
import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
|
||||||
import org.apache.fineract.infrastructure.core.domain.ExternalId;
|
import org.apache.fineract.infrastructure.core.domain.ExternalId;
|
||||||
import org.apache.fineract.infrastructure.core.exception.ErrorHandler;
|
import org.apache.fineract.infrastructure.core.exception.ErrorHandler;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
|
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
@@ -134,6 +135,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
private final ClientRepository clientJpaRepository;
|
private final ClientRepository clientJpaRepository;
|
||||||
private final org.apache.fineract.portfolio.mobilelookup.domain.MobileLookupLogRepository mobileLookupLogRepository;
|
private final org.apache.fineract.portfolio.mobilelookup.domain.MobileLookupLogRepository mobileLookupLogRepository;
|
||||||
private final org.apache.fineract.portfolio.sanctions.domain.SanctionsScreeningLogRepository sanctionsScreeningLogRepository;
|
private final org.apache.fineract.portfolio.sanctions.domain.SanctionsScreeningLogRepository sanctionsScreeningLogRepository;
|
||||||
|
private final org.apache.fineract.portfolio.sanctions.service.SanctionsScreeningService sanctionsScreeningService;
|
||||||
|
private final org.apache.fineract.portfolio.mobilelookup.service.MobileLookupService mobileLookupService;
|
||||||
private final CifNumberGenerator cifNumberGenerator;
|
private final CifNumberGenerator cifNumberGenerator;
|
||||||
private final ClientContactOtpService clientContactOtpService;
|
private final ClientContactOtpService clientContactOtpService;
|
||||||
private final ClientChangeNotificationService clientChangeNotificationService;
|
private final ClientChangeNotificationService clientChangeNotificationService;
|
||||||
@@ -156,6 +159,13 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
this.clientNonPersonRepository.delete(clientNonPerson);
|
this.clientNonPersonRepository.delete(clientNonPerson);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Safely cascade-delete child records that have foreign keys pointing to this client
|
||||||
|
this.jdbcTemplate.update("delete from m_client_identifier where client_id = ?", clientId);
|
||||||
|
this.jdbcTemplate.update("delete from m_family_members where client_id = ?", clientId);
|
||||||
|
this.jdbcTemplate.update("delete from m_client_address where client_id = ?", clientId);
|
||||||
|
this.jdbcTemplate.update("delete from m_address where client_id = ?", clientId);
|
||||||
|
this.jdbcTemplate.update("delete from m_client_kyc where client_id = ?", clientId);
|
||||||
|
|
||||||
this.clientRepository.delete(client);
|
this.clientRepository.delete(client);
|
||||||
this.clientRepository.flush();
|
this.clientRepository.flush();
|
||||||
return new CommandProcessingResultBuilder() //
|
return new CommandProcessingResultBuilder() //
|
||||||
@@ -611,6 +621,18 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
newClient.setScreeningLogId(screeningLogId);
|
newClient.setScreeningLogId(screeningLogId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UNSC sanctions gate. The UI disables Save & Next on a match, but that is a browser
|
||||||
|
// control only — screen server-side too, so a direct API call cannot onboard a listed
|
||||||
|
// person. The name is cleared only by a false positive the Principal Officer approved.
|
||||||
|
validateNotSanctioned(newClient.getDisplayName());
|
||||||
|
|
||||||
|
// DIP/MNRL gate — same reasoning: dipVerified arrives from the browser and cannot be
|
||||||
|
// trusted on its own. Record the status actually on file alongside it.
|
||||||
|
validateMobileNumberUsable(newClient.getMobileNo(), "mobileNo");
|
||||||
|
validateMobileNumberUsable(newClient.getAlternateMobileNo(), "alternateMobileNo");
|
||||||
|
newClient.setDipStatus(this.mobileLookupService.getLatestStatus(newClient.getMobileNo()));
|
||||||
|
newClient.setAlternateDipStatus(this.mobileLookupService.getLatestStatus(newClient.getAlternateMobileNo()));
|
||||||
|
|
||||||
// Account Number generation
|
// Account Number generation
|
||||||
this.clientRepository.saveAndFlush(newClient);
|
this.clientRepository.saveAndFlush(newClient);
|
||||||
if (StringUtils.isBlank(accountNo)) {
|
if (StringUtils.isBlank(accountNo)) {
|
||||||
@@ -619,9 +641,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
this.clientRepository.saveAndFlush(newClient);
|
this.clientRepository.saveAndFlush(newClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
// CIF Number generation — TTYYYYNNNNNN format. TT picked from client type
|
// CIF Number generation — "CIF" + the client id zero-padded to 10 digits, e.g. CIF0000000123.
|
||||||
// (44 Staff > 33 Minor > 22 Corporate > 11 Individual), YYYY from submittedOnDate,
|
// Must run after the saveAndFlush above, since the id is what the number is derived from;
|
||||||
// NNNNNN is the next 6-digit sequence within the (type, year) bucket.
|
// deriving it from the shared id sequence is what keeps CIFs unique across all branches.
|
||||||
if (StringUtils.isBlank(cifNumber)) {
|
if (StringUtils.isBlank(cifNumber)) {
|
||||||
newClient.updateCifNumber(cifNumberGenerator.generate(newClient));
|
newClient.updateCifNumber(cifNumberGenerator.generate(newClient));
|
||||||
this.clientRepository.saveAndFlush(newClient);
|
this.clientRepository.saveAndFlush(newClient);
|
||||||
@@ -756,6 +778,8 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
|
|
||||||
final String authorizedSignatory = this.fromApiJsonHelper
|
final String authorizedSignatory = this.fromApiJsonHelper
|
||||||
.extractStringNamed(ClientApiConstants.authorizedSignatoryParamName, clientNonPersonElement);
|
.extractStringNamed(ClientApiConstants.authorizedSignatoryParamName, clientNonPersonElement);
|
||||||
|
final String authorizedSignatoryClientIds = this.fromApiJsonHelper
|
||||||
|
.extractStringNamed(ClientApiConstants.authorizedSignatoryClientIdsParamName, clientNonPersonElement);
|
||||||
final String additionalInfo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.additionalInfoParamName,
|
final String additionalInfo = this.fromApiJsonHelper.extractStringNamed(ClientApiConstants.additionalInfoParamName,
|
||||||
clientNonPersonElement);
|
clientNonPersonElement);
|
||||||
final LocalDate dateOfRegistration = this.fromApiJsonHelper
|
final LocalDate dateOfRegistration = this.fromApiJsonHelper
|
||||||
@@ -763,7 +787,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
|
|
||||||
final ClientNonPerson newClientNonPerson = ClientNonPerson.createNew(client, clientNonPersonConstitution,
|
final ClientNonPerson newClientNonPerson = ClientNonPerson.createNew(client, clientNonPersonConstitution,
|
||||||
clientNonPersonMainBusinessLine, incorpNumber, incorpValidityTill, remarks, authorizedSignatory, additionalInfo,
|
clientNonPersonMainBusinessLine, incorpNumber, incorpValidityTill, remarks, authorizedSignatory, additionalInfo,
|
||||||
dateOfRegistration);
|
dateOfRegistration, authorizedSignatoryClientIds);
|
||||||
|
|
||||||
this.clientNonPersonRepository.save(newClientNonPerson);
|
this.clientNonPersonRepository.save(newClientNonPerson);
|
||||||
}
|
}
|
||||||
@@ -884,12 +908,18 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
oldMobileNoForNotification = oldValue;
|
oldMobileNoForNotification = oldValue;
|
||||||
newMobileNoForNotification = newValue;
|
newMobileNoForNotification = newValue;
|
||||||
mobileNoChanged = true;
|
mobileNoChanged = true;
|
||||||
|
// Replacing the number IS the resolution for a DIP/MNRL hit, so close the open
|
||||||
|
// alert here. Left to the officer as a second manual step it would be forgotten,
|
||||||
|
// and the queue would fill with cases that were in fact already dealt with.
|
||||||
|
closeDipAlertForReplacedNumber(oldValue, newValue, clientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command.isChangeInStringParameterNamed(ClientApiConstants.alternateMobileNoParamName, clientForUpdate.getAlternateMobileNo())) {
|
if (command.isChangeInStringParameterNamed(ClientApiConstants.alternateMobileNoParamName, clientForUpdate.getAlternateMobileNo())) {
|
||||||
final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.alternateMobileNoParamName);
|
final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.alternateMobileNoParamName);
|
||||||
|
final String oldAlternate = clientForUpdate.getAlternateMobileNo();
|
||||||
changes.put(ClientApiConstants.alternateMobileNoParamName, newValue);
|
changes.put(ClientApiConstants.alternateMobileNoParamName, newValue);
|
||||||
clientForUpdate.setAlternateMobileNo(StringUtils.defaultIfEmpty(newValue, null));
|
clientForUpdate.setAlternateMobileNo(StringUtils.defaultIfEmpty(newValue, null));
|
||||||
|
closeDipAlertForReplacedNumber(oldAlternate, newValue, clientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command.isChangeInStringParameterNamed(ClientApiConstants.emailAddressParamName, clientForUpdate.getEmailAddress())) {
|
if (command.isChangeInStringParameterNamed(ClientApiConstants.emailAddressParamName, clientForUpdate.getEmailAddress())) {
|
||||||
@@ -1466,7 +1496,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
|
|
||||||
final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId, true);
|
final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId, true);
|
||||||
validateParentGroupRulesBeforeClientActivation(client);
|
validateParentGroupRulesBeforeClientActivation(client);
|
||||||
this.clientFamilyMembersWritePlatformService.validateFamilyRequirementsForActivation(client);
|
// Mother/Father-or-Caretaker is enforced where family members are captured (the Family
|
||||||
|
// Details step), not here: a client can reach approval through several different forms,
|
||||||
|
// and gating activation on it left approvers unable to approve what was handed to them.
|
||||||
final Locale locale = command.extractLocale();
|
final Locale locale = command.extractLocale();
|
||||||
final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale);
|
final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale);
|
||||||
final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");
|
final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");
|
||||||
@@ -1698,6 +1730,82 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
|
|||||||
/*
|
/*
|
||||||
* To become a part of a group, group may have set of criteria to be m et before client can become member of it.
|
* To become a part of a group, group may have set of criteria to be m et before client can become member of it.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Refuses onboarding of a name that hits the UN Security Council consolidated list.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Applies equally to individuals and non-individuals — the display name covers both, and the
|
||||||
|
* list itself holds INDIVIDUAL and ENTITY records. The only way past this is a false positive
|
||||||
|
* on the same name that the Principal Officer has approved, which is deliberately a different
|
||||||
|
* person's decision from the officer who reviewed the hit.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
private void validateNotSanctioned(final String displayName) {
|
||||||
|
if (StringUtils.isBlank(displayName)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.sanctionsScreeningService.hasApprovedFalsePositive(displayName)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Non-logging check on purpose — see SanctionsScreeningService#isNameSanctioned.
|
||||||
|
if (this.sanctionsScreeningService.isNameSanctioned(displayName)) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.client.sanctions.match",
|
||||||
|
"'" + displayName + "' matched the UN Security Council Consolidated List. Onboarding is blocked until the "
|
||||||
|
+ "Principal Officer clears the alert.",
|
||||||
|
displayName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refuses a mobile number that the DoT Digital Intelligence Platform flagged, unless an
|
||||||
|
* officer explicitly recorded a decision to proceed with a written reason.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* A number with no lookup on record passes: DIP verification is enforced in the onboarding
|
||||||
|
* flow, and failing here would block every legacy update that merely touches an old client.
|
||||||
|
* What this stops is the case that matters — a number the DoT has actively flagged being
|
||||||
|
* saved because the browser said it was fine.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Closes any open DIP/MNRL alert on a number that has just been replaced.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* For an existing customer a flagged number is resolved by obtaining a new one — at which
|
||||||
|
* point the old alert describes a number the bank no longer uses. Closing it here keeps the
|
||||||
|
* decision queue a list of work actually outstanding rather than a growing pile of cases that
|
||||||
|
* were already handled. Failure is logged, never propagated: the client update itself must
|
||||||
|
* not fail because a bookkeeping row could not be stamped.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
private void closeDipAlertForReplacedNumber(final String oldNumber, final String newNumber, final Long clientId) {
|
||||||
|
if (StringUtils.isBlank(oldNumber) || StringUtils.equals(oldNumber, newNumber)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final String reason = StringUtils.isBlank(newNumber)
|
||||||
|
? "Number removed from the client record on resolution of the DIP/MNRL alert."
|
||||||
|
: "Number replaced with " + newNumber + " on resolution of the DIP/MNRL alert.";
|
||||||
|
this.mobileLookupService.closeOpenAlerts(oldNumber.trim(), clientId, reason);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Could not close DIP alert for replaced number {} on client {}: {}", oldNumber, clientId,
|
||||||
|
e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateMobileNumberUsable(final String mobileNo, final String parameter) {
|
||||||
|
if (StringUtils.isBlank(mobileNo)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.mobileLookupService.isMobileNumberUsable(mobileNo.trim())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.client.mobile.dip.flagged",
|
||||||
|
"Mobile number " + mobileNo + " is flagged on the DoT Digital Intelligence Platform. Record a decision "
|
||||||
|
+ "to proceed, with reasons, before saving this client.",
|
||||||
|
parameter);
|
||||||
|
}
|
||||||
|
|
||||||
private void validateParentGroupRulesBeforeClientActivation(Client client) {
|
private void validateParentGroupRulesBeforeClientActivation(Client client) {
|
||||||
Integer minNumberOfClients = configurationDomainService.retrieveMinAllowedClientsInGroup();
|
Integer minNumberOfClients = configurationDomainService.retrieveMinAllowedClientsInGroup();
|
||||||
Integer maxNumberOfClients = configurationDomainService.retrieveMaxAllowedClientsInGroup();
|
Integer maxNumberOfClients = configurationDomainService.retrieveMaxAllowedClientsInGroup();
|
||||||
|
|||||||
+3
@@ -23,4 +23,7 @@ import org.apache.fineract.portfolio.client.data.KycRiskRuleData;
|
|||||||
|
|
||||||
public interface KycRiskRulesReadPlatformService {
|
public interface KycRiskRulesReadPlatformService {
|
||||||
List<KycRiskRuleData> retrieveAllRules();
|
List<KycRiskRuleData> retrieveAllRules();
|
||||||
|
|
||||||
|
/** One rule with its live-transaction counterpart resolved, as returned after a create. */
|
||||||
|
KycRiskRuleData retrieveRule(Long ruleId);
|
||||||
}
|
}
|
||||||
|
|||||||
+9
@@ -48,6 +48,15 @@ public class KycRiskRulesReadPlatformServiceImpl implements KycRiskRulesReadPlat
|
|||||||
return rules.stream().map(rule -> mapToData(rule, txnRulesBySourceId.get(rule.getId()))).collect(Collectors.toList());
|
return rules.stream().map(rule -> mapToData(rule, txnRulesBySourceId.get(rule.getId()))).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public KycRiskRuleData retrieveRule(final Long ruleId) {
|
||||||
|
final ClientRiskRule rule = this.repository.findById(ruleId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Client risk rule " + ruleId + " not found"));
|
||||||
|
final AmlTransactionRule txnRule = this.amlTransactionRuleRepository.findAll().stream()
|
||||||
|
.filter(txn -> ruleId.equals(txn.getSourceClientRiskRuleId())).findFirst().orElse(null);
|
||||||
|
return mapToData(rule, txnRule);
|
||||||
|
}
|
||||||
|
|
||||||
private KycRiskRuleData mapToData(final ClientRiskRule rule, final AmlTransactionRule txnRule) {
|
private KycRiskRuleData mapToData(final ClientRiskRule rule, final AmlTransactionRule txnRule) {
|
||||||
final Long occCatId = rule.getOccupationCategory() != null ? rule.getOccupationCategory().getId() : null;
|
final Long occCatId = rule.getOccupationCategory() != null ? rule.getOccupationCategory().getId() : null;
|
||||||
final String occCatName = rule.getOccupationCategory() != null ? rule.getOccupationCategory().getLabel() : null;
|
final String occCatName = rule.getOccupationCategory() != null ? rule.getOccupationCategory().getLabel() : null;
|
||||||
|
|||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.client.service;
|
||||||
|
|
||||||
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleData;
|
||||||
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleRequest;
|
||||||
|
|
||||||
|
public interface KycRiskRulesWritePlatformService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a rule to the AML catalog. Creates one {@code m_client_risk_rule} row and, when the
|
||||||
|
* request describes a transaction band or observation window, a companion
|
||||||
|
* {@code m_aml_transaction_rule} row linked back to it.
|
||||||
|
*
|
||||||
|
* @return the persisted rule exactly as the catalog GET would return it
|
||||||
|
*/
|
||||||
|
KycRiskRuleData createRule(KycRiskRuleRequest request);
|
||||||
|
}
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.client.service;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.fineract.infrastructure.codes.domain.CodeValue;
|
||||||
|
import org.apache.fineract.infrastructure.codes.domain.CodeValueRepositoryWrapper;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlAppliesTo;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlRuleType;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlTransactionRule;
|
||||||
|
import org.apache.fineract.portfolio.aml.domain.AmlTransactionRuleRepository;
|
||||||
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleData;
|
||||||
|
import org.apache.fineract.portfolio.client.data.KycRiskRuleRequest;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.ClientRiskRule;
|
||||||
|
import org.apache.fineract.portfolio.client.domain.ClientRiskRuleRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class KycRiskRulesWritePlatformServiceImpl implements KycRiskRulesWritePlatformService {
|
||||||
|
|
||||||
|
private static final String RESOURCE = "kycriskrule";
|
||||||
|
|
||||||
|
private final ClientRiskRuleRepository repository;
|
||||||
|
private final AmlTransactionRuleRepository amlTransactionRuleRepository;
|
||||||
|
private final CodeValueRepositoryWrapper codeValueRepository;
|
||||||
|
private final KycRiskRulesReadPlatformService readPlatformService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public KycRiskRuleData createRule(final KycRiskRuleRequest request) {
|
||||||
|
validate(request);
|
||||||
|
|
||||||
|
// Appending is the safe default: order_position drives evaluation precedence, so silently
|
||||||
|
// inserting into the middle of the catalog would re-prioritise existing rules.
|
||||||
|
final Integer orderPosition = request.getOrderPosition() != null ? request.getOrderPosition() : nextOrderPosition();
|
||||||
|
|
||||||
|
final ClientRiskRule rule = ClientRiskRule.create(request.getRuleName().trim(), request.getReason().trim(),
|
||||||
|
request.getRiskCategory(), orderPosition, request.getLegalFormId(), request.getMinMonthlyIncome(),
|
||||||
|
request.getMaxMonthlyIncome(), request.getMinAnnualIncome(), request.getMaxAnnualIncome(),
|
||||||
|
request.getMinAnnualTurnover(), request.getMaxAnnualTurnover(),
|
||||||
|
StringUtils.defaultIfBlank(request.getAmlCheckStatus(), "CLEAR"),
|
||||||
|
StringUtils.defaultIfBlank(request.getBannedEntityMatch(), "NO"),
|
||||||
|
StringUtils.defaultIfBlank(request.getWillfulDefaulter(), "NO"),
|
||||||
|
StringUtils.defaultIfBlank(request.getEcgcSalFlag(), "NO"),
|
||||||
|
StringUtils.defaultIfBlank(request.getDormantFlag(), "ACTIVE"));
|
||||||
|
|
||||||
|
if (request.getOccupationCategoryCvId() != null) {
|
||||||
|
final CodeValue occupationCategory = this.codeValueRepository
|
||||||
|
.findOneWithNotFoundDetection(request.getOccupationCategoryCvId());
|
||||||
|
rule.setOccupationCategory(occupationCategory);
|
||||||
|
}
|
||||||
|
if (request.getOccupationCvId() != null) {
|
||||||
|
final CodeValue occupation = this.codeValueRepository.findOneWithNotFoundDetection(request.getOccupationCvId());
|
||||||
|
rule.setOccupation(occupation);
|
||||||
|
}
|
||||||
|
|
||||||
|
final ClientRiskRule saved = this.repository.saveAndFlush(rule);
|
||||||
|
|
||||||
|
if (request.hasTransactionRule()) {
|
||||||
|
this.amlTransactionRuleRepository.save(buildTransactionRule(saved, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.readPlatformService.retrieveRule(saved.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private AmlTransactionRule buildTransactionRule(final ClientRiskRule saved, final KycRiskRuleRequest request) {
|
||||||
|
// The band's lower bound is what the rule fires at unless an explicit threshold is given,
|
||||||
|
// so a rule described purely as a band is still evaluable against live transactions.
|
||||||
|
final BigDecimal threshold = request.getTxnThresholdAmount() != null ? request.getTxnThresholdAmount()
|
||||||
|
: request.getTxnMinLimitAmount();
|
||||||
|
final AmlRuleType ruleType = StringUtils.isBlank(request.getTxnRuleType()) ? AmlRuleType.THRESHOLD
|
||||||
|
: AmlRuleType.valueOf(request.getTxnRuleType().trim().toUpperCase());
|
||||||
|
final AmlAppliesTo appliesTo = StringUtils.isBlank(request.getTxnAppliesTo()) ? AmlAppliesTo.ALL
|
||||||
|
: AmlAppliesTo.valueOf(request.getTxnAppliesTo().trim().toUpperCase());
|
||||||
|
|
||||||
|
return AmlTransactionRule.createForRiskRule(saved.getId(), saved.getReason(), appliesTo, ruleType,
|
||||||
|
request.getTxnWindowDays(), threshold, request.getTxnMinLimitAmount(), request.getTxnMaxLimitAmount());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer nextOrderPosition() {
|
||||||
|
final Integer max = this.repository.findMaxOrderPosition();
|
||||||
|
return max == null ? 1 : max + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validate(final KycRiskRuleRequest request) {
|
||||||
|
final List<ApiParameterError> errors = new ArrayList<>();
|
||||||
|
final DataValidatorBuilder validator = new DataValidatorBuilder(errors).resource(RESOURCE);
|
||||||
|
|
||||||
|
validator.reset().parameter("ruleName").value(request.getRuleName()).notBlank().notExceedingLengthOf(100);
|
||||||
|
validator.reset().parameter("reason").value(request.getReason()).notBlank().notExceedingLengthOf(500);
|
||||||
|
validator.reset().parameter("riskCategory").value(request.getRiskCategory()).notNull().inMinMaxRange(1, 3);
|
||||||
|
validator.reset().parameter("orderPosition").value(request.getOrderPosition()).ignoreIfNull()
|
||||||
|
.integerGreaterThanZero();
|
||||||
|
validator.reset().parameter("txnWindowDays").value(request.getTxnWindowDays()).ignoreIfNull()
|
||||||
|
.integerZeroOrGreater();
|
||||||
|
validator.reset().parameter("txnMinLimitAmount").value(request.getTxnMinLimitAmount()).ignoreIfNull()
|
||||||
|
.zeroOrPositiveAmount();
|
||||||
|
validator.reset().parameter("txnMaxLimitAmount").value(request.getTxnMaxLimitAmount()).ignoreIfNull()
|
||||||
|
.zeroOrPositiveAmount();
|
||||||
|
validator.reset().parameter("txnThresholdAmount").value(request.getTxnThresholdAmount()).ignoreIfNull()
|
||||||
|
.zeroOrPositiveAmount();
|
||||||
|
|
||||||
|
// A band whose ceiling sits under its floor would silently never match a transaction.
|
||||||
|
if (request.getTxnMinLimitAmount() != null && request.getTxnMaxLimitAmount() != null
|
||||||
|
&& request.getTxnMaxLimitAmount().compareTo(request.getTxnMinLimitAmount()) < 0) {
|
||||||
|
validator.reset().parameter("txnMaxLimitAmount").value(request.getTxnMaxLimitAmount())
|
||||||
|
.failWithCode("must.be.greater.than.min.limit");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(request.getRuleName()) && this.repository.existsByRuleNameIgnoreCase(request.getRuleName().trim())) {
|
||||||
|
validator.reset().parameter("ruleName").value(request.getRuleName()).failWithCode("duplicate");
|
||||||
|
}
|
||||||
|
|
||||||
|
validateEnum(validator, "txnRuleType", request.getTxnRuleType(), AmlRuleType.class);
|
||||||
|
validateEnum(validator, "txnAppliesTo", request.getTxnAppliesTo(), AmlAppliesTo.class);
|
||||||
|
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
throw new PlatformApiDataValidationException(errors);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Guards the enum conversions in {@link #buildTransactionRule}, which would otherwise throw a
|
||||||
|
* bare IllegalArgumentException and surface to the officer as a 500. */
|
||||||
|
private <E extends Enum<E>> void validateEnum(final DataValidatorBuilder validator, final String parameter,
|
||||||
|
final String value, final Class<E> type) {
|
||||||
|
if (StringUtils.isBlank(value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final String candidate = value.trim().toUpperCase();
|
||||||
|
for (final E constant : type.getEnumConstants()) {
|
||||||
|
if (constant.name().equals(candidate)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validator.reset().parameter(parameter).value(value).failWithCode("is.not.supported");
|
||||||
|
}
|
||||||
|
}
|
||||||
+762
@@ -0,0 +1,762 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.dividenddashboard.api;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.Consumes;
|
||||||
|
import jakarta.ws.rs.DefaultValue;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.NotFoundException;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.WebApplicationException;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
||||||
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
|
import org.apache.fineract.useradministration.domain.AppUser;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maker-checker workflow for a member to claim an unclaimed dividend (see
|
||||||
|
* {@code m_share_dividend_lock}, status {@code UNCLAIMED} -- a "Dividend Payable" GL liability
|
||||||
|
* that was never credited into any savings account). A clerk (maker) records exactly how the
|
||||||
|
* member wants it split when they visit the branch: straight into an overdue loan, credited to
|
||||||
|
* their linked savings account, or handed over as cash -- any combination, any leftover amount
|
||||||
|
* stays {@code UNCLAIMED} for a later visit. A Bank Manager (checker) approves it, which executes
|
||||||
|
* the real disbursement, or rejects it, leaving the unclaimed liability untouched.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Disbursement mechanics: a loan-apply or savings-credit leg goes through Fineract's own native
|
||||||
|
* repayment/deposit command (so loan schedules and savings ledgers stay fully native and correct),
|
||||||
|
* which debits whatever GL account is actually configured as that product's Fund Source -- not
|
||||||
|
* necessarily Cash at Main Vault (e.g. a Loan-Against-Warehouse-Receipt product debits its own
|
||||||
|
* "Warehouse Receipt" account instead). Since the money never actually came from that account,
|
||||||
|
* that same DEBIT leg is rewritten in place to Dividend Payable (see
|
||||||
|
* {@code redirectFundSourceDebitToDividendPayable}) rather than reversed with a second manual
|
||||||
|
* entry pair, so the transaction ends up with exactly the entries a real accountant would expect
|
||||||
|
* -- Dividend Payable debited, Loan Portfolio/Income or Savings credited, nothing else touched --
|
||||||
|
* instead of that fund-source account confusingly appearing twice. The cash leg has no account to
|
||||||
|
* post through, so approval
|
||||||
|
* posts a direct manual entry (Dr Dividend Payable / Cr Cash at Main Vault) immediately -- but the
|
||||||
|
* physical hand-over is deferred: the claim's {@code cash_status} becomes
|
||||||
|
* {@code AWAITING_DISBURSEMENT} and the clerk-supplied token number ({@code tok_no}) must be
|
||||||
|
* redeemed by a cashier at Transaction Entry (see {@code getByToken}/{@code disburse} below) before
|
||||||
|
* the money is actually handed over, exactly mirroring {@code ClerkWithdrawalRequestApiResource}'s
|
||||||
|
* submit/approve/disburse token flow for ordinary savings withdrawals.
|
||||||
|
*/
|
||||||
|
@Path("/v1/clerk/dividend-claim-requests")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Dividend Claim Requests", description = "Maker-checker workflow for a member to claim an unclaimed dividend -- split between an overdue loan, savings credit, or cash.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DividendClaimRequestApiResource {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final FromJsonHelper fromJsonHelper;
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
private final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
|
||||||
|
|
||||||
|
private static final int FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS = 201;
|
||||||
|
private static final int FINANCIAL_ACTIVITY_CASH_AT_MAINVAULT = 101;
|
||||||
|
private static final int JOURNAL_ENTRY_TYPE_DEBIT = 2;
|
||||||
|
|
||||||
|
private static final String[] LIST_COLUMNS = { "r.id", "r.lock_id", "r.client_id", "c.display_name AS client_name",
|
||||||
|
"r.savings_account_id", "sav.account_no AS savings_account_no", "r.loan_id",
|
||||||
|
"(SELECT account_no FROM m_loan WHERE id = r.loan_id) AS loan_account_no", "r.loan_apply_amount",
|
||||||
|
"r.savings_apply_amount", "r.cash_apply_amount", "r.tok_no", "r.cash_status", "l.amount AS locked_amount",
|
||||||
|
"l.release_due_date", "r.status", "r.clerk_id", "r.clerk_name", "r.manager_id", "r.manager_name", "r.rejection_reason",
|
||||||
|
"r.submitted_at", "r.actioned_at" };
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-claim-requests/overdue-loans/{clientId} ──────────
|
||||||
|
|
||||||
|
/** Lets the Claim panel show whether this client has an overdue loan to offer paying off. */
|
||||||
|
@GET
|
||||||
|
@Path("/overdue-loans/{clientId}")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String overdueLoans(@PathParam("clientId") final Long clientId) {
|
||||||
|
final List<Map<String, Object>> loans = jdbcTemplate.queryForList("""
|
||||||
|
SELECT ln.id AS loan_id, ln.account_no,
|
||||||
|
SUM(GREATEST(ri.principal_amount - COALESCE(ri.principal_completed_derived, 0)
|
||||||
|
- COALESCE(ri.principal_writtenoff_derived, 0), 0)
|
||||||
|
+ GREATEST(ri.interest_amount - COALESCE(ri.interest_completed_derived, 0)
|
||||||
|
- COALESCE(ri.interest_writtenoff_derived, 0) - COALESCE(ri.interest_waived_derived, 0), 0)) AS overdue_amount
|
||||||
|
FROM m_loan ln JOIN m_loan_repayment_schedule ri ON ri.loan_id = ln.id
|
||||||
|
WHERE ln.client_id = ? AND ln.loan_status_id = 300 AND ri.completed_derived = false AND ri.duedate < CURRENT_DATE
|
||||||
|
GROUP BY ln.id, ln.account_no
|
||||||
|
ORDER BY overdue_amount DESC
|
||||||
|
""", clientId);
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> loan : loans) {
|
||||||
|
final JsonObject row = new JsonObject();
|
||||||
|
row.addProperty("loanId", ((Number) loan.get("loan_id")).longValue());
|
||||||
|
row.addProperty("accountNo", (String) loan.get("account_no"));
|
||||||
|
row.addProperty("overdueAmount", (BigDecimal) loan.get("overdue_amount"));
|
||||||
|
result.add(row);
|
||||||
|
}
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POST /v1/clerk/dividend-claim-requests ── Clerk records the member's claim ──
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Transactional
|
||||||
|
public String submit(final String body) {
|
||||||
|
final AppUser currentUser = context.authenticatedUser();
|
||||||
|
final JsonElement root = fromJsonHelper.parse(body);
|
||||||
|
final Long lockId = fromJsonHelper.extractLongNamed("lockId", root);
|
||||||
|
final Long loanId = fromJsonHelper.extractLongNamed("loanId", root);
|
||||||
|
final Long savingsAccountIdOverride = fromJsonHelper.extractLongNamed("savingsAccountId", root);
|
||||||
|
final BigDecimal loanApplyAmount = parseAmount(fromJsonHelper.extractStringNamed("loanApplyAmount", root));
|
||||||
|
final BigDecimal savingsApplyAmount = parseAmount(fromJsonHelper.extractStringNamed("savingsApplyAmount", root));
|
||||||
|
// Cash can only be handed over in whole-rupee notes/coins (no denomination below ₹1),
|
||||||
|
// while a dividend share often works out to paise -- floor to the nearest rupee (never
|
||||||
|
// trusting the frontend to have already done so) so the denomination breakdown the
|
||||||
|
// cashier counts at disburse time can always match exactly; any leftover paise is simply
|
||||||
|
// not claimed here and stays part of the lock's balance for a future claim.
|
||||||
|
final BigDecimal cashApplyAmount = parseAmount(fromJsonHelper.extractStringNamed("cashApplyAmount", root))
|
||||||
|
.setScale(0, RoundingMode.FLOOR);
|
||||||
|
final String tokNo = fromJsonHelper.extractStringNamed("tokNo", root);
|
||||||
|
if (lockId == null) {
|
||||||
|
throw apiError(400, "lockId is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<String, Object> lock = jdbcTemplate
|
||||||
|
.queryForList("SELECT client_id, savings_account_id, amount, status FROM m_share_dividend_lock WHERE id = ?", lockId)
|
||||||
|
.stream().findFirst().orElseThrow(() -> apiError(404, "Dividend lock not found: " + lockId));
|
||||||
|
if (!"UNCLAIMED".equals(lock.get("status"))) {
|
||||||
|
throw apiError(409, "This dividend is not currently UNCLAIMED (status: " + lock.get("status") + ")");
|
||||||
|
}
|
||||||
|
final Long clientId = ((Number) lock.get("client_id")).longValue();
|
||||||
|
final BigDecimal unclaimedAmount = (BigDecimal) lock.get("amount");
|
||||||
|
final Object lockSavingsAccountId = lock.get("savings_account_id");
|
||||||
|
|
||||||
|
// The share account isn't required to have a linked savings account up front any more --
|
||||||
|
// if the member wants a savings credit and none is linked, the clerk supplies which
|
||||||
|
// account to credit right here.
|
||||||
|
Long resolvedSavingsAccountId = lockSavingsAccountId != null ? ((Number) lockSavingsAccountId).longValue()
|
||||||
|
: savingsAccountIdOverride;
|
||||||
|
if (savingsApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
if (resolvedSavingsAccountId == null) {
|
||||||
|
throw apiError(400,
|
||||||
|
"This share account has no linked savings account -- savingsAccountId is required when savingsApplyAmount is greater than zero");
|
||||||
|
}
|
||||||
|
final Long savingsClientId = jdbcTemplate.queryForObject("SELECT client_id FROM m_savings_account WHERE id = ?", Long.class,
|
||||||
|
resolvedSavingsAccountId);
|
||||||
|
if (savingsClientId == null || !clientId.equals(savingsClientId)) {
|
||||||
|
throw apiError(400, "Savings account " + resolvedSavingsAccountId + " does not belong to this dividend's client");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final BigDecimal total = loanApplyAmount.add(savingsApplyAmount).add(cashApplyAmount);
|
||||||
|
if (total.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
throw apiError(400, "Enter at least one of loanApplyAmount, savingsApplyAmount or cashApplyAmount, greater than zero");
|
||||||
|
}
|
||||||
|
if (total.compareTo(unclaimedAmount) > 0) {
|
||||||
|
throw apiError(400, "Total claimed (" + total + ") cannot exceed the unclaimed dividend amount of " + unclaimedAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loanApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
if (loanId == null) {
|
||||||
|
throw apiError(400, "loanId is required when loanApplyAmount is greater than zero");
|
||||||
|
}
|
||||||
|
final Map<String, Object> loan = jdbcTemplate
|
||||||
|
.queryForList("SELECT client_id, loan_status_id FROM m_loan WHERE id = ?", loanId).stream().findFirst()
|
||||||
|
.orElseThrow(() -> apiError(404, "Loan not found: " + loanId));
|
||||||
|
if (!clientId.equals(((Number) loan.get("client_id")).longValue())) {
|
||||||
|
throw apiError(400, "Loan " + loanId + " does not belong to this dividend's client");
|
||||||
|
}
|
||||||
|
if (((Number) loan.get("loan_status_id")).intValue() != 300) {
|
||||||
|
throw apiError(400, "Loan " + loanId + " is not Active");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cashApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
if (tokNo == null || tokNo.isBlank()) {
|
||||||
|
throw apiError(400, "Token number (TOK. NO.) is required when cashApplyAmount is greater than zero");
|
||||||
|
}
|
||||||
|
validateTokenUniqueToday(tokNo, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
final Long existingPending = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM m_share_dividend_claim_request WHERE lock_id = ? AND status = 'PENDING'", Long.class, lockId);
|
||||||
|
if (existingPending != null && existingPending > 0) {
|
||||||
|
throw apiError(409, "A claim request for this dividend is already pending review.");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Long newId = jdbcTemplate.queryForObject("""
|
||||||
|
INSERT INTO m_share_dividend_claim_request
|
||||||
|
(lock_id, client_id, savings_account_id, requested_amount, loan_id, loan_apply_amount, savings_apply_amount,
|
||||||
|
cash_apply_amount, status, clerk_id, clerk_name, submitted_at, tok_no)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?)
|
||||||
|
RETURNING id
|
||||||
|
""", Long.class, lockId, clientId, resolvedSavingsAccountId, total, loanId, loanApplyAmount, savingsApplyAmount,
|
||||||
|
cashApplyAmount, currentUser.getId(), currentUser.getDisplayName(), Timestamp.from(Instant.now()),
|
||||||
|
cashApplyAmount.compareTo(BigDecimal.ZERO) > 0 ? tokNo : null);
|
||||||
|
|
||||||
|
return gson.toJson(Map.of("resourceId", newId, "status", "PENDING"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures the token number is unique for today's date across both this table and
|
||||||
|
* {@code m_clerk_withdrawal_request} -- cashiers type either kind of token into the same
|
||||||
|
* Transaction Entry field, so the two pools must never collide.
|
||||||
|
*/
|
||||||
|
private void validateTokenUniqueToday(final String tokNo, final Long excludeId) {
|
||||||
|
final StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM m_share_dividend_claim_request "
|
||||||
|
+ "WHERE tok_no = ? AND CAST(submitted_at AS DATE) = CURRENT_DATE AND status <> 'REJECTED'");
|
||||||
|
final List<Object> params = new ArrayList<>();
|
||||||
|
params.add(tokNo);
|
||||||
|
if (excludeId != null) {
|
||||||
|
sql.append(" AND id <> ?");
|
||||||
|
params.add(excludeId);
|
||||||
|
}
|
||||||
|
final Long ownCount = jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray());
|
||||||
|
final Long otherCount = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM m_clerk_withdrawal_request "
|
||||||
|
+ "WHERE tok_no = ? AND CAST(submitted_at AS DATE) = CURRENT_DATE AND status <> 'REJECTED'", Long.class, tokNo);
|
||||||
|
final long total = (ownCount == null ? 0 : ownCount) + (otherCount == null ? 0 : otherCount);
|
||||||
|
if (total > 0) {
|
||||||
|
throw apiError(400, "Token number '" + tokNo + "' is already used today. Please enter a different token number.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseAmount(final String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new BigDecimal(value.trim());
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
throw apiError(400, "'" + value + "' is not a valid amount");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-claim-requests ── Manager sees claim requests ────
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String list(@QueryParam("status") @DefaultValue("PENDING") final String status) {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT " + String.join(", ", LIST_COLUMNS) + """
|
||||||
|
FROM m_share_dividend_claim_request r
|
||||||
|
JOIN m_client c ON c.id = r.client_id
|
||||||
|
LEFT JOIN m_savings_account sav ON sav.id = r.savings_account_id
|
||||||
|
JOIN m_share_dividend_lock l ON l.id = r.lock_id
|
||||||
|
WHERE r.status = ?
|
||||||
|
ORDER BY r.submitted_at ASC
|
||||||
|
""", status);
|
||||||
|
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final Long clientId = ((Number) row.get("client_id")).longValue();
|
||||||
|
row.put("has_overdue_loan", hasOverdueLoan(clientId));
|
||||||
|
}
|
||||||
|
return gson.toJson(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasOverdueLoan(final Long clientId) {
|
||||||
|
final Long count = jdbcTemplate.queryForObject("""
|
||||||
|
SELECT COUNT(*) FROM m_loan ln JOIN m_loan_repayment_schedule ri ON ri.loan_id = ln.id
|
||||||
|
WHERE ln.client_id = ? AND ln.loan_status_id = 300 AND ri.completed_derived = false AND ri.duedate < CURRENT_DATE
|
||||||
|
""", Long.class, clientId);
|
||||||
|
return count != null && count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POST /v1/clerk/dividend-claim-requests/{id}/approve ── Manager executes the disbursement ──
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/{id}/approve")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Transactional
|
||||||
|
public String approve(@PathParam("id") final Long id, final String body) {
|
||||||
|
final AppUser currentUser = context.authenticatedUser();
|
||||||
|
validateCheckerRole(currentUser);
|
||||||
|
final Map<String, Object> record = loadRecord(id);
|
||||||
|
|
||||||
|
if (!"PENDING".equals(record.get("status"))) {
|
||||||
|
throw apiError(409, "Only PENDING claim requests can be approved. Current status: " + record.get("status"));
|
||||||
|
}
|
||||||
|
final Long makerId = ((Number) record.get("clerk_id")).longValue();
|
||||||
|
if (makerId.equals(currentUser.getId())) {
|
||||||
|
throw apiError(403, "Maker-checker: you cannot approve a dividend claim you submitted yourself. Ask another manager.");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Long lockId = ((Number) record.get("lock_id")).longValue();
|
||||||
|
final Map<String, Object> lock = jdbcTemplate
|
||||||
|
.queryForList("SELECT currency_code, amount, status FROM m_share_dividend_lock WHERE id = ?", lockId).stream()
|
||||||
|
.findFirst().orElseThrow(() -> apiError(404, "Dividend lock not found: " + lockId));
|
||||||
|
if (!"UNCLAIMED".equals(lock.get("status"))) {
|
||||||
|
throw apiError(409, "This dividend is no longer UNCLAIMED (status: " + lock.get("status") + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
final String currencyCode = (String) lock.get("currency_code");
|
||||||
|
final BigDecimal unclaimedAmount = (BigDecimal) lock.get("amount");
|
||||||
|
final BigDecimal loanApplyAmount = (BigDecimal) record.get("loan_apply_amount");
|
||||||
|
final BigDecimal savingsApplyAmount = (BigDecimal) record.get("savings_apply_amount");
|
||||||
|
final BigDecimal cashApplyAmount = (BigDecimal) record.get("cash_apply_amount");
|
||||||
|
final BigDecimal total = loanApplyAmount.add(savingsApplyAmount).add(cashApplyAmount);
|
||||||
|
if (total.compareTo(unclaimedAmount) > 0) {
|
||||||
|
throw apiError(409,
|
||||||
|
"The unclaimed amount has since reduced below what this claim requested -- reject this claim and resubmit.");
|
||||||
|
}
|
||||||
|
final Object claimSavingsAccountId = record.get("savings_account_id");
|
||||||
|
if (savingsApplyAmount.compareTo(BigDecimal.ZERO) > 0 && claimSavingsAccountId == null) {
|
||||||
|
throw apiError(409, "No savings account was recorded on this claim for the savings-credit portion.");
|
||||||
|
}
|
||||||
|
|
||||||
|
final LocalDate today = DateUtils.getBusinessLocalDate();
|
||||||
|
final String note = "Dividend claim #" + id + " (lock #" + lockId + ")";
|
||||||
|
|
||||||
|
if (loanApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
final Long loanId = ((Number) record.get("loan_id")).longValue();
|
||||||
|
final JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("locale", "en");
|
||||||
|
payload.addProperty("dateFormat", "yyyy-MM-dd");
|
||||||
|
payload.addProperty("transactionDate", today.toString());
|
||||||
|
payload.addProperty("transactionAmount", loanApplyAmount);
|
||||||
|
payload.addProperty("note", note);
|
||||||
|
final CommandWrapper repaymentCommand = new CommandWrapperBuilder().loanRepaymentTransaction(loanId)
|
||||||
|
.withJson(payload.toString()).build();
|
||||||
|
final CommandProcessingResult repaymentResult = commandsSourceWritePlatformService.logCommandSource(repaymentCommand);
|
||||||
|
redirectFundSourceDebitToDividendPayable(repaymentResult.getResourceId(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (savingsApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
final JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("locale", "en");
|
||||||
|
payload.addProperty("dateFormat", "yyyy-MM-dd");
|
||||||
|
payload.addProperty("transactionDate", today.toString());
|
||||||
|
payload.addProperty("transactionAmount", savingsApplyAmount);
|
||||||
|
payload.addProperty("note", note);
|
||||||
|
payload.addProperty("paymentTypeId", resolveDividendClaimPaymentTypeId());
|
||||||
|
final Long savingsAccountId = ((Number) claimSavingsAccountId).longValue();
|
||||||
|
final CommandWrapper depositCommand = new CommandWrapperBuilder().savingsAccountDeposit(savingsAccountId)
|
||||||
|
.withJson(payload.toString()).build();
|
||||||
|
final CommandProcessingResult depositResult = commandsSourceWritePlatformService.logCommandSource(depositCommand);
|
||||||
|
redirectFundSourceDebitToDividendPayable(null, depositResult.getResourceId());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cashApplyAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
payCashFromDividendPayable(id, currencyCode, cashApplyAmount, today);
|
||||||
|
}
|
||||||
|
|
||||||
|
final BigDecimal remainder = unclaimedAmount.subtract(total);
|
||||||
|
if (remainder.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
jdbcTemplate.update("UPDATE m_share_dividend_lock SET amount = ?, last_modified_date = now() WHERE id = ?", remainder,
|
||||||
|
lockId);
|
||||||
|
} else {
|
||||||
|
jdbcTemplate.update("UPDATE m_share_dividend_lock SET status = 'CLAIMED', last_modified_date = now() WHERE id = ?", lockId);
|
||||||
|
}
|
||||||
|
|
||||||
|
final String cashStatus = cashApplyAmount.compareTo(BigDecimal.ZERO) > 0 ? "AWAITING_DISBURSEMENT" : null;
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
UPDATE m_share_dividend_claim_request SET status = 'APPROVED', manager_id = ?, manager_name = ?, actioned_at = ?,
|
||||||
|
cash_status = ?
|
||||||
|
WHERE id = ? AND status = 'PENDING'
|
||||||
|
""", currentUser.getId(), currentUser.getDisplayName(), Timestamp.from(Instant.now()), cashStatus, id);
|
||||||
|
|
||||||
|
final JsonObject response = new JsonObject();
|
||||||
|
response.addProperty("resourceId", id);
|
||||||
|
response.addProperty("status", "APPROVED");
|
||||||
|
response.addProperty("totalDisbursed", total);
|
||||||
|
response.addProperty("remainingUnclaimed", remainder.max(BigDecimal.ZERO));
|
||||||
|
return gson.toJson(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-claim-requests/by-token/{token} ── Cashier token lookup ──
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors {@code ClerkWithdrawalRequestApiResource.getByToken} -- a cashier at Transaction
|
||||||
|
* Entry types the clerk-supplied token number here to resolve the approved cash amount before
|
||||||
|
* disbursing it, instead of the manager handing over cash directly at approval time.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("/by-token/{token}")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String getByToken(@PathParam("token") final String token) {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
|
||||||
|
SELECT r.id, r.client_id, c.display_name AS client_name, r.cash_apply_amount AS amount,
|
||||||
|
r.tok_no, r.status, r.cash_status, r.submitted_at, r.actioned_at
|
||||||
|
FROM m_share_dividend_claim_request r
|
||||||
|
JOIN m_client c ON c.id = r.client_id
|
||||||
|
WHERE r.tok_no = ? AND CAST(r.submitted_at AS DATE) = CURRENT_DATE
|
||||||
|
ORDER BY r.submitted_at DESC LIMIT 1
|
||||||
|
""", token);
|
||||||
|
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
throw apiError(404, "Token '" + token + "' not found for today. Please check the token number.");
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<String, Object> row = rows.get(0);
|
||||||
|
final String status = String.valueOf(row.get("status"));
|
||||||
|
final String cashStatus = row.get("cash_status") == null ? null : String.valueOf(row.get("cash_status"));
|
||||||
|
|
||||||
|
if ("PENDING".equals(status)) {
|
||||||
|
throw apiError(422, "Token '" + token + "' is still PENDING — manager has not approved this claim yet.");
|
||||||
|
}
|
||||||
|
if ("REJECTED".equals(status)) {
|
||||||
|
throw apiError(422, "Token '" + token + "' was REJECTED by the manager. This claim cannot be processed.");
|
||||||
|
}
|
||||||
|
if (!"APPROVED".equals(status)) {
|
||||||
|
throw apiError(422, "Token '" + token + "' has unexpected status: " + status);
|
||||||
|
}
|
||||||
|
if ("DISBURSED".equals(cashStatus)) {
|
||||||
|
throw apiError(422, "Token '" + token + "' has already been withdrawn. Cash was handed over by another cashier.");
|
||||||
|
}
|
||||||
|
if (!"AWAITING_DISBURSEMENT".equals(cashStatus)) {
|
||||||
|
throw apiError(422, "Token '" + token + "' has no cash portion awaiting disbursement.");
|
||||||
|
}
|
||||||
|
return gson.toJson(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POST /v1/clerk/dividend-claim-requests/{id}/disburse ── Cashier confirms cash hand-over ──
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors {@code ClerkWithdrawalRequestApiResource.disburse} -- the GL entry already posted at
|
||||||
|
* approve time, so this step is purely a physical-cash-handover record with double-disbursement
|
||||||
|
* protection ({@code WHERE cash_status = 'AWAITING_DISBURSEMENT'}), never a new transaction.
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@Path("/{id}/disburse")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Transactional
|
||||||
|
public String disburse(@PathParam("id") final Long id, final String body) {
|
||||||
|
final AppUser currentUser = context.authenticatedUser();
|
||||||
|
final Map<String, Object> record = jdbcTemplate
|
||||||
|
.queryForList("SELECT id, lock_id, client_id, cash_apply_amount, cash_status FROM m_share_dividend_claim_request WHERE id = ?",
|
||||||
|
id)
|
||||||
|
.stream().findFirst().orElseThrow(() -> new NotFoundException("Dividend claim request not found: " + id));
|
||||||
|
|
||||||
|
final String cashStatus = record.get("cash_status") == null ? null : String.valueOf(record.get("cash_status"));
|
||||||
|
if (!"AWAITING_DISBURSEMENT".equals(cashStatus)) {
|
||||||
|
throw apiError(409, "Only claims AWAITING_DISBURSEMENT can be disbursed. Current cash status: " + cashStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
String denominationData = null;
|
||||||
|
BigDecimal transactionAmount = null;
|
||||||
|
if (body != null && !body.isBlank()) {
|
||||||
|
final JsonElement root = fromJsonHelper.parse(body);
|
||||||
|
denominationData = fromJsonHelper.extractStringNamed("denominationData", root);
|
||||||
|
transactionAmount = parseAmount(fromJsonHelper.extractStringNamed("transactionAmount", root));
|
||||||
|
}
|
||||||
|
if (transactionAmount == null || transactionAmount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
throw apiError(400, "transactionAmount is required and must be greater than zero for disbursement.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// cash_apply_amount is floored to whole rupees at submit time now (see submit() above),
|
||||||
|
// but a claim created before that fix may still carry paise -- floor here too so an older
|
||||||
|
// claim can still be disbursed in whole-rupee cash rather than being stuck forever.
|
||||||
|
final BigDecimal cashApplyAmount = (BigDecimal) record.get("cash_apply_amount");
|
||||||
|
final BigDecimal disbursableAmount = cashApplyAmount.setScale(0, RoundingMode.FLOOR);
|
||||||
|
if (disbursableAmount.compareTo(transactionAmount) != 0) {
|
||||||
|
throw apiError(400, "Transaction amount " + transactionAmount + " does not match the claim's disbursable cash amount of "
|
||||||
|
+ disbursableAmount + " (cash can only be handed over in whole rupees).");
|
||||||
|
}
|
||||||
|
|
||||||
|
final long denomTotal = denominationTotal(denominationData);
|
||||||
|
if (denomTotal > 0 && BigDecimal.valueOf(denomTotal).compareTo(transactionAmount) != 0) {
|
||||||
|
throw apiError(400,
|
||||||
|
"Cash denomination total " + denomTotal + " does not match disbursement amount " + transactionAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
final int updated = jdbcTemplate.update("""
|
||||||
|
UPDATE m_share_dividend_claim_request SET
|
||||||
|
cash_status = 'DISBURSED', cashier_id = ?, disbursed_by = ?, disbursement_denomination_data = ?, disbursed_at = ?
|
||||||
|
WHERE id = ? AND cash_status = 'AWAITING_DISBURSEMENT'
|
||||||
|
""", currentUser.getId(), currentUser.getDisplayName(), denominationData, Timestamp.from(Instant.now()), id);
|
||||||
|
|
||||||
|
if (updated == 0) {
|
||||||
|
throw apiError(409, "This dividend cash claim has already been withdrawn by another cashier. Double disbursement prevented.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (denominationData != null && !denominationData.isBlank()) {
|
||||||
|
final Long clientId = ((Number) record.get("client_id")).longValue();
|
||||||
|
final Long lockId = ((Number) record.get("lock_id")).longValue();
|
||||||
|
saveDisbursementDenomination(id, clientId, lockId, denominationData, currentUser);
|
||||||
|
}
|
||||||
|
|
||||||
|
return gson.toJson(Map.of("resourceId", id, "status", "DISBURSED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sums a {"note:500": 2, "coin:1": 10} breakdown; 0 when absent or empty. */
|
||||||
|
private long denominationTotal(final String denominationData) {
|
||||||
|
if (denominationData == null || denominationData.isBlank()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
final JsonObject denomMap;
|
||||||
|
try {
|
||||||
|
denomMap = gson.fromJson(denominationData, JsonObject.class);
|
||||||
|
} catch (final Exception e) {
|
||||||
|
throw apiError(400, "denominationData is not valid JSON");
|
||||||
|
}
|
||||||
|
if (denomMap == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
long total = 0;
|
||||||
|
for (final Map.Entry<String, JsonElement> entry : denomMap.entrySet()) {
|
||||||
|
final String[] parts = entry.getKey().split(":", 2);
|
||||||
|
if (parts.length != 2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final int value;
|
||||||
|
final int count;
|
||||||
|
try {
|
||||||
|
value = Integer.parseInt(parts[1]);
|
||||||
|
count = entry.getValue().getAsInt();
|
||||||
|
} catch (final Exception e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (count > 0) {
|
||||||
|
total += (long) value * count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the cashier's note/coin breakdown for a dividend cash disbursement into
|
||||||
|
* {@code m_savings_txn_denomination} for vault-position reporting. There is no native savings
|
||||||
|
* transaction backing this (the cash leg is a pure GL entry posted at approve time), so this
|
||||||
|
* claim request's own id is used as the stable txn identifier for grouping.
|
||||||
|
*/
|
||||||
|
private void saveDisbursementDenomination(final Long claimRequestId, final Long clientId, final Long lockId,
|
||||||
|
final String denominationData, final AppUser cashier) {
|
||||||
|
final JsonObject denomMap;
|
||||||
|
try {
|
||||||
|
denomMap = gson.fromJson(denominationData, JsonObject.class);
|
||||||
|
} catch (final Exception e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (denomMap == null || denomMap.size() == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final Map.Entry<String, JsonElement> entry : denomMap.entrySet()) {
|
||||||
|
final int count;
|
||||||
|
try {
|
||||||
|
count = entry.getValue().getAsInt();
|
||||||
|
} catch (final Exception e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (count <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
final String[] parts = entry.getKey().split(":", 2);
|
||||||
|
if (parts.length != 2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final String kind = parts[0];
|
||||||
|
final int value;
|
||||||
|
try {
|
||||||
|
value = Integer.parseInt(parts[1]);
|
||||||
|
} catch (final Exception e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<Long> ids = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id FROM m_denomination_master WHERE denomination = ? AND kind = ? AND (deleted IS NULL OR deleted = false) LIMIT 1",
|
||||||
|
Long.class, value, kind);
|
||||||
|
if (ids.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final Long denomId = ids.get(0);
|
||||||
|
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_savings_txn_denomination
|
||||||
|
(txn_id, savings_account_id, account_no, client_id, denomination_id,
|
||||||
|
denomination_value, count, total_amount, txn_date, txn_type, officer_id, officer_username)
|
||||||
|
VALUES (?, NULL, ?, ?, ?, ?, ?, ?, CURRENT_DATE, 'WITHDRAWAL', ?, ?)
|
||||||
|
""", claimRequestId, "DIVIDEND-" + lockId, clientId, denomId, value, count,
|
||||||
|
BigDecimal.valueOf((long) value * count), cashier.getId(), cashier.getUsername());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fineract's savings deposit command mandates paymentTypeId even for an internal posting with
|
||||||
|
* no real customer payment instrument -- resolves the system-seeded "Dividend Claim
|
||||||
|
* Settlement" payment type (see migration 0464) rather than hardcoding a numeric id, which
|
||||||
|
* would break on any tenant seeded differently.
|
||||||
|
*/
|
||||||
|
private Long resolveDividendClaimPaymentTypeId() {
|
||||||
|
final Long paymentTypeId = jdbcTemplate
|
||||||
|
.queryForList("SELECT id FROM m_payment_type WHERE code_name = 'DIVIDEND_CLAIM_SETTLEMENT'", Long.class).stream()
|
||||||
|
.findFirst().orElse(null);
|
||||||
|
if (paymentTypeId == null) {
|
||||||
|
throw apiError(500, "Payment type 'DIVIDEND_CLAIM_SETTLEMENT' is not seeded -- run the latest database migrations.");
|
||||||
|
}
|
||||||
|
return paymentTypeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The loan repayment / savings deposit command just posted its own native GL entries assuming
|
||||||
|
* the money came out of whichever account is that product's actual Fund Source (not always
|
||||||
|
* literally "Cash at Main Vault" -- e.g. a Loan-Against-Warehouse-Receipt product debits its
|
||||||
|
* own "Warehouse Receipt" account instead) -- it didn't really. Rather than reverse that with
|
||||||
|
* a second manual entry pair (which would leave that fund-source account appearing twice, once
|
||||||
|
* debited then immediately credited back -- a confusing "wash" no real accountant would post),
|
||||||
|
* this rewrites that same DEBIT leg's account in place to Dividend Payable, so the transaction
|
||||||
|
* ends up with exactly the entries a real accountant would expect: Dividend Payable debited,
|
||||||
|
* Loan Portfolio/Income or Savings credited, nothing else touched. Skipped (loan/savings still
|
||||||
|
* updated) if the bank hasn't mapped the Dividend Payable financial activity. Exactly one of
|
||||||
|
* the two ids is non-null per call.
|
||||||
|
*/
|
||||||
|
private void redirectFundSourceDebitToDividendPayable(final Long loanTransactionId, final Long savingsTransactionId) {
|
||||||
|
final Long payableDividendsAccountId = jdbcTemplate
|
||||||
|
.queryForList("SELECT gl_account_id FROM acc_gl_financial_activity_account WHERE financial_activity_type = ?", Long.class,
|
||||||
|
FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS)
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
if (payableDividendsAccountId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (loanTransactionId != null) {
|
||||||
|
jdbcTemplate.update("UPDATE acc_gl_journal_entry SET account_id = ? WHERE loan_transaction_id = ? AND type_enum = ?",
|
||||||
|
payableDividendsAccountId, loanTransactionId, JOURNAL_ENTRY_TYPE_DEBIT);
|
||||||
|
}
|
||||||
|
if (savingsTransactionId != null) {
|
||||||
|
jdbcTemplate.update("UPDATE acc_gl_journal_entry SET account_id = ? WHERE savings_transaction_id = ? AND type_enum = ?",
|
||||||
|
payableDividendsAccountId, savingsTransactionId, JOURNAL_ENTRY_TYPE_DEBIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A straight cash handover has no account to post through, so Cash at Main Vault genuinely is
|
||||||
|
* correct here (unlike the loan/savings legs above) -- real cash leaves the vault into the
|
||||||
|
* member's hand.
|
||||||
|
*/
|
||||||
|
private void payCashFromDividendPayable(final Long claimRequestId, final String currencyCode, final BigDecimal amount,
|
||||||
|
final LocalDate entryDate) {
|
||||||
|
final Long payableDividendsAccountId = jdbcTemplate
|
||||||
|
.queryForList("SELECT gl_account_id FROM acc_gl_financial_activity_account WHERE financial_activity_type = ?", Long.class,
|
||||||
|
FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS)
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
final Long cashAtVaultAccountId = jdbcTemplate
|
||||||
|
.queryForList("SELECT gl_account_id FROM acc_gl_financial_activity_account WHERE financial_activity_type = ?", Long.class,
|
||||||
|
FINANCIAL_ACTIVITY_CASH_AT_MAINVAULT)
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
if (payableDividendsAccountId == null || cashAtVaultAccountId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final AppUser currentUser = context.authenticatedUser();
|
||||||
|
final java.sql.Date sqlEntryDate = java.sql.Date.valueOf(entryDate);
|
||||||
|
final String transactionId = "DIVCLAIM" + claimRequestId + "-" + System.nanoTime();
|
||||||
|
final String description = "Dividend claim #" + claimRequestId + " disbursed";
|
||||||
|
final String insertSql = """
|
||||||
|
INSERT INTO acc_gl_journal_entry
|
||||||
|
(account_id, office_id, currency_code, transaction_id, reversed, manual_entry, entry_date, type_enum, amount,
|
||||||
|
description, created_by, last_modified_by, created_date, lastmodified_date, created_on_utc, last_modified_on_utc,
|
||||||
|
submitted_on_date, transaction_date)
|
||||||
|
VALUES (?, 1, ?, ?, false, true, ?, ?, ?, ?, ?, ?, now(), now(), now(), now(), ?, ?)
|
||||||
|
""";
|
||||||
|
this.jdbcTemplate.update(insertSql, payableDividendsAccountId, currencyCode, transactionId, sqlEntryDate, 2, amount, description,
|
||||||
|
currentUser.getId(), currentUser.getId(), sqlEntryDate, sqlEntryDate);
|
||||||
|
this.jdbcTemplate.update(insertSql, cashAtVaultAccountId, currencyCode, transactionId, sqlEntryDate, 1, amount, description,
|
||||||
|
currentUser.getId(), currentUser.getId(), sqlEntryDate, sqlEntryDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POST /v1/clerk/dividend-claim-requests/{id}/reject ── Manager rejects ───
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/{id}/reject")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Transactional
|
||||||
|
public String reject(@PathParam("id") final Long id, final String body) {
|
||||||
|
final AppUser currentUser = context.authenticatedUser();
|
||||||
|
validateCheckerRole(currentUser);
|
||||||
|
final Map<String, Object> record = loadRecord(id);
|
||||||
|
|
||||||
|
if (!"PENDING".equals(record.get("status"))) {
|
||||||
|
throw apiError(409, "Only PENDING claim requests can be rejected. Current status: " + record.get("status"));
|
||||||
|
}
|
||||||
|
|
||||||
|
final JsonElement root = fromJsonHelper.parse(body != null && !body.isBlank() ? body : "{}");
|
||||||
|
final String reason = fromJsonHelper.extractStringNamed("reason", root);
|
||||||
|
if (reason == null || reason.isBlank()) {
|
||||||
|
throw apiError(400, "Rejection reason is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
UPDATE m_share_dividend_claim_request SET
|
||||||
|
status = 'REJECTED', manager_id = ?, manager_name = ?, rejection_reason = ?, actioned_at = ?
|
||||||
|
WHERE id = ? AND status = 'PENDING'
|
||||||
|
""", currentUser.getId(), currentUser.getDisplayName(), reason, Timestamp.from(Instant.now()), id);
|
||||||
|
|
||||||
|
return gson.toJson(Map.of("resourceId", id, "status", "REJECTED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateCheckerRole(final AppUser user) {
|
||||||
|
if (user.hasAnyPermission("ALL_FUNCTIONS")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final boolean isChecker = user.getRoles().stream().map(r -> r.getName() == null ? "" : r.getName().toLowerCase().trim())
|
||||||
|
.anyMatch(n -> n.contains("manager") || n.contains("head cashier"));
|
||||||
|
if (!isChecker) {
|
||||||
|
throw apiError(403, "Only a Bank Manager (or Head Cashier) can approve or reject a dividend claim request.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> loadRecord(final Long id) {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
|
||||||
|
SELECT id, lock_id, client_id, savings_account_id, loan_id, loan_apply_amount, savings_apply_amount, cash_apply_amount,
|
||||||
|
status, clerk_id, clerk_name
|
||||||
|
FROM m_share_dividend_claim_request WHERE id = ?
|
||||||
|
""", id);
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
throw new NotFoundException("Dividend claim request not found: " + id);
|
||||||
|
}
|
||||||
|
return rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebApplicationException apiError(final int httpStatus, final String message) {
|
||||||
|
final JsonObject errorBody = new JsonObject();
|
||||||
|
errorBody.addProperty("message", message);
|
||||||
|
errorBody.addProperty("defaultUserMessage", message);
|
||||||
|
errorBody.addProperty("httpStatus", httpStatus);
|
||||||
|
return new WebApplicationException(
|
||||||
|
Response.status(httpStatus).entity(gson.toJson(errorBody)).type(MediaType.APPLICATION_JSON).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
+400
@@ -0,0 +1,400 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.dividenddashboard.api;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.Consumes;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.WebApplicationException;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
||||||
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bank Manager's Dividend Dashboard: summary stats, every dividend ever declared and its payout
|
||||||
|
* progress, full 3-year lock history, and members whose unclaimed dividend (see
|
||||||
|
* {@code m_share_dividend_lock}) sits alongside an overdue loan installment so the manager can
|
||||||
|
* proactively apply it towards that EMI instead of waiting for the member to claim it or for it
|
||||||
|
* to be forfeited to profit after 3 years.
|
||||||
|
*/
|
||||||
|
@Path("/v1/clerk/dividend-dashboard")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Dividend Dashboard", description = "Bank Manager view of locked share dividends belonging to members with overdue loan EMIs, with an action to apply the dividend towards the loan.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DividendDashboardApiResource {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final FromJsonHelper fromJsonHelper;
|
||||||
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
|
private final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
|
||||||
|
|
||||||
|
private static final int FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS = 201;
|
||||||
|
private static final int JOURNAL_ENTRY_TYPE_DEBIT = 2;
|
||||||
|
|
||||||
|
private static final int DIVIDEND_PAYOUT_STATUS_PENDING_APPROVAL = 100;
|
||||||
|
private static final int DIVIDEND_PAYOUT_STATUS_APPROVED = 300;
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-dashboard/summary ─────────────────────────────────
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/summary")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String summary() {
|
||||||
|
final Map<String, Object> declarationStats = jdbcTemplate.queryForMap("""
|
||||||
|
SELECT COUNT(*) AS total_declarations,
|
||||||
|
COUNT(*) FILTER (WHERE status = %d) AS pending_approval_declarations,
|
||||||
|
COUNT(*) FILTER (WHERE status = %d) AS approved_declarations
|
||||||
|
FROM m_share_product_dividend_pay_out
|
||||||
|
""".formatted(DIVIDEND_PAYOUT_STATUS_PENDING_APPROVAL, DIVIDEND_PAYOUT_STATUS_APPROVED));
|
||||||
|
|
||||||
|
// Approval and disbursement now happen atomically (see
|
||||||
|
// ShareProductWritePlatformServiceJpaRepositoryImpl.makeDividendsClaimable) -- there's no
|
||||||
|
// more "posted vs pending vs failed" spread to track at the detail level once approved.
|
||||||
|
final Map<String, Object> detailStats = jdbcTemplate.queryForMap("""
|
||||||
|
SELECT COUNT(DISTINCT sa.client_id) AS members_affected,
|
||||||
|
COUNT(sad.id) AS total_member_dividends,
|
||||||
|
COALESCE(SUM(sad.amount), 0) AS total_amount
|
||||||
|
FROM m_share_account_dividend_details sad
|
||||||
|
JOIN m_share_account sa ON sa.id = sad.account_id
|
||||||
|
""");
|
||||||
|
|
||||||
|
final Map<String, Object> lockStats = jdbcTemplate.queryForMap("""
|
||||||
|
SELECT COUNT(*) FILTER (WHERE status = 'UNCLAIMED') AS locked_count,
|
||||||
|
COALESCE(SUM(amount) FILTER (WHERE status = 'UNCLAIMED'), 0) AS locked_amount,
|
||||||
|
COUNT(*) FILTER (WHERE status = 'CLAIMED' AND applied_loan_id IS NOT NULL) AS applied_count,
|
||||||
|
COALESCE(SUM(amount) FILTER (WHERE status = 'CLAIMED' AND applied_loan_id IS NOT NULL), 0) AS applied_amount,
|
||||||
|
COUNT(*) FILTER (WHERE status = 'FORFEITED') AS forfeited_count,
|
||||||
|
COALESCE(SUM(amount) FILTER (WHERE status = 'FORFEITED'), 0) AS forfeited_amount,
|
||||||
|
COUNT(*) FILTER (WHERE status = 'CLAIMED') AS claimed_count,
|
||||||
|
COALESCE(SUM(amount) FILTER (WHERE status = 'CLAIMED'), 0) AS claimed_amount
|
||||||
|
FROM m_share_dividend_lock
|
||||||
|
""");
|
||||||
|
|
||||||
|
final JsonObject result = new JsonObject();
|
||||||
|
result.addProperty("totalDeclarations", ((Number) declarationStats.get("total_declarations")).longValue());
|
||||||
|
result.addProperty("pendingApprovalDeclarations",
|
||||||
|
((Number) declarationStats.get("pending_approval_declarations")).longValue());
|
||||||
|
result.addProperty("approvedDeclarations", ((Number) declarationStats.get("approved_declarations")).longValue());
|
||||||
|
result.addProperty("membersAffected", ((Number) detailStats.get("members_affected")).longValue());
|
||||||
|
result.addProperty("totalMemberDividends", ((Number) detailStats.get("total_member_dividends")).longValue());
|
||||||
|
result.addProperty("totalAmount", (BigDecimal) detailStats.get("total_amount"));
|
||||||
|
result.addProperty("lockedCount", ((Number) lockStats.get("locked_count")).longValue());
|
||||||
|
result.addProperty("lockedAmount", (BigDecimal) lockStats.get("locked_amount"));
|
||||||
|
result.addProperty("appliedToLoanCount", ((Number) lockStats.get("applied_count")).longValue());
|
||||||
|
result.addProperty("appliedToLoanAmount", (BigDecimal) lockStats.get("applied_amount"));
|
||||||
|
result.addProperty("forfeitedCount", ((Number) lockStats.get("forfeited_count")).longValue());
|
||||||
|
result.addProperty("forfeitedAmount", (BigDecimal) lockStats.get("forfeited_amount"));
|
||||||
|
result.addProperty("claimedCount", ((Number) lockStats.get("claimed_count")).longValue());
|
||||||
|
result.addProperty("claimedAmount", (BigDecimal) lockStats.get("claimed_amount"));
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-dashboard/declarations ────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every dividend ever declared (across every share product), so a manager tracking multiple
|
||||||
|
* dividends at once can see -- per declaration -- how many members it covers and how far its
|
||||||
|
* payout has actually progressed, not just whether it was approved.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("/declarations")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String declarations() {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
|
||||||
|
SELECT spd.id AS declaration_id, sp.name AS product_name,
|
||||||
|
spd.dividend_period_start_date, spd.dividend_period_end_date, spd.amount AS declared_amount,
|
||||||
|
spd.status AS declaration_status, spd.created_date, spd.lastmodified_date AS approved_on,
|
||||||
|
COUNT(sad.id) AS total_members,
|
||||||
|
COALESCE(SUM(sad.amount), 0) AS total_distributed_amount
|
||||||
|
FROM m_share_product_dividend_pay_out spd
|
||||||
|
JOIN m_share_product sp ON sp.id = spd.product_id
|
||||||
|
LEFT JOIN m_share_account_dividend_details sad ON sad.dividend_pay_out_id = spd.id
|
||||||
|
GROUP BY spd.id, sp.name, spd.dividend_period_start_date, spd.dividend_period_end_date,
|
||||||
|
spd.amount, spd.status, spd.created_date, spd.lastmodified_date
|
||||||
|
ORDER BY spd.created_date DESC
|
||||||
|
""");
|
||||||
|
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final int declarationStatus = ((Number) row.get("declaration_status")).intValue();
|
||||||
|
final Timestamp approvedOn = (Timestamp) row.get("approved_on");
|
||||||
|
final boolean isApproved = declarationStatus == DIVIDEND_PAYOUT_STATUS_APPROVED;
|
||||||
|
|
||||||
|
final JsonObject entry = new JsonObject();
|
||||||
|
entry.addProperty("declarationId", ((Number) row.get("declaration_id")).longValue());
|
||||||
|
entry.addProperty("productName", (String) row.get("product_name"));
|
||||||
|
entry.addProperty("periodStartDate", row.get("dividend_period_start_date").toString());
|
||||||
|
entry.addProperty("periodEndDate", row.get("dividend_period_end_date").toString());
|
||||||
|
entry.addProperty("declaredAmount", (BigDecimal) row.get("declared_amount"));
|
||||||
|
entry.addProperty("totalDistributedAmount", (BigDecimal) row.get("total_distributed_amount"));
|
||||||
|
entry.addProperty("createdDate", row.get("created_date").toString());
|
||||||
|
entry.addProperty("approvedOn", approvedOn == null ? null : approvedOn.toString());
|
||||||
|
entry.addProperty("totalMembers", ((Number) row.get("total_members")).longValue());
|
||||||
|
entry.addProperty("status", isApproved ? "APPROVED" : "PENDING_APPROVAL");
|
||||||
|
result.add(entry);
|
||||||
|
}
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-dashboard/locks ───────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full history of every 3-year dividend lock, regardless of status -- UNCLAIMED (still
|
||||||
|
* counting down), CLAIMED (a member claimed it, or a manager applied it to an overdue loan --
|
||||||
|
* see {@code applied_loan_id}) or FORFEITED (3 years passed unclaimed, swept to the bank's
|
||||||
|
* profit). Optional {@code status} query param filters to one.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("/locks")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String locks(@QueryParam("status") final String status) {
|
||||||
|
final boolean filterByStatus = status != null && !status.isBlank() && !"ALL".equalsIgnoreCase(status);
|
||||||
|
final String sql = "SELECT l.id AS lock_id, l.client_id, c.display_name AS client_name, l.savings_account_id, "
|
||||||
|
+ "sav.account_no AS savings_account_no, l.amount, l.locked_date, l.release_due_date, l.status, "
|
||||||
|
+ "l.applied_loan_id, ln.account_no AS applied_loan_account_no " //
|
||||||
|
+ "FROM m_share_dividend_lock l " //
|
||||||
|
+ "JOIN m_client c ON c.id = l.client_id " //
|
||||||
|
+ "LEFT JOIN m_savings_account sav ON sav.id = l.savings_account_id " //
|
||||||
|
+ "LEFT JOIN m_loan ln ON ln.id = l.applied_loan_id " //
|
||||||
|
+ (filterByStatus ? "WHERE l.status = ? " : "") //
|
||||||
|
+ "ORDER BY l.locked_date DESC";
|
||||||
|
final List<Map<String, Object>> rows = filterByStatus ? jdbcTemplate.queryForList(sql, status.toUpperCase())
|
||||||
|
: jdbcTemplate.queryForList(sql);
|
||||||
|
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final JsonObject entry = new JsonObject();
|
||||||
|
entry.addProperty("lockId", ((Number) row.get("lock_id")).longValue());
|
||||||
|
entry.addProperty("clientId", ((Number) row.get("client_id")).longValue());
|
||||||
|
entry.addProperty("clientName", (String) row.get("client_name"));
|
||||||
|
final Object savingsAccountId = row.get("savings_account_id");
|
||||||
|
entry.addProperty("savingsAccountId", savingsAccountId == null ? null : ((Number) savingsAccountId).longValue());
|
||||||
|
entry.addProperty("savingsAccountNo", (String) row.get("savings_account_no"));
|
||||||
|
entry.addProperty("amount", (BigDecimal) row.get("amount"));
|
||||||
|
entry.addProperty("lockedDate", row.get("locked_date").toString());
|
||||||
|
entry.addProperty("releaseDueDate", row.get("release_due_date").toString());
|
||||||
|
entry.addProperty("status", (String) row.get("status"));
|
||||||
|
final Object appliedLoanId = row.get("applied_loan_id");
|
||||||
|
entry.addProperty("appliedLoanId", appliedLoanId == null ? null : ((Number) appliedLoanId).longValue());
|
||||||
|
entry.addProperty("appliedLoanAccountNo", (String) row.get("applied_loan_account_no"));
|
||||||
|
result.add(entry);
|
||||||
|
}
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /v1/clerk/dividend-dashboard ─────────────────────────────────────────
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String list() {
|
||||||
|
final List<Map<String, Object>> locks = jdbcTemplate.queryForList("""
|
||||||
|
SELECT l.id AS lock_id, l.client_id, c.display_name AS client_name, l.savings_account_id, l.amount AS locked_amount,
|
||||||
|
l.locked_date, l.release_due_date
|
||||||
|
FROM m_share_dividend_lock l
|
||||||
|
JOIN m_client c ON c.id = l.client_id
|
||||||
|
WHERE l.status = 'UNCLAIMED'
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM m_loan ln JOIN m_loan_repayment_schedule ri ON ri.loan_id = ln.id
|
||||||
|
WHERE ln.client_id = l.client_id AND ln.loan_status_id = 300
|
||||||
|
AND ri.completed_derived = false AND ri.duedate < CURRENT_DATE
|
||||||
|
)
|
||||||
|
ORDER BY l.locked_date ASC
|
||||||
|
""");
|
||||||
|
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> lock : locks) {
|
||||||
|
final Long clientId = ((Number) lock.get("client_id")).longValue();
|
||||||
|
final JsonObject row = new JsonObject();
|
||||||
|
row.addProperty("lockId", ((Number) lock.get("lock_id")).longValue());
|
||||||
|
row.addProperty("clientId", clientId);
|
||||||
|
row.addProperty("clientName", (String) lock.get("client_name"));
|
||||||
|
final Object savingsAccountId = lock.get("savings_account_id");
|
||||||
|
row.addProperty("savingsAccountId", savingsAccountId == null ? null : ((Number) savingsAccountId).longValue());
|
||||||
|
row.addProperty("lockedAmount", (BigDecimal) lock.get("locked_amount"));
|
||||||
|
row.addProperty("lockedDate", lock.get("locked_date").toString());
|
||||||
|
row.addProperty("releaseDueDate", lock.get("release_due_date").toString());
|
||||||
|
row.add("overdueLoans", overdueLoansFor(clientId));
|
||||||
|
result.add(row);
|
||||||
|
}
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonArray overdueLoansFor(final Long clientId) {
|
||||||
|
final List<Map<String, Object>> loans = jdbcTemplate.queryForList("""
|
||||||
|
SELECT ln.id AS loan_id, ln.account_no,
|
||||||
|
SUM(GREATEST(ri.principal_amount - COALESCE(ri.principal_completed_derived, 0)
|
||||||
|
- COALESCE(ri.principal_writtenoff_derived, 0), 0)
|
||||||
|
+ GREATEST(ri.interest_amount - COALESCE(ri.interest_completed_derived, 0)
|
||||||
|
- COALESCE(ri.interest_writtenoff_derived, 0) - COALESCE(ri.interest_waived_derived, 0), 0)) AS overdue_amount
|
||||||
|
FROM m_loan ln JOIN m_loan_repayment_schedule ri ON ri.loan_id = ln.id
|
||||||
|
WHERE ln.client_id = ? AND ln.loan_status_id = 300 AND ri.completed_derived = false AND ri.duedate < CURRENT_DATE
|
||||||
|
GROUP BY ln.id, ln.account_no
|
||||||
|
ORDER BY overdue_amount DESC
|
||||||
|
""", clientId);
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> loan : loans) {
|
||||||
|
final JsonObject row = new JsonObject();
|
||||||
|
row.addProperty("loanId", ((Number) loan.get("loan_id")).longValue());
|
||||||
|
row.addProperty("accountNo", (String) loan.get("account_no"));
|
||||||
|
row.addProperty("overdueAmount", (BigDecimal) loan.get("overdue_amount"));
|
||||||
|
result.add(row);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POST /v1/clerk/dividend-dashboard/{lockId}/apply-to-loan ────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proactive recovery: a manager notices a member with an unclaimed dividend AND an overdue
|
||||||
|
* loan EMI (see {@code list()} above) and applies it without waiting for the member to visit
|
||||||
|
* and file a claim. Since the dividend was never credited into any savings account (it's a
|
||||||
|
* pure "Dividend Payable" GL liability until claimed -- see
|
||||||
|
* {@code DividendClaimRequestApiResource}), there's no hold to release or account-transfer to
|
||||||
|
* make: this posts a native loan repayment (so the loan's own schedule/state stays fully
|
||||||
|
* native and correct) and then redirects the debit leg it assumed the cash came from to the
|
||||||
|
* Dividend Payable liability instead -- identical mechanic to a claim's loan leg.
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@Path("/{lockId}/apply-to-loan")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Transactional
|
||||||
|
public String applyToLoan(@PathParam("lockId") final Long lockId, final String body) {
|
||||||
|
final Map<String, Object> lock = jdbcTemplate
|
||||||
|
.queryForList("SELECT client_id, currency_code, amount, status FROM m_share_dividend_lock WHERE id = ?", lockId).stream()
|
||||||
|
.findFirst().orElseThrow(() -> apiError(404, "Dividend lock not found: " + lockId));
|
||||||
|
if (!"UNCLAIMED".equals(lock.get("status"))) {
|
||||||
|
throw apiError(409, "This dividend is not currently UNCLAIMED (status: " + lock.get("status") + ")");
|
||||||
|
}
|
||||||
|
final Long clientId = ((Number) lock.get("client_id")).longValue();
|
||||||
|
final BigDecimal unclaimedAmount = (BigDecimal) lock.get("amount");
|
||||||
|
|
||||||
|
final JsonElement root = fromJsonHelper.parse(body);
|
||||||
|
final Long loanId = fromJsonHelper.extractLongNamed("loanId", root);
|
||||||
|
final String amountString = fromJsonHelper.extractStringNamed("amount", root);
|
||||||
|
if (loanId == null) {
|
||||||
|
throw apiError(400, "loanId is required");
|
||||||
|
}
|
||||||
|
BigDecimal applyAmount;
|
||||||
|
try {
|
||||||
|
applyAmount = amountString == null ? null : new BigDecimal(amountString.trim());
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
throw apiError(400, "amount must be a valid number");
|
||||||
|
}
|
||||||
|
if (applyAmount == null || applyAmount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||||
|
throw apiError(400, "amount must be greater than zero");
|
||||||
|
}
|
||||||
|
if (applyAmount.compareTo(unclaimedAmount) > 0) {
|
||||||
|
throw apiError(400, "amount cannot exceed the unclaimed dividend amount of " + unclaimedAmount);
|
||||||
|
}
|
||||||
|
final Map<String, Object> loan = jdbcTemplate.queryForList("SELECT client_id, loan_status_id FROM m_loan WHERE id = ?", loanId)
|
||||||
|
.stream().findFirst().orElseThrow(() -> apiError(404, "Loan not found: " + loanId));
|
||||||
|
if (!clientId.equals(((Number) loan.get("client_id")).longValue())) {
|
||||||
|
throw apiError(400, "Loan " + loanId + " does not belong to this dividend's client");
|
||||||
|
}
|
||||||
|
|
||||||
|
final LocalDate today = DateUtils.getBusinessLocalDate();
|
||||||
|
|
||||||
|
final JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("locale", "en");
|
||||||
|
payload.addProperty("dateFormat", "yyyy-MM-dd");
|
||||||
|
payload.addProperty("transactionDate", today.toString());
|
||||||
|
payload.addProperty("transactionAmount", applyAmount);
|
||||||
|
payload.addProperty("note", "Unclaimed share dividend applied to overdue loan EMI (lock #" + lockId + ")");
|
||||||
|
final CommandWrapper repaymentCommand = new CommandWrapperBuilder().loanRepaymentTransaction(loanId)
|
||||||
|
.withJson(payload.toString()).build();
|
||||||
|
final CommandProcessingResult repaymentResult = commandsSourceWritePlatformService.logCommandSource(repaymentCommand);
|
||||||
|
redirectFundSourceDebitToDividendPayable(repaymentResult.getResourceId());
|
||||||
|
|
||||||
|
final BigDecimal remainder = unclaimedAmount.subtract(applyAmount);
|
||||||
|
if (remainder.compareTo(BigDecimal.ZERO) > 0) {
|
||||||
|
jdbcTemplate.update("UPDATE m_share_dividend_lock SET amount = ?, last_modified_date = now() WHERE id = ?", remainder,
|
||||||
|
lockId);
|
||||||
|
} else {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
UPDATE m_share_dividend_lock
|
||||||
|
SET status = 'CLAIMED', applied_loan_id = ?, applied_transaction_id = ?, last_modified_date = now()
|
||||||
|
WHERE id = ?
|
||||||
|
""", loanId, repaymentResult.getResourceId(), lockId);
|
||||||
|
}
|
||||||
|
|
||||||
|
final JsonObject response = new JsonObject();
|
||||||
|
response.addProperty("lockId", lockId);
|
||||||
|
response.addProperty("appliedAmount", applyAmount);
|
||||||
|
response.addProperty("remainingUnclaimed", remainder.max(BigDecimal.ZERO));
|
||||||
|
return gson.toJson(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The loan repayment just posted above assumed the money came out of whichever account is
|
||||||
|
* this loan product's actual Fund Source (not always literally "Cash at Main Vault" -- e.g. a
|
||||||
|
* Loan-Against-Warehouse-Receipt product debits its own "Warehouse Receipt" account instead)
|
||||||
|
* -- it didn't really. Rather than reverse that with a second manual entry pair (which would
|
||||||
|
* leave that fund-source account appearing twice, once debited then immediately credited back
|
||||||
|
* -- a confusing "wash" no real accountant would post), this rewrites that same DEBIT leg's
|
||||||
|
* account in place to Dividend Payable, so the transaction ends up with exactly the entries a
|
||||||
|
* real accountant would expect: Dividend Payable debited, Loan Portfolio/Income credited,
|
||||||
|
* nothing else touched. Skipped (loan still updated) if the bank hasn't mapped the Dividend
|
||||||
|
* Payable financial activity.
|
||||||
|
*/
|
||||||
|
private void redirectFundSourceDebitToDividendPayable(final Long loanTransactionId) {
|
||||||
|
final Long payableDividendsAccountId = jdbcTemplate
|
||||||
|
.queryForList("SELECT gl_account_id FROM acc_gl_financial_activity_account WHERE financial_activity_type = ?", Long.class,
|
||||||
|
FINANCIAL_ACTIVITY_PAYABLE_DIVIDENDS)
|
||||||
|
.stream().findFirst().orElse(null);
|
||||||
|
if (payableDividendsAccountId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
jdbcTemplate.update("UPDATE acc_gl_journal_entry SET account_id = ? WHERE loan_transaction_id = ? AND type_enum = ?",
|
||||||
|
payableDividendsAccountId, loanTransactionId, JOURNAL_ENTRY_TYPE_DEBIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebApplicationException apiError(final int httpStatus, final String message) {
|
||||||
|
final JsonObject errorBody = new JsonObject();
|
||||||
|
errorBody.addProperty("message", message);
|
||||||
|
errorBody.addProperty("defaultUserMessage", message);
|
||||||
|
errorBody.addProperty("httpStatus", httpStatus);
|
||||||
|
return new WebApplicationException(
|
||||||
|
Response.status(httpStatus).entity(gson.toJson(errorBody)).type(MediaType.APPLICATION_JSON).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
+86
@@ -0,0 +1,86 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.dividenddashboard.api;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every Share Product's dividend declaration that is still awaiting approval — Fineract only
|
||||||
|
* exposes dividends scoped to one product at a time
|
||||||
|
* ({@code GET /shareproduct/{productId}/dividend}), so a Bank Manager has no single place to see
|
||||||
|
* "everything currently waiting on me" across products. This aggregates all
|
||||||
|
* {@code m_share_product_dividend_pay_out} rows still INITIATED so they can be surfaced on the
|
||||||
|
* Approval Center (Checker Inbox) alongside the other maker-checker request types. Approval
|
||||||
|
* itself still goes through Fineract's native {@code approveDividend} command from the
|
||||||
|
* frontend — this resource only covers the missing cross-product listing.
|
||||||
|
*/
|
||||||
|
@Path("/v1/clerk/pending-dividends")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Pending Dividends", description = "Dividend declarations awaiting approval, across all Share Products.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PendingDividendsApiResource {
|
||||||
|
|
||||||
|
private static final int DIVIDEND_PAYOUT_STATUS_INITIATED = 100;
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public String list() {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
|
||||||
|
SELECT p.id AS dividend_id, p.product_id, sp.name AS product_name, p.amount,
|
||||||
|
p.dividend_period_start_date, p.dividend_period_end_date, p.created_date,
|
||||||
|
(SELECT COUNT(*) FROM m_share_account_dividend_details d WHERE d.dividend_pay_out_id = p.id) AS member_count
|
||||||
|
FROM m_share_product_dividend_pay_out p
|
||||||
|
JOIN m_share_product sp ON sp.id = p.product_id
|
||||||
|
WHERE p.status = ?
|
||||||
|
ORDER BY p.created_date ASC
|
||||||
|
""", DIVIDEND_PAYOUT_STATUS_INITIATED);
|
||||||
|
|
||||||
|
final JsonArray result = new JsonArray();
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final JsonObject entry = new JsonObject();
|
||||||
|
entry.addProperty("dividendId", ((Number) row.get("dividend_id")).longValue());
|
||||||
|
entry.addProperty("productId", ((Number) row.get("product_id")).longValue());
|
||||||
|
entry.addProperty("productName", (String) row.get("product_name"));
|
||||||
|
entry.addProperty("amount", (BigDecimal) row.get("amount"));
|
||||||
|
entry.addProperty("dividendPeriodStartDate", row.get("dividend_period_start_date").toString());
|
||||||
|
entry.addProperty("dividendPeriodEndDate", row.get("dividend_period_end_date").toString());
|
||||||
|
entry.addProperty("declaredOn", row.get("created_date") == null ? null : row.get("created_date").toString());
|
||||||
|
entry.addProperty("memberCount", ((Number) row.get("member_count")).intValue());
|
||||||
|
result.add(entry);
|
||||||
|
}
|
||||||
|
return gson.toJson(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
+277
@@ -0,0 +1,277 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.loanoriginationpipeline.api;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.ws.rs.Consumes;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.PUT;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.QueryParam;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
|
import org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationPipelineService;
|
||||||
|
import org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationStageService;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* REST endpoints for the Loan Origination Pipeline — the sanctioning workflow an application walks
|
||||||
|
* through before a real loan account is ever opened (Application → KYC/OVD → CIC Credit Bureau Check
|
||||||
|
* → Field Investigation → Personal Discussion → Credit Committee → Risk Approval → Legal Approval →
|
||||||
|
* Customer Signing → Cheque/ACH → Post-Disbursement Check → Disbursed).
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* GET /v1/loan-origination/applications – list (optional branchCode/stage/status filters)
|
||||||
|
* GET /v1/loan-origination/applications/{applicationNo} – one application, in full
|
||||||
|
* POST /v1/loan-origination/applications – create from the New Application wizard
|
||||||
|
* PUT /v1/loan-origination/applications/{applicationNo} – save the whole application back
|
||||||
|
* POST /v1/loan-origination/applications/seed – one-time seed; no-ops if already seeded
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Requests/responses are the application object verbatim, so the request body is passed straight
|
||||||
|
* through as JSON rather than being bound to a DTO. A DTO would have to mirror all ~111 workflow
|
||||||
|
* fields and would silently drop any field it had not been updated to know about — the exact failure
|
||||||
|
* this module has to avoid, since the workflow gains fields regularly.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Authorisation is a normal authenticated staff session. These endpoints deliberately do not define
|
||||||
|
* their own permission codes: the pipeline is the sanctioning process for lending, so it is gated by
|
||||||
|
* the same authenticated-staff check the rest of the loan screens use, and per-stage authority
|
||||||
|
* (who may sit on the Credit Committee, who signs off Risk/Legal) is a workflow concern enforced on
|
||||||
|
* the application record itself, not a Fineract entity permission.
|
||||||
|
*/
|
||||||
|
@Path("/v1/loan-origination/applications")
|
||||||
|
@Component
|
||||||
|
@Tag(name = "Loan Origination Pipeline",
|
||||||
|
description = "Pre-disbursement sanctioning workflow: KYC/OVD, CIC credit bureau check, Field Investigation, "
|
||||||
|
+ "Personal Discussion, Credit Committee, Risk & Legal approval, signing and disbursement.")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoanOriginationPipelineApiResource {
|
||||||
|
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
private final LoanOriginationPipelineService service;
|
||||||
|
private final LoanOriginationStageService stageService;
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "List loan origination applications",
|
||||||
|
description = "Newest first. Filters are optional — the Pipeline screen also filters client-side.")
|
||||||
|
public String retrieveAll(@QueryParam("branchCode") final String branchCode, @QueryParam("stage") final String stage,
|
||||||
|
@QueryParam("status") final String status) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.service.findAllAsJson(branchCode, stage, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{applicationNo}")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Retrieve one loan origination application in full")
|
||||||
|
public String retrieveOne(@PathParam("applicationNo") final String applicationNo) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.service.findOneAsJson(applicationNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Create a loan origination application",
|
||||||
|
description = "Body is the application object as built by the New Application wizard.")
|
||||||
|
public String create(final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.service.create(apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PUT
|
||||||
|
@Path("{applicationNo}")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Save a loan origination application",
|
||||||
|
description = "Full-object save: the body replaces the stored application, its stage history, "
|
||||||
|
+ "approvals, field-investigation checks and document checklists.")
|
||||||
|
public String save(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.service.save(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("seed")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Seed the pipeline once",
|
||||||
|
description = "Inserts the supplied applications only when the pipeline is empty, so reloading the "
|
||||||
|
+ "frontend cannot duplicate the book. Returns the number actually inserted.")
|
||||||
|
public String seed(final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return "{\"seeded\":" + this.service.seed(apiRequestBodyAsJson) + "}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────
|
||||||
|
// Per-stage transitions.
|
||||||
|
//
|
||||||
|
// Each of these takes only its own step's inputs (who acted, remarks, a resolution number) and
|
||||||
|
// lets the server validate the stage's prerequisites against the stored record before applying
|
||||||
|
// the change. The full-object PUT above still exists for inline field edits; these exist because
|
||||||
|
// a sanctioning decision should not be something a caller can simply assert. Every one returns
|
||||||
|
// the updated application, so the client replaces its copy rather than guessing the result.
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/kyc-complete")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Complete KYC & Document Collection",
|
||||||
|
description = "Requires Aadhaar/PAN verified, income proof, bank statement and address proof submitted, "
|
||||||
|
+ "income assessed, and every product-specific document submitted.")
|
||||||
|
public String completeKyc(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.completeKyc(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/cic-complete")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Complete the CIC / credit bureau check",
|
||||||
|
description = "Requires the borrower's signed consent, the collected bureau charge and an uploaded report.")
|
||||||
|
public String completeCicCheck(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.completeCicCheck(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/field-investigation/{checkKey}/verify")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Mark one field investigation check verified",
|
||||||
|
description = "Requires an assigned officer, GPS coordinates and at least one site photograph "
|
||||||
|
+ "to already be recorded against the visit.")
|
||||||
|
public String verifyFieldCheck(@PathParam("applicationNo") final String applicationNo,
|
||||||
|
@PathParam("checkKey") final String checkKey, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.verifyFieldCheck(applicationNo, checkKey, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/field-investigation/{checkKey}/reject")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Mark one field investigation check failed", description = "A reason is mandatory.")
|
||||||
|
public String rejectFieldCheck(@PathParam("applicationNo") final String applicationNo,
|
||||||
|
@PathParam("checkKey") final String checkKey, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.rejectFieldCheck(applicationNo, checkKey, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/field-investigation/complete")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Complete Field Investigation",
|
||||||
|
description = "Requires every applicable check (address, office, plus property when secured and shop "
|
||||||
|
+ "when the applicant runs one) to be verified.")
|
||||||
|
public String completeFieldInvestigation(@PathParam("applicationNo") final String applicationNo,
|
||||||
|
final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.completeFieldInvestigation(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/personal-discussion/clear")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Clear the personal discussion and proceed")
|
||||||
|
public String clearPersonalDiscussion(@PathParam("applicationNo") final String applicationNo,
|
||||||
|
final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.clearPersonalDiscussion(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/personal-discussion/flag")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Flag a discrepancy and hold the application",
|
||||||
|
description = "A discrepancy type and notes are both mandatory.")
|
||||||
|
public String flagDiscrepancy(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.flagDiscrepancy(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/personal-discussion/resolve")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Resolve a held discrepancy and proceed")
|
||||||
|
public String resolveDiscrepancy(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.resolveDiscrepancy(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/approvals/{field}")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Record an approval decision",
|
||||||
|
description = "`field` is one of creditCommitteeApproval, riskApproval, legalApproval, postCheckApproval. "
|
||||||
|
+ "An APPROVED decision is checked against that stage's own checklist — the Credit Committee also "
|
||||||
|
+ "requires a resolution number and date. A REJECTED decision is always permitted.")
|
||||||
|
public String decideApproval(@PathParam("applicationNo") final String applicationNo, @PathParam("field") final String field,
|
||||||
|
final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.decideApproval(applicationNo, field, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/signing")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Record the customer's signing of the loan agreement")
|
||||||
|
public String markSigned(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.markSigned(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/cheque-ach")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Confirm security cheques received and ACH mandate signed")
|
||||||
|
public String confirmChequeAch(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.confirmChequeAch(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{applicationNo}/disburse")
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
@Operation(summary = "Disburse the loan",
|
||||||
|
description = "Requires all four approval levels to stand as approved and the customer to have signed. "
|
||||||
|
+ "Optionally records the real Fineract loan account created at disbursement.")
|
||||||
|
public String disburse(@PathParam("applicationNo") final String applicationNo, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser();
|
||||||
|
return this.stageService.disburse(applicationNo, apiRequestBodyAsJson);
|
||||||
|
}
|
||||||
|
}
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.loanoriginationpipeline.service;
|
||||||
|
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Null-safe accessors for the loan origination application object.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* The application is handled as JSON rather than a typed entity (see
|
||||||
|
* {@link LoanOriginationPipelineService} for why), so every read has to tolerate a key being absent,
|
||||||
|
* explicitly null, or the wrong JSON type — an older application stored before a field existed is a
|
||||||
|
* normal, expected case, not an error. These helpers turn all three into a sensible default so no
|
||||||
|
* caller has to repeat the checks.
|
||||||
|
*/
|
||||||
|
public final class LoanOriginationJson {
|
||||||
|
|
||||||
|
private LoanOriginationJson() {}
|
||||||
|
|
||||||
|
public static JsonObject parseObject(final String body) {
|
||||||
|
if (body == null || body.isBlank()) {
|
||||||
|
// An action with no inputs (e.g. "mark signed") legitimately posts an empty body.
|
||||||
|
return new JsonObject();
|
||||||
|
}
|
||||||
|
final JsonElement parsed = JsonParser.parseString(body);
|
||||||
|
if (!parsed.isJsonObject()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.body.invalid",
|
||||||
|
"Request body must be a JSON object.");
|
||||||
|
}
|
||||||
|
return parsed.getAsJsonObject();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean present(final JsonObject obj, final String key) {
|
||||||
|
return obj != null && obj.has(key) && !obj.get(key).isJsonNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String str(final JsonObject obj, final String key) {
|
||||||
|
return present(obj, key) && obj.get(key).isJsonPrimitive() ? obj.get(key).getAsString() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Trimmed value, or the fallback when absent/blank. */
|
||||||
|
public static String strOr(final JsonObject obj, final String key, final String fallback) {
|
||||||
|
final String value = str(obj, key);
|
||||||
|
return value == null || value.isBlank() ? fallback : value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when a field holds real content. Treats the {@code '—'} em-dash as empty: the workflow uses
|
||||||
|
* it as a "nothing recorded yet" placeholder throughout, so a check for "has this been filled in"
|
||||||
|
* has to reject it or every blank field would read as populated.
|
||||||
|
*/
|
||||||
|
public static boolean filled(final JsonObject obj, final String key) {
|
||||||
|
final String value = str(obj, key);
|
||||||
|
return value != null && !value.trim().isEmpty() && !"—".equals(value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Long lng(final JsonObject obj, final String key) {
|
||||||
|
try {
|
||||||
|
return present(obj, key) && obj.get(key).isJsonPrimitive() ? obj.get(key).getAsLong() : null;
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BigDecimal dec(final JsonObject obj, final String key) {
|
||||||
|
try {
|
||||||
|
return present(obj, key) && obj.get(key).isJsonPrimitive() ? obj.get(key).getAsBigDecimal() : null;
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean bool(final JsonObject obj, final String key) {
|
||||||
|
return present(obj, key) && obj.get(key).isJsonPrimitive() && obj.get(key).getAsBoolean();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int intOr(final JsonObject obj, final String key, final int fallback) {
|
||||||
|
try {
|
||||||
|
return present(obj, key) && obj.get(key).isJsonPrimitive() ? obj.get(key).getAsInt() : fallback;
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject obj(final JsonObject parent, final String key) {
|
||||||
|
return present(parent, key) && parent.get(key).isJsonObject() ? parent.getAsJsonObject(key) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The nested object, creating and attaching an empty one if it isn't there yet. */
|
||||||
|
public static JsonObject objOrCreate(final JsonObject parent, final String key) {
|
||||||
|
final JsonObject existing = obj(parent, key);
|
||||||
|
if (existing != null) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
final JsonObject created = new JsonObject();
|
||||||
|
parent.add(key, created);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonArray arr(final JsonObject parent, final String key) {
|
||||||
|
return present(parent, key) && parent.get(key).isJsonArray() ? parent.getAsJsonArray(key) : new JsonArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonArray arrOrCreate(final JsonObject parent, final String key) {
|
||||||
|
if (present(parent, key) && parent.get(key).isJsonArray()) {
|
||||||
|
return parent.getAsJsonArray(key);
|
||||||
|
}
|
||||||
|
final JsonArray created = new JsonArray();
|
||||||
|
parent.add(key, created);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String rawJson(final JsonObject obj, final String key) {
|
||||||
|
return present(obj, key) ? obj.get(key).toString() : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+403
@@ -0,0 +1,403 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.loanoriginationpipeline.service;
|
||||||
|
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistence for the Loan Origination Pipeline — the pre-disbursement sanctioning workflow
|
||||||
|
* (Application → KYC → CIC Check → Field Investigation → Personal Discussion → Credit Committee →
|
||||||
|
* Risk → Legal → Signing → Cheque/ACH → Post-Check → Disbursed).
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* <b>Storage shape.</b> {@code payload} holds the complete application object as JSON and is the
|
||||||
|
* single source of truth for reads. The dozen real columns on
|
||||||
|
* {@code m_loan_origination_application}, and the four child tables, are <i>derived indexes</i> —
|
||||||
|
* they exist so the Pipeline list, the Channel/BC/Share reports, Target-vs-Actual and audit queries
|
||||||
|
* ("every application this officer approved") can be plain SQL instead of scanning JSON. They are
|
||||||
|
* never read back into the application object.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* That deliberately stores those fields twice, which is the right trade here: every write goes
|
||||||
|
* through {@link #writeApplication} in one transaction and rewrites the payload, the columns and all
|
||||||
|
* child rows together from the same source, so the copies cannot drift. The alternative — splitting
|
||||||
|
* fields so nothing repeats — would force the read path to reconstruct a dozen values back out of
|
||||||
|
* SQL types (a {@code DECIMAL(19,6)} returning {@code 100000.000000} where the UI expects
|
||||||
|
* {@code 100000}, a null {@code BIGINT} vs an absent key), which is exactly the class of silent
|
||||||
|
* field-level corruption this module cannot afford.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* The one field kept out of {@code payload} is {@code cicParsedAnalysis} — a parsed credit-bureau
|
||||||
|
* report with a per-account seven-year day-past-due grid. It is large, opaque and only ever rendered
|
||||||
|
* whole, so it gets its own column rather than being duplicated alongside everything else.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Because the payload is "the whole object minus that one field" rather than an allowlist of known
|
||||||
|
* keys, a field added to the workflow later persists with no schema or code change here. Given how
|
||||||
|
* fast this workflow gains fields, an allowlist would drop them silently.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoanOriginationPipelineService {
|
||||||
|
|
||||||
|
/** Pulled out of the payload into its own column — see class javadoc. */
|
||||||
|
private static final String CIC_ANALYSIS_KEY = "cicParsedAnalysis";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row's primary key. Kept out of the payload so it can only ever come from the column — a
|
||||||
|
* stale id round-tripped inside the JSON would silently point uploaded documents at the wrong
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
private static final String ID_KEY = "id";
|
||||||
|
|
||||||
|
private static final String SELECT_COLUMNS = "id, payload, cic_parsed_analysis";
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
// ── Read ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every application, newest first. Optional filters are pushed into SQL; the Pipeline screen also
|
||||||
|
* filters in-memory, so passing nothing here is perfectly valid.
|
||||||
|
*/
|
||||||
|
public String findAllAsJson(final String branchCode, final String stage, final String status) {
|
||||||
|
final StringBuilder sql = new StringBuilder("SELECT " + SELECT_COLUMNS + " FROM m_loan_origination_application WHERE 1=1");
|
||||||
|
final List<Object> params = new ArrayList<>();
|
||||||
|
if (isSet(branchCode)) {
|
||||||
|
sql.append(" AND branch_code = ?");
|
||||||
|
params.add(branchCode);
|
||||||
|
}
|
||||||
|
if (isSet(stage)) {
|
||||||
|
sql.append(" AND current_stage = ?");
|
||||||
|
params.add(stage);
|
||||||
|
}
|
||||||
|
if (isSet(status)) {
|
||||||
|
sql.append(" AND overall_status = ?");
|
||||||
|
params.add(status);
|
||||||
|
}
|
||||||
|
sql.append(" ORDER BY id DESC");
|
||||||
|
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
|
||||||
|
final JsonArray out = new JsonArray();
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
out.add(reassemble(row));
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String findOneAsJson(final String applicationNo) {
|
||||||
|
return loadApplication(applicationNo).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads one application as a mutable object. This is the entry point the per-stage endpoints use:
|
||||||
|
* they validate and apply their transition against the state that is actually stored, never
|
||||||
|
* against what a caller claims it is.
|
||||||
|
*/
|
||||||
|
public JsonObject loadApplication(final String applicationNo) {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate
|
||||||
|
.queryForList("SELECT " + SELECT_COLUMNS + " FROM m_loan_origination_application WHERE application_no = ?",
|
||||||
|
applicationNo);
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.application.not.found",
|
||||||
|
"No loan origination application found with number " + applicationNo + ".", applicationNo);
|
||||||
|
}
|
||||||
|
return reassemble(rows.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rebuilds the application object: the stored payload, with the bureau report re-attached and the
|
||||||
|
* row's own id surfaced. The id is what uploaded files hang off — documents are stored against
|
||||||
|
* {@code m_document.parent_entity_id}, so the client needs it to upload and fetch attachments.
|
||||||
|
*/
|
||||||
|
private JsonObject reassemble(final Map<String, Object> row) {
|
||||||
|
final JsonObject app = parseObject(asString(row.get("payload")));
|
||||||
|
final Object id = row.get("id");
|
||||||
|
if (id != null) {
|
||||||
|
app.addProperty("id", Long.valueOf(id.toString()));
|
||||||
|
}
|
||||||
|
final String cic = asString(row.get("cic_parsed_analysis"));
|
||||||
|
if (cic != null && !cic.isBlank()) {
|
||||||
|
app.add(CIC_ANALYSIS_KEY, JsonParser.parseString(cic));
|
||||||
|
}
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Write ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an application. The caller (the New Application wizard) has already derived the
|
||||||
|
* application number and the blank per-stage structures, so this stores the object as given
|
||||||
|
* rather than re-deriving a second, competing set of defaults server-side.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String create(final String requestBodyAsJson) {
|
||||||
|
final JsonObject app = parseObject(requestBodyAsJson);
|
||||||
|
final String applicationNo = stringOrNull(app, "applicationNo");
|
||||||
|
if (applicationNo == null || applicationNo.isBlank()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.application.no.required",
|
||||||
|
"applicationNo is required.");
|
||||||
|
}
|
||||||
|
final Long existing = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM m_loan_origination_application WHERE application_no = ?", Long.class, applicationNo);
|
||||||
|
if (existing != null && existing > 0) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.application.duplicate",
|
||||||
|
"An application numbered " + applicationNo + " already exists.", applicationNo);
|
||||||
|
}
|
||||||
|
// Read back rather than echoing the request: the caller needs the assigned id to be able to
|
||||||
|
// attach documents to this application.
|
||||||
|
insertApplication(app);
|
||||||
|
return findOneAsJson(applicationNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full-object save. The workflow's stage transitions are all applied client-side against the
|
||||||
|
* whole application object, so the whole object is what gets written back — there is no
|
||||||
|
* per-action field allowlist that could quietly omit a field.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String save(final String applicationNo, final String requestBodyAsJson) {
|
||||||
|
return storeApplication(applicationNo, parseObject(requestBodyAsJson));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes a whole application object back. Shared by the full-object save and every per-stage
|
||||||
|
* endpoint, so both paths persist through exactly the same code. */
|
||||||
|
@Transactional
|
||||||
|
public String storeApplication(final String applicationNo, final JsonObject app) {
|
||||||
|
final Long id = findIdOrThrow(applicationNo);
|
||||||
|
|
||||||
|
final JsonObject payload = app.deepCopy();
|
||||||
|
payload.remove(CIC_ANALYSIS_KEY);
|
||||||
|
payload.remove(ID_KEY);
|
||||||
|
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
UPDATE m_loan_origination_application SET
|
||||||
|
applicant_name = ?, client_id = ?, branch_code = ?, channel = ?, bc_agent_name = ?,
|
||||||
|
product_code = ?, requested_amount = ?, current_stage = ?, overall_status = ?,
|
||||||
|
is_share_member = ?, fineract_loan_id = ?, payload = ?, cic_parsed_analysis = ?,
|
||||||
|
last_modified_date = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = ?
|
||||||
|
""", stringOrNull(app, "applicantName"), longOrNull(app, "clientId"), stringOrNull(app, "branchCode"),
|
||||||
|
stringOrNull(app, "channel"), stringOrNull(app, "bcAgentName"), stringOrNull(app, "productCode"),
|
||||||
|
decimalOrNull(app, "requestedAmount"), stringOrNull(app, "currentStage"), stringOrNull(app, "overallStatus"),
|
||||||
|
boolOrFalse(app, "isShareMember"), longOrNull(app, "fineractLoanId"), payload.toString(),
|
||||||
|
childJsonOrNull(app, CIC_ANALYSIS_KEY), id);
|
||||||
|
|
||||||
|
writeChildren(id, app);
|
||||||
|
return findOneAsJson(applicationNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-time seed. Idempotent by design: it is called on first page load and must not duplicate the
|
||||||
|
* book if the frontend is reloaded, so a non-empty table short-circuits to 0.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public int seed(final String requestBodyAsJson) {
|
||||||
|
final Long existing = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM m_loan_origination_application", Long.class);
|
||||||
|
if (existing != null && existing > 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
final JsonElement parsed = JsonParser.parseString(requestBodyAsJson == null ? "[]" : requestBodyAsJson);
|
||||||
|
if (!parsed.isJsonArray()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.seed.invalid",
|
||||||
|
"Seed body must be a JSON array of applications.");
|
||||||
|
}
|
||||||
|
int seeded = 0;
|
||||||
|
for (final JsonElement element : parsed.getAsJsonArray()) {
|
||||||
|
if (element.isJsonObject()) {
|
||||||
|
insertApplication(element.getAsJsonObject());
|
||||||
|
seeded++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return seeded;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertApplication(final JsonObject app) {
|
||||||
|
final JsonObject payload = app.deepCopy();
|
||||||
|
payload.remove(CIC_ANALYSIS_KEY);
|
||||||
|
payload.remove(ID_KEY);
|
||||||
|
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_loan_origination_application
|
||||||
|
(application_no, applicant_name, client_id, branch_code, channel, bc_agent_name,
|
||||||
|
product_code, requested_amount, current_stage, overall_status, is_share_member,
|
||||||
|
fineract_loan_id, payload, cic_parsed_analysis)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", stringOrNull(app, "applicationNo"), stringOrNull(app, "applicantName"), longOrNull(app, "clientId"),
|
||||||
|
stringOrNull(app, "branchCode"), stringOrNull(app, "channel"), stringOrNull(app, "bcAgentName"),
|
||||||
|
stringOrNull(app, "productCode"), decimalOrNull(app, "requestedAmount"), stringOrNull(app, "currentStage"),
|
||||||
|
stringOrNull(app, "overallStatus"), boolOrFalse(app, "isShareMember"), longOrNull(app, "fineractLoanId"),
|
||||||
|
payload.toString(), childJsonOrNull(app, CIC_ANALYSIS_KEY));
|
||||||
|
|
||||||
|
final Long id = jdbcTemplate.queryForObject("SELECT id FROM m_loan_origination_application WHERE application_no = ?",
|
||||||
|
Long.class, stringOrNull(app, "applicationNo"));
|
||||||
|
writeChildren(id, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rewrites the derived child rows for one application. Delete-then-insert rather than a per-row
|
||||||
|
* diff: these collections are small (a stage history is a dozen rows), and a full rewrite cannot
|
||||||
|
* leave a stale row behind the way a partial diff can.
|
||||||
|
*/
|
||||||
|
private void writeChildren(final Long id, final JsonObject app) {
|
||||||
|
jdbcTemplate.update("DELETE FROM m_loan_origination_stage_history WHERE application_id = ?", id);
|
||||||
|
jdbcTemplate.update("DELETE FROM m_loan_origination_approval WHERE application_id = ?", id);
|
||||||
|
jdbcTemplate.update("DELETE FROM m_loan_origination_fi_check WHERE application_id = ?", id);
|
||||||
|
jdbcTemplate.update("DELETE FROM m_loan_origination_document WHERE application_id = ?", id);
|
||||||
|
|
||||||
|
final JsonArray history = arrayOrEmpty(app, "stageHistory");
|
||||||
|
for (int i = 0; i < history.size(); i++) {
|
||||||
|
if (!history.get(i).isJsonObject()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final JsonObject entry = history.get(i).getAsJsonObject();
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_loan_origination_stage_history
|
||||||
|
(application_id, seq_no, stage, action_date, action_by, outcome, remarks)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", id, i, stringOrNull(entry, "stage"), stringOrNull(entry, "date"), stringOrNull(entry, "actionBy"),
|
||||||
|
stringOrNull(entry, "outcome"), stringOrNull(entry, "remarks"));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final String field : new String[] { "creditCommitteeApproval", "riskApproval", "legalApproval", "postCheckApproval" }) {
|
||||||
|
final JsonObject approval = objectOrNull(app, field);
|
||||||
|
if (approval == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_loan_origination_approval
|
||||||
|
(application_id, approval_field, decision, approver_name, approver_role, decision_date, remarks)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", id, field, stringOrNull(approval, "decision"), stringOrNull(approval, "approverName"),
|
||||||
|
stringOrNull(approval, "approverRole"), stringOrNull(approval, "date"), stringOrNull(approval, "remarks"));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final String key : new String[] { "addressVerification", "officeVerification", "propertyVerification",
|
||||||
|
"shopVerification" }) {
|
||||||
|
final JsonObject check = objectOrNull(app, key);
|
||||||
|
if (check == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_loan_origination_fi_check
|
||||||
|
(application_id, check_key, status, verified_by, verified_date, remarks, officer_assigned,
|
||||||
|
assigned_date, assigned_at, latitude, longitude, photo_count)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", id, key, stringOrNull(check, "status"), stringOrNull(check, "verifiedBy"),
|
||||||
|
stringOrNull(check, "verifiedDate"), stringOrNull(check, "remarks"), stringOrNull(check, "officerAssigned"),
|
||||||
|
stringOrNull(check, "assignedDate"), longOrNull(check, "assignedAt"), stringOrNull(check, "latitude"),
|
||||||
|
stringOrNull(check, "longitude"), intOrZero(check, "photoCount"));
|
||||||
|
}
|
||||||
|
|
||||||
|
insertDocuments(id, arrayOrEmpty(app, "productDocuments"), "PRODUCT");
|
||||||
|
insertDocuments(id, arrayOrEmpty(app, "legalDocuments"), "LEGAL");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertDocuments(final Long id, final JsonArray docs, final String kind) {
|
||||||
|
for (int i = 0; i < docs.size(); i++) {
|
||||||
|
if (!docs.get(i).isJsonObject()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final JsonObject doc = docs.get(i).getAsJsonObject();
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO m_loan_origination_document
|
||||||
|
(application_id, doc_kind, doc_key, label, hint, is_custom, submitted, seq_no)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", id, kind, stringOrNull(doc, "key"), stringOrNull(doc, "label"), stringOrNull(doc, "hint"),
|
||||||
|
boolOrFalse(doc, "custom"), boolOrFalse(doc, "submitted"), i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long findIdOrThrow(final String applicationNo) {
|
||||||
|
final List<Long> ids = jdbcTemplate.queryForList("SELECT id FROM m_loan_origination_application WHERE application_no = ?",
|
||||||
|
Long.class, applicationNo);
|
||||||
|
if (ids.isEmpty()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.application.not.found",
|
||||||
|
"No loan origination application found with number " + applicationNo + ".", applicationNo);
|
||||||
|
}
|
||||||
|
return ids.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── JSON helpers ─────────────────────────────────────────────────────────
|
||||||
|
// Thin aliases over LoanOriginationJson so this class and the per-stage service share one
|
||||||
|
// implementation of the null/absent/wrong-type handling rather than each keeping its own.
|
||||||
|
|
||||||
|
private JsonObject parseObject(final String body) {
|
||||||
|
if (body == null || body.isBlank()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.loan.origination.body.required", "A request body is required.");
|
||||||
|
}
|
||||||
|
return LoanOriginationJson.parseObject(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean present(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.present(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String stringOrNull(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.str(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long longOrNull(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.lng(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal decimalOrNull(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.dec(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean boolOrFalse(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.bool(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int intOrZero(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.intOr(obj, key, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonObject objectOrNull(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.obj(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonArray arrayOrEmpty(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.arr(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String childJsonOrNull(final JsonObject obj, final String key) {
|
||||||
|
return LoanOriginationJson.rawJson(obj, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String asString(final Object value) {
|
||||||
|
return value == null ? null : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSet(final String value) {
|
||||||
|
return value != null && !value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+517
@@ -0,0 +1,517 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.loanoriginationpipeline.service;
|
||||||
|
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.arr;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.arrOrCreate;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.bool;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.filled;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.intOr;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.obj;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.objOrCreate;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.parseObject;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.str;
|
||||||
|
import static org.apache.fineract.portfolio.loanoriginationpipeline.service.LoanOriginationJson.strOr;
|
||||||
|
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
|
import org.apache.fineract.infrastructure.core.service.DateUtils;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server-side stage transitions for the Loan Origination Pipeline.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Each method here owns one sanctioning step: it loads the application <b>as stored</b>, checks that
|
||||||
|
* step's preconditions against that stored state, applies the change, appends the audit-trail entry
|
||||||
|
* and saves. The caller supplies only that step's own inputs (who acted, remarks, a resolution
|
||||||
|
* number) — never the resulting state — so a client cannot approve a stage whose prerequisites are
|
||||||
|
* not actually met, mark a field visit verified without the GPS fix and photographs really being on
|
||||||
|
* file, or minute a Credit Committee decision without a resolution number.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* That distinction matters for a sanctioning workflow: the screen also disables those buttons, but UI
|
||||||
|
* gating is a convenience, not a control — it is bypassed by any direct call to the API. These checks
|
||||||
|
* are the control. They are deliberately the same rules the screen enforces, so an officer never sees
|
||||||
|
* an enabled button that the server then rejects.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Dates are written in the {@code dd-MM-yyyy} form the rest of the workflow record already uses, and
|
||||||
|
* "nothing recorded" stays the {@code '—'} placeholder the existing data uses, so a server-applied
|
||||||
|
* transition is indistinguishable in shape from the client-applied ones already stored.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoanOriginationStageService {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter WORKFLOW_DATE = DateTimeFormatter.ofPattern("dd-MM-yyyy");
|
||||||
|
|
||||||
|
/** Must stay in step with STAGE_ORDER on the Application Detail screen. */
|
||||||
|
private static final List<String> STAGE_ORDER = List.of("APPLICATION", "KYC_DOCUMENTS", "CIC_CHECK", "FIELD_INVESTIGATION",
|
||||||
|
"PERSONAL_DISCUSSION", "CREDIT_COMMITTEE", "RISK_APPROVAL", "LEGAL_APPROVAL", "CUSTOMER_SIGNING", "CHEQUE_ACH",
|
||||||
|
"POST_CHECK", "DISBURSED");
|
||||||
|
|
||||||
|
private static final List<String> FI_CHECK_KEYS = List.of("addressVerification", "officeVerification", "propertyVerification",
|
||||||
|
"shopVerification");
|
||||||
|
|
||||||
|
private final LoanOriginationPipelineService pipelineService;
|
||||||
|
|
||||||
|
// ── KYC & Documents ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String completeKyc(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "KYC_DOCUMENTS");
|
||||||
|
|
||||||
|
require(bool(app, "aadhaarVerified"), "Aadhaar has not been verified.");
|
||||||
|
require(bool(app, "panVerified"), "PAN has not been verified.");
|
||||||
|
require(bool(app, "incomeProofSubmitted"), "Income proof has not been submitted.");
|
||||||
|
require(bool(app, "bankStatementSubmitted"), "Bank statement has not been submitted.");
|
||||||
|
require(bool(app, "electricityBillSubmitted"), "Address proof (electricity bill) has not been submitted.");
|
||||||
|
require(intOr(app, "monthlyIncome", 0) > 0, "Monthly income has not been assessed.");
|
||||||
|
for (final JsonElement element : arr(app, "productDocuments")) {
|
||||||
|
final JsonObject doc = element.getAsJsonObject();
|
||||||
|
require(bool(doc, "submitted"), "Required document not submitted: " + strOr(doc, "label", strOr(doc, "key", "document")));
|
||||||
|
}
|
||||||
|
|
||||||
|
advance(app, actor(input), "KYC Complete", strOr(input, "remarks", "KYC and document collection complete."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── CIC / Credit Bureau ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String completeCicCheck(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "CIC_CHECK");
|
||||||
|
|
||||||
|
// RBI's Fair Practices Code requires the borrower's written consent before a bureau pull, and
|
||||||
|
// the bureau's per-pull fee has to have actually been collected.
|
||||||
|
require(bool(app, "cicConsentSigned"), "The borrower's signed credit-bureau consent is not on file.");
|
||||||
|
require(bool(app, "cicChargeCollected"), "The credit bureau check charge has not been collected.");
|
||||||
|
require(bool(app, "cicReportUploaded"), "No credit bureau report has been uploaded.");
|
||||||
|
|
||||||
|
advance(app, actor(input), "CIC Check Complete",
|
||||||
|
strOr(input, "remarks", "Credit bureau report obtained and reviewed. Score " + intOr(app, "cibilScore", 0) + "."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Field Investigation ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks one field-investigation check verified. The GPS fix and site photographs are checked
|
||||||
|
* against what is stored, which is the point: "I visited" with nothing recorded is exactly what a
|
||||||
|
* field-investigation control exists to prevent.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String verifyFieldCheck(final String applicationNo, final String checkKey, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "FIELD_INVESTIGATION");
|
||||||
|
require(FI_CHECK_KEYS.contains(checkKey), "Unknown field investigation check: " + checkKey);
|
||||||
|
|
||||||
|
final JsonObject check = objOrCreate(app, checkKey);
|
||||||
|
require(filled(check, "officerAssigned"), "No field officer has been assigned to this visit.");
|
||||||
|
require(filled(check, "latitude") && filled(check, "longitude"), "The visit has no GPS coordinates recorded.");
|
||||||
|
require(intOr(check, "photoCount", 0) > 0, "No site photograph has been captured for this visit.");
|
||||||
|
|
||||||
|
check.addProperty("status", "VERIFIED");
|
||||||
|
check.addProperty("verifiedBy", strOr(input, "verifiedBy", strOr(check, "officerAssigned", "Field Officer")));
|
||||||
|
check.addProperty("verifiedDate", today());
|
||||||
|
check.addProperty("remarks", strOr(input, "remarks", "Visited and confirmed correct."));
|
||||||
|
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String rejectFieldCheck(final String applicationNo, final String checkKey, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "FIELD_INVESTIGATION");
|
||||||
|
require(FI_CHECK_KEYS.contains(checkKey), "Unknown field investigation check: " + checkKey);
|
||||||
|
// A failed visit must say why -- it is what the Personal Discussion stage then works from.
|
||||||
|
final String remarks = strOr(input, "remarks", "");
|
||||||
|
require(!remarks.isBlank(), "A reason is required when a field visit fails.");
|
||||||
|
|
||||||
|
final JsonObject check = objOrCreate(app, checkKey);
|
||||||
|
check.addProperty("status", "FAILED");
|
||||||
|
check.addProperty("verifiedBy", strOr(input, "verifiedBy", strOr(check, "officerAssigned", "Field Officer")));
|
||||||
|
check.addProperty("verifiedDate", today());
|
||||||
|
check.addProperty("remarks", remarks);
|
||||||
|
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String completeFieldInvestigation(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "FIELD_INVESTIGATION");
|
||||||
|
requireFieldInvestigationComplete(app);
|
||||||
|
|
||||||
|
advance(app, actor(input), "FI Complete", strOr(input, "remarks", "Field investigation complete on all applicable checks."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Personal Discussion ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String clearPersonalDiscussion(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "PERSONAL_DISCUSSION");
|
||||||
|
require(bool(app, "meetingScheduled"), "The personal discussion meeting has not been scheduled.");
|
||||||
|
|
||||||
|
final String remarks = strOr(input, "remarks", "No discrepancy found — cleared to proceed to Loan Committee.");
|
||||||
|
app.addProperty("discrepancyType", "NONE");
|
||||||
|
app.addProperty("overallStatus", "IN_PROGRESS");
|
||||||
|
app.addProperty("personalDiscussionDate", today());
|
||||||
|
app.addProperty("personalDiscussionNotes", remarks);
|
||||||
|
app.addProperty("declarationTaken", true);
|
||||||
|
app.addProperty("declarationDate", today());
|
||||||
|
|
||||||
|
advance(app, actor(input), "Cleared", remarks);
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String flagDiscrepancy(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "PERSONAL_DISCUSSION");
|
||||||
|
|
||||||
|
final String type = strOr(input, "discrepancyType", "");
|
||||||
|
require(!type.isBlank() && !"NONE".equals(type), "A discrepancy type is required.");
|
||||||
|
final String notes = strOr(input, "remarks", "");
|
||||||
|
require(!notes.isBlank(), "Notes are required when flagging a discrepancy.");
|
||||||
|
|
||||||
|
app.addProperty("discrepancyType", type);
|
||||||
|
app.addProperty("personalDiscussionDate", today());
|
||||||
|
app.addProperty("personalDiscussionNotes", notes);
|
||||||
|
// Held rather than rejected: a discrepancy is resolvable, and the application has to stay
|
||||||
|
// visible as outstanding work rather than dropping out of the pipeline.
|
||||||
|
app.addProperty("overallStatus", "ON_HOLD");
|
||||||
|
|
||||||
|
appendHistory(app, str(app, "currentStage"), actor(input), "Discrepancy Flagged", notes);
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String resolveDiscrepancy(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "PERSONAL_DISCUSSION");
|
||||||
|
require("ON_HOLD".equals(str(app, "overallStatus")), "This application is not on hold.");
|
||||||
|
|
||||||
|
final String remarks = strOr(input, "remarks", "Discrepancy resolved on further review — cleared to proceed.");
|
||||||
|
app.addProperty("discrepancyType", "NONE");
|
||||||
|
app.addProperty("overallStatus", "IN_PROGRESS");
|
||||||
|
app.addProperty("personalDiscussionNotes", remarks);
|
||||||
|
app.addProperty("declarationTaken", true);
|
||||||
|
app.addProperty("declarationDate", today());
|
||||||
|
|
||||||
|
advance(app, actor(input), "Resolved", remarks);
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Approvals ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records a Credit Committee / Risk / Legal / Post-Check decision.
|
||||||
|
*
|
||||||
|
* @param field one of creditCommitteeApproval, riskApproval, legalApproval, postCheckApproval
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String decideApproval(final String applicationNo, final String field, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
|
||||||
|
final String decision = strOr(input, "decision", "APPROVED");
|
||||||
|
require(List.of("APPROVED", "REJECTED", "EXCEPTION_APPROVED").contains(decision), "Unknown decision: " + decision);
|
||||||
|
|
||||||
|
final String expectedStage = switch (field) {
|
||||||
|
case "creditCommitteeApproval" -> "CREDIT_COMMITTEE";
|
||||||
|
case "riskApproval" -> "RISK_APPROVAL";
|
||||||
|
case "legalApproval" -> "LEGAL_APPROVAL";
|
||||||
|
case "postCheckApproval" -> "POST_CHECK";
|
||||||
|
default -> throw badRequest("Unknown approval stage: " + field);
|
||||||
|
};
|
||||||
|
requireStage(app, expectedStage);
|
||||||
|
|
||||||
|
// Prerequisites are only enforced for a positive decision: a rejection has to remain possible
|
||||||
|
// at any point, and blocking it on an incomplete checklist would trap the application.
|
||||||
|
if (!"REJECTED".equals(decision)) {
|
||||||
|
switch (field) {
|
||||||
|
case "creditCommitteeApproval" -> requireCommitteeReportsReady(app, input);
|
||||||
|
case "riskApproval" -> requireRiskChecklistReady(app);
|
||||||
|
case "legalApproval" -> requireLegalChecklistDone(app);
|
||||||
|
case "postCheckApproval" -> requirePostCheckSignatures(app);
|
||||||
|
default -> throw badRequest("Unknown approval stage: " + field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String remarks = strOr(input, "remarks", "REJECTED".equals(decision) ? "Declined on review." : "Reviewed and approved.");
|
||||||
|
if ("creditCommitteeApproval".equals(field) && !"REJECTED".equals(decision)) {
|
||||||
|
// The resolution number and date are what the sanction letter later quotes, so they are
|
||||||
|
// recorded on the application and restated in the audit trail.
|
||||||
|
final String resolutionNo = strOr(input, "resolutionNo", "");
|
||||||
|
final String resolutionDate = strOr(input, "resolutionDate", "");
|
||||||
|
app.addProperty("committeeResolutionNo", resolutionNo);
|
||||||
|
app.addProperty("committeeResolutionDate", resolutionDate);
|
||||||
|
remarks = remarks + " (Resolution No. " + resolutionNo + " dated " + resolutionDate + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
final JsonObject approval = objOrCreate(app, field);
|
||||||
|
approval.addProperty("decision", decision);
|
||||||
|
approval.addProperty("approverName", strOr(input, "approverName", "Bank Staff"));
|
||||||
|
approval.addProperty("approverRole", strOr(input, "approverRole", expectedStage));
|
||||||
|
approval.addProperty("date", today());
|
||||||
|
approval.addProperty("remarks", remarks);
|
||||||
|
|
||||||
|
if ("REJECTED".equals(decision)) {
|
||||||
|
app.addProperty("overallStatus", "REJECTED");
|
||||||
|
appendHistory(app, str(app, "currentStage"), actor(input), "Rejected", remarks);
|
||||||
|
} else {
|
||||||
|
advance(app, actor(input), "EXCEPTION_APPROVED".equals(decision) ? "Approved on Exception" : "Approved", remarks);
|
||||||
|
}
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Signing / Cheque-ACH / Disbursement ──────────────────────────────────
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String markSigned(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "CUSTOMER_SIGNING");
|
||||||
|
require(filled(app, "agreementSigningSlot"), "No agreement signing slot has been recorded.");
|
||||||
|
|
||||||
|
app.addProperty("customerSigningDate", today());
|
||||||
|
advance(app, strOr(input, "actionBy", strOr(app, "applicantName", "Customer")), "Signed",
|
||||||
|
strOr(input, "remarks", "Loan agreement signed by the customer."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public String confirmChequeAch(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "CHEQUE_ACH");
|
||||||
|
require(bool(app, "chequeReceived"), "Security cheques have not been received.");
|
||||||
|
require(bool(app, "achSigned"), "The ACH/NACH mandate has not been signed.");
|
||||||
|
|
||||||
|
advance(app, actor(input), "Cheque & ACH Received",
|
||||||
|
strOr(input, "remarks", "Security cheques received and ACH mandate signed."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Final disbursement. Requires every approval level to actually stand as approved on the stored
|
||||||
|
* record — the last point at which an application could otherwise slip through with a rejected or
|
||||||
|
* still-pending sign-off.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String disburse(final String applicationNo, final String body) {
|
||||||
|
final JsonObject app = pipelineService.loadApplication(applicationNo);
|
||||||
|
final JsonObject input = parseObject(body);
|
||||||
|
requireStage(app, "DISBURSED");
|
||||||
|
require(!"DISBURSED".equals(str(app, "overallStatus")), "This application has already been disbursed.");
|
||||||
|
|
||||||
|
for (final String field : List.of("creditCommitteeApproval", "riskApproval", "legalApproval", "postCheckApproval")) {
|
||||||
|
final JsonObject approval = obj(app, field);
|
||||||
|
final String decision = approval == null ? null : str(approval, "decision");
|
||||||
|
require("APPROVED".equals(decision) || "EXCEPTION_APPROVED".equals(decision),
|
||||||
|
"Cannot disburse: " + field + " is not approved.");
|
||||||
|
}
|
||||||
|
require(filled(app, "customerSigningDate"), "The customer has not signed the loan agreement.");
|
||||||
|
|
||||||
|
final String mode = strOr(input, "disbursementMode", "Account Credit");
|
||||||
|
app.addProperty("disbursementDate", today());
|
||||||
|
app.addProperty("disbursementMode", mode);
|
||||||
|
if (!filled(app, "achConfirmationRef")) {
|
||||||
|
final String suffix = applicationNo.length() >= 6 ? applicationNo.substring(applicationNo.length() - 6) : applicationNo;
|
||||||
|
app.addProperty("achConfirmationRef", "ACH" + suffix);
|
||||||
|
}
|
||||||
|
app.addProperty("emiActivationConfirmed", true);
|
||||||
|
app.addProperty("emiActivationDate", today());
|
||||||
|
app.addProperty("overallStatus", "DISBURSED");
|
||||||
|
if (LoanOriginationJson.present(input, "fineractLoanId")) {
|
||||||
|
app.addProperty("fineractLoanId", LoanOriginationJson.lng(input, "fineractLoanId"));
|
||||||
|
app.addProperty("fineractLoanAccountNo", str(input, "fineractLoanAccountNo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
appendHistory(app, "DISBURSED", actor(input), "Disbursed", strOr(input, "remarks",
|
||||||
|
"Disbursed via " + mode + " — ACH confirmation " + strOr(app, "achConfirmationRef", "—") + ". EMI activation confirmed."));
|
||||||
|
return pipelineService.storeApplication(applicationNo, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Shared checklist rules (mirror the Application Detail screen's gating) ─
|
||||||
|
|
||||||
|
private void requireFieldInvestigationComplete(final JsonObject app) {
|
||||||
|
requireCheckVerified(app, "addressVerification", "Address verification");
|
||||||
|
requireCheckVerified(app, "officeVerification", "Office/employment verification");
|
||||||
|
if (bool(app, "secured")) {
|
||||||
|
requireCheckVerified(app, "propertyVerification", "Property verification");
|
||||||
|
}
|
||||||
|
if (bool(app, "hasShop")) {
|
||||||
|
requireCheckVerified(app, "shopVerification", "Shop verification");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireCheckVerified(final JsonObject app, final String key, final String label) {
|
||||||
|
final JsonObject check = obj(app, key);
|
||||||
|
require(check != null && "VERIFIED".equals(str(check, "status")), label + " is not verified.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireCommitteeReportsReady(final JsonObject app, final JsonObject input) {
|
||||||
|
require(bool(app, "cicReportUploaded"), "The credit bureau report is not on file.");
|
||||||
|
require(bool(app, "backgroundCheckDone"), "The background check has not been done.");
|
||||||
|
if (bool(app, "secured")) {
|
||||||
|
require(bool(app, "cersaiSearchDone"), "The CERSAI search has not been done.");
|
||||||
|
}
|
||||||
|
require(bool(app, "aadhaarVerified"), "Aadhaar has not been verified.");
|
||||||
|
require(bool(app, "panVerified"), "PAN has not been verified.");
|
||||||
|
require(bool(app, "incomeProofSubmitted"), "Income proof has not been submitted.");
|
||||||
|
requireFieldInvestigationComplete(app);
|
||||||
|
require(bool(app, "managerMeetingDone"), "The manager meeting has not been recorded.");
|
||||||
|
require(!strOr(input, "resolutionNo", "").isBlank(), "A committee resolution number is required.");
|
||||||
|
require(!strOr(input, "resolutionDate", "").isBlank(), "A committee resolution date is required.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireRiskChecklistReady(final JsonObject app) {
|
||||||
|
requireCheckVerified(app, "addressVerification", "Address verification");
|
||||||
|
require(bool(app, "incomeProofSubmitted"), "Income proof has not been submitted.");
|
||||||
|
require(bool(app, "previousLoanDeclarationDone"), "The previous-loan declaration has not been taken.");
|
||||||
|
if (bool(app, "secured")) {
|
||||||
|
require(bool(app, "propertySearchReportDone"), "The property search report is not on file.");
|
||||||
|
require(bool(app, "valuationReportConfirmed"), "The valuation report has not been confirmed.");
|
||||||
|
}
|
||||||
|
requireFieldInvestigationComplete(app);
|
||||||
|
require(bool(app, "backgroundCheckDone"), "The background check has not been done.");
|
||||||
|
if (bool(app, "guarantorRequired")) {
|
||||||
|
// A guarantor at a co-operative bank has to be an existing member, not just a name: an
|
||||||
|
// onboarded client id AND a live share account.
|
||||||
|
require(LoanOriginationJson.lng(app, "guarantorClientId") != null,
|
||||||
|
"A guarantor is required but no existing client has been selected.");
|
||||||
|
require(bool(app, "guarantorHasShareAccount"), "The selected guarantor has no active share account.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireLegalChecklistDone(final JsonObject app) {
|
||||||
|
require(bool(app, "feesAndAccountOpened"), "Fees and account opening are not complete.");
|
||||||
|
if (bool(app, "secured")) {
|
||||||
|
require(bool(app, "mortgageCreated"), "The mortgage has not been created.");
|
||||||
|
}
|
||||||
|
require(bool(app, "legalStampDone"), "Legal stamping is not complete.");
|
||||||
|
require(bool(app, "fileFilingDone"), "File filing is not complete.");
|
||||||
|
for (final JsonElement element : arr(app, "legalDocuments")) {
|
||||||
|
final JsonObject doc = element.getAsJsonObject();
|
||||||
|
require(bool(doc, "submitted"), "Legal document not submitted: " + strOr(doc, "label", strOr(doc, "key", "document")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requirePostCheckSignatures(final JsonObject app) {
|
||||||
|
require(bool(app, "signedByAgent"), "The agent has not signed off.");
|
||||||
|
require(bool(app, "signedByManager"), "The manager has not signed off.");
|
||||||
|
require(bool(app, "signedByCommittee"), "The committee has not signed off.");
|
||||||
|
require(bool(app, "signedByRiskApproval"), "Risk approval has not signed off.");
|
||||||
|
require(bool(app, "signedByLegalApproval"), "Legal approval has not signed off.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Stage / history mechanics ────────────────────────────────────────────
|
||||||
|
|
||||||
|
private void requireStage(final JsonObject app, final String expected) {
|
||||||
|
final String actual = str(app, "currentStage");
|
||||||
|
if (!expected.equals(actual)) {
|
||||||
|
throw badRequest("This action applies at the " + expected + " stage, but the application is at " + actual + ".");
|
||||||
|
}
|
||||||
|
final String status = str(app, "overallStatus");
|
||||||
|
if ("REJECTED".equals(status)) {
|
||||||
|
throw badRequest("This application has been rejected and cannot be progressed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the application to the next stage and appends the audit entry. {@code furthestStageIndex}
|
||||||
|
* only ever increases, so jumping back to an earlier stage for a correction does not make
|
||||||
|
* already-completed stages look unfinished.
|
||||||
|
*/
|
||||||
|
private void advance(final JsonObject app, final String actionBy, final String outcome, final String remarks) {
|
||||||
|
final String current = str(app, "currentStage");
|
||||||
|
appendHistory(app, current, actionBy, outcome, remarks);
|
||||||
|
|
||||||
|
final int index = STAGE_ORDER.indexOf(current);
|
||||||
|
if (index >= 0 && index < STAGE_ORDER.size() - 1) {
|
||||||
|
final int next = index + 1;
|
||||||
|
app.addProperty("currentStage", STAGE_ORDER.get(next));
|
||||||
|
app.addProperty("furthestStageIndex", Math.max(intOr(app, "furthestStageIndex", 0), next));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendHistory(final JsonObject app, final String stage, final String actionBy, final String outcome,
|
||||||
|
final String remarks) {
|
||||||
|
final JsonArray history = arrOrCreate(app, "stageHistory");
|
||||||
|
final JsonObject entry = new JsonObject();
|
||||||
|
entry.addProperty("stage", stage);
|
||||||
|
entry.addProperty("date", today());
|
||||||
|
entry.addProperty("actionBy", actionBy);
|
||||||
|
entry.addProperty("outcome", outcome);
|
||||||
|
entry.addProperty("remarks", remarks);
|
||||||
|
history.add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String actor(final JsonObject input) {
|
||||||
|
return strOr(input, "actionBy", "Bank Staff");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String today() {
|
||||||
|
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
|
||||||
|
return (businessDate == null ? LocalDate.now(DateUtils.getDateTimeZoneOfTenant()) : businessDate).format(WORKFLOW_DATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void require(final boolean condition, final String message) {
|
||||||
|
if (!condition) {
|
||||||
|
throw badRequest(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeneralPlatformDomainRuleException badRequest(final String message) {
|
||||||
|
return new GeneralPlatformDomainRuleException("error.msg.loan.origination.stage.invalid", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kept for symmetry with the check-key list above; used by callers validating a key up front. */
|
||||||
|
public static boolean isKnownFieldCheck(final String checkKey) {
|
||||||
|
return FI_CHECK_KEYS.contains(checkKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exposed so the API layer can advertise the stage order without duplicating it. */
|
||||||
|
public static List<String> stageOrder() {
|
||||||
|
return Arrays.asList(STAGE_ORDER.toArray(new String[0]));
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
-4
@@ -18,6 +18,8 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.portfolio.mobilelookup.api;
|
package org.apache.fineract.portfolio.mobilelookup.api;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
@@ -26,11 +28,16 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
|||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.ws.rs.Consumes;
|
import jakarta.ws.rs.Consumes;
|
||||||
import jakarta.ws.rs.GET;
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
import jakarta.ws.rs.Path;
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
import jakarta.ws.rs.Produces;
|
import jakarta.ws.rs.Produces;
|
||||||
import jakarta.ws.rs.QueryParam;
|
import jakarta.ws.rs.QueryParam;
|
||||||
import jakarta.ws.rs.core.MediaType;
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
@@ -63,6 +70,8 @@ public class MobileLookupApiResource {
|
|||||||
private final MobileLookupService mobileLookupService;
|
private final MobileLookupService mobileLookupService;
|
||||||
private final DefaultToApiJsonSerializer<MobileLookupResult> resultSerializer;
|
private final DefaultToApiJsonSerializer<MobileLookupResult> resultSerializer;
|
||||||
private final DefaultToApiJsonSerializer<List> listSerializer;
|
private final DefaultToApiJsonSerializer<List> listSerializer;
|
||||||
|
private final DefaultToApiJsonSerializer<MobileLookupLogData> logSerializer;
|
||||||
|
private final DefaultToApiJsonSerializer<Map> mapSerializer;
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/check")
|
@Path("/check")
|
||||||
@@ -80,6 +89,20 @@ public class MobileLookupApiResource {
|
|||||||
@QueryParam("mobileNumber") @Parameter(description = "Mobile number to check (10-15 digits)") final String mobileNumber) {
|
@QueryParam("mobileNumber") @Parameter(description = "Mobile number to check (10-15 digits)") final String mobileNumber) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission("MOBILE_LOOKUP");
|
this.context.authenticatedUser().validateHasReadPermission("MOBILE_LOOKUP");
|
||||||
final MobileLookupResult result = mobileLookupService.checkMobileNumber(mobileNumber);
|
final MobileLookupResult result = mobileLookupService.checkMobileNumber(mobileNumber);
|
||||||
|
|
||||||
|
// Surface any earlier rejection of the same number so the officer screening it today is
|
||||||
|
// not the only one without that history.
|
||||||
|
final MobileLookupLog priorRejection = mobileLookupService.findPriorRejection(mobileNumber);
|
||||||
|
if (priorRejection != null && !priorRejection.getId().equals(result.getLookupLogId())) {
|
||||||
|
final Map<String, Object> payload = new LinkedHashMap<>();
|
||||||
|
payload.put("lookupLogId", result.getLookupLogId());
|
||||||
|
payload.put("success", result.isSuccess());
|
||||||
|
payload.put("message", result.getMessage());
|
||||||
|
payload.put("data", result.getData());
|
||||||
|
payload.put("timestamp", result.getTimestamp());
|
||||||
|
payload.put("priorRejection", MobileLookupLogData.fromEntity(priorRejection));
|
||||||
|
return mapSerializer.serialize(payload);
|
||||||
|
}
|
||||||
return resultSerializer.serialize(result);
|
return resultSerializer.serialize(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,10 +130,77 @@ public class MobileLookupApiResource {
|
|||||||
logs = mobileLookupService.getLookupLogs();
|
logs = mobileLookupService.getLookupLogs();
|
||||||
}
|
}
|
||||||
|
|
||||||
final List<MobileLookupLogData> logDataList = logs.stream()
|
return listSerializer.serialize(withClientNames(logs));
|
||||||
.map(MobileLookupLogData::fromEntity)
|
}
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
return listSerializer.serialize(logDataList);
|
/**
|
||||||
|
* Attaches the client's display name and account number to each row. The log stores only the
|
||||||
|
* client id, and a queue of bare ids is not something a reviewing officer can act on.
|
||||||
|
*/
|
||||||
|
private List<MobileLookupLogData> withClientNames(final List<MobileLookupLog> logs) {
|
||||||
|
final Set<Long> clientIds = logs.stream()
|
||||||
|
.map(MobileLookupLog::getClientId)
|
||||||
|
.filter(java.util.Objects::nonNull)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
final Map<Long, String[]> names = mobileLookupService.resolveClientNames(clientIds);
|
||||||
|
|
||||||
|
return logs.stream().map(log -> {
|
||||||
|
final String[] client = log.getClientId() == null ? null : names.get(log.getClientId());
|
||||||
|
return MobileLookupLogData.fromEntity(log, client == null ? null : client[0],
|
||||||
|
client == null ? null : client[1]);
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/pending")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Lookups awaiting an officer's decision",
|
||||||
|
description = "SUSPECTED or DISCONNECTED numbers on which no PROCEEDED/REJECTED decision "
|
||||||
|
+ "has been recorded yet.")
|
||||||
|
public String getPendingDecisions() {
|
||||||
|
this.context.authenticatedUser().validateHasReadPermission("MOBILE_LOOKUP");
|
||||||
|
|
||||||
|
return listSerializer.serialize(withClientNames(mobileLookupService.getPendingDecisions()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/logs/{logId}/decision")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Record the officer's decision on a flagged number",
|
||||||
|
description = "Body: {\"decision\": \"PROCEEDED|REJECTED\", \"reason\": \"...\"}. "
|
||||||
|
+ "A reason is mandatory when proceeding despite a DIP/MNRL hit.")
|
||||||
|
public String recordDecision(@PathParam("logId") final Long logId, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("OVERRIDE_MOBILE_LOOKUP");
|
||||||
|
|
||||||
|
final JsonObject json = JsonParser.parseString(apiRequestBodyAsJson).getAsJsonObject();
|
||||||
|
final String decision = json.has("decision") ? json.get("decision").getAsString() : null;
|
||||||
|
final String reason = json.has("reason") ? json.get("reason").getAsString() : null;
|
||||||
|
|
||||||
|
final MobileLookupLogData result = MobileLookupLogData.fromEntity(mobileLookupService
|
||||||
|
.recordDecision(logId, decision, reason, this.context.authenticatedUser().getId()));
|
||||||
|
return logSerializer.serialize(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/rescreen")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Re-screen existing clients' mobile numbers against DIP/MNRL",
|
||||||
|
description = "Screens every active client's mobile and alternate mobile numbers, opening a "
|
||||||
|
+ "decision row for each hit. Detects numbers reported for fraud or reassigned after "
|
||||||
|
+ "the customer was onboarded.")
|
||||||
|
public String rescreenExistingClients() {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("OVERRIDE_MOBILE_LOOKUP");
|
||||||
|
|
||||||
|
final int flagged = mobileLookupService.rescreenExistingClients();
|
||||||
|
final Map<String, Object> response = new LinkedHashMap<>();
|
||||||
|
response.put("message", "DIP/MNRL re-screening complete");
|
||||||
|
response.put("numbersFlagged", flagged);
|
||||||
|
// Reported so "0 flagged" can be told apart from "0 clients were even looked at" — the
|
||||||
|
// two mean very different things and the caller could not previously distinguish them.
|
||||||
|
response.put("clientsScanned", mobileLookupService.countScreenableClients());
|
||||||
|
return mapSerializer.serialize(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-1
@@ -34,9 +34,26 @@ public class MobileLookupLogData {
|
|||||||
private final String responseMessage;
|
private final String responseMessage;
|
||||||
private final String lookupSource;
|
private final String lookupSource;
|
||||||
private final Long clientId;
|
private final Long clientId;
|
||||||
|
/**
|
||||||
|
* Resolved separately from the log row, which stores only the id. A queue showing a bare
|
||||||
|
* "145" gives the reviewing officer nothing to act on — they need to know who it is.
|
||||||
|
*/
|
||||||
|
private final String clientName;
|
||||||
|
private final String clientAccountNo;
|
||||||
private final String lookedUpOn;
|
private final String lookedUpOn;
|
||||||
|
private final String overrideDecision;
|
||||||
|
private final String overrideReason;
|
||||||
|
private final Long decidedBy;
|
||||||
|
private final String decidedOn;
|
||||||
|
/** Whether this lookup permits the number to be used on a client record. */
|
||||||
|
private final boolean usable;
|
||||||
|
|
||||||
public static MobileLookupLogData fromEntity(final MobileLookupLog log) {
|
public static MobileLookupLogData fromEntity(final MobileLookupLog log) {
|
||||||
|
return fromEntity(log, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MobileLookupLogData fromEntity(final MobileLookupLog log, final String clientName,
|
||||||
|
final String clientAccountNo) {
|
||||||
return new MobileLookupLogData(
|
return new MobileLookupLogData(
|
||||||
log.getId(),
|
log.getId(),
|
||||||
log.getMobileNumber(),
|
log.getMobileNumber(),
|
||||||
@@ -46,6 +63,13 @@ public class MobileLookupLogData {
|
|||||||
log.getResponseMessage(),
|
log.getResponseMessage(),
|
||||||
log.getLookupSource(),
|
log.getLookupSource(),
|
||||||
log.getClientId(),
|
log.getClientId(),
|
||||||
log.getLookedUpOn() != null ? log.getLookedUpOn().toString() : null);
|
clientName,
|
||||||
|
clientAccountNo,
|
||||||
|
log.getLookedUpOn() != null ? log.getLookedUpOn().toString() : null,
|
||||||
|
log.getOverrideDecision(),
|
||||||
|
log.getOverrideReason(),
|
||||||
|
log.getDecidedBy(),
|
||||||
|
log.getDecidedOn() != null ? log.getDecidedOn().toString() : null,
|
||||||
|
log.isUsable());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+61
@@ -33,4 +33,65 @@ public interface MobileLookupService {
|
|||||||
List<MobileLookupLog> getLookupLogsByMobileNumber(String mobileNumber);
|
List<MobileLookupLog> getLookupLogsByMobileNumber(String mobileNumber);
|
||||||
|
|
||||||
List<MobileLookupLog> getLookupLogsByStatus(String status);
|
List<MobileLookupLog> getLookupLogsByStatus(String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the officer's decision on a lookup that came back SUSPECTED or DISCONNECTED.
|
||||||
|
*
|
||||||
|
* @param decision PROCEEDED or REJECTED
|
||||||
|
* @param reason mandatory when proceeding — why the number is acceptable anyway
|
||||||
|
*/
|
||||||
|
MobileLookupLog recordDecision(Long logId, String decision, String reason, Long userId);
|
||||||
|
|
||||||
|
/** Non-clean lookups still awaiting a decision. */
|
||||||
|
List<MobileLookupLog> getPendingDecisions();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the number's latest lookup permits it to be stored on a client — clean, or a hit
|
||||||
|
* the officer explicitly decided to proceed with. A DoT outage is not a pass.
|
||||||
|
*/
|
||||||
|
boolean isMobileNumberUsable(String mobileNumber);
|
||||||
|
|
||||||
|
/** Latest lookup status for the number, or null when it has never been checked. */
|
||||||
|
String getLatestStatus(String mobileNumber);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The most recent time this number was rejected, on any client, or null if never. A number
|
||||||
|
* turned away once should not be screened as if it had no history.
|
||||||
|
*/
|
||||||
|
MobileLookupLog findPriorRejection(String mobileNumber);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-screens every active client's mobile numbers against DIP/MNRL, opening a decision row
|
||||||
|
* for each hit.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Onboarding-time screening only ever sees a number as it is typed. A number reported for
|
||||||
|
* fraud, or disconnected and reassigned, after the customer was onboarded is otherwise never
|
||||||
|
* detected — and that is precisely the case where the bank's OTPs start reaching a stranger.
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @return count of numbers that came back flagged
|
||||||
|
*/
|
||||||
|
int rescreenExistingClients();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display name and account number for the given client ids, keyed by id. Resolved in one
|
||||||
|
* query so a queue of lookups does not issue a round trip per row.
|
||||||
|
*/
|
||||||
|
java.util.Map<Long, String[]> resolveClientNames(java.util.Collection<Long> clientIds);
|
||||||
|
|
||||||
|
/** How many clients the re-screen sweep would look at — lets "0 flagged" be interpreted. */
|
||||||
|
int countScreenableClients();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks every open alert on a number as resolved, recording why.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Called when the number is replaced on a client: the alert then refers to a number the bank
|
||||||
|
* no longer uses, and leaving it "Awaiting Decision" would misrepresent it as outstanding work.
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @return how many alerts were closed
|
||||||
|
*/
|
||||||
|
int closeOpenAlerts(String mobileNumber, Long clientId, String reason);
|
||||||
}
|
}
|
||||||
|
|||||||
+256
-4
@@ -21,8 +21,13 @@ package org.apache.fineract.portfolio.mobilelookup.service;
|
|||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonParser;
|
import com.google.gson.JsonParser;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
import org.apache.fineract.portfolio.mobilelookup.data.MobileLookupDetailData;
|
import org.apache.fineract.portfolio.mobilelookup.data.MobileLookupDetailData;
|
||||||
import org.apache.fineract.portfolio.mobilelookup.data.MobileLookupResult;
|
import org.apache.fineract.portfolio.mobilelookup.data.MobileLookupResult;
|
||||||
import org.apache.fineract.portfolio.mobilelookup.domain.MobileLookupLog;
|
import org.apache.fineract.portfolio.mobilelookup.domain.MobileLookupLog;
|
||||||
@@ -30,6 +35,8 @@ import org.apache.fineract.portfolio.mobilelookup.domain.MobileLookupLogReposito
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
@@ -50,15 +57,26 @@ public class MobileLookupServiceImpl implements MobileLookupService {
|
|||||||
"9752123456", "9752345678", "9752987654"
|
"9752123456", "9752345678", "9752987654"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** Demo numbers that always return DISCONNECTED (found on the MNRL) without calling the external API. */
|
||||||
|
private static final Set<String> DEMO_DISCONNECTED_NUMBERS = Set.of("9000000001", "9000000002");
|
||||||
|
|
||||||
|
/** Demo numbers that always return SUSPECTED_AND_DISCONNECTED without calling the external API. */
|
||||||
|
private static final Set<String> DEMO_SUSPECTED_AND_DISCONNECTED_NUMBERS = Set.of("9000000003");
|
||||||
|
|
||||||
private final String baseUrl;
|
private final String baseUrl;
|
||||||
|
private final boolean enabled;
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
private final MobileLookupLogRepository logRepository;
|
private final MobileLookupLogRepository logRepository;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
public MobileLookupServiceImpl(@Value("${fineract.mobile-lookup.base-url}") String baseUrl,
|
public MobileLookupServiceImpl(@Value("${fineract.mobile-lookup.base-url}") String baseUrl,
|
||||||
MobileLookupLogRepository logRepository) {
|
@Value("${fineract.mobile-lookup.enabled:true}") boolean enabled,
|
||||||
|
MobileLookupLogRepository logRepository, JdbcTemplate jdbcTemplate) {
|
||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl;
|
||||||
|
this.enabled = enabled;
|
||||||
this.restTemplate = new RestTemplate();
|
this.restTemplate = new RestTemplate();
|
||||||
this.logRepository = logRepository;
|
this.logRepository = logRepository;
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -94,6 +112,39 @@ public class MobileLookupServiceImpl implements MobileLookupService {
|
|||||||
return MobileLookupResult.clean(logId, trimmed);
|
return MobileLookupResult.clean(logId, trimmed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Demo numbers — return DISCONNECTED (on the MNRL) without calling the external API
|
||||||
|
if (isDemoDisconnectedNumber(trimmed)) {
|
||||||
|
LOG.info("Demo disconnected number detected: {}", trimmed);
|
||||||
|
final MobileLookupDetailData disconnectedDetail = MobileLookupDetailData.forDisconnected(
|
||||||
|
"Number revoked and listed on MNRL (demo data)", "DEMO");
|
||||||
|
final Long logId = saveLog(trimmed, "DISCONNECTED", false, true,
|
||||||
|
"Number is DISCONNECTED — found in MNRL records", null, source, clientId);
|
||||||
|
return MobileLookupResult.disconnected(logId, trimmed, disconnectedDetail);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Demo numbers — return SUSPECTED_AND_DISCONNECTED without calling the external API
|
||||||
|
if (isDemoSuspectedAndDisconnectedNumber(trimmed)) {
|
||||||
|
LOG.info("Demo suspected+disconnected number detected: {}", trimmed);
|
||||||
|
final MobileLookupDetailData suspectedDetail = MobileLookupDetailData.forSuspected(
|
||||||
|
"active", "Demo DIP suspected number", "DEMO");
|
||||||
|
final MobileLookupDetailData disconnectedDetail = MobileLookupDetailData.forDisconnected(
|
||||||
|
"Number revoked and listed on MNRL (demo data)", "DEMO");
|
||||||
|
final Long logId = saveLog(trimmed, "SUSPECTED_AND_DISCONNECTED", true, true,
|
||||||
|
"Number is SUSPECTED and DISCONNECTED — found in both DIP and MNRL records", null, source, clientId);
|
||||||
|
return MobileLookupResult.suspectedAndDisconnected(logId, trimmed, suspectedDetail, disconnectedDetail);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup switched off by config (fineract.mobile-lookup.enabled=false) -- skip the external
|
||||||
|
// call entirely rather than fail with a connection error. Logged distinctly from a genuine
|
||||||
|
// CLEAN result so it can never be mistaken for one in an audit trail.
|
||||||
|
if (!enabled) {
|
||||||
|
LOG.info("DIP/MNRL lookup is disabled by configuration — skipping check for {}", trimmed);
|
||||||
|
final Long logId = saveLog(trimmed, MobileLookupLog.STATUS_CLEAN, false, false,
|
||||||
|
"DIP/MNRL lookup is disabled by configuration — the number was not actually checked.",
|
||||||
|
"{\"provider\":\"LOOKUP_DISABLED_BY_CONFIG\"}", source, clientId);
|
||||||
|
return MobileLookupResult.clean(logId, trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
final String url = baseUrl + "/api/v1/lookup/check?mobileNumber=" + trimmed;
|
final String url = baseUrl + "/api/v1/lookup/check?mobileNumber=" + trimmed;
|
||||||
|
|
||||||
LOG.info("Calling DIP/MNRL lookup API: {}", url);
|
LOG.info("Calling DIP/MNRL lookup API: {}", url);
|
||||||
@@ -113,13 +164,194 @@ public class MobileLookupServiceImpl implements MobileLookupService {
|
|||||||
parsed.getData(), parsed.getTimestamp());
|
parsed.getData(), parsed.getTimestamp());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Failed to call DIP/MNRL lookup API for {}: {}", trimmed, e.getMessage());
|
LOG.error("Failed to call DIP/MNRL lookup API for {}: {}", trimmed, e.getMessage());
|
||||||
final Long logId = saveLog(trimmed, "ERROR", false, false,
|
// An unreachable DoT service means the number was NOT checked. It is logged under its
|
||||||
e.getMessage(), rawResponse, source, clientId);
|
// own status rather than ERROR so the queue can distinguish "we could not verify" from
|
||||||
|
// "the lookup itself failed", and it is never presented to the officer as a pass.
|
||||||
|
final Long logId = saveLog(trimmed, MobileLookupLog.STATUS_SERVICE_UNAVAILABLE, false, false,
|
||||||
|
"DIP/MNRL lookup service is unavailable — the number could not be verified.",
|
||||||
|
rawResponse, source, clientId);
|
||||||
return MobileLookupResult.serviceUnavailable(logId, trimmed,
|
return MobileLookupResult.serviceUnavailable(logId, trimmed,
|
||||||
"DIP/MNRL lookup service is unavailable. Number treated as CLEAN by default.");
|
"DIP/MNRL lookup service is unavailable — the number could not be verified.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public MobileLookupLog recordDecision(final Long logId, final String decision, final String reason,
|
||||||
|
final Long userId) {
|
||||||
|
final MobileLookupLog log = logRepository.findById(logId)
|
||||||
|
.orElseThrow(() -> new GeneralPlatformDomainRuleException("error.msg.mobile.lookup.not.found",
|
||||||
|
"Mobile lookup " + logId + " does not exist."));
|
||||||
|
|
||||||
|
final String normalised = decision == null ? "" : decision.trim().toUpperCase();
|
||||||
|
if (!MobileLookupLog.DECISION_PROCEEDED.equals(normalised)
|
||||||
|
&& !MobileLookupLog.DECISION_REJECTED.equals(normalised)) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.mobile.lookup.decision.invalid",
|
||||||
|
"Decision must be PROCEEDED or REJECTED.");
|
||||||
|
}
|
||||||
|
// Proceeding past a DIP hit is the judgement call that has to survive an audit, so it
|
||||||
|
// cannot be recorded without the officer's reasoning. Rejecting needs no justification.
|
||||||
|
if (MobileLookupLog.DECISION_PROCEEDED.equals(normalised) && (reason == null || reason.trim().length() < 10)) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.mobile.lookup.reason.required",
|
||||||
|
"Record why this number is acceptable despite the DIP/MNRL result (minimum 10 characters).");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.recordDecision(normalised, reason == null ? null : reason.trim(), userId);
|
||||||
|
logRepository.saveAndFlush(log);
|
||||||
|
LOG.warn("Mobile lookup {} for {} decided as {}", logId, log.getMobileNumber(), normalised);
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<MobileLookupLog> getPendingDecisions() {
|
||||||
|
return logRepository.findPendingDecisions();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean isMobileNumberUsable(final String mobileNumber) {
|
||||||
|
if (mobileNumber == null || mobileNumber.isBlank()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
final MobileLookupLog latest = findLatest(mobileNumber.trim());
|
||||||
|
// No lookup on record is handled by the caller (it decides whether a check is mandatory);
|
||||||
|
// here only an actual result can veto.
|
||||||
|
return latest == null || latest.isUsable();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public String getLatestStatus(final String mobileNumber) {
|
||||||
|
if (mobileNumber == null || mobileNumber.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final MobileLookupLog latest = findLatest(mobileNumber.trim());
|
||||||
|
return latest == null ? null : latest.getLookupStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Newest lookup row for a number, or null when it has never been checked. */
|
||||||
|
private MobileLookupLog findLatest(final String mobileNumber) {
|
||||||
|
final List<MobileLookupLog> rows = logRepository.findLatestByMobileNumber(mobileNumber, PageRequest.of(0, 1));
|
||||||
|
return rows.isEmpty() ? null : rows.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public int rescreenExistingClients() {
|
||||||
|
// Active clients only (status 300). A pending client is still inside the onboarding flow,
|
||||||
|
// where the number is screened as it is entered; this sweep exists for the customers that
|
||||||
|
// flow has already finished with. Closed/rejected/withdrawn have no live relationship.
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, mobile_no, alternate_mobile_no FROM m_client WHERE status_enum = 300 "
|
||||||
|
+ "AND (mobile_no IS NOT NULL OR alternate_mobile_no IS NOT NULL)");
|
||||||
|
|
||||||
|
LOG.info("DIP/MNRL re-screening starting for {} client(s) with a number on file", rows.size());
|
||||||
|
|
||||||
|
int flagged = 0;
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final Long clientId = ((Number) row.get("id")).longValue();
|
||||||
|
flagged += rescreenNumber((String) row.get("mobile_no"), clientId);
|
||||||
|
flagged += rescreenNumber((String) row.get("alternate_mobile_no"), clientId);
|
||||||
|
}
|
||||||
|
LOG.info("DIP/MNRL re-screening complete: {} number(s) flagged across {} clients", flagged, rows.size());
|
||||||
|
return flagged;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public int countScreenableClients() {
|
||||||
|
final Integer count = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM m_client WHERE status_enum = 300 "
|
||||||
|
+ "AND (mobile_no IS NOT NULL OR alternate_mobile_no IS NOT NULL)",
|
||||||
|
Integer.class);
|
||||||
|
return count == null ? 0 : count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Screens one number, tolerating per-number failure so one bad row cannot abort the sweep. */
|
||||||
|
private int rescreenNumber(final String mobileNumber, final Long clientId) {
|
||||||
|
if (mobileNumber == null || mobileNumber.isBlank()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
final String trimmed = mobileNumber.trim();
|
||||||
|
|
||||||
|
// Re-running the sweep must not stack another identical alert onto the queue. An open
|
||||||
|
// alert for this number and client is the same case still awaiting the same decision;
|
||||||
|
// duplicating it buries the real work under repeats of itself. A number already decided
|
||||||
|
// is likewise left alone until its value or decision changes.
|
||||||
|
final MobileLookupLog existing = findLatest(trimmed);
|
||||||
|
if (existing != null && existing.requiresDecision() && java.util.Objects.equals(existing.getClientId(), clientId)) {
|
||||||
|
LOG.debug("Skipping re-screen of {} for client {} — an open alert already exists", trimmed, clientId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final MobileLookupResult result = checkMobileNumber(trimmed, "PERIODIC_RESCREEN", clientId);
|
||||||
|
final boolean hit = result.getData() != null
|
||||||
|
&& (result.getData().isSuspected() || result.getData().isDisconnected());
|
||||||
|
return hit ? 1 : 0;
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOG.error("Re-screening failed for {} (client {}): {}", mobileNumber, clientId, e.getMessage());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Map<Long, String[]> resolveClientNames(final Collection<Long> clientIds) {
|
||||||
|
final Map<Long, String[]> byId = new HashMap<>();
|
||||||
|
if (clientIds == null || clientIds.isEmpty()) {
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
final String placeholders = clientIds.stream().map(id -> "?").collect(Collectors.joining(","));
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, display_name, account_no FROM m_client WHERE id IN (" + placeholders + ")",
|
||||||
|
clientIds.toArray());
|
||||||
|
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final Long id = ((Number) row.get("id")).longValue();
|
||||||
|
byId.put(id, new String[] { (String) row.get("display_name"), (String) row.get("account_no") });
|
||||||
|
}
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public int closeOpenAlerts(final String mobileNumber, final Long clientId, final String reason) {
|
||||||
|
if (mobileNumber == null || mobileNumber.isBlank()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
final List<MobileLookupLog> open = logRepository.findByMobileNumber(mobileNumber.trim()).stream()
|
||||||
|
.filter(MobileLookupLog::requiresDecision)
|
||||||
|
.filter(log -> log.getOverrideDecision() == null)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
for (final MobileLookupLog log : open) {
|
||||||
|
// REJECTED is the correct terminal state: the bank turned this number away. It also
|
||||||
|
// keeps isMobileNumberUsable() false, so the number cannot quietly come back into use.
|
||||||
|
log.recordDecision(MobileLookupLog.DECISION_REJECTED, reason, null);
|
||||||
|
if (log.getClientId() == null && clientId != null) {
|
||||||
|
log.setClientId(clientId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!open.isEmpty()) {
|
||||||
|
logRepository.saveAll(open);
|
||||||
|
logRepository.flush();
|
||||||
|
LOG.info("Closed {} open DIP alert(s) for replaced number {} on client {}", open.size(), mobileNumber, clientId);
|
||||||
|
}
|
||||||
|
return open.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public MobileLookupLog findPriorRejection(final String mobileNumber) {
|
||||||
|
if (mobileNumber == null || mobileNumber.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final List<MobileLookupLog> rejections = logRepository.findRejections(mobileNumber.trim(), PageRequest.of(0, 1));
|
||||||
|
return rejections.isEmpty() ? null : rejections.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public List<MobileLookupLog> getLookupLogs() {
|
public List<MobileLookupLog> getLookupLogs() {
|
||||||
@@ -212,6 +444,26 @@ public class MobileLookupServiceImpl implements MobileLookupService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isDemoDisconnectedNumber(final String mobileNumber) {
|
||||||
|
if (DEMO_DISCONNECTED_NUMBERS.contains(mobileNumber)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (mobileNumber.startsWith("91") && mobileNumber.length() > 10) {
|
||||||
|
return DEMO_DISCONNECTED_NUMBERS.contains(mobileNumber.substring(2));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isDemoSuspectedAndDisconnectedNumber(final String mobileNumber) {
|
||||||
|
if (DEMO_SUSPECTED_AND_DISCONNECTED_NUMBERS.contains(mobileNumber)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (mobileNumber.startsWith("91") && mobileNumber.length() > 10) {
|
||||||
|
return DEMO_SUSPECTED_AND_DISCONNECTED_NUMBERS.contains(mobileNumber.substring(2));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private String getStringOrNull(JsonObject json, String key) {
|
private String getStringOrNull(JsonObject json, String key) {
|
||||||
JsonElement el = json.get(key);
|
JsonElement el = json.get(key);
|
||||||
return (el != null && !el.isJsonNull()) ? el.getAsString() : null;
|
return (el != null && !el.isJsonNull()) ? el.getAsString() : null;
|
||||||
|
|||||||
+121
-4
@@ -28,6 +28,7 @@ import jakarta.ws.rs.Consumes;
|
|||||||
import jakarta.ws.rs.GET;
|
import jakarta.ws.rs.GET;
|
||||||
import jakarta.ws.rs.POST;
|
import jakarta.ws.rs.POST;
|
||||||
import jakarta.ws.rs.Path;
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.PathParam;
|
||||||
import jakarta.ws.rs.Produces;
|
import jakarta.ws.rs.Produces;
|
||||||
import jakarta.ws.rs.QueryParam;
|
import jakarta.ws.rs.QueryParam;
|
||||||
import jakarta.ws.rs.core.MediaType;
|
import jakarta.ws.rs.core.MediaType;
|
||||||
@@ -35,6 +36,7 @@ import java.io.InputStream;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
@@ -77,6 +79,7 @@ public class SanctionsScreeningApiResource {
|
|||||||
private final DefaultToApiJsonSerializer<SanctionsScreeningResult> screeningResultSerializer;
|
private final DefaultToApiJsonSerializer<SanctionsScreeningResult> screeningResultSerializer;
|
||||||
private final DefaultToApiJsonSerializer<Map> mapSerializer;
|
private final DefaultToApiJsonSerializer<Map> mapSerializer;
|
||||||
private final DefaultToApiJsonSerializer<List> listSerializer;
|
private final DefaultToApiJsonSerializer<List> listSerializer;
|
||||||
|
private final DefaultToApiJsonSerializer<SanctionsScreeningLogData> logSerializer;
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/screen")
|
@Path("/screen")
|
||||||
@@ -184,10 +187,124 @@ public class SanctionsScreeningApiResource {
|
|||||||
logs = sanctionsScreeningService.getScreeningLogs();
|
logs = sanctionsScreeningService.getScreeningLogs();
|
||||||
}
|
}
|
||||||
|
|
||||||
final List<SanctionsScreeningLogData> logDataList = logs.stream()
|
return listSerializer.serialize(withClientNames(logs));
|
||||||
.map(SanctionsScreeningLogData::fromEntity)
|
}
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
return listSerializer.serialize(logDataList);
|
/**
|
||||||
|
* Attaches the client's display name and account number to each row. The log stores only the
|
||||||
|
* client id, and a queue of bare ids is not something a reviewing officer can act on.
|
||||||
|
*/
|
||||||
|
private List<SanctionsScreeningLogData> withClientNames(final List<SanctionsScreeningLog> logs) {
|
||||||
|
final Set<Long> clientIds = logs.stream().map(SanctionsScreeningLog::getClientId).filter(java.util.Objects::nonNull)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
final Map<Long, String[]> names = sanctionsScreeningService.resolveClientNames(clientIds);
|
||||||
|
|
||||||
|
return logs.stream().map(log -> {
|
||||||
|
final String[] client = log.getClientId() == null ? null : names.get(log.getClientId());
|
||||||
|
return SanctionsScreeningLogData.fromEntity(log, client == null ? null : client[0],
|
||||||
|
client == null ? null : client[1]);
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Alert disposition ─────────────────────────────────────────────────────
|
||||||
|
// A flagged screening is a case, not a verdict. These endpoints close it out: the reviewing
|
||||||
|
// officer records whether it is the same person, the Principal Officer signs off, and a
|
||||||
|
// confirmed match carries the FIU-IND / nodal officer reporting references.
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/alerts")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "List sanctions alerts",
|
||||||
|
description = "Flagged screenings and their disposition state. Filter with "
|
||||||
|
+ "?status=PENDING_REVIEW | FALSE_POSITIVE | CONFIRMED_MATCH.")
|
||||||
|
public String getAlerts(
|
||||||
|
@QueryParam("status") @Parameter(description = "Filter by disposition") final String status) {
|
||||||
|
this.context.authenticatedUser().validateHasReadPermission("SANCTIONS");
|
||||||
|
|
||||||
|
return listSerializer.serialize(withClientNames(sanctionsScreeningService.getAlerts(status)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/alerts/{logId}/disposition")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Record the review outcome of a sanctions alert",
|
||||||
|
description = "Body: {\"disposition\": \"FALSE_POSITIVE|CONFIRMED_MATCH\", \"reason\": \"...\"}. "
|
||||||
|
+ "A false positive does not unblock onboarding until it is approved.")
|
||||||
|
public String recordDisposition(@PathParam("logId") final Long logId, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("DISPOSE_SANCTIONS");
|
||||||
|
|
||||||
|
final com.google.gson.JsonObject json = com.google.gson.JsonParser.parseString(apiRequestBodyAsJson).getAsJsonObject();
|
||||||
|
final String disposition = json.has("disposition") ? json.get("disposition").getAsString() : null;
|
||||||
|
final String reason = json.has("reason") ? json.get("reason").getAsString() : null;
|
||||||
|
|
||||||
|
final SanctionsScreeningLogData result = SanctionsScreeningLogData
|
||||||
|
.fromEntity(sanctionsScreeningService.recordDisposition(logId, disposition, reason));
|
||||||
|
return logSerializer.serialize(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/alerts/{logId}/approve")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Principal Officer approval of an alert disposition",
|
||||||
|
description = "Approving a FALSE_POSITIVE clears the name for onboarding. Approving a "
|
||||||
|
+ "CONFIRMED_MATCH freezes debits on every active deposit account of the client.")
|
||||||
|
public String approveAlert(@PathParam("logId") final Long logId) {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("APPROVE_SANCTIONS");
|
||||||
|
|
||||||
|
final SanctionsScreeningLogData result = SanctionsScreeningLogData
|
||||||
|
.fromEntity(sanctionsScreeningService.approveDisposition(logId));
|
||||||
|
return logSerializer.serialize(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/alerts/{logId}/report")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Record FIU-IND / nodal officer reporting for a confirmed match",
|
||||||
|
description = "Body: {\"fiuStrReference\": \"...\", \"nodalOfficerInformedOn\": \"yyyy-MM-dd\"}")
|
||||||
|
public String recordReporting(@PathParam("logId") final Long logId, final String apiRequestBodyAsJson) {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("APPROVE_SANCTIONS");
|
||||||
|
|
||||||
|
final com.google.gson.JsonObject json = com.google.gson.JsonParser.parseString(apiRequestBodyAsJson).getAsJsonObject();
|
||||||
|
final String strReference = json.has("fiuStrReference") ? json.get("fiuStrReference").getAsString() : null;
|
||||||
|
final String informedOn = json.has("nodalOfficerInformedOn") ? json.get("nodalOfficerInformedOn").getAsString() : null;
|
||||||
|
|
||||||
|
final SanctionsScreeningLogData result = SanctionsScreeningLogData
|
||||||
|
.fromEntity(sanctionsScreeningService.recordReporting(logId, strReference, informedOn));
|
||||||
|
return logSerializer.serialize(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("/str-cases")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Sanctions STR cases for the FIU-IND screen",
|
||||||
|
description = "Confirmed matches carrying a reporting obligation. Filter with "
|
||||||
|
+ "?status=PENDING_FILING | FILED. Kept separate from transaction-driven AML alerts.")
|
||||||
|
public String getStrCases(
|
||||||
|
@QueryParam("status") @Parameter(description = "PENDING_FILING or FILED") final String status) {
|
||||||
|
this.context.authenticatedUser().validateHasReadPermission("SANCTIONS");
|
||||||
|
|
||||||
|
return listSerializer.serialize(withClientNames(sanctionsScreeningService.getStrCases(status)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("/rescreen")
|
||||||
|
@Consumes({ MediaType.APPLICATION_JSON })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Re-screen all existing clients against the current list snapshot",
|
||||||
|
description = "Opens a PENDING_REVIEW alert for every existing client that now matches. "
|
||||||
|
+ "This is what detects a customer added to the list after onboarding.")
|
||||||
|
public String rescreenExistingClients() {
|
||||||
|
this.context.authenticatedUser().validateHasPermissionTo("LOAD_SANCTIONS");
|
||||||
|
|
||||||
|
final int flagged = sanctionsScreeningService.rescreenExistingClients();
|
||||||
|
final Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("message", "Re-screening complete");
|
||||||
|
response.put("clientsFlagged", flagged);
|
||||||
|
return mapSerializer.serialize(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+77
-3
@@ -34,14 +34,38 @@ public final class SanctionsScreeningLogData {
|
|||||||
private final String matchedNames;
|
private final String matchedNames;
|
||||||
private final String screeningSource;
|
private final String screeningSource;
|
||||||
private final Long clientId;
|
private final Long clientId;
|
||||||
|
/**
|
||||||
|
* Resolved separately from the log row, which stores only the id. A queue showing a bare
|
||||||
|
* "124" gives the reviewing officer nothing to act on — they need to know who it is.
|
||||||
|
*/
|
||||||
|
private final String clientName;
|
||||||
|
private final String clientAccountNo;
|
||||||
private final String ipAddress;
|
private final String ipAddress;
|
||||||
private final OffsetDateTime screenedOn;
|
private final OffsetDateTime screenedOn;
|
||||||
private final Long screenedBy;
|
private final Long screenedBy;
|
||||||
|
private final String disposition;
|
||||||
|
private final String dispositionReason;
|
||||||
|
private final Long reviewedBy;
|
||||||
|
private final OffsetDateTime reviewedOn;
|
||||||
|
private final Long approvedBy;
|
||||||
|
private final OffsetDateTime approvedOn;
|
||||||
|
private final String fiuStrReference;
|
||||||
|
private final OffsetDateTime nodalOfficerInformedOn;
|
||||||
|
private final String frozenAccountIds;
|
||||||
|
private final OffsetDateTime frozenOn;
|
||||||
|
private final String strStatus;
|
||||||
|
private final String strDueDate;
|
||||||
|
private final String strRaisedOn;
|
||||||
|
|
||||||
public SanctionsScreeningLogData(final Long id, final String screenedName, final String screeningResult,
|
public SanctionsScreeningLogData(final Long id, final String screenedName, final String screeningResult,
|
||||||
final Integer matchCount, final String matchedEntryIds, final String matchedNames,
|
final Integer matchCount, final String matchedEntryIds, final String matchedNames,
|
||||||
final String screeningSource, final Long clientId, final String ipAddress,
|
final String screeningSource, final Long clientId, final String clientName, final String clientAccountNo,
|
||||||
final OffsetDateTime screenedOn, final Long screenedBy) {
|
final String ipAddress,
|
||||||
|
final OffsetDateTime screenedOn, final Long screenedBy, final String disposition,
|
||||||
|
final String dispositionReason, final Long reviewedBy, final OffsetDateTime reviewedOn,
|
||||||
|
final Long approvedBy, final OffsetDateTime approvedOn, final String fiuStrReference,
|
||||||
|
final OffsetDateTime nodalOfficerInformedOn, final String frozenAccountIds,
|
||||||
|
final OffsetDateTime frozenOn, final String strStatus, final String strDueDate, final String strRaisedOn) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.screenedName = screenedName;
|
this.screenedName = screenedName;
|
||||||
this.screeningResult = screeningResult;
|
this.screeningResult = screeningResult;
|
||||||
@@ -50,12 +74,32 @@ public final class SanctionsScreeningLogData {
|
|||||||
this.matchedNames = matchedNames;
|
this.matchedNames = matchedNames;
|
||||||
this.screeningSource = screeningSource;
|
this.screeningSource = screeningSource;
|
||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
|
this.clientName = clientName;
|
||||||
|
this.clientAccountNo = clientAccountNo;
|
||||||
this.ipAddress = ipAddress;
|
this.ipAddress = ipAddress;
|
||||||
this.screenedOn = screenedOn;
|
this.screenedOn = screenedOn;
|
||||||
this.screenedBy = screenedBy;
|
this.screenedBy = screenedBy;
|
||||||
|
this.disposition = disposition;
|
||||||
|
this.dispositionReason = dispositionReason;
|
||||||
|
this.reviewedBy = reviewedBy;
|
||||||
|
this.reviewedOn = reviewedOn;
|
||||||
|
this.approvedBy = approvedBy;
|
||||||
|
this.approvedOn = approvedOn;
|
||||||
|
this.fiuStrReference = fiuStrReference;
|
||||||
|
this.nodalOfficerInformedOn = nodalOfficerInformedOn;
|
||||||
|
this.frozenAccountIds = frozenAccountIds;
|
||||||
|
this.frozenOn = frozenOn;
|
||||||
|
this.strStatus = strStatus;
|
||||||
|
this.strDueDate = strDueDate;
|
||||||
|
this.strRaisedOn = strRaisedOn;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static SanctionsScreeningLogData fromEntity(final SanctionsScreeningLog log) {
|
public static SanctionsScreeningLogData fromEntity(final SanctionsScreeningLog log) {
|
||||||
|
return fromEntity(log, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SanctionsScreeningLogData fromEntity(final SanctionsScreeningLog log, final String clientName,
|
||||||
|
final String clientAccountNo) {
|
||||||
return new SanctionsScreeningLogData(
|
return new SanctionsScreeningLogData(
|
||||||
log.getId(),
|
log.getId(),
|
||||||
log.getScreenedName(),
|
log.getScreenedName(),
|
||||||
@@ -65,9 +109,24 @@ public final class SanctionsScreeningLogData {
|
|||||||
log.getMatchedNames(),
|
log.getMatchedNames(),
|
||||||
log.getScreeningSource(),
|
log.getScreeningSource(),
|
||||||
log.getClientId(),
|
log.getClientId(),
|
||||||
|
clientName,
|
||||||
|
clientAccountNo,
|
||||||
log.getIpAddress(),
|
log.getIpAddress(),
|
||||||
log.getScreenedOn(),
|
log.getScreenedOn(),
|
||||||
log.getCreatedBy().orElse(null)
|
log.getCreatedBy().orElse(null),
|
||||||
|
log.getDisposition(),
|
||||||
|
log.getDispositionReason(),
|
||||||
|
log.getReviewedBy(),
|
||||||
|
log.getReviewedOn(),
|
||||||
|
log.getApprovedBy(),
|
||||||
|
log.getApprovedOn(),
|
||||||
|
log.getFiuStrReference(),
|
||||||
|
log.getNodalOfficerInformedOn(),
|
||||||
|
log.getFrozenAccountIds(),
|
||||||
|
log.getFrozenOn(),
|
||||||
|
log.getStrStatus(),
|
||||||
|
log.getStrDueDate() != null ? log.getStrDueDate().toString() : null,
|
||||||
|
log.getStrRaisedOn() != null ? log.getStrRaisedOn().toString() : null
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +138,22 @@ public final class SanctionsScreeningLogData {
|
|||||||
public String getMatchedNames() { return matchedNames; }
|
public String getMatchedNames() { return matchedNames; }
|
||||||
public String getScreeningSource() { return screeningSource; }
|
public String getScreeningSource() { return screeningSource; }
|
||||||
public Long getClientId() { return clientId; }
|
public Long getClientId() { return clientId; }
|
||||||
|
public String getClientName() { return clientName; }
|
||||||
|
public String getClientAccountNo() { return clientAccountNo; }
|
||||||
public String getIpAddress() { return ipAddress; }
|
public String getIpAddress() { return ipAddress; }
|
||||||
public OffsetDateTime getScreenedOn() { return screenedOn; }
|
public OffsetDateTime getScreenedOn() { return screenedOn; }
|
||||||
public Long getScreenedBy() { return screenedBy; }
|
public Long getScreenedBy() { return screenedBy; }
|
||||||
|
public String getDisposition() { return disposition; }
|
||||||
|
public String getDispositionReason() { return dispositionReason; }
|
||||||
|
public Long getReviewedBy() { return reviewedBy; }
|
||||||
|
public OffsetDateTime getReviewedOn() { return reviewedOn; }
|
||||||
|
public Long getApprovedBy() { return approvedBy; }
|
||||||
|
public OffsetDateTime getApprovedOn() { return approvedOn; }
|
||||||
|
public String getFiuStrReference() { return fiuStrReference; }
|
||||||
|
public OffsetDateTime getNodalOfficerInformedOn() { return nodalOfficerInformedOn; }
|
||||||
|
public String getFrozenAccountIds() { return frozenAccountIds; }
|
||||||
|
public OffsetDateTime getFrozenOn() { return frozenOn; }
|
||||||
|
public String getStrStatus() { return strStatus; }
|
||||||
|
public String getStrDueDate() { return strDueDate; }
|
||||||
|
public String getStrRaisedOn() { return strRaisedOn; }
|
||||||
}
|
}
|
||||||
|
|||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.sanctions.service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
|
||||||
|
import org.apache.fineract.portfolio.savings.domain.SavingsAccountRepository;
|
||||||
|
import org.apache.fineract.portfolio.savings.domain.SavingsAccountStatusType;
|
||||||
|
import org.apache.fineract.portfolio.savings.domain.SavingsAccountSubStatusEnum;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Freezes and releases a client's deposit accounts when a UNSC sanctions match is confirmed.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Under Section 51-A UAPA 1967 a confirmed match means funds may not move OUT — the account is
|
||||||
|
* not closed and incoming credits are not refused, so this applies a debit block rather than a
|
||||||
|
* full account block. Freezing is only reachable for a client that already exists; a match at
|
||||||
|
* onboarding has no account to freeze and is handled by refusing to create the client at all.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SanctionsFreezeService {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(SanctionsFreezeService.class);
|
||||||
|
|
||||||
|
private final SavingsAccountRepository savingsAccountRepository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks debits on every active savings account of the client.
|
||||||
|
*
|
||||||
|
* @return comma-separated ids of the accounts actually frozen (empty string when the client
|
||||||
|
* has no active account — a legitimate outcome, not an error)
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String freezeClientAccounts(final Long clientId, final Long alertId) {
|
||||||
|
if (clientId == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final List<SavingsAccount> accounts = savingsAccountRepository.findSavingAccountByClientId(clientId);
|
||||||
|
final List<String> frozen = new ArrayList<>();
|
||||||
|
|
||||||
|
for (final SavingsAccount account : accounts) {
|
||||||
|
// blockDebits() rejects anything not ACTIVE and anything already fully blocked. Filter
|
||||||
|
// here rather than catching, so a closed or already-frozen account is a skip, not noise.
|
||||||
|
if (!SavingsAccountStatusType.ACTIVE.hasStateOf(account.getStatus())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final SavingsAccountSubStatusEnum subStatus = SavingsAccountSubStatusEnum.fromInt(account.getSubStatus());
|
||||||
|
if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(subStatus)
|
||||||
|
|| SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(subStatus)) {
|
||||||
|
frozen.add(String.valueOf(account.getId()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
account.blockDebits(account.getSubStatus());
|
||||||
|
savingsAccountRepository.save(account);
|
||||||
|
frozen.add(String.valueOf(account.getId()));
|
||||||
|
LOG.warn("Sanctions alert {}: debits blocked on savings account {} of client {}", alertId, account.getId(),
|
||||||
|
clientId);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// One un-freezable account must not abort the freeze of the others.
|
||||||
|
LOG.error("Sanctions alert {}: could not block debits on savings account {}: {}", alertId, account.getId(),
|
||||||
|
e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return frozen.stream().collect(Collectors.joining(","));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the debit block. Only ever called on de-listing or revocation of the order, and
|
||||||
|
* only from the Principal Officer approval path.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void unfreezeClientAccounts(final Long clientId) {
|
||||||
|
if (clientId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (final SavingsAccount account : savingsAccountRepository.findSavingAccountByClientId(clientId)) {
|
||||||
|
final SavingsAccountSubStatusEnum subStatus = SavingsAccountSubStatusEnum.fromInt(account.getSubStatus());
|
||||||
|
if (!(SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(subStatus)
|
||||||
|
|| SavingsAccountSubStatusEnum.BLOCK.hasStateOf(subStatus))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
account.unblockDebits();
|
||||||
|
savingsAccountRepository.save(account);
|
||||||
|
LOG.info("Debits released on savings account {} of client {}", account.getId(), clientId);
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOG.error("Could not release debits on savings account {}: {}", account.getId(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -59,4 +59,77 @@ public interface SanctionsScreeningService {
|
|||||||
* Search screening logs by screened name.
|
* Search screening logs by screened name.
|
||||||
*/
|
*/
|
||||||
List<SanctionsScreeningLog> searchScreeningLogs(String name);
|
List<SanctionsScreeningLog> searchScreeningLogs(String name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alerts awaiting or carrying a disposition. Pass null for every alert regardless of state.
|
||||||
|
*/
|
||||||
|
List<SanctionsScreeningLog> getAlerts(String disposition);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the reviewing officer's assessment of a flagged screening.
|
||||||
|
*
|
||||||
|
* @param logId the flagged screening log id
|
||||||
|
* @param disposition FALSE_POSITIVE or CONFIRMED_MATCH
|
||||||
|
* @param reason mandatory narrative of the identifier comparison
|
||||||
|
*/
|
||||||
|
SanctionsScreeningLog recordDisposition(Long logId, String disposition, String reason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Principal Officer sign-off. Approving a FALSE_POSITIVE is what actually unblocks
|
||||||
|
* onboarding; approving a CONFIRMED_MATCH triggers the freeze of the client's accounts.
|
||||||
|
*/
|
||||||
|
SanctionsScreeningLog approveDisposition(Long logId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the FIU-IND STR reference and the date the nodal officer was informed, closing
|
||||||
|
* out the 24-hour reporting obligation on a confirmed match.
|
||||||
|
*/
|
||||||
|
SanctionsScreeningLog recordReporting(Long logId, String strReference, String nodalOfficerInformedOn);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when this exact name carries a false positive that the Principal Officer approved —
|
||||||
|
* the only condition under which a matched name may be onboarded.
|
||||||
|
*/
|
||||||
|
boolean hasApprovedFalsePositive(String name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Match check that does NOT write an activity log entry.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* Used by the server-side onboarding gate, which runs on every save attempt: logging there
|
||||||
|
* would stack a fresh alert onto the queue each time the officer retries a blocked client,
|
||||||
|
* burying the one real case under duplicates. The screening that belongs in the log is the
|
||||||
|
* one the officer deliberately ran from the UI.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
boolean isNameSanctioned(String name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-screens every existing client against the currently loaded list snapshot, opening an
|
||||||
|
* alert for each hit. This is what makes freezing reachable at all: without it a customer
|
||||||
|
* added to the list after onboarding is never detected.
|
||||||
|
*
|
||||||
|
* @return number of clients that produced a new flagged alert
|
||||||
|
*/
|
||||||
|
int rescreenExistingClients();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display name and account number for the given client ids, keyed by id. Resolved in one
|
||||||
|
* query so a queue of alerts does not issue a round trip per row.
|
||||||
|
*/
|
||||||
|
java.util.Map<Long, String[]> resolveClientNames(java.util.Collection<Long> clientIds);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposition of the client's most recent flagged alert (PENDING_REVIEW / FALSE_POSITIVE /
|
||||||
|
* CONFIRMED_MATCH), or null when they carry none. Drives the badge on the client's own page.
|
||||||
|
*/
|
||||||
|
String getLatestAlertStatus(Long clientId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirmed matches carrying an STR obligation — the sanctions stream shown on the FIU-IND
|
||||||
|
* screen, deliberately separate from transaction-driven AML alerts.
|
||||||
|
*
|
||||||
|
* @param status PENDING_FILING or FILED; null for all
|
||||||
|
*/
|
||||||
|
List<SanctionsScreeningLog> getStrCases(String status);
|
||||||
}
|
}
|
||||||
|
|||||||
+295
@@ -18,10 +18,19 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.portfolio.sanctions.service;
|
package org.apache.fineract.portfolio.sanctions.service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
import java.time.OffsetDateTime;
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
|
||||||
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.portfolio.sanctions.data.SanctionsMatchData;
|
import org.apache.fineract.portfolio.sanctions.data.SanctionsMatchData;
|
||||||
import org.apache.fineract.portfolio.sanctions.data.SanctionsScreeningResult;
|
import org.apache.fineract.portfolio.sanctions.data.SanctionsScreeningResult;
|
||||||
import org.apache.fineract.portfolio.sanctions.domain.SanctionsAlias;
|
import org.apache.fineract.portfolio.sanctions.domain.SanctionsAlias;
|
||||||
@@ -31,6 +40,7 @@ import org.apache.fineract.portfolio.sanctions.domain.SanctionsScreeningLog;
|
|||||||
import org.apache.fineract.portfolio.sanctions.domain.SanctionsScreeningLogRepository;
|
import org.apache.fineract.portfolio.sanctions.domain.SanctionsScreeningLogRepository;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -42,6 +52,9 @@ public class SanctionsScreeningServiceImpl implements SanctionsScreeningService
|
|||||||
|
|
||||||
private final SanctionsEntryRepository sanctionsEntryRepository;
|
private final SanctionsEntryRepository sanctionsEntryRepository;
|
||||||
private final SanctionsScreeningLogRepository screeningLogRepository;
|
private final SanctionsScreeningLogRepository screeningLogRepository;
|
||||||
|
private final SanctionsFreezeService sanctionsFreezeService;
|
||||||
|
private final PlatformSecurityContext context;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -113,6 +126,288 @@ public class SanctionsScreeningServiceImpl implements SanctionsScreeningService
|
|||||||
return screeningLogRepository.findByScreenedNameContaining(name);
|
return screeningLogRepository.findByScreenedNameContaining(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Alert disposition ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<SanctionsScreeningLog> getAlerts(final String disposition) {
|
||||||
|
if (disposition == null || disposition.isBlank()) {
|
||||||
|
return screeningLogRepository.findAllAlerts();
|
||||||
|
}
|
||||||
|
return screeningLogRepository.findByDisposition(disposition.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public SanctionsScreeningLog recordDisposition(final Long logId, final String disposition, final String reason) {
|
||||||
|
final SanctionsScreeningLog log = findAlertOrThrow(logId);
|
||||||
|
|
||||||
|
final String normalised = disposition == null ? "" : disposition.trim().toUpperCase();
|
||||||
|
if (!SanctionsScreeningLog.DISPOSITION_FALSE_POSITIVE.equals(normalised)
|
||||||
|
&& !SanctionsScreeningLog.DISPOSITION_CONFIRMED.equals(normalised)) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.disposition.invalid",
|
||||||
|
"Disposition must be FALSE_POSITIVE or CONFIRMED_MATCH.");
|
||||||
|
}
|
||||||
|
// The written reason IS the compliance record — an unexplained "not the same person" is
|
||||||
|
// exactly what a regulator would treat as no review having happened at all.
|
||||||
|
if (reason == null || reason.trim().length() < 10) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.disposition.reason.required",
|
||||||
|
"Record which identifiers were compared and why (minimum 10 characters).");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.recordDisposition(normalised, reason.trim(), currentUserId());
|
||||||
|
screeningLogRepository.saveAndFlush(log);
|
||||||
|
LOG.warn("Sanctions alert {} for '{}' dispositioned as {}", logId, log.getScreenedName(), normalised);
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public SanctionsScreeningLog approveDisposition(final Long logId) {
|
||||||
|
final SanctionsScreeningLog log = findAlertOrThrow(logId);
|
||||||
|
|
||||||
|
if (SanctionsScreeningLog.DISPOSITION_PENDING.equals(log.getDisposition())) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.alert.not.reviewed",
|
||||||
|
"This alert has not been reviewed yet — record a disposition before approving.");
|
||||||
|
}
|
||||||
|
final Long approverId = currentUserId();
|
||||||
|
// Maker-checker: whoever assessed the hit cannot also sign it off.
|
||||||
|
if (approverId != null && approverId.equals(log.getReviewedBy())) {
|
||||||
|
// Naming the reviewer turns a dead end into an instruction: the officer can see at a
|
||||||
|
// glance that they are the maker and that somebody else has to sign it off.
|
||||||
|
final String reviewer = resolveUsername(log.getReviewedBy());
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.alert.self.approval",
|
||||||
|
"This alert was assessed by '" + reviewer + "'. A different officer with the "
|
||||||
|
+ "APPROVE_SANCTIONS permission must approve it.",
|
||||||
|
reviewer);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.approve(approverId);
|
||||||
|
|
||||||
|
// Approving a confirmed match is the moment the freeze becomes due. Onboarding matches
|
||||||
|
// have no clientId and therefore nothing to freeze — that case is blocked at creation.
|
||||||
|
if (log.isConfirmedMatch() && log.getClientId() != null) {
|
||||||
|
final String frozen = sanctionsFreezeService.freezeClientAccounts(log.getClientId(), log.getId());
|
||||||
|
log.recordFreeze(frozen);
|
||||||
|
LOG.warn("Sanctions alert {}: froze accounts [{}] for client {}", logId, frozen, log.getClientId());
|
||||||
|
}
|
||||||
|
// A confirmed match is reportable under PMLA, so approval opens the STR obligation and the
|
||||||
|
// case becomes visible on the FIU-IND screen. Kept on this row rather than pushed into the
|
||||||
|
// AML alert pipeline — that pipeline is transaction-driven and this is identity-driven.
|
||||||
|
if (log.isConfirmedMatch()) {
|
||||||
|
log.raiseStr();
|
||||||
|
}
|
||||||
|
// A cleared false positive releases any freeze the alert previously imposed.
|
||||||
|
if (log.isApprovedFalsePositive() && log.getFrozenAccountIds() != null && !log.getFrozenAccountIds().isBlank()) {
|
||||||
|
sanctionsFreezeService.unfreezeClientAccounts(log.getClientId());
|
||||||
|
log.recordFreeze("");
|
||||||
|
}
|
||||||
|
|
||||||
|
screeningLogRepository.saveAndFlush(log);
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public SanctionsScreeningLog recordReporting(final Long logId, final String strReference,
|
||||||
|
final String nodalOfficerInformedOn) {
|
||||||
|
final SanctionsScreeningLog log = findAlertOrThrow(logId);
|
||||||
|
if (!log.isConfirmedMatch()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.reporting.not.confirmed",
|
||||||
|
"Only a confirmed match is reported to FIU-IND and the nodal officer.");
|
||||||
|
}
|
||||||
|
log.recordReporting(strReference, parseDateTime(nodalOfficerInformedOn));
|
||||||
|
screeningLogRepository.saveAndFlush(log);
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean hasApprovedFalsePositive(final String name) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return screeningLogRepository.countApprovedFalsePositives(name.trim()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public boolean isNameSanctioned(final String name) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return !sanctionsEntryRepository.searchByNameOrAlias(name.trim()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public int rescreenExistingClients() {
|
||||||
|
// display_name is denormalised from the name parts and can drift out of sync with them —
|
||||||
|
// a direct DB edit, or any write path that misses it, leaves it stale. Screening the
|
||||||
|
// stale value would silently clear a client whose actual name is on the list, so the
|
||||||
|
// name parts are rebuilt here and display_name used only as the fallback.
|
||||||
|
final List<Map<String, Object>> clients = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, firstname, middlename, lastname, fullname, display_name FROM m_client "
|
||||||
|
+ "WHERE status_enum = 300");
|
||||||
|
|
||||||
|
int flagged = 0;
|
||||||
|
for (final Map<String, Object> row : clients) {
|
||||||
|
final Long clientId = ((Number) row.get("id")).longValue();
|
||||||
|
final String name = resolveScreenableName(row);
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Re-running the sweep must not stack another identical alert onto the queue. An open
|
||||||
|
// alert for this client is the same case still awaiting the same decision; repeating
|
||||||
|
// it buries the real work under copies of itself.
|
||||||
|
if (hasOpenAlert(clientId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final SanctionsScreeningResult result = screenName(name, "PERIODIC_RESCREEN", clientId, null);
|
||||||
|
if (result.isMatchFound()) {
|
||||||
|
flagged++;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOG.error("Re-screening failed for client {} ('{}'): {}", clientId, name, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LOG.info("Periodic re-screening complete: {} of {} clients flagged", flagged, clients.size());
|
||||||
|
return flagged;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Map<Long, String[]> resolveClientNames(final Collection<Long> clientIds) {
|
||||||
|
final Map<Long, String[]> byId = new HashMap<>();
|
||||||
|
if (clientIds == null || clientIds.isEmpty()) {
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
final String placeholders = clientIds.stream().map(id -> "?").collect(Collectors.joining(","));
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||||
|
"SELECT id, display_name, account_no FROM m_client WHERE id IN (" + placeholders + ")",
|
||||||
|
clientIds.toArray());
|
||||||
|
|
||||||
|
for (final Map<String, Object> row : rows) {
|
||||||
|
final Long id = ((Number) row.get("id")).longValue();
|
||||||
|
byId.put(id, new String[] { (String) row.get("display_name"), (String) row.get("account_no") });
|
||||||
|
}
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public String getLatestAlertStatus(final Long clientId) {
|
||||||
|
if (clientId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// findFlaggedByClientId already orders newest first.
|
||||||
|
return screeningLogRepository.findFlaggedByClientId(clientId).stream().map(SanctionsScreeningLog::getDisposition)
|
||||||
|
.filter(java.util.Objects::nonNull).findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<SanctionsScreeningLog> getStrCases(final String status) {
|
||||||
|
final String normalised = status == null || status.isBlank() ? null : status.trim().toUpperCase();
|
||||||
|
return screeningLogRepository.findStrCases(normalised);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Username for a user id, falling back to the id when it cannot be resolved. */
|
||||||
|
private String resolveUsername(final Long userId) {
|
||||||
|
if (userId == null) {
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final List<Map<String, Object>> rows = jdbcTemplate
|
||||||
|
.queryForList("SELECT username FROM m_appuser WHERE id = ?", userId);
|
||||||
|
return rows.isEmpty() ? ("user " + userId) : (String) rows.get(0).get("username");
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "user " + userId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the client already has a flagged alert nobody has dispositioned yet. */
|
||||||
|
private boolean hasOpenAlert(final Long clientId) {
|
||||||
|
return screeningLogRepository.findFlaggedByClientId(clientId).stream().anyMatch(log -> {
|
||||||
|
// Unassessed — still the same case awaiting the same decision.
|
||||||
|
if (SanctionsScreeningLog.DISPOSITION_PENDING.equals(log.getDisposition())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Assessed but not yet signed off, or a standing confirmed match. Checking only for
|
||||||
|
// PENDING_REVIEW left a hole: the moment an officer recorded an assessment the guard
|
||||||
|
// stopped seeing the alert, so every later sweep raised a fresh duplicate of a case
|
||||||
|
// that was already being worked — or already confirmed and frozen.
|
||||||
|
if (log.getApprovedBy() == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return log.isConfirmedMatch();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name to screen for a client row, built from the authoritative name columns.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* An entity carries {@code fullname}; a person carries first/middle/last. Both are the source
|
||||||
|
* of truth, whereas {@code display_name} is a derived copy that can lag behind them. Falling
|
||||||
|
* back to it only when no name part exists keeps legacy rows screenable without trusting a
|
||||||
|
* value that may be stale.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
private String resolveScreenableName(final Map<String, Object> row) {
|
||||||
|
final String fullname = trimToNull((String) row.get("fullname"));
|
||||||
|
if (fullname != null) {
|
||||||
|
return fullname;
|
||||||
|
}
|
||||||
|
final String joined = Stream.of("firstname", "middlename", "lastname").map(col -> trimToNull((String) row.get(col)))
|
||||||
|
.filter(part -> part != null).collect(Collectors.joining(" "));
|
||||||
|
if (!joined.isBlank()) {
|
||||||
|
return joined;
|
||||||
|
}
|
||||||
|
return trimToNull((String) row.get("display_name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String trimToNull(final String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final String trimmed = value.trim();
|
||||||
|
return trimmed.isEmpty() ? null : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SanctionsScreeningLog findAlertOrThrow(final Long logId) {
|
||||||
|
final SanctionsScreeningLog log = screeningLogRepository.findById(logId)
|
||||||
|
.orElseThrow(() -> new GeneralPlatformDomainRuleException("error.msg.sanctions.alert.not.found",
|
||||||
|
"Sanctions alert " + logId + " does not exist."));
|
||||||
|
if (!log.isFlagged()) {
|
||||||
|
throw new GeneralPlatformDomainRuleException("error.msg.sanctions.alert.not.flagged",
|
||||||
|
"Screening " + logId + " produced no match, so there is nothing to disposition.");
|
||||||
|
}
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long currentUserId() {
|
||||||
|
try {
|
||||||
|
return context.authenticatedUser().getId();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Re-screening runs from a scheduler with no authenticated user.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private OffsetDateTime parseDateTime(final String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return LocalDate.parse(value.trim()).atStartOfDay().atOffset(ZoneOffset.UTC);
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
LOG.debug("Could not parse nodal officer date: {}", value);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Long saveLog(final String screenedName, final String result, final int matchCount,
|
private Long saveLog(final String screenedName, final String result, final int matchCount,
|
||||||
final String matchedEntryIds, final String matchedNames, final String source,
|
final String matchedEntryIds, final String matchedNames, final String source,
|
||||||
final Long clientId, final String ipAddress) {
|
final Long clientId, final String ipAddress) {
|
||||||
|
|||||||
+9
@@ -93,6 +93,15 @@ public class SanctionsXmlLoaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Replace the previous list rather than adding to it. A consolidated-list XML is a full
|
||||||
|
// snapshot, so appending would both duplicate every entry that is still listed and leave
|
||||||
|
// de-listed individuals active forever — screening has to reflect the current list only.
|
||||||
|
// Done after parsing has fully succeeded, so a malformed file cannot leave the table empty.
|
||||||
|
final long removed = sanctionsEntryRepository.countByActiveTrue();
|
||||||
|
sanctionsEntryRepository.deleteAllByActiveTrue();
|
||||||
|
sanctionsEntryRepository.flush();
|
||||||
|
LOG.info("Removed {} previously loaded sanctions entries before loading the new snapshot", removed);
|
||||||
|
|
||||||
// Save in batches
|
// Save in batches
|
||||||
final int batchSize = 100;
|
final int batchSize = 100;
|
||||||
for (int i = 0; i < allEntries.size(); i += batchSize) {
|
for (int i = 0; i < allEntries.size(); i += batchSize) {
|
||||||
|
|||||||
+69
@@ -18,6 +18,11 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.fineract.portfolio.savings.api;
|
package org.apache.fineract.portfolio.savings.api;
|
||||||
|
|
||||||
|
import static org.apache.fineract.infrastructure.documentmanagement.api.DocumentApiConstants.DOCUMENT_API_PARAM_DESCRIPTION;
|
||||||
|
import static org.apache.fineract.infrastructure.documentmanagement.api.DocumentApiConstants.DOCUMENT_API_PARAM_FILE;
|
||||||
|
import static org.apache.fineract.infrastructure.documentmanagement.api.DocumentApiConstants.DOCUMENT_API_PARAM_NAME;
|
||||||
|
import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
@@ -26,6 +31,7 @@ import jakarta.ws.rs.Consumes;
|
|||||||
import jakarta.ws.rs.DELETE;
|
import jakarta.ws.rs.DELETE;
|
||||||
import jakarta.ws.rs.DefaultValue;
|
import jakarta.ws.rs.DefaultValue;
|
||||||
import jakarta.ws.rs.GET;
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.HeaderParam;
|
||||||
import jakarta.ws.rs.POST;
|
import jakarta.ws.rs.POST;
|
||||||
import jakarta.ws.rs.PUT;
|
import jakarta.ws.rs.PUT;
|
||||||
import jakarta.ws.rs.Path;
|
import jakarta.ws.rs.Path;
|
||||||
@@ -34,9 +40,11 @@ import jakarta.ws.rs.Produces;
|
|||||||
import jakarta.ws.rs.QueryParam;
|
import jakarta.ws.rs.QueryParam;
|
||||||
import jakarta.ws.rs.core.Context;
|
import jakarta.ws.rs.core.Context;
|
||||||
import jakarta.ws.rs.core.MediaType;
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
import jakarta.ws.rs.core.Response;
|
||||||
import jakarta.ws.rs.core.UriInfo;
|
import jakarta.ws.rs.core.UriInfo;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -50,6 +58,10 @@ import org.apache.fineract.infrastructure.core.exception.UnrecognizedQueryParamE
|
|||||||
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
|
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
|
||||||
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
|
||||||
|
import org.apache.fineract.infrastructure.documentmanagement.api.DocumentApiResource;
|
||||||
|
import org.apache.fineract.infrastructure.documentmanagement.data.DocumentCreateResponse;
|
||||||
|
import org.apache.fineract.infrastructure.documentmanagement.data.DocumentData;
|
||||||
|
import org.apache.fineract.infrastructure.documentmanagement.data.DocumentDeleteResponse;
|
||||||
import org.apache.fineract.infrastructure.security.exception.NoAuthorizationException;
|
import org.apache.fineract.infrastructure.security.exception.NoAuthorizationException;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.infrastructure.security.service.SqlValidator;
|
import org.apache.fineract.infrastructure.security.service.SqlValidator;
|
||||||
@@ -63,6 +75,9 @@ import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformS
|
|||||||
import org.apache.fineract.portfolio.currentaccount.service.CurrentAccountEditWritePlatformService;
|
import org.apache.fineract.portfolio.currentaccount.service.CurrentAccountEditWritePlatformService;
|
||||||
import org.apache.fineract.portfolio.currentaccount.service.CurrentAccountWritePlatformService;
|
import org.apache.fineract.portfolio.currentaccount.service.CurrentAccountWritePlatformService;
|
||||||
import org.apache.fineract.portfolio.savings.service.CurrentAccountTemplateReadPlatformService;
|
import org.apache.fineract.portfolio.savings.service.CurrentAccountTemplateReadPlatformService;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@Path("/v1/currentaccounts")
|
@Path("/v1/currentaccounts")
|
||||||
@@ -84,6 +99,10 @@ public class CurrentAccountsApiResource {
|
|||||||
private final CurrentAccountEditWritePlatformService currentAccountEditWritePlatformService;
|
private final CurrentAccountEditWritePlatformService currentAccountEditWritePlatformService;
|
||||||
private final FromJsonHelper fromApiJsonHelper;
|
private final FromJsonHelper fromApiJsonHelper;
|
||||||
private final DefaultToApiJsonSerializer<CurrentAccountPendingEditData> pendingEditApiJsonSerializer;
|
private final DefaultToApiJsonSerializer<CurrentAccountPendingEditData> pendingEditApiJsonSerializer;
|
||||||
|
private final DocumentApiResource documentApiResource;
|
||||||
|
|
||||||
|
/** Matches the {@code entityType} current-account document requests are stored/looked up under. */
|
||||||
|
private static final String DOCUMENT_ENTITY_TYPE = "currentaccounts";
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("template")
|
@Path("template")
|
||||||
@@ -337,4 +356,54 @@ public class CurrentAccountsApiResource {
|
|||||||
return this.toApiJsonSerializer.serialize(result);
|
return this.toApiJsonSerializer.serialize(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Documents ────────────────────────────────────────────────────────────
|
||||||
|
// The generic /v1/{entityType}/{entityId}/documents resource (DocumentApiResource) never gets a
|
||||||
|
// chance to handle current-account requests: this class's own literal /v1/currentaccounts path
|
||||||
|
// is matched first for anything under {accountId}, and it has no "documents" method, so the
|
||||||
|
// request dead-ends in a 404 instead of falling through. These delegate straight to the same
|
||||||
|
// DocumentApiResource so current accounts get identical document-management behaviour.
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{accountId}/documents")
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "List documents attached to a current account")
|
||||||
|
@ApiResponse(responseCode = "200", description = "OK")
|
||||||
|
public List<DocumentData> retrieveDocuments(@PathParam("accountId") final Long accountId) {
|
||||||
|
return documentApiResource.retrieveAllDocuments(DOCUMENT_ENTITY_TYPE, accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{accountId}/documents/{documentId}/attachment")
|
||||||
|
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
|
||||||
|
@Operation(summary = "Download a document attached to a current account")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Not Shown: The corresponding Binary file")
|
||||||
|
public Response downloadDocument(@PathParam("accountId") final Long accountId, @PathParam("documentId") final Long documentId) {
|
||||||
|
return documentApiResource.downloadFile(DOCUMENT_ENTITY_TYPE, accountId, documentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Path("{accountId}/documents")
|
||||||
|
@Consumes({ MediaType.MULTIPART_FORM_DATA })
|
||||||
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
|
@Operation(summary = "Attach a document to a current account")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Not Shown (multi-part form data)")
|
||||||
|
public DocumentCreateResponse createDocument(@PathParam("accountId") final Long accountId,
|
||||||
|
@HeaderParam(CONTENT_LENGTH) final Long fileSize, @FormDataParam(DOCUMENT_API_PARAM_FILE) final InputStream inputStream,
|
||||||
|
@FormDataParam(DOCUMENT_API_PARAM_FILE) final FormDataContentDisposition fileDetails,
|
||||||
|
@FormDataParam(DOCUMENT_API_PARAM_FILE) final FormDataBodyPart filePart,
|
||||||
|
@FormDataParam(DOCUMENT_API_PARAM_NAME) final String name,
|
||||||
|
@FormDataParam(DOCUMENT_API_PARAM_DESCRIPTION) final String description) {
|
||||||
|
return documentApiResource.createDocument(DOCUMENT_ENTITY_TYPE, accountId, fileSize, inputStream, fileDetails, filePart, name,
|
||||||
|
description);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DELETE
|
||||||
|
@Path("{accountId}/documents/{documentId}")
|
||||||
|
@Operation(summary = "Remove a document attached to a current account")
|
||||||
|
@ApiResponse(responseCode = "200", description = "OK")
|
||||||
|
public DocumentDeleteResponse deleteDocument(@PathParam("accountId") final Long accountId,
|
||||||
|
@PathParam("documentId") final Long documentId) {
|
||||||
|
return documentApiResource.deleteDocument(DOCUMENT_ENTITY_TYPE, accountId, documentId);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-6
@@ -29,6 +29,10 @@ import jakarta.ws.rs.core.MediaType;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.commands.domain.CommandWrapper;
|
||||||
|
import org.apache.fineract.commands.service.CommandWrapperBuilder;
|
||||||
|
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
||||||
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
|
||||||
import org.apache.fineract.portfolio.savings.DepositsApiConstants;
|
import org.apache.fineract.portfolio.savings.DepositsApiConstants;
|
||||||
import org.apache.fineract.portfolio.savings.data.FdInterestRateEffectiveData;
|
import org.apache.fineract.portfolio.savings.data.FdInterestRateEffectiveData;
|
||||||
@@ -42,6 +46,7 @@ public class FixedDepositProductsBaseInterestRatesApiResource {
|
|||||||
|
|
||||||
private final PlatformSecurityContext context;
|
private final PlatformSecurityContext context;
|
||||||
private final FdBaseInterestRateReadPlatformService fdBaseInterestRateReadPlatformService;
|
private final FdBaseInterestRateReadPlatformService fdBaseInterestRateReadPlatformService;
|
||||||
|
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
|
||||||
private final Gson gson = new GsonBuilder()
|
private final Gson gson = new GsonBuilder()
|
||||||
.registerTypeAdapter(LocalDate.class,
|
.registerTypeAdapter(LocalDate.class,
|
||||||
(JsonSerializer<LocalDate>) (src, typeOfSrc, ctx) -> new JsonPrimitive(src.toString()))
|
(JsonSerializer<LocalDate>) (src, typeOfSrc, ctx) -> new JsonPrimitive(src.toString()))
|
||||||
@@ -77,11 +82,11 @@ public class FixedDepositProductsBaseInterestRatesApiResource {
|
|||||||
@Produces({ MediaType.APPLICATION_JSON })
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
@Operation(summary = "Save new FD base interest rate version", description = "Creates a new FD CBS base chart version for the given fdType and deactivates the previous active version.")
|
@Operation(summary = "Save new FD base interest rate version", description = "Creates a new FD CBS base chart version for the given fdType and deactivates the previous active version.")
|
||||||
@ApiResponses({ @ApiResponse(responseCode = "200", description = "OK") })
|
@ApiResponses({ @ApiResponse(responseCode = "200", description = "OK") })
|
||||||
public String saveInterestRates(@Parameter(hidden = true) final String apiRequestBodyAsJson) {
|
public CommandProcessingResult saveInterestRates(@Parameter(hidden = true) final String apiRequestBodyAsJson) {
|
||||||
this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_PRODUCT_RESOURCE_NAME);
|
final CommandWrapper commandRequest = new CommandWrapperBuilder()
|
||||||
final FdInterestRateSaveRequest request = gson.fromJson(apiRequestBodyAsJson, FdInterestRateSaveRequest.class);
|
.createCbsBaseInterestRate()
|
||||||
final Long createdById = this.context.authenticatedUser().getId();
|
.withJson(apiRequestBodyAsJson)
|
||||||
final FdInterestRateEffectiveData saved = this.fdBaseInterestRateReadPlatformService.saveInterestRates(request, createdById);
|
.build();
|
||||||
return gson.toJson(saved);
|
return this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-1
@@ -435,7 +435,10 @@ public class FixedDepositAccount extends SavingsAccount {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Money activateWithBalance() {
|
public Money activateWithBalance() {
|
||||||
return Money.of(this.currency, this.accountTermAndPreClosure.depositAmount());
|
// Activation never deposits money -- funding happens strictly through a separate deposit
|
||||||
|
// transaction (posted by a clerk) after the account is already active, regardless of the
|
||||||
|
// deposit amount configured on the account's term/pre-closure details.
|
||||||
|
return Money.zero(this.currency);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void close(final AppUser currentUser, final JsonCommand command, final Map<String, Object> actualChanges) {
|
public void close(final AppUser currentUser, final JsonCommand command, final Map<String, Object> actualChanges) {
|
||||||
|
|||||||
+4
-1
@@ -552,7 +552,10 @@ public class RecurringDepositAccount extends SavingsAccount {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Money activateWithBalance() {
|
public Money activateWithBalance() {
|
||||||
return Money.of(this.currency, this.minRequiredOpeningBalance);
|
// Activation never deposits money -- funding happens strictly through a separate deposit
|
||||||
|
// transaction (posted by a clerk) after the account is already active, regardless of any
|
||||||
|
// minimum required opening balance the product has configured.
|
||||||
|
return Money.zero(this.currency);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void processAccountUponActivation(final DateTimeFormatter fmt, final boolean postReversals,
|
protected void processAccountUponActivation(final DateTimeFormatter fmt, final boolean postReversals,
|
||||||
|
|||||||
+4
-13
@@ -19,7 +19,6 @@
|
|||||||
package org.apache.fineract.portfolio.savings.domain;
|
package org.apache.fineract.portfolio.savings.domain;
|
||||||
|
|
||||||
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME;
|
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME;
|
||||||
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.accountFacilityConfigParamName;
|
|
||||||
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.accountNoParamName;
|
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.accountNoParamName;
|
||||||
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.accountStatusParamName;
|
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.accountStatusParamName;
|
||||||
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.guardianClientIdParamName;
|
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.guardianClientIdParamName;
|
||||||
@@ -455,18 +454,10 @@ public class SavingsAccountAssembler {
|
|||||||
account.setLinkedAccountType(this.fromApiJsonHelper.extractStringNamed(linkedAccountTypeParamName, element));
|
account.setLinkedAccountType(this.fromApiJsonHelper.extractStringNamed(linkedAccountTypeParamName, element));
|
||||||
account.setLinkedAccountNo(this.fromApiJsonHelper.extractStringNamed(linkedAccountNoParamName, element));
|
account.setLinkedAccountNo(this.fromApiJsonHelper.extractStringNamed(linkedAccountNoParamName, element));
|
||||||
|
|
||||||
// Account Facility Config
|
// Every digital facility starts disabled at account opening, regardless of anything the
|
||||||
if (element.getAsJsonObject().has(accountFacilityConfigParamName)) {
|
// request sends or the product defaults to -- they're switched on deliberately, one at a
|
||||||
final JsonElement configEl = element.getAsJsonObject().get(accountFacilityConfigParamName);
|
// time, later, through the account's own Edit Nominee & Features screen.
|
||||||
if (configEl != null && !configEl.isJsonNull() && configEl.isJsonObject()) {
|
account.setFacilityConfig(new SavingsAccountFacilityConfig(account));
|
||||||
SavingsAccountFacilityConfig facilityConfig = account.getFacilityConfig();
|
|
||||||
if (facilityConfig == null) {
|
|
||||||
facilityConfig = new SavingsAccountFacilityConfig(account);
|
|
||||||
account.setFacilityConfig(facilityConfig);
|
|
||||||
}
|
|
||||||
facilityConfig.updateFrom(configEl.getAsJsonObject());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Joint holders
|
// Joint holders
|
||||||
if (element.getAsJsonObject().has(jointHoldersParamName)) {
|
if (element.getAsJsonObject().has(jointHoldersParamName)) {
|
||||||
|
|||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
* or more contributor license agreements. See the NOTICE file
|
||||||
|
* distributed with this work for additional information
|
||||||
|
* regarding copyright ownership. The ASF licenses this file
|
||||||
|
* to you under the Apache License, Version 2.0 (the
|
||||||
|
* "License"); you may not use this file except in compliance
|
||||||
|
* with the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
package org.apache.fineract.portfolio.savings.handler;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.fineract.commands.annotation.CommandType;
|
||||||
|
import org.apache.fineract.commands.handler.NewCommandSourceHandler;
|
||||||
|
import org.apache.fineract.infrastructure.core.api.JsonCommand;
|
||||||
|
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
|
||||||
|
import org.apache.fineract.portfolio.savings.service.FdBaseInterestRateWritePlatformService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@CommandType(entity = "CBSBASEINTERESTRATE", action = "CREATE")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CreateCbsBaseInterestRateCommandHandler implements NewCommandSourceHandler {
|
||||||
|
|
||||||
|
private final FdBaseInterestRateWritePlatformService writePlatformService;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
@Override
|
||||||
|
public CommandProcessingResult processCommand(final JsonCommand command) {
|
||||||
|
return this.writePlatformService.saveInterestRates(command);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user