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

work/finance-curated-20261123
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 909 lines 43.5 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 { createRetryStorageKey } from '../core/IssuanceReceipt.mjs';
16 import { lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
17
18 let ctx = {
19 editId: null,
20 data: null,
21 contacts: [],
22 products: [],
23 units: [],
24 invoices: [],
25 warehouses: [],
26 rowCounter: 0
27 };
28
29 class InvoiceFormViewImpl {
30 // ============================================================
31 // باز کردن فرم فاکتور (ایجاد یا ویرایش)
32 // ============================================================
33 async open(invoiceId = null) {
34 ctx.editId = invoiceId;
35 ctx.contacts = await ContactController.getAll();
36 ctx.products = await ProductController.getProducts();
37 ctx.units = await ProductController.getUnits();
38 ctx.invoices = await InvoiceController.getAll();
39 ctx.warehouses = await RetailPostingService.isEnabled() ? await RetailPostingService.warehouses() : [];
40 ctx.rowCounter = 0;
41
42 if (invoiceId) {
43 const existing = await InvoiceController.get(invoiceId);
44 ctx.data = existing;
45 } else {
46 ctx.data = {
47 kind: 'sale',
48 isPreInvoice: false,
49 date: this._todayJalali(),
50 contactId: null,
51 contactName: '',
52 items: [],
53 discountType: 'fixed',
54 discountInput: 0,
55 vatEnabled: false,
56 vatRate: 10,
57 paymentMethod: 'cash',
58 paidAmount: 0,
59 description: ''
60 };
61 }
62
63 ctx.invoiceSettings = await SettingsController.getInvoiceSettings();
64 if (!invoiceId) {
65 ctx.data.number = await InvoiceController.getNextNumber(ctx.data.kind);
66 }
67
68 // اگه فاکتور جدید بدون اقلام، یک ردیف خالی اضافه کن
69 if (!ctx.data.items || ctx.data.items.length === 0) {
70 ctx.data.items = [this._emptyItem()];
71 }
72
73 const body = this._renderFormBody();
74 const footer = this._renderFooter();
75
76 const modal = Modal.open({
77 title: invoiceId ? `ویرایش فاکتور #${ctx.data.number}` : 'صدور فاکتور جدید',
78 body,
79 footer,
80 size: 'lg',
81 onClose: () => { ctx = { editId: null, data: null, contacts: [], products: [], units: [], rowCounter: 0 }; }
82 });
83
84 // بعد از باز شدن مودال، اقلام رو رندر کن
85 setTimeout(() => {
86 this._renderItems();
87 this._recalc();
88 }, 50);
89 }
90
91 _emptyItem() {
92 return {
93 productId: null,
94 productName: '',
95 unit: 'عدد',
96 qty: 1,
97 price: 0,
98 discount: 0,
99 discountType: 'fixed',
100 lineSubtotal: 0,
101 lineTotal: 0
102 };
103 }
104
105 // ============================================================
106 // ساختار فرم
107 // ============================================================
108 _renderFormBody() {
109 const d = ctx.data;
110 const kindOptions = [
111 { value: 'sale', label: 'فاکتور فروش' },
112 { value: 'purchase', label: 'فاکتور خرید' },
113 { value: 'sale_return', label: 'برگشت از فروش' },
114 { value: 'purchase_return', label: 'برگشت از خرید' },
115 { value: 'non_formal', label: 'فاکتور غیررسمی' }
116 ];
117 const kindOpts = kindOptions.map(k =>
118 `<option value="${k.value}" ${d.kind === k.value ? 'selected' : ''}>${k.label}</option>`
119 ).join('');
120
121 const selectedContact = ctx.contacts.find(c => c.id === d.contactId);
122 const selectedContactLabel = selectedContact ? selectedContact.name : (d.contactName || '');
123
124 return `
125 <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:14px">
126 <div class="form-group" style="margin-bottom:0">
127 <label class="form-label">نوع سند</label>
128 <select class="form-control" id="invKind" onchange="window.InvoiceFormView._onKindChange()">${kindOpts}</select>
129 </div>
130 <div class="form-group" style="margin-bottom:0">
131 <label class="form-label">شماره فاکتور</label>
132 <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="شماره فاکتور" />
133 </div>
134 <div class="form-group" style="margin-bottom:0">
135 <label class="form-label">تاریخ (شمسی)</label>
136 <input type="text" class="form-control" id="invDate" value="${this._esc(d.date)}" placeholder="1405/06/27" />
137 </div>
138 </div>
139
140 ${ctx.warehouses.length ? `<div class="form-group" style="margin-bottom:12px">
141 <label class="form-label">انبار محل گردش کالا</label><select class="form-control" id="invWarehouse">
142 ${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('')}
143 </select></div>` : ''}
144 <div class="form-group" id="invOriginalWrap" style="margin-bottom:12px;${['sale_return','purchase_return'].includes(d.kind)?'':'display:none'}">
145 <label class="form-label">شماره فاکتور اولیه (الزامی برای مرجوعی)</label>
146 <select class="form-control" id="invOriginalInvoice">
147 <option value="">انتخاب فاکتور مرجع</option>
148 ${ctx.invoices.filter(i=>['sale','non_formal','purchase'].includes(i.kind)&&!i.isPreInvoice)
149 .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('')}
150 </select></div>
151 <div style="display:grid;grid-template-columns:2fr 1fr;gap:10px;margin-bottom:14px">
152 <div class="form-group" style="margin-bottom:0">
153 <label class="form-label">طرف حساب</label>
154 <div style="display:flex;gap:6px">
155 <div style="position:relative;flex:1;min-width:0">
156 <input type="hidden" id="invContact" value="${this._esc(d.contactId || '')}" />
157 <input type="text" class="form-control" id="invContactSearch" autocomplete="off" value="${this._esc(selectedContactLabel)}" placeholder="جستجوی نام یا کد طرف حساب" onfocus="window.InvoiceFormView._showContactOptions()" oninput="window.InvoiceFormView._showContactOptions(true)" />
158 <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>
159 </div>
160 <button class="btn btn-secondary" style="min-height:42px;padding:0 12px" onclick="window.InvoiceFormView._openQuickContact()" title="افزودن شخص جدید">➕</button>
161 </div>
162 </div>
163 <div class="form-group" style="margin-bottom:0">
164 <label class="form-label">
165 <input type="checkbox" id="invPreInvoice" ${d.isPreInvoice ? 'checked' : ''} />
166 پیش‌فاکتور
167 </label>
168 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">پیش‌فاکتور، موجودی انبار رو تغییر نمی‌ده</small>
169 </div>
170 </div>
171
172 <div style="margin:14px 0 10px;display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap">
173 <h4 style="font-size:14px;font-weight:700">اقلام فاکتور</h4>
174 <div style="display:flex;gap:6px">
175 <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._openQuickProduct()">➕ کالای جدید</button>
176 <button class="btn btn-secondary" style="min-height:34px;padding:4px 12px;font-size:12px" onclick="window.InvoiceFormView._addRow()">➕ افزودن ردیف</button>
177 </div>
178 </div>
179
180 <div class="table-wrap" style="overflow:visible">
181 <table>
182 <thead>
183 <tr>
184 <th style="width:36px;text-align:center">#</th>
185 <th style="min-width:200px">کالا / خدمات</th>
186 <th style="width:70px">واحد</th>
187 <th style="width:80px">مقدار</th>
188 <th style="width:130px">قیمت واحد</th>
189 <th style="width:130px">تخفیف</th>
190 <th style="width:140px">جمع</th>
191 <th style="width:40px"></th>
192 </tr>
193 </thead>
194 <tbody id="itemsBody"></tbody>
195 </table>
196 </div>
197
198 <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px">
199 <div class="card" style="margin:0;padding:16px">
200 <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">تخفیف، مالیات و پرداخت</div>
201
202 <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
203 <span style="flex:1;font-size:12.5px">تخفیف کلی</span>
204 <select class="form-control" id="invDiscType" aria-label="نوع تخفیف کل فاکتور" style="width:80px;min-height:34px" onchange="window.InvoiceFormView._onDiscTypeChange()">
205 <option value="fixed" ${d.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
206 <option value="percent" ${d.discountType === 'percent' ? 'selected' : ''}>درصد</option>
207 </select>
208 <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()" />
209 </div>
210
211 <div id="vatRow" style="display:${d.kind === 'non_formal' ? 'none' : 'flex'};gap:8px;align-items:center;margin-bottom:10px">
212 <label style="flex:1;font-size:12.5px;display:flex;align-items:center;gap:6px;cursor:pointer">
213 <input type="checkbox" id="invVatEnabled" ${d.vatEnabled ? 'checked' : ''} onchange="window.InvoiceFormView._recalc()" />
214 مالیات ارزش افزوده
215 </label>
216 <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()" />
217 <span style="font-size:12.5px;color:var(--text-muted)">٪</span>
218 </div>
219
220 <div style="display:flex;gap:8px;align-items:center;margin-bottom:10px">
221 <span style="flex:1;font-size:12.5px">روش پرداخت</span>
222 <select class="form-control" id="invPayment" aria-label="وضعیت پرداخت فاکتور" style="min-height:34px" onchange="window.InvoiceFormView._onPaymentChange()">
223 <option value="cash" ${d.paymentMethod === 'cash' ? 'selected' : ''}>نقدی</option>
224 <option value="credit" ${d.paymentMethod === 'credit' ? 'selected' : ''}>نسیه</option>
225 <option value="partial" ${d.paymentMethod === 'partial' ? 'selected' : ''}>پرداخت جزئی</option>
226 </select>
227 </div>
228
229 <div id="paidRow" style="display:${d.paymentMethod === 'partial' ? 'flex' : 'none'};gap:8px;align-items:center;margin-bottom:10px">
230 <label for="invPaidAmount" style="flex:1;font-size:12.5px;margin:0">مبلغ پرداخت‌شده</label>
231 <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()" />
232 </div>
233
234 <div class="form-group" style="margin-bottom:0">
235 <label class="form-label" style="font-size:12px">توضیحات</label>
236 <textarea class="form-control" id="invDescription" rows="2" style="font-size:12.5px">${this._esc(d.description)}</textarea>
237 </div>
238 </div>
239
240 <div class="card" style="margin:0;padding:16px;background:var(--bg)">
241 <div style="font-weight:700;font-size:13px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border)">جمع‌بندی</div>
242 <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
243 <span>جمع اقلام:</span>
244 <span id="sumSubtotal" style="font-weight:600">۰ ریال</span>
245 </div>
246 <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
247 <span>تخفیف:</span>
248 <span id="sumDiscount" style="font-weight:600;color:var(--danger)">۰ ریال</span>
249 </div>
250 <div id="sumVatRow" style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:13px">
251 <span>مالیات:</span>
252 <span id="sumVat" style="font-weight:600;color:var(--warning)">۰ ریال</span>
253 </div>
254 <div style="display:flex;justify-content:space-between;margin-top:12px;padding-top:12px;border-top:2px solid var(--primary);font-size:15px">
255 <span style="font-weight:700;color:var(--primary)">قابل پرداخت:</span>
256 <span id="sumGrand" style="font-weight:800;color:var(--primary)">۰ ریال</span>
257 </div>
258 <div style="display:flex;justify-content:space-between;margin-top:8px;font-size:12.5px">
259 <span>پرداخت‌شده:</span>
260 <span id="sumPaid">۰ ریال</span>
261 </div>
262 <div style="display:flex;justify-content:space-between;margin-top:6px;font-size:12.5px">
263 <span>باقیمانده:</span>
264 <span id="sumRemaining" style="font-weight:700;color:var(--danger)">۰ ریال</span>
265 </div>
266 <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>
267 </div>
268 </div>
269 `;
270 }
271
272 _renderFooter() {
273 return `
274 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
275 <button class="btn" onclick="window.InvoiceFormView._save(false)">💾 ذخیره</button>
276 <button class="btn btn-success" onclick="window.InvoiceFormView._save(true)">💾 ذخیره و چاپ</button>
277 `;
278 }
279
280 // ============================================================
281 // رندر اقلام
282 // ============================================================
283 _renderItems() {
284 const tbody = document.getElementById('itemsBody');
285 if (!tbody) return;
286 tbody.innerHTML = '';
287 ctx.data.items.forEach((item, idx) => this._renderRow(item, idx));
288 }
289
290 _renderRow(item, idx) {
291 const tbody = document.getElementById('itemsBody');
292 const row = document.createElement('tr');
293 row.dataset.idx = idx;
294
295 const selectedProduct = ctx.products.find(p => p.id === item.productId);
296 const selectedProductLabel = selectedProduct ? selectedProduct.name : (item.productName || '');
297
298 row.innerHTML = `
299 <td style="text-align:center;font-weight:700">${Formatters.toPersianDigits(idx + 1)}</td>
300 <td>
301 <div style="position:relative;min-width:190px">
302 <input type="hidden" class="row-product" value="${this._esc(item.productId || '')}" />
303 <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)" />
304 <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>
305 </div>
306 </td>
307 <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>
308 <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>
309 <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>
310 <td>
311 <div style="display:flex;gap:4px">
312 <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)" />
313 <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)">
314 <option value="fixed" ${item.discountType === 'fixed' ? 'selected' : ''}>مبلغ</option>
315 <option value="percent" ${item.discountType === 'percent' ? 'selected' : ''}>٪</option>
316 </select>
317 </div>
318 </td>
319 <td class="row-total" style="font-weight:700;text-align:left">${Formatters.money(item.lineTotal || 0)}</td>
320 <td style="text-align:center">
321 <button class="icon-btn-sm danger" onclick="window.InvoiceFormView._removeRow(${idx})" title="حذف">✕</button>
322 </td>
323 `;
324 tbody.appendChild(row);
325 }
326
327 _matchesOption(record, query) {
328 const normalize = value => String(value ?? '').toLocaleLowerCase('fa').replace(/ي/g, 'ی').replace(/ك/g, 'ک').trim();
329 return normalize([record.name, record.code, record.customerCode, record.contactCode].join(' ')).includes(normalize(query));
330 }
331
332 _showContactOptions(changed = false) {
333 const input = document.getElementById('invContactSearch');
334 const list = document.getElementById('invContactOptions');
335 const hidden = document.getElementById('invContact');
336 if (!input || !list || !hidden) return;
337 if (changed) hidden.value = '';
338 const matches = ctx.contacts.filter(c => this._matchesOption(c, input.value)).slice(0, 60);
339 list.innerHTML = matches.length ? matches.map(c =>
340 `<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>`
341 ).join('') : '<div style="padding:10px">موردی یافت نشد</div>';
342 list.style.display = 'block';
343 list.querySelectorAll('.contact-option').forEach(el => el.addEventListener('mousedown', event => {
344 event.preventDefault();
345 const contact = ctx.contacts.find(c => c.id === el.dataset.id);
346 if (!contact) return;
347 hidden.value = contact.id;
348 input.value = contact.name;
349 list.style.display = 'none';
350 }));
351 }
352
353 _showProductOptions(idx, changed = false) {
354 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
355 const input = row?.querySelector('.row-product-search');
356 const list = row?.querySelector('.row-product-options');
357 if (!input || !list) return;
358 if (changed) {
359 row.querySelector('.row-product').value = '';
360 ctx.data.items[idx].productId = null;
361 }
362 const matches = ctx.products.filter(p => this._matchesOption(p, input.value)).slice(0, 60);
363 list.innerHTML = matches.length ? matches.map(p =>
364 `<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>`
365 ).join('') : '<div style="padding:10px">کالایی یافت نشد</div>';
366 list.style.display = 'block';
367 list.querySelectorAll('.product-option').forEach(el => el.addEventListener('mousedown', event => {
368 event.preventDefault();
369 const product = ctx.products.find(p => p.id === el.dataset.id);
370 if (!product) return;
371 row.querySelector('.row-product').value = product.id;
372 input.value = product.name;
373 list.style.display = 'none';
374 this._onProductChange(idx, product.id);
375 }));
376 }
377
378 _addRow() {
379 ctx.data.items.push(this._emptyItem());
380 this._renderItems();
381 this._recalc();
382 }
383
384 _removeRow(idx) {
385 if (ctx.data.items.length === 1) {
386 Toast.warning('حداقل یک ردیف لازم است');
387 return;
388 }
389 ctx.data.items.splice(idx, 1);
390 this._renderItems();
391 this._recalc();
392 }
393
394 _onProductChange(idx, productId) {
395 const product = ctx.products.find(p => p.id === productId);
396 if (product) {
397 ctx.data.items[idx].productId = product.id;
398 ctx.data.items[idx].productName = product.name;
399 ctx.data.items[idx].unit = product.unitId
400 ? (window.__units_cache?.[product.unitId] || 'عدد')
401 : (product.unit || 'عدد');
402 ctx.data.items[idx].price = Number(product.sellPrice) || 0;
403 } else {
404 ctx.data.items[idx].productId = null;
405 ctx.data.items[idx].productName = '';
406 }
407 // به‌روزرسانی فیلدهای ردیف بدون رندر کامل
408 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
409 if (row) {
410 row.querySelector('.row-unit').value = ctx.data.items[idx].unit;
411 row.querySelector('.row-price').value = NumberInput.format(ctx.data.items[idx].price);
412 }
413 this._recalc();
414 }
415
416 _onFieldChange(idx, field, value) {
417 if (field === 'discount') {
418 // The textbox contains raw percent/rial input, not the computed rial
419 // discount. _recalc() sets item.discount only after using this value.
420 try {
421 ctx.data.items[idx].discountInput = NumberInput.parseStrict(value, {
422 decimals: ctx.data.items[idx].discountType === 'percent' ? 2 : 0, optional: true
423 });
424 } catch (_) { ctx.data.items[idx].discountInput = NaN; }
425 } else if (field === 'qty' || field === 'price') {
426 try {
427 ctx.data.items[idx][field] = NumberInput.parseStrict(value, {
428 decimals: field === 'qty' ? 3 : 0, optional: field !== 'qty'
429 });
430 } catch (_) { ctx.data.items[idx][field] = NaN; }
431 } else {
432 ctx.data.items[idx][field] = value;
433 }
434 this._recalc();
435 }
436
437 _onDiscTypeRowChange(idx, type) {
438 ctx.data.items[idx].discountType = type;
439 ctx.data.items[idx].discount = 0;
440 ctx.data.items[idx].discountInput = 0;
441 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
442 if (row) {
443 const input = row.querySelector('.row-disc');
444 input.value = '0';
445 input.dataset.decimals = type === 'percent' ? '2' : '0';
446 input.setAttribute('inputmode', type === 'percent' ? 'decimal' : 'numeric');
447 }
448 this._recalc();
449 }
450
451 async _onKindChange() {
452 const kind = document.getElementById('invKind').value;
453 ctx.data.kind = kind;
454 if (!ctx.editId) {
455 const number = await InvoiceController.getNextNumber(kind);
456 ctx.data.number = number;
457 const el = document.getElementById('invNumber');
458 if (el) el.value = number;
459 }
460 const originalWrap = document.getElementById('invOriginalWrap');
461 if (originalWrap) originalWrap.style.display = ['sale_return','purchase_return'].includes(kind) ? '' : 'none';
462 const originalSelect = document.getElementById('invOriginalInvoice');
463 if (originalSelect) {
464 for (const option of originalSelect.options) {
465 if (!option.value) continue;
466 option.disabled = kind === 'sale_return' ? !['sale','non_formal'].includes(option.dataset.kind) :
467 kind === 'purchase_return' ? option.dataset.kind !== 'purchase' : false;
468 }
469 if (originalSelect.selectedOptions[0]?.disabled) originalSelect.value = '';
470 }
471 const vatRow = document.getElementById('vatRow');
472 const sumVatRow = document.getElementById('sumVatRow');
473 if (kind === 'non_formal') {
474 vatRow.style.display = 'none';
475 sumVatRow.style.display = 'none';
476 document.getElementById('invVatEnabled').checked = false;
477 } else {
478 vatRow.style.display = 'flex';
479 sumVatRow.style.display = 'flex';
480 }
481 this._recalc();
482 }
483
484 _onDiscTypeChange() {
485 ctx.data.discountType = document.getElementById('invDiscType').value;
486 const input = document.getElementById('invDiscInput');
487 input.value = '0';
488 input.dataset.decimals = ctx.data.discountType === 'percent' ? '2' : '0';
489 input.setAttribute('inputmode', ctx.data.discountType === 'percent' ? 'decimal' : 'numeric');
490 ctx.data.discountInput = 0;
491 this._recalc();
492 }
493
494 _onPaymentChange() {
495 const method = document.getElementById('invPayment').value;
496 ctx.data.paymentMethod = method;
497 const paidRow = document.getElementById('paidRow');
498 if (method === 'partial') {
499 paidRow.style.display = 'flex';
500 } else {
501 paidRow.style.display = 'none';
502 document.getElementById('invPaidAmount').value = 0;
503 }
504 this._recalc();
505 }
506
507 // ============================================================
508 // محاسبه‌ی مجدد
509 // ============================================================
510 _recalc() {
511 // اقلام
512 let subtotal = 0;
513 const tbody = document.getElementById('itemsBody');
514 if (tbody) {
515 ctx.data.items.forEach((item, idx) => {
516 const qty = Number(item.qty) || 0;
517 const price = Number(item.price) || 0;
518 // While an input is incomplete/invalid, show a provisional zero; the
519 // persistence boundary rejects it rather than silently changing it.
520 let lineSubtotal = 0;
521 if (qty > 0 && Number.isSafeInteger(price) && price >= 0) {
522 try { lineSubtotal = lineGrossRials(qty, price); }
523 catch (_) { lineSubtotal = 0; }
524 }
525 let lineDiscount = 0;
526 const discInput = Number(item.discountInput !== undefined ? item.discountInput : item.discount) || 0;
527 if (item.discountType === 'percent') {
528 try { lineDiscount = percentOfRials(lineSubtotal,discInput); }
529 catch (_) { lineDiscount = 0; }
530 } else {
531 lineDiscount = discInput;
532 }
533 lineDiscount = Math.max(0, Math.min(lineDiscount, lineSubtotal));
534 item.lineSubtotal = lineSubtotal;
535 item.lineTotal = lineSubtotal - lineDiscount;
536 item.discount = lineDiscount;
537 item.discountInput = discInput;
538 subtotal += item.lineTotal;
539
540 const row = tbody.querySelector(`tr[data-idx="${idx}"]`);
541 if (row) {
542 const totalEl = row.querySelector('.row-total');
543 if (totalEl) totalEl.textContent = Formatters.money(item.lineTotal);
544 }
545 });
546 }
547
548 // تخفیف کلی
549 const discType = document.getElementById('invDiscType')?.value || 'fixed';
550 const discInput = NumberInput.parse(document.getElementById('invDiscInput')?.value);
551 let totalDiscount = 0;
552 if (discType === 'percent') {
553 try { totalDiscount = percentOfRials(subtotal,discInput); }
554 catch (_) { totalDiscount = 0; }
555 } else {
556 totalDiscount = discInput;
557 }
558 totalDiscount = Math.max(0, Math.min(totalDiscount, subtotal));
559 const afterDiscount = subtotal - totalDiscount;
560
561 // مالیات
562 const kind = document.getElementById('invKind')?.value || 'sale';
563 const vatEnabled = kind !== 'non_formal' && document.getElementById('invVatEnabled')?.checked;
564 const vatRate = NumberInput.parse(document.getElementById('invVatRate')?.value);
565 let vatAmount = 0;
566 if (vatEnabled) {
567 try { vatAmount = percentOfRials(afterDiscount,vatRate); }
568 catch (_) { vatAmount = 0; }
569 }
570
571 const grandTotal = afterDiscount + vatAmount;
572
573 // پرداخت
574 const method = document.getElementById('invPayment')?.value || 'cash';
575 let paidAmount = 0;
576 if (method === 'cash') paidAmount = grandTotal;
577 else if (method === 'credit') paidAmount = 0;
578 else if (method === 'partial') paidAmount = Math.max(0, Math.min(NumberInput.parse(document.getElementById('invPaidAmount')?.value), grandTotal));
579 const remaining = grandTotal - paidAmount;
580
581 // نمایش
582 const set = (id, val) => { const el = document.getElementById(id); if (el) el.textContent = val; };
583 set('sumSubtotal', Formatters.money(subtotal));
584 set('sumDiscount', Formatters.money(totalDiscount));
585 set('sumVat', Formatters.money(vatAmount));
586 set('sumGrand', Formatters.money(grandTotal));
587 set('sumPaid', Formatters.money(paidAmount));
588 set('sumRemaining', Formatters.money(remaining));
589
590 const wordsEl = document.getElementById('sumWords');
591 if (wordsEl) wordsEl.textContent = numberToWords(grandTotal);
592
593 // ذخیره در ctx برای استفاده در save
594 ctx.totals = { subtotal, totalDiscount, vatAmount, grandTotal, paidAmount, remaining };
595 }
596
597 // ============================================================
598 // افزودن سریع کالا (بدون خروج از فرم فاکتور)
599 // ============================================================
600 _openQuickProduct() {
601 const body = `
602 <div class="form-row">
603 <div class="form-group">
604 <label class="form-label">کد کالا</label>
605 <input type="text" class="form-control" id="qpCode" placeholder="اختیاری" />
606 </div>
607 <div class="form-group">
608 <label class="form-label">واحد</label>
609 <input type="text" class="form-control" id="qpUnit" value="عدد" />
610 </div>
611 </div>
612
613 <div class="form-group">
614 <label class="form-label">نام کالا / خدمت <span class="req">*</span></label>
615 <input type="text" class="form-control" id="qpName" placeholder="مثلاً هارد سرور" />
616 </div>
617
618 <div class="form-row">
619 <div class="form-group">
620 <label class="form-label">قیمت خرید (ریال)</label>
621 <input type="text" inputmode="numeric" class="form-control" id="qpBuyPrice" value="0" />
622 </div>
623 <div class="form-group">
624 <label class="form-label">قیمت فروش (ریال)</label>
625 <input type="text" inputmode="numeric" class="form-control" id="qpSellPrice" value="0" />
626 </div>
627 </div>
628
629 <div class="form-group">
630 <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px">
631 <input type="checkbox" id="qpTrackInventory" checked />
632 پیگیری موجودی انبار (اگه خدمت هست، تیک رو بردار)
633 </label>
634 </div>
635
636 <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
637 💡 بعد از ذخیره، این کالا خودکار توی ردیف فعلی فاکتور اضافه می‌شه.
638 </small>
639 `;
640
641 const footer = `
642 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
643 <button class="btn" onclick="window.InvoiceFormView._saveQuickProduct()">💾 ذخیره و افزودن</button>
644 `;
645
646 Modal.open({ title: '➕ کالای جدید سریع', body, footer, size: 'sm' });
647 }
648
649 async _saveQuickProduct() {
650 const name = document.getElementById('qpName').value.trim();
651 if (!name) { Toast.warning('نام کالا الزامی است'); return; }
652
653 let buyPrice, sellPrice;
654 try {
655 buyPrice = NumberInput.parseStrict(document.getElementById('qpBuyPrice'), { optional: true });
656 sellPrice = NumberInput.parseStrict(document.getElementById('qpSellPrice'), { optional: true });
657 } catch (error) {
658 Toast.warning('قیمت کالای جدید نامعتبر است: ' + error.message);
659 return;
660 }
661 const data = {
662 code: document.getElementById('qpCode').value,
663 barcode: '',
664 name,
665 unit: document.getElementById('qpUnit').value || 'عدد',
666 unitId: null,
667 categoryId: null,
668 buyPrice,
669 sellPrice,
670 trackInventory: document.getElementById('qpTrackInventory').checked,
671 isActiveSell: true,
672 isActiveBuy: true,
673 description: ''
674 };
675
676 try {
677 const newProduct = await ProductController.createProduct(data);
678
679 ctx.products.push(newProduct);
680
681 Toast.success('کالا اضافه شد و به فاکتور اضافه می‌شود');
682 Modal.close();
683
684 const emptyIdx = ctx.data.items.findIndex(it => !it.productId);
685 let targetIdx;
686 if (emptyIdx >= 0) {
687 targetIdx = emptyIdx;
688 } else {
689 ctx.data.items.push(this._emptyItem());
690 targetIdx = ctx.data.items.length - 1;
691 this._renderItems();
692 }
693
694 ctx.data.items[targetIdx].productId = newProduct.id;
695 ctx.data.items[targetIdx].productName = newProduct.name;
696 ctx.data.items[targetIdx].unit = newProduct.unit || 'عدد';
697 ctx.data.items[targetIdx].price = Number(newProduct.sellPrice) || 0;
698 ctx.data.items[targetIdx].qty = ctx.data.items[targetIdx].qty || 1;
699
700 this._renderItems();
701 this._recalc();
702
703 } catch (err) {
704 console.error(err);
705 Toast.error('خطا در ذخیره‌ی کالا: ' + err.message);
706 }
707 }
708
709 // ============================================================
710 // افزودن سریع شخص
711 // ============================================================
712 async _openQuickContact() {
713 const body = `
714 <div class="form-group">
715 <label class="form-label">نام <span class="req">*</span></label>
716 <input type="text" class="form-control" id="qcName" />
717 </div>
718 <div class="form-group">
719 <label class="form-label">موبایل</label>
720 <input type="tel" class="form-control" id="qcMobile" />
721 </div>
722 `;
723 const footer = `
724 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
725 <button class="btn" onclick="window.InvoiceFormView._saveQuickContact()">ذخیره</button>
726 `;
727 Modal.open({ title: 'شخص جدید سریع', body, footer, size: 'sm' });
728 }
729
730 async _saveQuickContact() {
731 const name = document.getElementById('qcName').value.trim();
732 const mobile = document.getElementById('qcMobile').value.trim();
733 if (!name) { Toast.warning('نام الزامی است'); return; }
734 try {
735 const newContact = await ContactController.create({
736 entityType: 'natural', role: 'customer', name, mobile
737 });
738 Toast.success('شخص اضافه شد');
739 ctx.contacts.push(newContact);
740 const select = document.getElementById('invContact');
741 if (select) select.value = newContact.id;
742 const search = document.getElementById('invContactSearch');
743 if (search) search.value = newContact.name;
744 const options = document.getElementById('invContactOptions');
745 if (options) options.style.display = 'none';
746 Modal.close();
747 } catch (err) {
748 Toast.error('خطا: ' + err.message);
749 }
750 }
751
752 // ============================================================
753 // ذخیره
754 // ============================================================
755 async _save(printAfter) {
756 const contactId = document.getElementById('invContact').value;
757 if (!contactId) {
758 Toast.warning('لطفاً طرف حساب را انتخاب کنید');
759 return;
760 }
761 const contact = ctx.contacts.find(c => c.id === contactId);
762 if (!contact) {
763 Toast.warning('طرف حساب انتخاب شده معتبر نیست');
764 return;
765 }
766
767 let discountInput, vatRate, partialPaidAmount;
768 try {
769 // Read raw user-visible values once, before any financial write. A
770 // loose parser must never silently convert "2x5" to 25 or bad VAT to 0.
771 ctx.data.items.forEach((item, idx) => {
772 if (!item.productId) return; // intentionally empty draft row
773 const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
774 if (!row) throw Error('ردیف کالای انتخاب‌شده در فرم یافت نشد');
775 const qtyField = row.querySelector('.row-qty');
776 const priceField = row.querySelector('.row-price');
777 const discountField = row.querySelector('.row-disc');
778 if (!qtyField || !priceField || !discountField)
779 throw Error('فیلدهای عددی ردیف کالای انتخاب‌شده کامل نیستند');
780 item.qty = NumberInput.parseStrict(qtyField, { decimals: 3 });
781 if (item.qty <= 0) throw Error('مقدار کالا باید مثبت باشد');
782 item.price = NumberInput.parseStrict(priceField, { optional: true });
783 item.discountInput = NumberInput.parseStrict(discountField, {
784 decimals: item.discountType === 'percent' ? 2 : 0, optional: true
785 });
786 });
787 discountInput = NumberInput.parseStrict(document.getElementById('invDiscInput'), {
788 decimals: document.getElementById('invDiscType').value === 'percent' ? 2 : 0,
789 optional: true
790 });
791 vatRate = NumberInput.parseStrict(document.getElementById('invVatRate'), {
792 decimals: 2, optional: true
793 });
794 if (document.getElementById('invPayment').value === 'partial')
795 partialPaidAmount = NumberInput.parseStrict(document.getElementById('invPaidAmount'), { optional: true });
796 } catch (error) {
797 Toast.warning('ورودی عددی قابل ذخیره نیست: ' + error.message);
798 return;
799 }
800
801 const validItems = ctx.data.items.filter(it => it.productId && it.qty > 0);
802 if (validItems.length === 0) {
803 Toast.warning('حداقل یک ردیف معتبر (کالا با مقدار) لازم است');
804 return;
805 }
806
807 this._recalc(); // read payment state from the same calculation shown in the summary
808 if (document.getElementById('invDiscType').value === 'fixed' && discountInput > ctx.totals.subtotal) {
809 Toast.warning('تخفیف کل نمی‌تواند بیشتر از مبلغ فاکتور باشد');
810 return;
811 }
812 if (partialPaidAmount !== undefined && partialPaidAmount > ctx.totals.grandTotal) {
813 Toast.warning('مبلغ پرداخت‌شده نمی‌تواند از مبلغ کل فاکتور بیشتر باشد');
814 return;
815 }
816 const data = {
817 kind: document.getElementById('invKind').value,
818 number: document.getElementById('invNumber')?.value,
819 isPreInvoice: document.getElementById('invPreInvoice').checked,
820 date: document.getElementById('invDate').value,
821 contactId: contact.id,
822 contactName: contact.name,
823 items: validItems,
824 discountType: document.getElementById('invDiscType').value,
825 discountInput,
826 vatEnabled: document.getElementById('invVatEnabled')?.checked || false,
827 vatRate,
828 paymentMethod: document.getElementById('invPayment').value,
829 paidAmount: ctx.totals?.paidAmount ?? 0,
830 originalInvoiceId: document.getElementById('invOriginalInvoice')?.value || null,
831 warehouseId: document.getElementById('invWarehouse')?.value || null,
832 description: document.getElementById('invDescription').value
833 };
834
835 // Persist the retry identity before posting; a crash must not mint a new invoice.
836 // A changed form intentionally receives a different operation identity.
837 let retryStorageKey = null;
838 if (!data.isPreInvoice) {
839 if (ctx.editId) {
840 // A preinvoice-to-invoice conversion keeps the same identity across retries.
841 data.idempotencyKey = 'preinvoice-finalize:' + ctx.editId;
842 } else {
843 const retryPayload = { ...data };
844 if (ctx.invoiceSettings?.numberingMode !== 'manual') delete retryPayload.number;
845 const signature = JSON.stringify(retryPayload);
846 // Each distinct invoice payload has its own durable retry slot. A pending
847 // invoice in another tab can no longer overwrite this operation's key.
848 retryStorageKey = await createRetryStorageKey(signature);
849 const signatureHash = retryStorageKey.slice(retryStorageKey.lastIndexOf(':') + 1);
850 let pending = null;
851 try { pending = JSON.parse(localStorage.getItem(retryStorageKey) || 'null'); }
852 catch (_) { localStorage.removeItem(retryStorageKey); }
853 const key = pending?.signatureHash === signatureHash && typeof pending?.key === 'string'
854 ? pending.key : crypto.randomUUID();
855 // Persist only the digest and operation key, never customer or invoice data.
856 localStorage.setItem(retryStorageKey, JSON.stringify({ signatureHash, key }));
857 data.idempotencyKey = key;
858 }
859 }
860 if (this._saving) return;
861 this._saving = true;
862 try {
863 const saved = await InvoiceController.save(data, ctx.editId);
864 if (retryStorageKey) localStorage.removeItem(retryStorageKey);
865 Toast.success(ctx.editId ? 'فاکتور ویرایش شد' : `فاکتور #${saved.number} صادر شد`);
866 const savedId = saved.id;
867 Modal.close();
868 if (printAfter) {
869 const { InvoicePrint } = await import('../utils/InvoicePrint.js');
870 setTimeout(() => InvoicePrint.openSettings(savedId), 250);
871 }
872 if (window.InvoicesView) window.InvoicesView.reloadAndRender?.();
873 } catch (err) {
874 console.error(err);
875 Toast.error('خطا: ' + err.message);
876 } finally {
877 this._saving = false;
878 }
879 }
880
881 // ============================================================
882 // Helpers
883 // ============================================================
884 _todayJalali() {
885 const d = new Date();
886 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
887 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
888 let jy = (gy <= 1600) ? 0 : 979;
889 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
890 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
891 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];
892 jy += 33 * Math.floor(days / 12053);
893 days %= 12053;
894 jy += 4 * Math.floor(days / 1461);
895 days %= 1461;
896 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
897 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
898 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
899 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
900 }
901
902 _esc(s) {
903 if (s === null || s === undefined) return '';
904 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
905 }
906 }
907
908 export const InvoiceFormView = new InvoiceFormViewImpl();
909 window.InvoiceFormView = InvoiceFormView;