فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

fix/a02-orphan-mapping-20261018
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
js 673 lines 29.2 KB
Raw
1 // ============================================================
2 // TreasuryView — صفحه‌ی خزانه‌داری
3 // ============================================================
4
5 import { TreasuryController } from '../controllers/TreasuryController.js';
6 import { ContactController } from '../controllers/ContactController.js';
7 import { InvoiceController } from '../controllers/InvoiceController.js';
8 import { Modal } from '../core/Modal.js';
9 import { Toast } from '../core/Toast.js';
10 import { Formatters } from '../utils/Formatters.js';
11 import { NumberInput } from '../utils/NumberInput.js';
12
13 let currentTab = 'accounts';
14 let txFilter = { search: '', type: '', accountId: '' };
15 let cache = { accounts: [], balances: {}, transactions: [], contacts: [], invoices: [] };
16
17 class TreasuryViewImpl {
18 async render() {
19 await this.reload();
20 return `
21 <div class="page-title">
22 <h2>خزانه‌داری و بانک</h2>
23 <p>مدیریت صندوق‌ها، حساب‌های بانکی و تراکنش‌های دریافت و پرداخت</p>
24 </div>
25
26 <div class="tabs">
27 <button class="tab-btn ${currentTab === 'accounts' ? 'active' : ''}" onclick="window.TreasuryView._switchTab('accounts', this)">
28 💳 حساب‌ها و صندوق‌ها
29 </button>
30 <button class="tab-btn ${currentTab === 'transactions' ? 'active' : ''}" onclick="window.TreasuryView._switchTab('transactions', this)">
31 💸 تراکنش‌ها
32 </button>
33 </div>
34
35 <div id="treasury-content">${this.renderTabContent()}</div>
36 `;
37 }
38
39 onMount() {
40 window.TreasuryView = this;
41 }
42
43 async reload() {
44 cache.accounts = await TreasuryController.getAccounts();
45 cache.balances = await TreasuryController.getBalanceMap();
46 cache.transactions = await TreasuryController.getTransactions();
47 cache.contacts = await ContactController.getAll();
48 // Invoice list is loaded only when opening a settlement dialog, not on
49 // every Treasury route render or startup (large companies may have 50k+).
50 }
51
52 _switchTab(tab, btn) {
53 currentTab = tab;
54 document.querySelectorAll('.tabs .tab-btn').forEach(b => b.classList.remove('active'));
55 if (btn) btn.classList.add('active');
56 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
57 }
58
59 renderTabContent() {
60 if (currentTab === 'accounts') return this.renderAccountsTab();
61 if (currentTab === 'transactions') return this.renderTransactionsTab();
62 return '';
63 }
64
65 // ============================================================
66 // تب حساب‌ها
67 // ============================================================
68 renderAccountsTab() {
69 const totalBalance = Object.values(cache.balances).reduce((s, v) => s + v, 0);
70
71 let cardsHtml = '';
72 if (cache.accounts.length === 0) {
73 cardsHtml = `
74 <div class="empty-state" style="grid-column:1/-1">
75 <div class="icon">💳</div>
76 <h3>هنوز حساب یا صندوقی تعریف نشده</h3>
77 <p>اولین حساب یا صندوق خود را اضافه کنید</p>
78 <button class="btn" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
79 </div>`;
80 } else {
81 cardsHtml = cache.accounts.map(acc => {
82 const bal = cache.balances[acc.id] || 0;
83 const typeLabels = {
84 cashbox: { label: 'صندوق', icon: '💰' },
85 bank: { label: 'بانک', icon: '🏦' },
86 pos: { label: 'پوز', icon: '💳' }
87 };
88 const t = typeLabels[acc.type] || { label: acc.type, icon: '📁' };
89 return `
90 <div class="account-card" style="border-top:3px solid ${acc.color || '#0d9488'}">
91 <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:14px">
92 <div>
93 <div style="font-size:24px;margin-bottom:4px">${t.icon}</div>
94 <div style="font-weight:700;font-size:14px">${this._esc(acc.name)}</div>
95 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${t.label}${acc.isDefault ? ' • پیش‌فرض' : ''}</div>
96 </div>
97 <div class="row-actions">
98 <button class="icon-btn-sm" title="ویرایش" onclick="window.TreasuryView.editAccount('${acc.id}')">✏️</button>
99 <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteAccount('${acc.id}')">🗑️</button>
100 </div>
101 </div>
102 ${acc.bankName ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">🏛️ ${this._esc(acc.bankName)}</div>` : ''}
103 ${acc.accountNumber ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">شماره: ${Formatters.toPersianDigits(acc.accountNumber)}</div>` : ''}
104 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
105 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی فعلی</div>
106 <div style="font-size:18px;font-weight:800;color:${bal >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(bal)}</div>
107 </div>
108 </div>
109 `;
110 }).join('');
111 }
112
113 return `
114 <div class="card" style="background:linear-gradient(135deg,var(--primary),var(--primary-dark));color:#fff;border:none">
115 <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
116 <div>
117 <div style="font-size:12px;opacity:.85;margin-bottom:4px">موجودی کل خزانه</div>
118 <div style="font-size:26px;font-weight:800">${Formatters.money(totalBalance)}</div>
119 <div style="font-size:11.5px;opacity:.85;margin-top:4px">${Formatters.toPersianDigits(cache.accounts.length)} حساب فعال</div>
120 </div>
121 <button class="btn" style="background:#fff;color:var(--primary)" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
122 </div>
123 </div>
124
125 <div class="account-grid">${cardsHtml}</div>
126 `;
127 }
128
129 // ============================================================
130 // تب تراکنش‌ها
131 // ============================================================
132 renderTransactionsTab() {
133 let list = cache.transactions;
134
135 if (txFilter.search) {
136 const q = txFilter.search.toLowerCase();
137 list = list.filter(t =>
138 (t.contactName || '').toLowerCase().includes(q) ||
139 (t.description || '').toLowerCase().includes(q) ||
140 String(t.refInvoiceNumber || '').includes(q)
141 );
142 }
143 if (txFilter.type) list = list.filter(t => t.type === txFilter.type);
144 if (txFilter.accountId) {
145 list = list.filter(t => t.fromAccountId === txFilter.accountId || t.toAccountId === txFilter.accountId);
146 }
147
148 const rows = list.length === 0
149 ? `<tr><td colspan="8"><div class="empty-state"><div class="icon">💸</div><h3>هیچ تراکنشی ثبت نشده</h3><p>اولین دریافت یا پرداخت را ثبت کنید</p></div></td></tr>`
150 : list.map(t => {
151 const fromAcc = cache.accounts.find(a => a.id === t.fromAccountId);
152 const toAcc = cache.accounts.find(a => a.id === t.toAccountId);
153 const typeInfo = {
154 receipt: { label: 'دریافت', cls: 'badge-success', icon: '📥' },
155 payment: { label: 'پرداخت', cls: 'badge-danger', icon: '📤' },
156 transfer: { label: 'انتقال', cls: 'badge-warning', icon: '🔄' }
157 }[t.type] || { label: t.type, cls: 'badge-muted', icon: '💸' };
158
159 let accountText = '—';
160 if (t.type === 'transfer') {
161 accountText = `${this._esc(fromAcc?.name || '—')} → ${this._esc(toAcc?.name || '—')}`;
162 } else if (t.type === 'receipt') {
163 accountText = this._esc(toAcc?.name || '—');
164 } else if (t.type === 'payment') {
165 accountText = this._esc(fromAcc?.name || '—');
166 }
167
168 return `
169 <tr>
170 <td><span class="badge ${typeInfo.cls}">${typeInfo.icon} ${typeInfo.label}</span></td>
171 <td>${Formatters.toPersianDigits(t.date)}</td>
172 <td>${this._esc(t.contactName || '—')}</td>
173 <td>${accountText}</td>
174 <td>${TreasuryController.getMethodLabel(t.method)}</td>
175 <td style="font-weight:700;color:${t.type === 'receipt' ? 'var(--success)' : t.type === 'payment' ? 'var(--danger)' : 'var(--warning)'}">
176 ${t.type === 'receipt' ? '+' : t.type === 'payment' ? '-' : ''}${Formatters.money(t.amount)}
177 </td>
178 <td>${t.refInvoiceNumber ? '#' + Formatters.toPersianDigits(t.refInvoiceNumber) : '—'}</td>
179 <td>
180 <div class="row-actions">
181 <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteTransaction('${t.id}')">🗑️</button>
182 </div>
183 </td>
184 </tr>
185 `;
186 }).join('');
187
188 const accountOptions = cache.accounts.map(a =>
189 `<option value="${a.id}" ${txFilter.accountId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
190 ).join('');
191
192 return `
193 <div class="toolbar">
194 <div class="search-input-wrap">
195 <span class="icon">🔍</span>
196 <input type="text" class="form-control" placeholder="جستجو..." value="${this._esc(txFilter.search)}" oninput="window.TreasuryView._onTxSearch(this.value)" />
197 </div>
198 <select class="form-control" style="width:auto;min-width:120px" onchange="window.TreasuryView._onTxFilter('type', this.value)">
199 <option value="">همه انواع</option>
200 <option value="receipt" ${txFilter.type === 'receipt' ? 'selected' : ''}>دریافت</option>
201 <option value="payment" ${txFilter.type === 'payment' ? 'selected' : ''}>پرداخت</option>
202 <option value="transfer" ${txFilter.type === 'transfer' ? 'selected' : ''}>انتقال</option>
203 </select>
204 <select class="form-control" style="width:auto;min-width:150px" onchange="window.TreasuryView._onTxFilter('accountId', this.value)">
205 <option value="">همه حساب‌ها</option>
206 ${accountOptions}
207 </select>
208 <button class="btn btn-secondary" onclick="window.TreasuryView.openTransferModal()">🔄 انتقال</button>
209 <button class="btn btn-danger" onclick="window.TreasuryView.openPaymentModal()">📤 پرداخت</button>
210 <button class="btn btn-success" onclick="window.TreasuryView.openReceiptModal()">📥 دریافت</button>
211 </div>
212
213 <div class="table-wrap">
214 <table>
215 <thead>
216 <tr>
217 <th style="width:100px">نوع</th>
218 <th style="width:100px">تاریخ</th>
219 <th>طرف حساب</th>
220 <th>حساب</th>
221 <th style="width:100px">روش</th>
222 <th style="width:140px">مبلغ</th>
223 <th style="width:100px">فاکتور</th>
224 <th style="width:80px">عملیات</th>
225 </tr>
226 </thead>
227 <tbody>${rows}</tbody>
228 </table>
229 </div>
230 `;
231 }
232
233 _onTxSearch(val) {
234 txFilter.search = val;
235 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
236 const input = document.querySelector('#treasury-content input[type="text"]');
237 if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
238 }
239
240 _onTxFilter(key, val) {
241 txFilter[key] = val;
242 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
243 }
244
245 // ============================================================
246 // فرم حساب
247 // ============================================================
248 async openAccountModal(accountId = null) {
249 const acc = accountId ? await TreasuryController.getAccount(accountId) : null;
250 const isEdit = !!acc;
251 const d = acc || {
252 type: 'cashbox', name: '', accountNumber: '', cardNumber: '', sheba: '',
253 bankName: '', branchName: '', branchCode: '', ownerName: '',
254 color: '#0d9488', initialBalance: 0
255 };
256
257 const body = `
258 <div class="form-row">
259 <div class="form-group">
260 <label class="form-label">نوع حساب <span class="req">*</span></label>
261 <select class="form-control" id="accType" onchange="window.TreasuryView._onAccTypeChange()">
262 <option value="cashbox" ${d.type === 'cashbox' ? 'selected' : ''}>صندوق نقدی</option>
263 <option value="bank" ${d.type === 'bank' ? 'selected' : ''}>حساب بانکی</option>
264 <option value="pos" ${d.type === 'pos' ? 'selected' : ''}>پوز</option>
265 </select>
266 </div>
267 <div class="form-group">
268 <label class="form-label">نام حساب <span class="req">*</span></label>
269 <input type="text" class="form-control" id="accName" value="${this._esc(d.name)}" placeholder="مثلاً صندوق اصلی / بانک ملی" />
270 </div>
271 </div>
272
273 <div id="bankFields" style="display:${d.type === 'bank' ? 'block' : 'none'}">
274 <div class="form-row">
275 <div class="form-group">
276 <label class="form-label">نام بانک</label>
277 <input type="text" class="form-control" id="accBankName" value="${this._esc(d.bankName)}" placeholder="مثلاً بانک ملی" />
278 </div>
279 <div class="form-group">
280 <label class="form-label">شماره حساب</label>
281 <input type="text" class="form-control" id="accAccountNumber" value="${this._esc(d.accountNumber)}" />
282 </div>
283 </div>
284
285 <div class="form-row">
286 <div class="form-group">
287 <label class="form-label">شماره کارت (۱۶ رقم)</label>
288 <input type="text" class="form-control" id="accCardNumber" value="${this._esc(d.cardNumber)}" maxlength="16" />
289 </div>
290 <div class="form-group">
291 <label class="form-label">شماره شبا</label>
292 <input type="text" class="form-control" id="accSheba" value="${this._esc(d.sheba)}" placeholder="IR..." />
293 </div>
294 </div>
295
296 <div class="form-row">
297 <div class="form-group">
298 <label class="form-label">نام شعبه</label>
299 <input type="text" class="form-control" id="accBranchName" value="${this._esc(d.branchName)}" />
300 </div>
301 <div class="form-group">
302 <label class="form-label">کد شعبه</label>
303 <input type="text" class="form-control" id="accBranchCode" value="${this._esc(d.branchCode)}" />
304 </div>
305 </div>
306 </div>
307
308 <div class="form-row">
309 <div class="form-group">
310 <label class="form-label">نام دارنده حساب</label>
311 <input type="text" class="form-control" id="accOwnerName" value="${this._esc(d.ownerName)}" />
312 </div>
313 <div class="form-group">
314 <label class="form-label">موجودی اولیه (ریال)</label>
315 <input type="text" inputmode="numeric" class="form-control" id="accInitialBalance" value="${NumberInput.format(d.initialBalance || 0)}" />
316 </div>
317 </div>
318
319 <div class="form-group">
320 <label class="form-label">رنگ نمایشی</label>
321 <input type="color" class="form-control" id="accColor" value="${d.color || '#0d9488'}" style="height:44px;padding:4px" />
322 </div>
323 `;
324
325 const footer = `
326 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
327 <button class="btn" onclick="window.TreasuryView.saveAccount(${isEdit ? `'${accountId}'` : 'null'})">💾 ذخیره</button>
328 `;
329
330 Modal.open({ title: isEdit ? 'ویرایش حساب' : 'حساب جدید', body, footer, size: 'md' });
331 }
332
333 _onAccTypeChange() {
334 const type = document.getElementById('accType').value;
335 document.getElementById('bankFields').style.display = type === 'bank' ? 'block' : 'none';
336 }
337
338 async saveAccount(id) {
339 const data = {
340 type: document.getElementById('accType').value,
341 name: document.getElementById('accName').value,
342 bankName: document.getElementById('accBankName')?.value || '',
343 accountNumber: document.getElementById('accAccountNumber')?.value || '',
344 cardNumber: document.getElementById('accCardNumber')?.value || '',
345 sheba: document.getElementById('accSheba')?.value || '',
346 branchName: document.getElementById('accBranchName')?.value || '',
347 branchCode: document.getElementById('accBranchCode')?.value || '',
348 ownerName: document.getElementById('accOwnerName').value,
349 color: document.getElementById('accColor').value,
350 initialBalance: NumberInput.parse(document.getElementById('accInitialBalance').value)
351 };
352
353 if (!data.name.trim()) { Toast.warning('نام حساب الزامی است'); return; }
354
355 try {
356 if (id) {
357 await TreasuryController.updateAccount(id, data);
358 Toast.success('حساب ویرایش شد');
359 } else {
360 await TreasuryController.createAccount(data);
361 Toast.success('حساب اضافه شد');
362 }
363 Modal.close();
364 await this.reload();
365 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
366 } catch (err) {
367 Toast.error('خطا: ' + err.message);
368 }
369 }
370
371 async editAccount(id) {
372 await this.openAccountModal(id);
373 }
374
375 async deleteAccount(id) {
376 const acc = cache.accounts.find(a => a.id === id);
377 Modal.confirm({
378 title: 'حذف حساب',
379 message: `آیا از حذف «${this._esc(acc?.name || '')}» مطمئن هستید؟`,
380 confirmText: 'حذف',
381 danger: true,
382 onConfirm: async () => {
383 try {
384 await TreasuryController.deleteAccount(id);
385 Toast.success('حساب حذف شد');
386 await this.reload();
387 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
388 } catch (err) {
389 Toast.error(err.message);
390 }
391 }
392 });
393 }
394
395 // ============================================================
396 // فرم‌های تراکنش
397 // ============================================================
398 _buildAccountOptions(selectedId = null, filterType = null) {
399 let list = cache.accounts;
400 if (filterType) list = list.filter(a => a.type === filterType);
401 return list.map(a =>
402 `<option value="${a.id}" ${selectedId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
403 ).join('');
404 }
405
406 _buildContactOptions() {
407 return cache.contacts.map(c =>
408 `<option value="${c.id}">${this._esc(c.name)}</option>`
409 ).join('');
410 }
411
412
413 _buildInvoiceOptions(type) {
414 const kinds=type==='receipt'
415 ? ['sale','non_formal','purchase_return']
416 : ['purchase','sale_return'];
417 const invoices=cache.invoices.filter(row=>
418 row.financePosted && !row.isPreInvoice && kinds.includes(row.kind) &&
419 Number(row.remaining)>0);
420 return '<option value="">— دریافت/پرداخت مستقل (بدون اتصال فاکتور) —</option>' +
421 invoices.map(row => `<option value="${this._esc(row.id)}">#${this._esc(row.number)} — ${this._esc(row.contactName||'بدون نام')} (${Formatters.number(row.remaining)} ریال)</option>`).join('');
422 }
423
424 _onInvoiceSelection() {
425 const id=document.getElementById('txInvoiceRef')?.value;
426 const row=cache.invoices.find(x=>x.id===id);
427 const contact=document.getElementById('txContact');
428 if(row?.contactId && contact) contact.value=row.contactId;
429 }
430
431 async openReceiptModal() {
432 if (cache.accounts.length === 0) {
433 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
434 return;
435 }
436 try { cache.invoices = await InvoiceController.getAll(); }
437 catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
438 const body = `
439 <div class="form-row">
440 <div class="form-group">
441 <label class="form-label">تاریخ</label>
442 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
443 </div>
444 <div class="form-group">
445 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
446 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
447 </div>
448 </div>
449
450 <div class="form-group">
451 <label class="form-label">از طرف (شخص)</label>
452 <select class="form-control" id="txContact">
453 <option value="">— بدون طرف حساب —</option>
454 ${this._buildContactOptions()}
455 </select>
456 </div>
457
458 <div class="form-group">
459 <label class="form-label">فاکتور مرتبط (اختیاری)</label>
460 <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
461 ${this._buildInvoiceOptions('receipt')}
462 </select>
463 </div>
464
465 <div class="form-group">
466 <label class="form-label">به حساب <span class="req">*</span></label>
467 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
468 </div>
469
470 <div class="form-group">
471 <label class="form-label">روش دریافت</label>
472 <select class="form-control" id="txMethod">
473 <option value="cash">نقدی</option>
474 <option value="card">کارت</option>
475 <option value="transfer">انتقال بانکی</option>
476 </select>
477 </div>
478
479 <div class="form-group">
480 <label class="form-label">توضیحات</label>
481 <textarea class="form-control" id="txDescription" rows="2"></textarea>
482 </div>
483 `;
484 const footer = `
485 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
486 <button class="btn btn-success" onclick="window.TreasuryView._saveTransaction('receipt')">📥 ثبت دریافت</button>
487 `;
488 Modal.open({ title: 'ثبت دریافت وجه', body, footer, size: 'md' });
489 }
490
491 async openPaymentModal() {
492 if (cache.accounts.length === 0) {
493 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
494 return;
495 }
496 try { cache.invoices = await InvoiceController.getAll(); }
497 catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
498 const body = `
499 <div class="form-row">
500 <div class="form-group">
501 <label class="form-label">تاریخ</label>
502 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
503 </div>
504 <div class="form-group">
505 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
506 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
507 </div>
508 </div>
509
510 <div class="form-group">
511 <label class="form-label">به شخص</label>
512 <select class="form-control" id="txContact">
513 <option value="">— بدون طرف حساب —</option>
514 ${this._buildContactOptions()}
515 </select>
516 </div>
517
518 <div class="form-group">
519 <label class="form-label">فاکتور مرتبط / بازپرداخت (اختیاری)</label>
520 <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
521 ${this._buildInvoiceOptions('payment')}
522 </select>
523 </div>
524
525 <div class="form-group">
526 <label class="form-label">از حساب <span class="req">*</span></label>
527 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
528 </div>
529
530 <div class="form-group">
531 <label class="form-label">روش پرداخت</label>
532 <select class="form-control" id="txMethod">
533 <option value="cash">نقدی</option>
534 <option value="card">کارت</option>
535 <option value="transfer">انتقال بانکی</option>
536 </select>
537 </div>
538
539 <div class="form-group">
540 <label class="form-label">توضیحات</label>
541 <textarea class="form-control" id="txDescription" rows="2"></textarea>
542 </div>
543 `;
544 const footer = `
545 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
546 <button class="btn btn-danger" onclick="window.TreasuryView._saveTransaction('payment')">📤 ثبت پرداخت</button>
547 `;
548 Modal.open({ title: 'ثبت پرداخت وجه', body, footer, size: 'md' });
549 }
550
551 openTransferModal() {
552 if (cache.accounts.length < 2) {
553 Toast.warning('برای انتقال، حداقل دو حساب لازم است');
554 return;
555 }
556 const body = `
557 <div class="form-row">
558 <div class="form-group">
559 <label class="form-label">تاریخ</label>
560 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
561 </div>
562 <div class="form-group">
563 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
564 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
565 </div>
566 </div>
567
568 <div class="form-group">
569 <label class="form-label">از حساب <span class="req">*</span></label>
570 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
571 </div>
572
573 <div class="form-group">
574 <label class="form-label">به حساب <span class="req">*</span></label>
575 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
576 </div>
577
578 <div class="form-group">
579 <label class="form-label">توضیحات</label>
580 <textarea class="form-control" id="txDescription" rows="2"></textarea>
581 </div>
582 `;
583 const footer = `
584 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
585 <button class="btn btn-warning" onclick="window.TreasuryView._saveTransaction('transfer')">🔄 انتقال</button>
586 `;
587 Modal.open({ title: 'انتقال بین حساب‌ها', body, footer, size: 'md' });
588 }
589
590 async _saveTransaction(type) {
591 const amount = NumberInput.parse(document.getElementById('txAmount').value);
592 if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
593
594 const contactSelect = document.getElementById('txContact');
595 const contactId = contactSelect?.value || null;
596 const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
597
598 const data = {
599 type,
600 date: document.getElementById('txDate').value,
601 amount,
602 method: document.getElementById('txMethod')?.value || 'cash',
603 contactId,
604 contactName: contact?.name || '',
605 refInvoiceId: document.getElementById('txInvoiceRef')?.value || null,
606 fromAccountId: document.getElementById('txFromAccount')?.value || null,
607 toAccountId: document.getElementById('txToAccount')?.value || null,
608 description: document.getElementById('txDescription')?.value || ''
609 };
610
611 if (type === 'transfer') {
612 if (!data.fromAccountId || !data.toAccountId) {
613 Toast.warning('حساب مبدأ و مقصد رو انتخاب کنید');
614 return;
615 }
616 if (data.fromAccountId === data.toAccountId) {
617 Toast.warning('حساب مبدأ و مقصد نباید یکی باشند');
618 return;
619 }
620 }
621
622 try {
623 await TreasuryController.createTransaction(data);
624 Toast.success(TreasuryController.getTypeLabel(type) + ' ثبت شد');
625 Modal.close();
626 await this.reload();
627 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
628 } catch (err) {
629 Toast.error('خطا: ' + err.message);
630 }
631 }
632
633 async deleteTransaction(id) {
634 Modal.confirm({
635 title: 'حذف تراکنش',
636 message: 'آیا از حذف این تراکنش مطمئن هستید؟ موجودی حساب به‌روزرسانی می‌شود.',
637 confirmText: 'حذف',
638 danger: true,
639 onConfirm: async () => {
640 await TreasuryController.deleteTransaction(id);
641 Toast.success('تراکنش حذف شد');
642 await this.reload();
643 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
644 }
645 });
646 }
647
648 _todayJalali() {
649 const d = new Date();
650 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
651 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
652 let jy = (gy <= 1600) ? 0 : 979;
653 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
654 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
655 let days = (365 * gy2) + Math.floor((gyAdj + 3) / 4) - Math.floor((gyAdj + 99) / 100) + Math.floor((gyAdj + 399) / 400) - 80 + gd + g_d_m[gm - 1];
656 jy += 33 * Math.floor(days / 12053);
657 days %= 12053;
658 jy += 4 * Math.floor(days / 1461);
659 days %= 1461;
660 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
661 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
662 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
663 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
664 }
665
666 _esc(s) {
667 if (!s) return '';
668 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
669 }
670 }
671
672 export const TreasuryView = new TreasuryViewImpl();
673 window.TreasuryView = TreasuryView;