Treasury & Bank Transfer Management System — سامانه مدیریت خزانهداری و حوالههای بانکی
feat: add isolated bank reconciliation safety guard with 16 tests
davoodmehraban89 committed
Oct 13, 2026 at 13:21 UTC
e53471e72b5ed6a0bccecf5eec4b05337b77c8ca
5 files changed
+285
modules/reconciliation-guard/README.md
new
+29
@@ -0,0 +1,29 @@
1
+# TreasuryFlow reconciliation guard (isolated module)
2
+
3
+**Status:** Standalone tested development module, NOT merged into the operating TreasuryFlow application.
4
+
5
+Use this when a transfer attempt has already been recorded but bank outcome is uncertain. This package neither sends money nor connects to a bank or modifies a database.
6
+
7
+Guarantees:
8
+- UNKNOWN is never eligible for automatic retransmission.
9
+- Bank acceptance is not final settlement.
10
+- A definitive bank rejection must be distinguished from network errors.
11
+- Evidence must match payment ID, amount as *string minor units*, and currency.
12
+- Each bank evidence ID is idempotent; inconsistent replays and terminal conflicts fail closed.
13
+- No automatic conversion between Iranian rials and tomans.
14
+
15
+Tests: Node >=20, run `npm test` and `npm run check` in this folder (16 tests).
16
+
17
+Important integration requirements:
18
+1. Run only server-side. `verifiedBy` is asserted by a trusted banking adapter, not cryptographic verification by this module; NEVER accept it from client payload.
19
+2. Save returned snapshot atomically using the current row version (compare-and-swap/SQLite transactional write).
20
+3. Deduplicate external bank references across transfers at persistence level.
21
+4. Inspect existing `TreasuryService.dispatchPayment` and adapt actual types before integrating.
22
+5. Status flags from legacy Mayan do not alone establish confirmed settlement.
23
+6. Require explicit authorized/manual workflow before retrying payment; this module provides no such permission.
24
+7. Test against official bank sandbox and approved contract before enabling any real transfer.
25
+
26
+The actual project source was previously reported at:
27
+`C:\TreasuryFlow-P1\.worktrees\batch-payment-import-v1.0.1`
28
+
29
+The GitHub TreasuryFlow repository main branch currently contains only README.md, therefore this isolated module is deliberately kept in a feature branch and is NOT an application release.
modules/reconciliation-guard/package.json
new
+18
@@ -0,0 +1,18 @@
1
+{
2
+ "name": "treasuryflow-reconciliation-guard",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Offline, side-effect-free bank payment reconciliation guard for TreasuryFlow",
6
+ "type": "module",
7
+ "engines": { "node": ">=20" },
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/reconciliation.d.mts",
11
+ "default": "./src/reconciliation.mjs"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "test": "node --test test/*.test.mjs",
16
+ "check": "node --check src/reconciliation.mjs"
17
+ }
18
+}
modules/reconciliation-guard/src/reconciliation.d.mts
new
+32
@@ -0,0 +1,32 @@
1
+export type PaymentStatus = 'READY' | 'DISPATCHING' | 'UNKNOWN' | 'BANK_ACCEPTED' | 'SETTLED' | 'BANK_REJECTED';
2
+export type EvidenceKind = 'ACCEPTED' | 'SETTLED' | 'REJECTED';
3
+export type AppliedProof = { evidenceId: string; digest: string };
4
+export interface PaymentSnapshot {
5
+ id: string;
6
+ status: PaymentStatus;
7
+ amountMinor: string;
8
+ currency: string;
9
+ version: number;
10
+ bankReference?: string | null;
11
+ appliedProofs: readonly AppliedProof[];
12
+}
13
+/** Only the trusted server-side bank adapter may fill verifiedBy after verifying the external response. */
14
+export interface VerifiedBankEvidence {
15
+ evidenceId: string;
16
+ kind: EvidenceKind;
17
+ paymentId: string;
18
+ amountMinor: string;
19
+ currency: string;
20
+ bankReference?: string;
21
+ verifiedBy: string;
22
+ observedAt: string;
23
+ definitive?: boolean;
24
+}
25
+export class ReconciliationError extends Error { constructor(code: string, message: string); code: string; }
26
+export function applyVerifiedBankEvidence(payment: PaymentSnapshot, proof: VerifiedBankEvidence): {
27
+ payment: PaymentSnapshot;
28
+ changed: boolean;
29
+ reason: 'DUPLICATE_EVIDENCE' | 'APPLIED';
30
+};
31
+export function mayAutomaticallyDispatch(status: PaymentStatus): boolean;
32
+export function hasFinalBankOutcome(status: PaymentStatus): boolean;
modules/reconciliation-guard/src/reconciliation.mjs
new
+104
@@ -0,0 +1,104 @@
1
+/**
2
+ * Pure, offline TreasuryFlow bank-reconciliation transition guard.
3
+ * It DOES NOT send transfers, call a bank, authenticate evidence or write to a DB.
4
+ * Only a server-side trusted adapter may produce evidence with verifiedBy.
5
+ */
6
+import { createHash } from 'node:crypto';
7
+
8
+export class ReconciliationError extends Error {
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.name = 'ReconciliationError';
12
+ this.code = code;
13
+ }
14
+}
15
+
16
+const assert = (condition, code, message) => {
17
+ if (!condition) throw new ReconciliationError(code, message);
18
+};
19
+const validText = (value) => typeof value === 'string' && value.length > 0 && value.trim() === value;
20
+const validMoney = (value) => typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value);
21
+const validCurrency = (value) => typeof value === 'string' && /^[A-Z]{3}$/.test(value);
22
+const allowedStatuses = new Set(['READY', 'DISPATCHING', 'UNKNOWN', 'BANK_ACCEPTED', 'SETTLED', 'BANK_REJECTED']);
23
+const allowedKinds = new Set(['ACCEPTED', 'SETTLED', 'REJECTED']);
24
+
25
+const stableDigest = (proof) => createHash('sha256').update(JSON.stringify([
26
+ proof.evidenceId, proof.kind, proof.paymentId, proof.amountMinor,
27
+ proof.currency, proof.bankReference, proof.verifiedBy, proof.observedAt,
28
+ proof.definitive === true,
29
+])).digest('hex');
30
+
31
+/**
32
+ * Uses a verified response from a trusted server-side banking adapter to move
33
+ * an already-dispatched payment toward a terminal state.
34
+ * The caller must commit the result with an atomic version check.
35
+ */
36
+export function applyVerifiedBankEvidence(payment, proof) {
37
+ assert(payment && typeof payment === 'object', 'INVALID_PAYMENT', 'Payment snapshot missing');
38
+ assert(validText(payment.id), 'INVALID_PAYMENT', 'Payment ID missing');
39
+ assert(allowedStatuses.has(payment.status), 'INVALID_PAYMENT', 'Payment status unknown');
40
+ assert(validMoney(payment.amountMinor), 'INVALID_PAYMENT', 'Payment amount must be decimal minor units');
41
+ assert(validCurrency(payment.currency), 'INVALID_PAYMENT', 'Payment currency must be ISO-like uppercase code');
42
+ assert(Number.isSafeInteger(payment.version) && payment.version >= 0, 'INVALID_PAYMENT', 'Version missing');
43
+ assert(Array.isArray(payment.appliedProofs), 'INVALID_PAYMENT', 'Applied proofs missing');
44
+ assert(proof && typeof proof === 'object', 'INVALID_PROOF', 'Bank evidence missing');
45
+ assert(validText(proof.evidenceId) && validText(proof.paymentId), 'INVALID_PROOF', 'Evidence ID/payment ID missing');
46
+ assert(allowedKinds.has(proof.kind), 'INVALID_PROOF', 'Evidence kind unknown');
47
+ assert(validMoney(proof.amountMinor), 'INVALID_PROOF', 'Evidence amount invalid');
48
+ assert(validCurrency(proof.currency), 'INVALID_PROOF', 'Evidence currency invalid');
49
+ assert(validText(proof.verifiedBy), 'UNVERIFIED_EVIDENCE', 'Only trusted adapters may verify bank evidence');
50
+ assert(validText(proof.observedAt) && !Number.isNaN(Date.parse(proof.observedAt)), 'INVALID_PROOF', 'Evidence timestamp invalid');
51
+ assert(payment.id === proof.paymentId, 'PAYMENT_MISMATCH', 'Evidence belongs to another payment');
52
+ assert(payment.amountMinor === proof.amountMinor, 'AMOUNT_MISMATCH', 'Evidence amount differs from payment');
53
+ assert(payment.currency === proof.currency, 'CURRENCY_MISMATCH', 'Evidence currency differs from payment');
54
+ if (proof.kind === 'SETTLED' || proof.kind === 'ACCEPTED') {
55
+ assert(validText(proof.bankReference), 'MISSING_BANK_REFERENCE', 'Bank reference required');
56
+ }
57
+ if (proof.kind === 'REJECTED') {
58
+ assert(proof.definitive === true, 'NON_DEFINITIVE_REJECTION', 'A transient bank failure is not a final rejection');
59
+ }
60
+
61
+ const digest = stableDigest(proof);
62
+ const existing = payment.appliedProofs.find((event) => event?.evidenceId === proof.evidenceId);
63
+ if (existing) {
64
+ assert(existing.digest === digest, 'EVIDENCE_ID_COLLISION', 'Evidence ID reused with changed content');
65
+ return { payment, changed: false, reason: 'DUPLICATE_EVIDENCE' };
66
+ }
67
+ assert(payment.status !== 'READY', 'NOT_DISPATCHED', 'Payment has no recorded dispatch attempt');
68
+ assert(payment.status !== 'SETTLED' && payment.status !== 'BANK_REJECTED', 'TERMINAL_CONFLICT', 'Terminal payment requires manual conflict investigation');
69
+ if (proof.kind === 'ACCEPTED' && payment.status === 'BANK_ACCEPTED' && payment.bankReference !== proof.bankReference) {
70
+ throw new ReconciliationError('BANK_REFERENCE_CONFLICT', 'Conflicting bank references require manual investigation');
71
+ }
72
+ if (payment.bankReference && proof.bankReference && payment.bankReference !== proof.bankReference) {
73
+ throw new ReconciliationError('BANK_REFERENCE_CONFLICT', 'Conflicting bank references require manual investigation');
74
+ }
75
+
76
+ const nextStatus = {
77
+ ACCEPTED: 'BANK_ACCEPTED',
78
+ SETTLED: 'SETTLED',
79
+ REJECTED: 'BANK_REJECTED',
80
+ }[proof.kind];
81
+ return {
82
+ changed: true,
83
+ reason: 'APPLIED',
84
+ payment: {
85
+ ...payment,
86
+ status: nextStatus,
87
+ version: payment.version + 1,
88
+ bankReference: proof.bankReference ?? payment.bankReference ?? null,
89
+ appliedProofs: [...payment.appliedProofs, { evidenceId: proof.evidenceId, digest }],
90
+ },
91
+ };
92
+}
93
+
94
+/** No automatic retry after a dispatch attempt, including UNKNOWN and REJECTED. */
95
+export function mayAutomaticallyDispatch(status) {
96
+ assert(allowedStatuses.has(status), 'INVALID_STATUS', 'Unknown payment status');
97
+ return status === 'READY';
98
+}
99
+
100
+/** A bank acceptance is NOT a settlement receipt. */
101
+export function hasFinalBankOutcome(status) {
102
+ assert(allowedStatuses.has(status), 'INVALID_STATUS', 'Unknown payment status');
103
+ return status === 'SETTLED' || status === 'BANK_REJECTED';
104
+}
modules/reconciliation-guard/test/reconciliation.test.mjs
new
+102
@@ -0,0 +1,102 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import {
4
+ applyVerifiedBankEvidence as apply, mayAutomaticallyDispatch,
5
+ hasFinalBankOutcome, ReconciliationError,
6
+} from '../src/reconciliation.mjs';
7
+
8
+const payment = (status = 'UNKNOWN') => ({
9
+ id: 'transfer-1', status, amountMinor: '1200000', currency: 'IRR',
10
+ version: 5, bankReference: null, appliedProofs: [],
11
+});
12
+const proof = (kind = 'SETTLED') => ({
13
+ evidenceId: 'bank-event-1', kind, paymentId: 'transfer-1',
14
+ amountMinor: '1200000', currency: 'IRR', bankReference: 'bank-ref-1',
15
+ verifiedBy: 'trusted-bank-adapter', observedAt: '2026-10-13T10:00:00Z',
16
+ definitive: kind === 'REJECTED',
17
+});
18
+function fails(fn, code) {
19
+ assert.throws(fn, (err) => err instanceof ReconciliationError && err.code === code);
20
+}
21
+
22
+test('bank acknowledgment is not final settlement', () => {
23
+ const next = apply(payment(), proof('ACCEPTED')).payment;
24
+ assert.equal(next.status, 'BANK_ACCEPTED');
25
+ assert.equal(next.version, 6);
26
+ assert.equal(hasFinalBankOutcome(next.status), false);
27
+});
28
+test('verified settlement resolves UNKNOWN without another transfer', () => {
29
+ const next = apply(payment(), proof()).payment;
30
+ assert.equal(next.status, 'SETTLED');
31
+ assert.equal(hasFinalBankOutcome(next.status), true);
32
+});
33
+test('definitive rejection resolves UNKNOWN', () => {
34
+ const next = apply(payment(), proof('REJECTED')).payment;
35
+ assert.equal(next.status, 'BANK_REJECTED');
36
+ assert.equal(hasFinalBankOutcome(next.status), true);
37
+});
38
+test('non-definitive bank failure cannot be treated as rejection', () => {
39
+ fails(() => apply(payment(), {...proof('REJECTED'), definitive: false}), 'NON_DEFINITIVE_REJECTION');
40
+});
41
+test('UNKNOWN and all post-send statuses cannot auto-dispatch', () => {
42
+ assert.equal(mayAutomaticallyDispatch('READY'), true);
43
+ for (const s of ['DISPATCHING', 'UNKNOWN', 'BANK_ACCEPTED', 'SETTLED', 'BANK_REJECTED']) {
44
+ assert.equal(mayAutomaticallyDispatch(s), false);
45
+ }
46
+});
47
+test('same verified event is idempotent and returns snapshot identity', () => {
48
+ const first = apply(payment(), proof()).payment;
49
+ const next = apply(first, proof());
50
+ assert.equal(next.changed, false);
51
+ assert.strictEqual(next.payment, first);
52
+});
53
+test('same event ID with changed contents is rejected', () => {
54
+ const first = apply(payment(), proof()).payment;
55
+ fails(() => apply(first, {...proof(), observedAt: '2026-10-13T10:00:01Z'}), 'EVIDENCE_ID_COLLISION');
56
+});
57
+test('mismatched recipient payment, amount and currency are rejected', () => {
58
+ fails(() => apply(payment(), {...proof(), paymentId: 'other'}), 'PAYMENT_MISMATCH');
59
+ fails(() => apply(payment(), {...proof(), amountMinor: '1200001'}), 'AMOUNT_MISMATCH');
60
+ fails(() => apply(payment(), {...proof(), currency: 'USD'}), 'CURRENCY_MISMATCH');
61
+});
62
+test('settlement and acknowledgment require a bank reference', () => {
63
+ fails(() => apply(payment(), {...proof(), bankReference: ''}), 'MISSING_BANK_REFERENCE');
64
+ fails(() => apply(payment(), {...proof('ACCEPTED'), bankReference: ''}), 'MISSING_BANK_REFERENCE');
65
+});
66
+test('evidence cannot affect a READY non-dispatched payment', () => {
67
+ fails(() => apply(payment('READY'), proof()), 'NOT_DISPATCHED');
68
+});
69
+test('conflicting terminal outcomes are rejected', () => {
70
+ const settled = apply(payment(), proof()).payment;
71
+ fails(() => apply(settled, {...proof('REJECTED'), evidenceId: 'evt-2'}), 'TERMINAL_CONFLICT');
72
+ const rejected = apply(payment(), proof('REJECTED')).payment;
73
+ fails(() => apply(rejected, {...proof('SETTLED'), evidenceId: 'evt-2'}), 'TERMINAL_CONFLICT');
74
+});
75
+test('new evidence cannot change bank reference', () => {
76
+ const accepted = apply(payment(), proof('ACCEPTED')).payment;
77
+ fails(() => apply(accepted, {...proof(), evidenceId: 'evt-2', bankReference: 'another-bank-ref'}), 'BANK_REFERENCE_CONFLICT');
78
+});
79
+test('matching acknowledgment followed by settlement is allowed', () => {
80
+ const acknowledged = apply(payment(), proof('ACCEPTED')).payment;
81
+ const settled = apply(acknowledged, {...proof(), evidenceId: 'evt-2'}).payment;
82
+ assert.equal(settled.status, 'SETTLED');
83
+ assert.equal(settled.appliedProofs.length, 2);
84
+ assert.equal(settled.version, 7);
85
+});
86
+test('unverified, malformed amounts and dates fail closed', () => {
87
+ fails(() => apply(payment(), {...proof(), verifiedBy: ''}), 'UNVERIFIED_EVIDENCE');
88
+ fails(() => apply(payment(), {...proof(), amountMinor: '1.20'}), 'INVALID_PROOF');
89
+ fails(() => apply(payment(), {...proof(), observedAt: 'not-a-date'}), 'INVALID_PROOF');
90
+ fails(() => apply({...payment(), amountMinor: 1200000}, proof()), 'INVALID_PAYMENT');
91
+});
92
+test('applied event digest does not store the bank reference in proof history', () => {
93
+ const applied = apply(payment(), proof()).payment.appliedProofs[0];
94
+ assert.deepEqual(Object.keys(applied).sort(), ['digest', 'evidenceId']);
95
+ assert.equal(applied.digest.length, 64);
96
+});
97
+test('input snapshot is unchanged by apply', () => {
98
+ const original = payment();
99
+ const snapshot = JSON.stringify(original);
100
+ apply(original, proof());
101
+ assert.equal(JSON.stringify(original), snapshot);
102
+});