فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Phase 7: Advanced dashboard with charts and KPIs
Davood Mehraban committed
Sep 18, 2026 at 20:09 UTC
7d81d46d61d982eaaa5eba182a55c468f62b05d1
7 files changed
+1382
-95
src/controllers/ExpenseController.js
new
+143
@@ -0,0 +1,143 @@
1
+// ============================================================
2
+// ExpenseController — منطق هزینهها و درآمدهای متفرقه
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
+const DEFAULT_EXPENSE_CATEGORIES = [
10
+ 'قبوض', 'اجاره', 'حقوق و دستمزد', 'ملزومات',
11
+ 'تعمیرات و نگهداری', 'حمل و نقل', 'مالیات و عوارض', 'بیمه', 'سایر'
12
+];
13
+
14
+const DEFAULT_INCOME_CATEGORIES = [
15
+ 'فروش متفرقه', 'خدمات', 'اجاره دریافتی',
16
+ 'سود بانکی', 'سود سرمایهگذاری', 'سایر'
17
+];
18
+
19
+class ExpenseControllerImpl {
20
+ async getAll(filter = {}) {
21
+ const user = Auth.current();
22
+ if (!user) return [];
23
+ let list = await StorageService.getByOwner('expenses', user.id);
24
+
25
+ if (filter.kind) list = list.filter(e => e.kind === filter.kind);
26
+ if (filter.category) list = list.filter(e => e.category === filter.category);
27
+ if (filter.dateFrom) list = list.filter(e => (e.date || '') >= filter.dateFrom);
28
+ if (filter.dateTo) list = list.filter(e => (e.date || '') <= filter.dateTo);
29
+ if (filter.search) {
30
+ const q = String(filter.search).toLowerCase();
31
+ list = list.filter(e =>
32
+ (e.category || '').toLowerCase().includes(q) ||
33
+ (e.description || '').toLowerCase().includes(q) ||
34
+ (e.refNumber || '').toLowerCase().includes(q)
35
+ );
36
+ }
37
+
38
+ return list.sort((a, b) => (b.date || '').localeCompare(a.date || ''));
39
+ }
40
+
41
+ async get(id) {
42
+ return await StorageService.get('expenses', id);
43
+ }
44
+
45
+ async create(data) {
46
+ const user = Auth.current();
47
+ if (!user) throw new Error('کاربر یافت نشد');
48
+ const expense = {
49
+ id: StorageService.uid('exp_'),
50
+ ownerUserId: user.id,
51
+ kind: data.kind === 'income' ? 'income' : 'expense',
52
+ category: (data.category || '').trim(),
53
+ amount: Math.max(0, Number(data.amount) || 0),
54
+ date: data.date || Jalali.today(),
55
+ method: data.method || 'cash',
56
+ description: (data.description || '').trim(),
57
+ refNumber: (data.refNumber || '').trim()
58
+ };
59
+ return await StorageService.put('expenses', expense);
60
+ }
61
+
62
+ async update(id, data) {
63
+ const existing = await StorageService.get('expenses', id);
64
+ if (!existing) throw new Error('سند یافت نشد');
65
+ const updated = {
66
+ ...existing,
67
+ kind: data.kind === 'income' ? 'income' : 'expense',
68
+ category: (data.category || '').trim(),
69
+ amount: Math.max(0, Number(data.amount) || 0),
70
+ date: data.date || existing.date,
71
+ method: data.method || existing.method,
72
+ description: (data.description || '').trim(),
73
+ refNumber: (data.refNumber || '').trim()
74
+ };
75
+ return await StorageService.put('expenses', updated);
76
+ }
77
+
78
+ async delete(id) {
79
+ return await StorageService.delete('expenses', id);
80
+ }
81
+
82
+ async getCategories(kind = null) {
83
+ const user = Auth.current();
84
+ if (!user) return [];
85
+ const all = await StorageService.getByOwner('expenses', user.id);
86
+ const custom = new Set();
87
+ all.forEach(e => {
88
+ if (kind && e.kind !== kind) return;
89
+ if (e.category) custom.add(e.category);
90
+ });
91
+
92
+ const defaults = kind === 'income' ? DEFAULT_INCOME_CATEGORIES
93
+ : kind === 'expense' ? DEFAULT_EXPENSE_CATEGORIES
94
+ : [...DEFAULT_EXPENSE_CATEGORIES, ...DEFAULT_INCOME_CATEGORIES];
95
+
96
+ const merged = new Set([...defaults, ...custom]);
97
+ return Array.from(merged).sort((a, b) => a.localeCompare(b, 'fa'));
98
+ }
99
+
100
+ async getStats(filter = {}) {
101
+ const list = await this.getAll(filter);
102
+ let totalIncome = 0, totalExpense = 0;
103
+ list.forEach(e => {
104
+ const amt = Number(e.amount) || 0;
105
+ if (e.kind === 'income') totalIncome += amt;
106
+ else totalExpense += amt;
107
+ });
108
+ return {
109
+ count: list.length,
110
+ totalIncome,
111
+ totalExpense,
112
+ balance: totalIncome - totalExpense
113
+ };
114
+ }
115
+
116
+ async getCategoryStats(kind = null, filter = {}) {
117
+ const list = await this.getAll({ ...filter, kind });
118
+ const map = {};
119
+ list.forEach(e => {
120
+ const cat = e.category || 'بدون سرفصل';
121
+ if (!map[cat]) map[cat] = { category: cat, total: 0, count: 0 };
122
+ map[cat].total += Number(e.amount) || 0;
123
+ map[cat].count += 1;
124
+ });
125
+ return Object.values(map).sort((a, b) => b.total - a.total);
126
+ }
127
+
128
+ getMethodLabel(method) {
129
+ return {
130
+ cash: 'نقدی',
131
+ card: 'کارت',
132
+ cheque: 'چک',
133
+ transfer: 'انتقال بانکی'
134
+ }[method] || method;
135
+ }
136
+
137
+ getKindLabel(kind) {
138
+ return kind === 'income' ? 'درآمد' : 'هزینه';
139
+ }
140
+}
141
+
142
+export const ExpenseController = new ExpenseControllerImpl();
143
+window.ExpenseController = ExpenseController;
\ No newline at end of file
src/main.js
+20
-63
@@ -8,6 +8,8 @@ import { TreasuryView } from './views/TreasuryView.js';
8
import { InvoicesView } from './views/InvoicesView.js';
9
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 { StorageService } from './core/StorageService.js';
14
import { Theme } from './core/Theme.js';
15
import { Toast } from './core/Toast.js';
@@ -44,67 +46,8 @@ function registerRoutes() {
46
47
Router.register('dashboard', {
48
title: 'داشبورد',
47
- render: async () => {
48
- const user = Auth.current();
49
- const invoices = await StorageService.getByOwner('invoices', user.id);
50
- const contacts = await StorageService.getByOwner('contacts', user.id);
51
- const products = await StorageService.getByOwner('products', user.id);
52
-
53
- const totalSales = invoices.reduce((s, i) => s + (i.grandTotal || 0), 0);
54
-
55
- return `
56
- <div class="page-title">
57
- <h2>داشبورد مدیریتی</h2>
58
- <p>نمای کلی از وضعیت کسبوکار شما</p>
59
- </div>
60
-
61
- <div class="grid-kpi">
62
- <div class="card" style="margin:0">
63
- <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">فروش کل</div>
64
- <div style="font-size:20px;font-weight:800;color:var(--primary);margin-bottom:4px">${Formatters.money(totalSales)}</div>
65
- <div style="font-size:11px;color:var(--text-muted)">${Formatters.number(invoices.length)} فاکتور</div>
66
- </div>
67
- <div class="card" style="margin:0">
68
- <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">اشخاص ثبتشده</div>
69
- <div style="font-size:20px;font-weight:800;color:var(--info);margin-bottom:4px">${Formatters.number(contacts.length)}</div>
70
- <div style="font-size:11px;color:var(--text-muted)">مشتری و تامینکننده</div>
71
- </div>
72
- <div class="card" style="margin:0">
73
- <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کالاها</div>
74
- <div style="font-size:20px;font-weight:800;color:var(--success);margin-bottom:4px">${Formatters.number(products.length)}</div>
75
- <div style="font-size:11px;color:var(--text-muted)">کالا و خدمات</div>
76
- </div>
77
- </div>
78
-
79
- <div class="card">
80
- <div class="card-title"><span>🎉 خوش آمدید به فینورا پرو</span></div>
81
- <p style="font-size:13.5px;line-height:1.9;color:var(--text-muted)">
82
- این <strong>فاز ۱</strong> از پروژه است. زیرساخت آماده است:
83
- </p>
84
- <ul style="margin-top:12px;padding-right:20px;font-size:13px;line-height:2;color:var(--text-muted)">
85
- <li>✅ پایگاهداده IndexedDB</li>
86
- <li>✅ معماری ماژولار ES Modules</li>
87
- <li>✅ Router داخلی SPA</li>
88
- <li>✅ تم روشن/تاریک</li>
89
- <li>✅ Toast حرفهای</li>
90
- <li>✅ تاریخ شمسی توکار</li>
91
- <li>✅ عدد به حروف فارسی</li>
92
- <li>✅ EventBus</li>
93
- </ul>
94
- </div>
95
-
96
- <div class="card">
97
- <div class="card-title"><span>🧪 تست سریع</span></div>
98
- <div style="display:flex;gap:10px;flex-wrap:wrap">
99
- <button class="btn" onclick="FINORA.Toast.success('این یک پیام موفقیت است')">تست Toast موفق</button>
100
- <button class="btn btn-danger" onclick="FINORA.Toast.error('این یک خطا است')">تست Toast خطا</button>
101
- <button class="btn btn-secondary" onclick="FINORA.Theme.toggle()">تغییر تم</button>
102
- <button class="btn btn-secondary" onclick="FINORA.Toast.info(FINORA.Utils.numberToWords(1234567890))">تست عدد به حروف</button>
103
- <button class="btn btn-secondary" onclick="FINORA.Toast.info(FINORA.Utils.Jalali.todayLong())">تاریخ امروز</button>
104
- </div>
105
- </div>
106
- `;
107
- }
49
+ render: () => DashboardView.render(),
50
+ onMount: () => DashboardView.onMount()
51
});
52
53
Router.register('invoices', {
@@ -112,28 +55,42 @@ function registerRoutes() {
55
render: () => InvoicesView.render(),
56
onMount: () => InvoicesView.onMount()
57
});
58
+
59
Router.register('products', {
60
title: 'کالا و انبار',
61
render: () => ProductsView.render(),
62
onMount: () => ProductsView.onMount()
63
});
64
+
65
Router.register('contacts', {
66
title: 'اشخاص',
67
render: () => ContactsView.render(),
68
onMount: () => ContactsView.onMount()
69
});
70
+
71
Router.register('treasury', {
72
title: 'خزانه و بانک',
73
render: () => TreasuryView.render(),
74
onMount: () => TreasuryView.onMount()
75
});
76
+
77
Router.register('cheques', {
78
title: 'چکها',
79
render: () => ChequesView.render(),
80
onMount: () => ChequesView.onMount()
81
});
135
- Router.register('expenses', { title: 'هزینه و درآمد', render: placeholder('هزینه و درآمد', 6) });
136
- Router.register('reports', { title: 'گزارش سود و زیان', render: placeholder('گزارش سود و زیان', 7) });
82
+
83
+ Router.register('expenses', {
84
+ title: 'هزینه و درآمد',
85
+ render: () => ExpensesView.render(),
86
+ onMount: () => ExpensesView.onMount()
87
+ });
88
+
89
+ Router.register('reports', {
90
+ title: 'گزارش سود و زیان',
91
+ render: placeholder('گزارش سود و زیان', 8)
92
+ });
93
+
94
Router.register('settings', {
95
title: 'تنظیمات',
96
render: () => SettingsView.render(),
src/styles/main.css
+62
@@ -647,4 +647,66 @@ textarea.form-control { min-height: 80px; resize: vertical; }
647
padding: 12px 6px;
648
background: var(--bg);
649
border-radius: 10px;
650
+}
651
+/* ===== Dashboard KPI Cards ===== */
652
+.kpi-card {
653
+ display: flex;
654
+ align-items: center;
655
+ gap: 12px;
656
+ padding: 14px 16px !important;
657
+}
658
+.kpi-card-icon {
659
+ width: 38px;
660
+ height: 38px;
661
+ border-radius: 10px;
662
+ display: flex;
663
+ align-items: center;
664
+ justify-content: center;
665
+ font-size: 18px;
666
+ flex-shrink: 0;
667
+}
668
+
669
+/* ===== Chart Tabs ===== */
670
+.chart-tabs {
671
+ display: flex;
672
+ gap: 4px;
673
+ background: var(--bg);
674
+ padding: 3px;
675
+ border-radius: 10px;
676
+}
677
+.chart-tab {
678
+ padding: 6px 12px;
679
+ border: none;
680
+ background: transparent;
681
+ color: var(--text-muted);
682
+ font-size: 12px;
683
+ font-weight: 600;
684
+ border-radius: 8px;
685
+ cursor: pointer;
686
+ font-family: inherit;
687
+ transition: all .15s;
688
+}
689
+.chart-tab:hover { color: var(--text); }
690
+.chart-tab.active {
691
+ background: var(--card-bg);
692
+ color: var(--primary);
693
+ box-shadow: 0 1px 3px rgba(0,0,0,.08);
694
+}
695
+
696
+/* ===== Dashboard Account Cards ===== */
697
+.dash-account-card {
698
+ background: var(--bg);
699
+ padding: 10px 12px;
700
+ border-radius: 10px;
701
+ transition: all .15s;
702
+}
703
+.dash-account-card:hover {
704
+ background: var(--primary-light);
705
+}
706
+
707
+/* ===== Dashboard Layout ===== */
708
+@media (max-width: 1024px) {
709
+ .dash-grid-main {
710
+ grid-template-columns: 1fr !important;
711
+ }
712
}
\ No newline at end of file
src/utils/Chart.js
new
+199
@@ -0,0 +1,199 @@
1
+// ============================================================
2
+// Chart — نمودار SVG سبک بدون کتابخانه خارجی
3
+// ============================================================
4
+
5
+import { Formatters } from './Formatters.js';
6
+
7
+class ChartImpl {
8
+ /**
9
+ * نمودار خطی
10
+ * @param {Array<{label, value}>} data
11
+ * @param {Object} options
12
+ */
13
+ line(data, options = {}) {
14
+ if (!data || data.length === 0) {
15
+ return this._emptyState('دادهای برای نمایش وجود ندارد');
16
+ }
17
+
18
+ const width = options.width || 800;
19
+ const height = options.height || 280;
20
+ const padding = { top: 30, right: 30, bottom: 50, left: 70 };
21
+ const chartWidth = width - padding.left - padding.right;
22
+ const chartHeight = height - padding.top - padding.bottom;
23
+ const color = options.color || '#0d9488';
24
+ const fillColor = options.fillColor || 'rgba(13, 148, 136, 0.12)';
25
+
26
+ const maxVal = Math.max(...data.map(d => Number(d.value) || 0), 1);
27
+ const stepX = data.length > 1 ? chartWidth / (data.length - 1) : 0;
28
+
29
+ // محاسبه نقاط
30
+ const points = data.map((d, i) => {
31
+ const x = padding.left + i * stepX;
32
+ const y = padding.top + chartHeight - ((Number(d.value) || 0) / maxVal) * chartHeight;
33
+ return { x, y, label: d.label, value: Number(d.value) || 0 };
34
+ });
35
+
36
+ // مسیر خط
37
+ const linePath = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`).join(' ');
38
+ // مسیر پرشده (زیر خط)
39
+ const fillPath = `${linePath} L ${points[points.length - 1].x.toFixed(1)} ${(padding.top + chartHeight).toFixed(1)} L ${points[0].x.toFixed(1)} ${(padding.top + chartHeight).toFixed(1)} Z`;
40
+
41
+ // خطوط گرید افقی
42
+ const gridLines = [];
43
+ const ySteps = 4;
44
+ for (let i = 0; i <= ySteps; i++) {
45
+ const y = padding.top + (chartHeight / ySteps) * i;
46
+ const val = maxVal * (1 - i / ySteps);
47
+ gridLines.push(`
48
+ <line x1="${padding.left}" y1="${y}" x2="${width - padding.right}" y2="${y}" stroke="#e2e8f0" stroke-dasharray="3,3" stroke-width="1"/>
49
+ <text x="${padding.left - 8}" y="${y + 4}" text-anchor="end" font-size="10" fill="#94a3b8">${Formatters.toPersianDigits(this._shortNum(val))}</text>
50
+ `);
51
+ }
52
+
53
+ // نقاط و لیبلهای محور X
54
+ const xLabels = points.map((p, i) => {
55
+ // فقط هر چند تا یک لیبل (برای جلوگیری از شلوغی)
56
+ const showEvery = Math.ceil(data.length / 10);
57
+ if (i % showEvery !== 0 && i !== data.length - 1) return '';
58
+ return `<text x="${p.x}" y="${height - padding.bottom + 18}" text-anchor="middle" font-size="9.5" fill="#64748b">${this._esc(p.label)}</text>`;
59
+ }).join('');
60
+
61
+ // نقاط دایرهای
62
+ const dots = points.map(p => `
63
+ <circle cx="${p.x}" cy="${p.y}" r="3.5" fill="#fff" stroke="${color}" stroke-width="2">
64
+ <title>${this._esc(p.label)}: ${Formatters.number(p.value)}</title>
65
+ </circle>
66
+ `).join('');
67
+
68
+ return `
69
+ <div style="width:100%;overflow-x:auto">
70
+ <svg viewBox="0 0 ${width} ${height}" style="width:100%;min-width:600px;height:auto;display:block" preserveAspectRatio="xMidYMid meet">
71
+ <defs>
72
+ <linearGradient id="lineGradient" x1="0" y1="0" x2="0" y2="1">
73
+ <stop offset="0%" stop-color="${color}" stop-opacity="0.3"/>
74
+ <stop offset="100%" stop-color="${color}" stop-opacity="0"/>
75
+ </linearGradient>
76
+ </defs>
77
+ ${gridLines.join('')}
78
+ <path d="${fillPath}" fill="url(#lineGradient)"/>
79
+ <path d="${linePath}" fill="none" stroke="${color}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>
80
+ ${dots}
81
+ ${xLabels}
82
+ </svg>
83
+ </div>
84
+ `;
85
+ }
86
+
87
+ /**
88
+ * نمودار ستونی (Bar)
89
+ * @param {Array<{label, income, expense}>} data
90
+ */
91
+ bars(data, options = {}) {
92
+ if (!data || data.length === 0) {
93
+ return this._emptyState('دادهای برای نمایش وجود ندارد');
94
+ }
95
+
96
+ const width = options.width || 800;
97
+ const height = options.height || 280;
98
+ const padding = { top: 30, right: 30, bottom: 50, left: 70 };
99
+ const chartWidth = width - padding.left - padding.right;
100
+ const chartHeight = height - padding.top - padding.bottom;
101
+ const incomeColor = options.incomeColor || '#059669';
102
+ const expenseColor = options.expenseColor || '#dc2626';
103
+
104
+ const allVals = [];
105
+ data.forEach(d => {
106
+ allVals.push(Number(d.income) || 0);
107
+ allVals.push(Number(d.expense) || 0);
108
+ });
109
+ const maxVal = Math.max(...allVals, 1);
110
+
111
+ const groupWidth = chartWidth / data.length;
112
+ const barGap = 3;
113
+ const barWidth = Math.max(4, (groupWidth - barGap * 3) / 2);
114
+
115
+ // Grid خطوط
116
+ const gridLines = [];
117
+ const ySteps = 4;
118
+ for (let i = 0; i <= ySteps; i++) {
119
+ const y = padding.top + (chartHeight / ySteps) * i;
120
+ const val = maxVal * (1 - i / ySteps);
121
+ gridLines.push(`
122
+ <line x1="${padding.left}" y1="${y}" x2="${width - padding.right}" y2="${y}" stroke="#e2e8f0" stroke-dasharray="3,3" stroke-width="1"/>
123
+ <text x="${padding.left - 8}" y="${y + 4}" text-anchor="end" font-size="10" fill="#94a3b8">${Formatters.toPersianDigits(this._shortNum(val))}</text>
124
+ `);
125
+ }
126
+
127
+ // ستونها
128
+ let barsHtml = '';
129
+ let labelsHtml = '';
130
+ data.forEach((d, i) => {
131
+ const groupX = padding.left + i * groupWidth;
132
+ const incomeH = ((Number(d.income) || 0) / maxVal) * chartHeight;
133
+ const expenseH = ((Number(d.expense) || 0) / maxVal) * chartHeight;
134
+
135
+ const incomeX = groupX + groupWidth / 2 - barWidth - barGap / 2;
136
+ const expenseX = groupX + groupWidth / 2 + barGap / 2;
137
+
138
+ const incomeY = padding.top + chartHeight - incomeH;
139
+ const expenseY = padding.top + chartHeight - expenseH;
140
+
141
+ barsHtml += `
142
+ <rect x="${incomeX}" y="${incomeY}" width="${barWidth}" height="${incomeH}" fill="${incomeColor}" rx="2">
143
+ <title>درآمد ${this._esc(d.label)}: ${Formatters.number(d.income || 0)}</title>
144
+ </rect>
145
+ <rect x="${expenseX}" y="${expenseY}" width="${barWidth}" height="${expenseH}" fill="${expenseColor}" rx="2">
146
+ <title>هزینه ${this._esc(d.label)}: ${Formatters.number(d.expense || 0)}</title>
147
+ </rect>
148
+ `;
149
+
150
+ labelsHtml += `<text x="${groupX + groupWidth / 2}" y="${height - padding.bottom + 18}" text-anchor="middle" font-size="10" fill="#64748b">${this._esc(d.label)}</text>`;
151
+ });
152
+
153
+ return `
154
+ <div style="width:100%;overflow-x:auto">
155
+ <svg viewBox="0 0 ${width} ${height}" style="width:100%;min-width:600px;height:auto;display:block" preserveAspectRatio="xMidYMid meet">
156
+ ${gridLines.join('')}
157
+ ${barsHtml}
158
+ ${labelsHtml}
159
+ </svg>
160
+ <div style="display:flex;justify-content:center;gap:20px;margin-top:8px;font-size:12px;color:var(--text-muted)">
161
+ <div style="display:flex;align-items:center;gap:6px">
162
+ <span style="display:inline-block;width:12px;height:12px;background:${incomeColor};border-radius:3px"></span>
163
+ <span>درآمد</span>
164
+ </div>
165
+ <div style="display:flex;align-items:center;gap:6px">
166
+ <span style="display:inline-block;width:12px;height:12px;background:${expenseColor};border-radius:3px"></span>
167
+ <span>هزینه</span>
168
+ </div>
169
+ </div>
170
+ </div>
171
+ `;
172
+ }
173
+
174
+ _shortNum(n) {
175
+ n = Math.abs(Math.round(n));
176
+ if (n >= 1e12) return (n / 1e12).toFixed(1) + 'T';
177
+ if (n >= 1e9) return (n / 1e9).toFixed(1) + 'M';
178
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'K';
179
+ if (n >= 1000) return (n / 1000).toFixed(1) + 'k';
180
+ return String(n);
181
+ }
182
+
183
+ _emptyState(msg) {
184
+ return `
185
+ <div style="text-align:center;padding:40px 20px;color:var(--text-muted);font-size:13px">
186
+ <div style="font-size:40px;margin-bottom:8px;opacity:.4">📊</div>
187
+ ${msg}
188
+ </div>
189
+ `;
190
+ }
191
+
192
+ _esc(s) {
193
+ if (s === null || s === undefined) return '';
194
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
195
+ }
196
+}
197
+
198
+export const Chart = new ChartImpl();
199
+window.Chart = Chart;
\ No newline at end of file
src/utils/InvoicePrint.js
+30
-32
@@ -15,28 +15,28 @@ class InvoicePrintImpl {
15
constructor() {
16
this.currentInvoiceId = null;
17
this.settings = {
18
- template: 'non_formal', // formal | non_formal | thermal
18
+ template: 'non_formal',
19
paperSize: 'A4',
20
orientation: 'portrait',
21
showSignature: true,
22
showCode: true,
23
themeColor: '#0d9488',
24
- showBalance: 'none' // none | simple | detailed
24
+ showBalance: 'none'
25
};
26
}
27
28
- // ============================================================
29
- // باز کردن تنظیمات چاپ
30
- // ============================================================
28
async openSettings(invoiceId) {
29
this.currentInvoiceId = invoiceId;
30
const inv = await InvoiceController.get(invoiceId);
31
if (!inv) { Toast.error('فاکتور یافت نشد'); return; }
32
36
- // پیشفرض بر اساس نوع سند
37
- if (inv.kind === 'formal') this.settings.template = 'formal';
38
- else if (inv.kind === 'non_formal') this.settings.template = 'non_formal';
39
- else this.settings.template = 'non_formal';
33
+ if (inv.isPreInvoice) {
34
+ this.settings.template = 'non_formal';
35
+ } else if (inv.kind === 'formal') {
36
+ this.settings.template = 'formal';
37
+ } else {
38
+ this.settings.template = 'non_formal';
39
+ }
40
41
const body = `
42
<div class="form-group">
@@ -115,7 +115,6 @@ class InvoicePrintImpl {
115
116
Modal.open({ title: 'تنظیمات چاپ فاکتور', body, footer, size: 'md' });
117
118
- // ذخیره تنظیمات در ctx
118
setTimeout(() => {
119
document.querySelectorAll('.print-tpl-card').forEach(card => {
120
card.addEventListener('click', () => {
@@ -128,8 +127,6 @@ class InvoicePrintImpl {
127
}
128
129
_collectSettings() {
131
- // فقط اگه فیلدهای تنظیمات توی صفحه موجودن، مقدار جدید رو بگیر
132
- // وگرنه از مقدار قبلی (this.settings) استفاده کن
130
const tpl = document.querySelector('input[name="tpl"]:checked');
131
if (tpl) this.settings.template = tpl.value;
132
@@ -157,7 +154,6 @@ class InvoicePrintImpl {
154
async _preview() {
155
this._collectSettings();
156
const html = await this._buildHtml(this.currentInvoiceId);
160
- // نمایش پیشنمایش در یک مودال جدید
157
const body = `
158
<div style="background:#e5e7eb;padding:20px;border-radius:8px;overflow:auto;max-height:70vh">
159
<div style="background:#fff;margin:0 auto;max-width:${this.settings.template === 'thermal' ? '80mm' : '210mm'};box-shadow:0 4px 20px rgba(0,0,0,.15)">
@@ -179,9 +175,6 @@ class InvoicePrintImpl {
175
Modal.close();
176
}
177
182
- // ============================================================
183
- // ساخت HTML چاپ
184
- // ============================================================
178
async _buildHtml(invoiceId) {
179
const inv = await InvoiceController.get(invoiceId);
180
if (!inv) throw new Error('فاکتور یافت نشد');
@@ -215,7 +208,10 @@ class InvoicePrintImpl {
208
// ------------------------------------------------------------
209
_formalTemplate(inv, seller, contact, balance) {
210
const color = this.settings.themeColor;
218
- const showCode = this.settings.showCode;
211
+
212
+ const headerTitle = inv.isPreInvoice
213
+ ? 'پیشفاکتور فروش کالا و خدمات'
214
+ : 'صورتحساب فروش کالا و خدمات';
215
216
const items = inv.items.map((it, idx) => {
217
const qty = Number(it.qty) || 0;
@@ -251,17 +247,21 @@ class InvoicePrintImpl {
247
<div class="print-doc" dir="rtl" style="direction:rtl;text-align:right;font-family:'Vazirmatn FD',Tahoma,sans-serif;color:#000;padding:6mm">
248
<table style="width:100%;border-collapse:collapse;border:2px solid ${color};margin-bottom:4px">
249
<tr>
254
- <td style="width:28%;border:1px solid ${color};padding:6px;font-size:11px;vertical-align:middle">
255
- <div style="font-weight:bold;font-size:13px;color:${color}">${this._esc(seller.name)}</div>
256
- <div style="font-size:9.5px;color:#475569;margin-top:2px">صادرکننده فاکتور رسمی</div>
250
+ <td style="width:28%;border:1px solid ${color};padding:6px;font-size:11px;vertical-align:middle;text-align:center">
251
+ <div style="font-weight:bold;font-size:7.5px;color:${color}">فینورا پرو</div>
252
</td>
253
<td style="width:44%;border:1px solid ${color};padding:8px;text-align:center;vertical-align:middle;background:#f0fdfa">
259
- <h1 style="font-size:16px;margin:0;font-weight:bold;color:${color}">صورتحساب فروش کالا و خدمات</h1>
260
- <div style="font-size:10px;margin-top:3px">(ماده ۱۶۹ مکرر قانون مالیاتهای مستقیم)</div>
254
+ <h1 style="font-size:16px;margin:0;font-weight:bold;color:${color}">${headerTitle}</h1>
255
</td>
262
- <td style="width:28%;border:1px solid ${color};padding:6px;font-size:10.5px;vertical-align:middle;text-align:left">
263
- <div>شماره سریال: <strong style="color:#b91c1c">${Formatters.toPersianDigits(inv.number)}</strong></div>
264
- <div style="margin-top:2px">تاریخ صدور: <strong>${Formatters.toPersianDigits(inv.date)}</strong></div>
256
+ <td style="width:28%;border:1px solid ${color};padding:6px;font-size:10.5px;vertical-align:middle">
257
+ <div style="display:flex;align-items:center;line-height:1.7;gap:4px">
258
+ <span style="display:inline-block;min-width:72px;text-align:left;white-space:nowrap">شماره سریال:</span>
259
+ <strong style="color:#b91c1c">${Formatters.toPersianDigits(inv.number)}</strong>
260
+ </div>
261
+ <div style="display:flex;align-items:center;line-height:1.7;gap:4px">
262
+ <span style="display:inline-block;min-width:72px;text-align:left;white-space:nowrap">تاریخ صدور:</span>
263
+ <strong>${Formatters.toPersianDigits(inv.date)}</strong>
264
+ </div>
265
</td>
266
</tr>
267
</table>
@@ -502,6 +502,10 @@ class InvoicePrintImpl {
502
${seller.address ? `<div style="font-size:9px;margin-top:2px">${this._esc(seller.address)}</div>` : ''}
503
</div>
504
505
+ <div style="text-align:center;font-size:11px;font-weight:700;margin-bottom:4px;padding:3px 0;background:#f3f4f6;border-radius:4px">
506
+ ${inv.isPreInvoice ? 'پیشفاکتور فروش' : 'فاکتور فروش'}
507
+ </div>
508
+
509
<div style="display:flex;justify-content:space-between;font-size:10px;margin-bottom:4px">
510
<div>شماره: ${Formatters.toPersianDigits(inv.number)}</div>
511
<div>تاریخ: ${Formatters.toPersianDigits(inv.date)}</div>
@@ -547,17 +551,13 @@ class InvoicePrintImpl {
551
`;
552
}
553
550
- // ============================================================
551
- // باز کردن پنجره چاپ
552
- // ============================================================
553
- _openPrintWindow(html) {
554
+ _openPrintWindow(html) {
555
const printWindow = window.open('', '_blank', 'width=900,height=700');
556
if (!printWindow) {
557
Toast.error('لطفاً پاپآپ را فعال کنید');
558
return;
559
}
560
560
- // تعیین اندازهی صفحه
561
let pageCss = 'A4 portrait';
562
if (this.settings.template === 'thermal') {
563
pageCss = '80mm auto';
@@ -574,7 +574,6 @@ class InvoicePrintImpl {
574
<title>چاپ فاکتور</title>
575
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
576
<style>
577
- /* @page باید بیرون از @media print باشه تا درست اعمال بشه */
577
@page {
578
size: ${pageCss};
579
margin: 6mm;
@@ -596,7 +595,6 @@ class InvoicePrintImpl {
595
@media print {
596
body { padding: 0; }
597
.print-doc { page-break-inside: auto; }
599
- /* جلوگیری از چاپ رنگهای پیشفرض */
598
* {
599
-webkit-print-color-adjust: exact !important;
600
print-color-adjust: exact !important;
src/views/DashboardView.js
new
+566
@@ -0,0 +1,566 @@
1
+// ============================================================
2
+// DashboardView — داشبورد کامل با KPI، نمودارها و آمار
3
+// ============================================================
4
+
5
+import { StorageService } from '../core/StorageService.js';
6
+import { Auth } from '../core/Auth.js';
7
+import { Chart } from '../utils/Chart.js';
8
+import { Formatters } from '../utils/Formatters.js';
9
+import { Jalali } from '../utils/Jalali.js';
10
+
11
+let cache = {
12
+ invoices: [],
13
+ expenses: [],
14
+ cheques: [],
15
+ treasury: [],
16
+ contacts: [],
17
+ products: [],
18
+ salesPeriod: 'monthly' // daily | monthly | yearly
19
+};
20
+
21
+class DashboardViewImpl {
22
+ async render() {
23
+ await this.reload();
24
+ return `
25
+ <div class="page-title" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
26
+ <div>
27
+ <h2>داشبورد مدیریتی</h2>
28
+ <p>${Jalali.formatLong()}</p>
29
+ </div>
30
+ <button class="btn btn-inline" onclick="FINORA.Router.go('invoices')">➕ فاکتور جدید</button>
31
+ </div>
32
+
33
+ ${this._renderKPIs()}
34
+
35
+ <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:16px" class="dash-grid-main">
36
+ ${this._renderSalesChart()}
37
+ ${this._renderAccountsCard()}
38
+ </div>
39
+
40
+ ${this._renderIncomeExpenseChart()}
41
+
42
+ ${this._renderRecentInvoices()}
43
+
44
+ ${this._renderUpcomingCheques()}
45
+ `;
46
+ }
47
+
48
+ onMount() {
49
+ window.DashboardView = this;
50
+ }
51
+
52
+ async reload() {
53
+ const user = Auth.current();
54
+ if (!user) return;
55
+ const [inv, exp, chq, trs, con, pro] = await Promise.all([
56
+ StorageService.getByOwner('invoices', user.id),
57
+ StorageService.getByOwner('expenses', user.id),
58
+ StorageService.getByOwner('cheques', user.id),
59
+ StorageService.getByOwner('treasury', user.id),
60
+ StorageService.getByOwner('contacts', user.id),
61
+ StorageService.getByOwner('products', user.id)
62
+ ]);
63
+ cache.invoices = inv || [];
64
+ cache.expenses = exp || [];
65
+ cache.cheques = chq || [];
66
+ cache.treasury = trs || [];
67
+ cache.contacts = con || [];
68
+ cache.products = pro || [];
69
+ }
70
+
71
+ // ============================================================
72
+ // KPI ها
73
+ // ============================================================
74
+ _renderKPIs() {
75
+ const today = new Date();
76
+ const currentJalali = Jalali.now();
77
+
78
+ const salesInvoices = cache.invoices.filter(i => i.kind === 'sale' && !i.isPreInvoice);
79
+
80
+ // فروش ماه جاری
81
+ const monthInvoices = salesInvoices.filter(i => {
82
+ const d = this._parseJalali(i.date);
83
+ return d && d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth();
84
+ });
85
+ const monthSales = monthInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
86
+
87
+ // فروش کل
88
+ const totalSales = salesInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
89
+
90
+ // مطالبات معوق
91
+ const unpaidInvoices = salesInvoices.filter(i => (Number(i.remaining) || 0) > 0);
92
+ const totalUnpaid = unpaidInvoices.reduce((s, i) => s + (Number(i.remaining) || 0), 0);
93
+
94
+ // درآمد و هزینه ماه
95
+ const monthExpenses = cache.expenses.filter(e => {
96
+ const d = this._parseJalali(e.date);
97
+ return d && d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth();
98
+ });
99
+ const monthIncomeTotal = monthExpenses.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0);
100
+ const monthExpenseTotal = monthExpenses.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0);
101
+
102
+ // چکهای سررسید ۷ روز آینده
103
+ const upcomingCheques = cache.cheques.filter(c => {
104
+ if (c.status !== 'pending') return false;
105
+ const due = this._parseJalali(c.dueDate);
106
+ if (!due) return false;
107
+ const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
108
+ return diff >= 0 && diff <= 7;
109
+ });
110
+ const upcomingChequesAmount = upcomingCheques.reduce((s, c) => s + (Number(c.amount) || 0), 0);
111
+
112
+ // موجودی کل خزانه
113
+ const accounts = cache.treasury.filter(t => t.recordType === 'account');
114
+ const transactions = cache.treasury.filter(t => t.recordType === 'transaction');
115
+ let totalBalance = 0;
116
+ accounts.forEach(a => totalBalance += Number(a.initialBalance) || 0);
117
+ transactions.forEach(t => {
118
+ const amt = Number(t.amount) || 0;
119
+ if (t.type === 'receipt' && t.toAccountId) totalBalance += amt;
120
+ else if (t.type === 'payment' && t.fromAccountId) totalBalance -= amt;
121
+ else if (t.type === 'transfer') {
122
+ if (t.fromAccountId) totalBalance -= amt;
123
+ if (t.toAccountId) totalBalance += amt;
124
+ }
125
+ });
126
+
127
+ return `
128
+ <div class="grid-kpi">
129
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
130
+ <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">💰</div>
131
+ <div style="flex:1">
132
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش ماه جاری</div>
133
+ <div style="font-size:17px;font-weight:800;color:var(--primary)">${Formatters.money(monthSales)}</div>
134
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(monthInvoices.length)} فاکتور</div>
135
+ </div>
136
+ </div>
137
+
138
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)">
139
+ <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">📊</div>
140
+ <div style="flex:1">
141
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش کل</div>
142
+ <div style="font-size:17px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div>
143
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(salesInvoices.length)} فاکتور کل</div>
144
+ </div>
145
+ </div>
146
+
147
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)">
148
+ <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">⏳</div>
149
+ <div style="flex:1">
150
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مطالبات معوق</div>
151
+ <div style="font-size:17px;font-weight:800;color:var(--danger)">${Formatters.money(totalUnpaid)}</div>
152
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(unpaidInvoices.length)} فاکتور</div>
153
+ </div>
154
+ </div>
155
+
156
+ <div class="card kpi-card" style="margin:0;border-top:3px solid #8b5cf6">
157
+ <div class="kpi-card-icon" style="background:#faf5ff;color:#8b5cf6">💵</div>
158
+ <div style="flex:1">
159
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">درآمد / هزینه ماه</div>
160
+ <div style="font-size:13px;font-weight:800">
161
+ <span style="color:var(--success)">${Formatters.money(monthIncomeTotal)}</span>
162
+ </div>
163
+ <div style="font-size:13px;font-weight:800;margin-top:2px">
164
+ <span style="color:var(--danger)">${Formatters.money(monthExpenseTotal)}</span>
165
+ </div>
166
+ </div>
167
+ </div>
168
+
169
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--warning)">
170
+ <div class="kpi-card-icon" style="background:#fffbeb;color:var(--warning)">💳</div>
171
+ <div style="flex:1">
172
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">چکهای سررسید (۷ روز)</div>
173
+ <div style="font-size:17px;font-weight:800;color:var(--warning)">${Formatters.money(upcomingChequesAmount)}</div>
174
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(upcomingCheques.length)} فقره</div>
175
+ </div>
176
+ </div>
177
+
178
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--info)">
179
+ <div class="kpi-card-icon" style="background:#f0f9ff;color:var(--info)">🏦</div>
180
+ <div style="flex:1">
181
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی کل خزانه</div>
182
+ <div style="font-size:17px;font-weight:800;color:var(--info)">${Formatters.money(totalBalance)}</div>
183
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(accounts.length)} حساب</div>
184
+ </div>
185
+ </div>
186
+ </div>
187
+ `;
188
+ }
189
+
190
+ // ============================================================
191
+ // نمودار فروش
192
+ // ============================================================
193
+ _renderSalesChart() {
194
+ const data = this._getSalesChartData();
195
+ const periods = [
196
+ { key: 'daily', label: '۱۴ روز' },
197
+ { key: 'monthly', label: '۱۲ ماه' },
198
+ { key: 'yearly', label: '۵ سال' }
199
+ ];
200
+ const tabsHtml = periods.map(p =>
201
+ `<button class="chart-tab ${cache.salesPeriod === p.key ? 'active' : ''}" onclick="window.DashboardView._switchPeriod('${p.key}')">${p.label}</button>`
202
+ ).join('');
203
+
204
+ return `
205
+ <div class="card" style="margin:0">
206
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
207
+ <h3 style="font-size:15px;font-weight:700">📈 روند فروش</h3>
208
+ <div class="chart-tabs">${tabsHtml}</div>
209
+ </div>
210
+ ${Chart.line(data, { color: '#0d9488' })}
211
+ </div>
212
+ `;
213
+ }
214
+
215
+ _getSalesChartData() {
216
+ const today = new Date();
217
+ const salesInvoices = cache.invoices.filter(i => i.kind === 'sale' && !i.isPreInvoice);
218
+
219
+ if (cache.salesPeriod === 'daily') {
220
+ // ۱۴ روز اخیر
221
+ const days = [];
222
+ for (let i = 13; i >= 0; i--) {
223
+ const d = new Date(today);
224
+ d.setDate(d.getDate() - i);
225
+ const jDate = Jalali.fromDate(d);
226
+ const label = `${jDate.day}/${jDate.month}`;
227
+ const total = salesInvoices
228
+ .filter(inv => {
229
+ const invDate = this._parseJalali(inv.date);
230
+ if (!invDate) return false;
231
+ return invDate.getFullYear() === d.getFullYear()
232
+ && invDate.getMonth() === d.getMonth()
233
+ && invDate.getDate() === d.getDate();
234
+ })
235
+ .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0);
236
+ days.push({ label, value: total });
237
+ }
238
+ return days;
239
+ }
240
+
241
+ if (cache.salesPeriod === 'monthly') {
242
+ // ۱۲ ماه اخیر
243
+ const months = [];
244
+ for (let i = 11; i >= 0; i--) {
245
+ const d = new Date(today);
246
+ d.setMonth(d.getMonth() - i);
247
+ const y = d.getFullYear();
248
+ const m = d.getMonth();
249
+ const jDate = Jalali.fromDate(d);
250
+ const label = Jalali.monthName(jDate.month);
251
+ const total = salesInvoices
252
+ .filter(inv => {
253
+ const invDate = this._parseJalali(inv.date);
254
+ if (!invDate) return false;
255
+ return invDate.getFullYear() === y && invDate.getMonth() === m;
256
+ })
257
+ .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0);
258
+ months.push({ label, value: total });
259
+ }
260
+ return months;
261
+ }
262
+
263
+ // yearly — ۵ سال اخیر
264
+ const years = [];
265
+ for (let i = 4; i >= 0; i--) {
266
+ const d = new Date(today);
267
+ d.setFullYear(d.getFullYear() - i);
268
+ const y = d.getFullYear();
269
+ const jDate = Jalali.fromDate(d);
270
+ const label = Formatters.toPersianDigits(jDate.year);
271
+ const total = salesInvoices
272
+ .filter(inv => {
273
+ const invDate = this._parseJalali(inv.date);
274
+ return invDate && invDate.getFullYear() === y;
275
+ })
276
+ .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0);
277
+ years.push({ label, value: total });
278
+ }
279
+ return years;
280
+ }
281
+
282
+ _switchPeriod(period) {
283
+ cache.salesPeriod = period;
284
+ const card = document.querySelector('#pageContent .card');
285
+ // رندر مجدد کل صفحه (سادهتر از پیدا کردن دقیق المان)
286
+ this.render().then(html => {
287
+ document.getElementById('pageContent').innerHTML = html;
288
+ });
289
+ }
290
+
291
+ // ============================================================
292
+ // کارت حسابها
293
+ // ============================================================
294
+ _renderAccountsCard() {
295
+ const accounts = cache.treasury.filter(t => t.recordType === 'account');
296
+ if (accounts.length === 0) {
297
+ return `
298
+ <div class="card" style="margin:0">
299
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:12px">🏦 حسابها</h3>
300
+ <div style="text-align:center;padding:30px 10px;color:var(--text-muted);font-size:12.5px">
301
+ هنوز حسابی تعریف نشده
302
+ <div style="margin-top:12px">
303
+ <button class="btn btn-secondary btn-inline" onclick="FINORA.Router.go('treasury')">➕ تعریف حساب</button>
304
+ </div>
305
+ </div>
306
+ </div>
307
+ `;
308
+ }
309
+
310
+ // محاسبه موجودی
311
+ const transactions = cache.treasury.filter(t => t.recordType === 'transaction');
312
+ const balances = {};
313
+ accounts.forEach(a => balances[a.id] = Number(a.initialBalance) || 0);
314
+ transactions.forEach(t => {
315
+ const amt = Number(t.amount) || 0;
316
+ if (t.type === 'receipt' && t.toAccountId && balances[t.toAccountId] !== undefined) balances[t.toAccountId] += amt;
317
+ else if (t.type === 'payment' && t.fromAccountId && balances[t.fromAccountId] !== undefined) balances[t.fromAccountId] -= amt;
318
+ else if (t.type === 'transfer') {
319
+ if (t.fromAccountId && balances[t.fromAccountId] !== undefined) balances[t.fromAccountId] -= amt;
320
+ if (t.toAccountId && balances[t.toAccountId] !== undefined) balances[t.toAccountId] += amt;
321
+ }
322
+ });
323
+
324
+ const typeIcons = { cashbox: '💰', bank: '🏦', pos: '💳' };
325
+
326
+ const cardsHtml = accounts.map(a => {
327
+ const bal = balances[a.id] || 0;
328
+ return `
329
+ <div class="dash-account-card" style="border-right:3px solid ${a.color || '#0d9488'}">
330
+ <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">
331
+ <span style="font-size:16px">${typeIcons[a.type] || '📁'}</span>
332
+ <span style="font-size:12.5px;font-weight:600">${this._esc(a.name)}</span>
333
+ ${a.isDefault ? '<span class="badge badge-success" style="font-size:9px">پیشفرض</span>' : ''}
334
+ </div>
335
+ <div style="font-size:15px;font-weight:800;color:${bal >= 0 ? 'var(--success)' : 'var(--danger)'}">
336
+ ${Formatters.money(bal)}
337
+ </div>
338
+ </div>
339
+ `;
340
+ }).join('');
341
+
342
+ return `
343
+ <div class="card" style="margin:0;display:flex;flex-direction:column">
344
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
345
+ <h3 style="font-size:15px;font-weight:700">🏦 حسابها</h3>
346
+ <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('treasury')">مدیریت</button>
347
+ </div>
348
+ <div style="display:flex;flex-direction:column;gap:8px;overflow-y:auto;max-height:280px">
349
+ ${cardsHtml}
350
+ </div>
351
+ </div>
352
+ `;
353
+ }
354
+
355
+ // ============================================================
356
+ // نمودار درآمد و هزینه
357
+ // ============================================================
358
+ _renderIncomeExpenseChart() {
359
+ const today = new Date();
360
+ const data = [];
361
+ for (let i = 5; i >= 0; i--) {
362
+ const d = new Date(today);
363
+ d.setMonth(d.getMonth() - i);
364
+ const y = d.getFullYear();
365
+ const m = d.getMonth();
366
+ const jDate = Jalali.fromDate(d);
367
+ const label = Jalali.monthName(jDate.month);
368
+
369
+ const monthExp = cache.expenses.filter(e => {
370
+ const ed = this._parseJalali(e.date);
371
+ if (!ed) return false;
372
+ return ed.getFullYear() === y && ed.getMonth() === m;
373
+ });
374
+
375
+ const income = monthExp.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0);
376
+ const expense = monthExp.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0);
377
+
378
+ data.push({ label, income, expense });
379
+ }
380
+
381
+ return `
382
+ <div class="card">
383
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📊 درآمد و هزینه ۶ ماه اخیر</h3>
384
+ ${Chart.bars(data)}
385
+ </div>
386
+ `;
387
+ }
388
+
389
+ // ============================================================
390
+ // آخرین فاکتورها
391
+ // ============================================================
392
+ _renderRecentInvoices() {
393
+ const recent = [...cache.invoices]
394
+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''))
395
+ .slice(0, 5);
396
+
397
+ if (recent.length === 0) {
398
+ return `
399
+ <div class="card">
400
+ <h3 style="font-size:15px;font-weight:700;margin-bottom:12px">🧾 آخرین فاکتورها</h3>
401
+ <div style="text-align:center;padding:30px 10px;color:var(--text-muted);font-size:12.5px">
402
+ هنوز فاکتوری صادر نشده
403
+ <div style="margin-top:12px">
404
+ <button class="btn btn-secondary btn-inline" onclick="FINORA.Router.go('invoices')">➕ فاکتور جدید</button>
405
+ </div>
406
+ </div>
407
+ </div>
408
+ `;
409
+ }
410
+
411
+ const rows = recent.map(inv => {
412
+ const kindLabels = {
413
+ sale: { label: 'فروش', cls: 'badge-success' },
414
+ purchase: { label: 'خرید', cls: 'badge-warning' },
415
+ sale_return: { label: 'برگشت فروش', cls: 'badge-danger' },
416
+ purchase_return: { label: 'برگشت خرید', cls: 'badge-danger' },
417
+ non_formal: { label: 'غیررسمی', cls: 'badge-muted' }
418
+ };
419
+ const k = kindLabels[inv.kind] || { label: inv.kind, cls: 'badge-muted' };
420
+
421
+ return `
422
+ <tr>
423
+ <td>
424
+ <strong>#${Formatters.toPersianDigits(inv.number || '—')}</strong>
425
+ ${inv.isPreInvoice ? ' <span class="badge badge-warning" style="font-size:9px">پیش</span>' : ''}
426
+ </td>
427
+ <td><span class="badge ${k.cls}">${k.label}</span></td>
428
+ <td>${this._esc(inv.contactName || '—')}</td>
429
+ <td>${Formatters.toPersianDigits(inv.date || '—')}</td>
430
+ <td style="font-weight:700">${Formatters.money(inv.grandTotal || 0)}</td>
431
+ <td>
432
+ <button class="icon-btn-sm" title="چاپ" onclick="window.DashboardView._printInvoice('${inv.id}')">🖨️</button>
433
+ </td>
434
+ </tr>
435
+ `;
436
+ }).join('');
437
+
438
+ return `
439
+ <div class="card">
440
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
441
+ <h3 style="font-size:15px;font-weight:700">🧾 آخرین فاکتورها</h3>
442
+ <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('invoices')">همه</button>
443
+ </div>
444
+ <div class="table-wrap">
445
+ <table>
446
+ <thead>
447
+ <tr>
448
+ <th>شماره</th>
449
+ <th style="width:100px">نوع</th>
450
+ <th>خریدار</th>
451
+ <th style="width:100px">تاریخ</th>
452
+ <th style="width:140px">مبلغ کل</th>
453
+ <th style="width:60px">عملیات</th>
454
+ </tr>
455
+ </thead>
456
+ <tbody>${rows}</tbody>
457
+ </table>
458
+ </div>
459
+ </div>
460
+ `;
461
+ }
462
+
463
+ // ============================================================
464
+ // چکهای سررسید
465
+ // ============================================================
466
+ _renderUpcomingCheques() {
467
+ const today = new Date();
468
+ const upcoming = cache.cheques
469
+ .filter(c => {
470
+ if (c.status !== 'pending') return false;
471
+ const due = this._parseJalali(c.dueDate);
472
+ if (!due) return false;
473
+ const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
474
+ return diff >= -30 && diff <= 30;
475
+ })
476
+ .sort((a, b) => (a.dueDate || '').localeCompare(b.dueDate || ''))
477
+ .slice(0, 8);
478
+
479
+ if (upcoming.length === 0) {
480
+ return '';
481
+ }
482
+
483
+ const rows = upcoming.map(c => {
484
+ const due = this._parseJalali(c.dueDate);
485
+ const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
486
+ let statusBadge = '';
487
+ if (diff < 0) statusBadge = `<span class="badge badge-danger" style="font-size:9.5px">${Formatters.toPersianDigits(Math.abs(diff))} روز گذشته</span>`;
488
+ else if (diff === 0) statusBadge = `<span class="badge badge-danger" style="font-size:9.5px">امروز</span>`;
489
+ else if (diff <= 7) statusBadge = `<span class="badge badge-warning" style="font-size:9.5px">${Formatters.toPersianDigits(diff)} روز مانده</span>`;
490
+ else statusBadge = `<span class="badge badge-muted" style="font-size:9.5px">${Formatters.toPersianDigits(diff)} روز</span>`;
491
+
492
+ return `
493
+ <tr>
494
+ <td><span class="badge ${c.direction === 'inbound' ? 'badge-success' : 'badge-danger'}">${c.direction === 'inbound' ? '📥 دریافتی' : '📤 پرداختی'}</span></td>
495
+ <td>${this._esc(c.contactName || '—')}</td>
496
+ <td>${this._esc(c.bankName || '—')}</td>
497
+ <td>${Formatters.toPersianDigits(c.dueDate || '—')}</td>
498
+ <td style="font-weight:700">${Formatters.money(c.amount || 0)}</td>
499
+ <td>${statusBadge}</td>
500
+ </tr>
501
+ `;
502
+ }).join('');
503
+
504
+ return `
505
+ <div class="card">
506
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
507
+ <h3 style="font-size:15px;font-weight:700">💳 چکهای نزدیک سررسید</h3>
508
+ <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('cheques')">مدیریت</button>
509
+ </div>
510
+ <div class="table-wrap">
511
+ <table>
512
+ <thead>
513
+ <tr>
514
+ <th style="width:110px">نوع</th>
515
+ <th>طرف حساب</th>
516
+ <th style="width:110px">بانک</th>
517
+ <th style="width:110px">سررسید</th>
518
+ <th style="width:140px">مبلغ</th>
519
+ <th style="width:130px">وضعیت</th>
520
+ </tr>
521
+ </thead>
522
+ <tbody>${rows}</tbody>
523
+ </table>
524
+ </div>
525
+ </div>
526
+ `;
527
+ }
528
+
529
+ // ============================================================
530
+ // Helpers
531
+ // ============================================================
532
+ async _printInvoice(invoiceId) {
533
+ const { InvoicePrint } = await import('../utils/InvoicePrint.js');
534
+ InvoicePrint.openSettings(invoiceId);
535
+ }
536
+
537
+ _parseJalali(str) {
538
+ if (!str) return null;
539
+ const parts = String(str).split('/').map(Number);
540
+ if (parts.length !== 3) return null;
541
+ const [jy, jm, jd] = parts;
542
+ if (!jy || !jm || !jd) return null;
543
+ let gy = (jy <= 979) ? 621 : 1600;
544
+ let jy2 = jy - (jy <= 979 ? 0 : 979);
545
+ 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);
546
+ gy += 400 * Math.floor(days / 146097);
547
+ days %= 146097;
548
+ if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
549
+ gy += 4 * Math.floor(days / 1461);
550
+ days %= 1461;
551
+ if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
552
+ let gd = days + 1;
553
+ 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];
554
+ let gm = 0;
555
+ for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
556
+ return new Date(gy, gm - 1, gd);
557
+ }
558
+
559
+ _esc(s) {
560
+ if (!s) return '';
561
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
562
+ }
563
+}
564
+
565
+export const DashboardView = new DashboardViewImpl();
566
+window.DashboardView = DashboardView;
\ No newline at end of file
src/views/ExpensesView.js
new
+362
@@ -0,0 +1,362 @@
1
+// ============================================================
2
+// ExpensesView — صفحهی هزینهها و درآمدهای متفرقه
3
+// ============================================================
4
+
5
+import { ExpenseController } from '../controllers/ExpenseController.js';
6
+import { Modal } from '../core/Modal.js';
7
+import { Toast } from '../core/Toast.js';
8
+import { Formatters } from '../utils/Formatters.js';
9
+import { NumberInput } from '../utils/NumberInput.js';
10
+import { Jalali } from '../utils/Jalali.js';
11
+
12
+let filter = { search: '', kind: '', category: '', dateFrom: '', dateTo: '' };
13
+let cache = { items: [], categories: [], stats: {} };
14
+
15
+class ExpensesViewImpl {
16
+ async render() {
17
+ await this.reload();
18
+ return `
19
+ <div class="page-title">
20
+ <h2>هزینهها و درآمدها</h2>
21
+ <p>ثبت و مدیریت هزینهها، درآمدهای متفرقه و تراز مالی</p>
22
+ </div>
23
+
24
+ <div class="grid-kpi">
25
+ <div class="card" style="margin:0">
26
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل درآمدها</div>
27
+ <div style="font-size:20px;font-weight:800;color:var(--success)">${Formatters.money(cache.stats.totalIncome || 0)}</div>
28
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.items.filter(i => i.kind === 'income').length)} سند</div>
29
+ </div>
30
+ <div class="card" style="margin:0">
31
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل هزینهها</div>
32
+ <div style="font-size:20px;font-weight:800;color:var(--danger)">${Formatters.money(cache.stats.totalExpense || 0)}</div>
33
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.items.filter(i => i.kind === 'expense').length)} سند</div>
34
+ </div>
35
+ <div class="card" style="margin:0">
36
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">تراز (درآمد - هزینه)</div>
37
+ <div style="font-size:20px;font-weight:800;color:${(cache.stats.balance || 0) >= 0 ? 'var(--primary)' : 'var(--danger)'}">${Formatters.money(cache.stats.balance || 0)}</div>
38
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${(cache.stats.balance || 0) >= 0 ? 'مثبت' : 'منفی'}</div>
39
+ </div>
40
+ <div class="card" style="margin:0">
41
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">تعداد اسناد</div>
42
+ <div style="font-size:20px;font-weight:800;color:var(--info)">${Formatters.number(cache.stats.count || 0)}</div>
43
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">در فیلتر فعلی</div>
44
+ </div>
45
+ </div>
46
+
47
+ <div id="expenses-content">${this.renderContent()}</div>
48
+ `;
49
+ }
50
+
51
+ onMount() {
52
+ window.ExpensesView = this;
53
+ }
54
+
55
+ async reload() {
56
+ cache.items = await ExpenseController.getAll(filter);
57
+ cache.categories = await ExpenseController.getCategories();
58
+ cache.stats = await ExpenseController.getStats(filter);
59
+ }
60
+
61
+ renderContent() {
62
+ const rows = cache.items.length === 0
63
+ ? `<tr><td colspan="7"><div class="empty-state"><div class="icon">💰</div><h3>هیچ سندی ثبت نشده</h3><p>اولین هزینه یا درآمد خود را ثبت کنید</p><button class="btn" onclick="window.ExpensesView.openExpenseModal()">➕ سند جدید</button></div></td></tr>`
64
+ : cache.items.map(e => {
65
+ const isIncome = e.kind === 'income';
66
+ return `
67
+ <tr>
68
+ <td>
69
+ <span class="badge ${isIncome ? 'badge-success' : 'badge-danger'}">
70
+ ${isIncome ? '📥 درآمد' : '📤 هزینه'}
71
+ </span>
72
+ </td>
73
+ <td>${Formatters.toPersianDigits(e.date || '—')}</td>
74
+ <td><strong>${this._esc(e.category || '—')}</strong></td>
75
+ <td>${this._esc(e.description || '—')}</td>
76
+ <td>${ExpenseController.getMethodLabel(e.method)}</td>
77
+ <td>${e.refNumber ? Formatters.toPersianDigits(e.refNumber) : '—'}</td>
78
+ <td style="font-weight:700;color:${isIncome ? 'var(--success)' : 'var(--danger)'}">
79
+ ${isIncome ? '+' : '-'}${Formatters.money(e.amount)}
80
+ </td>
81
+ <td>
82
+ <div class="row-actions">
83
+ <button class="icon-btn-sm" title="ویرایش" onclick="window.ExpensesView.editExpense('${e.id}')">✏️</button>
84
+ <button class="icon-btn-sm danger" title="حذف" onclick="window.ExpensesView.deleteExpense('${e.id}')">🗑️</button>
85
+ </div>
86
+ </td>
87
+ </tr>
88
+ `;
89
+ }).join('');
90
+
91
+ const categoryOptions = cache.categories.map(c =>
92
+ `<option value="${c}" ${filter.category === c ? 'selected' : ''}>${this._esc(c)}</option>`
93
+ ).join('');
94
+
95
+ return `
96
+ <div class="toolbar">
97
+ <div class="search-input-wrap">
98
+ <span class="icon">🔍</span>
99
+ <input type="text" class="form-control" id="expSearch" placeholder="جستجو در سرفصل، شرح یا شماره پیگیری..." value="${this._esc(filter.search)}" oninput="window.ExpensesView._onSearch(this.value)" />
100
+ </div>
101
+ <select class="form-control" style="width:auto;min-width:130px" onchange="window.ExpensesView._onFilter('kind', this.value)">
102
+ <option value="">همه انواع</option>
103
+ <option value="expense" ${filter.kind === 'expense' ? 'selected' : ''}>هزینه</option>
104
+ <option value="income" ${filter.kind === 'income' ? 'selected' : ''}>درآمد</option>
105
+ </select>
106
+ <select class="form-control" style="width:auto;min-width:150px" onchange="window.ExpensesView._onFilter('category', this.value)">
107
+ <option value="">همه سرفصلها</option>
108
+ ${categoryOptions}
109
+ </select>
110
+ <input type="text" class="form-control" style="width:130px" placeholder="از تاریخ" value="${this._esc(filter.dateFrom)}" onchange="window.ExpensesView._onFilter('dateFrom', this.value)" />
111
+ <input type="text" class="form-control" style="width:130px" placeholder="تا تاریخ" value="${this._esc(filter.dateTo)}" onchange="window.ExpensesView._onFilter('dateTo', this.value)" />
112
+ <button class="btn btn-secondary btn-inline" onclick="window.ExpensesView._clearFilters()">↺ پاک کردن فیلتر</button>
113
+ <button class="btn" onclick="window.ExpensesView.openExpenseModal()">➕ سند جدید</button>
114
+ </div>
115
+
116
+ <div class="table-wrap">
117
+ <table>
118
+ <thead>
119
+ <tr>
120
+ <th style="width:110px">نوع</th>
121
+ <th style="width:110px">تاریخ</th>
122
+ <th style="width:150px">سرفصل</th>
123
+ <th>شرح</th>
124
+ <th style="width:110px">روش</th>
125
+ <th style="width:120px">شماره پیگیری</th>
126
+ <th style="width:140px">مبلغ</th>
127
+ <th style="width:100px">عملیات</th>
128
+ </tr>
129
+ </thead>
130
+ <tbody>${rows}</tbody>
131
+ </table>
132
+ </div>
133
+ `;
134
+ }
135
+
136
+ _onSearch(val) {
137
+ filter.search = val;
138
+ this.reload().then(() => {
139
+ document.getElementById('expenses-content').innerHTML = this.renderContent();
140
+ const input = document.getElementById('expSearch');
141
+ if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
142
+ });
143
+ }
144
+
145
+ _onFilter(key, val) {
146
+ filter[key] = val;
147
+ this.reloadAndRender();
148
+ }
149
+
150
+ _clearFilters() {
151
+ filter = { search: '', kind: '', category: '', dateFrom: '', dateTo: '' };
152
+ this.reloadAndRender();
153
+ Toast.info('فیلترها پاک شد');
154
+ }
155
+
156
+ async reloadAndRender() {
157
+ await this.reload();
158
+ document.getElementById('expenses-content').innerHTML = this.renderContent();
159
+ // KPI ها را هم رفرش کن
160
+ const kpi = document.querySelector('.grid-kpi');
161
+ if (kpi) {
162
+ const stats = cache.stats;
163
+ kpi.children[0].querySelector('div:nth-child(2)').textContent = Formatters.money(stats.totalIncome || 0);
164
+ kpi.children[0].querySelector('div:nth-child(3)').textContent = Formatters.toPersianDigits(cache.items.filter(i => i.kind === 'income').length) + ' سند';
165
+ kpi.children[1].querySelector('div:nth-child(2)').textContent = Formatters.money(stats.totalExpense || 0);
166
+ kpi.children[1].querySelector('div:nth-child(3)').textContent = Formatters.toPersianDigits(cache.items.filter(i => i.kind === 'expense').length) + ' سند';
167
+ const bal = stats.balance || 0;
168
+ const balEl = kpi.children[2].querySelector('div:nth-child(2)');
169
+ balEl.textContent = Formatters.money(bal);
170
+ balEl.style.color = bal >= 0 ? 'var(--primary)' : 'var(--danger)';
171
+ kpi.children[2].querySelector('div:nth-child(3)').textContent = bal >= 0 ? 'مثبت' : 'منفی';
172
+ kpi.children[3].querySelector('div:nth-child(2)').textContent = Formatters.toPersianDigits(stats.count || 0);
173
+ }
174
+ }
175
+
176
+ // ============================================================
177
+ // فرم ثبت/ویرایش
178
+ // ============================================================
179
+ async openExpenseModal(expenseId = null) {
180
+ const isEdit = !!expenseId;
181
+ const d = isEdit ? await ExpenseController.get(expenseId) : {
182
+ kind: 'expense',
183
+ category: '',
184
+ amount: 0,
185
+ date: Jalali.today(),
186
+ method: 'cash',
187
+ description: '',
188
+ refNumber: ''
189
+ };
190
+
191
+ const categoriesForKind = await ExpenseController.getCategories(d.kind);
192
+
193
+ const body = `
194
+ <div class="form-group">
195
+ <label class="form-label">نوع سند <span class="req">*</span></label>
196
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
197
+ <label class="print-tpl-card ${d.kind === 'expense' ? 'active' : ''}" data-kind="expense" style="padding:12px 8px">
198
+ <input type="radio" name="expKind" value="expense" ${d.kind === 'expense' ? 'checked' : ''} style="display:none" />
199
+ <div style="font-size:22px">📤</div>
200
+ <div style="font-weight:700;font-size:13px;margin-top:4px">هزینه</div>
201
+ </label>
202
+ <label class="print-tpl-card ${d.kind === 'income' ? 'active' : ''}" data-kind="income" style="padding:12px 8px">
203
+ <input type="radio" name="expKind" value="income" ${d.kind === 'income' ? 'checked' : ''} style="display:none" />
204
+ <div style="font-size:22px">📥</div>
205
+ <div style="font-weight:700;font-size:13px;margin-top:4px">درآمد</div>
206
+ </label>
207
+ </div>
208
+ </div>
209
+
210
+ <div class="form-row">
211
+ <div class="form-group">
212
+ <label class="form-label">سرفصل <span class="req">*</span></label>
213
+ <div style="display:flex;gap:6px">
214
+ <select class="form-control" id="expCategory" style="flex:1">
215
+ ${categoriesForKind.map(c => `<option value="${this._esc(c)}" ${d.category === c ? 'selected' : ''}>${this._esc(c)}</option>`).join('')}
216
+ </select>
217
+ <button class="btn btn-secondary btn-inline" style="padding:0 12px" onclick="window.ExpensesView._promptNewCategory()" title="سرفصل جدید">➕</button>
218
+ </div>
219
+ </div>
220
+ <div class="form-group">
221
+ <label class="form-label">تاریخ <span class="req">*</span></label>
222
+ <input type="text" class="form-control" id="expDate" value="${this._esc(d.date)}" placeholder="1405/06/27" />
223
+ </div>
224
+ </div>
225
+
226
+ <div class="form-row">
227
+ <div class="form-group">
228
+ <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
229
+ <input type="text" inputmode="numeric" class="form-control" id="expAmount" value="${NumberInput.format(d.amount || 0)}" />
230
+ </div>
231
+ <div class="form-group">
232
+ <label class="form-label">روش پرداخت / دریافت</label>
233
+ <select class="form-control" id="expMethod">
234
+ <option value="cash" ${d.method === 'cash' ? 'selected' : ''}>نقدی</option>
235
+ <option value="card" ${d.method === 'card' ? 'selected' : ''}>کارت</option>
236
+ <option value="cheque" ${d.method === 'cheque' ? 'selected' : ''}>چک</option>
237
+ <option value="transfer" ${d.method === 'transfer' ? 'selected' : ''}>انتقال بانکی</option>
238
+ </select>
239
+ </div>
240
+ </div>
241
+
242
+ <div class="form-group">
243
+ <label class="form-label">شماره پیگیری / سند (اختیاری)</label>
244
+ <input type="text" class="form-control" id="expRef" value="${this._esc(d.refNumber)}" placeholder="مثلاً 12345" />
245
+ </div>
246
+
247
+ <div class="form-group">
248
+ <label class="form-label">شرح</label>
249
+ <textarea class="form-control" id="expDesc" rows="2" placeholder="توضیحات اضافی...">${this._esc(d.description)}</textarea>
250
+ </div>
251
+ `;
252
+
253
+ const footer = `
254
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
255
+ <button class="btn" onclick="window.ExpensesView.saveExpense(${isEdit ? `'${expenseId}'` : 'null'})">💾 ذخیره</button>
256
+ `;
257
+
258
+ Modal.open({ title: isEdit ? 'ویرایش سند' : 'سند جدید', body, footer, size: 'md' });
259
+
260
+ setTimeout(() => {
261
+ // انتخاب نوع
262
+ document.querySelectorAll('[data-kind]').forEach(card => {
263
+ card.addEventListener('click', async () => {
264
+ document.querySelectorAll('[data-kind]').forEach(c => c.classList.remove('active'));
265
+ card.classList.add('active');
266
+ card.querySelector('input').checked = true;
267
+
268
+ // آپدیت dropdown سرفصلها
269
+ const kind = card.getAttribute('data-kind');
270
+ const cats = await ExpenseController.getCategories(kind);
271
+ const select = document.getElementById('expCategory');
272
+ if (select) {
273
+ select.innerHTML = cats.map(c => `<option value="${this._esc(c)}">${this._esc(c)}</option>`).join('');
274
+ }
275
+ });
276
+ });
277
+ }, 50);
278
+ }
279
+
280
+ async _promptNewCategory() {
281
+ const catName = prompt('نام سرفصل جدید:');
282
+ if (!catName || !catName.trim()) return;
283
+ const select = document.getElementById('expCategory');
284
+ if (select) {
285
+ const trimmed = catName.trim();
286
+ const exists = Array.from(select.options).some(o => o.value === trimmed);
287
+ if (exists) {
288
+ select.value = trimmed;
289
+ Toast.info('این سرفصل از قبل وجود داشت');
290
+ return;
291
+ }
292
+ const opt = document.createElement('option');
293
+ opt.value = trimmed;
294
+ opt.textContent = trimmed;
295
+ select.appendChild(opt);
296
+ select.value = trimmed;
297
+ Toast.success('سرفصل اضافه شد');
298
+ }
299
+ }
300
+
301
+ async saveExpense(id) {
302
+ const kind = document.querySelector('input[name="expKind"]:checked')?.value || 'expense';
303
+ const category = document.getElementById('expCategory').value;
304
+ const date = document.getElementById('expDate').value.trim();
305
+ const amount = NumberInput.parse(document.getElementById('expAmount').value);
306
+ const method = document.getElementById('expMethod').value;
307
+ const refNumber = document.getElementById('expRef').value;
308
+ const description = document.getElementById('expDesc').value;
309
+
310
+ if (!category) { Toast.warning('سرفصل را انتخاب کنید'); return; }
311
+ if (!date) { Toast.warning('تاریخ الزامی است'); return; }
312
+ if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
313
+
314
+ const data = { kind, category, date, amount, method, refNumber, description };
315
+
316
+ try {
317
+ if (id) {
318
+ await ExpenseController.update(id, data);
319
+ Toast.success('سند ویرایش شد');
320
+ } else {
321
+ await ExpenseController.create(data);
322
+ Toast.success(kind === 'income' ? 'درآمد ثبت شد' : 'هزینه ثبت شد');
323
+ }
324
+ Modal.close();
325
+ await this.reloadAndRender();
326
+ } catch (err) {
327
+ console.error(err);
328
+ Toast.error('خطا: ' + err.message);
329
+ }
330
+ }
331
+
332
+ async editExpense(id) {
333
+ await this.openExpenseModal(id);
334
+ }
335
+
336
+ async deleteExpense(id) {
337
+ const e = cache.items.find(x => x.id === id);
338
+ Modal.confirm({
339
+ title: 'حذف سند',
340
+ message: `آیا از حذف «${this._esc(e?.category || '')} - ${Formatters.money(e?.amount || 0)}» مطمئن هستید؟`,
341
+ confirmText: 'حذف',
342
+ danger: true,
343
+ onConfirm: async () => {
344
+ try {
345
+ await ExpenseController.delete(id);
346
+ Toast.success('سند حذف شد');
347
+ await this.reloadAndRender();
348
+ } catch (err) {
349
+ Toast.error('خطا: ' + err.message);
350
+ }
351
+ }
352
+ });
353
+ }
354
+
355
+ _esc(s) {
356
+ if (!s) return '';
357
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
358
+ }
359
+}
360
+
361
+export const ExpensesView = new ExpensesViewImpl();
362
+window.ExpensesView = ExpensesView;
\ No newline at end of file