@davoodmehraban89 / Factor-easy / commits / 3d1078c
Fork 0

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

test(wp2): prove positive authorized journal create/replay/post and rollback over JWT

davoodmehraban89 committed Nov 22, 2026 at 06:48 UTC 3d1078c04f13cf47953aba7ce1368f0de484b55d
4 files changed +148
.github/workflows/free-supabase-local-e2e.yml
+9
@@ -13,6 +13,7 @@ on:
13 - "scripts/journal-rpc-adapter.test.mjs"
14 - "scripts/wp2-auth-tenant-e2e.mjs"
15 - "scripts/wp3-financial-tenant-e2e.mjs"
16 + - "scripts/wp2-authorized-journal-write-e2e.mjs"
17 - ".github/workflows/free-supabase-local-e2e.yml"
18 - "supabase/config.toml"
19 workflow_dispatch:
@@ -67,6 +68,14 @@ jobs:
68 set +a
69 node scripts/wp3-financial-tenant-e2e.mjs
70
71 + - name: Prove authorized financial draft and post through real Auth JWT
72 + run: |
73 + set -euo pipefail
74 + set -a
75 + . /tmp/supabase-local.env
76 + set +a
77 + node scripts/wp2-authorized-journal-write-e2e.mjs
78 +
79 - name: Verify WP1/WP2 journal RPC surface exists
80 run: |
81 set -a
docs/ACCOUNTING_CORE_ROADMAP_V1.md
+2
@@ -435,6 +435,8 @@ This register maps execution stages A/B to the **existing** accounting Phase 6 (
435
436 | FIN-CI-218-WP2 | تکمیل گیت WP2 برای تغییرات source مالی PR221 با فیلتر کمینه | QA مستقل؛ پذیرش نهایی با Codex اصلی | PR218/PR212، PR221 head 44b697b4، مسیر WP2 | در بررسی (تا پایان CI exact-head) | WP2 واقعاً اجرا و موفق شود؛ کیفیت/WP1/امنیت روی همان SHA تأیید؛ بازبینی اصلی جدا | QA successor PR (stacked on PR221) | PR221 docs-head: Quality 44978932775 SUCCESS, Security 44978932790 SUCCESS؛ WP1 44978932846 هنگام ثبت هنوز در حال اجرا؛ WP2 اجرا نشده | بررسی exact-head WP2 و گیت‌ها؛ سپس تحویل به Codex اصلی، بدون merge/deploy |
437
438 +| FIN-QA-POSITIVE-RPC | احراز آزمون مثبت ثبت و قطعی‌کردن سند دستی با JWT واقعی | QA مستقل؛ سرور/مالی نزد Codex اصلی | PR222 و WP2 disposable؛ RPC موجود | در پیاده‌سازی / منتظر CI | واقعی بودن JWT، create→replay→post، تراز و نسخه/شماره، rollback خطا، همهٔ گیت‌ها | QA follow-on stacked on PR222 | پیش از این تغییر فقط آزمون منفی `scripts/wp3-financial-tenant-e2e.mjs` وجود داشت؛ اجرا هنوز ادعا نشده | اجرای WP2 و Quality/WP1/Security روی SHA جدید؛ خروجی واقعی در همین ردیف ثبت شود |
439 +
440 **Release boundary:** successful Pages run 43606173842 applies only to `main dab1a45`; no candidate above is `منتشرشده`. Competing PR214/215/217/219 are alternative implementations, not sequential milestones. This worker changes documentation only; Codex main owns integration and release decisions.
441
442
docs/EXECUTION_STATUS.md
+6
@@ -1,5 +1,11 @@
1 # وضعیت اجرای فینورا
2
3 +### ۲۰۲۶-۱۱-۲۲ — QA آزمایشی عملیات مثبت مالی؛ کاندیدای مستقل بدون تغییر هسته
4 +- شکاف شواهد: WP2 قبلی فقط رد عملیات غیرمجاز سازمان دیگر و قرارداد mock adapter را تأیید می‌کرد. تست جدید `scripts/wp2-authorized-journal-write-e2e.mjs` باید روی Supabase disposable با Auth/JWT واقعی و PostgREST، ساخت سند دستی متوازن، retry با شناسه ثابت، قطعی‌سازی مستقل، بازخوانی شماره قطعی سرور و rollback درخواست نامتوازن را بررسی کند. Test fixtures با service-role و psql ساخته می‌شوند، اما **RPCهای تحت آزمون فقط JWT خود کاربر** دارند.
5 +- مسئول: QA مستقل. فایل‌های مجاز: اسکریپت جدید، `.github/workflows/free-supabase-local-e2e.yml` و اسناد مرجع موجود. `sync.js`، `organization-rbac.js`، `journal-ui.js`، SQL migration و داده Production تغییر نکنند. معیار پذیرش: WP2 واقعاً PASS، Quality/WP1/Security روی SHA exact و بازبینی Codex اصلی؛ تا پیش از آن «در بررسی/در پیاده‌سازی».
6 +- مرز: حتی آزمون مثبت دستی، اتمیک‌بودن منبع فاکتور و سند آن، شماره عطف دائمی، چک، یا Issue216 را اثبات نمی‌کند. در صورت شکست مجاز، لاگ واقعی و نقص سروری ثبت شود؛ مجوزها برای سبزکردن تست تضعیف نشوند.
7 +
8 +
9 ## ۲۰۲۶-۱۱-۲۲ — FIN-CI-218-WP2؛ تطبیق مستقل مرحله A و گیت مرحله B
10
11 **تصمیم مالک و مرز اجرا:** مسیر یکپارچه‌سازی همچنان PR218 است (وابسته به PR212). PR221 با اصلاح محدود دو فایل JS و سه فایل آزمون، روی مبنای PR218 حفظ می‌شود. PR220 مستندات ممیزی مستقل دارد و نباید کورکورانه ادغام شود. PR214/215/217/219 گزینه‌های متداخل چرخه سندند؛ هیچ‌کدام در این QA branch ادغام نشده‌اند. Codex اصلی مالک نهایی یکپارچه‌سازی، کدهای pending-edit، SQL مالی و تصمیم انتشار است. این شاخه صرفاً فیلتر مسیر WP2 و ثبت وضعیت را اصلاح می‌کند.
scripts/wp2-authorized-journal-write-e2e.mjs new
+131
@@ -0,0 +1,131 @@
1 +import assert from 'node:assert/strict';
2 +import {spawnSync} from 'node:child_process';
3 +
4 +// Positive financial RPC proof: real Auth JWT + PostgREST on a disposable Supabase.
5 +// The service key and psql are used ONLY to provision synthetic fixture records.
6 +const api=process.env.API_URL;
7 +const anon=process.env.ANON_KEY;
8 +const service=process.env.SERVICE_ROLE_KEY;
9 +const db=process.env.DB_URL;
10 +for(const [name,value] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db})){
11 + if(!value)throw new Error('Missing disposable Supabase value: '+name);
12 +}
13 +const suffix=Date.now()+'-'+crypto.randomUUID().slice(0,8);
14 +const q=value=>"'"+String(value).replaceAll("'","''")+"'";
15 +function sql(statement){
16 + const result=spawnSync('psql',[db,'-v','ON_ERROR_STOP=1','-c',statement],{encoding:'utf8'});
17 + assert.equal(result.status,0,'fixture SQL failed: '+(result.stderr||result.stdout));
18 +}
19 +async function rest(path,accessToken,init={}){
20 + return fetch(api+'/rest/v1/'+path,{
21 + ...init,
22 + headers:{apikey:anon,Authorization:'Bearer '+accessToken,...(init.headers||{})}
23 + });
24 +}
25 +async function rpc(name,args,jwt){
26 + const response=await rest('rpc/'+name,jwt,{
27 + method:'POST',headers:{'Content-Type':'application/json'},
28 + body:JSON.stringify(args)
29 + });
30 + const text=await response.text();
31 + let body;
32 + try{body=JSON.parse(text)}catch{body=text}
33 + return {status:response.status,body};
34 +}
35 +function success(result,label){
36 + assert.equal(result.status,200,label+' must succeed for an authorized JWT; result: '+JSON.stringify(result.body));
37 + assert.ok(result.body&&typeof result.body==='object',label+' returned no JSON object');
38 + return result.body;
39 +}
40 +async function ownRecords(org,jwt,collection){
41 + const response=await rest('records?select=id,version,data&organization_id=eq.'+encodeURIComponent(org)+'&collection=eq.'+encodeURIComponent(collection),jwt);
42 + assert.equal(response.status,200,'authorized '+collection+' read failed: '+await response.text().catch(()=>''));
43 + return response.json();
44 +}
45 +const email='wp2-positive-'+suffix+'@example.test';
46 +const password='WP2-'+crypto.randomUUID()+'-Aa9!';
47 +const signup=await fetch(api+'/auth/v1/admin/users',{
48 + method:'POST',
49 + headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'},
50 + body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'wp2positive'+Date.now()}})
51 +});
52 +const userBody=await signup.json();
53 +assert.equal(signup.status,200,'fixture user provisioning failed');
54 +const userId=userBody.id;
55 +const org=crypto.randomUUID();
56 +const company='POSITIVE_CO_'+suffix;
57 +const fiscal='POSITIVE_FY_'+suffix;
58 +const debitAccount='POSITIVE_DEBIT_'+suffix;
59 +const creditAccount='POSITIVE_CREDIT_'+suffix;
60 +const voucher='POSITIVE_JV_'+suffix;
61 +sql([
62 + 'insert into public.organizations(id,owner_user_id,name) values ('+q(org)+','+q(userId)+','+q('WP2 positive synthetic')+');',
63 + 'update public.licenses set organization_id='+q(org)+", plan='lifetime', status='active', ends_at=date '2099-01-01', modules=array['full_suite']::text[] where user_id="+q(userId)+';',
64 + 'insert into public.organization_members(organization_id,user_id,status,is_owner) values ('+q(org)+','+q(userId)+",'active',true);",
65 + 'insert into public.records(organization_id,owner_id,collection,id,data) values '+
66 + '('+q(org)+','+q(userId)+",'companies',"+q(company)+','+q(JSON.stringify({name:'WP2 synthetic company'}))+'::jsonb),'+
67 + '('+q(org)+','+q(userId)+",'fiscalYears',"+q(fiscal)+','+q(JSON.stringify({companyId:company,startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}))+'::jsonb),'+
68 + '('+q(org)+','+q(userId)+",'accounts',"+q(debitAccount)+','+q(JSON.stringify({companyId:company,code:'1101',name:'QA debit',postingAllowed:true,active:true}))+'::jsonb),'+
69 + '('+q(org)+','+q(userId)+",'accounts',"+q(creditAccount)+','+q(JSON.stringify({companyId:company,code:'4101',name:'QA credit',postingAllowed:true,active:true}))+'::jsonb);'
70 +].join('\n'));
71 +const login=await fetch(api+'/auth/v1/token?grant_type=password',{
72 + method:'POST',headers:{apikey:anon,'Content-Type':'application/json'},
73 + body:JSON.stringify({email,password})
74 +});
75 +const signed=await login.json();
76 +assert.equal(login.status,200,'disposable Auth JWT login failed');
77 +assert.equal(signed.user?.id,userId,'wrong synthetic actor');
78 +assert.ok(signed.access_token,'missing signed-in user JWT');
79 +const jwt=signed.access_token;
80 +const header={companyId:company,fiscalYearId:fiscal,date:'1405/01/01',sourceType:'manual',voucherType:'manual',description:'authorized synthetic double-entry'};
81 +const lines=[
82 + {id:'positive-debit-'+suffix,accountId:debitAccount,debit:150,credit:0,dimensions:[]},
83 + {id:'positive-credit-'+suffix,accountId:creditAccount,debit:0,credit:150,dimensions:[]}
84 +];
85 +const args={p_organization_id:org,p_voucher_id:voucher,p_header:header,p_lines:lines};
86 +const created=success(await rpc('finora_journal_create_draft',args,jwt),'create draft');
87 +assert.equal(created.replayed,false,'first draft create unexpectedly replayed');
88 +assert.equal(created.voucher?.status,'draft','draft status missing');
89 +assert.equal(created.voucher?.id,voucher,'unexpected draft id');
90 +const version=Number(created.voucher?.version);
91 +assert.ok(Number.isSafeInteger(version)&&version>0,'server version required for optimistic post');
92 +const replay=success(await rpc('finora_journal_create_draft',args,jwt),'same-request replay');
93 +assert.equal(replay.replayed,true,'same request must be idempotent');
94 +assert.equal(replay.voucher?.id,voucher,'replay changed identity');
95 +let voucherRows=(await ownRecords(org,jwt,'journalVouchers')).filter(v=>v.id===voucher);
96 +assert.equal(voucherRows.length,1,'draft must be recorded once');
97 +let journalRows=(await ownRecords(org,jwt,'journalLines')).filter(v=>v.data?.voucherId===voucher);
98 +assert.equal(journalRows.length,2,'replaying draft duplicated journal lines');
99 +assert.equal(journalRows.reduce((n,l)=>n+Number(l.data?.debit||0),0),150);
100 +assert.equal(journalRows.reduce((n,l)=>n+Number(l.data?.credit||0),0),150);
101 +const posted=success(await rpc('finora_journal_post',{
102 + p_organization_id:org,p_voucher_id:voucher,p_expected_version:version
103 +},jwt),'post draft');
104 +assert.equal(posted.voucher?.status,'posted','authorized post was not persisted');
105 +assert.match(String(posted.voucher?.number||''),/^[1-9][0-9]*$/,'posting must allocate a server number');
106 +const allocated=posted.voucher.number;
107 +const postReplay=success(await rpc('finora_journal_post',{
108 + p_organization_id:org,p_voucher_id:voucher,p_expected_version:version
109 +},jwt),'post replay');
110 +assert.equal(postReplay.replayed,true,'already-posted operation must replay safely');
111 +assert.equal(postReplay.voucher?.number,allocated,'post replay changed allocated number');
112 +voucherRows=(await ownRecords(org,jwt,'journalVouchers')).filter(v=>v.id===voucher);
113 +assert.equal(voucherRows.length,1,'posted document disappeared');
114 +assert.equal(voucherRows[0].data.status,'posted');
115 +assert.equal(voucherRows[0].data.number,allocated,'server number differs from returned post');
116 +journalRows=(await ownRecords(org,jwt,'journalLines')).filter(v=>v.data?.voucherId===voucher);
117 +assert.equal(journalRows.length,2,'posting changed balanced line count');
118 +const debit=journalRows.reduce((n,l)=>n+Number(l.data?.debit||0),0);
119 +const credit=journalRows.reduce((n,l)=>n+Number(l.data?.credit||0),0);
120 +assert.equal(debit,credit,'posted journal is unbalanced');
121 +assert.equal(debit,150);
122 +const badId='POSITIVE_UNBALANCED_'+suffix;
123 +const badArgs={...args,p_voucher_id:badId,p_lines:[
124 + {...lines[0],id:'bad-debit-'+suffix,debit:50},
125 + {...lines[1],id:'bad-credit-'+suffix,credit:40}
126 +]};
127 +const refused=await rpc('finora_journal_create_draft',badArgs,jwt);
128 +assert.ok(refused.status>=400,'unbalanced journal unexpectedly accepted by real service');
129 +assert.ok(!(await ownRecords(org,jwt,'journalVouchers')).some(x=>x.id===badId),'rejected draft left persisted voucher');
130 +assert.ok(!(await ownRecords(org,jwt,'journalLines')).some(x=>x.data?.voucherId===badId),'rejected draft left orphan lines');
131 +console.log('WP2_POSITIVE_AUTHORIZED_JOURNAL_PASS: real JWT create/replay/post/readback, balanced lines, immutable post number and failed-create rollback in disposable local Supabase');