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

fix(finance): isolate atomic issuance and return-credit flows with regression tests

Davood Mehraban committed Nov 23, 2026 at 08:55 UTC 96bbbc61dfdf59ddbc0e9d1ec09ff3e2db4cb129
28 files changed +1510 -72
src/controllers/InvoiceController.js
+80 -23
@@ -3,6 +3,7 @@
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';
@@ -30,12 +31,13 @@ class InvoiceControllerImpl {
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('فاکتور در شرکت فعال یافت نشد');
37 - if (previous.financePosted)
38 - 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 => {
@@ -112,6 +114,7 @@ class InvoiceControllerImpl {
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,
@@ -139,7 +142,7 @@ class InvoiceControllerImpl {
142 if (await RetailPostingService.isEnabled() && !baseData.isPreInvoice) {
143 LicenseService.assertWritable();
144 const previous = id ? await StorageService.get('invoices', id) : null;
142 - if (id && (!previous || previous.companyId !== baseData.companyId || !previous.isPreInvoice))
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);
@@ -147,17 +150,23 @@ class InvoiceControllerImpl {
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('شماره فاکتور از محدوده مجاز کوچک‌تر است');
150 - const issued = await RetailPostingService.issueInvoice({ ...baseData,
151 - id: id || StorageService.uid('inv_'), clientUuid: previous?.clientUuid || this._uuid(), number });
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();
153 - await SettingsController.saveInvoiceSettings({ ...settings,
154 - nextNumber: Math.max(Number(settings.nextNumber)||1, Number(number)+1) });
163 + // V2 numbering metadata is committed in issueInvoice's transaction.
164 return issued;
165 }
166
158 - // Prepare the legacy invoice before opening IndexedDB transaction.
159 - // License counters and settings are secondary metadata and cannot be
160 - // atomically committed with IndexedDB; they are updated only after commit.
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;
@@ -178,7 +187,7 @@ class InvoiceControllerImpl {
187 throw new Error(`Invoice number must be at least ${minimum}`);
188 }
189 saved = {
181 - id: StorageService.uid('inv_'),
190 + id: retryId || StorageService.uid('inv_'),
191 clientUuid: this._uuid(),
192 number,
193 ...baseData
@@ -186,27 +195,48 @@ class InvoiceControllerImpl {
195 issuedNow = !baseData.isPreInvoice;
196 if (issuedNow) nextNumber = Math.max(Number(settings.nextNumber) || 1, Number(number) + 1);
197 }
189 -
190 - await this._commitLegacyInvoiceWithStock(saved, { requireExisting: Boolean(id), requirePreInvoice: false });
191 - if (issuedNow) await LicenseService.recordIssuedInvoice();
192 - if (nextNumber !== null) {
193 - await SettingsController.saveInvoiceSettings({ ...settings, nextNumber });
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';
205 - return StorageService.transaction(['invoices', 'stock_movements', 'products'], async tx => {
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');
@@ -236,6 +266,22 @@ class InvoiceControllerImpl {
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 }
@@ -315,24 +361,35 @@ class InvoiceControllerImpl {
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);
320 - if (!inv || inv.companyId !== await DataScope.companyId() || !inv.isPreInvoice)
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);
324 - const issued = await RetailPostingService.issueInvoice({ ...inv, isPreInvoice: false, number });
379 + const issued = await RetailPostingService.issueInvoice({ ...inv, isPreInvoice: false, number, idempotencyKey });
380 await LicenseService.recordIssuedInvoice();
381 const settings = await SettingsController.getInvoiceSettings();
327 - await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber) || 1, Number(number) + 1) });
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);
332 - const issued = { ...inv, isPreInvoice: false, number };
333 - await this._commitLegacyInvoiceWithStock(issued, { requireExisting: true, requirePreInvoice: true });
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();
335 - return issued;
392 + return committed;
393 }
394
395 // Payments serialize with invoice mutations.
src/controllers/ReportController.js
+11 -1
@@ -400,7 +400,8 @@ class ReportControllerImpl {
400 totalReturns: 0,
401 netSales: 0,
402 totalPaid: 0,
403 - totalRemaining: 0
403 + totalRemaining: 0,
404 + returnCreditRemaining: 0
405 };
406 }
407 if (invoice.kind === 'sale') {
@@ -411,6 +412,10 @@ class ReportControllerImpl {
412 } else {
413 contactStats[key].returnCount += 1;
414 contactStats[key].totalReturns += Number(invoice.grandTotal) || 0;
415 + contactStats[key].totalPaid -= Number(invoice.paidAmount) || 0;
416 + const returnCreditRemaining = Number(invoice.remaining) || 0;
417 + contactStats[key].returnCreditRemaining += returnCreditRemaining;
418 + contactStats[key].totalRemaining -= returnCreditRemaining;
419 }
420 });
421
@@ -462,6 +467,7 @@ class ReportControllerImpl {
467 netSales: 0,
468 totalPaid: 0,
469 totalRemaining: 0,
470 + returnCreditRemaining: 0,
471 lastInvoiceDate: ''
472 };
473 }
@@ -473,6 +479,10 @@ class ReportControllerImpl {
479 } else {
480 stats[key].returnCount += 1;
481 stats[key].totalReturns += Number(invoice.grandTotal) || 0;
482 + stats[key].totalPaid -= Number(invoice.paidAmount) || 0;
483 + const returnCreditRemaining = Number(invoice.remaining) || 0;
484 + stats[key].returnCreditRemaining += returnCreditRemaining;
485 + stats[key].totalRemaining -= returnCreditRemaining;
486 }
487 if (invoice.date > (stats[key].lastInvoiceDate || ''))
488 stats[key].lastInvoiceDate = invoice.date;
src/controllers/TreasuryController.js
+29 -4
@@ -220,6 +220,7 @@ class TreasuryControllerImpl {
220 throw Error('حساب مبدا و مقصد انتقال باید متفاوت و مشخص باشند');
221 const tx = {
222 id: StorageService.uid('tx_'),
223 + idempotencyKey: data.idempotencyKey || null,
224 recordType: 'transaction',
225 ownerUserId: user.id,
226 type: data.type, // receipt | payment | transfer
@@ -237,12 +238,36 @@ class TreasuryControllerImpl {
238 ...(data.reasonCode ? { reasonCode: data.reasonCode } : {}),
239 ...(data.explicitlyApproved === true ? { explicitlyApproved: true } : {})
240 };
241 + const scoped = await DataScope.stamp('treasury', tx);
242 if (await RetailPostingService.isEnabled()) {
241 - return RetailPostingService.postTransaction(await DataScope.stamp('treasury',tx));
243 + return RetailPostingService.postTransaction(scoped);
244 }
243 - return await StorageService.put('treasury', await DataScope.stamp('treasury', tx));
245 + if (!scoped.idempotencyKey) return StorageService.put('treasury', scoped);
246 + if (String(scoped.idempotencyKey).length > 200) throw Error('طول کلید تکرارپذیری بیش از حد مجاز است');
247 + return StorageService.transaction('treasury', async store => {
248 + const duplicate = (await store.getAll('treasury')).find(row =>
249 + row.companyId === scoped.companyId && row.recordType === 'transaction' &&
250 + row.idempotencyKey === scoped.idempotencyKey);
251 + if (duplicate) {
252 + const sameRequest = duplicate.type === scoped.type &&
253 + Number(duplicate.amount) === transactionAmount &&
254 + (duplicate.fromAccountId || null) === (scoped.fromAccountId || null) &&
255 + (duplicate.toAccountId || null) === (scoped.toAccountId || null) &&
256 + (duplicate.contactId || null) === (scoped.contactId || null) &&
257 + (duplicate.refInvoiceId || null) === (scoped.refInvoiceId || null) &&
258 + (duplicate.method || 'cash') === (scoped.method || 'cash') &&
259 + (duplicate.date || '') === (scoped.date || '') &&
260 + (duplicate.description || '') === (scoped.description || '') &&
261 + (duplicate.reasonCode || null) === (scoped.reasonCode || null) &&
262 + (duplicate.explicitlyApproved === true) === (scoped.explicitlyApproved === true);
263 + if (!sameRequest) throw Error('کلید تکرارپذیری قبلاً برای درخواست مالی متفاوت استفاده شده است');
264 + return duplicate;
265 + }
266 + if (await store.get('treasury', scoped.id)) throw Error('تراکنش تکراری است');
267 + await store.put('treasury', scoped);
268 + return scoped;
269 + });
270 }
245 -
271 async deleteTransaction(id) {
272 const existing = await StorageService.get('treasury', id);
273 if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('تراکنش در شرکت فعال یافت نشد');
@@ -289,4 +314,4 @@ class TreasuryControllerImpl {
314 }
315 }
316
292 -export const TreasuryController = new TreasuryControllerImpl();
\ No newline at end of file
317 +export const TreasuryController = new TreasuryControllerImpl();
src/core/Auth.js
+1 -1
@@ -160,7 +160,7 @@ class AuthImpl {
160 root.setAttribute('dir', 'rtl');
161 root.style.cssText = 'position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:#0f172a;font-family:inherit;';
162 root.innerHTML = `
163 - <form id="finoraAuthForm" autocomplete="on" style="width:min(92vw,380px);background:#fff;color:#0f172a;border-radius:16px;padding:28px;box-shadow:0 20px 60px rgba(0,0,0,.4);display:flex;flex-direction:column;gap:12px;">
163 + <form id="finoraAuthForm" autocomplete="off" style="width:min(92vw,380px);background:#fff;color:#0f172a;border-radius:16px;padding:28px;box-shadow:0 20px 60px rgba(0,0,0,.4);display:flex;flex-direction:column;gap:12px;">
164 <div id="faTitle" style="font-size:20px;font-weight:700;"></div>
165 <div id="faHint" style="font-size:13px;color:#475569;line-height:1.7;"></div>
166 <input id="faUser" name="username" type="text" placeholder="نام کاربری" autocomplete="username" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;">
src/core/IssuanceReceipt.mjs new
+155
@@ -0,0 +1,155 @@
1 +export const receiptKey = (companyId, invoiceId) =>
2 + 'issuance_receipt_' + JSON.stringify([companyId, invoiceId]);
3 +export const counterKey = 'issuance_global_counter_v1';
4 +export const idempotencyRecordKey = (companyId, key) =>
5 + 'issuance_idempotency_' + JSON.stringify([companyId, key]);
6 +
7 +export async function createTreasuryRetryIdentity(signature, storageService,
8 + makeId = () => globalThis.crypto.randomUUID()) {
9 + if (typeof signature !== 'string' || !signature.length || signature.length > 32768)
10 + throw Error('Invalid treasury retry signature');
11 + if (!storageService || typeof storageService.transaction !== 'function')
12 + throw Error('Durable treasury retry storage is unavailable');
13 + const digest = await globalThis.crypto.subtle.digest(
14 + 'SHA-256', new TextEncoder().encode(signature)
15 + );
16 + const signatureHash = Array.from(new Uint8Array(digest),
17 + byte => byte.toString(16).padStart(2, '0')).join('');
18 + const storageKey = 'treasury_retry_v1:' + signatureHash;
19 + return storageService.transaction('settings', async tx => {
20 + const pending = await tx.get('settings', storageKey);
21 + if (pending) {
22 + if (pending.signatureHash !== signatureHash ||
23 + typeof pending.idempotencyKey !== 'string' ||
24 + pending.idempotencyKey.length < 16 || pending.idempotencyKey.length > 256)
25 + throw Error('Corrupt treasury retry identity; posting is blocked');
26 + return { storageKey, idempotencyKey: pending.idempotencyKey };
27 + }
28 + const idempotencyKey = makeId();
29 + if (typeof idempotencyKey !== 'string' || idempotencyKey.length < 16 || idempotencyKey.length > 256)
30 + throw Error('Invalid treasury idempotency key');
31 + await tx.put('settings', {
32 + id: storageKey, signatureHash, idempotencyKey,
33 + recordType: 'treasury_retry_pending', schemaVersion: 1
34 + });
35 + return { storageKey, idempotencyKey };
36 + });
37 +}
38 +
39 +export async function clearTreasuryRetryIdentity(storageService, identity) {
40 + if (!storageService || typeof storageService.transaction !== 'function' ||
41 + !identity?.storageKey || typeof identity.idempotencyKey !== 'string')
42 + throw Error('Invalid treasury retry cleanup identity');
43 + return storageService.transaction('settings', async tx => {
44 + const pending = await tx.get('settings', identity.storageKey);
45 + if (!pending || pending.idempotencyKey !== identity.idempotencyKey) return false;
46 + await tx.delete('settings', identity.storageKey);
47 + return true;
48 + });
49 +}
50 +export async function createRetryStorageKey(signature) {
51 + if (typeof signature !== 'string' || !signature.length)
52 + throw Error('Invalid retry signature');
53 + const digest = await globalThis.crypto.subtle.digest(
54 + 'SHA-256', new TextEncoder().encode(signature)
55 + );
56 + const hex = Array.from(new Uint8Array(digest),
57 + byte => byte.toString(16).padStart(2, '0')).join('');
58 + return 'factor_easypro_pending_invoice_v2:' + hex;
59 +}
60 +
61 +function canonical(value) {
62 + if (Array.isArray(value)) return value.map(canonical);
63 + if (value && typeof value === 'object') {
64 + const result = {};
65 + for (const key of Object.keys(value).sort()) {
66 + if (value[key] !== undefined) result[key] = canonical(value[key]);
67 + }
68 + return result;
69 + }
70 + if (typeof value === 'number' && !Number.isFinite(value))
71 + throw Error('Invalid non-finite value in issuance request');
72 + return value;
73 +}
74 +
75 +export async function createIssuanceIdentity(invoice, idempotencyKey) {
76 + if (!invoice?.companyId || typeof idempotencyKey !== 'string' ||
77 + idempotencyKey.length < 16 || idempotencyKey.length > 256)
78 + throw Error('Invalid issuance idempotency identity');
79 + const payload = {
80 + companyId: invoice.companyId,
81 + kind: invoice.kind,
82 + isPreInvoice: false,
83 + requestedNumber: invoice.requestedNumber ?? null,
84 + date: invoice.date ?? null,
85 + contactId: invoice.contactId ?? null,
86 + contactName: invoice.contactName ?? '',
87 + items: invoice.items ?? [],
88 + subtotal: invoice.subtotal,
89 + totalDiscount: invoice.totalDiscount,
90 + discountType: invoice.discountType,
91 + discountInput: invoice.discountInput,
92 + vatEnabled: invoice.vatEnabled,
93 + vatRate: invoice.vatRate,
94 + vatAmount: invoice.vatAmount,
95 + grandTotal: invoice.grandTotal,
96 + paymentMethod: invoice.paymentMethod,
97 + paidAmount: invoice.requestedPaidAmount ?? invoice.paidAmount ?? 0,
98 + originalInvoiceId: invoice.originalInvoiceId ?? null,
99 + warehouseId: Object.hasOwn(invoice, 'requestedWarehouseId') ? invoice.requestedWarehouseId : (invoice.warehouseId ?? null),
100 + description: invoice.description ?? ''
101 + };
102 + const bytes = new TextEncoder().encode(JSON.stringify(canonical(payload)));
103 + const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);
104 + const requestHash = Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('');
105 + return { idempotencyKey, requestHash, requestedPaidAmount: invoice.requestedPaidAmount ?? invoice.paidAmount ?? 0, requestedWarehouseId: Object.hasOwn(invoice, 'requestedWarehouseId') ? invoice.requestedWarehouseId : (invoice.warehouseId ?? null) };
106 +}
107 +
108 +export async function findIdempotentInvoice(tx, invoice) {
109 + const key = invoice?.idempotencyKey;
110 + if (!key) return null;
111 + const record = await tx.get('settings', idempotencyRecordKey(invoice.companyId, key));
112 + if (!record) return null;
113 + if (record.companyId !== invoice.companyId || record.requestHash !== invoice.requestHash)
114 + throw Error('Idempotency key reused with different invoice content');
115 + const previous = await tx.get('invoices', record.invoiceId);
116 + if (!previous || previous.companyId !== invoice.companyId)
117 + throw Error('Idempotency record exists without its invoice; issuance is blocked for safe recovery');
118 + return previous;
119 +}
120 +
121 +export async function recordIssuanceReceipt(tx, invoice, quota) {
122 + if (!invoice?.id || !invoice?.companyId || invoice.isPreInvoice)
123 + throw Error('Invalid issuance receipt');
124 + if (typeof invoice.idempotencyKey !== 'string' ||
125 + invoice.idempotencyKey.length < 16 || invoice.idempotencyKey.length > 256 ||
126 + typeof invoice.requestHash !== 'string' || !/^[a-f0-9]{64}$/.test(invoice.requestHash))
127 + throw Error('A durable idempotency key and request fingerprint are mandatory');
128 + const id = receiptKey(invoice.companyId, invoice.id);
129 + if (await tx.get('settings', id)) throw Error('Duplicate issuance receipt');
130 + const key = idempotencyRecordKey(invoice.companyId, invoice.idempotencyKey);
131 + if (await tx.get('settings', key)) throw Error('Duplicate issuance idempotency record');
132 + if (!quota || !Number.isSafeInteger(quota.floor) || quota.floor < 0 ||
133 + !Number.isSafeInteger(quota.limit) || quota.limit < 1)
134 + throw Error('A valid issuance quota is mandatory');
135 + const previous = await tx.get('settings', counterKey);
136 + const persisted = previous?.count;
137 + if (previous && (!Number.isSafeInteger(persisted) || persisted < 0))
138 + throw Error('Corrupt issuance counter');
139 + const current = Math.max(persisted ?? 0, quota.floor);
140 + if (current >= quota.limit) throw Error('Invoice quota exhausted');
141 + await tx.put('settings', {
142 + id: counterKey, count: current + 1, schemaVersion: 1
143 + });
144 + await tx.put('settings', {
145 + id, companyId: invoice.companyId, invoiceId: invoice.id,
146 + number: String(invoice.number), kind: invoice.kind, schemaVersion: 1
147 + });
148 + if (invoice.idempotencyKey) {
149 + await tx.put('settings', {
150 + id: idempotencyRecordKey(invoice.companyId, invoice.idempotencyKey),
151 + companyId: invoice.companyId, idempotencyKey: invoice.idempotencyKey,
152 + requestHash: invoice.requestHash, invoiceId: invoice.id, schemaVersion: 1
153 + });
154 + }
155 +}
src/core/LicenseService.js
+40 -6
@@ -1,4 +1,6 @@
1 import { SecureState } from './SecureState.js';
2 +import { StorageService } from './StorageService.js';
3 +import { counterKey } from './IssuanceReceipt.mjs';
4 import { trialStatus, licensedStatus } from './LicensePolicy.mjs';
5 import { validateEntitlementPayload } from './EntitlementVerifier.mjs';
6 import { loadProductionLicensePublicKey, validateOfflineActivation } from './LicenseActivationCore.mjs';
@@ -45,6 +47,7 @@ class LicenseServiceImpl {
47 this.clockRollback = Number.isFinite(previousClock) && now + 5 * 60 * 1000 < previousClock;
48 this.state = stored;
49 this.verifiedPayload = null;
50 + await this.reconcileIssuedInvoices();
51 if (!this.clockRollback && await validateOfflineActivation(
52 stored.signedEntitlement, trustedPublicKey, stored.installationId, now
53 )) {
@@ -58,6 +61,42 @@ class LicenseServiceImpl {
61 }
62
63 async _save() { await SecureState.set(KEY, this.state); }
64 + issuanceQuota() {
65 + this.assertWritable();
66 + const count = this.state?.issuedInvoiceCount;
67 + if (!Number.isSafeInteger(count) || count < 0)
68 + throw Error('Invalid persisted invoice count');
69 + return { floor: count, limit: this.verifiedPayload ? Number.MAX_SAFE_INTEGER : 20 };
70 + }
71 + async reconcileIssuedInvoices() {
72 + const previous = this.state?.issuedInvoiceCount;
73 + if (previous !== undefined && (!Number.isSafeInteger(previous) || previous < 0))
74 + throw Error('Corrupt secure invoice count');
75 + const reconciled = await StorageService.transaction(['invoices', 'settings'], async tx => {
76 + const persisted = await tx.get('settings', counterKey);
77 + if (persisted && (!Number.isSafeInteger(persisted.count) || persisted.count < 0))
78 + throw Error('Corrupt atomic issuance counter');
79 + const settings = await tx.getAll('settings');
80 + const receipts = settings.filter(row =>
81 + typeof row.id === 'string' && row.id.startsWith('issuance_receipt_')).length;
82 + const invoices = await tx.getAll('invoices');
83 + // If older installations have no receipt ledger, conservatively count
84 + // every surviving finalized invoice rather than silently granting a fresh trial.
85 + const historical = invoices.filter(row => row && !row.isPreInvoice).length;
86 + const count = Math.max(previous ?? 0, persisted?.count ?? 0, receipts, historical);
87 + if (!persisted || persisted.count !== count) {
88 + await tx.put('settings', { id: counterKey, count, schemaVersion: 1 });
89 + }
90 + return count;
91 + });
92 + this.state.issuedInvoiceCount = reconciled;
93 + return reconciled;
94 + }
95 + async recordIssuedInvoice() {
96 + await this.reconcileIssuedInvoices();
97 + await this._save();
98 + return this.status();
99 + }
100 hasTrustedIssuer() { return Boolean(trustedPublicKey); }
101 installationId() { return this.state?.installationId || null; }
102
@@ -110,11 +149,6 @@ class LicenseServiceImpl {
149 throw new Error('دوره استفاده یا مجوز به پایان رسیده است؛ اطلاعات فقط قابل مشاهده‌اند.');
150 }
151 }
113 - async recordIssuedInvoice() {
114 - this.assertWritable();
115 - this.state.issuedInvoiceCount = (this.state.issuedInvoiceCount || 0) + 1;
116 - await this._save();
117 - return this.status();
118 - }
152 +
153 }
154 export const LicenseService = new LicenseServiceImpl();
src/core/RetailPostingService.js
+120 -10
@@ -1,10 +1,13 @@
1 // Phase 2 transactional commercial posting. Every dependent row shares one IndexedDB transaction.
2 import { StorageService } from './StorageService.js';
3 +import { recordIssuanceReceipt, findIdempotentInvoice, createIssuanceIdentity } from './IssuanceReceipt.mjs';
4 +import { LicenseService } from './LicenseService.js';
5 import { DataScope } from './DataScope.js';
6 import { Auth } from './Auth.js';
7 import { AuditService } from './AuditService.js';
8 import { validateJournal, journalSourceKey, assertJalaliDate } from './AccountingCore.mjs';
9 import { previewSaleReturnSettlement } from './ReturnSettlementCore.mjs';
10 +import { previewReturnCreditAllocation } from './ReturnCreditAllocationCore.mjs';
11 import { LEDGER_CODES, INVOICE_DIRECTIONS, amount, positiveAmount,
12 qtyUnits, fromQtyUnits, receiveStock, issueStock, allocateDiscount,
13 postLine, differenceLines, assertInvoiceTotals } from './RetailFinanceCore.mjs';
@@ -218,6 +221,10 @@ class RetailPostingServiceImpl {
221 return {cost:next.cost};
222 }
223 async issueInvoice(invoice) {
224 + const enforcedQuota = LicenseService.issuanceQuota();
225 + const identity = await createIssuanceIdentity(invoice,
226 + invoice.idempotencyKey || ('factor-easypro-invoice-id:' + invoice.id));
227 + invoice = { ...invoice, ...identity };
228 const company=await DataScope.companyId();
229 if(!await this.isEnabled())throw Error('حسابداری یکپارچه برای این شرکت فعال نیست');
230 assertInvoiceTotals(invoice);
@@ -229,7 +236,13 @@ class RetailPostingServiceImpl {
236 }
237 if(invoice.isPreInvoice)throw Error('پیش‌فاکتور نباید سند مالی تولید کند');
238 if(!invoice.id)throw Error('شناسه یکتای فاکتور الزامی است');
239 + if(typeof invoice.idempotencyKey!=='string'||invoice.idempotencyKey.length<16||
240 + !/^[a-f0-9]{64}$/.test(invoice.requestHash||'')) {
241 + throw Error('شناسه و اثرانگشت پایدار صدور الزامی است');
242 + }
243 return StorageService.transaction(FINANCE_STORES,async tx=>{
244 + const replay=await findIdempotentInvoice(tx,invoice);
245 + if(replay)return replay;
246 const ctx=await this.context(tx,company,invoice.date);
247 const kinds=INVOICE_DIRECTIONS;
248 if(!kinds[invoice.kind])throw Error('نوع فاکتور نامعتبر است');
@@ -238,6 +251,7 @@ class RetailPostingServiceImpl {
251 const existing=(await tx.getAll('invoices')).filter(i=>i.companyId===company&&!i.isPreInvoice);
252 if(existing.some(i=>String(i.number)===String(invoice.number)))throw Error('شماره فاکتور تکراری است');
253 if(invoice.contactId)sameCompany(await tx.get('contacts',invoice.contactId),company,'طرف حساب');
254 + let returnAllocation = null;
255 if(['sale_return','purchase_return'].includes(invoice.kind)){
256 if(!invoice.originalInvoiceId)throw Error('فاکتور مرجوعی باید به فاکتور اولیه متصل باشد');
257 const origin=sameCompany(await tx.get('invoices',invoice.originalInvoiceId),company,'فاکتور اولیه');
@@ -266,6 +280,29 @@ class RetailPostingServiceImpl {
280 const requested=invoice.items.filter(matching).reduce((sum,x)=>sum+qtyUnits(x.qty),0);
281 if(!base||was+requested>base)throw Error('تعداد مرجوعی از مقدار فاکتور اصلی بیشتر است');
282 }
283 + const priorCreditRows=(await tx.getAll('settlements')).filter(row=>
284 + row.companyId===company && row.settlementType==='credit_allocation' &&
285 + row.targetInvoiceId===origin.id);
286 + const priorCreditApplied=priorCreditRows.reduce((sum,row)=>{
287 + const source=existing.find(candidate=>candidate.id===row.sourceInvoiceId);
288 + if(row.invoiceId!==origin.id||row.targetInvoiceId!==origin.id||row.transactionId!==null||
289 + !source||source.kind!==invoice.kind||source.originalInvoiceId!==origin.id||!source.financePosted||
290 + row.idempotencyKey!==JSON.stringify([company,'credit_allocation',source.id]))
291 + throw Error('Prior return-credit allocation has an invalid source, target or company relationship');
292 + if(!Number.isSafeInteger(row.amount)||row.amount<0||row.amount>amount(source.grandTotal)||
293 + !Number.isSafeInteger(sum+row.amount))throw Error('Invalid prior return-credit allocation');
294 + return sum+row.amount;
295 + },0);
296 + const storedCreditApplied=amount(origin.creditAppliedAmount||0);
297 + if(storedCreditApplied!==priorCreditApplied)
298 + throw Error('Original invoice credit-allocation ledger does not match its stored control total');
299 + const allocation=previewReturnCreditAllocation({
300 + originalTotal:amount(origin.grandTotal),
301 + originalPaidAmount:amount(origin.paidAmount||0),
302 + priorCreditApplied,
303 + returnAmount:amount(invoice.grandTotal)
304 + });
305 + returnAllocation={origin,priorCreditApplied,...allocation};
306 }
307 const warehouseId=invoice.warehouseId||await this.defaultWarehouse(tx,company);
308 sameCompany(await tx.get('warehouses',warehouseId),company,'انبار');
@@ -335,9 +372,41 @@ class RetailPostingServiceImpl {
372 }
373 const journal=await this.journal(tx,ctx,'invoice',invoice.id,lines,'فاکتور '+invoice.number);
374 const issued={...invoice,companyId:company,ownerUserId:actor(),warehouseId,
338 - financePosted:true,journalId:journal.id,status:invoice.paidAmount?'partial':'unpaid',
339 - remaining:grand,paidAmount:0};
375 + financePosted:true,journalId:journal.id,status:returnAllocation?(returnAllocation.returnCreditRemaining===0?'settled':'partial'):(invoice.paidAmount?'partial':'unpaid'),
376 + creditAppliedAmount:returnAllocation?.allocatedToOriginal||0,
377 + remaining:returnAllocation?returnAllocation.returnCreditRemaining:grand,
378 + settlementStatus:returnAllocation&&returnAllocation.returnCreditRemaining===0?'settled':
379 + returnAllocation?'credit_due':'open',paidAmount:0};
380 await tx.put('invoices',issued);
381 + if(returnAllocation){
382 + const allocation=returnAllocation.allocatedToOriginal;
383 + const origin=returnAllocation.origin;
384 + const nextCreditApplied=returnAllocation.priorCreditApplied+allocation;
385 + await tx.put('invoices',{...origin,creditAppliedAmount:nextCreditApplied,
386 + remaining:returnAllocation.originalOpenAfter,
387 + settlementStatus:returnAllocation.originalOpenAfter===0?'settled':'open',
388 + status:returnAllocation.originalOpenAfter===0?(amount(origin.paidAmount||0)===amount(origin.grandTotal)?'paid':'settled'):
389 + amount(origin.paidAmount||0)>0?'partial':'unpaid'});
390 + if(allocation>0){
391 + await tx.add('settlements',{id:uid('set_'),companyId:company,
392 + settlementType:'credit_allocation',invoiceId:origin.id,
393 + sourceInvoiceId:issued.id,targetInvoiceId:origin.id,transactionId:null,
394 + amount:allocation,date:ctx.date,ownerUserId:actor(),
395 + idempotencyKey:JSON.stringify([company,'credit_allocation',issued.id])});
396 + }
397 + }
398 + await recordIssuanceReceipt(tx, issued, enforcedQuota);
399 + const number = Number(issued.number);
400 + if (/^\d+$/.test(String(issued.number)) && Number.isSafeInteger(number) &&
401 + number >= 1 && number < Number.MAX_SAFE_INTEGER) {
402 + const numberKey = `invoice_numbering_${company}`;
403 + const numberSettings = await tx.get('settings', numberKey);
404 + await tx.put('settings', {
405 + ...numberSettings, id: numberKey, companyId: company,
406 + numberingMode: numberSettings?.numberingMode === 'manual' ? 'manual' : 'auto',
407 + nextNumber: Math.max(Number(numberSettings?.nextNumber) || 1, number + 1)
408 + });
409 + }
410 const previousItems=await tx.getAllByIndex('invoice_items','invoiceId',invoice.id);
411 for(const oldItem of previousItems){
412 if(oldItem.companyId!==company)throw Error('اقلام فاکتور متعلق به شرکت دیگری است');
@@ -378,16 +447,36 @@ class RetailPostingServiceImpl {
447 const to=cashAccounts.find(a=>a.id===chosen)||cashAccounts.find(a=>a.isDefault)||cashAccounts[0];
448 if(!to)throw Error('برای تسویه نقدی، حساب صندوق یا بانک فعال تعریف کنید');
449 const cashLedgerId=cashLedger(ctx,to);
381 - const id=info.transactionId||uid('tx_');
382 - if(await tx.get('treasury',id))throw Error('دریافت یا پرداخت تکراری است');
450 if(info.contactId)sameCompany(await tx.get('contacts',info.contactId),ctx.companyId,'طرف حساب دریافت/پرداخت');
451 let related=null;
452 if(info.invoiceId) {
453 related=sameCompany(await tx.get('invoices',info.invoiceId),ctx.companyId,'فاکتور تسویه');
454 if(related.isPreInvoice||!related.financePosted)throw Error('این فاکتور در دفتر مالی قطعی نشده است');
455 if(info.contactId&&related.contactId!==info.contactId)throw Error('شخص تراکنش با فاکتور متفاوت است');
389 - if(sum>related.remaining)throw Error('مبلغ تسویه بیش از مانده فاکتور است');
456 }
457 + const idempotencyKey=info.idempotencyKey==null?null:String(info.idempotencyKey).trim();
458 + if(idempotencyKey) {
459 + if(idempotencyKey.length>200)throw Error('طول کلید تکرارپذیری بیش از حد مجاز است');
460 + const duplicate=(await tx.getAll('treasury')).find(row=>
461 + row.companyId===ctx.companyId&&row.recordType==='transaction'&&
462 + row.idempotencyKey===idempotencyKey);
463 + if(duplicate) {
464 + const sameRequest=duplicate.type===info.type&&amount(duplicate.amount)===sum&&
465 + (duplicate.refInvoiceId||null)===(related?.id||null)&&
466 + (duplicate.contactId||null)===(info.contactId||related?.contactId||null)&&
467 + (duplicate.fromAccountId||null)===(info.type==='payment'?to.id:null)&&
468 + (duplicate.toAccountId||null)===(info.type==='receipt'?to.id:null)&&
469 + (duplicate.method||'cash')===(info.method||'cash')&&
470 + (duplicate.date||'')===ctx.date&&
471 + (duplicate.description||'')===(info.description||'')&&
472 + (duplicate.reasonCode||null)===(info.reasonCode||null)&&
473 + (duplicate.explicitlyApproved===true)===(info.explicitlyApproved===true);
474 + if(!sameRequest)throw Error('کلید تکرارپذیری قبلاً برای درخواست مالی متفاوت استفاده شده است');
475 + return duplicate;
476 + }
477 + }
478 + const id=info.transactionId||uid('tx_');
479 + if(await tx.get('treasury',id))throw Error('تراکنش تکراری است');
480 const isReceipt=info.type==='receipt';
481 let otherCode=isReceipt?LEDGER_CODES.receivable:LEDGER_CODES.payable;
482 if(related){
@@ -458,12 +547,18 @@ class RetailPostingServiceImpl {
547 recordType:'transaction',type:info.type,date:ctx.date,amount:sum,
548 fromAccountId:isReceipt?null:to.id,toAccountId:isReceipt?to.id:null,
549 contactId:info.contactId||related?.contactId||null,refInvoiceId:related?.id||null,
461 - method:info.method||'cash',description:info.description||'',financePosted:true,journalId:journal.id};
550 + method:info.method||'cash',description:info.description||'',idempotencyKey,
551 + reasonCode:info.reasonCode||null,explicitlyApproved:info.explicitlyApproved===true,
552 + financePosted:true,journalId:journal.id};
553 await tx.put('treasury',transaction);
554 if(related){
555 const paid=amount(related.paidAmount||0)+sum;
465 - await tx.put('invoices',{...related,paidAmount:paid,remaining:related.grandTotal-paid,
466 - status:paid===related.grandTotal?'paid':'partial'});
556 + const creditApplied=amount(related.creditAppliedAmount||0);
557 + const remaining=amount(related.grandTotal)-paid-creditApplied;
558 + if(remaining<0)throw Error('Cash settlement exceeds invoice balance after return-credit allocation');
559 + await tx.put('invoices',{...related,paidAmount:paid,remaining,
560 + settlementStatus:remaining===0?'settled':'open',
561 + status:remaining===0?(paid===related.grandTotal?'paid':'settled'):paid>0?'partial':'unpaid'});
562 await tx.put('settlements',{id:uid('set_'),companyId:ctx.companyId,
563 invoiceId:related.id,transactionId:id,amount:sum,date:ctx.date,ownerUserId:actor()});
564 // A01: returning goods and handing back (or recovering) money are
@@ -500,14 +595,29 @@ class RetailPostingServiceImpl {
595 throw Error('انتقال بین حساب‌های بانکی/صندوق غیرفعال مجاز نیست');
596 if(from.id===to.id)throw Error('حساب مبدا و مقصد باید متفاوت باشند');
597 const mapping=account=>cashLedger(ctx,account);
598 + const idempotencyKey=info.idempotencyKey==null?null:String(info.idempotencyKey).trim();
599 + if(idempotencyKey) {
600 + if(idempotencyKey.length>200)throw Error('طول کلید تکرارپذیری بیش از حد مجاز است');
601 + const duplicate=all.find(row=>row.companyId===ctx.companyId&&
602 + row.recordType==='transaction'&&row.idempotencyKey===idempotencyKey);
603 + if(duplicate) {
604 + const sameRequest=duplicate.type==='transfer'&&amount(duplicate.amount)===sum&&
605 + duplicate.fromAccountId===from.id&&duplicate.toAccountId===to.id&&
606 + (duplicate.date||'')===ctx.date&&(duplicate.description||'')===(info.description||'')&&
607 + (duplicate.reasonCode||null)===(info.reasonCode||null)&&
608 + (duplicate.explicitlyApproved===true)===(info.explicitlyApproved===true);
609 + if(!sameRequest)throw Error('کلید تکرارپذیری قبلاً برای درخواست مالی متفاوت استفاده شده است');
610 + return duplicate;
611 + }
612 + }
613 const id=info.transactionId||uid('tx_');
504 - if(await tx.get('treasury',id))throw Error('تراکنش انتقال تکراری است');
614 + if(await tx.get('treasury',id))throw Error('تراکنش تکراری است');
615 const journal=await this.journal(tx,ctx,'treasury',id,[
616 postLine(mapping(to),sum,0),postLine(mapping(from),0,sum)
617 ],'انتقال داخلی بین حساب‌ها');
618 const row={id,companyId:ctx.companyId,ownerUserId:actor(),recordType:'transaction',
619 type:'transfer',amount:sum,date:ctx.date,fromAccountId:from.id,toAccountId:to.id,
510 - contactId:null,method:'transfer',financePosted:true,journalId:journal.id,
620 + contactId:null,method:'transfer',idempotencyKey,financePosted:true,journalId:journal.id,
621 description:info.description||''};
622 await tx.put('treasury',row);
623 return row;
src/core/ReturnCreditAllocationCore.mjs new
+37
@@ -0,0 +1,37 @@
1 +// Pure allocation of a finalized return credit against its referenced original invoice.
2 +// All values are non-negative safe-integer Rials; this helper never writes or moves cash.
3 +function rial(value, label, { positive = false } = {}) {
4 + if (!Number.isSafeInteger(value) || value < (positive ? 1 : 0)) {
5 + throw new RangeError(`${label} must be a ${positive ? 'positive' : 'non-negative'} safe integer Rial amount`);
6 + }
7 + return value;
8 +}
9 +
10 +export function previewReturnCreditAllocation({
11 + originalTotal,
12 + originalPaidAmount = 0,
13 + priorCreditApplied = 0,
14 + returnAmount
15 +} = {}) {
16 + const gross = rial(originalTotal, 'originalTotal', { positive: true });
17 + const paid = rial(originalPaidAmount, 'originalPaidAmount');
18 + const prior = rial(priorCreditApplied, 'priorCreditApplied');
19 + const returned = rial(returnAmount, 'returnAmount', { positive: true });
20 + if (paid > gross || prior > gross - paid) {
21 + throw new RangeError('Original invoice cash paid and prior credit allocations exceed its gross total');
22 + }
23 + const originalOpenBefore = gross - paid - prior;
24 + const allocatedToOriginal = Math.min(returned, originalOpenBefore);
25 + const originalOpenAfter = originalOpenBefore - allocatedToOriginal;
26 + const returnCreditRemaining = returned - allocatedToOriginal;
27 + return Object.freeze({
28 + originalOpenBefore,
29 + allocatedToOriginal,
30 + originalOpenAfter,
31 + returnCreditRemaining,
32 + originalTotal: gross,
33 + originalPaidAmount: paid,
34 + priorCreditApplied: prior,
35 + returnAmount: returned
36 + });
37 +}
src/views/InvoiceFormView.js
+27
@@ -12,6 +12,7 @@ import { numberToWords } from '../utils/NumberToWords.js';
12 import { NumberInput } from '../utils/NumberInput.js';
13 import { SettingsController } from '../controllers/SettingsController.js';
14 import { RetailPostingService } from '../core/RetailPostingService.js';
15 +import { createRetryStorageKey } from '../core/IssuanceReceipt.mjs';
16 import { lineGrossRials, percentOfRials } from '../core/RetailFinanceCore.mjs';
17
18 let ctx = {
@@ -831,10 +832,36 @@ class InvoiceFormViewImpl {
832 description: document.getElementById('invDescription').value
833 };
834
835 + // Persist the retry identity before posting; a crash must not mint a new invoice.
836 + // A changed form intentionally receives a different operation identity.
837 + let retryStorageKey = null;
838 + if (!data.isPreInvoice) {
839 + if (ctx.editId) {
840 + // A preinvoice-to-invoice conversion keeps the same identity across retries.
841 + data.idempotencyKey = 'preinvoice-finalize:' + ctx.editId;
842 + } else {
843 + const retryPayload = { ...data };
844 + if (ctx.invoiceSettings?.numberingMode !== 'manual') delete retryPayload.number;
845 + const signature = JSON.stringify(retryPayload);
846 + // Each distinct invoice payload has its own durable retry slot. A pending
847 + // invoice in another tab can no longer overwrite this operation's key.
848 + retryStorageKey = await createRetryStorageKey(signature);
849 + const signatureHash = retryStorageKey.slice(retryStorageKey.lastIndexOf(':') + 1);
850 + let pending = null;
851 + try { pending = JSON.parse(localStorage.getItem(retryStorageKey) || 'null'); }
852 + catch (_) { localStorage.removeItem(retryStorageKey); }
853 + const key = pending?.signatureHash === signatureHash && typeof pending?.key === 'string'
854 + ? pending.key : crypto.randomUUID();
855 + // Persist only the digest and operation key, never customer or invoice data.
856 + localStorage.setItem(retryStorageKey, JSON.stringify({ signatureHash, key }));
857 + data.idempotencyKey = key;
858 + }
859 + }
860 if (this._saving) return;
861 this._saving = true;
862 try {
863 const saved = await InvoiceController.save(data, ctx.editId);
864 + if (retryStorageKey) localStorage.removeItem(retryStorageKey);
865 Toast.success(ctx.editId ? 'فاکتور ویرایش شد' : `فاکتور #${saved.number} صادر شد`);
866 const savedId = saved.id;
867 Modal.close();
src/views/InvoicesView.js
+5 -2
@@ -41,6 +41,7 @@ class InvoicesViewImpl {
41 <select class="form-control" style="width:auto;min-width:130px" aria-label="وضعیت پرداخت فاکتور" onchange="window.InvoicesView._onFilter('paymentStatus', this.value)">
42 <option value="">همه وضعیت‌ها</option>
43 <option value="paid" ${filter.paymentStatus === 'paid' ? 'selected' : ''}>تسویه‌شده</option>
44 + <option value="settled" ${filter.paymentStatus === 'settled' ? 'selected' : ''}>تسویه‌شده</option>
45 <option value="partial" ${filter.paymentStatus === 'partial' ? 'selected' : ''}>پرداخت جزئی</option>
46 <option value="unpaid" ${filter.paymentStatus === 'unpaid' ? 'selected' : ''}>پرداخت‌نشده</option>
47 </select>
@@ -91,7 +92,9 @@ class InvoicesViewImpl {
92 }
93
94 const rows = invoices.map(inv => {
94 - const statusBadge = inv.status === 'paid'
95 + const statusBadge = inv.settlementStatus === 'settled' && inv.status !== 'paid'
96 + ? '<span class="badge badge-success">تسویه‌شده</span>'
97 + : inv.status === 'paid'
98 ? '<span class="badge badge-success">تسویه‌شده</span>'
99 : inv.status === 'partial'
100 ? '<span class="badge badge-warning">پرداخت جزئی</span>'
@@ -119,7 +122,7 @@ class InvoicesViewImpl {
122 <td>${this._esc(inv.contactName || '—')}</td>
123 <td>${this._esc(Formatters.toPersianDigits(inv.date || '—'))}</td>
124 <td style="font-weight:600">${Formatters.money(inv.grandTotal)}</td>
122 - <td>${Formatters.money(inv.paidAmount || 0)}</td>
125 + <td>${Formatters.money(inv.paidAmount || 0)}${Number(inv.creditAppliedAmount)>0 ? '<div style="font-size:10px;color:var(--text-muted)">اعتبار برگشت: ' + Formatters.money(inv.creditAppliedAmount) + '</div>' : ''}</td>
126 <td style="color:${inv.remaining > 0 ? 'var(--danger)' : 'var(--success)'};font-weight:600">
127 ${Formatters.money(inv.remaining || 0)}
128 </td>
src/views/ReportsView.js
+4 -6
@@ -385,13 +385,13 @@ class ReportsViewImpl {
385 <td style="color:var(--danger)">${Formatters.money(c.totalReturns)}</td>
386 <td style="font-weight:700;color:${c.netSales < 0 ? 'var(--danger)' : 'var(--primary)'}">${Formatters.money(c.netSales)}</td>
387 <td style="color:var(--success)">${Formatters.money(c.totalPaid)}</td>
388 - <td style="font-weight:600;color:${c.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
388 + <td style="font-weight:600;color:${c.totalRemaining > 0 ? 'var(--danger)' : c.totalRemaining < 0 ? 'var(--warning)' : 'var(--success)'}">${Formatters.money(c.totalRemaining)}</td>
389 </tr>
390 `).join('')}
391 </tbody>
392 </table>
393 </div>
394 - <p role="note" style="font-size:12px;line-height:1.8;color:var(--text-muted);margin:10px 0 0">فروش خالص، مرجوعی را از فروش ناخالص کم می‌کند. مانده فقط جمع مانده فاکتورهای فروش است و اعتبار مرجوعی یا بازپرداخت را از دفتر کل محاسبه نمی‌کند.</p>
394 + <p role="note" style="font-size:12px;line-height:1.8;color:var(--text-muted);margin:10px 0 0">مانده خالص پس از کسر اعتبار برگشت‌ها و تسویه نقدی است؛ عدد مثبت یعنی طلب از مشتری و عدد منفی یعنی بدهی به مشتری.</p>
395 </div>
396 `;
397 }
@@ -532,9 +532,7 @@ class ReportsViewImpl {
532
533 <div class="card">
534 <h3 style="font-size:15px;font-weight:700;margin-bottom:8px">👥 گزارش تفصیلی مشتریان</h3>
535 - <p role="note" style="font-size:12px;line-height:1.8;color:var(--text-muted);margin:0 0 12px">
536 - فروش خالص، مرجوعی را از فروش ناخالص کم می‌کند. مانده این جدول فقط جمع مانده فاکتورهای فروش است و اعتبار مرجوعی یا بازپرداخت را از دفتر کل محاسبه نمی‌کند؛ برای مانده قطعی حساب، دفتر کل مبناست.
537 - </p>
535 + <p role="note" style="font-size:12px;line-height:1.8;color:var(--text-muted);margin:10px 0 0">مانده خالص پس از کسر اعتبار برگشت‌ها و تسویه نقدی است؛ عدد مثبت یعنی طلب از مشتری و عدد منفی یعنی بدهی به مشتری.</p>
536 <div class="table-wrap">
537 <table>
538 <thead>
@@ -562,7 +560,7 @@ class ReportsViewImpl {
560 <td style="color:var(--danger)">${Formatters.money(customer.totalReturns)}</td>
561 <td style="font-weight:700;color:${customer.netSales < 0 ? 'var(--danger)' : 'var(--primary)'}">${Formatters.money(customer.netSales)}</td>
562 <td style="color:var(--success)">${Formatters.money(customer.totalPaid)}</td>
565 - <td style="font-weight:700;color:${customer.totalRemaining > 0 ? 'var(--danger)' : 'var(--success)'}">${Formatters.money(customer.totalRemaining)}</td>
563 + <td style="font-weight:700;color:${customer.totalRemaining > 0 ? 'var(--danger)' : customer.totalRemaining < 0 ? 'var(--warning)' : 'var(--success)'}">${Formatters.money(customer.totalRemaining)}</td>
564 <td>${customer.lastInvoiceDate ? Formatters.toPersianDigits(customer.lastInvoiceDate) : '—'}</td>
565 </tr>
566 `).join('')}
src/views/TreasuryView.js
+36 -5
@@ -9,6 +9,9 @@ import { Modal } from '../core/Modal.js';
9 import { Toast } from '../core/Toast.js';
10 import { Formatters } from '../utils/Formatters.js';
11 import { NumberInput } from '../utils/NumberInput.js';
12 +import { createTreasuryRetryIdentity, clearTreasuryRetryIdentity } from '../core/IssuanceReceipt.mjs';
13 +import { StorageService } from '../core/StorageService.js';
14 +import { DataScope } from '../core/DataScope.js';
15
16 let currentTab = 'accounts';
17 let txFilter = { search: '', type: '', accountId: '' };
@@ -363,6 +366,10 @@ class TreasuryViewImpl {
366 Modal.close();
367 await this.reload();
368 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
369 + if (retryStorageKey) {
370 + try { await clearTreasuryRetryIdentity(StorageService, { storageKey: retryStorageKey, idempotencyKey: data.idempotencyKey }); }
371 + catch (_) { Toast.warning('تراکنش ثبت شد؛ پاک‌سازی نشانگر تکرار انجام نشد.'); }
372 + }
373 } catch (err) {
374 Toast.error('خطا: ' + err.message);
375 }
@@ -417,8 +424,14 @@ class TreasuryViewImpl {
424 const invoices=cache.invoices.filter(row=>
425 row.financePosted && !row.isPreInvoice && kinds.includes(row.kind) &&
426 Number(row.remaining)>0);
420 - return '<option value="">— دریافت/پرداخت مستقل (بدون اتصال فاکتور) —</option>' +
421 - invoices.map(row => `<option value="${this._esc(row.id)}">#${this._esc(row.number)} — ${this._esc(row.contactName||'بدون نام')} (${Formatters.number(row.remaining)} ریال)</option>`).join('');
427 + return '<option value="">انتخاب سند برای تسویه</option>' +
428 + invoices.map(row => {
429 + const balanceLabel=['sale_return','purchase_return'].includes(row.kind)
430 + ? 'اعتبار برگشت باقی‌مانده' : 'مانده خالص قابل تسویه';
431 + return '<option value="'+this._esc(row.id)+'">#'+this._esc(row.number)+
432 + ' — '+this._esc(row.contactName||'طرف حساب')+
433 + ' ('+balanceLabel+': '+Formatters.number(row.remaining)+' ریال)</option>';
434 + }).join('');
435 }
436
437 _onInvoiceSelection() {
@@ -634,6 +647,18 @@ class TreasuryViewImpl {
647 description: document.getElementById('txDescription')?.value || ''
648 };
649
650 + const persistRetryIdentity = async () => {
651 + const retrySignature = JSON.stringify({
652 + companyId: await DataScope.companyId(),
653 + type: data.type, date: data.date, amount: data.amount, method: data.method,
654 + contactId: data.contactId, refInvoiceId: data.refInvoiceId,
655 + fromAccountId: data.fromAccountId, toAccountId: data.toAccountId,
656 + description: data.description, reasonCode: data.reasonCode || null
657 + });
658 + const identity = await createTreasuryRetryIdentity(retrySignature, StorageService);
659 + data.idempotencyKey = identity.idempotencyKey;
660 + return identity;
661 + };
662 if (type === 'transfer') {
663 if (!data.fromAccountId || !data.toAccountId) {
664 Toast.warning('حساب مبدأ و مقصد رو انتخاب کنید');
@@ -652,25 +677,31 @@ class TreasuryViewImpl {
677 Toast.warning('برای تسویه مرجوعی دلیل را انتخاب کنید');
678 return;
679 }
680 + const retryIdentity = await persistRetryIdentity();
681 Modal.confirm({
682 title: type==='payment'?'تأیید بازپرداخت مرجوعی':'تأیید دریافت وجه مرجوعی',
683 message: 'آیا مبلغ '+Formatters.number(data.amount)+' ریال برای مرجوعی انتخاب‌شده تأیید می‌شود؟',
684 confirmText: 'تأیید و ثبت',
685 danger: type==='payment',
660 - onConfirm: () => this._commitTransaction(type,{...data,explicitlyApproved:true})
686 + onConfirm: () => this._commitTransaction(type,{...data,explicitlyApproved:true},retryIdentity.storageKey)
687 });
688 return;
689 }
664 - await this._commitTransaction(type,data);
690 + const retryIdentity = await persistRetryIdentity();
691 + await this._commitTransaction(type,data,retryIdentity.storageKey);
692 }
693
667 - async _commitTransaction(type,data) {
694 + async _commitTransaction(type,data,retryStorageKey = null) {
695 try {
696 await TreasuryController.createTransaction(data);
697 Toast.success(TreasuryController.getTypeLabel(type) + ' ثبت شد');
698 Modal.close();
699 await this.reload();
700 document.getElementById('treasury-content').innerHTML = this.renderTabContent();
701 + if (retryStorageKey) {
702 + try { await clearTreasuryRetryIdentity(StorageService, { storageKey: retryStorageKey, idempotencyKey: data.idempotencyKey }); }
703 + catch (_) { Toast.warning('تراکنش ثبت شد؛ پاک‌سازی نشانگر تکرار انجام نشد.'); }
704 + }
705 } catch (err) {
706 Toast.error('خطا: ' + err.message);
707 }
tests/financial-controller-money-boundaries.test.mjs
+20
@@ -41,6 +41,26 @@ test('treasury account and transaction controller reject malformed, fractional a
41 assert.equal(receipt.amount,125);
42 });
43
44 +test('treasury controller legacy path replays an idempotent request without duplicate writes',async()=>{
45 + await setup();
46 + const {TreasuryController}=await import('../src/controllers/TreasuryController.js');
47 + const {RetailPostingService}=await import('../src/core/RetailPostingService.js');
48 + const original=RetailPostingService.isEnabled;
49 + RetailPostingService.isEnabled=async()=>false;
50 + try {
51 + const account=await TreasuryController.createAccount({name:'Legacy synthetic cash',initialBalance:0});
52 + const request={type:'receipt',amount:125,toAccountId:account.id,
53 + idempotencyKey:'treasury:legacy-retry-001',date:'1405/07/18'};
54 + const first=await TreasuryController.createTransaction(request);
55 + const replay=await TreasuryController.createTransaction(request);
56 + assert.equal(replay.id,first.id);
57 + assert.equal((await rows('treasury')).filter(x=>x.recordType==='transaction').length,1);
58 + await assert.rejects(TreasuryController.createTransaction({...request,amount:126}),/کلید تکرارپذیری/);
59 + assert.equal((await rows('treasury')).filter(x=>x.recordType==='transaction').length,1);
60 + } finally {
61 + RetailPostingService.isEnabled=original;
62 + }
63 +});
64 test('cheque controller rejects invalid directions and all nonpositive/nonintegral rial amounts',async()=>{
65 await setup();
66 const {ChequeController}=await import('../src/controllers/ChequeController.js');
tests/g316-company-boundary.test.mjs new
+53
@@ -0,0 +1,53 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService as db } from '../src/core/StorageService.js';
5 +import { AccountingService as accounts } from '../src/core/AccountingService.js';
6 +import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
7 +import { Auth } from '../src/core/Auth.js';
8 +import { CompanyService } from '../src/core/CompanyService.js';
9 +import { LicenseService } from '../src/core/LicenseService.js';
10 +
11 +const date='1405/07/18';
12 +const company='g316-scope-local';
13 +async function setup(){
14 + await db.clearAll();
15 + LicenseService.state={trialStartedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),installationId:'g316-scope-test',issuedInvoiceCount:0};
16 + LicenseService.verifiedPayload=null;
17 + LicenseService.clockRollback=false;
18 + await db.put('companies',{id:company,name:'G316 local'});
19 + await db.put('companies',{id:'g316-scope-foreign',name:'G316 foreign'});
20 + Auth.currentUser={id:'g316-admin',role:'admin',username:'admin',companyIds:[company]};
21 + CompanyService.activeCompanyId=company;
22 + await accounts.createPeriod({name:'G316 scope FY1405',startDate:'1405/01/01',endDate:'1405/12/29'});
23 + await accounts.seedDefaultChart();
24 + await db.put('treasury',{id:'g316-local-cash',companyId:company,recordType:'account',type:'cashbox',name:'G316 local cash',isActive:true,isDefault:true,initialBalance:0});
25 + await db.put('treasury',{id:'g316-foreign-cash',companyId:'g316-scope-foreign',recordType:'account',type:'cashbox',name:'G316 foreign cash',isActive:true,isDefault:true,initialBalance:0});
26 + await db.put('contacts',{id:'g316-local-contact',companyId:company,name:'G316 local supplier',role:'supplier'});
27 + await db.put('contacts',{id:'g316-foreign-contact',companyId:'g316-scope-foreign',name:'G316 foreign supplier',role:'supplier'});
28 + await db.put('invoices',{id:'g316-foreign-purchase',companyId:'g316-scope-foreign',kind:'purchase',
29 + financePosted:true,isPreInvoice:false,grandTotal:1000,paidAmount:0,remaining:1000,
30 + contactId:'g316-foreign-contact',date});
31 + await retail.activate();
32 +}
33 +test('G316: treasury posting rejects foreign-company invoice, contact and bank account without writes',async()=>{
34 + await setup();
35 + const before={
36 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
37 + journals:(await db.getAll('journal_entries')).length,
38 + settlements:(await db.getAll('settlements')).length
39 + };
40 + await assert.rejects(retail.postTransaction({id:'g316-foreign-invoice-attempt',type:'payment',date,
41 + amount:1,contactId:'g316-foreign-contact',refInvoiceId:'g316-foreign-purchase',
42 + fromAccountId:'g316-local-cash',method:'cash'}));
43 + await assert.rejects(retail.postTransaction({id:'g316-foreign-account-attempt',type:'payment',date,
44 + amount:1,contactId:'g316-local-contact',fromAccountId:'g316-foreign-cash',method:'cash'}));
45 + const after={
46 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
47 + journals:(await db.getAll('journal_entries')).length,
48 + settlements:(await db.getAll('settlements')).length
49 + };
50 + assert.deepEqual(after,before,'cross-company attempts must not write financial records');
51 + assert.equal(await db.get('treasury','g316-foreign-invoice-attempt'),undefined);
52 + assert.equal(await db.get('treasury','g316-foreign-account-attempt'),undefined);
53 +});
tests/g316-purchase-return-offset.test.mjs new
+79
@@ -0,0 +1,79 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService as db } from '../src/core/StorageService.js';
5 +import { AccountingService as accounts } from '../src/core/AccountingService.js';
6 +import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
7 +import { Auth } from '../src/core/Auth.js';
8 +import { CompanyService } from '../src/core/CompanyService.js';
9 +import { LicenseService } from '../src/core/LicenseService.js';
10 +
11 +const date='1405/07/18';
12 +const company='g316-purchase-return-offset';
13 +async function setup(){
14 + await db.clearAll();
15 + LicenseService.state={trialStartedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),installationId:'g316-offset-test',issuedInvoiceCount:0};
16 + LicenseService.verifiedPayload=null;
17 + LicenseService.clockRollback=false;
18 + await db.put('companies',{id:company,name:'G316 synthetic company'});
19 + Auth.currentUser={id:'g316-admin',role:'admin',username:'admin'};
20 + CompanyService.activeCompanyId=company;
21 + await accounts.createPeriod({name:'G316 synthetic FY1405',startDate:'1405/01/01',endDate:'1405/12/29'});
22 + await accounts.seedDefaultChart();
23 + await db.put('treasury',{id:'g316-cash',companyId:company,recordType:'account',type:'cashbox',name:'G316 synthetic cash',isActive:true,isDefault:true,initialBalance:0});
24 + await db.put('products',{id:'g316-product',companyId:company,name:'G316 synthetic product',code:'G316-P01',buyPrice:100,sellPrice:200,trackInventory:true});
25 + await db.put('contacts',{id:'g316-supplier',companyId:company,name:'G316 synthetic supplier',role:'supplier'});
26 + await retail.activate();
27 +}
28 +function invoice(kind,qty,price,rest={}){
29 + const total=qty*price;
30 + return {id:'g316-inv-'+kind+'-'+qty+'-'+price,companyId:company,
31 + number:'G316-'+kind,clientUuid:'G316-'+kind,ownerUserId:'g316-admin',kind,
32 + date,contactId:'g316-supplier',contactName:'G316 synthetic supplier',
33 + isPreInvoice:false,items:[{productId:'g316-product',productName:'G316 synthetic product',
34 + qty,price,lineSubtotal:total,lineTotal:total,discount:0}],
35 + subtotal:total,totalDiscount:0,vatAmount:0,grandTotal:total,paidAmount:0,
36 + paymentMethod:'cash',status:'unpaid',remaining:total,...rest};
37 +}
38 +async function payableBalance(){
39 + const accountsRows=await db.getAll('account_chart');
40 + const payable=accountsRows.find(x=>x.code==='201');
41 + assert.ok(payable,'payable control account missing');
42 + const lines=await db.getAll('journal_lines');
43 + return lines.filter(x=>x.accountId===payable.id&&x.contactId==='g316-supplier')
44 + .reduce((n,x)=>n+Number(x.credit||0)-Number(x.debit||0),0);
45 +}
46 +test('G316: purchase return offsets supplier payable and blocks a second payment beyond net payable',async()=>{
47 + await setup();
48 + const purchased=await retail.issueInvoice(invoice('purchase',10,100));
49 + await retail.postTransaction({id:'g316-supplier-payment-700',type:'payment',date,amount:700,
50 + contactId:'g316-supplier',refInvoiceId:purchased.id,fromAccountId:'g316-cash',method:'cash'});
51 + const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{originalInvoiceId:purchased.id}));
52 + await retail.postTransaction({id:'g316-supplier-recovery-100',type:'receipt',date,amount:100,
53 + contactId:'g316-supplier',refInvoiceId:returned.id,toAccountId:'g316-cash',method:'cash',
54 + reasonCode:'goods_return',explicitlyApproved:true});
55 + const original=await db.get('invoices',purchased.id);
56 + const creditNote=await db.get('invoices',returned.id);
57 + assert.equal(original.remaining,0);
58 + assert.equal(creditNote.remaining,0);
59 + assert.equal(await payableBalance(),0,'supplier control-account balance must net to zero');
60 + const before={
61 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
62 + journals:(await db.getAll('journal_entries')).length,
63 + settlements:(await db.getAll('settlements')).length,
64 + lines:(await db.getAll('journal_lines')).length
65 + };
66 + await assert.rejects(retail.postTransaction({id:'g316-prohibited-extra-supplier-payment',
67 + type:'payment',date,amount:1,contactId:'g316-supplier',
68 + refInvoiceId:purchased.id,fromAccountId:'g316-cash',method:'cash'}));
69 + const after={
70 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
71 + journals:(await db.getAll('journal_entries')).length,
72 + settlements:(await db.getAll('settlements')).length,
73 + lines:(await db.getAll('journal_lines')).length
74 + };
75 + assert.deepEqual(after,before,'blocked payment must leave all financial records unchanged');
76 + assert.equal(await payableBalance(),0);
77 + assert.equal((await db.get('invoices',purchased.id)).remaining,0);
78 + assert.equal((await db.get('invoices',returned.id)).remaining,0);
79 +});
tests/g317-report-net-balance.test.mjs new
+44
@@ -0,0 +1,44 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +globalThis.window ??= globalThis;
4 +const { ReportController } = await import('../src/controllers/ReportController.js');
5 +
6 +test('G317 customer reports show net receivable after return-credit allocation and cash refunds',async()=>{
7 + const originalLoad=ReportController._loadData;
8 + const data={
9 + invoices:[
10 + {id:'a-sale',kind:'sale',isPreInvoice:false,date:'1405/01/02',contactId:'a',contactName:'Customer A',
11 + grandTotal:1000,paidAmount:400,creditAppliedAmount:250,remaining:350},
12 + {id:'a-return',kind:'sale_return',isPreInvoice:false,date:'1405/01/03',contactId:'a',contactName:'Customer A',
13 + grandTotal:250,paidAmount:0,creditAppliedAmount:250,remaining:0},
14 + {id:'b-sale',kind:'sale',isPreInvoice:false,date:'1405/01/02',contactId:'b',contactName:'Customer B',
15 + grandTotal:1000,paidAmount:900,creditAppliedAmount:100,remaining:0},
16 + {id:'b-return',kind:'sale_return',isPreInvoice:false,date:'1405/01/03',contactId:'b',contactName:'Customer B',
17 + grandTotal:400,paidAmount:100,creditAppliedAmount:100,remaining:200},
18 + {id:'c-return',kind:'sale_return',isPreInvoice:false,date:'1405/01/04',contactId:'c',contactName:'Customer C',
19 + grandTotal:50,paidAmount:0,creditAppliedAmount:0,remaining:50}
20 + ],
21 + contacts:[{id:'a',name:'Customer A'},{id:'b',name:'Customer B'},{id:'c',name:'Customer C'}],
22 + products:[],expenses:[],stockMovements:[],cheques:[],treasury:[]
23 + };
24 + ReportController._loadData=async()=>data;
25 + try{
26 + const filter={preset:'custom',from:'1405/01/01',to:'1405/12/29'};
27 + const rows=await ReportController.getCustomerReport(filter);
28 + const a=rows.find(x=>x.contactId==='a');
29 + const b=rows.find(x=>x.contactId==='b');
30 + const c=rows.find(x=>x.contactId==='c');
31 + assert.deepEqual({netSales:a.netSales,netCash:a.totalPaid,netReceivable:a.totalRemaining,
32 + returnCreditRemaining:a.returnCreditRemaining},{netSales:750,netCash:400,netReceivable:350,returnCreditRemaining:0});
33 + assert.deepEqual({netSales:b.netSales,netCash:b.totalPaid,netReceivable:b.totalRemaining,
34 + returnCreditRemaining:b.returnCreditRemaining},{netSales:600,netCash:800,netReceivable:-200,returnCreditRemaining:200});
35 + assert.equal(c.totalRemaining,-50,'return-only credit is a liability to the customer, not a receivable');
36 + const sales=await ReportController.getSalesAnalysis(filter);
37 + const salesA=sales.topCustomers.find(x=>x.contactId==='a');
38 + const salesB=sales.topCustomers.find(x=>x.contactId==='b');
39 + assert.equal(salesA.totalRemaining,350);
40 + assert.equal(salesA.totalPaid,400);
41 + assert.equal(salesB.totalRemaining,-200);
42 + assert.equal(salesB.totalPaid,800);
43 + }finally{ReportController._loadData=originalLoad;}
44 +});
tests/g317-return-credit-allocation.test.mjs new
+178
@@ -0,0 +1,178 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService as db } from '../src/core/StorageService.js';
5 +import { AccountingService as accounts } from '../src/core/AccountingService.js';
6 +import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
7 +import { Auth } from '../src/core/Auth.js';
8 +import { CompanyService } from '../src/core/CompanyService.js';
9 +import { LicenseService } from '../src/core/LicenseService.js';
10 +
11 +const date='1405/07/18';
12 +const company='g317-return-credit';
13 +let sequence=0;
14 +async function setup(){
15 + await db.clearAll();
16 + sequence=0;
17 + LicenseService.state={trialStartedAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),installationId:'g317-credit-test',issuedInvoiceCount:0};
18 + LicenseService.verifiedPayload=null;
19 + LicenseService.clockRollback=false;
20 + await db.put('companies',{id:company,name:'G317 synthetic company'});
21 + Auth.currentUser={id:'g317-admin',role:'admin',username:'admin'};
22 + CompanyService.activeCompanyId=company;
23 + await accounts.createPeriod({name:'G317 synthetic FY1405',startDate:'1405/01/01',endDate:'1405/12/29'});
24 + await accounts.seedDefaultChart();
25 + await db.put('treasury',{id:'g317-cash',companyId:company,recordType:'account',type:'cashbox',name:'G317 synthetic cash',isActive:true,isDefault:true,initialBalance:0});
26 + await db.put('products',{id:'g317-stock',companyId:company,name:'G317 stock product',code:'G317-S01',buyPrice:100,sellPrice:200,trackInventory:true});
27 + await db.put('products',{id:'g317-service',companyId:company,name:'G317 service',code:'G317-SVC',buyPrice:0,sellPrice:100,trackInventory:false});
28 + await db.put('contacts',{id:'g317-supplier',companyId:company,name:'G317 synthetic supplier',role:'supplier'});
29 + await db.put('contacts',{id:'g317-customer',companyId:company,name:'G317 synthetic customer',role:'customer'});
30 + await retail.activate();
31 +}
32 +function invoice(kind,qty,price,rest={}){
33 + const total=qty*price;
34 + const contactId=['purchase','purchase_return'].includes(kind)?'g317-supplier':'g317-customer';
35 + const productId=['purchase','purchase_return'].includes(kind)?'g317-stock':'g317-service';
36 + const id='g317-inv-'+(++sequence);
37 + return {id,companyId:company,number:'G317-'+sequence,clientUuid:id,ownerUserId:'g317-admin',kind,
38 + date,contactId,contactName:contactId==='g317-supplier'?'G317 synthetic supplier':'G317 synthetic customer',
39 + isPreInvoice:false,items:[{productId,productName:productId==='g317-stock'?'G317 stock product':'G317 service',
40 + qty,price,lineSubtotal:total,lineTotal:total,discount:0}],
41 + subtotal:total,totalDiscount:0,vatAmount:0,grandTotal:total,paidAmount:0,
42 + paymentMethod:'cash',status:'unpaid',remaining:total,...rest};
43 +}
44 +async function controlBalance(code,contactId,side){
45 + const chart=await db.getAll('account_chart');
46 + const account=chart.find(x=>x.code===code);
47 + assert.ok(account,'control account '+code+' missing');
48 + const lines=await db.getAll('journal_lines');
49 + return lines.filter(x=>x.accountId===account.id&&x.contactId===contactId)
50 + .reduce((n,x)=>n+(side==='debit'?Number(x.debit||0)-Number(x.credit||0):Number(x.credit||0)-Number(x.debit||0)),0);
51 +}
52 +async function allocationRows(targetId){
53 + return (await db.getAll('settlements')).filter(x=>
54 + x.settlementType==='credit_allocation'&&x.targetInvoiceId===targetId);
55 +}
56 +
57 +test('G317 purchase return allocates credit to open supplier payable before cash recovery',async()=>{
58 + await setup();
59 + const original=await retail.issueInvoice(invoice('purchase',10,100));
60 + await retail.postTransaction({id:'g317-supplier-payment',type:'payment',date,amount:700,
61 + contactId:'g317-supplier',refInvoiceId:original.id,fromAccountId:'g317-cash',method:'cash'});
62 + const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{originalInvoiceId:original.id}));
63 + let source=await db.get('invoices',original.id);
64 + let credit=await db.get('invoices',returned.id);
65 + assert.equal(source.creditAppliedAmount,300);
66 + assert.equal(source.remaining,0);
67 + assert.equal(source.settlementStatus,'settled');
68 + assert.equal(source.status,'settled');
69 + assert.equal(credit.creditAppliedAmount,300);
70 + assert.equal(credit.remaining,100);
71 + assert.equal(credit.settlementStatus,'credit_due');
72 + assert.equal(credit.status,'partial');
73 + const rows=await allocationRows(original.id);
74 + assert.equal(rows.length,1);
75 + assert.deepEqual({invoiceId:rows[0].invoiceId,sourceInvoiceId:rows[0].sourceInvoiceId,
76 + targetInvoiceId:rows[0].targetInvoiceId,transactionId:rows[0].transactionId,amount:rows[0].amount},
77 + {invoiceId:original.id,sourceInvoiceId:returned.id,targetInvoiceId:original.id,transactionId:null,amount:300});
78 + assert.equal(await controlBalance('201','g317-supplier','credit'),-100,
79 + 'supplier return creates a 100 Rial debit balance before cash recovery');
80 + await retail.postTransaction({id:'g317-supplier-recovery',type:'receipt',date,amount:100,
81 + contactId:'g317-supplier',refInvoiceId:returned.id,toAccountId:'g317-cash',method:'cash',
82 + reasonCode:'goods_return',explicitlyApproved:true});
83 + source=await db.get('invoices',original.id);
84 + credit=await db.get('invoices',returned.id);
85 + assert.equal(source.remaining,0);
86 + assert.equal(credit.paidAmount,100);
87 + assert.equal(credit.remaining,0);
88 + assert.equal(credit.settlementStatus,'settled');
89 + assert.equal(credit.status,'settled');
90 + assert.equal(await controlBalance('201','g317-supplier','credit'),0);
91 + const before={
92 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
93 + journals:(await db.getAll('journal_entries')).length,
94 + settlements:(await db.getAll('settlements')).length,
95 + lines:(await db.getAll('journal_lines')).length
96 + };
97 + await assert.rejects(retail.postTransaction({id:'g317-extra-supplier-payment',type:'payment',date,amount:1,
98 + contactId:'g317-supplier',refInvoiceId:original.id,fromAccountId:'g317-cash',method:'cash'}));
99 + await assert.rejects(retail.postTransaction({id:'g317-extra-supplier-recovery',type:'receipt',date,amount:1,contactId:'g317-supplier',refInvoiceId:returned.id,toAccountId:'g317-cash',method:'cash'}));
100 + assert.deepEqual({
101 + transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,
102 + journals:(await db.getAll('journal_entries')).length,
103 + settlements:(await db.getAll('settlements')).length,
104 + lines:(await db.getAll('journal_lines')).length
105 + },before);
106 +});
107 +
108 +test('G317 sale return allocates customer receivable first and refunds only excess credit',async()=>{
109 + await setup();
110 + const original=await retail.issueInvoice(invoice('sale',10,100));
111 + await retail.postTransaction({id:'g317-customer-receipt',type:'receipt',date,amount:700,
112 + contactId:'g317-customer',refInvoiceId:original.id,toAccountId:'g317-cash',method:'cash'});
113 + const returned=await retail.issueInvoice(invoice('sale_return',4,100,{originalInvoiceId:original.id}));
114 + let source=await db.get('invoices',original.id);
115 + let credit=await db.get('invoices',returned.id);
116 + assert.equal(source.creditAppliedAmount,300);
117 + assert.equal(source.remaining,0);
118 + assert.equal(credit.creditAppliedAmount,300);
119 + assert.equal(credit.remaining,100);
120 + assert.equal((await allocationRows(original.id)).length,1);
121 + assert.equal(await controlBalance('102','g317-customer','debit'),-100,
122 + 'customer return creates a 100 Rial credit balance before refund');
123 + await retail.postTransaction({id:'g317-customer-refund',type:'payment',date,amount:100,
124 + contactId:'g317-customer',refInvoiceId:returned.id,fromAccountId:'g317-cash',method:'cash',
125 + reasonCode:'goods_return',explicitlyApproved:true});
126 + source=await db.get('invoices',original.id);
127 + credit=await db.get('invoices',returned.id);
128 + assert.equal(source.remaining,0);
129 + assert.equal(credit.remaining,0);
130 + assert.equal(credit.paidAmount,100);
131 + assert.equal(await controlBalance('102','g317-customer','debit'),0);
132 + const beforeOverRefund={transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,journals:(await db.getAll('journal_entries')).length,settlements:(await db.getAll('settlements')).length};
133 + await assert.rejects(retail.postTransaction({id:'g317-extra-customer-refund',type:'payment',date,amount:1,contactId:'g317-customer',refInvoiceId:returned.id,fromAccountId:'g317-cash',method:'cash',reasonCode:'goods_return',explicitlyApproved:true}));
134 + assert.deepEqual({transactions:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,journals:(await db.getAll('journal_entries')).length,settlements:(await db.getAll('settlements')).length},beforeOverRefund);
135 +});
136 +
137 +test('G317 unpaid purchase is reduced by the full return credit without fake cash settlement',async()=>{
138 + await setup();
139 + const original=await retail.issueInvoice(invoice('purchase',10,100));
140 + const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{originalInvoiceId:original.id}));
141 + assert.equal((await db.get('invoices',original.id)).remaining,600);
142 + assert.equal((await db.get('invoices',original.id)).creditAppliedAmount,400);
143 + assert.equal((await db.get('invoices',returned.id)).remaining,0);
144 + assert.equal((await db.get('invoices',returned.id)).paidAmount,0);
145 + assert.equal((await allocationRows(original.id))[0].amount,400);
146 + assert.equal((await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,0);
147 +});
148 +
149 +test('G317 multiple partial purchase returns allocate the original payable only once',async()=>{
150 + await setup();
151 + const original=await retail.issueInvoice(invoice('purchase',10,100));
152 + await retail.postTransaction({id:'g317-multi-payment',type:'payment',date,amount:700,
153 + contactId:'g317-supplier',refInvoiceId:original.id,fromAccountId:'g317-cash',method:'cash'});
154 + const first=await retail.issueInvoice(invoice('purchase_return',2,100,{originalInvoiceId:original.id}));
155 + const second=await retail.issueInvoice(invoice('purchase_return',2,100,{originalInvoiceId:original.id}));
156 + assert.equal((await db.get('invoices',original.id)).creditAppliedAmount,300);
157 + assert.equal((await db.get('invoices',original.id)).remaining,0);
158 + assert.equal((await db.get('invoices',first.id)).remaining,0);
159 + assert.equal((await db.get('invoices',second.id)).creditAppliedAmount,100);
160 + assert.equal((await db.get('invoices',second.id)).remaining,100);
161 + const rows=await allocationRows(original.id);
162 + assert.equal(rows.length,2);
163 + assert.equal(rows.reduce((n,x)=>n+x.amount,0),300);
164 +});
165 +
166 +test('G317 concurrent idempotent return issuance creates one return and one credit allocation',async()=>{
167 + await setup();
168 + const original=await retail.issueInvoice(invoice('purchase',10,100));
169 + await retail.postTransaction({id:'g317-retry-payment',type:'payment',date,amount:700,
170 + contactId:'g317-supplier',refInvoiceId:original.id,fromAccountId:'g317-cash',method:'cash'});
171 + const draft=invoice('purchase_return',4,100,{originalInvoiceId:original.id});
172 + const results=await Promise.all([retail.issueInvoice(draft),retail.issueInvoice(draft)]);
173 + assert.equal(results[0].id,results[1].id);
174 + assert.equal((await db.getAll('invoices')).filter(x=>x.kind==='purchase_return').length,1);
175 + assert.equal((await allocationRows(original.id)).length,1);
176 + assert.equal((await db.get('invoices',original.id)).creditAppliedAmount,300);
177 + assert.equal((await db.get('invoices',results[0].id)).remaining,100);
178 +});
tests/g36-auth-session-isolation.test.mjs new
+47
@@ -0,0 +1,47 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import fs from 'node:fs';
4 +import vm from 'node:vm';
5 +import { fileURLToPath } from 'node:url';
6 +
7 +const authPath = fileURLToPath(new URL('../src/core/Auth.js', import.meta.url));
8 +const source = fs.readFileSync(authPath, 'utf8');
9 +const stripped = source
10 + .replace(/^import .*?;\s*$/gm, '')
11 + .replace(/^export (async function|function|const|class) /gm, '$1 ');
12 +const session = new Map();
13 +const context = vm.createContext({
14 + sessionStorage: {
15 + getItem: key => session.get(key) ?? null,
16 + setItem: (key, value) => session.set(key, String(value)),
17 + removeItem: key => session.delete(key)
18 + },
19 + StorageService: {},
20 + EventBus: {},
21 + LicenseService: {},
22 + TextEncoder, crypto: globalThis.crypto,
23 + Uint8Array, String, JSON, Promise, setTimeout, btoa, atob,
24 +});
25 +vm.runInContext(stripped + '\nthis.__auth = Auth;', context, { filename: authPath });
26 +const auth = context.__auth;
27 +const users = [
28 + { id: 'admin-synthetic', username: 'synthetic', pwHash: 'dummy', pwSalt: 'dummy', role: 'admin' },
29 + { id: 'uninitialized-synthetic', username: 'pending', mustSetPassword: true }
30 +];
31 +test('G36: unknown session identity is rejected', () => {
32 + session.set(auth.sessionKey, 'unknown');
33 + assert.equal(auth._restoreSession(users), null);
34 +});
35 +test('G36: password-uninitialized session is rejected', () => {
36 + session.set(auth.sessionKey, 'uninitialized-synthetic');
37 + assert.equal(auth._restoreSession(users), null);
38 +});
39 +test('G36: existing initialized session id restores without a fresh password challenge (documented risk)', () => {
40 + session.set(auth.sessionKey, 'admin-synthetic');
41 + assert.equal(auth._restoreSession(users)?.id, 'admin-synthetic');
42 +});
43 +test('G36: login screen form has autocomplete off, but this does not prove browser compliance', () => {
44 + assert.match(source, /<form id="finoraAuthForm" autocomplete="off"/);
45 + assert.match(source, /el\.pass\.value = ''/);
46 + assert.match(source, /el\.pass2\.value = ''/);
47 +});
tests/invoice-markpaid-concurrency.test.mjs
+37 -1
@@ -162,4 +162,40 @@ test('legacy concurrent duplicate invoice numbers serialize and reject one save'
162 assert.equal(results.filter(x => x.status === 'fulfilled').length, 1, JSON.stringify(results.map(x => x.status === 'rejected' ? String(x.reason) : x.status)));
163 assert.equal(results.filter(x => x.status === 'rejected').length, 1);
164 assert.equal((await StorageService.getByCompany('invoices', 'markpaid-company')).filter(x => !x.isPreInvoice).length, 1);
165 -});
\ No newline at end of file
165 +});
166 +
167 +test('legacy preinvoice conversion replay returns the same invoice and increments quota once', async () => {
168 + await seed({ isPreInvoice: true, number: '10', items: [], date: '1405/08/12',
169 + subtotal: 1000, totalDiscount: 0, discountType: 'fixed', discountInput: 0,
170 + vatEnabled: false, vatRate: 0, vatAmount: 0, grandTotal: 1000,
171 + paidAmount: 0, paymentMethod: 'cash', remaining: 1000 });
172 + const first = await InvoiceController.convertPreInvoice('markpaid-invoice');
173 + const second = await InvoiceController.convertPreInvoice('markpaid-invoice');
174 + assert.equal(first.id, second.id);
175 + assert.equal(second.isPreInvoice, false);
176 + assert.equal(await StorageService.count('invoices'), 1);
177 + const receipts = (await StorageService.getAll('settings'))
178 + .filter(row => String(row.id).startsWith('issuance_receipt_'));
179 + assert.equal(receipts.length, 1);
180 + const counter = await StorageService.get('settings', 'issuance_global_counter_v1');
181 + assert.equal(counter.count, 1);
182 +});
183 +
184 +test('legacy save-based preinvoice finalization uses payload-bound idempotency on retry', async () => {
185 + await seed({ isPreInvoice: true, number: '10', items: [], date: '1405/08/12' });
186 + const payload = {
187 + kind: 'sale', isPreInvoice: false, number: '10', items: [],
188 + vatEnabled: false, vatRate: 0, paidAmount: 0, discountInput: 0,
189 + idempotencyKey: 'preinvoice-finalize:markpaid-invoice'
190 + };
191 + const first = await InvoiceController.save(payload, 'markpaid-invoice');
192 + const second = await InvoiceController.save(payload, 'markpaid-invoice');
193 + assert.equal(first.id, second.id);
194 + assert.equal(second.isPreInvoice, false);
195 + assert.equal((await StorageService.getAll('settings')).filter(row =>
196 + String(row.id).startsWith('issuance_receipt_')).length, 1);
197 + assert.equal((await StorageService.get('settings', 'issuance_global_counter_v1')).count, 1);
198 + await assert.rejects(InvoiceController.save({
199 + ...payload, description: 'tampered retry', idempotencyKey: payload.idempotencyKey
200 + }, 'markpaid-invoice'));
201 +});
tests/issuance-indexeddb.integration.test.mjs new
+135
@@ -0,0 +1,135 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +import { LicenseService } from '../src/core/LicenseService.js';
6 +import {
7 + recordIssuanceReceipt, counterKey, receiptKey, createIssuanceIdentity,
8 + findIdempotentInvoice
9 +} from '../src/core/IssuanceReceipt.mjs';
10 +
11 +const invoice = (id, changes = {}) => ({
12 + id, companyId: 'idb-company', number: id, kind: 'sale',
13 + isPreInvoice: false, date: '1405/08/12', subtotal: 1000,
14 + totalDiscount: 0, discountType: 'fixed', discountInput: 0,
15 + vatEnabled: false, vatRate: 0, vatAmount: 0, grandTotal: 1000,
16 + paymentMethod: 'cash', paidAmount: 0, items: [],
17 + ...changes
18 +});
19 +async function issue(row, quota, key = 'integration-request-key-0001') {
20 + const identity = await createIssuanceIdentity(row, key);
21 + const request = { ...row, ...identity };
22 + return StorageService.transaction(['invoices', 'settings'], async tx => {
23 + const replay = await findIdempotentInvoice(tx, request);
24 + if (replay) return replay;
25 + await tx.put('invoices', request);
26 + await recordIssuanceReceipt(tx, request, quota);
27 + return request;
28 + });
29 +}
30 +
31 +test('real IndexedDB serializes concurrent issuance against a single remaining quota slot', async () => {
32 + await StorageService.clearAll();
33 + const attempts = Array.from({ length: 10 }, (_, i) =>
34 + issue(invoice('parallel-' + i), { floor: 0, limit: 1 }, 'parallel-request-' + i));
35 + const outcomes = await Promise.allSettled(attempts);
36 + assert.equal(outcomes.filter(x => x.status === 'fulfilled').length, 1);
37 + assert.equal(outcomes.filter(x => x.status === 'rejected').length, 9);
38 + assert.equal(await StorageService.count('invoices'), 1);
39 + const counter = await StorageService.get('settings', counterKey);
40 + assert.equal(counter.count, 1);
41 +});
42 +
43 +test('same idempotency key and same payload concurrently return one committed invoice', async () => {
44 + await StorageService.clearAll();
45 + const payload = invoice('same-request');
46 + const outcomes = await Promise.all([
47 + issue(payload, { floor: 0, limit: 5 }, 'stable-request-key-000001'),
48 + issue({ ...payload, items: [] }, { floor: 0, limit: 5 }, 'stable-request-key-000001')
49 + ]);
50 + assert.equal(outcomes[0].id, outcomes[1].id);
51 + assert.equal(await StorageService.count('invoices'), 1);
52 + assert.equal((await StorageService.get('settings', counterKey)).count, 1);
53 +});
54 +
55 +test('same idempotency key with changed financial payload is rejected without a second write', async () => {
56 + await StorageService.clearAll();
57 + const key = 'stable-request-key-000002';
58 + await issue(invoice('same-key-original'), { floor: 0, limit: 5 }, key);
59 + await assert.rejects(
60 + issue(invoice('same-key-tampered', { grandTotal: 900, subtotal: 900 }), { floor: 0, limit: 5 }, key),
61 + /Idempotency key reused with different invoice content/
62 + );
63 + assert.equal(await StorageService.count('invoices'), 1);
64 + assert.equal((await StorageService.get('settings', counterKey)).count, 1);
65 +});
66 +
67 +test('idempotency records are scoped to company and cannot replay another company invoice', async () => {
68 + await StorageService.clearAll();
69 + const key = 'shared-request-key-company';
70 + await issue(invoice('company-a'), { floor: 0, limit: 5 }, key);
71 + const other = invoice('company-b', { companyId: 'other-company' });
72 + const result = await issue(other, { floor: 0, limit: 5 }, key);
73 + assert.equal(result.id, 'company-b');
74 + assert.equal(result.companyId, 'other-company');
75 + assert.equal(await StorageService.count('invoices'), 2);
76 + assert.equal((await StorageService.get('settings', counterKey)).count, 2);
77 +});
78 +
79 +test('aborted transaction leaves no partial invoice, receipt, idempotency record or counter', async () => {
80 + await StorageService.clearAll();
81 + const row = invoice('abort-before-commit');
82 + const identity = await createIssuanceIdentity(row, 'abort-request-key-000001');
83 + const request = { ...row, ...identity };
84 + await assert.rejects(StorageService.transaction(['invoices', 'settings'], async tx => {
85 + await tx.put('invoices', request);
86 + await recordIssuanceReceipt(tx, request, { floor: 0, limit: 2 });
87 + throw new Error('injected failure before commit');
88 + }), /injected failure/);
89 + assert.equal(await StorageService.get('invoices', row.id), undefined);
90 + assert.equal(await StorageService.get('settings', receiptKey(row.companyId, row.id)), undefined);
91 + assert.equal(await StorageService.get('settings', counterKey), undefined);
92 +});
93 +
94 +test('committed receipt and counter survive database handle close and reopen', async () => {
95 + await StorageService.clearAll();
96 + await issue(invoice('persisted-invoice'), { floor: 0, limit: 3 }, 'persist-request-key-000001');
97 + StorageService.db.close();
98 + StorageService.db = null;
99 + StorageService._opening = null;
100 + await StorageService.init();
101 + assert.equal((await StorageService.get('invoices', 'persisted-invoice')).id, 'persisted-invoice');
102 + assert.equal((await StorageService.get('settings', receiptKey('idb-company', 'persisted-invoice'))).invoiceId, 'persisted-invoice');
103 + assert.equal((await StorageService.get('settings', counterKey)).count, 1);
104 +});
105 +
106 +test('license reconciliation bootstraps a missing counter from surviving historical invoices', async () => {
107 + await StorageService.clearAll();
108 + for (let i = 0; i < 4; i++) await StorageService.put('invoices', invoice('legacy-' + i));
109 + await StorageService.put('invoices', invoice('draft', { isPreInvoice: true }));
110 + const oldState = LicenseService.state;
111 + try {
112 + LicenseService.state = { issuedInvoiceCount: 1 };
113 + const recovered = await LicenseService.reconcileIssuedInvoices();
114 + assert.equal(recovered, 4);
115 + assert.equal(LicenseService.state.issuedInvoiceCount, 4);
116 + assert.equal((await StorageService.get('settings', counterKey)).count, 4);
117 + } finally {
118 + LicenseService.state = oldState;
119 + }
120 +});
121 +
122 +test('license reconciliation never lowers a surviving secure or database high-water mark', async () => {
123 + await StorageService.clearAll();
124 + await StorageService.put('invoices', invoice('one-historical'));
125 + await StorageService.put('settings', { id: counterKey, count: 12, schemaVersion: 1 });
126 + const oldState = LicenseService.state;
127 + try {
128 + LicenseService.state = { issuedInvoiceCount: 15 };
129 + const recovered = await LicenseService.reconcileIssuedInvoices();
130 + assert.equal(recovered, 15);
131 + assert.equal((await StorageService.get('settings', counterKey)).count, 15);
132 + } finally {
133 + LicenseService.state = oldState;
134 + }
135 +});
tests/pack7-license-persistence.test.mjs new
+29
@@ -0,0 +1,29 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { LicenseService } from '../src/core/LicenseService.js';
4 +
5 +test('pack7: failed secure-state persistence restores in-memory invoice count', async () => {
6 + const oldState = LicenseService.state;
7 + const oldSave = LicenseService._save;
8 + const oldPayload = LicenseService.verifiedPayload;
9 + const oldClock = LicenseService.clockRollback;
10 + const oldReconcile = LicenseService.reconcileIssuedInvoices;
11 + try {
12 + LicenseService.state = { trialStartedAt: new Date().toISOString(), issuedInvoiceCount: 3 };
13 + LicenseService.verifiedPayload = null;
14 + LicenseService.clockRollback = false;
15 + LicenseService.reconcileIssuedInvoices = async () => { LicenseService.state.issuedInvoiceCount = Math.max(LicenseService.state.issuedInvoiceCount, 4); };
16 + LicenseService._save = async () => { throw new Error('injected secure storage failure'); };
17 + await assert.rejects(LicenseService.recordIssuedInvoice(), /injected secure storage failure/);
18 + assert.equal(LicenseService.state.issuedInvoiceCount, 4);
19 + LicenseService._save = async () => {};
20 + await LicenseService.recordIssuedInvoice();
21 + assert.equal(LicenseService.state.issuedInvoiceCount, 4);
22 + } finally {
23 + LicenseService.state = oldState;
24 + LicenseService._save = oldSave;
25 + LicenseService.verifiedPayload = oldPayload;
26 + LicenseService.clockRollback = oldClock;
27 + LicenseService.reconcileIssuedInvoices = oldReconcile;
28 + }
29 +});
tests/pack74-issuance-receipt.test.mjs new
+25
@@ -0,0 +1,25 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { receiptKey, recordIssuanceReceipt } from '../src/core/IssuanceReceipt.mjs';
4 +
5 +test('receipt persists once and duplicate is rejected', async () => {
6 + const rows = new Map();
7 + const tx = { get: async (_, id) => rows.get(id), put: async (_, row) => { rows.set(row.id, row); } };
8 + const invoice = { id: 'inv1', companyId: 'c1', number: '5', kind: 'sale', isPreInvoice: false, idempotencyKey: 'receipt-test-key-0001', requestHash: 'a'.repeat(64) };
9 + await assert.rejects(recordIssuanceReceipt(tx, invoice), /quota is mandatory/);
10 + assert.equal(rows.size, 0);
11 + await recordIssuanceReceipt(tx, invoice, { floor: 0, limit: 20 });
12 + assert.equal(rows.get(receiptKey('c1', 'inv1')).number, '5');
13 + await assert.rejects(recordIssuanceReceipt(tx, invoice, { floor: 0, limit: 20 }), /Duplicate issuance receipt/);
14 + assert.equal(rows.get('issuance_global_counter_v1').count, 1);
15 +});
16 +
17 +test('receipt rejects preinvoice and missing identity', async () => {
18 + const tx = { get: async () => null, put: async () => { throw Error('should not write'); } };
19 + await assert.rejects(recordIssuanceReceipt(tx, { id: 'x', companyId: 'c', isPreInvoice: true }), /Invalid issuance receipt/);
20 + await assert.rejects(recordIssuanceReceipt(tx, { id: 'x', isPreInvoice: false }), /Invalid issuance receipt/);
21 +});
22 +
23 +test('receipt key separates company and invoice identities', () => {
24 + assert.notEqual(receiptKey('a', 'bc'), receiptKey('ab', 'c'));
25 +});
tests/pack75-atomic-quota.test.mjs new
+66
@@ -0,0 +1,66 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { recordIssuanceReceipt, counterKey, createRetryStorageKey, createIssuanceIdentity } from '../src/core/IssuanceReceipt.mjs';
4 +
5 +function store() {
6 + const rows = new Map();
7 + const tx = {
8 + get: async (_, id) => rows.get(id),
9 + put: async (_, row) => { rows.set(row.id, row); }
10 + };
11 + return { rows, tx };
12 +}
13 +const invoice = id => ({ id, companyId: 'c1', number: id, kind: 'sale', idempotencyKey: 'quota-test-key-' + id.padStart(8, '0'), requestHash: 'b'.repeat(64) });
14 +
15 +test('quota counts from secure floor and rejects twenty-first issuance', async () => {
16 + const { rows, tx } = store();
17 + await recordIssuanceReceipt(tx, invoice('20'), { floor: 19, limit: 20 });
18 + assert.equal(rows.get(counterKey).count, 20);
19 + await assert.rejects(recordIssuanceReceipt(tx, invoice('21'), { floor: 19, limit: 20 }), /quota exhausted/);
20 + assert.equal(rows.size, 3);
21 +});
22 +test('stale secure floor cannot reset persisted atomic counter', async () => {
23 + const { rows, tx } = store();
24 + await recordIssuanceReceipt(tx, invoice('1'), { floor: 18, limit: 20 });
25 + await recordIssuanceReceipt(tx, invoice('2'), { floor: 0, limit: 20 });
26 + assert.equal(rows.get(counterKey).count, 20);
27 + await assert.rejects(recordIssuanceReceipt(tx, invoice('3'), { floor: 0, limit: 20 }), /quota exhausted/);
28 +});
29 +test('malformed quota and corrupt counter fail closed', async () => {
30 + const { rows, tx } = store();
31 + await assert.rejects(recordIssuanceReceipt(tx, invoice('1'), { floor: -1, limit: 20 }), /quota is mandatory/);
32 + rows.set(counterKey, { id: counterKey, count: -1 });
33 + await assert.rejects(recordIssuanceReceipt(tx, invoice('2'), { floor: 0, limit: 20 }), /Corrupt issuance counter/);
34 +});
35 +
36 +test('receipt cannot be written without a mandatory quota', async () => {
37 + const { rows, tx } = store();
38 + await assert.rejects(recordIssuanceReceipt(tx, invoice('missing-quota')), /quota is mandatory/);
39 + assert.equal(rows.size, 0);
40 +});
41 +
42 +test('UI retry storage keys are deterministic per payload and isolated across payloads', async () => {
43 + const a = await createRetryStorageKey('payload-a');
44 + const aRetry = await createRetryStorageKey('payload-a');
45 + const b = await createRetryStorageKey('payload-b');
46 + assert.equal(a, aRetry);
47 + assert.notEqual(a, b);
48 + assert.match(a, /^factor_easypro_pending_invoice_v2:[a-f0-9]{64}$/);
49 + await assert.rejects(createRetryStorageKey(''), /Invalid retry signature/);
50 +});
51 +
52 +test('automatic server-assigned invoice number does not break a retry fingerprint', async () => {
53 + const base = {
54 + companyId: 'c1', kind: 'sale', date: '1405/08/12', contactId: 'cust1',
55 + items: [{ productId: 'p1', qty: 1, price: 500, discount: 0 }],
56 + subtotal: 500, totalDiscount: 0, discountType: 'fixed', discountInput: 0,
57 + vatEnabled: false, vatRate: 0, vatAmount: 0, grandTotal: 500,
58 + paymentMethod: 'cash', paidAmount: 0, requestedNumber: null
59 + };
60 + const first = await createIssuanceIdentity({ ...base, number: '101' }, 'stable-retry-number-test');
61 + const retry = await createIssuanceIdentity({ ...base, number: '102' }, 'stable-retry-number-test');
62 + assert.equal(first.requestHash, retry.requestHash);
63 + const manualA = await createIssuanceIdentity({ ...base, requestedNumber: '500', number: '500' }, 'manual-retry-number-test');
64 + const manualB = await createIssuanceIdentity({ ...base, requestedNumber: '501', number: '501' }, 'manual-retry-number-test');
65 + assert.notEqual(manualA.requestHash, manualB.requestHash);
66 +});
tests/reconciliation.test.mjs
+32
@@ -1,12 +1,17 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import 'fake-indexeddb/auto';
4 +globalThis.window ??= globalThis;
5 +const secureTestStorage = new Map();
6 +globalThis.localStorage ??= { getItem: key => secureTestStorage.get(key) ?? null, setItem: (key, value) => secureTestStorage.set(key, String(value)), removeItem: key => secureTestStorage.delete(key) };
7 import { reconcileFinancialData } from '../src/core/ReconciliationCore.mjs';
8 import { StorageService as db } from '../src/core/StorageService.js';
9 import { AccountingService as accounts } from '../src/core/AccountingService.js';
10 import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
11 import { Auth } from '../src/core/Auth.js';
12 import { CompanyService } from '../src/core/CompanyService.js';
13 +import { LicenseService } from '../src/core/LicenseService.js';
14 +const { InvoiceController } = await import('../src/controllers/InvoiceController.js');
15
16 const date='1405/07/20', company='reconciliation-c1';
17 const fixture=()=>({
@@ -64,6 +69,9 @@ test('legacy company report never compares stock to a non-integrated ledger',()=
69
70 async function setup(){
71 await db.clearAll();
72 + LicenseService.state = { trialStartedAt: new Date().toISOString(), lastSeenAt: new Date().toISOString(), installationId: 'reconciliation-test-installation', issuedInvoiceCount: 0 };
73 + LicenseService.verifiedPayload = null;
74 + LicenseService.clockRollback = false;
75 Auth.currentUser={id:'recon-admin',role:'admin',username:'admin'};
76 CompanyService.activeCompanyId=company;
77 await db.put('companies',{id:company,name:'Company A'});
@@ -343,3 +351,27 @@ test('A05: explicit outbound cheque clearance checks payable bank direction and
351 chequeOffset.contactId='wrong-drawer';
352 assert.ok(reconcileFinancialData(f).issues.some(x=>x.code==='CHEQUE_CLEARING_OFFSET_MISMATCH'));
353 });
354 +
355 +
356 +test('V2 preinvoice conversion replay returns the committed invoice without duplicate journal or quota', async () => {
357 + await setup();
358 + await db.put('invoices', {
359 + id: 'v2-preinvoice-replay', companyId: company, kind: 'sale',
360 + number: '120', date, contactId: 'contact-a', contactName: 'Customer',
361 + isPreInvoice: true, items: [{ productId: null, productName: 'Service', qty: 1, price: 1000, lineSubtotal: 1000, lineTotal: 1000, discount: 0 }], subtotal: 1000, totalDiscount: 0,
362 + discountType: 'fixed', discountInput: 0, vatEnabled: false,
363 + vatRate: 0, vatAmount: 0, grandTotal: 1000, paidAmount: 0,
364 + paymentMethod: 'cash', remaining: 1000, status: 'unpaid'
365 + });
366 + const first = await InvoiceController.convertPreInvoice('v2-preinvoice-replay');
367 + const journalCount = (await db.getAll('journal_entries')).length;
368 + const second = await InvoiceController.convertPreInvoice('v2-preinvoice-replay');
369 + assert.equal(first.id, second.id);
370 + assert.equal(second.isPreInvoice, false);
371 + assert.equal((await db.getAll('journal_entries')).length, journalCount);
372 + assert.equal((await db.getAll('journal_entries')).length, 1);
373 + const receipts = (await db.getAll('settings'))
374 + .filter(row => String(row.id).startsWith('issuance_receipt_'));
375 + assert.equal(receipts.length, 1);
376 + assert.equal((await db.get('settings', 'issuance_global_counter_v1')).count, 1);
377 +});
tests/report-controller-bundle.test.mjs
+9 -9
@@ -9,14 +9,14 @@ const fixture = {
9 invoices: [
10 {
11 id: 'sale-1', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
12 - subtotal: 100, totalDiscount: 10, grandTotal: 90, paidAmount: 30,
13 - remaining: 60, contactId: 'contact-1', contactName: 'Synthetic customer',
12 + subtotal: 100, totalDiscount: 10, grandTotal: 90, paidAmount: 30, creditAppliedAmount: 10,
13 + remaining: 50, contactId: 'contact-1', contactName: 'Synthetic customer',
14 items: [{ productId: 'product-1', productName: 'Synthetic product',
15 unit: 'عدد', qty: 2, price: 50, lineTotal: 100 }]
16 },
17 {
18 id: 'return-1', kind: 'sale_return', isPreInvoice: false, date: '1405/01/03',
19 - subtotal: 10, grandTotal: 10, contactId: 'contact-1', contactName: 'Synthetic customer',
19 + subtotal: 10, grandTotal: 10, paidAmount: 0, creditAppliedAmount: 10, remaining: 0, contactId: 'contact-1', contactName: 'Synthetic customer',
20 items: [{ productId: 'product-1', productName: 'Synthetic product',
21 unit: 'عدد', qty: 1, price: 10, lineTotal: 10 }]
22 },
@@ -226,17 +226,17 @@ test('a missing historical and current product cost is explicitly classified as
226 });
227
228
229 -test('customer reports subtract returns from net sales, include return-only customers and disclose gross invoice balances', async () => {
229 +test('customer reports subtract returns and return-credit allocations from net sales receivable, including return-only customers', async () => {
230 const originalLoad = ReportController._loadData;
231 const data = {
232 invoices: [
233 { id:'customer-sale', kind:'sale', isPreInvoice:false, date:'1405/01/02',
234 contactId:'customer-1', contactName:'Customer one', grandTotal:1000,
235 - paidAmount:400, remaining:600 },
235 + paidAmount:400, creditAppliedAmount:250, remaining:350 },
236 { id:'customer-return', kind:'sale_return', isPreInvoice:false, date:'1405/01/03',
237 - contactId:'customer-1', contactName:'Customer one', grandTotal:250 },
237 + contactId:'customer-1', contactName:'Customer one', grandTotal:250, paidAmount:0, creditAppliedAmount:250, remaining:0 },
238 { id:'return-only', kind:'sale_return', isPreInvoice:false, date:'1405/01/04',
239 - contactId:'customer-2', contactName:'Customer two', grandTotal:50 },
239 + contactId:'customer-2', contactName:'Customer two', grandTotal:50, paidAmount:0, remaining:50 },
240 { id:'supplier-purchase', kind:'purchase', isPreInvoice:false, date:'1405/01/05',
241 contactId:'supplier-1', contactName:'Supplier only', grandTotal:9999 }
242 ],
@@ -254,8 +254,8 @@ test('customer reports subtract returns from net sales, include return-only cust
254 assert.deepEqual(
255 { gross: customers[0].totalSales, returns: customers[0].totalReturns,
256 net: customers[0].netSales, paid: customers[0].totalPaid,
257 - invoiceBalanceBeforeReturns: customers[0].totalRemaining },
258 - { gross: 1000, returns: 250, net: 750, paid: 400, invoiceBalanceBeforeReturns: 600 }
257 + netReceivableAfterReturns: customers[0].totalRemaining },
258 + { gross: 1000, returns: 250, net: 750, paid: 400, netReceivableAfterReturns: 350 }
259 );
260 assert.deepEqual(
261 { name: customers[1].contactName, gross: customers[1].totalSales,
tests/retail-phase2.test.mjs
+67 -4
@@ -6,11 +6,17 @@ import { AccountingService as accounts } from '../src/core/AccountingService.js'
6 import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
7 import { Auth } from '../src/core/Auth.js';
8 import { CompanyService } from '../src/core/CompanyService.js';
9 +import { LicenseService } from '../src/core/LicenseService.js';
10
11 const date='1405/07/18';
12 const company='c2-phase2';
13 async function setup(){
14 await db.clearAll();
15 + // Each integration test receives an explicit, valid isolated trial state.
16 + // Production authorization remains mandatory; tests do not bypass it.
17 + LicenseService.state = { trialStartedAt: new Date().toISOString(), lastSeenAt: new Date().toISOString(), installationId: 'retail-phase2-test-installation', issuedInvoiceCount: 0 };
18 + LicenseService.verifiedPayload = null;
19 + LicenseService.clockRollback = false;
20 await db.put('companies',{id:company,name:'Store 2'});
21 Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'};
22 CompanyService.activeCompanyId=company;
@@ -54,7 +60,7 @@ test('v2 sale-purchase cash settlement balance, weighted average and exactly onc
60 assert.equal(journals.length,3);
61 const trial=await accounts.trialBalance();
62 assert.equal(trial.totals.debit,trial.totals.credit);
57 - await assert.rejects(retail.issueInvoice(sold),/قطعی|تکراری/);
63 + const replayed=await retail.issueInvoice(sold); assert.equal(replayed.id,sold.id);
64 assert.equal((await accounts.listJournals()).length,3);
65 const receipt=await retail.postTransaction({id:'receipt-1',type:'receipt',date,amount:400,
66 contactId:'contact-1',refInvoiceId:sold.id,toAccountId:'cash-1',method:'cash'});
@@ -64,6 +70,59 @@ test('v2 sale-purchase cash settlement balance, weighted average and exactly onc
70 assert.deepEqual((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit);
71 assert.equal((await retail.stockBalances({warehouseId:warehouse.id}))[0].value,700);
72 });
73 +test('v2 treasury idempotency key replays one linked receipt across fresh transaction ids',async()=>{
74 + await setup();await purchase10();
75 + const sold=await sale3();
76 + const request={type:'receipt',date,amount:200,contactId:'contact-1',
77 + refInvoiceId:sold.id,toAccountId:'cash-1',method:'cash',
78 + idempotencyKey:'treasury:stable-request-001'};
79 + const first=await retail.postTransaction({...request,id:'receipt-attempt-1'});
80 + const replay=await retail.postTransaction({...request,id:'receipt-attempt-2'});
81 + assert.equal(replay.id,first.id);
82 + assert.equal(replay.id,'receipt-attempt-1');
83 + assert.equal((await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,1);
84 + assert.equal((await db.getAll('journal_entries')).length,3);
85 + assert.equal((await db.getAll('settlements')).length,1);
86 + assert.equal((await db.get('invoices',sold.id)).paidAmount,200);
87 + assert.equal((await db.get('invoices',sold.id)).remaining,400);
88 + await assert.rejects(retail.postTransaction({...request,id:'receipt-attempt-3',amount:201}),/کلید تکرارپذیری/);
89 + assert.equal((await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,1);
90 + assert.equal((await db.getAll('journal_entries')).length,3);
91 + assert.equal((await db.getAll('settlements')).length,1);
92 + assert.equal((await db.get('invoices',sold.id)).paidAmount,200);
93 + const trial=await accounts.trialBalance();assert.equal(trial.totals.debit,trial.totals.credit);
94 +});
95 +test('v2 concurrent treasury requests with one idempotency key commit once',async()=>{
96 + await setup();await purchase10();
97 + const sold=await sale3();
98 + const request={type:'receipt',date,amount:150,contactId:'contact-1',
99 + refInvoiceId:sold.id,toAccountId:'cash-1',method:'cash',
100 + idempotencyKey:'treasury:concurrent-request-001'};
101 + const [first,second]=await Promise.all([
102 + retail.postTransaction({...request,id:'concurrent-attempt-1'}),
103 + retail.postTransaction({...request,id:'concurrent-attempt-2'})
104 + ]);
105 + assert.equal(first.id,second.id);
106 + assert.equal((await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,1);
107 + assert.equal((await db.getAll('settlements')).length,1);
108 + assert.equal((await db.getAll('journal_entries')).length,3);
109 + assert.equal((await db.get('invoices',sold.id)).paidAmount,150);
110 + assert.equal((await db.get('invoices',sold.id)).remaining,450);
111 + const trial=await accounts.trialBalance();assert.equal(trial.totals.debit,trial.totals.credit);
112 +});
113 +test('v2 treasury transfer idempotency key replays without a second journal',async()=>{
114 + await setup();
115 + const second=await retail.createTreasuryAccount({id:'cash-2',recordType:'account',type:'cashbox',
116 + name:'Second cashbox',initialBalance:0,isActive:true,isDefault:false});
117 + const request={type:'transfer',date,amount:50,fromAccountId:'cash-1',toAccountId:second.id,
118 + method:'transfer',idempotencyKey:'treasury:transfer-request-001'};
119 + const first=await retail.postTransaction({...request,id:'transfer-attempt-1'});
120 + const replay=await retail.postTransaction({...request,id:'transfer-attempt-2'});
121 + assert.equal(replay.id,first.id);
122 + assert.equal((await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length,1);
123 + assert.equal((await db.getAll('journal_entries')).length,1);
124 + const trial=await accounts.trialBalance();assert.equal(trial.totals.debit,trial.totals.credit);
125 +});
126 test('v2 stock over-issue aborts invoice, stock and journal atomically',async()=>{
127 await setup();await purchase10();
128 const invoiceTooBig=invoice('sale',11,200);
@@ -237,8 +296,9 @@ test('v2 concurrent posting of same invoice commits exactly once',async()=>{
296 await setup();await purchase10();
297 const same=invoice('sale',1,200);
298 const [a,b]=await Promise.allSettled([retail.issueInvoice(same),retail.issueInvoice(same)]);
240 - assert.equal([a,b].filter(x=>x.status==='fulfilled').length,1);
241 - assert.equal([a,b].filter(x=>x.status==='rejected').length,1);
299 + assert.equal([a,b].filter(x=>x.status==='fulfilled').length,2);
300 + assert.equal([a,b].filter(x=>x.status==='rejected').length,0);
301 + assert.equal(a.value.id,b.value.id);
302 assert.equal((await accounts.listJournals()).length,2);
303 assert.equal((await retail.stockBalances())[0].quantityUnits,9000);
304 assert.equal((await db.getAll('stock_movements')).length,2);
@@ -429,7 +489,10 @@ test('A01/A03: a referenced customer return creates one atomic correction and co
489 a.eventType === 'commercial_journal_posted'));
490 assert.equal((await db.get('invoices', sold.id)).grandTotal, 600);
491 assert.equal((await db.get('invoices', sold.id)).paidAmount, 200);
432 - assert.equal((await db.getAll('settlements')).length, 1);
492 + const settlements = await db.getAll('settlements');
493 + assert.equal(settlements.length, 2);
494 + assert.equal(settlements.filter(x => x.settlementType === 'credit_allocation' && x.sourceInvoiceId === returned.id).length, 1);
495 + assert.equal(settlements.find(x => x.settlementType === 'credit_allocation').amount, 200);
496 assert.equal((await db.getAll('stock_movements')).filter(x => x.refId === returned.id).length, 1);
497 await assert.rejects(retail.issueInvoice(invoice('sale_return', 3, 200, {
498 originalInvoiceId: sold.id
tests/return-credit-allocation-core.test.mjs new
+54
@@ -0,0 +1,54 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { previewReturnCreditAllocation } from '../src/core/ReturnCreditAllocationCore.mjs';
4 +
5 +test('return credit first offsets open original balance and leaves only excess as refundable credit',()=>{
6 + assert.deepEqual(previewReturnCreditAllocation({
7 + originalTotal:1_000_000,originalPaidAmount:700_000,priorCreditApplied:0,returnAmount:400_000
8 + }),{
9 + originalOpenBefore:300_000,allocatedToOriginal:300_000,originalOpenAfter:0,
10 + returnCreditRemaining:100_000,originalTotal:1_000_000,originalPaidAmount:700_000,
11 + priorCreditApplied:0,returnAmount:400_000
12 + });
13 +});
14 +
15 +test('unpaid original invoice absorbs the entire return credit without a cash refund',()=>{
16 + const result=previewReturnCreditAllocation({
17 + originalTotal:1_000_000,originalPaidAmount:0,returnAmount:400_000
18 + });
19 + assert.equal(result.allocatedToOriginal,400_000);
20 + assert.equal(result.originalOpenAfter,600_000);
21 + assert.equal(result.returnCreditRemaining,0);
22 +});
23 +
24 +test('fully paid original invoice leaves the full return as cash-recoverable credit',()=>{
25 + const result=previewReturnCreditAllocation({
26 + originalTotal:1_000_000,originalPaidAmount:1_000_000,returnAmount:400_000
27 + });
28 + assert.equal(result.allocatedToOriginal,0);
29 + assert.equal(result.originalOpenAfter,0);
30 + assert.equal(result.returnCreditRemaining,400_000);
31 +});
32 +
33 +test('multiple return allocations consume the original open amount once and conserve value',()=>{
34 + const first=previewReturnCreditAllocation({
35 + originalTotal:1_000_000,originalPaidAmount:700_000,returnAmount:200_000
36 + });
37 + const second=previewReturnCreditAllocation({
38 + originalTotal:1_000_000,originalPaidAmount:700_000,
39 + priorCreditApplied:first.allocatedToOriginal,returnAmount:200_000
40 + });
41 + assert.equal(first.allocatedToOriginal+second.allocatedToOriginal,300_000);
42 + assert.equal(second.originalOpenAfter,0);
43 + assert.equal(first.returnCreditRemaining+second.returnCreditRemaining,100_000);
44 +});
45 +
46 +test('unsafe, negative and over-allocated source amounts are rejected',()=>{
47 + for(const args of [
48 + {originalTotal:0,returnAmount:1},
49 + {originalTotal:10,originalPaidAmount:-1,returnAmount:1},
50 + {originalTotal:10,originalPaidAmount:8,priorCreditApplied:3,returnAmount:1},
51 + {originalTotal:10,returnAmount:Number.MAX_SAFE_INTEGER+1},
52 + {originalTotal:10,returnAmount:0}
53 + ]) assert.throws(()=>previewReturnCreditAllocation(args));
54 +});
tests/treasury-retry-identity.test.mjs new
+90
@@ -0,0 +1,90 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { webcrypto } from 'node:crypto';
5 +import { readFile } from 'node:fs/promises';
6 +import { StorageService } from '../src/core/StorageService.js';
7 +import {
8 + createTreasuryRetryIdentity, clearTreasuryRetryIdentity
9 +} from '../src/core/IssuanceReceipt.mjs';
10 +
11 +if (!globalThis.crypto) Object.defineProperty(globalThis, 'crypto', { value: webcrypto });
12 +let sequence = 0;
13 +const makeId = () => 'treasury:durable-request-' + (++sequence).toString().padStart(4, '0');
14 +async function clear(identity) {
15 + await StorageService.transaction('settings', tx => tx.delete('settings', identity.storageKey));
16 +}
17 +
18 +test('treasury retry identity is atomic across concurrent callers and survives WebView restart', async () => {
19 + const signature = JSON.stringify({
20 + companyId: 'synthetic-company-A', type: 'receipt', date: '1405/08/18',
21 + amount: 200000, method: 'cash', contactId: 'synthetic-contact',
22 + refInvoiceId: 'synthetic-invoice', fromAccountId: null,
23 + toAccountId: 'synthetic-cashbox', description: 'synthetic acceptance',
24 + reasonCode: null
25 + });
26 + const identities = await Promise.all(Array.from({ length: 6 },
27 + () => createTreasuryRetryIdentity(signature, StorageService, makeId)));
28 + assert.equal(new Set(identities.map(x => x.idempotencyKey)).size, 1);
29 + assert.equal(sequence, 1);
30 + const first = identities[0];
31 + const stored = await StorageService.get('settings', first.storageKey);
32 + assert.equal(stored.signatureHash.length, 64);
33 + assert.equal(stored.idempotencyKey, first.idempotencyKey);
34 + assert.equal(JSON.stringify(stored).includes('200000'), false);
35 + assert.equal(JSON.stringify(stored).includes('synthetic-invoice'), false);
36 +
37 + // A fresh WebView process reads the same IndexedDB retry record.
38 + const afterRestart = await createTreasuryRetryIdentity(signature, StorageService, makeId);
39 + assert.equal(afterRestart.idempotencyKey, first.idempotencyKey);
40 + assert.equal(afterRestart.storageKey, first.storageKey);
41 + assert.equal(sequence, 1);
42 + await clear(first);
43 +});
44 +
45 +test('changed payload or company receives a distinct retry identity', async () => {
46 + const base = { companyId: 'synthetic-company-A', type: 'receipt', amount: 200000, invoice: 'invoice-A' };
47 + const a = await createTreasuryRetryIdentity(JSON.stringify(base), StorageService, makeId);
48 + const changedAmount = await createTreasuryRetryIdentity(JSON.stringify({ ...base, amount: 300000 }), StorageService, makeId);
49 + const changedCompany = await createTreasuryRetryIdentity(JSON.stringify({ ...base, companyId: 'synthetic-company-B' }), StorageService, makeId);
50 + assert.notEqual(a.idempotencyKey, changedAmount.idempotencyKey);
51 + assert.notEqual(a.idempotencyKey, changedCompany.idempotencyKey);
52 + await Promise.all([clear(a), clear(changedAmount), clear(changedCompany)]);
53 +});
54 +
55 +test('successful completion clears only its matching pending key and allows a later identical intent', async () => {
56 + const signature = 'same valid synthetic receipt payload';
57 + const first = await createTreasuryRetryIdentity(signature, StorageService, makeId);
58 + const wrong = await clearTreasuryRetryIdentity(StorageService, {
59 + storageKey: first.storageKey, idempotencyKey: 'treasury:not-the-same-key'
60 + });
61 + assert.equal(wrong, false);
62 + const cleared = await clearTreasuryRetryIdentity(StorageService, first);
63 + assert.equal(cleared, true);
64 + const nextIntent = await createTreasuryRetryIdentity(signature, StorageService, makeId);
65 + assert.notEqual(first.idempotencyKey, nextIntent.idempotencyKey);
66 + await clear(nextIntent);
67 +});
68 +
69 +test('corrupt retry metadata fails closed rather than minting a replacement key', async () => {
70 + const signature = 'corruption synthetic signature';
71 + const first = await createTreasuryRetryIdentity(signature, StorageService, makeId);
72 + await StorageService.put('settings', {
73 + id: first.storageKey, signatureHash: first.storageKey.slice('treasury_retry_v1:'.length),
74 + idempotencyKey: '', recordType: 'treasury_retry_pending', schemaVersion: 1
75 + });
76 + await assert.rejects(
77 + createTreasuryRetryIdentity(signature, StorageService, makeId),
78 + /Corrupt treasury retry identity/
79 + );
80 + await clear(first);
81 +});
82 +
83 +test('treasury UI uses the durable company-scoped IndexedDB identity through commit', async () => {
84 + const source = await readFile(new URL('../src/views/TreasuryView.js', import.meta.url), 'utf8');
85 + assert.match(source, /createTreasuryRetryIdentity\(retrySignature, StorageService\)/);
86 + assert.match(source, /companyId: await DataScope\.companyId\(\)/);
87 + assert.match(source, /data\.idempotencyKey = identity\.idempotencyKey/);
88 + assert.match(source, /clearTreasuryRetryIdentity\(StorageService/);
89 + assert.doesNotMatch(source, /txIdempotencyKey|localStorage/);
90 +});