فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Phase 8: Reports (P&L, sales analysis, product profitability, customer report)
Davood Mehraban committed
Sep 18, 2026 at 20:21 UTC
e49c950b34d3a05e4002677fbbca7f6721e06520
3 files changed
+1075
-13
src/controllers/ReportController.js
new
+385
@@ -0,0 +1,385 @@
1
+// ============================================================
2
+// ReportController — محاسبات سود و زیان و تحلیل مالی
3
+// ============================================================
4
+
5
+import { StorageService } from '../core/StorageService.js';
6
+import { Auth } from '../core/Auth.js';
7
+import { Jalali } from '../utils/Jalali.js';
8
+
9
+class ReportControllerImpl {
10
+ async _loadData() {
11
+ const user = Auth.current();
12
+ if (!user) throw new Error('کاربر یافت نشد');
13
+ const [invoices, products, expenses, contacts, cheques, treasury] = await Promise.all([
14
+ StorageService.getByOwner('invoices', user.id),
15
+ StorageService.getByOwner('products', user.id),
16
+ StorageService.getByOwner('expenses', user.id),
17
+ StorageService.getByOwner('contacts', user.id),
18
+ StorageService.getByOwner('cheques', user.id),
19
+ StorageService.getByOwner('treasury', user.id)
20
+ ]);
21
+ return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [] };
22
+ }
23
+
24
+ _parseJalali(str) {
25
+ if (!str) return null;
26
+ const parts = String(str).split('/').map(Number);
27
+ if (parts.length !== 3) return null;
28
+ const [jy, jm, jd] = parts;
29
+ if (!jy || !jm || !jd) return null;
30
+ let gy = (jy <= 979) ? 621 : 1600;
31
+ let jy2 = jy - (jy <= 979 ? 0 : 979);
32
+ 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);
33
+ gy += 400 * Math.floor(days / 146097);
34
+ days %= 146097;
35
+ if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
36
+ gy += 4 * Math.floor(days / 1461);
37
+ days %= 1461;
38
+ if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
39
+ let gd = days + 1;
40
+ 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];
41
+ let gm = 0;
42
+ for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
43
+ return new Date(gy, gm - 1, gd);
44
+ }
45
+
46
+ _inRange(dateStr, from, to) {
47
+ const d = this._parseJalali(dateStr);
48
+ if (!d) return false;
49
+ if (from && d < from) return false;
50
+ if (to) {
51
+ const toEnd = new Date(to);
52
+ toEnd.setHours(23, 59, 59);
53
+ if (d > toEnd) return false;
54
+ }
55
+ return true;
56
+ }
57
+
58
+ _getRange(filter = {}) {
59
+ const today = new Date();
60
+ today.setHours(0, 0, 0, 0);
61
+ let from = null, to = new Date();
62
+
63
+ if (filter.preset) {
64
+ switch (filter.preset) {
65
+ case 'today':
66
+ from = new Date(today);
67
+ break;
68
+ case '7days':
69
+ from = new Date(today); from.setDate(from.getDate() - 6);
70
+ break;
71
+ case '30days':
72
+ from = new Date(today); from.setDate(from.getDate() - 29);
73
+ break;
74
+ case '3months':
75
+ from = new Date(today); from.setMonth(from.getMonth() - 3);
76
+ break;
77
+ case 'thisYear': {
78
+ const j = Jalali.now();
79
+ const g = this._parseJalali(`${j.year}/01/01`);
80
+ from = g || new Date(today);
81
+ break;
82
+ }
83
+ case 'lastYear': {
84
+ const j = Jalali.now();
85
+ const start = this._parseJalali(`${j.year - 1}/01/01`);
86
+ const end = this._parseJalali(`${j.year - 1}/12/29`);
87
+ from = start;
88
+ to = end || new Date();
89
+ break;
90
+ }
91
+ case 'custom':
92
+ from = filter.from ? this._parseJalali(filter.from) : null;
93
+ to = filter.to ? this._parseJalali(filter.to) : new Date();
94
+ break;
95
+ default:
96
+ from = null;
97
+ }
98
+ } else {
99
+ // پیشفرض: ۳۰ روز اخیر
100
+ from = new Date(today); from.setDate(from.getDate() - 29);
101
+ }
102
+
103
+ return { from, to };
104
+ }
105
+
106
+ // ============================================================
107
+ // ۱. سود و زیان
108
+ // ============================================================
109
+ async getProfitLoss(filter = {}) {
110
+ const { invoices, products, expenses } = await this._loadData();
111
+ const { from, to } = this._getRange(filter);
112
+
113
+ // فقط فاکتورهای فروش (بدون پیشفاکتور)
114
+ const salesInRange = invoices.filter(i =>
115
+ i.kind === 'sale' &&
116
+ !i.isPreInvoice &&
117
+ this._inRange(i.date, from, to)
118
+ );
119
+
120
+ // برگشت از فروش
121
+ const returnsInRange = invoices.filter(i =>
122
+ i.kind === 'sale_return' &&
123
+ !i.isPreInvoice &&
124
+ this._inRange(i.date, from, to)
125
+ );
126
+
127
+ // فروش ناخالص = مجموع فروش بدون مالیات و تخفیف نهایی
128
+ const grossSales = salesInRange.reduce((s, i) => s + (Number(i.subtotal) || 0), 0);
129
+ const salesDiscounts = salesInRange.reduce((s, i) => s + (Number(i.totalDiscount) || 0), 0);
130
+ const returnsAmount = returnsInRange.reduce((s, i) => s + (Number(i.subtotal) || 0), 0);
131
+ const netSales = grossSales - salesDiscounts - returnsAmount;
132
+
133
+ // بهای تمامشده (COGS) — از قیمت خرید هر کالا
134
+ let cogs = 0;
135
+ const productMap = {};
136
+ products.forEach(p => productMap[p.id] = p);
137
+
138
+ salesInRange.forEach(inv => {
139
+ (inv.items || []).forEach(it => {
140
+ const p = productMap[it.productId];
141
+ const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
142
+ const qty = Number(it.qty) || 0;
143
+ cogs += buyPrice * qty;
144
+ });
145
+ });
146
+
147
+ // برگشتها رو از COGS کم کن
148
+ returnsInRange.forEach(inv => {
149
+ (inv.items || []).forEach(it => {
150
+ const p = productMap[it.productId];
151
+ const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
152
+ const qty = Number(it.qty) || 0;
153
+ cogs -= buyPrice * qty;
154
+ });
155
+ });
156
+
157
+ cogs = Math.max(0, cogs);
158
+ const grossProfit = netSales - cogs;
159
+ const grossMargin = netSales > 0 ? (grossProfit / netSales) * 100 : 0;
160
+
161
+ // هزینههای عملیاتی و سایر درآمدها
162
+ const expensesInRange = expenses.filter(e => this._inRange(e.date, from, to));
163
+ const operatingExpenses = expensesInRange.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0);
164
+ const otherIncome = expensesInRange.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0);
165
+
166
+ const netProfit = grossProfit - operatingExpenses + otherIncome;
167
+ const netMargin = netSales > 0 ? (netProfit / netSales) * 100 : 0;
168
+
169
+ return {
170
+ grossSales,
171
+ salesDiscounts,
172
+ returnsAmount,
173
+ netSales,
174
+ cogs,
175
+ grossProfit,
176
+ grossMargin,
177
+ operatingExpenses,
178
+ otherIncome,
179
+ netProfit,
180
+ netMargin,
181
+ invoiceCount: salesInRange.length,
182
+ returnCount: returnsInRange.length,
183
+ periodFrom: from,
184
+ periodTo: to
185
+ };
186
+ }
187
+
188
+ // ============================================================
189
+ // ۲. تحلیل فروش (Top Products & Customers)
190
+ // ============================================================
191
+ async getSalesAnalysis(filter = {}) {
192
+ const { invoices, products, contacts } = await this._loadData();
193
+ const { from, to } = this._getRange(filter);
194
+
195
+ const salesInRange = invoices.filter(i =>
196
+ i.kind === 'sale' &&
197
+ !i.isPreInvoice &&
198
+ this._inRange(i.date, from, to)
199
+ );
200
+
201
+ // محصولات
202
+ const productStats = {};
203
+ const productMap = {};
204
+ products.forEach(p => productMap[p.id] = p);
205
+
206
+ salesInRange.forEach(inv => {
207
+ (inv.items || []).forEach(it => {
208
+ const key = it.productId || 'unknown_' + (it.productName || '');
209
+ if (!productStats[key]) {
210
+ productStats[key] = {
211
+ productId: it.productId,
212
+ productName: it.productName || 'ناشناس',
213
+ qty: 0,
214
+ totalSales: 0,
215
+ cogs: 0,
216
+ count: 0
217
+ };
218
+ }
219
+ const qty = Number(it.qty) || 0;
220
+ const lineTotal = Number(it.lineTotal) || (qty * (Number(it.price) || 0));
221
+ const p = productMap[it.productId];
222
+ const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
223
+ productStats[key].qty += qty;
224
+ productStats[key].totalSales += lineTotal;
225
+ productStats[key].cogs += buyPrice * qty;
226
+ productStats[key].count += 1;
227
+ });
228
+ });
229
+
230
+ const topProductsBySales = Object.values(productStats)
231
+ .map(s => ({ ...s, profit: s.totalSales - s.cogs }))
232
+ .sort((a, b) => b.totalSales - a.totalSales)
233
+ .slice(0, 10);
234
+
235
+ const topProductsByQty = Object.values(productStats)
236
+ .sort((a, b) => b.qty - a.qty)
237
+ .slice(0, 10);
238
+
239
+ // مشتریان
240
+ const contactStats = {};
241
+ salesInRange.forEach(inv => {
242
+ const key = inv.contactId || 'unknown';
243
+ if (!contactStats[key]) {
244
+ contactStats[key] = {
245
+ contactId: inv.contactId,
246
+ contactName: inv.contactName || 'ناشناس',
247
+ invoiceCount: 0,
248
+ totalSales: 0,
249
+ totalPaid: 0,
250
+ totalRemaining: 0
251
+ };
252
+ }
253
+ contactStats[key].invoiceCount += 1;
254
+ contactStats[key].totalSales += Number(inv.grandTotal) || 0;
255
+ contactStats[key].totalPaid += Number(inv.paidAmount) || 0;
256
+ contactStats[key].totalRemaining += Number(inv.remaining) || 0;
257
+ });
258
+
259
+ const topCustomers = Object.values(contactStats)
260
+ .sort((a, b) => b.totalSales - a.totalSales)
261
+ .slice(0, 10);
262
+
263
+ return {
264
+ topProductsBySales,
265
+ topProductsByQty,
266
+ topCustomers,
267
+ invoiceCount: salesInRange.length
268
+ };
269
+ }
270
+
271
+ // ============================================================
272
+ // ۳. سودآوری کالا (همه کالاها)
273
+ // ============================================================
274
+ async getProductProfitability(filter = {}) {
275
+ const { invoices, products } = await this._loadData();
276
+ const { from, to } = this._getRange(filter);
277
+
278
+ const salesInRange = invoices.filter(i =>
279
+ i.kind === 'sale' &&
280
+ !i.isPreInvoice &&
281
+ this._inRange(i.date, from, to)
282
+ );
283
+
284
+ const productMap = {};
285
+ products.forEach(p => productMap[p.id] = p);
286
+
287
+ const stats = {};
288
+ salesInRange.forEach(inv => {
289
+ (inv.items || []).forEach(it => {
290
+ const key = it.productId || 'unknown_' + (it.productName || '');
291
+ if (!stats[key]) {
292
+ const p = productMap[it.productId];
293
+ stats[key] = {
294
+ productId: it.productId,
295
+ productName: it.productName || 'ناشناس',
296
+ unit: it.unit || 'عدد',
297
+ qty: 0,
298
+ totalSales: 0,
299
+ cogs: 0,
300
+ profit: 0,
301
+ margin: 0
302
+ };
303
+ }
304
+ const qty = Number(it.qty) || 0;
305
+ const lineTotal = Number(it.lineTotal) || (qty * (Number(it.price) || 0));
306
+ const p = productMap[it.productId];
307
+ const buyPrice = p ? (Number(p.buyPrice) || 0) : 0;
308
+ stats[key].qty += qty;
309
+ stats[key].totalSales += lineTotal;
310
+ stats[key].cogs += buyPrice * qty;
311
+ });
312
+ });
313
+
314
+ const rows = Object.values(stats).map(s => {
315
+ s.profit = s.totalSales - s.cogs;
316
+ s.margin = s.totalSales > 0 ? (s.profit / s.totalSales) * 100 : 0;
317
+ return s;
318
+ }).sort((a, b) => b.profit - a.profit);
319
+
320
+ return rows;
321
+ }
322
+
323
+ // ============================================================
324
+ // ۴. گزارش مشتریان
325
+ // ============================================================
326
+ async getCustomerReport(filter = {}) {
327
+ const { invoices, contacts } = await this._loadData();
328
+ const { from, to } = this._getRange(filter);
329
+
330
+ const contactMap = {};
331
+ contacts.forEach(c => contactMap[c.id] = c);
332
+
333
+ const stats = {};
334
+ invoices.forEach(inv => {
335
+ if (inv.isPreInvoice) return;
336
+ if (!this._inRange(inv.date, from, to)) return;
337
+ const key = inv.contactId || 'unknown';
338
+ if (!stats[key]) {
339
+ const c = contactMap[inv.contactId];
340
+ stats[key] = {
341
+ contactId: inv.contactId,
342
+ contactName: inv.contactName || 'ناشناس',
343
+ entityType: c?.entityType || 'natural',
344
+ totalInvoices: 0,
345
+ totalSales: 0,
346
+ totalReturns: 0,
347
+ totalPaid: 0,
348
+ totalRemaining: 0,
349
+ lastInvoiceDate: ''
350
+ };
351
+ }
352
+ const isSale = inv.kind === 'sale';
353
+ const isReturn = inv.kind === 'sale_return';
354
+ if (isSale) {
355
+ stats[key].totalInvoices += 1;
356
+ stats[key].totalSales += Number(inv.grandTotal) || 0;
357
+ stats[key].totalPaid += Number(inv.paidAmount) || 0;
358
+ stats[key].totalRemaining += Number(inv.remaining) || 0;
359
+ } else if (isReturn) {
360
+ stats[key].totalReturns += Number(inv.grandTotal) || 0;
361
+ }
362
+ if (inv.date > (stats[key].lastInvoiceDate || '')) {
363
+ stats[key].lastInvoiceDate = inv.date;
364
+ }
365
+ });
366
+
367
+ return Object.values(stats).sort((a, b) => b.totalSales - a.totalSales);
368
+ }
369
+
370
+ // ============================================================
371
+ // آمار کمکی برای هدر صفحه
372
+ // ============================================================
373
+ async getQuickStats(filter = {}) {
374
+ const pl = await this.getProfitLoss(filter);
375
+ return {
376
+ netSales: pl.netSales,
377
+ netProfit: pl.netProfit,
378
+ netMargin: pl.netMargin,
379
+ grossMargin: pl.grossMargin
380
+ };
381
+ }
382
+}
383
+
384
+export const ReportController = new ReportControllerImpl();
385
+window.ReportController = ReportController;
\ No newline at end of file
src/main.js
+3
-13
@@ -10,6 +10,7 @@ import { ContactsView } from './views/ContactsView.js';
10
import { ProductsView } from './views/ProductsView.js';
11
import { ExpensesView } from './views/ExpensesView.js';
12
import { DashboardView } from './views/DashboardView.js';
13
+import { ReportsView } from './views/ReportsView.js';
14
import { StorageService } from './core/StorageService.js';
15
import { Theme } from './core/Theme.js';
16
import { Toast } from './core/Toast.js';
@@ -32,18 +33,6 @@ const FINORA = {
33
window.FINORA = FINORA;
34
35
function registerRoutes() {
35
- const placeholder = (title, phase) => async () => `
36
- <div class="page-title">
37
- <h2>${title}</h2>
38
- <p>این ماژول در فاز ${phase} پیادهسازی میشود</p>
39
- </div>
40
- <div class="card" style="text-align:center;padding:60px 20px">
41
- <div style="font-size:60px;margin-bottom:16px">🚧</div>
42
- <h3 style="margin-bottom:8px">در حال توسعه</h3>
43
- <p class="text-muted">این بخش بهزودی اضافه میشود</p>
44
- </div>
45
- `;
46
-
36
Router.register('dashboard', {
37
title: 'داشبورد',
38
render: () => DashboardView.render(),
@@ -88,7 +77,8 @@ function registerRoutes() {
77
78
Router.register('reports', {
79
title: 'گزارش سود و زیان',
91
- render: placeholder('گزارش سود و زیان', 8)
80
+ render: () => ReportsView.render(),
81
+ onMount: () => ReportsView.onMount()
82
});
83
84
Router.register('settings', {
src/views/ReportsView.js
new
+687
@@ -0,0 +1,687 @@
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" 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" 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
+ // تب ۱: سود و زیان
168
+ // ============================================================
169
+ renderPLTab() {
170
+ const pl = cache.pl || {};
171
+
172
+ const rows = [
173
+ { label: 'فروش ناخالص', value: pl.grossSales, color: 'var(--text)', bold: false, sign: '+' },
174
+ { label: 'تخفیف فروش', value: -pl.salesDiscounts, color: 'var(--danger)', bold: false, sign: '-' },
175
+ { label: 'برگشت از فروش', value: -pl.returnsAmount, color: 'var(--danger)', bold: false, sign: '-' },
176
+ { label: 'فروش خالص', value: pl.netSales, color: 'var(--primary)', bold: true, sign: '=' },
177
+ { label: 'بهای تمامشده کالای فروشرفته (COGS)', value: -pl.cogs, color: 'var(--warning)', bold: false, sign: '-' },
178
+ { label: 'سود ناخالص', value: pl.grossProfit, color: 'var(--success)', bold: true, sign: '=' },
179
+ { label: 'هزینههای عملیاتی', value: -pl.operatingExpenses, color: 'var(--danger)', bold: false, sign: '-' },
180
+ { label: 'سایر درآمدها', value: pl.otherIncome, color: 'var(--success)', bold: false, sign: '+' },
181
+ { label: 'سود (زیان) خالص', value: pl.netProfit, color: pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)', bold: true, sign: '=' }
182
+ ];
183
+
184
+ const rowsHtml = rows.map(r => {
185
+ const isBold = r.bold;
186
+ const val = Math.abs(Number(r.value) || 0);
187
+ const sign = Number(r.value) < 0 ? '-' : (r.sign === '+' ? '+' : '');
188
+ const display = (r.value === 0) ? Formatters.money(0) : `${sign} ${Formatters.money(val)}`;
189
+ return `
190
+ <tr style="${isBold ? 'background:var(--bg);font-weight:700' : ''}">
191
+ <td style="padding:12px 16px;font-size:${isBold ? '14px' : '13px'}">${r.label}</td>
192
+ <td style="padding:12px 16px;text-align:left;font-size:${isBold ? '14px' : '13px'};color:${r.color};font-weight:${isBold ? '800' : '600'}">
193
+ ${display}
194
+ </td>
195
+ </tr>
196
+ `;
197
+ }).join('');
198
+
199
+ const marginLabel = pl.netProfit >= 0 ? 'حاشیه سود خالص' : 'حاشیه زیان خالص';
200
+
201
+ return `
202
+ <div class="grid-kpi">
203
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
204
+ <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📊</div>
205
+ <div style="flex:1">
206
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش خالص</div>
207
+ <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.money(pl.netSales)}</div>
208
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(pl.invoiceCount)} فاکتور</div>
209
+ </div>
210
+ </div>
211
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)">
212
+ <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💵</div>
213
+ <div style="flex:1">
214
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">سود ناخالص</div>
215
+ <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(pl.grossProfit)}</div>
216
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.percent(pl.grossMargin || 0)}</div>
217
+ </div>
218
+ </div>
219
+ <div class="card kpi-card" style="margin:0;border-top:3px solid ${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">
220
+ <div class="kpi-card-icon" style="background:${pl.netProfit >= 0 ? '#ecfdf5' : '#fef2f2'};color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">${pl.netProfit >= 0 ? '📈' : '📉'}</div>
221
+ <div style="flex:1">
222
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">سود (زیان) خالص</div>
223
+ <div style="font-size:16px;font-weight:800;color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(pl.netProfit)}</div>
224
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.percent(pl.netMargin || 0)}</div>
225
+ </div>
226
+ </div>
227
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)">
228
+ <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">💸</div>
229
+ <div style="flex:1">
230
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">بهای تمامشده</div>
231
+ <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(pl.cogs)}</div>
232
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">COGS</div>
233
+ </div>
234
+ </div>
235
+ </div>
236
+
237
+ <div class="card">
238
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">💹 صورت سود و زیان</h3>
239
+ <div class="table-wrap">
240
+ <table>
241
+ <thead>
242
+ <tr>
243
+ <th style="width:60%">شرح</th>
244
+ <th style="text-align:left">مبلغ</th>
245
+ </tr>
246
+ </thead>
247
+ <tbody>${rowsHtml}</tbody>
248
+ <tfoot>
249
+ <tr style="background:${pl.netProfit >= 0 ? 'linear-gradient(135deg,#ecfdf5,#f0fdf4)' : 'linear-gradient(135deg,#fef2f2,#fff1f2)'}">
250
+ <td style="padding:16px;font-weight:800;font-size:15px">${marginLabel}</td>
251
+ <td style="padding:16px;text-align:left;font-weight:800;font-size:15px;color:${pl.netProfit >= 0 ? 'var(--success)' : 'var(--danger)'}">
252
+ ${Formatters.percent(pl.netMargin || 0)}
253
+ </td>
254
+ </tr>
255
+ </tfoot>
256
+ </table>
257
+ </div>
258
+ </div>
259
+
260
+ ${pl.netSales === 0 ? `
261
+ <div class="card" style="text-align:center;padding:30px">
262
+ <div style="font-size:40px;margin-bottom:10px;opacity:.4">📊</div>
263
+ <p style="font-size:13px;color:var(--text-muted)">در این بازهی زمانی فروشی ثبت نشده است</p>
264
+ </div>
265
+ ` : ''}
266
+ `;
267
+ }
268
+
269
+ // ============================================================
270
+ // تب ۲: تحلیل فروش
271
+ // ============================================================
272
+ renderSalesTab() {
273
+ const s = cache.sales || {};
274
+ const topBySales = s.topProductsBySales || [];
275
+ const topByQty = s.topProductsByQty || [];
276
+ const topCustomers = s.topCustomers || [];
277
+
278
+ const productsChartData = topBySales.slice(0, 8).map(p => ({
279
+ label: this._truncate(p.productName, 12),
280
+ value: p.totalSales
281
+ }));
282
+
283
+ return `
284
+ <div class="card">
285
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📊 پرفروشترین کالاها (به ترتیب مبلغ)</h3>
286
+ ${Chart.bars(topBySales.slice(0, 8).map(p => ({
287
+ label: this._truncate(p.productName, 10),
288
+ income: p.totalSales,
289
+ expense: p.cogs
290
+ })), { incomeColor: '#0d9488', expenseColor: '#d97706' })}
291
+ </div>
292
+
293
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px" class="dash-grid-main">
294
+ <div class="card" style="margin:0">
295
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">🏆 ۱۰ کالای پرفروش (مبلغ)</h3>
296
+ <div class="table-wrap">
297
+ <table>
298
+ <thead>
299
+ <tr>
300
+ <th style="width:30px">#</th>
301
+ <th>نام کالا</th>
302
+ <th style="width:70px">تعداد</th>
303
+ <th style="width:130px">مبلغ فروش</th>
304
+ </tr>
305
+ </thead>
306
+ <tbody>
307
+ ${topBySales.length === 0 ? '<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">دادهای نیست</td></tr>' : topBySales.map((p, i) => `
308
+ <tr>
309
+ <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
310
+ <td>${this._esc(p.productName)}</td>
311
+ <td>${Formatters.number(p.qty)}</td>
312
+ <td style="font-weight:600">${Formatters.money(p.totalSales)}</td>
313
+ </tr>
314
+ `).join('')}
315
+ </tbody>
316
+ </table>
317
+ </div>
318
+ </div>
319
+
320
+ <div class="card" style="margin:0">
321
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">🏆 ۱۰ کالای پرفروش (تعداد)</h3>
322
+ <div class="table-wrap">
323
+ <table>
324
+ <thead>
325
+ <tr>
326
+ <th style="width:30px">#</th>
327
+ <th>نام کالا</th>
328
+ <th style="width:70px">تعداد</th>
329
+ <th style="width:130px">مبلغ فروش</th>
330
+ </tr>
331
+ </thead>
332
+ <tbody>
333
+ ${topByQty.length === 0 ? '<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">دادهای نیست</td></tr>' : topByQty.map((p, i) => `
334
+ <tr>
335
+ <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
336
+ <td>${this._esc(p.productName)}</td>
337
+ <td style="font-weight:700;color:var(--primary)">${Formatters.number(p.qty)}</td>
338
+ <td>${Formatters.money(p.totalSales)}</td>
339
+ </tr>
340
+ `).join('')}
341
+ </tbody>
342
+ </table>
343
+ </div>
344
+ </div>
345
+ </div>
346
+
347
+ <div class="card">
348
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">👥 ۱۰ مشتری برتر (به ترتیب مبلغ خرید)</h3>
349
+ <div class="table-wrap">
350
+ <table>
351
+ <thead>
352
+ <tr>
353
+ <th style="width:30px">#</th>
354
+ <th>مشتری</th>
355
+ <th style="width:100px">تعداد فاکتور</th>
356
+ <th style="width:150px">مجموع خرید</th>
357
+ <th style="width:150px">مجموع پرداخت</th>
358
+ <th style="width:150px">مانده</th>
359
+ </tr>
360
+ </thead>
361
+ <tbody>
362
+ ${topCustomers.length === 0 ? '<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-muted)">دادهای نیست</td></tr>' : topCustomers.map((c, i) => `
363
+ <tr>
364
+ <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
365
+ <td>${this._esc(c.contactName)}</td>
366
+ <td>${Formatters.number(c.invoiceCount)}</td>
367
+ <td style="font-weight:600;color:var(--primary)">${Formatters.money(c.totalSales)}</td>
368
+ <td style="color:var(--success)">${Formatters.money(c.totalPaid)}</td>
369
+ <td style="font-weight:600;color:${c.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
370
+ </tr>
371
+ `).join('')}
372
+ </tbody>
373
+ </table>
374
+ </div>
375
+ </div>
376
+ `;
377
+ }
378
+
379
+ // ============================================================
380
+ // تب ۳: سودآوری کالاها
381
+ // ============================================================
382
+ renderProductsTab() {
383
+ const list = cache.products || [];
384
+ const totalSales = list.reduce((s, p) => s + p.totalSales, 0);
385
+ const totalProfit = list.reduce((s, p) => s + p.profit, 0);
386
+
387
+ return `
388
+ <div class="grid-kpi">
389
+ <div class="card kpi-card" style="margin:0">
390
+ <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📦</div>
391
+ <div style="flex:1">
392
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد کالاهای فروشرفته</div>
393
+ <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(list.length)}</div>
394
+ </div>
395
+ </div>
396
+ <div class="card kpi-card" style="margin:0">
397
+ <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💰</div>
398
+ <div style="flex:1">
399
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع فروش</div>
400
+ <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div>
401
+ </div>
402
+ </div>
403
+ <div class="card kpi-card" style="margin:0">
404
+ <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">📈</div>
405
+ <div style="flex:1">
406
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع سود</div>
407
+ <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(totalProfit)}</div>
408
+ </div>
409
+ </div>
410
+ <div class="card kpi-card" style="margin:0">
411
+ <div class="kpi-card-icon" style="background:#fef3c7;color:var(--warning)">%</div>
412
+ <div style="flex:1">
413
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">میانگین حاشیه سود</div>
414
+ <div style="font-size:16px;font-weight:800;color:var(--warning)">${Formatters.percent(totalSales > 0 ? (totalProfit / totalSales) * 100 : 0)}</div>
415
+ </div>
416
+ </div>
417
+ </div>
418
+
419
+ <div class="card">
420
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📦 جدول سودآوری کالاها</h3>
421
+ <div class="table-wrap">
422
+ <table>
423
+ <thead>
424
+ <tr>
425
+ <th style="width:30px">#</th>
426
+ <th>نام کالا</th>
427
+ <th style="width:80px">واحد</th>
428
+ <th style="width:80px">تعداد فروش</th>
429
+ <th style="width:140px">فروش کل</th>
430
+ <th style="width:140px">بهای تمامشده</th>
431
+ <th style="width:140px">سود خالص</th>
432
+ <th style="width:100px">حاشیه سود</th>
433
+ </tr>
434
+ </thead>
435
+ <tbody>
436
+ ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">هیچ کالایی در این بازه فروش نرفته</td></tr>' : list.map((p, i) => `
437
+ <tr>
438
+ <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
439
+ <td>${this._esc(p.productName)}</td>
440
+ <td>${this._esc(p.unit)}</td>
441
+ <td style="font-weight:700">${Formatters.number(p.qty)}</td>
442
+ <td>${Formatters.money(p.totalSales)}</td>
443
+ <td style="color:var(--warning)">${Formatters.money(p.cogs)}</td>
444
+ <td style="font-weight:700;color:${p.profit >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(p.profit)}</td>
445
+ <td>
446
+ <span class="badge ${p.margin >= 30 ? 'badge-success' : p.margin >= 10 ? 'badge-warning' : 'badge-danger'}">
447
+ ${Formatters.percent(p.margin)}
448
+ </span>
449
+ </td>
450
+ </tr>
451
+ `).join('')}
452
+ </tbody>
453
+ </table>
454
+ </div>
455
+ </div>
456
+ `;
457
+ }
458
+
459
+ // ============================================================
460
+ // تب ۴: گزارش مشتریان
461
+ // ============================================================
462
+ renderCustomersTab() {
463
+ const list = cache.customers || [];
464
+ const totalSales = list.reduce((s, c) => s + c.totalSales, 0);
465
+ const totalRemaining = list.reduce((s, c) => s + c.totalRemaining, 0);
466
+
467
+ return `
468
+ <div class="grid-kpi">
469
+ <div class="card kpi-card" style="margin:0">
470
+ <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">👥</div>
471
+ <div style="flex:1">
472
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد مشتریان فعال</div>
473
+ <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(list.length)}</div>
474
+ </div>
475
+ </div>
476
+ <div class="card kpi-card" style="margin:0">
477
+ <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💰</div>
478
+ <div style="flex:1">
479
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع فروش</div>
480
+ <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div>
481
+ </div>
482
+ </div>
483
+ <div class="card kpi-card" style="margin:0">
484
+ <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">⏳</div>
485
+ <div style="flex:1">
486
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مجموع مطالبات</div>
487
+ <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(totalRemaining)}</div>
488
+ </div>
489
+ </div>
490
+ </div>
491
+
492
+ <div class="card">
493
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">👥 گزارش تفصیلی مشتریان</h3>
494
+ <div class="table-wrap">
495
+ <table>
496
+ <thead>
497
+ <tr>
498
+ <th style="width:30px">#</th>
499
+ <th>نام مشتری</th>
500
+ <th style="width:100px">نوع</th>
501
+ <th style="width:110px">تعداد فاکتور</th>
502
+ <th style="width:140px">مجموع خرید</th>
503
+ <th style="width:140px">پرداختشده</th>
504
+ <th style="width:140px">مانده</th>
505
+ <th style="width:120px">آخرین فاکتور</th>
506
+ </tr>
507
+ </thead>
508
+ <tbody>
509
+ ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">دادهای نیست</td></tr>' : list.map((c, i) => `
510
+ <tr>
511
+ <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
512
+ <td>${this._esc(c.contactName)}</td>
513
+ <td><span class="badge ${c.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entityType === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
514
+ <td>${Formatters.number(c.totalInvoices)}</td>
515
+ <td style="font-weight:600;color:var(--primary)">${Formatters.money(c.totalSales)}</td>
516
+ <td style="color:var(--success)">${Formatters.money(c.totalPaid)}</td>
517
+ <td style="font-weight:700;color:${c.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
518
+ <td>${c.lastInvoiceDate ? Formatters.toPersianDigits(c.lastInvoiceDate) : '—'}</td>
519
+ </tr>
520
+ `).join('')}
521
+ </tbody>
522
+ </table>
523
+ </div>
524
+ </div>
525
+ `;
526
+ }
527
+
528
+ // ============================================================
529
+ // چاپ گزارش
530
+ // ============================================================
531
+ _printReport() {
532
+ const pl = cache.pl || {};
533
+ const tabNames = { pl: 'سود و زیان', sales: 'تحلیل فروش', products: 'سودآوری کالاها', customers: 'گزارش مشتریان' };
534
+ const rangeText = this._formatRange(pl.periodFrom, pl.periodTo);
535
+
536
+ const printWin = window.open('', '_blank', 'width=900,height=700');
537
+ if (!printWin) { Toast.error('پاپآپ را فعال کنید'); return; }
538
+
539
+ const content = this._buildPrintContent();
540
+
541
+ printWin.document.write(`
542
+ <!DOCTYPE html>
543
+ <html lang="fa" dir="rtl">
544
+ <head>
545
+ <meta charset="UTF-8" />
546
+ <title>گزارش ${tabNames[currentTab]}</title>
547
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
548
+ <style>
549
+ @page { size: A4 portrait; margin: 10mm; }
550
+ * { box-sizing: border-box; margin: 0; padding: 0; }
551
+ html, body { direction: rtl; text-align: right; font-family: 'Vazirmatn FD', Tahoma, sans-serif; background: #fff; color: #000; }
552
+ body { padding: 10px; }
553
+ table { width: 100%; border-collapse: collapse; direction: rtl; }
554
+ th, td { padding: 8px 10px; border: 1px solid #cbd5e1; text-align: right; font-size: 11.5px; }
555
+ th { background: #f1f5f9; font-weight: 700; }
556
+ h1 { font-size: 18px; margin-bottom: 6px; color: #0d9488; text-align: center; }
557
+ h2 { font-size: 14px; margin: 16px 0 10px; color: #0d9488; border-bottom: 2px solid #0d9488; padding-bottom: 4px; }
558
+ .header-info { text-align: center; font-size: 12px; color: #64748b; margin-bottom: 20px; }
559
+ .footer { margin-top: 30px; text-align: center; font-size: 10px; color: #94a3b8; padding-top: 10px; border-top: 1px dashed #cbd5e1; }
560
+ @media print {
561
+ * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
562
+ }
563
+ </style>
564
+ </head>
565
+ <body>
566
+ <h1>گزارش ${tabNames[currentTab]}</h1>
567
+ <div class="header-info">بازه: ${rangeText} | تاریخ چاپ: ${Jalali.today()}</div>
568
+ ${content}
569
+ <div class="footer">فینورا پرو - سامانه مدیریت کسبوکار</div>
570
+ </body>
571
+ </html>
572
+ `);
573
+ printWin.document.close();
574
+ setTimeout(() => { printWin.focus(); printWin.print(); }, 500);
575
+ }
576
+
577
+ _buildPrintContent() {
578
+ const pl = cache.pl || {};
579
+ if (currentTab === 'pl') {
580
+ return `
581
+ <h2>صورت سود و زیان</h2>
582
+ <table>
583
+ <tr><td style="width:60%">فروش ناخالص</td><td>${Formatters.money(pl.grossSales)}</td></tr>
584
+ <tr><td>تخفیف فروش</td><td style="color:#dc2626">- ${Formatters.money(pl.salesDiscounts)}</td></tr>
585
+ <tr><td>برگشت از فروش</td><td style="color:#dc2626">- ${Formatters.money(pl.returnsAmount)}</td></tr>
586
+ <tr style="background:#f1f5f9;font-weight:700"><td>فروش خالص</td><td>${Formatters.money(pl.netSales)}</td></tr>
587
+ <tr><td>بهای تمامشده کالای فروشرفته</td><td style="color:#d97706">- ${Formatters.money(pl.cogs)}</td></tr>
588
+ <tr style="background:#f1f5f9;font-weight:700"><td>سود ناخالص</td><td style="color:#059669">${Formatters.money(pl.grossProfit)}</td></tr>
589
+ <tr><td>هزینههای عملیاتی</td><td style="color:#dc2626">- ${Formatters.money(pl.operatingExpenses)}</td></tr>
590
+ <tr><td>سایر درآمدها</td><td style="color:#059669">+ ${Formatters.money(pl.otherIncome)}</td></tr>
591
+ <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>
592
+ </table>
593
+ <h2>شاخصها</h2>
594
+ <table>
595
+ <tr><td>حاشیه سود ناخالص</td><td>${Formatters.percent(pl.grossMargin)}</td></tr>
596
+ <tr><td>حاشیه سود خالص</td><td>${Formatters.percent(pl.netMargin)}</td></tr>
597
+ <tr><td>تعداد فاکتور فروش</td><td>${Formatters.number(pl.invoiceCount)}</td></tr>
598
+ </table>
599
+ `;
600
+ }
601
+
602
+ if (currentTab === 'products') {
603
+ const list = cache.products || [];
604
+ return `
605
+ <h2>سودآوری کالاها (${Formatters.number(list.length)} کالا)</h2>
606
+ <table>
607
+ <thead><tr><th>#</th><th>نام کالا</th><th>تعداد</th><th>فروش کل</th><th>بهای تمامشده</th><th>سود خالص</th><th>حاشیه سود</th></tr></thead>
608
+ <tbody>
609
+ ${list.map((p, i) => `
610
+ <tr>
611
+ <td>${Formatters.toPersianDigits(i + 1)}</td>
612
+ <td>${this._esc(p.productName)}</td>
613
+ <td>${Formatters.number(p.qty)}</td>
614
+ <td>${Formatters.money(p.totalSales)}</td>
615
+ <td>${Formatters.money(p.cogs)}</td>
616
+ <td>${Formatters.money(p.profit)}</td>
617
+ <td>${Formatters.percent(p.margin)}</td>
618
+ </tr>
619
+ `).join('')}
620
+ </tbody>
621
+ </table>
622
+ `;
623
+ }
624
+
625
+ if (currentTab === 'customers') {
626
+ const list = cache.customers || [];
627
+ return `
628
+ <h2>گزارش مشتریان (${Formatters.number(list.length)} مشتری)</h2>
629
+ <table>
630
+ <thead><tr><th>#</th><th>نام مشتری</th><th>تعداد فاکتور</th><th>مجموع خرید</th><th>پرداختشده</th><th>مانده</th></tr></thead>
631
+ <tbody>
632
+ ${list.map((c, i) => `
633
+ <tr>
634
+ <td>${Formatters.toPersianDigits(i + 1)}</td>
635
+ <td>${this._esc(c.contactName)}</td>
636
+ <td>${Formatters.number(c.totalInvoices)}</td>
637
+ <td>${Formatters.money(c.totalSales)}</td>
638
+ <td>${Formatters.money(c.totalPaid)}</td>
639
+ <td>${Formatters.money(c.totalRemaining)}</td>
640
+ </tr>
641
+ `).join('')}
642
+ </tbody>
643
+ </table>
644
+ `;
645
+ }
646
+
647
+ if (currentTab === 'sales') {
648
+ const topP = cache.sales?.topProductsBySales || [];
649
+ const topC = cache.sales?.topCustomers || [];
650
+ return `
651
+ <h2>۱۰ کالای پرفروش</h2>
652
+ <table>
653
+ <thead><tr><th>#</th><th>نام کالا</th><th>تعداد</th><th>مبلغ فروش</th></tr></thead>
654
+ <tbody>
655
+ ${topP.map((p, i) => `
656
+ <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>
657
+ `).join('')}
658
+ </tbody>
659
+ </table>
660
+ <h2>۱۰ مشتری برتر</h2>
661
+ <table>
662
+ <thead><tr><th>#</th><th>نام مشتری</th><th>تعداد فاکتور</th><th>مجموع خرید</th></tr></thead>
663
+ <tbody>
664
+ ${topC.map((c, i) => `
665
+ <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>
666
+ `).join('')}
667
+ </tbody>
668
+ </table>
669
+ `;
670
+ }
671
+
672
+ return '';
673
+ }
674
+
675
+ _truncate(str, len) {
676
+ if (!str) return '';
677
+ return str.length > len ? str.slice(0, len) + '…' : str;
678
+ }
679
+
680
+ _esc(s) {
681
+ if (!s) return '';
682
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
683
+ }
684
+}
685
+
686
+export const ReportsView = new ReportsViewImpl();
687
+window.ReportsView = ReportsView;
\ No newline at end of file