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

audit/a01-readonly-invoice-metadata-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 874 lines 41.4 KB
Raw
1 // ============================================================
2 // InvoiceFormView — فرم صدور و ویرایش فاکتور
3 // ============================================================
4
5 import { InvoiceController } from '../controllers/InvoiceController.js';
6 import { ContactController } from '../controllers/ContactController.js';
7 import { ProductController } from '../controllers/ProductController.js';
8 import { Modal } from '../core/Modal.js';
9 import { Toast } from '../core/Toast.js';
10 import { Formatters } from '../utils/Formatters.js';
11 import { numberToWords } from '../utils/NumberToWords.js';
12 import { NumberInput } from '../utils/NumberInput.js';
13 import { SettingsController } from '../controllers/SettingsController.js';
14 import { RetailPostingService } from '../core/RetailPostingService.js';
15 import { lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
16
17 let ctx = {
18 editId: null,
19 data: null,
20 contacts: [],
21 products: [],
22 units: [],
23 invoices: [],
24 warehouses: [],
25 rowCounter: 0
26 };
27
28 class InvoiceFormViewImpl {
29 // ============================================================
30 // باز کردن فرم فاکتور (ایجاد یا ویرایش)
31 // ============================================================
32 async open(invoiceId = null) {
33 ctx.editId = invoiceId;
34 ctx.contacts = await ContactController.getAll();
35 ctx.products = await ProductController.getProducts();
36 ctx.units = await ProductController.getUnits();
37 ctx.invoices = await InvoiceController.getAll();
38 ctx.warehouses = await RetailPostingService.isEnabled() ? await RetailPostingService.warehouses() : [];
39 ctx.rowCounter = 0;
40
41 if (invoiceId) {
42 const existing = await InvoiceController.get(invoiceId);
43 ctx.data = existing;
44 } else {
45 ctx.data = {
46 kind: 'sale',
47 isPreInvoice: false,
48 date: this._todayJalali(),
49 contactId: null,
50 contactName: '',
51 items: [],
52 discountType: 'fixed',
53 discountInput: 0,
54 vatEnabled: false,
55 vatRate: 10,
56 paymentMethod: 'cash',
57 paidAmount: 0,
58 description: ''
59 };
60 }
61
62 ctx.invoiceSettings = await SettingsController.getInvoiceSettings();
63 if (!invoiceId) {
64 ctx.data.number = await InvoiceController.getNextNumber(ctx.data.kind);
65 }
66
67 // اگه فاکتور جدید بدون اقلام، یک ردیف خالی اضافه کن
68 if (!ctx.data.items || ctx.data.items.length === 0) {
69 ctx.data.items = [this._emptyItem()];
70 }
71
72 const body = this._renderFormBody();
73 const footer = this._renderFooter();
74
75 const modal = Modal.open({
76 title: invoiceId ? `ویرایش فاکتور #${ctx.data.number}` : 'صدور فاکتور جدید',
77 body,
78 footer,
79 size: 'lg',
80 onClose: () => { ctx = { editId: null, data: null, contacts: [], products: [], units: [], rowCounter: 0 }; }
81 });
82
83 // بعد از باز شدن مودال، اقلام رو رندر کن
84 setTimeout(() => {
85 this._renderItems();
86 this._recalc();
87 }, 50);
88 }
89
90 _emptyItem() {
91 return {
92 productId: null,
93 productName: '',
94 unit: 'عدد',
95 qty: 1,
96 price: 0,
97 discount: 0,
98 discountType: 'fixed',
99 lineSubtotal: 0,
100 lineTotal: 0
101 };
102 }
103
104 // ============================================================
105 // ساختار فرم
106 // ============================================================
107 _renderFormBody() {
108 const d = ctx.data;
109 const kindOptions = [
110 { value: 'sale', label: 'فاکتور فروش' },
111 { value: 'purchase', label: 'فاکتور خرید' },
112 { value: 'sale_return', label: 'برگشت از فروش' },
113 { value: 'purchase_return', label: 'برگشت از خرید' },
114 { value: 'non_formal', label: 'فاکتور غیررسمی' }
115 ];
116 const kindOpts = kindOptions.map(k =>
117 `<option value="${k.value}" ${d.kind === k.value ? 'selected' : ''}>${k.label}</option>`
118 ).join('');
119
120 const selectedContact = ctx.contacts.find(c => c.id === d.contactId);
121 const selectedContactLabel = selectedContact ? selectedContact.name : (d.contactName || '');
122
123 return `
124 <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:14px">
125 <div class="form-group" style="margin-bottom:0">
126 <label class="form-label">نوع سند</label>
127 <select class="form-control" id="invKind" onchange="window.InvoiceFormView._onKindChange()">${kindOpts}</select>
128 </div>
129 <div class="form-group" style="margin-bottom:0">
130 <label class="form-label">شماره فاکتور</label>
131 <input type="text" class="form-control" id="invNumber" value="${this._esc(d.number || '')}" ${ctx.invoiceSettings?.numberingMode === 'manual' && !ctx.editId ? '' : 'disabled'} style="background:var(--bg)" placeholder="شماره فاکتور" />
132 </div>
133 <div class="form-group" style="margin-bottom:0">
134 <label class="form-label">تاریخ (شمسی)</label>
135 <input type="text" class="form-control" id="invDate" value="${this._esc(d.date)}" placeholder="1405/06/27" />
136 </div>
137 </div>
138
139 ${ctx.warehouses.length ? `<div class="form-group" style="margin-bottom:12px">
140 <label class="form-label">انبار محل گردش کالا</label><select class="form-control" id="invWarehouse">
141 ${ctx.warehouses.map(w=>`<option value="${this._esc(w.id)}" ${(d.warehouseId||ctx.warehouses.find(x=>x.isDefault)?.id)===w.id?'selected':''}>${this._esc(w.name)}</option>`).join('')}
142 </select></div>` : ''}
143 <div class="form-group" id="invOriginalWrap" style="margin-bottom:12px;${['sale_return','purchase_return'].includes(d.kind)?'':'display:none'}">
144 <label class="form-label">شماره فاکتور اولیه (الزامی برای مرجوعی)</label>
145 <select class="form-control" id="invOriginalInvoice">
146 <option value="">انتخاب فاکتور مرجع</option>
147 ${ctx.invoices.filter(i=>['sale','non_formal','purchase'].includes(i.kind)&&!i.isPreInvoice)
148 .map(i=>`<option data-kind="${this._esc(i.kind)}" value="${this._esc(i.id)}" ${d.originalInvoiceId===i.id?'selected':''}>${this._esc('#'+i.number+' — '+(i.contactName||''))}</option>`).join('')}
149 </select></div>
150 <div style="display:grid;grid-template-columns:2fr 1fr;gap:10px;margin-bottom:14px">
151 <div class="form-group" style="margin-bottom:0">
152 <label class="form-label">طرف حساب</label>
153 <div style="display:flex;gap:6px">
154 <div style="position:relative;flex:1;min-width:0">
155 <input type="hidden" id="invContact" value="${this._esc(d.contactId || '')}" />
156 <input type="text" class="form-control" id="invContactSearch" autocomplete="off" value="${this._esc(selectedContactLabel)}" placeholder="جستجوی نام یا کد طرف حساب" onfocus="window.InvoiceFormView._showContactOptions()" oninput="window.InvoiceFormView._showContactOptions(true)" />
157 <div id="invContactOptions" style="display:none;position:absolute;z-index:10010;top:100%;right:0;left:0;max-height:230px;overflow:auto;background:var(--card-bg,#fff);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 20px #0002"></div>
158 </div>
159 <button class="btn btn-secondary" style="min-height:42px;padding:0 12px" onclick="window.InvoiceFormView._openQuickContact()" title="افزودن شخص جدید">➕</button>
160 </div>
161 </div>
162 <div class="form-group" style="margin-bottom:0">
163 <label class="form-label">
164 <input type="checkbox" id="invPreInvoice" ${d.isPreInvoice ? 'checked' : ''} />
165 پیش‌فاکتور
166 </label>
167 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">پیش‌فاکتور، موجودی انبار رو تغییر نمی‌ده</small>
168 </div>
169 </div>
170
171 <div style="margin:14px 0 10px;display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap">
172 <h4 style="font-size:14px;font-weight:700">اقلام فاکتور</h4>
173 <div style="display:flex;gap:6px">
174 <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._openQuickProduct()">➕ کالای جدید</button>
175 <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._addRow()">➕ افزودن ردیف</button>
176 </div>
177 </div>
178
179 <div class="table-wrap" style="overflow:visible">
180 <table>
181 <thead>
182 <tr>
183 <th style="width:36px;text-align:center">#</th>
184 <th style="min-width:200px">کالا / خدمات</th>
185 <th style="width:70px">واحد</th>
186 <th style="width:80px">مقدار</th>
187 <th style="width:130px">قیمت واحد</th>
188 <th style="width:130px">تخفیف</th>
189 <th style="width:140px">جمع</th>
190 <th style="width:40px"></th>
191 </tr>
192 </thead>
193 <tbody id="itemsBody"></tbody>
194 </table>
195 </div>
196
197 <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px">
198 <div class="card" style="margin:0;padding:16px">
199 <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">تخفیف، مالیات و پرداخت</div>
200
201 <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
202 <span style="flex:1;font-size:12.5px">تخفیف کلی</span>
203 <select class="form-control" id="invDiscType" aria-label="نوع تخفیف کل فاکتور" style="width:80px;min-height:34px" onchange="window.InvoiceFormView._onDiscTypeChange()">
204 <option value="fixed" ${d.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
205 <option value="percent" ${d.discountType === 'percent' ? 'selected' : ''}>درصد</option>
206 </select>
207 <input type="text" inputmode="numeric" class="form-control" id="invDiscInput" aria-label="مقدار تخفیف کل فاکتور" style="width:110px;min-height:34px" data-decimals="${d.discountType === 'percent' ? 2 : 0}" value="${NumberInput.format(d.discountInput ?? 0, d.discountType === 'percent' ? 2 : 0)}" oninput="window.InvoiceFormView._recalc()" />
208 </div>
209
210 <div id="vatRow" style="display:${d.kind === 'non_formal' ? 'none' : 'flex'};gap:8px;align-items:center;margin-bottom:10px">
211 <label style="flex:1;font-size:12.5px;display:flex;align-items:center;gap:6px;cursor:pointer">
212 <input type="checkbox" id="invVatEnabled" ${d.vatEnabled ? 'checked' : ''} onchange="window.InvoiceFormView._recalc()" />
213 مالیات ارزش افزوده
214 </label>
215 <input type="text" inputmode="numeric" class="form-control" id="invVatRate" aria-label="درصد مالیات بر ارزش افزوده" style="width:80px;min-height:34px" data-decimals="2" value="${NumberInput.format(d.vatRate ?? 10, 2)}" oninput="window.InvoiceFormView._recalc()" />
216 <span style="font-size:12.5px;color:var(--text-muted)">٪</span>
217 </div>
218
219 <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
220 <span style="flex:1;font-size:12.5px">روش پرداخت</span>
221 <select class="form-control" id="invPayment" aria-label="وضعیت پرداخت فاکتور" style="min-height:34px" onchange="window.InvoiceFormView._onPaymentChange()">
222 <option value="cash" ${d.paymentMethod === 'cash' ? 'selected' : ''}>نقدی</option>
223 <option value="credit" ${d.paymentMethod === 'credit' ? 'selected' : ''}>نسیه</option>
224 <option value="partial" ${d.paymentMethod === 'partial' ? 'selected' : ''}>پرداخت جزئی</option>
225 </select>
226 </div>
227
228 <div id="paidRow" style="display:${d.paymentMethod === 'partial' ? 'flex' : 'none'};gap:8px;align-items:center;margin-bottom:10px">
229 <label for="invPaidAmount" style="flex:1;font-size:12.5px;margin:0">مبلغ پرداخت‌شده</label>
230 <input type="text" inputmode="numeric" class="form-control" id="invPaidAmount" aria-label="مبلغ پرداخت‌شده" style="width:140px;min-height:34px" value="${NumberInput.format(d.paidAmount || 0)}" oninput="window.InvoiceFormView._recalc()" />
231 </div>
232
233 <div class="form-group" style="margin-bottom:0">
234 <label class="form-label" style="font-size:12px">توضیحات</label>
235 <textarea class="form-control" id="invDescription" rows="2" style="font-size:12.5px">${this._esc(d.description)}</textarea>
236 </div>
237 </div>
238
239 <div class="card" style="margin:0;padding:16px;background:var(--bg)">
240 <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">جمع‌بندی</div>
241 <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
242 <span>جمع اقلام:</span>
243 <span id="sumSubtotal" style="font-weight:600">۰ ریال</span>
244 </div>
245 <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
246 <span>تخفیف:</span>
247 <span id="sumDiscount" style="font-weight:600;color:var(--danger)">۰ ریال</span>
248 </div>
249 <div id="sumVatRow" style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
250 <span>مالیات:</span>
251 <span id="sumVat" style="font-weight:600;color:var(--warning)">۰ ریال</span>
252 </div>
253 <div style="display:flex;justify-content:space-between;margin-top:12px;padding-top:12px;border-top:2px solid var(--primary);font-size:15px">
254 <span style="font-weight:700;color:var(--primary)">قابل پرداخت:</span>
255 <span id="sumGrand" style="font-weight:800;color:var(--primary)">۰ ریال</span>
256 </div>
257 <div style="display:flex;justify-content:space-between;margin-top:8px;font-size:12.5px">
258 <span>پرداخت‌شده:</span>
259 <span id="sumPaid">۰ ریال</span>
260 </div>
261 <div style="display:flex;justify-content:space-between;margin-top:6px;font-size:12.5px">
262 <span>باقیمانده:</span>
263 <span id="sumRemaining" style="font-weight:700;color:var(--danger)">۰ ریال</span>
264 </div>
265 <div id="sumWords" style="margin-top:14px;padding:10px;background:var(--card-bg);border-radius:8px;font-size:11px;color:var(--text-muted);line-height:1.7;text-align:justify"></div>
266 </div>
267 </div>
268 `;
269 }
270
271 _renderFooter() {
272 return `
273 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
274 <button class="btn" onclick="window.InvoiceFormView._save(false)">💾 ذخیره</button>
275 <button class="btn btn-success" onclick="window.InvoiceFormView._save(true)">💾 ذخیره و چاپ</button>
276 `;
277 }
278
279 // ============================================================
280 // رندر اقلام
281 // ============================================================
282 _renderItems() {
283 const tbody = document.getElementById('itemsBody');
284 if (!tbody) return;
285 tbody.innerHTML = '';
286 ctx.data.items.forEach((item, idx) => this._renderRow(item, idx));
287 }
288
289 _renderRow(item, idx) {
290 const tbody = document.getElementById('itemsBody');
291 const row = document.createElement('tr');
292 row.dataset.idx = idx;
293
294 const selectedProduct = ctx.products.find(p => p.id === item.productId);
295 const selectedProductLabel = selectedProduct ? selectedProduct.name : (item.productName || '');
296
297 row.innerHTML = `
298 <td style="text-align:center;font-weight:700">${Formatters.toPersianDigits(idx + 1)}</td>
299 <td>
300 <div style="position:relative;min-width:190px">
301 <input type="hidden" class="row-product" value="${this._esc(item.productId || '')}" />
302 <input type="text" class="form-control row-product-search" aria-label="جستجوی کالای ردیف فاکتور" autocomplete="off" value="${this._esc(selectedProductLabel)}" placeholder="جستجوی کالا یا کد" onfocus="window.InvoiceFormView._showProductOptions(${idx})" oninput="window.InvoiceFormView._showProductOptions(${idx}, true)" />
303 <div class="row-product-options" style="display:none;position:absolute;z-index:10010;top:100%;right:0;left:0;max-height:220px;overflow:auto;background:var(--card-bg,#fff);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 20px #0002"></div>
304 </div>
305 </td>
306 <td><input type="text" class="form-control row-unit" aria-label="واحد کالای ردیف" style="min-height:36px;text-align:center" value="${this._esc(item.unit)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'unit', this.value)" /></td>
307 <td><input type="text" inputmode="numeric" class="form-control row-qty" aria-label="تعداد ردیف فاکتور" style="min-height:36px;text-align:center" data-decimals="3" value="${NumberInput.format(item.qty, 3)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
308 <td><input type="text" inputmode="numeric" class="form-control row-price" aria-label="قیمت واحد ردیف فاکتور" style="min-height:36px;text-align:left" value="${NumberInput.format(item.price)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'price', this.value)" /></td>
309 <td>
310 <div style="display:flex;gap:4px">
311 <input type="text" inputmode="numeric" class="form-control row-disc" aria-label="تخفیف ردیف فاکتور" style="min-height:36px;text-align:left;flex:1" data-decimals="${item.discountType === 'percent' ? 2 : 0}" value="${NumberInput.format(item.discountInput ?? item.discount ?? 0, item.discountType === 'percent' ? 2 : 0)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'discount', this.value)" />
312 <select class="form-control" style="min-height:36px;width:60px;padding:0 6px;text-align:center;font-size:12px" aria-label="نوع تخفیف ردیف" onchange="window.InvoiceFormView._onDiscTypeRowChange(${idx}, this.value)">
313 <option value="fixed" ${item.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
314 <option value="percent" ${item.discountType === 'percent' ? 'selected' : ''}>٪</option>
315 </select>
316 </div>
317 </td>
318 <td class="row-total" style="font-weight:700;text-align:left">${Formatters.money(item.lineTotal || 0)}</td>
319 <td style="text-align:center">
320 <button class="icon-btn-sm danger" onclick="window.InvoiceFormView._removeRow(${idx})" title="حذف">✕</button>
321 </td>
322 `;
323 tbody.appendChild(row);
324 }
325
326 _matchesOption(record, query) {
327 const normalize = value => String(value ?? '').toLocaleLowerCase('fa').replace(/ي/g, 'ی').replace(/ك/g, 'ک').trim();
328 return normalize([record.name, record.code, record.customerCode, record.contactCode].join(' ')).includes(normalize(query));
329 }
330
331 _showContactOptions(changed = false) {
332 const input = document.getElementById('invContactSearch');
333 const list = document.getElementById('invContactOptions');
334 const hidden = document.getElementById('invContact');
335 if (!input || !list || !hidden) return;
336 if (changed) hidden.value = '';
337 const matches = ctx.contacts.filter(c => this._matchesOption(c, input.value)).slice(0, 60);
338 list.innerHTML = matches.length ? matches.map(c =>
339 `<div class="contact-option" data-id="${this._esc(c.id)}" style="padding:9px 12px;cursor:pointer;border-bottom:1px solid var(--border)">${this._esc(c.name)} ${c.code ? '— ' + this._esc(c.code) : ''}</div>`
340 ).join('') : '<div style="padding:10px">موردی یافت نشد</div>';
341 list.style.display = 'block';
342 list.querySelectorAll('.contact-option').forEach(el => el.addEventListener('mousedown', event => {
343 event.preventDefault();
344 const contact = ctx.contacts.find(c => c.id === el.dataset.id);
345 if (!contact) return;
346 hidden.value = contact.id;
347 input.value = contact.name;
348 list.style.display = 'none';
349 }));
350 }
351
352 _showProductOptions(idx, changed = false) {
353 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
354 const input = row?.querySelector('.row-product-search');
355 const list = row?.querySelector('.row-product-options');
356 if (!input || !list) return;
357 if (changed) {
358 row.querySelector('.row-product').value = '';
359 ctx.data.items[idx].productId = null;
360 }
361 const matches = ctx.products.filter(p => this._matchesOption(p, input.value)).slice(0, 60);
362 list.innerHTML = matches.length ? matches.map(p =>
363 `<div class="product-option" data-id="${this._esc(p.id)}" style="padding:9px 12px;cursor:pointer;border-bottom:1px solid var(--border)">${this._esc(p.name)} ${p.code ? '— ' + this._esc(p.code) : ''}</div>`
364 ).join('') : '<div style="padding:10px">کالایی یافت نشد</div>';
365 list.style.display = 'block';
366 list.querySelectorAll('.product-option').forEach(el => el.addEventListener('mousedown', event => {
367 event.preventDefault();
368 const product = ctx.products.find(p => p.id === el.dataset.id);
369 if (!product) return;
370 row.querySelector('.row-product').value = product.id;
371 input.value = product.name;
372 list.style.display = 'none';
373 this._onProductChange(idx, product.id);
374 }));
375 }
376
377 _addRow() {
378 ctx.data.items.push(this._emptyItem());
379 this._renderItems();
380 this._recalc();
381 }
382
383 _removeRow(idx) {
384 if (ctx.data.items.length === 1) {
385 Toast.warning('حداقل یک ردیف لازم است');
386 return;
387 }
388 ctx.data.items.splice(idx, 1);
389 this._renderItems();
390 this._recalc();
391 }
392
393 _onProductChange(idx, productId) {
394 const product = ctx.products.find(p => p.id === productId);
395 if (product) {
396 ctx.data.items[idx].productId = product.id;
397 ctx.data.items[idx].productName = product.name;
398 ctx.data.items[idx].unit = product.unitId
399 ? (window.__units_cache?.[product.unitId] || 'عدد')
400 : (product.unit || 'عدد');
401 ctx.data.items[idx].price = Number(product.sellPrice) || 0;
402 } else {
403 ctx.data.items[idx].productId = null;
404 ctx.data.items[idx].productName = '';
405 }
406 // به‌روزرسانی فیلدهای ردیف بدون رندر کامل
407 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
408 if (row) {
409 row.querySelector('.row-unit').value = ctx.data.items[idx].unit;
410 row.querySelector('.row-price').value = NumberInput.format(ctx.data.items[idx].price);
411 }
412 this._recalc();
413 }
414
415 _onFieldChange(idx, field, value) {
416 if (field === 'discount') {
417 // The textbox contains raw percent/rial input, not the computed rial
418 // discount. _recalc() sets item.discount only after using this value.
419 try {
420 ctx.data.items[idx].discountInput = NumberInput.parseStrict(value, {
421 decimals: ctx.data.items[idx].discountType === 'percent' ? 2 : 0, optional: true
422 });
423 } catch (_) { ctx.data.items[idx].discountInput = NaN; }
424 } else if (field === 'qty' || field === 'price') {
425 try {
426 ctx.data.items[idx][field] = NumberInput.parseStrict(value, {
427 decimals: field === 'qty' ? 3 : 0, optional: field !== 'qty'
428 });
429 } catch (_) { ctx.data.items[idx][field] = NaN; }
430 } else {
431 ctx.data.items[idx][field] = value;
432 }
433 this._recalc();
434 }
435
436 _onDiscTypeRowChange(idx, type) {
437 ctx.data.items[idx].discountType = type;
438 ctx.data.items[idx].discount = 0;
439 ctx.data.items[idx].discountInput = 0;
440 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
441 if (row) {
442 const input = row.querySelector('.row-disc');
443 input.value = '0';
444 input.dataset.decimals = type === 'percent' ? '2' : '0';
445 input.setAttribute('inputmode', type === 'percent' ? 'decimal' : 'numeric');
446 }
447 this._recalc();
448 }
449
450 async _onKindChange() {
451 const kind = document.getElementById('invKind').value;
452 ctx.data.kind = kind;
453 if (!ctx.editId) {
454 const number = await InvoiceController.getNextNumber(kind);
455 ctx.data.number = number;
456 const el = document.getElementById('invNumber');
457 if (el) el.value = number;
458 }
459 const originalWrap = document.getElementById('invOriginalWrap');
460 if (originalWrap) originalWrap.style.display = ['sale_return','purchase_return'].includes(kind) ? '' : 'none';
461 const originalSelect = document.getElementById('invOriginalInvoice');
462 if (originalSelect) {
463 for (const option of originalSelect.options) {
464 if (!option.value) continue;
465 option.disabled = kind === 'sale_return' ? !['sale','non_formal'].includes(option.dataset.kind) :
466 kind === 'purchase_return' ? option.dataset.kind !== 'purchase' : false;
467 }
468 if (originalSelect.selectedOptions[0]?.disabled) originalSelect.value = '';
469 }
470 const vatRow = document.getElementById('vatRow');
471 const sumVatRow = document.getElementById('sumVatRow');
472 if (kind === 'non_formal') {
473 vatRow.style.display = 'none';
474 sumVatRow.style.display = 'none';
475 document.getElementById('invVatEnabled').checked = false;
476 } else {
477 vatRow.style.display = 'flex';
478 sumVatRow.style.display = 'flex';
479 }
480 this._recalc();
481 }
482
483 _onDiscTypeChange() {
484 ctx.data.discountType = document.getElementById('invDiscType').value;
485 const input = document.getElementById('invDiscInput');
486 input.value = '0';
487 input.dataset.decimals = ctx.data.discountType === 'percent' ? '2' : '0';
488 input.setAttribute('inputmode', ctx.data.discountType === 'percent' ? 'decimal' : 'numeric');
489 ctx.data.discountInput = 0;
490 this._recalc();
491 }
492
493 _onPaymentChange() {
494 const method = document.getElementById('invPayment').value;
495 ctx.data.paymentMethod = method;
496 const paidRow = document.getElementById('paidRow');
497 if (method === 'partial') {
498 paidRow.style.display = 'flex';
499 } else {
500 paidRow.style.display = 'none';
501 document.getElementById('invPaidAmount').value = 0;
502 }
503 this._recalc();
504 }
505
506 // ============================================================
507 // محاسبه‌ی مجدد
508 // ============================================================
509 _recalc() {
510 // اقلام
511 let subtotal = 0;
512 const tbody = document.getElementById('itemsBody');
513 if (tbody) {
514 ctx.data.items.forEach((item, idx) => {
515 const qty = Number(item.qty) || 0;
516 const price = Number(item.price) || 0;
517 // While an input is incomplete/invalid, show a provisional zero; the
518 // persistence boundary rejects it rather than silently changing it.
519 let lineSubtotal = 0;
520 if (qty > 0 && Number.isSafeInteger(price) && price >= 0) {
521 try { lineSubtotal = lineGrossRials(qty, price); }
522 catch (_) { lineSubtotal = 0; }
523 }
524 let lineDiscount = 0;
525 const discInput = Number(item.discountInput !== undefined ? item.discountInput : item.discount) || 0;
526 if (item.discountType === 'percent') {
527 try { lineDiscount = percentOfRials(lineSubtotal,discInput); }
528 catch (_) { lineDiscount = 0; }
529 } else {
530 lineDiscount = discInput;
531 }
532 lineDiscount = Math.max(0, Math.min(lineDiscount, lineSubtotal));
533 item.lineSubtotal = lineSubtotal;
534 item.lineTotal = lineSubtotal - lineDiscount;
535 item.discount = lineDiscount;
536 item.discountInput = discInput;
537 subtotal += item.lineTotal;
538
539 const row = tbody.querySelector(`tr[data-idx="${idx}"]`);
540 if (row) {
541 const totalEl = row.querySelector('.row-total');
542 if (totalEl) totalEl.textContent = Formatters.money(item.lineTotal);
543 }
544 });
545 }
546
547 // تخفیف کلی
548 const discType = document.getElementById('invDiscType')?.value || 'fixed';
549 const discInput = NumberInput.parse(document.getElementById('invDiscInput')?.value);
550 let totalDiscount = 0;
551 if (discType === 'percent') {
552 try { totalDiscount = percentOfRials(subtotal,discInput); }
553 catch (_) { totalDiscount = 0; }
554 } else {
555 totalDiscount = discInput;
556 }
557 totalDiscount = Math.max(0, Math.min(totalDiscount, subtotal));
558 const afterDiscount = subtotal - totalDiscount;
559
560 // مالیات
561 const kind = document.getElementById('invKind')?.value || 'sale';
562 const vatEnabled = kind !== 'non_formal' && document.getElementById('invVatEnabled')?.checked;
563 const vatRate = NumberInput.parse(document.getElementById('invVatRate')?.value);
564 let vatAmount = 0;
565 if (vatEnabled) {
566 try { vatAmount = percentOfRials(afterDiscount,vatRate); }
567 catch (_) { vatAmount = 0; }
568 }
569
570 const grandTotal = afterDiscount + vatAmount;
571
572 // پرداخت
573 const method = document.getElementById('invPayment')?.value || 'cash';
574 let paidAmount = 0;
575 if (method === 'cash') paidAmount = grandTotal;
576 else if (method === 'credit') paidAmount = 0;
577 else if (method === 'partial') paidAmount = Math.max(0, Math.min(NumberInput.parse(document.getElementById('invPaidAmount')?.value), grandTotal));
578 const remaining = grandTotal - paidAmount;
579
580 // نمایش
581 const set = (id, val) => { const el = document.getElementById(id); if (el) el.textContent = val; };
582 set('sumSubtotal', Formatters.money(subtotal));
583 set('sumDiscount', Formatters.money(totalDiscount));
584 set('sumVat', Formatters.money(vatAmount));
585 set('sumGrand', Formatters.money(grandTotal));
586 set('sumPaid', Formatters.money(paidAmount));
587 set('sumRemaining', Formatters.money(remaining));
588
589 const wordsEl = document.getElementById('sumWords');
590 if (wordsEl) wordsEl.textContent = numberToWords(grandTotal);
591
592 // ذخیره در ctx برای استفاده در save
593 ctx.totals = { subtotal, totalDiscount, vatAmount, grandTotal, paidAmount, remaining };
594 }
595
596 // ============================================================
597 // افزودن سریع کالا (بدون خروج از فرم فاکتور)
598 // ============================================================
599 _openQuickProduct() {
600 const body = `
601 <div class="form-row">
602 <div class="form-group">
603 <label class="form-label">کد کالا</label>
604 <input type="text" class="form-control" id="qpCode" placeholder="اختیاری" />
605 </div>
606 <div class="form-group">
607 <label class="form-label">واحد</label>
608 <input type="text" class="form-control" id="qpUnit" value="عدد" />
609 </div>
610 </div>
611
612 <div class="form-group">
613 <label class="form-label">نام کالا / خدمت <span class="req">*</span></label>
614 <input type="text" class="form-control" id="qpName" placeholder="مثلاً هارد سرور" />
615 </div>
616
617 <div class="form-row">
618 <div class="form-group">
619 <label class="form-label">قیمت خرید (ریال)</label>
620 <input type="text" inputmode="numeric" class="form-control" id="qpBuyPrice" value="0" />
621 </div>
622 <div class="form-group">
623 <label class="form-label">قیمت فروش (ریال)</label>
624 <input type="text" inputmode="numeric" class="form-control" id="qpSellPrice" value="0" />
625 </div>
626 </div>
627
628 <div class="form-group">
629 <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px">
630 <input type="checkbox" id="qpTrackInventory" checked />
631 پیگیری موجودی انبار (اگه خدمت هست، تیک رو بردار)
632 </label>
633 </div>
634
635 <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
636 💡 بعد از ذخیره، این کالا خودکار توی ردیف فعلی فاکتور اضافه می‌شه.
637 </small>
638 `;
639
640 const footer = `
641 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
642 <button class="btn" onclick="window.InvoiceFormView._saveQuickProduct()">💾 ذخیره و افزودن</button>
643 `;
644
645 Modal.open({ title: '➕ کالای جدید سریع', body, footer, size: 'sm' });
646 }
647
648 async _saveQuickProduct() {
649 const name = document.getElementById('qpName').value.trim();
650 if (!name) { Toast.warning('نام کالا الزامی است'); return; }
651
652 let buyPrice, sellPrice;
653 try {
654 buyPrice = NumberInput.parseStrict(document.getElementById('qpBuyPrice'), { optional: true });
655 sellPrice = NumberInput.parseStrict(document.getElementById('qpSellPrice'), { optional: true });
656 } catch (error) {
657 Toast.warning('قیمت کالای جدید نامعتبر است: ' + error.message);
658 return;
659 }
660 const data = {
661 code: document.getElementById('qpCode').value,
662 barcode: '',
663 name,
664 unit: document.getElementById('qpUnit').value || 'عدد',
665 unitId: null,
666 categoryId: null,
667 buyPrice,
668 sellPrice,
669 trackInventory: document.getElementById('qpTrackInventory').checked,
670 isActiveSell: true,
671 isActiveBuy: true,
672 description: ''
673 };
674
675 try {
676 const newProduct = await ProductController.createProduct(data);
677
678 ctx.products.push(newProduct);
679
680 Toast.success('کالا اضافه شد و به فاکتور اضافه می‌شود');
681 Modal.close();
682
683 const emptyIdx = ctx.data.items.findIndex(it => !it.productId);
684 let targetIdx;
685 if (emptyIdx >= 0) {
686 targetIdx = emptyIdx;
687 } else {
688 ctx.data.items.push(this._emptyItem());
689 targetIdx = ctx.data.items.length - 1;
690 this._renderItems();
691 }
692
693 ctx.data.items[targetIdx].productId = newProduct.id;
694 ctx.data.items[targetIdx].productName = newProduct.name;
695 ctx.data.items[targetIdx].unit = newProduct.unit || 'عدد';
696 ctx.data.items[targetIdx].price = Number(newProduct.sellPrice) || 0;
697 ctx.data.items[targetIdx].qty = ctx.data.items[targetIdx].qty || 1;
698
699 this._renderItems();
700 this._recalc();
701
702 } catch (err) {
703 console.error(err);
704 Toast.error('خطا در ذخیره‌ی کالا: ' + err.message);
705 }
706 }
707
708 // ============================================================
709 // افزودن سریع شخص
710 // ============================================================
711 async _openQuickContact() {
712 const body = `
713 <div class="form-group">
714 <label class="form-label">نام <span class="req">*</span></label>
715 <input type="text" class="form-control" id="qcName" />
716 </div>
717 <div class="form-group">
718 <label class="form-label">موبایل</label>
719 <input type="tel" class="form-control" id="qcMobile" />
720 </div>
721 `;
722 const footer = `
723 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
724 <button class="btn" onclick="window.InvoiceFormView._saveQuickContact()">ذخیره</button>
725 `;
726 Modal.open({ title: 'شخص جدید سریع', body, footer, size: 'sm' });
727 }
728
729 async _saveQuickContact() {
730 const name = document.getElementById('qcName').value.trim();
731 const mobile = document.getElementById('qcMobile').value.trim();
732 if (!name) { Toast.warning('نام الزامی است'); return; }
733 try {
734 const newContact = await ContactController.create({
735 entityType: 'natural', role: 'customer', name, mobile
736 });
737 Toast.success('شخص اضافه شد');
738 ctx.contacts.push(newContact);
739 const select = document.getElementById('invContact');
740 if (select) select.value = newContact.id;
741 const search = document.getElementById('invContactSearch');
742 if (search) search.value = newContact.name;
743 const options = document.getElementById('invContactOptions');
744 if (options) options.style.display = 'none';
745 Modal.close();
746 } catch (err) {
747 Toast.error('خطا: ' + err.message);
748 }
749 }
750
751 // ============================================================
752 // ذخیره
753 // ============================================================
754 async _save(printAfter) {
755 const contactId = document.getElementById('invContact').value;
756 if (!contactId) {
757 Toast.warning('لطفاً طرف حساب را انتخاب کنید');
758 return;
759 }
760 const contact = ctx.contacts.find(c => c.id === contactId);
761 if (!contact) {
762 Toast.warning('طرف حساب انتخاب شده معتبر نیست');
763 return;
764 }
765
766 let discountInput, vatRate;
767 try {
768 // Read raw user-visible values once, before any financial write. A
769 // loose parser must never silently convert "2x5" to 25 or bad VAT to 0.
770 ctx.data.items.forEach((item, idx) => {
771 if (!item.productId) return; // intentionally empty draft row
772 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
773 if (!row) throw Error('ردیف کالای انتخاب‌شده در فرم یافت نشد');
774 const qtyField = row.querySelector('.row-qty');
775 const priceField = row.querySelector('.row-price');
776 const discountField = row.querySelector('.row-disc');
777 if (!qtyField || !priceField || !discountField)
778 throw Error('فیلدهای عددی ردیف کالای انتخاب‌شده کامل نیستند');
779 item.qty = NumberInput.parseStrict(qtyField, { decimals: 3 });
780 if (item.qty <= 0) throw Error('مقدار کالا باید مثبت باشد');
781 item.price = NumberInput.parseStrict(priceField, { optional: true });
782 item.discountInput = NumberInput.parseStrict(discountField, {
783 decimals: item.discountType === 'percent' ? 2 : 0, optional: true
784 });
785 });
786 discountInput = NumberInput.parseStrict(document.getElementById('invDiscInput'), {
787 decimals: document.getElementById('invDiscType').value === 'percent' ? 2 : 0,
788 optional: true
789 });
790 vatRate = NumberInput.parseStrict(document.getElementById('invVatRate'), {
791 decimals: 2, optional: true
792 });
793 if (document.getElementById('invPayment').value === 'partial')
794 NumberInput.parseStrict(document.getElementById('invPaidAmount'), { optional: true });
795 } catch (error) {
796 Toast.warning('ورودی عددی قابل ذخیره نیست: ' + error.message);
797 return;
798 }
799
800 const validItems = ctx.data.items.filter(it => it.productId && it.qty > 0);
801 if (validItems.length === 0) {
802 Toast.warning('حداقل یک ردیف معتبر (کالا با مقدار) لازم است');
803 return;
804 }
805
806 this._recalc(); // read payment state from the same calculation shown in the summary
807 const data = {
808 kind: document.getElementById('invKind').value,
809 number: document.getElementById('invNumber')?.value,
810 isPreInvoice: document.getElementById('invPreInvoice').checked,
811 date: document.getElementById('invDate').value,
812 contactId: contact.id,
813 contactName: contact.name,
814 items: validItems,
815 discountType: document.getElementById('invDiscType').value,
816 discountInput,
817 vatEnabled: document.getElementById('invVatEnabled')?.checked || false,
818 vatRate,
819 paymentMethod: document.getElementById('invPayment').value,
820 paidAmount: ctx.totals?.paidAmount ?? 0,
821 originalInvoiceId: document.getElementById('invOriginalInvoice')?.value || null,
822 warehouseId: document.getElementById('invWarehouse')?.value || null,
823 description: document.getElementById('invDescription').value
824 };
825
826 if (this._saving) return;
827 this._saving = true;
828 try {
829 const saved = await InvoiceController.save(data, ctx.editId);
830 Toast.success(ctx.editId ? 'فاکتور ویرایش شد' : `فاکتور #${saved.number} صادر شد`);
831 const savedId = saved.id;
832 Modal.close();
833 if (printAfter) {
834 const { InvoicePrint } = await import('../utils/InvoicePrint.js');
835 setTimeout(() => InvoicePrint.openSettings(savedId), 250);
836 }
837 if (window.InvoicesView) window.InvoicesView.reloadAndRender?.();
838 } catch (err) {
839 console.error(err);
840 Toast.error('خطا: ' + err.message);
841 } finally {
842 this._saving = false;
843 }
844 }
845
846 // ============================================================
847 // Helpers
848 // ============================================================
849 _todayJalali() {
850 const d = new Date();
851 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
852 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
853 let jy = (gy <= 1600) ? 0 : 979;
854 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
855 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
856 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];
857 jy += 33 * Math.floor(days / 12053);
858 days %= 12053;
859 jy += 4 * Math.floor(days / 1461);
860 days %= 1461;
861 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
862 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
863 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
864 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
865 }
866
867 _esc(s) {
868 if (s === null || s === undefined) return '';
869 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
870 }
871 }
872
873 export const InvoiceFormView = new InvoiceFormViewImpl();
874 window.InvoiceFormView = InvoiceFormView;