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

feat/a05-cheque-treasury-reconciliation
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 386 lines 13 KB
Raw
1 // ============================================================
2 // ReportController — محاسبات سود و زیان و تحلیل مالی
3 // ============================================================
4
5 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
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] = 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 ]);
22 return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [] };
23 }
24
25 _parseJalali(str) {
26 if (!str) return null;
27 const parts = String(str).split('/').map(Number);
28 if (parts.length !== 3) return null;
29 const [jy, jm, jd] = parts;
30 if (!jy || !jm || !jd) return null;
31 let gy = (jy <= 979) ? 621 : 1600;
32 let jy2 = jy - (jy <= 979 ? 0 : 979);
33 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);
34 gy += 400 * Math.floor(days / 146097);
35 days %= 146097;
36 if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
37 gy += 4 * Math.floor(days / 1461);
38 days %= 1461;
39 if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
40 let gd = days + 1;
41 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];
42 let gm = 0;
43 for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
44 return new Date(gy, gm - 1, gd);
45 }
46
47 _inRange(dateStr, from, to) {
48 const d = this._parseJalali(dateStr);
49 if (!d) return false;
50 if (from && d < from) return false;
51 if (to) {
52 const toEnd = new Date(to);
53 toEnd.setHours(23, 59, 59);
54 if (d > toEnd) return false;
55 }
56 return true;
57 }
58
59 _getRange(filter = {}) {
60 const today = new Date();
61 today.setHours(0, 0, 0, 0);
62 let from = null, to = new Date();
63
64 if (filter.preset) {
65 switch (filter.preset) {
66 case 'today':
67 from = new Date(today);
68 break;
69 case '7days':
70 from = new Date(today); from.setDate(from.getDate() - 6);
71 break;
72 case '30days':
73 from = new Date(today); from.setDate(from.getDate() - 29);
74 break;
75 case '3months':
76 from = new Date(today); from.setMonth(from.getMonth() - 3);
77 break;
78 case 'thisYear': {
79 const j = Jalali.now();
80 const g = this._parseJalali(`${j.year}/01/01`);
81 from = g || new Date(today);
82 break;
83 }
84 case 'lastYear': {
85 const j = Jalali.now();
86 const start = this._parseJalali(`${j.year - 1}/01/01`);
87 const end = this._parseJalali(`${j.year - 1}/12/29`);
88 from = start;
89 to = end || new Date();
90 break;
91 }
92 case 'custom':
93 from = filter.from ? this._parseJalali(filter.from) : null;
94 to = filter.to ? this._parseJalali(filter.to) : new Date();
95 break;
96 default:
97 from = null;
98 }
99 } else {
100 // پیش‌فرض: ۳۰ روز اخیر
101 from = new Date(today); from.setDate(from.getDate() - 29);
102 }
103
104 return { from, to };
105 }
106
107 // ============================================================
108 // ۱. سود و زیان
109 // ============================================================
110 async getProfitLoss(filter = {}) {
111 const { invoices, products, expenses } = await this._loadData();
112 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)
119 );
120
121 // برگشت از فروش
122 const returnsInRange = invoices.filter(i =>
123 i.kind === 'sale_return' &&
124 !i.isPreInvoice &&
125 this._inRange(i.date, from, to)
126 );
127
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);
132 const netSales = grossSales - salesDiscounts - returnsAmount;
133
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);
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);
166
167 const netProfit = grossProfit - operatingExpenses + otherIncome;
168 const netMargin = netSales > 0 ? (netProfit / netSales) * 100 : 0;
169
170 return {
171 grossSales,
172 salesDiscounts,
173 returnsAmount,
174 netSales,
175 cogs,
176 grossProfit,
177 grossMargin,
178 operatingExpenses,
179 otherIncome,
180 netProfit,
181 netMargin,
182 invoiceCount: salesInRange.length,
183 returnCount: returnsInRange.length,
184 periodFrom: from,
185 periodTo: to
186 };
187 }
188
189 // ============================================================
190 // ۲. تحلیل فروش (Top Products & Customers)
191 // ============================================================
192 async getSalesAnalysis(filter = {}) {
193 const { invoices, products, contacts } = await this._loadData();
194 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)
200 );
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 }))
233 .sort((a, b) => b.totalSales - a.totalSales)
234 .slice(0, 10);
235
236 const topProductsByQty = Object.values(productStats)
237 .sort((a, b) => b.qty - a.qty)
238 .slice(0, 10);
239
240 // مشتریان
241 const contactStats = {};
242 salesInRange.forEach(inv => {
243 const key = inv.contactId || 'unknown';
244 if (!contactStats[key]) {
245 contactStats[key] = {
246 contactId: inv.contactId,
247 contactName: inv.contactName || 'ناشناس',
248 invoiceCount: 0,
249 totalSales: 0,
250 totalPaid: 0,
251 totalRemaining: 0
252 };
253 }
254 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;
258 });
259
260 const topCustomers = Object.values(contactStats)
261 .sort((a, b) => b.totalSales - a.totalSales)
262 .slice(0, 10);
263
264 return {
265 topProductsBySales,
266 topProductsByQty,
267 topCustomers,
268 invoiceCount: salesInRange.length
269 };
270 }
271
272 // ============================================================
273 // ۳. سودآوری کالا (همه کالاها)
274 // ============================================================
275 async getProductProfitability(filter = {}) {
276 const { invoices, products } = await this._loadData();
277 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)
283 );
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;
322 }
323
324 // ============================================================
325 // ۴. گزارش مشتریان
326 // ============================================================
327 async getCustomerReport(filter = {}) {
328 const { invoices, contacts } = await this._loadData();
329 const { from, to } = this._getRange(filter);
330
331 const contactMap = {};
332 contacts.forEach(c => contactMap[c.id] = c);
333
334 const stats = {};
335 invoices.forEach(inv => {
336 if (inv.isPreInvoice) return;
337 if (!this._inRange(inv.date, from, to)) return;
338 const key = inv.contactId || 'unknown';
339 if (!stats[key]) {
340 const c = contactMap[inv.contactId];
341 stats[key] = {
342 contactId: inv.contactId,
343 contactName: inv.contactName || 'ناشناس',
344 entityType: c?.entityType || 'natural',
345 totalInvoices: 0,
346 totalSales: 0,
347 totalReturns: 0,
348 totalPaid: 0,
349 totalRemaining: 0,
350 lastInvoiceDate: ''
351 };
352 }
353 const isSale = inv.kind === 'sale';
354 const isReturn = inv.kind === 'sale_return';
355 if (isSale) {
356 stats[key].totalInvoices += 1;
357 stats[key].totalSales += Number(inv.grandTotal) || 0;
358 stats[key].totalPaid += Number(inv.paidAmount) || 0;
359 stats[key].totalRemaining += Number(inv.remaining) || 0;
360 } else if (isReturn) {
361 stats[key].totalReturns += Number(inv.grandTotal) || 0;
362 }
363 if (inv.date > (stats[key].lastInvoiceDate || '')) {
364 stats[key].lastInvoiceDate = inv.date;
365 }
366 });
367
368 return Object.values(stats).sort((a, b) => b.totalSales - a.totalSales);
369 }
370
371 // ============================================================
372 // آمار کمکی برای هدر صفحه
373 // ============================================================
374 async getQuickStats(filter = {}) {
375 const pl = await this.getProfitLoss(filter);
376 return {
377 netSales: pl.netSales,
378 netProfit: pl.netProfit,
379 netMargin: pl.netMargin,
380 grossMargin: pl.grossMargin
381 };
382 }
383 }
384
385 export const ReportController = new ReportControllerImpl();
386 window.ReportController = ReportController;