@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 5bdfe03
Fork 0

سامانه صدور فاکتور و حسابداری

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 4, 10:30 UTC

test(finora): reproduce inventory-count Save premature journal and stock posting

davoodmehraban89 committed Nov 23, 2026 at 07:33 UTC 5bdfe03dc0141e10ec1bdcb613f547a60fb7903f
3 files changed +105
PROJECT_STATE.md
+6
@@ -756,3 +756,9 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
756 - **Bounded QA-only plan:** new isolated branch `qa/finora-issue238-inventory-count-browser-red-20261123` from PR239 exact SHA, Draft child PR stacked on PR239; extend **existing** `scripts/accounting-document-workflow.spec.js` and reuse its loaded authenticated Playwright + synthetic Supabase harness. Seed only synthetic QA product buy cost and inventory-adjustment posting accounts. Drive actual `p5SaveCount()` DOM button with positive count variance, and inspect **persisted** count, movement, linked journal, balanced lines, stock quantity and effective posted ledger.
757 - **Desired acceptance:** Save count must persist source-linked balanced DRAFT journal with corresponding non-effective draft stock adjustment; do not recognize posted voucher, stock change or postedAt before a distinct server-authorized accounting Finalize. Preserve a single movement/voucher graph and company scope; allow draft provisional number, disallow posted status/postedAt. **Known current defect:** count, movement and journal immediately POSTED, stock quantity and posted ledger changed. Classify as expected PRODUCT RED only after an exact broken fingerprint; any orphan, missing, duplicate, unbalanced or inconsistent third state is real CI FAILURE. A truly corrected linked-draft result is a normal PASS.
758 - **Ownership:** Codex-main alone owns financial JS, SQL/RPC/schema/migrations, RLS/Auth/grants and release. This QA branch may only change `scripts/accounting-document-workflow.spec.js`, append-only `PROJECT_STATE.md` and `docs/EXECUTION_STATUS.md`. No `main`, merge, production, hosted DB or historical financial records. Run exact-head Quality/WP1/WP2/Security if triggered, record evidence without inflating phase completion.
759 +
760 +
761 +### 2026-11-23 — FIN-QA-ISSUE238-INVENTORY-COUNT-SAVE / implementation checkpoint before CI
762 +- Inherited the actual Playwright authenticated synthetic Supabase harness rather than creating a parallel ledger. Added one genuine loaded-DOM `p5SaveCount` browser test: seeded **two opening units @ 25** in one tenant/company, physical count 5 (variance +3, valuation +75), with exact inventory and adjustment accounts. The opening movement is a fixture prerequisite because weighted-average cost is otherwise zero.
763 +- Asserts persisted **inventoryCount -> stockMovement -> journalVoucher -> two balanced journalLines** graph; exact current posted stock/journal fingerprint (stock 2→5, posted valuation +75) vs required pending linked balanced DRAFT (stock stays 2, posted ledger unchanged). Verifies source company/qty/valuation and 1:1 graph; unknown/orphan/duplicate/unbalanced/partial states throw `FINORA_ISSUE238_INVENTORY_COUNT_THIRD_STATE` **before** any expected-RED masking. `FINORA_ISSUE238_INVENTORY_COUNT_EXPECTED_RED` emitted only for the exact current defect; a corrected source-linked draft would be normal PASS.
764 +- Source limitation: this browser test uses synthetic sync and checks client lifecycle, NOT real-JWT authorization, server transaction boundaries, or accounting finalization. Codex-main owns a single authoritative implementation. **Final exact-SHA CI not yet verified**. No financial app JS, SQL/migration, schema/RLS/Auth/grants, protected main, hosted DB, production, release or merge.
docs/EXECUTION_STATUS.md
+6
@@ -236,3 +236,9 @@
236 - همهٔ گیت‌های QA در [PR239](https://github.com/davoodmehraban89/Factor-easy/pull/239) روی SHA `47f482f389f955824f653942cd14754c376eae50` کامل و موفق شدند؛ بااین‌حال Issue216/229/238 و نقص‌های مالی باز هستند.
237 - در کد فعال `js/phase5-enterprise.js::p5SaveCount` ثبت شمارش دارای اختلاف، گردش انبار و سند ارزش‌گذاری را بی‌درنگ posted می‌کند. آزمون مستقل با فرم مرورگر و سرور همگام‌سازی ساختگی بررسی می‌کند که ثبت شمارش **نباید** پیش از Finalize مستقل، موجودی قطعی یا دفترکل را تغییر دهد و سند حسابداری متصل باید DRAFT و متوازن بماند.
238 - آزمون فقط در مجموعهٔ مرورگر موجود اضافه می‌شود؛ هیچ کد اجرایی مالی، SQL، RPC، مجوز، دادهٔ واقعی یا main تغییر نمی‌کند. قبل از تأیید CI روی SHA نهایی ادعای موفقیت ممنوع است.
239 +
240 +
241 +### ۱۴۰۵/۰۹/۰۲ — پیاده‌سازی آزمون واقعی انبارگردانی در مرورگر
242 +- یک مورد جدید در Playwright فعلی ساخته شد: موجودی آغازین ۲ واحد با بهای ۲۵؛ شمارش ۵ واحد؛ اختلاف مثبت ۳ واحد و ارزش حسابداری ۷۵. دکمهٔ واقعی `p5SaveCount` اجرا می‌شود و داده‌های ذخیره‌شده در سرور ساختگی بررسی می‌شوند.
243 +- قرارداد مورد انتظار: شمارش و گردش موجودی تا تأیید مستقل DRAFT بمانند، یک سند حسابداری متوازن DRAFT متصل باشد، قبل از تأیید هیچ اثر قطعی روی موجودی ۲ واحدی یا دفترکل ایجاد نشود. رفتار اشتباه فعلی با `FINORA_ISSUE238_INVENTORY_COUNT_EXPECTED_RED` ثبت می‌شود؛ هر حالت ناشناخته یا بدون اتصال شکست واقعی است.
244 +- در این مرحله هیچ کد اجرایی مالی یا مجوز و دادهٔ واقعی تغییر نکرده؛ آزمون برای پذیرش نیازمند CI روی SHA نهایی است.
scripts/accounting-document-workflow.spec.js
+93
@@ -1437,3 +1437,96 @@ for(const kind of ['expense','income'])test('P0 #238 expected RED: '+kind+' Save
1437 const observed=issue238JournalSnapshot(server,'expenses',kind);
1438 issue238AssertKnownRedOrDraft(observed,issue238KnownPosted,issue238RequiredDraft,'expense-'+kind);
1439 });
1440 +
1441 +// #238 / ADR216: count-Save must not finalize valuation or operational stock.
1442 +// The browser uses the real loaded phase5 module and a synthetic sync server.
1443 +// Real database/JWT approval, inventory locking and duplicate-count safety need
1444 +// separate Codex-main E2E. Keep this expected RED strict and source-grounded.
1445 +test('P0 #238 expected RED: inventory count Save must persist pending stock and a balanced DRAFT valuation journal',async({page})=>{
1446 + const server=fakeServer();
1447 + // Genuine positive weighted-average valuation requires existing priced stock:
1448 + // without an opening movement, weightedAverage(0, buy_price, []) returns 0.
1449 + server.records.get('products|QA_PROD').data.buy_price=25;
1450 + for(const [collection,id,data] of [
1451 + ['warehouses','QA_WH',{companyId:'QA_CO',code:'MAIN',name:'انبار آزمون',active:true}],
1452 + ['stockMovements','QA_OPEN',{companyId:'QA_CO',kind:'opening',productId:'QA_PROD',
1453 + warehouseId:'QA_WH',qty:2,unitCost:25,date:'1405/07/19',status:'posted'}],
1454 + ['accounts','QA_INVENTORY',{companyId:'QA_CO',code:'1103',title:'موجودی کالا',active:true,postingAllowed:true}],
1455 + ['accounts','QA_INVENTORY_GAIN',{companyId:'QA_CO',code:'4201',title:'تعدیل افزایشی موجودی',active:true,postingAllowed:true}]
1456 + ])server.records.set(collection+'|'+id,{collection,id,data:copy(data),version:1});
1457 + await installHarness(page,server);
1458 + await authenticatedMockBrowser(page);
1459 + const before=await page.evaluate(()=>{
1460 + if(typeof p5SaveCount!=='function'||typeof p5RenderInventory!=='function')
1461 + throw Error('FINORA_ISSUE238_INVENTORY_RUNTIME_MISSING');
1462 + switchView('view-inventory');
1463 + p5RenderInventory();
1464 + return {stock:p5Stock('QA_PROD','QA_WH'),averageCost:p5AverageCost('QA_PROD')};
1465 + });
1466 + expect(before).toEqual({stock:2,averageCost:25});
1467 + await expect(page.locator('#p5-count-product option[value="QA_PROD"]')).toHaveCount(1);
1468 + await expect(page.locator('#p5-count-wh option[value="QA_WH"]')).toHaveCount(1);
1469 + await page.locator('#p5-count-product').selectOption('QA_PROD');
1470 + await page.locator('#p5-count-wh').selectOption('QA_WH');
1471 + await page.locator('#p5-count-qty').fill('5');
1472 + await page.locator('#p5-inventory-root button[onclick="p5SaveCount()"]').click();
1473 + await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='inventoryCounts').length,
1474 + {timeout:15000}).toBe(1);
1475 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
1476 + const counts=[...server.records.values()].filter(r=>r.collection==='inventoryCounts');
1477 + const count=counts[0];
1478 + const adjustments=[...server.records.values()].filter(r=>r.collection==='stockMovements'&&
1479 + r.data.sourceType==='inventory_count'&&r.data.sourceId===count?.id);
1480 + const move=adjustments[0];
1481 + const vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers');
1482 + const linked=vouchers.find(r=>r.id===move?.data.journalVoucherId);
1483 + const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&
1484 + r.data.voucherId===linked?.id);
1485 + const debit=lines.reduce((n,r)=>n+Number(r.data.debit||0),0);
1486 + const credit=lines.reduce((n,r)=>n+Number(r.data.credit||0),0);
1487 + if(count?.data.companyId!=='QA_CO'||count.data.productId!=='QA_PROD'||
1488 + count.data.warehouseId!=='QA_WH'||count.data.systemQty!==2||
1489 + count.data.physicalQty!==5||count.data.difference!==3||
1490 + move?.data.qty!==3||move.data.unitCost!==25||move.data.kind!=='adjustment_in')
1491 + throw Error('FINORA_ISSUE238_INVENTORY_COUNT_FIXTURE_INVALID '+JSON.stringify({count:count?.data,move:move?.data}));
1492 + const observed={
1493 + countStatus:count.data.status||'missing',
1494 + adjustmentStatus:move.data.status||'missing',
1495 + valuationStatus:linked?.data.status||'missing',
1496 + movementAccountingStatus:move.data.accountingStatus||'',
1497 + countLinkedToJournal:!!linked&&count.data.journalVoucherId===linked.id,
1498 + movementLinkedToJournal:!!linked&&move.data.journalVoucherId===linked.id,
1499 + journalSourceMatches:!!linked&&linked.data.sourceType==='inventory_adjustment'&&
1500 + linked.data.sourceId===move.id&&linked.data.companyId==='QA_CO',
1501 + balancedValuation:lines.length===2&&debit===75&&credit===75,
1502 + countCount:counts.length,adjustmentCount:adjustments.length,voucherCount:vouchers.length,
1503 + postedJournalCount:vouchers.filter(v=>v.data.status==='posted').length,
1504 + countPostedAt:!!count.data.postedAt,adjustmentPostedAt:!!move.data.postedAt,
1505 + valuationPostedAt:!!linked?.data.postedAt,
1506 + effectiveStock:await page.evaluate(()=>p5Stock('QA_PROD','QA_WH')),
1507 + effectiveValuationLines:await page.evaluate(()=>
1508 + jeLedgerRows().filter(x=>x.voucher?.sourceType==='inventory_adjustment').length)
1509 + };
1510 + const broken={
1511 + countStatus:'posted',adjustmentStatus:'posted',valuationStatus:'posted',
1512 + movementAccountingStatus:'posted',
1513 + countLinkedToJournal:true,movementLinkedToJournal:true,journalSourceMatches:true,balancedValuation:true,
1514 + countCount:1,adjustmentCount:1,voucherCount:1,postedJournalCount:1,
1515 + countPostedAt:true,adjustmentPostedAt:true,valuationPostedAt:true,
1516 + effectiveStock:5,effectiveValuationLines:2
1517 + };
1518 + const required={
1519 + countStatus:'draft',adjustmentStatus:'draft',valuationStatus:'draft',
1520 + movementAccountingStatus:'draft',
1521 + countLinkedToJournal:true,movementLinkedToJournal:true,journalSourceMatches:true,balancedValuation:true,
1522 + countCount:1,adjustmentCount:1,voucherCount:1,postedJournalCount:0,
1523 + countPostedAt:false,adjustmentPostedAt:false,valuationPostedAt:false,
1524 + effectiveStock:2,effectiveValuationLines:0
1525 + };
1526 + if(isDeepStrictEqual(observed,required))return;
1527 + if(!isDeepStrictEqual(observed,broken))
1528 + throw Error('FINORA_ISSUE238_INVENTORY_COUNT_THIRD_STATE '+JSON.stringify({observed,broken,required}));
1529 + console.log('FINORA_ISSUE238_INVENTORY_COUNT_EXPECTED_RED: count Save immediately posts stock movement and balanced valuation journal');
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 +});