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