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

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