فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

feat(A05): detect invalid cheque clearing and reused settlement transactions in read-only financial report

Add company-scoped read-only financial reconciliation checks for cheque origin/status journals, single correct bank receipt/payment, orphan cheque cash, duplicate transaction-to-settlement allocations and mismatched cash/invoice references. Expose cheque count in AccountingView, with tests proving mismatch detection and no data mutations. Mandatory 13th real NSIS-installed Tauri/WebView2 scenario injects a synthetic malformed cheque into disposable VM, verifies report codes and no writes, then cleans up. PR Quality #38966862057 (195 Node tests, Vite, audit and preview installer) and full native Windows #38966862121 green, artifact #12075666586. Independent accountant acceptance remains open. No public release.

davoodmehraban89 committed Oct 17, 2026 at 00:42 UTC 693b6e84b41f1b6bd7e1e831e998464906401b01
6 files changed +177 -7
scripts/windows-vm-native-lab.ps1
+1
@@ -171,6 +171,7 @@ try {
171 'purchase-and-post-ledger',
172 'partial-sale-and-inventory',
173 'inactive-treasury-cheque-settlement',
174 + 'treasury-cheque-reconciliation-readonly',
175 'sale-return-immutable-stock-and-ledger',
176 'purchase-return-and-stock-guardrails',
177 'append-only-history-bulk-clear-protection',
src/core/AccountingService.js
+4 -4
@@ -55,19 +55,19 @@ class AccountingServiceImpl {
55 if (!Auth.isAdmin()) throw new Error('گزارش کنترل مغایرت فقط برای مدیر مجاز است');
56 const companyId = await DataScope.companyId();
57 const stores = ['account_chart','journal_entries','journal_lines','invoices',
58 - 'settlements','treasury','inventory_balances','stock_movements','settings'];
58 + 'settlements','treasury','cheques','inventory_balances','stock_movements','settings'];
59 return StorageService.transaction(stores, async tx => {
60 const scoped = async store =>
61 (await tx.getAll(store)).filter(row => row.companyId === companyId);
62 - const [accounts,journals,journalLines,invoices,settlements,transactions,
62 + const [accounts,journals,journalLines,invoices,settlements,transactions,cheques,
63 inventoryBalances,stockMovements,activation] = await Promise.all([
64 scoped('account_chart'),scoped('journal_entries'),scoped('journal_lines'),
65 - scoped('invoices'),scoped('settlements'),scoped('treasury'),
65 + scoped('invoices'),scoped('settlements'),scoped('treasury'),scoped('cheques'),
66 scoped('inventory_balances'),scoped('stock_movements'),
67 tx.get('settings','finance_v2_enabled_'+companyId)
68 ]);
69 return reconcileFinancialData({accounts,journals,journalLines,invoices,
70 - settlements,transactions,inventoryBalances,stockMovements,
70 + settlements,transactions,cheques,inventoryBalances,stockMovements,
71 integrated:!!activation?.enabled});
72 },'readonly');
73 }
src/core/ReconciliationCore.mjs
+71 -2
@@ -12,7 +12,7 @@ const safeAdd = (a,b) => {
12
13 export function reconcileFinancialData({
14 accounts = [], journals = [], journalLines = [], invoices = [],
15 - settlements = [], transactions = [], inventoryBalances = [],
15 + settlements = [], transactions = [], cheques = [], inventoryBalances = [],
16 stockMovements = [], integrated = false
17 } = {}) {
18 const issues = [];
@@ -58,10 +58,27 @@ export function reconcileFinancialData({
58
59 const allTransactions = new Map(transactions.filter(t => t.recordType === 'transaction').map(t => [t.id,t]));
60 const invoiceById = new Map(invoices.map(i => [i.id,i]));
61 + const settlementTransactionUse = new Map();
62 const settlementsByInvoice = new Map();
63 for (const row of settlements) {
64 if (!invoiceById.has(row.invoiceId)) report('ORPHAN_SETTLEMENT', 'تسویه به فاکتور ناموجود متصل است', row.id);
64 - if (!allTransactions.has(row.transactionId)) report('MISSING_SETTLEMENT_TRANSACTION', 'تراکنش مربوط به تسویه یافت نشد', row.id);
65 + const cash = allTransactions.get(row.transactionId);
66 + if (!cash) {
67 + report('MISSING_SETTLEMENT_TRANSACTION', 'تراکنش مربوط به تسویه یافت نشد', row.id);
68 + } else {
69 + if (cash.refInvoiceId !== undefined && cash.refInvoiceId !== null &&
70 + cash.refInvoiceId !== row.invoiceId) {
71 + report('SETTLEMENT_REFERENCE_MISMATCH', 'ارجاع تسویه و تراکنش خزانه به فاکتور متفاوت است', row.id);
72 + }
73 + if (safeMoney(cash.amount) && cash.amount !== row.amount) {
74 + report('SETTLEMENT_CASH_MISMATCH', 'مبلغ تسویه با تراکنش خزانه متناظر برابر نیست', row.id,
75 + 'error', row.amount, cash.amount);
76 + }
77 + if (settlementTransactionUse.has(row.transactionId)) {
78 + report('DUPLICATE_SETTLEMENT_TRANSACTION', 'یک تراکنش خزانه در چند تسویه استفاده شده است', row.id);
79 + }
80 + settlementTransactionUse.set(row.transactionId, row.id);
81 + }
82 if (!safeMoney(row.amount) || row.amount === 0) report('INVALID_SETTLEMENT_AMOUNT', 'مبلغ تسویه نامعتبر است', row.id);
83 if (!settlementsByInvoice.has(row.invoiceId)) settlementsByInvoice.set(row.invoiceId, []);
84 settlementsByInvoice.get(row.invoiceId).push(row);
@@ -90,6 +107,57 @@ export function reconcileFinancialData({
107 }
108 }
109
110 +
111 + // A05: read-only cheque lifecycle and its bank/cash evidence.
112 + // Legacy unposted cheques are not asserted to have journal references.
113 + // Only posted integrated cheques can be reconciled against double-entry GL.
114 + if (integrated) {
115 + const chequeById = new Map(cheques.map(row => [row.id, row]));
116 + const moneyByCheque = new Map();
117 + for (const transaction of transactions.filter(row =>
118 + row.recordType === 'transaction' && row.refChequeId)) {
119 + if (!moneyByCheque.has(transaction.refChequeId)) moneyByCheque.set(transaction.refChequeId, []);
120 + moneyByCheque.get(transaction.refChequeId).push(transaction);
121 + if (!chequeById.has(transaction.refChequeId)) {
122 + report('ORPHAN_CHEQUE_CASH', 'دریافت یا پرداخت چک به چک ناموجود متصل است', transaction.id);
123 + }
124 + }
125 + for (const cheque of cheques.filter(row => row.financePosted)) {
126 + const origin = byJournal.get(cheque.journalId);
127 + if (!origin || origin.status !== 'posted' || origin.sourceType !== 'cheque' ||
128 + origin.sourceId !== cheque.id) {
129 + report('CHEQUE_SOURCE_JOURNAL_MISSING', 'چک قطعی سند اولیه معتبر ندارد', cheque.id);
130 + }
131 + const money = moneyByCheque.get(cheque.id) || [];
132 + if (cheque.status === 'pending') {
133 + if (cheque.statusJournalId || money.length) {
134 + report('PENDING_CHEQUE_HAS_SETTLEMENT', 'چک در جریان دارای سند یا تراکنش تعیین‌تکلیف است', cheque.id);
135 + }
136 + continue;
137 + }
138 + const final = byJournal.get(cheque.statusJournalId);
139 + if (!final || final.status !== 'posted' || final.sourceType !== 'cheque_status' ||
140 + final.sourceId !== cheque.id) {
141 + report('CHEQUE_STATUS_JOURNAL_MISSING', 'وضعیت قطعی چک سند تعیین‌تکلیف معتبر ندارد', cheque.id);
142 + }
143 + if (cheque.status === 'cleared') {
144 + if (money.length !== 1) {
145 + report('CHEQUE_CLEARING_CASH_COUNT', 'چک وصول‌شده باید دقیقاً یک دریافت یا پرداخت خزانه داشته باشد',
146 + cheque.id, 'error', 1, money.length);
147 + }
148 + for (const transaction of money) {
149 + const direction = cheque.direction === 'inbound' ? 'receipt' : 'payment';
150 + if (transaction.type !== direction || transaction.amount !== cheque.amount ||
151 + transaction.journalId !== cheque.statusJournalId || !transaction.financePosted) {
152 + report('CHEQUE_CLEARING_CASH_MISMATCH', 'وصول چک با جهت یا مبلغ یا سند خزانه مغایرت دارد', cheque.id);
153 + }
154 + }
155 + } else if (money.length) {
156 + report('NONCLEARED_CHEQUE_HAS_CASH', 'چک وصول‌نشده دارای دریافت یا پرداخت خزانه است', cheque.id);
157 + }
158 + }
159 + }
160 +
161 let inventoryBook = 0, inventoryLedger = 0;
162 let stockUnits = 0;
163 if (integrated) {
@@ -144,6 +212,7 @@ export function reconcileFinancialData({
212 return {
213 integrated, checkedAt: new Date().toISOString(),
214 counts: { journals: posted.length, invoices: checkedInvoices, settlements: settlements.length,
215 + cheques: cheques.filter(row => row.financePosted).length,
216 inventoryBalances: inventoryBalances.length, issues: issues.length },
217 totals: { inventoryBook, inventoryLedger, stockUnits },
218 issues
src/views/AccountingView.js
+2 -1
@@ -304,7 +304,7 @@ class AccountingViewImpl {
304 <td>${html(item.expected === null ? '—' : Formatters.number(item.expected))}</td>
305 <td>${html(item.actual === null ? '—' : Formatters.number(item.actual))}</td></tr>`).join('');
306 return `<div class="card">
307 - <div class="toolbar"><strong>کنترل مغایرت اسناد، تسویه‌ها و موجودی</strong>
307 + <div class="toolbar"><strong>کنترل مغایرت اسناد، تسویه‌ها، چک‌ها و موجودی</strong>
308 <button class="btn btn-secondary" onclick="window.AccountingView.exportReconciliation()">خروجی CSV</button>
309 <button class="btn btn-secondary" onclick="window.AccountingView.refresh()">بررسی مجدد</button>
310 </div>
@@ -313,6 +313,7 @@ class AccountingViewImpl {
313 <p><strong>اسناد قطعی:</strong> ${Formatters.number(counts.journals)} |
314 <strong>فاکتورهای مالی:</strong> ${Formatters.number(counts.invoices)} |
315 <strong>تسویه‌ها:</strong> ${Formatters.number(counts.settlements)} |
316 + <strong>چک‌های مالی:</strong> ${Formatters.number(counts.cheques)} |
317 <strong>مغایرت‌های شناسایی‌شده:</strong> ${Formatters.number(counts.issues)}</p>
318 ${report.integrated ? `<p>ارزش موجودی انبار: ${Formatters.number(totals.inventoryBook)} ریال |
319 مانده دفتر کل موجودی: ${Formatters.number(totals.inventoryLedger)} ریال</p>` : ''}
tests/reconciliation.test.mjs
+58
@@ -112,3 +112,61 @@ test('accounting report period filters reject foreign periods and malformed Jala
112 const report=await accounts.financialReports({periodId:p.id,from:'1405/01/01',to:'1405/12/29'});
113 assert.equal(report.postedCount,0);
114 });
115 +
116 +test('A05: reconciliation detects mismatched settlement transaction and duplicate allocation without mutations',()=>{
117 + const f=fixture();
118 + f.transactions=[{id:'cash-1',recordType:'transaction',type:'receipt',amount:35,refInvoiceId:'other',
119 + financePosted:true}];
120 + f.settlements=[
121 + {id:'s1',invoiceId:'i1',transactionId:'cash-1',amount:40},
122 + {id:'s2',invoiceId:'i1',transactionId:'cash-1',amount:35}
123 + ];
124 + f.invoices[0].paidAmount=75;f.invoices[0].remaining=25;
125 + const snapshot=structuredClone(f);
126 + const report=reconcileFinancialData(f);
127 + for(const code of [
128 + 'SETTLEMENT_REFERENCE_MISMATCH','SETTLEMENT_CASH_MISMATCH',
129 + 'DUPLICATE_SETTLEMENT_TRANSACTION'
130 + ]) assert.ok(report.issues.some(x=>x.code===code),code);
131 + assert.deepEqual(f,snapshot,'A05 diagnostic must be read-only');
132 +});
133 +
134 +test('A05: reconciler checks posted cheque lifecycle and its single matched cash entry',()=>{
135 + const f=fixture();
136 + f.journals.push(
137 + {id:'cheque-j1',status:'posted',sourceType:'cheque',sourceId:'ch-1',debit:80,credit:80},
138 + {id:'cheque-j2',status:'posted',sourceType:'cheque_status',sourceId:'ch-1',debit:80,credit:80}
139 + );
140 + f.journalLines.push(
141 + {id:'c1',journalId:'cheque-j1',accountId:'a103',debit:80,credit:0},
142 + {id:'c2',journalId:'cheque-j1',accountId:'a201',debit:0,credit:80},
143 + {id:'c3',journalId:'cheque-j2',accountId:'a103',debit:80,credit:0},
144 + {id:'c4',journalId:'cheque-j2',accountId:'a201',debit:0,credit:80}
145 + );
146 + // No inventory ledger comparison from synthetic cheque-only ledger fixture.
147 + f.integrated=true;
148 + f.inventoryBalances[0].value=260;
149 + f.stockMovements[0].cost=260;
150 + f.cheques=[{id:'ch-1',financePosted:true,direction:'inbound',
151 + status:'cleared',amount:80,journalId:'cheque-j1',statusJournalId:'cheque-j2'}];
152 + f.transactions=[{id:'ct-1',recordType:'transaction',refChequeId:'ch-1',
153 + type:'receipt',amount:80,journalId:'cheque-j2',financePosted:true}];
154 + const baseline=reconcileFinancialData(f);
155 + assert.equal(baseline.issues.length,0,JSON.stringify(baseline.issues));
156 + assert.equal(baseline.counts.cheques,1);
157 + const before=structuredClone(f);
158 + f.transactions[0].amount=90;
159 + const mismatch=reconcileFinancialData(f);
160 + assert.ok(mismatch.issues.some(x=>x.code==='CHEQUE_CLEARING_CASH_MISMATCH'));
161 + assert.equal(f.cheques[0].status,'cleared','read-only checker must never revert cheque status');
162 + f.transactions[0].amount=80;
163 + f.transactions.push({...f.transactions[0],id:'ct-dup'});
164 + const duplicate=reconcileFinancialData(f);
165 + assert.ok(duplicate.issues.some(x=>x.code==='CHEQUE_CLEARING_CASH_COUNT'));
166 + f.transactions=f.transactions.slice(0,1);
167 + f.cheques[0].status='bounced';
168 + const bounced=reconcileFinancialData(f);
169 + assert.ok(bounced.issues.some(x=>x.code==='NONCLEARED_CHEQUE_HAS_CASH'));
170 + assert.equal(before.cheques[0].status,'cleared');
171 +});
172 +
tests/windows-vm-native-functional-matrix.cjs
+41
@@ -559,6 +559,46 @@ async function nativeInactiveBankSettlementGuard() {
559 disabledChequeClearingRejected:true, validChequeClearedExactlyOnce:true };
560 }
561
562 +async function nativeTreasuryChequeReconciliation() {
563 + const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
564 + const check=(ok,msg)=>{if(!ok)throw Error(msg);};
565 + const storage=FINORA.Storage,company=await FINORA.Company.current();
566 + check(company?.id&&FINORA.Auth.isAdmin(),'A05 reconciliation requires synthetic admin');
567 + await FINORA.Router.go('accounting');await wait(130);
568 + const view=window.AccountingView;
569 + await view.switchTab('reconciliation');
570 + const original=await view.renderReconciliation();
571 + check(original.includes('چک‌های مالی'),'Native reconciliation does not show cheque controls');
572 + check(!original.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
573 + !original.includes('CHEQUE_CLEARING_CASH_COUNT'),
574 + 'Real posted VM cheque failed reconciliation before fault injection');
575 + // Corrupt only a synthetic fixture in the disposable native VM, never
576 + // alter a customer accounting record. This probes read-only detection.
577 + const id='vm-a05-invalid-cheque-reconciliation';
578 + const broken={id,companyId:company.id,financePosted:true,
579 + direction:'inbound',status:'cleared',amount:90,journalId:'not-there',
580 + statusJournalId:'not-there-either'};
581 + await storage.put('cheques',broken);
582 + const before=(await storage.getAll('journal_entries')).length;
583 + const checked=await view.renderReconciliation();
584 + check(checked.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
585 + checked.includes('CHEQUE_STATUS_JOURNAL_MISSING')&&
586 + checked.includes('CHEQUE_CLEARING_CASH_COUNT'),
587 + 'Native installed reconciliation failed to report malformed cheque');
588 + check((await storage.getAll('journal_entries')).length===before&&
589 + (await storage.get('cheques',id))?.status==='cleared',
590 + 'Read-only reconciliation changed journal or cheque state');
591 + await storage.delete('cheques',id);
592 + const after=await view.renderReconciliation();
593 + check(!after.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
594 + !after.includes('CHEQUE_CLEARING_CASH_COUNT'),
595 + 'Reconciliation still reports synthetic cheque after fixture removal');
596 + await view.switchTab('journals');
597 + check(!document.querySelector('.toast-error'),'A05 reconciliation left toast');
598 + return {livePostedChequeReviewed:true,chequeDiscrepanciesDetected:true,
599 + reportingReadOnly:true,fixtureRemoved:true};
600 +}
601 +
602 async function nativeBackupRestore() {
603 const check = (value, message) => { if (!value) throw Error(message); };
604 const S = FINORA.Storage;
@@ -821,6 +861,7 @@ module.exports = async function nativeFunctionalMatrix(cdp) {
861 ['purchase-and-post-ledger', purchaseInvoice],
862 ['partial-sale-and-inventory', saleInvoice],
863 ['inactive-treasury-cheque-settlement', nativeInactiveBankSettlementGuard],
864 + ['treasury-cheque-reconciliation-readonly', nativeTreasuryChequeReconciliation],
865 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
866 ['purchase-return-and-stock-guardrails', nativePurchaseReturnGuardrails],
867 ['append-only-history-bulk-clear-protection', nativeHistoryClearFailClosed],