سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 10:30 UTC
test(finora): prove draft purchase leaks into Phase5 stock and weighted average
davoodmehraban89 committed
Nov 23, 2026 at 08:55 UTC
f899b81e937c23da74b5d76ca86536c8de4abfaf
3 files changed
+117
PROJECT_STATE.md
+5
@@ -769,3 +769,8 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
769
- **Implementation scope:** amend **existing Draft PR240** (no new QA PR) on branch `qa/finora-issue238-inventory-count-browser-red-20261123`. Extend only the current `scripts/accounting-document-workflow.spec.js` + append-only `PROJECT_STATE.md` and `docs/EXECUTION_STATUS.md` with one loaded-browser deterministic read-model test. Seed the existing authenticated synthetic Supabase fixture with one posted linked purchase (2 units @ 50) and one linked DRAFT purchase (3 units @ 100), both same company/warehouse/product, with balanced synthetic voucher lines and no posted warehouse receipt for draft. Verify both purchase status resolution and that `productMovement`/Kardex consistently project **2** while current Phase5 stock incorrectly projects **5**, current Phase5 average cost **80**, and its rendered inventory table reflects the wrong numbers. Desired Phase5: stock **2**, average cost **50**, excluding the DRAFT from effective operational purchase events and read model. This is a stated acceptance policy *only where no independent physical receipt/commit exists*; if physical receipt is a separate event, product owner must define its recognition contract.
770
- **Fail-closed sentinel:** exact known defect fingerprint -> transparent `FINORA_ISSUE238_DRAFT_PURCHASE_STOCK_EXPECTED_RED` and Playwright expected-failure; corrected consistent status-aware stock/average/Kardex -> regular PASS; all third states, missing linked vouchers, wrong source status, company/warehouse, unbalanced seeded graph or mismatched display -> **real CI failure before xfail**.
771
- **Boundary:** synthetic authenticated browser test, NOT a real-JWT inventory permission exploit or production proof. No production JS, SQL/migrations, RLS/Auth/grants, ledger history, main/merge/hosted database or release changed. Run exact successor head Quality/WP1/WP2/Security; verify specific browser marker, not only green CI. Phase completion estimates unchanged.
772
+
773
+### 2026-11-23 — FIN-QA-ISSUE238-DRAFT-PURCHASE-STOCK / test implementation before CI
774
+- Extended existing `scripts/accounting-document-workflow.spec.js` with one actual loaded Phase5 inventory render/read-model Playwright regression on a synthetic authenticated Supabase fixture. Posted credit purchase: QA_CO/QA_WH/QA_PROD 2×50, source-linked POSTED voucher; DRAFT purchase: same scope 3×100, source-linked balanced DRAFT voucher; **no physical receipt/stockMovement**. Both journal lines validated as balanced before test.
775
+- Expected current PRODUCT RED: `productMovement`/Kardex see only posted 2 units, but Phase5 operational inventory events include both sources, p5Stock + rendered stock show 5, weighted average + rendered cost show 80. Required effective read-model excludes the draft source: posted 2 and average 50, preserves visible committed purchase, and does not count draft until a separate authorized receipt. Exact wrong fingerprint alone yields `FINORA_ISSUE238_DRAFT_PURCHASE_STOCK_EXPECTED_RED`; unknown third state fails CI before expected failure. Future correct projection is ordinary PASS.
776
+- No financial runtime JS, SQL/migrations, schema/permissions/Auth/RLS, posted history, main, prod or merge changes. Final exact-SHA CI must be checked and not confused with product acceptance.
docs/EXECUTION_STATUS.md
+6
@@ -242,3 +242,9 @@
242
- یک مورد جدید در Playwright فعلی ساخته شد: موجودی آغازین ۲ واحد با بهای ۲۵؛ شمارش ۵ واحد؛ اختلاف مثبت ۳ واحد و ارزش حسابداری ۷۵. دکمهٔ واقعی `p5SaveCount` اجرا میشود و دادههای ذخیرهشده در سرور ساختگی بررسی میشوند.
243
- قرارداد مورد انتظار: شمارش و گردش موجودی تا تأیید مستقل DRAFT بمانند، یک سند حسابداری متوازن DRAFT متصل باشد، قبل از تأیید هیچ اثر قطعی روی موجودی ۲ واحدی یا دفترکل ایجاد نشود. رفتار اشتباه فعلی با `FINORA_ISSUE238_INVENTORY_COUNT_EXPECTED_RED` ثبت میشود؛ هر حالت ناشناخته یا بدون اتصال شکست واقعی است.
244
- در این مرحله هیچ کد اجرایی مالی یا مجوز و دادهٔ واقعی تغییر نکرده؛ آزمون برای پذیرش نیازمند CI روی SHA نهایی است.
245
+
246
+
247
+### ۱۴۰۵/۰۹/۰۲ — آزمون خواندن موجودی با خرید قطعی و پیشنویس
248
+- در همان PR240، یک سناریوی Playwright با دو منبع خرید ساختگی اما متصل به اسناد حسابداری متوازن و با وضعیت قطعی/پیشنویس اضافه شد: خرید قطعی ۲ واحد × ۵۰؛ خرید پیشنویس ۳ واحد × ۱۰۰؛ بدون هیچ رسید/حرکت انبار جداگانه.
249
+- تست، وضعیت سند، کاردکس، `productMovement`، `p5OperationalEvents`، موجودی و میانگین بهای Phase5 و جدول واقعی UI را مقایسه میکند. خروجی صحیح تا پیش از رسید و تأیید مستقل: موجودی ۲، بهای میانگین ۵۰؛ رفتار فعلی مورد انتظار: موجودی ۵، بهای میانگین ۸۰. فقط اثر دقیق شناختهشده با `FINORA_ISSUE238_DRAFT_PURCHASE_STOCK_EXPECTED_RED` بهعنوان شکست مورد انتظار ثبت میشود؛ حالت سوم باعث شکست واقعی CI است.
250
+- این یک آزمون مرورگر با سرور ساختگی است؛ ادعای اثبات مجوز JWT انبار یا اصلاح نرمافزار نیست. نتیجهٔ آزمونها تا مشاهدهٔ CI روی SHA جدید در انتظار تأیید است.
scripts/accounting-document-workflow.spec.js
+106
@@ -1530,3 +1530,109 @@ test('P0 #238 expected RED: inventory count Save must persist pending stock and
1530
test.fail(true,'#238 / ADR216: inventory count Save must not finalize stock or journal without independent accounting approval');
1531
expect(observed).toEqual(required);
1532
});
1533
+
1534
+
1535
+// #238: a linked DRAFT purchase with NO committed physical receiving document
1536
+// must not change effective Phase5 stock/weighted-average valuation. Compare the
1537
+// same authenticated loaded browser's Kardex and accounting read models. This is
1538
+// synthetic Supabase-backed UI evidence, NOT a real JWT warehouse transaction.
1539
+test('P0 #238 expected RED: draft purchase must not inflate Phase5 stock or weighted-average cost',async({page})=>{
1540
+ const server=fakeServer();
1541
+ server.records.get('products|QA_PROD').data.stock=0;
1542
+ server.records.get('products|QA_PROD').data.buy_price=25;
1543
+ const fixture=[
1544
+ ['warehouses','QA_WH',{companyId:'QA_CO',code:'MAIN',name:'انبار آزمایشی',active:true}],
1545
+ ['purchases','QA_PUR_POSTED',{companyId:'QA_CO',warehouseId:'QA_WH',date:'1405/07/21',
1546
+ number:'P-POSTED',documentStatus:'posted',accountingStatus:'posted',
1547
+ journalVoucherId:'QA_JV_POSTED',items:[{prodId:'QA_PROD',qty:2,price:50}],grandTotal:100}],
1548
+ ['purchases','QA_PUR_DRAFT',{companyId:'QA_CO',warehouseId:'QA_WH',date:'1405/07/22',
1549
+ number:'P-DRAFT',documentStatus:'draft',accountingStatus:'draft',
1550
+ journalVoucherId:'QA_JV_DRAFT',items:[{prodId:'QA_PROD',qty:3,price:100}],grandTotal:300}],
1551
+ ['journalVouchers','QA_JV_POSTED',{companyId:'QA_CO',fiscalYearId:'FY_QA',sourceType:'purchase',
1552
+ sourceId:'QA_PUR_POSTED',status:'posted',date:'1405/07/21',voucherType:'purchase',number:'1',
1553
+ postedAt:'2026-10-13T08:00:00.000Z'}],
1554
+ ['journalVouchers','QA_JV_DRAFT',{companyId:'QA_CO',fiscalYearId:'FY_QA',sourceType:'purchase',
1555
+ sourceId:'QA_PUR_DRAFT',status:'draft',date:'1405/07/22',voucherType:'purchase'}],
1556
+ ['journalLines','QA_POSTED_DR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_POSTED',
1557
+ accountId:'A_BUY',debit:100,credit:0}],
1558
+ ['journalLines','QA_POSTED_CR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_POSTED',
1559
+ accountId:'A_AP',debit:0,credit:100}],
1560
+ ['journalLines','QA_DRAFT_DR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_DRAFT',
1561
+ accountId:'A_BUY',debit:300,credit:0}],
1562
+ ['journalLines','QA_DRAFT_CR',{companyId:'QA_CO',fiscalYearId:'FY_QA',voucherId:'QA_JV_DRAFT',
1563
+ accountId:'A_AP',debit:0,credit:300}]
1564
+ ];
1565
+ for(const [collection,id,data] of fixture)
1566
+ server.records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
1567
+ // Validate the fixture financial graph before classifying the read-model RED.
1568
+ for(const [purchaseId,voucherId,amount,status] of [
1569
+ ['QA_PUR_POSTED','QA_JV_POSTED',100,'posted'],
1570
+ ['QA_PUR_DRAFT','QA_JV_DRAFT',300,'draft']
1571
+ ]){
1572
+ const p=server.records.get('purchases|'+purchaseId)?.data;
1573
+ const v=server.records.get('journalVouchers|'+voucherId)?.data;
1574
+ const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&r.data.voucherId===voucherId);
1575
+ if(!p||!v||p.companyId!=='QA_CO'||p.warehouseId!=='QA_WH'||
1576
+ p.journalVoucherId!==voucherId||p.documentStatus!==status||
1577
+ v.sourceType!=='purchase'||v.sourceId!==purchaseId||v.status!==status||
1578
+ lines.length!==2||lines.reduce((s,r)=>s+Number(r.data.debit||0),0)!==amount||
1579
+ lines.reduce((s,r)=>s+Number(r.data.credit||0),0)!==amount)
1580
+ throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_INVALID_GRAPH '+purchaseId);
1581
+ }
1582
+ if([...server.records.values()].some(r=>r.collection==='stockMovements'))
1583
+ throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_UNEXPECTED_RECEIPT');
1584
+ await installHarness(page,server);
1585
+ await authenticatedMockBrowser(page);
1586
+ const observed=await page.evaluate(()=>{
1587
+ if(typeof p5Stock!=='function'||typeof p5AverageCost!=='function'||
1588
+ typeof productMovement!=='function'||typeof productKardexRows!=='function'||
1589
+ typeof purchaseDocumentStatus!=='function')
1590
+ throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_MODULE_MISSING');
1591
+ switchView('view-inventory');
1592
+ p5RenderInventory();
1593
+ const purchases=getMyPurchases();
1594
+ const statuses=purchases.map(p=>[p.id,purchaseDocumentStatus(p)]).sort((a,b)=>a[0].localeCompare(b[0]));
1595
+ const rows=[...document.querySelectorAll('#p5-inventory-root table tbody tr')];
1596
+ const row=rows.find(r=>r.cells[0]?.textContent.includes('بلوک سیمانی')&&
1597
+ r.cells[1]?.textContent.includes('انبار آزمایشی'));
1598
+ if(!row)throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_INVENTORY_ROW_MISSING');
1599
+ const parseCell=cell=>{
1600
+ const value=toEnDigits(cell.textContent).replace(/[٬,\s]/g,'');
1601
+ const number=Number(value);if(!Number.isFinite(number))
1602
+ throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_BAD_UI_NUMBER '+value);
1603
+ return number;
1604
+ };
1605
+ const kardex=productKardexRows('QA_PROD').filter(x=>x.kind==='خرید');
1606
+ const balance=productMovement('QA_PROD');
1607
+ return {
1608
+ purchaseStatuses:statuses,
1609
+ postedPurchasedQty:balance.purchased,
1610
+ kardexPurchaseCount:kardex.length,
1611
+ kardexPurchaseQty:kardex.reduce((sum,x)=>sum+x.qty,0),
1612
+ inventoryEventSourceIds:p5OperationalEvents('QA_PROD','QA_WH')
1613
+ .filter(x=>x.source==='purchase').map(x=>x.sourceId).sort(),
1614
+ phase5EffectiveQty:p5Stock('QA_PROD','QA_WH'),
1615
+ phase5AverageCost:p5AverageCost('QA_PROD'),
1616
+ renderedQty:parseCell(row.cells[2]),
1617
+ renderedAverageCost:parseCell(row.cells[3])
1618
+ };
1619
+ });
1620
+ const shared={
1621
+ purchaseStatuses:[['QA_PUR_DRAFT','draft'],['QA_PUR_POSTED','posted']],
1622
+ postedPurchasedQty:2,kardexPurchaseCount:1,kardexPurchaseQty:2
1623
+ };
1624
+ const broken={...shared,
1625
+ inventoryEventSourceIds:['QA_PUR_DRAFT','QA_PUR_POSTED'],
1626
+ phase5EffectiveQty:5,phase5AverageCost:80,renderedQty:5,renderedAverageCost:80
1627
+ };
1628
+ const required={...shared,
1629
+ inventoryEventSourceIds:['QA_PUR_POSTED'],
1630
+ phase5EffectiveQty:2,phase5AverageCost:50,renderedQty:2,renderedAverageCost:50
1631
+ };
1632
+ if(isDeepStrictEqual(observed,required))return;
1633
+ if(!isDeepStrictEqual(observed,broken))
1634
+ throw Error('FINORA_ISSUE238_DRAFT_PURCHASE_THIRD_STATE '+JSON.stringify({observed,broken,required}));
1635
+ console.log('FINORA_ISSUE238_DRAFT_PURCHASE_STOCK_EXPECTED_RED: linked DRAFT purchase inflates Phase5 stock and cost, while posted-only Kardex excludes it');
1636
+ test.fail(true,'#238: DRAFT purchase without committed physical receipt must not alter Phase5 stock/valuation');
1637
+ expect(observed).toEqual(required);
1638
+});