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

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

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

Synced Dec 3, 18:15 UTC

docs/finora-v2-m01-coverage-20261124
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
mjs 400 lines 24.4 KB
Raw
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 const auditCount=id=>Number(command(
116 'SELECT count(*) FROM private.finora_phase1a_journal_audit WHERE organization_id='+
117 q(org)+' AND voucher_id='+q(id)+';',true));
118 const auditWrongActors=id=>Number(command(
119 'SELECT count(*) FROM private.finora_phase1a_journal_audit WHERE organization_id='+
120 q(org)+' AND voucher_id='+q(id)+' AND actor_id IS DISTINCT FROM '+q(uid)+'::uuid;',true));
121 const businessOnly=data=>{
122 const copy={...data};
123 for(const key of ['journalVoucherId','accountingStatus','accountingPostedAt',
124 'documentStatus','documentPostedAt','documentPostedBy','documentVersion',
125 'updatedAt','accountingPostingPending','accountingPostingPendingAt'])delete copy[key];
126 return copy;
127 };
128
129 // 1. Positive real source→journal commit, plus replay with an unrelated RPC
130 // request voucher ID: server must recover by stable source/version, not caller ID.
131 const firstSource='QA_SALE_A_'+suffix,firstVoucher='QA_VOUCH_A_'+suffix;
132 seedSource(firstSource,120);
133 const initial=await sourceRow(firstSource);
134 assert.equal(initial.data?.journalVoucherId,undefined,'draft already linked');
135 const posted=ok(await rpc('finora_journal_autopost',voucherArgs(firstVoucher,firstSource),jwt),'source autopost');
136 assert.equal(posted.voucher?.status,'posted','autopost did not post');
137 assert.equal(posted.voucher?.id,firstVoucher,'server changed voucher ID');
138 assert.match(String(posted.voucher?.number||''),/^[1-9][0-9]*$/);
139 let source=await sourceRow(firstSource);
140 assert.equal(source.data.journalVoucherId,firstVoucher,'server failed to link source in same operation');
141 assert.equal(source.data.accountingStatus,'posted');
142 assert.equal(source.data.documentStatus,'posted');
143 assert.equal(source.data.grandTotal,120,'autopost mutated source business amount');
144 assert.deepEqual(businessOnly(source.data),businessOnly(initial.data),
145 'posted source must preserve all unrelated business fields');
146 let vouchers=await voucherRows(firstSource);
147 assert.equal(vouchers.length,1,'duplicate source vouchers');
148 let lines=await voucherLines(firstVoucher);
149 assert.equal(lines.length,2,'source has wrong number of ledger lines');
150 assert.equal(lines.reduce((s,x)=>s+Number(x.data?.debit||0),0),120);
151 assert.equal(lines.reduce((s,x)=>s+Number(x.data?.credit||0),0),120);
152 const successfulAuditCount=auditCount(firstVoucher);
153 assert.ok(successfulAuditCount>=2,'source posting must keep draft-created and posted audit events');
154 assert.equal(auditWrongActors(firstVoucher),0,'source audit actor must be Auth JWT subject');
155 const replay=ok(await rpc('finora_journal_autopost',
156 voucherArgs('QA_DIFFERENT_RETRY_'+suffix,firstSource),jwt),'replay with changed request ID');
157 assert.equal(replay.replayed,true,'source-level replay did not succeed');
158 assert.equal(replay.voucher?.id,firstVoucher,'source retry created different voucher');
159 assert.equal(replay.voucher?.number,posted.voucher.number,'source retry changed financial number');
160 assert.equal((await voucherRows(firstSource)).length,1);
161 assert.equal((await voucherLines(firstVoucher)).length,2);
162 assert.equal(auditCount(firstVoucher),successfulAuditCount,
163 'idempotent source retry must not append another posting audit event');
164
165 // 2. Deterministic AFTER-POST failure at the source link: all rows and
166 // counters MUST roll back. Only the disposable local database gets this trigger.
167 const failingSource='QA_FAIL_LINK_'+suffix,failingVoucher='QA_FAIL_JV_'+suffix;
168 seedSource(failingSource,130);
169 const oldCounter=counter();
170 const fn='finora_qa_inject_source_link_'+suffix.replaceAll('-','_');
171 const trigger='finora_qa_fail_link_'+suffix.replaceAll('-','_');
172 command('CREATE FUNCTION private.'+fn+'() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path='+
173 q('')+' AS $f$ BEGIN IF NEW.collection='+q('invoices')+' AND NEW.id='+q(failingSource)+
174 " AND coalesce(NEW.data->>'journalVoucherId','')<>'' THEN "+
175 "RAISE EXCEPTION 'FINORA_QA_FORCED_LINK_FAILURE' USING ERRCODE='P0001'; "+
176 'END IF; RETURN NEW; END $f$;');
177 command('CREATE TRIGGER '+trigger+' BEFORE UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION private.'+fn+'();');
178 const rejected=await rpc('finora_journal_autopost',voucherArgs(failingVoucher,failingSource),jwt);
179 assert.ok(rejected.status>=400,'injected source link failure unexpectedly posted');
180 assert.match(JSON.stringify(rejected.body),/FINORA_QA_FORCED_LINK_FAILURE/,
181 'expected failure must occur at source link AFTER posting attempt');
182 assert.equal((await voucherRows(failingSource)).length,0,'journal header survived failed source link');
183 assert.equal((await voucherLines(failingVoucher)).length,0,'journal lines survived failed source link');
184 const afterFailure=await sourceRow(failingSource);
185 assert.equal(afterFailure.data.accountingStatus,'draft','source status changed despite rollback');
186 assert.ok(!afterFailure.data.journalVoucherId,'source link survived failed transaction');
187 assert.equal(counter(),oldCounter,'failed source link consumed a committed number');
188 assert.equal(auditCount(failingVoucher),0,
189 'audit records survived a rolled-back source-link failure');
190 command('DROP TRIGGER '+trigger+' ON public.records;');
191 command('DROP FUNCTION private.'+fn+'();');
192
193 // 3. Two independent real JWT RPC requests for the SAME source with different
194 // voucher IDs are forced to race. At most one source voucher/number may persist.
195 const racingSource='QA_RACE_SALE_'+suffix;
196 seedSource(racingSource,140);
197 const [raceA,raceB]=await Promise.all([
198 rpc('finora_journal_autopost',voucherArgs('QA_RACE_A_'+suffix,racingSource),jwt),
199 rpc('finora_journal_autopost',voucherArgs('QA_RACE_B_'+suffix,racingSource),jwt)
200 ]);
201 const a=ok(raceA,'concurrent source A'),b=ok(raceB,'concurrent source B');
202 assert.equal(a.voucher.id,b.voucher.id,'concurrent source requests posted different vouchers');
203 assert.equal(a.voucher.number,b.voucher.number,'concurrent source requests allocated different numbers');
204 assert.ok(a.replayed===true||b.replayed===true,
205 'one concurrent request must recover already-posted source');
206 source=await sourceRow(racingSource);
207 assert.equal(source.data.journalVoucherId,a.voucher.id,'concurrent source link is inconsistent');
208 vouchers=await voucherRows(racingSource);
209 assert.equal(vouchers.length,1,'concurrent source request double-posted');
210 lines=await voucherLines(a.voucher.id);
211 assert.equal(lines.length,2,'concurrent source created duplicate lines');
212 assert.equal(lines.reduce((s,x)=>s+Number(x.data?.debit||0),0),140);
213 assert.equal(lines.reduce((s,x)=>s+Number(x.data?.credit||0),0),140);
214 assert.ok(auditCount(a.voucher.id)>=2,'concurrent winner is missing audit trail');
215 assert.equal(auditWrongActors(a.voucher.id),0,
216 'concurrent source posting audit actor must be Auth JWT subject');
217 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; audit attribution and rollback also verified in disposable Supabase');
218
219 // 4. Auth-JWT negative contract for the REAL persisted posted source.
220 command('INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode) VALUES ('+
221 q(org)+",'enforce') ON CONFLICT (organization_id) DO UPDATE SET mode='enforce';");
222 async function userRestMutation(method,collection,id,data){
223 const url=new URL(api+'/rest/v1/records');
224 for(const [key,value] of Object.entries({
225 organization_id:org,collection,id
226 }))url.searchParams.set(key,'eq.'+value);
227 const res=await fetch(url,{method,
228 headers:{apikey:anon,Authorization:'Bearer '+jwt,
229 'Content-Type':'application/json',Prefer:'return=representation'},
230 ...(data===undefined?{}:{body:JSON.stringify({data})})
231 });
232 const raw=await res.text();let body;
233 try{body=JSON.parse(raw)}catch{body=raw}
234 return {status:res.status,body};
235 }
236 function financialGuardRejected(result,label,pattern){
237 assert.ok(result.status>=400&&result.status<500,
238 label+' succeeded or had unexpected status: '+JSON.stringify(result));
239 assert.ok(result.body&&typeof result.body==='object'&&
240 ['23514','P0001'].includes(String(result.body.code||'')),
241 label+' was only RLS denied or did not hit financial guard: '+JSON.stringify(result));
242 assert.match(JSON.stringify(result.body),pattern,label+' wrong guard error');
243 }
244 const frozenSource=(await sourceRow(firstSource)).data;
245 const frozenVoucher=(await voucherRows(firstSource))[0];
246 const frozenLines=await voucherLines(firstVoucher);
247 const frozenCounter=counter(),frozenAudit=auditCount(firstVoucher);
248 financialGuardRejected(await userRestMutation('PATCH','invoices',firstSource,{
249 ...frozenSource,description:'forged commercial amendment'
250 }),'posted sale commercial edit',/FINORA_POSTED_SOURCE_IMMUTABLE|linked to posted\/reversed/i);
251 financialGuardRejected(await userRestMutation('PATCH','invoices',firstSource,{
252 ...frozenSource,journalVoucherId:'FORGED_JOURNAL',documentStatus:'draft'
253 }),'posted sale accounting projection forgery',
254 /FINORA_POSTED_SOURCE_LINK_PROJECTION_INVALID|linked to posted\/reversed/i);
255 financialGuardRejected(await userRestMutation('DELETE','invoices',firstSource),
256 'posted sale direct delete',/FINORA_POSTED_SOURCE_IMMUTABLE|linked to posted\/reversed/i);
257 financialGuardRejected(await userRestMutation('PATCH','journalLines',frozenLines[0].id,{
258 ...frozenLines[0].data,debit:1
259 }),'posted journal line edit',/FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE|posted\/reversed journal lines are immutable/i);
260 const deniedVoucherDelete=await rpc('finora_journal_delete_draft',{
261 p_organization_id:org,p_voucher_id:firstVoucher,
262 p_expected_version:frozenVoucher.version
263 },jwt);
264 assert.ok(deniedVoucherDelete.status>=400&&deniedVoucherDelete.status<500,
265 'posted source voucher delete_draft RPC succeeded');
266 assert.match(JSON.stringify(deniedVoucherDelete.body),
267 /FINORA_JOURNAL_NOT_DRAFT|FINORA_SOURCE|FORBIDDEN/i,
268 'posted source voucher RPC did not reject for a financial reason');
269 assert.deepEqual((await sourceRow(firstSource)).data,frozenSource,
270 'posted source changed after denied JWT mutation');
271 assert.deepEqual((await voucherRows(firstSource))[0],frozenVoucher,
272 'posted voucher changed after denied JWT mutation');
273 assert.deepEqual(await voucherLines(firstVoucher),frozenLines,
274 'posted journal lines changed after denied JWT mutation');
275 assert.equal(counter(),frozenCounter,'denied JWT action changed final counter');
276 assert.equal(auditCount(firstVoucher),frozenAudit,'denied JWT action changed audit');
277 console.log('FINORA_POSTED_SOURCE_JWT_IMMUTABLE_PASS: live JWT source edit, forged link, delete, posted journal line edit and linked voucher delete rejected by financial guard; source, voucher, lines, counter and audit unchanged');
278
279
280 // 5. Separate real-JWT purchase acceptance. Reuse the ORIGINAL approved role
281 // snapshot and append a purchase-capable version; never mutate its history.
282 // Fixture SQL remains local/trusted; real purchase RPCs use Auth-user JWT.
283 const purchaseCost='QA_PURCHASE_COST_'+suffix,accountsPayable='QA_PAYABLE_'+suffix;
284 const accPurchaseCost={companyId:co,systemRole:'purchase_default',accountType:'expense',
285 normalBalance:'debit',level:'detail',postingAllowed:true,active:true,code:'5101',
286 name:'Synthetic purchases'};
287 const accPayable={companyId:co,systemRole:'payable_control',accountType:'liability',
288 normalBalance:'credit',level:'detail',postingAllowed:true,active:true,code:'2101',
289 name:'Synthetic accounts payable'};
290 command('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+
291 [rec('accounts',purchaseCost,accPurchaseCost),
292 rec('accounts',accountsPayable,accPayable)].join(',')+';');
293 command('INSERT INTO private.finora_phase1a_account_role_snapshots ('+
294 'organization_id,company_id,version,assignments,account_fields,approved,approved_by,reason) '+
295 'SELECT '+q(org)+','+q(co)+',2,'+
296 'old.assignments || jsonb_build_object('+
297 "'purchase_default',"+q(purchaseCost)+",'payable_control',"+q(accountsPayable)+'),' +
298 'old.account_fields || jsonb_build_object('+
299 "'purchase_default',private.finora_phase1a_account_fields(p.data),"+
300 "'payable_control',private.finora_phase1a_account_fields(a.data)),true,"+
301 q(uid)+",'QA purchase role extension of immutable v1' "+
302 'FROM private.finora_phase1a_account_role_snapshots old '+
303 'JOIN public.records p ON p.organization_id=old.organization_id AND p.collection='+
304 q('accounts')+' AND p.id='+q(purchaseCost)+' '+
305 'JOIN public.records a ON a.organization_id=old.organization_id AND a.collection='+
306 q('accounts')+' AND a.id='+q(accountsPayable)+' '+
307 'WHERE old.organization_id='+q(org)+' AND old.company_id='+q(co)+
308 ' AND old.version=1 AND old.approved=true;');
309 assert.equal(command('SELECT count(*) FROM private.finora_phase1a_account_role_snapshots WHERE organization_id='+
310 q(org)+' AND company_id='+q(co)+' AND approved;',true),'2',
311 'approved role configuration history must be append-only');
312 const purchaseSource='QA_PURCHASE_'+suffix,purchaseVoucher='QA_PURCHASE_JV_'+suffix;
313 const purchasePayload={
314 ...newSource(purchaseSource,170),
315 description:'Synthetic supplier credit purchase',
316 paymentMethod:'credit'
317 };
318 command('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+
319 rec('purchases',purchaseSource,purchasePayload)+';');
320 const purchaseArgs=(voucherId)=>({
321 p_organization_id:org,p_voucher_id:voucherId,
322 p_source_collection:'purchases',p_source_id:purchaseSource,
323 p_header:{companyId:co,fiscalYearId:fy,date:'1405/01/01',
324 voucherType:'purchase',sourceType:'purchase',sourceId:purchaseSource,
325 sourceVersion:'1',description:'JWT credit purchase posting'},
326 p_lines:[]
327 });
328 const purchaseBefore=(await own('purchases')).filter(v=>v.id===purchaseSource);
329 assert.equal(purchaseBefore.length,1,'owner JWT cannot read purchase fixture');
330 const purchaseCountBefore=Number(counter());
331 const purchaseResult=ok(await rpc('finora_journal_autopost',purchaseArgs(purchaseVoucher),jwt),
332 'credit purchase autopost using real JWT');
333 assert.equal(purchaseResult.voucher?.id,purchaseVoucher);
334 assert.equal(purchaseResult.voucher?.status,'posted');
335 assert.match(String(purchaseResult.voucher?.number||''),/^[1-9][0-9]*$/);
336 assert.equal(Number(purchaseResult.voucher.number),purchaseCountBefore+1,
337 'purchase did not consume exactly the next posted journal number');
338 const purchaseRows=(await own('purchases')).filter(v=>v.id===purchaseSource);
339 assert.equal(purchaseRows.length,1);
340 let purchaseData=purchaseRows[0].data;
341 assert.equal(purchaseData.journalVoucherId,purchaseVoucher,
342 'purchase-to-posted voucher link absent');
343 assert.equal(purchaseData.accountingStatus,'posted');
344 assert.equal(purchaseData.documentStatus,'posted');
345 assert.deepEqual(businessOnly(purchaseData),businessOnly(purchaseBefore[0].data),
346 'purchase posting changed commercial inputs');
347 const purchaseJournals=(await own('journalVouchers')).filter(v=>
348 v.data?.sourceType==='purchase'&&v.data?.sourceId===purchaseSource);
349 assert.equal(purchaseJournals.length,1,'purchase source is double-posted');
350 const purchaseLines=await voucherLines(purchaseVoucher);
351 assert.equal(purchaseLines.length,2);
352 const actualPurchaseEntries=purchaseLines.map(v=>({
353 accountId:v.data.accountId,debit:Number(v.data.debit),credit:Number(v.data.credit)
354 })).sort((a,b)=>a.accountId.localeCompare(b.accountId));
355 const wantedPurchaseEntries=[
356 {accountId:purchaseCost,debit:170,credit:0},
357 {accountId:accountsPayable,debit:0,credit:170}
358 ].sort((a,b)=>a.accountId.localeCompare(b.accountId));
359 assert.deepEqual(actualPurchaseEntries,wantedPurchaseEntries,
360 'purchase cash/payable/expense debit-credit mapping is wrong');
361 const auditBeforePurchaseReplay=auditCount(purchaseVoucher);
362 assert.ok(auditBeforePurchaseReplay>=2,'purchase posting audit missing');
363 assert.equal(auditWrongActors(purchaseVoucher),0,'purchase audit actor differs from Auth JWT');
364 const purchaseReplay=ok(await rpc('finora_journal_autopost',
365 purchaseArgs('QA_PURCHASE_OTHER_REQUEST_'+suffix),jwt),'credit purchase replay');
366 assert.equal(purchaseReplay.replayed,true);
367 assert.equal(purchaseReplay.voucher?.id,purchaseVoucher);
368 assert.equal(purchaseReplay.voucher?.number,purchaseResult.voucher.number);
369 assert.equal(Number(counter()),purchaseCountBefore+1,
370 'purchase replay consumed another final number');
371 assert.equal(auditCount(purchaseVoucher),auditBeforePurchaseReplay,
372 'purchase replay appended redundant audit');
373 assert.equal((await own('journalVouchers')).filter(v=>
374 v.data?.sourceType==='purchase'&&v.data?.sourceId===purchaseSource).length,1,
375 'purchase replay created another voucher');
376 purchaseData=(await own('purchases')).find(v=>v.id===purchaseSource)?.data;
377 assert.equal(purchaseData.journalVoucherId,purchaseVoucher);
378 assert.deepEqual(businessOnly(purchaseData),businessOnly(purchaseBefore[0].data));
379 const frozenPurchase={...purchaseData},frozenPurchaseLines=await voucherLines(purchaseVoucher);
380 const frozenPurchaseAudit=auditCount(purchaseVoucher),frozenPurchaseCounter=counter();
381 financialGuardRejected(await userRestMutation('PATCH','purchases',purchaseSource,{
382 ...frozenPurchase,grandTotal:999
383 }),'posted purchase amount tampering',
384 /FINORA_POSTED_SOURCE_IMMUTABLE|linked to posted\/reversed/i);
385 financialGuardRejected(await userRestMutation('PATCH','purchases',purchaseSource,{
386 ...frozenPurchase,journalVoucherId:'FORGED_PURCHASE_LINK',documentStatus:'draft'
387 }),'posted purchase accounting link forgery',
388 /FINORA_POSTED_SOURCE_LINK_PROJECTION_INVALID|linked to posted\/reversed/i);
389 financialGuardRejected(await userRestMutation('DELETE','purchases',purchaseSource),
390 'posted purchase REST deletion',
391 /FINORA_POSTED_SOURCE_IMMUTABLE|linked to posted\/reversed/i);
392 assert.deepEqual((await own('purchases')).find(v=>v.id===purchaseSource)?.data,frozenPurchase,
393 'posted purchase source changed after rejected Auth JWT requests');
394 assert.deepEqual(await voucherLines(purchaseVoucher),frozenPurchaseLines,
395 'posted purchase ledger changed after denied source mutation');
396 assert.equal(auditCount(purchaseVoucher),frozenPurchaseAudit,
397 'denied purchase tampering altered official audit');
398 assert.equal(counter(),frozenPurchaseCounter,
399 'denied purchase tampering changed final number');
400 console.log('FINORA_PURCHASE_JWT_PARITY_PASS: real JWT credit purchase posting, expense/payable ledger mapping, persisted source link, replay with changed request ID, immutable source PATCH/DELETE, audit actor and number consistency; disposable Supabase only');