فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix/a04-backup-checksum-preflight
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 | // DashboardView — داشبورد کامل با KPI، نمودارها و آمار |
| 3 | // ============================================================ |
| 4 | |
| 5 | import { StorageService } from '../core/StorageService.js'; |
| 6 | import { Auth } from '../core/Auth.js'; |
| 7 | import { Chart } from '../utils/Chart.js'; |
| 8 | import { Formatters } from '../utils/Formatters.js'; |
| 9 | import { Jalali } from '../utils/Jalali.js'; |
| 10 | |
| 11 | let cache = { |
| 12 | invoices: [], |
| 13 | expenses: [], |
| 14 | cheques: [], |
| 15 | treasury: [], |
| 16 | contacts: [], |
| 17 | products: [], |
| 18 | salesPeriod: 'monthly' // daily | monthly | yearly |
| 19 | }; |
| 20 | |
| 21 | class DashboardViewImpl { |
| 22 | async render() { |
| 23 | await this.reload(); |
| 24 | return ` |
| 25 | <div class="page-title" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px"> |
| 26 | <div> |
| 27 | <h2>داشبورد مدیریتی</h2> |
| 28 | <p>${Jalali.formatLong()}</p> |
| 29 | </div> |
| 30 | <button class="btn btn-inline" onclick="FINORA.Router.go('invoices')">➕ فاکتور جدید</button> |
| 31 | </div> |
| 32 | |
| 33 | ${this._renderKPIs()} |
| 34 | |
| 35 | <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:16px" class="dash-grid-main"> |
| 36 | ${this._renderSalesChart()} |
| 37 | ${this._renderAccountsCard()} |
| 38 | </div> |
| 39 | |
| 40 | ${this._renderIncomeExpenseChart()} |
| 41 | |
| 42 | ${this._renderRecentInvoices()} |
| 43 | |
| 44 | ${this._renderUpcomingCheques()} |
| 45 | `; |
| 46 | } |
| 47 | |
| 48 | onMount() { |
| 49 | window.DashboardView = this; |
| 50 | } |
| 51 | |
| 52 | async reload() { |
| 53 | const user = Auth.current(); |
| 54 | if (!user) return; |
| 55 | const [inv, exp, chq, trs, con, pro] = await Promise.all([ |
| 56 | StorageService.getByOwner('invoices', user.id), |
| 57 | StorageService.getByOwner('expenses', user.id), |
| 58 | StorageService.getByOwner('cheques', user.id), |
| 59 | StorageService.getByOwner('treasury', user.id), |
| 60 | StorageService.getByOwner('contacts', user.id), |
| 61 | StorageService.getByOwner('products', user.id) |
| 62 | ]); |
| 63 | cache.invoices = inv || []; |
| 64 | cache.expenses = exp || []; |
| 65 | cache.cheques = chq || []; |
| 66 | cache.treasury = trs || []; |
| 67 | cache.contacts = con || []; |
| 68 | cache.products = pro || []; |
| 69 | } |
| 70 | |
| 71 | // ============================================================ |
| 72 | // KPI ها |
| 73 | // ============================================================ |
| 74 | _renderKPIs() { |
| 75 | const today = new Date(); |
| 76 | const currentJalali = Jalali.now(); |
| 77 | |
| 78 | const salesInvoices = cache.invoices.filter(i => i.kind === 'sale' && !i.isPreInvoice); |
| 79 | |
| 80 | // فروش ماه جاری |
| 81 | const monthInvoices = salesInvoices.filter(i => { |
| 82 | const d = this._parseJalali(i.date); |
| 83 | return d && d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth(); |
| 84 | }); |
| 85 | const monthSales = monthInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0); |
| 86 | |
| 87 | // فروش کل |
| 88 | const totalSales = salesInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0); |
| 89 | |
| 90 | // مطالبات معوق |
| 91 | const unpaidInvoices = salesInvoices.filter(i => (Number(i.remaining) || 0) > 0); |
| 92 | const totalUnpaid = unpaidInvoices.reduce((s, i) => s + (Number(i.remaining) || 0), 0); |
| 93 | |
| 94 | // درآمد و هزینه ماه |
| 95 | const monthExpenses = cache.expenses.filter(e => { |
| 96 | const d = this._parseJalali(e.date); |
| 97 | return d && d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth(); |
| 98 | }); |
| 99 | const monthIncomeTotal = monthExpenses.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0); |
| 100 | const monthExpenseTotal = monthExpenses.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0); |
| 101 | |
| 102 | // چکهای سررسید ۷ روز آینده |
| 103 | const upcomingCheques = cache.cheques.filter(c => { |
| 104 | if (c.status !== 'pending') return false; |
| 105 | const due = this._parseJalali(c.dueDate); |
| 106 | if (!due) return false; |
| 107 | const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24)); |
| 108 | return diff >= 0 && diff <= 7; |
| 109 | }); |
| 110 | const upcomingChequesAmount = upcomingCheques.reduce((s, c) => s + (Number(c.amount) || 0), 0); |
| 111 | |
| 112 | // موجودی کل خزانه |
| 113 | const accounts = cache.treasury.filter(t => t.recordType === 'account'); |
| 114 | const transactions = cache.treasury.filter(t => t.recordType === 'transaction'); |
| 115 | let totalBalance = 0; |
| 116 | accounts.forEach(a => totalBalance += Number(a.initialBalance) || 0); |
| 117 | transactions.forEach(t => { |
| 118 | const amt = Number(t.amount) || 0; |
| 119 | if (t.type === 'receipt' && t.toAccountId) totalBalance += amt; |
| 120 | else if (t.type === 'payment' && t.fromAccountId) totalBalance -= amt; |
| 121 | else if (t.type === 'transfer') { |
| 122 | if (t.fromAccountId) totalBalance -= amt; |
| 123 | if (t.toAccountId) totalBalance += amt; |
| 124 | } |
| 125 | }); |
| 126 | |
| 127 | return ` |
| 128 | <div class="grid-kpi"> |
| 129 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)"> |
| 130 | <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">💰</div> |
| 131 | <div style="flex:1"> |
| 132 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش ماه جاری</div> |
| 133 | <div style="font-size:17px;font-weight:800;color:var(--primary)">${Formatters.money(monthSales)}</div> |
| 134 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(monthInvoices.length)} فاکتور</div> |
| 135 | </div> |
| 136 | </div> |
| 137 | |
| 138 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)"> |
| 139 | <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">📊</div> |
| 140 | <div style="flex:1"> |
| 141 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">فروش کل</div> |
| 142 | <div style="font-size:17px;font-weight:800;color:var(--success)">${Formatters.money(totalSales)}</div> |
| 143 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(salesInvoices.length)} فاکتور کل</div> |
| 144 | </div> |
| 145 | </div> |
| 146 | |
| 147 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)"> |
| 148 | <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">⏳</div> |
| 149 | <div style="flex:1"> |
| 150 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">مطالبات معوق</div> |
| 151 | <div style="font-size:17px;font-weight:800;color:var(--danger)">${Formatters.money(totalUnpaid)}</div> |
| 152 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(unpaidInvoices.length)} فاکتور</div> |
| 153 | </div> |
| 154 | </div> |
| 155 | |
| 156 | <div class="card kpi-card" style="margin:0;border-top:3px solid #8b5cf6"> |
| 157 | <div class="kpi-card-icon" style="background:#faf5ff;color:#8b5cf6">💵</div> |
| 158 | <div style="flex:1"> |
| 159 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">درآمد / هزینه ماه</div> |
| 160 | <div style="font-size:13px;font-weight:800"> |
| 161 | <span style="color:var(--success)">${Formatters.money(monthIncomeTotal)}</span> |
| 162 | </div> |
| 163 | <div style="font-size:13px;font-weight:800;margin-top:2px"> |
| 164 | <span style="color:var(--danger)">${Formatters.money(monthExpenseTotal)}</span> |
| 165 | </div> |
| 166 | </div> |
| 167 | </div> |
| 168 | |
| 169 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--warning)"> |
| 170 | <div class="kpi-card-icon" style="background:#fffbeb;color:var(--warning)">💳</div> |
| 171 | <div style="flex:1"> |
| 172 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">چکهای سررسید (۷ روز)</div> |
| 173 | <div style="font-size:17px;font-weight:800;color:var(--warning)">${Formatters.money(upcomingChequesAmount)}</div> |
| 174 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(upcomingCheques.length)} فقره</div> |
| 175 | </div> |
| 176 | </div> |
| 177 | |
| 178 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--info)"> |
| 179 | <div class="kpi-card-icon" style="background:#f0f9ff;color:var(--info)">🏦</div> |
| 180 | <div style="flex:1"> |
| 181 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی کل خزانه</div> |
| 182 | <div style="font-size:17px;font-weight:800;color:var(--info)">${Formatters.money(totalBalance)}</div> |
| 183 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(accounts.length)} حساب</div> |
| 184 | </div> |
| 185 | </div> |
| 186 | </div> |
| 187 | `; |
| 188 | } |
| 189 | |
| 190 | // ============================================================ |
| 191 | // نمودار فروش |
| 192 | // ============================================================ |
| 193 | _renderSalesChart() { |
| 194 | const data = this._getSalesChartData(); |
| 195 | const periods = [ |
| 196 | { key: 'daily', label: '۱۴ روز' }, |
| 197 | { key: 'monthly', label: '۱۲ ماه' }, |
| 198 | { key: 'yearly', label: '۵ سال' } |
| 199 | ]; |
| 200 | const tabsHtml = periods.map(p => |
| 201 | `<button class="chart-tab ${cache.salesPeriod === p.key ? 'active' : ''}" onclick="window.DashboardView._switchPeriod('${p.key}')">${p.label}</button>` |
| 202 | ).join(''); |
| 203 | |
| 204 | return ` |
| 205 | <div class="card" style="margin:0"> |
| 206 | <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px"> |
| 207 | <h3 style="font-size:15px;font-weight:700">📈 روند فروش</h3> |
| 208 | <div class="chart-tabs">${tabsHtml}</div> |
| 209 | </div> |
| 210 | ${Chart.line(data, { color: '#0d9488' })} |
| 211 | </div> |
| 212 | `; |
| 213 | } |
| 214 | |
| 215 | _getSalesChartData() { |
| 216 | const today = new Date(); |
| 217 | const salesInvoices = cache.invoices.filter(i => i.kind === 'sale' && !i.isPreInvoice); |
| 218 | |
| 219 | if (cache.salesPeriod === 'daily') { |
| 220 | // ۱۴ روز اخیر |
| 221 | const days = []; |
| 222 | for (let i = 13; i >= 0; i--) { |
| 223 | const d = new Date(today); |
| 224 | d.setDate(d.getDate() - i); |
| 225 | const jDate = Jalali.fromDate(d); |
| 226 | const label = `${jDate.day}/${jDate.month}`; |
| 227 | const total = salesInvoices |
| 228 | .filter(inv => { |
| 229 | const invDate = this._parseJalali(inv.date); |
| 230 | if (!invDate) return false; |
| 231 | return invDate.getFullYear() === d.getFullYear() |
| 232 | && invDate.getMonth() === d.getMonth() |
| 233 | && invDate.getDate() === d.getDate(); |
| 234 | }) |
| 235 | .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0); |
| 236 | days.push({ label, value: total }); |
| 237 | } |
| 238 | return days; |
| 239 | } |
| 240 | |
| 241 | if (cache.salesPeriod === 'monthly') { |
| 242 | // ۱۲ ماه اخیر |
| 243 | const months = []; |
| 244 | for (let i = 11; i >= 0; i--) { |
| 245 | const d = new Date(today); |
| 246 | d.setMonth(d.getMonth() - i); |
| 247 | const y = d.getFullYear(); |
| 248 | const m = d.getMonth(); |
| 249 | const jDate = Jalali.fromDate(d); |
| 250 | const label = Jalali.monthName(jDate.month); |
| 251 | const total = salesInvoices |
| 252 | .filter(inv => { |
| 253 | const invDate = this._parseJalali(inv.date); |
| 254 | if (!invDate) return false; |
| 255 | return invDate.getFullYear() === y && invDate.getMonth() === m; |
| 256 | }) |
| 257 | .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0); |
| 258 | months.push({ label, value: total }); |
| 259 | } |
| 260 | return months; |
| 261 | } |
| 262 | |
| 263 | // yearly — ۵ سال اخیر |
| 264 | const years = []; |
| 265 | for (let i = 4; i >= 0; i--) { |
| 266 | const d = new Date(today); |
| 267 | d.setFullYear(d.getFullYear() - i); |
| 268 | const y = d.getFullYear(); |
| 269 | const jDate = Jalali.fromDate(d); |
| 270 | const label = Formatters.toPersianDigits(jDate.year); |
| 271 | const total = salesInvoices |
| 272 | .filter(inv => { |
| 273 | const invDate = this._parseJalali(inv.date); |
| 274 | return invDate && invDate.getFullYear() === y; |
| 275 | }) |
| 276 | .reduce((s, inv) => s + (Number(inv.grandTotal) || 0), 0); |
| 277 | years.push({ label, value: total }); |
| 278 | } |
| 279 | return years; |
| 280 | } |
| 281 | |
| 282 | _switchPeriod(period) { |
| 283 | cache.salesPeriod = period; |
| 284 | const card = document.querySelector('#pageContent .card'); |
| 285 | // رندر مجدد کل صفحه (سادهتر از پیدا کردن دقیق المان) |
| 286 | this.render().then(html => { |
| 287 | document.getElementById('pageContent').innerHTML = html; |
| 288 | }); |
| 289 | } |
| 290 | |
| 291 | // ============================================================ |
| 292 | // کارت حسابها |
| 293 | // ============================================================ |
| 294 | _renderAccountsCard() { |
| 295 | const accounts = cache.treasury.filter(t => t.recordType === 'account'); |
| 296 | if (accounts.length === 0) { |
| 297 | return ` |
| 298 | <div class="card" style="margin:0"> |
| 299 | <h3 style="font-size:15px;font-weight:700;margin-bottom:12px">🏦 حسابها</h3> |
| 300 | <div style="text-align:center;padding:30px 10px;color:var(--text-muted);font-size:12.5px"> |
| 301 | هنوز حسابی تعریف نشده |
| 302 | <div style="margin-top:12px"> |
| 303 | <button class="btn btn-secondary btn-inline" onclick="FINORA.Router.go('treasury')">➕ تعریف حساب</button> |
| 304 | </div> |
| 305 | </div> |
| 306 | </div> |
| 307 | `; |
| 308 | } |
| 309 | |
| 310 | // محاسبه موجودی |
| 311 | const transactions = cache.treasury.filter(t => t.recordType === 'transaction'); |
| 312 | const balances = {}; |
| 313 | accounts.forEach(a => balances[a.id] = Number(a.initialBalance) || 0); |
| 314 | transactions.forEach(t => { |
| 315 | const amt = Number(t.amount) || 0; |
| 316 | if (t.type === 'receipt' && t.toAccountId && balances[t.toAccountId] !== undefined) balances[t.toAccountId] += amt; |
| 317 | else if (t.type === 'payment' && t.fromAccountId && balances[t.fromAccountId] !== undefined) balances[t.fromAccountId] -= amt; |
| 318 | else if (t.type === 'transfer') { |
| 319 | if (t.fromAccountId && balances[t.fromAccountId] !== undefined) balances[t.fromAccountId] -= amt; |
| 320 | if (t.toAccountId && balances[t.toAccountId] !== undefined) balances[t.toAccountId] += amt; |
| 321 | } |
| 322 | }); |
| 323 | |
| 324 | const typeIcons = { cashbox: '💰', bank: '🏦', pos: '💳' }; |
| 325 | |
| 326 | const cardsHtml = accounts.map(a => { |
| 327 | const bal = balances[a.id] || 0; |
| 328 | return ` |
| 329 | <div class="dash-account-card" style="border-right:3px solid ${a.color || '#0d9488'}"> |
| 330 | <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px"> |
| 331 | <span style="font-size:16px">${typeIcons[a.type] || '📁'}</span> |
| 332 | <span style="font-size:12.5px;font-weight:600">${this._esc(a.name)}</span> |
| 333 | ${a.isDefault ? '<span class="badge badge-success" style="font-size:9px">پیشفرض</span>' : ''} |
| 334 | </div> |
| 335 | <div style="font-size:15px;font-weight:800;color:${bal >= 0 ? 'var(--success)' : 'var(--danger)'}"> |
| 336 | ${Formatters.money(bal)} |
| 337 | </div> |
| 338 | </div> |
| 339 | `; |
| 340 | }).join(''); |
| 341 | |
| 342 | return ` |
| 343 | <div class="card" style="margin:0;display:flex;flex-direction:column"> |
| 344 | <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"> |
| 345 | <h3 style="font-size:15px;font-weight:700">🏦 حسابها</h3> |
| 346 | <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('treasury')">مدیریت</button> |
| 347 | </div> |
| 348 | <div style="display:flex;flex-direction:column;gap:8px;overflow-y:auto;max-height:280px"> |
| 349 | ${cardsHtml} |
| 350 | </div> |
| 351 | </div> |
| 352 | `; |
| 353 | } |
| 354 | |
| 355 | // ============================================================ |
| 356 | // نمودار درآمد و هزینه |
| 357 | // ============================================================ |
| 358 | _renderIncomeExpenseChart() { |
| 359 | const today = new Date(); |
| 360 | const data = []; |
| 361 | for (let i = 5; i >= 0; i--) { |
| 362 | const d = new Date(today); |
| 363 | d.setMonth(d.getMonth() - i); |
| 364 | const y = d.getFullYear(); |
| 365 | const m = d.getMonth(); |
| 366 | const jDate = Jalali.fromDate(d); |
| 367 | const label = Jalali.monthName(jDate.month); |
| 368 | |
| 369 | const monthExp = cache.expenses.filter(e => { |
| 370 | const ed = this._parseJalali(e.date); |
| 371 | if (!ed) return false; |
| 372 | return ed.getFullYear() === y && ed.getMonth() === m; |
| 373 | }); |
| 374 | |
| 375 | const income = monthExp.filter(e => e.kind === 'income').reduce((s, e) => s + (Number(e.amount) || 0), 0); |
| 376 | const expense = monthExp.filter(e => e.kind === 'expense').reduce((s, e) => s + (Number(e.amount) || 0), 0); |
| 377 | |
| 378 | data.push({ label, income, expense }); |
| 379 | } |
| 380 | |
| 381 | return ` |
| 382 | <div class="card"> |
| 383 | <h3 style="font-size:15px;font-weight:700;margin-bottom:14px">📊 درآمد و هزینه ۶ ماه اخیر</h3> |
| 384 | ${Chart.bars(data)} |
| 385 | </div> |
| 386 | `; |
| 387 | } |
| 388 | |
| 389 | // ============================================================ |
| 390 | // آخرین فاکتورها |
| 391 | // ============================================================ |
| 392 | _renderRecentInvoices() { |
| 393 | const recent = [...cache.invoices] |
| 394 | .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')) |
| 395 | .slice(0, 5); |
| 396 | |
| 397 | if (recent.length === 0) { |
| 398 | return ` |
| 399 | <div class="card"> |
| 400 | <h3 style="font-size:15px;font-weight:700;margin-bottom:12px">🧾 آخرین فاکتورها</h3> |
| 401 | <div style="text-align:center;padding:30px 10px;color:var(--text-muted);font-size:12.5px"> |
| 402 | هنوز فاکتوری صادر نشده |
| 403 | <div style="margin-top:12px"> |
| 404 | <button class="btn btn-secondary btn-inline" onclick="FINORA.Router.go('invoices')">➕ فاکتور جدید</button> |
| 405 | </div> |
| 406 | </div> |
| 407 | </div> |
| 408 | `; |
| 409 | } |
| 410 | |
| 411 | const rows = recent.map(inv => { |
| 412 | const kindLabels = { |
| 413 | sale: { label: 'فروش', cls: 'badge-success' }, |
| 414 | purchase: { label: 'خرید', cls: 'badge-warning' }, |
| 415 | sale_return: { label: 'برگشت فروش', cls: 'badge-danger' }, |
| 416 | purchase_return: { label: 'برگشت خرید', cls: 'badge-danger' }, |
| 417 | non_formal: { label: 'غیررسمی', cls: 'badge-muted' } |
| 418 | }; |
| 419 | const k = kindLabels[inv.kind] || { label: inv.kind, cls: 'badge-muted' }; |
| 420 | |
| 421 | return ` |
| 422 | <tr> |
| 423 | <td> |
| 424 | <strong>#${Formatters.toPersianDigits(inv.number || '—')}</strong> |
| 425 | ${inv.isPreInvoice ? ' <span class="badge badge-warning" style="font-size:9px">پیش</span>' : ''} |
| 426 | </td> |
| 427 | <td><span class="badge ${k.cls}">${k.label}</span></td> |
| 428 | <td>${this._esc(inv.contactName || '—')}</td> |
| 429 | <td>${Formatters.toPersianDigits(inv.date || '—')}</td> |
| 430 | <td style="font-weight:700">${Formatters.money(inv.grandTotal || 0)}</td> |
| 431 | <td> |
| 432 | <button class="icon-btn-sm" title="چاپ" onclick="window.DashboardView._printInvoice('${inv.id}')">🖨️</button> |
| 433 | </td> |
| 434 | </tr> |
| 435 | `; |
| 436 | }).join(''); |
| 437 | |
| 438 | return ` |
| 439 | <div class="card"> |
| 440 | <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"> |
| 441 | <h3 style="font-size:15px;font-weight:700">🧾 آخرین فاکتورها</h3> |
| 442 | <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('invoices')">همه</button> |
| 443 | </div> |
| 444 | <div class="table-wrap"> |
| 445 | <table> |
| 446 | <thead> |
| 447 | <tr> |
| 448 | <th>شماره</th> |
| 449 | <th style="width:100px">نوع</th> |
| 450 | <th>خریدار</th> |
| 451 | <th style="width:100px">تاریخ</th> |
| 452 | <th style="width:140px">مبلغ کل</th> |
| 453 | <th style="width:60px">عملیات</th> |
| 454 | </tr> |
| 455 | </thead> |
| 456 | <tbody>${rows}</tbody> |
| 457 | </table> |
| 458 | </div> |
| 459 | </div> |
| 460 | `; |
| 461 | } |
| 462 | |
| 463 | // ============================================================ |
| 464 | // چکهای سررسید |
| 465 | // ============================================================ |
| 466 | _renderUpcomingCheques() { |
| 467 | const today = new Date(); |
| 468 | const upcoming = cache.cheques |
| 469 | .filter(c => { |
| 470 | if (c.status !== 'pending') return false; |
| 471 | const due = this._parseJalali(c.dueDate); |
| 472 | if (!due) return false; |
| 473 | const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24)); |
| 474 | return diff >= -30 && diff <= 30; |
| 475 | }) |
| 476 | .sort((a, b) => (a.dueDate || '').localeCompare(b.dueDate || '')) |
| 477 | .slice(0, 8); |
| 478 | |
| 479 | if (upcoming.length === 0) { |
| 480 | return ''; |
| 481 | } |
| 482 | |
| 483 | const rows = upcoming.map(c => { |
| 484 | const due = this._parseJalali(c.dueDate); |
| 485 | const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24)); |
| 486 | let statusBadge = ''; |
| 487 | if (diff < 0) statusBadge = `<span class="badge badge-danger" style="font-size:9.5px">${Formatters.toPersianDigits(Math.abs(diff))} روز گذشته</span>`; |
| 488 | else if (diff === 0) statusBadge = `<span class="badge badge-danger" style="font-size:9.5px">امروز</span>`; |
| 489 | else if (diff <= 7) statusBadge = `<span class="badge badge-warning" style="font-size:9.5px">${Formatters.toPersianDigits(diff)} روز مانده</span>`; |
| 490 | else statusBadge = `<span class="badge badge-muted" style="font-size:9.5px">${Formatters.toPersianDigits(diff)} روز</span>`; |
| 491 | |
| 492 | return ` |
| 493 | <tr> |
| 494 | <td><span class="badge ${c.direction === 'inbound' ? 'badge-success' : 'badge-danger'}">${c.direction === 'inbound' ? '📥 دریافتی' : '📤 پرداختی'}</span></td> |
| 495 | <td>${this._esc(c.contactName || '—')}</td> |
| 496 | <td>${this._esc(c.bankName || '—')}</td> |
| 497 | <td>${Formatters.toPersianDigits(c.dueDate || '—')}</td> |
| 498 | <td style="font-weight:700">${Formatters.money(c.amount || 0)}</td> |
| 499 | <td>${statusBadge}</td> |
| 500 | </tr> |
| 501 | `; |
| 502 | }).join(''); |
| 503 | |
| 504 | return ` |
| 505 | <div class="card"> |
| 506 | <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"> |
| 507 | <h3 style="font-size:15px;font-weight:700">💳 چکهای نزدیک سررسید</h3> |
| 508 | <button class="btn btn-secondary btn-inline" style="font-size:11px;min-height:28px;padding:2px 10px" onclick="FINORA.Router.go('cheques')">مدیریت</button> |
| 509 | </div> |
| 510 | <div class="table-wrap"> |
| 511 | <table> |
| 512 | <thead> |
| 513 | <tr> |
| 514 | <th style="width:110px">نوع</th> |
| 515 | <th>طرف حساب</th> |
| 516 | <th style="width:110px">بانک</th> |
| 517 | <th style="width:110px">سررسید</th> |
| 518 | <th style="width:140px">مبلغ</th> |
| 519 | <th style="width:130px">وضعیت</th> |
| 520 | </tr> |
| 521 | </thead> |
| 522 | <tbody>${rows}</tbody> |
| 523 | </table> |
| 524 | </div> |
| 525 | </div> |
| 526 | `; |
| 527 | } |
| 528 | |
| 529 | // ============================================================ |
| 530 | // Helpers |
| 531 | // ============================================================ |
| 532 | async _printInvoice(invoiceId) { |
| 533 | const { InvoicePrint } = await import('../utils/InvoicePrint.js'); |
| 534 | InvoicePrint.openSettings(invoiceId); |
| 535 | } |
| 536 | |
| 537 | _parseJalali(str) { |
| 538 | if (!str) return null; |
| 539 | const parts = String(str).split('/').map(Number); |
| 540 | if (parts.length !== 3) return null; |
| 541 | const [jy, jm, jd] = parts; |
| 542 | if (!jy || !jm || !jd) return null; |
| 543 | let gy = (jy <= 979) ? 621 : 1600; |
| 544 | let jy2 = jy - (jy <= 979 ? 0 : 979); |
| 545 | let days = (365 * jy2) + (Math.floor(jy2 / 33) * 8) + Math.floor(((jy2 % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186); |
| 546 | gy += 400 * Math.floor(days / 146097); |
| 547 | days %= 146097; |
| 548 | if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; } |
| 549 | gy += 4 * Math.floor(days / 1461); |
| 550 | days %= 1461; |
| 551 | if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; } |
| 552 | let gd = days + 1; |
| 553 | const sal_a = [0,31,((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31]; |
| 554 | let gm = 0; |
| 555 | for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm]; |
| 556 | return new Date(gy, gm - 1, gd); |
| 557 | } |
| 558 | |
| 559 | _esc(s) { |
| 560 | if (!s) return ''; |
| 561 | return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | export const DashboardView = new DashboardViewImpl(); |
| 566 | window.DashboardView = DashboardView; |