فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
test/a04-real-native-interrupted-restore
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 | class ExcelControllerImpl { |
| 26 | // ============================================================ |
| 27 | // ذخیره فایل + نمایش پیام + باز کردن خودکار (سازگار با Tauri) |
| 28 | // ============================================================ |
| 29 | async _saveFile(wb, fileName) { |
| 30 | await loadSheetJS(); |
| 31 | const isTauri = '__TAURI_INTERNALS__' in window; |
| 32 | |
| 33 | // حالت مرورگر: دانلود معمولی |
| 34 | if (!isTauri) { |
| 35 | XLSX.writeFile(wb, fileName); |
| 36 | Toast.success(`فایل «${fileName}» دانلود شد`, 'خروجی Excel'); |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | // حالت Tauri: گرفتن مسیر از کاربر + نوشتن + باز کردن |
| 41 | try { |
| 42 | const { save } = await import('@tauri-apps/plugin-dialog'); |
| 43 | const { writeFile } = await import('@tauri-apps/plugin-fs'); |
| 44 | const { openPath } = await import('@tauri-apps/plugin-opener'); |
| 45 | |
| 46 | const filePath = await save({ |
| 47 | defaultPath: fileName, |
| 48 | filters: [{ name: 'Excel', extensions: ['xlsx'] }] |
| 49 | }); |
| 50 | |
| 51 | if (!filePath) { |
| 52 | Toast.info('ذخیره فایل لغو شد'); |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | const data = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); |
| 57 | await writeFile(filePath, new Uint8Array(data)); |
| 58 | |
| 59 | Toast.success('فایل با موفقیت ذخیره و باز شد', 'خروجی Excel'); |
| 60 | |
| 61 | try { |
| 62 | await openPath(filePath); |
| 63 | } catch (openErr) { |
| 64 | console.warn('خطا در باز کردن فایل:', openErr); |
| 65 | } |
| 66 | } catch (err) { |
| 67 | console.error('خطا در ذخیره فایل:', err); |
| 68 | Toast.error('خطا در ذخیره فایل: ' + err.message, 'خروجی Excel'); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // ============================================================ |
| 73 | // خروجی کامل (Backup Excel) |
| 74 | // ============================================================ |
| 75 | async exportAll() { |
| 76 | await loadSheetJS(); |
| 77 | const user = Auth.current(); |
| 78 | if (!user) throw new Error('کاربر یافت نشد'); |
| 79 | |
| 80 | const [companies, contacts, products, invoices, cheques, treasury, expenses, units, categories] = await Promise.all([ |
| 81 | DataScope.list('companies'), |
| 82 | DataScope.list('contacts'), |
| 83 | DataScope.list('products'), |
| 84 | DataScope.list('invoices'), |
| 85 | DataScope.list('cheques'), |
| 86 | DataScope.list('treasury'), |
| 87 | DataScope.list('expenses'), |
| 88 | DataScope.list('units'), |
| 89 | DataScope.list('categories') |
| 90 | ]); |
| 91 | |
| 92 | const accounts = treasury.filter(t => t.recordType === 'account'); |
| 93 | const transactions = treasury.filter(t => t.recordType === 'transaction'); |
| 94 | const stockMovements = await DataScope.list('stock_movements'); |
| 95 | |
| 96 | const wb = XLSX.utils.book_new(); |
| 97 | |
| 98 | // ۱. کالاها |
| 99 | const productsData = [ |
| 100 | ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی', 'نوع'] |
| 101 | ]; |
| 102 | const stockMap = await ProductController.getStockMap(products.map(p => p.id)); |
| 103 | products.forEach(p => { |
| 104 | const unit = units.find(u => u.id === p.unitId); |
| 105 | productsData.push([ |
| 106 | p.code || '', |
| 107 | p.name || '', |
| 108 | p.spec || '', |
| 109 | unit?.name || p.unit || 'عدد', |
| 110 | Number(p.buyPrice) || 0, |
| 111 | Number(p.sellPrice) || 0, |
| 112 | Number(p.minStock) || 0, |
| 113 | p.trackInventory === false ? '—' : (stockMap[p.id] || 0), |
| 114 | p.trackInventory === false ? 'خدمت' : 'کالا' |
| 115 | ]); |
| 116 | }); |
| 117 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(productsData), 'کالاها'); |
| 118 | |
| 119 | // ۲. اشخاص |
| 120 | const contactsData = [ |
| 121 | ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی', 'مانده'] |
| 122 | ]; |
| 123 | const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id)); |
| 124 | contacts.forEach(c => { |
| 125 | contactsData.push([ |
| 126 | c.name || '', |
| 127 | c.entityType === 'legal' ? 'حقوقی' : 'حقیقی', |
| 128 | c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامینکننده' : 'هر دو', |
| 129 | c.mobile || '', |
| 130 | c.phone || '', |
| 131 | c.nationalId || '', |
| 132 | c.economicCode || '', |
| 133 | c.regNumber || '', |
| 134 | c.postalCode || '', |
| 135 | c.address || '', |
| 136 | Number(balanceMap[c.id]) || 0 |
| 137 | ]); |
| 138 | }); |
| 139 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(contactsData), 'اشخاص'); |
| 140 | |
| 141 | // ۳. فاکتورها (خلاصه) |
| 142 | const invoicesData = [ |
| 143 | ['شماره', 'تاریخ', 'نوع', 'پیشفاکتور', 'فروشنده', 'خریدار', 'جمع کل', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداختشده', 'باقیمانده', 'وضعیت', 'توضیحات'] |
| 144 | ]; |
| 145 | const kindLabels = { |
| 146 | sale: 'فروش', purchase: 'خرید', sale_return: 'برگشت فروش', |
| 147 | purchase_return: 'برگشت خرید', non_formal: 'غیررسمی' |
| 148 | }; |
| 149 | invoices.forEach(inv => { |
| 150 | invoicesData.push([ |
| 151 | inv.number || '', |
| 152 | inv.date || '', |
| 153 | kindLabels[inv.kind] || inv.kind, |
| 154 | inv.isPreInvoice ? 'بله' : 'خیر', |
| 155 | inv.companyName || '', |
| 156 | inv.contactName || '', |
| 157 | Number(inv.subtotal) || 0, |
| 158 | Number(inv.totalDiscount) || 0, |
| 159 | Number(inv.vatAmount) || 0, |
| 160 | Number(inv.grandTotal) || 0, |
| 161 | Number(inv.paidAmount) || 0, |
| 162 | Number(inv.remaining) || 0, |
| 163 | inv.status === 'paid' ? 'تسویه' : inv.status === 'partial' ? 'جزئی' : 'پرداختنشده', |
| 164 | inv.description || '' |
| 165 | ]); |
| 166 | }); |
| 167 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(invoicesData), 'فاکتورها'); |
| 168 | |
| 169 | // ۴. اقلام فاکتور |
| 170 | const itemsData = [ |
| 171 | ['شماره فاکتور', 'تاریخ', 'کالا', 'واحد', 'تعداد', 'قیمت واحد', 'تخفیف', 'جمع ردیف'] |
| 172 | ]; |
| 173 | invoices.forEach(inv => { |
| 174 | (inv.items || []).forEach(it => { |
| 175 | itemsData.push([ |
| 176 | inv.number || '', |
| 177 | inv.date || '', |
| 178 | it.productName || '', |
| 179 | it.unit || 'عدد', |
| 180 | Number(it.qty) || 0, |
| 181 | Number(it.price) || 0, |
| 182 | Number(it.discount) || 0, |
| 183 | Number(it.lineTotal) || 0 |
| 184 | ]); |
| 185 | }); |
| 186 | }); |
| 187 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(itemsData), 'اقلام فاکتور'); |
| 188 | |
| 189 | // ۵. چکها |
| 190 | const chequesData = [ |
| 191 | ['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'شعبه', 'مبلغ', 'تاریخ صدور', 'سررسید', 'وضعیت', 'توضیحات'] |
| 192 | ]; |
| 193 | const chequeStatusLabels = { |
| 194 | pending: 'در جریان', cleared: 'وصول شده', bounced: 'برگشتی', |
| 195 | returned: 'عودت داده شده', spent: 'خرج شده' |
| 196 | }; |
| 197 | cheques.forEach(c => { |
| 198 | chequesData.push([ |
| 199 | c.direction === 'inbound' ? 'دریافتی' : 'پرداختی', |
| 200 | c.contactName || '', |
| 201 | c.sayadNumber || '', |
| 202 | c.bankName || '', |
| 203 | c.branchName || '', |
| 204 | Number(c.amount) || 0, |
| 205 | c.issueDate || '', |
| 206 | c.dueDate || '', |
| 207 | chequeStatusLabels[c.status] || c.status, |
| 208 | c.description || '' |
| 209 | ]); |
| 210 | }); |
| 211 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(chequesData), 'چکها'); |
| 212 | |
| 213 | // ۶. تراکنشها |
| 214 | const txData = [ |
| 215 | ['نوع', 'تاریخ', 'طرف حساب', 'از حساب', 'به حساب', 'مبلغ', 'روش', 'توضیحات'] |
| 216 | ]; |
| 217 | const methodLabels = { cash: 'نقدی', card: 'کارت', cheque: 'چک', transfer: 'انتقال' }; |
| 218 | transactions.forEach(t => { |
| 219 | const fromAcc = accounts.find(a => a.id === t.fromAccountId); |
| 220 | const toAcc = accounts.find(a => a.id === t.toAccountId); |
| 221 | txData.push([ |
| 222 | t.type === 'receipt' ? 'دریافت' : t.type === 'payment' ? 'پرداخت' : 'انتقال', |
| 223 | t.date || '', |
| 224 | t.contactName || '', |
| 225 | fromAcc?.name || '', |
| 226 | toAcc?.name || '', |
| 227 | Number(t.amount) || 0, |
| 228 | methodLabels[t.method] || t.method, |
| 229 | t.description || '' |
| 230 | ]); |
| 231 | }); |
| 232 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(txData), 'تراکنشها'); |
| 233 | |
| 234 | // ۷. هزینهها |
| 235 | const expData = [ |
| 236 | ['نوع', 'تاریخ', 'سرفصل', 'شرح', 'روش', 'شماره پیگیری', 'مبلغ'] |
| 237 | ]; |
| 238 | expenses.forEach(e => { |
| 239 | expData.push([ |
| 240 | e.kind === 'income' ? 'درآمد' : 'هزینه', |
| 241 | e.date || '', |
| 242 | e.category || '', |
| 243 | e.description || '', |
| 244 | methodLabels[e.method] || e.method, |
| 245 | e.refNumber || '', |
| 246 | Number(e.amount) || 0 |
| 247 | ]); |
| 248 | }); |
| 249 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(expData), 'هزینهها'); |
| 250 | |
| 251 | // ۸. شرکتها |
| 252 | const compData = [ |
| 253 | ['نام', 'نوع', 'تلفن', 'شناسه ملی', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'] |
| 254 | ]; |
| 255 | companies.forEach(c => { |
| 256 | compData.push([ |
| 257 | c.name || '', |
| 258 | c.entity_type === 'legal' ? 'حقوقی' : 'حقیقی', |
| 259 | c.phone || '', |
| 260 | c.national_id || '', |
| 261 | c.economic_code || '', |
| 262 | c.reg_number || '', |
| 263 | c.postal_code || '', |
| 264 | c.address || '' |
| 265 | ]); |
| 266 | }); |
| 267 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(compData), 'شرکتها'); |
| 268 | |
| 269 | // ۹. کاردکس انبار |
| 270 | const mvData = [ |
| 271 | ['کالا', 'نوع حرکت', 'تعداد', 'مرجع', 'یادداشت', 'تاریخ'] |
| 272 | ]; |
| 273 | const typeLabels = { in: 'ورود', out: 'خروج', adjust: 'اصلاح' }; |
| 274 | stockMovements.forEach(m => { |
| 275 | const p = products.find(prod => prod.id === m.productId); |
| 276 | mvData.push([ |
| 277 | p?.name || '', |
| 278 | typeLabels[m.type] || m.type, |
| 279 | Number(m.qty) || 0, |
| 280 | m.refType || '', |
| 281 | m.note || '', |
| 282 | m.date || '' |
| 283 | ]); |
| 284 | }); |
| 285 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(mvData), 'کاردکس'); |
| 286 | |
| 287 | // ذخیره + پیام |
| 288 | const date = Jalali.today().replace(/\//g, '-'); |
| 289 | await this._saveFile(wb, `finora-backup-${date}.xlsx`); |
| 290 | |
| 291 | return { |
| 292 | sheets: 9, |
| 293 | counts: { |
| 294 | products: products.length, |
| 295 | contacts: contacts.length, |
| 296 | invoices: invoices.length, |
| 297 | items: itemsData.length - 1, |
| 298 | cheques: cheques.length, |
| 299 | transactions: transactions.length, |
| 300 | expenses: expenses.length, |
| 301 | companies: companies.length, |
| 302 | movements: stockMovements.length |
| 303 | } |
| 304 | }; |
| 305 | } |
| 306 | |
| 307 | // ============================================================ |
| 308 | // خروجی انتخابی |
| 309 | // ============================================================ |
| 310 | async exportSection(section) { |
| 311 | await loadSheetJS(); |
| 312 | const user = Auth.current(); |
| 313 | if (!user) throw new Error('کاربر یافت نشد'); |
| 314 | |
| 315 | const wb = XLSX.utils.book_new(); |
| 316 | const date = Jalali.today().replace(/\//g, '-'); |
| 317 | |
| 318 | switch (section) { |
| 319 | case 'products': { |
| 320 | const products = await DataScope.list('products'); |
| 321 | const units = await DataScope.list('units'); |
| 322 | const stockMap = await ProductController.getStockMap(products.map(p => p.id)); |
| 323 | const data = [['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی']]; |
| 324 | products.forEach(p => { |
| 325 | const unit = units.find(u => u.id === p.unitId); |
| 326 | data.push([ |
| 327 | p.code || '', p.name || '', p.spec || '', |
| 328 | unit?.name || p.unit || 'عدد', |
| 329 | Number(p.buyPrice) || 0, |
| 330 | Number(p.sellPrice) || 0, |
| 331 | Number(p.minStock) || 0, |
| 332 | p.trackInventory === false ? '—' : (stockMap[p.id] || 0) |
| 333 | ]); |
| 334 | }); |
| 335 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'کالاها'); |
| 336 | await this._saveFile(wb, `finora-products-${date}.xlsx`); |
| 337 | return { count: products.length }; |
| 338 | } |
| 339 | |
| 340 | case 'contacts': { |
| 341 | const contacts = await DataScope.list('contacts'); |
| 342 | const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id)); |
| 343 | const data = [['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد پستی', 'نشانی', 'مانده']]; |
| 344 | contacts.forEach(c => { |
| 345 | data.push([ |
| 346 | c.name || '', |
| 347 | c.entityType === 'legal' ? 'حقوقی' : 'حقیقی', |
| 348 | c.role === 'customer' ? 'مشتری' : c.role === 'supplier' ? 'تامینکننده' : 'هر دو', |
| 349 | c.mobile || '', c.phone || '', c.nationalId || '', |
| 350 | c.postalCode || '', c.address || '', |
| 351 | Number(balanceMap[c.id]) || 0 |
| 352 | ]); |
| 353 | }); |
| 354 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'اشخاص'); |
| 355 | await this._saveFile(wb, `finora-contacts-${date}.xlsx`); |
| 356 | return { count: contacts.length }; |
| 357 | } |
| 358 | |
| 359 | case 'invoices': { |
| 360 | const invoices = await DataScope.list('invoices'); |
| 361 | const data = [['شماره', 'تاریخ', 'نوع', 'خریدار', 'جمع', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداختشده', 'باقیمانده']]; |
| 362 | invoices.forEach(inv => { |
| 363 | data.push([ |
| 364 | inv.number || '', inv.date || '', |
| 365 | inv.kindLabel || inv.kind || '', |
| 366 | inv.contactName || '', |
| 367 | Number(inv.subtotal) || 0, |
| 368 | Number(inv.totalDiscount) || 0, |
| 369 | Number(inv.vatAmount) || 0, |
| 370 | Number(inv.grandTotal) || 0, |
| 371 | Number(inv.paidAmount) || 0, |
| 372 | Number(inv.remaining) || 0 |
| 373 | ]); |
| 374 | }); |
| 375 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'فاکتورها'); |
| 376 | await this._saveFile(wb, `finora-invoices-${date}.xlsx`); |
| 377 | return { count: invoices.length }; |
| 378 | } |
| 379 | |
| 380 | case 'cheques': { |
| 381 | const cheques = await DataScope.list('cheques'); |
| 382 | const data = [['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'مبلغ', 'سررسید', 'وضعیت']]; |
| 383 | cheques.forEach(c => { |
| 384 | data.push([ |
| 385 | c.direction === 'inbound' ? 'دریافتی' : 'پرداختی', |
| 386 | c.contactName || '', c.sayadNumber || '', c.bankName || '', |
| 387 | Number(c.amount) || 0, c.dueDate || '', c.status || '' |
| 388 | ]); |
| 389 | }); |
| 390 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'چکها'); |
| 391 | await this._saveFile(wb, `finora-cheques-${date}.xlsx`); |
| 392 | return { count: cheques.length }; |
| 393 | } |
| 394 | |
| 395 | case 'expenses': { |
| 396 | const expenses = await DataScope.list('expenses'); |
| 397 | const data = [['نوع', 'تاریخ', 'سرفصل', 'شرح', 'مبلغ']]; |
| 398 | expenses.forEach(e => { |
| 399 | data.push([ |
| 400 | e.kind === 'income' ? 'درآمد' : 'هزینه', |
| 401 | e.date || '', e.category || '', |
| 402 | e.description || '', Number(e.amount) || 0 |
| 403 | ]); |
| 404 | }); |
| 405 | XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(data), 'هزینهها'); |
| 406 | await this._saveFile(wb, `finora-expenses-${date}.xlsx`); |
| 407 | return { count: expenses.length }; |
| 408 | } |
| 409 | |
| 410 | default: |
| 411 | throw new Error('بخش نامعتبر'); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | // ============================================================ |
| 416 | // ورودی از Excel |
| 417 | // ============================================================ |
| 418 | async readExcelFile(file) { |
| 419 | await loadSheetJS(); |
| 420 | return new Promise((resolve, reject) => { |
| 421 | const reader = new FileReader(); |
| 422 | reader.onload = (e) => { |
| 423 | try { |
| 424 | const data = new Uint8Array(e.target.result); |
| 425 | const workbook = XLSX.read(data, { type: 'array' }); |
| 426 | const result = {}; |
| 427 | workbook.SheetNames.forEach(sheetName => { |
| 428 | result[sheetName] = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]); |
| 429 | }); |
| 430 | resolve(result); |
| 431 | } catch (err) { |
| 432 | reject(new Error('خطا در خواندن فایل اکسل: ' + err.message)); |
| 433 | } |
| 434 | }; |
| 435 | reader.onerror = () => reject(new Error('خطا در خواندن فایل')); |
| 436 | reader.readAsArrayBuffer(file); |
| 437 | }); |
| 438 | } |
| 439 | |
| 440 | /** |
| 441 | * پیشنمایش فایل قبل از ایمپورت |
| 442 | */ |
| 443 | async previewFile(file) { |
| 444 | const data = await this.readExcelFile(file); |
| 445 | const sheets = Object.keys(data).map(name => ({ |
| 446 | name, |
| 447 | count: data[name].length, |
| 448 | sample: data[name].slice(0, 3) |
| 449 | })); |
| 450 | return { sheets, raw: data }; |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * ایمپورت کالاها از Excel |
| 455 | */ |
| 456 | async importProducts(rawData, options = {}) { |
| 457 | const user = Auth.current(); |
| 458 | 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 | |
| 467 | const mode = options.mode || 'merge'; |
| 468 | const existing = await DataScope.list('products'); |
| 469 | |
| 470 | if (mode === 'replace') { |
| 471 | for (const p of existing) { |
| 472 | await StorageService.delete('products', p.id); |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | let added = 0, skipped = 0; |
| 477 | for (const row of rows) { |
| 478 | const name = row['نام'] || row['نام کالا'] || row['عنوان']; |
| 479 | if (!name) { skipped++; continue; } |
| 480 | |
| 481 | const code = String(row['کد'] || row['کد کالا'] || '').trim(); |
| 482 | if (mode === 'merge' && code && existing.some(p => p.code === code)) { |
| 483 | skipped++; |
| 484 | continue; |
| 485 | } |
| 486 | |
| 487 | const product = { |
| 488 | id: StorageService.uid('prod_'), |
| 489 | ownerUserId: user.id, |
| 490 | code, |
| 491 | name: String(name).trim(), |
| 492 | spec: String(row['مشخصه'] || row['مشخصه و نوع'] || '').trim(), |
| 493 | unit: String(row['واحد'] || 'عدد').trim(), |
| 494 | unitId: null, |
| 495 | categoryId: null, |
| 496 | buyPrice: Number(row['قیمت خرید'] || row['قیمت خرید (ریال)'] || 0) || 0, |
| 497 | sellPrice: Number(row['قیمت فروش'] || row['قیمت فروش (ریال)'] || 0) || 0, |
| 498 | minStock: Number(row['نقطه سفارش'] || 0) || 0, |
| 499 | trackInventory: (row['نوع'] || '').toString().includes('خدمت') ? false : true, |
| 500 | isActiveSell: true, |
| 501 | isActiveBuy: true, |
| 502 | description: '' |
| 503 | }; |
| 504 | await StorageService.put('products', await DataScope.stamp('products', product)); |
| 505 | added++; |
| 506 | } |
| 507 | |
| 508 | return { added, skipped, mode }; |
| 509 | } |
| 510 | |
| 511 | /** |
| 512 | * ایمپورت اشخاص از Excel |
| 513 | */ |
| 514 | async importContacts(rawData, options = {}) { |
| 515 | const user = Auth.current(); |
| 516 | if (!user) throw new Error('کاربر یافت نشد'); |
| 517 | |
| 518 | const sheetName = Object.keys(rawData).find(n => |
| 519 | n.includes('اشخاص') || n.toLowerCase().includes('contact') |
| 520 | ) || Object.keys(rawData)[0]; |
| 521 | |
| 522 | const rows = rawData[sheetName] || []; |
| 523 | if (rows.length === 0) throw new Error('شیت اشخاص خالی است'); |
| 524 | |
| 525 | const mode = options.mode || 'merge'; |
| 526 | const existing = await DataScope.list('contacts'); |
| 527 | |
| 528 | if (mode === 'replace') { |
| 529 | for (const c of existing) { |
| 530 | await StorageService.delete('contacts', c.id); |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | let added = 0, skipped = 0; |
| 535 | for (const row of rows) { |
| 536 | const name = row['نام'] || row['نام شخص یا شرکت'] || row['نام شخص']; |
| 537 | if (!name) { skipped++; continue; } |
| 538 | |
| 539 | const mobile = String(row['موبایل'] || row['شماره همراه'] || '').trim(); |
| 540 | if (mode === 'merge' && mobile && existing.some(c => c.mobile === mobile)) { |
| 541 | skipped++; |
| 542 | continue; |
| 543 | } |
| 544 | |
| 545 | const entityType = (row['نوع'] || row['نوع (حقیقی/حقوقی)'] || '').toString().includes('حقوقی') ? 'legal' : 'natural'; |
| 546 | |
| 547 | const contact = { |
| 548 | id: StorageService.uid('contact_'), |
| 549 | ownerUserId: user.id, |
| 550 | entityType, |
| 551 | role: (row['نقش'] || '').toString().includes('تامین') ? 'supplier' : 'customer', |
| 552 | prefix: '', |
| 553 | name: String(name).trim(), |
| 554 | mobile, |
| 555 | phone: String(row['تلفن'] || '').trim(), |
| 556 | nationalId: String(row['کد ملی/شناسه'] || row['شناسه یا کد ملی'] || row['کد ملی'] || '').trim(), |
| 557 | economicCode: String(row['کد اقتصادی'] || '').trim(), |
| 558 | regNumber: String(row['شماره ثبت'] || '').trim(), |
| 559 | postalCode: String(row['کد پستی'] || '').trim(), |
| 560 | address: String(row['نشانی'] || '').trim(), |
| 561 | tags: [], |
| 562 | note: '', |
| 563 | isActive: true |
| 564 | }; |
| 565 | await StorageService.put('contacts', await DataScope.stamp('contacts', contact)); |
| 566 | added++; |
| 567 | } |
| 568 | |
| 569 | return { added, skipped, mode }; |
| 570 | } |
| 571 | |
| 572 | // ============================================================ |
| 573 | // دانلود قالبهای نمونه |
| 574 | // ============================================================ |
| 575 | async downloadProductsTemplate() { |
| 576 | await loadSheetJS(); |
| 577 | const data = [ |
| 578 | ['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'نوع'], |
| 579 | ['P001', 'هارد سرور 2.5 اینچ', 'SAS 1TB', 'عدد', 30000000, 37000000, 5, 'کالا'], |
| 580 | ['P002', 'سوئیچ 24 پورت', 'با 2 پاور', 'عدد', 1800000000, 2180000000, 2, 'کالا'], |
| 581 | ['S001', 'خدمات نصب و راهاندازی', '', 'ساعت', 0, 5000000, 0, 'خدمت'] |
| 582 | ]; |
| 583 | const ws = XLSX.utils.aoa_to_sheet(data); |
| 584 | const wb = XLSX.utils.book_new(); |
| 585 | XLSX.utils.book_append_sheet(wb, ws, 'کالاها'); |
| 586 | await this._saveFile(wb, 'finora-products-template.xlsx'); |
| 587 | } |
| 588 | |
| 589 | async downloadContactsTemplate() { |
| 590 | await loadSheetJS(); |
| 591 | const data = [ |
| 592 | ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'], |
| 593 | ['شرکت آرا بتن', 'حقوقی', 'مشتری', '09124376991', '', '14008507476', '14008507476', '544926', '1445956311', 'تهران'], |
| 594 | ['آقای احمدی', 'حقیقی', 'مشتری', '09121111111', '', '1234567890', '', '', '1234567890', 'اصفهان'] |
| 595 | ]; |
| 596 | const ws = XLSX.utils.aoa_to_sheet(data); |
| 597 | const wb = XLSX.utils.book_new(); |
| 598 | XLSX.utils.book_append_sheet(wb, ws, 'اشخاص'); |
| 599 | await this._saveFile(wb, 'finora-contacts-template.xlsx'); |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | export const ExcelController = new ExcelControllerImpl(); |
| 604 | window.ExcelController = ExcelController; |