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

fix/p0-reports-immutable-cogs-20261101
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 709 lines 33.9 KB
Raw
1 // ============================================================
2 // ReportsView — گزارش سود و زیان، تحلیل فروش و سودآوری
3 // ============================================================
4
5 import { ReportController } from '../controllers/ReportController.js';
6 import { Formatters } from '../utils/Formatters.js';
7 import { Jalali } from '../utils/Jalali.js';
8 import { Toast } from '../core/Toast.js';
9 import { Chart } from '../utils/Chart.js';
10
11 let currentTab = 'pl'; // pl | sales | products | customers
12 let currentFilter = {
13 preset: '30days',
14 from: '',
15 to: ''
16 };
17
18 let cache = {
19 pl: null,
20 sales: null,
21 products: [],
22 customers: []
23 };
24
25 class ReportsViewImpl {
26 async render() {
27 await this.reload();
28 return `
29 <div class="page-title" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
30 <div>
31 <h2>گزارش‌های مالی</h2>
32 <p>تحلیل سود و زیان، فروش و سودآوری کسب‌وکار</p>
33 </div>
34 <button class="btn btn-secondary btn-inline" onclick="window.ReportsView._printReport()">🖨️ چاپ گزارش</button>
35 </div>
36
37 ${this._renderFilterBar()}
38
39 <div class="tabs" style="margin-top:16px">
40 <button class="tab-btn ${currentTab === 'pl' ? 'active' : ''}" onclick="window.ReportsView._switchTab('pl', event)">
41 💹 سود و زیان
42 </button>
43 <button class="tab-btn ${currentTab === 'sales' ? 'active' : ''}" onclick="window.ReportsView._switchTab('sales', event)">
44 📈 تحلیل فروش
45 </button>
46 <button class="tab-btn ${currentTab === 'products' ? 'active' : ''}" onclick="window.ReportsView._switchTab('products', event)">
47 📦 سودآوری کالاها
48 </button>
49 <button class="tab-btn ${currentTab === 'customers' ? 'active' : ''}" onclick="window.ReportsView._switchTab('customers', event)">
50 👥 گزارش مشتریان
51 </button>
52 </div>
53
54 <div id="reports-content">${this.renderTabContent()}</div>
55 `;
56 }
57
58 onMount() {
59 window.ReportsView = this;
60 }
61
62 async reload() {
63 cache.pl = await ReportController.getProfitLoss(currentFilter);
64 cache.sales = await ReportController.getSalesAnalysis(currentFilter);
65 cache.products = await ReportController.getProductProfitability(currentFilter);
66 cache.customers = await ReportController.getCustomerReport(currentFilter);
67 }
68
69 renderTabContent() {
70 if (currentTab === 'pl') return this.renderPLTab();
71 if (currentTab === 'sales') return this.renderSalesTab();
72 if (currentTab === 'products') return this.renderProductsTab();
73 if (currentTab === 'customers') return this.renderCustomersTab();
74 return '';
75 }
76
77 _switchTab(tab, event) {
78 currentTab = tab;
79 document.querySelectorAll('.tabs .tab-btn').forEach(btn => btn.classList.remove('active'));
80 if (event && event.target) {
81 const target = event.target.closest('.tab-btn');
82 if (target) target.classList.add('active');
83 }
84 document.getElementById('reports-content').innerHTML = this.renderTabContent();
85 }
86
87 // ============================================================
88 // فیلتر بازه
89 // ============================================================
90 _renderFilterBar() {
91 const presets = [
92 { key: 'today', label: 'امروز' },
93 { key: '7days', label: '۷ روز' },
94 { key: '30days', label: '۳۰ روز' },
95 { key: '3months', label: '۳ ماه' },
96 { key: 'thisYear', label: 'سال جاری' },
97 { key: 'lastYear', label: 'سال قبل' },
98 { key: 'custom', label: 'دلخواه' }
99 ];
100
101 const buttons = presets.map(p =>
102 `<button class="chart-tab ${currentFilter.preset === p.key ? 'active' : ''}" onclick="window.ReportsView._setPreset('${p.key}')">${p.label}</button>`
103 ).join('');
104
105 const customInputs = currentFilter.preset === 'custom' ? `
106 <div style="display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap">
107 <span style="font-size:12.5px;color:var(--text-muted)">از تاریخ:</span>
108 <input type="text" class="form-control" style="width:130px" placeholder="1405/01/01" aria-label="از تاریخ گزارش" value="${this._esc(currentFilter.from)}" onchange="window.ReportsView._setCustomDate('from', this.value)" />
109 <span style="font-size:12.5px;color:var(--text-muted)">تا تاریخ:</span>
110 <input type="text" class="form-control" style="width:130px" placeholder="1405/06/27" aria-label="تا تاریخ گزارش" value="${this._esc(currentFilter.to)}" onchange="window.ReportsView._setCustomDate('to', this.value)" />
111 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.ReportsView._applyCustom()">اعمال</button>
112 </div>
113 ` : '';
114
115 const rangeText = this._formatRange(cache.pl?.periodFrom, cache.pl?.periodTo);
116
117 return `
118 <div class="card" style="padding:14px 16px;margin-bottom:0">
119 <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
120 <div>
121 <span style="font-size:13px;font-weight:700">دوره‌ی گزارش:</span>
122 <span style="font-size:12.5px;color:var(--primary);margin-right:6px">${rangeText}</span>
123 </div>
124 <div class="chart-tabs" style="flex-wrap:wrap">${buttons}</div>
125 </div>
126 ${customInputs}
127 </div>
128 `;
129 }
130
131 _formatRange(from, to) {
132 if (!from && !to) return 'همه‌ی زمان‌ها';
133 const f = from ? Jalali.format(from) : '—';
134 const t = to ? Jalali.format(to) : '—';
135 return `${Formatters.toPersianDigits(f)} تا ${Formatters.toPersianDigits(t)}`;
136 }
137
138 _setPreset(preset) {
139 currentFilter.preset = preset;
140 if (preset !== 'custom') {
141 currentFilter.from = '';
142 currentFilter.to = '';
143 }
144 this._refresh();
145 }
146
147 _setCustomDate(key, value) {
148 currentFilter[key] = value;
149 }
150
151 _applyCustom() {
152 if (!currentFilter.from || !currentFilter.to) {
153 Toast.warning('تاریخ شروع و پایان رو کامل وارد کنید');
154 return;
155 }
156 this._refresh();
157 }
158
159 async _refresh() {
160 await this.reload();
161 // رندر کامل مجدد تا فیلتر و همه‌چیز آپدیت بشه
162 const html = await this.render();
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 // ============================================================
187 renderPLTab() {
188 const pl = cache.pl || {};
189
190 const rows = [
191 { label: 'فروش ناخالص', value: pl.grossSales, color: 'var(--text)', bold: false, sign: '+' },
192 { label: 'تخفیف فروش', value: -pl.salesDiscounts, color: 'var(--danger)', bold: false, sign: '-' },
193 { label: 'برگشت از فروش', value: -pl.returnsAmount, color: 'var(--danger)', bold: false, sign: '-' },
194 { label: 'فروش خالص', value: pl.netSales, color: 'var(--primary)', bold: true, sign: '=' },
195 { label: 'بهای تمام‌شده کالای فروش‌رفته (COGS)', value: -pl.cogs, color: 'var(--warning)', bold: false, sign: '-' },
196 { label: 'سود ناخالص', value: pl.grossProfit, color: 'var(--success)', bold: true, sign: '=' },
197 { label: 'هزینه‌های عملیاتی', value: -pl.operatingExpenses, color: 'var(--danger)', bold: false, sign: '-' },
198 { label: 'سایر درآمدها', value: pl.otherIncome, color: 'var(--success)', bold: false, sign: '+' },
199 { label: 'سود (زیان) خالص', value: pl.netProfit, color: pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)', bold: true, sign: '=' }
200 ];
201
202 const rowsHtml = rows.map(r => {
203 const isBold = r.bold;
204 const val = Math.abs(Number(r.value) || 0);
205 const sign = Number(r.value) < 0 ? '-' : (r.sign === '+' ? '+' : '');
206 const display = (r.value === 0) ? Formatters.money(0) : `${sign} ${Formatters.money(val)}`;
207 return `
208 <tr style="${isBold ? 'background:var(--bg);font-weight:700' : ''}">
209 <td style="padding:12px 16px;font-size:${isBold ? '14px' : '13px'}">${r.label}</td>
210 <td style="padding:12px 16px;text-align:left;font-size:${isBold ? '14px' : '13px'};color:${r.color};font-weight:${isBold ? '800' : '600'}">
211 ${display}
212 </td>
213 </tr>
214 `;
215 }).join('');
216
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>
224 <div style="flex:1">
225 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش خالص</div>
226 <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.money(pl.netSales)}</div>
227 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(pl.invoiceCount)} فاکتور</div>
228 </div>
229 </div>
230 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)">
231 <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💵</div>
232 <div style="flex:1">
233 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">سود ناخالص</div>
234 <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(pl.grossProfit)}</div>
235 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.percent(pl.grossMargin || 0)}</div>
236 </div>
237 </div>
238 <div class="card kpi-card" style="margin:0;border-top:3px solid ${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">
239 <div class="kpi-card-icon" style="background:${pl.netProfit >= 0 ? '#ecfdf5' : '#fef2f2'};color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">${pl.netProfit >= 0 ? '📈' : '📉'}</div>
240 <div style="flex:1">
241 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">سود (زیان) خالص</div>
242 <div style="font-size:16px;font-weight:800;color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(pl.netProfit)}</div>
243 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.percent(pl.netMargin || 0)}</div>
244 </div>
245 </div>
246 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)">
247 <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">💸</div>
248 <div style="flex:1">
249 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">بهای تمام‌شده</div>
250 <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(pl.cogs)}</div>
251 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">COGS</div>
252 </div>
253 </div>
254 </div>
255
256 <div class="card">
257 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">💹 صورت سود و زیان</h3>
258 <div class="table-wrap">
259 <table>
260 <thead>
261 <tr>
262 <th style="width:60%">شرح</th>
263 <th style="text-align:left">مبلغ</th>
264 </tr>
265 </thead>
266 <tbody>${rowsHtml}</tbody>
267 <tfoot>
268 <tr style="background:${pl.netProfit >= 0 ? 'linear-gradient(135deg,#ecfdf5,#f0fdf4)' : 'linear-gradient(135deg,#fef2f2,#fff1f2)'}">
269 <td style="padding:16px;font-weight:800;font-size:15px">${marginLabel}</td>
270 <td style="padding:16px;text-align:left;font-weight:800;font-size:15px;color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">
271 ${Formatters.percent(pl.netMargin || 0)}
272 </td>
273 </tr>
274 </tfoot>
275 </table>
276 </div>
277 </div>
278
279 ${pl.netSales === 0 ? `
280 <div class="card" style="text-align:center;padding:30px">
281 <div style="font-size:40px;margin-bottom:10px;opacity:.4">📊</div>
282 <p style="font-size:13px;color:var(--text-muted)">در این بازه‌ی زمانی فروشی ثبت نشده است</p>
283 </div>
284 ` : ''}
285 `;
286 }
287
288 // ============================================================
289 // تب ۲: تحلیل فروش
290 // ============================================================
291 renderSalesTab() {
292 const s = cache.sales || {};
293 const topBySales = s.topProductsBySales || [];
294 const topByQty = s.topProductsByQty || [];
295 const topCustomers = s.topCustomers || [];
296
297 const productsChartData = topBySales.slice(0, 8).map(p => ({
298 label: this._truncate(p.productName, 12),
299 value: p.totalSales
300 }));
301
302 return `
303 <div class="card">
304 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📊 پرفروش‌ترین کالاها (به ترتیب مبلغ)</h3>
305 ${Chart.bars(topBySales.slice(0, 8).map(p => ({
306 label: this._truncate(p.productName, 10),
307 income: p.totalSales,
308 expense: p.cogs
309 })), { incomeColor: '#0d9488', expenseColor: '#d97706' })}
310 </div>
311
312 <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px" class="dash-grid-main">
313 <div class="card" style="margin:0">
314 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">🏆 ۱۰ کالای پرفروش (مبلغ)</h3>
315 <div class="table-wrap">
316 <table>
317 <thead>
318 <tr>
319 <th style="width:30px">#</th>
320 <th>نام کالا</th>
321 <th style="width:70px">تعداد</th>
322 <th style="width:130px">مبلغ فروش</th>
323 </tr>
324 </thead>
325 <tbody>
326 ${topBySales.length === 0 ? '<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : topBySales.map((p, i) => `
327 <tr>
328 <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
329 <td>${this._esc(p.productName)}</td>
330 <td>${Formatters.number(p.qty)}</td>
331 <td style="font-weight:600">${Formatters.money(p.totalSales)}</td>
332 </tr>
333 `).join('')}
334 </tbody>
335 </table>
336 </div>
337 </div>
338
339 <div class="card" style="margin:0">
340 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">🏆 ۱۰ کالای پرفروش (تعداد)</h3>
341 <div class="table-wrap">
342 <table>
343 <thead>
344 <tr>
345 <th style="width:30px">#</th>
346 <th>نام کالا</th>
347 <th style="width:70px">تعداد</th>
348 <th style="width:130px">مبلغ فروش</th>
349 </tr>
350 </thead>
351 <tbody>
352 ${topByQty.length === 0 ? '<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : topByQty.map((p, i) => `
353 <tr>
354 <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
355 <td>${this._esc(p.productName)}</td>
356 <td style="font-weight:700;color:var(--primary)">${Formatters.number(p.qty)}</td>
357 <td>${Formatters.money(p.totalSales)}</td>
358 </tr>
359 `).join('')}
360 </tbody>
361 </table>
362 </div>
363 </div>
364 </div>
365
366 <div class="card">
367 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">👥 ۱۰ مشتری برتر (به ترتیب مبلغ خرید)</h3>
368 <div class="table-wrap">
369 <table>
370 <thead>
371 <tr>
372 <th style="width:30px">#</th>
373 <th>مشتری</th>
374 <th style="width:100px">تعداد فاکتور</th>
375 <th style="width:150px">مجموع خرید</th>
376 <th style="width:150px">مجموع پرداخت</th>
377 <th style="width:150px">مانده</th>
378 </tr>
379 </thead>
380 <tbody>
381 ${topCustomers.length === 0 ? '<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : topCustomers.map((c, i) => `
382 <tr>
383 <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
384 <td>${this._esc(c.contactName)}</td>
385 <td>${Formatters.number(c.invoiceCount)}</td>
386 <td style="font-weight:600;color:var(--primary)">${Formatters.money(c.totalSales)}</td>
387 <td style="color:var(--success)">${Formatters.money(c.totalPaid)}</td>
388 <td style="font-weight:600;color:${c.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
389 </tr>
390 `).join('')}
391 </tbody>
392 </table>
393 </div>
394 </div>
395 `;
396 }
397
398 // ============================================================
399 // تب ۳: سودآوری کالاها
400 // ============================================================
401 renderProductsTab() {
402 const list = cache.products || [];
403 const totalSales = list.reduce((s, p) => s + p.totalSales, 0);
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>
411 <div style="flex:1">
412 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد کالاهای فروش‌رفته</div>
413 <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(list.length)}</div>
414 </div>
415 </div>
416 <div class="card kpi-card" style="margin:0">
417 <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💰</div>
418 <div style="flex:1">
419 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع فروش</div>
420 <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div>
421 </div>
422 </div>
423 <div class="card kpi-card" style="margin:0">
424 <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">📈</div>
425 <div style="flex:1">
426 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع سود</div>
427 <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(totalProfit)}</div>
428 </div>
429 </div>
430 <div class="card kpi-card" style="margin:0">
431 <div class="kpi-card-icon" style="background:#fef3c7;color:var(--warning)">%</div>
432 <div style="flex:1">
433 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">میانگین حاشیه سود</div>
434 <div style="font-size:16px;font-weight:800;color:var(--warning)">${Formatters.percent(totalSales > 0 ? (totalProfit / totalSales) * 100 : 0)}</div>
435 </div>
436 </div>
437 </div>
438
439 <div class="card">
440 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📦 جدول سودآوری کالاها</h3>
441 <div class="table-wrap">
442 <table>
443 <thead>
444 <tr>
445 <th style="width:30px">#</th>
446 <th>نام کالا</th>
447 <th style="width:80px">واحد</th>
448 <th style="width:80px">تعداد فروش</th>
449 <th style="width:140px">فروش کل</th>
450 <th style="width:140px">بهای تمام‌شده</th>
451 <th style="width:140px">سود خالص</th>
452 <th style="width:100px">حاشیه سود</th>
453 </tr>
454 </thead>
455 <tbody>
456 ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">هیچ کالایی در این بازه فروش نرفته</td></tr>' : list.map((p, i) => `
457 <tr>
458 <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
459 <td>${this._esc(p.productName)}</td>
460 <td>${this._esc(p.unit)}</td>
461 <td style="font-weight:700">${Formatters.number(p.qty)}</td>
462 <td>${Formatters.money(p.totalSales)}</td>
463 <td style="color:var(--warning)">${Formatters.money(p.cogs)}</td>
464 <td style="font-weight:700;color:${p.profit >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(p.profit)}</td>
465 <td>
466 <span class="badge ${p.margin >= 30 ? 'badge-success' : p.margin >= 10 ? 'badge-warning' : 'badge-danger'}">
467 ${Formatters.percent(p.margin)}
468 </span>
469 </td>
470 </tr>
471 `).join('')}
472 </tbody>
473 </table>
474 </div>
475 </div>
476 `;
477 }
478
479 // ============================================================
480 // تب ۴: گزارش مشتریان
481 // ============================================================
482 renderCustomersTab() {
483 const list = cache.customers || [];
484 const totalSales = list.reduce((s, c) => s + c.totalSales, 0);
485 const totalRemaining = list.reduce((s, c) => s + c.totalRemaining, 0);
486
487 return `
488 <div class="grid-kpi">
489 <div class="card kpi-card" style="margin:0">
490 <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">👥</div>
491 <div style="flex:1">
492 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد مشتریان فعال</div>
493 <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(list.length)}</div>
494 </div>
495 </div>
496 <div class="card kpi-card" style="margin:0">
497 <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💰</div>
498 <div style="flex:1">
499 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع فروش</div>
500 <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div>
501 </div>
502 </div>
503 <div class="card kpi-card" style="margin:0">
504 <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">⏳</div>
505 <div style="flex:1">
506 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع مطالبات</div>
507 <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(totalRemaining)}</div>
508 </div>
509 </div>
510 </div>
511
512 <div class="card">
513 <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">👥 گزارش تفصیلی مشتریان</h3>
514 <div class="table-wrap">
515 <table>
516 <thead>
517 <tr>
518 <th style="width:30px">#</th>
519 <th>نام مشتری</th>
520 <th style="width:100px">نوع</th>
521 <th style="width:110px">تعداد فاکتور</th>
522 <th style="width:140px">مجموع خرید</th>
523 <th style="width:140px">پرداخت‌شده</th>
524 <th style="width:140px">مانده</th>
525 <th style="width:120px">آخرین فاکتور</th>
526 </tr>
527 </thead>
528 <tbody>
529 ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : list.map((c, i) => `
530 <tr>
531 <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
532 <td>${this._esc(c.contactName)}</td>
533 <td><span class="badge ${c.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entityType === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
534 <td>${Formatters.number(c.totalInvoices)}</td>
535 <td style="font-weight:600;color:var(--primary)">${Formatters.money(c.totalSales)}</td>
536 <td style="color:var(--success)">${Formatters.money(c.totalPaid)}</td>
537 <td style="font-weight:700;color:${c.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
538 <td>${c.lastInvoiceDate ? Formatters.toPersianDigits(c.lastInvoiceDate) : '—'}</td>
539 </tr>
540 `).join('')}
541 </tbody>
542 </table>
543 </div>
544 </div>
545 `;
546 }
547
548 // ============================================================
549 // چاپ گزارش
550 // ============================================================
551 _printReport() {
552 const pl = cache.pl || {};
553 const tabNames = { pl: 'سود و زیان', sales: 'تحلیل فروش', products: 'سودآوری کالاها', customers: 'گزارش مشتریان' };
554 const rangeText = this._formatRange(pl.periodFrom, pl.periodTo);
555
556 const printWin = window.open('', '_blank', 'width=900,height=700');
557 if (!printWin) { Toast.error('پاپ‌آپ را فعال کنید'); return; }
558
559 const content = this._buildPrintContent();
560
561 printWin.document.write(`
562 <!DOCTYPE html>
563 <html lang="fa" dir="rtl">
564 <head>
565 <meta charset="UTF-8" />
566 <title>گزارش ${tabNames[currentTab]}</title>
567 <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
568 <style>
569 @page { size: A4 portrait; margin: 10mm; }
570 * { box-sizing: border-box; margin: 0; padding: 0; }
571 html, body { direction: rtl; text-align: right; font-family: 'Vazirmatn FD', Tahoma, sans-serif; background: #fff; color: #000; }
572 body { padding: 10px; }
573 table { width: 100%; border-collapse: collapse; direction: rtl; }
574 th, td { padding: 8px 10px; border: 1px solid #cbd5e1; text-align: right; font-size: 11.5px; }
575 th { background: #f1f5f9; font-weight: 700; }
576 h1 { font-size: 18px; margin-bottom: 6px; color: #0d9488; text-align: center; }
577 h2 { font-size: 14px; margin: 16px 0 10px; color: #0d9488; border-bottom: 2px solid #0d9488; padding-bottom: 4px; }
578 .header-info { text-align: center; font-size: 12px; color: #64748b; margin-bottom: 20px; }
579 .footer { margin-top: 30px; text-align: center; font-size: 10px; color: #94a3b8; padding-top: 10px; border-top: 1px dashed #cbd5e1; }
580 @media print {
581 * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
582 }
583 </style>
584 </head>
585 <body>
586 <h1>گزارش ${tabNames[currentTab]}</h1>
587 <div class="header-info">بازه: ${rangeText} | تاریخ چاپ: ${Jalali.today()}</div>
588 ${content}
589 <div class="footer">Factor-easyPro - سامانه مدیریت کسب‌وکار</div>
590 </body>
591 </html>
592 `);
593 printWin.document.close();
594 setTimeout(() => { printWin.focus(); printWin.print(); }, 500);
595 }
596
597 _buildPrintContent() {
598 const pl = cache.pl || {};
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>
606 <tr><td>برگشت از فروش</td><td style="color:#dc2626">- ${Formatters.money(pl.returnsAmount)}</td></tr>
607 <tr style="background:#f1f5f9;font-weight:700"><td>فروش خالص</td><td>${Formatters.money(pl.netSales)}</td></tr>
608 <tr><td>بهای تمام‌شده کالای فروش‌رفته</td><td style="color:#d97706">- ${Formatters.money(pl.cogs)}</td></tr>
609 <tr style="background:#f1f5f9;font-weight:700"><td>سود ناخالص</td><td style="color:#059669">${Formatters.money(pl.grossProfit)}</td></tr>
610 <tr><td>هزینه‌های عملیاتی</td><td style="color:#dc2626">- ${Formatters.money(pl.operatingExpenses)}</td></tr>
611 <tr><td>سایر درآمدها</td><td style="color:#059669">+ ${Formatters.money(pl.otherIncome)}</td></tr>
612 <tr style="background:#ecfdf5;font-weight:800;font-size:13px"><td>سود (زیان) خالص</td><td style="color:${pl.netProfit >= 0 ? '#059669' : '#dc2626'}">${Formatters.money(pl.netProfit)}</td></tr>
613 </table>
614 <h2>شاخص‌ها</h2>
615 <table>
616 <tr><td>حاشیه سود ناخالص</td><td>${Formatters.percent(pl.grossMargin)}</td></tr>
617 <tr><td>حاشیه سود خالص</td><td>${Formatters.percent(pl.netMargin)}</td></tr>
618 <tr><td>تعداد فاکتور فروش</td><td>${Formatters.number(pl.invoiceCount)}</td></tr>
619 </table>
620 `;
621 }
622
623 if (currentTab === 'products') {
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>
631 ${list.map((p, i) => `
632 <tr>
633 <td>${Formatters.toPersianDigits(i + 1)}</td>
634 <td>${this._esc(p.productName)}</td>
635 <td>${Formatters.number(p.qty)}</td>
636 <td>${Formatters.money(p.totalSales)}</td>
637 <td>${Formatters.money(p.cogs)}</td>
638 <td>${Formatters.money(p.profit)}</td>
639 <td>${Formatters.percent(p.margin)}</td>
640 </tr>
641 `).join('')}
642 </tbody>
643 </table>
644 `;
645 }
646
647 if (currentTab === 'customers') {
648 const list = cache.customers || [];
649 return `
650 <h2>گزارش مشتریان (${Formatters.number(list.length)} مشتری)</h2>
651 <table>
652 <thead><tr><th>#</th><th>نام مشتری</th><th>تعداد فاکتور</th><th>مجموع خرید</th><th>پرداخت‌شده</th><th>مانده</th></tr></thead>
653 <tbody>
654 ${list.map((c, i) => `
655 <tr>
656 <td>${Formatters.toPersianDigits(i + 1)}</td>
657 <td>${this._esc(c.contactName)}</td>
658 <td>${Formatters.number(c.totalInvoices)}</td>
659 <td>${Formatters.money(c.totalSales)}</td>
660 <td>${Formatters.money(c.totalPaid)}</td>
661 <td>${Formatters.money(c.totalRemaining)}</td>
662 </tr>
663 `).join('')}
664 </tbody>
665 </table>
666 `;
667 }
668
669 if (currentTab === 'sales') {
670 const topP = cache.sales?.topProductsBySales || [];
671 const topC = cache.sales?.topCustomers || [];
672 return `
673 <h2>۱۰ کالای پرفروش</h2>
674 <table>
675 <thead><tr><th>#</th><th>نام کالا</th><th>تعداد</th><th>مبلغ فروش</th></tr></thead>
676 <tbody>
677 ${topP.map((p, i) => `
678 <tr><td>${Formatters.toPersianDigits(i + 1)}</td><td>${this._esc(p.productName)}</td><td>${Formatters.number(p.qty)}</td><td>${Formatters.money(p.totalSales)}</td></tr>
679 `).join('')}
680 </tbody>
681 </table>
682 <h2>۱۰ مشتری برتر</h2>
683 <table>
684 <thead><tr><th>#</th><th>نام مشتری</th><th>تعداد فاکتور</th><th>مجموع خرید</th></tr></thead>
685 <tbody>
686 ${topC.map((c, i) => `
687 <tr><td>${Formatters.toPersianDigits(i + 1)}</td><td>${this._esc(c.contactName)}</td><td>${Formatters.number(c.invoiceCount)}</td><td>${Formatters.money(c.totalSales)}</td></tr>
688 `).join('')}
689 </tbody>
690 </table>
691 `;
692 }
693
694 return '';
695 }
696
697 _truncate(str, len) {
698 if (!str) return '';
699 return str.length > len ? str.slice(0, len) + '…' : str;
700 }
701
702 _esc(s) {
703 if (!s) return '';
704 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
705 }
706 }
707
708 export const ReportsView = new ReportsViewImpl();
709 window.ReportsView = ReportsView;