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

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