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

fix(A01): prevent over-refund and overcollection after commercial returns; link treasury cash to invoices

Finance transaction now caps cash collections to net original amount after finalized purchase/sale returns, and caps cash refunds to genuine original paid credit minus prior refunds. Rejects partial or duplicate refunds atomically. Treasury receipt/payment dialogs support optional posted invoice references and lazy-load invoice lists only when operator opens settlement form, preserving initial route performance. Verified 198 Node tests PR Quality #38968458992 and full real NSIS/Tauri/WebView2 Windows native #38968458924 with 14 mandatory financial scenarios including over-collection rejection, zero-credit refund rejection and legal receipt acceptance, plus backups, RTL PDF, offline routes and crash restore. Synthetic only; independent finance QA and all release gates remain open.

davoodmehraban89 committed Oct 17, 2026 at 00:56 UTC 4cb4d665445c58f982b58b2a19a4f2ae51e9292c
5 files changed +224 -3
scripts/windows-vm-native-lab.ps1
+1
@@ -174,6 +174,7 @@ try {
174 'treasury-cheque-reconciliation-readonly',
175 'sale-return-immutable-stock-and-ledger',
176 'purchase-return-and-stock-guardrails',
177 + 'return-cash-settlement-net-credit',
178 'append-only-history-bulk-clear-protection',
179 'backup-and-atomic-rejection',
180 'rtl-invoice-print-settings',
src/core/RetailPostingService.js
+37
@@ -396,6 +396,43 @@ class RetailPostingServiceImpl {
396 if(!expected.includes(kind))throw Error('جهت دریافت/پرداخت با فاکتور مطابقت ندارد');
397 if(kind==='purchase_return')otherCode=LEDGER_CODES.payable;
398 if(kind==='sale_return')otherCode=LEDGER_CODES.receivable;
399 + if(['sale','non_formal','purchase','sale_return','purchase_return'].includes(kind)) {
400 + // A01: a posted return reduces the *net* payable/receivable of its
401 + // original invoice. Its remaining field alone does not establish that
402 + // cash is owed: it also includes the amount offset against open AR/AP.
403 + // All checks take place in the same atomic posting transaction.
404 + const isReturn=kind==='sale_return'||kind==='purchase_return';
405 + const original=isReturn
406 + ? sameCompany(await tx.get('invoices',related.originalInvoiceId),
407 + ctx.companyId,'فاکتور اصلی مرجوعی')
408 + : related;
409 + const validSource=isReturn
410 + ? (kind==='sale_return'?['sale','non_formal']:['purchase'])
411 + : [kind];
412 + if (!validSource.includes(original.kind) || original.isPreInvoice ||
413 + !original.financePosted) {
414 + throw Error('فاکتور اصلی برای محاسبه مانده خالص معتبر نیست');
415 + }
416 + const returnKind=['sale','non_formal'].includes(original.kind)
417 + ? 'sale_return' : 'purchase_return';
418 + const finalized=(await tx.getAll('invoices')).filter(row =>
419 + row.companyId===ctx.companyId && row.kind===returnKind &&
420 + row.originalInvoiceId===original.id && !row.isPreInvoice && row.financePosted);
421 + const totalReturns=finalized.reduce((n,row)=>n+BigInt(amount(row.grandTotal)),0n);
422 + const paidRefunds=finalized.reduce((n,row)=>n+BigInt(amount(row.paidAmount||0)),0n);
423 + const net=BigInt(amount(original.grandTotal))-totalReturns;
424 + const originalPaid=BigInt(amount(original.paidAmount||0));
425 + if(net<0n || originalPaid>BigInt(amount(original.grandTotal)))
426 + throw Error('مانده خالص فاکتور با مرجوعی‌ها مغایرت دارد');
427 + const available=isReturn
428 + ? (originalPaid>net ? originalPaid-net-paidRefunds : -paidRefunds)
429 + : net-originalPaid;
430 + if(available<0n || BigInt(sum)>available) {
431 + throw Error(isReturn
432 + ? 'بازپرداخت مجاز از اعتبار نقدی مشتری/تامین‌کننده بیشتر است'
433 + : 'دریافت یا پرداخت از مانده خالص پس از مرجوعی بیشتر است');
434 + }
435 + }
436 }
437 const side=leg(ctx,otherCode);
438 const lines=[postLine(isReceipt?cashLedgerId:side,sum,0,{contactId:info.contactId||related?.contactId||null}),
src/views/TreasuryView.js
+43 -3
@@ -12,7 +12,7 @@ import { NumberInput } from '../utils/NumberInput.js';
12
13 let currentTab = 'accounts';
14 let txFilter = { search: '', type: '', accountId: '' };
15 -let cache = { accounts: [], balances: {}, transactions: [], contacts: [] };
15 +let cache = { accounts: [], balances: {}, transactions: [], contacts: [], invoices: [] };
16
17 class TreasuryViewImpl {
18 async render() {
@@ -45,6 +45,8 @@ class TreasuryViewImpl {
45 cache.balances = await TreasuryController.getBalanceMap();
46 cache.transactions = await TreasuryController.getTransactions();
47 cache.contacts = await ContactController.getAll();
48 + // Invoice list is loaded only when opening a settlement dialog, not on
49 + // every Treasury route render or startup (large companies may have 50k+).
50 }
51
52 _switchTab(tab, btn) {
@@ -407,11 +409,32 @@ class TreasuryViewImpl {
409 ).join('');
410 }
411
410 - openReceiptModal() {
412 +
413 + _buildInvoiceOptions(type) {
414 + const kinds=type==='receipt'
415 + ? ['sale','non_formal','purchase_return']
416 + : ['purchase','sale_return'];
417 + const invoices=cache.invoices.filter(row=>
418 + row.financePosted && !row.isPreInvoice && kinds.includes(row.kind) &&
419 + Number(row.remaining)>0);
420 + return '<option value="">— دریافت/پرداخت مستقل (بدون اتصال فاکتور) —</option>' +
421 + invoices.map(row => `<option value="${this._esc(row.id)}">#${this._esc(row.number)} — ${this._esc(row.contactName||'بدون نام')} (${Formatters.number(row.remaining)} ریال)</option>`).join('');
422 + }
423 +
424 + _onInvoiceSelection() {
425 + const id=document.getElementById('txInvoiceRef')?.value;
426 + const row=cache.invoices.find(x=>x.id===id);
427 + const contact=document.getElementById('txContact');
428 + if(row?.contactId && contact) contact.value=row.contactId;
429 + }
430 +
431 + async openReceiptModal() {
432 if (cache.accounts.length === 0) {
433 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
434 return;
435 }
436 + try { cache.invoices = await InvoiceController.getAll(); }
437 + catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
438 const body = `
439 <div class="form-row">
440 <div class="form-group">
@@ -432,6 +455,13 @@ class TreasuryViewImpl {
455 </select>
456 </div>
457
458 + <div class="form-group">
459 + <label class="form-label">فاکتور مرتبط (اختیاری)</label>
460 + <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
461 + ${this._buildInvoiceOptions('receipt')}
462 + </select>
463 + </div>
464 +
465 <div class="form-group">
466 <label class="form-label">به حساب <span class="req">*</span></label>
467 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
@@ -458,11 +488,13 @@ class TreasuryViewImpl {
488 Modal.open({ title: 'ثبت دریافت وجه', body, footer, size: 'md' });
489 }
490
461 - openPaymentModal() {
491 + async openPaymentModal() {
492 if (cache.accounts.length === 0) {
493 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
494 return;
495 }
496 + try { cache.invoices = await InvoiceController.getAll(); }
497 + catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
498 const body = `
499 <div class="form-row">
500 <div class="form-group">
@@ -483,6 +515,13 @@ class TreasuryViewImpl {
515 </select>
516 </div>
517
518 + <div class="form-group">
519 + <label class="form-label">فاکتور مرتبط / بازپرداخت (اختیاری)</label>
520 + <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
521 + ${this._buildInvoiceOptions('payment')}
522 + </select>
523 + </div>
524 +
525 <div class="form-group">
526 <label class="form-label">از حساب <span class="req">*</span></label>
527 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
@@ -563,6 +602,7 @@ class TreasuryViewImpl {
602 method: document.getElementById('txMethod')?.value || 'cash',
603 contactId,
604 contactName: contact?.name || '',
605 + refInvoiceId: document.getElementById('txInvoiceRef')?.value || null,
606 fromAccountId: document.getElementById('txFromAccount')?.value || null,
607 toAccountId: document.getElementById('txToAccount')?.value || null,
608 description: document.getElementById('txDescription')?.value || ''
tests/retail-phase2.test.mjs
+86
@@ -536,3 +536,89 @@ test('A05: inactive treasury accounts reject transfers, expenses and cheque clea
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 + }),/بازپرداخت مجاز/);
551 + await assert.rejects(retail.postTransaction({
552 + id:'a01-overcollect',type:'receipt',date,amount:201,
553 + refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1'
554 + }),/مانده خالص/);
555 + assert.equal((await db.getAll('journal_entries')).length,before);
556 + assert.equal(await db.get('treasury','a01-invalid-refund'),undefined);
557 + assert.equal(await db.get('treasury','a01-overcollect'),undefined);
558 + const receipt=await retail.postTransaction({
559 + id:'a01-valid-remaining',type:'receipt',date,amount:200,
560 + refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1'
561 + });
562 + assert.equal(receipt.amount,200);
563 + assert.equal((await db.get('invoices',sold.id)).paidAmount,400);
564 + await assert.rejects(retail.postTransaction({
565 + id:'a01-extra-collection',type:'receipt',date,amount:1,
566 + refInvoiceId:sold.id,contactId:'contact-1',toAccountId:'cash-1'
567 + }),/مانده خالص/);
568 + const trial=await accounts.trialBalance();
569 + assert.equal(trial.totals.debit,trial.totals.credit);
570 +});
571 +
572 +test('A01: only genuinely paid customer credit may be refunded, once, even with concurrent requests',async()=>{
573 + await setup();await purchase10();
574 + const sold=await retail.issueInvoice(invoice('sale',3,200,{paidAmount:500}));
575 + const returned=await retail.issueInvoice(invoice('sale_return',1,200,{
576 + originalInvoiceId:sold.id
577 + }));
578 + const attempts=await Promise.allSettled([
579 + retail.postTransaction({id:'refund-a',type:'payment',date,amount:70,
580 + refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1'}),
581 + retail.postTransaction({id:'refund-b',type:'payment',date,amount:70,
582 + refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1'})
583 + ]);
584 + assert.equal(attempts.filter(x=>x.status==='fulfilled').length,1);
585 + assert.equal(attempts.filter(x=>x.status==='rejected').length,1);
586 + assert.equal((await db.get('invoices',returned.id)).paidAmount,70);
587 + const finish=await retail.postTransaction({
588 + id:'refund-final',type:'payment',date,amount:30,
589 + refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1'
590 + });
591 + assert.equal(finish.amount,30);
592 + await assert.rejects(retail.postTransaction({
593 + id:'refund-excess',type:'payment',date,amount:1,
594 + refInvoiceId:returned.id,contactId:'contact-1',fromAccountId:'cash-1'
595 + }),/بازپرداخت مجاز/);
596 + assert.equal((await db.get('invoices',returned.id)).paidAmount,100);
597 + assert.equal((await db.getAll('treasury')).filter(t=>
598 + t.refInvoiceId===returned.id&&t.recordType==='transaction').length,2);
599 + const balance=await accounts.trialBalance();
600 + assert.equal(balance.totals.debit,balance.totals.credit);
601 +});
602 +
603 +test('A01: supplier cash recovery cannot exceed previously paid credit after purchase return',async()=>{
604 + await setup();
605 + const purchased=await retail.issueInvoice(invoice('purchase',10,100,{paidAmount:700}));
606 + const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{
607 + originalInvoiceId:purchased.id
608 + }));
609 + await assert.rejects(retail.postTransaction({
610 + id:'supplier-refund-over',type:'receipt',date,amount:101,
611 + refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1'
612 + }),/بازپرداخت مجاز/);
613 + const cash=await retail.postTransaction({
614 + id:'supplier-refund-valid',type:'receipt',date,amount:100,
615 + refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1'
616 + });
617 + assert.equal(cash.amount,100);
618 + await assert.rejects(retail.postTransaction({
619 + id:'supplier-refund-excess',type:'receipt',date,amount:1,
620 + refInvoiceId:returned.id,contactId:'contact-1',toAccountId:'cash-1'
621 + }),/بازپرداخت مجاز/);
622 + const trial=await accounts.trialBalance();
623 + assert.equal(trial.totals.debit,trial.totals.credit);
624 +});
tests/windows-vm-native-functional-matrix.cjs
+57
@@ -599,6 +599,62 @@ async function nativeTreasuryChequeReconciliation() {
599 reportingReadOnly:true,fixtureRemoved:true};
600 }
601
602 +async function nativeReturnCashSettlementGuardrails() {
603 + const wait=ms=>new Promise(r=>setTimeout(r,ms));
604 + const check=(ok,msg)=>{if(!ok)throw Error(msg);};
605 + const db=FINORA.Storage,company=await FINORA.Company.current();
606 + const sale=(await db.getAll('invoices')).find(x=>
607 + x.companyId===company.id&&x.kind==='sale'&&x.grandTotal===600);
608 + const returned=(await db.getAll('invoices')).find(x=>
609 + x.companyId===company.id&&x.kind==='sale_return'&&x.originalInvoiceId===sale?.id);
610 + check(sale?.paidAmount===200&&returned?.grandTotal===200,
611 + 'A01 net-refund native sale/return prerequisite absent');
612 + await FINORA.Router.go('treasury');await wait(170);
613 + const view=window.TreasuryView;
614 + const before=()=>Promise.all(['journal_entries','treasury','settlements'].map(async name=>
615 + (await db.getAll(name)).length));
616 + const testReceipt=async(amount)=>{
617 + await view.openReceiptModal();
618 + const sel=document.getElementById('txInvoiceRef');
619 + check(sel&&[...sel.options].some(x=>x.value===sale.id),
620 + 'Real treasury UI does not list the unpaid original sale');
621 + sel.value=sale.id;view._onInvoiceSelection();
622 + document.getElementById('txAmount').value=String(amount);
623 + document.getElementById('txDate').value='1405/07/18';
624 + await view._saveTransaction('receipt');
625 + };
626 + const start=await before();
627 + await testReceipt(201);
628 + let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('مانده خالص'));
629 + check(toast,'Overcollection after posted return not visibly rejected');
630 + check(JSON.stringify(await before())===JSON.stringify(start),
631 + 'Rejected overcollection wrote a ledger, treasury or settlement');
632 + toast.querySelector('.toast-close')?.click();
633 + FINORA.Modal.close();
634 + await testReceipt(200);
635 + check((await db.get('invoices',sale.id)).paidAmount===400,
636 + 'Allowed residual collection did not reach net post-return amount');
637 + await view.openPaymentModal();
638 + const sel=document.getElementById('txInvoiceRef');
639 + check(sel&&[...sel.options].some(x=>x.value===returned.id),
640 + 'Real treasury UI cannot select the customer return');
641 + sel.value=returned.id;view._onInvoiceSelection();
642 + document.getElementById('txAmount').value='1';
643 + document.getElementById('txDate').value='1405/07/18';
644 + const preRefund=await before();
645 + await view._saveTransaction('payment');
646 + toast=[...document.querySelectorAll('.toast-error')].find(x=>
647 + x.textContent.includes('بازپرداخت مجاز'));
648 + check(toast,'Cash refund with zero actual paid customer credit was not rejected');
649 + check(JSON.stringify(await before())===JSON.stringify(preRefund),
650 + 'Rejected customer refund wrote a ledger, treasury or settlement');
651 + toast.querySelector('.toast-close')?.click();FINORA.Modal.close();
652 + check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
653 + 'Native A01 cash cap left an error toast/modal');
654 + return {overcollectionRejectedWithoutWrites:true,netReceiptAccepted:true,
655 + nonexistentRefundCreditRejected:true,realTreasuryInvoiceSelector:true};
656 +}
657 +
658 async function nativeBackupRestore() {
659 const check = (value, message) => { if (!value) throw Error(message); };
660 const S = FINORA.Storage;
@@ -864,6 +920,7 @@ module.exports = async function nativeFunctionalMatrix(cdp) {
920 ['treasury-cheque-reconciliation-readonly', nativeTreasuryChequeReconciliation],
921 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
922 ['purchase-return-and-stock-guardrails', nativePurchaseReturnGuardrails],
923 + ['return-cash-settlement-net-credit', nativeReturnCashSettlementGuardrails],
924 ['append-only-history-bulk-clear-protection', nativeHistoryClearFailClosed],
925 ['backup-and-atomic-rejection', nativeBackupRestore],
926 ['rtl-invoice-print-settings', invoicePrintLayout],