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

fix(reports): use historical inventory cost and net return allocation

davoodmehraban89 committed Nov 1, 2026 at 15:12 UTC cf8bb92a260d2c106dbca3cf050ac6e4abe7f6a7
3 files changed +444 -160
src/controllers/ReportController.js
+265 -159
@@ -2,7 +2,7 @@
2 // ReportController — محاسبات سود و زیان و تحلیل مالی
3 // ============================================================
4
5 -import { StorageService } from '../core/StorageService.js';
5 +import { allocateDiscount } from '../core/RetailFinanceCore.mjs';
6 import { Auth } from '../core/Auth.js';
7 import { DataScope } from '../core/DataScope.js';
8 import { Jalali } from '../utils/Jalali.js';
@@ -11,15 +11,16 @@ class ReportControllerImpl {
11 async _loadData() {
12 const user = Auth.current();
13 if (!user) throw new Error('کاربر یافت نشد');
14 - const [invoices, products, expenses, contacts, cheques, treasury] = await Promise.all([
14 + const [invoices, products, expenses, contacts, cheques, treasury, stockMovements] = await Promise.all([
15 DataScope.list('invoices'),
16 DataScope.list('products'),
17 DataScope.list('expenses'),
18 DataScope.list('contacts'),
19 DataScope.list('cheques'),
20 - DataScope.list('treasury')
20 + DataScope.list('treasury'),
21 + DataScope.list('stock_movements')
22 ]);
22 - return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [] };
23 + return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [], stockMovements: stockMovements || [] };
24 }
25
26 _parseJalali(str) {
@@ -104,68 +105,249 @@ class ReportControllerImpl {
105 return { from, to };
106 }
107
108 + _netInvoiceLines(invoice) {
109 + const source = Array.isArray(invoice?.items) ? invoice.items : [];
110 + if (!source.length) return { items: [], allocationComplete: true };
111 + const items = [];
112 + for (const item of source) {
113 + let lineTotal = Number(item.lineTotal);
114 + if (!Number.isSafeInteger(lineTotal) || lineTotal < 0) {
115 + const gross = Number(item.qty) * Number(item.price);
116 + const rowDiscount = Number(item.discount ?? 0);
117 + const fallback = Math.round(gross) - rowDiscount;
118 + if (!Number.isSafeInteger(fallback) || fallback < 0) {
119 + return {
120 + items: source.map(row => ({ ...row, netLineTotal: Number(row.lineTotal) || 0 })),
121 + allocationComplete: false
122 + };
123 + }
124 + lineTotal = fallback;
125 + }
126 + items.push({ ...item, lineTotal });
127 + }
128 + const total = items.reduce((sum, item) => {
129 + const next = sum + item.lineTotal;
130 + return Number.isSafeInteger(next) ? next : NaN;
131 + }, 0);
132 + const discount = Number(invoice.totalDiscount ?? 0);
133 + if (!Number.isSafeInteger(total) || !Number.isSafeInteger(discount) ||
134 + discount < 0 || discount > total) {
135 + return {
136 + items: items.map(item => ({ ...item, netLineTotal: item.lineTotal })),
137 + allocationComplete: false
138 + };
139 + }
140 + try {
141 + return { items: allocateDiscount(items, discount), allocationComplete: true };
142 + } catch {
143 + return {
144 + items: items.map(item => ({ ...item, netLineTotal: item.lineTotal })),
145 + allocationComplete: false
146 + };
147 + }
148 + }
149 +
150 + _invoiceTotals(invoice) {
151 + const normalized = this._netInvoiceLines(invoice);
152 + const fallbackSubtotal = normalized.items.reduce((sum, item) => {
153 + const next = sum + item.lineTotal;
154 + return Number.isSafeInteger(next) ? next : NaN;
155 + }, 0);
156 + const storedSubtotal = Number(invoice.subtotal);
157 + const subtotal = Number.isSafeInteger(storedSubtotal) && storedSubtotal >= 0
158 + ? storedSubtotal : fallbackSubtotal;
159 + const storedDiscount = Number(invoice.totalDiscount ?? 0);
160 + const validDiscount = Number.isSafeInteger(subtotal) &&
161 + Number.isSafeInteger(storedDiscount) && storedDiscount >= 0 && storedDiscount <= subtotal;
162 + const normalizedSubtotal = normalized.items.reduce((sum, item) => {
163 + const next = sum + item.lineTotal;
164 + return Number.isSafeInteger(next) ? next : NaN;
165 + }, 0);
166 + const discount = validDiscount ? storedDiscount : 0;
167 + return {
168 + subtotal,
169 + discount,
170 + net: Number.isSafeInteger(subtotal) ? subtotal - discount : 0,
171 + valid: validDiscount && normalized.allocationComplete &&
172 + Number.isSafeInteger(normalizedSubtotal) && normalizedSubtotal === subtotal
173 + };
174 + }
175 +
176 + _stockMovementCostIndex(stockMovements = []) {
177 + const costs = new Map();
178 + for (const movement of stockMovements) {
179 + if (movement.refType !== 'invoice' || !movement.refId || !movement.productId ||
180 + !['in', 'out'].includes(movement.type) ||
181 + !Number.isSafeInteger(movement.cost) || movement.cost < 0) continue;
182 + const key = JSON.stringify([movement.refId, movement.productId, movement.type]);
183 + const next = (costs.get(key) || 0) + movement.cost;
184 + if (!Number.isSafeInteger(next)) throw Error('سرریز بهای تمام‌شده در گردش انبار');
185 + costs.set(key, next);
186 + }
187 + return costs;
188 + }
189 +
190 + _invoiceProductCosts(invoice, productsById, movementCosts) {
191 + const direction = invoice.kind === 'sale' ? 'out' :
192 + invoice.kind === 'sale_return' ? 'in' : null;
193 + const quantities = new Map();
194 + for (const item of (invoice.items || [])) {
195 + if (!item.productId) continue;
196 + const qty = Number(item.qty);
197 + const previous = quantities.get(item.productId) || 0;
198 + const next = previous + qty;
199 + if (!Number.isFinite(qty) || qty < 0 || !Number.isFinite(next))
200 + throw Error('مقدار کالا برای گزارش سودآوری نامعتبر است');
201 + quantities.set(item.productId, next);
202 + }
203 + const byProduct = new Map();
204 + const counts = { historical: 0, estimated: 0, unknown: 0 };
205 + for (const [productId, qty] of quantities) {
206 + const movementKey = JSON.stringify([invoice.id, productId, direction]);
207 + if (direction && movementCosts.has(movementKey)) {
208 + byProduct.set(productId, { cost: movementCosts.get(movementKey), basis: 'historical' });
209 + counts.historical++;
210 + continue;
211 + }
212 + const product = productsById.get(productId);
213 + if (product && product.trackInventory === false) {
214 + byProduct.set(productId, { cost: 0, basis: 'not-applicable' });
215 + continue;
216 + }
217 + const buyPrice = Number(product?.buyPrice);
218 + const estimated = buyPrice * qty;
219 + if (product && Number.isSafeInteger(buyPrice) && buyPrice >= 0 &&
220 + Number.isSafeInteger(Math.round(estimated)) && estimated >= 0) {
221 + byProduct.set(productId, { cost: Math.round(estimated), basis: 'estimated' });
222 + counts.estimated++;
223 + } else {
224 + byProduct.set(productId, { cost: 0, basis: 'unknown' });
225 + counts.unknown++;
226 + }
227 + }
228 + return { byProduct, counts };
229 + }
230 +
231 + _costBasisSummary(counts) {
232 + const historical = counts.historical || 0;
233 + const estimated = counts.estimated || 0;
234 + const unknown = counts.unknown || 0;
235 + const basis = unknown ? 'incomplete' :
236 + (historical && estimated) ? 'mixed' :
237 + estimated ? 'estimated' :
238 + historical ? 'historical' : 'not-applicable';
239 + return { basis, historical, estimated, unknown };
240 + }
241 +
242 + _buildProductStats(invoices, products, stockMovements) {
243 + const productsById = new Map(products.map(product => [product.id, product]));
244 + const movementCosts = this._stockMovementCostIndex(stockMovements);
245 + const stats = new Map();
246 + for (const invoice of invoices) {
247 + if (!['sale', 'sale_return'].includes(invoice.kind) || invoice.isPreInvoice) continue;
248 + const isReturn = invoice.kind === 'sale_return';
249 + const sign = isReturn ? -1 : 1;
250 + const normalized = this._netInvoiceLines(invoice);
251 + const byProduct = new Map();
252 + for (const item of normalized.items) {
253 + const productId = item.productId || null;
254 + const key = productId || 'unknown_' + (item.productName || '');
255 + const row = byProduct.get(key) || {
256 + productId,
257 + productName: item.productName || 'ناشناس',
258 + unit: item.unit || 'عدد',
259 + qty: 0,
260 + totalSales: 0
261 + };
262 + row.qty += Number(item.qty) || 0;
263 + row.totalSales += Number(item.netLineTotal) || 0;
264 + byProduct.set(key, row);
265 + }
266 + const costs = this._invoiceProductCosts(invoice, productsById, movementCosts);
267 + for (const [key, item] of byProduct) {
268 + const row = stats.get(key) || {
269 + productId: item.productId,
270 + productName: item.productName,
271 + unit: item.unit,
272 + qty: 0,
273 + totalSales: 0,
274 + cogs: 0,
275 + profit: 0,
276 + margin: 0,
277 + count: 0,
278 + returnCount: 0,
279 + costBasisCounts: { historical: 0, estimated: 0, unknown: 0 },
280 + discountAllocationIncomplete: false
281 + };
282 + row.qty += sign * item.qty;
283 + row.totalSales += sign * item.totalSales;
284 + if (isReturn) row.returnCount++;
285 + else row.count++;
286 + if (item.productId) {
287 + const cost = costs.byProduct.get(item.productId);
288 + if (cost?.basis === 'historical' || cost?.basis === 'estimated') {
289 + row.cogs += sign * cost.cost;
290 + row.costBasisCounts[cost.basis]++;
291 + } else if (cost?.basis === 'unknown') {
292 + row.costBasisCounts.unknown++;
293 + }
294 + }
295 + row.discountAllocationIncomplete ||= !normalized.allocationComplete;
296 + stats.set(key, row);
297 + }
298 + }
299 + return [...stats.values()].map(row => {
300 + row.profit = row.totalSales - row.cogs;
301 + row.margin = row.totalSales > 0 ? (row.profit / row.totalSales) * 100 : 0;
302 + row.costBasis = this._costBasisSummary(row.costBasisCounts).basis;
303 + row.costBasisDetails = this._costBasisSummary(row.costBasisCounts);
304 + return row;
305 + });
306 + }
307 +
308 // ============================================================
309 // ۱. سود و زیان
310 // ============================================================
311 async getProfitLoss(filter = {}, data = null) {
111 - const { invoices, products, expenses } = data || await this._loadData();
312 + const { invoices, products, expenses, stockMovements = [] } = data || await this._loadData();
313 const { from, to } = this._getRange(filter);
113 -
114 - // فقط فاکتورهای فروش (بدون پیش‌فاکتور)
115 - const salesInRange = invoices.filter(i =>
116 - i.kind === 'sale' &&
117 - !i.isPreInvoice &&
118 - this._inRange(i.date, from, to)
314 + const inRange = invoices.filter(invoice => this._inRange(invoice.date, from, to));
315 + const salesInRange = inRange.filter(invoice =>
316 + invoice.kind === 'sale' && !invoice.isPreInvoice
317 );
120 -
121 - // برگشت از فروش
122 - const returnsInRange = invoices.filter(i =>
123 - i.kind === 'sale_return' &&
124 - !i.isPreInvoice &&
125 - this._inRange(i.date, from, to)
318 + const returnsInRange = inRange.filter(invoice =>
319 + invoice.kind === 'sale_return' && !invoice.isPreInvoice
320 );
321
128 - // فروش ناخالص = مجموع فروش بدون مالیات و تخفیف نهایی
129 - const grossSales = salesInRange.reduce((s, i) => s + (Number(i.subtotal) || 0), 0);
130 - 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);
322 + const salesTotals = salesInRange.map(invoice => this._invoiceTotals(invoice));
323 + const returnTotals = returnsInRange.map(invoice => this._invoiceTotals(invoice));
324 + const grossSales = salesTotals.reduce((sum, totals) => sum + totals.subtotal, 0);
325 + const salesDiscounts = salesTotals.reduce((sum, totals) => sum + totals.discount, 0);
326 + const returnsAmount = returnTotals.reduce((sum, totals) => sum + totals.net, 0);
327 const netSales = grossSales - salesDiscounts - returnsAmount;
328
134 - // بهای تمام‌شده (COGS) — از قیمت خرید هر کالا
329 + const productsById = new Map(products.map(product => [product.id, product]));
330 + const movementCosts = this._stockMovementCostIndex(stockMovements);
331 + const costCounts = { historical: 0, estimated: 0, unknown: 0 };
332 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);
159 - const grossProfit = netSales - cogs;
160 - const grossMargin = netSales > 0 ? (grossProfit / netSales) * 100 : 0;
161 -
162 - // هزینه‌های عملیاتی و سایر درآمدها
163 - const expensesInRange = expenses.filter(e => this._inRange(e.date, from, to));
164 - const operatingExpenses = expensesInRange.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0);
165 - const otherIncome = expensesInRange.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0);
333 + for (const [rows, sign] of [[salesInRange, 1], [returnsInRange, -1]]) {
334 + for (const invoice of rows) {
335 + const result = this._invoiceProductCosts(invoice, productsById, movementCosts);
336 + for (const cost of result.byProduct.values()) cogs += sign * cost.cost;
337 + for (const key of Object.keys(costCounts)) costCounts[key] += result.counts[key];
338 + }
339 + }
340
167 - const netProfit = grossProfit - operatingExpenses + otherIncome;
168 - const netMargin = netSales > 0 ? (netProfit / netSales) * 100 : 0;
341 + const expensesInRange = expenses.filter(expense => this._inRange(expense.date, from, to));
342 + const operatingExpenses = expensesInRange
343 + .filter(expense => expense.kind === 'expense')
344 + .reduce((sum, expense) => sum + (Number(expense.amount) || 0), 0);
345 + const otherIncome = expensesInRange
346 + .filter(expense => expense.kind === 'income')
347 + .reduce((sum, expense) => sum + (Number(expense.amount) || 0), 0);
348 + const netProfit = netSales - cogs - operatingExpenses + otherIncome;
349 + const netMargin = netSales !== 0 ? (netProfit / netSales) * 100 : 0;
350 + const costBasisDetails = this._costBasisSummary(costCounts);
351
352 return {
353 grossSales,
@@ -173,8 +355,8 @@ class ReportControllerImpl {
355 returnsAmount,
356 netSales,
357 cogs,
176 - grossProfit,
177 - grossMargin,
358 + grossProfit: netSales - cogs,
359 + grossMargin: netSales !== 0 ? ((netSales - cogs) / netSales) * 100 : 0,
360 operatingExpenses,
361 otherIncome,
362 netProfit,
@@ -182,69 +364,37 @@ class ReportControllerImpl {
364 invoiceCount: salesInRange.length,
365 returnCount: returnsInRange.length,
366 periodFrom: from,
185 - periodTo: to
367 + periodTo: to,
368 + costBasis: costBasisDetails.basis,
369 + costBasisDetails,
370 + discountAllocationIncomplete: [...salesTotals, ...returnTotals].some(totals => !totals.valid)
371 };
372 }
373
189 - // ============================================================
190 - // ۲. تحلیل فروش (Top Products & Customers)
191 - // ============================================================
374 async getSalesAnalysis(filter = {}, data = null) {
193 - const { invoices, products, contacts } = data || await this._loadData();
375 + const { invoices, products, contacts, stockMovements = [] } = data || await this._loadData();
376 const { from, to } = this._getRange(filter);
195 -
196 - const salesInRange = invoices.filter(i =>
197 - i.kind === 'sale' &&
198 - !i.isPreInvoice &&
199 - this._inRange(i.date, from, to)
377 + const rows = invoices.filter(invoice =>
378 + ['sale', 'sale_return'].includes(invoice.kind) &&
379 + !invoice.isPreInvoice &&
380 + this._inRange(invoice.date, from, to)
381 );
201 -
202 - // محصولات
203 - const productStats = {};
204 - const productMap = {};
205 - products.forEach(p => productMap[p.id] = p);
206 -
207 - salesInRange.forEach(inv => {
208 - (inv.items || []).forEach(it => {
209 - const key = it.productId || 'unknown_' + (it.productName || '');
210 - if (!productStats[key]) {
211 - productStats[key] = {
212 - productId: it.productId,
213 - productName: it.productName || 'ناشناس',
214 - qty: 0,
215 - totalSales: 0,
216 - cogs: 0,
217 - count: 0
218 - };
219 - }
220 - const qty = Number(it.qty) || 0;
221 - 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;
224 - productStats[key].qty += qty;
225 - productStats[key].totalSales += lineTotal;
226 - productStats[key].cogs += buyPrice * qty;
227 - productStats[key].count += 1;
228 - });
229 - });
230 -
231 - const topProductsBySales = Object.values(productStats)
232 - .map(s => ({ ...s, profit: s.totalSales - s.cogs }))
382 + const productStats = this._buildProductStats(rows, products, stockMovements);
383 + const topProductsBySales = [...productStats]
384 .sort((a, b) => b.totalSales - a.totalSales)
385 .slice(0, 10);
235 -
236 - const topProductsByQty = Object.values(productStats)
386 + const topProductsByQty = [...productStats]
387 .sort((a, b) => b.qty - a.qty)
388 .slice(0, 10);
389
240 - // مشتریان
390 + const salesInRange = rows.filter(invoice => invoice.kind === 'sale');
391 const contactStats = {};
242 - salesInRange.forEach(inv => {
243 - const key = inv.contactId || 'unknown';
392 + salesInRange.forEach(invoice => {
393 + const key = invoice.contactId || 'unknown';
394 if (!contactStats[key]) {
395 contactStats[key] = {
246 - contactId: inv.contactId,
247 - contactName: inv.contactName || 'ناشناس',
396 + contactId: invoice.contactId,
397 + contactName: invoice.contactName || 'ناشناس',
398 invoiceCount: 0,
399 totalSales: 0,
400 totalPaid: 0,
@@ -252,15 +402,14 @@ class ReportControllerImpl {
402 };
403 }
404 contactStats[key].invoiceCount += 1;
255 - contactStats[key].totalSales += Number(inv.grandTotal) || 0;
256 - contactStats[key].totalPaid += Number(inv.paidAmount) || 0;
257 - contactStats[key].totalRemaining += Number(inv.remaining) || 0;
405 + contactStats[key].totalSales += Number(invoice.grandTotal) || 0;
406 + contactStats[key].totalPaid += Number(invoice.paidAmount) || 0;
407 + contactStats[key].totalRemaining += Number(invoice.remaining) || 0;
408 });
409
410 const topCustomers = Object.values(contactStats)
411 .sort((a, b) => b.totalSales - a.totalSales)
412 .slice(0, 10);
263 -
413 return {
414 topProductsBySales,
415 topProductsByQty,
@@ -269,61 +418,18 @@ class ReportControllerImpl {
418 };
419 }
420
272 - // ============================================================
273 - // ۳. سودآوری کالا (همه کالاها)
274 - // ============================================================
421 async getProductProfitability(filter = {}, data = null) {
276 - const { invoices, products } = data || await this._loadData();
422 + const { invoices, products, stockMovements = [] } = data || await this._loadData();
423 const { from, to } = this._getRange(filter);
278 -
279 - const salesInRange = invoices.filter(i =>
280 - i.kind === 'sale' &&
281 - !i.isPreInvoice &&
282 - this._inRange(i.date, from, to)
424 + const rows = invoices.filter(invoice =>
425 + ['sale', 'sale_return'].includes(invoice.kind) &&
426 + !invoice.isPreInvoice &&
427 + this._inRange(invoice.date, from, to)
428 );
284 -
285 - const productMap = {};
286 - products.forEach(p => productMap[p.id] = p);
287 -
288 - const stats = {};
289 - salesInRange.forEach(inv => {
290 - (inv.items || []).forEach(it => {
291 - const key = it.productId || 'unknown_' + (it.productName || '');
292 - if (!stats[key]) {
293 - const p = productMap[it.productId];
294 - stats[key] = {
295 - productId: it.productId,
296 - productName: it.productName || 'ناشناس',
297 - unit: it.unit || 'عدد',
298 - qty: 0,
299 - totalSales: 0,
300 - cogs: 0,
301 - profit: 0,
302 - margin: 0
303 - };
304 - }
305 - const qty = Number(it.qty) || 0;
306 - 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;
309 - stats[key].qty += qty;
310 - stats[key].totalSales += lineTotal;
311 - stats[key].cogs += buyPrice * qty;
312 - });
313 - });
314 -
315 - const rows = Object.values(stats).map(s => {
316 - s.profit = s.totalSales - s.cogs;
317 - s.margin = s.totalSales > 0 ? (s.profit / s.totalSales) * 100 : 0;
318 - return s;
319 - }).sort((a, b) => b.profit - a.profit);
320 -
321 - return rows;
429 + return this._buildProductStats(rows, products, stockMovements)
430 + .sort((a, b) => b.profit - a.profit);
431 }
432
324 - // ============================================================
325 - // ۴. گزارش مشتریان
326 - // ============================================================
433 async getCustomerReport(filter = {}, data = null) {
434 const { invoices, contacts } = data || await this._loadData();
435 const { from, to } = this._getRange(filter);
src/views/ReportsView.js
+30
@@ -181,6 +181,7 @@ class ReportsViewImpl {
181 // ============================================================
182 renderPLTab() {
183 const pl = cache.pl || {};
184 + const costNotice = this._costBasisNotice(pl.costBasis, pl.costBasisDetails, pl.discountAllocationIncomplete);
185
186 const rows = [
187 { label: 'فروش ناخالص', value: pl.grossSales, color: 'var(--text)', bold: false, sign: '+' },
@@ -212,6 +213,7 @@ class ReportsViewImpl {
213 const marginLabel = pl.netProfit >= 0 ? 'حاشیه سود خالص' : 'حاشیه زیان خالص';
214
215 return `
216 + ${costNotice}
217 <div class="grid-kpi">
218 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
219 <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📊</div>
@@ -396,12 +398,23 @@ class ReportsViewImpl {
398 const list = cache.products || [];
399 const totalSales = list.reduce((s, p) => s + p.totalSales, 0);
400 const totalProfit = list.reduce((s, p) => s + p.profit, 0);
401 + const costCounts = list.reduce((counts, product) => {
402 + for (const key of ['historical', 'estimated', 'unknown'])
403 + counts[key] += product.costBasisDetails?.[key] || 0;
404 + return counts;
405 + }, { historical: 0, estimated: 0, unknown: 0 });
406 + const costBasis = costCounts.unknown ? 'incomplete' :
407 + (costCounts.historical && costCounts.estimated) ? 'mixed' :
408 + costCounts.estimated ? 'estimated' : costCounts.historical ? 'historical' : 'not-applicable';
409 + const discountAllocationIncomplete = list.some(product => product.discountAllocationIncomplete);
410 + const costNotice = this._costBasisNotice(costBasis, costCounts, discountAllocationIncomplete);
411 const totalPages = Math.max(1, Math.ceil(list.length / PRODUCTS_PAGE_SIZE));
412 productsPage = Math.min(totalPages, Math.max(1, productsPage));
413 const startIndex = (productsPage - 1) * PRODUCTS_PAGE_SIZE;
414 const pageRows = list.slice(startIndex, startIndex + PRODUCTS_PAGE_SIZE);
415
416 return `
417 + ${costNotice}
418 <div class="grid-kpi">
419 <div class="card kpi-card" style="margin:0">
420 <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📦</div>
@@ -700,6 +713,23 @@ class ReportsViewImpl {
713 return str.length > len ? str.slice(0, len) + '…' : str;
714 }
715
716 + _costBasisNotice(basis, details = {}, discountAllocationIncomplete = false) {
717 + const messages = [];
718 + const estimated = details.estimated || 0;
719 + const unknown = details.unknown || 0;
720 + if (estimated) messages.push(
721 + Formatters.number(estimated) + ' گروه کالا با قیمت خرید فعلی برآورد شده‌اند؛ سود تاریخی آن‌ها قطعی نیست.'
722 + );
723 + if (unknown) messages.push(
724 + Formatters.number(unknown) + ' گروه کالا بهای تمام‌شده قابل بازیابی ندارند؛ سود نمایش‌داده‌شده ناقص است.'
725 + );
726 + if (discountAllocationIncomplete) messages.push(
727 + 'توزیع تخفیف کل فاکتور روی ردیف کالاها برای بخشی از سوابق قابل بازسازی نیست.'
728 + );
729 + if (!messages.length) return '';
730 + return '<div class="card" role="note" style="border-right:4px solid var(--warning);font-size:12px;line-height:1.9;color:var(--text-muted)"><strong>محدودیت دقت گزارش:</strong> ' + messages.join(' ') + '</div>';
731 + }
732 +
733 _esc(s) {
734 if (!s) return '';
735 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
tests/report-controller-bundle.test.mjs
+149 -1
@@ -12,7 +12,7 @@ const fixture = {
12 subtotal: 100, totalDiscount: 10, grandTotal: 90, paidAmount: 30,
13 remaining: 60, contactId: 'contact-1', contactName: 'Synthetic customer',
14 items: [{ productId: 'product-1', productName: 'Synthetic product',
15 - unit: 'عدد', qty: 2, price: 50, lineTotal: 90 }]
15 + unit: 'عدد', qty: 2, price: 50, lineTotal: 100 }]
16 },
17 {
18 id: 'return-1', kind: 'sale_return', isPreInvoice: false, date: '1405/01/03',
@@ -55,6 +55,10 @@ test('report bundle reads one company-scoped snapshot and preserves all four rep
55 assert.equal(bundle.sales.invoiceCount, 1);
56 assert.equal(bundle.products.length, 1);
57 assert.equal(bundle.customers[0].totalReturns, 10);
58 + assert.equal(bundle.pl.costBasis, 'estimated');
59 + assert.equal(bundle.products[0].totalSales, 80);
60 + assert.equal(bundle.products[0].cogs, 20);
61 + assert.equal(bundle.products[0].profit, 60);
62 } finally {
63 ReportController._loadData = originalLoad;
64 }
@@ -75,3 +79,147 @@ test('standalone report APIs retain their original self-loading contract', async
79 ReportController._loadData = originalLoad;
80 }
81 });
82 +
83 +
84 +test('posted reports use immutable inventory movement cost, net returns and allocated invoice discounts', async () => {
85 + const originalLoad = ReportController._loadData;
86 + const data = {
87 + invoices: [
88 + {
89 + id: 'historical-sale', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
90 + subtotal: 200, totalDiscount: 20, grandTotal: 180, paidAmount: 180, remaining: 0,
91 + items: [
92 + { productId: 'product-1', productName: 'Product one', unit: 'عدد', qty: 2, price: 50, lineTotal: 100 },
93 + { productId: 'product-2', productName: 'Product two', unit: 'عدد', qty: 1, price: 100, lineTotal: 100 }
94 + ]
95 + },
96 + {
97 + id: 'historical-return', kind: 'sale_return', isPreInvoice: false, date: '1405/01/03',
98 + subtotal: 30, totalDiscount: 5, grandTotal: 25, paidAmount: 0, remaining: 25,
99 + items: [{ productId: 'product-1', productName: 'Product one', unit: 'عدد', qty: 1, price: 30, lineTotal: 30 }]
100 + }
101 + ],
102 + products: [
103 + { id: 'product-1', name: 'Product one', buyPrice: 999, trackInventory: true },
104 + { id: 'product-2', name: 'Product two', buyPrice: 888, trackInventory: true }
105 + ],
106 + stockMovements: [
107 + { id: 'move-sale-1', refType: 'invoice', refId: 'historical-sale', productId: 'product-1', type: 'out', cost: 40 },
108 + { id: 'move-sale-2', refType: 'invoice', refId: 'historical-sale', productId: 'product-2', type: 'out', cost: 30 },
109 + { id: 'move-return-1', refType: 'invoice', refId: 'historical-return', productId: 'product-1', type: 'in', cost: 10 }
110 + ],
111 + expenses: [{ id: 'expense', kind: 'expense', date: '1405/01/02', amount: 5 },
112 + { id: 'income', kind: 'income', date: '1405/01/02', amount: 2 }],
113 + contacts: [], cheques: [], treasury: []
114 + };
115 + ReportController._loadData = async () => data;
116 + try {
117 + const bundle = await ReportController.getReportBundle(filter);
118 + assert.equal(bundle.pl.grossSales, 200);
119 + assert.equal(bundle.pl.salesDiscounts, 20);
120 + assert.equal(bundle.pl.returnsAmount, 25);
121 + assert.equal(bundle.pl.netSales, 155);
122 + assert.equal(bundle.pl.cogs, 60, 'current product buyPrice must not rewrite historical weighted-average cost');
123 + assert.equal(bundle.pl.grossProfit, 95);
124 + assert.equal(bundle.pl.netProfit, 92);
125 + assert.equal(bundle.pl.costBasis, 'historical');
126 + assert.deepEqual(bundle.pl.costBasisDetails, { basis: 'historical', historical: 3, estimated: 0, unknown: 0 });
127 + const one = bundle.products.find(row => row.productId === 'product-1');
128 + const two = bundle.products.find(row => row.productId === 'product-2');
129 + assert.deepEqual({ qty: one.qty, sales: one.totalSales, cogs: one.cogs, profit: one.profit },
130 + { qty: 1, sales: 65, cogs: 30, profit: 35 });
131 + assert.deepEqual({ qty: two.qty, sales: two.totalSales, cogs: two.cogs, profit: two.profit },
132 + { qty: 1, sales: 90, cogs: 30, profit: 60 });
133 + assert.equal(bundle.sales.topProductsBySales[0].productId, 'product-2');
134 + } finally {
135 + ReportController._loadData = originalLoad;
136 + }
137 +});
138 +
139 +test('a return in a later period keeps its historical COGS credit instead of clamping period COGS to zero', async () => {
140 + const originalLoad = ReportController._loadData;
141 + ReportController._loadData = async () => ({
142 + invoices: [{
143 + id: 'late-return', kind: 'sale_return', isPreInvoice: false, date: '1405/01/03',
144 + subtotal: 20, totalDiscount: 0, grandTotal: 20,
145 + items: [{ productId: 'product-1', productName: 'Product one', qty: 1, price: 20, lineTotal: 20 }]
146 + }],
147 + products: [{ id: 'product-1', name: 'Product one', buyPrice: 999, trackInventory: true }],
148 + stockMovements: [{ id: 'late-return-move', refType: 'invoice', refId: 'late-return',
149 + productId: 'product-1', type: 'in', cost: 7 }],
150 + expenses: [], contacts: [], cheques: [], treasury: []
151 + });
152 + try {
153 + const result = await ReportController.getProfitLoss(filter);
154 + assert.equal(result.netSales, -20);
155 + assert.equal(result.cogs, -7);
156 + assert.equal(result.grossProfit, -13);
157 + assert.equal(result.costBasis, 'historical');
158 + } finally {
159 + ReportController._loadData = originalLoad;
160 + }
161 +});
162 +
163 +test('reports label legacy current-price COGS estimates instead of presenting them as historical costs', async () => {
164 + const originalLoad = ReportController._loadData;
165 + ReportController._loadData = async () => ({
166 + invoices: [{
167 + id: 'legacy-sale', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
168 + subtotal: 50, totalDiscount: 0, grandTotal: 50,
169 + items: [{ productId: 'product-legacy', productName: 'Legacy item', qty: 2, price: 25, lineTotal: 50 }]
170 + }],
171 + products: [{ id: 'product-legacy', name: 'Legacy item', buyPrice: 12, trackInventory: true }],
172 + stockMovements: [], expenses: [], contacts: [], cheques: [], treasury: []
173 + });
174 + try {
175 + const result = await ReportController.getProfitLoss(filter);
176 + assert.equal(result.cogs, 24);
177 + assert.equal(result.costBasis, 'estimated');
178 + assert.deepEqual(result.costBasisDetails, { basis: 'estimated', historical: 0, estimated: 1, unknown: 0 });
179 + } finally {
180 + ReportController._loadData = originalLoad;
181 + }
182 +});
183 +
184 +
185 +test('legacy invoice subtotal mismatches are surfaced as incomplete line discount allocation', async () => {
186 + const originalLoad = ReportController._loadData;
187 + ReportController._loadData = async () => ({
188 + invoices: [{
189 + id: 'mismatched-legacy-sale', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
190 + subtotal: 100, totalDiscount: 10, grandTotal: 90,
191 + items: [{ productId: 'product-1', productName: 'Product one', qty: 1, price: 80, lineTotal: 80 }]
192 + }],
193 + products: [{ id: 'product-1', name: 'Product one', buyPrice: 20, trackInventory: true }],
194 + stockMovements: [{ id: 'move', refType: 'invoice', refId: 'mismatched-legacy-sale',
195 + productId: 'product-1', type: 'out', cost: 15 }],
196 + expenses: [], contacts: [], cheques: [], treasury: []
197 + });
198 + try {
199 + const result = await ReportController.getProfitLoss(filter);
200 + assert.equal(result.costBasis, 'historical');
201 + assert.equal(result.discountAllocationIncomplete, true);
202 + } finally {
203 + ReportController._loadData = originalLoad;
204 + }
205 +});
206 +
207 +test('a missing historical and current product cost is explicitly classified as incomplete', async () => {
208 + const originalLoad = ReportController._loadData;
209 + ReportController._loadData = async () => ({
210 + invoices: [{
211 + id: 'orphan-sale', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
212 + subtotal: 50, totalDiscount: 0, grandTotal: 50,
213 + items: [{ productId: 'deleted-product', productName: 'Unknown item', qty: 1, price: 50, lineTotal: 50 }]
214 + }],
215 + products: [], stockMovements: [], expenses: [], contacts: [], cheques: [], treasury: []
216 + });
217 + try {
218 + const result = await ReportController.getProfitLoss(filter);
219 + assert.equal(result.cogs, 0);
220 + assert.equal(result.costBasis, 'incomplete');
221 + assert.equal(result.costBasisDetails.unknown, 1);
222 + } finally {
223 + ReportController._loadData = originalLoad;
224 + }
225 +});