فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
test/a07-native-webview2-offline-routes
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 { OpeningBalanceService } from '../core/OpeningBalanceService.js'; |
| 5 | import { RetailPostingService as Retail } from '../core/RetailPostingService.js'; |
| 6 | import { DataScope } from '../core/DataScope.js'; |
| 7 | import { Auth } from '../core/Auth.js'; |
| 8 | import { Modal } from '../core/Modal.js'; |
| 9 | import { Toast } from '../core/Toast.js'; |
| 10 | import { Formatters } from '../utils/Formatters.js'; |
| 11 | import { Jalali } from '../utils/Jalali.js'; |
| 12 | import { ACCOUNT_LEVELS, ACCOUNT_TYPES } from '../core/AccountingCore.mjs'; |
| 13 | |
| 14 | const levelNames = { group: 'گروه', general: 'کل', subsidiary: 'معین', detail: 'تفصیلی' }; |
| 15 | const typeNames = { asset: 'دارایی', liability: 'بدهی', equity: 'حقوق مالکانه', revenue: 'درآمد', expense: 'هزینه' }; |
| 16 | const html = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 17 | const digits = input => String(input ?? '').replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632)); |
| 18 | const rial = input => { |
| 19 | const raw = digits(input).replace(/[,_،\s]/g, ''); |
| 20 | if (!raw) return 0; |
| 21 | if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error('مبلغ باید عدد صحیح و غیرمنفی به ریال باشد'); |
| 22 | return Number(raw); |
| 23 | }; |
| 24 | const safeDate = () => Jalali.today(); |
| 25 | |
| 26 | class AccountingViewImpl { |
| 27 | constructor() { |
| 28 | this.tab = 'journals'; |
| 29 | this.accounts = []; |
| 30 | this.periods = []; |
| 31 | this.journals = []; |
| 32 | this.reportFilter = {periodId:'',from:'',to:''}; |
| 33 | this.busy = false; |
| 34 | } |
| 35 | async reload() { |
| 36 | [this.accounts, this.periods, this.journals] = await Promise.all([ |
| 37 | Ledger.listAccounts(), Ledger.listPeriods(), Ledger.listJournals() |
| 38 | ]); |
| 39 | } |
| 40 | async render() { |
| 41 | await this.reload(); |
| 42 | const tabs = [ |
| 43 | ['journals', 'اسناد حسابداری'], |
| 44 | ['accounts', 'کدینگ حسابها'], |
| 45 | ['periods', 'دورههای مالی'], |
| 46 | ['trial', 'تراز آزمایشی'], |
| 47 | ['reports', 'گزارشهای مالی'], |
| 48 | ...(Auth.isAdmin() ? [['reconciliation','کنترل مغایرت']] : []), |
| 49 | ...(Auth.isAdmin() ? [['opening','افتتاحیه کنترلشده']] : []), |
| 50 | ['integration', 'عملیات یکپارچه و انبار'] |
| 51 | ]; |
| 52 | return `<div class="page-title"><h2>حسابداری دوبل</h2> |
| 53 | <p>گردشهای مالی و موجودی برای شرکتهای فعالشده بهصورت اتمیک ثبت میشوند؛ دادههای قدیمی بدون مهاجرت تأییدشده تغییر نمیکنند.</p></div> |
| 54 | <div class="toolbar" style="gap:8px;flex-wrap:wrap"> |
| 55 | ${tabs.map(([id, label]) => `<button class="btn ${this.tab === id ? '' : 'btn-secondary'}" onclick="window.AccountingView.switchTab('${id}')">${label}</button>`).join('')} |
| 56 | </div> |
| 57 | <div id="accountingWorkbench">${await this.body()}</div>`; |
| 58 | } |
| 59 | onMount() { window.AccountingView = this; } |
| 60 | async switchTab(tab) { |
| 61 | this.tab = tab; |
| 62 | await this.refresh(); |
| 63 | } |
| 64 | async refresh() { |
| 65 | try { |
| 66 | await this.reload(); |
| 67 | const host = document.getElementById('accountingWorkbench'); |
| 68 | if (host) host.innerHTML = await this.body(); |
| 69 | } catch (error) { |
| 70 | Toast.error('خطای حسابداری: ' + error.message); |
| 71 | } |
| 72 | } |
| 73 | async body() { |
| 74 | switch (this.tab) { |
| 75 | case 'accounts': return this.renderAccounts(); |
| 76 | case 'periods': return this.renderPeriods(); |
| 77 | case 'trial': return this.renderTrial(); |
| 78 | case 'reports': return this.renderReports(); |
| 79 | case 'reconciliation': return this.renderReconciliation(); |
| 80 | case 'opening': return Auth.isAdmin() ? this.renderOpening() : '<p>دسترسی مجاز نیست.</p>'; |
| 81 | case 'integration': return this.renderIntegration(); |
| 82 | default: return this.renderJournals(); |
| 83 | } |
| 84 | } |
| 85 | renderOpening() { |
| 86 | if (!Auth.isAdmin()) return '<p>دسترسی مجاز نیست.</p>'; |
| 87 | return ` |
| 88 | <section class="card" style="max-width:850px"> |
| 89 | <h3>ثبت دفتر افتتاحیه — فقط دادههای پایه موجود</h3> |
| 90 | <p style="line-height:1.9"> |
| 91 | پیش از هر ثبت، باید اشخاص، حسابها، موجودی انبار و بانک/صندوق در شرکت فعال |
| 92 | ایجاد و کنترل شده باشند. این صفحه <strong>هیچ داده قدیمی را وارد نمیکند</strong> |
| 93 | و فقط یک سند دفتر کل افتتاحیه تراز و تأییدشده ثبت میکند. |
| 94 | </p> |
| 95 | <p style="color:var(--text-muted);font-size:12px"> |
| 96 | فایل JSON باید حاوی periodId، openingDate، lines، contacts، stock و cash |
| 97 | مطابق قرارداد docs/A02_OPENING_LEDGER_SCOPE_FA.md باشد. |
| 98 | فایل برای بررسی در حافظه خوانده میشود و بدون تأیید شما نوشته نخواهد شد. |
| 99 | </p> |
| 100 | <div class="form-group"> |
| 101 | <label class="form-label" for="openingFileInput">فایل افتتاحیه برای بررسی</label> |
| 102 | <input id="openingFileInput" class="form-control" type="file" |
| 103 | accept=".json,application/json" |
| 104 | onchange="window.AccountingView.resetOpeningPreview()" /> |
| 105 | </div> |
| 106 | <button class="btn btn-secondary" onclick="window.AccountingView.previewOpeningFile()"> |
| 107 | کنترل ماندهها و دوره (بدون ثبت) |
| 108 | </button> |
| 109 | <div id="openingPreviewReport" style="margin-top:16px" role="status"> |
| 110 | <p>هنوز فایلی بررسی نشده است.</p> |
| 111 | </div> |
| 112 | </section> |
| 113 | `; |
| 114 | } |
| 115 | |
| 116 | resetOpeningPreview() { |
| 117 | this._openingCandidate = null; |
| 118 | this._openingReview = null; |
| 119 | const host = document.getElementById('openingPreviewReport'); |
| 120 | if (host) host.textContent = 'فایل تغییر کرد؛ لازم است دوباره بررسی شود.'; |
| 121 | } |
| 122 | |
| 123 | async previewOpeningFile() { |
| 124 | if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; } |
| 125 | const file = document.getElementById('openingFileInput')?.files?.[0]; |
| 126 | if (!file || file.size > 1024 * 1024) { |
| 127 | Toast.error('یک فایل JSON معتبر و حداکثر ۱ مگابایتی انتخاب کنید'); |
| 128 | return; |
| 129 | } |
| 130 | const host = document.getElementById('openingPreviewReport'); |
| 131 | this._openingCandidate = null; |
| 132 | this._openingReview = null; |
| 133 | try { |
| 134 | const raw = await file.text(); |
| 135 | const candidate = JSON.parse(raw); |
| 136 | if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) { |
| 137 | throw Error('ساختار فایل ورودی نامعتبر است'); |
| 138 | } |
| 139 | const review = await OpeningBalanceService.preview(candidate); |
| 140 | this._openingCandidate = candidate; |
| 141 | this._openingReview = review; |
| 142 | if (host) { |
| 143 | const issues = review.issues.map(code => `<li>${html(code)}</li>`).join(''); |
| 144 | host.innerHTML = ` |
| 145 | <p><strong>وضعیت:</strong> |
| 146 | ${review.readiness === 'ready-for-review' ? 'آماده تأیید' : 'ثبت مسدود'} |
| 147 | </p> |
| 148 | <p>بدهکار: ${Formatters.number(review.journal.debit)} ریال |
| 149 | | بستانکار: ${Formatters.number(review.journal.credit)} ریال</p> |
| 150 | ${issues ? `<ul style="color:var(--danger)">${issues}</ul>` : |
| 151 | '<p>در کنترلهای فعلی مغایرتی یافت نشد.</p>'} |
| 152 | <button class="btn btn-danger" ${review.readiness === 'ready-for-review' ? '' : 'disabled'} |
| 153 | onclick="window.AccountingView.confirmOpeningPosting()"> |
| 154 | ثبت قطعی سند افتتاحیه |
| 155 | </button> |
| 156 | <p style="font-size:12px;color:var(--text-muted)"> |
| 157 | در زمان ثبت، تمام کنترلها دوباره در یک تراکنش انجام میشوند. |
| 158 | بدون تأیید صریح هیچ دادهای نوشته نخواهد شد. |
| 159 | </p> |
| 160 | `; |
| 161 | } |
| 162 | } catch (error) { |
| 163 | if (host) host.textContent = 'بررسی افتتاحیه ناموفق بود: ' + error.message; |
| 164 | Toast.error('بررسی افتتاحیه متوقف شد: ' + error.message); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | confirmOpeningPosting() { |
| 169 | if (!Auth.isAdmin() || this._openingReview?.readiness !== 'ready-for-review' || |
| 170 | !this._openingCandidate) { |
| 171 | Toast.error('ابتدا فایل افتتاحیه را بدون مغایرت بررسی کنید'); |
| 172 | return; |
| 173 | } |
| 174 | Modal.confirm({ |
| 175 | title: 'تأیید ثبت قطعی افتتاحیه', |
| 176 | message: 'این عملیات سند دفتر کل افتتاحیه و رویداد حسابرسی ثبت میکند. دادههای پایه باید قبلاً کنترل و پشتیبانگیری شده باشند. آیا ثبت قطعی را تأیید میکنید؟', |
| 177 | confirmText: 'تأیید ثبت قطعی', |
| 178 | danger: true, |
| 179 | onConfirm: async () => { |
| 180 | const candidate = this._openingCandidate; |
| 181 | this._openingCandidate = null; |
| 182 | this._openingReview = null; |
| 183 | try { |
| 184 | const result = await OpeningBalanceService.commit(candidate, { |
| 185 | confirmation: 'CONFIRM_OPENING_LEDGER' |
| 186 | }); |
| 187 | Toast.success('سند افتتاحیه ' + result.journalId + ' با موفقیت ثبت شد'); |
| 188 | this.tab = 'journals'; |
| 189 | await this.refresh(); |
| 190 | } catch (error) { |
| 191 | Toast.error('ثبت افتتاحیه انجام نشد: ' + error.message); |
| 192 | } |
| 193 | } |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | openPeriods() { |
| 198 | this.tab = 'periods'; |
| 199 | return this.refresh(); |
| 200 | } |
| 201 | renderPeriods() { |
| 202 | const rows = this.periods.map(p => `<tr> |
| 203 | <td><strong>${html(p.name)}</strong></td> |
| 204 | <td>${html(p.startDate)}</td><td>${html(p.endDate)}</td> |
| 205 | <td><span class="badge ${p.closed ? 'badge-muted' : 'badge-success'}">${p.closed ? 'بسته' : 'باز'}</span></td> |
| 206 | <td>${p.closed ? '—' : `<button class="btn btn-secondary" onclick="window.AccountingView.closePeriod('${html(p.id)}')">بستن دوره</button>`}</td></tr>`).join(''); |
| 207 | return `<div class="card"> |
| 208 | <div class="toolbar"><strong>دورههای مالی</strong> |
| 209 | <button class="btn" onclick="window.AccountingView.openPeriodModal()">افزودن دوره مالی</button></div> |
| 210 | <div class="table-wrap"><table><thead><tr><th>نام دوره</th><th>شروع</th><th>پایان</th><th>وضعیت</th><th>عملیات</th></tr></thead> |
| 211 | <tbody>${rows || '<tr><td colspan="5">هنوز دوره مالی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 212 | } |
| 213 | renderAccounts() { |
| 214 | const rows = this.accounts.slice().sort((a, b) => String(a.code).localeCompare(String(b.code), 'fa')).map(a => `<tr> |
| 215 | <td>${html(a.code)}</td><td>${html(a.name)}</td><td>${levelNames[a.level] || html(a.level)}</td> |
| 216 | <td>${typeNames[a.type] || html(a.type)}</td><td>${html(a.parentCode || '—')}</td> |
| 217 | <td>${a.active === false ? 'غیرفعال' : 'فعال'}</td></tr>`).join(''); |
| 218 | return `<div class="card"> |
| 219 | <div class="toolbar"><strong>سرفصلهای حسابداری</strong> |
| 220 | <button class="btn btn-secondary" onclick="window.AccountingView.seedChart()">ایجاد کدینگ پیشنهادی</button> |
| 221 | <button class="btn" onclick="window.AccountingView.openAccountModal()">افزودن حساب</button></div> |
| 222 | <p style="font-size:12px;color:var(--text-muted);margin:10px 0">کدینگ پیشنهادی مختص این پروژه است و رونوشتی از کدینگ اختصاصی هلو نیست. حساب دارای زیرمجموعه قابل انتخاب در سند نیست.</p> |
| 223 | <div class="table-wrap"><table><thead><tr><th>کد</th><th>نام</th><th>سطح</th><th>ماهیت</th><th>والد</th><th>وضعیت</th></tr></thead> |
| 224 | <tbody>${rows || '<tr><td colspan="6">حسابی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 225 | } |
| 226 | renderJournals() { |
| 227 | const rows = this.journals.slice().reverse().map(j => `<tr> |
| 228 | <td>${html(j.date)}</td><td>${html(j.description || '—')}</td> |
| 229 | <td>${this.periods.find(p => p.id === j.periodId)?.name ? html(this.periods.find(p => p.id === j.periodId).name) : '—'}</td> |
| 230 | <td>${Formatters.number(j.debit || 0)}</td><td>${Formatters.number(j.credit || 0)}</td> |
| 231 | <td><span class="badge ${j.status === 'posted' ? 'badge-success' : 'badge-warning'}">${j.status === 'posted' ? 'قطعی' : 'پیشنویس'}</span>${j.reversedById ? ' / برگشتخورده' : ''}</td> |
| 232 | <td style="white-space:nowrap"> |
| 233 | <button class="btn btn-secondary" onclick="window.AccountingView.showJournal('${html(j.id)}')">مشاهده</button> |
| 234 | ${j.status === 'draft' ? `<button class="btn btn-secondary" onclick="window.AccountingView.openJournalModal('${html(j.id)}')">ویرایش</button> |
| 235 | <button class="btn" onclick="window.AccountingView.postDraft('${html(j.id)}')">قطعی</button> |
| 236 | <button class="btn btn-secondary" onclick="window.AccountingView.deleteDraft('${html(j.id)}')">حذف پیشنویس</button>` : ''} |
| 237 | ${j.status === 'posted' && !j.reversedById && !j.reversalOfId |
| 238 | ? `<button class="btn btn-secondary" onclick="window.AccountingView.openReversal('${html(j.id)}')">برگشت</button>` : ''} |
| 239 | </td></tr>`).join(''); |
| 240 | return `<div class="card"> |
| 241 | <div class="toolbar"><strong>اسناد حسابداری مستقل</strong> |
| 242 | <button class="btn" onclick="window.AccountingView.openJournalModal()">ایجاد سند دستی</button></div> |
| 243 | <p style="font-size:12px;color:var(--text-muted);margin:10px 0">اسناد این قسمت فعلاً مستقل از فاکتورها هستند. برای ثبت سند حداقل یک دوره باز و حساب قابل ثبت لازم است.</p> |
| 244 | <div class="table-wrap"><table><thead><tr> |
| 245 | <th>تاریخ</th><th>شرح</th><th>دوره</th><th>بدهکار (ریال)</th><th>بستانکار (ریال)</th><th>وضعیت</th><th>عملیات</th> |
| 246 | </tr></thead><tbody>${rows || '<tr><td colspan="7">سندی ثبت نشده است.</td></tr>'}</tbody></table></div></div>`; |
| 247 | } |
| 248 | async renderTrial() { |
| 249 | if (!this.periods.length) return '<div class="card">ابتدا دوره مالی تعریف کنید.</div>'; |
| 250 | const periodId = this.selectedTrialPeriod && this.periods.some(p => p.id === this.selectedTrialPeriod) |
| 251 | ? this.selectedTrialPeriod : this.periods[0].id; |
| 252 | this.selectedTrialPeriod = periodId; |
| 253 | const result = await Ledger.trialBalance({ periodId }); |
| 254 | const opts = this.periods.map(p => `<option value="${html(p.id)}" ${p.id === periodId ? 'selected' : ''}>${html(p.name)}</option>`).join(''); |
| 255 | const rows = result.rows.map(r => `<tr><td>${html(r.code)}</td><td>${html(r.name)}</td> |
| 256 | <td>${Formatters.number(r.debit)}</td><td>${Formatters.number(r.credit)}</td><td>${Formatters.number(r.balance)}</td></tr>`).join(''); |
| 257 | return `<div class="card"><div class="toolbar"><strong>تراز آزمایشی اسناد قطعی</strong> |
| 258 | <select class="form-control" style="max-width:210px" onchange="window.AccountingView.setTrialPeriod(this.value)">${opts}</select></div> |
| 259 | <div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>گردش بدهکار</th><th>گردش بستانکار</th><th>مانده بدهکار - بستانکار</th></tr></thead> |
| 260 | <tbody>${rows || '<tr><td colspan="5">گردشی وجود ندارد.</td></tr>'}</tbody> |
| 261 | <tfoot><tr><th colspan="2">جمع</th><th>${Formatters.number(result.totals.debit)}</th><th>${Formatters.number(result.totals.credit)}</th><th>۰</th></tr></tfoot> |
| 262 | </table></div></div>`; |
| 263 | } |
| 264 | async renderReports() { |
| 265 | const r = await Ledger.financialReports(this.reportFilter); |
| 266 | const filter=this.reportFilter; |
| 267 | const periodOptions=this.periods.map(p=>`<option value="${html(p.id)}" ${p.id===filter.periodId?'selected':''}>${html(p.name)}</option>`).join(''); |
| 268 | 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(''); |
| 269 | 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(''); |
| 270 | return `<div class="card"><div class="toolbar"><strong>گزارشهای مبتنی بر اسناد قطعی دفتر کل</strong> |
| 271 | <button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div> |
| 272 | <div class="toolbar" style="margin:8px 0;flex-wrap:wrap;gap:8px"> |
| 273 | <label>دوره مالی <select class="form-control" style="min-width:140px" onchange="window.AccountingView.setReportFilter('periodId',this.value)"> |
| 274 | <option value="">تمام دورهها</option>${periodOptions}</select></label> |
| 275 | <label>از تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۰۱/۰۱" value="${html(filter.from)}" |
| 276 | onchange="window.AccountingView.setReportFilter('from',this.value)"></label> |
| 277 | <label>تا تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۱۲/۲۹" value="${html(filter.to)}" |
| 278 | onchange="window.AccountingView.setReportFilter('to',this.value)"></label> |
| 279 | </div> |
| 280 | <p style="font-size:12px;color:var(--text-muted)">سود و زیان و ریز اسناد براساس فیلتر محاسبه میشوند. ترازنامه تا تاریخ انتهای بازه، تجمعی است.</p> |
| 281 | <p>درآمد: ${Formatters.number(r.profitLoss.revenue)} ریال | هزینه و بهای تمامشده: ${Formatters.number(r.profitLoss.expenses)} ریال | سود خالص: ${Formatters.number(r.profitLoss.netProfit)} ریال</p> |
| 282 | <p>دارایی: ${Formatters.number(r.balanceSheet.assets)} | بدهی: ${Formatters.number(r.balanceSheet.liabilities)} | حقوق مالکانه با سود جاری: ${Formatters.number(r.balanceSheet.equityWithProfit)} | اختلاف ترازنامه: ${Formatters.number(r.balanceSheet.difference)}</p> |
| 283 | <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> |
| 284 | <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>`; |
| 285 | } |
| 286 | async exportReports() { |
| 287 | try { |
| 288 | const r = await Ledger.financialReports(this.reportFilter); |
| 289 | const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"'; |
| 290 | 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'); |
| 291 | const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'}); |
| 292 | const url = URL.createObjectURL(blob); |
| 293 | const a=document.createElement('a');a.href=url;a.download='factor-easypro-ledger.csv';document.body.appendChild(a);a.click();a.remove(); |
| 294 | setTimeout(()=>URL.revokeObjectURL(url),3000); |
| 295 | } catch(error) { Toast.error(error.message); } |
| 296 | } |
| 297 | async renderReconciliation() { |
| 298 | if (!Auth.isAdmin()) return '<div class="card">دسترسی به کنترل مغایرت فقط برای مدیر مجاز است.</div>'; |
| 299 | const report = await Ledger.reconciliationReport(); |
| 300 | const counts = report.counts, totals = report.totals; |
| 301 | const rows = report.issues.slice(0,200).map(item => `<tr> |
| 302 | <td>${html(item.code)}</td><td>${html(item.reference||'—')}</td> |
| 303 | <td>${html(item.message)}</td> |
| 304 | <td>${html(item.expected === null ? '—' : Formatters.number(item.expected))}</td> |
| 305 | <td>${html(item.actual === null ? '—' : Formatters.number(item.actual))}</td></tr>`).join(''); |
| 306 | return `<div class="card"> |
| 307 | <div class="toolbar"><strong>کنترل مغایرت اسناد، تسویهها و موجودی</strong> |
| 308 | <button class="btn btn-secondary" onclick="window.AccountingView.exportReconciliation()">خروجی CSV</button> |
| 309 | <button class="btn btn-secondary" onclick="window.AccountingView.refresh()">بررسی مجدد</button> |
| 310 | </div> |
| 311 | <p style="margin:10px 0;line-height:1.9">این بررسی فقط خواندنی است و هیچ مبلغ یا سندی را اصلاح نمیکند. |
| 312 | ${report.integrated ? 'مغایرت حساب موجودی (۱۰۳) نیز بررسی شده است.' : 'حسابداری یکپارچه غیرفعال است؛ تطبیق انبار و دفتر کل انجام نمیشود.'}</p> |
| 313 | <p><strong>اسناد قطعی:</strong> ${Formatters.number(counts.journals)} | |
| 314 | <strong>فاکتورهای مالی:</strong> ${Formatters.number(counts.invoices)} | |
| 315 | <strong>تسویهها:</strong> ${Formatters.number(counts.settlements)} | |
| 316 | <strong>مغایرتهای شناساییشده:</strong> ${Formatters.number(counts.issues)}</p> |
| 317 | ${report.integrated ? `<p>ارزش موجودی انبار: ${Formatters.number(totals.inventoryBook)} ریال | |
| 318 | مانده دفتر کل موجودی: ${Formatters.number(totals.inventoryLedger)} ریال</p>` : ''} |
| 319 | ${!rows ? '<p style="margin:14px 0;color:var(--text-muted)">در کنترلهای فعلی مغایرتی مشاهده نشد. این نتیجه جایگزین حسابرسی مستقل نیست.</p>' : ''} |
| 320 | <div class="table-wrap"><table><thead><tr> |
| 321 | <th>نوع کنترل</th><th>مرجع</th><th>شرح مغایرت</th><th>انتظار</th><th>مقدار فعلی</th> |
| 322 | </tr></thead><tbody>${rows}</tbody></table></div> |
| 323 | ${counts.issues>200 ? '<p>فقط ۲۰۰ ردیف نخست نمایش داده شدهاند؛ برای همه ردیفها خروجی CSV بگیرید.</p>' : ''} |
| 324 | </div>`; |
| 325 | } |
| 326 | |
| 327 | async exportReconciliation() { |
| 328 | try { |
| 329 | if (!Auth.isAdmin()) throw Error('دسترسی مجاز نیست'); |
| 330 | const result = await Ledger.reconciliationReport(); |
| 331 | const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"'; |
| 332 | const rows = [['code','reference','message','expected','actual'], |
| 333 | ...result.issues.map(x=>[x.code,x.reference,x.message,x.expected,x.actual])]; |
| 334 | const csv = rows.map(line=>line.map(esc).join(',')).join('\r\n'); |
| 335 | const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'}); |
| 336 | const url=URL.createObjectURL(blob); |
| 337 | const a=document.createElement('a');a.href=url;a.download='factor-easypro-reconciliation.csv'; |
| 338 | document.body.appendChild(a);a.click();a.remove(); |
| 339 | setTimeout(()=>URL.revokeObjectURL(url),3000); |
| 340 | } catch(error){Toast.error('خروجی مغایرت: '+error.message);} |
| 341 | } |
| 342 | |
| 343 | setReportFilter(key,value) { |
| 344 | if (!['periodId','from','to'].includes(key)) return; |
| 345 | this.reportFilter={...this.reportFilter,[key]:key==='periodId'?value:digits(value).trim()}; |
| 346 | return this.refresh(); |
| 347 | } |
| 348 | setTrialPeriod(id) { this.selectedTrialPeriod = id; return this.refresh(); } |
| 349 | openPeriodModal() { |
| 350 | const body = `<div class="form-group"><label class="form-label">نام دوره</label> |
| 351 | <input id="acPeriodName" class="form-control" value="سال مالی جدید"></div> |
| 352 | <div class="form-row"><div class="form-group"><label class="form-label">از تاریخ شمسی</label> |
| 353 | <input id="acPeriodStart" class="form-control" placeholder="1405/01/01"></div> |
| 354 | <div class="form-group"><label class="form-label">تا تاریخ شمسی</label> |
| 355 | <input id="acPeriodEnd" class="form-control" placeholder="1405/12/29"></div></div>`; |
| 356 | const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.savePeriod()">ذخیره دوره</button>'; |
| 357 | Modal.open({ title: 'دوره مالی جدید', body, footer, size: 'sm', closeOnBackdrop: false }); |
| 358 | } |
| 359 | async savePeriod() { |
| 360 | if (this.busy) return; |
| 361 | this.busy = true; |
| 362 | try { |
| 363 | await Ledger.createPeriod({ |
| 364 | name: document.getElementById('acPeriodName').value, |
| 365 | startDate: digits(document.getElementById('acPeriodStart').value).trim(), |
| 366 | endDate: digits(document.getElementById('acPeriodEnd').value).trim() |
| 367 | }); |
| 368 | Modal.close(); |
| 369 | Toast.success('دوره مالی ایجاد شد'); |
| 370 | await this.refresh(); |
| 371 | } catch (error) { Toast.error(error.message); } |
| 372 | finally { this.busy = false; } |
| 373 | } |
| 374 | closePeriod(id) { |
| 375 | Modal.confirm({ title: 'بستن دوره مالی', danger: true, |
| 376 | message: 'بعد از بستن، ثبت یا برگشت سند در این دوره مجاز نیست. ابتدا پشتیبان تهیه کرده و پیشنویسها را تعیین تکلیف کنید.', |
| 377 | confirmText: 'بستن قطعی دوره', onConfirm: async () => { |
| 378 | try { |
| 379 | await Ledger.closePeriod(id); |
| 380 | Toast.success('دوره مالی بسته شد'); |
| 381 | await this.refresh(); |
| 382 | } catch (error) { Toast.error(error.message); } |
| 383 | } |
| 384 | }); |
| 385 | } |
| 386 | seedChart() { |
| 387 | Modal.confirm({ title: 'ایجاد کدینگ پیشنهادی', message: |
| 388 | 'سرفصلهای پایه نمونه به شرکت فعال اضافه میشوند؛ حسابهای قبلی حذف یا تغییر نمیکنند. ادامه میدهید؟', |
| 389 | onConfirm: async () => { |
| 390 | try { |
| 391 | const r = await Ledger.seedDefaultChart(); |
| 392 | Toast.success(`${r.added} سرفصل جدید ایجاد شد`); |
| 393 | await this.refresh(); |
| 394 | } catch (error) { Toast.error(error.message); } |
| 395 | } |
| 396 | }); |
| 397 | } |
| 398 | openAccountModal() { |
| 399 | const parents = this.accounts.map(a => `<option value="${html(a.code)}">${html(a.code + ' — ' + a.name)}</option>`).join(''); |
| 400 | const levelOptions = ACCOUNT_LEVELS.map(l => `<option value="${l}">${levelNames[l]}</option>`).join(''); |
| 401 | const typeOptions = ACCOUNT_TYPES.map(t => `<option value="${t}">${typeNames[t]}</option>`).join(''); |
| 402 | const body = `<div class="form-row"><div class="form-group"><label class="form-label">کد حساب</label> |
| 403 | <input class="form-control" id="acCode" inputmode="text"></div> |
| 404 | <div class="form-group"><label class="form-label">عنوان</label> |
| 405 | <input class="form-control" id="acName"></div></div> |
| 406 | <div class="form-row"><div class="form-group"><label class="form-label">سطح</label> |
| 407 | <select class="form-control" id="acLevel" onchange="window.AccountingView.toggleParent()">${levelOptions}</select></div> |
| 408 | <div class="form-group"><label class="form-label">ماهیت</label> |
| 409 | <select class="form-control" id="acType">${typeOptions}</select></div></div> |
| 410 | <div class="form-group" id="acParentGroup" style="display:none"><label class="form-label">کد حساب والد</label> |
| 411 | <select class="form-control" id="acParent"><option value="">انتخاب والد</option>${parents}</select></div>`; |
| 412 | const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveAccount()">ثبت حساب</button>'; |
| 413 | Modal.open({ title: 'حساب جدید', body, footer, size: 'sm', closeOnBackdrop: false }); |
| 414 | } |
| 415 | toggleParent() { |
| 416 | document.getElementById('acParentGroup').style.display = document.getElementById('acLevel').value === 'group' ? 'none' : ''; |
| 417 | } |
| 418 | async saveAccount() { |
| 419 | if (this.busy) return; |
| 420 | this.busy = true; |
| 421 | try { |
| 422 | await Ledger.addAccount({ |
| 423 | code: digits(document.getElementById('acCode').value).trim(), |
| 424 | name: document.getElementById('acName').value.trim(), |
| 425 | level: document.getElementById('acLevel').value, |
| 426 | type: document.getElementById('acType').value, |
| 427 | parentCode: document.getElementById('acLevel').value === 'group' ? null : document.getElementById('acParent').value |
| 428 | }); |
| 429 | Modal.close(); |
| 430 | Toast.success('حساب اضافه شد'); |
| 431 | await this.refresh(); |
| 432 | } catch (error) { Toast.error(error.message); } |
| 433 | finally { this.busy = false; } |
| 434 | } |
| 435 | accountOptions(selected = '') { |
| 436 | const postable = this.accounts.filter(a => a.level !== 'group' && a.active !== false && a.postable !== false && |
| 437 | !this.accounts.some(child => child.parentCode === a.code)); |
| 438 | return '<option value="">انتخاب حساب</option>' + postable.map(a => `<option value="${html(a.id)}" ${a.id === selected ? 'selected' : ''}>${html(a.code + ' — ' + a.name)}</option>`).join(''); |
| 439 | } |
| 440 | journalRow(line = {}) { |
| 441 | return `<tr class="ac-journal-line"> |
| 442 | <td><select class="form-control ac-line-account">${this.accountOptions(line.accountId)}</select></td> |
| 443 | <td><input class="form-control ac-line-debit" inputmode="text" placeholder="۰" value="${html(line.debit ?? '0')}"></td> |
| 444 | <td><input class="form-control ac-line-credit" inputmode="text" placeholder="۰" value="${html(line.credit ?? '0')}"></td> |
| 445 | <td><input class="form-control ac-line-note" value="${html(line.description || '')}"></td> |
| 446 | <td><button class="btn btn-secondary" onclick="this.closest('tr').remove()">حذف</button></td> |
| 447 | </tr>`; |
| 448 | } |
| 449 | async openJournalModal(id = null) { |
| 450 | if (!this.periods.some(p => !p.closed)) { |
| 451 | Toast.warning('ابتدا یک دوره مالی باز تعریف کنید'); |
| 452 | return; |
| 453 | } |
| 454 | if (!this.accounts.some(a => a.level !== 'group')) { |
| 455 | Toast.warning('ابتدا کدینگ حسابداری را تعریف کنید'); |
| 456 | return; |
| 457 | } |
| 458 | try { |
| 459 | const draft = id ? await Ledger.getJournal(id) : null; |
| 460 | if (draft && draft.status !== 'draft') throw new Error('تنها اسناد پیشنویس قابل ویرایشاند'); |
| 461 | const periods = this.periods.filter(p => !p.closed); |
| 462 | const selected = draft?.periodId || periods.find(p => safeDate() >= p.startDate && safeDate() <= p.endDate)?.id || periods[0].id; |
| 463 | const options = periods.map(p => `<option value="${html(p.id)}" ${p.id === selected ? 'selected' : ''}>${html(p.name)}</option>`).join(''); |
| 464 | const body = `<input id="acDraftId" type="hidden" value="${html(id || '')}"> |
| 465 | <div class="form-row"><div class="form-group"><label class="form-label">دوره مالی</label> |
| 466 | <select id="acJournalPeriod" class="form-control">${options}</select></div> |
| 467 | <div class="form-group"><label class="form-label">تاریخ شمسی</label> |
| 468 | <input id="acJournalDate" class="form-control" value="${html(draft?.date || safeDate())}"></div></div> |
| 469 | <div class="form-group"><label class="form-label">شرح سند</label> |
| 470 | <input id="acJournalDescription" class="form-control" value="${html(draft?.description || '')}"></div> |
| 471 | <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار (ریال)</th> |
| 472 | <th>بستانکار (ریال)</th><th>شرح ردیف</th><th>عملیات</th></tr></thead> |
| 473 | <tbody id="acJournalLines">${(draft?.lines?.length ? draft.lines : [{}, {}]).map(l => this.journalRow(l)).join('')}</tbody> |
| 474 | </table></div><button class="btn btn-secondary" style="margin-top:10px" onclick="window.AccountingView.addJournalRow()">افزودن ردیف</button> |
| 475 | <p style="font-size:12px;color:var(--text-muted);margin-top:10px">مبالغ باید عدد صحیح به ریال باشند. پیشنویس میتواند نامتوازن باشد؛ سند قطعی باید تراز شود.</p>`; |
| 476 | const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 477 | <button class="btn btn-secondary" onclick="window.AccountingView.saveJournal('draft')">ذخیره پیشنویس</button> |
| 478 | <button class="btn" onclick="window.AccountingView.saveJournal('posted')">ثبت قطعی</button>`; |
| 479 | Modal.open({ title: id ? 'ویرایش پیشنویس' : 'سند حسابداری دستی', body, footer, size: 'lg', closeOnBackdrop: false }); |
| 480 | } catch (error) { Toast.error(error.message); } |
| 481 | } |
| 482 | addJournalRow() { |
| 483 | document.getElementById('acJournalLines')?.insertAdjacentHTML('beforeend', this.journalRow()); |
| 484 | } |
| 485 | readJournalForm() { |
| 486 | const lines = [...document.querySelectorAll('#acJournalLines .ac-journal-line')].map(row => ({ |
| 487 | accountId: row.querySelector('.ac-line-account').value, |
| 488 | debit: rial(row.querySelector('.ac-line-debit').value), |
| 489 | credit: rial(row.querySelector('.ac-line-credit').value), |
| 490 | description: row.querySelector('.ac-line-note').value.trim() |
| 491 | })); |
| 492 | return { |
| 493 | periodId: document.getElementById('acJournalPeriod').value, |
| 494 | date: digits(document.getElementById('acJournalDate').value).trim(), |
| 495 | description: document.getElementById('acJournalDescription').value.trim(), |
| 496 | lines |
| 497 | }; |
| 498 | } |
| 499 | async saveJournal(mode) { |
| 500 | if (this.busy) return; |
| 501 | this.busy = true; |
| 502 | try { |
| 503 | const draftId = document.getElementById('acDraftId').value; |
| 504 | const data = this.readJournalForm(); |
| 505 | if (draftId) { |
| 506 | await Ledger.updateDraftJournal(draftId, data, { post: mode === 'posted' }); |
| 507 | } else if (mode === 'posted') { |
| 508 | await Ledger.postJournal(data); |
| 509 | } else { |
| 510 | await Ledger.saveDraftJournal(data); |
| 511 | } |
| 512 | Modal.close(); |
| 513 | Toast.success(mode === 'posted' ? 'سند حسابداری قطعی شد' : 'پیشنویس ذخیره شد'); |
| 514 | await this.refresh(); |
| 515 | } catch (error) { Toast.error('خطای ثبت سند: ' + error.message); } |
| 516 | finally { this.busy = false; } |
| 517 | } |
| 518 | deleteDraft(id) { |
| 519 | Modal.confirm({ title: 'حذف پیشنویس', danger: true, |
| 520 | message: 'فقط سند پیشنویس و ردیفهای آن حذف میشوند. سند قطعی هرگز از این مسیر حذف نخواهد شد.', |
| 521 | confirmText: 'حذف پیشنویس', onConfirm: async () => { |
| 522 | try { |
| 523 | await Ledger.discardDraftJournal(id); |
| 524 | Toast.success('پیشنویس حذف شد'); |
| 525 | await this.refresh(); |
| 526 | } catch (error) { Toast.error(error.message); } |
| 527 | } |
| 528 | }); |
| 529 | } |
| 530 | async postDraft(id) { |
| 531 | Modal.confirm({ title: 'قطعیسازی سند', message: 'پس از قطعی شدن امکان ویرایش مستقیم وجود ندارد. ادامه میدهید؟', |
| 532 | confirmText: 'ثبت قطعی', onConfirm: async () => { |
| 533 | try { |
| 534 | await Ledger.postDraftJournal(id); |
| 535 | Toast.success('سند قطعی شد'); |
| 536 | await this.refresh(); |
| 537 | } catch (error) { Toast.error(error.message); } |
| 538 | } |
| 539 | }); |
| 540 | } |
| 541 | async showJournal(id) { |
| 542 | try { |
| 543 | const j = await Ledger.getJournal(id); |
| 544 | const lines = j.lines.map(l => { |
| 545 | const a = this.accounts.find(x => x.id === l.accountId); |
| 546 | return `<tr><td>${html(a ? a.code + ' — ' + a.name : l.accountId)}</td> |
| 547 | <td>${Formatters.number(l.debit)}</td><td>${Formatters.number(l.credit)}</td><td>${html(l.description)}</td></tr>`; |
| 548 | }).join(''); |
| 549 | Modal.open({ title: 'جزئیات سند حسابداری', size: 'lg', |
| 550 | body: `<p style="margin-bottom:10px">تاریخ: ${html(j.date)} | وضعیت: ${html(j.status)} | شرح: ${html(j.description)}</p> |
| 551 | <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>شرح</th></tr></thead> |
| 552 | <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>`, |
| 553 | footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>' |
| 554 | }); |
| 555 | } catch (error) { Toast.error(error.message); } |
| 556 | } |
| 557 | async renderIntegration() { |
| 558 | const active = await Retail.isEnabled(); |
| 559 | if (!active) return `<div class="card"> |
| 560 | <h3>اتصال یکپارچه خرید، فروش و حسابداری</h3> |
| 561 | <p style="line-height:2;margin:12px 0">فعالسازی فقط برای شرکت بدون گردش مالی قبلی مجاز است. اگر شرکت سابقه فاکتور، انبار یا خزانه دارد، ابتدا مانده افتتاحیه و مهاجرت آن باید تأیید شود. دادههای قبلی پاک یا تبدیل خودکار نمیشوند.</p> |
| 562 | <p style="line-height:2;margin-bottom:14px">پیش از فعالسازی، دوره مالی باز بسازید و دکمه «ایجاد کدینگ پیشنهادی» را از تب کدینگ اجرا کنید.</p> |
| 563 | <button class="btn" onclick="window.AccountingView.activateRetail()">فعالسازی حسابداری یکپارچه برای شرکت خالی</button></div>`; |
| 564 | const [warehouses, balances, stocktakes, products] = await Promise.all([ |
| 565 | Retail.warehouses(),Retail.stockBalances(),Retail.getStocktakes(),DataScope.list('products') |
| 566 | ]); |
| 567 | const names = Object.fromEntries(products.map(p=>[p.id,p.name])); |
| 568 | const warehouseNames = Object.fromEntries(warehouses.map(w=>[w.id,w.name])); |
| 569 | const stockRows = balances.map(b=>`<tr><td>${html(names[b.productId]||b.productId)}</td> |
| 570 | <td>${html(warehouseNames[b.warehouseId]||b.warehouseId)}</td> |
| 571 | <td>${Formatters.number(b.quantityUnits/1000)}</td><td>${Formatters.number(b.value)} ریال</td></tr>`).join(''); |
| 572 | const takeRows=stocktakes.map(s=>`<tr><td>${html(warehouseNames[s.warehouseId]||s.warehouseId)}</td> |
| 573 | <td>${html(s.date)}</td><td>${s.status==='draft'?'در انتظار شمارش':'قطعی'}</td> |
| 574 | <td><button class="btn btn-secondary" onclick="window.AccountingView.openStocktake('${html(s.id)}')">مشاهده و شمارش</button></td></tr>`).join(''); |
| 575 | return `<div class="card"><div class="toolbar"><strong>حسابداری یکپارچه فعال است</strong> |
| 576 | <button class="btn" onclick="window.AccountingView.openWarehouse()">انبار جدید</button> |
| 577 | <button class="btn btn-secondary" onclick="window.AccountingView.openTransfer()">انتقال کالا</button> |
| 578 | <button class="btn" onclick="window.AccountingView.openStocktakeCreate()">انبارگردانی جدید</button></div> |
| 579 | <p style="margin:10px 0">فاکتور جدید، دریافت و پرداخت، هزینه و چک به دفتر حسابداری متصلاند. تغییر اسناد قطعی فقط با فرآیند اصلاح و برگشت مجاز است.</p> |
| 580 | <h4>موجودی و ارزش انبار</h4><div class="table-wrap"><table><thead><tr><th>کالا</th><th>انبار</th><th>مقدار</th><th>ارزش (ریال)</th></tr></thead> |
| 581 | <tbody>${stockRows||'<tr><td colspan="4">موجودی ثبت نشده است.</td></tr>'}</tbody></table></div> |
| 582 | <h4 style="margin-top:16px">جلسات انبارگردانی</h4><div class="table-wrap"><table><thead><tr><th>انبار</th><th>تاریخ</th><th>وضعیت</th><th>عملیات</th></tr></thead> |
| 583 | <tbody>${takeRows||'<tr><td colspan="4">جلسهای وجود ندارد.</td></tr>'}</tbody></table></div></div>`; |
| 584 | } |
| 585 | activateRetail() { |
| 586 | Modal.confirm({title:'فعالسازی ثبت مالی یکپارچه',danger:true, |
| 587 | message:'این کار گردش جدید فروش، خرید، خزانه و انبار را به حسابداری دوبل متصل میکند. شرکت دارای گردش قبلی بدون مهاجرت تأییدشده فعال نمیشود. ابتدا نسخه پشتیبان بگیرید.', |
| 588 | confirmText:'فعالسازی برای شرکت خالی', |
| 589 | onConfirm:async()=>{ |
| 590 | try{await Retail.activate();Toast.success('ثبت یکپارچه فعال شد');await this.refresh()} |
| 591 | catch(e){Toast.error(e.message)} |
| 592 | }}); |
| 593 | } |
| 594 | openWarehouse() { |
| 595 | Modal.open({title:'ایجاد انبار',size:'sm',closeOnBackdrop:false, |
| 596 | body:'<label class="form-label">نام انبار</label><input id="acWhName" class="form-control">', |
| 597 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveWarehouse()">ثبت انبار</button>'}); |
| 598 | } |
| 599 | async saveWarehouse() { |
| 600 | if(this.busy)return;this.busy=true; |
| 601 | try{await Retail.addWarehouse(document.getElementById('acWhName').value); |
| 602 | Modal.close();Toast.success('انبار ایجاد شد');await this.refresh()} |
| 603 | catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 604 | } |
| 605 | async openTransfer() { |
| 606 | try { |
| 607 | const [warehouses,products]=await Promise.all([Retail.warehouses(),DataScope.list('products')]); |
| 608 | if(warehouses.length<2){Toast.warning('برای انتقال کالا حداقل دو انبار لازم است');return} |
| 609 | const opts=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join(''); |
| 610 | const prod=products.filter(p=>p.trackInventory!==false) |
| 611 | .map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 612 | Modal.open({title:'انتقال کالا بین انبارها',size:'sm',closeOnBackdrop:false, |
| 613 | body:`<div class="form-group"><label class="form-label">کالا</label><select class="form-control" id="acTrProduct">${prod}</select></div> |
| 614 | <div class="form-group"><label class="form-label">انبار مبدا</label><select class="form-control" id="acTrFrom">${opts}</select></div> |
| 615 | <div class="form-group"><label class="form-label">انبار مقصد</label><select class="form-control" id="acTrTo">${opts}</select></div> |
| 616 | <div class="form-group"><label class="form-label">مقدار</label><input id="acTrQty" class="form-control" value="1"></div> |
| 617 | <div class="form-group"><label class="form-label">تاریخ</label><input id="acTrDate" class="form-control" value="${safeDate()}"></div>`, |
| 618 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveTransfer()">ثبت انتقال</button>'}); |
| 619 | }catch(e){Toast.error(e.message)} |
| 620 | } |
| 621 | async saveTransfer() { |
| 622 | if(this.busy)return;this.busy=true; |
| 623 | try { |
| 624 | await Retail.transferStock({ |
| 625 | productId:document.getElementById('acTrProduct').value, |
| 626 | fromWarehouseId:document.getElementById('acTrFrom').value, |
| 627 | toWarehouseId:document.getElementById('acTrTo').value, |
| 628 | quantity:Number(digits(document.getElementById('acTrQty').value)), |
| 629 | date:digits(document.getElementById('acTrDate').value)}); |
| 630 | Modal.close();Toast.success('انتقال انبار ثبت شد');await this.refresh(); |
| 631 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 632 | } |
| 633 | async openStocktakeCreate() { |
| 634 | try { |
| 635 | const warehouses=await Retail.warehouses(); |
| 636 | const options=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join(''); |
| 637 | Modal.open({title:'شروع شمارش انبار',size:'sm',closeOnBackdrop:false, |
| 638 | body:`<label class="form-label">انبار</label><select class="form-control" id="acStWarehouse">${options}</select> |
| 639 | <label class="form-label">تاریخ شمسی</label><input class="form-control" id="acStDate" value="${safeDate()}"> |
| 640 | <p style="margin-top:12px">موجودی مبنا ثابت ثبت میشود؛ برای تأیید، شمارش همه اقلام ضروری است.</p>`, |
| 641 | footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.createStocktake()">ایجاد جلسه</button>'}); |
| 642 | }catch(e){Toast.error(e.message)} |
| 643 | } |
| 644 | async createStocktake() { |
| 645 | if(this.busy)return;this.busy=true; |
| 646 | try { |
| 647 | const take=await Retail.newStocktake({warehouseId:document.getElementById('acStWarehouse').value, |
| 648 | date:digits(document.getElementById('acStDate').value)}); |
| 649 | Modal.close();Toast.success('جلسه شمارش ایجاد شد');await this.refresh();await this.openStocktake(take.id); |
| 650 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 651 | } |
| 652 | async openStocktake(id) { |
| 653 | try { |
| 654 | const sessions=await Retail.getStocktakes(),take=sessions.find(s=>s.id===id); |
| 655 | if(!take)throw Error('جلسه شمارش یافت نشد'); |
| 656 | const lines=await Retail.getStocktakeLines(id),products=await DataScope.list('products'); |
| 657 | const names=Object.fromEntries(products.map(p=>[p.id,p.name])); |
| 658 | const extras=products.filter(p=>p.trackInventory!==false&&!lines.some(l=>l.productId===p.id)); |
| 659 | const extraOptions=extras.map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 660 | const existing=lines.map(l=>`<tr data-product="${html(l.productId)}"> |
| 661 | <td>${html(names[l.productId]||l.productId)}</td><td>${l.expectedUnits/1000}</td> |
| 662 | <td><input class="form-control ac-count" value="${l.countedUnits===null?'':l.countedUnits/1000}" ${take.status!=='draft'?'disabled':''}></td> |
| 663 | <td><input class="form-control ac-cost" placeholder="ریال" value="${l.unitCost??''}" ${take.status!=='draft'?'disabled':''}></td></tr>`).join(''); |
| 664 | Modal.open({title:'برگه انبارگردانی',size:'lg',closeOnBackdrop:false, |
| 665 | body:`<input type="hidden" id="acStocktakeId" value="${html(id)}"> |
| 666 | <p style="margin-bottom:10px">مقدار شمارش واقعی و در صورت مازاد کالای بدون مانده، قیمت تمامشده واحد را وارد کنید.</p> |
| 667 | <div class="table-wrap"><table><thead><tr><th>کالا</th><th>مبنای سیستم</th><th>شمارش واقعی</th><th>بهای واحد مازاد</th></tr></thead> |
| 668 | <tbody id="acTakeRows">${existing}</tbody></table></div> |
| 669 | ${take.status==='draft'&&extras.length?`<div style="display:flex;gap:8px;margin-top:12px;align-items:center"> |
| 670 | <select class="form-control" id="acTakeNewProduct">${extraOptions}</select> |
| 671 | <button class="btn btn-secondary" onclick="window.AccountingView.addStocktakeProduct()">افزودن کالای جدید به شمارش</button> |
| 672 | </div>`:''}`, |
| 673 | 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>': |
| 674 | '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'}); |
| 675 | }catch(e){Toast.error(e.message)} |
| 676 | } |
| 677 | addStocktakeProduct() { |
| 678 | const selector=document.getElementById('acTakeNewProduct'); |
| 679 | if(!selector?.value)return; |
| 680 | const id=selector.value; |
| 681 | const label=selector.selectedOptions[0]?.textContent||id; |
| 682 | const body=document.getElementById('acTakeRows'); |
| 683 | if(!body||body.querySelector('[data-product="'+id+'"]'))return; |
| 684 | body.insertAdjacentHTML('beforeend',`<tr data-product="${html(id)}"> |
| 685 | <td>${html(label)}</td><td>۰</td> |
| 686 | <td><input class="form-control ac-count" value="0"></td> |
| 687 | <td><input class="form-control ac-cost" placeholder="ریال"></td></tr>`); |
| 688 | selector.selectedOptions[0]?.remove(); |
| 689 | } |
| 690 | async persistStocktakeCounts(id) { |
| 691 | for(const row of document.querySelectorAll('#acTakeRows tr[data-product]')){ |
| 692 | const count=digits(row.querySelector('.ac-count').value).trim(); |
| 693 | const cost=digits(row.querySelector('.ac-cost').value).trim(); |
| 694 | if(!count)throw Error('برای همه اقلام مقدار شمارش را وارد کنید'); |
| 695 | await Retail.countStocktake(id,row.dataset.product,Number(count),cost?Number(cost):null); |
| 696 | } |
| 697 | } |
| 698 | async saveStocktake() { |
| 699 | if(this.busy)return;this.busy=true; |
| 700 | try { |
| 701 | const id=document.getElementById('acStocktakeId').value; |
| 702 | await this.persistStocktakeCounts(id); |
| 703 | Modal.close();Toast.success('شمارش ثبت شد');await this.refresh(); |
| 704 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 705 | } |
| 706 | async finishStocktake() { |
| 707 | if(this.busy)return;this.busy=true; |
| 708 | try { |
| 709 | const id=document.getElementById('acStocktakeId').value; |
| 710 | await this.persistStocktakeCounts(id); |
| 711 | await Retail.finalizeStocktake(id); |
| 712 | Modal.close();Toast.success('انبارگردانی تأیید و سند تعدیل ثبت شد');await this.refresh(); |
| 713 | }catch(e){Toast.error(e.message)}finally{this.busy=false} |
| 714 | } |
| 715 | openReversal(id) { |
| 716 | const periods = this.periods.filter(p => !p.closed); |
| 717 | if (!periods.length) { Toast.error('دوره باز برای ثبت سند برگشت وجود ندارد'); return; } |
| 718 | const opts = periods.map(p => `<option value="${html(p.id)}">${html(p.name)}</option>`).join(''); |
| 719 | Modal.open({ title: 'ثبت سند معکوس', size: 'sm', closeOnBackdrop: false, |
| 720 | body: `<input type="hidden" id="acReversalId" value="${html(id)}"> |
| 721 | <p style="font-size:12px;margin-bottom:10px">این عملیات سندی جداگانه با بدهکار/بستانکار معکوس میسازد و سند اصلی حذف نمیشود.</p> |
| 722 | <div class="form-group"><label class="form-label">دوره باز</label> |
| 723 | <select class="form-control" id="acReversalPeriod">${opts}</select></div> |
| 724 | <div class="form-group"><label class="form-label">تاریخ برگشت</label> |
| 725 | <input class="form-control" id="acReversalDate" value="${html(safeDate())}"></div>`, |
| 726 | footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveReversal()">ثبت سند برگشت</button>' |
| 727 | }); |
| 728 | } |
| 729 | async saveReversal() { |
| 730 | if (this.busy) return; |
| 731 | this.busy = true; |
| 732 | try { |
| 733 | await Ledger.reverseJournal(document.getElementById('acReversalId').value, { |
| 734 | periodId: document.getElementById('acReversalPeriod').value, |
| 735 | date: digits(document.getElementById('acReversalDate').value).trim() |
| 736 | }); |
| 737 | Modal.close(); |
| 738 | Toast.success('سند برگشت مستقل ثبت شد'); |
| 739 | await this.refresh(); |
| 740 | } catch (error) { Toast.error(error.message); } |
| 741 | finally { this.busy = false; } |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | export const AccountingView = new AccountingViewImpl(); |