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

fix/a01-cheque-clearance-explicit-account-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 503 lines 23.9 KB
Raw
1 // ============================================================
2 // ChequesView — صفحه‌ی مدیریت چک‌ها
3 // ============================================================
4
5 import { NumberInput } from '../utils/NumberInput.js';
6 import { ChequeController } from '../controllers/ChequeController.js';
7 import { ContactController } from '../controllers/ContactController.js';
8 import { TreasuryController } from '../controllers/TreasuryController.js';
9 import { Modal } from '../core/Modal.js';
10 import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12
13 let filter = { search: '', direction: '', status: '' };
14 let cache = { cheques: [], contacts: [], accounts: [], stats: {} };
15
16 class ChequesViewImpl {
17 async render() {
18 await this.reload();
19 return `
20 <div class="page-title">
21 <h2>چک‌ها</h2>
22 <p>مدیریت چک‌های دریافتی و پرداختی با شماره صیادی</p>
23 </div>
24
25 <div class="grid-kpi">
26 <div class="card" style="margin:0">
27 <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">کل چک‌ها</div>
28 <div style="font-size:20px;font-weight:800">${Formatters.number(cache.stats.total || 0)}</div>
29 <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.toPersianDigits(cache.stats.pending || 0)} در جریان</div>
30 </div>
31 <div class="card" style="margin:0">
32 <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">چک‌های دریافتی</div>
33 <div style="font-size:18px;font-weight:800;color:var(--success)">${Formatters.money(cache.stats.inboundAmount || 0)}</div>
34 <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.stats.inbound || 0)} فقره</div>
35 </div>
36 <div class="card" style="margin:0">
37 <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">چک‌های پرداختی</div>
38 <div style="font-size:18px;font-weight:800;color:var(--danger)">${Formatters.money(cache.stats.outboundAmount || 0)}</div>
39 <div style="font-size:11px;color:var(--text-muted);margin-top:4px">${Formatters.number(cache.stats.outbound || 0)} فقره</div>
40 </div>
41 <div class="card" style="margin:0">
42 <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">مانده در جریان</div>
43 <div style="font-size:18px;font-weight:800;color:var(--warning)">${Formatters.money(cache.stats.pendingAmount || 0)}</div>
44 <div style="font-size:11px;color:var(--text-muted);margin-top:4px">جمع مبلغ چک‌های باز</div>
45 </div>
46 </div>
47
48 <div id="cheques-content">${this.renderContent()}</div>
49 `;
50 }
51
52 onMount() {
53 window.ChequesView = this;
54 }
55
56 async reload() {
57 cache.cheques = await ChequeController.getAll();
58 cache.contacts = await ContactController.getAll();
59 cache.accounts = (await TreasuryController.getAccounts())
60 .filter(x=>x.isActive!==false && !!x.ledgerAccountId);
61 cache.stats = await ChequeController.getStats();
62 }
63
64 renderContent() {
65 let list = cache.cheques;
66 if (filter.search) {
67 const q = filter.search.toLowerCase();
68 list = list.filter(c =>
69 (c.contactName || '').toLowerCase().includes(q) ||
70 (c.sayadNumber || '').includes(q) ||
71 (c.bankName || '').toLowerCase().includes(q)
72 );
73 }
74 if (filter.direction) list = list.filter(c => c.direction === filter.direction);
75 if (filter.status) list = list.filter(c => c.status === filter.status);
76
77 const rows = list.length === 0
78 ? `<tr><td colspan="9"><div class="empty-state"><div class="icon">💳</div><h3>هیچ چکی ثبت نشده</h3><p>اولین چک دریافتی یا پرداختی خود را ثبت کنید</p><button class="btn" onclick="window.ChequesView.openChequeModal()">➕ چک جدید</button></div></td></tr>`
79 : list.map(c => {
80 const today = new Date();
81 const due = new Date(c.dueDate ? this._parseJalali(c.dueDate) : new Date());
82 const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
83 const isOverdue = diffDays < 0 && c.status === 'pending';
84 const isSoon = diffDays >= 0 && diffDays <= 7 && c.status === 'pending';
85
86 let dueDisplay = Formatters.toPersianDigits(c.dueDate || '—');
87 if (isOverdue) dueDisplay += ` <span class="badge badge-danger" style="font-size:9px">${Formatters.toPersianDigits(Math.abs(diffDays))} روز گذشته</span>`;
88 else if (isSoon) dueDisplay += ` <span class="badge badge-warning" style="font-size:9px">${Formatters.toPersianDigits(diffDays)} روز مانده</span>`;
89
90 return `
91 <tr>
92 <td>
93 <span class="badge ${c.direction === 'inbound' ? 'badge-success' : 'badge-danger'}">
94 ${c.direction === 'inbound' ? '📥 دریافتی' : '📤 پرداختی'}
95 </span>
96 </td>
97 <td><strong>${this._esc(c.contactName || '—')}</strong></td>
98 <td style="font-family:monospace;font-size:11.5px">${Formatters.toPersianDigits(c.sayadNumber || '—')}</td>
99 <td>${this._esc(c.bankName || '—')}</td>
100 <td style="font-weight:700">${Formatters.money(c.amount)}</td>
101 <td>${dueDisplay}</td>
102 <td>${Formatters.toPersianDigits(c.issueDate || '—')}</td>
103 <td>
104 <span class="badge ${ChequeController.getStatusClass(c.status)}">
105 ${ChequeController.getStatusLabel(c.status)}
106 </span>
107 </td>
108 <td>
109 <div class="row-actions">
110 <button class="icon-btn-sm" title="تغییر وضعیت" onclick="window.ChequesView.changeStatus('${c.id}')">🔄</button>
111 <button class="icon-btn-sm" title="ویرایش" onclick="window.ChequesView.editCheque('${c.id}')">✏️</button>
112 <button class="icon-btn-sm danger" title="حذف" onclick="window.ChequesView.deleteCheque('${c.id}')">🗑️</button>
113 </div>
114 </td>
115 </tr>
116 `;
117 }).join('');
118
119 return `
120 <div class="toolbar">
121 <div class="search-input-wrap">
122 <span class="icon">🔍</span>
123 <input type="text" class="form-control" placeholder="جستجو بر اساس طرف حساب، صیادی یا بانک..." value="${this._esc(filter.search)}" oninput="window.ChequesView._onSearch(this.value)" />
124 </div>
125 <select class="form-control" style="width:auto;min-width:130px" onchange="window.ChequesView._onFilter('direction', this.value)">
126 <option value="">همه انواع</option>
127 <option value="inbound" ${filter.direction === 'inbound' ? 'selected' : ''}>دریافتی</option>
128 <option value="outbound" ${filter.direction === 'outbound' ? 'selected' : ''}>پرداختی</option>
129 </select>
130 <select class="form-control" style="width:auto;min-width:130px" onchange="window.ChequesView._onFilter('status', this.value)">
131 <option value="">همه وضعیت‌ها</option>
132 <option value="pending" ${filter.status === 'pending' ? 'selected' : ''}>در جریان</option>
133 <option value="cleared" ${filter.status === 'cleared' ? 'selected' : ''}>وصول شده</option>
134 <option value="bounced" ${filter.status === 'bounced' ? 'selected' : ''}>برگشتی</option>
135 <option value="returned" ${filter.status === 'returned' ? 'selected' : ''}>عودت داده شده</option>
136 </select>
137 <button class="btn" onclick="window.ChequesView.openChequeModal()">➕ چک جدید</button>
138 </div>
139
140 <div class="table-wrap">
141 <table>
142 <thead>
143 <tr>
144 <th style="width:110px">نوع</th>
145 <th>طرف حساب</th>
146 <th style="width:160px">شماره صیادی</th>
147 <th style="width:110px">بانک</th>
148 <th style="width:140px">مبلغ</th>
149 <th style="width:170px">سررسید</th>
150 <th style="width:100px">تاریخ صدور</th>
151 <th style="width:110px">وضعیت</th>
152 <th style="width:130px">عملیات</th>
153 </tr>
154 </thead>
155 <tbody>${rows}</tbody>
156 </table>
157 </div>
158 `;
159 }
160
161 _onSearch(val) {
162 filter.search = val;
163 document.getElementById('cheques-content').innerHTML = this.renderContent();
164 const input = document.querySelector('#cheques-content input[type="text"]');
165 if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
166 }
167
168 _onFilter(key, val) {
169 filter[key] = val;
170 document.getElementById('cheques-content').innerHTML = this.renderContent();
171 }
172
173 // ============================================================
174 // فرم چک
175 // ============================================================
176 async openChequeModal(chequeId = null) {
177 const cheque = chequeId ? await ChequeController.get(chequeId) : null;
178 const isEdit = !!cheque;
179 const d = cheque || {
180 direction: 'inbound',
181 contactId: null,
182 sayadNumber: '',
183 bankName: '',
184 branchName: '',
185 accountNumber: '',
186 holderName: '',
187 amount: 0,
188 issueDate: this._todayJalali(),
189 dueDate: this._todayJalali(),
190 description: ''
191 };
192
193 const contactOptions = cache.contacts.map(c =>
194 `<option value="${c.id}" ${d.contactId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
195 ).join('');
196
197 const body = `
198 <div class="form-row">
199 <div class="form-group">
200 <label class="form-label">نوع چک <span class="req">*</span></label>
201 <select class="form-control" id="chqDirection">
202 <option value="inbound" ${d.direction === 'inbound' ? 'selected' : ''}>دریافتی (از مشتری)</option>
203 <option value="outbound" ${d.direction === 'outbound' ? 'selected' : ''}>پرداختی (به تامین‌کننده)</option>
204 </select>
205 </div>
206 <div class="form-group">
207 <label class="form-label">طرف حساب</label>
208 <select class="form-control" id="chqContact">
209 <option value="">— انتخاب کنید —</option>
210 ${contactOptions}
211 </select>
212 </div>
213 </div>
214
215 <div class="form-row">
216 <div class="form-group">
217 <label class="form-label">شماره صیادی (۱۶ رقم) <span class="req">*</span></label>
218 <input type="text" class="form-control" id="chqSayad" value="${this._esc(d.sayadNumber)}" maxlength="16" placeholder="۱۶ رقم" />
219 </div>
220 <div class="form-group">
221 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
222 <input type="text" inputmode="numeric" class="form-control" id="chqAmount" value="${NumberInput.format(d.amount || 0)}" />
223 </div>
224 </div>
225
226 <div class="form-row">
227 <div class="form-group">
228 <label class="form-label">بانک</label>
229 <input type="text" class="form-control" id="chqBank" value="${this._esc(d.bankName)}" placeholder="مثلاً ملی" />
230 </div>
231 <div class="form-group">
232 <label class="form-label">شعبه</label>
233 <input type="text" class="form-control" id="chqBranch" value="${this._esc(d.branchName)}" />
234 </div>
235 </div>
236
237 <div class="form-row">
238 <div class="form-group">
239 <label class="form-label">شماره حساب</label>
240 <input type="text" class="form-control" id="chqAccount" value="${this._esc(d.accountNumber)}" />
241 </div>
242 <div class="form-group">
243 <label class="form-label">نام صاحب حساب</label>
244 <input type="text" class="form-control" id="chqHolder" value="${this._esc(d.holderName)}" />
245 </div>
246 </div>
247
248 <div class="form-row">
249 <div class="form-group">
250 <label class="form-label">تاریخ صدور (شمسی)</label>
251 <input type="text" class="form-control" id="chqIssueDate" value="${this._esc(d.issueDate)}" placeholder="1405/06/27" />
252 </div>
253 <div class="form-group">
254 <label class="form-label">تاریخ سررسید (شمسی) <span class="req">*</span></label>
255 <input type="text" class="form-control" id="chqDueDate" value="${this._esc(d.dueDate)}" placeholder="1405/06/27" />
256 </div>
257 </div>
258
259 <div class="form-group">
260 <label class="form-label">توضیحات</label>
261 <textarea class="form-control" id="chqDescription" rows="2">${this._esc(d.description)}</textarea>
262 </div>
263 `;
264
265 const footer = `
266 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
267 <button class="btn" onclick="window.ChequesView.saveCheque(${isEdit ? `'${chequeId}'` : 'null'})">💾 ذخیره</button>
268 `;
269
270 Modal.open({ title: isEdit ? 'ویرایش چک' : 'چک جدید', body, footer, size: 'md' });
271 }
272
273 async saveCheque(id) {
274 const contactId = document.getElementById('chqContact').value || null;
275 const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
276
277 const data = {
278 direction: document.getElementById('chqDirection').value,
279 contactId,
280 contactName: contact?.name || '',
281 sayadNumber: document.getElementById('chqSayad').value,
282 bankName: document.getElementById('chqBank').value,
283 branchName: document.getElementById('chqBranch').value,
284 accountNumber: document.getElementById('chqAccount').value,
285 holderName: document.getElementById('chqHolder').value,
286 amount: NumberInput.parse(document.getElementById('chqAmount').value),
287 issueDate: document.getElementById('chqIssueDate').value,
288 dueDate: document.getElementById('chqDueDate').value,
289 description: document.getElementById('chqDescription').value
290 };
291
292 if (!data.sayadNumber.trim()) { Toast.warning('شماره صیادی الزامی است'); return; }
293 if (data.amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
294 if (!data.dueDate.trim()) { Toast.warning('سررسید الزامی است'); return; }
295
296 try {
297 if (id) {
298 await ChequeController.update(id, data);
299 Toast.success('چک ویرایش شد');
300 } else {
301 await ChequeController.create(data);
302 Toast.success('چک ثبت شد');
303 }
304 Modal.close();
305 await this.reload();
306 document.getElementById('cheques-content').innerHTML = this.renderContent();
307 } catch (err) {
308 Toast.error('خطا: ' + err.message);
309 }
310 }
311
312 async editCheque(id) {
313 await this.openChequeModal(id);
314 }
315
316 async changeStatus(id) {
317 const cheque = cache.cheques.find(c => c.id === id);
318 if (!cheque) return;
319 if(cheque.financePosted && cheque.status!=='pending') {
320 Toast.warning('چک دارای سند مالی قبلاً تعیین تکلیف شده؛ اصلاح آن نیازمند سند مستقل است');
321 return;
322 }
323 cache.accounts=(await TreasuryController.getAccounts())
324 .filter(x=>x.isActive!==false && !!x.ledgerAccountId);
325
326 const statuses = [
327 { value: 'pending', label: 'در جریان' },
328 { value: 'cleared', label: 'وصول شده' },
329 { value: 'bounced', label: 'برگشتی' },
330 { value: 'returned', label: 'عودت داده شده' },
331 ...(cheque.direction === 'inbound'
332 ? [{ value: 'spent', label: 'خرج شده (به شخص دیگر واگذار شد)' }] : [])
333 ];
334 const eligibleEndorsees=cache.contacts.filter(c=>c.id!==cheque.contactId);
335 const endorseeOptions=eligibleEndorsees.map(c=>
336 `<option value="${this._esc(c.id)}">${this._esc(c.name)}</option>`).join('');
337 const accountOptions=cache.accounts.map(a=>
338 `<option value="${this._esc(a.id)}">${this._esc(a.name)}</option>`).join('');
339
340 const body = `
341 <p style="font-size:13px;margin-bottom:14px;color:var(--text-muted)">وضعیت فعلی: <strong>${ChequeController.getStatusLabel(cheque.status)}</strong></p>
342 <div class="form-group">
343 <label class="form-label">وضعیت جدید</label>
344 <select class="form-control" id="newStatus" onchange="window.ChequesView._onChequeStatusSelection()">
345 ${statuses.map(s => `<option value="${s.value}" ${cheque.status === s.value ? 'selected' : ''}>${s.label}</option>`).join('')}
346 </select>
347 </div>
348 ${cheque.financePosted ? `
349 <div class="form-group" id="chqClearingAccountGroup" style="display:none">
350 <label class="form-label">حساب بانک یا صندوق وصول <span class="req">*</span></label>
351 <select class="form-control" id="chqClearingAccount">
352 <option value="">— حساب وصول را انتخاب کنید —</option>
353 ${accountOptions}
354 </select>
355 <small class="form-hint">وجه فقط به همین حساب وارد یا از آن خارج می‌شود.</small>
356 </div>` : ''}
357 ${cheque.financePosted && cheque.direction === 'inbound' ? `
358 <div class="form-group" id="chqEndorseeGroup" style="display:none">
359 <label class="form-label">دریافت‌کننده واگذاری <span class="req">*</span></label>
360 <select class="form-control" id="chqEndorsee">
361 <option value="">— شخص ثالث را انتخاب کنید —</option>
362 ${endorseeOptions}
363 </select>
364 <small class="form-hint">سند حساب‌های پرداختنی به نام این شخص ثبت می‌شود، نه صادرکننده چک.</small>
365 </div>` : ''}
366 ${cheque.financePosted ? `
367 <div class="form-group">
368 <label class="form-label">تاریخ ثبت رویداد مالی <span class="req">*</span></label>
369 <input type="text" class="form-control" id="chqEventDate"
370 value="${this._todayJalali()}" placeholder="1405/07/29" />
371 <small class="form-hint">تاریخ ثبت باید در دوره مالی باز باشد؛ تاریخ سررسید چک تغییر نمی‌کند.</small>
372 </div>` : ''}
373 `;
374 const footer = `
375 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
376 <button class="btn" onclick="window.ChequesView._applyStatusChange('${id}')">اعمال</button>
377 `;
378 Modal.open({ title: 'تغییر وضعیت چک', body, footer, size: 'sm' });
379 this._onChequeStatusSelection();
380 }
381
382 _onChequeStatusSelection() {
383 const status=document.getElementById('newStatus')?.value;
384 const group=document.getElementById('chqEndorseeGroup');
385 if(group) group.style.display=status==='spent'?'':'none';
386 const clearing=document.getElementById('chqClearingAccountGroup');
387 if(clearing) clearing.style.display=status==='cleared'?'':'none';
388 }
389
390 async _applyStatusChange(id) {
391 const status=document.getElementById('newStatus').value;
392 const eventDate=document.getElementById('chqEventDate')?.value.trim();
393 const options=eventDate===undefined?{}:{date:eventDate};
394 if(status==='cleared' && document.getElementById('chqClearingAccount')) {
395 const accountId=document.getElementById('chqClearingAccount').value;
396 if(!accountId) { Toast.warning('برای وصول چک، حساب بانک یا صندوق را انتخاب کنید'); return; }
397 const bank=cache.accounts.find(a=>a.id===accountId);
398 const cheque=cache.cheques.find(c=>c.id===id);
399 Modal.confirm({
400 title:'تأیید وصول چک',
401 message:`وصول چک ${this._esc(cheque?.chequeNumber||cheque?.sayadNumber||id)} به مبلغ ${Formatters.money(cheque?.amount||0)} در حساب «${this._esc(bank?.name||'')}» ثبت شود؟ این ثبت مالی قطعی است.`,
402 confirmText:'تأیید و ثبت وصول',
403 danger:true,
404 onConfirm:()=>this._commitStatusChange(id,status,{
405 ...options,accountId,explicitlyApproved:true
406 })
407 });
408 return;
409 }
410 if(status==='spent' && document.getElementById('chqEndorsee')) {
411 const endorseeContactId=document.getElementById('chqEndorsee').value;
412 if(!endorseeContactId) { Toast.warning('دریافت‌کننده واگذاری چک را انتخاب کنید'); return; }
413 const recipient=cache.contacts.find(c=>c.id===endorseeContactId);
414 const cheque=cache.cheques.find(c=>c.id===id);
415 Modal.confirm({
416 title:'تأیید واگذاری چک',
417 message:`واگذاری چک ${this._esc(cheque?.chequeNumber||cheque?.sayadNumber||id)} به «${this._esc(recipient?.name||'')}» به مبلغ ${Formatters.money(cheque?.amount||0)} ثبت شود؟ این ثبت مالی قطعی است.`,
418 confirmText:'تأیید و ثبت واگذاری',
419 danger:true,
420 onConfirm:()=>this._commitStatusChange(id,status,{
421 ...options,endorseeContactId,explicitlyApproved:true
422 })
423 });
424 return;
425 }
426 await this._commitStatusChange(id,status,options);
427 }
428
429 async _commitStatusChange(id,status,options) {
430 try {
431 await ChequeController.changeStatus(id,status,options);
432 Toast.success('وضعیت چک تغییر کرد');
433 Modal.close();
434 await this.reload();
435 document.getElementById('cheques-content').innerHTML=this.renderContent();
436 } catch(err) {
437 Toast.error('خطا: '+err.message);
438 }
439 }
440
441 async deleteCheque(id) {
442 const c = cache.cheques.find(x => x.id === id);
443 Modal.confirm({
444 title: 'حذف چک',
445 message: `آیا از حذف چک ${Formatters.toPersianDigits(c?.sayadNumber || '')} مطمئن هستید؟`,
446 confirmText: 'حذف',
447 danger: true,
448 onConfirm: async () => {
449 await ChequeController.delete(id);
450 Toast.success('چک حذف شد');
451 await this.reload();
452 document.getElementById('cheques-content').innerHTML = this.renderContent();
453 }
454 });
455 }
456
457 _todayJalali() {
458 const d = new Date();
459 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
460 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
461 let jy = (gy <= 1600) ? 0 : 979;
462 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
463 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
464 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];
465 jy += 33 * Math.floor(days / 12053);
466 days %= 12053;
467 jy += 4 * Math.floor(days / 1461);
468 days %= 1461;
469 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
470 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
471 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
472 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
473 }
474
475 _parseJalali(str) {
476 if (!str) return new Date();
477 const parts = str.split('/').map(Number);
478 if (parts.length !== 3) return new Date();
479 const [jy, jm, jd] = parts;
480 let gy = (jy <= 979) ? 621 : 1600;
481 let jy2 = jy - (jy <= 979 ? 0 : 979);
482 let days = (365 * jy2) + (Math.floor(jy2 / 33) * 8) + Math.floor(((jy2 % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
483 gy += 400 * Math.floor(days / 146097);
484 days %= 146097;
485 if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
486 gy += 4 * Math.floor(days / 1461);
487 days %= 1461;
488 if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
489 let gd = days + 1;
490 const sal_a = [0,31,((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,31,30,31,30,31,31,30,31,30,31];
491 let gm = 0;
492 for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
493 return new Date(gy, gm - 1, gd);
494 }
495
496 _esc(s) {
497 if (!s) return '';
498 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
499 }
500 }
501
502 export const ChequesView = new ChequesViewImpl();
503 window.ChequesView = ChequesView;