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