فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix/phase-a-pack4-stock-scope-20261101
a02/strict-export-preflight-20261018
audit/a01-readonly-invoice-metadata-20261101
ci/a06-require-trusted-issuer-for-release
ci/main-postmerge-phase-a-validation-20261020
ci/phase-a-controlled-public-release
design/issue-5-commercial-corrections-adr
docs/a01-a02-a05-oct23-verified-evidence
docs/a01-cheque-endorsement-evidence-20261022
docs/a01-cheque-event-date-evidence-20261021
docs/a01-explicit-refund-reason-evidence-20261021
docs/a01-refund-auth-status-20261020
docs/a01-refund-trace-evidence-20261020
docs/a02-102-evidence-20261018
docs/a02-pr104-evidence-20261018
docs/a02-pr106-evidence-20261019
docs/a02-pr108-ten-tests-20261019
docs/a02-private-sql-backup-evidence-20261111
docs/a03-merge-status-sync-20261020
docs/a04-software-gate-acceptance-20261020
docs/feature-matrix-20261014
docs/finora-master-execution-playbook
docs/four-phase-execution-20261014
docs/four-phase-roadmap-20261014
docs/holoo-lab-stabilization-phase1-20261111
docs/holoo-runtime-schema-audit-20261111
docs/ops-142-governance-5-1-3-20261030
docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023
docs/phase-a-a01-a05-a06-evidence-20261023
docs/phase-a-independent-acceptance-evidence
docs/phase-a-pr110-evidence-20261019
docs/project-status-phase-a-20261014
feat/a01-referenced-return-corrections
feat/a01-referenced-returns-on-main
feat/a02-atomic-opening-ledger-preflight
feat/a02-holoo-compatibility-preflight
feat/a02-holoo-declared-control-totals
feat/a02-holoo-explicit-csv-gate
feat/a02-holoo-safe-zip-intake-offline-webview2-20261030
feat/a02-offline-sql-server-provisioning-20261030
feat/a02-opening-balance-dry-run
feat/a02-opening-ledger-admin-ui
feat/a02-opt-in-isolated-sql-restore-executor-20261030
feat/a02-private-holoo-zip-staging-20261030
feat/a02-safe-isolated-restore-plan-20261030
feat/a02-sql-backup-header-verifyonly-20261030
feat/a03-audit-schema-atomic-events
feat/a03-complete-manual-journal-audit
feat/a05-cheque-treasury-reconciliation
feat/a06-signed-offline-license-activation
feat/a08-synthetic-performance-baseline
feat/phase-a-accounting-benchmark-return-preview
feat/phase-a-ledger-settlement-diagnostics
feature/v2-reconciliation-20261013
fix/a01-atomic-confirm-ui-one-shot-20261031
fix/a01-cheque-clearance-explicit-account-20261023
fix/a01-cheque-contractual-due-date-validity-20261023
fix/a01-cheque-endorsement-counterparty-20261022
fix/a01-cheque-event-date-open-period-20261021
fix/a01-cumulative-return-amount-cap
fix/a01-explicit-refund-reason-approval-20261021
fix/a01-manager-authorized-customer-refunds-20261020
fix/a01-no-implicit-refund
fix/a01-one-shot-confirm-on-atomic-import-20261031
fix/a01-refund-and-overcollection-net-cash
fix/a01-refund-correction-trace-20261020
fix/a02-atomic-excel-master-merge-20261031
fix/a02-canonical-mapping-contract-20261018
fix/a02-disable-destructive-excel-replace-20261031
fix/a02-holoo-invoice-line-coverage-20261023
fix/a02-holoo-preflight-required-invoice-lines-20261023
fix/a02-mapping-contract-20261018
fix/a02-opening-preflight-unbalanced-report
fix/a02-orphan-mapping-20261018
fix/a02-private-excel-import-session-20261031
fix/a02-strict-export-input-20261019
fix/a03-append-only-full-backup-import
fix/a03-append-only-write-guard
fix/a03-block-transaction-clear-append-only-20261016
fix/a03-chain-validation-20261020
fix/a03-company-scoped-audit-data-access
fix/a03-deny-direct-audit-write-20261019
fix/a03-escaped-expense-list-20261031
fix/a03-escaped-financial-record-ids-20261031
fix/a03-financial-ledger-actions-and-print-20261031
fix/a04-backup-checksum-preflight
fix/a04-company-audit-replay-stable-compare
fix/a04-company-backup-source-isolation-20261020
fix/a04-full-restore-posted-financial-integrity
fix/a04-reject-mixed-company-backup-20261019
fix/a04-replace-immutable-posted-ledger
fix/a04-restore-financial-journal-references
fix/a04-service-source-company-boundary-20261020
fix/a05-block-inactive-treasury-settlements
fix/a05-cheque-cash-evidence-reconciliation-20261023
fix/a05-cheque-ledger-and-bank-reconciliation-20261023
fix/a05-fiscal-close-invariant-gates
fix/a06-backup-restore-user-privileges
fix/a06-license-user-company-quota-20261023
fix/a06-malformed-trial-state-fail-closed
fix/a06-offline-clock-fail-closed-20261019
fix/a07-indexeddb-blocked-startup
fix/a07-offline-bundled-assets
fix/a07-version-and-startup-banner
fix/issue-7-company-backup-isolation
fix/p0-deterministic-fractional-invoice-money-20261031
fix/p0-fractional-quantity-input-20261031
fix/p0-fractional-quantity-integrated-20261031
fix/p0-invoice-posting-invariants-20261031
fix/p0-legacy-stock-and-product-inputs-20261031
fix/p0-reports-immutable-cogs-20261101
fix/p0-verified-financial-percent-20261031
fix/p0-zero-discount-report-revenue-20261101
fix/phase-a-backup-app-version
fix/phase-a-backup-integrity-checksum
fix/phase-a-backup-record-id-validation-20261014
fix/phase-a-backup-version-validation-20261014
fix/phase-a-closure-pack3-20261101
fix/phase-a-entitlement-payload-validation
fix/phase-a-gate-exact-evidence-20261019
fix/phase-a-pack4-stock-scope-20261101
fix/phase-a-pack5-integrated-evidence-20261101
fix/phase-a-pack6-atomic-legacy-20261101
fix/phase-a-restore-envelope-and-rollback
fix/phase-a-settings-admin-gate
fix/print-browser-header-footer-20261014
fix/q01-expense-security-probe-exact-option-20261031
fix/q01-financial-grid-labels-20261031
fix/q01-form-label-association-20261031
fix/q01-native-evidence-integrity-20261030
fix/q01-number-input-persian-decimal-20261031
fix/q01-responsive-dashboard-and-cheque-table-20261031
fix/q01-safe-ui-action-audit-coverage-20261031
fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030
fix/roadmap-metadata-sync-20261014
gate/a03-audit-metadata-validation-20261019
integration/a02-windows-holoo-setup-candidate-20261030
license-server
main
perf/a07-lazy-load-excel
perf/a08-cheque-reconciliation-account-index-20261023
perf/a08-paginated-reports-20261101
phase1-restore-hardening
planning/holoo-execution-20261013
planning/roadmap-project-management-20261014
qa/native-click-coverage-audit-20261030
release/v2.0.0
test/a01-native-endorsement-mandatory-20261023
test/a01-native-purchase-return-guardrails
test/a01-native-sale-return-financial-guardrails
test/a01-safe-integer-boundary-20261019
test/a02-native-opening-dry-run-rejections
test/a02-native-positive-opening-ledger
test/a04-native-corrupt-fbackup-20261016
test/a04-native-encrypted-company-backup
test/a04-native-encrypted-company-backup-main
test/a04-native-late-transaction-rollback
test/a04-native-windows-backup-recovery
test/a04-real-edge-v6-v7-migration
test/a04-real-native-interrupted-restore
test/a05-native-draft-ledger-and-repeat-close-20261016
test/a05-native-fiscal-close-guardrails
test/a07-native-multipage-print-engine
test/a07-native-origin-provenance
test/a07-native-webview2-offline-routes
test/a07-windows-offline-startup-smoke
test/a08-installed-webview2-60k-baseline
test/a08-native-webview2-heap-metrics
test/a08-windows-synthetic-performance-baseline
test/github-write-access-20261009
test/native-win-ui-routes-after-finance-backup
test/phase-a-combined-a01-a05-a08-final-evidence
test/phase-a-combined-native-acceptance-matrix
test/phase-a-ledger-invariants-20261014
test/phase-a-native-all-routes-on-merged-lab
test/phase-a-native-encrypted-backup
test/phase-a-native-finance-backup-matrix
test/phase-a-native-ui-and-backup-smoke
test/phase-a-windows-native-installer-lab
work/a08-dispatch-activation-20261123
work/a08-memory-stability-20261123
work/finance-curated-20261123
| 1 | // ============================================================ |
| 2 | // ExcelController — خروجی و ورودی Excel |
| 3 | // ============================================================ |
| 4 | |
| 5 | // Excel and Persian text editing are not needed on the login screen. |
| 6 | // Load the locally bundled, pinned library only when an Excel action starts. |
| 7 | let XLSX = null; |
| 8 | let xlsxPending = null; |
| 9 | async function loadSheetJS() { |
| 10 | if (XLSX) return XLSX; |
| 11 | if (!xlsxPending) { |
| 12 | xlsxPending = import('xlsx').then(module => { XLSX = module; return module; }) |
| 13 | .catch(error => { xlsxPending = null; throw error; }); |
| 14 | } |
| 15 | return xlsxPending; |
| 16 | } |
| 17 | import { StorageService } from '../core/StorageService.js'; |
| 18 | import { Auth } from '../core/Auth.js'; |
| 19 | import { DataScope } from '../core/DataScope.js'; |
| 20 | import { Jalali } from '../utils/Jalali.js'; |
| 21 | 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 | // Stock reorder thresholds are quantities, not rial. Fractional stock |
| 42 | // quantities (for example 2.5 kg) are valid and must survive Excel import. |
| 43 | function excelQuantity(value) { |
| 44 | if (value === null || value === undefined || value === '') return 0; |
| 45 | const ascii = String(value) |
| 46 | .replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776)) |
| 47 | .replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632)) |
| 48 | .replace(/[,\s،٬]/g, ''); |
| 49 | const amount = Number(ascii); |
| 50 | if (!/^\d+(?:\.\d+)?$/.test(ascii) || !Number.isFinite(amount) || |
| 51 | amount < 0 || amount > Number.MAX_SAFE_INTEGER) { |
| 52 | throw new Error('نقطه سفارش کالا مقدار نامعتبر دارد'); |
| 53 | } |
| 54 | return amount; |
| 55 | } |
| 56 | |
| 57 | class ExcelControllerImpl { |
| 58 | // ============================================================ |
| 59 | // ذخیره فایل + نمایش پیام + باز کردن خودکار (سازگار با Tauri) |
| 60 | // ============================================================ |
| 61 | async _saveFile(wb, fileName) { |
| 62 | await loadSheetJS(); |
| 63 | const isTauri = '__TAURI_INTERNALS__' in window; |
| 64 | |
| 65 | // حالت مرورگر: دانلود معمولی |
| 66 | if (!isTauri) { |
| 67 | XLSX.writeFile(wb, fileName); |
| 68 | Toast.success(`فایل «${fileName}» دانلود شد`, 'خروجی Excel'); |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | // حالت Tauri: گرفتن مسیر از کاربر + نوشتن + باز کردن |
| 73 | try { |
| 74 | const { save } = await import('@tauri-apps/plugin-dialog'); |
| 75 | const { writeFile } = await import('@tauri-apps/plugin-fs'); |
| 76 | const { openPath } = await import('@tauri-apps/plugin-opener'); |
| 77 | |
| 78 | const filePath = await save({ |
| 79 | defaultPath: fileName, |
| 80 | filters: [{ name: 'Excel', extensions: ['xlsx'] }] |
| 81 | }); |
| 82 | |
| 83 | if (!filePath) { |
| 84 | Toast.info('ذخیره فایل لغو شد'); |
| 85 | return; |
| 86 | } |
| 87 | |
| 88 | const data = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); |
| 89 | await writeFile(filePath, new Uint8Array(data)); |
| 90 | |
| 91 | Toast.success('فایل با موفقیت ذخیره و باز شد', 'خروجی Excel'); |
| 92 | |
| 93 | try { |
| 94 | await openPath(filePath); |
| 95 | } catch (openErr) { |
| 96 | console.warn('خطا در باز کردن فایل:', openErr); |
| 97 | } |
| 98 | } catch (err) { |
| 99 | console.error('خطا در ذخیره فایل:', err); |
| 100 | Toast.error('خطا در ذخیره فایل: ' + err.message, 'خروجی Excel'); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | // ============================================================ |
| 105 | // خروجی کامل (Backup Excel) |
| 106 | // ============================================================ |
| 107 | async exportAll() { |
| 108 | await loadSheetJS(); |
| 109 | const user = Auth.current(); |
| 110 | if (!user) throw new Error('کاربر یافت نشد'); |
| 111 | |
| 112 | const [companies, contacts, products, invoices, cheques, treasury, expenses, units, categories] = await Promise.all([ |
| 113 | DataScope.list('companies'), |
| 114 | DataScope.list('contacts'), |
| 115 | DataScope.list('products'), |
| 116 | DataScope.list('invoices'), |
| 117 | DataScope.list('cheques'), |
| 118 | DataScope.list('treasury'), |
| 119 | DataScope.list('expenses'), |
| 120 | DataScope.list('units'), |
| 121 | DataScope.list('categories') |
| 122 | ]); |
| 123 | |
| 124 | const accounts = treasury.filter(t => t.recordType === 'account'); |
| 125 | const transactions = treasury.filter(t => t.recordType === 'transaction'); |
| 126 | const stockMovements = await DataScope.list('stock_movements'); |
| 127 | |
| 128 | const wb = XLSX.utils.book_new(); |
| 129 | |
| 130 | // ۱. کالاها |
| 131 | const productsData = [ |
| 132 | ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی', 'نوع'] |
| 133 | ]; |
| 134 | const stockMap = await ProductController.getStockMap(products.map(p => p.id)); |
| 135 | products.forEach(p => { |
| 136 | const unit = units.find(u => u.id === p.unitId); |
| 137 | productsData.push([ |
| 138 | p.code || '', |
| 139 | p.name || '', |
| 140 | p.spec || '', |
| 141 | unit?.name || p.unit || 'عدد', |
| 142 | Number(p.buyPrice) || 0, |
| 143 | Number(p.sellPrice) || 0, |
| 144 | Number(p.minStock) || 0, |
| 145 | p.trackInventory === false ? '—' : (stockMap[p.id] || 0), |
| 146 | p.trackInventory === false ? 'خدمت' : 'کالا' |
| 147 | ]); |
| 148 | }); |
| 149 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(productsData), 'کالاها'); |
| 150 | |
| 151 | // ۲. اشخاص |
| 152 | const contactsData = [ |
| 153 | ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی', 'مانده'] |
| 154 | ]; |
| 155 | const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id)); |
| 156 | contacts.forEach(c => { |
| 157 | contactsData.push([ |
| 158 | c.name || '', |
| 159 | c.entityType === 'legal' ? 'حقوقی' : 'حقیقی', |
| 160 | c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامینکننده' : 'هر دو', |
| 161 | c.mobile || '', |
| 162 | c.phone || '', |
| 163 | c.nationalId || '', |
| 164 | c.economicCode || '', |
| 165 | c.regNumber || '', |
| 166 | c.postalCode || '', |
| 167 | c.address || '', |
| 168 | Number(balanceMap[c.id]) || 0 |
| 169 | ]); |
| 170 | }); |
| 171 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(contactsData), 'اشخاص'); |
| 172 | |
| 173 | // ۳. فاکتورها (خلاصه) |
| 174 | const invoicesData = [ |
| 175 | ['شماره', 'تاریخ', 'نوع', 'پیشفاکتور', 'فروشنده', 'خریدار', 'جمع کل', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداختشده', 'باقیمانده', 'وضعیت', 'توضیحات'] |
| 176 | ]; |
| 177 | const kindLabels = { |
| 178 | sale: 'فروش', purchase: 'خرید', sale_return: 'برگشت فروش', |
| 179 | purchase_return: 'برگشت خرید', non_formal: 'غیررسمی' |
| 180 | }; |
| 181 | invoices.forEach(inv => { |
| 182 | invoicesData.push([ |
| 183 | inv.number || '', |
| 184 | inv.date || '', |
| 185 | kindLabels[inv.kind] || inv.kind, |
| 186 | inv.isPreInvoice ? 'بله' : 'خیر', |
| 187 | inv.companyName || '', |
| 188 | inv.contactName || '', |
| 189 | Number(inv.subtotal) || 0, |
| 190 | Number(inv.totalDiscount) || 0, |
| 191 | Number(inv.vatAmount) || 0, |
| 192 | Number(inv.grandTotal) || 0, |
| 193 | Number(inv.paidAmount) || 0, |
| 194 | Number(inv.remaining) || 0, |
| 195 | inv.status === 'paid' ? 'تسویه' : inv.status === 'partial' ? 'جزئی' : 'پرداختنشده', |
| 196 | inv.description || '' |
| 197 | ]); |
| 198 | }); |
| 199 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(invoicesData), 'فاکتورها'); |
| 200 | |
| 201 | // ۴. اقلام فاکتور |
| 202 | const itemsData = [ |
| 203 | ['شماره فاکتور', 'تاریخ', 'کالا', 'واحد', 'تعداد', 'قیمت واحد', 'تخفیف', 'جمع ردیف'] |
| 204 | ]; |
| 205 | invoices.forEach(inv => { |
| 206 | (inv.items || []).forEach(it => { |
| 207 | itemsData.push([ |
| 208 | inv.number || '', |
| 209 | inv.date || '', |
| 210 | it.productName || '', |
| 211 | it.unit || 'عدد', |
| 212 | Number(it.qty) || 0, |
| 213 | Number(it.price) || 0, |
| 214 | Number(it.discount) || 0, |
| 215 | Number(it.lineTotal) || 0 |
| 216 | ]); |
| 217 | }); |
| 218 | }); |
| 219 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(itemsData), 'اقلام فاکتور'); |
| 220 | |
| 221 | // ۵. چکها |
| 222 | const chequesData = [ |
| 223 | ['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'شعبه', 'مبلغ', 'تاریخ صدور', 'سررسید', 'وضعیت', 'توضیحات'] |
| 224 | ]; |
| 225 | const chequeStatusLabels = { |
| 226 | pending: 'در جریان', cleared: 'وصول شده', bounced: 'برگشتی', |
| 227 | returned: 'عودت داده شده', spent: 'خرج شده' |
| 228 | }; |
| 229 | cheques.forEach(c => { |
| 230 | chequesData.push([ |
| 231 | c.direction === 'inbound' ? 'دریافتی' : 'پرداختی', |
| 232 | c.contactName || '', |
| 233 | c.sayadNumber || '', |
| 234 | c.bankName || '', |
| 235 | c.branchName || '', |
| 236 | Number(c.amount) || 0, |
| 237 | c.issueDate || '', |
| 238 | c.dueDate || '', |
| 239 | chequeStatusLabels[c.status] || c.status, |
| 240 | c.description || '' |
| 241 | ]); |
| 242 | }); |
| 243 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(chequesData), 'چکها'); |
| 244 | |
| 245 | // ۶. تراکنشها |
| 246 | const txData = [ |
| 247 | ['نوع', 'تاریخ', 'طرف حساب', 'از حساب', 'به حساب', 'مبلغ', 'روش', 'توضیحات'] |
| 248 | ]; |
| 249 | const methodLabels = { cash: 'نقدی', card: 'کارت', cheque: 'چک', transfer: 'انتقال' }; |
| 250 | transactions.forEach(t => { |
| 251 | const fromAcc = accounts.find(a => a.id === t.fromAccountId); |
| 252 | const toAcc = accounts.find(a => a.id === t.toAccountId); |
| 253 | txData.push([ |
| 254 | t.type === 'receipt' ? 'دریافت' : t.type === 'payment' ? 'پرداخت' : 'انتقال', |
| 255 | t.date || '', |
| 256 | t.contactName || '', |
| 257 | fromAcc?.name || '', |
| 258 | toAcc?.name || '', |
| 259 | Number(t.amount) || 0, |
| 260 | methodLabels[t.method] || t.method, |
| 261 | t.description || '' |
| 262 | ]); |
| 263 | }); |
| 264 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(txData), 'تراکنشها'); |
| 265 | |
| 266 | // ۷. هزینهها |
| 267 | const expData = [ |
| 268 | ['نوع', 'تاریخ', 'سرفصل', 'شرح', 'روش', 'شماره پیگیری', 'مبلغ'] |
| 269 | ]; |
| 270 | expenses.forEach(e => { |
| 271 | expData.push([ |
| 272 | e.kind === 'income' ? 'درآمد' : 'هزینه', |
| 273 | e.date || '', |
| 274 | e.category || '', |
| 275 | e.description || '', |
| 276 | methodLabels[e.method] || e.method, |
| 277 | e.refNumber || '', |
| 278 | Number(e.amount) || 0 |
| 279 | ]); |
| 280 | }); |
| 281 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(expData), 'هزینهها'); |
| 282 | |
| 283 | // ۸. شرکتها |
| 284 | const compData = [ |
| 285 | ['نام', 'نوع', 'تلفن', 'شناسه ملی', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'] |
| 286 | ]; |
| 287 | companies.forEach(c => { |
| 288 | compData.push([ |
| 289 | c.name || '', |
| 290 | c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی', |
| 291 | c.phone || '', |
| 292 | c.national_id || '', |
| 293 | c.economic_code || '', |
| 294 | c.reg_number || '', |
| 295 | c.postal_code || '', |
| 296 | c.address || '' |
| 297 | ]); |
| 298 | }); |
| 299 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(compData), 'شرکتها'); |
| 300 | |
| 301 | // ۹. کاردکس انبار |
| 302 | const mvData = [ |
| 303 | ['کالا', 'نوع حرکت', 'تعداد', 'مرجع', 'یادداشت', 'تاریخ'] |
| 304 | ]; |
| 305 | const typeLabels = { in: 'ورود', out: 'خروج', adjust: 'اصلاح' }; |
| 306 | stockMovements.forEach(m => { |
| 307 | const p = products.find(prod => prod.id === m.productId); |
| 308 | mvData.push([ |
| 309 | p?.name || '', |
| 310 | typeLabels[m.type] || m.type, |
| 311 | Number(m.qty) || 0, |
| 312 | m.refType || '', |
| 313 | m.note || '', |
| 314 | m.date || '' |
| 315 | ]); |
| 316 | }); |
| 317 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(mvData), 'کاردکس'); |
| 318 | |
| 319 | // ذخیره + پیام |
| 320 | const date = Jalali.today().replace(/\//g, '-'); |
| 321 | await this._saveFile(wb, `finora-backup-${date}.xlsx`); |
| 322 | |
| 323 | return { |
| 324 | sheets: 9, |
| 325 | counts: { |
| 326 | products: products.length, |
| 327 | contacts: contacts.length, |
| 328 | invoices: invoices.length, |
| 329 | items: itemsData.length - 1, |
| 330 | cheques: cheques.length, |
| 331 | transactions: transactions.length, |
| 332 | expenses: expenses.length, |
| 333 | companies: companies.length, |
| 334 | movements: stockMovements.length |
| 335 | } |
| 336 | }; |
| 337 | } |
| 338 | |
| 339 | // ============================================================ |
| 340 | // خروجی انتخابی |
| 341 | // ============================================================ |
| 342 | async exportSection(section) { |
| 343 | await loadSheetJS(); |
| 344 | const user = Auth.current(); |
| 345 | if (!user) throw new Error('کاربر یافت نشد'); |
| 346 | |
| 347 | const wb = XLSX.utils.book_new(); |
| 348 | const date = Jalali.today().replace(/\//g, '-'); |
| 349 | |
| 350 | switch (section) { |
| 351 | case 'products': { |
| 352 | const products = await DataScope.list('products'); |
| 353 | const units = await DataScope.list('units'); |
| 354 | const stockMap = await ProductController.getStockMap(products.map(p => p.id)); |
| 355 | const data = [['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی']]; |
| 356 | products.forEach(p => { |
| 357 | const unit = units.find(u => u.id === p.unitId); |
| 358 | data.push([ |
| 359 | p.code || '', p.name || '', p.spec || '', |
| 360 | unit?.name || p.unit || 'عدد', |
| 361 | Number(p.buyPrice) || 0, |
| 362 | Number(p.sellPrice) || 0, |
| 363 | Number(p.minStock) || 0, |
| 364 | p.trackInventory === false ? '—' : (stockMap[p.id] || 0) |
| 365 | ]); |
| 366 | }); |
| 367 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'کالاها'); |
| 368 | await this._saveFile(wb, `finora-products-${date}.xlsx`); |
| 369 | return { count: products.length }; |
| 370 | } |
| 371 | |
| 372 | case 'contacts': { |
| 373 | const contacts = await DataScope.list('contacts'); |
| 374 | const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id)); |
| 375 | const data = [['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد پستی', 'نشانی', 'مانده']]; |
| 376 | contacts.forEach(c => { |
| 377 | data.push([ |
| 378 | c.name || '', |
| 379 | c.entityType === 'legal' ? 'حقوقی' : 'حقیقی', |
| 380 | c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامینکننده' : 'هر دو', |
| 381 | c.mobile || '', c.phone || '', c.nationalId || '', |
| 382 | c.postalCode || '', c.address || '', |
| 383 | Number(balanceMap[c.id]) || 0 |
| 384 | ]); |
| 385 | }); |
| 386 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'اشخاص'); |
| 387 | await this._saveFile(wb, `finora-contacts-${date}.xlsx`); |
| 388 | return { count: contacts.length }; |
| 389 | } |
| 390 | |
| 391 | case 'invoices': { |
| 392 | const invoices = await DataScope.list('invoices'); |
| 393 | const data = [['شماره', 'تاریخ', 'نوع', 'خریدار', 'جمع', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداختشده', 'باقیمانده']]; |
| 394 | invoices.forEach(inv => { |
| 395 | data.push([ |
| 396 | inv.number || '', inv.date || '', |
| 397 | inv.kindLabel || inv.kind || '', |
| 398 | inv.contactName || '', |
| 399 | Number(inv.subtotal) || 0, |
| 400 | Number(inv.totalDiscount) || 0, |
| 401 | Number(inv.vatAmount) || 0, |
| 402 | Number(inv.grandTotal) || 0, |
| 403 | Number(inv.paidAmount) || 0, |
| 404 | Number(inv.remaining) || 0 |
| 405 | ]); |
| 406 | }); |
| 407 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'فاکتورها'); |
| 408 | await this._saveFile(wb, `finora-invoices-${date}.xlsx`); |
| 409 | return { count: invoices.length }; |
| 410 | } |
| 411 | |
| 412 | case 'cheques': { |
| 413 | const cheques = await DataScope.list('cheques'); |
| 414 | const data = [['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'مبلغ', 'سررسید', 'وضعیت']]; |
| 415 | cheques.forEach(c => { |
| 416 | data.push([ |
| 417 | c.direction === 'inbound' ? 'دریافتی' : 'پرداختی', |
| 418 | c.contactName || '', c.sayadNumber || '', c.bankName || '', |
| 419 | Number(c.amount) || 0, c.dueDate || '', c.status || '' |
| 420 | ]); |
| 421 | }); |
| 422 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'چکها'); |
| 423 | await this._saveFile(wb, `finora-cheques-${date}.xlsx`); |
| 424 | return { count: cheques.length }; |
| 425 | } |
| 426 | |
| 427 | case 'expenses': { |
| 428 | const expenses = await DataScope.list('expenses'); |
| 429 | const data = [['نوع', 'تاریخ', 'سرفصل', 'شرح', 'مبلغ']]; |
| 430 | expenses.forEach(e => { |
| 431 | data.push([ |
| 432 | e.kind === 'income' ? 'درآمد' : 'هزینه', |
| 433 | e.date || '', e.category || '', |
| 434 | e.description || '', Number(e.amount) || 0 |
| 435 | ]); |
| 436 | }); |
| 437 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'هزینهها'); |
| 438 | await this._saveFile(wb, `finora-expenses-${date}.xlsx`); |
| 439 | return { count: expenses.length }; |
| 440 | } |
| 441 | |
| 442 | default: |
| 443 | throw new Error('بخش نامعتبر'); |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | // ============================================================ |
| 448 | // ورودی از Excel |
| 449 | // ============================================================ |
| 450 | async readExcelFile(file) { |
| 451 | await loadSheetJS(); |
| 452 | return new Promise((resolve, reject) => { |
| 453 | const reader = new FileReader(); |
| 454 | reader.onload = (e) => { |
| 455 | try { |
| 456 | const data = new Uint8Array(e.target.result); |
| 457 | const workbook = XLSX.read(data, { type: 'array' }); |
| 458 | const result = {}; |
| 459 | workbook.SheetNames.forEach(sheetName => { |
| 460 | result[sheetName] = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]); |
| 461 | }); |
| 462 | resolve(result); |
| 463 | } catch (err) { |
| 464 | reject(new Error('خطا در خواندن فایل اکسل: ' + err.message)); |
| 465 | } |
| 466 | }; |
| 467 | reader.onerror = () => reject(new Error('خطا در خواندن فایل')); |
| 468 | reader.readAsArrayBuffer(file); |
| 469 | }); |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * پیشنمایش فایل قبل از ایمپورت |
| 474 | */ |
| 475 | async previewFile(file) { |
| 476 | const data = await this.readExcelFile(file); |
| 477 | const sheets = Object.keys(data).map(name => ({ |
| 478 | name, |
| 479 | count: data[name].length, |
| 480 | sample: data[name].slice(0, 3) |
| 481 | })); |
| 482 | return { sheets, raw: data }; |
| 483 | } |
| 484 | |
| 485 | /** |
| 486 | * ایمپورت کالاها از Excel |
| 487 | */ |
| 488 | async importProducts(rawData, options = {}) { |
| 489 | const user = Auth.current(); |
| 490 | if (!user) throw new Error('کاربر یافت نشد'); |
| 491 | const mode = options.mode || 'merge'; |
| 492 | // Replacing referenced masters is prohibited without a verified migration. |
| 493 | if (mode !== 'merge') { |
| 494 | throw new Error('جایگزینی گروهی اطلاعات پشتیبانی نمیشود؛ اطلاعات موجود حفظ شدند. فقط حالت ادغام مجاز است.'); |
| 495 | } |
| 496 | if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) { |
| 497 | throw new Error('ساختار فایل کالاها نامعتبر است'); |
| 498 | } |
| 499 | const sheetName = Object.keys(rawData).find(n => |
| 500 | n.includes('کالا') || n.toLowerCase().includes('product') |
| 501 | ) || Object.keys(rawData)[0]; |
| 502 | const rows = rawData[sheetName]; |
| 503 | if (!Array.isArray(rows) || !rows.length) throw new Error('شیت کالاها خالی یا نامعتبر است'); |
| 504 | |
| 505 | // Preflight ALL rows before a single database write, using one company ID. |
| 506 | const companyId = await DataScope.companyId(); |
| 507 | const submitted = []; |
| 508 | let skipped = 0; |
| 509 | const now = new Date().toISOString(); |
| 510 | for (const row of rows) { |
| 511 | if (row == null) { skipped++; continue; } |
| 512 | if (typeof row !== 'object' || Array.isArray(row)) { |
| 513 | throw new Error('ردیف کالا ساختار نامعتبر دارد'); |
| 514 | } |
| 515 | const name = String(row['نام'] || row['نام کالا'] || row['عنوان'] || '').trim(); |
| 516 | if (!name) { skipped++; continue; } |
| 517 | const code = String(row['کد'] || row['کد کالا'] || '').trim(); |
| 518 | submitted.push({ |
| 519 | id: StorageService.uid('prod_'), ownerUserId: user.id, companyId, |
| 520 | code, name, |
| 521 | spec: String(row['مشخصه'] || row['مشخصه و نوع'] || '').trim(), |
| 522 | unit: String(row['واحد'] || 'عدد').trim(), |
| 523 | unitId: null, categoryId: null, |
| 524 | buyPrice: excelRial(row['قیمت خرید'] ?? row['قیمت خرید (ریال)'], 'قیمت خرید'), |
| 525 | sellPrice: excelRial(row['قیمت فروش'] ?? row['قیمت فروش (ریال)'], 'قیمت فروش'), |
| 526 | minStock: excelQuantity(row['نقطه سفارش']), |
| 527 | trackInventory: !String(row['نوع'] || '').includes('خدمت'), |
| 528 | isActiveSell: true, isActiveBuy: true, description: '', |
| 529 | createdAt: now, updatedAt: now |
| 530 | }); |
| 531 | } |
| 532 | |
| 533 | // Read, deduplicate and add inside the SAME IndexedDB transaction: another |
| 534 | // import cannot race the code check; any write failure rolls back all rows. |
| 535 | return StorageService.transaction('products', async tx => { |
| 536 | const current = await tx.getAll('products'); |
| 537 | const codes = new Set(current |
| 538 | .filter(p => p.companyId === companyId && p.code) |
| 539 | .map(p => String(p.code).trim())); |
| 540 | let added = 0; |
| 541 | for (const product of submitted) { |
| 542 | if (product.code && codes.has(product.code)) { skipped++; continue; } |
| 543 | await tx.add('products', product); |
| 544 | if (product.code) codes.add(product.code); |
| 545 | added++; |
| 546 | } |
| 547 | return { added, skipped, mode }; |
| 548 | }); |
| 549 | } |
| 550 | |
| 551 | /** |
| 552 | * Merge imported contacts atomically without disturbing existing journal |
| 553 | * references, and avoid duplicates inside a single workbook. |
| 554 | */ |
| 555 | async importContacts(rawData, options = {}) { |
| 556 | const user = Auth.current(); |
| 557 | if (!user) throw new Error('کاربر یافت نشد'); |
| 558 | const mode = options.mode || 'merge'; |
| 559 | if (mode !== 'merge') { |
| 560 | throw new Error('جایگزینی گروهی اطلاعات پشتیبانی نمیشود؛ اطلاعات موجود حفظ شدند. فقط حالت ادغام مجاز است.'); |
| 561 | } |
| 562 | if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) { |
| 563 | throw new Error('ساختار فایل اشخاص نامعتبر است'); |
| 564 | } |
| 565 | const sheetName = Object.keys(rawData).find(n => |
| 566 | n.includes('اشخاص') || n.toLowerCase().includes('contact') |
| 567 | ) || Object.keys(rawData)[0]; |
| 568 | const rows = rawData[sheetName]; |
| 569 | if (!Array.isArray(rows) || !rows.length) throw new Error('شیت اشخاص خالی یا نامعتبر است'); |
| 570 | |
| 571 | const companyId = await DataScope.companyId(); |
| 572 | const submitted = []; |
| 573 | let skipped = 0; |
| 574 | const now = new Date().toISOString(); |
| 575 | for (const row of rows) { |
| 576 | if (row == null) { skipped++; continue; } |
| 577 | if (typeof row !== 'object' || Array.isArray(row)) { |
| 578 | throw new Error('ردیف شخص ساختار نامعتبر دارد'); |
| 579 | } |
| 580 | const name = String(row['نام'] || row['نام شخص یا شرکت'] || row['نام شخص'] || '').trim(); |
| 581 | if (!name) { skipped++; continue; } |
| 582 | const mobile = String(row['موبایل'] || row['شماره همراه'] || '').trim(); |
| 583 | const sourceRole = String(row['نقش'] || '').trim(); |
| 584 | submitted.push({ |
| 585 | id: StorageService.uid('contact_'), ownerUserId: user.id, companyId, |
| 586 | entityType: String(row['نوع'] || row['نوع (حقیقی/حقوقی)'] || '').includes('حقوقی') ? 'legal' : 'natural', |
| 587 | role: sourceRole.includes('هر دو') ? 'both' |
| 588 | : sourceRole.includes('تامین') ? 'supplier' : 'customer', |
| 589 | prefix: '', name, mobile, |
| 590 | phone: String(row['تلفن'] || '').trim(), |
| 591 | nationalId: String(row['کد ملی/شناسه'] || row['شناسه یا کد ملی'] || row['کد ملی'] || '').trim(), |
| 592 | economicCode: String(row['کد اقتصادی'] || '').trim(), |
| 593 | regNumber: String(row['شماره ثبت'] || '').trim(), |
| 594 | postalCode: String(row['کد پستی'] || '').trim(), |
| 595 | address: String(row['نشانی'] || '').trim(), |
| 596 | tags: [], note: '', isActive: true, createdAt: now, updatedAt: now |
| 597 | }); |
| 598 | } |
| 599 | |
| 600 | return StorageService.transaction('contacts', async tx => { |
| 601 | const current = await tx.getAll('contacts'); |
| 602 | const mobiles = new Set(current |
| 603 | .filter(c => c.companyId === companyId && c.mobile) |
| 604 | .map(c => String(c.mobile).trim())); |
| 605 | let added = 0; |
| 606 | for (const contact of submitted) { |
| 607 | if (contact.mobile && mobiles.has(contact.mobile)) { skipped++; continue; } |
| 608 | await tx.add('contacts', contact); |
| 609 | if (contact.mobile) mobiles.add(contact.mobile); |
| 610 | added++; |
| 611 | } |
| 612 | return { added, skipped, mode }; |
| 613 | }); |
| 614 | } |
| 615 | |
| 616 | // ============================================================ |
| 617 | // دانلود قالبهای نمونه |
| 618 | // ============================================================ |
| 619 | async downloadProductsTemplate() { |
| 620 | await loadSheetJS(); |
| 621 | const data = [ |
| 622 | ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'نوع'], |
| 623 | ['P001', 'هارد سرور 2.5 اینچ', 'SAS 1TB', 'عدد', 30000000, 37000000, 5, 'کالا'], |
| 624 | ['P002', 'سوئیچ 24 پورت', 'با 2 پاور', 'عدد', 1800000000, 2180000000, 2, 'کالا'], |
| 625 | ['S001', 'خدمات نصب و راهاندازی', '', 'ساعت', 0, 5000000, 0, 'خدمت'] |
| 626 | ]; |
| 627 | const ws = XLSX.utils.aoa_to_sheet(data); |
| 628 | const wb = XLSX.utils.book_new(); |
| 629 | XLSX.utils.book_append_sheet(wb, ws, 'کالاها'); |
| 630 | await this._saveFile(wb, 'finora-products-template.xlsx'); |
| 631 | } |
| 632 | |
| 633 | async downloadContactsTemplate() { |
| 634 | await loadSheetJS(); |
| 635 | // A blank, privacy-safe template must never ship real customer identifiers. |
| 636 | // Users populate their own records; no real-looking phone/national-ID samples. |
| 637 | const data = [ |
| 638 | ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'] |
| 639 | ]; |
| 640 | const ws = XLSX.utils.aoa_to_sheet(data); |
| 641 | const wb = XLSX.utils.book_new(); |
| 642 | XLSX.utils.book_append_sheet(wb, ws, 'اشخاص'); |
| 643 | await this._saveFile(wb, 'finora-contacts-template.xlsx'); |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | export const ExcelController = new ExcelControllerImpl(); |
| 648 | window.ExcelController = ExcelController; |