فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Phase 10: Contact ledger (debit/credit, balance, statement print)
Davood Mehraban committed
Sep 18, 2026 at 21:01 UTC
6abaf11793bb94a6c07e6a4d285b165c41baa73a
3 files changed
+568
-27
src/controllers/ContactController.js
+212
-17
@@ -40,8 +40,8 @@ class ContactControllerImpl {
40
const contact = {
41
id: StorageService.uid('contact_'),
42
ownerUserId: user.id,
43
- entityType: data.entityType || 'natural', // natural | legal
44
- role: data.role || 'customer', // customer | supplier | both
43
+ entityType: data.entityType || 'natural',
44
+ role: data.role || 'customer',
45
prefix: (data.prefix || '').trim(),
46
name: (data.name || '').trim(),
47
mobile: (data.mobile || '').trim(),
@@ -85,44 +85,45 @@ class ContactControllerImpl {
85
}
86
87
/**
88
- * محاسبهی مانده حساب از تراکنشها
89
- * فرمول: sum(invoices.grandTotal - receivedAmounts) - sum(payments)
88
+ * محاسبهی مانده حساب
89
*/
90
async getBalance(contactId) {
91
const user = Auth.current();
92
if (!user) return 0;
93
94
const invoices = await StorageService.getByOwner('invoices', user.id);
96
- const transactions = await StorageService.getByOwner('transactions', user.id);
95
+ const transactions = await StorageService.getByOwner('treasury', user.id);
96
98
- const contactInvoices = invoices.filter(i => i.contactId === contactId);
99
- const invoiceTotal = contactInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
97
+ const contactInvoices = invoices.filter(i => i.contactId === contactId && !i.isPreInvoice);
98
+ const invoiceTotal = contactInvoices.filter(i => i.kind === 'sale').reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
99
+ const returnTotal = contactInvoices.filter(i => i.kind === 'sale_return').reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
100
101
- // دریافت وجه از مشتری (receipt) مانده رو کم میکنه
102
- // پرداخت به تامینکننده (payment) مانده رو زیاد میکنه
103
- const contactTransactions = transactions.filter(t => t.contactId === contactId);
101
+ const contactTransactions = transactions.filter(t => t.recordType === 'transaction' && t.contactId === contactId);
102
let receipts = 0, payments = 0;
103
contactTransactions.forEach(t => {
104
if (t.type === 'receipt') receipts += Number(t.amount) || 0;
105
if (t.type === 'payment') payments += Number(t.amount) || 0;
106
});
107
110
- // مانده = فاکتورها - دریافتها + پرداختها
111
- return invoiceTotal - receipts + payments;
108
+ return (invoiceTotal - returnTotal) - receipts + payments;
109
}
110
111
async getBalanceMap(contactIds) {
112
const user = Auth.current();
113
const invoices = await StorageService.getByOwner('invoices', user.id);
117
- const transactions = await StorageService.getByOwner('transactions', user.id);
114
+ const transactions = await StorageService.getByOwner('treasury', user.id);
115
const map = {};
119
- contactIds.forEach(id => map[id] = { invoices: 0, receipts: 0, payments: 0 });
116
+ contactIds.forEach(id => map[id] = { invoices: 0, returns: 0, receipts: 0, payments: 0 });
117
118
invoices.forEach(inv => {
122
- if (map[inv.contactId]) map[inv.contactId].invoices += Number(inv.grandTotal) || 0;
119
+ if (!map[inv.contactId]) return;
120
+ if (inv.isPreInvoice) return;
121
+ if (inv.kind === 'sale') map[inv.contactId].invoices += Number(inv.grandTotal) || 0;
122
+ if (inv.kind === 'sale_return') map[inv.contactId].returns += Number(inv.grandTotal) || 0;
123
});
124
transactions.forEach(t => {
125
if (!map[t.contactId]) return;
126
+ if (t.recordType !== 'transaction') return;
127
if (t.type === 'receipt') map[t.contactId].receipts += Number(t.amount) || 0;
128
if (t.type === 'payment') map[t.contactId].payments += Number(t.amount) || 0;
129
});
@@ -130,11 +131,204 @@ class ContactControllerImpl {
131
const result = {};
132
contactIds.forEach(id => {
133
const m = map[id];
133
- result[id] = m.invoices - m.receipts + m.payments;
134
+ result[id] = (m.invoices - m.returns) - m.receipts + m.payments;
135
});
136
return result;
137
}
138
139
+ // ============================================================
140
+ // متدهای جدید فاز ۱۰: کارت حساب (Ledger)
141
+ // ============================================================
142
+
143
+ /**
144
+ * کارت حساب کامل یک شخص
145
+ * تمام تراکنشها (فاکتورها، برگشتها، دریافتها، پرداختها، چکها) با مانده تجمعی
146
+ */
147
+ async getLedger(contactId) {
148
+ const user = Auth.current();
149
+ if (!user) return { rows: [], totalDebit: 0, totalCredit: 0, finalBalance: 0 };
150
+
151
+ const [invoices, transactions, cheques] = await Promise.all([
152
+ StorageService.getByOwner('invoices', user.id),
153
+ StorageService.getByOwner('treasury', user.id),
154
+ StorageService.getByOwner('cheques', user.id)
155
+ ]);
156
+
157
+ const entries = [];
158
+
159
+ // ۱. فاکتورها
160
+ invoices.forEach(inv => {
161
+ if (inv.contactId !== contactId) return;
162
+ if (inv.isPreInvoice) return;
163
+
164
+ if (inv.kind === 'sale') {
165
+ entries.push({
166
+ date: inv.date,
167
+ dateISO: inv.createdAt || inv.date,
168
+ type: 'invoice_sale',
169
+ typeLabel: 'فاکتور فروش',
170
+ refNumber: inv.number,
171
+ refId: inv.id,
172
+ debit: Number(inv.grandTotal) || 0,
173
+ credit: 0,
174
+ note: `فاکتور #${inv.number}`
175
+ });
176
+ } else if (inv.kind === 'sale_return') {
177
+ entries.push({
178
+ date: inv.date,
179
+ dateISO: inv.createdAt || inv.date,
180
+ type: 'return_sale',
181
+ typeLabel: 'برگشت از فروش',
182
+ refNumber: inv.number,
183
+ refId: inv.id,
184
+ debit: 0,
185
+ credit: Number(inv.grandTotal) || 0,
186
+ note: `برگشت #${inv.number}`
187
+ });
188
+ } else if (inv.kind === 'purchase') {
189
+ entries.push({
190
+ date: inv.date,
191
+ dateISO: inv.createdAt || inv.date,
192
+ type: 'invoice_purchase',
193
+ typeLabel: 'فاکتور خرید',
194
+ refNumber: inv.number,
195
+ refId: inv.id,
196
+ debit: 0,
197
+ credit: Number(inv.grandTotal) || 0,
198
+ note: `خرید #${inv.number}`
199
+ });
200
+ } else if (inv.kind === 'purchase_return') {
201
+ entries.push({
202
+ date: inv.date,
203
+ dateISO: inv.createdAt || inv.date,
204
+ type: 'return_purchase',
205
+ typeLabel: 'برگشت از خرید',
206
+ refNumber: inv.number,
207
+ refId: inv.id,
208
+ debit: Number(inv.grandTotal) || 0,
209
+ credit: 0,
210
+ note: `برگشت خرید #${inv.number}`
211
+ });
212
+ }
213
+ });
214
+
215
+ // ۲. تراکنشها (دریافت/پرداخت)
216
+ transactions.forEach(t => {
217
+ if (t.recordType !== 'transaction') return;
218
+ if (t.contactId !== contactId) return;
219
+
220
+ if (t.type === 'receipt') {
221
+ entries.push({
222
+ date: t.date,
223
+ dateISO: t.createdAt || t.date,
224
+ type: 'receipt',
225
+ typeLabel: 'دریافت وجه',
226
+ refNumber: '',
227
+ refId: t.id,
228
+ debit: 0,
229
+ credit: Number(t.amount) || 0,
230
+ note: t.description || 'دریافت وجه'
231
+ });
232
+ } else if (t.type === 'payment') {
233
+ entries.push({
234
+ date: t.date,
235
+ dateISO: t.createdAt || t.date,
236
+ type: 'payment',
237
+ typeLabel: 'پرداخت وجه',
238
+ refNumber: '',
239
+ refId: t.id,
240
+ debit: Number(t.amount) || 0,
241
+ credit: 0,
242
+ note: t.description || 'پرداخت وجه'
243
+ });
244
+ }
245
+ });
246
+
247
+ // ۳. چکها (بهعنوان بدهی/طلب)
248
+ cheques.forEach(c => {
249
+ if (c.contactId !== contactId) return;
250
+ if (c.status === 'pending') {
251
+ // چک در جریان — یک یادداشت
252
+ if (c.direction === 'inbound') {
253
+ entries.push({
254
+ date: c.dueDate,
255
+ dateISO: c.createdAt || c.dueDate,
256
+ type: 'cheque_in',
257
+ typeLabel: 'چک دریافتی (در جریان)',
258
+ refNumber: c.sayadNumber || '',
259
+ refId: c.id,
260
+ debit: 0,
261
+ credit: 0,
262
+ note: `چک ${Formatters.toPersianDigits ? '' : ''}${c.amount ? '' : ''}`,
263
+ isCheque: true,
264
+ chequeAmount: Number(c.amount) || 0,
265
+ chequeDirection: 'inbound'
266
+ });
267
+ } else {
268
+ entries.push({
269
+ date: c.dueDate,
270
+ dateISO: c.createdAt || c.dueDate,
271
+ type: 'cheque_out',
272
+ typeLabel: 'چک پرداختی (در جریان)',
273
+ refNumber: c.sayadNumber || '',
274
+ refId: c.id,
275
+ debit: 0,
276
+ credit: 0,
277
+ note: `چک پرداختی`,
278
+ isCheque: true,
279
+ chequeAmount: Number(c.amount) || 0,
280
+ chequeDirection: 'outbound'
281
+ });
282
+ }
283
+ }
284
+ });
285
+
286
+ // مرتبسازی بر اساس تاریخ
287
+ entries.sort((a, b) => String(a.dateISO || a.date).localeCompare(String(b.dateISO || b.date)));
288
+
289
+ // محاسبه مانده تجمعی
290
+ let running = 0;
291
+ let totalDebit = 0, totalCredit = 0;
292
+ const rows = entries.map(e => {
293
+ running += (e.debit || 0) - (e.credit || 0);
294
+ totalDebit += (e.debit || 0);
295
+ totalCredit += (e.credit || 0);
296
+ return { ...e, balance: running };
297
+ });
298
+
299
+ return {
300
+ rows,
301
+ totalDebit,
302
+ totalCredit,
303
+ finalBalance: running
304
+ };
305
+ }
306
+
307
+ /**
308
+ * خلاصهی دفتر کل: جمع بدهکاران و بستانکاران
309
+ */
310
+ async getGlobalSummary() {
311
+ const user = Auth.current();
312
+ if (!user) return { totalDebt: 0, totalCredit: 0, debtorsCount: 0, creditorsCount: 0 };
313
+
314
+ const contacts = await StorageService.getByOwner('contacts', user.id);
315
+ const ids = contacts.map(c => c.id);
316
+ const balanceMap = await this.getBalanceMap(ids);
317
+
318
+ let totalDebt = 0, totalCredit = 0, debtorsCount = 0, creditorsCount = 0;
319
+ Object.values(balanceMap).forEach(b => {
320
+ if (b > 0) {
321
+ totalDebt += b;
322
+ debtorsCount++;
323
+ } else if (b < 0) {
324
+ totalCredit += Math.abs(b);
325
+ creditorsCount++;
326
+ }
327
+ });
328
+
329
+ return { totalDebt, totalCredit, debtorsCount, creditorsCount };
330
+ }
331
+
332
async getAllTags() {
333
const user = Auth.current();
334
const all = await StorageService.getByOwner('contacts', user.id);
@@ -144,4 +338,5 @@ class ContactControllerImpl {
338
}
339
}
340
147
-export const ContactController = new ContactControllerImpl();
\ No newline at end of file
341
+export const ContactController = new ContactControllerImpl();
342
+window.ContactController = ContactController;
\ No newline at end of file
src/views/ContactLedgerModal.js
new
+286
@@ -0,0 +1,286 @@
1
+// ============================================================
2
+// ContactLedgerModal — کارت حساب اشخاص (دفتر معین)
3
+// ============================================================
4
+
5
+import { ContactController } from '../controllers/ContactController.js';
6
+import { Modal } from '../core/Modal.js';
7
+import { Toast } from '../core/Toast.js';
8
+import { Formatters } from '../utils/Formatters.js';
9
+import { Jalali } from '../utils/Jalali.js';
10
+
11
+class ContactLedgerModalImpl {
12
+ async open(contactId) {
13
+ const contact = await ContactController.get(contactId);
14
+ if (!contact) { Toast.error('شخص یافت نشد'); return; }
15
+
16
+ const ledger = await ContactController.getLedger(contactId);
17
+
18
+ const body = this._buildBody(contact, ledger);
19
+ const footer = `
20
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>
21
+ <button class="btn" onclick="window.ContactLedgerModal._printLedger('${contactId}')">🖨️ چاپ صورتحساب</button>
22
+ `;
23
+
24
+ Modal.open({
25
+ title: `📒 کارت حساب: ${contact.name}`,
26
+ body,
27
+ footer,
28
+ size: 'lg'
29
+ });
30
+
31
+ window.__ledgerContactId = contactId;
32
+ }
33
+
34
+ _buildBody(contact, ledger) {
35
+ const balance = ledger.finalBalance;
36
+ const isDebtor = balance > 0;
37
+ const isCreditor = balance < 0;
38
+ const isSettled = balance === 0;
39
+
40
+ const balanceColor = isDebtor ? 'var(--danger)' : isCreditor ? 'var(--success)' : 'var(--text-muted)';
41
+ const balanceText = isSettled ? 'تسویه' :
42
+ isDebtor ? Formatters.money(balance) + ' بدهکار' :
43
+ Formatters.money(Math.abs(balance)) + ' بستانکار';
44
+
45
+ const entityLabel = contact.entityType === 'legal' ? 'حقوقی' : 'حقیقی';
46
+ const roleLabel = contact.role === 'customer' ? 'مشتری' :
47
+ contact.role === 'supplier' ? 'تامینکننده' : 'هر دو';
48
+
49
+ // ریز تراکنشها
50
+ const rowsHtml = ledger.rows.length === 0
51
+ ? `<tr><td colspan="7" style="text-align:center;padding:30px;color:var(--text-muted)">
52
+ <div style="font-size:40px;margin-bottom:8px;opacity:.4">📭</div>
53
+ هیچ تراکنشی برای این شخص ثبت نشده
54
+ </td></tr>`
55
+ : ledger.rows.map(r => {
56
+ const typeColors = {
57
+ invoice_sale: 'badge-success',
58
+ invoice_purchase: 'badge-warning',
59
+ return_sale: 'badge-danger',
60
+ return_purchase: 'badge-danger',
61
+ receipt: 'badge-info',
62
+ payment: 'badge-danger',
63
+ cheque_in: 'badge-muted',
64
+ cheque_out: 'badge-muted'
65
+ };
66
+ const typeCls = typeColors[r.type] || 'badge-muted';
67
+
68
+ let balanceHtml;
69
+ if (r.isCheque) {
70
+ balanceHtml = `<span style="color:var(--text-muted);font-size:11px">— (در جریان: ${Formatters.money(r.chequeAmount || 0)})</span>`;
71
+ } else {
72
+ const bal = r.balance;
73
+ balanceHtml = `<strong style="color:${bal > 0 ? 'var(--danger)' : bal < 0 ? 'var(--success)' : 'var(--text-muted)'}">${Formatters.money(Math.abs(bal))}</strong> <small style="color:var(--text-muted);font-size:9.5px">${bal > 0 ? 'بد' : bal < 0 ? 'بس' : ''}</small>`;
74
+ }
75
+
76
+ return `
77
+ <tr>
78
+ <td style="font-size:11.5px;width:110px">${Formatters.toPersianDigits(r.date || '—')}</td>
79
+ <td><span class="badge ${typeCls}" style="font-size:10px">${this._esc(r.typeLabel)}</span></td>
80
+ <td style="font-size:11.5px;color:var(--text-muted)">${r.refNumber ? '#' + Formatters.toPersianDigits(r.refNumber) : '—'}</td>
81
+ <td style="text-align:left;font-weight:600;color:var(--danger)">
82
+ ${r.debit > 0 ? Formatters.money(r.debit) : '—'}
83
+ </td>
84
+ <td style="text-align:left;font-weight:600;color:var(--success)">
85
+ ${r.credit > 0 ? Formatters.money(r.credit) : '—'}
86
+ </td>
87
+ <td style="text-align:left">${balanceHtml}</td>
88
+ <td style="font-size:11px;color:var(--text-muted)">${this._esc(r.note || '—')}</td>
89
+ </tr>
90
+ `;
91
+ }).join('');
92
+
93
+ const tags = (contact.tags || []).map(t => `<span class="badge badge-muted" style="font-size:10px;margin-left:4px">${this._esc(t)}</span>`).join('');
94
+
95
+ return `
96
+ <div style="background:linear-gradient(135deg,#f0fdfa,#eff6ff);border-radius:12px;padding:16px;margin-bottom:16px;border:1px solid #bfdbfe">
97
+ <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:12px">
98
+ <div style="flex:1;min-width:220px">
99
+ <div style="font-size:16px;font-weight:800;margin-bottom:4px">${this._esc(contact.name)}</div>
100
+ <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px">
101
+ <span class="badge ${contact.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">${entityLabel}</span>
102
+ <span class="badge badge-info" style="margin-right:4px">${roleLabel}</span>
103
+ ${tags}
104
+ </div>
105
+ ${contact.mobile ? `<div style="font-size:11.5px;color:var(--text-muted)">📱 ${Formatters.phone(contact.mobile)}</div>` : ''}
106
+ ${contact.nationalId ? `<div style="font-size:11.5px;color:var(--text-muted)">🆔 ${Formatters.toPersianDigits(contact.nationalId)}</div>` : ''}
107
+ </div>
108
+ <div style="text-align:left;min-width:200px">
109
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مانده حساب</div>
110
+ <div style="font-size:20px;font-weight:800;color:${balanceColor}">${balanceText}</div>
111
+ </div>
112
+ </div>
113
+ </div>
114
+
115
+ <div class="grid-kpi" style="margin-bottom:14px">
116
+ <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--danger)">
117
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">جمع بدهی (بدهکار)</div>
118
+ <div style="font-size:15px;font-weight:800;color:var(--danger)">${Formatters.money(ledger.totalDebit)}</div>
119
+ </div>
120
+ <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--success)">
121
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">جمع پرداختی (بستانکار)</div>
122
+ <div style="font-size:15px;font-weight:800;color:var(--success)">${Formatters.money(ledger.totalCredit)}</div>
123
+ </div>
124
+ <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--primary)">
125
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد تراکنش</div>
126
+ <div style="font-size:15px;font-weight:800;color:var(--primary)">${Formatters.number(ledger.rows.length)}</div>
127
+ </div>
128
+ </div>
129
+
130
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
131
+ <div style="font-size:12.5px;color:var(--text-muted)">ریز تراکنشها</div>
132
+ </div>
133
+
134
+ <div class="table-wrap" style="max-height:400px;overflow-y:auto">
135
+ <table style="min-width:750px">
136
+ <thead style="position:sticky;top:0;z-index:2">
137
+ <tr>
138
+ <th style="width:110px">تاریخ</th>
139
+ <th style="width:130px">نوع</th>
140
+ <th style="width:90px">مرجع</th>
141
+ <th style="width:130px;text-align:left">بدهکار</th>
142
+ <th style="width:130px;text-align:left">بستانکار</th>
143
+ <th style="width:160px;text-align:left">مانده</th>
144
+ <th>شرح</th>
145
+ </tr>
146
+ </thead>
147
+ <tbody>${rowsHtml}</tbody>
148
+ </table>
149
+ </div>
150
+ `;
151
+ }
152
+
153
+ // ============================================================
154
+ // چاپ صورتحساب
155
+ // ============================================================
156
+ async _printLedger(contactId) {
157
+ const contact = await ContactController.get(contactId);
158
+ if (!contact) return;
159
+ const ledger = await ContactController.getLedger(contactId);
160
+
161
+ const balance = ledger.finalBalance;
162
+ const isDebtor = balance > 0;
163
+ const isCreditor = balance < 0;
164
+ const balanceText = balance === 0 ? 'تسویه' :
165
+ isDebtor ? Formatters.money(balance) + ' بدهکار' :
166
+ Formatters.money(Math.abs(balance)) + ' بستانکار';
167
+
168
+ const rowsHtml = ledger.rows.map(r => {
169
+ let balanceCell;
170
+ if (r.isCheque) {
171
+ balanceCell = `در جریان: ${Formatters.money(r.chequeAmount || 0)}`;
172
+ } else {
173
+ const bal = r.balance;
174
+ balanceCell = `${Formatters.money(Math.abs(bal))} ${bal > 0 ? 'بد' : bal < 0 ? 'بس' : ''}`;
175
+ }
176
+
177
+ return `
178
+ <tr>
179
+ <td>${Formatters.toPersianDigits(r.date || '—')}</td>
180
+ <td>${this._esc(r.typeLabel)}</td>
181
+ <td>${r.refNumber ? '#' + Formatters.toPersianDigits(r.refNumber) : '—'}</td>
182
+ <td>${r.debit > 0 ? Formatters.money(r.debit) : '—'}</td>
183
+ <td>${r.credit > 0 ? Formatters.money(r.credit) : '—'}</td>
184
+ <td>${balanceCell}</td>
185
+ </tr>
186
+ `;
187
+ }).join('');
188
+
189
+ const printWin = window.open('', '_blank', 'width=900,height=700');
190
+ if (!printWin) { Toast.error('پاپآپ را فعال کنید'); return; }
191
+
192
+ printWin.document.write(`
193
+ <!DOCTYPE html>
194
+ <html lang="fa" dir="rtl">
195
+ <head>
196
+ <meta charset="UTF-8" />
197
+ <title>صورتحساب ${contact.name}</title>
198
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
199
+ <style>
200
+ @page { size: A4 portrait; margin: 10mm; }
201
+ * { box-sizing: border-box; margin: 0; padding: 0; }
202
+ html, body { direction: rtl; text-align: right; font-family: 'Vazirmatn FD', Tahoma, sans-serif; background: #fff; color: #000; }
203
+ body { padding: 10px; }
204
+ h1 { font-size: 18px; color: #0d9488; text-align: center; margin-bottom: 6px; }
205
+ .info { text-align: center; font-size: 12px; color: #64748b; margin-bottom: 16px; }
206
+ .contact-card { border: 1.5px solid #0d9488; border-radius: 10px; padding: 12px 16px; margin-bottom: 16px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
207
+ .contact-card .name { font-size: 14px; font-weight: 800; }
208
+ .contact-card .details { font-size: 11.5px; color: #64748b; line-height: 1.8; }
209
+ .contact-card .balance-box { text-align: left; }
210
+ .contact-card .balance-label { font-size: 11px; color: #64748b; }
211
+ .contact-card .balance-val { font-size: 16px; font-weight: 800; margin-top: 4px; color: ${isDebtor ? '#dc2626' : isCreditor ? '#059669' : '#64748b'}; }
212
+ .summary { display: flex; gap: 10px; margin-bottom: 16px; }
213
+ .summary > div { flex: 1; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; text-align: center; }
214
+ .summary .val { font-size: 16px; font-weight: 800; margin-top: 4px; }
215
+ .summary .lbl { font-size: 11px; color: #64748b; }
216
+ table { width: 100%; border-collapse: collapse; }
217
+ th, td { padding: 7px 9px; border: 1px solid #cbd5e1; text-align: right; font-size: 11px; }
218
+ th { background: #f1f5f9; font-weight: 700; }
219
+ .footer { margin-top: 20px; text-align: center; font-size: 10px; color: #94a3b8; padding-top: 10px; border-top: 1px dashed #cbd5e1; }
220
+ </style>
221
+ </head>
222
+ <body>
223
+ <h1>صورتحساب شخص</h1>
224
+ <div class="info">تاریخ چاپ: ${Jalali.today()}</div>
225
+
226
+ <div class="contact-card">
227
+ <div>
228
+ <div class="name">${this._esc(contact.name)}</div>
229
+ <div class="details">
230
+ ${contact.entityType === 'legal' ? 'شخص حقوقی' : 'شخص حقیقی'}
231
+ ${contact.nationalId ? ' | کد ملی/شناسه: ' + Formatters.toPersianDigits(contact.nationalId) : ''}
232
+ ${contact.mobile ? '<br>همراه: ' + Formatters.phone(contact.mobile) : ''}
233
+ ${contact.address ? '<br>نشانی: ' + this._esc(contact.address) : ''}
234
+ </div>
235
+ </div>
236
+ <div class="balance-box">
237
+ <div class="balance-label">مانده حساب نهایی</div>
238
+ <div class="balance-val">${balanceText}</div>
239
+ </div>
240
+ </div>
241
+
242
+ <div class="summary">
243
+ <div>
244
+ <div class="lbl">جمع بدهی</div>
245
+ <div class="val" style="color:#dc2626">${Formatters.money(ledger.totalDebit)}</div>
246
+ </div>
247
+ <div>
248
+ <div class="lbl">جمع پرداختی</div>
249
+ <div class="val" style="color:#059669">${Formatters.money(ledger.totalCredit)}</div>
250
+ </div>
251
+ <div>
252
+ <div class="lbl">تعداد تراکنش</div>
253
+ <div class="val" style="color:#0d9488">${Formatters.number(ledger.rows.length)}</div>
254
+ </div>
255
+ </div>
256
+
257
+ <table>
258
+ <thead>
259
+ <tr>
260
+ <th style="width:90px">تاریخ</th>
261
+ <th style="width:130px">نوع</th>
262
+ <th style="width:70px">مرجع</th>
263
+ <th style="text-align:left">بدهکار (ریال)</th>
264
+ <th style="text-align:left">بستانکار (ریال)</th>
265
+ <th style="text-align:left">مانده</th>
266
+ </tr>
267
+ </thead>
268
+ <tbody>${rowsHtml}</tbody>
269
+ </table>
270
+
271
+ <div class="footer">فینورا پرو - سامانه مدیریت کسبوکار</div>
272
+ </body>
273
+ </html>
274
+ `);
275
+ printWin.document.close();
276
+ setTimeout(() => { printWin.focus(); printWin.print(); }, 500);
277
+ }
278
+
279
+ _esc(s) {
280
+ if (!s) return '';
281
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
282
+ }
283
+}
284
+
285
+export const ContactLedgerModal = new ContactLedgerModalImpl();
286
+window.ContactLedgerModal = ContactLedgerModal;
\ No newline at end of file
src/views/ContactsView.js
+70
-10
@@ -6,11 +6,13 @@ import { ContactController } from '../controllers/ContactController.js';
6
import { Modal } from '../core/Modal.js';
7
import { Toast } from '../core/Toast.js';
8
import { Formatters } from '../utils/Formatters.js';
9
+import { ContactLedgerModal } from './ContactLedgerModal.js';
10
11
let currentSearch = '';
12
let currentRoleFilter = 'all';
13
let currentTypeFilter = 'all';
13
-let cache = { contacts: [], balances: {}, tags: [] };
14
+let currentBalanceFilter = ''; // '' | 'debtor' | 'creditor' | 'settled'
15
+let cache = { contacts: [], balances: {}, tags: [], globalSummary: {} };
16
17
class ContactsViewImpl {
18
async render() {
@@ -21,22 +23,57 @@ class ContactsViewImpl {
23
<p>مدیریت مشتریان، تامینکنندگان و طرفحسابها</p>
24
</div>
25
26
+ <div class="grid-kpi">
27
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)">
28
+ <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">📥</div>
29
+ <div style="flex:1">
30
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کل مطالبات</div>
31
+ <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(cache.globalSummary.totalDebt || 0)}</div>
32
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(cache.globalSummary.debtorsCount || 0)} بدهکار</div>
33
+ </div>
34
+ </div>
35
+
36
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)">
37
+ <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">📤</div>
38
+ <div style="flex:1">
39
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کل بدهی ما</div>
40
+ <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(cache.globalSummary.totalCredit || 0)}</div>
41
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(cache.globalSummary.creditorsCount || 0)} بستانکار</div>
42
+ </div>
43
+ </div>
44
+
45
+ <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
46
+ <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">👥</div>
47
+ <div style="flex:1">
48
+ <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد اشخاص</div>
49
+ <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(cache.contacts.length)}</div>
50
+ <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">ثبتشده در سیستم</div>
51
+ </div>
52
+ </div>
53
+ </div>
54
+
55
<div class="toolbar">
56
<div class="search-input-wrap">
57
<span class="icon">🔍</span>
58
<input type="text" class="form-control" id="contactSearch" placeholder="جستجو بر اساس نام، تلفن یا کد ملی..." value="${this._esc(currentSearch)}" oninput="window.ContactsView._onSearch(this.value)" />
59
</div>
29
- <select class="form-control" style="width:auto;min-width:140px" id="roleFilter" onchange="window.ContactsView._onFilterRole(this.value)">
60
+ <select class="form-control" style="width:auto;min-width:130px" id="roleFilter" onchange="window.ContactsView._onFilterRole(this.value)">
61
<option value="all" ${currentRoleFilter === 'all' ? 'selected' : ''}>همه نقشها</option>
62
<option value="customer" ${currentRoleFilter === 'customer' ? 'selected' : ''}>مشتری</option>
63
<option value="supplier" ${currentRoleFilter === 'supplier' ? 'selected' : ''}>تامینکننده</option>
64
<option value="both" ${currentRoleFilter === 'both' ? 'selected' : ''}>هر دو</option>
65
</select>
35
- <select class="form-control" style="width:auto;min-width:140px" id="typeFilter" onchange="window.ContactsView._onFilterType(this.value)">
66
+ <select class="form-control" style="width:auto;min-width:120px" id="typeFilter" onchange="window.ContactsView._onFilterType(this.value)">
67
<option value="all" ${currentTypeFilter === 'all' ? 'selected' : ''}>همه انواع</option>
68
<option value="natural" ${currentTypeFilter === 'natural' ? 'selected' : ''}>حقیقی</option>
69
<option value="legal" ${currentTypeFilter === 'legal' ? 'selected' : ''}>حقوقی</option>
70
</select>
71
+ <select class="form-control" style="width:auto;min-width:140px" onchange="window.ContactsView._onFilterBalance(this.value)">
72
+ <option value="" ${currentBalanceFilter === '' ? 'selected' : ''}>همه ماندهها</option>
73
+ <option value="debtor" ${currentBalanceFilter === 'debtor' ? 'selected' : ''}>فقط بدهکاران</option>
74
+ <option value="creditor" ${currentBalanceFilter === 'creditor' ? 'selected' : ''}>فقط بستانکاران</option>
75
+ <option value="settled" ${currentBalanceFilter === 'settled' ? 'selected' : ''}>تسویهشده</option>
76
+ </select>
77
<button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
78
</div>
79
@@ -53,6 +90,7 @@ class ContactsViewImpl {
90
cache.tags = await ContactController.getAllTags();
91
const ids = cache.contacts.map(c => c.id);
92
cache.balances = await ContactController.getBalanceMap(ids);
93
+ cache.globalSummary = await ContactController.getGlobalSummary();
94
}
95
96
renderTable() {
@@ -73,6 +111,15 @@ class ContactsViewImpl {
111
if (currentTypeFilter !== 'all') {
112
list = list.filter(c => c.entityType === currentTypeFilter);
113
}
114
+ if (currentBalanceFilter) {
115
+ list = list.filter(c => {
116
+ const b = cache.balances[c.id] || 0;
117
+ if (currentBalanceFilter === 'debtor') return b > 0;
118
+ if (currentBalanceFilter === 'creditor') return b < 0;
119
+ if (currentBalanceFilter === 'settled') return b === 0;
120
+ return true;
121
+ });
122
+ }
123
124
if (list.length === 0) {
125
return `
@@ -81,8 +128,8 @@ class ContactsViewImpl {
128
<tr><td>
129
<div class="empty-state">
130
<div class="icon">👥</div>
84
- <h3>هیچ شخصی ثبت نشده</h3>
85
- <p>اولین مشتری یا تامینکنندهی خود را اضافه کنید</p>
131
+ <h3>هیچ شخصی یافت نشد</h3>
132
+ <p>${currentSearch || currentRoleFilter !== 'all' || currentTypeFilter !== 'all' || currentBalanceFilter ? 'فیلترها را تغییر بده یا شخص جدید اضافه کن' : 'اولین مشتری یا تامینکنندهی خود را اضافه کنید'}</p>
133
<button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
134
</div>
135
</td></tr>
@@ -92,8 +139,8 @@ class ContactsViewImpl {
139
140
const rows = list.map(c => {
141
const balance = cache.balances[c.id] || 0;
95
- const isDebtor = balance > 0; // مشتری بدهکار
96
- const isCreditor = balance < 0; // ما بدهکاریم
142
+ const isDebtor = balance > 0;
143
+ const isCreditor = balance < 0;
144
const balanceColor = isDebtor ? 'var(--danger)' : isCreditor ? 'var(--success)' : 'var(--text-muted)';
145
const balanceText = balance === 0 ? 'تسویه' :
146
isDebtor ? Formatters.money(Math.abs(balance)) + ' بدهکار' :
@@ -127,6 +174,7 @@ class ContactsViewImpl {
174
<td style="font-weight:600;color:${balanceColor}">${balanceText}</td>
175
<td>
176
<div class="row-actions">
177
+ <button class="icon-btn-sm" title="کارت حساب" onclick="window.ContactsView.openLedger('${c.id}')">📒</button>
178
<button class="icon-btn-sm" title="ویرایش" onclick="window.ContactsView.editContact('${c.id}')">✏️</button>
179
<button class="icon-btn-sm danger" title="حذف" onclick="window.ContactsView.deleteContact('${c.id}')">🗑️</button>
180
</div>
@@ -146,7 +194,7 @@ class ContactsViewImpl {
194
<th style="width:150px">تماس</th>
195
<th style="width:130px">شناسه / کد ملی</th>
196
<th style="width:180px">مانده حساب</th>
149
- <th style="width:100px">عملیات</th>
197
+ <th style="width:130px">عملیات</th>
198
</tr>
199
</thead>
200
<tbody>${rows}</tbody>
@@ -172,6 +220,18 @@ class ContactsViewImpl {
220
document.getElementById('contacts-content').innerHTML = this.renderTable();
221
}
222
223
+ _onFilterBalance(val) {
224
+ currentBalanceFilter = val;
225
+ document.getElementById('contacts-content').innerHTML = this.renderTable();
226
+ }
227
+
228
+ // ============================================================
229
+ // کارت حساب
230
+ // ============================================================
231
+ openLedger(contactId) {
232
+ ContactLedgerModal.open(contactId);
233
+ }
234
+
235
// ============================================================
236
// فرم شخص
237
// ============================================================
@@ -320,7 +380,6 @@ class ContactsViewImpl {
380
const container = document.getElementById('tagsContainer');
381
if (container.querySelector('small')) container.innerHTML = '';
382
323
- // چک تکراری
383
const existing = Array.from(container.querySelectorAll('.tagCheckbox')).map(cb => cb.value);
384
if (existing.includes(tag)) {
385
Toast.warning('این برچسب قبلاً اضافه شده');
@@ -406,4 +465,5 @@ class ContactsViewImpl {
465
}
466
}
467
409
-export const ContactsView = new ContactsViewImpl();
\ No newline at end of file
468
+export const ContactsView = new ContactsViewImpl();
469
+window.ContactsView = ContactsView;
\ No newline at end of file