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

fix/a02-holoo-invoice-line-coverage-20261023
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 717 lines 31.7 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 const reasonGroup=document.getElementById('txReturnReasonGroup');
430 if(reasonGroup) {
431 const isReturn=row && ['sale_return','purchase_return'].includes(row.kind);
432 reasonGroup.style.display=isReturn?'':'none';
433 if(!isReturn) document.getElementById('txReturnReason').value='';
434 }
435 }
436
437 async openReceiptModal() {
438 if (cache.accounts.length === 0) {
439 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
440 return;
441 }
442 try { cache.invoices = await InvoiceController.getAll(); }
443 catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
444 const body = `
445 <div class="form-row">
446 <div class="form-group">
447 <label class="form-label">تاریخ</label>
448 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
449 </div>
450 <div class="form-group">
451 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
452 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
453 </div>
454 </div>
455
456 <div class="form-group">
457 <label class="form-label">از طرف (شخص)</label>
458 <select class="form-control" id="txContact">
459 <option value="">— بدون طرف حساب —</option>
460 ${this._buildContactOptions()}
461 </select>
462 </div>
463
464 <div class="form-group">
465 <label class="form-label">فاکتور مرتبط (اختیاری)</label>
466 <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
467 ${this._buildInvoiceOptions('receipt')}
468 </select>
469 </div>
470
471 <div class="form-group">
472 <label class="form-label">به حساب <span class="req">*</span></label>
473 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
474 </div>
475
476 <div class="form-group">
477 <label class="form-label">روش دریافت</label>
478 <select class="form-control" id="txMethod">
479 <option value="cash">نقدی</option>
480 <option value="card">کارت</option>
481 <option value="transfer">انتقال بانکی</option>
482 </select>
483 </div>
484
485 <div class="form-group" id="txReturnReasonGroup" style="display:none">
486 <label class="form-label">دلیل تسویه مرجوعی <span class="req">*</span></label>
487 <select class="form-control" id="txReturnReason">
488 <option value="">— دلیل را انتخاب کنید —</option>
489 <option value="goods_return">برگشت کالا</option>
490 <option value="quality_issue">ایراد یا کیفیت کالا</option>
491 <option value="pricing_dispute">اختلاف قیمت/محاسبه</option>
492 </select>
493 </div>
494 <div class="form-group">
495 <label class="form-label">توضیحات</label>
496 <textarea class="form-control" id="txDescription" rows="2"></textarea>
497 </div>
498 `;
499 const footer = `
500 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
501 <button class="btn btn-success" onclick="window.TreasuryView._saveTransaction('receipt')">📥 ثبت دریافت</button>
502 `;
503 Modal.open({ title: 'ثبت دریافت وجه', body, footer, size: 'md' });
504 }
505
506 async openPaymentModal() {
507 if (cache.accounts.length === 0) {
508 Toast.warning('ابتدا یک حساب یا صندوق تعریف کنید');
509 return;
510 }
511 try { cache.invoices = await InvoiceController.getAll(); }
512 catch (error) { Toast.error('بارگذاری فاکتورها: ' + error.message); return; }
513 const body = `
514 <div class="form-row">
515 <div class="form-group">
516 <label class="form-label">تاریخ</label>
517 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
518 </div>
519 <div class="form-group">
520 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
521 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
522 </div>
523 </div>
524
525 <div class="form-group">
526 <label class="form-label">به شخص</label>
527 <select class="form-control" id="txContact">
528 <option value="">— بدون طرف حساب —</option>
529 ${this._buildContactOptions()}
530 </select>
531 </div>
532
533 <div class="form-group">
534 <label class="form-label">فاکتور مرتبط / بازپرداخت (اختیاری)</label>
535 <select class="form-control" id="txInvoiceRef" onchange="window.TreasuryView._onInvoiceSelection()">
536 ${this._buildInvoiceOptions('payment')}
537 </select>
538 </div>
539
540 <div class="form-group">
541 <label class="form-label">از حساب <span class="req">*</span></label>
542 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
543 </div>
544
545 <div class="form-group">
546 <label class="form-label">روش پرداخت</label>
547 <select class="form-control" id="txMethod">
548 <option value="cash">نقدی</option>
549 <option value="card">کارت</option>
550 <option value="transfer">انتقال بانکی</option>
551 </select>
552 </div>
553
554 <div class="form-group" id="txReturnReasonGroup" style="display:none">
555 <label class="form-label">دلیل تسویه مرجوعی <span class="req">*</span></label>
556 <select class="form-control" id="txReturnReason">
557 <option value="">— دلیل را انتخاب کنید —</option>
558 <option value="goods_return">برگشت کالا</option>
559 <option value="quality_issue">ایراد یا کیفیت کالا</option>
560 <option value="pricing_dispute">اختلاف قیمت/محاسبه</option>
561 </select>
562 </div>
563 <div class="form-group">
564 <label class="form-label">توضیحات</label>
565 <textarea class="form-control" id="txDescription" rows="2"></textarea>
566 </div>
567 `;
568 const footer = `
569 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
570 <button class="btn btn-danger" onclick="window.TreasuryView._saveTransaction('payment')">📤 ثبت پرداخت</button>
571 `;
572 Modal.open({ title: 'ثبت پرداخت وجه', body, footer, size: 'md' });
573 }
574
575 openTransferModal() {
576 if (cache.accounts.length < 2) {
577 Toast.warning('برای انتقال، حداقل دو حساب لازم است');
578 return;
579 }
580 const body = `
581 <div class="form-row">
582 <div class="form-group">
583 <label class="form-label">تاریخ</label>
584 <input type="text" class="form-control" id="txDate" value="${this._todayJalali()}" />
585 </div>
586 <div class="form-group">
587 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
588 <input type="text" inputmode="numeric" class="form-control" id="txAmount" value="0" />
589 </div>
590 </div>
591
592 <div class="form-group">
593 <label class="form-label">از حساب <span class="req">*</span></label>
594 <select class="form-control" id="txFromAccount">${this._buildAccountOptions()}</select>
595 </div>
596
597 <div class="form-group">
598 <label class="form-label">به حساب <span class="req">*</span></label>
599 <select class="form-control" id="txToAccount">${this._buildAccountOptions()}</select>
600 </div>
601
602 <div class="form-group">
603 <label class="form-label">توضیحات</label>
604 <textarea class="form-control" id="txDescription" rows="2"></textarea>
605 </div>
606 `;
607 const footer = `
608 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
609 <button class="btn btn-warning" onclick="window.TreasuryView._saveTransaction('transfer')">🔄 انتقال</button>
610 `;
611 Modal.open({ title: 'انتقال بین حساب‌ها', body, footer, size: 'md' });
612 }
613
614 async _saveTransaction(type) {
615 const amount = NumberInput.parse(document.getElementById('txAmount').value);
616 if (amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
617
618 const contactSelect = document.getElementById('txContact');
619 const contactId = contactSelect?.value || null;
620 const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
621
622 const data = {
623 type,
624 date: document.getElementById('txDate').value,
625 amount,
626 method: document.getElementById('txMethod')?.value || 'cash',
627 contactId,
628 contactName: contact?.name || '',
629 refInvoiceId: document.getElementById('txInvoiceRef')?.value || null,
630 fromAccountId: document.getElementById('txFromAccount')?.value || null,
631 toAccountId: document.getElementById('txToAccount')?.value || null,
632 description: document.getElementById('txDescription')?.value || ''
633 };
634
635 if (type === 'transfer') {
636 if (!data.fromAccountId || !data.toAccountId) {
637 Toast.warning('حساب مبدأ و مقصد رو انتخاب کنید');
638 return;
639 }
640 if (data.fromAccountId === data.toAccountId) {
641 Toast.warning('حساب مبدأ و مقصد نباید یکی باشند');
642 return;
643 }
644 }
645
646 const related=cache.invoices.find(x=>x.id===data.refInvoiceId);
647 if(related && ['sale_return','purchase_return'].includes(related.kind)) {
648 data.reasonCode=document.getElementById('txReturnReason')?.value||'';
649 if(!['goods_return','quality_issue','pricing_dispute'].includes(data.reasonCode)) {
650 Toast.warning('برای تسویه مرجوعی دلیل را انتخاب کنید');
651 return;
652 }
653 Modal.confirm({
654 title: type==='payment'?'تأیید بازپرداخت مرجوعی':'تأیید دریافت وجه مرجوعی',
655 message: 'آیا مبلغ '+Formatters.number(data.amount)+' ریال برای مرجوعی انتخاب‌شده تأیید می‌شود؟',
656 confirmText: 'تأیید و ثبت',
657 danger: type==='payment',
658 onConfirm: () => this._commitTransaction(type,{...data,explicitlyApproved:true})
659 });
660 return;
661 }
662 await this._commitTransaction(type,data);
663 }
664
665 async _commitTransaction(type,data) {
666 try {
667 await TreasuryController.createTransaction(data);
668 Toast.success(TreasuryController.getTypeLabel(type) + ' ثبت شد');
669 Modal.close();
670 await this.reload();
671 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
672 } catch (err) {
673 Toast.error('خطا: ' + err.message);
674 }
675 }
676
677 async deleteTransaction(id) {
678 Modal.confirm({
679 title: 'حذف تراکنش',
680 message: 'آیا از حذف این تراکنش مطمئن هستید؟ موجودی حساب به‌روزرسانی می‌شود.',
681 confirmText: 'حذف',
682 danger: true,
683 onConfirm: async () => {
684 await TreasuryController.deleteTransaction(id);
685 Toast.success('تراکنش حذف شد');
686 await this.reload();
687 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
688 }
689 });
690 }
691
692 _todayJalali() {
693 const d = new Date();
694 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
695 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
696 let jy = (gy <= 1600) ? 0 : 979;
697 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
698 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
699 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];
700 jy += 33 * Math.floor(days / 12053);
701 days %= 12053;
702 jy += 4 * Math.floor(days / 1461);
703 days %= 1461;
704 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
705 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
706 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
707 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
708 }
709
710 _esc(s) {
711 if (!s) return '';
712 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
713 }
714 }
715
716 export const TreasuryView = new TreasuryViewImpl();
717 window.TreasuryView = TreasuryView;