Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/WEB-1493-cash-register-closing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# WEB-1493 opening validation for cash register closing

The old closing context mapped the absence of a reconciliation to `OPEN`. The closing command consequently allowed a never-opened drawer to be reconciled, including with zero cash.

Closing now requires a completed opening/provisioning allocation, with a matching native allocation transaction, in the current tenant database for the selected destination cashier, office, business date and currency. Both supported cashier allocation types qualify. The check does not depend on the allocation amount or remaining balance; the opening workflow itself permits positive allocations, and a subsequently exhausted drawer remains eligible. There is no carry-forward opening or supported allocation reversal API. Non-completed records cannot authorize closing.

The context adds a closing-specific `registerStatus` (`NOT_OPENED`, `OPEN`, `COMPLETED`) and nullable `closingId`. Shared `CashManagementStatus` values and existing endpoint/request contracts remain compatible. `status` alone is not opening eligibility. The matching web-app branch fails closed when this new evidence is missing.

Opening and closing use the custody mutex before cashier locks. Closing selects the opening/native records under shared row locks, rereads the cashier after locking, and checks opening eligibility again at the common posting boundary before reconciliation, settlement or accounting commands. End-of-Day Closing retains its register-wide semantics for all tenant currencies, including unused currencies, while still requiring a completed register opening. The existing separate-authorizer, permission, office hierarchy and fingerprint checks remain in place. Closing explicitly uses transaction-local read committed isolation so a waiter sees a completed matching replay after taking the lock; matching authorized historical replay remains available.

Unopened commands throw the structured domain rule `error.msg.base.teller.closing.not.opened`; no migration is needed. A second distinct closing is rejected. A matching idempotent request returns the existing authorized receipt.

The context's transaction-group callback also previously skipped its first row. It now uses `RowCallbackHandler` correctly, so allocations are included in expected balances. Regressions assert a funded expected balance and an opened drawer with zero remaining cash.

## Validation

On 26 November 2026, `./mvnw verify -Dit.test=CashManagementPlatformServiceIntegrationTest,EndOfDayClosingPlatformServiceIntegrationTest,CashAllocationLiquibaseIntegrationTest` passed 970 unit tests, 39 PostgreSQL integration tests and the coverage gates, and built the plugin JAR. Changed-file Spotless validation passed. Full Spotless reports unrelated upstream formatting violations, reproduced against unmodified upstream `7f31cd2`.

Integration tests exercise actual PostgreSQL transactions, row locks, migrations and uniqueness constraints. Native Fineract commands are mocked at the boundary and write settlement rows into the same database transaction. Cases include never-opened/zero-cash closing, zero remaining balance after opening, wrong scope/date/currency/cashier/office, incomplete/cancelled/reversed openings, missing native linkage, permissions, self-authorization, duplicate commands, two concurrent distinct commands, concurrent identical replay from a repeatable-read caller, historical replay and EOD rollback with no financial writes.

Reviewed the original [Savings Plugin #107](https://github.com/openMF/savings-plugin/pull/107) and [web-app #4050](https://github.com/openMF/web-app/pull/4050), including historical review feedback. The backend thread has no actionable review; frontend idempotency, stale-context and translation safeguards are addressed in the companion.

Deploy this plugin before [the companion frontend](https://github.com/openMF/web-app/compare/dev...AnvayKharb:fix/WEB-1493-cash-register-closing-validation?expand=1). Screenshots and frontend validation details are in its `docs/WEB-1493-cash-register-closing.md`. A safe live Fineract opening/closing/manual accounting exercise remains required; there was no running local Fineract service. This is implementation and automated regression evidence, not a claim of production deployment or ticket resolution.

## Full integration-suite follow-up

The first full CI run exposed shared-fixture failures beyond the focused closing suites. The reversal HTTP fixture had used a teller command's `resourceId` as its cashier ID, which could address another suite's drawer when the IDs differed. It now resolves the actual assignment by its newly created staff and teller and owns a separate office. It performs a real vault/head-cashier opening and then a real bank deposit to exhaust that opening, preserving the existing reversal tests' zero starting custody while satisfying opening validation. The financial activity setup uses an equity account for the native opening-balance contra requirement. No financial rows are fabricated to establish eligibility.

The native savings-policy test also asserted an obsolete dependency version. Failsafe now supplies the exact Maven `fineract.version`; the test requires the corresponding provider filename and classifier and still verifies the deployed provider and plugin hashes. Version and accounting assertions remain enforced.

Focused rechecks passed all 11 reversal HTTP tests and the native savings-policy HTTP test. The unfiltered Maven integration suite and the [PR checks](https://github.com/openMF/savings-plugin/pull/154/checks) provide the full-suite verification. No test exclusions, disabled tests, ignored failures or reduced coverage thresholds were introduced.
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,7 @@
</includes>
<systemPropertyVariables>
<spring.profiles.active>integration-test</spring.profiles.active>
<fineract.test.runtime.version>${fineract.version}</fineract.test.runtime.version>
</systemPropertyVariables>
</configuration>
<executions>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ public record CashierClosingContextData(
BigDecimal previousSettlements,
BigDecimal expectedAmount,
List<CashierCheckData> eligibleChecks,
CashManagementStatus status) {}
CashManagementStatus status,
CashierClosingStatus registerStatus,
Long closingId) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.apache.fineract.baseteller.data;

/** Closing eligibility only; shared cash-operation statuses retain their existing contract. */
public enum CashierClosingStatus {
NOT_OPENED,
OPEN,
COMPLETED
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ public CashAllocationReceiptData allocate(final CashAllocationRequest request) {
return receipt(existing.id(), user);
}

// Use the same lock order as closing and EOD so opening cannot race reconciliation.
jdbcTemplate.queryForObject(
"SELECT id FROM m_cash_exchange_mutex WHERE id=1 FOR UPDATE", Long.class);
final PreparedAllocation prepared = prepare(request, user, true, true);
existing = existing(request.idempotencyKey());
if (existing != null) {
Expand Down Expand Up @@ -145,18 +148,30 @@ public CashAllocationReceiptData allocate(final CashAllocationRequest request) {
} else if (request.operationType() == CashAllocationType.HEAD_CASHIER_ALLOCATION) {
final CommandProcessingResult allocation =
allocateToCashier(
prepared.destination(), prepared.total(), prepared.currency(), prepared.date(), reference,
prepared.destination(),
prepared.total(),
prepared.currency(),
prepared.date(),
reference,
request.idempotencyKey() + ":destination");
destinationTransactionId = requiredCashierTransactionId(allocation);
} else {
final CommandProcessingResult settlement =
settleFromCashier(
prepared.source(), prepared.total(), prepared.currency(), prepared.date(), reference,
prepared.source(),
prepared.total(),
prepared.currency(),
prepared.date(),
reference,
request.idempotencyKey() + ":source");
sourceTransactionId = requiredCashierTransactionId(settlement);
final CommandProcessingResult allocation =
allocateToCashier(
prepared.destination(), prepared.total(), prepared.currency(), prepared.date(), reference,
prepared.destination(),
prepared.total(),
prepared.currency(),
prepared.date(),
reference,
request.idempotencyKey() + ":destination");
destinationTransactionId = requiredCashierTransactionId(allocation);
}
Expand Down Expand Up @@ -212,29 +227,36 @@ private PreparedAllocation prepare(
source = cashier(request.sourceCashierId(), office.id(), request.businessDate(), lock);
}
if (request.destinationCashierId() != null) {
destination = cashier(request.destinationCashierId(), office.id(), request.businessDate(), lock);
destination =
cashier(request.destinationCashierId(), office.id(), request.businessDate(), lock);
}
if (request.operationType() == CashAllocationType.OPERATIONAL_TELLER_ALLOCATION
&& !isFundedHeadCashier(source.id(), office.id(), request.businessDate(), currency.code())) {
&& !isFundedHeadCashier(
source.id(), office.id(), request.businessDate(), currency.code())) {
throw invalid(
"source.not.head.cashier",
"The source cashier has no completed head-cashier opening allocation for this business date and currency.");
}
if (source != null) rejectClosed(source.id(), request.businessDate(), currency.code());
if (destination != null) rejectClosed(destination.id(), request.businessDate(), currency.code());
if (destination != null)
rejectClosed(destination.id(), request.businessDate(), currency.code());

final BigDecimal vaultBefore = vaultBalance(office.id(), request.businessDate(), currency.code());
final BigDecimal vaultBefore =
vaultBalance(office.id(), request.businessDate(), currency.code());
final BigDecimal sourceBefore =
request.operationType() == CashAllocationType.HEAD_CASHIER_ALLOCATION
? vaultBefore
: source == null ? null : cashierBalance(source.id(), request.businessDate(), currency.code());
: source == null
? null
: cashierBalance(source.id(), request.businessDate(), currency.code());
final BigDecimal destinationBefore =
request.operationType() == CashAllocationType.SAFE_VAULT_OPENING
? vaultBefore
: cashierBalance(destination.id(), request.businessDate(), currency.code());
if (request.operationType() != CashAllocationType.SAFE_VAULT_OPENING
&& sourceBefore.compareTo(total) < 0) {
throw invalid("source.insufficient", "The allocation exceeds the authoritative source cash balance.");
throw invalid(
"source.insufficient", "The allocation exceeds the authoritative source cash balance.");
}
final BigDecimal sourceAfter = sourceBefore == null ? null : sourceBefore.subtract(total);
final BigDecimal destinationAfter = destinationBefore.add(total);
Expand Down Expand Up @@ -322,8 +344,7 @@ private CurrencySnapshot currency(final String code) {

private List<CashAllocationCurrencyData> currencies(final String requestedCurrency) {
final Map<String, CurrencySnapshot> configured = new LinkedHashMap<>();
String sql =
"SELECT code,decimal_places,name,display_symbol FROM m_organisation_currency";
String sql = "SELECT code,decimal_places,name,display_symbol FROM m_organisation_currency";
final List<Object> arguments = new ArrayList<>();
if (StringUtils.isNotBlank(requestedCurrency)) {
sql += " WHERE LOWER(code)=LOWER(?)";
Expand Down Expand Up @@ -400,8 +421,7 @@ private List<CashAllocationCashierData> activeCashiers(
cashier.tellerName(),
cashier.staffId(),
cashier.cashierName(),
currency != null
&& isFundedHeadCashier(cashier.id(), officeId, date, currency),
currency != null && isFundedHeadCashier(cashier.id(), officeId, date, currency),
currency == null ? ZERO : cashierBalance(cashier.id(), date, currency)))
.toList();
}
Expand Down Expand Up @@ -455,7 +475,8 @@ private BigDecimal cashierBalance(
return result == null ? ZERO : result;
}

private BigDecimal vaultBalance(final Long officeId, final LocalDate date, final String currency) {
private BigDecimal vaultBalance(
final Long officeId, final LocalDate date, final String currency) {
final BigDecimal result =
jdbcTemplate.queryForObject(
"SELECT COALESCE(SUM(CASE WHEN operation_type='SAFE_VAULT_OPENING' THEN amount"
Expand Down
Loading
Loading