سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 17:00 UTC
test(wp2): verify real source-linked autopost replay concurrency and rollback with JWT
davoodmehraban89 committed
Nov 22, 2026 at 07:15 UTC
3f8e8a9cbc22f0fb5e42d3845a6e550a0af544a8
4 files changed
+211
.github/workflows/free-supabase-local-e2e.yml
+9
@@ -14,6 +14,7 @@ on:
14
- "scripts/wp2-auth-tenant-e2e.mjs"
15
- "scripts/wp3-financial-tenant-e2e.mjs"
16
- "scripts/wp2-authorized-journal-write-e2e.mjs"
17
+ - "scripts/wp2-source-autopost-jwt-e2e.mjs"
18
- ".github/workflows/free-supabase-local-e2e.yml"
19
- "supabase/config.toml"
20
workflow_dispatch:
@@ -76,6 +77,14 @@ jobs:
77
set +a
78
node scripts/wp2-authorized-journal-write-e2e.mjs
79
80
+ - name: Prove source-to-posted-journal atomicity and replay with authorized JWT
81
+ run: |
82
+ set -euo pipefail
83
+ set -a
84
+ . /tmp/supabase-local.env
85
+ set +a
86
+ node scripts/wp2-source-autopost-jwt-e2e.mjs
87
+
88
- name: Verify WP1/WP2 journal RPC surface exists
89
run: |
90
set -a
docs/ACCOUNTING_CORE_ROADMAP_V1.md
+2
@@ -437,6 +437,8 @@ This register maps execution stages A/B to the **existing** accounting Phase 6 (
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
+| FIN-QA-SOURCE-JWT-ATOMIC | اثبات واقعی پیوند تراکنشی منبع از قبل ثبتشده، rollback و retry | QA مستقل؛ پذیرش Codex اصلی | PR218 migration `20261117110000` و PR224 CI موفق | در بررسی / در پیادهسازی | JWT مثبت فروش، پیوند اتمیک، رقابت دو اتصال، replay با شناسه دیگر، برگشت شمارنده/سند در شکستِ پیوند، CI SHA نهایی | QA successor stacked on PR224 | PR224 `6f16c00b` چهار گیت موفق؛ اسکریپت جدید هنوز روی SHA نهایی آزموده نشده | بررسی WP2/Quality/WP1/Security؛ بررسی مستقل، بدون merge یا تغییر مالی |
441
+
442
**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.
443
444
docs/EXECUTION_STATUS.md
+8
@@ -1,5 +1,13 @@
1
# وضعیت اجرای فینورا
2
3
+### ۲۰۲۶-۱۱-۲۲ — FIN-QA-SOURCE-JWT-ATOMIC (Stage C، آزمون غیرهمپوشان)
4
+- **شاهد قطعی قبلی:** PR224 `6f16c00b9b67eeace45cc2f5b46e8dfaff34c3ef`، تمام چهار workflow اصلی SUCCESS؛ Quality `44980084933`، WP1 `44980084934`، WP2 `44980084953`، Security `44980084871`. این نتیجه به هیچ SHA جدیدی تعمیم داده نمیشود؛ Dependency review در Security skipped بوده است. بازبینی Codex اصلی انجام نشده و انتشار نیست.
5
+- **تصحیح فنی با حفظ تاریخچه:** نسخه مؤثر `finora_journal_autopost` در migration `20261117110000_wp1_autopost_source_link_atomic.sql` است، نه تابع superseded در `20261016102000`. این تابع پیوند فاکتور/خرید از قبل ذخیرهشده و سند قطعی را در یک تراکنش ثبت میکند. ادعای قبلی مبنی بر نبود پیوند اتمیک، دربارهٔ نسخهٔ فعلی نادرست بود و در PR218 تصحیح شده است. تعمیم آن به ایجاد/ویرایش/حذف منبع و چرخهٔ کامل سند موقت هم نادرست است.
6
+- **کار جاری:** اسکریپت مستقل `scripts/wp2-source-autopost-jwt-e2e.mjs` همراه با گیت WP2، برای آزمون سروری مثبت source-linked sale، retry با شناسه درخواست متفاوت، تزریق خطای تراکنشی در مرحله ثبت پیوند، برگشت header/lines/counter و رقابت دو درخواست واقعی. فقط حساب مصنوعی، شرکت مصنوعی و دیتابیس disposable؛ هیچ تغییر SQL migration/Production/هستهٔ مالی یا sync.js ایجاد نشده.
7
+- **وضعیت:** در پیادهسازی/در بررسی تا CI exact-head. گیت خروج = WP2 به همراه Quality/WP1/Security موفق روی SHA واحد و بازبینی مستقل Codex اصلی. این مأموریت stage C را کامل اعلام نمیکند؛ draft-first مستقل، tombstone، شماره عطف و چک همچنان بازند.
8
+- **نقطه ادامه:** `.github/workflows/free-supabase-local-e2e.yml::local-supabase` → `scripts/wp2-source-autopost-jwt-e2e.mjs` و Actions شاخه QA؛ اگر آزمون شکست خورد خطا را طبقهبندی کن، بدون تضعیف guard و بدون ساخت جایگزین مالی.
9
+
10
+
11
### ۲۰۲۶-۱۱-۲۲ — QA آزمایشی عملیات مثبت مالی؛ کاندیدای مستقل بدون تغییر هسته
12
- شکاف شواهد: WP2 قبلی فقط رد عملیات غیرمجاز سازمان دیگر و قرارداد mock adapter را تأیید میکرد. تست جدید `scripts/wp2-authorized-journal-write-e2e.mjs` باید روی Supabase disposable با Auth/JWT واقعی و PostgREST، ساخت سند دستی متوازن، retry با شناسه ثابت، قطعیسازی مستقل، بازخوانی شماره قطعی سرور و rollback درخواست نامتوازن را بررسی کند. Test fixtures با service-role و psql ساخته میشوند، اما **RPCهای تحت آزمون فقط JWT خود کاربر** دارند.
13
- مسئول: 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 اصلی؛ تا پیش از آن «در بررسی/در پیادهسازی».
scripts/wp2-source-autopost-jwt-e2e.mjs
new
+192
@@ -0,0 +1,192 @@
1
+import assert from 'node:assert/strict';
2
+import {spawnSync} from 'node:child_process';
3
+
4
+// Stage C QA only — live local Auth/JWT + PostgREST, synthetic fixture.
5
+// psql and the local admin service key ONLY prepare disposable data and inject
6
+// a deterministic failure at the final source-link write. The financial RPC
7
+// requests themselves MUST use the logged-in user's JWT.
8
+const api=process.env.API_URL,anon=process.env.ANON_KEY;
9
+const service=process.env.SERVICE_ROLE_KEY,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
+ assert.ok(value,'missing disposable local Supabase setting '+name);
12
+}
13
+const suffix=Date.now()+'_'+crypto.randomUUID().slice(0,8);
14
+const q=value=>"'"+String(value).replaceAll("'","''")+"'";
15
+function command(statement,scalar=false){
16
+ const flags=['-X','-v','ON_ERROR_STOP=1'];
17
+ if(scalar)flags.push('-At');
18
+ const out=spawnSync('psql',[db,...flags,'-c',statement],{encoding:'utf8'});
19
+ assert.equal(out.status,0,'local fixture SQL failed: '+(out.stderr||out.stdout).slice(-800));
20
+ return (out.stdout||'').trim();
21
+}
22
+async function rest(collection,token){
23
+ const url=api+'/rest/v1/records?select=id,owner_id,version,data&collection=eq.'+encodeURIComponent(collection);
24
+ const response=await fetch(url,{headers:{apikey:anon,Authorization:'Bearer '+token}});
25
+ const raw=await response.text();
26
+ assert.equal(response.status,200,'signed-in journal read failed ('+collection+'): '+raw.slice(0,600));
27
+ return JSON.parse(raw);
28
+}
29
+async function rpc(name,args,jwt){
30
+ const response=await fetch(api+'/rest/v1/rpc/'+name,{
31
+ method:'POST',headers:{apikey:anon,Authorization:'Bearer '+jwt,'Content-Type':'application/json'},
32
+ body:JSON.stringify(args)
33
+ });
34
+ const raw=await response.text();
35
+ let body;
36
+ try{body=JSON.parse(raw)}catch{body=raw}
37
+ return {status:response.status,body};
38
+}
39
+function ok(result,label){
40
+ assert.equal(result.status,200,label+': '+JSON.stringify(result.body));
41
+ assert.ok(result.body&&typeof result.body==='object',label+': missing object');
42
+ return result.body;
43
+}
44
+const email='wp2-source-'+suffix+'@example.test',password='Qa-'+crypto.randomUUID()+'-Aa9!';
45
+const signup=await fetch(api+'/auth/v1/admin/users',{
46
+ method:'POST',headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'},
47
+ body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'qa'+suffix}})
48
+});
49
+const user=await signup.json();
50
+assert.equal(signup.status,200,'disposable Auth user setup failed');
51
+const uid=user.id,org=crypto.randomUUID();
52
+const co='QA_CO_'+suffix,fy='QA_FY_'+suffix;
53
+const cash='QA_CASH_'+suffix,revenue='QA_REV_'+suffix;
54
+const accCash={companyId:co,systemRole:'cash_default',accountType:'asset',normalBalance:'debit',
55
+ level:'detail',postingAllowed:true,active:true,code:'1101',name:'Synthetic cash'};
56
+const accRevenue={companyId:co,systemRole:'revenue_default',accountType:'revenue',normalBalance:'credit',
57
+ level:'detail',postingAllowed:true,active:true,code:'4101',name:'Synthetic revenue'};
58
+command('INSERT INTO public.organizations(id,owner_user_id,name) VALUES ('+
59
+ q(org)+','+q(uid)+','+q('QA source '+suffix)+');');
60
+command("UPDATE public.licenses SET organization_id="+q(org)+
61
+ ",plan='lifetime',status='active',ends_at=date '2099-01-01',modules=array['full_suite']::text[] WHERE user_id="+q(uid)+';');
62
+command('INSERT INTO public.organization_members(organization_id,user_id,status,is_owner) VALUES ('+
63
+ q(org)+','+q(uid)+",'active',true);");
64
+const rec=(collection,id,data)=>'('+q(org)+','+q(uid)+','+q(collection)+','+q(id)+','+q(JSON.stringify(data))+'::jsonb)';
65
+command('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+
66
+ [rec('companies',co,{name:'QA company'}),rec('fiscalYears',fy,{companyId:co,startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}),
67
+ rec('accounts',cash,accCash),rec('accounts',revenue,accRevenue)].join(',')+';');
68
+command('INSERT INTO private.finora_phase1a_account_role_snapshots ('+
69
+ 'organization_id,company_id,version,assignments,account_fields,approved,approved_by,reason) '+
70
+ 'SELECT '+q(org)+','+q(co)+",1,jsonb_build_object('cash_default',"+q(cash)+
71
+ ",'revenue_default',"+q(revenue)+"),jsonb_build_object('cash_default',"+
72
+ 'private.finora_phase1a_account_fields(c.data),'+
73
+ "'revenue_default',private.finora_phase1a_account_fields(r.data)),true,"+q(uid)+
74
+ ",'QA disposable approved binding' FROM public.records c JOIN public.records r ON "+
75
+ 'r.organization_id=c.organization_id AND r.collection='+q('accounts')+' AND r.id='+q(revenue)+
76
+ ' WHERE c.organization_id='+q(org)+' AND c.collection='+q('accounts')+' AND c.id='+q(cash)+';');
77
+const login=await fetch(api+'/auth/v1/token?grant_type=password',{
78
+ method:'POST',headers:{apikey:anon,'Content-Type':'application/json'},body:JSON.stringify({email,password})
79
+});
80
+const signed=await login.json();
81
+assert.equal(login.status,200,'real user sign-in failed');
82
+assert.equal(signed.user?.id,uid,'wrong authenticated user');
83
+assert.ok(signed.access_token,'missing Auth-issued token');
84
+const jwt=signed.access_token;
85
+function newSource(id,amount){
86
+ return {companyId:co,date:'1405/01/01',kind:'formal',description:'Synthetic sale',
87
+ reference:id,accountingVersion:1,accountingStatus:'draft',documentStatus:'draft',
88
+ paymentMethod:'cash',currencyCode:'IRR',
89
+ items:[{prodId:'QA_PRODUCT',qty:1,price:amount,lineTotal:amount}],
90
+ subtotal:amount,discountType:'fixed',discountInput:0,discount:0,
91
+ vatMode:'none',vatType:'percent',vatRate:0,vat:0,grandTotal:amount};
92
+}
93
+function seedSource(id,amount){
94
+ command('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+
95
+ rec('invoices',id,newSource(id,amount))+';');
96
+}
97
+const voucherArgs=(id,source)=>({
98
+ p_organization_id:org,p_voucher_id:id,p_source_collection:'invoices',p_source_id:source,
99
+ p_header:{companyId:co,fiscalYearId:fy,date:'1405/01/01',voucherType:'sale',
100
+ sourceType:'sale',sourceId:source,sourceVersion:'1',description:'JWT source autolink'},
101
+ p_lines:[]
102
+});
103
+const own=async(collection)=> (await rest(collection,jwt))
104
+ .filter(x=>x.data?.companyId===co);
105
+const sourceRow=async(id)=>{
106
+ const items=(await own('invoices')).filter(x=>x.id===id);
107
+ assert.equal(items.length,1,'source not found by authorized JWT');
108
+ return items[0];
109
+};
110
+const voucherRows=async(source)=> (await own('journalVouchers')).filter(x=>
111
+ x.data?.sourceType==='sale'&&x.data?.sourceId===source);
112
+const voucherLines=async(id)=> (await own('journalLines')).filter(x=>x.data?.voucherId===id);
113
+const counter=()=>command('SELECT last_no FROM private.finora_phase1a_journal_counters WHERE organization_id='+
114
+ q(org)+' AND fiscal_year_id='+q(fy)+';',true);
115
+
116
+// 1. Positive real source→journal commit, plus replay with an unrelated RPC
117
+// request voucher ID: server must recover by stable source/version, not caller ID.
118
+const firstSource='QA_SALE_A_'+suffix,firstVoucher='QA_VOUCH_A_'+suffix;
119
+seedSource(firstSource,120);
120
+const initial=await sourceRow(firstSource);
121
+assert.equal(initial.data?.journalVoucherId,undefined,'draft already linked');
122
+const posted=ok(await rpc('finora_journal_autopost',voucherArgs(firstVoucher,firstSource),jwt),'source autopost');
123
+assert.equal(posted.voucher?.status,'posted','autopost did not post');
124
+assert.equal(posted.voucher?.id,firstVoucher,'server changed voucher ID');
125
+assert.match(String(posted.voucher?.number||''),/^[1-9][0-9]*$/);
126
+let source=await sourceRow(firstSource);
127
+assert.equal(source.data.journalVoucherId,firstVoucher,'server failed to link source in same operation');
128
+assert.equal(source.data.accountingStatus,'posted');
129
+assert.equal(source.data.documentStatus,'posted');
130
+assert.equal(source.data.grandTotal,120,'autopost mutated source business amount');
131
+let vouchers=await voucherRows(firstSource);
132
+assert.equal(vouchers.length,1,'duplicate source vouchers');
133
+let lines=await voucherLines(firstVoucher);
134
+assert.equal(lines.length,2,'source has wrong number of ledger lines');
135
+assert.equal(lines.reduce((s,x)=>s+Number(x.data?.debit||0),0),120);
136
+assert.equal(lines.reduce((s,x)=>s+Number(x.data?.credit||0),0),120);
137
+const replay=ok(await rpc('finora_journal_autopost',
138
+ voucherArgs('QA_DIFFERENT_RETRY_'+suffix,firstSource),jwt),'replay with changed request ID');
139
+assert.equal(replay.replayed,true,'source-level replay did not succeed');
140
+assert.equal(replay.voucher?.id,firstVoucher,'source retry created different voucher');
141
+assert.equal(replay.voucher?.number,posted.voucher.number,'source retry changed financial number');
142
+assert.equal((await voucherRows(firstSource)).length,1);
143
+assert.equal((await voucherLines(firstVoucher)).length,2);
144
+
145
+// 2. Deterministic AFTER-POST failure at the source link: all rows and
146
+// counters MUST roll back. Only the disposable local database gets this trigger.
147
+const failingSource='QA_FAIL_LINK_'+suffix,failingVoucher='QA_FAIL_JV_'+suffix;
148
+seedSource(failingSource,130);
149
+const oldCounter=counter();
150
+const fn='finora_qa_inject_source_link_'+suffix.replaceAll('-','_');
151
+const trigger='finora_qa_fail_link_'+suffix.replaceAll('-','_');
152
+command('CREATE FUNCTION private.'+fn+'() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path='+
153
+ q('')+' AS $f$ BEGIN IF NEW.collection='+q('invoices')+' AND NEW.id='+q(failingSource)+
154
+ " AND coalesce(NEW.data->>'journalVoucherId','')<>'' THEN "+
155
+ "RAISE EXCEPTION 'FINORA_QA_FORCED_LINK_FAILURE' USING ERRCODE='P0001'; "+
156
+ 'END IF; RETURN NEW; END $f$;');
157
+command('CREATE TRIGGER '+trigger+' BEFORE UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION private.'+fn+'();');
158
+const rejected=await rpc('finora_journal_autopost',voucherArgs(failingVoucher,failingSource),jwt);
159
+assert.ok(rejected.status>=400,'injected source link failure unexpectedly posted');
160
+assert.match(JSON.stringify(rejected.body),/FINORA_QA_FORCED_LINK_FAILURE/,
161
+ 'expected failure must occur at source link AFTER posting attempt');
162
+assert.equal((await voucherRows(failingSource)).length,0,'journal header survived failed source link');
163
+assert.equal((await voucherLines(failingVoucher)).length,0,'journal lines survived failed source link');
164
+const afterFailure=await sourceRow(failingSource);
165
+assert.equal(afterFailure.data.accountingStatus,'draft','source status changed despite rollback');
166
+assert.ok(!afterFailure.data.journalVoucherId,'source link survived failed transaction');
167
+assert.equal(counter(),oldCounter,'failed source link consumed a committed number');
168
+command('DROP TRIGGER '+trigger+' ON public.records;');
169
+command('DROP FUNCTION private.'+fn+'();');
170
+
171
+// 3. Two independent real JWT RPC requests for the SAME source with different
172
+// voucher IDs are forced to race. At most one source voucher/number may persist.
173
+const racingSource='QA_RACE_SALE_'+suffix;
174
+seedSource(racingSource,140);
175
+const [raceA,raceB]=await Promise.all([
176
+ rpc('finora_journal_autopost',voucherArgs('QA_RACE_A_'+suffix,racingSource),jwt),
177
+ rpc('finora_journal_autopost',voucherArgs('QA_RACE_B_'+suffix,racingSource),jwt)
178
+]);
179
+const a=ok(raceA,'concurrent source A'),b=ok(raceB,'concurrent source B');
180
+assert.equal(a.voucher.id,b.voucher.id,'concurrent source requests posted different vouchers');
181
+assert.equal(a.voucher.number,b.voucher.number,'concurrent source requests allocated different numbers');
182
+assert.ok(a.replayed===true||b.replayed===true,
183
+ 'one concurrent request must recover already-posted source');
184
+source=await sourceRow(racingSource);
185
+assert.equal(source.data.journalVoucherId,a.voucher.id,'concurrent source link is inconsistent');
186
+vouchers=await voucherRows(racingSource);
187
+assert.equal(vouchers.length,1,'concurrent source request double-posted');
188
+lines=await voucherLines(a.voucher.id);
189
+assert.equal(lines.length,2,'concurrent source created duplicate lines');
190
+assert.equal(lines.reduce((s,x)=>s+Number(x.data?.debit||0),0),140);
191
+assert.equal(lines.reduce((s,x)=>s+Number(x.data?.credit||0),0),140);
192
+console.log('FINORA_SOURCE_JWT_ATOMIC_PASS: real user JWT positive source link/replay, injected late-link rollback with unchanged counter, and two-request source concurrency in disposable Supabase');