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

Phase 11: Excel Bridge (export/import, templates)

Davood Mehraban committed Sep 18, 2026 at 22:04 UTC 7390c1f923f1ca8d555b4a726506d145cf03ad9d
3 files changed +768 -15
index.html
+2
@@ -8,6 +8,8 @@
8
9 <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
10 <link rel="stylesheet" href="/src/styles/main.css" />
11 +<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
12 +<link rel="icon" href="data:,">
13 </head>
14 <body>
15 <div id="app" class="app">
src/controllers/ExcelController.js new
+540
@@ -0,0 +1,540 @@
1 +// ============================================================
2 +// ExcelController — خروجی و ورودی Excel
3 +// ============================================================
4 +
5 +import { StorageService } from '../core/StorageService.js';
6 +import { Auth } from '../core/Auth.js';
7 +import { Jalali } from '../utils/Jalali.js';
8 +import { ContactController } from './ContactController.js';
9 +import { ProductController } from './ProductController.js';
10 +
11 +class ExcelControllerImpl {
12 + // ============================================================
13 + // خروجی کامل (Backup Excel)
14 + // ============================================================
15 + async exportAll() {
16 + const user = Auth.current();
17 + if (!user) throw new Error('کاربر یافت نشد');
18 +
19 + const [companies, contacts, products, invoices, cheques, treasury, expenses, units, categories] = await Promise.all([
20 + StorageService.getByOwner('companies', user.id),
21 + StorageService.getByOwner('contacts', user.id),
22 + StorageService.getByOwner('products', user.id),
23 + StorageService.getByOwner('invoices', user.id),
24 + StorageService.getByOwner('cheques', user.id),
25 + StorageService.getByOwner('treasury', user.id),
26 + StorageService.getByOwner('expenses', user.id),
27 + StorageService.getByOwner('units', user.id),
28 + StorageService.getByOwner('categories', user.id)
29 + ]);
30 +
31 + const accounts = treasury.filter(t => t.recordType === 'account');
32 + const transactions = treasury.filter(t => t.recordType === 'transaction');
33 + const stockMovements = await StorageService.getByOwner('stock_movements', user.id);
34 +
35 + const wb = XLSX.utils.book_new();
36 +
37 + // ۱. کالاها
38 + const productsData = [
39 + ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی', 'نوع']
40 + ];
41 + const stockMap = await ProductController.getStockMap(products.map(p => p.id));
42 + products.forEach(p => {
43 + const unit = units.find(u => u.id === p.unitId);
44 + productsData.push([
45 + p.code || '',
46 + p.name || '',
47 + p.spec || '',
48 + unit?.name || p.unit || 'عدد',
49 + Number(p.buyPrice) || 0,
50 + Number(p.sellPrice) || 0,
51 + Number(p.minStock) || 0,
52 + p.trackInventory === false ? '—' : (stockMap[p.id] || 0),
53 + p.trackInventory === false ? 'خدمت' : 'کالا'
54 + ]);
55 + });
56 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(productsData), 'کالاها');
57 +
58 + // ۲. اشخاص
59 + const contactsData = [
60 + ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی', 'مانده']
61 + ];
62 + const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id));
63 + contacts.forEach(c => {
64 + contactsData.push([
65 + c.name || '',
66 + c.entityType === 'legal' ? 'حقوقی' : 'حقیقی',
67 + c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامین‌کننده' : 'هر دو',
68 + c.mobile || '',
69 + c.phone || '',
70 + c.nationalId || '',
71 + c.economicCode || '',
72 + c.regNumber || '',
73 + c.postalCode || '',
74 + c.address || '',
75 + Number(balanceMap[c.id]) || 0
76 + ]);
77 + });
78 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(contactsData), 'اشخاص');
79 +
80 + // ۳. فاکتورها (خلاصه)
81 + const invoicesData = [
82 + ['شماره', 'تاریخ', 'نوع', 'پیش‌فاکتور', 'فروشنده', 'خریدار', 'جمع کل', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداخت‌شده', 'باقیمانده', 'وضعیت', 'توضیحات']
83 + ];
84 + const kindLabels = {
85 + sale: 'فروش', purchase: 'خرید', sale_return: 'برگشت فروش',
86 + purchase_return: 'برگشت خرید', non_formal: 'غیررسمی'
87 + };
88 + invoices.forEach(inv => {
89 + invoicesData.push([
90 + inv.number || '',
91 + inv.date || '',
92 + kindLabels[inv.kind] || inv.kind,
93 + inv.isPreInvoice ? 'بله' : 'خیر',
94 + inv.companyName || '',
95 + inv.contactName || '',
96 + Number(inv.subtotal) || 0,
97 + Number(inv.totalDiscount) || 0,
98 + Number(inv.vatAmount) || 0,
99 + Number(inv.grandTotal) || 0,
100 + Number(inv.paidAmount) || 0,
101 + Number(inv.remaining) || 0,
102 + inv.status === 'paid' ? 'تسویه' : inv.status === 'partial' ? 'جزئی' : 'پرداخت‌نشده',
103 + inv.description || ''
104 + ]);
105 + });
106 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(invoicesData), 'فاکتورها');
107 +
108 + // ۴. اقلام فاکتور
109 + const itemsData = [
110 + ['شماره فاکتور', 'تاریخ', 'کالا', 'واحد', 'تعداد', 'قیمت واحد', 'تخفیف', 'جمع ردیف']
111 + ];
112 + invoices.forEach(inv => {
113 + (inv.items || []).forEach(it => {
114 + itemsData.push([
115 + inv.number || '',
116 + inv.date || '',
117 + it.productName || '',
118 + it.unit || 'عدد',
119 + Number(it.qty) || 0,
120 + Number(it.price) || 0,
121 + Number(it.discount) || 0,
122 + Number(it.lineTotal) || 0
123 + ]);
124 + });
125 + });
126 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(itemsData), 'اقلام فاکتور');
127 +
128 + // ۵. چک‌ها
129 + const chequesData = [
130 + ['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'شعبه', 'مبلغ', 'تاریخ صدور', 'سررسید', 'وضعیت', 'توضیحات']
131 + ];
132 + const chequeStatusLabels = {
133 + pending: 'در جریان', cleared: 'وصول شده', bounced: 'برگشتی',
134 + returned: 'عودت داده شده', spent: 'خرج شده'
135 + };
136 + cheques.forEach(c => {
137 + chequesData.push([
138 + c.direction === 'inbound' ? 'دریافتی' : 'پرداختی',
139 + c.contactName || '',
140 + c.sayadNumber || '',
141 + c.bankName || '',
142 + c.branchName || '',
143 + Number(c.amount) || 0,
144 + c.issueDate || '',
145 + c.dueDate || '',
146 + chequeStatusLabels[c.status] || c.status,
147 + c.description || ''
148 + ]);
149 + });
150 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(chequesData), 'چک‌ها');
151 +
152 + // ۶. تراکنش‌ها
153 + const txData = [
154 + ['نوع', 'تاریخ', 'طرف حساب', 'از حساب', 'به حساب', 'مبلغ', 'روش', 'توضیحات']
155 + ];
156 + const methodLabels = { cash: 'نقدی', card: 'کارت', cheque: 'چک', transfer: 'انتقال' };
157 + transactions.forEach(t => {
158 + const fromAcc = accounts.find(a => a.id === t.fromAccountId);
159 + const toAcc = accounts.find(a => a.id === t.toAccountId);
160 + txData.push([
161 + t.type === 'receipt' ? 'دریافت' : t.type === 'payment' ? 'پرداخت' : 'انتقال',
162 + t.date || '',
163 + t.contactName || '',
164 + fromAcc?.name || '',
165 + toAcc?.name || '',
166 + Number(t.amount) || 0,
167 + methodLabels[t.method] || t.method,
168 + t.description || ''
169 + ]);
170 + });
171 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(txData), 'تراکنش‌ها');
172 +
173 + // ۷. هزینه‌ها
174 + const expData = [
175 + ['نوع', 'تاریخ', 'سرفصل', 'شرح', 'روش', 'شماره پیگیری', 'مبلغ']
176 + ];
177 + expenses.forEach(e => {
178 + expData.push([
179 + e.kind === 'income' ? 'درآمد' : 'هزینه',
180 + e.date || '',
181 + e.category || '',
182 + e.description || '',
183 + methodLabels[e.method] || e.method,
184 + e.refNumber || '',
185 + Number(e.amount) || 0
186 + ]);
187 + });
188 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(expData), 'هزینه‌ها');
189 +
190 + // ۸. شرکت‌ها
191 + const compData = [
192 + ['نام', 'نوع', 'تلفن', 'شناسه ملی', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی']
193 + ];
194 + companies.forEach(c => {
195 + compData.push([
196 + c.name || '',
197 + c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی',
198 + c.phone || '',
199 + c.national_id || '',
200 + c.economic_code || '',
201 + c.reg_number || '',
202 + c.postal_code || '',
203 + c.address || ''
204 + ]);
205 + });
206 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(compData), 'شرکت‌ها');
207 +
208 + // ۹. کاردکس انبار
209 + const mvData = [
210 + ['کالا', 'نوع حرکت', 'تعداد', 'مرجع', 'یادداشت', 'تاریخ']
211 + ];
212 + const typeLabels = { in: 'ورود', out: 'خروج', adjust: 'اصلاح' };
213 + stockMovements.forEach(m => {
214 + const p = products.find(prod => prod.id === m.productId);
215 + mvData.push([
216 + p?.name || '',
217 + typeLabels[m.type] || m.type,
218 + Number(m.qty) || 0,
219 + m.refType || '',
220 + m.note || '',
221 + m.date || ''
222 + ]);
223 + });
224 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(mvData), 'کاردکس');
225 +
226 + // دانلود
227 + const date = Jalali.today().replace(/\//g, '-');
228 + XLSX.writeFile(wb, `finora-backup-${date}.xlsx`);
229 +
230 + return {
231 + sheets: 9,
232 + counts: {
233 + products: products.length,
234 + contacts: contacts.length,
235 + invoices: invoices.length,
236 + items: itemsData.length - 1,
237 + cheques: cheques.length,
238 + transactions: transactions.length,
239 + expenses: expenses.length,
240 + companies: companies.length,
241 + movements: stockMovements.length
242 + }
243 + };
244 + }
245 +
246 + // ============================================================
247 + // خروجی انتخابی
248 + // ============================================================
249 + async exportSection(section) {
250 + const user = Auth.current();
251 + if (!user) throw new Error('کاربر یافت نشد');
252 +
253 + const wb = XLSX.utils.book_new();
254 + const date = Jalali.today().replace(/\//g, '-');
255 +
256 + switch (section) {
257 + case 'products': {
258 + const products = await StorageService.getByOwner('products', user.id);
259 + const units = await StorageService.getByOwner('units', user.id);
260 + const stockMap = await ProductController.getStockMap(products.map(p => p.id));
261 + const data = [['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی']];
262 + products.forEach(p => {
263 + const unit = units.find(u => u.id === p.unitId);
264 + data.push([
265 + p.code || '', p.name || '', p.spec || '',
266 + unit?.name || p.unit || 'عدد',
267 + Number(p.buyPrice) || 0,
268 + Number(p.sellPrice) || 0,
269 + Number(p.minStock) || 0,
270 + p.trackInventory === false ? '—' : (stockMap[p.id] || 0)
271 + ]);
272 + });
273 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'کالاها');
274 + XLSX.writeFile(wb, `finora-products-${date}.xlsx`);
275 + return { count: products.length };
276 + }
277 +
278 + case 'contacts': {
279 + const contacts = await StorageService.getByOwner('contacts', user.id);
280 + const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id));
281 + const data = [['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد پستی', 'نشانی', 'مانده']];
282 + contacts.forEach(c => {
283 + data.push([
284 + c.name || '',
285 + c.entityType === 'legal' ? 'حقوقی' : 'حقیقی',
286 + c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامین‌کننده' : 'هر دو',
287 + c.mobile || '', c.phone || '', c.nationalId || '',
288 + c.postalCode || '', c.address || '',
289 + Number(balanceMap[c.id]) || 0
290 + ]);
291 + });
292 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'اشخاص');
293 + XLSX.writeFile(wb, `finora-contacts-${date}.xlsx`);
294 + return { count: contacts.length };
295 + }
296 +
297 + case 'invoices': {
298 + const invoices = await StorageService.getByOwner('invoices', user.id);
299 + const data = [['شماره', 'تاریخ', 'نوع', 'خریدار', 'جمع', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداخت‌شده', 'باقیمانده']];
300 + invoices.forEach(inv => {
301 + data.push([
302 + inv.number || '', inv.date || '',
303 + inv.kindLabel || inv.kind || '',
304 + inv.contactName || '',
305 + Number(inv.subtotal) || 0,
306 + Number(inv.totalDiscount) || 0,
307 + Number(inv.vatAmount) || 0,
308 + Number(inv.grandTotal) || 0,
309 + Number(inv.paidAmount) || 0,
310 + Number(inv.remaining) || 0
311 + ]);
312 + });
313 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'فاکتورها');
314 + XLSX.writeFile(wb, `finora-invoices-${date}.xlsx`);
315 + return { count: invoices.length };
316 + }
317 +
318 + case 'cheques': {
319 + const cheques = await StorageService.getByOwner('cheques', user.id);
320 + const data = [['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'مبلغ', 'سررسید', 'وضعیت']];
321 + cheques.forEach(c => {
322 + data.push([
323 + c.direction === 'inbound' ? 'دریافتی' : 'پرداختی',
324 + c.contactName || '', c.sayadNumber || '', c.bankName || '',
325 + Number(c.amount) || 0, c.dueDate || '', c.status || ''
326 + ]);
327 + });
328 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'چک‌ها');
329 + XLSX.writeFile(wb, `finora-cheques-${date}.xlsx`);
330 + return { count: cheques.length };
331 + }
332 +
333 + case 'expenses': {
334 + const expenses = await StorageService.getByOwner('expenses', user.id);
335 + const data = [['نوع', 'تاریخ', 'سرفصل', 'شرح', 'مبلغ']];
336 + expenses.forEach(e => {
337 + data.push([
338 + e.kind === 'income' ? 'درآمد' : 'هزینه',
339 + e.date || '', e.category || '',
340 + e.description || '', Number(e.amount) || 0
341 + ]);
342 + });
343 + XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'هزینه‌ها');
344 + XLSX.writeFile(wb, `finora-expenses-${date}.xlsx`);
345 + return { count: expenses.length };
346 + }
347 +
348 + default:
349 + throw new Error('بخش نامعتبر');
350 + }
351 + }
352 +
353 + // ============================================================
354 + // ورودی از Excel
355 + // ============================================================
356 + async readExcelFile(file) {
357 + return new Promise((resolve, reject) => {
358 + const reader = new FileReader();
359 + reader.onload = (e) => {
360 + try {
361 + const data = new Uint8Array(e.target.result);
362 + const workbook = XLSX.read(data, { type: 'array' });
363 + const result = {};
364 + workbook.SheetNames.forEach(sheetName => {
365 + result[sheetName] = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
366 + });
367 + resolve(result);
368 + } catch (err) {
369 + reject(new Error('خطا در خواندن فایل اکسل: ' + err.message));
370 + }
371 + };
372 + reader.onerror = () => reject(new Error('خطا در خواندن فایل'));
373 + reader.readAsArrayBuffer(file);
374 + });
375 + }
376 +
377 + /**
378 + * پیش‌نمایش فایل قبل از ایمپورت
379 + */
380 + async previewFile(file) {
381 + const data = await this.readExcelFile(file);
382 + const sheets = Object.keys(data).map(name => ({
383 + name,
384 + count: data[name].length,
385 + sample: data[name].slice(0, 3)
386 + }));
387 + return { sheets, raw: data };
388 + }
389 +
390 + /**
391 + * ایمپورت کالاها از Excel
392 + */
393 + async importProducts(rawData, options = {}) {
394 + const user = Auth.current();
395 + if (!user) throw new Error('کاربر یافت نشد');
396 +
397 + // پیدا کردن شیت مناسب
398 + const sheetName = Object.keys(rawData).find(n =>
399 + n.includes('کالا') || n.toLowerCase().includes('product')
400 + ) || Object.keys(rawData)[0];
401 +
402 + const rows = rawData[sheetName] || [];
403 + if (rows.length === 0) throw new Error('شیت کالاها خالی است');
404 +
405 + const mode = options.mode || 'merge';
406 + const existing = await StorageService.getByOwner('products', user.id);
407 +
408 + if (mode === 'replace') {
409 + for (const p of existing) {
410 + await StorageService.delete('products', p.id);
411 + }
412 + }
413 +
414 + let added = 0, skipped = 0;
415 + for (const row of rows) {
416 + const name = row['نام'] || row['نام کالا'] || row['عنوان'];
417 + if (!name) { skipped++; continue; }
418 +
419 + const code = String(row['کد'] || row['کد کالا'] || '').trim();
420 + if (mode === 'merge' && code && existing.some(p => p.code === code)) {
421 + skipped++;
422 + continue;
423 + }
424 +
425 + const product = {
426 + id: StorageService.uid('prod_'),
427 + ownerUserId: user.id,
428 + code,
429 + name: String(name).trim(),
430 + spec: String(row['مشخصه'] || row['مشخصه و نوع'] || '').trim(),
431 + unit: String(row['واحد'] || 'عدد').trim(),
432 + unitId: null,
433 + categoryId: null,
434 + buyPrice: Number(row['قیمت خرید'] || row['قیمت خرید (ریال)'] || 0) || 0,
435 + sellPrice: Number(row['قیمت فروش'] || row['قیمت فروش (ریال)'] || 0) || 0,
436 + minStock: Number(row['نقطه سفارش'] || 0) || 0,
437 + trackInventory: (row['نوع'] || '').toString().includes('خدمت') ? false : true,
438 + isActiveSell: true,
439 + isActiveBuy: true,
440 + description: ''
441 + };
442 + await StorageService.put('products', product);
443 + added++;
444 + }
445 +
446 + return { added, skipped, mode };
447 + }
448 +
449 + /**
450 + * ایمپورت اشخاص از Excel
451 + */
452 + async importContacts(rawData, options = {}) {
453 + const user = Auth.current();
454 + if (!user) throw new Error('کاربر یافت نشد');
455 +
456 + const sheetName = Object.keys(rawData).find(n =>
457 + n.includes('اشخاص') || n.toLowerCase().includes('contact')
458 + ) || Object.keys(rawData)[0];
459 +
460 + const rows = rawData[sheetName] || [];
461 + if (rows.length === 0) throw new Error('شیت اشخاص خالی است');
462 +
463 + const mode = options.mode || 'merge';
464 + const existing = await StorageService.getByOwner('contacts', user.id);
465 +
466 + if (mode === 'replace') {
467 + for (const c of existing) {
468 + await StorageService.delete('contacts', c.id);
469 + }
470 + }
471 +
472 + let added = 0, skipped = 0;
473 + for (const row of rows) {
474 + const name = row['نام'] || row['نام شخص یا شرکت'] || row['نام شخص'];
475 + if (!name) { skipped++; continue; }
476 +
477 + const mobile = String(row['موبایل'] || row['شماره همراه'] || '').trim();
478 + if (mode === 'merge' && mobile && existing.some(c => c.mobile === mobile)) {
479 + skipped++;
480 + continue;
481 + }
482 +
483 + const entityType = (row['نوع'] || row['نوع (حقیقی/حقوقی)'] || '').toString().includes('حقوقی') ? 'legal' : 'natural';
484 +
485 + const contact = {
486 + id: StorageService.uid('contact_'),
487 + ownerUserId: user.id,
488 + entityType,
489 + role: (row['نقش'] || '').toString().includes('تامین') ? 'supplier' : 'customer',
490 + prefix: '',
491 + name: String(name).trim(),
492 + mobile,
493 + phone: String(row['تلفن'] || '').trim(),
494 + nationalId: String(row['کد ملی/شناسه'] || row['شناسه یا کد ملی'] || row['کد ملی'] || '').trim(),
495 + economicCode: String(row['کد اقتصادی'] || '').trim(),
496 + regNumber: String(row['شماره ثبت'] || '').trim(),
497 + postalCode: String(row['کد پستی'] || '').trim(),
498 + address: String(row['نشانی'] || '').trim(),
499 + tags: [],
500 + note: '',
501 + isActive: true
502 + };
503 + await StorageService.put('contacts', contact);
504 + added++;
505 + }
506 +
507 + return { added, skipped, mode };
508 + }
509 +
510 + // ============================================================
511 + // دانلود قالب‌های نمونه
512 + // ============================================================
513 + downloadProductsTemplate() {
514 + const data = [
515 + ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'نوع'],
516 + ['P001', 'هارد سرور 2.5 اینچ', 'SAS 1TB', 'عدد', 30000000, 37000000, 5, 'کالا'],
517 + ['P002', 'سوئیچ 24 پورت', 'با 2 پاور', 'عدد', 1800000000, 2180000000, 2, 'کالا'],
518 + ['S001', 'خدمات نصب و راه‌اندازی', '', 'ساعت', 0, 5000000, 0, 'خدمت']
519 + ];
520 + const ws = XLSX.utils.aoa_to_sheet(data);
521 + const wb = XLSX.utils.book_new();
522 + XLSX.utils.book_append_sheet(wb, ws, 'کالاها');
523 + XLSX.writeFile(wb, 'finora-products-template.xlsx');
524 + }
525 +
526 + downloadContactsTemplate() {
527 + const data = [
528 + ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'],
529 + ['شرکت آرا بتن', 'حقوقی', 'مشتری', '09124376991', '', '14008507476', '14008507476', '544926', '1445956311', 'تهران'],
530 + ['آقای احمدی', 'حقیقی', 'مشتری', '09121111111', '', '1234567890', '', '', '1234567890', 'اصفهان']
531 + ];
532 + const ws = XLSX.utils.aoa_to_sheet(data);
533 + const wb = XLSX.utils.book_new();
534 + XLSX.utils.book_append_sheet(wb, ws, 'اشخاص');
535 + XLSX.writeFile(wb, 'finora-contacts-template.xlsx');
536 + }
537 +}
538 +
539 +export const ExcelController = new ExcelControllerImpl();
540 +window.ExcelController = ExcelController;
\ No newline at end of file
src/views/SettingsView.js
+226 -15
@@ -1,5 +1,5 @@
1 // ============================================================
2 -// SettingsView — صفحه‌ی تنظیمات، بکاپ و شرکت
2 +// SettingsView — صفحه‌ی تنظیمات، بکاپ، شرکت و Excel
3 // ============================================================
4
5 import { SettingsController } from '../controllers/SettingsController.js';
@@ -10,6 +10,7 @@ import { Modal } from '../core/Modal.js';
10 import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 +import { ExcelController } from '../controllers/ExcelController.js';
14
15 let cache = { company: {}, stats: {} };
16
@@ -19,11 +20,12 @@ class SettingsViewImpl {
20 return `
21 <div class="page-title">
22 <h2>تنظیمات</h2>
22 - <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری و تنظیمات سیستم</p>
23 + <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری، Excel و تنظیمات سیستم</p>
24 </div>
25
26 <div class="settings-grid">
27 ${this._renderCompanyCard()}
28 + ${this._renderExcelCard()}
29 ${this._renderShortcutsCard()}
30 ${this._renderBackupCard()}
31 ${this._renderStatsCard()}
@@ -94,6 +96,224 @@ class SettingsViewImpl {
96 `;
97 }
98
99 + // ============================================================
100 + // کارت Excel (جدید)
101 + // ============================================================
102 + _renderExcelCard() {
103 + const s = cache.stats;
104 + return `
105 + <div class="card settings-card" style="border-color:#bbf7d0;background:linear-gradient(135deg,#f0fdf4,#f8fafc)">
106 + <div class="settings-card-header">
107 + <div class="settings-card-icon" style="background:linear-gradient(135deg,#16a34a,#15803d)">📊</div>
108 + <div>
109 + <h3 class="settings-card-title">Excel — خروجی و ورودی</h3>
110 + <p class="settings-card-desc">داده‌ها را به Excel ببر یا از Excel بیار</p>
111 + </div>
112 + </div>
113 +
114 + <div style="font-size:12.5px;color:var(--text-muted);line-height:1.8;margin-bottom:12px;padding:10px 12px;background:rgba(255,255,255,.6);border-radius:8px">
115 + <strong>💡 نکته:</strong> از این بخش می‌تونی کل داده‌ها رو در یه فایل Excel بگیری، یا از یه فایل Excel (که قبلاً آماده کردی) کالا و اشخاص اضافه کنی.
116 + </div>
117 +
118 + <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px">
119 + <button class="btn" style="background:linear-gradient(135deg,#16a34a,#15803d)" onclick="window.SettingsView.exportAllExcel()">
120 + 📥 خروجی کامل (Excel)
121 + </button>
122 + <button class="btn btn-secondary" onclick="window.SettingsView.openExportSectionModal()">
123 + 🎯 خروجی انتخابی
124 + </button>
125 + </div>
126 +
127 + <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
128 + <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📤 ورود از Excel</div>
129 + <div style="display:flex;gap:10px;flex-wrap:wrap">
130 + <button class="btn btn-secondary" onclick="window.SettingsView.importProductsExcel()">
131 + 📦 ورود کالاها
132 + </button>
133 + <button class="btn btn-secondary" onclick="window.SettingsView.importContactsExcel()">
134 + 👥 ورود اشخاص
135 + </button>
136 + </div>
137 + </div>
138 +
139 + <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
140 + <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📄 قالب‌های نمونه</div>
141 + <div style="display:flex;gap:10px;flex-wrap:wrap">
142 + <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadProductsTemplate()">
143 + 📋 قالب کالاها
144 + </button>
145 + <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadContactsTemplate()">
146 + 📋 قالب اشخاص
147 + </button>
148 + </div>
149 + </div>
150 + </div>
151 + `;
152 + }
153 +
154 + async exportAllExcel() {
155 + try {
156 + Toast.info('در حال آماده‌سازی فایل Excel...');
157 + const result = await ExcelController.exportAll();
158 + Toast.success(`فایل Excel با ${Formatters.toPersianDigits(result.sheets)} شیت دانلود شد`);
159 + } catch (err) {
160 + console.error(err);
161 + Toast.error('خطا در خروجی: ' + err.message);
162 + }
163 + }
164 +
165 + openExportSectionModal() {
166 + const body = `
167 + <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">کدوم بخش رو می‌خوای به Excel ببری؟</p>
168 + <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
169 + <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('products')">
170 + <div style="font-size:22px">📦</div>
171 + <div style="font-size:12.5px">کالاها</div>
172 + </button>
173 + <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('contacts')">
174 + <div style="font-size:22px">👥</div>
175 + <div style="font-size:12.5px">اشخاص</div>
176 + </button>
177 + <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('invoices')">
178 + <div style="font-size:22px">🧾</div>
179 + <div style="font-size:12.5px">فاکتورها</div>
180 + </button>
181 + <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('cheques')">
182 + <div style="font-size:22px">💳</div>
183 + <div style="font-size:12.5px">چک‌ها</div>
184 + </button>
185 + <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('expenses')">
186 + <div style="font-size:22px">💰</div>
187 + <div style="font-size:12.5px">هزینه و درآمد</div>
188 + </button>
189 + </div>
190 + `;
191 + const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>`;
192 + Modal.open({ title: '🎯 خروجی انتخابی به Excel', body, footer, size: 'md' });
193 + }
194 +
195 + async _exportSection(section) {
196 + try {
197 + const result = await ExcelController.exportSection(section);
198 + Toast.success(`فایل دانلود شد (${Formatters.number(result.count)} مورد)`);
199 + Modal.close();
200 + } catch (err) {
201 + Toast.error('خطا: ' + err.message);
202 + }
203 + }
204 +
205 + // ============================================================
206 + // ورودی از Excel
207 + // ============================================================
208 + importProductsExcel() {
209 + const input = document.createElement('input');
210 + input.type = 'file';
211 + input.accept = '.xlsx,.xls';
212 + input.onchange = async (e) => {
213 + const file = e.target.files[0];
214 + if (!file) return;
215 + await this._handleImportFile(file, 'products');
216 + };
217 + input.click();
218 + }
219 +
220 + importContactsExcel() {
221 + const input = document.createElement('input');
222 + input.type = 'file';
223 + input.accept = '.xlsx,.xls';
224 + input.onchange = async (e) => {
225 + const file = e.target.files[0];
226 + if (!file) return;
227 + await this._handleImportFile(file, 'contacts');
228 + };
229 + input.click();
230 + }
231 +
232 + async _handleImportFile(file, kind) {
233 + try {
234 + Toast.info('در حال خواندن فایل...');
235 + const preview = await ExcelController.previewFile(file);
236 +
237 + const kindLabel = kind === 'products' ? 'کالاها' : 'اشخاص';
238 + const sheetsHtml = preview.sheets.map(s => `
239 + <div style="padding:8px 12px;background:var(--bg);border-radius:8px;margin-bottom:6px;font-size:12.5px">
240 + <strong>${this._esc(s.name)}</strong>
241 + <span style="color:var(--text-muted);margin-right:6px">(${Formatters.number(s.count)} سطر)</span>
242 + </div>
243 + `).join('');
244 +
245 + const body = `
246 + <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px">
247 + فایل <strong>${this._esc(file.name)}</strong> خونده شد. شیت‌های موجود:
248 + </p>
249 + ${sheetsHtml}
250 + <div class="form-group" style="margin-top:14px">
251 + <label class="form-label">حالت ورود</label>
252 + <select class="form-control" id="importMode">
253 + <option value="merge">🔀 ادغام (Merge) — فقط موارد جدید اضافه می‌شن</option>
254 + <option value="replace">🔄 جایگزینی (Replace) — همه‌ی ${kindLabel} فعلی پاک و از فایل جایگزین می‌شن</option>
255 + </select>
256 + </div>
257 + `;
258 + const footer = `
259 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
260 + <button class="btn btn-success" onclick="window.SettingsView._confirmImport(${JSON.stringify(kind).replace(/"/g, "'")}, '${this._esc(file.name)}')">✅ شروع ایمپورت</button>
261 + `;
262 + Modal.open({ title: `📤 ورود ${kindLabel} از Excel`, body, footer, size: 'md' });
263 +
264 + // ذخیره‌ی موقت داده
265 + window.__importRawData = preview.raw;
266 + window.__importKind = kind;
267 + } catch (err) {
268 + console.error(err);
269 + Toast.error('خطا: ' + err.message);
270 + }
271 + }
272 +
273 + async _confirmImport(kind, fileName) {
274 + const mode = document.getElementById('importMode').value;
275 + const rawData = window.__importRawData;
276 +
277 + if (!rawData) {
278 + Toast.error('داده‌ای برای ایمپورت نیست');
279 + return;
280 + }
281 +
282 + try {
283 + Toast.info('در حال ایمپورت...');
284 + let result;
285 + if (kind === 'products') {
286 + result = await ExcelController.importProducts(rawData, { mode });
287 + } else {
288 + result = await ExcelController.importContacts(rawData, { mode });
289 + }
290 +
291 + Modal.close();
292 + Toast.success(`ایمپورت انجام شد: ${Formatters.number(result.added)} اضافه، ${Formatters.number(result.skipped)} رد شده`);
293 +
294 + // رفرش KPI ها
295 + await this.reload();
296 + const grid = document.querySelector('.settings-grid');
297 + if (grid) grid.innerHTML = this._renderAllCards();
298 + } catch (err) {
299 + console.error(err);
300 + Toast.error('خطا در ایمپورت: ' + err.message);
301 + } finally {
302 + window.__importRawData = null;
303 + window.__importKind = null;
304 + }
305 + }
306 +
307 + downloadProductsTemplate() {
308 + ExcelController.downloadProductsTemplate();
309 + Toast.success('قالب کالاها دانلود شد');
310 + }
311 +
312 + downloadContactsTemplate() {
313 + ExcelController.downloadContactsTemplate();
314 + Toast.success('قالب اشخاص دانلود شد');
315 + }
316 +
317 // ============================================================
318 // کارت میانبرهای صفحه‌کلید
319 // ============================================================
@@ -141,15 +361,6 @@ class SettingsViewImpl {
361 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
362 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
363 </div>
144 -
145 - <div style="margin-top:14px;padding:12px 14px;background:var(--bg);border-radius:8px;font-size:11.5px;color:var(--text-muted);line-height:2">
146 - <div><strong style="color:var(--text)">راهنمای سریع:</strong></div>
147 - <div>• <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">Enter</kbd> — تأیید فرم</div>
148 - <div>• <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">Esc</kbd> — بستن مودال</div>
149 - <div>• <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">Ctrl+S</kbd> — ذخیره</div>
150 - <div>• <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">Ctrl+Enter</kbd> — تأیید از هر فیلد (حتی توضیحات)</div>
151 - <div>• <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">+</kbd> و <kbd style="background:var(--card-bg);border:1px solid var(--border);padding:1px 6px;border-radius:4px;font-family:monospace">−</kbd> — روی فیلدهای مبلغ، ضریب صفر</div>
152 - </div>
364 </div>
365 `;
366 }
@@ -184,7 +395,6 @@ class SettingsViewImpl {
395 onConfirm: () => {
396 KeyboardShortcuts.resetSettings();
397 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
187 - // رفرش کارت
398 const grid = document.querySelector('.settings-grid');
399 if (grid) grid.innerHTML = this._renderAllCards();
400 }
@@ -200,8 +410,8 @@ class SettingsViewImpl {
410 <div class="settings-card-header">
411 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
412 <div>
203 - <h3 class="settings-card-title">پشتیبان‌گیری و بازیابی</h3>
204 - <p class="settings-card-desc">از داده‌های خود نسخه‌ی پشتیبان بگیرید تا در صورت نیاز بازیابی کنید</p>
413 + <h3 class="settings-card-title">پشتیبان‌گیری JSON</h3>
414 + <p class="settings-card-desc">پشتیبان‌گیری کامل از دیتابیس (فقط JSON، نه Excel)</p>
415 </div>
416 </div>
417
@@ -311,6 +521,7 @@ class SettingsViewImpl {
521
522 _renderAllCards() {
523 return this._renderCompanyCard()
524 + + this._renderExcelCard()
525 + this._renderShortcutsCard()
526 + this._renderBackupCard()
527 + this._renderStatsCard()
@@ -410,7 +621,7 @@ class SettingsViewImpl {
621 }
622
623 // ============================================================
413 - // بکاپ
624 + // بکاپ JSON
625 // ============================================================
626 async downloadBackup() {
627 try {