سامانه صدور فاکتور و حسابداری
test(finora): execute Issue238 receipt payment expense income draft-first red contracts
davoodmehraban89 committed
Nov 22, 2026 at 22:26 UTC
16177737bc8d4cf199fee97426a9c5e222749bc5
3 files changed
+111
PROJECT_STATE.md
+6
@@ -725,3 +725,9 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
725
- Owner requested another concrete continuation. Live GitHub protected `main` `dab1a45fcfc4f12e675cfe055e477138cd3e99fa`; no new owner financial-core implementation seen. [Issue238](https://github.com/davoodmehraban89/Factor-easy/issues/238) documents client Save→local posting for receipt/payment and expense/income plus other financial producers, but has not had independently executed browser RED proof. Existing [Draft PR237](https://github.com/davoodmehraban89/Factor-easy/pull/237) HEAD `b2a9a6238eae5618840a17137bef8f91fe80a910` passed all three triggered Quality/WP1/Security gates, WP2 skipped by paths.
726
- **Narrow QA-only scope:** create separate Draft child branch `qa/finora-issue238-save-browser-red-20261122` from this exact PR237 head, target PR237, and extend existing `scripts/accounting-document-workflow.spec.js` using its authenticated synthetic server browser harness. Execute **four** real DOM Save scenarios: receipt, payment, expense, income (including runtime `operations.js` override of `expenses.js`). Assert source→balanced linked journal, count/status and no immediate post under ADR216; label current result as expected PRODUCT RED **without masking unexpected states**: call `test.fail(true)` only after a strict exact known-broken fingerprint. A future correct draft state must be ordinary PASS, not an xfail; unexpected partial/unbalanced/orphan states must FAIL. Preserve existing tests and QA status docs.
727
- No SQL/DB schema, RLS/Auth/grants, financial runtime JS, workflow, posted history, protected main, merger, hosted database or release changes authorized. This browser mock exercises the loaded UI/client sync but **cannot** prove real SQL JWT permission. Run Quality, WP1, Security exact-head and WP2 only if path-filtered run triggered. Independent Codex-main server change remains prerequisite; estimates unchanged and #216/#229/#238 open.
728
+
729
+
730
+### 2026-11-22 — FIN-QA-ISSUE238-LIVE-SAVE / browser acceptance implementation before CI
731
+- **QA-only code:** extended the existing `scripts/accounting-document-workflow.spec.js` with 4 loaded-browser, authenticated synthetic sync fixture scenarios: unallocated receipt, payment, expense, income Save. Existing `fakeServer/authenticatedMockBrowser` test harness reused; expense/income scenarios add only synthetic expense/other-income ledger role accounts to isolated fixture. They run actual `commitSavePayment` / active runtime `window.commitSaveExpense`, inspect synchronized source, linked voucher/lines and strict status/amount/one-voucher source graph.
732
+- The new `issue238AssertKnownRedOrDraft` invokes `test.fail(true)` **only if exact known current POSTED defect fingerprint is observed**, then asserts desired linked DRAFT. A corrected linked DRAFT returns normal PASS; unknown or orphan/unbalanced/third-state result throws as normal CI failure BEFORE setting xfail. Print specific `FINORA_ISSUE238_SAVE_EXPECTED_RED` markers only on observed known problem. These tests prove loaded client UI behavior against synthetic Supabase, **not** a real JWT/server authorization decision.
733
+- **Not yet verified** on new exact SHA: Quality browser and full repo jobs, WP1/WP2/Security must be checked after code commit. No finance app `js/`, SQL/migrations/schema/RLS/grants, protected main, Production, merging or release changed. Issue216/229/238 remain open; phase estimates unchanged.
docs/EXECUTION_STATUS.md
+5
@@ -1,5 +1,10 @@
1
# وضعیت اجرای فینورا
2
3
+### ۲۰۲۶/۱۱/۲۲ — Issue238: چهار سناریوی مرورگر برای نقص Save دریافت/پرداخت و هزینه/درآمد
4
+- چهار سناریو در مجموعهٔ موجود `scripts/accounting-document-workflow.spec.js` اضافه شد: دریافت، پرداخت، هزینه، درآمد. هر چهار مورد رفتار واقعی کلاینت را با سرور مصنوعی آزمون میکنند: باید در Save منبع به سند متوازن DRAFT متصل بماند و سند قطعی ایجاد نشود. وضع فعلی ثبت قطعیِ خودکار با `expected RED` مشخص میشود؛ فقط اثر دقیق و شناختهشده xfail است و حالت نامعتبر دیگر باید CI را بشکند. اصلاح آینده بهطور عادی PASS خواهد شد. آزمون JWT واقعی سرور محسوب نمیشود.
5
+- بدون تغییر کد اجرایی حسابداری یا SQL. نتیجهٔ CI تازه تا اتمام اجرای SHA جدید نامعلوم است؛ Issue216/229/238 باز میمانند.
6
+
7
+
8
### ۲۲ نوامبر ۲۰۲۶ — اصلاح ضعف کنترل امنیتی PR237 در مجوزهای پیشفرض
9
- کنترل قبلی فقط SQL دارای `GRANT EXECUTE` صریح را بررسی میکرد؛ اما PostgreSQL بهصورت پیشفرض برای تابع جدید به `PUBLIC` مجوز اجرای تابع میدهد. اکنون تابع عمومی `SECURITY DEFINER` با الگوی خطرناک حتی بدون GRANT صریح هم بازبینی میشود؛ `REVOKE` صریح از PUBLIC در همان منبع، بدون GRANT مجدد، این هشدار را برای همان تابع حذف میکند.
10
- `GRANT` مستقلِ تابع هویت سند در migration جداگانه نیز هشدار میدهد؛ چهار آزمون جدید سناریوی مجوز پیشفرض، REVOKE/GRANT، GRANT مستقل و diff واقعی مخزن موقت را میپوشانند. **این الگوی متنی اثبات امنیت SQL یا اصلاح محصول نیست**؛ تاریخچهٔ ACL و JWT واقعی باید جداگانه بررسی شود. نتیجهٔ CI روی SHA جدید تا اتمام Workflowها نامعلوم است؛ Issue216/229 باز هستند.
scripts/accounting-document-workflow.spec.js
+100
@@ -1310,3 +1310,103 @@ test('P0 #229 expected RED: posted purchase correction Save must remain linked a
1310
balancedDraftLines:true,correctionAlreadyPosted:false,originalReversalCount:1
1311
});
1312
});
1313
+
1314
+
1315
+// Issue238 / ADR216 — real loaded-browser negative acceptance for non-sale
1316
+// financial producers. The Supabase fixture is synthetic: these tests prove
1317
+// the UI's client Save call chain, NOT real-JWT server authorization.
1318
+// A known broken state is an expected PRODUCT RED; an unknown third state is
1319
+// a genuine test failure; a fixed linked DRAFT is a regular passing test.
1320
+function issue238AssertKnownRedOrDraft(observed,broken,required,label){
1321
+ if(isDeepStrictEqual(observed,required))return;
1322
+ if(!isDeepStrictEqual(observed,broken))
1323
+ throw Error('FINORA_ISSUE238_UNEXPECTED_PRODUCT_STATE '+label+' '+JSON.stringify({observed,broken,required}));
1324
+ console.log('FINORA_ISSUE238_SAVE_EXPECTED_RED '+label+': Save already finalizes a source-linked journal');
1325
+ test.fail(true,'#238 / ADR216: '+label+' Save auto-posts instead of saving a linked accounting draft');
1326
+ expect(observed).toEqual(required);
1327
+}
1328
+function issue238JournalSnapshot(server,collection,kind){
1329
+ const sourceRows=[...server.records.values()].filter(r=>r.collection===collection&&r.data?.kind===kind||
1330
+ r.collection===collection&&r.data?.direction===kind);
1331
+ if(sourceRows.length!==1)throw Error('FINORA_ISSUE238_INVALID_FIXTURE '+collection+'/'+kind+' sourceRows='+sourceRows.length);
1332
+ const source=sourceRows[0],vouchers=[...server.records.values()].filter(r=>r.collection==='journalVouchers');
1333
+ const linked=vouchers.find(v=>v.id===source.data.journalVoucherId);
1334
+ const lines=[...server.records.values()].filter(r=>r.collection==='journalLines'&&r.data.voucherId===source.data.journalVoucherId);
1335
+ const debit=lines.reduce((sum,r)=>sum+Number(r.data.debit||0),0);
1336
+ const credit=lines.reduce((sum,r)=>sum+Number(r.data.credit||0),0);
1337
+ return {
1338
+ sourceStatus:source.data.accountingStatus||'',
1339
+ linkedDraft:!!linked&&linked.data.status==='draft',
1340
+ linkedPosted:!!linked&&linked.data.status==='posted',
1341
+ linkedToSource:!!linked&&linked.data.sourceId===source.id&&
1342
+ linked.data.sourceType===(collection==='payments'?(kind==='inbound'?'receipt':'payment'):kind),
1343
+ balanced:lines.length>=2&&debit===credit&&debit===Number(source.data.amount),
1344
+ postedCount:vouchers.filter(v=>v.data.status==='posted').length,
1345
+ voucherCount:vouchers.length
1346
+ };
1347
+}
1348
+const issue238KnownPosted={
1349
+ sourceStatus:'posted',linkedDraft:false,linkedPosted:true,linkedToSource:true,
1350
+ balanced:true,postedCount:1,voucherCount:1
1351
+};
1352
+const issue238RequiredDraft={
1353
+ sourceStatus:'draft',linkedDraft:true,linkedPosted:false,linkedToSource:true,
1354
+ balanced:true,postedCount:0,voucherCount:1
1355
+};
1356
+
1357
+for(const direction of ['inbound','outbound'])test('P0 #238 expected RED: '+direction+' payment Save must leave balanced linked journal DRAFT',async({page})=>{
1358
+ const server=fakeServer();
1359
+ await installHarness(page,server);
1360
+ await authenticatedMockBrowser(page);
1361
+ await page.evaluate(dir=>{
1362
+ switchView('view-payments');renderPayments();
1363
+ for(const [id,value] of [['pay-direction',dir],['pay-contact','QA_CONTACT'],
1364
+ ['pay-method','bank'],['pay-amount','1200'],['pay-reference','ISSUE238-'+dir]]){
1365
+ const el=document.getElementById(id);
1366
+ if(!el)throw Error('FINORA_ISSUE238_PAYMENT_FORM_MISSING '+id);
1367
+ el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
1368
+ }
1369
+ commitSavePayment();
1370
+ },direction);
1371
+ await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='payments').length,
1372
+ {timeout:14000}).toBe(1);
1373
+ await page.waitForFunction(()=>!syncPending&&!syncRunning);
1374
+ const rows=[...server.records.values()].filter(r=>r.collection==='payments');
1375
+ if(rows[0]?.data.amount!==1200||rows[0]?.data.companyId!=='QA_CO'||rows[0]?.data.direction!==direction)
1376
+ throw Error('FINORA_ISSUE238_PAYMENT_FIXTURE_INVALID '+JSON.stringify(rows[0]?.data));
1377
+ const observed=issue238JournalSnapshot(server,'payments',direction);
1378
+ issue238AssertKnownRedOrDraft(observed,issue238KnownPosted,issue238RequiredDraft,'payment-'+direction);
1379
+});
1380
+
1381
+for(const kind of ['expense','income'])test('P0 #238 expected RED: '+kind+' Save must leave balanced linked journal DRAFT',async({page})=>{
1382
+ const server=fakeServer();
1383
+ // The original sale/purchase fixture does not seed expense/income posting roles.
1384
+ for(const [id,code,title,role] of [
1385
+ ['A_EXP','6103','هزینه عمومی','expense_default'],
1386
+ ['A_OTHER','4201','سایر درآمد','other_income_default']
1387
+ ])server.records.set('accounts|'+id,{
1388
+ collection:'accounts',id,data:{code,title,systemRole:role,active:true,postingAllowed:true},version:1
1389
+ });
1390
+ await installHarness(page,server);
1391
+ await authenticatedMockBrowser(page);
1392
+ await page.evaluate(k=>{
1393
+ switchView('view-expenses');
1394
+ if(typeof window.commitSaveExpense!=='function')
1395
+ throw Error('FINORA_ISSUE238_EXPENSE_OVERRIDE_MISSING');
1396
+ for(const [id,value] of [['trx-kind-input',k],['trx-amount-input','1200'],
1397
+ ['trx-desc-input','ISSUE238 '+k]]){
1398
+ const el=document.getElementById(id);
1399
+ if(!el)throw Error('FINORA_ISSUE238_EXPENSE_FORM_MISSING '+id);
1400
+ el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
1401
+ }
1402
+ window.commitSaveExpense();
1403
+ },kind);
1404
+ await expect.poll(()=>[...server.records.values()].filter(r=>r.collection==='expenses').length,
1405
+ {timeout:14000}).toBe(1);
1406
+ await page.waitForFunction(()=>!syncPending&&!syncRunning);
1407
+ const rows=[...server.records.values()].filter(r=>r.collection==='expenses');
1408
+ if(rows[0]?.data.amount!==1200||rows[0]?.data.companyId!=='QA_CO'||rows[0]?.data.kind!==kind)
1409
+ throw Error('FINORA_ISSUE238_EXPENSE_FIXTURE_INVALID '+JSON.stringify(rows[0]?.data));
1410
+ const observed=issue238JournalSnapshot(server,'expenses',kind);
1411
+ issue238AssertKnownRedOrDraft(observed,issue238KnownPosted,issue238RequiredDraft,'expense-'+kind);
1412
+});