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

work/finance-curated-20261123
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 524 lines 20.6 KB
Raw
1 // ============================================================
2 // ReportController — محاسبات سود و زیان و تحلیل مالی
3 // ============================================================
4
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';
9
10 class ReportControllerImpl {
11 async _loadData() {
12 const user = Auth.current();
13 if (!user) throw new Error('کاربر یافت نشد');
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'),
21 DataScope.list('stock_movements')
22 ]);
23 return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [], stockMovements: stockMovements || [] };
24 }
25
26 _parseJalali(str) {
27 if (!str) return null;
28 const parts = String(str).split('/').map(Number);
29 if (parts.length !== 3) return null;
30 const [jy, jm, jd] = parts;
31 if (!jy || !jm || !jd) return null;
32 let gy = (jy <= 979) ? 621 : 1600;
33 let jy2 = jy - (jy <= 979 ? 0 : 979);
34 let days = (365 * jy2) + (Math.floor(jy2 / 33) * 8) + Math.floor(((jy2 % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
35 gy += 400 * Math.floor(days / 146097);
36 days %= 146097;
37 if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
38 gy += 4 * Math.floor(days / 1461);
39 days %= 1461;
40 if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
41 let gd = days + 1;
42 const sal_a = [0,31,((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31];
43 let gm = 0;
44 for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
45 return new Date(gy, gm - 1, gd);
46 }
47
48 _inRange(dateStr, from, to) {
49 const d = this._parseJalali(dateStr);
50 if (!d) return false;
51 if (from && d < from) return false;
52 if (to) {
53 const toEnd = new Date(to);
54 toEnd.setHours(23, 59, 59);
55 if (d > toEnd) return false;
56 }
57 return true;
58 }
59
60 _getRange(filter = {}) {
61 const today = new Date();
62 today.setHours(0, 0, 0, 0);
63 let from = null, to = new Date();
64
65 if (filter.preset) {
66 switch (filter.preset) {
67 case 'today':
68 from = new Date(today);
69 break;
70 case '7days':
71 from = new Date(today); from.setDate(from.getDate() - 6);
72 break;
73 case '30days':
74 from = new Date(today); from.setDate(from.getDate() - 29);
75 break;
76 case '3months':
77 from = new Date(today); from.setMonth(from.getMonth() - 3);
78 break;
79 case 'thisYear': {
80 const j = Jalali.now();
81 const g = this._parseJalali(`${j.year}/01/01`);
82 from = g || new Date(today);
83 break;
84 }
85 case 'lastYear': {
86 const j = Jalali.now();
87 const start = this._parseJalali(`${j.year - 1}/01/01`);
88 const end = this._parseJalali(`${j.year - 1}/12/29`);
89 from = start;
90 to = end || new Date();
91 break;
92 }
93 case 'custom':
94 from = filter.from ? this._parseJalali(filter.from) : null;
95 to = filter.to ? this._parseJalali(filter.to) : new Date();
96 break;
97 default:
98 from = null;
99 }
100 } else {
101 // پیش‌فرض: ۳۰ روز اخیر
102 from = new Date(today); from.setDate(from.getDate() - 29);
103 }
104
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) {
312 const { invoices, products, expenses, stockMovements = [] } = data || await this._loadData();
313 const { from, to } = this._getRange(filter);
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 );
318 const returnsInRange = inRange.filter(invoice =>
319 invoice.kind === 'sale_return' && !invoice.isPreInvoice
320 );
321
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
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;
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
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,
354 salesDiscounts,
355 returnsAmount,
356 netSales,
357 cogs,
358 grossProfit: netSales - cogs,
359 grossMargin: netSales !== 0 ? ((netSales - cogs) / netSales) * 100 : 0,
360 operatingExpenses,
361 otherIncome,
362 netProfit,
363 netMargin,
364 invoiceCount: salesInRange.length,
365 returnCount: returnsInRange.length,
366 periodFrom: from,
367 periodTo: to,
368 costBasis: costBasisDetails.basis,
369 costBasisDetails,
370 discountAllocationIncomplete: [...salesTotals, ...returnTotals].some(totals => !totals.valid)
371 };
372 }
373
374 async getSalesAnalysis(filter = {}, data = null) {
375 const { invoices, products, stockMovements = [] } = data || await this._loadData();
376 const { from, to } = this._getRange(filter);
377 const rows = invoices.filter(invoice =>
378 ['sale', 'sale_return'].includes(invoice.kind) &&
379 !invoice.isPreInvoice &&
380 this._inRange(invoice.date, from, to)
381 );
382 const productStats = this._buildProductStats(rows, products, stockMovements);
383 const topProductsBySales = [...productStats]
384 .sort((a, b) => b.totalSales - a.totalSales)
385 .slice(0, 10);
386 const topProductsByQty = [...productStats]
387 .sort((a, b) => b.qty - a.qty)
388 .slice(0, 10);
389
390 const contactStats = {};
391 rows.forEach(invoice => {
392 const key = invoice.contactId || 'unknown';
393 if (!contactStats[key]) {
394 contactStats[key] = {
395 contactId: invoice.contactId,
396 contactName: invoice.contactName || 'ناشناس',
397 invoiceCount: 0,
398 returnCount: 0,
399 totalSales: 0,
400 totalReturns: 0,
401 netSales: 0,
402 totalPaid: 0,
403 totalRemaining: 0,
404 returnCreditRemaining: 0
405 };
406 }
407 if (invoice.kind === 'sale') {
408 contactStats[key].invoiceCount += 1;
409 contactStats[key].totalSales += Number(invoice.grandTotal) || 0;
410 contactStats[key].totalPaid += Number(invoice.paidAmount) || 0;
411 contactStats[key].totalRemaining += Number(invoice.remaining) || 0;
412 } else {
413 contactStats[key].returnCount += 1;
414 contactStats[key].totalReturns += Number(invoice.grandTotal) || 0;
415 contactStats[key].totalPaid -= Number(invoice.paidAmount) || 0;
416 const returnCreditRemaining = Number(invoice.remaining) || 0;
417 contactStats[key].returnCreditRemaining += returnCreditRemaining;
418 contactStats[key].totalRemaining -= returnCreditRemaining;
419 }
420 });
421
422 const topCustomers = Object.values(contactStats)
423 .map(customer => ({ ...customer, netSales: customer.totalSales - customer.totalReturns }))
424 .sort((a, b) => b.netSales - a.netSales)
425 .slice(0, 10);
426 return {
427 topProductsBySales,
428 topProductsByQty,
429 topCustomers,
430 invoiceCount: rows.filter(invoice => invoice.kind === 'sale').length
431 };
432 }
433
434 async getProductProfitability(filter = {}, data = null) {
435 const { invoices, products, stockMovements = [] } = data || await this._loadData();
436 const { from, to } = this._getRange(filter);
437 const rows = invoices.filter(invoice =>
438 ['sale', 'sale_return'].includes(invoice.kind) &&
439 !invoice.isPreInvoice &&
440 this._inRange(invoice.date, from, to)
441 );
442 return this._buildProductStats(rows, products, stockMovements)
443 .sort((a, b) => b.profit - a.profit);
444 }
445
446 async getCustomerReport(filter = {}, data = null) {
447 const { invoices, contacts } = data || await this._loadData();
448 const { from, to } = this._getRange(filter);
449 const contactMap = {};
450 contacts.forEach(contact => { contactMap[contact.id] = contact; });
451
452 const stats = {};
453 invoices.forEach(invoice => {
454 if (!['sale', 'sale_return'].includes(invoice.kind) || invoice.isPreInvoice) return;
455 if (!this._inRange(invoice.date, from, to)) return;
456 const key = invoice.contactId || 'unknown';
457 if (!stats[key]) {
458 const contact = contactMap[invoice.contactId];
459 stats[key] = {
460 contactId: invoice.contactId,
461 contactName: invoice.contactName || contact?.name || 'ناشناس',
462 entityType: contact?.entityType || 'natural',
463 totalInvoices: 0,
464 returnCount: 0,
465 totalSales: 0,
466 totalReturns: 0,
467 netSales: 0,
468 totalPaid: 0,
469 totalRemaining: 0,
470 returnCreditRemaining: 0,
471 lastInvoiceDate: ''
472 };
473 }
474 if (invoice.kind === 'sale') {
475 stats[key].totalInvoices += 1;
476 stats[key].totalSales += Number(invoice.grandTotal) || 0;
477 stats[key].totalPaid += Number(invoice.paidAmount) || 0;
478 stats[key].totalRemaining += Number(invoice.remaining) || 0;
479 } else {
480 stats[key].returnCount += 1;
481 stats[key].totalReturns += Number(invoice.grandTotal) || 0;
482 stats[key].totalPaid -= Number(invoice.paidAmount) || 0;
483 const returnCreditRemaining = Number(invoice.remaining) || 0;
484 stats[key].returnCreditRemaining += returnCreditRemaining;
485 stats[key].totalRemaining -= returnCreditRemaining;
486 }
487 if (invoice.date > (stats[key].lastInvoiceDate || ''))
488 stats[key].lastInvoiceDate = invoice.date;
489 });
490
491 return Object.values(stats)
492 .map(customer => ({ ...customer, netSales: customer.totalSales - customer.totalReturns }))
493 .sort((a, b) => b.netSales - a.netSales);
494 }
495
496 // Load one company-scoped snapshot and reuse it across all report calculations.
497 // The standalone methods keep their existing behavior when no snapshot is passed.
498 async getReportBundle(filter = {}) {
499 const data = await this._loadData();
500 const [pl, sales, products, customers] = await Promise.all([
501 this.getProfitLoss(filter, data),
502 this.getSalesAnalysis(filter, data),
503 this.getProductProfitability(filter, data),
504 this.getCustomerReport(filter, data)
505 ]);
506 return { pl, sales, products, customers };
507 }
508
509 // ============================================================
510 // آمار کمکی برای هدر صفحه
511 // ============================================================
512 async getQuickStats(filter = {}) {
513 const pl = await this.getProfitLoss(filter);
514 return {
515 netSales: pl.netSales,
516 netProfit: pl.netProfit,
517 netMargin: pl.netMargin,
518 grossMargin: pl.grossMargin
519 };
520 }
521 }
522
523 export const ReportController = new ReportControllerImpl();
524 window.ReportController = ReportController;