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

fix(a02): validate full Excel master batches and commit merge in one IndexedDB transaction

davoodmehraban89 committed Oct 31, 2026 at 06:48 UTC c3c2716a78ed6b374061e05d636aff0d072173b9
1 file changed +105 -79
src/controllers/ExcelController.js
+105 -79
@@ -22,6 +22,22 @@ import { ContactController } from './ContactController.js';
22 import { ProductController } from './ProductController.js';
23 import { Toast } from '../core/Toast.js';
24
25 +
26 +// Reusable preflight for monetary Excel cells. Reject malformed amounts rather
27 +// than silently turning a customer's financial value into zero.
28 +function excelRial(value, field) {
29 + if (value === null || value === undefined || value === '') return 0;
30 + const ascii = String(value)
31 + .replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776))
32 + .replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632))
33 + .replace(/[,\s،٬]/g, '');
34 + const amount = Number(ascii);
35 + if (!/^\d+$/.test(ascii) || !Number.isSafeInteger(amount)) {
36 + throw new Error('مقدار ریالی نامعتبر در ستون ' + field);
37 + }
38 + return amount;
39 +}
40 +
41 class ExcelControllerImpl {
42 // ============================================================
43 // ذخیره فایل + نمایش پیام + باز کردن خودکار (سازگار با Tauri)
@@ -456,119 +472,129 @@ class ExcelControllerImpl {
472 async importProducts(rawData, options = {}) {
473 const user = Auth.current();
474 if (!user) throw new Error('کاربر یافت نشد');
459 -
460 - const sheetName = Object.keys(rawData).find(n =>
461 - n.includes('کالا') || n.toLowerCase().includes('product')
462 - ) || Object.keys(rawData)[0];
463 -
464 - const rows = rawData[sheetName] || [];
465 - if (rows.length === 0) throw new Error('شیت کالاها خالی است');
466 -
475 const mode = options.mode || 'merge';
468 - // A multi-store accounting system must never delete referenced master data
469 - // then import row-by-row: one malformed row/crash can destroy existing
470 - // invoices, ledgers and company references. Replacement is deliberately
471 - // disabled until a transactional, referentially-safe migration exists.
476 + // Replacing referenced masters is prohibited without a verified migration.
477 if (mode !== 'merge') {
478 throw new Error('جایگزینی گروهی اطلاعات پشتیبانی نمی‌شود؛ اطلاعات موجود حفظ شدند. فقط حالت ادغام مجاز است.');
479 }
475 - const existing = await DataScope.list('products');
476 -
477 - let added = 0, skipped = 0;
480 + if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) {
481 + throw new Error('ساختار فایل کالاها نامعتبر است');
482 + }
483 + const sheetName = Object.keys(rawData).find(n =>
484 + n.includes('کالا') || n.toLowerCase().includes('product')
485 + ) || Object.keys(rawData)[0];
486 + const rows = rawData[sheetName];
487 + if (!Array.isArray(rows) || !rows.length) throw new Error('شیت کالاها خالی یا نامعتبر است');
488 +
489 + // Preflight ALL rows before a single database write, using one company ID.
490 + const companyId = await DataScope.companyId();
491 + const submitted = [];
492 + let skipped = 0;
493 + const now = new Date().toISOString();
494 for (const row of rows) {
479 - const name = row['نام'] || row['نام کالا'] || row['عنوان'];
495 + if (row == null) { skipped++; continue; }
496 + if (typeof row !== 'object' || Array.isArray(row)) {
497 + throw new Error('ردیف کالا ساختار نامعتبر دارد');
498 + }
499 + const name = String(row['نام'] || row['نام کالا'] || row['عنوان'] || '').trim();
500 if (!name) { skipped++; continue; }
481 -
501 const code = String(row['کد'] || row['کد کالا'] || '').trim();
483 - if (mode === 'merge' && code && existing.some(p => p.code === code)) {
484 - skipped++;
485 - continue;
486 - }
487 -
488 - const product = {
489 - id: StorageService.uid('prod_'),
490 - ownerUserId: user.id,
491 - code,
492 - name: String(name).trim(),
502 + submitted.push({
503 + id: StorageService.uid('prod_'), ownerUserId: user.id, companyId,
504 + code, name,
505 spec: String(row['مشخصه'] || row['مشخصه و نوع'] || '').trim(),
506 unit: String(row['واحد'] || 'عدد').trim(),
495 - unitId: null,
496 - categoryId: null,
497 - buyPrice: Number(row['قیمت خرید'] || row['قیمت خرید (ریال)'] || 0) || 0,
498 - sellPrice: Number(row['قیمت فروش'] || row['قیمت فروش (ریال)'] || 0) || 0,
499 - minStock: Number(row['نقطه سفارش'] || 0) || 0,
500 - trackInventory: (row['نوع'] || '').toString().includes('خدمت') ? false : true,
501 - isActiveSell: true,
502 - isActiveBuy: true,
503 - description: ''
504 - };
505 - await StorageService.put('products', await DataScope.stamp('products', product));
506 - added++;
507 + unitId: null, categoryId: null,
508 + buyPrice: excelRial(row['قیمت خرید'] ?? row['قیمت خرید (ریال)'], 'قیمت خرید'),
509 + sellPrice: excelRial(row['قیمت فروش'] ?? row['قیمت فروش (ریال)'], 'قیمت فروش'),
510 + minStock: excelRial(row['نقطه سفارش'], 'نقطه سفارش'),
511 + trackInventory: !String(row['نوع'] || '').includes('خدمت'),
512 + isActiveSell: true, isActiveBuy: true, description: '',
513 + createdAt: now, updatedAt: now
514 + });
515 }
516
509 - return { added, skipped, mode };
517 + // Read, deduplicate and add inside the SAME IndexedDB transaction: another
518 + // import cannot race the code check; any write failure rolls back all rows.
519 + return StorageService.transaction('products', async tx => {
520 + const current = await tx.getAll('products');
521 + const codes = new Set(current
522 + .filter(p => p.companyId === companyId && p.code)
523 + .map(p => String(p.code).trim()));
524 + let added = 0;
525 + for (const product of submitted) {
526 + if (product.code && codes.has(product.code)) { skipped++; continue; }
527 + await tx.add('products', product);
528 + if (product.code) codes.add(product.code);
529 + added++;
530 + }
531 + return { added, skipped, mode };
532 + });
533 }
534
535 /**
513 - * ایمپورت اشخاص از Excel
536 + * Merge imported contacts atomically without disturbing existing journal
537 + * references, and avoid duplicates inside a single workbook.
538 */
539 async importContacts(rawData, options = {}) {
540 const user = Auth.current();
541 if (!user) throw new Error('کاربر یافت نشد');
518 -
519 - const sheetName = Object.keys(rawData).find(n =>
520 - n.includes('اشخاص') || n.toLowerCase().includes('contact')
521 - ) || Object.keys(rawData)[0];
522 -
523 - const rows = rawData[sheetName] || [];
524 - if (rows.length === 0) throw new Error('شیت اشخاص خالی است');
525 -
542 const mode = options.mode || 'merge';
527 - // A multi-store accounting system must never delete referenced master data
528 - // then import row-by-row: one malformed row/crash can destroy existing
529 - // invoices, ledgers and company references. Replacement is deliberately
530 - // disabled until a transactional, referentially-safe migration exists.
543 if (mode !== 'merge') {
544 throw new Error('جایگزینی گروهی اطلاعات پشتیبانی نمی‌شود؛ اطلاعات موجود حفظ شدند. فقط حالت ادغام مجاز است.');
545 }
534 - const existing = await DataScope.list('contacts');
546 + if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) {
547 + throw new Error('ساختار فایل اشخاص نامعتبر است');
548 + }
549 + const sheetName = Object.keys(rawData).find(n =>
550 + n.includes('اشخاص') || n.toLowerCase().includes('contact')
551 + ) || Object.keys(rawData)[0];
552 + const rows = rawData[sheetName];
553 + if (!Array.isArray(rows) || !rows.length) throw new Error('شیت اشخاص خالی یا نامعتبر است');
554
536 - let added = 0, skipped = 0;
555 + const companyId = await DataScope.companyId();
556 + const submitted = [];
557 + let skipped = 0;
558 + const now = new Date().toISOString();
559 for (const row of rows) {
538 - const name = row['نام'] || row['نام شخص یا شرکت'] || row['نام شخص'];
560 + if (row == null) { skipped++; continue; }
561 + if (typeof row !== 'object' || Array.isArray(row)) {
562 + throw new Error('ردیف شخص ساختار نامعتبر دارد');
563 + }
564 + const name = String(row['نام'] || row['نام شخص یا شرکت'] || row['نام شخص'] || '').trim();
565 if (!name) { skipped++; continue; }
540 -
566 const mobile = String(row['موبایل'] || row['شماره همراه'] || '').trim();
542 - if (mode === 'merge' && mobile && existing.some(c => c.mobile === mobile)) {
543 - skipped++;
544 - continue;
545 - }
546 -
547 - const entityType = (row['نوع'] || row['نوع (حقیقی/حقوقی)'] || '').toString().includes('حقوقی') ? 'legal' : 'natural';
548 -
549 - const contact = {
550 - id: StorageService.uid('contact_'),
551 - ownerUserId: user.id,
552 - entityType,
553 - role: (row['نقش'] || '').toString().includes('تامین') ? 'supplier' : 'customer',
554 - prefix: '',
555 - name: String(name).trim(),
556 - mobile,
567 + const sourceRole = String(row['نقش'] || '').trim();
568 + submitted.push({
569 + id: StorageService.uid('contact_'), ownerUserId: user.id, companyId,
570 + entityType: String(row['نوع'] || row['نوع (حقیقی/حقوقی)'] || '').includes('حقوقی') ? 'legal' : 'natural',
571 + role: sourceRole.includes('هر دو') ? 'both'
572 + : sourceRole.includes('تامین') ? 'supplier' : 'customer',
573 + prefix: '', name, mobile,
574 phone: String(row['تلفن'] || '').trim(),
575 nationalId: String(row['کد ملی/شناسه'] || row['شناسه یا کد ملی'] || row['کد ملی'] || '').trim(),
576 economicCode: String(row['کد اقتصادی'] || '').trim(),
577 regNumber: String(row['شماره ثبت'] || '').trim(),
578 postalCode: String(row['کد پستی'] || '').trim(),
579 address: String(row['نشانی'] || '').trim(),
563 - tags: [],
564 - note: '',
565 - isActive: true
566 - };
567 - await StorageService.put('contacts', await DataScope.stamp('contacts', contact));
568 - added++;
580 + tags: [], note: '', isActive: true, createdAt: now, updatedAt: now
581 + });
582 }
583
571 - return { added, skipped, mode };
584 + return StorageService.transaction('contacts', async tx => {
585 + const current = await tx.getAll('contacts');
586 + const mobiles = new Set(current
587 + .filter(c => c.companyId === companyId && c.mobile)
588 + .map(c => String(c.mobile).trim()));
589 + let added = 0;
590 + for (const contact of submitted) {
591 + if (contact.mobile && mobiles.has(contact.mobile)) { skipped++; continue; }
592 + await tx.add('contacts', contact);
593 + if (contact.mobile) mobiles.add(contact.mobile);
594 + added++;
595 + }
596 + return { added, skipped, mode };
597 + });
598 }
599
600 // ============================================================