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

release/v2.0.0
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 633 lines 27.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: [] };
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 }
49
50 _switchTab(tab, btn) {
51 currentTab = tab;
52 document.querySelectorAll('.tabs .tab-btn').forEach(b => b.classList.remove('active'));
53 if (btn) btn.classList.add('active');
54 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
55 }
56
57 renderTabContent() {
58 if (currentTab === 'accounts') return this.renderAccountsTab();
59 if (currentTab === 'transactions') return this.renderTransactionsTab();
60 return '';
61 }
62
63 // ============================================================
64 // تب حساب‌ها
65 // ============================================================
66 renderAccountsTab() {
67 const totalBalance = Object.values(cache.balances).reduce((s, v) => s + v, 0);
68
69 let cardsHtml = '';
70 if (cache.accounts.length === 0) {
71 cardsHtml = `
72 <div class="empty-state" style="grid-column:1/-1">
73 <div class="icon">💳</div>
74 <h3>هنوز حساب یا صندوقی تعریف نشده</h3>
75 <p>اولین حساب یا صندوق خود را اضافه کنید</p>
76 <button class="btn" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
77 </div>`;
78 } else {
79 cardsHtml = cache.accounts.map(acc => {
80 const bal = cache.balances[acc.id] || 0;
81 const typeLabels = {
82 cashbox: { label: 'صندوق', icon: '💰' },
83 bank: { label: 'بانک', icon: '🏦' },
84 pos: { label: 'پوز', icon: '💳' }
85 };
86 const t = typeLabels[acc.type] || { label: acc.type, icon: '📁' };
87 return `
88 <div class="account-card" style="border-top:3px solid ${acc.color || '#0d9488'}">
89 <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:14px">
90 <div>
91 <div style="font-size:24px;margin-bottom:4px">${t.icon}</div>
92 <div style="font-weight:700;font-size:14px">${this._esc(acc.name)}</div>
93 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${t.label}${acc.isDefault ? ' • پیش‌فرض' : ''}</div>
94 </div>
95 <div class="row-actions">
96 <button class="icon-btn-sm" title="ویرایش" onclick="window.TreasuryView.editAccount('${acc.id}')">✏️</button>
97 <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteAccount('${acc.id}')">🗑️</button>
98 </div>
99 </div>
100 ${acc.bankName ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">🏛️ ${this._esc(acc.bankName)}</div>` : ''}
101 ${acc.accountNumber ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:4px">شماره: ${Formatters.toPersianDigits(acc.accountNumber)}</div>` : ''}
102 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
103 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی فعلی</div>
104 <div style="font-size:18px;font-weight:800;color:${bal >= 0 ? 'var(--success)' : 'var(--danger)'}">${Formatters.money(bal)}</div>
105 </div>
106 </div>
107 `;
108 }).join('');
109 }
110
111 return `
112 <div class="card" style="background:linear-gradient(135deg,var(--primary),var(--primary-dark));color:#fff;border:none">
113 <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px">
114 <div>
115 <div style="font-size:12px;opacity:.85;margin-bottom:4px">موجودی کل خزانه</div>
116 <div style="font-size:26px;font-weight:800">${Formatters.money(totalBalance)}</div>
117 <div style="font-size:11.5px;opacity:.85;margin-top:4px">${Formatters.toPersianDigits(cache.accounts.length)} حساب فعال</div>
118 </div>
119 <button class="btn" style="background:#fff;color:var(--primary)" onclick="window.TreasuryView.openAccountModal()">➕ حساب جدید</button>
120 </div>
121 </div>
122
123 <div class="account-grid">${cardsHtml}</div>
124 `;
125 }
126
127 // ============================================================
128 // تب تراکنش‌ها
129 // ============================================================
130 renderTransactionsTab() {
131 let list = cache.transactions;
132
133 if (txFilter.search) {
134 const q = txFilter.search.toLowerCase();
135 list = list.filter(t =>
136 (t.contactName || '').toLowerCase().includes(q) ||
137 (t.description || '').toLowerCase().includes(q) ||
138 String(t.refInvoiceNumber || '').includes(q)
139 );
140 }
141 if (txFilter.type) list = list.filter(t => t.type === txFilter.type);
142 if (txFilter.accountId) {
143 list = list.filter(t => t.fromAccountId === txFilter.accountId || t.toAccountId === txFilter.accountId);
144 }
145
146 const rows = list.length === 0
147 ? `<tr><td colspan="8"><div class="empty-state"><div class="icon">💸</div><h3>هیچ تراکنشی ثبت نشده</h3><p>اولین دریافت یا پرداخت را ثبت کنید</p></div></td></tr>`
148 : list.map(t => {
149 const fromAcc = cache.accounts.find(a => a.id === t.fromAccountId);
150 const toAcc = cache.accounts.find(a => a.id === t.toAccountId);
151 const typeInfo = {
152 receipt: { label: 'دریافت', cls: 'badge-success', icon: '📥' },
153 payment: { label: 'پرداخت', cls: 'badge-danger', icon: '📤' },
154 transfer: { label: 'انتقال', cls: 'badge-warning', icon: '🔄' }
155 }[t.type] || { label: t.type, cls: 'badge-muted', icon: '💸' };
156
157 let accountText = '—';
158 if (t.type === 'transfer') {
159 accountText = `${this._esc(fromAcc?.name || '—')} → ${this._esc(toAcc?.name || '—')}`;
160 } else if (t.type === 'receipt') {
161 accountText = this._esc(toAcc?.name || '—');
162 } else if (t.type === 'payment') {
163 accountText = this._esc(fromAcc?.name || '—');
164 }
165
166 return `
167 <tr>
168 <td><span class="badge ${typeInfo.cls}">${typeInfo.icon} ${typeInfo.label}</span></td>
169 <td>${Formatters.toPersianDigits(t.date)}</td>
170 <td>${this._esc(t.contactName || '—')}</td>
171 <td>${accountText}</td>
172 <td>${TreasuryController.getMethodLabel(t.method)}</td>
173 <td style="font-weight:700;color:${t.type === 'receipt' ? 'var(--success)' : t.type === 'payment' ? 'var(--danger)' : 'var(--warning)'}">
174 ${t.type === 'receipt' ? '+' : t.type === 'payment' ? '-' : ''}${Formatters.money(t.amount)}
175 </td>
176 <td>${t.refInvoiceNumber ? '#' + Formatters.toPersianDigits(t.refInvoiceNumber) : '—'}</td>
177 <td>
178 <div class="row-actions">
179 <button class="icon-btn-sm danger" title="حذف" onclick="window.TreasuryView.deleteTransaction('${t.id}')">🗑️</button>
180 </div>
181 </td>
182 </tr>
183 `;
184 }).join('');
185
186 const accountOptions = cache.accounts.map(a =>
187 `<option value="${a.id}" ${txFilter.accountId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
188 ).join('');
189
190 return `
191 <div class="toolbar">
192 <div class="search-input-wrap">
193 <span class="icon">🔍</span>
194 <input type="text" class="form-control" placeholder="جستجو..." value="${this._esc(txFilter.search)}" oninput="window.TreasuryView._onTxSearch(this.value)" />
195 </div>
196 <select class="form-control" style="width:auto;min-width:120px" onchange="window.TreasuryView._onTxFilter('type', this.value)">
197 <option value="">همه انواع</option>
198 <option value="receipt" ${txFilter.type === 'receipt' ? 'selected' : ''}>دریافت</option>
199 <option value="payment" ${txFilter.type === 'payment' ? 'selected' : ''}>پرداخت</option>
200 <option value="transfer" ${txFilter.type === 'transfer' ? 'selected' : ''}>انتقال</option>
201 </select>
202 <select class="form-control" style="width:auto;min-width:150px" onchange="window.TreasuryView._onTxFilter('accountId', this.value)">
203 <option value="">همه حساب‌ها</option>
204 ${accountOptions}
205 </select>
206 <button class="btn btn-secondary" onclick="window.TreasuryView.openTransferModal()">🔄 انتقال</button>
207 <button class="btn btn-danger" onclick="window.TreasuryView.openPaymentModal()">📤 پرداخت</button>
208 <button class="btn btn-success" onclick="window.TreasuryView.openReceiptModal()">📥 دریافت</button>
209 </div>
210
211 <div class="table-wrap">
212 <table>
213 <thead>
214 <tr>
215 <th style="width:100px">نوع</th>
216 <th style="width:100px">تاریخ</th>
217 <th>طرف حساب</th>
218 <th>حساب</th>
219 <th style="width:100px">روش</th>
220 <th style="width:140px">مبلغ</th>
221 <th style="width:100px">فاکتور</th>
222 <th style="width:80px">عملیات</th>
223 </tr>
224 </thead>
225 <tbody>${rows}</tbody>
226 </table>
227 </div>
228 `;
229 }
230
231 _onTxSearch(val) {
232 txFilter.search = val;
233 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
234 const input = document.querySelector('#treasury-content input[type="text"]');
235 if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
236 }
237
238 _onTxFilter(key, val) {
239 txFilter[key] = val;
240 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
241 }
242
243 // ============================================================
244 // فرم حساب
245 // ============================================================
246 async openAccountModal(accountId = null) {
247 const acc = accountId ? await TreasuryController.getAccount(accountId) : null;
248 const isEdit = !!acc;
249 const d = acc || {
250 type: 'cashbox', name: '', accountNumber: '', cardNumber: '', sheba: '',
251 bankName: '', branchName: '', branchCode: '', ownerName: '',
252 color: '#0d9488', initialBalance: 0
253 };
254
255 const body = `
256 <div class="form-row">
257 <div class="form-group">
258 <label class="form-label">نوع حساب <span class="req">*</span></label>
259 <select class="form-control" id="accType" onchange="window.TreasuryView._onAccTypeChange()">
260 <option value="cashbox" ${d.type === 'cashbox' ? 'selected' : ''}>صندوق نقدی</option>
261 <option value="bank" ${d.type === 'bank' ? 'selected' : ''}>حساب بانکی</option>
262 <option value="pos" ${d.type === 'pos' ? 'selected' : ''}>پوز</option>
263 </select>
264 </div>
265 <div class="form-group">
266 <label class="form-label">نام حساب <span class="req">*</span></label>
267 <input type="text" class="form-control" id="accName" value="${this._esc(d.name)}" placeholder="مثلاً صندوق اصلی / بانک ملی" />
268 </div>
269 </div>
270
271 <div id="bankFields" style="display:${d.type === 'bank' ? 'block' : 'none'}">
272 <div class="form-row">
273 <div class="form-group">
274 <label class="form-label">نام بانک</label>
275 <input type="text" class="form-control" id="accBankName" value="${this._esc(d.bankName)}" placeholder="مثلاً بانک ملی" />
276 </div>
277 <div class="form-group">
278 <label class="form-label">شماره حساب</label>
279 <input type="text" class="form-control" id="accAccountNumber" value="${this._esc(d.accountNumber)}" />
280 </div>
281 </div>
282
283 <div class="form-row">
284 <div class="form-group">
285 <label class="form-label">شماره کارت (۱۶ رقم)</label>
286 <input type="text" class="form-control" id="accCardNumber" value="${this._esc(d.cardNumber)}" maxlength="16" />
287 </div>
288 <div class="form-group">
289 <label class="form-label">شماره شبا</label>
290 <input type="text" class="form-control" id="accSheba" value="${this._esc(d.sheba)}" placeholder="IR..." />
291 </div>
292 </div>
293
294 <div class="form-row">
295 <div class="form-group">
296 <label class="form-label">نام شعبه</label>
297 <input type="text" class="form-control" id="accBranchName" value="${this._esc(d.branchName)}" />
298 </div>
299 <div class="form-group">
300 <label class="form-label">کد شعبه</label>
301 <input type="text" class="form-control" id="accBranchCode" value="${this._esc(d.branchCode)}" />
302 </div>
303 </div>
304 </div>
305
306 <div class="form-row">
307 <div class="form-group">
308 <label class="form-label">نام دارنده حساب</label>
309 <input type="text" class="form-control" id="accOwnerName" value="${this._esc(d.ownerName)}" />
310 </div>
311 <div class="form-group">
312 <label class="form-label">موجودی اولیه (ریال)</label>
313 <input type="text" inputmode="numeric" class="form-control" id="accInitialBalance" value="${NumberInput.format(d.initialBalance || 0)}" />
314 </div>
315 </div>
316
317 <div class="form-group">
318 <label class="form-label">رنگ نمایشی</label>
319 <input type="color" class="form-control" id="accColor" value="${d.color || '#0d9488'}" style="height:44px;padding:4px" />
320 </div>
321 `;
322
323 const footer = `
324 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
325 <button class="btn" onclick="window.TreasuryView.saveAccount(${isEdit ? `'${accountId}'` : 'null'})">💾 ذخیره</button>
326 `;
327
328 Modal.open({ title: isEdit ? 'ویرایش حساب' : 'حساب جدید', body, footer, size: 'md' });
329 }
330
331 _onAccTypeChange() {
332 const type = document.getElementById('accType').value;
333 document.getElementById('bankFields').style.display = type === 'bank' ? 'block' : 'none';
334 }
335
336 async saveAccount(id) {
337 const data = {
338 type: document.getElementById('accType').value,
339 name: document.getElementById('accName').value,
340 bankName: document.getElementById('accBankName')?.value || '',
341 accountNumber: document.getElementById('accAccountNumber')?.value || '',
342 cardNumber: document.getElementById('accCardNumber')?.value || '',
343 sheba: document.getElementById('accSheba')?.value || '',
344 branchName: document.getElementById('accBranchName')?.value || '',
345 branchCode: document.getElementById('accBranchCode')?.value || '',
346 ownerName: document.getElementById('accOwnerName').value,
347 color: document.getElementById('accColor').value,
348 initialBalance: NumberInput.parse(document.getElementById('accInitialBalance').value)
349 };
350
351 if (!data.name.trim()) { Toast.warning('نام حساب الزامی است'); return; }
352
353 try {
354 if (id) {
355 await TreasuryController.updateAccount(id, data);
356 Toast.success('حساب ویرایش شد');
357 } else {
358 await TreasuryController.createAccount(data);
359 Toast.success('حساب اضافه شد');
360 }
361 Modal.close();
362 await this.reload();
363 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
364 } catch (err) {
365 Toast.error('خطا: ' + err.message);
366 }
367 }
368
369 async editAccount(id) {
370 await this.openAccountModal(id);
371 }
372
373 async deleteAccount(id) {
374 const acc = cache.accounts.find(a => a.id === id);
375 Modal.confirm({
376 title: 'حذف حساب',
377 message: `آیا از حذف «${this._esc(acc?.name || '')}» مطمئن هستید؟`,
378 confirmText: 'حذف',
379 danger: true,
380 onConfirm: async () => {
381 try {
382 await TreasuryController.deleteAccount(id);
383 Toast.success('حساب حذف شد');
384 await this.reload();
385 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
386 } catch (err) {
387 Toast.error(err.message);
388 }
389 }
390 });
391 }
392
393 // ============================================================
394 // فرم‌های تراکنش
395 // ============================================================
396 _buildAccountOptions(selectedId = null, filterType = null) {
397 let list = cache.accounts;
398 if (filterType) list = list.filter(a => a.type === filterType);
399 return list.map(a =>
400 `<option value="${a.id}" ${selectedId === a.id ? 'selected' : ''}>${this._esc(a.name)}</option>`
401 ).join('');
402 }
403
404 _buildContactOptions() {
405 return cache.contacts.map(c =>
406 `<option value="${c.id}">${this._esc(c.name)}</option>`
407 ).join('');
408 }
409
410 openReceiptModal() {
411 if (cache.accounts.length === 0) {
412 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
413 return;
414 }
415 const body = `
416 <div class="form-row">
417 <div class="form-group">
418 <label class="form-label">تاریخ</label>
419 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
420 </div>
421 <div class="form-group">
422 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
423 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
424 </div>
425 </div>
426
427 <div class="form-group">
428 <label class="form-label">از طرف (شخص)</label>
429 <select class="form-control" id="txContact">
430 <option value="">— بدون طرف حساب —</option>
431 ${this._buildContactOptions()}
432 </select>
433 </div>
434
435 <div class="form-group">
436 <label class="form-label">به حساب <span class="req">*</span></label>
437 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
438 </div>
439
440 <div class="form-group">
441 <label class="form-label">روش دریافت</label>
442 <select class="form-control" id="txMethod">
443 <option value="cash">نقدی</option>
444 <option value="card">کارت</option>
445 <option value="transfer">انتقال بانکی</option>
446 </select>
447 </div>
448
449 <div class="form-group">
450 <label class="form-label">توضیحات</label>
451 <textarea class="form-control" id="txDescription" rows="2"></textarea>
452 </div>
453 `;
454 const footer = `
455 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
456 <button class="btn btn-success" onclick="window.TreasuryView._saveTransaction('receipt')">📥 ثبت دریافت</button>
457 `;
458 Modal.open({ title: 'ثبت دریافت وجه', body, footer, size: 'md' });
459 }
460
461 openPaymentModal() {
462 if (cache.accounts.length === 0) {
463 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
464 return;
465 }
466 const body = `
467 <div class="form-row">
468 <div class="form-group">
469 <label class="form-label">تاریخ</label>
470 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
471 </div>
472 <div class="form-group">
473 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
474 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
475 </div>
476 </div>
477
478 <div class="form-group">
479 <label class="form-label">به شخص</label>
480 <select class="form-control" id="txContact">
481 <option value="">— بدون طرف حساب —</option>
482 ${this._buildContactOptions()}
483 </select>
484 </div>
485
486 <div class="form-group">
487 <label class="form-label">از حساب <span class="req">*</span></label>
488 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
489 </div>
490
491 <div class="form-group">
492 <label class="form-label">روش پرداخت</label>
493 <select class="form-control" id="txMethod">
494 <option value="cash">نقدی</option>
495 <option value="card">کارت</option>
496 <option value="transfer">انتقال بانکی</option>
497 </select>
498 </div>
499
500 <div class="form-group">
501 <label class="form-label">توضیحات</label>
502 <textarea class="form-control" id="txDescription" rows="2"></textarea>
503 </div>
504 `;
505 const footer = `
506 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
507 <button class="btn btn-danger" onclick="window.TreasuryView._saveTransaction('payment')">📤 ثبت پرداخت</button>
508 `;
509 Modal.open({ title: 'ثبت پرداخت وجه', body, footer, size: 'md' });
510 }
511
512 openTransferModal() {
513 if (cache.accounts.length < 2) {
514 Toast.warning('برای انتقال، حداقل دو حساب لازم است');
515 return;
516 }
517 const body = `
518 <div class="form-row">
519 <div class="form-group">
520 <label class="form-label">تاریخ</label>
521 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
522 </div>
523 <div class="form-group">
524 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
525 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
526 </div>
527 </div>
528
529 <div class="form-group">
530 <label class="form-label">از حساب <span class="req">*</span></label>
531 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
532 </div>
533
534 <div class="form-group">
535 <label class="form-label">به حساب <span class="req">*</span></label>
536 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</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-warning" onclick="window.TreasuryView._saveTransaction('transfer')">🔄 انتقال</button>
547 `;
548 Modal.open({ title: 'انتقال بین حساب‌ها', body, footer, size: 'md' });
549 }
550
551 async _saveTransaction(type) {
552 const amount = NumberInput.parse(document.getElementById('txAmount').value);
553 if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
554
555 const contactSelect = document.getElementById('txContact');
556 const contactId = contactSelect?.value || null;
557 const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
558
559 const data = {
560 type,
561 date: document.getElementById('txDate').value,
562 amount,
563 method: document.getElementById('txMethod')?.value || 'cash',
564 contactId,
565 contactName: contact?.name || '',
566 fromAccountId: document.getElementById('txFromAccount')?.value || null,
567 toAccountId: document.getElementById('txToAccount')?.value || null,
568 description: document.getElementById('txDescription')?.value || ''
569 };
570
571 if (type === 'transfer') {
572 if (!data.fromAccountId || !data.toAccountId) {
573 Toast.warning('حساب مبدأ و مقصد رو انتخاب کنید');
574 return;
575 }
576 if (data.fromAccountId === data.toAccountId) {
577 Toast.warning('حساب مبدأ و مقصد نباید یکی باشند');
578 return;
579 }
580 }
581
582 try {
583 await TreasuryController.createTransaction(data);
584 Toast.success(TreasuryController.getTypeLabel(type) + ' ثبت شد');
585 Modal.close();
586 await this.reload();
587 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
588 } catch (err) {
589 Toast.error('خطا: ' + err.message);
590 }
591 }
592
593 async deleteTransaction(id) {
594 Modal.confirm({
595 title: 'حذف تراکنش',
596 message: 'آیا از حذف این تراکنش مطمئن هستید؟ موجودی حساب به‌روزرسانی می‌شود.',
597 confirmText: 'حذف',
598 danger: true,
599 onConfirm: async () => {
600 await TreasuryController.deleteTransaction(id);
601 Toast.success('تراکنش حذف شد');
602 await this.reload();
603 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
604 }
605 });
606 }
607
608 _todayJalali() {
609 const d = new Date();
610 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
611 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
612 let jy = (gy <= 1600) ? 0 : 979;
613 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
614 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
615 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];
616 jy += 33 * Math.floor(days / 12053);
617 days %= 12053;
618 jy += 4 * Math.floor(days / 1461);
619 days %= 1461;
620 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
621 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
622 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
623 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
624 }
625
626 _esc(s) {
627 if (!s) return '';
628 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
629 }
630 }
631
632 export const TreasuryView = new TreasuryViewImpl();
633 window.TreasuryView = TreasuryView;