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

work/a08-memory-stability-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 476 lines 23.4 KB
Raw
1 // ============================================================
2 // InvoiceController — منطق کامل فاکتور
3 // ============================================================
4
5 import { StorageService } from '../core/StorageService.js';
6 import { recordIssuanceReceipt, findIdempotentInvoice, createIssuanceIdentity, idempotencyRecordKey } from '../core/IssuanceReceipt.mjs';
7 import { Auth } from '../core/Auth.js';
8 import { ProductController } from './ProductController.js';
9 import { SettingsController } from './SettingsController.js';
10 import { LicenseService } from '../core/LicenseService.js';
11 import { DataScope } from '../core/DataScope.js';
12 import { RetailPostingService } from '../core/RetailPostingService.js';
13 import { amount, lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
14
15 class InvoiceControllerImpl {
16 // شماره‌ی بعدی سریال (بر اساس نوع سند)
17 async getNextNumber(kind = 'sale') {
18 const all = await DataScope.list('invoices');
19 const kindInvoices = all.filter(i => i.kind === kind && !i.isPreInvoice);
20 const maxNum = kindInvoices.length ? Math.max(...kindInvoices.map(i => Number(i.number) || 0)) : 0;
21 const settings = await SettingsController.getInvoiceSettings();
22 return Math.max(maxNum + 1, Number(settings.nextNumber) || 1);
23 }
24
25 async _assertUniqueNumber(number, excludeId = null) {
26 const all = await DataScope.list('invoices');
27 if (all.some(i => i.id !== excludeId && !i.isPreInvoice && String(i.number) === String(number))) {
28 throw new Error('شماره فاکتور تکراری است');
29 }
30 }
31
32 // ذخیره‌ی فاکتور (ایجاد یا ویرایش)
33 async save(data, id = null) {
34 const retryId = typeof data?.idempotencyKey === 'string' && data.idempotencyKey.length >= 16
35 ? data.idempotencyKey : null;
36 if (id) {
37 const previous = await StorageService.get('invoices', id);
38 if (!previous || previous.companyId !== await DataScope.companyId())
39 throw new Error('فاکتور در شرکت فعال یافت نشد');
40 // Finalized records are rejected inside the issuance transaction unless this is a verified idempotent retry.
41 }
42 const user = Auth.current();
43 const items = (data.items || []).map(it => {
44 const qty = Number(it.qty);
45 const price = amount(it.price ?? 0, 'قیمت');
46 // Both UI and persisted invoice use the exact same whole-rial rule.
47 // Reject quantities with >3 decimals and monetary overflow before writes.
48 const lineSubtotal = lineGrossRials(qty, price);
49 let lineDiscount = 0;
50 // The form stores the USER'S percentage in discountInput and the
51 // resulting rial discount in discount. Reusing discount as a percent
52 // would apply the reduction twice when saving a line.
53 const discInput = Number(it.discountInput ?? it.discount ?? 0);
54 if (!Number.isFinite(discInput) || discInput < 0 ||
55 !['fixed','percent'].includes(it.discountType || 'fixed'))
56 throw Error('تخفیف ردیف فاکتور نامعتبر است');
57 if (it.discountType === 'percent') {
58 lineDiscount = percentOfRials(lineSubtotal,it.discountInput ?? it.discount ?? 0,'درصد تخفیف ردیف');
59 } else {
60 lineDiscount = amount(it.discountInput ?? it.discount ?? 0,'تخفیف ثابت ردیف');
61 }
62 if (lineDiscount > lineSubtotal)
63 throw Error('تخفیف ردیف بیش از مبلغ ناخالص است');
64 const lineTotal = lineSubtotal - lineDiscount;
65 return {
66 productId: it.productId || null,
67 productName: it.productName || '',
68 unit: it.unit || 'عدد',
69 qty,
70 price,
71 discount: lineDiscount,
72 discountInput: discInput,
73 discountType: it.discountType || 'fixed',
74 lineSubtotal,
75 lineTotal
76 };
77 });
78
79 // Every intermediate must fit a safe integer, including pre-invoices
80 // that bypass the finalized double-entry posting boundary.
81 const subtotal = items.reduce((sum, it) => amount(sum + it.lineTotal, 'جمع فاکتور'), 0);
82
83 // تخفیف کلی
84 let totalDiscount = 0;
85 const discInput = data.discountInput ?? 0;
86 if (!['fixed','percent'].includes(data.discountType || 'fixed'))
87 throw Error('نوع تخفیف کل فاکتور نامعتبر است');
88 if (data.discountType === 'percent') {
89 totalDiscount = percentOfRials(subtotal,discInput,'درصد تخفیف کل');
90 } else {
91 totalDiscount = amount(discInput,'تخفیف ثابت کل');
92 }
93 if (totalDiscount > subtotal)
94 throw Error('تخفیف کل نمی‌تواند بیشتر از مبلغ فاکتور باشد');
95
96 const afterDiscount = Math.max(0, subtotal - totalDiscount);
97
98 // مالیات
99 // Validate supplied VAT rate even for tax-exempt invoices.
100 const vatRate = data.vatRate ?? 0;
101 percentOfRials(0,vatRate,'درصد مالیات');
102 let vatAmount = 0;
103 if (data.vatEnabled && data.kind !== 'non_formal')
104 vatAmount = percentOfRials(afterDiscount,vatRate,'درصد مالیات');
105 const grandTotal = amount(afterDiscount + vatAmount, 'جمع کل فاکتور');
106
107 // پرداخت
108 const paidAmount = amount(data.paidAmount ?? 0, 'مبلغ پرداخت');
109 if (paidAmount > grandTotal)
110 throw Error('مبلغ پرداخت بیش از مبلغ فاکتور است');
111 const remaining = Math.max(0, grandTotal - paidAmount);
112
113 const baseData = {
114 ownerUserId: user.id,
115 companyId: await DataScope.companyId(),
116 kind: data.kind || 'sale',
117 requestedNumber: null,
118 isPreInvoice: !!data.isPreInvoice,
119 date: data.date || this._todayJalali(),
120 contactId: data.contactId || null,
121 contactName: data.contactName || '',
122 items,
123 subtotal,
124 totalDiscount,
125 discountType: data.discountType || 'fixed',
126 discountInput: Number(discInput),
127 vatEnabled: !!data.vatEnabled,
128 vatRate: Number(vatRate),
129 vatAmount,
130 grandTotal,
131 paymentMethod: data.paymentMethod || 'cash',
132 paidAmount,
133 remaining,
134 description: (data.description || '').trim(),
135 status: remaining === 0 ? 'paid' : (paidAmount > 0 ? 'partial' : 'unpaid'),
136 originalInvoiceId: data.originalInvoiceId || null,
137 warehouseId: data.warehouseId || null
138 };
139
140 // V2: once activated, issuance, stock movement, settlement and general ledger
141 // must commit together. Existing posted documents are never silently rewritten.
142 if (await RetailPostingService.isEnabled() && !baseData.isPreInvoice) {
143 LicenseService.assertWritable();
144 const previous = id ? await StorageService.get('invoices', id) : null;
145 if (id && (!previous || previous.companyId !== baseData.companyId))
146 throw new Error('فاکتور قطعی قابل ویرایش مستقیم نیست؛ اصلاح از مسیر مرجوعی یا سند معکوس انجام شود');
147 const settings = await SettingsController.getInvoiceSettings();
148 const minimum = await this.getNextNumber(baseData.kind);
149 const typed = String(data.number ?? '').trim().replace(/[۰-۹]/g, c => String(c.charCodeAt(0)-1776));
150 const number = settings.numberingMode === 'manual' && typed ? typed : String(minimum);
151 if (!/^\d+$/.test(number) || !Number.isSafeInteger(Number(number)) || Number(number)<minimum)
152 throw new Error('شماره فاکتور از محدوده مجاز کوچک‌تر است');
153 const invoiceId = id || retryId || StorageService.uid('inv_');
154 const idempotencyKey = retryId || (id
155 ? 'preinvoice-finalize:' + baseData.companyId + ':' + id
156 : 'factor-easypro-invoice-id:' + invoiceId);
157 const issueRequest = { ...baseData, id: invoiceId,
158 requestedNumber: settings.numberingMode === 'manual' ? (data.number ?? null) : null,
159 idempotencyKey, clientUuid: previous?.clientUuid || this._uuid(), number };
160 const identity = await createIssuanceIdentity(issueRequest, idempotencyKey);
161 const issued = await RetailPostingService.issueInvoice({ ...issueRequest, ...identity });
162 await LicenseService.recordIssuedInvoice();
163 // V2 numbering metadata is committed in issueInvoice's transaction.
164 return issued;
165 }
166
167 // The invoice, stock movements, receipt, idempotency record and IndexedDB
168 // quota counter commit together. DPAPI SecureState is a separate high-water
169 // mirror and is reconciled from the committed IndexedDB ledger on restart.
170 let saved;
171 let settings = null;
172 let issuedNow = false;
173 let nextNumber = null;
174 if (id) {
175 const existing = await StorageService.get('invoices', id);
176 if (!existing || existing.companyId !== baseData.companyId) throw new Error('Invoice not found in active company');
177 issuedNow = !!existing.isPreInvoice && !baseData.isPreInvoice;
178 if (issuedNow) LicenseService.assertWritable();
179 saved = { ...existing, ...baseData };
180 } else {
181 if (!baseData.isPreInvoice) LicenseService.assertWritable();
182 settings = await SettingsController.getInvoiceSettings();
183 const minimum = await this.getNextNumber(baseData.kind);
184 const rawNumber = String(data.number ?? '').trim().replace(/[۰-۹]/g, ch => String(ch.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, ch => String(ch.charCodeAt(0) - 1632));
185 const number = settings.numberingMode === 'manual' ? (rawNumber || String(minimum)) : String(minimum);
186 if (!/^\d+$/.test(number) || !Number.isSafeInteger(Number(number)) || Number(number) < minimum) {
187 throw new Error(`Invoice number must be at least ${minimum}`);
188 }
189 saved = {
190 id: retryId || StorageService.uid('inv_'),
191 clientUuid: this._uuid(),
192 number,
193 ...baseData
194 };
195 issuedNow = !baseData.isPreInvoice;
196 if (issuedNow) nextNumber = Math.max(Number(settings.nextNumber) || 1, Number(number) + 1);
197 }
198 if (!saved.isPreInvoice) {
199 saved.requestedNumber = id
200 ? (saved.requestedNumber ?? saved.number ?? null)
201 : (settings?.numberingMode === 'manual' ? (data.number ?? null) : null);
202 const idempotencyKey = retryId || (id
203 ? 'preinvoice-finalize:' + baseData.companyId + ':' + id
204 : 'factor-easypro-invoice-id:' + saved.id);
205 const identity = await createIssuanceIdentity(saved, idempotencyKey);
206 saved = { ...saved, ...identity };
207 }
208
209 saved = await this._commitLegacyInvoiceWithStock(saved, {
210 requireExisting: Boolean(id), requirePreInvoice: false
211 });
212 if (!saved.isPreInvoice) await LicenseService.recordIssuedInvoice();
213 // Return the row read/committed inside the transaction, including on replay.
214 return saved;
215 }
216
217 // All legacy invoice and inventory mutations share one transaction. Both
218 // active-company checks and concurrent update checks run inside the lock.
219 async _commitLegacyInvoiceWithStock(invoice, { requireExisting = false, requirePreInvoice = false } = {}) {
220 if (invoice && !invoice.isPreInvoice) {
221 const identity = await createIssuanceIdentity(invoice,
222 invoice.idempotencyKey || ('factor-easypro-invoice-id:' + invoice.id));
223 invoice = { ...invoice, ...identity };
224 }
225 const companyId = await DataScope.companyId();
226 if (!invoice || invoice.companyId !== companyId) throw new Error('Invoice outside active company');
227 const user = Auth.current();
228 const direction = ['purchase', 'sale_return'].includes(invoice.kind) ? 'in' : 'out';
229 return StorageService.transaction(['invoices', 'stock_movements', 'products', 'settings'], async tx => {
230 if (!invoice.isPreInvoice) {
231 const replay = await findIdempotentInvoice(tx, invoice);
232 if (replay) return replay;
233 }
234 const existing = await tx.get('invoices', invoice.id);
235 if (requireExisting && (!existing || existing.companyId !== companyId)) throw new Error('Invoice not found in active company');
236 if (!requireExisting && existing) throw new Error('Duplicate invoice id');
237 if (existing?.financePosted) throw new Error('Posted invoice is immutable');
238 if (existing && !existing.isPreInvoice && !invoice.isPreInvoice)
239 throw new Error('Issued invoice is immutable; only a verified idempotent retry may replay it');
240 if (requirePreInvoice && !existing?.isPreInvoice) throw new Error('Preinvoice required');
241 if (existing && !requirePreInvoice && existing.isPreInvoice !== invoice.isPreInvoice && !existing.isPreInvoice) {
242 throw new Error('Issued invoice cannot be reverted to preinvoice');
243 }
244 const allInvoices = await tx.getAll('invoices');
245 if (!invoice.isPreInvoice && allInvoices.some(row =>
246 row.id !== invoice.id && row.companyId === companyId && !row.isPreInvoice &&
247 String(row.number) === String(invoice.number))) {
248 throw new Error('Duplicate issued invoice number');
249 }
250 const movements = await tx.getAll('stock_movements');
251 for (const movement of movements.filter(row => row.companyId === companyId && row.refType === 'invoice' && row.refId === invoice.id)) {
252 await tx.delete('stock_movements', movement.id);
253 }
254 if (!invoice.isPreInvoice) {
255 for (const item of invoice.items || []) {
256 if (!item.productId) continue;
257 const product = await tx.get('products', item.productId);
258 if (!product || product.companyId !== companyId) throw new Error('Invoice item references a product outside the active company');
259 if (product.trackInventory === false) continue;
260 await tx.put('stock_movements', {
261 id: StorageService.uid('mv_'), ownerUserId: user.id, companyId,
262 productId: item.productId, type: direction, qty: Number(item.qty) || 0,
263 refType: 'invoice', refId: invoice.id,
264 note: `Invoice #${invoice.number}`, date: new Date().toISOString()
265 });
266 }
267 }
268 await tx.put('invoices', invoice);
269 if (!invoice.isPreInvoice && (!existing || existing.isPreInvoice)) {
270 await recordIssuanceReceipt(tx, invoice, LicenseService.issuanceQuota());
271 }
272 if (!invoice.isPreInvoice) {
273 const key = `invoice_numbering_${companyId}`;
274 const prior = await tx.get('settings', key);
275 const numeric = Number(invoice.number);
276 if (!Number.isSafeInteger(numeric) || numeric < 1 || numeric >= Number.MAX_SAFE_INTEGER) {
277 throw new Error('Invalid invoice number for atomic numbering');
278 }
279 await tx.put('settings', {
280 ...prior, id: key, companyId,
281 numberingMode: prior?.numberingMode === 'manual' ? 'manual' : 'auto',
282 nextNumber: Math.max(Number(prior?.nextNumber) || 1, numeric + 1)
283 });
284 }
285 return invoice;
286 });
287 }
288
289 async _rebuildStockMovements(invoice) {
290 // Retained for older callers. InvoiceController.save and convertPreInvoice
291 // use the full invoice+stock transaction instead.
292 const companyId = await DataScope.companyId();
293 if (!invoice || invoice.companyId !== companyId) throw new Error('Invoice stock rebuild is restricted to the active company');
294 const user = Auth.current();
295 const direction = ['purchase', 'sale_return'].includes(invoice.kind) ? 'in' : 'out';
296 return StorageService.transaction(['stock_movements', 'products'], async tx => {
297 const movements = await tx.getAll('stock_movements');
298 for (const movement of movements.filter(m => m.companyId === companyId && m.refType === 'invoice' && m.refId === invoice.id)) {
299 await tx.delete('stock_movements', movement.id);
300 }
301 if (invoice.isPreInvoice) return;
302 for (const item of invoice.items || []) {
303 if (!item.productId) continue;
304 const product = await tx.get('products', item.productId);
305 if (!product || product.companyId !== companyId) throw new Error('Invoice item references a product outside the active company');
306 if (product.trackInventory === false) continue;
307 await tx.put('stock_movements', {
308 id: StorageService.uid('mv_'), ownerUserId: user.id, companyId,
309 productId: item.productId, type: direction, qty: Number(item.qty) || 0,
310 refType: 'invoice', refId: invoice.id,
311 note: `Invoice #${invoice.number}`, date: new Date().toISOString()
312 });
313 }
314 });
315 }
316
317 async getAll(filter = {}) {
318 const user = Auth.current();
319 let list = await DataScope.list('invoices');
320
321 if (filter.kind) list = list.filter(i => i.kind === filter.kind);
322 if (filter.preInvoice !== undefined && filter.preInvoice !== '') {
323 list = list.filter(i => !!i.isPreInvoice === filter.preInvoice);
324 }
325 if (filter.contactId) list = list.filter(i => i.contactId === filter.contactId);
326 if (filter.paymentStatus) {
327 list = list.filter(i => i.status === filter.paymentStatus);
328 }
329 if (filter.search) {
330 const q = String(filter.search).toLowerCase();
331 list = list.filter(i =>
332 String(i.number || '').includes(q) ||
333 (i.contactName || '').toLowerCase().includes(q) ||
334 (i.description || '').toLowerCase().includes(q)
335 );
336 }
337 if (filter.dateFrom) list = list.filter(i => (i.date || '') >= filter.dateFrom);
338 if (filter.dateTo) list = list.filter(i => (i.date || '') <= filter.dateTo);
339
340 return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
341 }
342
343 async get(id) {
344 return await StorageService.get('invoices', id);
345 }
346
347 async delete(id) {
348 const companyId = await DataScope.companyId();
349 // Invoice and its stock movements must disappear together or not at all.
350 // This also serializes deletion against other invoice-store transactions.
351 return StorageService.transaction(['invoices', 'stock_movements'], async tx => {
352 const record = await tx.get('invoices', id);
353 if (!record || record.companyId !== companyId) throw new Error('فاکتور در شرکت جاری یافت نشد');
354 if (record.financePosted) throw new Error('حذف فاکتور ثبت مالی‌شده مجاز نیست');
355 const movements = await tx.getAll('stock_movements');
356 for (const m of movements.filter(x => x.companyId === companyId && x.refType === 'invoice' && x.refId === id)) {
357 await tx.delete('stock_movements', m.id);
358 }
359 await tx.delete('invoices', id);
360 });
361 }
362 // تبدیل پیش‌فاکتور به فاکتور
363 async convertPreInvoice(id) {
364 const companyId = await DataScope.companyId();
365 const idempotencyKey = 'factor-easypro-preinvoice-finalize:' + companyId + ':' + id;
366 const priorRecord = await StorageService.get('settings', idempotencyRecordKey(companyId, idempotencyKey));
367 if (priorRecord) {
368 const priorInvoice = await StorageService.get('invoices', priorRecord.invoiceId);
369 if (!priorInvoice || priorInvoice.companyId !== companyId)
370 throw Error('Preinvoice idempotency record requires recovery');
371 return priorInvoice;
372 }
373 LicenseService.assertWritable();
374 const inv = await StorageService.get('invoices', id);
375 if (!inv || inv.companyId !== companyId || !inv.isPreInvoice)
376 throw new Error('Preinvoice not found in active company');
377 if (await RetailPostingService.isEnabled()) {
378 const number = await this.getNextNumber(inv.kind);
379 const issued = await RetailPostingService.issueInvoice({ ...inv, isPreInvoice: false, number, idempotencyKey });
380 await LicenseService.recordIssuedInvoice();
381 const settings = await SettingsController.getInvoiceSettings();
382 // V2 numbering metadata is committed in issueInvoice's transaction.
383 return issued;
384 }
385 const number = await this.getNextNumber(inv.kind);
386 await this._assertUniqueNumber(number, inv.id);
387 const issued = { ...inv, isPreInvoice: false, number, idempotencyKey };
388 const committed = await this._commitLegacyInvoiceWithStock(issued, {
389 requireExisting: true, requirePreInvoice: true
390 });
391 await LicenseService.recordIssuedInvoice();
392 return committed;
393 }
394
395 // Payments serialize with invoice mutations.
396 async markPaid(id, payment = null) {
397 // The invoice read, validation and write must share one IndexedDB transaction.
398 // Concurrent payment attempts serialize on the invoices object store.
399 const companyId = await DataScope.companyId();
400 return StorageService.transaction(['invoices'], async tx => {
401 const inv = await tx.get('invoices', id);
402 if (!inv || inv.companyId !== companyId) throw new Error('فاکتور در شرکت جاری یافت نشد');
403 if (inv.financePosted) throw new Error('پرداخت فاکتور ثبت مالی‌شده از این مسیر مجاز نیست');
404 if (inv.isPreInvoice) throw new Error('ثبت پرداخت برای پیش‌فاکتور مجاز نیست');
405 const total = amount(inv.grandTotal, 'مبلغ فاکتور');
406 const alreadyPaid = amount(inv.paidAmount ?? 0, 'مبلغ پرداخت‌شده');
407 if (alreadyPaid > total) throw new Error('مبلغ پرداخت‌شده بیشتر از مبلغ فاکتور است');
408 const remaining = total - alreadyPaid;
409 const pay = payment === null ? remaining : amount(payment, 'مبلغ پرداخت');
410 if (pay <= 0 || pay > remaining) throw new Error('مبلغ پرداخت باید مثبت و حداکثر برابر مانده فاکتور باشد');
411 inv.paidAmount = alreadyPaid + pay;
412 inv.remaining = total - inv.paidAmount;
413 inv.status = inv.remaining === 0 ? 'paid' : 'partial';
414 inv.companyId = companyId;
415 return tx.put('invoices', inv);
416 });
417 }
418 // آمار برای داشبورد
419 async getStats() {
420 const all = await DataScope.list('invoices');
421 const salesInvoices = all.filter(i => i.kind === 'sale' && !i.isPreInvoice);
422
423 const totalSales = salesInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
424 const totalPaid = salesInvoices.reduce((s, i) => s + (Number(i.paidAmount) || 0), 0);
425 const totalRemaining = salesInvoices.reduce((s, i) => s + (Number(i.remaining) || 0), 0);
426
427 return {
428 count: all.length,
429 salesCount: salesInvoices.length,
430 totalSales,
431 totalPaid,
432 totalRemaining,
433 preInvoiceCount: all.filter(i => i.isPreInvoice).length
434 };
435 }
436
437 // لیبل نوع سند
438 getKindLabel(kind) {
439 const labels = {
440 sale: 'فاکتور فروش',
441 purchase: 'فاکتور خرید',
442 sale_return: 'برگشت از فروش',
443 purchase_return: 'برگشت از خرید',
444 non_formal: 'غیررسمی'
445 };
446 return labels[kind] || kind;
447 }
448
449 _todayJalali() {
450 const d = new Date();
451 const gy = d.getFullYear(), gm = d.getMonth() + 1, gd = d.getDate();
452 const g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
453 let jy = (gy <= 1600) ? 0 : 979;
454 let gy2 = gy - (gy <= 1600 ? 621 : 1600);
455 const gyAdj = (gm > 2) ? (gy2 + 1) : gy2;
456 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];
457 jy += 33 * Math.floor(days / 12053);
458 days %= 12053;
459 jy += 4 * Math.floor(days / 1461);
460 days %= 1461;
461 if (days > 365) { jy += Math.floor((days - 1) / 365); days = (days - 1) % 365; }
462 const jm = (days < 186) ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30);
463 const jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
464 return `${jy}/${String(jm).padStart(2, '0')}/${String(jd).padStart(2, '0')}`;
465 }
466
467 _uuid() {
468 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
469 const r = Math.random() * 16 | 0;
470 const v = c === 'x' ? r : (r & 0x3 | 0x8);
471 return v.toString(16);
472 });
473 }
474 }
475
476 export const InvoiceController = new InvoiceControllerImpl();