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

Fix: NumberInput, KeyboardShortcuts, editProduct, and phase 5 view fixes

Davood Mehraban committed Sep 18, 2026 at 09:41 UTC f88c909db47892c768b7e9b47ab40fb0cb9d7e27
13 files changed +2793 -70
src/controllers/ChequeController.js new
+200
@@ -0,0 +1,200 @@
1 +// ============================================================
2 +// ChequeController — منطق چک‌های دریافتی و پرداختی
3 +// ============================================================
4 +
5 +import { StorageService } from '../core/StorageService.js';
6 +import { Auth } from '../core/Auth.js';
7 +
8 +class ChequeControllerImpl {
9 + async getAll(filter = {}) {
10 + const user = Auth.current();
11 + if (!user) return [];
12 + let list = await StorageService.getByOwner('cheques', user.id);
13 +
14 + if (filter.direction) list = list.filter(c => c.direction === filter.direction);
15 + if (filter.status) list = list.filter(c => c.status === filter.status);
16 + if (filter.contactId) list = list.filter(c => c.contactId === filter.contactId);
17 + if (filter.search) {
18 + const q = String(filter.search).toLowerCase();
19 + list = list.filter(c =>
20 + (c.contactName || '').toLowerCase().includes(q) ||
21 + (c.sayadNumber || '').includes(q) ||
22 + (c.bankName || '').toLowerCase().includes(q) ||
23 + (c.chequeNumber || '').includes(q)
24 + );
25 + }
26 +
27 + return list.sort((a, b) => (a.dueDate || '').localeCompare(b.dueDate || ''));
28 + }
29 +
30 + async get(id) {
31 + return await StorageService.get('cheques', id);
32 + }
33 +
34 + async create(data) {
35 + const user = Auth.current();
36 + const cheque = {
37 + id: StorageService.uid('chq_'),
38 + ownerUserId: user.id,
39 + direction: data.direction || 'inbound', // inbound | outbound
40 + contactId: data.contactId || null,
41 + contactName: data.contactName || '',
42 + sayadNumber: (data.sayadNumber || '').trim(),
43 + chequeNumber: (data.chequeNumber || '').trim(),
44 + bankName: (data.bankName || '').trim(),
45 + branchName: (data.branchName || '').trim(),
46 + accountNumber: (data.accountNumber || '').trim(),
47 + holderName: (data.holderName || '').trim(),
48 + amount: Number(data.amount) || 0,
49 + issueDate: data.issueDate || this._todayJalali(),
50 + dueDate: data.dueDate || this._todayJalali(),
51 + status: data.status || 'pending', // pending | cleared | bounced | returned | spent
52 + refInvoiceId: data.refInvoiceId || null,
53 + refInvoiceNumber: data.refInvoiceNumber || null,
54 + description: (data.description || '').trim()
55 + };
56 + return await StorageService.put('cheques', cheque);
57 + }
58 +
59 + async update(id, data) {
60 + const existing = await StorageService.get('cheques', id);
61 + if (!existing) throw new Error('چک یافت نشد');
62 + const updated = {
63 + ...existing,
64 + direction: data.direction || existing.direction,
65 + contactId: data.contactId || null,
66 + contactName: data.contactName || '',
67 + sayadNumber: (data.sayadNumber || '').trim(),
68 + chequeNumber: (data.chequeNumber || '').trim(),
69 + bankName: (data.bankName || '').trim(),
70 + branchName: (data.branchName || '').trim(),
71 + accountNumber: (data.accountNumber || '').trim(),
72 + holderName: (data.holderName || '').trim(),
73 + amount: Number(data.amount) || 0,
74 + issueDate: data.issueDate || existing.issueDate,
75 + dueDate: data.dueDate || existing.dueDate,
76 + refInvoiceId: data.refInvoiceId || existing.refInvoiceId,
77 + refInvoiceNumber: data.refInvoiceNumber || existing.refInvoiceNumber,
78 + description: (data.description || '').trim()
79 + };
80 + return await StorageService.put('cheques', updated);
81 + }
82 +
83 + async changeStatus(id, status) {
84 + const cheque = await StorageService.get('cheques', id);
85 + if (!cheque) throw new Error('چک یافت نشد');
86 + cheque.status = status;
87 + cheque.statusChangedAt = new Date().toISOString();
88 + return await StorageService.put('cheques', cheque);
89 + }
90 +
91 + async delete(id) {
92 + return await StorageService.delete('cheques', id);
93 + }
94 +
95 + // چک‌های نزدیک سررسید (۷ روز آینده)
96 + async getUpcoming(days = 7) {
97 + const all = await this.getAll({ status: 'pending' });
98 + const today = new Date();
99 + const future = new Date();
100 + future.setDate(future.getDate() + days);
101 +
102 + return all.filter(c => {
103 + const due = this._jalaliToDate(c.dueDate);
104 + return due >= today && due <= future;
105 + });
106 + }
107 +
108 + // چک‌های سررسید گذشته (پرداخت‌نشده)
109 + async getOverdue() {
110 + const all = await this.getAll({ status: 'pending' });
111 + const today = new Date();
112 + return all.filter(c => {
113 + const due = this._jalaliToDate(c.dueDate);
114 + return due < today;
115 + });
116 + }
117 +
118 + async getStats() {
119 + const all = await this.getAll();
120 + const inbound = all.filter(c => c.direction === 'inbound');
121 + const outbound = all.filter(c => c.direction === 'outbound');
122 +
123 + return {
124 + total: all.length,
125 + inbound: inbound.length,
126 + outbound: outbound.length,
127 + pending: all.filter(c => c.status === 'pending').length,
128 + inboundAmount: inbound.reduce((s, c) => s + (Number(c.amount) || 0), 0),
129 + outboundAmount: outbound.reduce((s, c) => s + (Number(c.amount) || 0), 0),
130 + pendingAmount: all.filter(c => c.status === 'pending').reduce((s, c) => s + (Number(c.amount) || 0), 0)
131 + };
132 + }
133 +
134 + getStatusLabel(status) {
135 + return {
136 + pending: 'در جریان',
137 + cleared: 'وصول شده',
138 + bounced: 'برگشتی',
139 + returned: 'عودت داده شده',
140 + spent: 'خرج شده'
141 + }[status] || status;
142 + }
143 +
144 + getStatusClass(status) {
145 + return {
146 + pending: 'badge-warning',
147 + cleared: 'badge-success',
148 + bounced: 'badge-danger',
149 + returned: 'badge-muted',
150 + spent: 'badge-info'
151 + }[status] || 'badge-muted';
152 + }
153 +
154 + getDirectionLabel(direction) {
155 + return direction === 'inbound' ? 'دریافتی' : 'پرداختی';
156 + }
157 +
158 + _todayJalali() {
159 + const d = new Date();
160 + const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
161 + const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
162 + let jy = (gy <= 1600) ? 0 : 979;
163 + let gy2 = gy - (gy <= 1600 ? 621 : 1600);
164 + const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
165 + 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];
166 + jy += 33 * Math.floor(days / 12053);
167 + days %= 12053;
168 + jy += 4 * Math.floor(days / 1461);
169 + days %= 1461;
170 + if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
171 + const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
172 + const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
173 + return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
174 + }
175 +
176 + _jalaliToDate(jalaliStr) {
177 + if (!jalaliStr) return new Date();
178 + const [jy, jm, jd] = jalaliStr.split('/').map(Number);
179 + let gy = (jy <= 979) ? 621 : 1600;
180 + let jy2 = jy - (jy <= 979 ? 0 : 979);
181 + let days = (365 * jy2) + (Math.floor(jy2 / 33) * 8) + Math.floor(((jy2 % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
182 + gy += 400 * Math.floor(days / 146097);
183 + days %= 146097;
184 + if (days > 36524) {
185 + gy += 100 * Math.floor(--days / 36524);
186 + days %= 36524;
187 + if (days >= 365) days++;
188 + }
189 + gy += 4 * Math.floor(days / 1461);
190 + days %= 1461;
191 + if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
192 + let gd = days + 1;
193 + const sal_a = [0,31,((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31];
194 + let gm = 0;
195 + for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
196 + return new Date(gy, gm - 1, gd);
197 + }
198 +}
199 +
200 +export const ChequeController = new ChequeControllerImpl();
\ No newline at end of file
src/controllers/SettingsController.js new
+222
@@ -0,0 +1,222 @@
1 +// ============================================================
2 +// SettingsController — تنظیمات، بکاپ و بازیابی
3 +// ============================================================
4 +
5 +import { StorageService, STORES } from '../core/StorageService.js';
6 +import { Auth } from '../core/Auth.js';
7 +
8 +class SettingsControllerImpl {
9 + // ============================================================
10 + // بکاپ‌گیری
11 + // ============================================================
12 + async exportBackup() {
13 + const user = Auth.current();
14 + if (!user) throw new Error('کاربر یافت نشد');
15 +
16 + const backup = {
17 + app: 'Finora Pro',
18 + version: '0.1.0',
19 + exportedAt: new Date().toISOString(),
20 + exportedAtJalali: this._todayJalali(),
21 + user: {
22 + id: user.id,
23 + username: user.username,
24 + displayName: user.displayName
25 + },
26 + data: {}
27 + };
28 +
29 + // همه‌ی جدول‌ها رو خونده و توی بکاپ می‌ذاریم
30 + for (const store of STORES) {
31 + try {
32 + if (store === 'settings' || store === 'logs') {
33 + backup.data[store] = await StorageService.getAll(store);
34 + } else {
35 + backup.data[store] = await StorageService.getByOwner(store, user.id);
36 + }
37 + } catch (e) {
38 + console.warn(`Backup: store "${store}" skipped:`, e.message);
39 + backup.data[store] = [];
40 + }
41 + }
42 +
43 + return backup;
44 + }
45 +
46 + downloadBackup() {
47 + return this.exportBackup().then(backup => {
48 + const json = JSON.stringify(backup, null, 2);
49 + const blob = new Blob([json], { type: 'application/json;charset=utf-8' });
50 + const url = URL.createObjectURL(blob);
51 +
52 + const date = backup.exportedAtJalali.replace(/\//g, '-');
53 + const filename = `finora-backup-${date}-${Date.now()}.json`;
54 +
55 + const a = document.createElement('a');
56 + a.href = url;
57 + a.download = filename;
58 + document.body.appendChild(a);
59 + a.click();
60 + document.body.removeChild(a);
61 + URL.revokeObjectURL(url);
62 +
63 + return { filename, size: json.length, counts: this._countItems(backup.data) };
64 + });
65 + }
66 +
67 + _countItems(data) {
68 + const counts = {};
69 + Object.keys(data).forEach(k => {
70 + const arr = data[k];
71 + if (Array.isArray(arr) && arr.length > 0) counts[k] = arr.length;
72 + });
73 + return counts;
74 + }
75 +
76 + // ============================================================
77 + // بازیابی
78 + // ============================================================
79 + async importBackup(fileContent, options = {}) {
80 + const user = Auth.current();
81 + if (!user) throw new Error('کاربر یافت نشد');
82 +
83 + let backup;
84 + try {
85 + backup = typeof fileContent === 'string' ? JSON.parse(fileContent) : fileContent;
86 + } catch (e) {
87 + throw new Error('فایل بکاپ معتبر نیست (JSON نامعتبر)');
88 + }
89 +
90 + if (!backup || !backup.data) {
91 + throw new Error('ساختار فایل بکاپ نامعتبر است');
92 + }
93 +
94 + const mode = options.mode || 'merge'; // merge | replace
95 + const counts = { added: 0, updated: 0, skipped: 0 };
96 +
97 + for (const store of STORES) {
98 + const items = backup.data[store];
99 + if (!Array.isArray(items) || items.length === 0) continue;
100 +
101 + // برای settings/logs مستقیم؛ بقیه با ownerUserId
102 + for (const rawItem of items) {
103 + const item = { ...rawItem };
104 +
105 + // اگه مالک اصلی فرق داره، به کاربر فعلی نسبت بده
106 + if (item.ownerUserId && item.ownerUserId !== user.id && store !== 'settings' && store !== 'logs') {
107 + item.ownerUserId = user.id;
108 + item.id = StorageService.uid(item.id?.split('_')[0] + '_' || 'item_');
109 + }
110 +
111 + if (mode === 'replace') {
112 + await StorageService.put(store, item);
113 + counts.added++;
114 + } else {
115 + // merge: اگه id از قبل هست، skip کن
116 + const existing = await StorageService.get(store, item.id);
117 + if (existing) {
118 + counts.skipped++;
119 + } else {
120 + await StorageService.put(store, item);
121 + counts.added++;
122 + }
123 + }
124 + }
125 + }
126 +
127 + return counts;
128 + }
129 +
130 + async readFileAsText(file) {
131 + return new Promise((resolve, reject) => {
132 + const reader = new FileReader();
133 + reader.onload = (e) => resolve(e.target.result);
134 + reader.onerror = () => reject(new Error('خطا در خواندن فایل'));
135 + reader.readAsText(file);
136 + });
137 + }
138 +
139 + // ============================================================
140 + // پاک کردن همه‌ی داده‌ها
141 + // ============================================================
142 + async wipeAll() {
143 + await StorageService.clearAll();
144 + // sessionStorage و localStorage تمیز
145 + sessionStorage.clear();
146 + // دیتای آخرین route رو نگه‌دار، ولی بقیه رو پاک کن
147 + const lastRoute = localStorage.getItem('finora_pro_last_route');
148 + localStorage.clear();
149 + if (lastRoute) localStorage.setItem('finora_pro_last_route', lastRoute);
150 + return true;
151 + }
152 +
153 + // ============================================================
154 + // اطلاعات شرکت
155 + // ============================================================
156 + async getCompanyInfo() {
157 + const user = Auth.current();
158 + const list = await StorageService.getByOwner('companies', user.id);
159 + if (list.length > 0) return list[0];
160 + return {
161 + id: null,
162 + name: '',
163 + entityType: 'legal',
164 + nationalId: '',
165 + economicCode: '',
166 + regNumber: '',
167 + postalCode: '',
168 + phone: '',
169 + mobile: '',
170 + address: '',
171 + footer: ''
172 + };
173 + }
174 +
175 + async saveCompanyInfo(data) {
176 + const user = Auth.current();
177 + let company = await this.getCompanyInfo();
178 + const isNew = !company.id;
179 +
180 + const updated = {
181 + ...company,
182 + id: company.id || StorageService.uid('company_'),
183 + ownerUserId: user.id,
184 + name: (data.name || '').trim(),
185 + entityType: data.entityType || 'legal',
186 + nationalId: (data.nationalId || '').trim(),
187 + economicCode: (data.economicCode || '').trim(),
188 + regNumber: (data.regNumber || '').trim(),
189 + postalCode: (data.postalCode || '').trim(),
190 + phone: (data.phone || '').trim(),
191 + mobile: (data.mobile || '').trim(),
192 + address: (data.address || '').trim(),
193 + footer: (data.footer || '').trim()
194 + };
195 +
196 + await StorageService.put('companies', updated);
197 + return updated;
198 + }
199 +
200 + // ============================================================
201 + // Helpers
202 + // ============================================================
203 + _todayJalali() {
204 + const d = new Date();
205 + const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
206 + const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
207 + let jy = (gy <= 1600) ? 0 : 979;
208 + let gy2 = gy - (gy <= 1600 ? 621 : 1600);
209 + const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
210 + 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];
211 + jy += 33 * Math.floor(days / 12053);
212 + days %= 12053;
213 + jy += 4 * Math.floor(days / 1461);
214 + days %= 1461;
215 + if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
216 + const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
217 + const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
218 + return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
219 + }
220 +}
221 +
222 +export const SettingsController = new SettingsControllerImpl();
\ No newline at end of file
src/controllers/TreasuryController.js new
+265
@@ -0,0 +1,265 @@
1 +// ============================================================
2 +// TreasuryController — حساب‌ها، صندوق، بانک و تراکنش‌ها
3 +// ============================================================
4 +
5 +import { StorageService } from '../core/StorageService.js';
6 +import { Auth } from '../core/Auth.js';
7 +
8 +class TreasuryControllerImpl {
9 + // ============================================================
10 + // حساب‌ها (Accounts)
11 + // ============================================================
12 + async getAccounts(filter = {}) {
13 + const user = Auth.current();
14 + if (!user) return [];
15 + let list = await StorageService.getByOwner('treasury', user.id);
16 +
17 + // فقط حساب‌ها (نه تراکنش‌ها) — با تفکیک recordType
18 + list = list.filter(a => (a.recordType || 'account') === 'account');
19 +
20 + if (filter.type) list = list.filter(a => a.type === filter.type);
21 + if (filter.search) {
22 + const q = String(filter.search).toLowerCase();
23 + list = list.filter(a =>
24 + (a.name || '').toLowerCase().includes(q) ||
25 + (a.accountNumber || '').includes(q) ||
26 + (a.bankName || '').toLowerCase().includes(q)
27 + );
28 + }
29 + return list.sort((a, b) => {
30 + if (a.isDefault && !b.isDefault) return -1;
31 + if (!a.isDefault && b.isDefault) return 1;
32 + return (a.name || '').localeCompare(b.name || '', 'fa');
33 + });
34 + }
35 +
36 + async getAccount(id) {
37 + return await StorageService.get('treasury', id);
38 + }
39 +
40 + async createAccount(data) {
41 + const user = Auth.current();
42 + const account = {
43 + id: StorageService.uid('acc_'),
44 + recordType: 'account',
45 + ownerUserId: user.id,
46 + type: data.type || 'cashbox', // cashbox | bank | pos
47 + name: (data.name || '').trim(),
48 + accountNumber: (data.accountNumber || '').trim(),
49 + cardNumber: (data.cardNumber || '').trim(),
50 + sheba: (data.sheba || '').trim(),
51 + bankName: (data.bankName || '').trim(),
52 + branchName: (data.branchName || '').trim(),
53 + branchCode: (data.branchCode || '').trim(),
54 + ownerName: (data.ownerName || '').trim(),
55 + color: data.color || '#0d9488',
56 + initialBalance: Number(data.initialBalance) || 0,
57 + isDefault: false,
58 + isActive: true
59 + };
60 +
61 + // اگه اولین حسابه، پیش‌فرض بشه
62 + const existing = await this.getAccounts();
63 + if (existing.length === 0) account.isDefault = true;
64 +
65 + return await StorageService.put('treasury', account);
66 + }
67 +
68 + async updateAccount(id, data) {
69 + const existing = await StorageService.get('treasury', id);
70 + if (!existing) throw new Error('حساب یافت نشد');
71 + const updated = {
72 + ...existing,
73 + type: data.type || existing.type,
74 + name: (data.name || '').trim(),
75 + accountNumber: (data.accountNumber || '').trim(),
76 + cardNumber: (data.cardNumber || '').trim(),
77 + sheba: (data.sheba || '').trim(),
78 + bankName: (data.bankName || '').trim(),
79 + branchName: (data.branchName || '').trim(),
80 + branchCode: (data.branchCode || '').trim(),
81 + ownerName: (data.ownerName || '').trim(),
82 + color: data.color || existing.color,
83 + initialBalance: Number(data.initialBalance) || 0
84 + };
85 + return await StorageService.put('treasury', updated);
86 + }
87 +
88 + async deleteAccount(id) {
89 + // چک کن تراکنشی وابسته نباشه
90 + const user = Auth.current();
91 + const all = await StorageService.getByOwner('treasury', user.id);
92 + const related = all.filter(t => t.recordType === 'transaction' && (t.fromAccountId === id || t.toAccountId === id));
93 + if (related.length > 0) {
94 + throw new Error('این حساب تراکنش دارد. اول تراکنش‌ها را حذف کنید.');
95 + }
96 + return await StorageService.delete('treasury', id);
97 + }
98 +
99 + async setDefaultAccount(id) {
100 + const user = Auth.current();
101 + const all = await StorageService.getByOwner('treasury', user.id);
102 + for (const a of all.filter(x => x.recordType === 'account')) {
103 + a.isDefault = a.id === id;
104 + await StorageService.put('treasury', a);
105 + }
106 + }
107 +
108 + // ============================================================
109 + // محاسبه‌ی موجودی
110 + // ============================================================
111 + async getAccountBalance(accountId) {
112 + const user = Auth.current();
113 + const all = await StorageService.getByOwner('treasury', user.id);
114 + const account = all.find(a => a.id === accountId);
115 + if (!account) return 0;
116 +
117 + let balance = Number(account.initialBalance) || 0;
118 +
119 + // تراکنش‌ها
120 + const transactions = all.filter(t => t.recordType === 'transaction');
121 + transactions.forEach(t => {
122 + const amount = Number(t.amount) || 0;
123 + if (t.type === 'receipt') {
124 + // دریافت: به حساب مقصد اضافه می‌شه
125 + if (t.toAccountId === accountId) balance += amount;
126 + } else if (t.type === 'payment') {
127 + // پرداخت: از حساب مبدأ کم می‌شه
128 + if (t.fromAccountId === accountId) balance -= amount;
129 + } else if (t.type === 'transfer') {
130 + // انتقال: دو تا رکورد داره
131 + if (t.fromAccountId === accountId) balance -= amount;
132 + if (t.toAccountId === accountId) balance += amount;
133 + }
134 + });
135 +
136 + return balance;
137 + }
138 +
139 + async getBalanceMap() {
140 + const user = Auth.current();
141 + const all = await StorageService.getByOwner('treasury', user.id);
142 + const accounts = all.filter(a => a.recordType === 'account');
143 + const transactions = all.filter(t => t.recordType === 'transaction');
144 + const map = {};
145 +
146 + accounts.forEach(a => map[a.id] = Number(a.initialBalance) || 0);
147 +
148 + transactions.forEach(t => {
149 + const amount = Number(t.amount) || 0;
150 + if (t.type === 'receipt' && t.toAccountId && map[t.toAccountId] !== undefined) {
151 + map[t.toAccountId] += amount;
152 + } else if (t.type === 'payment' && t.fromAccountId && map[t.fromAccountId] !== undefined) {
153 + map[t.fromAccountId] -= amount;
154 + } else if (t.type === 'transfer') {
155 + if (t.fromAccountId && map[t.fromAccountId] !== undefined) map[t.fromAccountId] -= amount;
156 + if (t.toAccountId && map[t.toAccountId] !== undefined) map[t.toAccountId] += amount;
157 + }
158 + });
159 +
160 + return map;
161 + }
162 +
163 + async getTotalBalance() {
164 + const map = await this.getBalanceMap();
165 + return Object.values(map).reduce((s, v) => s + v, 0);
166 + }
167 +
168 + // ============================================================
169 + // تراکنش‌ها
170 + // ============================================================
171 + async getTransactions(filter = {}) {
172 + const user = Auth.current();
173 + if (!user) return [];
174 + let list = await StorageService.getByOwner('treasury', user.id);
175 + list = list.filter(t => t.recordType === 'transaction');
176 +
177 + if (filter.type) list = list.filter(t => t.type === filter.type);
178 + if (filter.accountId) {
179 + list = list.filter(t => t.fromAccountId === filter.accountId || t.toAccountId === filter.accountId);
180 + }
181 + if (filter.contactId) list = list.filter(t => t.contactId === filter.contactId);
182 + if (filter.dateFrom) list = list.filter(t => (t.date || '') >= filter.dateFrom);
183 + if (filter.dateTo) list = list.filter(t => (t.date || '') <= filter.dateTo);
184 + if (filter.search) {
185 + const q = String(filter.search).toLowerCase();
186 + list = list.filter(t =>
187 + (t.contactName || '').toLowerCase().includes(q) ||
188 + (t.description || '').toLowerCase().includes(q) ||
189 + String(t.refInvoiceNumber || '').includes(q)
190 + );
191 + }
192 +
193 + return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
194 + }
195 +
196 + async getTransaction(id) {
197 + return await StorageService.get('treasury', id);
198 + }
199 +
200 + async createTransaction(data) {
201 + const user = Auth.current();
202 + const tx = {
203 + id: StorageService.uid('tx_'),
204 + recordType: 'transaction',
205 + ownerUserId: user.id,
206 + type: data.type, // receipt | payment | transfer
207 + date: data.date || this._todayJalali(),
208 + amount: Number(data.amount) || 0,
209 + fromAccountId: data.fromAccountId || null,
210 + toAccountId: data.toAccountId || null,
211 + contactId: data.contactId || null,
212 + contactName: data.contactName || '',
213 + refInvoiceId: data.refInvoiceId || null,
214 + refInvoiceNumber: data.refInvoiceNumber || null,
215 + method: data.method || 'cash', // cash | card | cheque | transfer
216 + description: (data.description || '').trim(),
217 + chequeNumber: data.chequeNumber || ''
218 + };
219 + return await StorageService.put('treasury', tx);
220 + }
221 +
222 + async deleteTransaction(id) {
223 + return await StorageService.delete('treasury', id);
224 + }
225 +
226 + // ============================================================
227 + // Helpers
228 + // ============================================================
229 + getTypeLabel(type) {
230 + return { receipt: 'دریافت', payment: 'پرداخت', transfer: 'انتقال' }[type] || type;
231 + }
232 +
233 + getMethodLabel(method) {
234 + return {
235 + cash: 'نقدی',
236 + card: 'کارت',
237 + cheque: 'چک',
238 + transfer: 'انتقال بانکی'
239 + }[method] || method;
240 + }
241 +
242 + getAccountTypeLabel(type) {
243 + return { cashbox: 'صندوق', bank: 'بانک', pos: 'پوز' }[type] || type;
244 + }
245 +
246 + _todayJalali() {
247 + const d = new Date();
248 + const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
249 + const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
250 + let jy = (gy <= 1600) ? 0 : 979;
251 + let gy2 = gy - (gy <= 1600 ? 621 : 1600);
252 + const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
253 + 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];
254 + jy += 33 * Math.floor(days / 12053);
255 + days %= 12053;
256 + jy += 4 * Math.floor(days / 1461);
257 + days %= 1461;
258 + if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
259 + const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
260 + const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
261 + return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
262 + }
263 +}
264 +
265 +export const TreasuryController = new TreasuryControllerImpl();
\ No newline at end of file
src/core/KeyboardShortcuts.js new
+180
@@ -0,0 +1,180 @@
1 +// ============================================================
2 +// KeyboardShortcuts — میانبرهای صفحه‌کلید و کلیدهای ترکیبی
3 +// ============================================================
4 +
5 +import { Toast } from './Toast.js';
6 +
7 +const STORAGE_KEY = 'finora_pro_shortcuts';
8 +
9 +const DEFAULTS = {
10 + enabled: true,
11 + enterConfirms: true,
12 + escapeCloses: true,
13 + ctrlSaves: true,
14 + plusMinusZeros: true,
15 + plusZeros: 3,
16 + minusZeros: 2
17 +};
18 +
19 +class KeyboardShortcutsImpl {
20 + constructor() {
21 + this.settings = { ...DEFAULTS };
22 + this._initialized = false;
23 + }
24 +
25 + init() {
26 + if (this._initialized) return;
27 + this._initialized = true;
28 + this.loadSettings();
29 + // capture: true یعنی قبل از هر listener دیگه‌ای این صدا زده می‌شه
30 + document.addEventListener('keydown', (e) => this._onKeyDown(e), true);
31 + // بعضی مرورگرها (مثل فایرفاکس) در مرحله‌ی keypress هم چک می‌کنن
32 + document.addEventListener('keypress', (e) => this._onKeyPress(e), true);
33 + }
34 +
35 + loadSettings() {
36 + try {
37 + const saved = localStorage.getItem(STORAGE_KEY);
38 + if (saved) {
39 + const parsed = JSON.parse(saved);
40 + Object.assign(this.settings, parsed);
41 + }
42 + } catch (e) {
43 + console.warn('KeyboardShortcuts: load failed:', e);
44 + }
45 + }
46 +
47 + saveSettings(newSettings) {
48 + Object.assign(this.settings, newSettings);
49 + localStorage.setItem(STORAGE_KEY, JSON.stringify(this.settings));
50 + }
51 +
52 + resetSettings() {
53 + this.settings = { ...DEFAULTS };
54 + localStorage.setItem(STORAGE_KEY, JSON.stringify(this.settings));
55 + }
56 +
57 + // چک می‌کنه که آیا Ctrl+S هست یا نه — مستقل از زبان کیبورد
58 + _isCtrlS(e) {
59 + const hasCtrl = e.ctrlKey || e.metaKey;
60 + if (!hasCtrl) return false;
61 + // چندین روش چک (چون زبان کیبورد ممکنه فرق کنه)
62 + if (e.code === 'KeyS') return true; // مستقل از زبان — مطمئن‌ترین
63 + if (e.key === 's' || e.key === 'S') return true; // انگلیسی
64 + if (e.keyCode === 83) return true; // legacy
65 + return false;
66 + }
67 +
68 + _onKeyDown(e) {
69 + if (!this.settings.enabled) return;
70 +
71 + const modal = document.querySelector('.modal-backdrop.active') ||
72 + document.querySelector('.modal-backdrop');
73 +
74 + // ────── Ctrl+S / Cmd+S ──────
75 + if (this._isCtrlS(e)) {
76 + e.preventDefault();
77 + e.stopPropagation();
78 + e.returnValue = false;
79 + if (this.settings.ctrlSaves && modal) {
80 + this._clickPrimaryButton(modal);
81 + }
82 + return false;
83 + }
84 +
85 + // ────── Ctrl+Enter → تأیید از هر جا ──────
86 + if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
87 + if (this.settings.enterConfirms && modal) {
88 + e.preventDefault();
89 + this._clickPrimaryButton(modal);
90 + }
91 + return;
92 + }
93 +
94 + // ────── Escape → بستن مودال ──────
95 + if (e.key === 'Escape' && this.settings.escapeCloses) {
96 + if (modal) {
97 + e.preventDefault();
98 + this._clickCloseButton(modal);
99 + }
100 + return;
101 + }
102 +
103 + // ────── Enter → تأیید (فقط داخل مودال، نه در textarea) ──────
104 + if (e.key === 'Enter' && !e.shiftKey && this.settings.enterConfirms) {
105 + const active = document.activeElement;
106 + if (active && active.tagName === 'TEXTAREA') return;
107 + if (modal) {
108 + e.preventDefault();
109 + this._clickPrimaryButton(modal);
110 + }
111 + return;
112 + }
113 +
114 + // ────── کلیدهای + و - توی فیلدهای مبلغ ──────
115 + if (this.settings.plusMinusZeros) {
116 + const active = document.activeElement;
117 + if (active && active.tagName === 'INPUT' && active.getAttribute('data-money') === '1') {
118 + if (e.key === '+') {
119 + e.preventDefault();
120 + this._applyMultiplier(active, this.settings.plusZeros);
121 + return;
122 + }
123 + if (e.key === '-' || e.key === '−') {
124 + e.preventDefault();
125 + this._applyMultiplier(active, this.settings.minusZeros);
126 + return;
127 + }
128 + }
129 + }
130 + }
131 +
132 + // برای فایرفاکس که در keypress event چک می‌کنه
133 + _onKeyPress(e) {
134 + if (!this.settings.enabled) return;
135 + if (this._isCtrlS(e)) {
136 + e.preventDefault();
137 + e.stopPropagation();
138 + return false;
139 + }
140 + }
141 +
142 + _applyMultiplier(input, zeros) {
143 + const currentRaw = String(input.value || '').replace(/[^\d]/g, '');
144 + if (!currentRaw) return;
145 +
146 + const current = Number(currentRaw);
147 + if (!isFinite(current) || current === 0) return;
148 +
149 + const multiplier = Math.pow(10, zeros);
150 + let newVal = current * multiplier;
151 + if (newVal > Number.MAX_SAFE_INTEGER) newVal = Number.MAX_SAFE_INTEGER;
152 +
153 + input.value = newVal.toLocaleString('en-US');
154 + input.dispatchEvent(new Event('input', { bubbles: true }));
155 +
156 + Toast.info(`× ${multiplier.toLocaleString('en-US')} → ${newVal.toLocaleString('fa-IR')}`, 'ضریب اعمال شد');
157 + }
158 +
159 + _clickPrimaryButton(modal) {
160 + const btns = modal.querySelectorAll('.modal-footer .btn, .modal-card .btn');
161 + for (let i = btns.length - 1; i >= 0; i--) {
162 + const b = btns[i];
163 + if (b.classList.contains('btn-secondary')) continue;
164 + if (b.classList.contains('btn-danger')) continue;
165 + if (b.disabled) continue;
166 + b.click();
167 + return;
168 + }
169 + }
170 +
171 + _clickCloseButton(modal) {
172 + const closeBtn = modal.querySelector('.modal-close');
173 + if (closeBtn) { closeBtn.click(); return; }
174 + const cancelBtn = modal.querySelector('.modal-footer .btn-secondary');
175 + if (cancelBtn) cancelBtn.click();
176 + }
177 +}
178 +
179 +export const KeyboardShortcuts = new KeyboardShortcutsImpl();
180 +window.KeyboardShortcuts = KeyboardShortcuts;
\ No newline at end of file
src/core/StorageService.js
+2 -1
@@ -3,11 +3,12 @@
3 // ============================================================
4
5 const DB_NAME = 'finora_pro_db';
6 -const DB_VERSION = 2;
6 +const DB_VERSION = 3;
7
8 const STORES = [
9 'users', 'companies', 'contacts', 'products',
10 'units', 'categories',
11 + 'treasury',
12 'invoices', 'invoice_items', 'stock_movements',
13 'transactions', 'cheques', 'expenses',
14 'settings', 'logs'
src/main.js
+37 -27
@@ -2,6 +2,9 @@
2 // Finora Pro — Main Entry Point
3 // ============================================================
4
5 +import { SettingsView } from './views/SettingsView.js';
6 +import { ChequesView } from './views/ChequesView.js';
7 +import { TreasuryView } from './views/TreasuryView.js';
8 import { InvoicesView } from './views/InvoicesView.js';
9 import { ContactsView } from './views/ContactsView.js';
10 import { ProductsView } from './views/ProductsView.js';
@@ -11,15 +14,18 @@ import { Toast } from './core/Toast.js';
14 import { Router } from './core/Router.js';
15 import { Auth } from './core/Auth.js';
16 import { EventBus } from './core/EventBus.js';
17 +import { Modal } from './core/Modal.js';
18 +import { KeyboardShortcuts } from './core/KeyboardShortcuts.js';
19 import { Formatters } from './utils/Formatters.js';
20 import { Jalali } from './utils/Jalali.js';
21 import { numberToWords } from './utils/NumberToWords.js';
22 +import { NumberInput } from './utils/NumberInput.js';
23
24 const FINORA = {
25 version: '0.1.0',
26 Storage: StorageService,
21 - Theme, Toast, Router, Auth, EventBus,
22 - Utils: { Formatters, Jalali, numberToWords }
27 + Theme, Toast, Router, Auth, EventBus, Modal, KeyboardShortcuts,
28 + Utils: { Formatters, Jalali, numberToWords, NumberInput }
29 };
30 window.FINORA = FINORA;
31
@@ -102,25 +108,37 @@ function registerRoutes() {
108 });
109
110 Router.register('invoices', {
105 - title: 'فاکتورها',
106 - render: () => InvoicesView.render(),
107 - onMount: () => InvoicesView.onMount()
108 -});
111 + title: 'فاکتورها',
112 + render: () => InvoicesView.render(),
113 + onMount: () => InvoicesView.onMount()
114 + });
115 Router.register('products', {
110 - title: 'کالا و انبار',
111 - render: () => ProductsView.render(),
112 - onMount: () => ProductsView.onMount()
113 -});
116 + title: 'کالا و انبار',
117 + render: () => ProductsView.render(),
118 + onMount: () => ProductsView.onMount()
119 + });
120 Router.register('contacts', {
115 - title: 'اشخاص',
116 - render: () => ContactsView.render(),
117 - onMount: () => ContactsView.onMount()
118 -});
119 - Router.register('treasury', { title: 'خزانه و بانک', render: placeholder('خزانه و بانک', 6) });
120 - Router.register('cheques', { title: 'چک‌ها', render: placeholder('چک‌ها', 6) });
121 + title: 'اشخاص',
122 + render: () => ContactsView.render(),
123 + onMount: () => ContactsView.onMount()
124 + });
125 + Router.register('treasury', {
126 + title: 'خزانه و بانک',
127 + render: () => TreasuryView.render(),
128 + onMount: () => TreasuryView.onMount()
129 + });
130 + Router.register('cheques', {
131 + title: 'چک‌ها',
132 + render: () => ChequesView.render(),
133 + onMount: () => ChequesView.onMount()
134 + });
135 Router.register('expenses', { title: 'هزینه و درآمد', render: placeholder('هزینه و درآمد', 6) });
136 Router.register('reports', { title: 'گزارش سود و زیان', render: placeholder('گزارش سود و زیان', 7) });
123 - Router.register('settings', { title: 'تنظیمات', render: placeholder('تنظیمات', 9) });
137 + Router.register('settings', {
138 + title: 'تنظیمات',
139 + render: () => SettingsView.render(),
140 + onMount: () => SettingsView.onMount()
141 + });
142 }
143
144 function getGreeting() {
@@ -180,27 +198,19 @@ function setupSidebar() {
198 }
199 }
200
183 -function setupKeyboard() {
184 - document.addEventListener('keydown', e => {
185 - if ((e.ctrlKey || e.metaKey) && e.key === 's') {
186 - e.preventDefault();
187 - Toast.info('میانبر ذخیره در فازهای بعدی فعال می‌شود');
188 - }
189 - });
190 -}
191 -
201 async function bootstrap() {
202 try {
203 console.log('🚀 Finora Pro v' + FINORA.version);
204
205 Theme.init();
206 + NumberInput.init();
207 + KeyboardShortcuts.init();
208 await StorageService.init();
209 await Auth.init();
210
211 registerRoutes();
212 Router.init('pageContent');
213 setupSidebar();
203 - setupKeyboard();
214
215 EventBus.on('route:changed', () => {
216 updateHeader();
src/styles/main.css
+100
@@ -547,4 +547,104 @@ textarea.form-control { min-height: 80px; resize: vertical; }
547 .print-tpl-card.active {
548 border-color: var(--primary);
549 background: var(--primary-light);
550 +}
551 +/* ===== Account Cards ===== */
552 +.account-grid {
553 + display: grid;
554 + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
555 + gap: 14px;
556 + margin-bottom: 20px;
557 +}
558 +.account-card {
559 + background: var(--card-bg);
560 + border: 1px solid var(--border);
561 + border-radius: var(--radius);
562 + padding: 18px;
563 + transition: all .15s;
564 + box-shadow: var(--shadow-sm);
565 +}
566 +.account-card:hover {
567 + box-shadow: var(--shadow-md);
568 + transform: translateY(-2px);
569 +}
570 +/* ===== Settings Cards ===== */
571 +.settings-grid {
572 + display: grid;
573 + grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
574 + gap: 16px;
575 + margin-bottom: 20px;
576 +}
577 +.settings-card {
578 + padding: 20px;
579 + margin: 0;
580 +}
581 +.settings-card-header {
582 + display: flex;
583 + gap: 14px;
584 + align-items: flex-start;
585 + margin-bottom: 16px;
586 +}
587 +.settings-card-icon {
588 + width: 46px;
589 + height: 46px;
590 + border-radius: 12px;
591 + background: linear-gradient(135deg, var(--primary), var(--primary-dark));
592 + color: #fff;
593 + display: flex;
594 + align-items: center;
595 + justify-content: center;
596 + font-size: 22px;
597 + flex-shrink: 0;
598 +}
599 +.settings-card-title {
600 + font-size: 15px;
601 + font-weight: 700;
602 + margin-bottom: 4px;
603 +}
604 +.settings-card-desc {
605 + font-size: 12px;
606 + color: var(--text-muted);
607 + line-height: 1.6;
608 +}
609 +.company-preview {
610 + padding: 12px 14px;
611 + background: var(--bg);
612 + border-radius: 10px;
613 + margin-bottom: 14px;
614 + border-right: 3px solid var(--primary);
615 +}
616 +.empty-mini {
617 + padding: 20px;
618 + text-align: center;
619 + background: var(--bg);
620 + border-radius: 10px;
621 + font-size: 12.5px;
622 + color: var(--text-muted);
623 + margin-bottom: 14px;
624 +}
625 +.backup-warning {
626 + padding: 10px 14px;
627 + background: #fef3c7;
628 + border: 1px solid #fcd34d;
629 + border-radius: 8px;
630 + font-size: 12px;
631 + color: #78350f;
632 + line-height: 1.7;
633 + margin-bottom: 4px;
634 +}
635 +[data-theme="dark"] .backup-warning {
636 + background: #422006;
637 + border-color: #92400e;
638 + color: #fed7aa;
639 +}
640 +.stats-grid {
641 + display: grid;
642 + grid-template-columns: repeat(3, 1fr);
643 + gap: 10px;
644 +}
645 +.stat-mini {
646 + text-align: center;
647 + padding: 12px 6px;
648 + background: var(--bg);
649 + border-radius: 10px;
650 }
\ No newline at end of file
src/utils/NumberInput.js new
+126
@@ -0,0 +1,126 @@
1 +// ============================================================
2 +// NumberInput — جداکننده‌ی هزارگان زنده برای input ها
3 +// ============================================================
4 +
5 +export const NumberInput = {
6 + // فرمت کردن عدد → "1,234,567"
7 + format(n) {
8 + if (n === '' || n === null || n === undefined) return '';
9 + const num = Math.round(Number(n));
10 + if (isNaN(num)) return '';
11 + return num.toLocaleString('en-US');
12 + },
13 +
14 + // تبدیل رشته یا element → عدد خالص
15 + parse(input) {
16 + if (input === null || input === undefined) return 0;
17 + const s = typeof input === 'string' ? input : (input.value || '');
18 + const cleaned = String(s).replace(/[^\d.-]/g, '');
19 + return Number(cleaned) || 0;
20 + },
21 +
22 + // خواندن مقدار عددی از element
23 + value(el) {
24 + return this.parse(el);
25 + },
26 +
27 + // فرمت‌دهی زنده با حفظ موقعیت cursor
28 + _formatLive(el) {
29 + const cursorStart = el.selectionStart;
30 + const oldValue = el.value;
31 +
32 + let raw = oldValue.replace(/[^\d]/g, '');
33 + if (raw.length > 1) raw = raw.replace(/^0+/, '');
34 +
35 + const formatted = raw ? Number(raw).toLocaleString('en-US') : '';
36 + if (formatted === oldValue) return;
37 +
38 + const digitsBefore = oldValue.slice(0, cursorStart).replace(/\D/g, '').length;
39 +
40 + el.value = formatted;
41 +
42 + if (digitsBefore === 0) {
43 + el.setSelectionRange(0, 0);
44 + } else if (digitsBefore >= raw.length) {
45 + el.setSelectionRange(formatted.length, formatted.length);
46 + } else {
47 + let pos = 0, count = 0;
48 + for (let i = 0; i < formatted.length; i++) {
49 + if (/\d/.test(formatted[i])) count++;
50 + if (count === digitsBefore) { pos = i + 1; break; }
51 + }
52 + el.setSelectionRange(pos, pos);
53 + }
54 + },
55 +
56 + // بررسی اینکه آیا این input باید فرمت بشه؟
57 + _shouldFormat(el) {
58 + if (!el || el.tagName !== 'INPUT') return false;
59 + if (el.type === 'number') return true;
60 + if (el.dataset.money === '1') return true;
61 + if (el.getAttribute('inputmode') === 'numeric') return true;
62 + return false;
63 + },
64 +
65 + // تبدیل و علامت‌گذاری input ها
66 + _markAndFormat(el) {
67 + if (!this._shouldFormat(el)) return;
68 +
69 + // تبدیل number به text
70 + if (el.type === 'number') {
71 + el.type = 'text';
72 + }
73 +
74 + // علامت‌گذاری
75 + el.setAttribute('data-money', '1');
76 + el.setAttribute('inputmode', 'numeric');
77 + el.setAttribute('autocomplete', 'off');
78 +
79 + // فرمت کردن مقدار اولیه اگه خالص عددی بود
80 + const raw = (el.value || '').replace(/,/g, '').trim();
81 + if (raw && /^-?\d+$/.test(raw) && raw !== '0') {
82 + el.value = this.format(raw);
83 + } else if (raw === '0') {
84 + // 0 رو نگه‌دار بدون فرمت اضافی
85 + el.value = '0';
86 + }
87 + },
88 +
89 + // اسکن کل DOM
90 + _convertAll() {
91 + document.querySelectorAll('input').forEach(el => {
92 + if (this._shouldFormat(el)) {
93 + this._markAndFormat(el);
94 + }
95 + });
96 + },
97 +
98 + init() {
99 + // تبدیل اولیه
100 + this._convertAll();
101 +
102 + // ناظر برای ورودی‌های جدید (مودال‌ها، ردیف‌های جدید و...)
103 + const observer = new MutationObserver(() => {
104 + this._convertAll();
105 + });
106 + observer.observe(document.body, { childList: true, subtree: true });
107 +
108 + // فرمت‌دهی زنده در هنگام تایپ
109 + document.addEventListener('input', (e) => {
110 + const el = e.target;
111 + if (!el || !el.matches || !el.matches('input')) return;
112 + if (el.getAttribute('data-money') !== '1') return;
113 + this._formatLive(el);
114 + });
115 +
116 + // پاک کردن مقدار صفر در ورودی اگه کاربر کلیک کرد و تایپ کرد
117 + document.addEventListener('focus', (e) => {
118 + const el = e.target;
119 + if (!el || !el.matches || !el.matches('input')) return;
120 + if (el.getAttribute('data-money') !== '1') return;
121 + if (el.value === '0') {
122 + el.value = '';
123 + }
124 + }, true);
125 + }
126 +};
\ No newline at end of file
src/views/ChequesView.js new
+416
@@ -0,0 +1,416 @@
1 +// ============================================================
2 +// ChequesView — صفحه‌ی مدیریت چک‌ها
3 +// ============================================================
4 +
5 +import { NumberInput } from '../utils/NumberInput.js';
6 +import { ChequeController } from '../controllers/ChequeController.js';
7 +import { ContactController } from '../controllers/ContactController.js';
8 +import { Modal } from '../core/Modal.js';
9 +import { Toast } from '../core/Toast.js';
10 +import { Formatters } from '../utils/Formatters.js';
11 +
12 +let filter = { search: '', direction: '', status: '' };
13 +let cache = { cheques: [], contacts: [], stats: {} };
14 +
15 +class ChequesViewImpl {
16 + async render() {
17 + await this.reload();
18 + return `
19 + <div class="page-title">
20 + <h2>چک‌ها</h2>
21 + <p>مدیریت چک‌های دریافتی و پرداختی با شماره صیادی</p>
22 + </div>
23 +
24 + <div class="grid-kpi">
25 + <div class="card" style="margin:0">
26 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل چک‌ها</div>
27 + <div style="font-size:20px;font-weight:800">${Formatters.number(cache.stats.total || 0)}</div>
28 + <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.toPersianDigits(cache.stats.pending || 0)} در جریان</div>
29 + </div>
30 + <div class="card" style="margin:0">
31 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">چک‌های دریافتی</div>
32 + <div style="font-size:18px;font-weight:800;color:var(--success)">${Formatters.money(cache.stats.inboundAmount || 0)}</div>
33 + <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.stats.inbound || 0)} فقره</div>
34 + </div>
35 + <div class="card" style="margin:0">
36 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">چک‌های پرداختی</div>
37 + <div style="font-size:18px;font-weight:800;color:var(--danger)">${Formatters.money(cache.stats.outboundAmount || 0)}</div>
38 + <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.stats.outbound || 0)} فقره</div>
39 + </div>
40 + <div class="card" style="margin:0">
41 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">مانده در جریان</div>
42 + <div style="font-size:18px;font-weight:800;color:var(--warning)">${Formatters.money(cache.stats.pendingAmount || 0)}</div>
43 + <div style="font-size:11px;color:var(--text-muted);margin-top:4px">جمع مبلغ چک‌های باز</div>
44 + </div>
45 + </div>
46 +
47 + <div id="cheques-content">${this.renderContent()}</div>
48 + `;
49 + }
50 +
51 + onMount() {
52 + window.ChequesView = this;
53 + }
54 +
55 + async reload() {
56 + cache.cheques = await ChequeController.getAll();
57 + cache.contacts = await ContactController.getAll();
58 + cache.stats = await ChequeController.getStats();
59 + }
60 +
61 + renderContent() {
62 + let list = cache.cheques;
63 + if (filter.search) {
64 + const q = filter.search.toLowerCase();
65 + list = list.filter(c =>
66 + (c.contactName || '').toLowerCase().includes(q) ||
67 + (c.sayadNumber || '').includes(q) ||
68 + (c.bankName || '').toLowerCase().includes(q)
69 + );
70 + }
71 + if (filter.direction) list = list.filter(c => c.direction === filter.direction);
72 + if (filter.status) list = list.filter(c => c.status === filter.status);
73 +
74 + const rows = list.length === 0
75 + ? `<tr><td colspan="9"><div class="empty-state"><div class="icon">💳</div><h3>هیچ چکی ثبت نشده</h3><p>اولین چک دریافتی یا پرداختی خود را ثبت کنید</p><button class="btn" onclick="window.ChequesView.openChequeModal()">➕ چک جدید</button></div></td></tr>`
76 + : list.map(c => {
77 + const today = new Date();
78 + const due = new Date(c.dueDate ? this._parseJalali(c.dueDate) : new Date());
79 + const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
80 + const isOverdue = diffDays < 0 && c.status === 'pending';
81 + const isSoon = diffDays >= 0 && diffDays <= 7 && c.status === 'pending';
82 +
83 + let dueDisplay = Formatters.toPersianDigits(c.dueDate || '—');
84 + if (isOverdue) dueDisplay += ` <span class="badge badge-danger" style="font-size:9px">${Formatters.toPersianDigits(Math.abs(diffDays))} روز گذشته</span>`;
85 + else if (isSoon) dueDisplay += ` <span class="badge badge-warning" style="font-size:9px">${Formatters.toPersianDigits(diffDays)} روز مانده</span>`;
86 +
87 + return `
88 + <tr>
89 + <td>
90 + <span class="badge ${c.direction === 'inbound' ? 'badge-success' : 'badge-danger'}">
91 + ${c.direction === 'inbound' ? '📥 دریافتی' : '📤 پرداختی'}
92 + </span>
93 + </td>
94 + <td><strong>${this._esc(c.contactName || '—')}</strong></td>
95 + <td style="font-family:monospace;font-size:11.5px">${Formatters.toPersianDigits(c.sayadNumber || '—')}</td>
96 + <td>${this._esc(c.bankName || '—')}</td>
97 + <td style="font-weight:700">${Formatters.money(c.amount)}</td>
98 + <td>${dueDisplay}</td>
99 + <td>${Formatters.toPersianDigits(c.issueDate || '—')}</td>
100 + <td>
101 + <span class="badge ${ChequeController.getStatusClass(c.status)}">
102 + ${ChequeController.getStatusLabel(c.status)}
103 + </span>
104 + </td>
105 + <td>
106 + <div class="row-actions">
107 + <button class="icon-btn-sm" title="تغییر وضعیت" onclick="window.ChequesView.changeStatus('${c.id}')">🔄</button>
108 + <button class="icon-btn-sm" title="ویرایش" onclick="window.ChequesView.editCheque('${c.id}')">✏️</button>
109 + <button class="icon-btn-sm danger" title="حذف" onclick="window.ChequesView.deleteCheque('${c.id}')">🗑️</button>
110 + </div>
111 + </td>
112 + </tr>
113 + `;
114 + }).join('');
115 +
116 + return `
117 + <div class="toolbar">
118 + <div class="search-input-wrap">
119 + <span class="icon">🔍</span>
120 + <input type="text" class="form-control" placeholder="جستجو بر اساس طرف حساب، صیادی یا بانک..." value="${this._esc(filter.search)}" oninput="window.ChequesView._onSearch(this.value)" />
121 + </div>
122 + <select class="form-control" style="width:auto;min-width:130px" onchange="window.ChequesView._onFilter('direction', this.value)">
123 + <option value="">همه انواع</option>
124 + <option value="inbound" ${filter.direction === 'inbound' ? 'selected' : ''}>دریافتی</option>
125 + <option value="outbound" ${filter.direction === 'outbound' ? 'selected' : ''}>پرداختی</option>
126 + </select>
127 + <select class="form-control" style="width:auto;min-width:130px" onchange="window.ChequesView._onFilter('status', this.value)">
128 + <option value="">همه وضعیت‌ها</option>
129 + <option value="pending" ${filter.status === 'pending' ? 'selected' : ''}>در جریان</option>
130 + <option value="cleared" ${filter.status === 'cleared' ? 'selected' : ''}>وصول شده</option>
131 + <option value="bounced" ${filter.status === 'bounced' ? 'selected' : ''}>برگشتی</option>
132 + <option value="returned" ${filter.status === 'returned' ? 'selected' : ''}>عودت داده شده</option>
133 + </select>
134 + <button class="btn" onclick="window.ChequesView.openChequeModal()">➕ چک جدید</button>
135 + </div>
136 +
137 + <div class="table-wrap">
138 + <table>
139 + <thead>
140 + <tr>
141 + <th style="width:110px">نوع</th>
142 + <th>طرف حساب</th>
143 + <th style="width:160px">شماره صیادی</th>
144 + <th style="width:110px">بانک</th>
145 + <th style="width:140px">مبلغ</th>
146 + <th style="width:170px">سررسید</th>
147 + <th style="width:100px">تاریخ صدور</th>
148 + <th style="width:110px">وضعیت</th>
149 + <th style="width:130px">عملیات</th>
150 + </tr>
151 + </thead>
152 + <tbody>${rows}</tbody>
153 + </table>
154 + </div>
155 + `;
156 + }
157 +
158 + _onSearch(val) {
159 + filter.search = val;
160 + document.getElementById('cheques-content').innerHTML = this.renderContent();
161 + const input = document.querySelector('#cheques-content input[type="text"]');
162 + if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
163 + }
164 +
165 + _onFilter(key, val) {
166 + filter[key] = val;
167 + document.getElementById('cheques-content').innerHTML = this.renderContent();
168 + }
169 +
170 + // ============================================================
171 + // فرم چک
172 + // ============================================================
173 + async openChequeModal(chequeId = null) {
174 + const cheque = chequeId ? await ChequeController.get(chequeId) : null;
175 + const isEdit = !!cheque;
176 + const d = cheque || {
177 + direction: 'inbound',
178 + contactId: null,
179 + sayadNumber: '',
180 + bankName: '',
181 + branchName: '',
182 + accountNumber: '',
183 + holderName: '',
184 + amount: 0,
185 + issueDate: this._todayJalali(),
186 + dueDate: this._todayJalali(),
187 + description: ''
188 + };
189 +
190 + const contactOptions = cache.contacts.map(c =>
191 + `<option value="${c.id}" ${d.contactId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
192 + ).join('');
193 +
194 + const body = `
195 + <div class="form-row">
196 + <div class="form-group">
197 + <label class="form-label">نوع چک <span class="req">*</span></label>
198 + <select class="form-control" id="chqDirection">
199 + <option value="inbound" ${d.direction === 'inbound' ? 'selected' : ''}>دریافتی (از مشتری)</option>
200 + <option value="outbound" ${d.direction === 'outbound' ? 'selected' : ''}>پرداختی (به تامین‌کننده)</option>
201 + </select>
202 + </div>
203 + <div class="form-group">
204 + <label class="form-label">طرف حساب</label>
205 + <select class="form-control" id="chqContact">
206 + <option value="">— انتخاب کنید —</option>
207 + ${contactOptions}
208 + </select>
209 + </div>
210 + </div>
211 +
212 + <div class="form-row">
213 + <div class="form-group">
214 + <label class="form-label">شماره صیادی (۱۶ رقم) <span class="req">*</span></label>
215 + <input type="text" class="form-control" id="chqSayad" value="${this._esc(d.sayadNumber)}" maxlength="16" placeholder="۱۶ رقم" />
216 + </div>
217 + <div class="form-group">
218 + <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
219 + <input type="text" inputmode="numeric" class="form-control" id="chqAmount" value="${NumberInput.format(d.amount || 0)}" />
220 + </div>
221 + </div>
222 +
223 + <div class="form-row">
224 + <div class="form-group">
225 + <label class="form-label">بانک</label>
226 + <input type="text" class="form-control" id="chqBank" value="${this._esc(d.bankName)}" placeholder="مثلاً ملی" />
227 + </div>
228 + <div class="form-group">
229 + <label class="form-label">شعبه</label>
230 + <input type="text" class="form-control" id="chqBranch" value="${this._esc(d.branchName)}" />
231 + </div>
232 + </div>
233 +
234 + <div class="form-row">
235 + <div class="form-group">
236 + <label class="form-label">شماره حساب</label>
237 + <input type="text" class="form-control" id="chqAccount" value="${this._esc(d.accountNumber)}" />
238 + </div>
239 + <div class="form-group">
240 + <label class="form-label">نام صاحب حساب</label>
241 + <input type="text" class="form-control" id="chqHolder" value="${this._esc(d.holderName)}" />
242 + </div>
243 + </div>
244 +
245 + <div class="form-row">
246 + <div class="form-group">
247 + <label class="form-label">تاریخ صدور (شمسی)</label>
248 + <input type="text" class="form-control" id="chqIssueDate" value="${this._esc(d.issueDate)}" placeholder="1405/06/27" />
249 + </div>
250 + <div class="form-group">
251 + <label class="form-label">تاریخ سررسید (شمسی) <span class="req">*</span></label>
252 + <input type="text" class="form-control" id="chqDueDate" value="${this._esc(d.dueDate)}" placeholder="1405/06/27" />
253 + </div>
254 + </div>
255 +
256 + <div class="form-group">
257 + <label class="form-label">توضیحات</label>
258 + <textarea class="form-control" id="chqDescription" rows="2">${this._esc(d.description)}</textarea>
259 + </div>
260 + `;
261 +
262 + const footer = `
263 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
264 + <button class="btn" onclick="window.ChequesView.saveCheque(${isEdit ? `'${chequeId}'` : 'null'})">💾 ذخیره</button>
265 + `;
266 +
267 + Modal.open({ title: isEdit ? 'ویرایش چک' : 'چک جدید', body, footer, size: 'md' });
268 + }
269 +
270 + async saveCheque(id) {
271 + const contactId = document.getElementById('chqContact').value || null;
272 + const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
273 +
274 + const data = {
275 + direction: document.getElementById('chqDirection').value,
276 + contactId,
277 + contactName: contact?.name || '',
278 + sayadNumber: document.getElementById('chqSayad').value,
279 + bankName: document.getElementById('chqBank').value,
280 + branchName: document.getElementById('chqBranch').value,
281 + accountNumber: document.getElementById('chqAccount').value,
282 + holderName: document.getElementById('chqHolder').value,
283 + amount: NumberInput.parse(document.getElementById('chqAmount').value),
284 + issueDate: document.getElementById('chqIssueDate').value,
285 + dueDate: document.getElementById('chqDueDate').value,
286 + description: document.getElementById('chqDescription').value
287 + };
288 +
289 + if (!data.sayadNumber.trim()) { Toast.warning('شماره صیادی الزامی است'); return; }
290 + if (data.amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
291 + if (!data.dueDate.trim()) { Toast.warning('سررسید الزامی است'); return; }
292 +
293 + try {
294 + if (id) {
295 + await ChequeController.update(id, data);
296 + Toast.success('چک ویرایش شد');
297 + } else {
298 + await ChequeController.create(data);
299 + Toast.success('چک ثبت شد');
300 + }
301 + Modal.close();
302 + await this.reload();
303 + document.getElementById('cheques-content').innerHTML = this.renderContent();
304 + } catch (err) {
305 + Toast.error('خطا: ' + err.message);
306 + }
307 + }
308 +
309 + async editCheque(id) {
310 + await this.openChequeModal(id);
311 + }
312 +
313 + async changeStatus(id) {
314 + const cheque = cache.cheques.find(c => c.id === id);
315 + if (!cheque) return;
316 +
317 + const statuses = [
318 + { value: 'pending', label: 'در جریان' },
319 + { value: 'cleared', label: 'وصول شده' },
320 + { value: 'bounced', label: 'برگشتی' },
321 + { value: 'returned', label: 'عودت داده شده' },
322 + { value: 'spent', label: 'خرج شده (به شخص دیگر واگذار شد)' }
323 + ];
324 +
325 + const body = `
326 + <p style="font-size:13px;margin-bottom:14px;color:var(--text-muted)">وضعیت فعلی: <strong>${ChequeController.getStatusLabel(cheque.status)}</strong></p>
327 + <div class="form-group">
328 + <label class="form-label">وضعیت جدید</label>
329 + <select class="form-control" id="newStatus">
330 + ${statuses.map(s => `<option value="${s.value}" ${cheque.status === s.value ? 'selected' : ''}>${s.label}</option>`).join('')}
331 + </select>
332 + </div>
333 + `;
334 + const footer = `
335 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
336 + <button class="btn" onclick="window.ChequesView._applyStatusChange('${id}')">اعمال</button>
337 + `;
338 + Modal.open({ title: 'تغییر وضعیت چک', body, footer, size: 'sm' });
339 + }
340 +
341 + async _applyStatusChange(id) {
342 + const status = document.getElementById('newStatus').value;
343 + try {
344 + await ChequeController.changeStatus(id, status);
345 + Toast.success('وضعیت چک تغییر کرد');
346 + Modal.close();
347 + await this.reload();
348 + document.getElementById('cheques-content').innerHTML = this.renderContent();
349 + } catch (err) {
350 + Toast.error('خطا: ' + err.message);
351 + }
352 + }
353 +
354 + async deleteCheque(id) {
355 + const c = cache.cheques.find(x => x.id === id);
356 + Modal.confirm({
357 + title: 'حذف چک',
358 + message: `آیا از حذف چک ${Formatters.toPersianDigits(c?.sayadNumber || '')} مطمئن هستید؟`,
359 + confirmText: 'حذف',
360 + danger: true,
361 + onConfirm: async () => {
362 + await ChequeController.delete(id);
363 + Toast.success('چک حذف شد');
364 + await this.reload();
365 + document.getElementById('cheques-content').innerHTML = this.renderContent();
366 + }
367 + });
368 + }
369 +
370 + _todayJalali() {
371 + const d = new Date();
372 + const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
373 + const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
374 + let jy = (gy <= 1600) ? 0 : 979;
375 + let gy2 = gy - (gy <= 1600 ? 621 : 1600);
376 + const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
377 + 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];
378 + jy += 33 * Math.floor(days / 12053);
379 + days %= 12053;
380 + jy += 4 * Math.floor(days / 1461);
381 + days %= 1461;
382 + if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
383 + const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
384 + const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
385 + return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
386 + }
387 +
388 + _parseJalali(str) {
389 + if (!str) return new Date();
390 + const parts = str.split('/').map(Number);
391 + if (parts.length !== 3) return new Date();
392 + const [jy, jm, jd] = parts;
393 + let gy = (jy <= 979) ? 621 : 1600;
394 + let jy2 = jy - (jy <= 979 ? 0 : 979);
395 + let days = (365 * jy2) + (Math.floor(jy2 / 33) * 8) + Math.floor(((jy2 % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
396 + gy += 400 * Math.floor(days / 146097);
397 + days %= 146097;
398 + if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
399 + gy += 4 * Math.floor(days / 1461);
400 + days %= 1461;
401 + if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
402 + let gd = days + 1;
403 + const sal_a = [0,31,((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31];
404 + let gm = 0;
405 + for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
406 + return new Date(gy, gm - 1, gd);
407 + }
408 +
409 + _esc(s) {
410 + if (!s) return '';
411 + return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
412 + }
413 +}
414 +
415 +export const ChequesView = new ChequesViewImpl();
416 +window.ChequesView = ChequesView;
\ No newline at end of file
src/views/InvoiceFormView.js
+137 -22
@@ -9,12 +9,14 @@ 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 +import { NumberInput } from '../utils/NumberInput.js';
13
14 let ctx = {
15 editId: null,
16 data: null,
17 contacts: [],
18 products: [],
19 + units: [],
20 rowCounter: 0
21 };
22
@@ -26,6 +28,7 @@ class InvoiceFormViewImpl {
28 ctx.editId = invoiceId;
29 ctx.contacts = await ContactController.getAll();
30 ctx.products = await ProductController.getProducts();
31 + ctx.units = await ProductController.getUnits();
32 ctx.rowCounter = 0;
33
34 if (invoiceId) {
@@ -42,7 +45,7 @@ class InvoiceFormViewImpl {
45 discountType: 'fixed',
46 discountInput: 0,
47 vatEnabled: false,
45 - vatRate: 9,
48 + vatRate: 10,
49 paymentMethod: 'cash',
50 paidAmount: 0,
51 description: ''
@@ -62,7 +65,7 @@ class InvoiceFormViewImpl {
65 body,
66 footer,
67 size: 'lg',
65 - onClose: () => { ctx = { editId: null, data: null, contacts: [], products: [], rowCounter: 0 }; }
68 + onClose: () => { ctx = { editId: null, data: null, contacts: [], products: [], units: [], rowCounter: 0 }; }
69 });
70
71 // بعد از باز شدن مودال، اقلام رو رندر کن
@@ -142,9 +145,12 @@ class InvoiceFormViewImpl {
145 </div>
146 </div>
147
145 - <div style="margin:14px 0 10px;display:flex;justify-content:space-between;align-items:center">
148 + <div style="margin:14px 0 10px;display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap">
149 <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>
150 + <div style="display:flex;gap:6px">
151 + <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._openQuickProduct()">➕ کالای جدید</button>
152 + <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._addRow()">➕ افزودن ردیف</button>
153 + </div>
154 </div>
155
156 <div class="table-wrap" style="max-height:340px;overflow-y:auto">
@@ -175,7 +181,7 @@ class InvoiceFormViewImpl {
181 <option value="fixed" ${d.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
182 <option value="percent" ${d.discountType === 'percent' ? 'selected' : ''}>درصد</option>
183 </select>
178 - <input type="number" class="form-control" id="invDiscInput" style="width:110px;min-height:34px" value="${d.discountInput || 0}" oninput="window.InvoiceFormView._recalc()" />
184 + <input type="text" inputmode="numeric" class="form-control" id="invDiscInput" style="width:110px;min-height:34px" value="${NumberInput.format(d.discountInput || 0)}" oninput="window.InvoiceFormView._recalc()" />
185 </div>
186
187 <div id="vatRow" style="display:${d.kind === 'non_formal' ? 'none' : 'flex'};gap:8px;align-items:center;margin-bottom:10px">
@@ -183,7 +189,7 @@ class InvoiceFormViewImpl {
189 <input type="checkbox" id="invVatEnabled" ${d.vatEnabled ? 'checked' : ''} onchange="window.InvoiceFormView._recalc()" />
190 مالیات ارزش افزوده
191 </label>
186 - <input type="number" class="form-control" id="invVatRate" style="width:80px;min-height:34px" value="${d.vatRate || 9}" oninput="window.InvoiceFormView._recalc()" />
192 + <input type="text" inputmode="numeric" class="form-control" id="invVatRate" style="width:80px;min-height:34px" value="${NumberInput.format(d.vatRate || 10)}" oninput="window.InvoiceFormView._recalc()" />
193 <span style="font-size:12.5px;color:var(--text-muted)">٪</span>
194 </div>
195
@@ -198,7 +204,7 @@ class InvoiceFormViewImpl {
204
205 <div id="paidRow" style="display:${d.paymentMethod === 'partial' ? 'flex' : 'none'};gap:8px;align-items:center;margin-bottom:10px">
206 <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()" />
207 + <input type="text" inputmode="numeric" class="form-control" id="invPaidAmount" style="width:140px;min-height:34px" value="${NumberInput.format(d.paidAmount || 0)}" oninput="window.InvoiceFormView._recalc()" />
208 </div>
209
210 <div class="form-group" style="margin-bottom:0">
@@ -275,11 +281,11 @@ class InvoiceFormViewImpl {
281 </select>
282 </td>
283 <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>
284 + <td><input type="text" inputmode="numeric" class="form-control row-qty" style="min-height:36px;text-align:center" value="${NumberInput.format(item.qty)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
285 + <td><input type="text" inputmode="numeric" class="form-control row-price" style="min-height:36px;text-align:left" value="${NumberInput.format(item.price)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'price', this.value)" /></td>
286 <td>
287 <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)" />
288 + <input type="text" inputmode="numeric" class="form-control row-disc" style="min-height:36px;text-align:left;flex:1" value="${NumberInput.format(item.discountType === 'percent' ? (item.discountInput || 0) : (item.discount || 0))}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'discount', this.value)" />
289 <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)">
290 <option value="fixed" ${item.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
291 <option value="percent" ${item.discountType === 'percent' ? 'selected' : ''}>٪</option>
@@ -327,14 +333,14 @@ class InvoiceFormViewImpl {
333 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
334 if (row) {
335 row.querySelector('.row-unit').value = ctx.data.items[idx].unit;
330 - row.querySelector('.row-price').value = ctx.data.items[idx].price;
336 + row.querySelector('.row-price').value = NumberInput.format(ctx.data.items[idx].price);
337 }
338 this._recalc();
339 }
340
341 _onFieldChange(idx, field, value) {
342 if (field === 'qty' || field === 'price' || field === 'discount') {
337 - ctx.data.items[idx][field] = Number(value) || 0;
343 + ctx.data.items[idx][field] = NumberInput.parse(value);
344 } else {
345 ctx.data.items[idx][field] = value;
346 }
@@ -422,7 +428,7 @@ class InvoiceFormViewImpl {
428
429 // تخفیف کلی
430 const discType = document.getElementById('invDiscType')?.value || 'fixed';
425 - const discInput = Number(document.getElementById('invDiscInput')?.value) || 0;
431 + const discInput = NumberInput.parse(document.getElementById('invDiscInput')?.value);
432 let totalDiscount = 0;
433 if (discType === 'percent') {
434 totalDiscount = Math.round(subtotal * discInput / 100);
@@ -435,7 +441,7 @@ class InvoiceFormViewImpl {
441 // مالیات
442 const kind = document.getElementById('invKind')?.value || 'sale';
443 const vatEnabled = kind !== 'non_formal' && document.getElementById('invVatEnabled')?.checked;
438 - const vatRate = Number(document.getElementById('invVatRate')?.value) || 0;
444 + const vatRate = NumberInput.parse(document.getElementById('invVatRate')?.value);
445 let vatAmount = 0;
446 if (vatEnabled) vatAmount = Math.round(afterDiscount * vatRate / 100);
447
@@ -446,7 +452,7 @@ class InvoiceFormViewImpl {
452 let paidAmount = 0;
453 if (method === 'cash') paidAmount = grandTotal;
454 else if (method === 'credit') paidAmount = 0;
449 - else if (method === 'partial') paidAmount = Math.max(0, Math.min(Number(document.getElementById('invPaidAmount')?.value) || 0, grandTotal));
455 + else if (method === 'partial') paidAmount = Math.max(0, Math.min(NumberInput.parse(document.getElementById('invPaidAmount')?.value), grandTotal));
456 const remaining = grandTotal - paidAmount;
457
458 // نمایش
@@ -465,6 +471,118 @@ class InvoiceFormViewImpl {
471 ctx.totals = { subtotal, totalDiscount, vatAmount, grandTotal, paidAmount, remaining };
472 }
473
474 + // ============================================================
475 + // افزودن سریع کالا (بدون خروج از فرم فاکتور)
476 + // ============================================================
477 + _openQuickProduct() {
478 + const body = `
479 + <div class="form-row">
480 + <div class="form-group">
481 + <label class="form-label">کد کالا</label>
482 + <input type="text" class="form-control" id="qpCode" placeholder="اختیاری" />
483 + </div>
484 + <div class="form-group">
485 + <label class="form-label">واحد</label>
486 + <input type="text" class="form-control" id="qpUnit" value="عدد" />
487 + </div>
488 + </div>
489 +
490 + <div class="form-group">
491 + <label class="form-label">نام کالا / خدمت <span class="req">*</span></label>
492 + <input type="text" class="form-control" id="qpName" placeholder="مثلاً هارد سرور" />
493 + </div>
494 +
495 + <div class="form-row">
496 + <div class="form-group">
497 + <label class="form-label">قیمت خرید (ریال)</label>
498 + <input type="text" inputmode="numeric" class="form-control" id="qpBuyPrice" value="0" />
499 + </div>
500 + <div class="form-group">
501 + <label class="form-label">قیمت فروش (ریال)</label>
502 + <input type="text" inputmode="numeric" class="form-control" id="qpSellPrice" value="0" />
503 + </div>
504 + </div>
505 +
506 + <div class="form-group">
507 + <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px">
508 + <input type="checkbox" id="qpTrackInventory" checked />
509 + پیگیری موجودی انبار (اگه خدمت هست، تیک رو بردار)
510 + </label>
511 + </div>
512 +
513 + <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
514 + 💡 بعد از ذخیره، این کالا خودکار توی ردیف فعلی فاکتور اضافه می‌شه.
515 + </small>
516 + `;
517 +
518 + const footer = `
519 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
520 + <button class="btn" onclick="window.InvoiceFormView._saveQuickProduct()">💾 ذخیره و افزودن</button>
521 + `;
522 +
523 + Modal.open({ title: '➕ کالای جدید سریع', body, footer, size: 'sm' });
524 + }
525 +
526 + async _saveQuickProduct() {
527 + const name = document.getElementById('qpName').value.trim();
528 + if (!name) { Toast.warning('نام کالا الزامی است'); return; }
529 +
530 + const data = {
531 + code: document.getElementById('qpCode').value,
532 + barcode: '',
533 + name,
534 + unit: document.getElementById('qpUnit').value || 'عدد',
535 + unitId: null,
536 + categoryId: null,
537 + buyPrice: NumberInput.parse(document.getElementById('qpBuyPrice').value),
538 + sellPrice: NumberInput.parse(document.getElementById('qpSellPrice').value),
539 + trackInventory: document.getElementById('qpTrackInventory').checked,
540 + isActiveSell: true,
541 + isActiveBuy: true,
542 + description: ''
543 + };
544 +
545 + try {
546 + const newProduct = await ProductController.createProduct(data);
547 +
548 + ctx.products.push(newProduct);
549 +
550 + Toast.success('کالا اضافه شد و به فاکتور اضافه می‌شود');
551 + Modal.close();
552 +
553 + // اضافه کردن به dropdown همه‌ی ردیف‌ها
554 + document.querySelectorAll('#itemsBody .row-product').forEach(select => {
555 + const opt = document.createElement('option');
556 + opt.value = newProduct.id;
557 + opt.textContent = newProduct.name + (newProduct.code ? ` (${newProduct.code})` : '');
558 + select.appendChild(opt);
559 + });
560 +
561 + const emptyIdx = ctx.data.items.findIndex(it => !it.productId);
562 + let targetIdx;
563 + if (emptyIdx >= 0) {
564 + targetIdx = emptyIdx;
565 + } else {
566 + ctx.data.items.push(this._emptyItem());
567 + targetIdx = ctx.data.items.length - 1;
568 + this._renderItems();
569 + }
570 +
571 + ctx.data.items[targetIdx].productId = newProduct.id;
572 + ctx.data.items[targetIdx].productName = newProduct.name;
573 + ctx.data.items[targetIdx].unit = newProduct.unit || 'عدد';
574 + ctx.data.items[targetIdx].price = Number(newProduct.sellPrice) || 0;
575 + ctx.data.items[targetIdx].qty = ctx.data.items[targetIdx].qty || 1;
576 +
577 + this._renderItems();
578 + this._recalc();
579 +
580 + } catch (err) {
581 + console.error(err);
582 + Toast.error('خطا در ذخیره‌ی کالا: ' + err.message);
583 + }
584 + }
585 +
586 // ============================================================
587 // افزودن سریع شخص
588 // ============================================================
@@ -495,7 +613,6 @@ class InvoiceFormViewImpl {
613 entityType: 'natural', role: 'customer', name, mobile
614 });
615 Toast.success('شخص اضافه شد');
498 - // refresh dropdown
616 const select = document.getElementById('invContact');
617 const opt = document.createElement('option');
618 opt.value = newContact.id;
@@ -523,7 +640,6 @@ class InvoiceFormViewImpl {
640 return;
641 }
642
526 - // اعتبارسنجی اقلام
643 const validItems = ctx.data.items.filter(it => it.productId && (Number(it.qty) || 0) > 0);
644 if (validItems.length === 0) {
645 Toast.warning('حداقل یک ردیف معتبر (کالا با مقدار) لازم است');
@@ -538,11 +654,11 @@ class InvoiceFormViewImpl {
654 contactName: contact.name,
655 items: validItems,
656 discountType: document.getElementById('invDiscType').value,
541 - discountInput: Number(document.getElementById('invDiscInput').value) || 0,
657 + discountInput: NumberInput.parse(document.getElementById('invDiscInput').value),
658 vatEnabled: document.getElementById('invVatEnabled')?.checked || false,
543 - vatRate: Number(document.getElementById('invVatRate')?.value) || 0,
659 + vatRate: NumberInput.parse(document.getElementById('invVatRate')?.value),
660 paymentMethod: document.getElementById('invPayment').value,
545 - paidAmount: Number(document.getElementById('invPaidAmount')?.value) || 0,
661 + paidAmount: NumberInput.parse(document.getElementById('invPaidAmount')?.value),
662 description: document.getElementById('invDescription').value
663 };
664
@@ -553,9 +669,8 @@ class InvoiceFormViewImpl {
669 Modal.close();
670 if (printAfter) {
671 const { InvoicePrint } = await import('../utils/InvoicePrint.js');
556 - setTimeout(() => InvoicePrint.print(savedId), 200);
672 + setTimeout(() => InvoicePrint.openSettings(savedId), 250);
673 }
558 - // refresh list
674 if (window.InvoicesView) window.InvoicesView.reloadAndRender?.();
675 } catch (err) {
676 console.error(err);
src/views/ProductsView.js
+57 -20
@@ -7,6 +7,7 @@ import { Modal } from '../core/Modal.js';
7 import { Toast } from '../core/Toast.js';
8 import { Formatters } from '../utils/Formatters.js';
9 import { numberToWords } from '../utils/NumberToWords.js';
10 +import { NumberInput } from '../utils/NumberInput.js';
11
12 let currentTab = 'products';
13 let currentSearch = '';
@@ -22,13 +23,13 @@ class ProductsViewImpl {
23 </div>
24
25 <div class="tabs">
25 - <button class="tab-btn ${currentTab === 'products' ? 'active' : ''}" onclick="window.ProductsView._switchTab('products')">
26 + <button class="tab-btn ${currentTab === 'products' ? 'active' : ''}" onclick="window.ProductsView._switchTab('products', event)">
27 📦 کالاها و خدمات
28 </button>
28 - <button class="tab-btn ${currentTab === 'units' ? 'active' : ''}" onclick="window.ProductsView._switchTab('units')">
29 + <button class="tab-btn ${currentTab === 'units' ? 'active' : ''}" onclick="window.ProductsView._switchTab('units', event)">
30 📏 واحدها
31 </button>
31 - <button class="tab-btn ${currentTab === 'categories' ? 'active' : ''}" onclick="window.ProductsView._switchTab('categories')">
32 + <button class="tab-btn ${currentTab === 'categories' ? 'active' : ''}" onclick="window.ProductsView._switchTab('categories', event)">
33 🗂️ گروه‌ها
34 </button>
35 </div>
@@ -58,12 +59,13 @@ class ProductsViewImpl {
59 return '';
60 }
61
61 - _switchTab(tab) {
62 + _switchTab(tab, evt) {
63 currentTab = tab;
64 const el = document.getElementById('products-tab-content');
65 if (el) {
65 - document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
66 - event.target.classList.add('active');
66 + document.querySelectorAll('.tabs .tab-btn').forEach(btn => btn.classList.remove('active'));
67 + const target = (evt && evt.target) ? evt.target.closest('.tab-btn') : null;
68 + if (target) target.classList.add('active');
69 el.innerHTML = this.renderTabContent();
70 }
71 }
@@ -282,11 +284,11 @@ class ProductsViewImpl {
284 <div class="form-row">
285 <div class="form-group">
286 <label class="form-label">قیمت خرید (ریال)</label>
285 - <input type="number" class="form-control" id="pBuyPrice" value="${data.buyPrice || 0}" min="0" />
287 + <input type="text" inputmode="numeric" class="form-control" id="pBuyPrice" value="${NumberInput.format(data.buyPrice || 0)}" />
288 </div>
289 <div class="form-group">
290 <label class="form-label">قیمت فروش (ریال)</label>
289 - <input type="number" class="form-control" id="pSellPrice" value="${data.sellPrice || 0}" min="0" />
291 + <input type="text" inputmode="numeric" class="form-control" id="pSellPrice" value="${NumberInput.format(data.sellPrice || 0)}" />
292 </div>
293 </div>
294
@@ -319,6 +321,10 @@ class ProductsViewImpl {
321 });
322 }
323
324 + async editProduct(id) {
325 + await this.openProductModal(id);
326 + }
327 +
328 async saveProduct(id) {
329 const data = {
330 code: document.getElementById('pCode').value,
@@ -326,8 +332,8 @@ class ProductsViewImpl {
332 name: document.getElementById('pName').value,
333 unitId: document.getElementById('pUnit').value || null,
334 categoryId: document.getElementById('pCategory').value || null,
329 - buyPrice: document.getElementById('pBuyPrice').value,
330 - sellPrice: document.getElementById('pSellPrice').value,
335 + buyPrice: NumberInput.parse(document.getElementById('pBuyPrice').value),
336 + sellPrice: NumberInput.parse(document.getElementById('pSellPrice').value),
337 trackInventory: document.getElementById('pTrackInventory').checked,
338 description: document.getElementById('pDescription').value
339 };
@@ -398,16 +404,31 @@ class ProductsViewImpl {
404 const name = document.getElementById('uName').value;
405 const symbol = document.getElementById('uSymbol').value;
406 if (!name.trim()) { Toast.warning('نام واحد الزامی است'); return; }
407 +
408 try {
402 - await ProductController.createUnit(name, symbol);
409 + const newUnit = await ProductController.createUnit(name, symbol);
410 Toast.success('واحد ثبت شد');
411 +
412 + // بستن مودال واحد (برمی‌گرده به مودال کالا اگه باز بود)
413 Modal.close();
405 - await this.reload();
414 +
415 + // cache واحدها رو به‌روز کن
416 + cache.units = await ProductController.getUnits();
417 +
418 if (fromProductForm) {
407 - // به فرم کالا برگرد و dropdown رو refresh کن
408 - Toast.info('واحد اضافه شد. لطفاً فرم کالا رو دوباره باز کنید');
419 + // ⬇️ اصلاح اصلی: dropdown واحد توی فرم کالا رو به‌روز کن
420 + const unitSelect = document.getElementById('pUnit');
421 + if (unitSelect) {
422 + unitSelect.innerHTML = cache.units.map(u =>
423 + `<option value="${u.id}">${this._esc(u.name)}</option>`
424 + ).join('');
425 + // واحد جدید رو انتخاب کن
426 + unitSelect.value = newUnit.id;
427 + }
428 } else {
410 - document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
429 + // توی تب واحدها هستیم، جدول رو رفرش کن
430 + const el = document.getElementById('products-tab-content');
431 + if (el) el.innerHTML = this.renderTabContent();
432 }
433 } catch (err) {
434 Toast.error('خطا: ' + err.message);
@@ -460,15 +481,30 @@ class ProductsViewImpl {
481 const name = document.getElementById('cName').value;
482 const parentId = document.getElementById('cParent').value || null;
483 if (!name.trim()) { Toast.warning('نام گروه الزامی است'); return; }
484 +
485 try {
464 - await ProductController.createCategory(name, parentId);
486 + const newCategory = await ProductController.createCategory(name, parentId);
487 Toast.success('گروه ثبت شد');
488 +
489 + // بستن مودال گروه
490 Modal.close();
467 - await this.reload();
491 +
492 + // cache گروه‌ها رو به‌روز کن
493 + cache.categories = await ProductController.getCategories();
494 +
495 if (fromProductForm) {
469 - Toast.info('گروه اضافه شد. لطفاً فرم کالا رو دوباره باز کنید');
496 + // ⬇️ اصلاح اصلی: dropdown گروه توی فرم کالا رو به‌روز کن
497 + const catSelect = document.getElementById('pCategory');
498 + if (catSelect) {
499 + catSelect.innerHTML = cache.categories.map(c =>
500 + `<option value="${c.id}">${this._esc(c.name)}</option>`
501 + ).join('');
502 + // گروه جدید رو انتخاب کن
503 + catSelect.value = newCategory.id;
504 + }
505 } else {
471 - document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
506 + const el = document.getElementById('products-tab-content');
507 + if (el) el.innerHTML = this.renderTabContent();
508 }
509 } catch (err) {
510 Toast.error('خطا: ' + err.message);
@@ -496,4 +532,5 @@ class ProductsViewImpl {
532 }
533 }
534
499 -export const ProductsView = new ProductsViewImpl();
\ No newline at end of file
535 +export const ProductsView = new ProductsViewImpl();
536 +window.ProductsView = ProductsView;
\ No newline at end of file
src/views/SettingsView.js new
+418
@@ -0,0 +1,418 @@
1 +// ============================================================
2 +// SettingsView — صفحه‌ی تنظیمات، بکاپ و شرکت
3 +// ============================================================
4 +
5 +import { SettingsController } from '../controllers/SettingsController.js';
6 +import { StorageService } from '../core/StorageService.js';
7 +import { Theme } from '../core/Theme.js';
8 +import { Modal } from '../core/Modal.js';
9 +import { Toast } from '../core/Toast.js';
10 +import { Formatters } from '../utils/Formatters.js';
11 +import { Auth } from '../core/Auth.js';
12 +
13 +let cache = { company: {}, stats: {} };
14 +
15 +class SettingsViewImpl {
16 + async render() {
17 + await this.reload();
18 + return `
19 + <div class="page-title">
20 + <h2>تنظیمات</h2>
21 + <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری و تنظیمات سیستم</p>
22 + </div>
23 +
24 + <div class="settings-grid">
25 + ${this._renderCompanyCard()}
26 + ${this._renderBackupCard()}
27 + ${this._renderStatsCard()}
28 + ${this._renderThemeCard()}
29 + ${this._renderAboutCard()}
30 + </div>
31 + `;
32 + }
33 +
34 + onMount() {
35 + window.SettingsView = this;
36 + }
37 +
38 + async reload() {
39 + cache.company = await SettingsController.getCompanyInfo();
40 + cache.stats = await this._collectStats();
41 + }
42 +
43 + async _collectStats() {
44 + const user = Auth.current();
45 + if (!user) return {};
46 + const stores = ['products', 'contacts', 'invoices', 'cheques', 'treasury'];
47 + const stats = {};
48 + for (const s of stores) {
49 + try {
50 + const list = await StorageService.getByOwner(s, user.id);
51 + if (s === 'treasury') {
52 + stats.accounts = list.filter(x => x.recordType === 'account').length;
53 + stats.transactions = list.filter(x => x.recordType === 'transaction').length;
54 + } else {
55 + stats[s] = list.length;
56 + }
57 + } catch (e) {
58 + stats[s] = 0;
59 + }
60 + }
61 + return stats;
62 + }
63 +
64 + // ============================================================
65 + // کارت اطلاعات شرکت
66 + // ============================================================
67 + _renderCompanyCard() {
68 + const c = cache.company;
69 + return `
70 + <div class="card settings-card">
71 + <div class="settings-card-header">
72 + <div class="settings-card-icon">🏢</div>
73 + <div>
74 + <h3 class="settings-card-title">اطلاعات شرکت / فروشگاه</h3>
75 + <p class="settings-card-desc">این اطلاعات در سربرگ فاکتورهای چاپی نمایش داده می‌شود</p>
76 + </div>
77 + </div>
78 + ${c.name ? `
79 + <div class="company-preview">
80 + <div style="font-weight:700;font-size:14px">${this._esc(c.name)}</div>
81 + ${c.nationalId ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:3px">شناسه ملی: ${Formatters.toPersianDigits(c.nationalId)}</div>` : ''}
82 + ${c.address ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">${this._esc(c.address)}</div>` : ''}
83 + ${c.phone ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">تلفن: ${Formatters.phone(c.phone)}</div>` : ''}
84 + </div>
85 + ` : `
86 + <div class="empty-mini">هنوز اطلاعاتی وارد نشده</div>
87 + `}
88 + <button class="btn" onclick="window.SettingsView.openCompanyModal()">
89 + ${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}
90 + </button>
91 + </div>
92 + `;
93 + }
94 +
95 + // ============================================================
96 + // کارت بکاپ
97 + // ============================================================
98 + _renderBackupCard() {
99 + return `
100 + <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
101 + <div class="settings-card-header">
102 + <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
103 + <div>
104 + <h3 class="settings-card-title">پشتیبان‌گیری و بازیابی</h3>
105 + <p class="settings-card-desc">از داده‌های خود نسخه‌ی پشتیبان بگیرید تا در صورت نیاز بازیابی کنید</p>
106 + </div>
107 + </div>
108 +
109 + <div class="backup-warning">
110 + ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
111 + </div>
112 +
113 + <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
114 + <button class="btn" onclick="window.SettingsView.downloadBackup()">
115 + 📥 دانلود فایل بکاپ
116 + </button>
117 + <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
118 + 📤 بازیابی از بکاپ
119 + </button>
120 + </div>
121 +
122 + <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
123 + <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
124 + 🗑️ پاک کردن کامل داده‌ها
125 + </button>
126 + <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
127 + </div>
128 + </div>
129 + `;
130 + }
131 +
132 + // ============================================================
133 + // کارت آمار
134 + // ============================================================
135 + _renderStatsCard() {
136 + const s = cache.stats;
137 + const items = [
138 + { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
139 + { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
140 + { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
141 + { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
142 + { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
143 + { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
144 + ];
145 + return `
146 + <div class="card settings-card">
147 + <div class="settings-card-header">
148 + <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
149 + <div>
150 + <h3 class="settings-card-title">آمار داده‌ها</h3>
151 + <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
152 + </div>
153 + </div>
154 + <div class="stats-grid">
155 + ${items.map(i => `
156 + <div class="stat-mini">
157 + <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
158 + <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
159 + <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
160 + </div>
161 + `).join('')}
162 + </div>
163 + </div>
164 + `;
165 + }
166 +
167 + // ============================================================
168 + // کارت تم
169 + // ============================================================
170 + _renderThemeCard() {
171 + const current = Theme.current();
172 + return `
173 + <div class="card settings-card">
174 + <div class="settings-card-header">
175 + <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
176 + <div>
177 + <h3 class="settings-card-title">ظاهر و تم</h3>
178 + <p class="settings-card-desc">حالت نمایش برنامه</p>
179 + </div>
180 + </div>
181 + <div style="display:flex;gap:10px;margin-top:8px">
182 + <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
183 + <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
184 + </div>
185 + </div>
186 + `;
187 + }
188 +
189 + // ============================================================
190 + // کارت درباره
191 + // ============================================================
192 + _renderAboutCard() {
193 + return `
194 + <div class="card settings-card">
195 + <div class="settings-card-header">
196 + <div class="settings-card-icon">ℹ️</div>
197 + <div>
198 + <h3 class="settings-card-title">درباره فینورا پرو</h3>
199 + <p class="settings-card-desc">نسخه ۰.۱.۰</p>
200 + </div>
201 + </div>
202 + <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
203 + <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
204 + <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
205 + <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
206 + <a href="https://wa.me/989124376991" target="_blank" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E);font-size:12.5px;min-height:36px">💬 واتس‌اپ پشتیبانی</a>
207 + </div>
208 + </div>
209 + </div>
210 + `;
211 + }
212 +
213 + // ============================================================
214 + // فرم اطلاعات شرکت
215 + // ============================================================
216 + openCompanyModal() {
217 + const c = cache.company;
218 + const body = `
219 + <div class="form-row">
220 + <div class="form-group">
221 + <label class="form-label">نوع شخص</label>
222 + <select class="form-control" id="coEntityType">
223 + <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
224 + <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
225 + </select>
226 + </div>
227 + <div class="form-group">
228 + <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
229 + <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
230 + </div>
231 + </div>
232 + <div class="form-row">
233 + <div class="form-group">
234 + <label class="form-label">شناسه ملی / کد ملی</label>
235 + <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
236 + </div>
237 + <div class="form-group">
238 + <label class="form-label">کد اقتصادی</label>
239 + <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
240 + </div>
241 + </div>
242 + <div class="form-row">
243 + <div class="form-group">
244 + <label class="form-label">شماره ثبت</label>
245 + <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
246 + </div>
247 + <div class="form-group">
248 + <label class="form-label">کد پستی</label>
249 + <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
250 + </div>
251 + </div>
252 + <div class="form-row">
253 + <div class="form-group">
254 + <label class="form-label">تلفن</label>
255 + <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
256 + </div>
257 + <div class="form-group">
258 + <label class="form-label">موبایل</label>
259 + <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
260 + </div>
261 + </div>
262 + <div class="form-group">
263 + <label class="form-label">نشانی</label>
264 + <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
265 + </div>
266 + <div class="form-group">
267 + <label class="form-label">پاورقی فاکتور</label>
268 + <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
269 + </div>
270 + `;
271 + const footer = `
272 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
273 + <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
274 + `;
275 + Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
276 + }
277 +
278 + async saveCompany() {
279 + const data = {
280 + name: document.getElementById('coName').value,
281 + entityType: document.getElementById('coEntityType').value,
282 + nationalId: document.getElementById('coNationalId').value,
283 + economicCode: document.getElementById('coEconomicCode').value,
284 + regNumber: document.getElementById('coRegNumber').value,
285 + postalCode: document.getElementById('coPostalCode').value,
286 + phone: document.getElementById('coPhone').value,
287 + mobile: document.getElementById('coMobile').value,
288 + address: document.getElementById('coAddress').value,
289 + footer: document.getElementById('coFooter').value
290 + };
291 + if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
292 + try {
293 + await SettingsController.saveCompanyInfo(data);
294 + Toast.success('اطلاعات ذخیره شد');
295 + Modal.close();
296 + await this.reload();
297 + document.querySelector('.settings-grid').outerHTML = `<div class="settings-grid">${this._renderCompanyCard()}${this._renderBackupCard()}${this._renderStatsCard()}${this._renderThemeCard()}${this._renderAboutCard()}</div>`;
298 + } catch (err) {
299 + Toast.error('خطا: ' + err.message);
300 + }
301 + }
302 +
303 + // ============================================================
304 + // بکاپ
305 + // ============================================================
306 + async downloadBackup() {
307 + try {
308 + Toast.info('در حال آماده‌سازی بکاپ...');
309 + const result = await SettingsController.downloadBackup();
310 + Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
311 + } catch (err) {
312 + Toast.error('خطا در بکاپ: ' + err.message);
313 + }
314 + }
315 +
316 + openRestoreModal() {
317 + const body = `
318 + <div class="backup-warning" style="margin-bottom:14px">
319 + ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، همه‌چیز با بکاپ جایگزین می‌شه.
320 + </div>
321 +
322 + <div class="form-group">
323 + <label class="form-label">فایل بکاپ (JSON)</label>
324 + <input type="file" class="form-control" id="restoreFile" accept=".json,application/json" />
325 + </div>
326 +
327 + <div class="form-group">
328 + <label class="form-label">حالت بازیابی</label>
329 + <select class="form-control" id="restoreMode">
330 + <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
331 + <option value="replace">🔄 جایگزینی (Replace) — همه‌چیز با بکاپ عوض می‌شه</option>
332 + </select>
333 + </div>
334 + `;
335 + const footer = `
336 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
337 + <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
338 + `;
339 + Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
340 + }
341 +
342 + async restoreBackup() {
343 + const fileInput = document.getElementById('restoreFile');
344 + const file = fileInput.files[0];
345 + if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
346 +
347 + const mode = document.getElementById('restoreMode').value;
348 +
349 + try {
350 + Toast.info('در حال بازیابی...');
351 + const content = await SettingsController.readFileAsText(file);
352 + const counts = await SettingsController.importBackup(content, { mode });
353 + Modal.close();
354 + Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
355 + setTimeout(() => location.reload(), 1500);
356 + } catch (err) {
357 + Toast.error('خطا: ' + err.message);
358 + }
359 + }
360 +
361 + // ============================================================
362 + // پاک کردن کامل
363 + // ============================================================
364 + openWipeModal() {
365 + const body = `
366 + <div style="text-align:center;padding:10px 0">
367 + <div style="font-size:48px;margin-bottom:12px">⚠️</div>
368 + <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
369 + <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
370 + این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
371 + <br><strong>قابل بازگشت نیست!</strong>
372 + </p>
373 + <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
374 + لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
375 + </p>
376 + <input type="text" class="form-control" id="wipeConfirm" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
377 + </div>
378 + `;
379 + const footer = `
380 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
381 + <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
382 + `;
383 + Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
384 + }
385 +
386 + async confirmWipe() {
387 + const confirmText = document.getElementById('wipeConfirm').value.trim();
388 + if (confirmText !== 'حذف') {
389 + Toast.warning('متن تأیید اشتباه است');
390 + return;
391 + }
392 + try {
393 + await SettingsController.wipeAll();
394 + Toast.success('همه‌ی داده‌ها پاک شد');
395 + setTimeout(() => location.reload(), 800);
396 + } catch (err) {
397 + Toast.error('خطا: ' + err.message);
398 + }
399 + }
400 +
401 + // ============================================================
402 + // Theme
403 + // ============================================================
404 + setTheme(theme) {
405 + Theme.apply(theme);
406 + const grid = document.querySelector('.settings-grid');
407 + if (grid) {
408 + grid.innerHTML = this._renderCompanyCard() + this._renderBackupCard() + this._renderStatsCard() + this._renderThemeCard() + this._renderAboutCard();
409 + }
410 + }
411 +
412 + _esc(s) {
413 + if (!s) return '';
414 + return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
415 + }
416 +}
417 +
418 +export const SettingsView = new SettingsViewImpl();
\ No newline at end of file
src/views/TreasuryView.js new
+633
@@ -0,0 +1,633 @@
1 +// ============================================================
2 +// TreasuryView — صفحه‌ی خزانه‌داری
3 +// ============================================================
4 +
5 +import { TreasuryController } from '../controllers/TreasuryController.js';
6 +import { ContactController } from '../controllers/ContactController.js';
7 +import { InvoiceController } from '../controllers/InvoiceController.js';
8 +import { Modal } from '../core/Modal.js';
9 +import { Toast } from '../core/Toast.js';
10 +import { Formatters } from '../utils/Formatters.js';
11 +import { NumberInput } from '../utils/NumberInput.js';
12 +
13 +let currentTab = 'accounts';
14 +let txFilter = { search: '', type: '', accountId: '' };
15 +let cache = { accounts: [], balances: {}, transactions: [], contacts: [] };
16 +
17 +class TreasuryViewImpl {
18 + async render() {
19 + await this.reload();
20 + return `
21 + <div class="page-title">
22 + <h2>خزانه‌داری و بانک</h2>
23 + <p>مدیریت صندوق‌ها، حساب‌های بانکی و تراکنش‌های دریافت و پرداخت</p>
24 + </div>
25 +
26 + <div class="tabs">
27 + <button class="tab-btn ${currentTab === 'accounts' ? 'active' : ''}" onclick="window.TreasuryView._switchTab('accounts', this)">
28 + 💳 حساب‌ها و صندوق‌ها
29 + </button>
30 + <button class="tab-btn ${currentTab === 'transactions' ? 'active' : ''}" onclick="window.TreasuryView._switchTab('transactions', this)">
31 + 💸 تراکنش‌ها
32 + </button>
33 + </div>
34 +
35 + <div id="treasury-content">${this.renderTabContent()}</div>
36 + `;
37 + }
38 +
39 + onMount() {
40 + window.TreasuryView = this;
41 + }
42 +
43 + async reload() {
44 + cache.accounts = await TreasuryController.getAccounts();
45 + cache.balances = await TreasuryController.getBalanceMap();
46 + cache.transactions = await TreasuryController.getTransactions();
47 + cache.contacts = await ContactController.getAll();
48 + }
49 +
50 + _switchTab(tab, btn) {
51 + currentTab = tab;
52 + document.querySelectorAll('.tabs .tab-btn').forEach(b => b.classList.remove('active'));
53 + if (btn) btn.classList.add('active');
54 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
55 + }
56 +
57 + renderTabContent() {
58 + if (currentTab === 'accounts') return this.renderAccountsTab();
59 + if (currentTab === 'transactions') return this.renderTransactionsTab();
60 + return '';
61 + }
62 +
63 + // ============================================================
64 + // تب حساب‌ها
65 + // ============================================================
66 + renderAccountsTab() {
67 + const totalBalance = Object.values(cache.balances).reduce((s, v) => s + v, 0);
68 +
69 + let cardsHtml = '';
70 + if (cache.accounts.length === 0) {
71 + cardsHtml = `
72 + <div class="empty-state" style="grid-column:1/-1">
73 + <div class="icon">💳</div>
74 + <h3>هنوز حساب یا صندوقی تعریف نشده</h3>
75 + <p>اولین حساب یا صندوق خود را اضافه کنید</p>
76 + <button class="btn" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
77 + </div>`;
78 + } else {
79 + cardsHtml = cache.accounts.map(acc => {
80 + const bal = cache.balances[acc.id] || 0;
81 + const typeLabels = {
82 + cashbox: { label: 'صندوق', icon: '💰' },
83 + bank: { label: 'بانک', icon: '🏦' },
84 + pos: { label: 'پوز', icon: '💳' }
85 + };
86 + const t = typeLabels[acc.type] || { label: acc.type, icon: '📁' };
87 + return `
88 + <div class="account-card" style="border-top:3px solid ${acc.color || '#0d9488'}">
89 + <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:14px">
90 + <div>
91 + <div style="font-size:24px;margin-bottom:4px">${t.icon}</div>
92 + <div style="font-weight:700;font-size:14px">${this._esc(acc.name)}</div>
93 + <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${t.label}${acc.isDefault ? ' • پیش‌فرض' : ''}</div>
94 + </div>
95 + <div class="row-actions">
96 + <button class="icon-btn-sm" title="ویرایش" onclick="window.TreasuryView.editAccount('${acc.id}')">✏️</button>
97 + <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteAccount('${acc.id}')">🗑️</button>
98 + </div>
99 + </div>
100 + ${acc.bankName ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">🏛️ ${this._esc(acc.bankName)}</div>` : ''}
101 + ${acc.accountNumber ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">شماره: ${Formatters.toPersianDigits(acc.accountNumber)}</div>` : ''}
102 + <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
103 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی فعلی</div>
104 + <div style="font-size:18px;font-weight:800;color:${bal >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(bal)}</div>
105 + </div>
106 + </div>
107 + `;
108 + }).join('');
109 + }
110 +
111 + return `
112 + <div class="card" style="background:linear-gradient(135deg,var(--primary),var(--primary-dark));color:#fff;border:none">
113 + <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
114 + <div>
115 + <div style="font-size:12px;opacity:.85;margin-bottom:4px">موجودی کل خزانه</div>
116 + <div style="font-size:26px;font-weight:800">${Formatters.money(totalBalance)}</div>
117 + <div style="font-size:11.5px;opacity:.85;margin-top:4px">${Formatters.toPersianDigits(cache.accounts.length)} حساب فعال</div>
118 + </div>
119 + <button class="btn" style="background:#fff;color:var(--primary)" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
120 + </div>
121 + </div>
122 +
123 + <div class="account-grid">${cardsHtml}</div>
124 + `;
125 + }
126 +
127 + // ============================================================
128 + // تب تراکنش‌ها
129 + // ============================================================
130 + renderTransactionsTab() {
131 + let list = cache.transactions;
132 +
133 + if (txFilter.search) {
134 + const q = txFilter.search.toLowerCase();
135 + list = list.filter(t =>
136 + (t.contactName || '').toLowerCase().includes(q) ||
137 + (t.description || '').toLowerCase().includes(q) ||
138 + String(t.refInvoiceNumber || '').includes(q)
139 + );
140 + }
141 + if (txFilter.type) list = list.filter(t => t.type === txFilter.type);
142 + if (txFilter.accountId) {
143 + list = list.filter(t => t.fromAccountId === txFilter.accountId || t.toAccountId === txFilter.accountId);
144 + }
145 +
146 + const rows = list.length === 0
147 + ? `<tr><td colspan="8"><div class="empty-state"><div class="icon">💸</div><h3>هیچ تراکنشی ثبت نشده</h3><p>اولین دریافت یا پرداخت را ثبت کنید</p></div></td></tr>`
148 + : list.map(t => {
149 + const fromAcc = cache.accounts.find(a => a.id === t.fromAccountId);
150 + const toAcc = cache.accounts.find(a => a.id === t.toAccountId);
151 + const typeInfo = {
152 + receipt: { label: 'دریافت', cls: 'badge-success', icon: '📥' },
153 + payment: { label: 'پرداخت', cls: 'badge-danger', icon: '📤' },
154 + transfer: { label: 'انتقال', cls: 'badge-warning', icon: '🔄' }
155 + }[t.type] || { label: t.type, cls: 'badge-muted', icon: '💸' };
156 +
157 + let accountText = '—';
158 + if (t.type === 'transfer') {
159 + accountText = `${this._esc(fromAcc?.name || '—')} → ${this._esc(toAcc?.name || '—')}`;
160 + } else if (t.type === 'receipt') {
161 + accountText = this._esc(toAcc?.name || '—');
162 + } else if (t.type === 'payment') {
163 + accountText = this._esc(fromAcc?.name || '—');
164 + }
165 +
166 + return `
167 + <tr>
168 + <td><span class="badge ${typeInfo.cls}">${typeInfo.icon} ${typeInfo.label}</span></td>
169 + <td>${Formatters.toPersianDigits(t.date)}</td>
170 + <td>${this._esc(t.contactName || '—')}</td>
171 + <td>${accountText}</td>
172 + <td>${TreasuryController.getMethodLabel(t.method)}</td>
173 + <td style="font-weight:700;color:${t.type === 'receipt' ? 'var(--success)' : t.type === 'payment' ? 'var(--danger)' : 'var(--warning)'}">
174 + ${t.type === 'receipt' ? '+' : t.type === 'payment' ? '-' : ''}${Formatters.money(t.amount)}
175 + </td>
176 + <td>${t.refInvoiceNumber ? '#' + Formatters.toPersianDigits(t.refInvoiceNumber) : '—'}</td>
177 + <td>
178 + <div class="row-actions">
179 + <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteTransaction('${t.id}')">🗑️</button>
180 + </div>
181 + </td>
182 + </tr>
183 + `;
184 + }).join('');
185 +
186 + const accountOptions = cache.accounts.map(a =>
187 + `<option value="${a.id}" ${txFilter.accountId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
188 + ).join('');
189 +
190 + return `
191 + <div class="toolbar">
192 + <div class="search-input-wrap">
193 + <span class="icon">🔍</span>
194 + <input type="text" class="form-control" placeholder="جستجو..." value="${this._esc(txFilter.search)}" oninput="window.TreasuryView._onTxSearch(this.value)" />
195 + </div>
196 + <select class="form-control" style="width:auto;min-width:120px" onchange="window.TreasuryView._onTxFilter('type', this.value)">
197 + <option value="">همه انواع</option>
198 + <option value="receipt" ${txFilter.type === 'receipt' ? 'selected' : ''}>دریافت</option>
199 + <option value="payment" ${txFilter.type === 'payment' ? 'selected' : ''}>پرداخت</option>
200 + <option value="transfer" ${txFilter.type === 'transfer' ? 'selected' : ''}>انتقال</option>
201 + </select>
202 + <select class="form-control" style="width:auto;min-width:150px" onchange="window.TreasuryView._onTxFilter('accountId', this.value)">
203 + <option value="">همه حساب‌ها</option>
204 + ${accountOptions}
205 + </select>
206 + <button class="btn btn-secondary" onclick="window.TreasuryView.openTransferModal()">🔄 انتقال</button>
207 + <button class="btn btn-danger" onclick="window.TreasuryView.openPaymentModal()">📤 پرداخت</button>
208 + <button class="btn btn-success" onclick="window.TreasuryView.openReceiptModal()">📥 دریافت</button>
209 + </div>
210 +
211 + <div class="table-wrap">
212 + <table>
213 + <thead>
214 + <tr>
215 + <th style="width:100px">نوع</th>
216 + <th style="width:100px">تاریخ</th>
217 + <th>طرف حساب</th>
218 + <th>حساب</th>
219 + <th style="width:100px">روش</th>
220 + <th style="width:140px">مبلغ</th>
221 + <th style="width:100px">فاکتور</th>
222 + <th style="width:80px">عملیات</th>
223 + </tr>
224 + </thead>
225 + <tbody>${rows}</tbody>
226 + </table>
227 + </div>
228 + `;
229 + }
230 +
231 + _onTxSearch(val) {
232 + txFilter.search = val;
233 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
234 + const input = document.querySelector('#treasury-content input[type="text"]');
235 + if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
236 + }
237 +
238 + _onTxFilter(key, val) {
239 + txFilter[key] = val;
240 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
241 + }
242 +
243 + // ============================================================
244 + // فرم حساب
245 + // ============================================================
246 + async openAccountModal(accountId = null) {
247 + const acc = accountId ? await TreasuryController.getAccount(accountId) : null;
248 + const isEdit = !!acc;
249 + const d = acc || {
250 + type: 'cashbox', name: '', accountNumber: '', cardNumber: '', sheba: '',
251 + bankName: '', branchName: '', branchCode: '', ownerName: '',
252 + color: '#0d9488', initialBalance: 0
253 + };
254 +
255 + const body = `
256 + <div class="form-row">
257 + <div class="form-group">
258 + <label class="form-label">نوع حساب <span class="req">*</span></label>
259 + <select class="form-control" id="accType" onchange="window.TreasuryView._onAccTypeChange()">
260 + <option value="cashbox" ${d.type === 'cashbox' ? 'selected' : ''}>صندوق نقدی</option>
261 + <option value="bank" ${d.type === 'bank' ? 'selected' : ''}>حساب بانکی</option>
262 + <option value="pos" ${d.type === 'pos' ? 'selected' : ''}>پوز</option>
263 + </select>
264 + </div>
265 + <div class="form-group">
266 + <label class="form-label">نام حساب <span class="req">*</span></label>
267 + <input type="text" class="form-control" id="accName" value="${this._esc(d.name)}" placeholder="مثلاً صندوق اصلی / بانک ملی" />
268 + </div>
269 + </div>
270 +
271 + <div id="bankFields" style="display:${d.type === 'bank' ? 'block' : 'none'}">
272 + <div class="form-row">
273 + <div class="form-group">
274 + <label class="form-label">نام بانک</label>
275 + <input type="text" class="form-control" id="accBankName" value="${this._esc(d.bankName)}" placeholder="مثلاً بانک ملی" />
276 + </div>
277 + <div class="form-group">
278 + <label class="form-label">شماره حساب</label>
279 + <input type="text" class="form-control" id="accAccountNumber" value="${this._esc(d.accountNumber)}" />
280 + </div>
281 + </div>
282 +
283 + <div class="form-row">
284 + <div class="form-group">
285 + <label class="form-label">شماره کارت (۱۶ رقم)</label>
286 + <input type="text" class="form-control" id="accCardNumber" value="${this._esc(d.cardNumber)}" maxlength="16" />
287 + </div>
288 + <div class="form-group">
289 + <label class="form-label">شماره شبا</label>
290 + <input type="text" class="form-control" id="accSheba" value="${this._esc(d.sheba)}" placeholder="IR..." />
291 + </div>
292 + </div>
293 +
294 + <div class="form-row">
295 + <div class="form-group">
296 + <label class="form-label">نام شعبه</label>
297 + <input type="text" class="form-control" id="accBranchName" value="${this._esc(d.branchName)}" />
298 + </div>
299 + <div class="form-group">
300 + <label class="form-label">کد شعبه</label>
301 + <input type="text" class="form-control" id="accBranchCode" value="${this._esc(d.branchCode)}" />
302 + </div>
303 + </div>
304 + </div>
305 +
306 + <div class="form-row">
307 + <div class="form-group">
308 + <label class="form-label">نام دارنده حساب</label>
309 + <input type="text" class="form-control" id="accOwnerName" value="${this._esc(d.ownerName)}" />
310 + </div>
311 + <div class="form-group">
312 + <label class="form-label">موجودی اولیه (ریال)</label>
313 + <input type="text" inputmode="numeric" class="form-control" id="accInitialBalance" value="${NumberInput.format(d.initialBalance || 0)}" />
314 + </div>
315 + </div>
316 +
317 + <div class="form-group">
318 + <label class="form-label">رنگ نمایشی</label>
319 + <input type="color" class="form-control" id="accColor" value="${d.color || '#0d9488'}" style="height:44px;padding:4px" />
320 + </div>
321 + `;
322 +
323 + const footer = `
324 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
325 + <button class="btn" onclick="window.TreasuryView.saveAccount(${isEdit ? `'${accountId}'` : 'null'})">💾 ذخیره</button>
326 + `;
327 +
328 + Modal.open({ title: isEdit ? 'ویرایش حساب' : 'حساب جدید', body, footer, size: 'md' });
329 + }
330 +
331 + _onAccTypeChange() {
332 + const type = document.getElementById('accType').value;
333 + document.getElementById('bankFields').style.display = type === 'bank' ? 'block' : 'none';
334 + }
335 +
336 + async saveAccount(id) {
337 + const data = {
338 + type: document.getElementById('accType').value,
339 + name: document.getElementById('accName').value,
340 + bankName: document.getElementById('accBankName')?.value || '',
341 + accountNumber: document.getElementById('accAccountNumber')?.value || '',
342 + cardNumber: document.getElementById('accCardNumber')?.value || '',
343 + sheba: document.getElementById('accSheba')?.value || '',
344 + branchName: document.getElementById('accBranchName')?.value || '',
345 + branchCode: document.getElementById('accBranchCode')?.value || '',
346 + ownerName: document.getElementById('accOwnerName').value,
347 + color: document.getElementById('accColor').value,
348 + initialBalance: NumberInput.parse(document.getElementById('accInitialBalance').value)
349 + };
350 +
351 + if (!data.name.trim()) { Toast.warning('نام حساب الزامی است'); return; }
352 +
353 + try {
354 + if (id) {
355 + await TreasuryController.updateAccount(id, data);
356 + Toast.success('حساب ویرایش شد');
357 + } else {
358 + await TreasuryController.createAccount(data);
359 + Toast.success('حساب اضافه شد');
360 + }
361 + Modal.close();
362 + await this.reload();
363 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
364 + } catch (err) {
365 + Toast.error('خطا: ' + err.message);
366 + }
367 + }
368 +
369 + async editAccount(id) {
370 + await this.openAccountModal(id);
371 + }
372 +
373 + async deleteAccount(id) {
374 + const acc = cache.accounts.find(a => a.id === id);
375 + Modal.confirm({
376 + title: 'حذف حساب',
377 + message: `آیا از حذف «${this._esc(acc?.name || '')}» مطمئن هستید؟`,
378 + confirmText: 'حذف',
379 + danger: true,
380 + onConfirm: async () => {
381 + try {
382 + await TreasuryController.deleteAccount(id);
383 + Toast.success('حساب حذف شد');
384 + await this.reload();
385 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
386 + } catch (err) {
387 + Toast.error(err.message);
388 + }
389 + }
390 + });
391 + }
392 +
393 + // ============================================================
394 + // فرم‌های تراکنش
395 + // ============================================================
396 + _buildAccountOptions(selectedId = null, filterType = null) {
397 + let list = cache.accounts;
398 + if (filterType) list = list.filter(a => a.type === filterType);
399 + return list.map(a =>
400 + `<option value="${a.id}" ${selectedId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
401 + ).join('');
402 + }
403 +
404 + _buildContactOptions() {
405 + return cache.contacts.map(c =>
406 + `<option value="${c.id}">${this._esc(c.name)}</option>`
407 + ).join('');
408 + }
409 +
410 + openReceiptModal() {
411 + if (cache.accounts.length === 0) {
412 + Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
413 + return;
414 + }
415 + const body = `
416 + <div class="form-row">
417 + <div class="form-group">
418 + <label class="form-label">تاریخ</label>
419 + <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
420 + </div>
421 + <div class="form-group">
422 + <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
423 + <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
424 + </div>
425 + </div>
426 +
427 + <div class="form-group">
428 + <label class="form-label">از طرف (شخص)</label>
429 + <select class="form-control" id="txContact">
430 + <option value="">— بدون طرف حساب —</option>
431 + ${this._buildContactOptions()}
432 + </select>
433 + </div>
434 +
435 + <div class="form-group">
436 + <label class="form-label">به حساب <span class="req">*</span></label>
437 + <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
438 + </div>
439 +
440 + <div class="form-group">
441 + <label class="form-label">روش دریافت</label>
442 + <select class="form-control" id="txMethod">
443 + <option value="cash">نقدی</option>
444 + <option value="card">کارت</option>
445 + <option value="transfer">انتقال بانکی</option>
446 + </select>
447 + </div>
448 +
449 + <div class="form-group">
450 + <label class="form-label">توضیحات</label>
451 + <textarea class="form-control" id="txDescription" rows="2"></textarea>
452 + </div>
453 + `;
454 + const footer = `
455 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
456 + <button class="btn btn-success" onclick="window.TreasuryView._saveTransaction('receipt')">📥 ثبت دریافت</button>
457 + `;
458 + Modal.open({ title: 'ثبت دریافت وجه', body, footer, size: 'md' });
459 + }
460 +
461 + openPaymentModal() {
462 + if (cache.accounts.length === 0) {
463 + Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
464 + return;
465 + }
466 + const body = `
467 + <div class="form-row">
468 + <div class="form-group">
469 + <label class="form-label">تاریخ</label>
470 + <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
471 + </div>
472 + <div class="form-group">
473 + <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
474 + <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
475 + </div>
476 + </div>
477 +
478 + <div class="form-group">
479 + <label class="form-label">به شخص</label>
480 + <select class="form-control" id="txContact">
481 + <option value="">— بدون طرف حساب —</option>
482 + ${this._buildContactOptions()}
483 + </select>
484 + </div>
485 +
486 + <div class="form-group">
487 + <label class="form-label">از حساب <span class="req">*</span></label>
488 + <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
489 + </div>
490 +
491 + <div class="form-group">
492 + <label class="form-label">روش پرداخت</label>
493 + <select class="form-control" id="txMethod">
494 + <option value="cash">نقدی</option>
495 + <option value="card">کارت</option>
496 + <option value="transfer">انتقال بانکی</option>
497 + </select>
498 + </div>
499 +
500 + <div class="form-group">
501 + <label class="form-label">توضیحات</label>
502 + <textarea class="form-control" id="txDescription" rows="2"></textarea>
503 + </div>
504 + `;
505 + const footer = `
506 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
507 + <button class="btn btn-danger" onclick="window.TreasuryView._saveTransaction('payment')">📤 ثبت پرداخت</button>
508 + `;
509 + Modal.open({ title: 'ثبت پرداخت وجه', body, footer, size: 'md' });
510 + }
511 +
512 + openTransferModal() {
513 + if (cache.accounts.length < 2) {
514 + Toast.warning('برای انتقال، حداقل دو حساب لازم است');
515 + return;
516 + }
517 + const body = `
518 + <div class="form-row">
519 + <div class="form-group">
520 + <label class="form-label">تاریخ</label>
521 + <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
522 + </div>
523 + <div class="form-group">
524 + <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
525 + <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
526 + </div>
527 + </div>
528 +
529 + <div class="form-group">
530 + <label class="form-label">از حساب <span class="req">*</span></label>
531 + <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
532 + </div>
533 +
534 + <div class="form-group">
535 + <label class="form-label">به حساب <span class="req">*</span></label>
536 + <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
537 + </div>
538 +
539 + <div class="form-group">
540 + <label class="form-label">توضیحات</label>
541 + <textarea class="form-control" id="txDescription" rows="2"></textarea>
542 + </div>
543 + `;
544 + const footer = `
545 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
546 + <button class="btn btn-warning" onclick="window.TreasuryView._saveTransaction('transfer')">🔄 انتقال</button>
547 + `;
548 + Modal.open({ title: 'انتقال بین حساب‌ها', body, footer, size: 'md' });
549 + }
550 +
551 + async _saveTransaction(type) {
552 + const amount = NumberInput.parse(document.getElementById('txAmount').value);
553 + if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
554 +
555 + const contactSelect = document.getElementById('txContact');
556 + const contactId = contactSelect?.value || null;
557 + const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
558 +
559 + const data = {
560 + type,
561 + date: document.getElementById('txDate').value,
562 + amount,
563 + method: document.getElementById('txMethod')?.value || 'cash',
564 + contactId,
565 + contactName: contact?.name || '',
566 + fromAccountId: document.getElementById('txFromAccount')?.value || null,
567 + toAccountId: document.getElementById('txToAccount')?.value || null,
568 + description: document.getElementById('txDescription')?.value || ''
569 + };
570 +
571 + if (type === 'transfer') {
572 + if (!data.fromAccountId || !data.toAccountId) {
573 + Toast.warning('حساب مبدأ و مقصد رو انتخاب کنید');
574 + return;
575 + }
576 + if (data.fromAccountId === data.toAccountId) {
577 + Toast.warning('حساب مبدأ و مقصد نباید یکی باشند');
578 + return;
579 + }
580 + }
581 +
582 + try {
583 + await TreasuryController.createTransaction(data);
584 + Toast.success(TreasuryController.getTypeLabel(type) + ' ثبت شد');
585 + Modal.close();
586 + await this.reload();
587 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
588 + } catch (err) {
589 + Toast.error('خطا: ' + err.message);
590 + }
591 + }
592 +
593 + async deleteTransaction(id) {
594 + Modal.confirm({
595 + title: 'حذف تراکنش',
596 + message: 'آیا از حذف این تراکنش مطمئن هستید؟ موجودی حساب به‌روزرسانی می‌شود.',
597 + confirmText: 'حذف',
598 + danger: true,
599 + onConfirm: async () => {
600 + await TreasuryController.deleteTransaction(id);
601 + Toast.success('تراکنش حذف شد');
602 + await this.reload();
603 + document.getElementById('treasury-content').innerHTML = this.renderTabContent();
604 + }
605 + });
606 + }
607 +
608 + _todayJalali() {
609 + const d = new Date();
610 + const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
611 + const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
612 + let jy = (gy <= 1600) ? 0 : 979;
613 + let gy2 = gy - (gy <= 1600 ? 621 : 1600);
614 + const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
615 + 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];
616 + jy += 33 * Math.floor(days / 12053);
617 + days %= 12053;
618 + jy += 4 * Math.floor(days / 1461);
619 + days %= 1461;
620 + if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
621 + const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
622 + const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
623 + return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
624 + }
625 +
626 + _esc(s) {
627 + if (!s) return '';
628 + return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
629 + }
630 +}
631 +
632 +export const TreasuryView = new TreasuryViewImpl();
633 +window.TreasuryView = TreasuryView;
\ No newline at end of file