فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix(P0): derive posted invoice COGS from immutable stock movements, disclose legacy estimates
davoodmehraban89 committed
Nov 1, 2026 at 10:43 UTC
854c2b5096c129259328252a501048e6e0d4d360
5 files changed
+313
-47
src/controllers/ReportController.js
+31
-47
@@ -6,20 +6,22 @@ import { StorageService } from '../core/StorageService.js';
6
import { Auth } from '../core/Auth.js';
7
import { DataScope } from '../core/DataScope.js';
8
import { Jalali } from '../utils/Jalali.js';
9
+import { buildInvoiceCosting } from '../core/ReportCosting.mjs';
10
11
class ReportControllerImpl {
12
async _loadData() {
13
const user = Auth.current();
14
if (!user) throw new Error('کاربر یافت نشد');
14
- const [invoices, products, expenses, contacts, cheques, treasury] = await Promise.all([
15
+ const [invoices, products, expenses, contacts, cheques, treasury, stock_movements] = await Promise.all([
16
DataScope.list('invoices'),
17
DataScope.list('products'),
18
DataScope.list('expenses'),
19
DataScope.list('contacts'),
20
DataScope.list('cheques'),
20
- DataScope.list('treasury')
21
+ DataScope.list('treasury'),
22
+ DataScope.list('stock_movements')
23
]);
22
- return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [] };
24
+ return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [], stock_movements: stock_movements || [] };
25
}
26
27
_parseJalali(str) {
@@ -108,12 +110,12 @@ class ReportControllerImpl {
110
// ۱. سود و زیان
111
// ============================================================
112
async getProfitLoss(filter = {}) {
111
- const { invoices, products, expenses } = await this._loadData();
113
+ const { invoices, products, expenses, stock_movements } = await this._loadData();
114
const { from, to } = this._getRange(filter);
115
116
// فقط فاکتورهای فروش (بدون پیشفاکتور)
117
const salesInRange = invoices.filter(i =>
116
- i.kind === 'sale' &&
118
+ ['sale', 'non_formal'].includes(i.kind) &&
119
!i.isPreInvoice &&
120
this._inRange(i.date, from, to)
121
);
@@ -128,34 +130,19 @@ class ReportControllerImpl {
130
// فروش ناخالص = مجموع فروش بدون مالیات و تخفیف نهایی
131
const grossSales = salesInRange.reduce((s, i) => s + (Number(i.subtotal) || 0), 0);
132
const salesDiscounts = salesInRange.reduce((s, i) => s + (Number(i.totalDiscount) || 0), 0);
131
- const returnsAmount = returnsInRange.reduce((s, i) => s + (Number(i.subtotal) || 0), 0);
133
+ const returnsAmount = returnsInRange.reduce((s, i) =>
134
+ s + (Number(i.subtotal) || 0) - (Number(i.totalDiscount) || 0), 0);
135
const netSales = grossSales - salesDiscounts - returnsAmount;
136
134
- // بهای تمامشده (COGS) — از قیمت خرید هر کالا
135
- let cogs = 0;
136
- const productMap = {};
137
- products.forEach(p => productMap[p.id] = p);
138
-
139
- salesInRange.forEach(inv => {
140
- (inv.items || []).forEach(it => {
141
- const p = productMap[it.productId];
142
- const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
143
- const qty = Number(it.qty) || 0;
144
- cogs += buyPrice * qty;
145
- });
146
- });
147
-
148
- // برگشتها رو از COGS کم کن
149
- returnsInRange.forEach(inv => {
150
- (inv.items || []).forEach(it => {
151
- const p = productMap[it.productId];
152
- const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
153
- const qty = Number(it.qty) || 0;
154
- cogs -= buyPrice * qty;
155
- });
156
- });
157
-
158
- cogs = Math.max(0, cogs);
137
+ // Finalized invoices use historical stock movements. Legacy sales are
138
+ // explicitly estimates, never misrepresented as immutable ledger costs.
139
+ const valuation = buildInvoiceCosting(
140
+ [...salesInRange, ...returnsInRange], products, stock_movements
141
+ );
142
+ const totalCost = rows => rows.reduce((sum, row) =>
143
+ sum + valuation.byInvoice.get(row.id).total, 0);
144
+ // A return-only period can legitimately have negative COGS.
145
+ const cogs = totalCost(salesInRange) - totalCost(returnsInRange);
146
const grossProfit = netSales - cogs;
147
const grossMargin = netSales > 0 ? (grossProfit / netSales) * 100 : 0;
148
@@ -173,6 +160,7 @@ class ReportControllerImpl {
160
returnsAmount,
161
netSales,
162
cogs,
163
+ costBasis: valuation.summary,
164
grossProfit,
165
grossMargin,
166
operatingExpenses,
@@ -190,22 +178,22 @@ class ReportControllerImpl {
178
// ۲. تحلیل فروش (Top Products & Customers)
179
// ============================================================
180
async getSalesAnalysis(filter = {}) {
193
- const { invoices, products, contacts } = await this._loadData();
181
+ const { invoices, products, contacts, stock_movements } = await this._loadData();
182
const { from, to } = this._getRange(filter);
183
184
const salesInRange = invoices.filter(i =>
197
- i.kind === 'sale' &&
185
+ ['sale', 'non_formal'].includes(i.kind) &&
186
!i.isPreInvoice &&
187
this._inRange(i.date, from, to)
188
);
189
190
// محصولات
191
const productStats = {};
204
- const productMap = {};
205
- products.forEach(p => productMap[p.id] = p);
192
+ const valuation = buildInvoiceCosting(salesInRange, products, stock_movements);
193
194
salesInRange.forEach(inv => {
208
- (inv.items || []).forEach(it => {
195
+ const costs = valuation.byInvoice.get(inv.id).lines;
196
+ (inv.items || []).forEach((it, index) => {
197
const key = it.productId || 'unknown_' + (it.productName || '');
198
if (!productStats[key]) {
199
productStats[key] = {
@@ -219,11 +207,9 @@ class ReportControllerImpl {
207
}
208
const qty = Number(it.qty) || 0;
209
const lineTotal = Number(it.lineTotal) || (qty * (Number(it.price) || 0));
222
- const p = productMap[it.productId];
223
- const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
210
productStats[key].qty += qty;
211
productStats[key].totalSales += lineTotal;
226
- productStats[key].cogs += buyPrice * qty;
212
+ productStats[key].cogs += costs[index].cost;
213
productStats[key].count += 1;
214
});
215
});
@@ -273,21 +259,21 @@ class ReportControllerImpl {
259
// ۳. سودآوری کالا (همه کالاها)
260
// ============================================================
261
async getProductProfitability(filter = {}) {
276
- const { invoices, products } = await this._loadData();
262
+ const { invoices, products, stock_movements } = await this._loadData();
263
const { from, to } = this._getRange(filter);
264
265
const salesInRange = invoices.filter(i =>
280
- i.kind === 'sale' &&
266
+ ['sale', 'non_formal'].includes(i.kind) &&
267
!i.isPreInvoice &&
268
this._inRange(i.date, from, to)
269
);
270
285
- const productMap = {};
286
- products.forEach(p => productMap[p.id] = p);
271
+ const valuation = buildInvoiceCosting(salesInRange, products, stock_movements);
272
273
const stats = {};
274
salesInRange.forEach(inv => {
290
- (inv.items || []).forEach(it => {
275
+ const costs = valuation.byInvoice.get(inv.id).lines;
276
+ (inv.items || []).forEach((it, index) => {
277
const key = it.productId || 'unknown_' + (it.productName || '');
278
if (!stats[key]) {
279
const p = productMap[it.productId];
@@ -304,11 +290,9 @@ class ReportControllerImpl {
290
}
291
const qty = Number(it.qty) || 0;
292
const lineTotal = Number(it.lineTotal) || (qty * (Number(it.price) || 0));
307
- const p = productMap[it.productId];
308
- const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
293
stats[key].qty += qty;
294
stats[key].totalSales += lineTotal;
311
- stats[key].cogs += buyPrice * qty;
295
+ stats[key].cogs += costs[index].cost;
296
});
297
});
298
src/core/ReportCosting.mjs
new
+100
@@ -0,0 +1,100 @@
1
+// Historical inventory costing for management reports.
2
+// Posted invoice costs come from immutable stock movements, never mutable product buyPrice.
3
+// Legacy, unposted invoices can only have an ESTIMATED cost; surface that status.
4
+const safeRials = (value, label) => {
5
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
6
+ throw Error('مبلغ نامعتبر در گزارش: ' + label);
7
+ return value;
8
+};
9
+const safePlus = (a, b) => {
10
+ const n = a + b;
11
+ if (!Number.isSafeInteger(n)) throw Error('سرریز مبلغ گزارش');
12
+ return n;
13
+};
14
+const keyOf = (invoiceId, productId, direction) =>
15
+ JSON.stringify([invoiceId, productId, direction]);
16
+
17
+export function buildInvoiceCosting(invoices, products, movements) {
18
+ const productMap = new Map(products.map(p => [p.id, p]));
19
+ const stock = new Map();
20
+ for (const m of movements) {
21
+ // Only movements issued by finalized invoices may establish historical COGS.
22
+ if (m.refType !== 'invoice' || !m.refId || !m.productId ||
23
+ !['in', 'out'].includes(m.type)) continue;
24
+ const key = keyOf(m.refId, m.productId, m.type);
25
+ const prior = stock.get(key) || { total: 0, count: 0 };
26
+ prior.total = safePlus(prior.total, safeRials(m.cost, 'بهای گردش انبار'));
27
+ prior.count++;
28
+ stock.set(key, prior);
29
+ }
30
+
31
+ const byInvoice = new Map();
32
+ const summary = { recordedLines: 0, estimatedLines: 0, missingCostLines: 0,
33
+ serviceLines: 0 };
34
+ for (const invoice of invoices) {
35
+ const items = invoice.items || [];
36
+ const results = Array(items.length);
37
+ const groups = new Map();
38
+ items.forEach((item, index) => {
39
+ const quantity = Number(item.qty);
40
+ if (!Number.isFinite(quantity) || quantity <= 0)
41
+ throw Error('مقدار نامعتبر در گزارش فاکتور');
42
+ if (!item.productId) {
43
+ results[index] = { cost: 0, source: 'service' };
44
+ summary.serviceLines++;
45
+ return;
46
+ }
47
+ if (!groups.has(item.productId)) groups.set(item.productId, []);
48
+ groups.get(item.productId).push({ index, quantity });
49
+ });
50
+
51
+ for (const [productId, group] of groups) {
52
+ const direction = invoice.kind === 'sale_return' ? 'in' : 'out';
53
+ const movement = invoice.financePosted === true
54
+ ? stock.get(keyOf(invoice.id, productId, direction)) : null;
55
+ const product = productMap.get(productId);
56
+ // Preserve a posted cost even if the catalog price has since changed or
57
+ // the product record is no longer available.
58
+ if (movement && movement.count > 0) {
59
+ const totalQty = group.reduce((n, row) => n + row.quantity, 0);
60
+ let distributed = 0;
61
+ group.forEach((row, index) => {
62
+ const last = index === group.length - 1;
63
+ const share = last ? movement.total - distributed :
64
+ Math.min(movement.total - distributed,
65
+ Math.round(movement.total * row.quantity / totalQty));
66
+ results[row.index] = { cost: safeRials(share, 'تخصیص بهای تمامشده'),
67
+ source: 'recorded' };
68
+ distributed = safePlus(distributed, share);
69
+ summary.recordedLines++;
70
+ });
71
+ } else if (product?.trackInventory === false) {
72
+ group.forEach(row => {
73
+ results[row.index] = { cost: 0, source: 'service' };
74
+ summary.serviceLines++;
75
+ });
76
+ } else if (product && product.buyPrice !== undefined &&
77
+ product.buyPrice !== null) {
78
+ const unitCost = safeRials(product.buyPrice, 'قیمت خرید فعلی');
79
+ group.forEach(row => {
80
+ const cost = Math.round(unitCost * row.quantity);
81
+ results[row.index] = {
82
+ cost: safeRials(cost, 'بهای برآوردی'), source: 'estimated'
83
+ };
84
+ summary.estimatedLines++;
85
+ });
86
+ } else {
87
+ group.forEach(row => {
88
+ // Do not misrepresent missing cost information as confirmed zero.
89
+ results[row.index] = { cost: 0, source: 'missing' };
90
+ summary.missingCostLines++;
91
+ });
92
+ }
93
+ }
94
+
95
+ let total = 0;
96
+ for (const row of results) total = safePlus(total, row.cost);
97
+ byInvoice.set(invoice.id, { lines: results, total });
98
+ }
99
+ return { byInvoice, summary };
100
+}
src/views/ReportsView.js
+22
@@ -163,6 +163,24 @@ class ReportsViewImpl {
163
document.getElementById('pageContent').innerHTML = html;
164
}
165
166
+ // ============================================================
167
+ // Transparent costing disclosure: legacy invoices are only estimates.
168
+ // The posted general ledger remains the source for formal financial reports.
169
+ // ============================================================
170
+ _costBasisWarning(basis) {
171
+ const estimated = Number(basis?.estimatedLines) || 0;
172
+ const missing = Number(basis?.missingCostLines) || 0;
173
+ if (!estimated && !missing) return '';
174
+ const details = [
175
+ estimated ? Formatters.number(estimated) + ' ردیف با قیمت خرید فعلی برآورد شده' : '',
176
+ missing ? Formatters.number(missing) + ' ردیف بدون اطلاعات بهای تمامشده' : ''
177
+ ].filter(Boolean).join('؛ ');
178
+ return `<div role="status" class="card" style="border-right:4px solid var(--warning);padding:13px;margin-bottom:16px;line-height:1.9">
179
+ <strong>⚠️ این سود و زیان قطعی نیست.</strong> ${details}.
180
+ قیمت خرید امروز جایگزین بهای تاریخی فروش نمیشود؛ برای صورت مالی قابل استناد، دفتر کل و اسناد قطعی را ملاک قرار دهید.
181
+ </div>`;
182
+ }
183
+
184
// ============================================================
185
// تب ۱: سود و زیان
186
// ============================================================
@@ -199,6 +217,7 @@ class ReportsViewImpl {
217
const marginLabel = pl.netProfit >= 0 ? 'حاشیه سود خالص' : 'حاشیه زیان خالص';
218
219
return `
220
+ ${this._costBasisWarning(pl.costBasis)}
221
<div class="grid-kpi">
222
<div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
223
<div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📊</div>
@@ -385,6 +404,7 @@ class ReportsViewImpl {
404
const totalProfit = list.reduce((s, p) => s + p.profit, 0);
405
406
return `
407
+ ${this._costBasisWarning(cache.pl?.costBasis)}
408
<div class="grid-kpi">
409
<div class="card kpi-card" style="margin:0">
410
<div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📦</div>
@@ -579,6 +599,7 @@ class ReportsViewImpl {
599
if (currentTab === 'pl') {
600
return `
601
<h2>صورت سود و زیان</h2>
602
+ ${this._costBasisWarning(pl.costBasis)}
603
<table>
604
<tr><td style="width:60%">فروش ناخالص</td><td>${Formatters.money(pl.grossSales)}</td></tr>
605
<tr><td>تخفیف فروش</td><td style="color:#dc2626">- ${Formatters.money(pl.salesDiscounts)}</td></tr>
@@ -603,6 +624,7 @@ class ReportsViewImpl {
624
const list = cache.products || [];
625
return `
626
<h2>سودآوری کالاها (${Formatters.number(list.length)} کالا)</h2>
627
+ ${this._costBasisWarning(pl.costBasis)}
628
<table>
629
<thead><tr><th>#</th><th>نام کالا</th><th>تعداد</th><th>فروش کل</th><th>بهای تمامشده</th><th>سود خالص</th><th>حاشیه سود</th></tr></thead>
630
<tbody>
tests/report-historical-cogs-integration.test.mjs
new
+90
@@ -0,0 +1,90 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import 'fake-indexeddb/auto';
4
+import { StorageService } from '../src/core/StorageService.js';
5
+import { Auth } from '../src/core/Auth.js';
6
+import { CompanyService } from '../src/core/CompanyService.js';
7
+
8
+globalThis.window ??= globalThis;
9
+const company = 'report-historical-cogs-fixture';
10
+const filter = { preset: 'custom', from: '1405/01/01', to: '1406/01/01' };
11
+const base = {companyId:company, ownerUserId:'report-test-user'};
12
+async function setup() {
13
+ await StorageService.clearAll();
14
+ Auth.currentUser={id:'report-test-user',username:'admin',role:'admin'};
15
+ await StorageService.put('companies',{id:company,name:'Synthetic report company'});
16
+ CompanyService.activeCompanyId=company;
17
+}
18
+async function put(store,rows) {
19
+ for(const row of rows) await StorageService.put(store,{...base,...row});
20
+}
21
+const invoice=(id,kind,productId,qty,net,discount=0)=>({
22
+ id,kind,date:'1405/07/01',isPreInvoice:false,financePosted:true,
23
+ subtotal:net+discount,totalDiscount:discount,grandTotal:net,
24
+ paidAmount:0,remaining:net,
25
+ items:[{productId,productName:'Synthetic item',qty,price:net/qty,
26
+ lineTotal:net,discount:0}]
27
+});
28
+const move=(id,refId,type,cost)=>({
29
+ id,refId,refType:'invoice',productId:'p',type,cost,qty:1,date:'1405/07/01'
30
+});
31
+
32
+test('P0: posted report COGS and product margins are independent from mutable current buyPrice',async()=>{
33
+ await setup();
34
+ await put('products',[{id:'p',name:'Synthetic item',buyPrice:75,
35
+ sellPrice:300,trackInventory:true}]);
36
+ await put('invoices',[
37
+ invoice('sale-1','sale','p',2,400),
38
+ invoice('nonformal-1','non_formal','p',1,280,20),
39
+ invoice('return-1','sale_return','p',1,150,50)
40
+ ]);
41
+ await put('stock_movements',[
42
+ move('out-1','sale-1','out',120),
43
+ move('out-2','nonformal-1','out',50),
44
+ move('return-cost','return-1','in',60)
45
+ ]);
46
+ const {ReportController}=await import('../src/controllers/ReportController.js');
47
+ const first=await ReportController.getProfitLoss(filter);
48
+ assert.equal(first.grossSales,700);
49
+ assert.equal(first.salesDiscounts,20);
50
+ assert.equal(first.returnsAmount,150);
51
+ assert.equal(first.netSales,530);
52
+ assert.equal(first.cogs,110);
53
+ assert.equal(first.grossProfit,420);
54
+ assert.equal(first.costBasis.recordedLines,3);
55
+ assert.equal(first.costBasis.estimatedLines,0);
56
+
57
+ const productProfit=await ReportController.getProductProfitability(filter);
58
+ const topSales=await ReportController.getSalesAnalysis(filter);
59
+ assert.equal(productProfit[0].cogs,170);
60
+ assert.equal(topSales.topProductsBySales[0].cogs,170);
61
+
62
+ const product=await StorageService.get('products','p');
63
+ await StorageService.put('products',{...product,buyPrice:999});
64
+ const second=await ReportController.getProfitLoss(filter);
65
+ const updated=await ReportController.getProductProfitability(filter);
66
+ assert.equal(second.cogs,110);
67
+ assert.equal(second.grossProfit,420);
68
+ assert.equal(updated[0].cogs,170);
69
+});
70
+
71
+test('P0: legacy invoices are estimated, and return-only periods retain negative COGS',async()=>{
72
+ await setup();
73
+ await put('products',[{id:'p',name:'Synthetic item',buyPrice:100,trackInventory:true}]);
74
+ await put('invoices',[
75
+ {...invoice('legacy','sale','p',1,180),financePosted:false},
76
+ invoice('return','sale_return','p',1,150)
77
+ ]);
78
+ await put('stock_movements',[move('returned','return','in',60)]);
79
+ const {ReportController}=await import('../src/controllers/ReportController.js');
80
+ const pl=await ReportController.getProfitLoss(filter);
81
+ assert.equal(pl.cogs,40);
82
+ assert.equal(pl.costBasis.estimatedLines,1);
83
+ assert.equal(pl.costBasis.recordedLines,1);
84
+ // An isolated return is an inventory-cost credit, not an invalid zero cost.
85
+ const onlyReturns={...filter,from:'1405/07/01',to:'1405/07/01'};
86
+ await StorageService.delete('invoices','legacy');
87
+ const returnOnly=await ReportController.getProfitLoss(onlyReturns);
88
+ assert.equal(returnOnly.cogs,-60);
89
+ assert.equal(returnOnly.grossProfit,-90);
90
+});
tests/report-historical-cogs.test.mjs
new
+70
@@ -0,0 +1,70 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { buildInvoiceCosting } from '../src/core/ReportCosting.mjs';
4
+
5
+const sale = (id, productId, qty=2, extra={}) =>
6
+ ({ id, kind:'sale', financePosted:true, items:[{productId,qty}], ...extra });
7
+const movement = (refId, productId, type, cost) =>
8
+ ({ refId, productId, refType:'invoice', type, cost });
9
+
10
+test('posted sale COGS never changes when current catalog purchase price changes', () => {
11
+ const invoice=sale('sale-1','p',2);
12
+ const movements=[movement('sale-1','p','out',120)];
13
+ const before=buildInvoiceCosting([invoice],[{id:'p',buyPrice:60}],movements);
14
+ const after=buildInvoiceCosting([invoice],[{id:'p',buyPrice:900}],movements);
15
+ assert.equal(before.byInvoice.get('sale-1').total,120);
16
+ assert.equal(after.byInvoice.get('sale-1').total,120);
17
+ assert.equal(after.summary.recordedLines,1);
18
+ assert.equal(after.summary.estimatedLines,0);
19
+});
20
+
21
+test('posted returns use actual original stock cost and do not use catalog cost', () => {
22
+ const records=[sale('sale-1','p',2),
23
+ sale('return-1','p',1,{kind:'sale_return'})];
24
+ const costs=buildInvoiceCosting(records,[{id:'p',buyPrice:777}],[
25
+ movement('sale-1','p','out',120),
26
+ movement('return-1','p','in',60)
27
+ ]);
28
+ assert.equal(costs.byInvoice.get('sale-1').total-
29
+ costs.byInvoice.get('return-1').total,60);
30
+ assert.equal(costs.summary.recordedLines,2);
31
+});
32
+
33
+test('multiple invoice lines for the same product allocate recorded cost only once', () => {
34
+ const inv=sale('s','p',1,{items:[{productId:'p',qty:1},{productId:'p',qty:2}]});
35
+ const result=buildInvoiceCosting([inv],[{id:'p',buyPrice:500}],
36
+ [movement('s','p','out',250)]);
37
+ assert.deepEqual(result.byInvoice.get('s').lines.map(x=>x.cost),[83,167]);
38
+ assert.equal(result.byInvoice.get('s').total,250);
39
+});
40
+
41
+test('legacy data is explicitly estimated and missing catalog cost is flagged', () => {
42
+ const rows=[sale('legacy','p',1,{financePosted:false}),
43
+ sale('missing','deleted',1,{financePosted:false}),
44
+ sale('service','svc',1,{financePosted:true})];
45
+ const result=buildInvoiceCosting(rows,[{id:'p',buyPrice:42},
46
+ {id:'svc',trackInventory:false,buyPrice:1000}],[]);
47
+ assert.equal(result.byInvoice.get('legacy').total,42);
48
+ assert.equal(result.byInvoice.get('missing').lines[0].source,'missing');
49
+ assert.equal(result.byInvoice.get('service').total,0);
50
+ assert.deepEqual(result.summary,{recordedLines:0,estimatedLines:1,
51
+ missingCostLines:1,serviceLines:1});
52
+});
53
+
54
+test('reject unsafe monetary movement and calculated estimates instead of silently coercing', () => {
55
+ assert.throws(()=>buildInvoiceCosting([sale('s','p')],[{id:'p',buyPrice:4}],
56
+ [movement('s','p','out',1.5)]),/نامعتبر/);
57
+ assert.throws(()=>buildInvoiceCosting([sale('s','p')],[{id:'p',buyPrice:Number.MAX_SAFE_INTEGER}],
58
+ []),/نامعتبر/);
59
+});
60
+
61
+test('historical movement uses the matching invoice, product and direction only', () => {
62
+ const result=buildInvoiceCosting([sale('s','p')],[{id:'p',buyPrice:11}],[
63
+ movement('other','p','out',800),
64
+ movement('s','other','out',900),
65
+ movement('s','p','in',700),
66
+ movement('s','p','out',35)
67
+ ]);
68
+ assert.equal(result.byInvoice.get('s').total,35);
69
+ assert.equal(result.summary.recordedLines,1);
70
+});