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

perf/a08-paginated-reports-20261101
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 504 lines 24.4 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 = this._esc(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">${this._esc(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>${this._esc(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(${this._esc(JSON.stringify(String(c.id ?? '')))})">🔄</button>
111 <button class="icon-btn-sm" title="ویرایش" onclick="window.ChequesView.editCheque(${this._esc(JSON.stringify(String(c.id ?? '')))})">✏️</button>
112 <button class="icon-btn-sm danger" title="حذف" onclick="window.ChequesView.deleteCheque(${this._esc(JSON.stringify(String(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="جستجو بر اساس طرف حساب، صیادی یا بانک..." aria-label="جستجوی چک" value="${this._esc(filter.search)}" oninput="window.ChequesView._onSearch(this.value)" />
124 </div>
125 <select class="form-control" style="width:auto;min-width:130px" aria-label="نوع چک" 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" aria-label="وضعیت چک" 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 cheques-table-scroll" tabindex="0" role="region"
141 aria-label="جدول چک‌ها؛ برای مشاهده ستون‌های بیشتر پیمایش افقی کنید">
142 <table>
143 <thead>
144 <tr>
145 <th style="width:110px">نوع</th>
146 <th>طرف حساب</th>
147 <th style="width:160px">شماره صیادی</th>
148 <th style="width:110px">بانک</th>
149 <th style="width:140px">مبلغ</th>
150 <th style="width:170px">سررسید</th>
151 <th style="width:100px">تاریخ صدور</th>
152 <th style="width:110px">وضعیت</th>
153 <th style="width:130px">عملیات</th>
154 </tr>
155 </thead>
156 <tbody>${rows}</tbody>
157 </table>
158 </div>
159 `;
160 }
161
162 _onSearch(val) {
163 filter.search = val;
164 document.getElementById('cheques-content').innerHTML = this.renderContent();
165 const input = document.querySelector('#cheques-content input[type="text"]');
166 if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
167 }
168
169 _onFilter(key, val) {
170 filter[key] = val;
171 document.getElementById('cheques-content').innerHTML = this.renderContent();
172 }
173
174 // ============================================================
175 // فرم چک
176 // ============================================================
177 async openChequeModal(chequeId = null) {
178 const cheque = chequeId ? await ChequeController.get(chequeId) : null;
179 const isEdit = !!cheque;
180 const d = cheque || {
181 direction: 'inbound',
182 contactId: null,
183 sayadNumber: '',
184 bankName: '',
185 branchName: '',
186 accountNumber: '',
187 holderName: '',
188 amount: 0,
189 issueDate: this._todayJalali(),
190 dueDate: this._todayJalali(),
191 description: ''
192 };
193
194 const contactOptions = cache.contacts.map(c =>
195 `<option value="${this._esc(c.id)}" ${d.contactId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
196 ).join('');
197
198 const body = `
199 <div class="form-row">
200 <div class="form-group">
201 <label class="form-label">نوع چک <span class="req">*</span></label>
202 <select class="form-control" id="chqDirection">
203 <option value="inbound" ${d.direction === 'inbound' ? 'selected' : ''}>دریافتی (از مشتری)</option>
204 <option value="outbound" ${d.direction === 'outbound' ? 'selected' : ''}>پرداختی (به تامین‌کننده)</option>
205 </select>
206 </div>
207 <div class="form-group">
208 <label class="form-label">طرف حساب</label>
209 <select class="form-control" id="chqContact">
210 <option value="">— انتخاب کنید —</option>
211 ${contactOptions}
212 </select>
213 </div>
214 </div>
215
216 <div class="form-row">
217 <div class="form-group">
218 <label class="form-label">شماره صیادی (۱۶ رقم) <span class="req">*</span></label>
219 <input type="text" class="form-control" id="chqSayad" value="${this._esc(d.sayadNumber)}" maxlength="16" placeholder="۱۶ رقم" />
220 </div>
221 <div class="form-group">
222 <label class="form-label">مبلغ (ریال) <span class="req">*</span></label>
223 <input type="text" inputmode="numeric" class="form-control" id="chqAmount" value="${NumberInput.format(d.amount || 0)}" />
224 </div>
225 </div>
226
227 <div class="form-row">
228 <div class="form-group">
229 <label class="form-label">بانک</label>
230 <input type="text" class="form-control" id="chqBank" value="${this._esc(d.bankName)}" placeholder="مثلاً ملی" />
231 </div>
232 <div class="form-group">
233 <label class="form-label">شعبه</label>
234 <input type="text" class="form-control" id="chqBranch" value="${this._esc(d.branchName)}" />
235 </div>
236 </div>
237
238 <div class="form-row">
239 <div class="form-group">
240 <label class="form-label">شماره حساب</label>
241 <input type="text" class="form-control" id="chqAccount" value="${this._esc(d.accountNumber)}" />
242 </div>
243 <div class="form-group">
244 <label class="form-label">نام صاحب حساب</label>
245 <input type="text" class="form-control" id="chqHolder" value="${this._esc(d.holderName)}" />
246 </div>
247 </div>
248
249 <div class="form-row">
250 <div class="form-group">
251 <label class="form-label">تاریخ صدور (شمسی)</label>
252 <input type="text" class="form-control" id="chqIssueDate" value="${this._esc(d.issueDate)}" placeholder="1405/06/27" />
253 </div>
254 <div class="form-group">
255 <label class="form-label">تاریخ سررسید (شمسی) <span class="req">*</span></label>
256 <input type="text" class="form-control" id="chqDueDate" value="${this._esc(d.dueDate)}" placeholder="1405/06/27" />
257 </div>
258 </div>
259
260 <div class="form-group">
261 <label class="form-label">توضیحات</label>
262 <textarea class="form-control" id="chqDescription" rows="2">${this._esc(d.description)}</textarea>
263 </div>
264 `;
265
266 const footer = `
267 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
268 <button class="btn" onclick="window.ChequesView.saveCheque(${isEdit ? this._esc(JSON.stringify(String(chequeId ?? ''))) : 'null'})">💾 ذخیره</button>
269 `;
270
271 Modal.open({ title: isEdit ? 'ویرایش چک' : 'چک جدید', body, footer, size: 'md' });
272 }
273
274 async saveCheque(id) {
275 const contactId = document.getElementById('chqContact').value || null;
276 const contact = contactId ? cache.contacts.find(c => c.id === contactId) : null;
277
278 const data = {
279 direction: document.getElementById('chqDirection').value,
280 contactId,
281 contactName: contact?.name || '',
282 sayadNumber: document.getElementById('chqSayad').value,
283 bankName: document.getElementById('chqBank').value,
284 branchName: document.getElementById('chqBranch').value,
285 accountNumber: document.getElementById('chqAccount').value,
286 holderName: document.getElementById('chqHolder').value,
287 amount: NumberInput.parseStrict(document.getElementById('chqAmount')),
288 issueDate: document.getElementById('chqIssueDate').value,
289 dueDate: document.getElementById('chqDueDate').value,
290 description: document.getElementById('chqDescription').value
291 };
292
293 if (!data.sayadNumber.trim()) { Toast.warning('شماره صیادی الزامی است'); return; }
294 if (data.amount <= 0) { Toast.warning('مبلغ معتبر نیست'); return; }
295 if (!data.dueDate.trim()) { Toast.warning('سررسید الزامی است'); return; }
296
297 try {
298 if (id) {
299 await ChequeController.update(id, data);
300 Toast.success('چک ویرایش شد');
301 } else {
302 await ChequeController.create(data);
303 Toast.success('چک ثبت شد');
304 }
305 Modal.close();
306 await this.reload();
307 document.getElementById('cheques-content').innerHTML = this.renderContent();
308 } catch (err) {
309 Toast.error('خطا: ' + err.message);
310 }
311 }
312
313 async editCheque(id) {
314 await this.openChequeModal(id);
315 }
316
317 async changeStatus(id) {
318 const cheque = cache.cheques.find(c => c.id === id);
319 if (!cheque) return;
320 if(cheque.financePosted && cheque.status!=='pending') {
321 Toast.warning('چک دارای سند مالی قبلاً تعیین تکلیف شده؛ اصلاح آن نیازمند سند مستقل است');
322 return;
323 }
324 cache.accounts=(await TreasuryController.getAccounts())
325 .filter(x=>x.isActive!==false && !!x.ledgerAccountId);
326
327 const statuses = [
328 { value: 'pending', label: 'در جریان' },
329 { value: 'cleared', label: 'وصول شده' },
330 { value: 'bounced', label: 'برگشتی' },
331 { value: 'returned', label: 'عودت داده شده' },
332 ...(cheque.direction === 'inbound'
333 ? [{ value: 'spent', label: 'خرج شده (به شخص دیگر واگذار شد)' }] : [])
334 ];
335 const eligibleEndorsees=cache.contacts.filter(c=>c.id!==cheque.contactId);
336 const endorseeOptions=eligibleEndorsees.map(c=>
337 `<option value="${this._esc(c.id)}">${this._esc(c.name)}</option>`).join('');
338 const accountOptions=cache.accounts.map(a=>
339 `<option value="${this._esc(a.id)}">${this._esc(a.name)}</option>`).join('');
340
341 const body = `
342 <p style="font-size:13px;margin-bottom:14px;color:var(--text-muted)">وضعیت فعلی: <strong>${ChequeController.getStatusLabel(cheque.status)}</strong></p>
343 <div class="form-group">
344 <label class="form-label">وضعیت جدید</label>
345 <select class="form-control" id="newStatus" onchange="window.ChequesView._onChequeStatusSelection()">
346 ${statuses.map(s => `<option value="${s.value}" ${cheque.status === s.value ? 'selected' : ''}>${s.label}</option>`).join('')}
347 </select>
348 </div>
349 ${cheque.financePosted ? `
350 <div class="form-group" id="chqClearingAccountGroup" style="display:none">
351 <label class="form-label">حساب بانک یا صندوق وصول <span class="req">*</span></label>
352 <select class="form-control" id="chqClearingAccount">
353 <option value="">— حساب وصول را انتخاب کنید —</option>
354 ${accountOptions}
355 </select>
356 <small class="form-hint">وجه فقط به همین حساب وارد یا از آن خارج می‌شود.</small>
357 </div>` : ''}
358 ${cheque.financePosted && cheque.direction === 'inbound' ? `
359 <div class="form-group" id="chqEndorseeGroup" style="display:none">
360 <label class="form-label">دریافت‌کننده واگذاری <span class="req">*</span></label>
361 <select class="form-control" id="chqEndorsee">
362 <option value="">— شخص ثالث را انتخاب کنید —</option>
363 ${endorseeOptions}
364 </select>
365 <small class="form-hint">سند حساب‌های پرداختنی به نام این شخص ثبت می‌شود، نه صادرکننده چک.</small>
366 </div>` : ''}
367 ${cheque.financePosted ? `
368 <div class="form-group">
369 <label class="form-label">تاریخ ثبت رویداد مالی <span class="req">*</span></label>
370 <input type="text" class="form-control" id="chqEventDate"
371 value="${this._todayJalali()}" placeholder="1405/07/29" />
372 <small class="form-hint">تاریخ ثبت باید در دوره مالی باز باشد؛ تاریخ سررسید چک تغییر نمی‌کند.</small>
373 </div>` : ''}
374 `;
375 const footer = `
376 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
377 <button class="btn" onclick="window.ChequesView._applyStatusChange(${this._esc(JSON.stringify(String(id ?? '')))})">اعمال</button>
378 `;
379 Modal.open({ title: 'تغییر وضعیت چک', body, footer, size: 'sm' });
380 this._onChequeStatusSelection();
381 }
382
383 _onChequeStatusSelection() {
384 const status=document.getElementById('newStatus')?.value;
385 const group=document.getElementById('chqEndorseeGroup');
386 if(group) group.style.display=status==='spent'?'':'none';
387 const clearing=document.getElementById('chqClearingAccountGroup');
388 if(clearing) clearing.style.display=status==='cleared'?'':'none';
389 }
390
391 async _applyStatusChange(id) {
392 const status=document.getElementById('newStatus').value;
393 const eventDate=document.getElementById('chqEventDate')?.value.trim();
394 const options=eventDate===undefined?{}:{date:eventDate};
395 if(status==='cleared' && document.getElementById('chqClearingAccount')) {
396 const accountId=document.getElementById('chqClearingAccount').value;
397 if(!accountId) { Toast.warning('برای وصول چک، حساب بانک یا صندوق را انتخاب کنید'); return; }
398 const bank=cache.accounts.find(a=>a.id===accountId);
399 const cheque=cache.cheques.find(c=>c.id===id);
400 Modal.confirm({
401 title:'تأیید وصول چک',
402 message:`وصول چک ${this._esc(cheque?.chequeNumber||cheque?.sayadNumber||id)} به مبلغ ${Formatters.money(cheque?.amount||0)} در حساب «${this._esc(bank?.name||'')}» ثبت شود؟ این ثبت مالی قطعی است.`,
403 confirmText:'تأیید و ثبت وصول',
404 danger:true,
405 onConfirm:()=>this._commitStatusChange(id,status,{
406 ...options,accountId,explicitlyApproved:true
407 })
408 });
409 return;
410 }
411 if(status==='spent' && document.getElementById('chqEndorsee')) {
412 const endorseeContactId=document.getElementById('chqEndorsee').value;
413 if(!endorseeContactId) { Toast.warning('دریافت‌کننده واگذاری چک را انتخاب کنید'); return; }
414 const recipient=cache.contacts.find(c=>c.id===endorseeContactId);
415 const cheque=cache.cheques.find(c=>c.id===id);
416 Modal.confirm({
417 title:'تأیید واگذاری چک',
418 message:`واگذاری چک ${this._esc(cheque?.chequeNumber||cheque?.sayadNumber||id)} به «${this._esc(recipient?.name||'')}» به مبلغ ${Formatters.money(cheque?.amount||0)} ثبت شود؟ این ثبت مالی قطعی است.`,
419 confirmText:'تأیید و ثبت واگذاری',
420 danger:true,
421 onConfirm:()=>this._commitStatusChange(id,status,{
422 ...options,endorseeContactId,explicitlyApproved:true
423 })
424 });
425 return;
426 }
427 await this._commitStatusChange(id,status,options);
428 }
429
430 async _commitStatusChange(id,status,options) {
431 try {
432 await ChequeController.changeStatus(id,status,options);
433 Toast.success('وضعیت چک تغییر کرد');
434 Modal.close();
435 await this.reload();
436 document.getElementById('cheques-content').innerHTML=this.renderContent();
437 } catch(err) {
438 Toast.error('خطا: '+err.message);
439 }
440 }
441
442 async deleteCheque(id) {
443 const c = cache.cheques.find(x => x.id === id);
444 Modal.confirm({
445 title: 'حذف چک',
446 message: `آیا از حذف چک ${Formatters.toPersianDigits(c?.sayadNumber || '')} مطمئن هستید؟`,
447 confirmText: 'حذف',
448 danger: true,
449 onConfirm: async () => {
450 await ChequeController.delete(id);
451 Toast.success('چک حذف شد');
452 await this.reload();
453 document.getElementById('cheques-content').innerHTML = this.renderContent();
454 }
455 });
456 }
457
458 _todayJalali() {
459 const d = new Date();
460 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
461 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
462 let jy = (gy <= 1600) ? 0 : 979;
463 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
464 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
465 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];
466 jy += 33 * Math.floor(days / 12053);
467 days %= 12053;
468 jy += 4 * Math.floor(days / 1461);
469 days %= 1461;
470 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
471 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
472 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
473 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
474 }
475
476 _parseJalali(str) {
477 if (!str) return new Date();
478 const parts = str.split('/').map(Number);
479 if (parts.length !== 3) return new Date();
480 const [jy, jm, jd] = parts;
481 let gy = (jy <= 979) ? 621 : 1600;
482 let jy2 = jy - (jy <= 979 ? 0 : 979);
483 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);
484 gy += 400 * Math.floor(days / 146097);
485 days %= 146097;
486 if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
487 gy += 4 * Math.floor(days / 1461);
488 days %= 1461;
489 if (days > 365) { gy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
490 let gd = days + 1;
491 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];
492 let gm = 0;
493 for (gm = 0; gm < 13 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
494 return new Date(gy, gm - 1, gd);
495 }
496
497 _esc(s) {
498 if (!s) return '';
499 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
500 }
501 }
502
503 export const ChequesView = new ChequesViewImpl();
504 window.ChequesView = ChequesView;