فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Phase 4: Invoices module (form, list, print with 3 templates)
Davood Mehraban committed
Sep 18, 2026 at 07:32 UTC
9eba8baa080679e2f5e41c658a8359a8ee238da8
6 files changed
+1791
-1
src/controllers/InvoiceController.js
new
+282
@@ -0,0 +1,282 @@
1
+// ============================================================
2
+// InvoiceController — منطق کامل فاکتور
3
+// ============================================================
4
+
5
+import { StorageService } from '../core/StorageService.js';
6
+import { Auth } from '../core/Auth.js';
7
+import { ProductController } from './ProductController.js';
8
+
9
+class InvoiceControllerImpl {
10
+ // شمارهی بعدی سریال (بر اساس نوع سند)
11
+ async getNextNumber(kind = 'sale') {
12
+ const user = Auth.current();
13
+ const all = await StorageService.getByOwner('invoices', user.id);
14
+ const kindInvoices = all.filter(i => i.kind === kind && !i.isPreInvoice);
15
+ if (kindInvoices.length === 0) return 1;
16
+ const maxNum = Math.max(...kindInvoices.map(i => Number(i.number) || 0));
17
+ return maxNum + 1;
18
+ }
19
+
20
+ // ذخیرهی فاکتور (ایجاد یا ویرایش)
21
+ async save(data, id = null) {
22
+ const user = Auth.current();
23
+ const items = (data.items || []).map(it => {
24
+ const qty = Number(it.qty) || 0;
25
+ const price = Number(it.price) || 0;
26
+ const lineSubtotal = qty * price;
27
+ let lineDiscount = 0;
28
+ const discInput = Number(it.discount) || 0;
29
+ if (it.discountType === 'percent') {
30
+ lineDiscount = Math.round(lineSubtotal * discInput / 100);
31
+ } else {
32
+ lineDiscount = discInput;
33
+ }
34
+ lineDiscount = Math.max(0, Math.min(lineDiscount, lineSubtotal));
35
+ const lineTotal = lineSubtotal - lineDiscount;
36
+ return {
37
+ productId: it.productId || null,
38
+ productName: it.productName || '',
39
+ unit: it.unit || 'عدد',
40
+ qty,
41
+ price,
42
+ discount: lineDiscount,
43
+ discountInput: discInput,
44
+ discountType: it.discountType || 'fixed',
45
+ lineSubtotal,
46
+ lineTotal
47
+ };
48
+ });
49
+
50
+ const subtotal = items.reduce((s, it) => s + it.lineTotal, 0);
51
+
52
+ // تخفیف کلی
53
+ let totalDiscount = 0;
54
+ const discInput = Number(data.discountInput) || 0;
55
+ if (data.discountType === 'percent') {
56
+ totalDiscount = Math.round(subtotal * discInput / 100);
57
+ } else {
58
+ totalDiscount = discInput;
59
+ }
60
+ totalDiscount = Math.max(0, Math.min(totalDiscount, subtotal));
61
+
62
+ const afterDiscount = Math.max(0, subtotal - totalDiscount);
63
+
64
+ // مالیات
65
+ let vatAmount = 0;
66
+ if (data.vatEnabled && data.kind !== 'non_formal') {
67
+ const rate = Number(data.vatRate) || 0;
68
+ vatAmount = Math.round(afterDiscount * rate / 100);
69
+ }
70
+ const grandTotal = afterDiscount + vatAmount;
71
+
72
+ // پرداخت
73
+ const paidAmount = Math.max(0, Math.min(Number(data.paidAmount) || 0, grandTotal));
74
+ const remaining = Math.max(0, grandTotal - paidAmount);
75
+
76
+ const baseData = {
77
+ ownerUserId: user.id,
78
+ kind: data.kind || 'sale',
79
+ isPreInvoice: !!data.isPreInvoice,
80
+ date: data.date || this._todayJalali(),
81
+ contactId: data.contactId || null,
82
+ contactName: data.contactName || '',
83
+ items,
84
+ subtotal,
85
+ totalDiscount,
86
+ discountType: data.discountType || 'fixed',
87
+ discountInput: discInput,
88
+ vatEnabled: !!data.vatEnabled,
89
+ vatRate: Number(data.vatRate) || 0,
90
+ vatAmount,
91
+ grandTotal,
92
+ paymentMethod: data.paymentMethod || 'cash',
93
+ paidAmount,
94
+ remaining,
95
+ description: (data.description || '').trim(),
96
+ status: remaining === 0 ? 'paid' : (paidAmount > 0 ? 'partial' : 'unpaid')
97
+ };
98
+
99
+ let saved;
100
+ if (id) {
101
+ const existing = await StorageService.get('invoices', id);
102
+ if (!existing) throw new Error('فاکتور یافت نشد');
103
+ saved = { ...existing, ...baseData };
104
+ await StorageService.put('invoices', saved);
105
+ } else {
106
+ const number = await this.getNextNumber(baseData.kind);
107
+ saved = {
108
+ id: StorageService.uid('inv_'),
109
+ clientUuid: this._uuid(),
110
+ number,
111
+ ...baseData
112
+ };
113
+ await StorageService.put('invoices', saved);
114
+ }
115
+
116
+ // بازنویسی حرکات انبار
117
+ await this._rebuildStockMovements(saved);
118
+ return saved;
119
+ }
120
+
121
+ // ثبت حرکات انبار بر اساس نوع سند
122
+ async _rebuildStockMovements(invoice) {
123
+ const user = Auth.current();
124
+ const all = await StorageService.getByOwner('stock_movements', user.id);
125
+
126
+ // حذف حرکات قبلی این فاکتور
127
+ for (const m of all.filter(x => x.refId === invoice.id)) {
128
+ await StorageService.delete('stock_movements', m.id);
129
+ }
130
+
131
+ // تعیین جهت
132
+ const inKinds = ['purchase', 'sale_return']; // ورود به انبار
133
+ const outKinds = ['sale', 'purchase_return']; // خروج از انبار
134
+ const direction = inKinds.includes(invoice.kind) ? 'in' :
135
+ outKinds.includes(invoice.kind) ? 'out' : 'out';
136
+
137
+ // اگه پیشفاکتوره، حرکات ثبت نمیشه
138
+ if (invoice.isPreInvoice) return;
139
+
140
+ for (const item of invoice.items) {
141
+ if (!item.productId) continue;
142
+ const product = await StorageService.get('products', item.productId);
143
+ if (!product || product.trackInventory === false) continue;
144
+
145
+ const mv = {
146
+ id: StorageService.uid('mv_'),
147
+ ownerUserId: user.id,
148
+ productId: item.productId,
149
+ type: direction,
150
+ qty: Number(item.qty) || 0,
151
+ refType: 'invoice',
152
+ refId: invoice.id,
153
+ note: `فاکتور #${invoice.number}`,
154
+ date: new Date().toISOString()
155
+ };
156
+ await StorageService.put('stock_movements', mv);
157
+ }
158
+ }
159
+
160
+ async getAll(filter = {}) {
161
+ const user = Auth.current();
162
+ let list = await StorageService.getByOwner('invoices', user.id);
163
+
164
+ if (filter.kind) list = list.filter(i => i.kind === filter.kind);
165
+ if (filter.preInvoice !== undefined && filter.preInvoice !== '') {
166
+ list = list.filter(i => !!i.isPreInvoice === filter.preInvoice);
167
+ }
168
+ if (filter.contactId) list = list.filter(i => i.contactId === filter.contactId);
169
+ if (filter.paymentStatus) {
170
+ list = list.filter(i => i.status === filter.paymentStatus);
171
+ }
172
+ if (filter.search) {
173
+ const q = String(filter.search).toLowerCase();
174
+ list = list.filter(i =>
175
+ String(i.number || '').includes(q) ||
176
+ (i.contactName || '').toLowerCase().includes(q) ||
177
+ (i.description || '').toLowerCase().includes(q)
178
+ );
179
+ }
180
+ if (filter.dateFrom) list = list.filter(i => (i.date || '') >= filter.dateFrom);
181
+ if (filter.dateTo) list = list.filter(i => (i.date || '') <= filter.dateTo);
182
+
183
+ return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
184
+ }
185
+
186
+ async get(id) {
187
+ return await StorageService.get('invoices', id);
188
+ }
189
+
190
+ async delete(id) {
191
+ const user = Auth.current();
192
+ const movements = await StorageService.getByOwner('stock_movements', user.id);
193
+ for (const m of movements.filter(x => x.refId === id)) {
194
+ await StorageService.delete('stock_movements', m.id);
195
+ }
196
+ return await StorageService.delete('invoices', id);
197
+ }
198
+
199
+ // تبدیل پیشفاکتور به فاکتور
200
+ async convertPreInvoice(id) {
201
+ const inv = await StorageService.get('invoices', id);
202
+ if (!inv) throw new Error('پیشفاکتور یافت نشد');
203
+ const number = await this.getNextNumber(inv.kind);
204
+ inv.isPreInvoice = false;
205
+ inv.number = number;
206
+ await StorageService.put('invoices', inv);
207
+ await this._rebuildStockMovements(inv);
208
+ return inv;
209
+ }
210
+
211
+ // علامتگذاری بهعنوان پرداختشده
212
+ async markPaid(id, amount = null) {
213
+ const inv = await StorageService.get('invoices', id);
214
+ if (!inv) throw new Error('فاکتور یافت نشد');
215
+ const pay = amount === null ? inv.grandTotal : Number(amount);
216
+ inv.paidAmount = (Number(inv.paidAmount) || 0) + pay;
217
+ inv.paidAmount = Math.min(inv.paidAmount, inv.grandTotal);
218
+ inv.remaining = Math.max(0, inv.grandTotal - inv.paidAmount);
219
+ inv.status = inv.remaining === 0 ? 'paid' : (inv.paidAmount > 0 ? 'partial' : 'unpaid');
220
+ return await StorageService.put('invoices', inv);
221
+ }
222
+
223
+ // آمار برای داشبورد
224
+ async getStats() {
225
+ const user = Auth.current();
226
+ const all = await StorageService.getByOwner('invoices', user.id);
227
+ const salesInvoices = all.filter(i => i.kind === 'sale' && !i.isPreInvoice);
228
+
229
+ const totalSales = salesInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
230
+ const totalPaid = salesInvoices.reduce((s, i) => s + (Number(i.paidAmount) || 0), 0);
231
+ const totalRemaining = salesInvoices.reduce((s, i) => s + (Number(i.remaining) || 0), 0);
232
+
233
+ return {
234
+ count: all.length,
235
+ salesCount: salesInvoices.length,
236
+ totalSales,
237
+ totalPaid,
238
+ totalRemaining,
239
+ preInvoiceCount: all.filter(i => i.isPreInvoice).length
240
+ };
241
+ }
242
+
243
+ // لیبل نوع سند
244
+ getKindLabel(kind) {
245
+ const labels = {
246
+ sale: 'فاکتور فروش',
247
+ purchase: 'فاکتور خرید',
248
+ sale_return: 'برگشت از فروش',
249
+ purchase_return: 'برگشت از خرید',
250
+ non_formal: 'غیررسمی'
251
+ };
252
+ return labels[kind] || kind;
253
+ }
254
+
255
+ _todayJalali() {
256
+ const d = new Date();
257
+ const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
258
+ const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
259
+ let jy = (gy <= 1600) ? 0 : 979;
260
+ let gy2 = gy - (gy <= 1600 ? 621 : 1600);
261
+ const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
262
+ let days = (365 * gy2) + Math.floor((gyAdj + 3) / 4) - Math.floor((gyAdj + 99) / 100) + Math.floor((gyAdj + 399) / 400) - 80 + gd + g_d_m[gm - 1];
263
+ jy += 33 * Math.floor(days / 12053);
264
+ days %= 12053;
265
+ jy += 4 * Math.floor(days / 1461);
266
+ days %= 1461;
267
+ if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
268
+ const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
269
+ const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
270
+ return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
271
+ }
272
+
273
+ _uuid() {
274
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
275
+ const r = Math.random() * 16 | 0;
276
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
277
+ return v.toString(16);
278
+ });
279
+ }
280
+}
281
+
282
+export const InvoiceController = new InvoiceControllerImpl();
\ No newline at end of file
src/main.js
+6
-1
@@ -2,6 +2,7 @@
2
// Finora Pro — Main Entry Point
3
// ============================================================
4
5
+import { InvoicesView } from './views/InvoicesView.js';
6
import { ContactsView } from './views/ContactsView.js';
7
import { ProductsView } from './views/ProductsView.js';
8
import { StorageService } from './core/StorageService.js';
@@ -100,7 +101,11 @@ function registerRoutes() {
101
}
102
});
103
103
- Router.register('invoices', { title: 'فاکتورها', render: placeholder('فاکتورها', 4) });
104
+ Router.register('invoices', {
105
+ title: 'فاکتورها',
106
+ render: () => InvoicesView.render(),
107
+ onMount: () => InvoicesView.onMount()
108
+});
109
Router.register('products', {
110
title: 'کالا و انبار',
111
render: () => ProductsView.render(),
src/styles/main.css
+21
@@ -526,4 +526,25 @@ textarea.form-control { min-height: 80px; resize: vertical; }
526
.btn-add-inline:hover {
527
background: var(--primary);
528
color: #fff;
529
+}
530
+/* ===== Print template cards ===== */
531
+.print-tpl-card {
532
+ display: flex;
533
+ flex-direction: column;
534
+ align-items: center;
535
+ padding: 14px 8px;
536
+ border: 2px solid var(--border);
537
+ border-radius: 10px;
538
+ cursor: pointer;
539
+ transition: all .15s;
540
+ text-align: center;
541
+ background: var(--card-bg);
542
+}
543
+.print-tpl-card:hover {
544
+ border-color: var(--primary);
545
+ transform: translateY(-2px);
546
+}
547
+.print-tpl-card.active {
548
+ border-color: var(--primary);
549
+ background: var(--primary-light);
550
}
\ No newline at end of file
src/utils/InvoicePrint.js
new
+630
@@ -0,0 +1,630 @@
1
+// ============================================================
2
+// InvoicePrint — چاپ فاکتور با ۳ قالب و تنظیمات زنده
3
+// ============================================================
4
+
5
+import { InvoiceController } from '../controllers/InvoiceController.js';
6
+import { ContactController } from '../controllers/ContactController.js';
7
+import { StorageService } from '../core/StorageService.js';
8
+import { Auth } from '../core/Auth.js';
9
+import { Modal } from '../core/Modal.js';
10
+import { Toast } from '../core/Toast.js';
11
+import { Formatters } from '../utils/Formatters.js';
12
+import { numberToWords } from '../utils/NumberToWords.js';
13
+
14
+class InvoicePrintImpl {
15
+ constructor() {
16
+ this.currentInvoiceId = null;
17
+ this.settings = {
18
+ template: 'non_formal', // formal | non_formal | thermal
19
+ paperSize: 'A4',
20
+ orientation: 'portrait',
21
+ showSignature: true,
22
+ showCode: true,
23
+ themeColor: '#0d9488',
24
+ showBalance: 'none' // none | simple | detailed
25
+ };
26
+ }
27
+
28
+ // ============================================================
29
+ // باز کردن تنظیمات چاپ
30
+ // ============================================================
31
+ async openSettings(invoiceId) {
32
+ this.currentInvoiceId = invoiceId;
33
+ const inv = await InvoiceController.get(invoiceId);
34
+ if (!inv) { Toast.error('فاکتور یافت نشد'); return; }
35
+
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';
40
+
41
+ const body = `
42
+ <div class="form-group">
43
+ <label class="form-label">قالب چاپ</label>
44
+ <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px">
45
+ <label class="print-tpl-card ${this.settings.template === 'formal' ? 'active' : ''}" data-tpl="formal">
46
+ <input type="radio" name="tpl" value="formal" ${this.settings.template === 'formal' ? 'checked' : ''} style="display:none" />
47
+ <div style="font-size:24px">📋</div>
48
+ <div style="font-weight:700;font-size:12.5px;margin-top:4px">فاکتور رسمی</div>
49
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">مطابق مالیاتی</div>
50
+ </label>
51
+ <label class="print-tpl-card ${this.settings.template === 'non_formal' ? 'active' : ''}" data-tpl="non_formal">
52
+ <input type="radio" name="tpl" value="non_formal" ${this.settings.template === 'non_formal' ? 'checked' : ''} style="display:none" />
53
+ <div style="font-size:24px">📄</div>
54
+ <div style="font-weight:700;font-size:12.5px;margin-top:4px">غیررسمی</div>
55
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">فروشگاهی مدرن</div>
56
+ </label>
57
+ <label class="print-tpl-card ${this.settings.template === 'thermal' ? 'active' : ''}" data-tpl="thermal">
58
+ <input type="radio" name="tpl" value="thermal" ${this.settings.template === 'thermal' ? 'checked' : ''} style="display:none" />
59
+ <div style="font-size:24px">🧾</div>
60
+ <div style="font-weight:700;font-size:12.5px;margin-top:4px">فیش حرارتی</div>
61
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">۸۰ میلیمتری</div>
62
+ </label>
63
+ </div>
64
+ </div>
65
+
66
+ <div class="form-row">
67
+ <div class="form-group">
68
+ <label class="form-label">اندازه کاغذ</label>
69
+ <select class="form-control" id="prPaper">
70
+ <option value="A4" ${this.settings.paperSize === 'A4' ? 'selected' : ''}>A4</option>
71
+ <option value="A5" ${this.settings.paperSize === 'A5' ? 'selected' : ''}>A5</option>
72
+ </select>
73
+ </div>
74
+ <div class="form-group">
75
+ <label class="form-label">جهت صفحه</label>
76
+ <select class="form-control" id="prOrientation">
77
+ <option value="portrait" ${this.settings.orientation === 'portrait' ? 'selected' : ''}>عمودی</option>
78
+ <option value="landscape" ${this.settings.orientation === 'landscape' ? 'selected' : ''}>افقی</option>
79
+ </select>
80
+ </div>
81
+ <div class="form-group">
82
+ <label class="form-label">رنگ سربرگ</label>
83
+ <input type="color" class="form-control" id="prColor" value="${this.settings.themeColor}" style="height:42px;padding:4px" />
84
+ </div>
85
+ </div>
86
+
87
+ <div class="form-group">
88
+ <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px">
89
+ <input type="checkbox" id="prSignature" ${this.settings.showSignature ? 'checked' : ''} />
90
+ نمایش محل مهر و امضا
91
+ </label>
92
+ </div>
93
+
94
+ <div class="form-group">
95
+ <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px">
96
+ <input type="checkbox" id="prCode" ${this.settings.showCode ? 'checked' : ''} />
97
+ نمایش کد کالا در جدول
98
+ </label>
99
+ </div>
100
+
101
+ <div class="form-group">
102
+ <label class="form-label">نمایش وضعیت حساب مشتری</label>
103
+ <select class="form-control" id="prBalance">
104
+ <option value="none" ${this.settings.showBalance === 'none' ? 'selected' : ''}>عدم نمایش</option>
105
+ <option value="simple" ${this.settings.showBalance === 'simple' ? 'selected' : ''}>فقط مانده فعلی</option>
106
+ </select>
107
+ </div>
108
+ `;
109
+
110
+ const footer = `
111
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
112
+ <button class="btn btn-secondary" onclick="window.InvoicePrint._preview()">👁️ پیشنمایش</button>
113
+ <button class="btn" onclick="window.InvoicePrint._print()">🖨️ چاپ</button>
114
+ `;
115
+
116
+ Modal.open({ title: 'تنظیمات چاپ فاکتور', body, footer, size: 'md' });
117
+
118
+ // ذخیره تنظیمات در ctx
119
+ setTimeout(() => {
120
+ document.querySelectorAll('.print-tpl-card').forEach(card => {
121
+ card.addEventListener('click', () => {
122
+ document.querySelectorAll('.print-tpl-card').forEach(c => c.classList.remove('active'));
123
+ card.classList.add('active');
124
+ card.querySelector('input').checked = true;
125
+ });
126
+ });
127
+ }, 50);
128
+ }
129
+
130
+ _collectSettings() {
131
+ // فقط اگه فیلدهای تنظیمات توی صفحه موجودن، مقدار جدید رو بگیر
132
+ // وگرنه از مقدار قبلی (this.settings) استفاده کن
133
+ const tpl = document.querySelector('input[name="tpl"]:checked');
134
+ if (tpl) this.settings.template = tpl.value;
135
+
136
+ const paper = document.getElementById('prPaper');
137
+ if (paper) this.settings.paperSize = paper.value;
138
+
139
+ const orientation = document.getElementById('prOrientation');
140
+ if (orientation) this.settings.orientation = orientation.value;
141
+
142
+ const color = document.getElementById('prColor');
143
+ if (color) this.settings.themeColor = color.value;
144
+
145
+ const sig = document.getElementById('prSignature');
146
+ if (sig) this.settings.showSignature = sig.checked;
147
+
148
+ const code = document.getElementById('prCode');
149
+ if (code) this.settings.showCode = code.checked;
150
+
151
+ const bal = document.getElementById('prBalance');
152
+ if (bal) this.settings.showBalance = bal.value;
153
+
154
+ return this.settings;
155
+ }
156
+
157
+ async _preview() {
158
+ this._collectSettings();
159
+ const html = await this._buildHtml(this.currentInvoiceId);
160
+ // نمایش پیشنمایش در یک مودال جدید
161
+ const body = `
162
+ <div style="background:#e5e7eb;padding:20px;border-radius:8px;overflow:auto;max-height:70vh">
163
+ <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)">
164
+ ${html}
165
+ </div>
166
+ </div>
167
+ `;
168
+ const footer = `
169
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>
170
+ <button class="btn" onclick="window.InvoicePrint._print()">🖨️ چاپ</button>
171
+ `;
172
+ Modal.open({ title: 'پیشنمایش چاپ', body, footer, size: 'lg' });
173
+ }
174
+
175
+ async _print() {
176
+ this._collectSettings();
177
+ const html = await this._buildHtml(this.currentInvoiceId);
178
+ this._openPrintWindow(html);
179
+ Modal.close();
180
+ }
181
+
182
+ // ============================================================
183
+ // ساخت HTML چاپ
184
+ // ============================================================
185
+ async _buildHtml(invoiceId) {
186
+ const inv = await InvoiceController.get(invoiceId);
187
+ if (!inv) throw new Error('فاکتور یافت نشد');
188
+
189
+ const user = Auth.current();
190
+ const companies = await StorageService.getByOwner('companies', user.id);
191
+ const seller = companies[0] || {
192
+ name: 'شرکت شما',
193
+ phone: '', address: '', national_id: '', economic_code: '',
194
+ reg_number: '', postal_code: '', footer: ''
195
+ };
196
+
197
+ const contact = inv.contactId ? await StorageService.get('contacts', inv.contactId) : {};
198
+
199
+ let balance = 0;
200
+ if (this.settings.showBalance !== 'none' && inv.contactId) {
201
+ balance = await ContactController.getBalance(inv.contactId);
202
+ }
203
+
204
+ if (this.settings.template === 'formal') {
205
+ return this._formalTemplate(inv, seller, contact, balance);
206
+ } else if (this.settings.template === 'thermal') {
207
+ return this._thermalTemplate(inv, seller, contact);
208
+ } else {
209
+ return this._nonFormalTemplate(inv, seller, contact, balance);
210
+ }
211
+ }
212
+
213
+ // ------------------------------------------------------------
214
+ // قالب فاکتور رسمی
215
+ // ------------------------------------------------------------
216
+ _formalTemplate(inv, seller, contact, balance) {
217
+ const color = this.settings.themeColor;
218
+ const showCode = this.settings.showCode;
219
+
220
+ const items = inv.items.map((it, idx) => {
221
+ const qty = Number(it.qty) || 0;
222
+ const price = Number(it.price) || 0;
223
+ const lineSub = qty * price;
224
+ const disc = Number(it.discount) || 0;
225
+ const afterDisc = lineSub - disc;
226
+ const vat = inv.vatEnabled ? Math.round(afterDisc * (Number(inv.vatRate) || 0) / 100) : 0;
227
+ const net = afterDisc + vat;
228
+ return `
229
+ <tr>
230
+ <td>${Formatters.toPersianDigits(idx + 1)}</td>
231
+ <td style="text-align:right">${this._esc(it.productName)}</td>
232
+ <td>${Formatters.toPersianDigits(qty)}</td>
233
+ <td>${this._esc(it.unit || 'عدد')}</td>
234
+ <td>${Formatters.number(price)}</td>
235
+ <td>${Formatters.number(lineSub)}</td>
236
+ <td>${Formatters.number(disc)}</td>
237
+ <td>${Formatters.number(vat)}</td>
238
+ <td style="font-weight:700">${Formatters.number(net)}</td>
239
+ </tr>
240
+ `;
241
+ }).join('');
242
+
243
+ const balanceHtml = this.settings.showBalance === 'simple' && balance !== 0 ? `
244
+ <div style="margin-top:6px;padding:6px 10px;background:#fef3c7;border-radius:6px;font-size:10px">
245
+ <strong>مانده حساب فعلی مشتری:</strong>
246
+ ${balance > 0 ? Formatters.money(balance) + ' بدهکار' : Formatters.money(Math.abs(balance)) + ' بستانکار'}
247
+ </div>
248
+ ` : '';
249
+
250
+ return `
251
+ <div class="print-doc" dir="rtl" style="direction:rtl;text-align:right;font-family:'Vazirmatn FD',Tahoma,sans-serif;color:#000;padding:6mm">
252
+ <table style="width:100%;border-collapse:collapse;border:2px solid ${color};margin-bottom:4px">
253
+ <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>
257
+ </td>
258
+ <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>
261
+ </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>
265
+ </td>
266
+ </tr>
267
+ </table>
268
+
269
+ <table style="width:100%;border-collapse:collapse;border:1.5px solid ${color};font-size:10.5px;margin-bottom:4px">
270
+ <tr style="background:#f8fafc;font-weight:bold">
271
+ <td colspan="4" style="border:1px solid ${color};padding:3px 8px;color:${color}">الف) مشخصات فروشنده</td>
272
+ </tr>
273
+ <tr>
274
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
275
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:35%"><strong>${this._esc(seller.name)}</strong></td>
276
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
277
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:35%">${this._esc(seller.economic_code || '—')}</td>
278
+ </tr>
279
+ <tr>
280
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
281
+ <td style="border:1px solid #cbd5e1;padding:4px 8px">${this._esc(seller.national_id || '—')} / ${this._esc(seller.reg_number || '—')}</td>
282
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
283
+ <td style="border:1px solid #cbd5e1;padding:4px 8px">${Formatters.toPersianDigits(seller.postal_code || '—')}</td>
284
+ </tr>
285
+ <tr>
286
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">نشانی و تلفن:</td>
287
+ <td colspan="3" style="border:1px solid #cbd5e1;padding:4px 8px">${this._esc(seller.address || '—')}${seller.phone ? ' | تلفن: ' + Formatters.phone(seller.phone) : ''}</td>
288
+ </tr>
289
+ </table>
290
+
291
+ <table style="width:100%;border-collapse:collapse;border:1.5px solid ${color};font-size:10.5px;margin-bottom:4px">
292
+ <tr style="background:#f8fafc;font-weight:bold">
293
+ <td colspan="4" style="border:1px solid ${color};padding:3px 8px;color:${color}">ب) مشخصات خریدار</td>
294
+ </tr>
295
+ <tr>
296
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:15%;background:#f1f5f9">نام شخص حقیقی/حقوقی:</td>
297
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:35%"><strong>${this._esc(contact.name || inv.contactName || '—')}</strong></td>
298
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:15%;background:#f1f5f9">شماره اقتصادی:</td>
299
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;width:35%">${this._esc(contact.economicCode || '—')}</td>
300
+ </tr>
301
+ <tr>
302
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">شناسه ملی / شماره ثبت:</td>
303
+ <td style="border:1px solid #cbd5e1;padding:4px 8px">${this._esc(contact.nationalId || '—')} / ${this._esc(contact.regNumber || '—')}</td>
304
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">کد پستی ۱۰ رقمی:</td>
305
+ <td style="border:1px solid #cbd5e1;padding:4px 8px">${Formatters.toPersianDigits(contact.postalCode || '—')}</td>
306
+ </tr>
307
+ <tr>
308
+ <td style="border:1px solid #cbd5e1;padding:4px 8px;background:#f1f5f9">نشانی و تلفن:</td>
309
+ <td colspan="3" style="border:1px solid #cbd5e1;padding:4px 8px">${this._esc(contact.address || '—')}${contact.mobile ? ' | همراه: ' + Formatters.phone(contact.mobile) : ''}</td>
310
+ </tr>
311
+ </table>
312
+
313
+ <table style="width:100%;border-collapse:collapse;border:1.5px solid ${color};font-size:10.5px">
314
+ <thead>
315
+ <tr style="background:${color};color:#fff;font-weight:bold;text-align:center">
316
+ <th style="border:1px solid ${color};padding:4px;width:30px">ردیف</th>
317
+ <th style="border:1px solid ${color};padding:4px 6px;text-align:right">شرح کالا یا خدمات</th>
318
+ <th style="border:1px solid ${color};padding:4px;width:50px">تعداد</th>
319
+ <th style="border:1px solid ${color};padding:4px;width:50px">واحد</th>
320
+ <th style="border:1px solid ${color};padding:4px;width:90px">مبلغ واحد</th>
321
+ <th style="border:1px solid ${color};padding:4px;width:100px">مبلغ کل</th>
322
+ <th style="border:1px solid ${color};padding:4px;width:75px">تخفیف</th>
323
+ <th style="border:1px solid ${color};padding:4px;width:80px">مالیات</th>
324
+ <th style="border:1px solid ${color};padding:4px;width:110px">مبلغ نهایی</th>
325
+ </tr>
326
+ </thead>
327
+ <tbody>${items}</tbody>
328
+ </table>
329
+
330
+ <table style="width:100%;border-collapse:collapse;border:1.5px solid ${color};font-size:10.5px;margin-top:4px">
331
+ <tr>
332
+ <td style="width:60%;border:1px solid ${color};padding:8px;vertical-align:top;background:#f8fafc">
333
+ <div style="margin-bottom:5px"><strong>مبلغ کل به حروف:</strong> ${numberToWords(inv.grandTotal)}</div>
334
+ <div style="margin-bottom:5px"><strong>شرایط و نحوه پرداخت:</strong> ${this._paymentLabel(inv.paymentMethod)}</div>
335
+ ${inv.description ? `<div style="margin-bottom:5px"><strong>توضیحات:</strong> ${this._esc(inv.description)}</div>` : ''}
336
+ ${balanceHtml}
337
+ </td>
338
+ <td style="width:40%;border:1px solid ${color};padding:0">
339
+ <table style="width:100%;border-collapse:collapse;font-size:10.5px">
340
+ <tr><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px">جمع کل اقلام:</td><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px;text-align:left">${Formatters.money(inv.subtotal)}</td></tr>
341
+ <tr><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px">مجموع تخفیف:</td><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px;text-align:left">${Formatters.money(inv.totalDiscount)}</td></tr>
342
+ ${inv.vatEnabled ? `<tr><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px">مالیات (${Formatters.toPersianDigits(inv.vatRate)}٪):</td><td style="border-bottom:1px solid #cbd5e1;padding:4px 10px;text-align:left">${Formatters.money(inv.vatAmount)}</td></tr>` : ''}
343
+ <tr style="background:#f0fdfa;font-weight:bold;font-size:12px;color:${color}">
344
+ <td style="padding:6px 10px">مبلغ قابل پرداخت:</td>
345
+ <td style="padding:6px 10px;text-align:left">${Formatters.money(inv.grandTotal)}</td>
346
+ </tr>
347
+ ${inv.paidAmount > 0 ? `<tr><td style="padding:4px 10px">پرداختشده:</td><td style="padding:4px 10px;text-align:left">${Formatters.money(inv.paidAmount)}</td></tr>` : ''}
348
+ ${inv.remaining > 0 ? `<tr><td style="padding:4px 10px;color:#b91c1c"><strong>باقیمانده:</strong></td><td style="padding:4px 10px;text-align:left;color:#b91c1c;font-weight:bold">${Formatters.money(inv.remaining)}</td></tr>` : ''}
349
+ </table>
350
+ </td>
351
+ </tr>
352
+ </table>
353
+
354
+ ${this.settings.showSignature ? `
355
+ <table style="width:100%;border-collapse:collapse;border:1px solid ${color};margin-top:8px;text-align:center;font-size:11px">
356
+ <tr>
357
+ <td style="width:50%;height:70px;vertical-align:top;border:1px solid ${color};padding:6px;background:#fff"><div style="font-weight:bold">مهر و امضای فروشنده</div></td>
358
+ <td style="width:50%;height:70px;vertical-align:top;border:1px solid ${color};padding:6px;background:#fff"><div style="font-weight:bold">مهر و امضای خریدار</div></td>
359
+ </tr>
360
+ </table>
361
+ ` : ''}
362
+ </div>
363
+ `;
364
+ }
365
+
366
+ // ------------------------------------------------------------
367
+ // قالب غیررسمی
368
+ // ------------------------------------------------------------
369
+ _nonFormalTemplate(inv, seller, contact, balance) {
370
+ const color = this.settings.themeColor;
371
+
372
+ const items = inv.items.map((it, idx) => {
373
+ const qty = Number(it.qty) || 0;
374
+ const price = Number(it.price) || 0;
375
+ const lineSub = qty * price;
376
+ const disc = Number(it.discount) || 0;
377
+ const total = lineSub - disc;
378
+ return `
379
+ <tr>
380
+ <td style="text-align:center">${Formatters.toPersianDigits(idx + 1)}</td>
381
+ <td style="text-align:right">${this._esc(it.productName)}</td>
382
+ <td style="text-align:center">${this._esc(it.unit || 'عدد')}</td>
383
+ <td style="text-align:center">${Formatters.toPersianDigits(qty)}</td>
384
+ <td style="text-align:left">${Formatters.number(price)}</td>
385
+ <td style="text-align:left">${Formatters.number(disc)}</td>
386
+ <td style="text-align:left;font-weight:700">${Formatters.number(total)}</td>
387
+ </tr>
388
+ `;
389
+ }).join('');
390
+
391
+ const balanceHtml = this.settings.showBalance === 'simple' && balance !== 0 ? `
392
+ <div style="margin-top:8px;padding:8px 12px;background:#fef3c7;border-radius:8px;font-size:11px">
393
+ <strong>مانده حساب فعلی مشتری:</strong>
394
+ ${balance > 0 ? Formatters.money(balance) + ' بدهکار' : Formatters.money(Math.abs(balance)) + ' بستانکار'}
395
+ </div>
396
+ ` : '';
397
+
398
+ return `
399
+ <div class="print-doc" dir="rtl" style="direction:rtl;text-align:right;font-family:'Vazirmatn FD',Tahoma,sans-serif;color:#000;padding:8mm">
400
+ <div style="display:flex;justify-content:space-between;align-items:start;padding-bottom:12px;border-bottom:3px solid ${color};margin-bottom:14px">
401
+ <div style="flex:1">
402
+ <div style="font-size:20px;font-weight:800;color:${color}">${this._esc(seller.name)}</div>
403
+ ${seller.address ? `<div style="font-size:11px;color:#64748b;margin-top:4px">${this._esc(seller.address)}</div>` : ''}
404
+ ${seller.phone ? `<div style="font-size:11px;color:#64748b;margin-top:2px">تلفن: ${Formatters.phone(seller.phone)}</div>` : ''}
405
+ </div>
406
+ <div style="text-align:left;min-width:180px">
407
+ <div style="font-size:22px;font-weight:800;color:${color};margin-bottom:6px">${inv.isPreInvoice ? 'پیشفاکتور' : 'فاکتور فروش'}</div>
408
+ <div style="font-size:12px;background:${color};color:#fff;padding:6px 12px;border-radius:6px;font-weight:700;display:inline-block">#${Formatters.toPersianDigits(inv.number)}</div>
409
+ <div style="font-size:11px;color:#475569;margin-top:6px">تاریخ: ${Formatters.toPersianDigits(inv.date)}</div>
410
+ </div>
411
+ </div>
412
+
413
+ <div style="display:flex;gap:12px;margin-bottom:14px">
414
+ <div style="flex:1;background:#f8fafc;padding:10px 12px;border-radius:8px;border-right:3px solid ${color}">
415
+ <div style="font-size:11px;font-weight:700;color:${color};margin-bottom:6px">فروشنده</div>
416
+ <div style="font-size:12px;font-weight:600">${this._esc(seller.name)}</div>
417
+ ${seller.national_id ? `<div style="font-size:10.5px;color:#64748b;margin-top:2px">شناسه ملی: ${Formatters.toPersianDigits(seller.national_id)}</div>` : ''}
418
+ ${seller.phone ? `<div style="font-size:10.5px;color:#64748b;margin-top:2px">تلفن: ${Formatters.phone(seller.phone)}</div>` : ''}
419
+ </div>
420
+ <div style="flex:1;background:#f8fafc;padding:10px 12px;border-radius:8px;border-right:3px solid ${color}">
421
+ <div style="font-size:11px;font-weight:700;color:${color};margin-bottom:6px">خریدار</div>
422
+ <div style="font-size:12px;font-weight:600">${this._esc(contact.name || inv.contactName || '—')}</div>
423
+ ${contact.mobile ? `<div style="font-size:10.5px;color:#64748b;margin-top:2px">همراه: ${Formatters.phone(contact.mobile)}</div>` : ''}
424
+ ${contact.address ? `<div style="font-size:10.5px;color:#64748b;margin-top:2px;line-height:1.5">${this._esc(contact.address)}</div>` : ''}
425
+ </div>
426
+ </div>
427
+
428
+ <table style="width:100%;border-collapse:collapse;font-size:11px;margin-bottom:14px">
429
+ <thead>
430
+ <tr style="background:${color};color:#fff">
431
+ <th style="padding:8px 4px;width:40px;text-align:center;border-radius:0 6px 0 0">#</th>
432
+ <th style="padding:8px 8px;text-align:right">شرح کالا یا خدمات</th>
433
+ <th style="padding:8px 4px;width:60px;text-align:center">واحد</th>
434
+ <th style="padding:8px 4px;width:60px;text-align:center">مقدار</th>
435
+ <th style="padding:8px 4px;width:100px;text-align:left">قیمت واحد</th>
436
+ <th style="padding:8px 4px;width:90px;text-align:left">تخفیف</th>
437
+ <th style="padding:8px 4px;width:110px;text-align:left;border-radius:6px 0 0 0">جمع</th>
438
+ </tr>
439
+ </thead>
440
+ <tbody>${items}</tbody>
441
+ </table>
442
+
443
+ <div style="display:flex;gap:14px;align-items:stretch">
444
+ <div style="flex:1">
445
+ <div style="background:#f8fafc;padding:12px;border-radius:8px;font-size:11px;line-height:1.9">
446
+ <div style="font-weight:700;color:${color};margin-bottom:6px">مبلغ به حروف:</div>
447
+ <div>${numberToWords(inv.grandTotal)}</div>
448
+ ${inv.description ? `<div style="margin-top:10px;padding-top:10px;border-top:1px dashed #cbd5e1"><strong>توضیحات:</strong> ${this._esc(inv.description)}</div>` : ''}
449
+ ${balanceHtml}
450
+ </div>
451
+ </div>
452
+ <div style="flex:0 0 280px">
453
+ <table style="width:100%;border-collapse:collapse;font-size:11.5px;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden">
454
+ <tr style="background:#f8fafc"><td style="padding:8px 12px">جمع اقلام:</td><td style="padding:8px 12px;text-align:left">${Formatters.money(inv.subtotal)}</td></tr>
455
+ ${inv.totalDiscount > 0 ? `<tr><td style="padding:8px 12px">تخفیف:</td><td style="padding:8px 12px;text-align:left;color:#dc2626">- ${Formatters.money(inv.totalDiscount)}</td></tr>` : ''}
456
+ ${inv.vatEnabled ? `<tr><td style="padding:8px 12px">مالیات (${Formatters.toPersianDigits(inv.vatRate)}٪):</td><td style="padding:8px 12px;text-align:left;color:#d97706">${Formatters.money(inv.vatAmount)}</td></tr>` : ''}
457
+ <tr style="background:${color};color:#fff;font-weight:700;font-size:14px"><td style="padding:10px 12px">قابل پرداخت:</td><td style="padding:10px 12px;text-align:left">${Formatters.money(inv.grandTotal)}</td></tr>
458
+ ${inv.paidAmount > 0 ? `<tr><td style="padding:6px 12px">پرداختشده:</td><td style="padding:6px 12px;text-align:left;color:#059669">${Formatters.money(inv.paidAmount)}</td></tr>` : ''}
459
+ ${inv.remaining > 0 ? `<tr style="background:#fef2f2"><td style="padding:6px 12px;color:#b91c1c;font-weight:700">باقیمانده:</td><td style="padding:6px 12px;text-align:left;color:#b91c1c;font-weight:700">${Formatters.money(inv.remaining)}</td></tr>` : ''}
460
+ </table>
461
+ </div>
462
+ </div>
463
+
464
+ ${this.settings.showSignature ? `
465
+ <div style="display:flex;justify-content:space-between;gap:20px;margin-top:24px;padding-top:14px;border-top:1px dashed #cbd5e1">
466
+ <div style="flex:1;text-align:center;font-size:11px;color:#64748b">
467
+ <div style="font-weight:700;color:#0f172a;margin-bottom:40px">مهر و امضای فروشنده</div>
468
+ </div>
469
+ <div style="flex:1;text-align:center;font-size:11px;color:#64748b">
470
+ <div style="font-weight:700;color:#0f172a;margin-bottom:40px">مهر و امضای خریدار</div>
471
+ </div>
472
+ </div>
473
+ ` : ''}
474
+
475
+ ${seller.footer ? `<div style="margin-top:20px;padding:10px;background:#f8fafc;border-radius:6px;font-size:10.5px;color:#64748b;text-align:center">${this._esc(seller.footer)}</div>` : ''}
476
+ </div>
477
+ `;
478
+ }
479
+
480
+ // ------------------------------------------------------------
481
+ // قالب فیش حرارتی
482
+ // ------------------------------------------------------------
483
+ _thermalTemplate(inv, seller, contact) {
484
+ const items = inv.items.map((it, idx) => {
485
+ const qty = Number(it.qty) || 0;
486
+ const price = Number(it.price) || 0;
487
+ const total = qty * price - (Number(it.discount) || 0);
488
+ return `
489
+ <tr>
490
+ <td style="text-align:right;padding:2px 0;font-size:10px">${this._esc(it.productName)}</td>
491
+ <td style="text-align:center;padding:2px 0;font-size:10px">${Formatters.toPersianDigits(qty)}</td>
492
+ <td style="text-align:left;padding:2px 0;font-size:10px">${Formatters.number(total)}</td>
493
+ </tr>
494
+ `;
495
+ }).join('');
496
+
497
+ return `
498
+ <div class="print-doc" dir="rtl" style="direction:rtl;text-align:right;font-family:'Vazirmatn FD',Tahoma,monospace;color:#000;padding:3mm;width:76mm;font-size:11px;background:#fff">
499
+ <div style="text-align:center;padding-bottom:6px;border-bottom:1px dashed #000;margin-bottom:6px">
500
+ <div style="font-size:14px;font-weight:800">${this._esc(seller.name)}</div>
501
+ ${seller.phone ? `<div style="font-size:10px;margin-top:2px">تلفن: ${Formatters.phone(seller.phone)}</div>` : ''}
502
+ ${seller.address ? `<div style="font-size:9px;margin-top:2px">${this._esc(seller.address)}</div>` : ''}
503
+ </div>
504
+
505
+ <div style="display:flex;justify-content:space-between;font-size:10px;margin-bottom:4px">
506
+ <div>شماره: ${Formatters.toPersianDigits(inv.number)}</div>
507
+ <div>تاریخ: ${Formatters.toPersianDigits(inv.date)}</div>
508
+ </div>
509
+
510
+ <div style="font-size:10px;padding:4px 0;border-top:1px dashed #000;border-bottom:1px dashed #000;margin-bottom:6px">
511
+ مشتری: ${this._esc(contact.name || inv.contactName || '—')}
512
+ </div>
513
+
514
+ <table style="width:100%;border-collapse:collapse;font-size:10px;margin-bottom:6px">
515
+ <thead>
516
+ <tr style="border-bottom:1px solid #000">
517
+ <th style="text-align:right;padding:3px 0">شرح</th>
518
+ <th style="text-align:center;padding:3px 0;width:30px">تعداد</th>
519
+ <th style="text-align:left;padding:3px 0;width:70px">مبلغ</th>
520
+ </tr>
521
+ </thead>
522
+ <tbody>${items}</tbody>
523
+ </table>
524
+
525
+ <div style="border-top:1px dashed #000;padding-top:6px;font-size:11px">
526
+ <div style="display:flex;justify-content:space-between;margin-bottom:3px">
527
+ <span>جمع کل:</span>
528
+ <span>${Formatters.number(inv.subtotal)}</span>
529
+ </div>
530
+ ${inv.totalDiscount > 0 ? `<div style="display:flex;justify-content:space-between;margin-bottom:3px"><span>تخفیف:</span><span>- ${Formatters.number(inv.totalDiscount)}</span></div>` : ''}
531
+ ${inv.vatEnabled ? `<div style="display:flex;justify-content:space-between;margin-bottom:3px"><span>مالیات:</span><span>${Formatters.number(inv.vatAmount)}</span></div>` : ''}
532
+ <div style="display:flex;justify-content:space-between;font-size:14px;font-weight:800;padding:6px 0;border-top:1px solid #000;border-bottom:1px solid #000;margin:4px 0">
533
+ <span>قابل پرداخت:</span>
534
+ <span>${Formatters.number(inv.grandTotal)}</span>
535
+ </div>
536
+ ${inv.paidAmount > 0 ? `<div style="display:flex;justify-content:space-between;margin-top:3px"><span>پرداخت:</span><span>${Formatters.number(inv.paidAmount)}</span></div>` : ''}
537
+ ${inv.remaining > 0 ? `<div style="display:flex;justify-content:space-between;margin-top:3px;font-weight:700"><span>باقیمانده:</span><span>${Formatters.number(inv.remaining)}</span></div>` : ''}
538
+ </div>
539
+
540
+ <div style="text-align:center;margin-top:8px;padding-top:6px;border-top:1px dashed #000;font-size:9.5px">
541
+ ${seller.footer ? this._esc(seller.footer) : 'از خرید شما سپاسگزاریم'}
542
+ </div>
543
+ <div style="text-align:center;font-size:9px;margin-top:4px;color:#64748b">
544
+ فینورا پرو
545
+ </div>
546
+ </div>
547
+ `;
548
+ }
549
+
550
+ // ============================================================
551
+ // باز کردن پنجره چاپ
552
+ // ============================================================
553
+ _openPrintWindow(html) {
554
+ const printWindow = window.open('', '_blank', 'width=900,height=700');
555
+ if (!printWindow) {
556
+ Toast.error('لطفاً پاپآپ را فعال کنید');
557
+ return;
558
+ }
559
+
560
+ // تعیین اندازهی صفحه
561
+ let pageCss = 'A4 portrait';
562
+ if (this.settings.template === 'thermal') {
563
+ pageCss = '80mm auto';
564
+ } else {
565
+ const size = this.settings.paperSize === 'A5' ? 'A5' : 'A4';
566
+ pageCss = size + ' ' + (this.settings.orientation || 'portrait');
567
+ }
568
+
569
+ printWindow.document.write(`
570
+ <!DOCTYPE html>
571
+ <html lang="fa" dir="rtl">
572
+ <head>
573
+ <meta charset="UTF-8" />
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 باشه تا درست اعمال بشه */
578
+ @page {
579
+ size: ${pageCss};
580
+ margin: 6mm;
581
+ }
582
+
583
+ * { box-sizing: border-box; margin: 0; padding: 0; }
584
+ html, body {
585
+ direction: rtl;
586
+ text-align: right;
587
+ font-family: 'Vazirmatn FD', Tahoma, sans-serif;
588
+ background: #fff;
589
+ color: #000;
590
+ }
591
+ body { padding: 4px; }
592
+ table { direction: rtl; }
593
+ td, th { direction: rtl; }
594
+ .print-doc { direction: rtl !important; }
595
+
596
+ @media print {
597
+ body { padding: 0; }
598
+ .print-doc { page-break-inside: auto; }
599
+ /* جلوگیری از چاپ رنگهای پیشفرض */
600
+ * {
601
+ -webkit-print-color-adjust: exact !important;
602
+ print-color-adjust: exact !important;
603
+ }
604
+ }
605
+ </style>
606
+ </head>
607
+ <body>${html}</body>
608
+ </html>
609
+ `);
610
+ printWindow.document.close();
611
+
612
+ setTimeout(() => {
613
+ printWindow.focus();
614
+ printWindow.print();
615
+ }, 500);
616
+ }
617
+
618
+ _paymentLabel(method) {
619
+ const labels = { cash: 'نقدی ☑', credit: 'نسیه/چک ☑', partial: 'پرداخت جزئی ☑' };
620
+ return labels[method] || '—';
621
+ }
622
+
623
+ _esc(s) {
624
+ if (s === null || s === undefined) return '';
625
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
626
+ }
627
+}
628
+
629
+export const InvoicePrint = new InvoicePrintImpl();
630
+window.InvoicePrint = InvoicePrint;
\ No newline at end of file
src/views/InvoiceFormView.js
new
+594
@@ -0,0 +1,594 @@
1
+// ============================================================
2
+// InvoiceFormView — فرم صدور و ویرایش فاکتور
3
+// ============================================================
4
+
5
+import { InvoiceController } from '../controllers/InvoiceController.js';
6
+import { ContactController } from '../controllers/ContactController.js';
7
+import { ProductController } from '../controllers/ProductController.js';
8
+import { Modal } from '../core/Modal.js';
9
+import { Toast } from '../core/Toast.js';
10
+import { Formatters } from '../utils/Formatters.js';
11
+import { numberToWords } from '../utils/NumberToWords.js';
12
+
13
+let ctx = {
14
+ editId: null,
15
+ data: null,
16
+ contacts: [],
17
+ products: [],
18
+ rowCounter: 0
19
+};
20
+
21
+class InvoiceFormViewImpl {
22
+ // ============================================================
23
+ // باز کردن فرم فاکتور (ایجاد یا ویرایش)
24
+ // ============================================================
25
+ async open(invoiceId = null) {
26
+ ctx.editId = invoiceId;
27
+ ctx.contacts = await ContactController.getAll();
28
+ ctx.products = await ProductController.getProducts();
29
+ ctx.rowCounter = 0;
30
+
31
+ if (invoiceId) {
32
+ const existing = await InvoiceController.get(invoiceId);
33
+ ctx.data = existing;
34
+ } else {
35
+ ctx.data = {
36
+ kind: 'sale',
37
+ isPreInvoice: false,
38
+ date: this._todayJalali(),
39
+ contactId: null,
40
+ contactName: '',
41
+ items: [],
42
+ discountType: 'fixed',
43
+ discountInput: 0,
44
+ vatEnabled: false,
45
+ vatRate: 9,
46
+ paymentMethod: 'cash',
47
+ paidAmount: 0,
48
+ description: ''
49
+ };
50
+ }
51
+
52
+ // اگه فاکتور جدید بدون اقلام، یک ردیف خالی اضافه کن
53
+ if (!ctx.data.items || ctx.data.items.length === 0) {
54
+ ctx.data.items = [this._emptyItem()];
55
+ }
56
+
57
+ const body = this._renderFormBody();
58
+ const footer = this._renderFooter();
59
+
60
+ const modal = Modal.open({
61
+ title: invoiceId ? `ویرایش فاکتور #${ctx.data.number}` : 'صدور فاکتور جدید',
62
+ body,
63
+ footer,
64
+ size: 'lg',
65
+ onClose: () => { ctx = { editId: null, data: null, contacts: [], products: [], rowCounter: 0 }; }
66
+ });
67
+
68
+ // بعد از باز شدن مودال، اقلام رو رندر کن
69
+ setTimeout(() => {
70
+ this._renderItems();
71
+ this._recalc();
72
+ }, 50);
73
+ }
74
+
75
+ _emptyItem() {
76
+ return {
77
+ productId: null,
78
+ productName: '',
79
+ unit: 'عدد',
80
+ qty: 1,
81
+ price: 0,
82
+ discount: 0,
83
+ discountType: 'fixed',
84
+ lineSubtotal: 0,
85
+ lineTotal: 0
86
+ };
87
+ }
88
+
89
+ // ============================================================
90
+ // ساختار فرم
91
+ // ============================================================
92
+ _renderFormBody() {
93
+ const d = ctx.data;
94
+ const kindOptions = [
95
+ { value: 'sale', label: 'فاکتور فروش' },
96
+ { value: 'purchase', label: 'فاکتور خرید' },
97
+ { value: 'sale_return', label: 'برگشت از فروش' },
98
+ { value: 'purchase_return', label: 'برگشت از خرید' },
99
+ { value: 'non_formal', label: 'فاکتور غیررسمی' }
100
+ ];
101
+ const kindOpts = kindOptions.map(k =>
102
+ `<option value="${k.value}" ${d.kind === k.value ? 'selected' : ''}>${k.label}</option>`
103
+ ).join('');
104
+
105
+ const contactOptions = ctx.contacts.map(c =>
106
+ `<option value="${c.id}" ${d.contactId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
107
+ ).join('');
108
+
109
+ return `
110
+ <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:14px">
111
+ <div class="form-group" style="margin-bottom:0">
112
+ <label class="form-label">نوع سند</label>
113
+ <select class="form-control" id="invKind" onchange="window.InvoiceFormView._onKindChange()">${kindOpts}</select>
114
+ </div>
115
+ <div class="form-group" style="margin-bottom:0">
116
+ <label class="form-label">شماره فاکتور</label>
117
+ <input type="text" class="form-control" value="${d.number ? '#' + d.number : '(خودکار)'}" disabled style="background:var(--bg)" />
118
+ </div>
119
+ <div class="form-group" style="margin-bottom:0">
120
+ <label class="form-label">تاریخ (شمسی)</label>
121
+ <input type="text" class="form-control" id="invDate" value="${this._esc(d.date)}" placeholder="1405/06/27" />
122
+ </div>
123
+ </div>
124
+
125
+ <div style="display:grid;grid-template-columns:2fr 1fr;gap:10px;margin-bottom:14px">
126
+ <div class="form-group" style="margin-bottom:0">
127
+ <label class="form-label">طرف حساب</label>
128
+ <div style="display:flex;gap:6px">
129
+ <select class="form-control" id="invContact" style="flex:1">
130
+ <option value="">— انتخاب کنید —</option>
131
+ ${contactOptions}
132
+ </select>
133
+ <button class="btn btn-secondary" style="min-height:42px;padding:0 12px" onclick="window.InvoiceFormView._openQuickContact()" title="افزودن شخص جدید">➕</button>
134
+ </div>
135
+ </div>
136
+ <div class="form-group" style="margin-bottom:0">
137
+ <label class="form-label">
138
+ <input type="checkbox" id="invPreInvoice" ${d.isPreInvoice ? 'checked' : ''} />
139
+ پیشفاکتور
140
+ </label>
141
+ <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">پیشفاکتور، موجودی انبار رو تغییر نمیده</small>
142
+ </div>
143
+ </div>
144
+
145
+ <div style="margin:14px 0 10px;display:flex;justify-content:space-between;align-items:center">
146
+ <h4 style="font-size:14px;font-weight:700">اقلام فاکتور</h4>
147
+ <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._addRow()">➕ افزودن ردیف</button>
148
+ </div>
149
+
150
+ <div class="table-wrap" style="max-height:340px;overflow-y:auto">
151
+ <table>
152
+ <thead>
153
+ <tr>
154
+ <th style="width:36px;text-align:center">#</th>
155
+ <th style="min-width:200px">کالا / خدمات</th>
156
+ <th style="width:70px">واحد</th>
157
+ <th style="width:80px">مقدار</th>
158
+ <th style="width:130px">قیمت واحد</th>
159
+ <th style="width:130px">تخفیف</th>
160
+ <th style="width:140px">جمع</th>
161
+ <th style="width:40px"></th>
162
+ </tr>
163
+ </thead>
164
+ <tbody id="itemsBody"></tbody>
165
+ </table>
166
+ </div>
167
+
168
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px">
169
+ <div class="card" style="margin:0;padding:16px">
170
+ <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">تخفیف، مالیات و پرداخت</div>
171
+
172
+ <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
173
+ <span style="flex:1;font-size:12.5px">تخفیف کلی</span>
174
+ <select class="form-control" id="invDiscType" style="width:80px;min-height:34px" onchange="window.InvoiceFormView._onDiscTypeChange()">
175
+ <option value="fixed" ${d.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
176
+ <option value="percent" ${d.discountType === 'percent' ? 'selected' : ''}>درصد</option>
177
+ </select>
178
+ <input type="number" class="form-control" id="invDiscInput" style="width:110px;min-height:34px" value="${d.discountInput || 0}" oninput="window.InvoiceFormView._recalc()" />
179
+ </div>
180
+
181
+ <div id="vatRow" style="display:${d.kind === 'non_formal' ? 'none' : 'flex'};gap:8px;align-items:center;margin-bottom:10px">
182
+ <label style="flex:1;font-size:12.5px;display:flex;align-items:center;gap:6px;cursor:pointer">
183
+ <input type="checkbox" id="invVatEnabled" ${d.vatEnabled ? 'checked' : ''} onchange="window.InvoiceFormView._recalc()" />
184
+ مالیات ارزش افزوده
185
+ </label>
186
+ <input type="number" class="form-control" id="invVatRate" style="width:80px;min-height:34px" value="${d.vatRate || 9}" oninput="window.InvoiceFormView._recalc()" />
187
+ <span style="font-size:12.5px;color:var(--text-muted)">٪</span>
188
+ </div>
189
+
190
+ <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
191
+ <span style="flex:1;font-size:12.5px">روش پرداخت</span>
192
+ <select class="form-control" id="invPayment" style="min-height:34px" onchange="window.InvoiceFormView._onPaymentChange()">
193
+ <option value="cash" ${d.paymentMethod === 'cash' ? 'selected' : ''}>نقدی</option>
194
+ <option value="credit" ${d.paymentMethod === 'credit' ? 'selected' : ''}>نسیه</option>
195
+ <option value="partial" ${d.paymentMethod === 'partial' ? 'selected' : ''}>پرداخت جزئی</option>
196
+ </select>
197
+ </div>
198
+
199
+ <div id="paidRow" style="display:${d.paymentMethod === 'partial' ? 'flex' : 'none'};gap:8px;align-items:center;margin-bottom:10px">
200
+ <span style="flex:1;font-size:12.5px">مبلغ پرداختشده</span>
201
+ <input type="number" class="form-control" id="invPaidAmount" style="width:140px;min-height:34px" value="${d.paidAmount || 0}" oninput="window.InvoiceFormView._recalc()" />
202
+ </div>
203
+
204
+ <div class="form-group" style="margin-bottom:0">
205
+ <label class="form-label" style="font-size:12px">توضیحات</label>
206
+ <textarea class="form-control" id="invDescription" rows="2" style="font-size:12.5px">${this._esc(d.description)}</textarea>
207
+ </div>
208
+ </div>
209
+
210
+ <div class="card" style="margin:0;padding:16px;background:var(--bg)">
211
+ <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">جمعبندی</div>
212
+ <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
213
+ <span>جمع اقلام:</span>
214
+ <span id="sumSubtotal" style="font-weight:600">۰ ریال</span>
215
+ </div>
216
+ <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
217
+ <span>تخفیف:</span>
218
+ <span id="sumDiscount" style="font-weight:600;color:var(--danger)">۰ ریال</span>
219
+ </div>
220
+ <div id="sumVatRow" style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
221
+ <span>مالیات:</span>
222
+ <span id="sumVat" style="font-weight:600;color:var(--warning)">۰ ریال</span>
223
+ </div>
224
+ <div style="display:flex;justify-content:space-between;margin-top:12px;padding-top:12px;border-top:2px solid var(--primary);font-size:15px">
225
+ <span style="font-weight:700;color:var(--primary)">قابل پرداخت:</span>
226
+ <span id="sumGrand" style="font-weight:800;color:var(--primary)">۰ ریال</span>
227
+ </div>
228
+ <div style="display:flex;justify-content:space-between;margin-top:8px;font-size:12.5px">
229
+ <span>پرداختشده:</span>
230
+ <span id="sumPaid">۰ ریال</span>
231
+ </div>
232
+ <div style="display:flex;justify-content:space-between;margin-top:6px;font-size:12.5px">
233
+ <span>باقیمانده:</span>
234
+ <span id="sumRemaining" style="font-weight:700;color:var(--danger)">۰ ریال</span>
235
+ </div>
236
+ <div id="sumWords" style="margin-top:14px;padding:10px;background:var(--card-bg);border-radius:8px;font-size:11px;color:var(--text-muted);line-height:1.7;text-align:justify"></div>
237
+ </div>
238
+ </div>
239
+ `;
240
+ }
241
+
242
+ _renderFooter() {
243
+ return `
244
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
245
+ <button class="btn" onclick="window.InvoiceFormView._save(false)">💾 ذخیره</button>
246
+ <button class="btn btn-success" onclick="window.InvoiceFormView._save(true)">💾 ذخیره و چاپ</button>
247
+ `;
248
+ }
249
+
250
+ // ============================================================
251
+ // رندر اقلام
252
+ // ============================================================
253
+ _renderItems() {
254
+ const tbody = document.getElementById('itemsBody');
255
+ if (!tbody) return;
256
+ tbody.innerHTML = '';
257
+ ctx.data.items.forEach((item, idx) => this._renderRow(item, idx));
258
+ }
259
+
260
+ _renderRow(item, idx) {
261
+ const tbody = document.getElementById('itemsBody');
262
+ const row = document.createElement('tr');
263
+ row.dataset.idx = idx;
264
+
265
+ const productOptions = ctx.products.map(p =>
266
+ `<option value="${p.id}" ${item.productId === p.id ? 'selected' : ''}>${this._esc(p.name)}${p.code ? ' (' + this._esc(p.code) + ')' : ''}</option>`
267
+ ).join('');
268
+
269
+ row.innerHTML = `
270
+ <td style="text-align:center;font-weight:700">${Formatters.toPersianDigits(idx + 1)}</td>
271
+ <td>
272
+ <select class="form-control row-product" style="min-height:36px" onchange="window.InvoiceFormView._onProductChange(${idx}, this.value)">
273
+ <option value="">— انتخاب کالا —</option>
274
+ ${productOptions}
275
+ </select>
276
+ </td>
277
+ <td><input type="text" class="form-control row-unit" style="min-height:36px;text-align:center" value="${this._esc(item.unit)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'unit', this.value)" /></td>
278
+ <td><input type="number" class="form-control row-qty" style="min-height:36px;text-align:center" value="${item.qty}" min="0" step="any" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
279
+ <td><input type="number" class="form-control row-price" style="min-height:36px;text-align:left" value="${item.price}" min="0" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'price', this.value)" /></td>
280
+ <td>
281
+ <div style="display:flex;gap:4px">
282
+ <input type="number" class="form-control row-disc" style="min-height:36px;text-align:left;flex:1" value="${item.discountType === 'percent' ? (item.discountInput || 0) : (item.discount || 0)}" min="0" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'discount', this.value)" />
283
+ <select class="form-control" style="min-height:36px;width:60px;padding:0 6px;text-align:center;font-size:12px" onchange="window.InvoiceFormView._onDiscTypeRowChange(${idx}, this.value)">
284
+ <option value="fixed" ${item.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
285
+ <option value="percent" ${item.discountType === 'percent' ? 'selected' : ''}>٪</option>
286
+ </select>
287
+ </div>
288
+ </td>
289
+ <td class="row-total" style="font-weight:700;text-align:left">${Formatters.money(item.lineTotal || 0)}</td>
290
+ <td style="text-align:center">
291
+ <button class="icon-btn-sm danger" onclick="window.InvoiceFormView._removeRow(${idx})" title="حذف">✕</button>
292
+ </td>
293
+ `;
294
+ tbody.appendChild(row);
295
+ }
296
+
297
+ _addRow() {
298
+ ctx.data.items.push(this._emptyItem());
299
+ this._renderItems();
300
+ this._recalc();
301
+ }
302
+
303
+ _removeRow(idx) {
304
+ if (ctx.data.items.length === 1) {
305
+ Toast.warning('حداقل یک ردیف لازم است');
306
+ return;
307
+ }
308
+ ctx.data.items.splice(idx, 1);
309
+ this._renderItems();
310
+ this._recalc();
311
+ }
312
+
313
+ _onProductChange(idx, productId) {
314
+ const product = ctx.products.find(p => p.id === productId);
315
+ if (product) {
316
+ ctx.data.items[idx].productId = product.id;
317
+ ctx.data.items[idx].productName = product.name;
318
+ ctx.data.items[idx].unit = product.unitId
319
+ ? (window.__units_cache?.[product.unitId] || 'عدد')
320
+ : (product.unit || 'عدد');
321
+ ctx.data.items[idx].price = Number(product.sellPrice) || 0;
322
+ } else {
323
+ ctx.data.items[idx].productId = null;
324
+ ctx.data.items[idx].productName = '';
325
+ }
326
+ // بهروزرسانی فیلدهای ردیف بدون رندر کامل
327
+ const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
328
+ if (row) {
329
+ row.querySelector('.row-unit').value = ctx.data.items[idx].unit;
330
+ row.querySelector('.row-price').value = ctx.data.items[idx].price;
331
+ }
332
+ this._recalc();
333
+ }
334
+
335
+ _onFieldChange(idx, field, value) {
336
+ if (field === 'qty' || field === 'price' || field === 'discount') {
337
+ ctx.data.items[idx][field] = Number(value) || 0;
338
+ } else {
339
+ ctx.data.items[idx][field] = value;
340
+ }
341
+ this._recalc();
342
+ }
343
+
344
+ _onDiscTypeRowChange(idx, type) {
345
+ ctx.data.items[idx].discountType = type;
346
+ ctx.data.items[idx].discount = 0;
347
+ ctx.data.items[idx].discountInput = 0;
348
+ const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
349
+ if (row) row.querySelector('.row-disc').value = 0;
350
+ this._recalc();
351
+ }
352
+
353
+ _onKindChange() {
354
+ const kind = document.getElementById('invKind').value;
355
+ ctx.data.kind = kind;
356
+ const vatRow = document.getElementById('vatRow');
357
+ const sumVatRow = document.getElementById('sumVatRow');
358
+ if (kind === 'non_formal') {
359
+ vatRow.style.display = 'none';
360
+ sumVatRow.style.display = 'none';
361
+ document.getElementById('invVatEnabled').checked = false;
362
+ } else {
363
+ vatRow.style.display = 'flex';
364
+ sumVatRow.style.display = 'flex';
365
+ }
366
+ this._recalc();
367
+ }
368
+
369
+ _onDiscTypeChange() {
370
+ ctx.data.discountType = document.getElementById('invDiscType').value;
371
+ document.getElementById('invDiscInput').value = 0;
372
+ ctx.data.discountInput = 0;
373
+ this._recalc();
374
+ }
375
+
376
+ _onPaymentChange() {
377
+ const method = document.getElementById('invPayment').value;
378
+ ctx.data.paymentMethod = method;
379
+ const paidRow = document.getElementById('paidRow');
380
+ if (method === 'partial') {
381
+ paidRow.style.display = 'flex';
382
+ } else {
383
+ paidRow.style.display = 'none';
384
+ document.getElementById('invPaidAmount').value = 0;
385
+ }
386
+ this._recalc();
387
+ }
388
+
389
+ // ============================================================
390
+ // محاسبهی مجدد
391
+ // ============================================================
392
+ _recalc() {
393
+ // اقلام
394
+ let subtotal = 0;
395
+ const tbody = document.getElementById('itemsBody');
396
+ if (tbody) {
397
+ ctx.data.items.forEach((item, idx) => {
398
+ const qty = Number(item.qty) || 0;
399
+ const price = Number(item.price) || 0;
400
+ const lineSubtotal = qty * price;
401
+ let lineDiscount = 0;
402
+ const discInput = Number(item.discountInput !== undefined ? item.discountInput : item.discount) || 0;
403
+ if (item.discountType === 'percent') {
404
+ lineDiscount = Math.round(lineSubtotal * discInput / 100);
405
+ } else {
406
+ lineDiscount = discInput;
407
+ }
408
+ lineDiscount = Math.max(0, Math.min(lineDiscount, lineSubtotal));
409
+ item.lineSubtotal = lineSubtotal;
410
+ item.lineTotal = lineSubtotal - lineDiscount;
411
+ item.discount = lineDiscount;
412
+ item.discountInput = discInput;
413
+ subtotal += item.lineTotal;
414
+
415
+ const row = tbody.querySelector(`tr[data-idx="${idx}"]`);
416
+ if (row) {
417
+ const totalEl = row.querySelector('.row-total');
418
+ if (totalEl) totalEl.textContent = Formatters.money(item.lineTotal);
419
+ }
420
+ });
421
+ }
422
+
423
+ // تخفیف کلی
424
+ const discType = document.getElementById('invDiscType')?.value || 'fixed';
425
+ const discInput = Number(document.getElementById('invDiscInput')?.value) || 0;
426
+ let totalDiscount = 0;
427
+ if (discType === 'percent') {
428
+ totalDiscount = Math.round(subtotal * discInput / 100);
429
+ } else {
430
+ totalDiscount = discInput;
431
+ }
432
+ totalDiscount = Math.max(0, Math.min(totalDiscount, subtotal));
433
+ const afterDiscount = subtotal - totalDiscount;
434
+
435
+ // مالیات
436
+ const kind = document.getElementById('invKind')?.value || 'sale';
437
+ const vatEnabled = kind !== 'non_formal' && document.getElementById('invVatEnabled')?.checked;
438
+ const vatRate = Number(document.getElementById('invVatRate')?.value) || 0;
439
+ let vatAmount = 0;
440
+ if (vatEnabled) vatAmount = Math.round(afterDiscount * vatRate / 100);
441
+
442
+ const grandTotal = afterDiscount + vatAmount;
443
+
444
+ // پرداخت
445
+ const method = document.getElementById('invPayment')?.value || 'cash';
446
+ let paidAmount = 0;
447
+ if (method === 'cash') paidAmount = grandTotal;
448
+ else if (method === 'credit') paidAmount = 0;
449
+ else if (method === 'partial') paidAmount = Math.max(0, Math.min(Number(document.getElementById('invPaidAmount')?.value) || 0, grandTotal));
450
+ const remaining = grandTotal - paidAmount;
451
+
452
+ // نمایش
453
+ const set = (id, val) => { const el = document.getElementById(id); if (el) el.textContent = val; };
454
+ set('sumSubtotal', Formatters.money(subtotal));
455
+ set('sumDiscount', Formatters.money(totalDiscount));
456
+ set('sumVat', Formatters.money(vatAmount));
457
+ set('sumGrand', Formatters.money(grandTotal));
458
+ set('sumPaid', Formatters.money(paidAmount));
459
+ set('sumRemaining', Formatters.money(remaining));
460
+
461
+ const wordsEl = document.getElementById('sumWords');
462
+ if (wordsEl) wordsEl.textContent = numberToWords(grandTotal);
463
+
464
+ // ذخیره در ctx برای استفاده در save
465
+ ctx.totals = { subtotal, totalDiscount, vatAmount, grandTotal, paidAmount, remaining };
466
+ }
467
+
468
+ // ============================================================
469
+ // افزودن سریع شخص
470
+ // ============================================================
471
+ async _openQuickContact() {
472
+ const body = `
473
+ <div class="form-group">
474
+ <label class="form-label">نام <span class="req">*</span></label>
475
+ <input type="text" class="form-control" id="qcName" />
476
+ </div>
477
+ <div class="form-group">
478
+ <label class="form-label">موبایل</label>
479
+ <input type="tel" class="form-control" id="qcMobile" />
480
+ </div>
481
+ `;
482
+ const footer = `
483
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
484
+ <button class="btn" onclick="window.InvoiceFormView._saveQuickContact()">ذخیره</button>
485
+ `;
486
+ Modal.open({ title: 'شخص جدید سریع', body, footer, size: 'sm' });
487
+ }
488
+
489
+ async _saveQuickContact() {
490
+ const name = document.getElementById('qcName').value.trim();
491
+ const mobile = document.getElementById('qcMobile').value.trim();
492
+ if (!name) { Toast.warning('نام الزامی است'); return; }
493
+ try {
494
+ const newContact = await ContactController.create({
495
+ entityType: 'natural', role: 'customer', name, mobile
496
+ });
497
+ Toast.success('شخص اضافه شد');
498
+ // refresh dropdown
499
+ const select = document.getElementById('invContact');
500
+ const opt = document.createElement('option');
501
+ opt.value = newContact.id;
502
+ opt.textContent = newContact.name;
503
+ opt.selected = true;
504
+ select.appendChild(opt);
505
+ Modal.close();
506
+ } catch (err) {
507
+ Toast.error('خطا: ' + err.message);
508
+ }
509
+ }
510
+
511
+ // ============================================================
512
+ // ذخیره
513
+ // ============================================================
514
+ async _save(printAfter) {
515
+ const contactId = document.getElementById('invContact').value;
516
+ if (!contactId) {
517
+ Toast.warning('لطفاً طرف حساب را انتخاب کنید');
518
+ return;
519
+ }
520
+ const contact = ctx.contacts.find(c => c.id === contactId);
521
+ if (!contact) {
522
+ Toast.warning('طرف حساب انتخاب شده معتبر نیست');
523
+ return;
524
+ }
525
+
526
+ // اعتبارسنجی اقلام
527
+ const validItems = ctx.data.items.filter(it => it.productId && (Number(it.qty) || 0) > 0);
528
+ if (validItems.length === 0) {
529
+ Toast.warning('حداقل یک ردیف معتبر (کالا با مقدار) لازم است');
530
+ return;
531
+ }
532
+
533
+ const data = {
534
+ kind: document.getElementById('invKind').value,
535
+ isPreInvoice: document.getElementById('invPreInvoice').checked,
536
+ date: document.getElementById('invDate').value,
537
+ contactId: contact.id,
538
+ contactName: contact.name,
539
+ items: validItems,
540
+ discountType: document.getElementById('invDiscType').value,
541
+ discountInput: Number(document.getElementById('invDiscInput').value) || 0,
542
+ vatEnabled: document.getElementById('invVatEnabled')?.checked || false,
543
+ vatRate: Number(document.getElementById('invVatRate')?.value) || 0,
544
+ paymentMethod: document.getElementById('invPayment').value,
545
+ paidAmount: Number(document.getElementById('invPaidAmount')?.value) || 0,
546
+ description: document.getElementById('invDescription').value
547
+ };
548
+
549
+ try {
550
+ const saved = await InvoiceController.save(data, ctx.editId);
551
+ Toast.success(ctx.editId ? 'فاکتور ویرایش شد' : `فاکتور #${saved.number} صادر شد`);
552
+ const savedId = saved.id;
553
+ Modal.close();
554
+ if (printAfter) {
555
+ const { InvoicePrint } = await import('../utils/InvoicePrint.js');
556
+ setTimeout(() => InvoicePrint.print(savedId), 200);
557
+ }
558
+ // refresh list
559
+ if (window.InvoicesView) window.InvoicesView.reloadAndRender?.();
560
+ } catch (err) {
561
+ console.error(err);
562
+ Toast.error('خطا: ' + err.message);
563
+ }
564
+ }
565
+
566
+ // ============================================================
567
+ // Helpers
568
+ // ============================================================
569
+ _todayJalali() {
570
+ const d = new Date();
571
+ const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
572
+ const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
573
+ let jy = (gy <= 1600) ? 0 : 979;
574
+ let gy2 = gy - (gy <= 1600 ? 621 : 1600);
575
+ const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
576
+ let days = (365 * gy2) + Math.floor((gyAdj + 3) / 4) - Math.floor((gyAdj + 99) / 100) + Math.floor((gyAdj + 399) / 400) - 80 + gd + g_d_m[gm - 1];
577
+ jy += 33 * Math.floor(days / 12053);
578
+ days %= 12053;
579
+ jy += 4 * Math.floor(days / 1461);
580
+ days %= 1461;
581
+ if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
582
+ const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
583
+ const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
584
+ return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
585
+ }
586
+
587
+ _esc(s) {
588
+ if (s === null || s === undefined) return '';
589
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
590
+ }
591
+}
592
+
593
+export const InvoiceFormView = new InvoiceFormViewImpl();
594
+window.InvoiceFormView = InvoiceFormView;
\ No newline at end of file
src/views/InvoicesView.js
new
+258
@@ -0,0 +1,258 @@
1
+// ============================================================
2
+// InvoicesView — لیست و مدیریت فاکتورها
3
+// ============================================================
4
+
5
+import { InvoiceController } from '../controllers/InvoiceController.js';
6
+import { InvoiceFormView } from './InvoiceFormView.js';
7
+import { Modal } from '../core/Modal.js';
8
+import { Toast } from '../core/Toast.js';
9
+import { Formatters } from '../utils/Formatters.js';
10
+
11
+let filter = {
12
+ search: '',
13
+ kind: '',
14
+ preInvoice: '',
15
+ paymentStatus: ''
16
+};
17
+let cache = { invoices: [] };
18
+
19
+class InvoicesViewImpl {
20
+ async render() {
21
+ await this.reload();
22
+ return `
23
+ <div class="page-title">
24
+ <h2>فاکتورها</h2>
25
+ <p>مدیریت فاکتورهای فروش، خرید، برگشت و پیشفاکتورها</p>
26
+ </div>
27
+
28
+ <div class="toolbar">
29
+ <div class="search-input-wrap">
30
+ <span class="icon">🔍</span>
31
+ <input type="text" class="form-control" id="invSearch" placeholder="جستجو بر اساس شماره، طرف حساب یا توضیحات..." value="${this._esc(filter.search)}" oninput="window.InvoicesView._onSearch(this.value)" />
32
+ </div>
33
+ <select class="form-control" style="width:auto;min-width:140px" onchange="window.InvoicesView._onFilter('kind', this.value)">
34
+ <option value="">همه انواع</option>
35
+ <option value="sale" ${filter.kind === 'sale' ? 'selected' : ''}>فروش</option>
36
+ <option value="purchase" ${filter.kind === 'purchase' ? 'selected' : ''}>خرید</option>
37
+ <option value="sale_return" ${filter.kind === 'sale_return' ? 'selected' : ''}>برگشت از فروش</option>
38
+ <option value="purchase_return" ${filter.kind === 'purchase_return' ? 'selected' : ''}>برگشت از خرید</option>
39
+ <option value="non_formal" ${filter.kind === 'non_formal' ? 'selected' : ''}>غیررسمی</option>
40
+ </select>
41
+ <select class="form-control" style="width:auto;min-width:130px" onchange="window.InvoicesView._onFilter('paymentStatus', this.value)">
42
+ <option value="">همه وضعیتها</option>
43
+ <option value="paid" ${filter.paymentStatus === 'paid' ? 'selected' : ''}>تسویهشده</option>
44
+ <option value="partial" ${filter.paymentStatus === 'partial' ? 'selected' : ''}>پرداخت جزئی</option>
45
+ <option value="unpaid" ${filter.paymentStatus === 'unpaid' ? 'selected' : ''}>پرداختنشده</option>
46
+ </select>
47
+ <button class="btn btn-secondary" onclick="window.InvoicesView._togglePreInvoice()">
48
+ ${filter.preInvoice === true ? '📄 فقط پیشفاکتور' : '📄 نمایش پیشفاکتورها'}
49
+ </button>
50
+ <button class="btn" onclick="window.InvoicesView.openNewInvoice()">➕ فاکتور جدید</button>
51
+ </div>
52
+
53
+ <div id="invoices-content">${this.renderTable()}</div>
54
+ `;
55
+ }
56
+
57
+ onMount() {
58
+ window.InvoicesView = this;
59
+ }
60
+
61
+ async reload() {
62
+ cache.invoices = await InvoiceController.getAll({
63
+ search: filter.search,
64
+ kind: filter.kind,
65
+ paymentStatus: filter.paymentStatus,
66
+ preInvoice: filter.preInvoice === true ? true : ''
67
+ });
68
+ }
69
+
70
+ async reloadAndRender() {
71
+ await this.reload();
72
+ const el = document.getElementById('invoices-content');
73
+ if (el) el.innerHTML = this.renderTable();
74
+ }
75
+
76
+ renderTable() {
77
+ if (cache.invoices.length === 0) {
78
+ return `
79
+ <div class="table-wrap">
80
+ <table><tbody>
81
+ <tr><td>
82
+ <div class="empty-state">
83
+ <div class="icon">🧾</div>
84
+ <h3>هیچ فاکتوری یافت نشد</h3>
85
+ <p>اولین فاکتور خود را صادر کنید</p>
86
+ <button class="btn" onclick="window.InvoicesView.openNewInvoice()">➕ فاکتور جدید</button>
87
+ </div>
88
+ </td></tr>
89
+ </tbody></table>
90
+ </div>`;
91
+ }
92
+
93
+ const rows = cache.invoices.map(inv => {
94
+ const statusBadge = inv.status === 'paid'
95
+ ? '<span class="badge badge-success">تسویهشده</span>'
96
+ : inv.status === 'partial'
97
+ ? '<span class="badge badge-warning">پرداخت جزئی</span>'
98
+ : '<span class="badge badge-danger">پرداختنشده</span>';
99
+
100
+ const kindLabels = {
101
+ sale: { label: 'فروش', cls: 'badge-success' },
102
+ purchase: { label: 'خرید', cls: 'badge-warning' },
103
+ sale_return: { label: 'برگشت فروش', cls: 'badge-danger' },
104
+ purchase_return: { label: 'برگشت خرید', cls: 'badge-danger' },
105
+ non_formal: { label: 'غیررسمی', cls: 'badge-muted' }
106
+ };
107
+ const k = kindLabels[inv.kind] || { label: inv.kind, cls: 'badge-muted' };
108
+ const preBadge = inv.isPreInvoice ? ' <span class="badge badge-warning" style="font-size:10px">پیشفاکتور</span>' : '';
109
+
110
+ return `
111
+ <tr>
112
+ <td>
113
+ <strong style="font-size:13.5px">#${Formatters.toPersianDigits(inv.number || '—')}</strong>
114
+ ${preBadge}
115
+ </td>
116
+ <td>
117
+ <span class="badge ${k.cls}">${k.label}</span>
118
+ </td>
119
+ <td>${this._esc(inv.contactName || '—')}</td>
120
+ <td>${Formatters.toPersianDigits(inv.date || '—')}</td>
121
+ <td style="font-weight:600">${Formatters.money(inv.grandTotal)}</td>
122
+ <td>${Formatters.money(inv.paidAmount || 0)}</td>
123
+ <td style="color:${inv.remaining > 0 ? 'var(--danger)' : 'var(--success)'};font-weight:600">
124
+ ${Formatters.money(inv.remaining || 0)}
125
+ </td>
126
+ <td>${statusBadge}</td>
127
+ <td>
128
+ <div class="row-actions">
129
+ <button class="icon-btn-sm" title="چاپ" onclick="window.InvoicesView.printInvoice('${inv.id}')">🖨️</button>
130
+ <button class="icon-btn-sm" title="ویرایش" onclick="window.InvoicesView.editInvoice('${inv.id}')">✏️</button>
131
+ ${inv.isPreInvoice ? `<button class="icon-btn-sm" title="تبدیل به فاکتور" onclick="window.InvoicesView.convertPreInvoice('${inv.id}')">✅</button>` : ''}
132
+ <button class="icon-btn-sm danger" title="حذف" onclick="window.InvoicesView.deleteInvoice('${inv.id}')">🗑️</button>
133
+ </div>
134
+ </td>
135
+ </tr>
136
+ `;
137
+ }).join('');
138
+
139
+ // خلاصه
140
+ const totalGrand = cache.invoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
141
+ const totalRemaining = cache.invoices.reduce((s, i) => s + (Number(i.remaining) || 0), 0);
142
+
143
+ return `
144
+ <div class="table-wrap">
145
+ <table>
146
+ <thead>
147
+ <tr>
148
+ <th style="width:120px">شماره</th>
149
+ <th style="width:110px">نوع</th>
150
+ <th>طرف حساب</th>
151
+ <th style="width:100px">تاریخ</th>
152
+ <th style="width:130px">مبلغ کل</th>
153
+ <th style="width:120px">پرداختشده</th>
154
+ <th style="width:120px">باقیمانده</th>
155
+ <th style="width:120px">وضعیت</th>
156
+ <th style="width:140px">عملیات</th>
157
+ </tr>
158
+ </thead>
159
+ <tbody>${rows}</tbody>
160
+ <tfoot>
161
+ <tr style="background:var(--bg);font-weight:700">
162
+ <td colspan="4" style="text-align:left">جمع کل:</td>
163
+ <td>${Formatters.money(totalGrand)}</td>
164
+ <td colspan="2" style="color:var(--danger)">${Formatters.money(totalRemaining)}</td>
165
+ <td colspan="2"></td>
166
+ </tr>
167
+ </tfoot>
168
+ </table>
169
+ </div>
170
+ `;
171
+ }
172
+
173
+ _onSearch(val) {
174
+ filter.search = val;
175
+ this.reload().then(() => {
176
+ document.getElementById('invoices-content').innerHTML = this.renderTable();
177
+ const input = document.getElementById('invSearch');
178
+ if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
179
+ });
180
+ }
181
+
182
+ _onFilter(key, val) {
183
+ filter[key] = val;
184
+ this.reloadAndRender();
185
+ }
186
+
187
+ _togglePreInvoice() {
188
+ filter.preInvoice = filter.preInvoice === true ? '' : true;
189
+ this.reloadAndRender().then(() => {
190
+ // بهروزرسانی دکمه
191
+ const btns = document.querySelectorAll('.toolbar .btn');
192
+ btns.forEach(b => {
193
+ if (b.textContent.includes('پیشفاکتور')) {
194
+ b.textContent = filter.preInvoice === true ? '📄 فقط پیشفاکتور' : '📄 نمایش پیشفاکتورها';
195
+ }
196
+ });
197
+ });
198
+ }
199
+
200
+ // ============================================================
201
+ // عملیات
202
+ // ============================================================
203
+ openNewInvoice() {
204
+ InvoiceFormView.open(null);
205
+ }
206
+
207
+ async editInvoice(id) {
208
+ InvoiceFormView.open(id);
209
+ }
210
+
211
+ async printInvoice(id) {
212
+ const { InvoicePrint } = await import('../utils/InvoicePrint.js');
213
+ InvoicePrint.openSettings(id);
214
+ }
215
+
216
+ async deleteInvoice(id) {
217
+ const inv = cache.invoices.find(i => i.id === id);
218
+ Modal.confirm({
219
+ title: 'حذف فاکتور',
220
+ message: `آیا از حذف فاکتور #${inv?.number || ''} مطمئن هستید؟ حرکات انبار مرتبط هم حذف میشوند.`,
221
+ confirmText: 'حذف',
222
+ danger: true,
223
+ onConfirm: async () => {
224
+ try {
225
+ await InvoiceController.delete(id);
226
+ Toast.success('فاکتور حذف شد');
227
+ await this.reloadAndRender();
228
+ } catch (err) {
229
+ Toast.error('خطا: ' + err.message);
230
+ }
231
+ }
232
+ });
233
+ }
234
+
235
+ async convertPreInvoice(id) {
236
+ Modal.confirm({
237
+ title: 'تبدیل پیشفاکتور',
238
+ message: 'آیا میخواهید این پیشفاکتور به فاکتور قطعی تبدیل شود؟ شمارهی رسمی صادر شده و حرکات انبار ثبت میشوند.',
239
+ confirmText: 'تبدیل کن',
240
+ onConfirm: async () => {
241
+ try {
242
+ const inv = await InvoiceController.convertPreInvoice(id);
243
+ Toast.success(`پیشفاکتور به فاکتور #${inv.number} تبدیل شد`);
244
+ await this.reloadAndRender();
245
+ } catch (err) {
246
+ Toast.error('خطا: ' + err.message);
247
+ }
248
+ }
249
+ });
250
+ }
251
+
252
+ _esc(s) {
253
+ if (!s) return '';
254
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
255
+ }
256
+}
257
+
258
+export const InvoicesView = new InvoicesViewImpl();
\ No newline at end of file