فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
docs/finora-master-execution-playbook
a02/strict-export-preflight-20261018
audit/a01-readonly-invoice-metadata-20261101
ci/a06-require-trusted-issuer-for-release
ci/main-postmerge-phase-a-validation-20261020
ci/phase-a-controlled-public-release
design/issue-5-commercial-corrections-adr
docs/a01-a02-a05-oct23-verified-evidence
docs/a01-cheque-endorsement-evidence-20261022
docs/a01-cheque-event-date-evidence-20261021
docs/a01-explicit-refund-reason-evidence-20261021
docs/a01-refund-auth-status-20261020
docs/a01-refund-trace-evidence-20261020
docs/a02-102-evidence-20261018
docs/a02-pr104-evidence-20261018
docs/a02-pr106-evidence-20261019
docs/a02-pr108-ten-tests-20261019
docs/a02-private-sql-backup-evidence-20261111
docs/a03-merge-status-sync-20261020
docs/a04-software-gate-acceptance-20261020
docs/feature-matrix-20261014
docs/finora-master-execution-playbook
docs/four-phase-execution-20261014
docs/four-phase-roadmap-20261014
docs/holoo-lab-stabilization-phase1-20261111
docs/holoo-runtime-schema-audit-20261111
docs/ops-142-governance-5-1-3-20261030
docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023
docs/phase-a-a01-a05-a06-evidence-20261023
docs/phase-a-independent-acceptance-evidence
docs/phase-a-pr110-evidence-20261019
docs/project-status-phase-a-20261014
feat/a01-referenced-return-corrections
feat/a01-referenced-returns-on-main
feat/a02-atomic-opening-ledger-preflight
feat/a02-holoo-compatibility-preflight
feat/a02-holoo-declared-control-totals
feat/a02-holoo-explicit-csv-gate
feat/a02-holoo-safe-zip-intake-offline-webview2-20261030
feat/a02-offline-sql-server-provisioning-20261030
feat/a02-opening-balance-dry-run
feat/a02-opening-ledger-admin-ui
feat/a02-opt-in-isolated-sql-restore-executor-20261030
feat/a02-private-holoo-zip-staging-20261030
feat/a02-safe-isolated-restore-plan-20261030
feat/a02-sql-backup-header-verifyonly-20261030
feat/a03-audit-schema-atomic-events
feat/a03-complete-manual-journal-audit
feat/a05-cheque-treasury-reconciliation
feat/a06-signed-offline-license-activation
feat/a08-synthetic-performance-baseline
feat/phase-a-accounting-benchmark-return-preview
feat/phase-a-ledger-settlement-diagnostics
feature/v2-reconciliation-20261013
fix/a01-atomic-confirm-ui-one-shot-20261031
fix/a01-cheque-clearance-explicit-account-20261023
fix/a01-cheque-contractual-due-date-validity-20261023
fix/a01-cheque-endorsement-counterparty-20261022
fix/a01-cheque-event-date-open-period-20261021
fix/a01-cumulative-return-amount-cap
fix/a01-explicit-refund-reason-approval-20261021
fix/a01-manager-authorized-customer-refunds-20261020
fix/a01-no-implicit-refund
fix/a01-one-shot-confirm-on-atomic-import-20261031
fix/a01-refund-and-overcollection-net-cash
fix/a01-refund-correction-trace-20261020
fix/a02-atomic-excel-master-merge-20261031
fix/a02-canonical-mapping-contract-20261018
fix/a02-disable-destructive-excel-replace-20261031
fix/a02-holoo-invoice-line-coverage-20261023
fix/a02-holoo-preflight-required-invoice-lines-20261023
fix/a02-mapping-contract-20261018
fix/a02-opening-preflight-unbalanced-report
fix/a02-orphan-mapping-20261018
fix/a02-private-excel-import-session-20261031
fix/a02-strict-export-input-20261019
fix/a03-append-only-full-backup-import
fix/a03-append-only-write-guard
fix/a03-block-transaction-clear-append-only-20261016
fix/a03-chain-validation-20261020
fix/a03-company-scoped-audit-data-access
fix/a03-deny-direct-audit-write-20261019
fix/a03-escaped-expense-list-20261031
fix/a03-escaped-financial-record-ids-20261031
fix/a03-financial-ledger-actions-and-print-20261031
fix/a04-backup-checksum-preflight
fix/a04-company-audit-replay-stable-compare
fix/a04-company-backup-source-isolation-20261020
fix/a04-full-restore-posted-financial-integrity
fix/a04-reject-mixed-company-backup-20261019
fix/a04-replace-immutable-posted-ledger
fix/a04-restore-financial-journal-references
fix/a04-service-source-company-boundary-20261020
fix/a05-block-inactive-treasury-settlements
fix/a05-cheque-cash-evidence-reconciliation-20261023
fix/a05-cheque-ledger-and-bank-reconciliation-20261023
fix/a05-fiscal-close-invariant-gates
fix/a06-backup-restore-user-privileges
fix/a06-license-user-company-quota-20261023
fix/a06-malformed-trial-state-fail-closed
fix/a06-offline-clock-fail-closed-20261019
fix/a07-indexeddb-blocked-startup
fix/a07-offline-bundled-assets
fix/a07-version-and-startup-banner
fix/issue-7-company-backup-isolation
fix/p0-deterministic-fractional-invoice-money-20261031
fix/p0-fractional-quantity-input-20261031
fix/p0-fractional-quantity-integrated-20261031
fix/p0-invoice-posting-invariants-20261031
fix/p0-legacy-stock-and-product-inputs-20261031
fix/p0-reports-immutable-cogs-20261101
fix/p0-verified-financial-percent-20261031
fix/p0-zero-discount-report-revenue-20261101
fix/phase-a-backup-app-version
fix/phase-a-backup-integrity-checksum
fix/phase-a-backup-record-id-validation-20261014
fix/phase-a-backup-version-validation-20261014
fix/phase-a-closure-pack3-20261101
fix/phase-a-entitlement-payload-validation
fix/phase-a-gate-exact-evidence-20261019
fix/phase-a-pack4-stock-scope-20261101
fix/phase-a-pack5-integrated-evidence-20261101
fix/phase-a-pack6-atomic-legacy-20261101
fix/phase-a-restore-envelope-and-rollback
fix/phase-a-settings-admin-gate
fix/print-browser-header-footer-20261014
fix/q01-expense-security-probe-exact-option-20261031
fix/q01-financial-grid-labels-20261031
fix/q01-form-label-association-20261031
fix/q01-native-evidence-integrity-20261030
fix/q01-number-input-persian-decimal-20261031
fix/q01-responsive-dashboard-and-cheque-table-20261031
fix/q01-safe-ui-action-audit-coverage-20261031
fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030
fix/roadmap-metadata-sync-20261014
gate/a03-audit-metadata-validation-20261019
integration/a02-windows-holoo-setup-candidate-20261030
license-server
main
perf/a07-lazy-load-excel
perf/a08-cheque-reconciliation-account-index-20261023
perf/a08-paginated-reports-20261101
phase1-restore-hardening
planning/holoo-execution-20261013
planning/roadmap-project-management-20261014
qa/native-click-coverage-audit-20261030
release/v2.0.0
test/a01-native-endorsement-mandatory-20261023
test/a01-native-purchase-return-guardrails
test/a01-native-sale-return-financial-guardrails
test/a01-safe-integer-boundary-20261019
test/a02-native-opening-dry-run-rejections
test/a02-native-positive-opening-ledger
test/a04-native-corrupt-fbackup-20261016
test/a04-native-encrypted-company-backup
test/a04-native-encrypted-company-backup-main
test/a04-native-late-transaction-rollback
test/a04-native-windows-backup-recovery
test/a04-real-edge-v6-v7-migration
test/a04-real-native-interrupted-restore
test/a05-native-draft-ledger-and-repeat-close-20261016
test/a05-native-fiscal-close-guardrails
test/a07-native-multipage-print-engine
test/a07-native-origin-provenance
test/a07-native-webview2-offline-routes
test/a07-windows-offline-startup-smoke
test/a08-installed-webview2-60k-baseline
test/a08-native-webview2-heap-metrics
test/a08-windows-synthetic-performance-baseline
test/github-write-access-20261009
test/native-win-ui-routes-after-finance-backup
test/phase-a-combined-a01-a05-a08-final-evidence
test/phase-a-combined-native-acceptance-matrix
test/phase-a-ledger-invariants-20261014
test/phase-a-native-all-routes-on-merged-lab
test/phase-a-native-encrypted-backup
test/phase-a-native-finance-backup-matrix
test/phase-a-native-ui-and-backup-smoke
test/phase-a-windows-native-installer-lab
work/a08-dispatch-activation-20261123
work/a08-memory-stability-20261123
work/finance-curated-20261123
| 1 | import test from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import 'fake-indexeddb/auto'; |
| 4 | import { StorageService as db } from '../src/core/StorageService.js'; |
| 5 | import { AccountingService as accounts } from '../src/core/AccountingService.js'; |
| 6 | import { RetailPostingService as retail } from '../src/core/RetailPostingService.js'; |
| 7 | import { Auth } from '../src/core/Auth.js'; |
| 8 | import { CompanyService } from '../src/core/CompanyService.js'; |
| 9 | |
| 10 | const date='1405/07/18'; |
| 11 | const company='c2-phase2'; |
| 12 | async function setup(){ |
| 13 | await db.clearAll(); |
| 14 | await db.put('companies',{id:company,name:'Store 2'}); |
| 15 | Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'}; |
| 16 | CompanyService.activeCompanyId=company; |
| 17 | const period=await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'}); |
| 18 | await accounts.seedDefaultChart(); |
| 19 | const bank={id:'cash-1',companyId:company,recordType:'account', |
| 20 | type:'cashbox',name:'صندوق',isActive:true,isDefault:true,initialBalance:0}; |
| 21 | const product={id:'product-1',companyId:company,name:'کالای تست', |
| 22 | code:'X1',buyPrice:100,sellPrice:200,trackInventory:true}; |
| 23 | const contact={id:'contact-1',companyId:company,name:'مشتری'}; |
| 24 | await db.put('treasury',bank);await db.put('products',product);await db.put('contacts',contact); |
| 25 | assert.deepEqual(await retail.activate(),{enabled:true}); |
| 26 | return {period,bank,product,contact,warehouse:(await retail.warehouses())[0]}; |
| 27 | } |
| 28 | let seq=100; |
| 29 | function invoice(kind,qty,price,rest={}){ |
| 30 | const total=qty*price; |
| 31 | return {id:'phase2-inv-'+(++seq),companyId:company, |
| 32 | number:String(seq),clientUuid:'test-'+seq,ownerUserId:'phase2-admin',kind, |
| 33 | date,contactId:'contact-1',contactName:'مشتری',isPreInvoice:false, |
| 34 | items:[{productId:'product-1',productName:'کالای تست',qty,price, |
| 35 | lineSubtotal:total,lineTotal:total,discount:0}],subtotal:total, |
| 36 | totalDiscount:0,vatAmount:0,grandTotal:total,paidAmount:0, |
| 37 | paymentMethod:'cash',status:'unpaid',remaining:total,...rest}; |
| 38 | } |
| 39 | async function purchase10(){return retail.issueInvoice(invoice('purchase',10,100))} |
| 40 | async function sale3(rest={}){return retail.issueInvoice(invoice('sale',3,200,rest))} |
| 41 | test('v2 sale-purchase cash settlement balance, weighted average and exactly once',async()=>{ |
| 42 | const {warehouse}=await setup(); |
| 43 | const p=await purchase10(); |
| 44 | const first=(await retail.stockBalances())[0]; |
| 45 | assert.equal(first.quantityUnits,10000);assert.equal(first.value,1000); |
| 46 | const sold=await sale3({paidAmount:200}); |
| 47 | assert.equal(sold.paidAmount,200);assert.equal(sold.remaining,400); |
| 48 | const second=(await retail.stockBalances())[0]; |
| 49 | assert.equal(second.quantityUnits,7000);assert.equal(second.value,700); |
| 50 | const stock=await db.getAllByIndex('stock_movements','productId','product-1'); |
| 51 | assert.equal(stock.filter(m=>m.financePosted).length,0); |
| 52 | assert.equal(stock.length,2); |
| 53 | const journals=await accounts.listJournals(); |
| 54 | assert.equal(journals.length,3); |
| 55 | const trial=await accounts.trialBalance(); |
| 56 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 57 | await assert.rejects(retail.issueInvoice(sold),/قطعی|تکراری/); |
| 58 | assert.equal((await accounts.listJournals()).length,3); |
| 59 | const receipt=await retail.postTransaction({id:'receipt-1',type:'receipt',date,amount:400, |
| 60 | contactId:'contact-1',refInvoiceId:sold.id,toAccountId:'cash-1',method:'cash'}); |
| 61 | assert.equal(receipt.amount,400); |
| 62 | assert.equal((await db.get('invoices',sold.id)).remaining,0); |
| 63 | assert.equal((await db.getAllByIndex('settlements','invoiceId',sold.id)).length,2); |
| 64 | assert.deepEqual((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit); |
| 65 | assert.equal((await retail.stockBalances({warehouseId:warehouse.id}))[0].value,700); |
| 66 | }); |
| 67 | test('v2 stock over-issue aborts invoice, stock and journal atomically',async()=>{ |
| 68 | await setup();await purchase10(); |
| 69 | const invoiceTooBig=invoice('sale',11,200); |
| 70 | await assert.rejects(retail.issueInvoice(invoiceTooBig),/موجودی/); |
| 71 | assert.equal(await db.get('invoices',invoiceTooBig.id),undefined); |
| 72 | assert.equal((await accounts.listJournals()).length,1); |
| 73 | assert.equal((await retail.stockBalances())[0].quantityUnits,10000); |
| 74 | }); |
| 75 | test('v2 sale return references original COGS and limits cumulative returned quantity',async()=>{ |
| 76 | await setup();await purchase10(); |
| 77 | const sold=await sale3(); |
| 78 | const back=invoice('sale_return',1,200,{originalInvoiceId:sold.id}); |
| 79 | const returned=await retail.issueInvoice(back); |
| 80 | assert.equal(returned.kind,'sale_return'); |
| 81 | assert.equal((await retail.stockBalances())[0].value,800); |
| 82 | assert.equal((await retail.stockBalances())[0].quantityUnits,8000); |
| 83 | await assert.rejects(retail.issueInvoice(invoice('sale_return',3,200,{originalInvoiceId:sold.id})),/بیشتر/); |
| 84 | assert.equal((await accounts.listJournals()).length,3); |
| 85 | }); |
| 86 | test('v2 cash expense, cheque deposit and bank transfer produce balanced journals',async()=>{ |
| 87 | await setup();await purchase10();await sale3(); |
| 88 | const e=await retail.postExpense({id:'exp-phase2',kind:'expense',date,amount:60,method:'cash',category:'اجاره'}); |
| 89 | assert.equal(e.financePosted,true); |
| 90 | await assert.rejects(retail.postExpense(e),/تکراری/); |
| 91 | const c=await retail.postCheque({id:'cheque-in-1',issueDate:date,dueDate:date, |
| 92 | direction:'inbound',status:'pending',contactId:'contact-1',amount:250,chequeNumber:'C1'}); |
| 93 | assert.equal(c.status,'pending'); |
| 94 | const cleared=await retail.changeChequeStatus(c.id,'cleared',{date,accountId:'cash-1',explicitlyApproved:true}); |
| 95 | assert.equal(cleared.status,'cleared'); |
| 96 | await assert.rejects(retail.changeChequeStatus(c.id,'cleared',{date}),/در جریان/); |
| 97 | assert.equal((await db.getAll('treasury')).filter(r=>r.refChequeId===c.id).length,1); |
| 98 | const b=await retail.addWarehouse('انبار دوم'); |
| 99 | assert.ok(b.id); |
| 100 | const trial=await accounts.trialBalance(); |
| 101 | assert.equal(trial.totals.credit,trial.totals.debit); |
| 102 | }); |
| 103 | test('v2 multiwarehouse transfer and stocktake adjustment preserve value reconciliation',async()=>{ |
| 104 | const {warehouse}=await setup();await purchase10(); |
| 105 | const other=await retail.addWarehouse('شعبه دوم'); |
| 106 | const transfer=await retail.transferStock({fromWarehouseId:warehouse.id, |
| 107 | toWarehouseId:other.id,productId:'product-1',quantity:4,date}); |
| 108 | assert.equal(transfer.cost,400); |
| 109 | let balances=await retail.stockBalances(); |
| 110 | assert.equal(balances.reduce((s,x)=>s+x.value,0),1000); |
| 111 | assert.equal(balances.find(x=>x.warehouseId===warehouse.id).quantityUnits,6000); |
| 112 | const take=await retail.newStocktake({warehouseId:other.id,date}); |
| 113 | const count=(await retail.getStocktakeLines(take.id))[0]; |
| 114 | assert.equal(count.expectedUnits,4000); |
| 115 | await retail.countStocktake(take.id,'product-1',3); |
| 116 | const done=await retail.finalizeStocktake(take.id); |
| 117 | assert.equal(done.decrease,100); |
| 118 | balances=await retail.stockBalances(); |
| 119 | assert.equal(balances.reduce((s,x)=>s+x.value,0),900); |
| 120 | await assert.rejects(retail.finalizeStocktake(take.id),/قبلاً/); |
| 121 | assert.equal((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit); |
| 122 | }); |
| 123 | test('v2 activation refuses silently migrating legacy movements',async()=>{ |
| 124 | await db.clearAll(); |
| 125 | await db.put('companies',{id:company,name:'old'}); |
| 126 | Auth.currentUser={id:'phase2-admin',role:'admin'}; |
| 127 | CompanyService.activeCompanyId=company; |
| 128 | await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'}); |
| 129 | await accounts.seedDefaultChart(); |
| 130 | await db.put('stock_movements',{id:'historical',companyId:company,productId:'old',type:'in',qty:5}); |
| 131 | await assert.rejects(retail.activate(),/گردش قبلی/); |
| 132 | assert.equal(await retail.isEnabled(),false); |
| 133 | }); |
| 134 | |
| 135 | test('v2 standalone GL reversal of a commercial invoice is prohibited',async()=>{ |
| 136 | const {period}=await setup();await purchase10(); |
| 137 | const journal=(await accounts.listJournals())[0]; |
| 138 | await assert.rejects(accounts.reverseJournal(journal.id,{periodId:period.id,date}),/تجاری/); |
| 139 | assert.equal((await accounts.listJournals()).length,1); |
| 140 | }); |
| 141 | test('v2 cross-company contact and treasury references roll back without leakage',async()=>{ |
| 142 | await setup();await purchase10(); |
| 143 | await db.put('contacts',{id:'foreign-person',companyId:'elsewhere',name:'foreign'}); |
| 144 | const receipt={id:'foreign-receipt',date,type:'receipt',amount:100,contactId:'foreign-person',toAccountId:'cash-1'}; |
| 145 | await assert.rejects(retail.postTransaction(receipt),/شرکت/); |
| 146 | assert.equal(await db.get('treasury',receipt.id),undefined); |
| 147 | const issued=invoice('sale',2,200,{contactId:'foreign-person'}); |
| 148 | await assert.rejects(retail.issueInvoice(issued),/شرکت/); |
| 149 | assert.equal(await db.get('invoices',issued.id),undefined); |
| 150 | assert.equal((await retail.stockBalances())[0].quantityUnits,10000); |
| 151 | }); |
| 152 | test('v2 purchase-return financial variance remains balanced when costs and sale price differ',async()=>{ |
| 153 | await setup();const purchased=await purchase10(); |
| 154 | const result=await retail.issueInvoice(invoice('purchase_return',2,120,{originalInvoiceId:purchased.id})); |
| 155 | assert.equal(result.grandTotal,240); |
| 156 | assert.equal((await retail.stockBalances())[0].quantityUnits,8000); |
| 157 | assert.equal((await retail.stockBalances())[0].value,800); |
| 158 | const trial=await accounts.trialBalance(); |
| 159 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 160 | const chart=await accounts.listAccounts(); |
| 161 | const variance=chart.find(x=>x.code==='503'); |
| 162 | assert.ok(trial.rows.some(row=>row.accountId===variance.id)); |
| 163 | }); |
| 164 | test('v2 open stocktake locks other inventory transactions until approval',async()=>{ |
| 165 | const {warehouse}=await setup();await purchase10(); |
| 166 | const take=await retail.newStocktake({warehouseId:warehouse.id,date}); |
| 167 | const attempted=invoice('sale',1,200); |
| 168 | await assert.rejects(retail.issueInvoice(attempted),/شمارش/); |
| 169 | assert.equal(await db.get('invoices',attempted.id),undefined); |
| 170 | await retail.countStocktake(take.id,'product-1',10); |
| 171 | await retail.finalizeStocktake(take.id); |
| 172 | const issued=await retail.issueInvoice(invoice('sale',1,200)); |
| 173 | assert.equal(issued.financePosted,true); |
| 174 | }); |
| 175 | test('v2 full company backup/restore round trip preserves stock valuation and financial postings',async()=>{ |
| 176 | const {warehouse}=await setup(); |
| 177 | await purchase10();await sale3({paidAmount:200}); |
| 178 | const { SettingsController }=await import('../src/controllers/SettingsController.js'); |
| 179 | const backup=await SettingsController.exportBackup(); |
| 180 | assert.equal(backup.data.inventory_balances.length,1); |
| 181 | assert.equal(backup.data.settlements.length,1); |
| 182 | assert.equal(backup.data.journal_entries.length,3); |
| 183 | await db.clearAll(); |
| 184 | await db.put('companies',{id:company,name:'restored'}); |
| 185 | CompanyService.activeCompanyId=company; |
| 186 | const counts=await SettingsController.importBackup(backup,{mode:'merge'}); |
| 187 | assert.ok(counts.added>=10); |
| 188 | assert.equal(await retail.isEnabled(),true); |
| 189 | assert.equal((await retail.stockBalances())[0].value,700); |
| 190 | assert.equal((await accounts.listJournals()).length,3); |
| 191 | assert.equal((await db.getAllByIndex('settlements','companyId',company)).length,1); |
| 192 | const corrupted=structuredClone(backup); |
| 193 | corrupted.data.inventory_balances[0].warehouseId='missing-warehouse'; |
| 194 | await assert.rejects(SettingsController.importBackup(corrupted,{mode:'replace'}),/موجودی|انبار/); |
| 195 | assert.equal((await retail.stockBalances())[0].value,700); |
| 196 | }); |
| 197 | test('v2 fiscal period closure forbids invoice and stock writes atomically',async()=>{ |
| 198 | const {period}=await setup();await purchase10(); |
| 199 | await accounts.closePeriod(period.id); |
| 200 | const newSale=invoice('sale',1,200); |
| 201 | await assert.rejects(retail.issueInvoice(newSale),/دوره مالی باز/); |
| 202 | assert.equal(await db.get('invoices',newSale.id),undefined); |
| 203 | assert.equal((await accounts.listJournals()).length,1); |
| 204 | assert.equal((await retail.stockBalances())[0].quantityUnits,10000); |
| 205 | }); |
| 206 | test('v2 tax input/output and mixed transaction amounts remain balanced',async()=>{ |
| 207 | await setup();await retail.issueInvoice(invoice('purchase',10,100, |
| 208 | {vatAmount:100,grandTotal:1100})); |
| 209 | const s=await retail.issueInvoice(invoice('sale',1,200, |
| 210 | {vatAmount:20,grandTotal:220})); |
| 211 | assert.equal(s.remaining,220); |
| 212 | const trial=await accounts.trialBalance(); |
| 213 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 214 | const chart=await accounts.listAccounts(); |
| 215 | assert.ok(trial.rows.find(x=>x.accountId===chart.find(a=>a.code==='104').id)?.debit===100); |
| 216 | assert.ok(trial.rows.find(x=>x.accountId===chart.find(a=>a.code==='202').id)?.credit===20); |
| 217 | }); |
| 218 | test('v2 stocktake can post shortage and surplus together in one balanced journal',async()=>{ |
| 219 | const {warehouse}=await setup(); |
| 220 | await purchase10(); |
| 221 | await db.put('products',{id:'product-extra',companyId:company,name:'extra',trackInventory:true}); |
| 222 | const second=invoice('purchase',4,100,{ |
| 223 | items:[{productId:'product-extra',qty:4,price:100,lineTotal:400,discount:0}], |
| 224 | subtotal:400,grandTotal:400 |
| 225 | }); |
| 226 | await retail.issueInvoice(second); |
| 227 | const take=await retail.newStocktake({warehouseId:warehouse.id,date}); |
| 228 | await retail.countStocktake(take.id,'product-1',9); |
| 229 | await retail.countStocktake(take.id,'product-extra',5); |
| 230 | const result=await retail.finalizeStocktake(take.id); |
| 231 | assert.equal(result.increase,100); |
| 232 | assert.equal(result.decrease,100); |
| 233 | const trial=await accounts.trialBalance(); |
| 234 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 235 | }); |
| 236 | test('v2 concurrent posting of same invoice commits exactly once',async()=>{ |
| 237 | await setup();await purchase10(); |
| 238 | const same=invoice('sale',1,200); |
| 239 | const [a,b]=await Promise.allSettled([retail.issueInvoice(same),retail.issueInvoice(same)]); |
| 240 | assert.equal([a,b].filter(x=>x.status==='fulfilled').length,1); |
| 241 | assert.equal([a,b].filter(x=>x.status==='rejected').length,1); |
| 242 | assert.equal((await accounts.listJournals()).length,2); |
| 243 | assert.equal((await retail.stockBalances())[0].quantityUnits,9000); |
| 244 | assert.equal((await db.getAll('stock_movements')).length,2); |
| 245 | }); |
| 246 | test('v2 concurrent invoice number collision commits only one',async()=>{ |
| 247 | await setup();await purchase10(); |
| 248 | const first=invoice('sale',1,200),second=invoice('sale',2,200); |
| 249 | second.number=first.number; |
| 250 | const results=await Promise.allSettled([retail.issueInvoice(first),retail.issueInvoice(second)]); |
| 251 | assert.equal(results.filter(x=>x.status==='fulfilled').length,1); |
| 252 | assert.equal(results.filter(x=>x.status==='rejected').length,1); |
| 253 | assert.equal((await accounts.listJournals()).length,2); |
| 254 | }); |
| 255 | test('v2 all partial sale returns restore every rial of original COGS',async()=>{ |
| 256 | await setup(); |
| 257 | const buy=invoice('purchase',3,33); |
| 258 | buy.items[0].lineTotal=100;buy.items[0].lineSubtotal=100;buy.subtotal=100;buy.grandTotal=100;buy.remaining=100; |
| 259 | await retail.issueInvoice(buy); |
| 260 | const sale=await retail.issueInvoice(invoice('sale',3,200)); |
| 261 | for(let j=0;j<3;j++){ |
| 262 | const returned=invoice('sale_return',1,200,{originalInvoiceId:sale.id}); |
| 263 | await retail.issueInvoice(returned); |
| 264 | } |
| 265 | const balance=(await retail.stockBalances())[0]; |
| 266 | assert.equal(balance.quantityUnits,3000); |
| 267 | assert.equal(balance.value,100); |
| 268 | assert.equal((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit); |
| 269 | }); |
| 270 | test('v2 duplicate product lines on last sale return do not overvalue returned goods',async()=>{ |
| 271 | await setup(); |
| 272 | const buy=invoice('purchase',3,33); |
| 273 | buy.items[0].lineTotal=100;buy.subtotal=100;buy.grandTotal=100;buy.remaining=100; |
| 274 | await retail.issueInvoice(buy); |
| 275 | const sale=await retail.issueInvoice(invoice('sale',3,200)); |
| 276 | const returned=invoice('sale_return',3,200,{originalInvoiceId:sale.id}); |
| 277 | returned.items=[{...returned.items[0],qty:1,lineTotal:200}, |
| 278 | {...returned.items[0],qty:2,lineTotal:400}]; |
| 279 | await retail.issueInvoice(returned); |
| 280 | assert.equal((await retail.stockBalances())[0].value,100); |
| 281 | }); |
| 282 | test('v2 product controller forbids bypass stock writes and uses inventory book valuation',async()=>{ |
| 283 | await setup(); |
| 284 | globalThis.window??={}; |
| 285 | const { ProductController } = await import('../src/controllers/ProductController.js'); |
| 286 | await purchase10(); |
| 287 | const b=invoice('purchase',10,200); |
| 288 | await retail.issueInvoice(b); |
| 289 | const valuation=await ProductController.getTotalStockValue(); |
| 290 | assert.equal(valuation.totalBuyValue,3000); |
| 291 | assert.equal((await ProductController.getStockMap(['product-1']))['product-1'],20); |
| 292 | await assert.rejects( |
| 293 | ProductController.addStockMovement('product-1','in',100,'manual'),/دستی/ |
| 294 | ); |
| 295 | await assert.rejects( |
| 296 | ProductController.updateProduct('product-1',{name:'کالای آزمایش',trackInventory:false}), |
| 297 | /نوع کالا/ |
| 298 | ); |
| 299 | assert.equal((await retail.stockBalances())[0].value,3000); |
| 300 | }); |
| 301 | test('v2 purchase returns require a matching original invoice and cannot exceed quantity',async()=>{ |
| 302 | await setup();const original=await purchase10(); |
| 303 | const without=invoice('purchase_return',1,100); |
| 304 | await assert.rejects(retail.issueInvoice(without),/اولیه/); |
| 305 | const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{originalInvoiceId:original.id})); |
| 306 | assert.equal(returned.financePosted,true); |
| 307 | await assert.rejects(retail.issueInvoice(invoice('purchase_return',7,100,{originalInvoiceId:original.id})),/بیشتر/); |
| 308 | assert.equal((await retail.stockBalances())[0].quantityUnits,6000); |
| 309 | }); |
| 310 | test('v2 integrated issuance commits invoice item rows and rolls back on failure',async()=>{ |
| 311 | await setup();await purchase10(); |
| 312 | const rows=await db.getAll('invoice_items'); |
| 313 | assert.equal(rows.length,1); |
| 314 | assert.equal(rows[0].invoiceId,(await db.getAll('invoices'))[0].id); |
| 315 | assert.equal(rows[0].companyId,company); |
| 316 | const bad=invoice('sale',100,200); |
| 317 | await assert.rejects(retail.issueInvoice(bad),/موجودی/); |
| 318 | assert.equal((await db.getAll('invoice_items')).length,1); |
| 319 | }); |
| 320 | test('fresh-company activation creates default cash account and chart subledger',async()=>{ |
| 321 | await db.clearAll(); |
| 322 | await db.put('companies',{id:company,name:'empty'}); |
| 323 | Auth.currentUser={id:'phase2-admin',role:'admin'}; |
| 324 | CompanyService.activeCompanyId=company; |
| 325 | await accounts.createPeriod({name:'سال',startDate:'1405/01/01',endDate:'1405/12/29'}); |
| 326 | await accounts.seedDefaultChart(); |
| 327 | await retail.activate(); |
| 328 | const banks=(await db.getAll('treasury')).filter(x=>x.companyId===company&&x.recordType==='account'); |
| 329 | assert.equal(banks.length,1); |
| 330 | assert.ok(banks[0].ledgerAccountId); |
| 331 | assert.ok((await accounts.listAccounts()).some(a=>a.id===banks[0].ledgerAccountId)); |
| 332 | assert.equal((await db.getAll('journal_entries')).length,0); |
| 333 | }); |
| 334 | test('regression: pre-existing 101 cash subsidiary permits activation and cash settlement',async()=>{ |
| 335 | await db.clearAll(); |
| 336 | await db.put('companies',{id:company,name:'Existing account hierarchy'}); |
| 337 | Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'}; |
| 338 | CompanyService.activeCompanyId=company; |
| 339 | await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'}); |
| 340 | await accounts.seedDefaultChart(); |
| 341 | const existing=await accounts.addAccount({code:'101001',name:'صندوق متصل قبلی', |
| 342 | level:'subsidiary',parentCode:'101',type:'asset'}); |
| 343 | await db.put('treasury',{id:'cash-existing',companyId:company,recordType:'account', |
| 344 | name:'صندوق قبلی',isActive:true,isDefault:true,initialBalance:0,ledgerAccountId:existing.id}); |
| 345 | assert.deepEqual(await retail.activate(),{enabled:true}); |
| 346 | assert.equal((await retail.activate()).alreadyEnabled,true); |
| 347 | const cashParent=(await accounts.listAccounts()).find(x=>x.code==='101'); |
| 348 | assert.equal(cashParent.postable,false); |
| 349 | const cash=(await db.get('treasury','cash-existing')); |
| 350 | assert.equal(cash.ledgerAccountId,existing.id); |
| 351 | assert.equal((await accounts.listAccounts()).filter(a=>a.parentCode==='101').length,1); |
| 352 | await db.put('products',{id:'product-1',companyId:company,trackInventory:true,name:'کالا'}); |
| 353 | await db.put('contacts',{id:'contact-1',companyId:company,name:'مشتری'}); |
| 354 | await purchase10(); |
| 355 | const sale=await sale3({paidAmount:200}); |
| 356 | assert.equal(sale.paidAmount,200); |
| 357 | const lines=await db.getAll('journal_lines'); |
| 358 | assert.ok(lines.some(l=>l.accountId===existing.id&&l.debit===200)); |
| 359 | const totals=(await accounts.trialBalance()).totals; |
| 360 | assert.equal(totals.debit,totals.credit); |
| 361 | }); |
| 362 | test('regression: non-postable 101 with other children creates valid mapped cash subledger',async()=>{ |
| 363 | await db.clearAll(); |
| 364 | await db.put('companies',{id:company,name:'Previous chart'}); |
| 365 | Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'}; |
| 366 | CompanyService.activeCompanyId=company; |
| 367 | await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'}); |
| 368 | await accounts.seedDefaultChart(); |
| 369 | await accounts.addAccount({code:'101001',name:'صندوق فرعی قدیمی', |
| 370 | level:'subsidiary',parentCode:'101',type:'asset'}); |
| 371 | const cashParent=(await accounts.listAccounts()).find(x=>x.code==='101'); |
| 372 | await db.put('account_chart',{...cashParent,postable:false}); |
| 373 | assert.deepEqual(await retail.activate(),{enabled:true}); |
| 374 | const cashAccounts=(await db.getAll('treasury')).filter(x=>x.companyId===company&&x.recordType==='account'); |
| 375 | assert.equal(cashAccounts.length,1); |
| 376 | const ledger=(await accounts.listAccounts()).find(x=>x.id===cashAccounts[0].ledgerAccountId); |
| 377 | assert.equal(ledger.parentCode,'101'); |
| 378 | assert.notEqual(ledger.code,'101001'); |
| 379 | assert.equal(ledger.active,true); |
| 380 | }); |
| 381 | |
| 382 | test('A01: sales and purchase returns cannot silently refund or collect cash', async () => { |
| 383 | await setup(); |
| 384 | const purchased = await purchase10(); |
| 385 | const sold = await sale3({ paidAmount: 200 }); |
| 386 | const original = { |
| 387 | invoices: (await db.getAll('invoices')).length, |
| 388 | treasury: (await db.getAll('treasury')).length, |
| 389 | journals: (await db.getAll('journal_entries')).length, |
| 390 | stock: (await db.getAll('stock_movements')).length, |
| 391 | settlements: (await db.getAll('settlements')).length |
| 392 | }; |
| 393 | for (const draft of [ |
| 394 | invoice('sale_return', 1, 200, { originalInvoiceId: sold.id, paidAmount: 100 }), |
| 395 | invoice('purchase_return', 1, 100, { originalInvoiceId: purchased.id, paidAmount: 100 }) |
| 396 | ]) { |
| 397 | await assert.rejects(retail.issueInvoice(draft), /سند مستقل خزانه/); |
| 398 | assert.equal(await db.get('invoices', draft.id), undefined); |
| 399 | assert.equal((await db.getAll('invoices')).length, original.invoices); |
| 400 | assert.equal((await db.getAll('treasury')).length, original.treasury); |
| 401 | assert.equal((await db.getAll('journal_entries')).length, original.journals); |
| 402 | assert.equal((await db.getAll('stock_movements')).length, original.stock); |
| 403 | assert.equal((await db.getAll('settlements')).length, original.settlements); |
| 404 | } |
| 405 | }); |
| 406 | |
| 407 | test('A01/A03: a referenced customer return creates one atomic correction and correlated audit record', async () => { |
| 408 | await setup(); |
| 409 | await purchase10(); |
| 410 | const sold = await sale3({ paidAmount: 200 }); |
| 411 | const returned = await retail.issueInvoice(invoice('sale_return', 1, 200, { |
| 412 | originalInvoiceId: sold.id |
| 413 | })); |
| 414 | const corrections = await db.getAll('document_corrections'); |
| 415 | assert.equal(corrections.length, 1); |
| 416 | const correction = corrections[0]; |
| 417 | assert.equal(correction.companyId, company); |
| 418 | assert.equal(correction.sourceId, sold.id); |
| 419 | assert.equal(correction.resultId, returned.id); |
| 420 | assert.equal(correction.correctionType, 'return'); |
| 421 | assert.equal(correction.reasonCode, 'customer_return'); |
| 422 | assert.equal(correction.actorId, 'phase2-admin'); |
| 423 | assert.ok(correction.idempotencyKey.includes(returned.id)); |
| 424 | const audits = await db.getAll('audit_events'); |
| 425 | assert.ok(audits.some(a => a.sourceId === returned.journalId && |
| 426 | a.correlationId === correction.correlationId && |
| 427 | a.eventType === 'commercial_journal_posted')); |
| 428 | assert.equal((await db.get('invoices', sold.id)).grandTotal, 600); |
| 429 | assert.equal((await db.get('invoices', sold.id)).paidAmount, 200); |
| 430 | assert.equal((await db.getAll('settlements')).length, 1); |
| 431 | assert.equal((await db.getAll('stock_movements')).filter(x => x.refId === returned.id).length, 1); |
| 432 | await assert.rejects(retail.issueInvoice(invoice('sale_return', 3, 200, { |
| 433 | originalInvoiceId: sold.id |
| 434 | })), /بیشتر/); |
| 435 | assert.equal((await db.getAll('document_corrections')).length, 1); |
| 436 | }); |
| 437 | |
| 438 | test('A01: customer returns reject non-posted legacy origin without partial writes', async () => { |
| 439 | await setup(); |
| 440 | await purchase10(); |
| 441 | await db.put('invoices', { |
| 442 | id: 'old-unposted', companyId: company, kind: 'sale', |
| 443 | financePosted: false, isPreInvoice: false, |
| 444 | contactId: 'contact-1', items: [{ |
| 445 | productId: 'product-1', qty: 2, price: 200, |
| 446 | lineTotal: 400, lineSubtotal: 400 |
| 447 | }], |
| 448 | grandTotal: 400, subtotal: 400, totalDiscount: 0, vatAmount: 0, number: 'legacy' |
| 449 | }); |
| 450 | const countBefore = (await db.getAll('journal_entries')).length; |
| 451 | const target = invoice('sale_return', 1, 200, { originalInvoiceId: 'old-unposted' }); |
| 452 | await assert.rejects(retail.issueInvoice(target), /سازگار نیست/); |
| 453 | assert.equal(await db.get('invoices', target.id), undefined); |
| 454 | assert.equal((await db.getAll('journal_entries')).length, countBefore); |
| 455 | assert.equal((await db.getAll('document_corrections')).length, 0); |
| 456 | }); |
| 457 | |
| 458 | test('A01: inflated return price cannot credit more than the original sale total', async () => { |
| 459 | await setup(); |
| 460 | await purchase10(); |
| 461 | const original = await sale3({ paidAmount: 200 }); |
| 462 | const before = { |
| 463 | stock: await db.getAll('stock_movements'), |
| 464 | journals: await db.getAll('journal_entries'), |
| 465 | settlements: await db.getAll('settlements'), |
| 466 | invoices: await db.getAll('invoices') |
| 467 | }; |
| 468 | const inflated = invoice('sale_return', 1, 650, { originalInvoiceId: original.id }); |
| 469 | await assert.rejects(retail.issueInvoice(inflated), /مجموع مبلغ مرجوعی/); |
| 470 | assert.deepEqual(await db.getAll('stock_movements'), before.stock); |
| 471 | assert.deepEqual(await db.getAll('journal_entries'), before.journals); |
| 472 | assert.deepEqual(await db.getAll('settlements'), before.settlements); |
| 473 | assert.deepEqual(await db.getAll('invoices'), before.invoices); |
| 474 | }); |
| 475 | |
| 476 | test('A01: successive returns cannot exceed original gross even if total quantities fit', async () => { |
| 477 | await setup(); |
| 478 | await purchase10(); |
| 479 | const original = await sale3(); |
| 480 | await retail.issueInvoice(invoice('sale_return', 1, 400, { |
| 481 | originalInvoiceId: original.id |
| 482 | })); |
| 483 | const excessive = invoice('sale_return', 1, 300, { originalInvoiceId: original.id }); |
| 484 | await assert.rejects(retail.issueInvoice(excessive), /مجموع مبلغ مرجوعی/); |
| 485 | assert.equal((await db.getAll('document_corrections')).length, 1); |
| 486 | }); |
| 487 | |
| 488 | test('A05: inactive treasury accounts reject transfers, expenses and cheque clearance atomically',async()=>{ |
| 489 | await setup();await purchase10();await sale3(); |
| 490 | const active=await db.get('treasury','cash-1'); |
| 491 | const second=await retail.createTreasuryAccount({ |
| 492 | id:'disabled-a05',companyId:company,recordType:'account', |
| 493 | type:'bank',name:'بانک مسدود',ownerUserId:'phase2-admin', |
| 494 | initialBalance:0,isActive:true,isDefault:false |
| 495 | }); |
| 496 | await db.put('treasury',{...second,isActive:false}); |
| 497 | const count=(name)=>db.getAll(name).then(rows=>rows.length); |
| 498 | const before={journals:await count('journal_entries'),money:await count('treasury')}; |
| 499 | for(const [id,fromAccountId,toAccountId] of [ |
| 500 | ['disabled-transfer-to',active.id,second.id], |
| 501 | ['disabled-transfer-from',second.id,active.id] |
| 502 | ]){ |
| 503 | await assert.rejects(retail.postTransaction({ |
| 504 | id,type:'transfer',date,amount:45,fromAccountId,toAccountId |
| 505 | }),/غیرفعال/); |
| 506 | assert.equal(await db.get('treasury',id),undefined); |
| 507 | } |
| 508 | assert.equal(await count('journal_entries'),before.journals); |
| 509 | assert.equal(await count('treasury'),before.money); |
| 510 | await db.put('treasury',{...active,isActive:false}); |
| 511 | await assert.rejects(retail.postExpense({ |
| 512 | id:'disabled-expense',kind:'expense',date,amount:60,method:'cash',category:'تست' |
| 513 | }),/صندوق یا بانک/); |
| 514 | assert.equal(await db.get('expenses','disabled-expense'),undefined); |
| 515 | await db.put('treasury',active); |
| 516 | const cheque=await retail.postCheque({ |
| 517 | id:'disabled-cheque',direction:'inbound',status:'pending', |
| 518 | issueDate:date,dueDate:date,contactId:'contact-1',amount:120, |
| 519 | chequeNumber:'A05' |
| 520 | }); |
| 521 | const preClear=await count('journal_entries'); |
| 522 | await assert.rejects(retail.changeChequeStatus(cheque.id,'cleared',{ |
| 523 | date,accountId:second.id,explicitlyApproved:true |
| 524 | }),/فعال نیست/); |
| 525 | assert.equal((await db.get('cheques',cheque.id)).status,'pending'); |
| 526 | assert.equal(await count('journal_entries'),preClear); |
| 527 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===cheque.id).length,0); |
| 528 | const cleared=await retail.changeChequeStatus(cheque.id,'cleared',{ |
| 529 | date,accountId:active.id,explicitlyApproved:true |
| 530 | }); |
| 531 | assert.equal(cleared.status,'cleared'); |
| 532 | await assert.rejects(retail.changeChequeStatus(cheque.id,'cleared',{ |
| 533 | date,accountId:active.id |
| 534 | }),/در جریان/); |
| 535 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===cheque.id).length,1); |
| 536 | const balance=await accounts.trialBalance(); |
| 537 | assert.equal(balance.totals.debit,balance.totals.credit); |
| 538 | }); |
| 539 | |
| 540 | test('A01: a return offsets receivables before any cash refund and caps later receipts to net amount',async()=>{ |
| 541 | await setup();await purchase10(); |
| 542 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:200})); |
| 543 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 544 | originalInvoiceId:sold.id |
| 545 | })); |
| 546 | const before=(await db.getAll('journal_entries')).length; |
| 547 | await assert.rejects(retail.postTransaction({ |
| 548 | id:'a01-invalid-refund',type:'payment',date,amount:1, |
| 549 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 550 | reasonCode:'goods_return',explicitlyApproved:true |
| 551 | }),/بازپرداخت مجاز/); |
| 552 | await assert.rejects(retail.postTransaction({ |
| 553 | id:'a01-overcollect',type:'receipt',date,amount:201, |
| 554 | refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1' |
| 555 | }),/مانده خالص/); |
| 556 | assert.equal((await db.getAll('journal_entries')).length,before); |
| 557 | assert.equal(await db.get('treasury','a01-invalid-refund'),undefined); |
| 558 | assert.equal(await db.get('treasury','a01-overcollect'),undefined); |
| 559 | const receipt=await retail.postTransaction({ |
| 560 | id:'a01-valid-remaining',type:'receipt',date,amount:200, |
| 561 | refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1' |
| 562 | }); |
| 563 | assert.equal(receipt.amount,200); |
| 564 | assert.equal((await db.get('invoices',sold.id)).paidAmount,400); |
| 565 | await assert.rejects(retail.postTransaction({ |
| 566 | id:'a01-extra-collection',type:'receipt',date,amount:1, |
| 567 | refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1' |
| 568 | }),/مانده خالص/); |
| 569 | const trial=await accounts.trialBalance(); |
| 570 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 571 | }); |
| 572 | |
| 573 | test('A01: only genuinely paid customer credit may be refunded, once, even with concurrent requests',async()=>{ |
| 574 | await setup();await purchase10(); |
| 575 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500})); |
| 576 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 577 | originalInvoiceId:sold.id |
| 578 | })); |
| 579 | const attempts=await Promise.allSettled([ |
| 580 | retail.postTransaction({id:'refund-a',type:'payment',date,amount:70, |
| 581 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 582 | reasonCode:'goods_return',explicitlyApproved:true}), |
| 583 | retail.postTransaction({id:'refund-b',type:'payment',date,amount:70, |
| 584 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 585 | reasonCode:'goods_return',explicitlyApproved:true}) |
| 586 | ]); |
| 587 | assert.equal(attempts.filter(x=>x.status==='fulfilled').length,1); |
| 588 | assert.equal(attempts.filter(x=>x.status==='rejected').length,1); |
| 589 | assert.equal((await db.get('invoices',returned.id)).paidAmount,70); |
| 590 | const finish=await retail.postTransaction({ |
| 591 | id:'refund-final',type:'payment',date,amount:30, |
| 592 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 593 | reasonCode:'goods_return',explicitlyApproved:true |
| 594 | }); |
| 595 | assert.equal(finish.amount,30); |
| 596 | await assert.rejects(retail.postTransaction({ |
| 597 | id:'refund-excess',type:'payment',date,amount:1, |
| 598 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 599 | reasonCode:'goods_return',explicitlyApproved:true |
| 600 | }),/بازپرداخت مجاز/); |
| 601 | assert.equal((await db.get('invoices',returned.id)).paidAmount,100); |
| 602 | assert.equal((await db.getAll('treasury')).filter(t=> |
| 603 | t.refInvoiceId===returned.id&&t.recordType==='transaction').length,2); |
| 604 | const balance=await accounts.trialBalance(); |
| 605 | assert.equal(balance.totals.debit,balance.totals.credit); |
| 606 | }); |
| 607 | |
| 608 | test('A01: customer credit refund requires administrator and rejected attempt leaves no writes',async()=>{ |
| 609 | await setup();await purchase10(); |
| 610 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500})); |
| 611 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 612 | originalInvoiceId:sold.id |
| 613 | })); |
| 614 | const beforeJournals=(await db.getAll('journal_entries')).length; |
| 615 | const beforeAudits=(await db.getAll('audit_events')).length; |
| 616 | Auth.currentUser={id:'phase2-clerk',role:'user',username:'clerk',companyIds:[company]}; |
| 617 | await assert.rejects(retail.postTransaction({ |
| 618 | id:'unauthorized-return-refund',type:'payment',date,amount:25, |
| 619 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 620 | reasonCode:'goods_return',explicitlyApproved:true |
| 621 | }),/فقط توسط مدیر/); |
| 622 | assert.equal(await db.get('treasury','unauthorized-return-refund'),undefined); |
| 623 | assert.equal((await db.get('invoices',returned.id)).paidAmount,0); |
| 624 | assert.equal((await db.getAll('journal_entries')).length,beforeJournals); |
| 625 | assert.equal((await db.getAll('audit_events')).length,beforeAudits); |
| 626 | Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'}; |
| 627 | const approved=await retail.postTransaction({ |
| 628 | id:'approved-return-refund',type:'payment',date,amount:25, |
| 629 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 630 | reasonCode:'goods_return',explicitlyApproved:true |
| 631 | }); |
| 632 | assert.equal(approved.amount,25); |
| 633 | assert.equal((await db.get('invoices',returned.id)).paidAmount,25); |
| 634 | const trial=await accounts.trialBalance(); |
| 635 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 636 | }); |
| 637 | |
| 638 | test('A01: supplier cash recovery cannot exceed previously paid credit after purchase return',async()=>{ |
| 639 | await setup(); |
| 640 | const purchased=await retail.issueInvoice(invoice('purchase',10,100,{paidAmount:700})); |
| 641 | const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{ |
| 642 | originalInvoiceId:purchased.id |
| 643 | })); |
| 644 | await assert.rejects(retail.postTransaction({ |
| 645 | id:'supplier-refund-over',type:'receipt',date,amount:101, |
| 646 | refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1', |
| 647 | reasonCode:'goods_return',explicitlyApproved:true |
| 648 | }),/بازپرداخت مجاز/); |
| 649 | const cash=await retail.postTransaction({ |
| 650 | id:'supplier-refund-valid',type:'receipt',date,amount:100, |
| 651 | refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1', |
| 652 | reasonCode:'goods_return',explicitlyApproved:true |
| 653 | }); |
| 654 | assert.equal(cash.amount,100); |
| 655 | await assert.rejects(retail.postTransaction({ |
| 656 | id:'supplier-refund-excess',type:'receipt',date,amount:1, |
| 657 | refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1', |
| 658 | reasonCode:'goods_return',explicitlyApproved:true |
| 659 | }),/بازپرداخت مجاز/); |
| 660 | const trial=await accounts.trialBalance(); |
| 661 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 662 | }); |
| 663 | |
| 664 | test('A01: authorized customer credit refund creates one linked correction, settlement and audit atomically',async()=>{ |
| 665 | await setup();await purchase10(); |
| 666 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500})); |
| 667 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 668 | originalInvoiceId:sold.id |
| 669 | })); |
| 670 | const before=(await db.getAll('document_corrections')).length; |
| 671 | const refund=await retail.postTransaction({ |
| 672 | id:'a01-refund-trace',type:'payment',date,amount:100, |
| 673 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 674 | reasonCode:'goods_return',explicitlyApproved:true |
| 675 | }); |
| 676 | const records=(await db.getAll('document_corrections')).filter(c=> |
| 677 | c.correctionType==='settlement_refund'); |
| 678 | assert.equal((await db.getAll('document_corrections')).length,before+1); |
| 679 | assert.equal(records.length,1); |
| 680 | assert.equal(records[0].sourceId,returned.id); |
| 681 | assert.equal(records[0].resultType,'treasury'); |
| 682 | assert.equal(records[0].resultId,refund.id); |
| 683 | assert.equal(records[0].correlationId,refund.journalId); |
| 684 | assert.equal(records[0].reasonCode,'goods_return'); |
| 685 | assert.equal(records[0].actionCode,'customer_credit_refund'); |
| 686 | assert.equal(records[0].approvedBy,'phase2-admin'); |
| 687 | assert.equal(records[0].approvalMethod,'explicit_confirmation'); |
| 688 | assert.ok(records[0].approvedAtUtc); |
| 689 | assert.equal(records[0].amount,100); |
| 690 | assert.equal(records[0].actorId,'phase2-admin'); |
| 691 | assert.equal((await db.getAll('settlements')).filter(s=> |
| 692 | s.transactionId===refund.id&&s.invoiceId===returned.id).length,1); |
| 693 | const audit=(await db.getAll('audit_events')).find(a=> |
| 694 | a.sourceId===refund.journalId&&a.correlationId===records[0].correlationId); |
| 695 | assert.ok(audit); |
| 696 | await assert.rejects(retail.postTransaction({ |
| 697 | id:refund.id,type:'payment',date,amount:100, |
| 698 | refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1', |
| 699 | reasonCode:'goods_return',explicitlyApproved:true |
| 700 | }),/تکراری/); |
| 701 | assert.equal((await db.getAll('document_corrections')).length,before+1); |
| 702 | assert.equal((await db.get('invoices',sold.id)).paidAmount,500); |
| 703 | assert.equal((await db.get('invoices',returned.id)).paidAmount,100); |
| 704 | const trial=await accounts.trialBalance(); |
| 705 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 706 | }); |
| 707 | |
| 708 | test('A01: supplier recovery trace is linked; rejected over-recovery adds no correction',async()=>{ |
| 709 | await setup(); |
| 710 | const purchased=await retail.issueInvoice(invoice('purchase',10,100,{paidAmount:700})); |
| 711 | const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{ |
| 712 | originalInvoiceId:purchased.id |
| 713 | })); |
| 714 | const base=(await db.getAll('document_corrections')).length; |
| 715 | await assert.rejects(retail.postTransaction({ |
| 716 | id:'a01-supplier-over',type:'receipt',date,amount:101, |
| 717 | refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1', |
| 718 | reasonCode:'goods_return',explicitlyApproved:true |
| 719 | }),/بازپرداخت مجاز/); |
| 720 | assert.equal((await db.getAll('document_corrections')).length,base); |
| 721 | assert.equal(await db.get('treasury','a01-supplier-over'),undefined); |
| 722 | const recovered=await retail.postTransaction({ |
| 723 | id:'a01-supplier-trace',type:'receipt',date,amount:100, |
| 724 | refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1', |
| 725 | reasonCode:'goods_return',explicitlyApproved:true |
| 726 | }); |
| 727 | const records=(await db.getAll('document_corrections')).filter(c=> |
| 728 | c.correctionType==='settlement_refund'); |
| 729 | assert.equal(records.length,1); |
| 730 | assert.equal(records[0].sourceId,returned.id); |
| 731 | assert.equal(records[0].resultId,recovered.id); |
| 732 | assert.equal(records[0].correlationId,recovered.journalId); |
| 733 | assert.equal(records[0].reasonCode,'goods_return'); |
| 734 | assert.equal(records[0].actionCode,'supplier_credit_recovery'); |
| 735 | assert.equal(records[0].approvedBy,'phase2-admin'); |
| 736 | assert.equal(records[0].amount,100); |
| 737 | assert.equal((await db.get('invoices',purchased.id)).paidAmount,700); |
| 738 | const trial=await accounts.trialBalance(); |
| 739 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 740 | }); |
| 741 | |
| 742 | test('A01: late correction idempotency collision rolls back cash, journal, settlement and audit',async()=>{ |
| 743 | await setup();await purchase10(); |
| 744 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500})); |
| 745 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 746 | originalInvoiceId:sold.id |
| 747 | })); |
| 748 | const id='a01-late-correction-conflict'; |
| 749 | // Fixture simulates an existing append-only correction key independently of |
| 750 | // the treasury ID; the UNIQUE constraint must abort the entire later write. |
| 751 | await db.transaction('document_corrections',async tx=>{ |
| 752 | await tx.add('document_corrections',{ |
| 753 | id:'a01-existing-conflict',companyId:company, |
| 754 | sourceType:'invoice',sourceId:returned.id, |
| 755 | correctionType:'settlement_refund',resultType:'treasury',resultId:'historical', |
| 756 | idempotencyKey:JSON.stringify([company,'settlement_refund',id]) |
| 757 | }); |
| 758 | }); |
| 759 | const before={ |
| 760 | journals:(await db.getAll('journal_entries')).length, |
| 761 | audits:(await db.getAll('audit_events')).length, |
| 762 | settlements:(await db.getAll('settlements')).length, |
| 763 | corrections:(await db.getAll('document_corrections')).length |
| 764 | }; |
| 765 | await assert.rejects(retail.postTransaction({ |
| 766 | id,type:'payment',date,amount:100,refInvoiceId:returned.id, |
| 767 | contactId:'contact-1',fromAccountId:'cash-1' |
| 768 | })); |
| 769 | assert.equal(await db.get('treasury',id),undefined); |
| 770 | assert.equal((await db.get('invoices',returned.id)).paidAmount,0); |
| 771 | assert.equal((await db.getAll('journal_entries')).length,before.journals); |
| 772 | assert.equal((await db.getAll('audit_events')).length,before.audits); |
| 773 | assert.equal((await db.getAll('settlements')).length,before.settlements); |
| 774 | assert.equal((await db.getAll('document_corrections')).length,before.corrections); |
| 775 | const trial=await accounts.trialBalance(); |
| 776 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 777 | }); |
| 778 | |
| 779 | test('A01: return cash flow requires structured reason and explicit approval before writes',async()=>{ |
| 780 | await setup();await purchase10(); |
| 781 | const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500})); |
| 782 | const returned=await retail.issueInvoice(invoice('sale_return',1,200,{ |
| 783 | originalInvoiceId:sold.id |
| 784 | })); |
| 785 | const before={ |
| 786 | treasury:(await db.getAll('treasury')).length, |
| 787 | journals:(await db.getAll('journal_entries')).length, |
| 788 | audit:(await db.getAll('audit_events')).length, |
| 789 | corrections:(await db.getAll('document_corrections')).length, |
| 790 | settlements:(await db.getAll('settlements')).length |
| 791 | }; |
| 792 | const base={ |
| 793 | type:'payment',date,amount:50,refInvoiceId:returned.id, |
| 794 | contactId:'contact-1',fromAccountId:'cash-1' |
| 795 | }; |
| 796 | await assert.rejects(retail.postTransaction({ |
| 797 | ...base,id:'no-reason',explicitlyApproved:true |
| 798 | }),/دلیل ساختاریافته/); |
| 799 | await assert.rejects(retail.postTransaction({ |
| 800 | ...base,id:'invalid-reason',reasonCode:'unauthorized-text',explicitlyApproved:true |
| 801 | }),/دلیل ساختاریافته/); |
| 802 | await assert.rejects(retail.postTransaction({ |
| 803 | ...base,id:'unconfirmed',reasonCode:'quality_issue' |
| 804 | }),/تأیید صریح/); |
| 805 | await assert.rejects(retail.postTransaction({ |
| 806 | ...base,id:'wrong-confirmation',reasonCode:'quality_issue',explicitlyApproved:'true' |
| 807 | }),/تأیید صریح/); |
| 808 | for(const id of ['no-reason','invalid-reason','unconfirmed','wrong-confirmation']){ |
| 809 | assert.equal(await db.get('treasury',id),undefined); |
| 810 | } |
| 811 | assert.equal((await db.get('invoices',returned.id)).paidAmount,0); |
| 812 | assert.deepEqual({ |
| 813 | treasury:(await db.getAll('treasury')).length, |
| 814 | journals:(await db.getAll('journal_entries')).length, |
| 815 | audit:(await db.getAll('audit_events')).length, |
| 816 | corrections:(await db.getAll('document_corrections')).length, |
| 817 | settlements:(await db.getAll('settlements')).length |
| 818 | },before); |
| 819 | const approved=await retail.postTransaction({ |
| 820 | ...base,id:'approved-reason',reasonCode:'quality_issue',explicitlyApproved:true |
| 821 | }); |
| 822 | const correction=(await db.getAll('document_corrections')).find(x=> |
| 823 | x.resultId===approved.id); |
| 824 | assert.equal(correction?.reasonCode,'quality_issue'); |
| 825 | assert.equal(correction?.actionCode,'customer_credit_refund'); |
| 826 | assert.equal(correction?.approvedBy,'phase2-admin'); |
| 827 | assert.equal(correction?.approvalMethod,'explicit_confirmation'); |
| 828 | assert.equal((await accounts.trialBalance()).totals.debit, |
| 829 | (await accounts.trialBalance()).totals.credit); |
| 830 | }); |
| 831 | |
| 832 | test('A01: cheque status uses selected open-period posting date after its due-date period closes',async()=>{ |
| 833 | const {period}=await setup(); |
| 834 | const issued=await retail.postCheque({ |
| 835 | id:'a01-cheque-carry',direction:'inbound',status:'pending', |
| 836 | issueDate:date,dueDate:date,contactId:'contact-1', |
| 837 | amount:250,chequeNumber:'A01-CARRY' |
| 838 | }); |
| 839 | const before={ |
| 840 | journals:(await db.getAll('journal_entries')).length, |
| 841 | audits:(await db.getAll('audit_events')).length, |
| 842 | cash:(await db.getAll('treasury')).filter(x=>x.refChequeId===issued.id).length |
| 843 | }; |
| 844 | await assert.rejects(retail.changeChequeStatus(issued.id,'cleared',{ |
| 845 | date:'1405/07/17',accountId:'cash-1',explicitlyApproved:true |
| 846 | }),/پیش از تاریخ صدور/); |
| 847 | await assert.rejects(retail.changeChequeStatus(issued.id,'cleared',{ |
| 848 | date:'',accountId:'cash-1',explicitlyApproved:true |
| 849 | }),/تاریخ شمسی/); |
| 850 | assert.equal((await db.getAll('journal_entries')).length,before.journals); |
| 851 | assert.equal((await db.getAll('audit_events')).length,before.audits); |
| 852 | assert.equal((await db.get('cheques',issued.id)).status,'pending'); |
| 853 | await accounts.closePeriod(period.id); |
| 854 | const newPeriod=await accounts.createPeriod({ |
| 855 | name:'۱۴۰۶',startDate:'1406/01/01',endDate:'1406/12/29' |
| 856 | }); |
| 857 | const beforeClosedAttempt={ |
| 858 | journals:(await db.getAll('journal_entries')).length, |
| 859 | audits:(await db.getAll('audit_events')).length |
| 860 | }; |
| 861 | await assert.rejects(retail.changeChequeStatus(issued.id,'cleared',{ |
| 862 | date,accountId:'cash-1',explicitlyApproved:true |
| 863 | }),/دوره مالی باز/); |
| 864 | assert.equal((await db.getAll('journal_entries')).length,beforeClosedAttempt.journals); |
| 865 | assert.equal((await db.getAll('audit_events')).length,beforeClosedAttempt.audits); |
| 866 | assert.equal((await db.get('cheques',issued.id)).status,'pending'); |
| 867 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===issued.id).length,0); |
| 868 | |
| 869 | // Exercise the real controller forwarding, not only the retail service. |
| 870 | const { ChequeController }=await import('../src/controllers/ChequeController.js'); |
| 871 | const eventDate='1406/01/05'; |
| 872 | const settled=await ChequeController.changeStatus(issued.id,'cleared',{ |
| 873 | date:eventDate,accountId:'cash-1',explicitlyApproved:true |
| 874 | }); |
| 875 | assert.equal(settled.status,'cleared'); |
| 876 | assert.equal(settled.dueDate,date); |
| 877 | assert.equal(settled.issueDate,date); |
| 878 | assert.equal(settled.statusBusinessDate,eventDate); |
| 879 | const statusJournal=await db.get('journal_entries',settled.statusJournalId); |
| 880 | assert.equal(statusJournal.date,eventDate); |
| 881 | assert.equal(statusJournal.periodId,newPeriod.id); |
| 882 | const cash=(await db.getAll('treasury')).filter(x=>x.refChequeId===issued.id); |
| 883 | assert.equal(cash.length,1); |
| 884 | assert.equal(cash[0].date,eventDate); |
| 885 | assert.equal(cash[0].journalId,statusJournal.id); |
| 886 | const receipt=(await db.getAll('audit_events')).filter(x=> |
| 887 | x.correlationId===statusJournal.id&&x.sourceId===statusJournal.id); |
| 888 | assert.equal(receipt.length,1); |
| 889 | assert.equal(receipt[0].businessDate,eventDate); |
| 890 | await assert.rejects(ChequeController.changeStatus(issued.id,'cleared',{ |
| 891 | date:eventDate,accountId:'cash-1' |
| 892 | }),/در جریان/); |
| 893 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===issued.id).length,1); |
| 894 | const trial=await accounts.trialBalance(); |
| 895 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 896 | }); |
| 897 | |
| 898 | test('A01: outbound bounced cheque in later open period reverses without cash posting',async()=>{ |
| 899 | const {period}=await setup(); |
| 900 | const outgoing=await retail.postCheque({ |
| 901 | id:'a01-cheque-outgoing',direction:'outbound',status:'pending', |
| 902 | issueDate:date,dueDate:date,contactId:'contact-1', |
| 903 | amount:120,chequeNumber:'A01-OUT' |
| 904 | }); |
| 905 | await accounts.closePeriod(period.id); |
| 906 | const next=await accounts.createPeriod({ |
| 907 | name:'۱۴۰۶',startDate:'1406/01/01',endDate:'1406/12/29' |
| 908 | }); |
| 909 | const settled=await retail.changeChequeStatus(outgoing.id,'bounced',{ |
| 910 | date:'1406/01/09' |
| 911 | }); |
| 912 | assert.equal(settled.status,'bounced'); |
| 913 | assert.equal(settled.dueDate,date); |
| 914 | assert.equal(settled.statusBusinessDate,'1406/01/09'); |
| 915 | const journal=await db.get('journal_entries',settled.statusJournalId); |
| 916 | assert.equal(journal.periodId,next.id); |
| 917 | assert.equal(journal.date,'1406/01/09'); |
| 918 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===outgoing.id).length,0); |
| 919 | await assert.rejects(retail.changeChequeStatus(outgoing.id,'cleared',{ |
| 920 | date:'1406/01/09' |
| 921 | }),/در جریان/); |
| 922 | const trial=await accounts.trialBalance(); |
| 923 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 924 | }); |
| 925 | |
| 926 | test('A01: cheque endorsement requires third-party identity and explicit confirmation before posting',async()=>{ |
| 927 | await setup(); |
| 928 | const id='a01-endorsement-identity'; |
| 929 | await db.put('contacts',{id:'endorsee-1',companyId:company,name:'تأمینکننده دریافتکننده'}); |
| 930 | await db.put('contacts',{id:'other-company-contact',companyId:'other-company',name:'خارج از شرکت'}); |
| 931 | const cheque=await retail.postCheque({ |
| 932 | id,direction:'inbound',status:'pending',issueDate:date,dueDate:date, |
| 933 | contactId:'contact-1',amount:370,chequeNumber:'E370' |
| 934 | }); |
| 935 | const snapshot=async()=>({ |
| 936 | cheque:await db.get('cheques',id), |
| 937 | journals:(await db.getAll('journal_entries')).length, |
| 938 | lines:(await db.getAll('journal_lines')).length, |
| 939 | audit:(await db.getAll('audit_events')).length, |
| 940 | corrections:(await db.getAll('document_corrections')).length, |
| 941 | cash:(await db.getAll('treasury')).filter(x=>x.refChequeId===id).length |
| 942 | }); |
| 943 | const baseline=await snapshot(); |
| 944 | for(const options of [ |
| 945 | {date}, {date,endorseeContactId:''}, |
| 946 | {date,endorseeContactId:'contact-1',explicitlyApproved:true}, |
| 947 | {date,endorseeContactId:'not-existent',explicitlyApproved:true}, |
| 948 | {date,endorseeContactId:'other-company-contact',explicitlyApproved:true}, |
| 949 | {date,endorseeContactId:'endorsee-1'}, |
| 950 | {date,endorseeContactId:'endorsee-1',explicitlyApproved:'true'}, |
| 951 | {date,endorseeContactId:'endorsee-1',explicitlyApproved:false} |
| 952 | ]){ |
| 953 | await assert.rejects(retail.changeChequeStatus(id,'spent',options), |
| 954 | /دریافتکننده|واگذاری|تأیید/); |
| 955 | assert.deepEqual(await snapshot(),baseline,'Rejected endorsement mutated financial data'); |
| 956 | } |
| 957 | const approved=await retail.changeChequeStatus(id,'spent',{ |
| 958 | date,endorseeContactId:'endorsee-1',explicitlyApproved:true |
| 959 | }); |
| 960 | assert.equal(approved.status,'spent'); |
| 961 | assert.equal(approved.endorseeContactId,'endorsee-1'); |
| 962 | assert.equal(approved.endorseeContactName,'تأمینکننده دریافتکننده'); |
| 963 | assert.equal(approved.endorsementApprovedBy,'phase2-admin'); |
| 964 | assert.equal(approved.statusBusinessDate,date); |
| 965 | const statusJournal=await db.get('journal_entries',approved.statusJournalId); |
| 966 | const journalLines=(await db.getAll('journal_lines')) |
| 967 | .filter(x=>x.journalId===statusJournal.id); |
| 968 | const payable=(await db.getAll('account_chart')).find(x=>x.companyId===company&&x.code==='201'); |
| 969 | const incoming=(await db.getAll('account_chart')).find(x=>x.companyId===company&&x.code==='105'); |
| 970 | assert.ok(payable&&incoming); |
| 971 | assert.deepEqual(journalLines.sort((a,b)=>b.debit-a.debit).map(x=>({ |
| 972 | accountId:x.accountId,debit:x.debit,credit:x.credit,contactId:x.contactId |
| 973 | })),[ |
| 974 | {accountId:payable.id,debit:370,credit:0,contactId:'endorsee-1'}, |
| 975 | {accountId:incoming.id,debit:0,credit:370,contactId:'contact-1'} |
| 976 | ]); |
| 977 | const correction=(await db.getAll('document_corrections')) |
| 978 | .find(x=>x.sourceType==='cheque'&&x.sourceId===id); |
| 979 | assert.equal(correction.correctionType,'endorsement'); |
| 980 | assert.equal(correction.endorseeContactId,'endorsee-1'); |
| 981 | assert.equal(correction.originalDrawerContactId,'contact-1'); |
| 982 | assert.equal(correction.correlationId,statusJournal.id); |
| 983 | assert.equal(correction.approvedBy,'phase2-admin'); |
| 984 | assert.equal(correction.amount,370); |
| 985 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===id).length,0); |
| 986 | const audit=(await db.getAll('audit_events')).filter(x=>x.correlationId===statusJournal.id); |
| 987 | assert.equal(audit.length,1); |
| 988 | const once=await snapshot(); |
| 989 | await assert.rejects(retail.changeChequeStatus(id,'spent',{ |
| 990 | date,endorseeContactId:'endorsee-1',explicitlyApproved:true |
| 991 | }),/در جریان/); |
| 992 | assert.deepEqual(await snapshot(),once); |
| 993 | const trial=await accounts.trialBalance(); |
| 994 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 995 | }); |
| 996 | |
| 997 | test('A01: duplicate endorsement correction key rolls back GL, status and audit atomically',async()=>{ |
| 998 | await setup(); |
| 999 | await db.put('contacts',{id:'endorsee-1',companyId:company,name:'تأمینکننده'}); |
| 1000 | const id='a01-endorsement-rollback'; |
| 1001 | await retail.postCheque({ |
| 1002 | id,direction:'inbound',status:'pending',issueDate:date,dueDate:date, |
| 1003 | contactId:'contact-1',amount:120,chequeNumber:'E120' |
| 1004 | }); |
| 1005 | const idem=JSON.stringify([company,'cheque_endorsement',id,2]); |
| 1006 | await db.transaction(['document_corrections'],async tx=>{ |
| 1007 | await tx.add('document_corrections',{ |
| 1008 | id:'collision-endorsement',companyId:company,sourceType:'cheque',sourceId:'fixture', |
| 1009 | correctionType:'endorsement',idempotencyKey:idem |
| 1010 | }); |
| 1011 | }); |
| 1012 | const before={ |
| 1013 | cheque:await db.get('cheques',id), |
| 1014 | journals:(await db.getAll('journal_entries')).length, |
| 1015 | lines:(await db.getAll('journal_lines')).length, |
| 1016 | audit:(await db.getAll('audit_events')).length, |
| 1017 | corrections:(await db.getAll('document_corrections')).length, |
| 1018 | cash:(await db.getAll('treasury')).length |
| 1019 | }; |
| 1020 | await assert.rejects(retail.changeChequeStatus(id,'spent',{ |
| 1021 | date,endorseeContactId:'endorsee-1',explicitlyApproved:true |
| 1022 | })); |
| 1023 | assert.deepEqual({ |
| 1024 | cheque:await db.get('cheques',id), |
| 1025 | journals:(await db.getAll('journal_entries')).length, |
| 1026 | lines:(await db.getAll('journal_lines')).length, |
| 1027 | audit:(await db.getAll('audit_events')).length, |
| 1028 | corrections:(await db.getAll('document_corrections')).length, |
| 1029 | cash:(await db.getAll('treasury')).length |
| 1030 | },before); |
| 1031 | const trial=await accounts.trialBalance(); |
| 1032 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 1033 | }); |
| 1034 | |
| 1035 | test('A01/A05: cheque cash clearing requires explicit active company account and confirmation',async()=>{ |
| 1036 | await setup(); |
| 1037 | const id='cheque-explicit-bank-a01'; |
| 1038 | const first=await retail.postCheque({id,issueDate:date,dueDate:date, |
| 1039 | direction:'inbound',status:'pending',contactId:'contact-1', |
| 1040 | amount:365,chequeNumber:'A01-BANK'}); |
| 1041 | const second=await retail.createTreasuryAccount({ |
| 1042 | id:'bank-a01',companyId:company,recordType:'account', |
| 1043 | type:'bank',name:'بانک مقصد',ownerUserId:'phase2-admin', |
| 1044 | initialBalance:0,isActive:true,isDefault:false |
| 1045 | }); |
| 1046 | const state=async()=>({ |
| 1047 | cheque:await db.get('cheques',id), |
| 1048 | journals:(await db.getAll('journal_entries')).length, |
| 1049 | lines:(await db.getAll('journal_lines')).length, |
| 1050 | audit:(await db.getAll('audit_events')).length, |
| 1051 | transactions:(await db.getAll('treasury')).filter(x=>x.refChequeId===id).length |
| 1052 | }); |
| 1053 | const before=await state(); |
| 1054 | for(const options of [ |
| 1055 | {date,explicitlyApproved:true}, |
| 1056 | {date,accountId:'',explicitlyApproved:true}, |
| 1057 | {date,accountId:second.id}, |
| 1058 | {date,accountId:second.id,explicitlyApproved:'true'}, |
| 1059 | {date,accountId:'nonexistent',explicitlyApproved:true}, |
| 1060 | {date,accountId:'cash-1',explicitlyApproved:false} |
| 1061 | ]){ |
| 1062 | await assert.rejects(retail.changeChequeStatus(id,'cleared',options), |
| 1063 | /انتخاب|تأیید|فعال نیست/); |
| 1064 | assert.deepEqual(await state(),before,'Rejected clearing changed financial state'); |
| 1065 | } |
| 1066 | const result=await retail.changeChequeStatus(id,'cleared',{ |
| 1067 | date,accountId:second.id,explicitlyApproved:true |
| 1068 | }); |
| 1069 | assert.equal(result.status,'cleared'); |
| 1070 | assert.equal(result.clearingAccountId,second.id); |
| 1071 | assert.equal(result.clearingApprovedBy,'phase2-admin'); |
| 1072 | const journal=await db.get('journal_entries',result.statusJournalId); |
| 1073 | const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal.id); |
| 1074 | assert.ok(lines.some(x=>x.accountId===second.ledgerAccountId&&x.debit===365)); |
| 1075 | const defaultCash=await db.get('treasury','cash-1'); |
| 1076 | assert.ok(!lines.some(x=>x.accountId===defaultCash.ledgerAccountId&&x.debit===365)); |
| 1077 | const receipts=(await db.getAll('treasury')).filter(x=>x.refChequeId===id); |
| 1078 | assert.equal(receipts.length,1); |
| 1079 | assert.equal(receipts[0].toAccountId,second.id); |
| 1080 | assert.equal(receipts[0].journalId,journal.id); |
| 1081 | await assert.rejects(retail.changeChequeStatus(first.id,'cleared',{ |
| 1082 | date,accountId:second.id,explicitlyApproved:true |
| 1083 | }),/در جریان/); |
| 1084 | assert.equal((await db.getAll('treasury')).filter(x=>x.refChequeId===id).length,1); |
| 1085 | const trial=await accounts.trialBalance(); |
| 1086 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 1087 | }); |
| 1088 | |
| 1089 | test('A01: immutable cheque rejects invalid or pre-issuance due dates with zero financial writes',async()=>{ |
| 1090 | await setup(); |
| 1091 | const baseline={ |
| 1092 | cheques:(await db.getAll('cheques')).length, |
| 1093 | journals:(await db.getAll('journal_entries')).length, |
| 1094 | lines:(await db.getAll('journal_lines')).length, |
| 1095 | audits:(await db.getAll('audit_events')).length, |
| 1096 | treasury:(await db.getAll('treasury')).length |
| 1097 | }; |
| 1098 | const issueDate=date; |
| 1099 | for(const [id,dueDate] of [ |
| 1100 | ['early','1405/07/17'], |
| 1101 | ['malformed','2026-10-15'], |
| 1102 | ['invalid','1405/13/01'], |
| 1103 | ['empty',''] |
| 1104 | ]){ |
| 1105 | const row={id:'a01-due-'+id,issueDate,dueDate, |
| 1106 | direction:'inbound',status:'pending',contactId:'contact-1', |
| 1107 | amount:80,chequeNumber:'due-'+id}; |
| 1108 | await assert.rejects(retail.postCheque(row),/سررسید|تاریخ/); |
| 1109 | assert.equal(await db.get('cheques',row.id),undefined); |
| 1110 | assert.deepEqual({ |
| 1111 | cheques:(await db.getAll('cheques')).length, |
| 1112 | journals:(await db.getAll('journal_entries')).length, |
| 1113 | lines:(await db.getAll('journal_lines')).length, |
| 1114 | audits:(await db.getAll('audit_events')).length, |
| 1115 | treasury:(await db.getAll('treasury')).length |
| 1116 | },baseline,'Invalid cheque must leave all financial stores unchanged'); |
| 1117 | } |
| 1118 | const valid=await retail.postCheque({ |
| 1119 | id:'a01-due-valid',issueDate, |
| 1120 | dueDate:'1405/08/05',direction:'inbound', |
| 1121 | status:'pending',contactId:'contact-1', |
| 1122 | amount:80,chequeNumber:'due-valid' |
| 1123 | }); |
| 1124 | assert.equal(valid.dueDate,'1405/08/05'); |
| 1125 | assert.equal(valid.issueDate,issueDate); |
| 1126 | assert.equal((await db.getAll('journal_entries')).length,baseline.journals+1); |
| 1127 | assert.equal((await db.getAll('audit_events')).length,baseline.audits+1); |
| 1128 | const trial=await accounts.trialBalance(); |
| 1129 | assert.equal(trial.totals.debit,trial.totals.credit); |
| 1130 | }); |