فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix/a03-append-only-write-guard
a02/strict-export-preflight-20261018
audit/a01-readonly-invoice-metadata-20261101
ci/a06-require-trusted-issuer-for-release
ci/main-postmerge-phase-a-validation-20261020
ci/phase-a-controlled-public-release
design/issue-5-commercial-corrections-adr
docs/a01-a02-a05-oct23-verified-evidence
docs/a01-cheque-endorsement-evidence-20261022
docs/a01-cheque-event-date-evidence-20261021
docs/a01-explicit-refund-reason-evidence-20261021
docs/a01-refund-auth-status-20261020
docs/a01-refund-trace-evidence-20261020
docs/a02-102-evidence-20261018
docs/a02-pr104-evidence-20261018
docs/a02-pr106-evidence-20261019
docs/a02-pr108-ten-tests-20261019
docs/a02-private-sql-backup-evidence-20261111
docs/a03-merge-status-sync-20261020
docs/a04-software-gate-acceptance-20261020
docs/feature-matrix-20261014
docs/finora-master-execution-playbook
docs/four-phase-execution-20261014
docs/four-phase-roadmap-20261014
docs/holoo-lab-stabilization-phase1-20261111
docs/holoo-runtime-schema-audit-20261111
docs/ops-142-governance-5-1-3-20261030
docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023
docs/phase-a-a01-a05-a06-evidence-20261023
docs/phase-a-independent-acceptance-evidence
docs/phase-a-pr110-evidence-20261019
docs/project-status-phase-a-20261014
feat/a01-referenced-return-corrections
feat/a01-referenced-returns-on-main
feat/a02-atomic-opening-ledger-preflight
feat/a02-holoo-compatibility-preflight
feat/a02-holoo-declared-control-totals
feat/a02-holoo-explicit-csv-gate
feat/a02-holoo-safe-zip-intake-offline-webview2-20261030
feat/a02-offline-sql-server-provisioning-20261030
feat/a02-opening-balance-dry-run
feat/a02-opening-ledger-admin-ui
feat/a02-opt-in-isolated-sql-restore-executor-20261030
feat/a02-private-holoo-zip-staging-20261030
feat/a02-safe-isolated-restore-plan-20261030
feat/a02-sql-backup-header-verifyonly-20261030
feat/a03-audit-schema-atomic-events
feat/a03-complete-manual-journal-audit
feat/a05-cheque-treasury-reconciliation
feat/a06-signed-offline-license-activation
feat/a08-synthetic-performance-baseline
feat/phase-a-accounting-benchmark-return-preview
feat/phase-a-ledger-settlement-diagnostics
feature/v2-reconciliation-20261013
fix/a01-atomic-confirm-ui-one-shot-20261031
fix/a01-cheque-clearance-explicit-account-20261023
fix/a01-cheque-contractual-due-date-validity-20261023
fix/a01-cheque-endorsement-counterparty-20261022
fix/a01-cheque-event-date-open-period-20261021
fix/a01-cumulative-return-amount-cap
fix/a01-explicit-refund-reason-approval-20261021
fix/a01-manager-authorized-customer-refunds-20261020
fix/a01-no-implicit-refund
fix/a01-one-shot-confirm-on-atomic-import-20261031
fix/a01-refund-and-overcollection-net-cash
fix/a01-refund-correction-trace-20261020
fix/a02-atomic-excel-master-merge-20261031
fix/a02-canonical-mapping-contract-20261018
fix/a02-disable-destructive-excel-replace-20261031
fix/a02-holoo-invoice-line-coverage-20261023
fix/a02-holoo-preflight-required-invoice-lines-20261023
fix/a02-mapping-contract-20261018
fix/a02-opening-preflight-unbalanced-report
fix/a02-orphan-mapping-20261018
fix/a02-private-excel-import-session-20261031
fix/a02-strict-export-input-20261019
fix/a03-append-only-full-backup-import
fix/a03-append-only-write-guard
fix/a03-block-transaction-clear-append-only-20261016
fix/a03-chain-validation-20261020
fix/a03-company-scoped-audit-data-access
fix/a03-deny-direct-audit-write-20261019
fix/a03-escaped-expense-list-20261031
fix/a03-escaped-financial-record-ids-20261031
fix/a03-financial-ledger-actions-and-print-20261031
fix/a04-backup-checksum-preflight
fix/a04-company-audit-replay-stable-compare
fix/a04-company-backup-source-isolation-20261020
fix/a04-full-restore-posted-financial-integrity
fix/a04-reject-mixed-company-backup-20261019
fix/a04-replace-immutable-posted-ledger
fix/a04-restore-financial-journal-references
fix/a04-service-source-company-boundary-20261020
fix/a05-block-inactive-treasury-settlements
fix/a05-cheque-cash-evidence-reconciliation-20261023
fix/a05-cheque-ledger-and-bank-reconciliation-20261023
fix/a05-fiscal-close-invariant-gates
fix/a06-backup-restore-user-privileges
fix/a06-license-user-company-quota-20261023
fix/a06-malformed-trial-state-fail-closed
fix/a06-offline-clock-fail-closed-20261019
fix/a07-indexeddb-blocked-startup
fix/a07-offline-bundled-assets
fix/a07-version-and-startup-banner
fix/issue-7-company-backup-isolation
fix/p0-deterministic-fractional-invoice-money-20261031
fix/p0-fractional-quantity-input-20261031
fix/p0-fractional-quantity-integrated-20261031
fix/p0-invoice-posting-invariants-20261031
fix/p0-legacy-stock-and-product-inputs-20261031
fix/p0-reports-immutable-cogs-20261101
fix/p0-verified-financial-percent-20261031
fix/p0-zero-discount-report-revenue-20261101
fix/phase-a-backup-app-version
fix/phase-a-backup-integrity-checksum
fix/phase-a-backup-record-id-validation-20261014
fix/phase-a-backup-version-validation-20261014
fix/phase-a-closure-pack3-20261101
fix/phase-a-entitlement-payload-validation
fix/phase-a-gate-exact-evidence-20261019
fix/phase-a-pack4-stock-scope-20261101
fix/phase-a-pack5-integrated-evidence-20261101
fix/phase-a-pack6-atomic-legacy-20261101
fix/phase-a-restore-envelope-and-rollback
fix/phase-a-settings-admin-gate
fix/print-browser-header-footer-20261014
fix/q01-expense-security-probe-exact-option-20261031
fix/q01-financial-grid-labels-20261031
fix/q01-form-label-association-20261031
fix/q01-native-evidence-integrity-20261030
fix/q01-number-input-persian-decimal-20261031
fix/q01-responsive-dashboard-and-cheque-table-20261031
fix/q01-safe-ui-action-audit-coverage-20261031
fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030
fix/roadmap-metadata-sync-20261014
gate/a03-audit-metadata-validation-20261019
integration/a02-windows-holoo-setup-candidate-20261030
license-server
main
perf/a07-lazy-load-excel
perf/a08-cheque-reconciliation-account-index-20261023
perf/a08-paginated-reports-20261101
phase1-restore-hardening
planning/holoo-execution-20261013
planning/roadmap-project-management-20261014
qa/native-click-coverage-audit-20261030
release/v2.0.0
test/a01-native-endorsement-mandatory-20261023
test/a01-native-purchase-return-guardrails
test/a01-native-sale-return-financial-guardrails
test/a01-safe-integer-boundary-20261019
test/a02-native-opening-dry-run-rejections
test/a02-native-positive-opening-ledger
test/a04-native-corrupt-fbackup-20261016
test/a04-native-encrypted-company-backup
test/a04-native-encrypted-company-backup-main
test/a04-native-late-transaction-rollback
test/a04-native-windows-backup-recovery
test/a04-real-edge-v6-v7-migration
test/a04-real-native-interrupted-restore
test/a05-native-draft-ledger-and-repeat-close-20261016
test/a05-native-fiscal-close-guardrails
test/a07-native-multipage-print-engine
test/a07-native-origin-provenance
test/a07-native-webview2-offline-routes
test/a07-windows-offline-startup-smoke
test/a08-installed-webview2-60k-baseline
test/a08-native-webview2-heap-metrics
test/a08-windows-synthetic-performance-baseline
test/github-write-access-20261009
test/native-win-ui-routes-after-finance-backup
test/phase-a-combined-a01-a05-a08-final-evidence
test/phase-a-combined-native-acceptance-matrix
test/phase-a-ledger-invariants-20261014
test/phase-a-native-all-routes-on-merged-lab
test/phase-a-native-encrypted-backup
test/phase-a-native-finance-backup-matrix
test/phase-a-native-ui-and-backup-smoke
test/phase-a-windows-native-installer-lab
work/a08-dispatch-activation-20261123
work/a08-memory-stability-20261123
work/finance-curated-20261123
| 1 | // ============================================================ |
| 2 | // ExpensesView — صفحهی هزینهها و درآمدهای متفرقه |
| 3 | // ============================================================ |
| 4 | |
| 5 | import { ExpenseController } from '../controllers/ExpenseController.js'; |
| 6 | import { Modal } from '../core/Modal.js'; |
| 7 | import { Toast } from '../core/Toast.js'; |
| 8 | import { Formatters } from '../utils/Formatters.js'; |
| 9 | import { NumberInput } from '../utils/NumberInput.js'; |
| 10 | import { Jalali } from '../utils/Jalali.js'; |
| 11 | |
| 12 | let filter = { search: '', kind: '', category: '', dateFrom: '', dateTo: '' }; |
| 13 | let cache = { items: [], categories: [], stats: {} }; |
| 14 | |
| 15 | class ExpensesViewImpl { |
| 16 | async render() { |
| 17 | await this.reload(); |
| 18 | return ` |
| 19 | <div class="page-title"> |
| 20 | <h2>هزینهها و درآمدها</h2> |
| 21 | <p>ثبت و مدیریت هزینهها، درآمدهای متفرقه و تراز مالی</p> |
| 22 | </div> |
| 23 | |
| 24 | <div class="grid-kpi"> |
| 25 | <div class="card" style="margin:0"> |
| 26 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل درآمدها</div> |
| 27 | <div style="font-size:20px;font-weight:800;color:var(--success)">${Formatters.money(cache.stats.totalIncome || 0)}</div> |
| 28 | <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.items.filter(i => i.kind === 'income').length)} سند</div> |
| 29 | </div> |
| 30 | <div class="card" style="margin:0"> |
| 31 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل هزینهها</div> |
| 32 | <div style="font-size:20px;font-weight:800;color:var(--danger)">${Formatters.money(cache.stats.totalExpense || 0)}</div> |
| 33 | <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.items.filter(i => i.kind === 'expense').length)} سند</div> |
| 34 | </div> |
| 35 | <div class="card" style="margin:0"> |
| 36 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">تراز (درآمد - هزینه)</div> |
| 37 | <div style="font-size:20px;font-weight:800;color:${(cache.stats.balance || 0) >= 0 ? 'var(--primary)' : 'var(--danger)'}">${Formatters.money(cache.stats.balance || 0)}</div> |
| 38 | <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${(cache.stats.balance || 0) >= 0 ? 'مثبت' : 'منفی'}</div> |
| 39 | </div> |
| 40 | <div class="card" style="margin:0"> |
| 41 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">تعداد اسناد</div> |
| 42 | <div style="font-size:20px;font-weight:800;color:var(--info)">${Formatters.number(cache.stats.count || 0)}</div> |
| 43 | <div style="font-size:11px;color:var(--text-muted);margin-top:4px">در فیلتر فعلی</div> |
| 44 | </div> |
| 45 | </div> |
| 46 | |
| 47 | <div id="expenses-content">${this.renderContent()}</div> |
| 48 | `; |
| 49 | } |
| 50 | |
| 51 | onMount() { |
| 52 | window.ExpensesView = this; |
| 53 | } |
| 54 | |
| 55 | async reload() { |
| 56 | cache.items = await ExpenseController.getAll(filter); |
| 57 | cache.categories = await ExpenseController.getCategories(); |
| 58 | cache.stats = await ExpenseController.getStats(filter); |
| 59 | } |
| 60 | |
| 61 | renderContent() { |
| 62 | const rows = cache.items.length === 0 |
| 63 | ? `<tr><td colspan="7"><div class="empty-state"><div class="icon">💰</div><h3>هیچ سندی ثبت نشده</h3><p>اولین هزینه یا درآمد خود را ثبت کنید</p><button class="btn" onclick="window.ExpensesView.openExpenseModal()">➕ سند جدید</button></div></td></tr>` |
| 64 | : cache.items.map(e => { |
| 65 | const isIncome = e.kind === 'income'; |
| 66 | return ` |
| 67 | <tr> |
| 68 | <td> |
| 69 | <span class="badge ${isIncome ? 'badge-success' : 'badge-danger'}"> |
| 70 | ${isIncome ? '📥 درآمد' : '📤 هزینه'} |
| 71 | </span> |
| 72 | </td> |
| 73 | <td>${Formatters.toPersianDigits(e.date || '—')}</td> |
| 74 | <td><strong>${this._esc(e.category || '—')}</strong></td> |
| 75 | <td>${this._esc(e.description || '—')}</td> |
| 76 | <td>${ExpenseController.getMethodLabel(e.method)}</td> |
| 77 | <td>${e.refNumber ? Formatters.toPersianDigits(e.refNumber) : '—'}</td> |
| 78 | <td style="font-weight:700;color:${isIncome ? 'var(--success)' : 'var(--danger)'}"> |
| 79 | ${isIncome ? '+' : '-'}${Formatters.money(e.amount)} |
| 80 | </td> |
| 81 | <td> |
| 82 | <div class="row-actions"> |
| 83 | <button class="icon-btn-sm" title="ویرایش" onclick="window.ExpensesView.editExpense('${e.id}')">✏️</button> |
| 84 | <button class="icon-btn-sm danger" title="حذف" onclick="window.ExpensesView.deleteExpense('${e.id}')">🗑️</button> |
| 85 | </div> |
| 86 | </td> |
| 87 | </tr> |
| 88 | `; |
| 89 | }).join(''); |
| 90 | |
| 91 | const categoryOptions = cache.categories.map(c => |
| 92 | `<option value="${c}" ${filter.category === c ? 'selected' : ''}>${this._esc(c)}</option>` |
| 93 | ).join(''); |
| 94 | |
| 95 | return ` |
| 96 | <div class="toolbar"> |
| 97 | <div class="search-input-wrap"> |
| 98 | <span class="icon">🔍</span> |
| 99 | <input type="text" class="form-control" id="expSearch" placeholder="جستجو در سرفصل، شرح یا شماره پیگیری..." value="${this._esc(filter.search)}" oninput="window.ExpensesView._onSearch(this.value)" /> |
| 100 | </div> |
| 101 | <select class="form-control" style="width:auto;min-width:130px" onchange="window.ExpensesView._onFilter('kind', this.value)"> |
| 102 | <option value="">همه انواع</option> |
| 103 | <option value="expense" ${filter.kind === 'expense' ? 'selected' : ''}>هزینه</option> |
| 104 | <option value="income" ${filter.kind === 'income' ? 'selected' : ''}>درآمد</option> |
| 105 | </select> |
| 106 | <select class="form-control" style="width:auto;min-width:150px" onchange="window.ExpensesView._onFilter('category', this.value)"> |
| 107 | <option value="">همه سرفصلها</option> |
| 108 | ${categoryOptions} |
| 109 | </select> |
| 110 | <input type="text" class="form-control" style="width:130px" placeholder="از تاریخ" value="${this._esc(filter.dateFrom)}" onchange="window.ExpensesView._onFilter('dateFrom', this.value)" /> |
| 111 | <input type="text" class="form-control" style="width:130px" placeholder="تا تاریخ" value="${this._esc(filter.dateTo)}" onchange="window.ExpensesView._onFilter('dateTo', this.value)" /> |
| 112 | <button class="btn btn-secondary btn-inline" onclick="window.ExpensesView._clearFilters()">↺ پاک کردن فیلتر</button> |
| 113 | <button class="btn" onclick="window.ExpensesView.openExpenseModal()">➕ سند جدید</button> |
| 114 | </div> |
| 115 | |
| 116 | <div class="table-wrap"> |
| 117 | <table> |
| 118 | <thead> |
| 119 | <tr> |
| 120 | <th style="width:110px">نوع</th> |
| 121 | <th style="width:110px">تاریخ</th> |
| 122 | <th style="width:150px">سرفصل</th> |
| 123 | <th>شرح</th> |
| 124 | <th style="width:110px">روش</th> |
| 125 | <th style="width:120px">شماره پیگیری</th> |
| 126 | <th style="width:140px">مبلغ</th> |
| 127 | <th style="width:100px">عملیات</th> |
| 128 | </tr> |
| 129 | </thead> |
| 130 | <tbody>${rows}</tbody> |
| 131 | </table> |
| 132 | </div> |
| 133 | `; |
| 134 | } |
| 135 | |
| 136 | _onSearch(val) { |
| 137 | filter.search = val; |
| 138 | this.reload().then(() => { |
| 139 | document.getElementById('expenses-content').innerHTML = this.renderContent(); |
| 140 | const input = document.getElementById('expSearch'); |
| 141 | if (input) { input.focus(); input.setSelectionRange(val.length, val.length); } |
| 142 | }); |
| 143 | } |
| 144 | |
| 145 | _onFilter(key, val) { |
| 146 | filter[key] = val; |
| 147 | this.reloadAndRender(); |
| 148 | } |
| 149 | |
| 150 | _clearFilters() { |
| 151 | filter = { search: '', kind: '', category: '', dateFrom: '', dateTo: '' }; |
| 152 | this.reloadAndRender(); |
| 153 | Toast.info('فیلترها پاک شد'); |
| 154 | } |
| 155 | |
| 156 | async reloadAndRender() { |
| 157 | await this.reload(); |
| 158 | document.getElementById('expenses-content').innerHTML = this.renderContent(); |
| 159 | // KPI ها را هم رفرش کن |
| 160 | const kpi = document.querySelector('.grid-kpi'); |
| 161 | if (kpi) { |
| 162 | const stats = cache.stats; |
| 163 | kpi.children[0].querySelector('div:nth-child(2)').textContent = Formatters.money(stats.totalIncome || 0); |
| 164 | kpi.children[0].querySelector('div:nth-child(3)').textContent = Formatters.toPersianDigits(cache.items.filter(i => i.kind === 'income').length) + ' سند'; |
| 165 | kpi.children[1].querySelector('div:nth-child(2)').textContent = Formatters.money(stats.totalExpense || 0); |
| 166 | kpi.children[1].querySelector('div:nth-child(3)').textContent = Formatters.toPersianDigits(cache.items.filter(i => i.kind === 'expense').length) + ' سند'; |
| 167 | const bal = stats.balance || 0; |
| 168 | const balEl = kpi.children[2].querySelector('div:nth-child(2)'); |
| 169 | balEl.textContent = Formatters.money(bal); |
| 170 | balEl.style.color = bal >= 0 ? 'var(--primary)' : 'var(--danger)'; |
| 171 | kpi.children[2].querySelector('div:nth-child(3)').textContent = bal >= 0 ? 'مثبت' : 'منفی'; |
| 172 | kpi.children[3].querySelector('div:nth-child(2)').textContent = Formatters.toPersianDigits(stats.count || 0); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // ============================================================ |
| 177 | // فرم ثبت/ویرایش |
| 178 | // ============================================================ |
| 179 | async openExpenseModal(expenseId = null) { |
| 180 | const isEdit = !!expenseId; |
| 181 | const d = isEdit ? await ExpenseController.get(expenseId) : { |
| 182 | kind: 'expense', |
| 183 | category: '', |
| 184 | amount: 0, |
| 185 | date: Jalali.today(), |
| 186 | method: 'cash', |
| 187 | description: '', |
| 188 | refNumber: '' |
| 189 | }; |
| 190 | |
| 191 | const categoriesForKind = await ExpenseController.getCategories(d.kind); |
| 192 | |
| 193 | const body = ` |
| 194 | <div class="form-group"> |
| 195 | <label class="form-label">نوع سند <span class="req">*</span></label> |
| 196 | <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px"> |
| 197 | <label class="print-tpl-card ${d.kind === 'expense' ? 'active' : ''}" data-kind="expense" style="padding:12px 8px"> |
| 198 | <input type="radio" name="expKind" value="expense" ${d.kind === 'expense' ? 'checked' : ''} style="display:none" /> |
| 199 | <div style="font-size:22px">📤</div> |
| 200 | <div style="font-weight:700;font-size:13px;margin-top:4px">هزینه</div> |
| 201 | </label> |
| 202 | <label class="print-tpl-card ${d.kind === 'income' ? 'active' : ''}" data-kind="income" style="padding:12px 8px"> |
| 203 | <input type="radio" name="expKind" value="income" ${d.kind === 'income' ? 'checked' : ''} style="display:none" /> |
| 204 | <div style="font-size:22px">📥</div> |
| 205 | <div style="font-weight:700;font-size:13px;margin-top:4px">درآمد</div> |
| 206 | </label> |
| 207 | </div> |
| 208 | </div> |
| 209 | |
| 210 | <div class="form-row"> |
| 211 | <div class="form-group"> |
| 212 | <label class="form-label">سرفصل <span class="req">*</span></label> |
| 213 | <div style="display:flex;gap:6px"> |
| 214 | <select class="form-control" id="expCategory" style="flex:1"> |
| 215 | ${categoriesForKind.map(c => `<option value="${this._esc(c)}" ${d.category === c ? 'selected' : ''}>${this._esc(c)}</option>`).join('')} |
| 216 | </select> |
| 217 | <button class="btn btn-secondary btn-inline" style="padding:0 12px" onclick="window.ExpensesView._promptNewCategory()" title="سرفصل جدید">➕</button> |
| 218 | </div> |
| 219 | </div> |
| 220 | <div class="form-group"> |
| 221 | <label class="form-label">تاریخ <span class="req">*</span></label> |
| 222 | <input type="text" class="form-control" id="expDate" value="${this._esc(d.date)}" placeholder="1405/06/27" /> |
| 223 | </div> |
| 224 | </div> |
| 225 | |
| 226 | <div class="form-row"> |
| 227 | <div class="form-group"> |
| 228 | <label class="form-label">مبلغ (ریال) <span class="req">*</span></label> |
| 229 | <input type="text" inputmode="numeric" class="form-control" id="expAmount" value="${NumberInput.format(d.amount || 0)}" /> |
| 230 | </div> |
| 231 | <div class="form-group"> |
| 232 | <label class="form-label">روش پرداخت / دریافت</label> |
| 233 | <select class="form-control" id="expMethod"> |
| 234 | <option value="cash" ${d.method === 'cash' ? 'selected' : ''}>نقدی</option> |
| 235 | <option value="card" ${d.method === 'card' ? 'selected' : ''}>کارت</option> |
| 236 | <option value="cheque" ${d.method === 'cheque' ? 'selected' : ''}>چک</option> |
| 237 | <option value="transfer" ${d.method === 'transfer' ? 'selected' : ''}>انتقال بانکی</option> |
| 238 | </select> |
| 239 | </div> |
| 240 | </div> |
| 241 | |
| 242 | <div class="form-group"> |
| 243 | <label class="form-label">شماره پیگیری / سند (اختیاری)</label> |
| 244 | <input type="text" class="form-control" id="expRef" value="${this._esc(d.refNumber)}" placeholder="مثلاً 12345" /> |
| 245 | </div> |
| 246 | |
| 247 | <div class="form-group"> |
| 248 | <label class="form-label">شرح</label> |
| 249 | <textarea class="form-control" id="expDesc" rows="2" placeholder="توضیحات اضافی...">${this._esc(d.description)}</textarea> |
| 250 | </div> |
| 251 | `; |
| 252 | |
| 253 | const footer = ` |
| 254 | <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 255 | <button class="btn" onclick="window.ExpensesView.saveExpense(${isEdit ? `'${expenseId}'` : 'null'})">💾 ذخیره</button> |
| 256 | `; |
| 257 | |
| 258 | Modal.open({ title: isEdit ? 'ویرایش سند' : 'سند جدید', body, footer, size: 'md' }); |
| 259 | |
| 260 | setTimeout(() => { |
| 261 | // انتخاب نوع |
| 262 | document.querySelectorAll('[data-kind]').forEach(card => { |
| 263 | card.addEventListener('click', async () => { |
| 264 | document.querySelectorAll('[data-kind]').forEach(c => c.classList.remove('active')); |
| 265 | card.classList.add('active'); |
| 266 | card.querySelector('input').checked = true; |
| 267 | |
| 268 | // آپدیت dropdown سرفصلها |
| 269 | const kind = card.getAttribute('data-kind'); |
| 270 | const cats = await ExpenseController.getCategories(kind); |
| 271 | const select = document.getElementById('expCategory'); |
| 272 | if (select) { |
| 273 | select.innerHTML = cats.map(c => `<option value="${this._esc(c)}">${this._esc(c)}</option>`).join(''); |
| 274 | } |
| 275 | }); |
| 276 | }); |
| 277 | }, 50); |
| 278 | } |
| 279 | |
| 280 | async _promptNewCategory() { |
| 281 | const catName = prompt('نام سرفصل جدید:'); |
| 282 | if (!catName || !catName.trim()) return; |
| 283 | const select = document.getElementById('expCategory'); |
| 284 | if (select) { |
| 285 | const trimmed = catName.trim(); |
| 286 | const exists = Array.from(select.options).some(o => o.value === trimmed); |
| 287 | if (exists) { |
| 288 | select.value = trimmed; |
| 289 | Toast.info('این سرفصل از قبل وجود داشت'); |
| 290 | return; |
| 291 | } |
| 292 | const opt = document.createElement('option'); |
| 293 | opt.value = trimmed; |
| 294 | opt.textContent = trimmed; |
| 295 | select.appendChild(opt); |
| 296 | select.value = trimmed; |
| 297 | Toast.success('سرفصل اضافه شد'); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | async saveExpense(id) { |
| 302 | const kind = document.querySelector('input[name="expKind"]:checked')?.value || 'expense'; |
| 303 | const category = document.getElementById('expCategory').value; |
| 304 | const date = document.getElementById('expDate').value.trim(); |
| 305 | const amount = NumberInput.parse(document.getElementById('expAmount').value); |
| 306 | const method = document.getElementById('expMethod').value; |
| 307 | const refNumber = document.getElementById('expRef').value; |
| 308 | const description = document.getElementById('expDesc').value; |
| 309 | |
| 310 | if (!category) { Toast.warning('سرفصل را انتخاب کنید'); return; } |
| 311 | if (!date) { Toast.warning('تاریخ الزامی است'); return; } |
| 312 | if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; } |
| 313 | |
| 314 | const data = { kind, category, date, amount, method, refNumber, description }; |
| 315 | |
| 316 | try { |
| 317 | if (id) { |
| 318 | await ExpenseController.update(id, data); |
| 319 | Toast.success('سند ویرایش شد'); |
| 320 | } else { |
| 321 | await ExpenseController.create(data); |
| 322 | Toast.success(kind === 'income' ? 'درآمد ثبت شد' : 'هزینه ثبت شد'); |
| 323 | } |
| 324 | Modal.close(); |
| 325 | await this.reloadAndRender(); |
| 326 | } catch (err) { |
| 327 | console.error(err); |
| 328 | Toast.error('خطا: ' + err.message); |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | async editExpense(id) { |
| 333 | await this.openExpenseModal(id); |
| 334 | } |
| 335 | |
| 336 | async deleteExpense(id) { |
| 337 | const e = cache.items.find(x => x.id === id); |
| 338 | Modal.confirm({ |
| 339 | title: 'حذف سند', |
| 340 | message: `آیا از حذف «${this._esc(e?.category || '')} - ${Formatters.money(e?.amount || 0)}» مطمئن هستید؟`, |
| 341 | confirmText: 'حذف', |
| 342 | danger: true, |
| 343 | onConfirm: async () => { |
| 344 | try { |
| 345 | await ExpenseController.delete(id); |
| 346 | Toast.success('سند حذف شد'); |
| 347 | await this.reloadAndRender(); |
| 348 | } catch (err) { |
| 349 | Toast.error('خطا: ' + err.message); |
| 350 | } |
| 351 | } |
| 352 | }); |
| 353 | } |
| 354 | |
| 355 | _esc(s) { |
| 356 | if (!s) return ''; |
| 357 | return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | export const ExpensesView = new ExpensesViewImpl(); |
| 362 | window.ExpensesView = ExpensesView; |