فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix(A01): cap receipt/refund against net obligation and actual unrefunded cash
davoodmehraban89 committed
Oct 17, 2026 at 00:44 UTC
c6a03006e2223597f42c9e80f4d388e4efe64785
1 file changed
+37
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}),