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

fix(finance): consistent exact percentage, VAT and global discount validations

davoodmehraban89 committed Oct 31, 2026 at 20:22 UTC 4b26b49b34e0d88e50135972acbccaa9f7b0e7f3
4 files changed +88 -23
src/controllers/InvoiceController.js
+17 -15
@@ -9,7 +9,7 @@ import { SettingsController } from './SettingsController.js';
9 import { LicenseService } from '../core/LicenseService.js';
10 import { DataScope } from '../core/DataScope.js';
11 import { RetailPostingService } from '../core/RetailPostingService.js';
12 -import { amount, lineGrossRials } from '../core/RetailFinanceCore.mjs';
12 +import { amount, lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
13
14 class InvoiceControllerImpl {
15 // شماره‌ی بعدی سریال (بر اساس نوع سند)
@@ -50,13 +50,12 @@ class InvoiceControllerImpl {
50 // would apply the reduction twice when saving a line.
51 const discInput = Number(it.discountInput ?? it.discount ?? 0);
52 if (!Number.isFinite(discInput) || discInput < 0 ||
53 - (it.discountType === 'percent' ? discInput > 100 : !Number.isSafeInteger(discInput))) {
53 + !['fixed','percent'].includes(it.discountType || 'fixed'))
54 throw Error('تخفیف ردیف فاکتور نامعتبر است');
55 - }
55 if (it.discountType === 'percent') {
57 - lineDiscount = Math.round(lineSubtotal * discInput / 100);
56 + lineDiscount = percentOfRials(lineSubtotal,it.discountInput ?? it.discount ?? 0,'درصد تخفیف ردیف');
57 } else {
59 - lineDiscount = discInput;
58 + lineDiscount = amount(it.discountInput ?? it.discount ?? 0,'تخفیف ثابت ردیف');
59 }
60 lineDiscount = Math.max(0, Math.min(lineDiscount, lineSubtotal));
61 const lineTotal = lineSubtotal - lineDiscount;
@@ -78,26 +77,29 @@ class InvoiceControllerImpl {
77
78 // تخفیف کلی
79 let totalDiscount = 0;
81 - const discInput = Number(data.discountInput) || 0;
80 + const discInput = data.discountInput ?? 0;
81 + if (!['fixed','percent'].includes(data.discountType || 'fixed'))
82 + throw Error('نوع تخفیف کل فاکتور نامعتبر است');
83 if (data.discountType === 'percent') {
83 - totalDiscount = Math.round(subtotal * discInput / 100);
84 + totalDiscount = percentOfRials(subtotal,discInput,'درصد تخفیف کل');
85 } else {
85 - totalDiscount = discInput;
86 + totalDiscount = amount(discInput,'تخفیف ثابت کل');
87 }
88 totalDiscount = Math.max(0, Math.min(totalDiscount, subtotal));
89
90 const afterDiscount = Math.max(0, subtotal - totalDiscount);
91
92 // مالیات
93 + // Validate supplied VAT rate even for tax-exempt invoices.
94 + const vatRate = data.vatRate ?? 0;
95 + percentOfRials(0,vatRate,'درصد مالیات');
96 let vatAmount = 0;
93 - if (data.vatEnabled && data.kind !== 'non_formal') {
94 - const rate = Number(data.vatRate) || 0;
95 - vatAmount = Math.round(afterDiscount * rate / 100);
96 - }
97 + if (data.vatEnabled && data.kind !== 'non_formal')
98 + vatAmount = percentOfRials(afterDiscount,vatRate,'درصد مالیات');
99 const grandTotal = afterDiscount + vatAmount;
100
101 // پرداخت
100 - const paidAmount = Math.max(0, Math.min(Number(data.paidAmount) || 0, grandTotal));
102 + const paidAmount = Math.min(amount(data.paidAmount ?? 0,'مبلغ پرداخت'), grandTotal);
103 const remaining = Math.max(0, grandTotal - paidAmount);
104
105 const baseData = {
@@ -112,9 +114,9 @@ class InvoiceControllerImpl {
114 subtotal,
115 totalDiscount,
116 discountType: data.discountType || 'fixed',
115 - discountInput: discInput,
117 + discountInput: Number(discInput),
118 vatEnabled: !!data.vatEnabled,
117 - vatRate: Number(data.vatRate) || 0,
119 + vatRate: Number(vatRate),
120 vatAmount,
121 grandTotal,
122 paymentMethod: data.paymentMethod || 'cash',
src/core/RetailFinanceCore.mjs
+27 -4
@@ -37,6 +37,19 @@ export function lineGrossRials(quantity, unitPrice) {
37 throw Error('جمع ردیف فاکتور از محدوده مجاز ریالی بیشتر است');
38 return Number(gross);
39 }
40 +// Exact whole-rial percentages: 2-decimal rate, integer basis points and BigInt.
41 +// Reject rates not representable without silently losing fractional percent.
42 +export function percentOfRials(rials, rate, label='درصد') {
43 + const base=amount(rials,'مبلغ مبنای درصد');
44 + if(typeof rate!=='number'&&typeof rate!=='string')throw Error(label+' نامعتبر است');
45 + if(typeof rate==='string'&&!/^\d+(?:\.\d{1,2})?$/.test(rate.trim()))
46 + throw Error(label+' باید حداکثر دو رقم اعشار داشته باشد');
47 + const n=Number(rate), scaled=n*100;
48 + if(!Number.isFinite(n)||n<0||n>100||
49 + Math.abs(scaled-Math.round(scaled))>1e-7)
50 + throw Error(label+' باید بین صفر و صد با حداکثر دو رقم اعشار باشد');
51 + return Number((BigInt(base)*BigInt(Math.round(scaled))+5000n)/10000n);
52 +}
53 export const fromQtyUnits=q=>q/QTY_SCALE;
54 const plus=(a,b)=>{const n=a+b;if(!Number.isSafeInteger(n))throw Error('سرریز موجودی یا مبلغ');return n};
55 export function receiveStock(current,quantity,totalCost) {
@@ -91,11 +104,8 @@ export function assertInvoiceTotals(inv) {
104 const discount=amount(i.discount??0,'تخفیف ردیف');
105 if(discount>gross)throw Error('تخفیف ردیف بیش از مبلغ ناخالص است');
106 if(i.discountInput!==undefined) {
94 - const raw=Number(i.discountInput);
95 - if(!Number.isFinite(raw)||raw<0)throw Error('ورودی تخفیف ردیف نامعتبر است');
107 if(discountType==='percent'){
97 - if(raw>100)throw Error('درصد تخفیف ردیف بیش از صد است');
98 - if(discount!==Math.round(gross*raw/100))
108 + if(discount!==percentOfRials(gross,i.discountInput,'درصد تخفیف ردیف'))
109 throw Error('تخفیف محاسبه‌شده ردیف با درصد واردشده ناسازگار است');
110 }else if(discount!==amount(i.discountInput,'تخفیف ثابت ردیف')){
111 throw Error('تخفیف ثابت ردیف با ورودی اصلی ناسازگار است');
@@ -108,6 +118,19 @@ export function assertInvoiceTotals(inv) {
118 if(amount(inv.subtotal)!==total)throw Error('جمع ردیف‌ها نادرست است');
119 const disc=amount(inv.totalDiscount,'تخفیف'),vat=amount(inv.vatAmount,'مالیات');
120 if(disc>total)throw Error('تخفیف نامعتبر است');
121 + if(inv.discountInput!==undefined) {
122 + const mode=inv.discountType||'fixed';
123 + if(!['fixed','percent'].includes(mode))throw Error('نوع تخفیف کل فاکتور نامعتبر است');
124 + const expected=mode==='percent'
125 + ? percentOfRials(total,inv.discountInput,'درصد تخفیف کل')
126 + : Math.min(total,amount(inv.discountInput,'تخفیف ثابت کل'));
127 + if(disc!==expected)throw Error('تخفیف کل با ورودی ثبت‌شده ناسازگار است');
128 + }
129 + if(inv.vatEnabled!==undefined) {
130 + const expected=inv.vatEnabled && inv.kind!=='non_formal'
131 + ? percentOfRials(total-disc,inv.vatRate??0,'درصد مالیات') : 0;
132 + if(vat!==expected)throw Error('مالیات فاکتور با نرخ و وضعیت مالیات ناسازگار است');
133 + }
134 if(amount(inv.grandTotal)!==total-disc+vat)throw Error('مبلغ کل فاکتور ناسازگار است');
135 if(amount(inv.paidAmount)>inv.grandTotal)throw Error('مبلغ پرداخت بیش از مبلغ فاکتور است');
136 return true;
src/views/InvoiceFormView.js
+9 -4
@@ -12,7 +12,7 @@ import { numberToWords } from '../utils/NumberToWords.js';
12 import { NumberInput } from '../utils/NumberInput.js';
13 import { SettingsController } from '../controllers/SettingsController.js';
14 import { RetailPostingService } from '../core/RetailPostingService.js';
15 -import { lineGrossRials } from '../core/RetailFinanceCore.mjs';
15 +import { lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
16
17 let ctx = {
18 editId: null,
@@ -508,7 +508,8 @@ class InvoiceFormViewImpl {
508 let lineDiscount = 0;
509 const discInput = Number(item.discountInput !== undefined ? item.discountInput : item.discount) || 0;
510 if (item.discountType === 'percent') {
511 - lineDiscount = Math.round(lineSubtotal * discInput / 100);
511 + try { lineDiscount = percentOfRials(lineSubtotal,discInput); }
512 + catch (_) { lineDiscount = 0; }
513 } else {
514 lineDiscount = discInput;
515 }
@@ -532,7 +533,8 @@ class InvoiceFormViewImpl {
533 const discInput = NumberInput.parse(document.getElementById('invDiscInput')?.value);
534 let totalDiscount = 0;
535 if (discType === 'percent') {
535 - totalDiscount = Math.round(subtotal * discInput / 100);
536 + try { totalDiscount = percentOfRials(subtotal,discInput); }
537 + catch (_) { totalDiscount = 0; }
538 } else {
539 totalDiscount = discInput;
540 }
@@ -544,7 +546,10 @@ class InvoiceFormViewImpl {
546 const vatEnabled = kind !== 'non_formal' && document.getElementById('invVatEnabled')?.checked;
547 const vatRate = NumberInput.parse(document.getElementById('invVatRate')?.value);
548 let vatAmount = 0;
547 - if (vatEnabled) vatAmount = Math.round(afterDiscount * vatRate / 100);
549 + if (vatEnabled) {
550 + try { vatAmount = percentOfRials(afterDiscount,vatRate); }
551 + catch (_) { vatAmount = 0; }
552 + }
553
554 const grandTotal = afterDiscount + vatAmount;
555
tests/financial-percent-boundary.test.mjs new
+35
@@ -0,0 +1,35 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { percentOfRials, assertInvoiceTotals } from '../src/core/RetailFinanceCore.mjs';
4 +
5 +const fixture=()=>({
6 + kind:'sale',items:[{qty:2.5,price:1201,lineSubtotal:3003,discountType:'percent',
7 + discountInput:10,discount:300,lineTotal:2703}],subtotal:2703,
8 + totalDiscount:270,discountType:'percent',discountInput:10,
9 + vatEnabled:true,vatRate:10.5,vatAmount:255,grandTotal:2688,paidAmount:0
10 +});
11 +
12 +test('bigint percentage keeps two-decimal rates and half-up whole-rial rounding',()=>{
13 + assert.equal(percentOfRials(3003,10),300);
14 + assert.equal(percentOfRials(1000,10.55),106);
15 + assert.equal(percentOfRials(1,50),1);
16 + assert.equal(percentOfRials(1,49.99),0);
17 + assert.equal(percentOfRials(Number.MAX_SAFE_INTEGER,100),Number.MAX_SAFE_INTEGER);
18 +});
19 +
20 +test('adversarial percentage inputs are rejected, not silently zeroed',()=>{
21 + for(const value of [-1,100.01,0.001,99.999,NaN,Infinity,'hello','100.001',null,true,{},'1e2'])
22 + assert.throws(()=>percentOfRials(100,value),/درصد|نامعتبر/);
23 +});
24 +
25 +test('posting verifies typed row discount, total discount and enabled VAT',()=>{
26 + assert.equal(assertInvoiceTotals(fixture()),true);
27 + const a=fixture();a.items[0].discount=301;a.items[0].lineTotal=2702;a.subtotal=2702;a.totalDiscount=270;a.grandTotal=2687;
28 + assert.throws(()=>assertInvoiceTotals(a),/تخفیف محاسبه‌شده/);
29 + const b=fixture();b.totalDiscount=200;b.grandTotal=2766;
30 + assert.throws(()=>assertInvoiceTotals(b),/تخفیف کل/);
31 + const c=fixture();c.vatAmount=256;c.grandTotal=2689;
32 + assert.throws(()=>assertInvoiceTotals(c),/مالیات فاکتور/);
33 + const d=fixture();d.vatEnabled=false;
34 + assert.throws(()=>assertInvoiceTotals(d),/مالیات فاکتور/);
35 +});