فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
release/v2.0.0
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 | // Factor-easyPro V2 / Phase 1: isolated accounting workbench. |
| 2 | // Existing invoice, inventory and treasury workflows are deliberately untouched. |
| 3 | import { AccountingService as Ledger } from '../core/AccountingService.js'; |
| 4 | import { RetailPostingService as Retail } from '../core/RetailPostingService.js'; |
| 5 | import { DataScope } from '../core/DataScope.js'; |
| 6 | import { Auth } from '../core/Auth.js'; |
| 7 | import { Modal } from '../core/Modal.js'; |
| 8 | import { Toast } from '../core/Toast.js'; |
| 9 | import { Formatters } from '../utils/Formatters.js'; |
| 10 | import { Jalali } from '../utils/Jalali.js'; |
| 11 | import { ACCOUNT_LEVELS, ACCOUNT_TYPES } from '../core/AccountingCore.mjs'; |
| 12 | |
| 13 | const levelNames = { group: 'گروه', general: 'کل', subsidiary: 'معین', detail: 'تفصیلی' }; |
| 14 | const typeNames = { asset: 'دارایی', liability: 'بدهی', equity: 'حقوق مالکانه', revenue: 'درآمد', expense: 'هزینه' }; |
| 15 | const html = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 16 | const digits = input => String(input ?? '').replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632)); |
| 17 | const rial = input => { |
| 18 | const raw = digits(input).replace(/[,_،\s]/g, ''); |
| 19 | if (!raw) return 0; |
| 20 | if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error('مبلغ باید عدد صحیح و غیرمنفی به ریال باشد'); |
| 21 | return Number(raw); |
| 22 | }; |
| 23 | const safeDate = () => Jalali.today(); |
| 24 | |
| 25 | class AccountingViewImpl { |
| 26 | constructor() { |
| 27 | this.tab = 'journals'; |
| 28 | this.accounts = []; |
| 29 | this.periods = []; |
| 30 | this.journals = []; |
| 31 | this.busy = false; |
| 32 | } |
| 33 | async reload() { |
| 34 | [this.accounts, this.periods, this.journals] = await Promise.all([ |
| 35 | Ledger.listAccounts(), Ledger.listPeriods(), Ledger.listJournals() |
| 36 | ]); |
| 37 | } |
| 38 | async render() { |
| 39 | await this.reload(); |
| 40 | const tabs = [ |
| 41 | ['journals', 'اسناد حسابداری'], |
| 42 | ['accounts', 'کدینگ حسابها'], |
| 43 | ['periods', 'دورههای مالی'], |
| 44 | ['trial', 'تراز آزمایشی'], |
| 45 | ['reports', 'گزارشهای مالی'], |
| 46 | ['integration', 'عملیات یکپارچه و انبار'] |
| 47 | ]; |
| 48 | return `<div class="page-title"><h2>حسابداری دوبل</h2> |
| 49 | <p>گردشهای مالی و موجودی برای شرکتهای فعالشده بهصورت اتمیک ثبت میشوند؛ دادههای قدیمی بدون مهاجرت تأییدشده تغییر نمیکنند.</p></div> |
| 50 | <div class="toolbar" style="gap:8px;flex-wrap:wrap"> |
| 51 | ${tabs.map(([id, label]) => `<button class="btn ${this.tab === id ? '' : 'btn-secondary'}" onclick="window.AccountingView.switchTab('${id}')">${label}</button>`).join('')} |
| 52 | </div> |
| 53 | <div id="accountingWorkbench">${await this.body()}</div>`; |
| 54 | } |
| 55 | onMount() { window.AccountingView = this; } |
| 56 | async switchTab(tab) { |
| 57 | this.tab = tab; |
| 58 | await this.refresh(); |
| 59 | } |
| 60 | async refresh() { |
| 61 | try { |
| 62 | await this.reload(); |
| 63 | const host = document.getElementById('accountingWorkbench'); |
| 64 | if (host) host.innerHTML = await this.body(); |
| 65 | } catch (error) { |
| 66 | Toast.error('خطای حسابداری: ' + error.message); |
| 67 | } |
| 68 | } |
| 69 | async body() { |
| 70 | switch (this.tab) { |
| 71 | case 'accounts': return this.renderAccounts(); |
| 72 | case 'periods': return this.renderPeriods(); |
| 73 | case 'trial': return this.renderTrial(); |
| 74 | case 'reports': return this.renderReports(); |
| 75 | case 'integration': return this.renderIntegration(); |
| 76 | default: return this.renderJournals(); |
| 77 | } |
| 78 | } |
| 79 | openPeriods() { |
| 80 | this.tab = 'periods'; |
| 81 | return this.refresh(); |
| 82 | } |
| 83 | renderPeriods() { |
| 84 | const rows = this.periods.map(p => `<tr> |
| 85 | <td><strong>${html(p.name)}</strong></td> |
| 86 | <td>${html(p.startDate)}</td><td>${html(p.endDate)}</td> |
| 87 | <td><span class="badge ${p.closed ? 'badge-muted' : 'badge-success'}">${p.closed ? 'بسته' : 'باز'}</span></td> |
| 88 | <td>${p.closed ? '—' : `<button class="btn btn-secondary" onclick="window.AccountingView.closePeriod('${html(p.id)}')">بستن دوره</button>`}</td></tr>`).join(''); |
| 89 | return `<div class="card"> |
| 90 | <div class="toolbar"><strong>دورههای مالی</strong> |
| 91 | <button class="btn" onclick="window.AccountingView.openPeriodModal()">افزودن دوره مالی</button></div> |
| 92 | <div class="table-wrap"><table><thead><tr><th>نام دوره</th><th>شروع</th><th>پایان</th><th>وضعیت</th><th>عملیات</th></tr></thead> |
| 93 | <tbody>${rows || '<tr><td colspan="5">هنوز دوره مالی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 94 | } |
| 95 | renderAccounts() { |
| 96 | const rows = this.accounts.slice().sort((a, b) => String(a.code).localeCompare(String(b.code), 'fa')).map(a => `<tr> |
| 97 | <td>${html(a.code)}</td><td>${html(a.name)}</td><td>${levelNames[a.level] || html(a.level)}</td> |
| 98 | <td>${typeNames[a.type] || html(a.type)}</td><td>${html(a.parentCode || '—')}</td> |
| 99 | <td>${a.active === false ? 'غیرفعال' : 'فعال'}</td></tr>`).join(''); |
| 100 | return `<div class="card"> |
| 101 | <div class="toolbar"><strong>سرفصلهای حسابداری</strong> |
| 102 | <button class="btn btn-secondary" onclick="window.AccountingView.seedChart()">ایجاد کدینگ پیشنهادی</button> |
| 103 | <button class="btn" onclick="window.AccountingView.openAccountModal()">افزودن حساب</button></div> |
| 104 | <p style="font-size:12px;color:var(--text-muted);margin:10px 0">کدینگ پیشنهادی مختص این پروژه است و رونوشتی از کدینگ اختصاصی هلو نیست. حساب دارای زیرمجموعه قابل انتخاب در سند نیست.</p> |
| 105 | <div class="table-wrap"><table><thead><tr><th>کد</th><th>نام</th><th>سطح</th><th>ماهیت</th><th>والد</th><th>وضعیت</th></tr></thead> |
| 106 | <tbody>${rows || '<tr><td colspan="6">حسابی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 107 | } |
| 108 | renderJournals() { |
| 109 | const rows = this.journals.slice().reverse().map(j => `<tr> |
| 110 | <td>${html(j.date)}</td><td>${html(j.description || '—')}</td> |
| 111 | <td>${this.periods.find(p => p.id === j.periodId)?.name ? html(this.periods.find(p => p.id === j.periodId).name) : '—'}</td> |
| 112 | <td>${Formatters.number(j.debit || 0)}</td><td>${Formatters.number(j.credit || 0)}</td> |
| 113 | <td><span class="badge ${j.status === 'posted' ? 'badge-success' : 'badge-warning'}">${j.status === 'posted' ? 'قطعی' : 'پیشنویس'}</span>${j.reversedById ? ' / برگشتخورده' : ''}</td> |
| 114 | <td style="white-space:nowrap"> |
| 115 | <button class="btn btn-secondary" onclick="window.AccountingView.showJournal('${html(j.id)}')">مشاهده</button> |
| 116 | ${j.status === 'draft' ? `<button class="btn btn-secondary" onclick="window.AccountingView.openJournalModal('${html(j.id)}')">ویرایش</button> |
| 117 | <button class="btn" onclick="window.AccountingView.postDraft('${html(j.id)}')">قطعی</button> |
| 118 | <button class="btn btn-secondary" onclick="window.AccountingView.deleteDraft('${html(j.id)}')">حذف پیشنویس</button>` : ''} |
| 119 | ${j.status === 'posted' && !j.reversedById && !j.reversalOfId |
| 120 | ? `<button class="btn btn-secondary" onclick="window.AccountingView.openReversal('${html(j.id)}')">برگشت</button>` : ''} |
| 121 | </td></tr>`).join(''); |
| 122 | return `<div class="card"> |
| 123 | <div class="toolbar"><strong>اسناد حسابداری مستقل</strong> |
| 124 | <button class="btn" onclick="window.AccountingView.openJournalModal()">ایجاد سند دستی</button></div> |
| 125 | <p style="font-size:12px;color:var(--text-muted);margin:10px 0">اسناد این قسمت فعلاً مستقل از فاکتورها هستند. برای ثبت سند حداقل یک دوره باز و حساب قابل ثبت لازم است.</p> |
| 126 | <div class="table-wrap"><table><thead><tr> |
| 127 | <th>تاریخ</th><th>شرح</th><th>دوره</th><th>بدهکار (ریال)</th><th>بستانکار (ریال)</th><th>وضعیت</th><th>عملیات</th> |
| 128 | </tr></thead><tbody>${rows || '<tr><td colspan="7">سندی ثبت نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 129 | } |
| 130 | async renderTrial() { |
| 131 | if (!this.periods.length) return '<div class="card">ابتدا دوره مالی تعریف کنید.</div>'; |
| 132 | const periodId = this.selectedTrialPeriod && this.periods.some(p => p.id === this.selectedTrialPeriod) |
| 133 | ? this.selectedTrialPeriod : this.periods[0].id; |
| 134 | this.selectedTrialPeriod = periodId; |
| 135 | const result = await Ledger.trialBalance({ periodId }); |
| 136 | const opts = this.periods.map(p => `<option value="${html(p.id)}" ${p.id === periodId ? 'selected' : ''}>${html(p.name)}</option>`).join(''); |
| 137 | const rows = result.rows.map(r => `<tr><td>${html(r.code)}</td><td>${html(r.name)}</td> |
| 138 | <td>${Formatters.number(r.debit)}</td><td>${Formatters.number(r.credit)}</td><td>${Formatters.number(r.balance)}</td></tr>`).join(''); |
| 139 | return `<div class="card"><div class="toolbar"><strong>تراز آزمایشی اسناد قطعی</strong> |
| 140 | <select class="form-control" style="max-width:210px" onchange="window.AccountingView.setTrialPeriod(this.value)">${opts}</select></div> |
| 141 | <div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>گردش بدهکار</th><th>گردش بستانکار</th><th>مانده بدهکار - بستانکار</th></tr></thead> |
| 142 | <tbody>${rows || '<tr><td colspan="5">گردشی وجود ندارد.</td></tr>'}</tbody> |
| 143 | <tfoot><tr><th colspan="2">جمع</th><th>${Formatters.number(result.totals.debit)}</th><th>${Formatters.number(result.totals.credit)}</th><th>۰</th></tr></tfoot> |
| 144 | </table></div></div>`; |
| 145 | } |
| 146 | async renderReports() { |
| 147 | const r = await Ledger.financialReports(); |
| 148 | const rows = r.trial.map(x => `<tr><td>${html(x.code)}</td><td>${html(x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td><td>${Formatters.number(x.balance)}</td></tr>`).join(''); |
| 149 | const detail = r.detail.map(x => `<tr><td>${html(x.date)}</td><td>${html(x.description)}</td><td>${html(x.code+' — '+x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td></tr>`).join(''); |
| 150 | return `<div class="card"><div class="toolbar"><strong>گزارشهای مبتنی بر اسناد قطعی دفتر کل</strong><button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div> |
| 151 | <p>درآمد: ${Formatters.number(r.profitLoss.revenue)} ریال | هزینه و بهای تمامشده: ${Formatters.number(r.profitLoss.expenses)} ریال | سود خالص: ${Formatters.number(r.profitLoss.netProfit)} ریال</p> |
| 152 | <p>دارایی: ${Formatters.number(r.balanceSheet.assets)} | بدهی: ${Formatters.number(r.balanceSheet.liabilities)} | حقوق مالکانه با سود جاری: ${Formatters.number(r.balanceSheet.equityWithProfit)} | اختلاف ترازنامه: ${Formatters.number(r.balanceSheet.difference)}</p> |
| 153 | <h3>تراز حسابها</h3><div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody>${rows||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div> |
| 154 | <h3>روزنامه و ریز دفتر کل</h3><div class="table-wrap"><table><thead><tr><th>تاریخ</th><th>شرح</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th></tr></thead><tbody>${detail||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div></div>`; |
| 155 | } |
| 156 | async exportReports() { |
| 157 | try { |
| 158 | const r = await Ledger.financialReports(); |
| 159 | const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"'; |
| 160 | const csv = [['date','description','account_code','account_name','debit_irr','credit_irr'],...r.detail.map(x=>[x.date,x.description,x.code,x.name,x.debit,x.credit])].map(a=>a.map(esc).join(',')).join('\r\n'); |
| 161 | const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'}); |
| 162 | const url = URL.createObjectURL(blob); |
| 163 | const a=document.createElement('a');a.href=url;a.download='factor-easypro-ledger.csv';document.body.appendChild(a);a.click();a.remove(); |
| 164 | setTimeout(()=>URL.revokeObjectURL(url),3000); |
| 165 | } catch(error) { Toast.error(error.message); } |
| 166 | } |
| 167 | setTrialPeriod(id) { this.selectedTrialPeriod = id; return this.refresh(); } |
| 168 | openPeriodModal() { |
| 169 | const body = `<div class="form-group"><label class="form-label">نام دوره</label> |
| 170 | <input id="acPeriodName" class="form-control" value="سال مالی جدید"></div> |
| 171 | <div class="form-row"><div class="form-group"><label class="form-label">از تاریخ شمسی</label> |
| 172 | <input id="acPeriodStart" class="form-control" placeholder="1405/01/01"></div> |
| 173 | <div class="form-group"><label class="form-label">تا تاریخ شمسی</label> |
| 174 | <input id="acPeriodEnd" class="form-control" placeholder="1405/12/29"></div></div>`; |
| 175 | const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.savePeriod()">ذخیره دوره</button>'; |
| 176 | Modal.open({ title: 'دوره مالی جدید', body, footer, size: 'sm', closeOnBackdrop: false }); |
| 177 | } |
| 178 | async savePeriod() { |
| 179 | if (this.busy) return; |
| 180 | this.busy = true; |
| 181 | try { |
| 182 | await Ledger.createPeriod({ |
| 183 | name: document.getElementById('acPeriodName').value, |
| 184 | startDate: digits(document.getElementById('acPeriodStart').value).trim(), |
| 185 | endDate: digits(document.getElementById('acPeriodEnd').value).trim() |
| 186 | }); |
| 187 | Modal.close(); |
| 188 | Toast.success('دوره مالی ایجاد شد'); |
| 189 | await this.refresh(); |
| 190 | } catch (error) { Toast.error(error.message); } |
| 191 | finally { this.busy = false; } |
| 192 | } |
| 193 | closePeriod(id) { |
| 194 | Modal.confirm({ title: 'بستن دوره مالی', danger: true, |
| 195 | message: 'بعد از بستن، ثبت یا برگشت سند در این دوره مجاز نیست. ابتدا پشتیبان تهیه کرده و پیشنویسها را تعیین تکلیف کنید.', |
| 196 | confirmText: 'بستن قطعی دوره', onConfirm: async () => { |
| 197 | try { |
| 198 | await Ledger.closePeriod(id); |
| 199 | Toast.success('دوره مالی بسته شد'); |
| 200 | await this.refresh(); |
| 201 | } catch (error) { Toast.error(error.message); } |
| 202 | } |
| 203 | }); |
| 204 | } |
| 205 | seedChart() { |
| 206 | Modal.confirm({ title: 'ایجاد کدینگ پیشنهادی', message: |
| 207 | 'سرفصلهای پایه نمونه به شرکت فعال اضافه میشوند؛ حسابهای قبلی حذف یا تغییر نمیکنند. ادامه میدهید؟', |
| 208 | onConfirm: async () => { |
| 209 | try { |
| 210 | const r = await Ledger.seedDefaultChart(); |
| 211 | Toast.success(`${r.added} سرفصل جدید ایجاد شد`); |
| 212 | await this.refresh(); |
| 213 | } catch (error) { Toast.error(error.message); } |
| 214 | } |
| 215 | }); |
| 216 | } |
| 217 | openAccountModal() { |
| 218 | const parents = this.accounts.map(a => `<option value="${html(a.code)}">${html(a.code + ' — ' + a.name)}</option>`).join(''); |
| 219 | const levelOptions = ACCOUNT_LEVELS.map(l => `<option value="${l}">${levelNames[l]}</option>`).join(''); |
| 220 | const typeOptions = ACCOUNT_TYPES.map(t => `<option value="${t}">${typeNames[t]}</option>`).join(''); |
| 221 | const body = `<div class="form-row"><div class="form-group"><label class="form-label">کد حساب</label> |
| 222 | <input class="form-control" id="acCode" inputmode="text"></div> |
| 223 | <div class="form-group"><label class="form-label">عنوان</label> |
| 224 | <input class="form-control" id="acName"></div></div> |
| 225 | <div class="form-row"><div class="form-group"><label class="form-label">سطح</label> |
| 226 | <select class="form-control" id="acLevel" onchange="window.AccountingView.toggleParent()">${levelOptions}</select></div> |
| 227 | <div class="form-group"><label class="form-label">ماهیت</label> |
| 228 | <select class="form-control" id="acType">${typeOptions}</select></div></div> |
| 229 | <div class="form-group" id="acParentGroup" style="display:none"><label class="form-label">کد حساب والد</label> |
| 230 | <select class="form-control" id="acParent"><option value="">انتخاب والد</option>${parents}</select></div>`; |
| 231 | const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveAccount()">ثبت حساب</button>'; |
| 232 | Modal.open({ title: 'حساب جدید', body, footer, size: 'sm', closeOnBackdrop: false }); |
| 233 | } |
| 234 | toggleParent() { |
| 235 | document.getElementById('acParentGroup').style.display = document.getElementById('acLevel').value === 'group' ? 'none' : ''; |
| 236 | } |
| 237 | async saveAccount() { |
| 238 | if (this.busy) return; |
| 239 | this.busy = true; |
| 240 | try { |
| 241 | await Ledger.addAccount({ |
| 242 | code: digits(document.getElementById('acCode').value).trim(), |
| 243 | name: document.getElementById('acName').value.trim(), |
| 244 | level: document.getElementById('acLevel').value, |
| 245 | type: document.getElementById('acType').value, |
| 246 | parentCode: document.getElementById('acLevel').value === 'group' ? null : document.getElementById('acParent').value |
| 247 | }); |
| 248 | Modal.close(); |
| 249 | Toast.success('حساب اضافه شد'); |
| 250 | await this.refresh(); |
| 251 | } catch (error) { Toast.error(error.message); } |
| 252 | finally { this.busy = false; } |
| 253 | } |
| 254 | accountOptions(selected = '') { |
| 255 | const postable = this.accounts.filter(a => a.level !== 'group' && a.active !== false && a.postable !== false && |
| 256 | !this.accounts.some(child => child.parentCode === a.code)); |
| 257 | return '<option value="">انتخاب حساب</option>' + postable.map(a => `<option value="${html(a.id)}" ${a.id === selected ? 'selected' : ''}>${html(a.code + ' — ' + a.name)}</option>`).join(''); |
| 258 | } |
| 259 | journalRow(line = {}) { |
| 260 | return `<tr class="ac-journal-line"> |
| 261 | <td><select class="form-control ac-line-account">${this.accountOptions(line.accountId)}</select></td> |
| 262 | <td><input class="form-control ac-line-debit" inputmode="text" placeholder="۰" value="${html(line.debit ?? '0')}"></td> |
| 263 | <td><input class="form-control ac-line-credit" inputmode="text" placeholder="۰" value="${html(line.credit ?? '0')}"></td> |
| 264 | <td><input class="form-control ac-line-note" value="${html(line.description || '')}"></td> |
| 265 | <td><button class="btn btn-secondary" onclick="this.closest('tr').remove()">حذف</button></td> |
| 266 | </tr>`; |
| 267 | } |
| 268 | async openJournalModal(id = null) { |
| 269 | if (!this.periods.some(p => !p.closed)) { |
| 270 | Toast.warning('ابتدا یک دوره مالی باز تعریف کنید'); |
| 271 | return; |
| 272 | } |
| 273 | if (!this.accounts.some(a => a.level !== 'group')) { |
| 274 | Toast.warning('ابتدا کدینگ حسابداری را تعریف کنید'); |
| 275 | return; |
| 276 | } |
| 277 | try { |
| 278 | const draft = id ? await Ledger.getJournal(id) : null; |
| 279 | if (draft && draft.status !== 'draft') throw new Error('تنها اسناد پیشنویس قابل ویرایشاند'); |
| 280 | const periods = this.periods.filter(p => !p.closed); |
| 281 | const selected = draft?.periodId || periods.find(p => safeDate() >= p.startDate && safeDate() <= p.endDate)?.id || periods[0].id; |
| 282 | const options = periods.map(p => `<option value="${html(p.id)}" ${p.id === selected ? 'selected' : ''}>${html(p.name)}</option>`).join(''); |
| 283 | const body = `<input id="acDraftId" type="hidden" value="${html(id || '')}"> |
| 284 | <div class="form-row"><div class="form-group"><label class="form-label">دوره مالی</label> |
| 285 | <select id="acJournalPeriod" class="form-control">${options}</select></div> |
| 286 | <div class="form-group"><label class="form-label">تاریخ شمسی</label> |
| 287 | <input id="acJournalDate" class="form-control" value="${html(draft?.date || safeDate())}"></div></div> |
| 288 | <div class="form-group"><label class="form-label">شرح سند</label> |
| 289 | <input id="acJournalDescription" class="form-control" value="${html(draft?.description || '')}"></div> |
| 290 | <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار (ریال)</th> |
| 291 | <th>بستانکار (ریال)</th><th>شرح ردیف</th><th>عملیات</th></tr></thead> |
| 292 | <tbody id="acJournalLines">${(draft?.lines?.length ? draft.lines : [{}, {}]).map(l => this.journalRow(l)).join('')}</tbody> |
| 293 | </table></div><button class="btn btn-secondary" style="margin-top:10px" onclick="window.AccountingView.addJournalRow()">افزودن ردیف</button> |
| 294 | <p style="font-size:12px;color:var(--text-muted);margin-top:10px">مبالغ باید عدد صحیح به ریال باشند. پیشنویس میتواند نامتوازن باشد؛ سند قطعی باید تراز شود.</p>`; |
| 295 | const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 296 | <button class="btn btn-secondary" onclick="window.AccountingView.saveJournal('draft')">ذخیره پیشنویس</button> |
| 297 | <button class="btn" onclick="window.AccountingView.saveJournal('posted')">ثبت قطعی</button>`; |
| 298 | Modal.open({ title: id ? 'ویرایش پیشنویس' : 'سند حسابداری دستی', body, footer, size: 'lg', closeOnBackdrop: false }); |
| 299 | } catch (error) { Toast.error(error.message); } |
| 300 | } |
| 301 | addJournalRow() { |
| 302 | document.getElementById('acJournalLines')?.insertAdjacentHTML('beforeend', this.journalRow()); |
| 303 | } |
| 304 | readJournalForm() { |
| 305 | const lines = [...document.querySelectorAll('#acJournalLines .ac-journal-line')].map(row => ({ |
| 306 | accountId: row.querySelector('.ac-line-account').value, |
| 307 | debit: rial(row.querySelector('.ac-line-debit').value), |
| 308 | credit: rial(row.querySelector('.ac-line-credit').value), |
| 309 | description: row.querySelector('.ac-line-note').value.trim() |
| 310 | })); |
| 311 | return { |
| 312 | periodId: document.getElementById('acJournalPeriod').value, |
| 313 | date: digits(document.getElementById('acJournalDate').value).trim(), |
| 314 | description: document.getElementById('acJournalDescription').value.trim(), |
| 315 | lines |
| 316 | }; |
| 317 | } |
| 318 | async saveJournal(mode) { |
| 319 | if (this.busy) return; |
| 320 | this.busy = true; |
| 321 | try { |
| 322 | const draftId = document.getElementById('acDraftId').value; |
| 323 | const data = this.readJournalForm(); |
| 324 | if (draftId) { |
| 325 | await Ledger.updateDraftJournal(draftId, data, { post: mode === 'posted' }); |
| 326 | } else if (mode === 'posted') { |
| 327 | await Ledger.postJournal(data); |
| 328 | } else { |
| 329 | await Ledger.saveDraftJournal(data); |
| 330 | } |
| 331 | Modal.close(); |
| 332 | Toast.success(mode === 'posted' ? 'سند حسابداری قطعی شد' : 'پیشنویس ذخیره شد'); |
| 333 | await this.refresh(); |
| 334 | } catch (error) { Toast.error('خطای ثبت سند: ' + error.message); } |
| 335 | finally { this.busy = false; } |
| 336 | } |
| 337 | deleteDraft(id) { |
| 338 | Modal.confirm({ title: 'حذف پیشنویس', danger: true, |
| 339 | message: 'فقط سند پیشنویس و ردیفهای آن حذف میشوند. سند قطعی هرگز از این مسیر حذف نخواهد شد.', |
| 340 | confirmText: 'حذف پیشنویس', onConfirm: async () => { |
| 341 | try { |
| 342 | await Ledger.discardDraftJournal(id); |
| 343 | Toast.success('پیشنویس حذف شد'); |
| 344 | await this.refresh(); |
| 345 | } catch (error) { Toast.error(error.message); } |
| 346 | } |
| 347 | }); |
| 348 | } |
| 349 | async postDraft(id) { |
| 350 | Modal.confirm({ title: 'قطعیسازی سند', message: 'پس از قطعی شدن امکان ویرایش مستقیم وجود ندارد. ادامه میدهید؟', |
| 351 | confirmText: 'ثبت قطعی', onConfirm: async () => { |
| 352 | try { |
| 353 | await Ledger.postDraftJournal(id); |
| 354 | Toast.success('سند قطعی شد'); |
| 355 | await this.refresh(); |
| 356 | } catch (error) { Toast.error(error.message); } |
| 357 | } |
| 358 | }); |
| 359 | } |
| 360 | async showJournal(id) { |
| 361 | try { |
| 362 | const j = await Ledger.getJournal(id); |
| 363 | const lines = j.lines.map(l => { |
| 364 | const a = this.accounts.find(x => x.id === l.accountId); |
| 365 | return `<tr><td>${html(a ? a.code + ' — ' + a.name : l.accountId)}</td> |
| 366 | <td>${Formatters.number(l.debit)}</td><td>${Formatters.number(l.credit)}</td><td>${html(l.description)}</td></tr>`; |
| 367 | }).join(''); |
| 368 | Modal.open({ title: 'جزئیات سند حسابداری', size: 'lg', |
| 369 | body: `<p style="margin-bottom:10px">تاریخ: ${html(j.date)} | وضعیت: ${html(j.status)} | شرح: ${html(j.description)}</p> |
| 370 | <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>شرح</th></tr></thead> |
| 371 | <tbody>${lines}</tbody><tfoot><tr><th>جمع</th><th>${Formatters.number(j.debit)}</th><th>${Formatters.number(j.credit)}</th><th></th></tr></tfoot></table></div>`, |
| 372 | footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>' |
| 373 | }); |
| 374 | } catch (error) { Toast.error(error.message); } |
| 375 | } |
| 376 | async renderIntegration() { |
| 377 | const active = await Retail.isEnabled(); |
| 378 | if (!active) return `<div class="card"> |
| 379 | <h3>اتصال یکپارچه خرید، فروش و حسابداری</h3> |
| 380 | <p style="line-height:2;margin:12px 0">فعالسازی فقط برای شرکت بدون گردش مالی قبلی مجاز است. اگر شرکت سابقه فاکتور، انبار یا خزانه دارد، ابتدا مانده افتتاحیه و مهاجرت آن باید تأیید شود. دادههای قبلی پاک یا تبدیل خودکار نمیشوند.</p> |
| 381 | <p style="line-height:2;margin-bottom:14px">پیش از فعالسازی، دوره مالی باز بسازید و دکمه «ایجاد کدینگ پیشنهادی» را از تب کدینگ اجرا کنید.</p> |
| 382 | <button class="btn" onclick="window.AccountingView.activateRetail()">فعالسازی حسابداری یکپارچه برای شرکت خالی</button></div>`; |
| 383 | const [warehouses, balances, stocktakes, products] = await Promise.all([ |
| 384 | Retail.warehouses(),Retail.stockBalances(),Retail.getStocktakes(),DataScope.list('products') |
| 385 | ]); |
| 386 | const names = Object.fromEntries(products.map(p=>[p.id,p.name])); |
| 387 | const warehouseNames = Object.fromEntries(warehouses.map(w=>[w.id,w.name])); |
| 388 | const stockRows = balances.map(b=>`<tr><td>${html(names[b.productId]||b.productId)}</td> |
| 389 | <td>${html(warehouseNames[b.warehouseId]||b.warehouseId)}</td> |
| 390 | <td>${Formatters.number(b.quantityUnits/1000)}</td><td>${Formatters.number(b.value)} ریال</td></tr>`).join(''); |
| 391 | const takeRows=stocktakes.map(s=>`<tr><td>${html(warehouseNames[s.warehouseId]||s.warehouseId)}</td> |
| 392 | <td>${html(s.date)}</td><td>${s.status==='draft'?'در انتظار شمارش':'قطعی'}</td> |
| 393 | <td><button class="btn btn-secondary" onclick="window.AccountingView.openStocktake('${html(s.id)}')">مشاهده و شمارش</button></td></tr>`).join(''); |
| 394 | return `<div class="card"><div class="toolbar"><strong>حسابداری یکپارچه فعال است</strong> |
| 395 | <button class="btn" onclick="window.AccountingView.openWarehouse()">انبار جدید</button> |
| 396 | <button class="btn btn-secondary" onclick="window.AccountingView.openTransfer()">انتقال کالا</button> |
| 397 | <button class="btn" onclick="window.AccountingView.openStocktakeCreate()">انبارگردانی جدید</button></div> |
| 398 | <p style="margin:10px 0">فاکتور جدید، دریافت و پرداخت، هزینه و چک به دفتر حسابداری متصلاند. تغییر اسناد قطعی فقط با فرآیند اصلاح و برگشت مجاز است.</p> |
| 399 | <h4>موجودی و ارزش انبار</h4><div class="table-wrap"><table><thead><tr><th>کالا</th><th>انبار</th><th>مقدار</th><th>ارزش (ریال)</th></tr></thead> |
| 400 | <tbody>${stockRows||'<tr><td colspan="4">موجودی ثبت نشده است.</td></tr>'}</tbody></table></div> |
| 401 | <h4 style="margin-top:16px">جلسات انبارگردانی</h4><div class="table-wrap"><table><thead><tr><th>انبار</th><th>تاریخ</th><th>وضعیت</th><th>عملیات</th></tr></thead> |
| 402 | <tbody>${takeRows||'<tr><td colspan="4">جلسهای وجود ندارد.</td></tr>'}</tbody></table></div></div>`; |
| 403 | } |
| 404 | activateRetail() { |
| 405 | Modal.confirm({title:'فعالسازی ثبت مالی یکپارچه',danger:true, |
| 406 | message:'این کار گردش جدید فروش، خرید، خزانه و انبار را به حسابداری دوبل متصل میکند. شرکت دارای گردش قبلی بدون مهاجرت تأییدشده فعال نمیشود. ابتدا نسخه پشتیبان بگیرید.', |
| 407 | confirmText:'فعالسازی برای شرکت خالی', |
| 408 | onConfirm:async()=>{ |
| 409 | try{await Retail.activate();Toast.success('ثبت یکپارچه فعال شد');await this.refresh()} |
| 410 | catch(e){Toast.error(e.message)} |
| 411 | }}); |
| 412 | } |
| 413 | openWarehouse() { |
| 414 | Modal.open({title:'ایجاد انبار',size:'sm',closeOnBackdrop:false, |
| 415 | body:'<label class="form-label">نام انبار</label><input id="acWhName" class="form-control">', |
| 416 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveWarehouse()">ثبت انبار</button>'}); |
| 417 | } |
| 418 | async saveWarehouse() { |
| 419 | if(this.busy)return;this.busy=true; |
| 420 | try{await Retail.addWarehouse(document.getElementById('acWhName').value); |
| 421 | Modal.close();Toast.success('انبار ایجاد شد');await this.refresh()} |
| 422 | catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 423 | } |
| 424 | async openTransfer() { |
| 425 | try { |
| 426 | const [warehouses,products]=await Promise.all([Retail.warehouses(),DataScope.list('products')]); |
| 427 | if(warehouses.length<2){Toast.warning('برای انتقال کالا حداقل دو انبار لازم است');return} |
| 428 | const opts=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join(''); |
| 429 | const prod=products.filter(p=>p.trackInventory!==false) |
| 430 | .map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 431 | Modal.open({title:'انتقال کالا بین انبارها',size:'sm',closeOnBackdrop:false, |
| 432 | body:`<div class="form-group"><label class="form-label">کالا</label><select class="form-control" id="acTrProduct">${prod}</select></div> |
| 433 | <div class="form-group"><label class="form-label">انبار مبدا</label><select class="form-control" id="acTrFrom">${opts}</select></div> |
| 434 | <div class="form-group"><label class="form-label">انبار مقصد</label><select class="form-control" id="acTrTo">${opts}</select></div> |
| 435 | <div class="form-group"><label class="form-label">مقدار</label><input id="acTrQty" class="form-control" value="1"></div> |
| 436 | <div class="form-group"><label class="form-label">تاریخ</label><input id="acTrDate" class="form-control" value="${safeDate()}"></div>`, |
| 437 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveTransfer()">ثبت انتقال</button>'}); |
| 438 | }catch(e){Toast.error(e.message)} |
| 439 | } |
| 440 | async saveTransfer() { |
| 441 | if(this.busy)return;this.busy=true; |
| 442 | try { |
| 443 | await Retail.transferStock({ |
| 444 | productId:document.getElementById('acTrProduct').value, |
| 445 | fromWarehouseId:document.getElementById('acTrFrom').value, |
| 446 | toWarehouseId:document.getElementById('acTrTo').value, |
| 447 | quantity:Number(digits(document.getElementById('acTrQty').value)), |
| 448 | date:digits(document.getElementById('acTrDate').value)}); |
| 449 | Modal.close();Toast.success('انتقال انبار ثبت شد');await this.refresh(); |
| 450 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 451 | } |
| 452 | async openStocktakeCreate() { |
| 453 | try { |
| 454 | const warehouses=await Retail.warehouses(); |
| 455 | const options=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join(''); |
| 456 | Modal.open({title:'شروع شمارش انبار',size:'sm',closeOnBackdrop:false, |
| 457 | body:`<label class="form-label">انبار</label><select class="form-control" id="acStWarehouse">${options}</select> |
| 458 | <label class="form-label">تاریخ شمسی</label><input class="form-control" id="acStDate" value="${safeDate()}"> |
| 459 | <p style="margin-top:12px">موجودی مبنا ثابت ثبت میشود؛ برای تأیید، شمارش همه اقلام ضروری است.</p>`, |
| 460 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.createStocktake()">ایجاد جلسه</button>'}); |
| 461 | }catch(e){Toast.error(e.message)} |
| 462 | } |
| 463 | async createStocktake() { |
| 464 | if(this.busy)return;this.busy=true; |
| 465 | try { |
| 466 | const take=await Retail.newStocktake({warehouseId:document.getElementById('acStWarehouse').value, |
| 467 | date:digits(document.getElementById('acStDate').value)}); |
| 468 | Modal.close();Toast.success('جلسه شمارش ایجاد شد');await this.refresh();await this.openStocktake(take.id); |
| 469 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 470 | } |
| 471 | async openStocktake(id) { |
| 472 | try { |
| 473 | const sessions=await Retail.getStocktakes(),take=sessions.find(s=>s.id===id); |
| 474 | if(!take)throw Error('جلسه شمارش یافت نشد'); |
| 475 | const lines=await Retail.getStocktakeLines(id),products=await DataScope.list('products'); |
| 476 | const names=Object.fromEntries(products.map(p=>[p.id,p.name])); |
| 477 | const extras=products.filter(p=>p.trackInventory!==false&&!lines.some(l=>l.productId===p.id)); |
| 478 | const extraOptions=extras.map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 479 | const existing=lines.map(l=>`<tr data-product="${html(l.productId)}"> |
| 480 | <td>${html(names[l.productId]||l.productId)}</td><td>${l.expectedUnits/1000}</td> |
| 481 | <td><input class="form-control ac-count" value="${l.countedUnits===null?'':l.countedUnits/1000}" ${take.status!=='draft'?'disabled':''}></td> |
| 482 | <td><input class="form-control ac-cost" placeholder="ریال" value="${l.unitCost??''}" ${take.status!=='draft'?'disabled':''}></td></tr>`).join(''); |
| 483 | Modal.open({title:'برگه انبارگردانی',size:'lg',closeOnBackdrop:false, |
| 484 | body:`<input type="hidden" id="acStocktakeId" value="${html(id)}"> |
| 485 | <p style="margin-bottom:10px">مقدار شمارش واقعی و در صورت مازاد کالای بدون مانده، قیمت تمامشده واحد را وارد کنید.</p> |
| 486 | <div class="table-wrap"><table><thead><tr><th>کالا</th><th>مبنای سیستم</th><th>شمارش واقعی</th><th>بهای واحد مازاد</th></tr></thead> |
| 487 | <tbody id="acTakeRows">${existing}</tbody></table></div> |
| 488 | ${take.status==='draft'&&extras.length?`<div style="display:flex;gap:8px;margin-top:12px;align-items:center"> |
| 489 | <select class="form-control" id="acTakeNewProduct">${extraOptions}</select> |
| 490 | <button class="btn btn-secondary" onclick="window.AccountingView.addStocktakeProduct()">افزودن کالای جدید به شمارش</button> |
| 491 | </div>`:''}`, |
| 492 | footer:take.status==='draft'?'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button><button class="btn" onclick="window.AccountingView.saveStocktake()">ذخیره شمارش</button><button class="btn btn-secondary" onclick="window.AccountingView.finishStocktake()">تأیید نهایی</button>': |
| 493 | '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'}); |
| 494 | }catch(e){Toast.error(e.message)} |
| 495 | } |
| 496 | addStocktakeProduct() { |
| 497 | const selector=document.getElementById('acTakeNewProduct'); |
| 498 | if(!selector?.value)return; |
| 499 | const id=selector.value; |
| 500 | const label=selector.selectedOptions[0]?.textContent||id; |
| 501 | const body=document.getElementById('acTakeRows'); |
| 502 | if(!body||body.querySelector('[data-product="'+id+'"]'))return; |
| 503 | body.insertAdjacentHTML('beforeend',`<tr data-product="${html(id)}"> |
| 504 | <td>${html(label)}</td><td>۰</td> |
| 505 | <td><input class="form-control ac-count" value="0"></td> |
| 506 | <td><input class="form-control ac-cost" placeholder="ریال"></td></tr>`); |
| 507 | selector.selectedOptions[0]?.remove(); |
| 508 | } |
| 509 | async persistStocktakeCounts(id) { |
| 510 | for(const row of document.querySelectorAll('#acTakeRows tr[data-product]')){ |
| 511 | const count=digits(row.querySelector('.ac-count').value).trim(); |
| 512 | const cost=digits(row.querySelector('.ac-cost').value).trim(); |
| 513 | if(!count)throw Error('برای همه اقلام مقدار شمارش را وارد کنید'); |
| 514 | await Retail.countStocktake(id,row.dataset.product,Number(count),cost?Number(cost):null); |
| 515 | } |
| 516 | } |
| 517 | async saveStocktake() { |
| 518 | if(this.busy)return;this.busy=true; |
| 519 | try { |
| 520 | const id=document.getElementById('acStocktakeId').value; |
| 521 | await this.persistStocktakeCounts(id); |
| 522 | Modal.close();Toast.success('شمارش ثبت شد');await this.refresh(); |
| 523 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 524 | } |
| 525 | async finishStocktake() { |
| 526 | if(this.busy)return;this.busy=true; |
| 527 | try { |
| 528 | const id=document.getElementById('acStocktakeId').value; |
| 529 | await this.persistStocktakeCounts(id); |
| 530 | await Retail.finalizeStocktake(id); |
| 531 | Modal.close();Toast.success('انبارگردانی تأیید و سند تعدیل ثبت شد');await this.refresh(); |
| 532 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 533 | } |
| 534 | openReversal(id) { |
| 535 | const periods = this.periods.filter(p => !p.closed); |
| 536 | if (!periods.length) { Toast.error('دوره باز برای ثبت سند برگشت وجود ندارد'); return; } |
| 537 | const opts = periods.map(p => `<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 538 | Modal.open({ title: 'ثبت سند معکوس', size: 'sm', closeOnBackdrop: false, |
| 539 | body: `<input type="hidden" id="acReversalId" value="${html(id)}"> |
| 540 | <p style="font-size:12px;margin-bottom:10px">این عملیات سندی جداگانه با بدهکار/بستانکار معکوس میسازد و سند اصلی حذف نمیشود.</p> |
| 541 | <div class="form-group"><label class="form-label">دوره باز</label> |
| 542 | <select class="form-control" id="acReversalPeriod">${opts}</select></div> |
| 543 | <div class="form-group"><label class="form-label">تاریخ برگشت</label> |
| 544 | <input class="form-control" id="acReversalDate" value="${html(safeDate())}"></div>`, |
| 545 | footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveReversal()">ثبت سند برگشت</button>' |
| 546 | }); |
| 547 | } |
| 548 | async saveReversal() { |
| 549 | if (this.busy) return; |
| 550 | this.busy = true; |
| 551 | try { |
| 552 | await Ledger.reverseJournal(document.getElementById('acReversalId').value, { |
| 553 | periodId: document.getElementById('acReversalPeriod').value, |
| 554 | date: digits(document.getElementById('acReversalDate').value).trim() |
| 555 | }); |
| 556 | Modal.close(); |
| 557 | Toast.success('سند برگشت مستقل ثبت شد'); |
| 558 | await this.refresh(); |
| 559 | } catch (error) { Toast.error(error.message); } |
| 560 | finally { this.busy = false; } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | export const AccountingView = new AccountingViewImpl(); |