فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(A01): create atomic commercial return correction records
* feat(A01): combine independent-refund safety and atomic correction references * test(A01): cover linked return corrections after treasury safety guard
davoodmehraban89 committed
Oct 14, 2026 at 23:53 UTC
faa3c311ba2bdd356978d7ffc59401fec7b42fcf
2 files changed
+65
-3
src/core/RetailPostingService.js
+14
-3
@@ -14,7 +14,7 @@ export const FINANCE_STORES = Object.freeze([
14
'invoices','invoice_items','stock_movements','products','contacts','treasury',
15
'warehouses','inventory_balances','stocktakes','stocktake_lines',
16
'settlements','expenses','cheques','settings','account_mappings',
17
- 'audit_events'
17
+ 'audit_events','document_corrections'
18
]);
19
const uid=p=>StorageService.uid(p);
20
const actor=()=>Auth.current()?.id||null;
@@ -196,7 +196,7 @@ class RetailPostingServiceImpl {
196
await AuditService.append(tx, { companyId: ctx.companyId,
197
eventType: 'commercial_journal_posted', sourceType: kind, sourceId: journal.id,
198
commandKey: 'retail-journal:' + key, businessDate: ctx.date,
199
- lineCount: filtered.length });
199
+ lineCount: filtered.length, correlationId: journal.id });
200
return journal;
201
}
202
async stock(tx,ctx,warehouseId,item,direction,costValue,refId,refType='invoice') {
@@ -242,7 +242,7 @@ class RetailPostingServiceImpl {
242
if(!invoice.originalInvoiceId)throw Error('فاکتور مرجوعی باید به فاکتور اولیه متصل باشد');
243
const origin=sameCompany(await tx.get('invoices',invoice.originalInvoiceId),company,'فاکتور اولیه');
244
const validKinds=invoice.kind==='sale_return'?['sale','non_formal']:['purchase'];
245
- if(!validKinds.includes(origin.kind)||origin.isPreInvoice)
245
+ if(!validKinds.includes(origin.kind)||origin.isPreInvoice||!origin.financePosted)
246
throw Error('نوع فاکتور اولیه با مرجوعی سازگار نیست');
247
if(origin.contactId!==invoice.contactId)
248
throw Error('طرف حساب مرجوعی با فاکتور اولیه مطابقت ندارد');
@@ -343,6 +343,17 @@ class RetailPostingServiceImpl {
343
contactId:invoice.contactId,invoiceId:invoice.id,method:invoice.paymentMethod,
344
type:isIncoming?'receipt':'payment',referenceKind:invoice.kind});
345
}
346
+ if(['sale_return','purchase_return'].includes(invoice.kind)) {
347
+ await tx.add('document_corrections', {
348
+ id: uid('cor_'), companyId: company, sourceType: 'invoice',
349
+ sourceId: invoice.originalInvoiceId, correctionType: 'return',
350
+ resultType: 'invoice', resultId: invoice.id,
351
+ correlationId: journal.id, idempotencyKey: JSON.stringify([company,'return',invoice.id]),
352
+ actorId: actor(), occurredAtUtc: today(), businessDate: ctx.date,
353
+ documentVersion: 1, schemaVersion: 1,
354
+ reasonCode: invoice.kind === 'sale_return' ? 'customer_return' : 'supplier_return'
355
+ });
356
+ }
357
return (await tx.get('invoices',invoice.id));
358
});
359
}
tests/retail-phase2.test.mjs
+51
@@ -403,3 +403,54 @@ test('A01: sales and purchase returns cannot silently refund or collect cash', a
403
assert.equal((await db.getAll('settlements')).length, original.settlements);
404
}
405
});
406
+
407
+test('A01/A03: a referenced customer return creates one atomic correction and correlated audit record', async () => {
408
+ await setup();
409
+ await purchase10();
410
+ const sold = await sale3({ paidAmount: 200 });
411
+ const returned = await retail.issueInvoice(invoice('sale_return', 1, 200, {
412
+ originalInvoiceId: sold.id
413
+ }));
414
+ const corrections = await db.getAll('document_corrections');
415
+ assert.equal(corrections.length, 1);
416
+ const correction = corrections[0];
417
+ assert.equal(correction.companyId, company);
418
+ assert.equal(correction.sourceId, sold.id);
419
+ assert.equal(correction.resultId, returned.id);
420
+ assert.equal(correction.correctionType, 'return');
421
+ assert.equal(correction.reasonCode, 'customer_return');
422
+ assert.equal(correction.actorId, 'phase2-admin');
423
+ assert.ok(correction.idempotencyKey.includes(returned.id));
424
+ const audits = await db.getAll('audit_events');
425
+ assert.ok(audits.some(a => a.sourceId === returned.journalId &&
426
+ a.correlationId === correction.correlationId &&
427
+ a.eventType === 'commercial_journal_posted'));
428
+ assert.equal((await db.get('invoices', sold.id)).grandTotal, 600);
429
+ assert.equal((await db.get('invoices', sold.id)).paidAmount, 200);
430
+ assert.equal((await db.getAll('settlements')).length, 1);
431
+ assert.equal((await db.getAll('stock_movements')).filter(x => x.refId === returned.id).length, 1);
432
+ await assert.rejects(retail.issueInvoice(invoice('sale_return', 3, 200, {
433
+ originalInvoiceId: sold.id
434
+ })), /بیشتر/);
435
+ assert.equal((await db.getAll('document_corrections')).length, 1);
436
+});
437
+
438
+test('A01: customer returns reject non-posted legacy origin without partial writes', async () => {
439
+ await setup();
440
+ await purchase10();
441
+ await db.put('invoices', {
442
+ id: 'old-unposted', companyId: company, kind: 'sale',
443
+ financePosted: false, isPreInvoice: false,
444
+ contactId: 'contact-1', items: [{
445
+ productId: 'product-1', qty: 2, price: 200,
446
+ lineTotal: 400, lineSubtotal: 400
447
+ }],
448
+ grandTotal: 400, subtotal: 400, totalDiscount: 0, vatAmount: 0, number: 'legacy'
449
+ });
450
+ const countBefore = (await db.getAll('journal_entries')).length;
451
+ const target = invoice('sale_return', 1, 200, { originalInvoiceId: 'old-unposted' });
452
+ await assert.rejects(retail.issueInvoice(target), /سازگار نیست/);
453
+ assert.equal(await db.get('invoices', target.id), undefined);
454
+ assert.equal((await db.getAll('journal_entries')).length, countBefore);
455
+ assert.equal((await db.getAll('document_corrections')).length, 0);
456
+});