سامانه صدور فاکتور و حسابداری
test(stage1): account role audit/enforce and independent 1000-sale oracle
davoodmehraban89 committed
Oct 17, 2026 at 10:36 UTC
2f831632eb386aa5240e2068e67fe84045bd978a
3 files changed
+289
.github/workflows/phase1a-supabase-parity.yml
+33
@@ -93,6 +93,8 @@ jobs:
93
PGPASSWORD=postgres psql -h 127.0.0.1 -p 54322 -U postgres -d postgres -X -v ON_ERROR_STOP=1 -f /tmp/finora-phase1a-migrations/20261016103100_phase1a_autopost_server_authority.sql
94
- name: RED FIRST — sale with 900-series balanced unrelated accounts must be rejected
95
run: PGPASSWORD=postgres psql -h 127.0.0.1 -p 54322 -U postgres -d postgres -X -v ON_ERROR_STOP=1 -f supabase/tests/phase1a_stage1_autopost_semantic_red.sql
96
+ - name: Stage 1 enforce/audit accounting role sync, owner RPC and append-only audit
97
+ run: PGPASSWORD=postgres psql -h 127.0.0.1 -p 54322 -U postgres -d postgres -X -v ON_ERROR_STOP=1 -f supabase/tests/phase1a_stage1_account_role_controls.sql
98
- name: Run 1A green-after-red authenticated adversarial tests
99
run: node scripts/phase1a-adversarial-red.mjs
100
- name: Test 1A versioned CAS and two-tenant RLS
@@ -182,3 +184,34 @@ jobs:
184
done
185
- name: EXPECTED RED — assert exactly three known Stage 2 client incompatibilities (guard enforce)
186
run: node scripts/phase1a-client-compat-expected-red.mjs
187
+
188
+ autopost-sale-independent-oracle:
189
+ name: stage1-sale-independent-1000-oracle
190
+ runs-on: ubuntu-latest
191
+ timeout-minutes: 40
192
+ steps:
193
+ - uses: actions/checkout@v4
194
+ - uses: supabase/setup-cli@v1
195
+ with:
196
+ version: 2.121.0
197
+ - name: Verify offline migration preflight
198
+ run: node scripts/phase1a-migration-preflight.mjs
199
+ - name: Prepare local-only Supabase and stage migrations
200
+ run: |
201
+ supabase init --force
202
+ python3 - <<'PY'
203
+ from pathlib import Path
204
+ for p in Path('supabase/migrations').glob('*.sql'):
205
+ b=p.read_bytes()
206
+ if b.endswith(b'\\n'): p.write_bytes(b[:-2]+b'\n')
207
+ PY
208
+ mkdir -p /tmp/finora-oracle-migrations
209
+ mv supabase/migrations/2026101610{0000,0500,1000,1500,2000,2500,3000,3100}_*.sql /tmp/finora-oracle-migrations/
210
+ supabase start -x inbucket
211
+ - name: Apply Stage 1 SQL on disposable local database
212
+ run: |
213
+ for migration in /tmp/finora-oracle-migrations/*.sql; do
214
+ PGPASSWORD=postgres psql -h 127.0.0.1 -p 54322 -U postgres -d postgres -X -v ON_ERROR_STOP=1 -f "$migration"
215
+ done
216
+ - name: Sale — independently compare 1000 source postings, seed 20261017 and enforce
217
+ run: node scripts/phase1a-autopost-oracle.mjs sale
scripts/phase1a-autopost-oracle.mjs
new
+86
@@ -0,0 +1,86 @@
1
+#!/usr/bin/env node
2
+// FINORA Stage1 source oracle — independent JS arithmetic, isolated Postgres only.
3
+import {spawnSync} from 'node:child_process';
4
+import fs from 'node:fs';
5
+import os from 'node:os';
6
+import path from 'node:path';
7
+const kind=process.argv[2],N=1000,seed=20261017;
8
+if(kind!=='sale'&&kind!=='purchase')throw Error('Use sale or purchase');
9
+let x=seed;const rand=()=>{x^=x<<13;x^=x>>>17;x^=x<<5;return x>>>0};
10
+const pick=n=>rand()%n,div=n=>Math.floor((n+50)/100);
11
+const uid='aaaa1111-1111-4111-8111-111111111111';
12
+const quote=z=>"'"+String(z).replaceAll("'","''")+"'";
13
+const specs=[
14
+ ['CASH','1101','cash_default','asset','debit'],
15
+ ['AR','1102','receivable_control','asset','debit'],
16
+ ['REV','4101','revenue_default','revenue','credit'],
17
+ ['VATP','2102','vat_payable','liability','credit'],
18
+ ['PUR','5101','purchase_default','expense','debit'],
19
+ ['AP','2101','payable_control','liability','credit'],
20
+ ['VATR','1108','vat_recoverable','asset','debit']];
21
+const binds=Object.fromEntries(specs.map(a=>[a[2],a[0]]));
22
+const samples=[];
23
+for(let i=0;i<N;i++){
24
+ const items=Array.from({length:1+pick(4)},()=>{const qty=1+pick(8),price=50+pick(6000);return{qty,price,lineTotal:qty*price}});
25
+ const subtotal=items.reduce((s,z)=>s+z.lineTotal,0);
26
+ const discountType=pick(2)?'percent':'fixed';
27
+ const discountInput=discountType==='percent'?pick(21):pick(Math.max(1,Math.floor(subtotal/4)));
28
+ const discount=Math.min(subtotal,discountType==='percent'?div(subtotal*discountInput):discountInput);
29
+ const net=subtotal-discount,vatMode=pick(3)===0?'none':'with_vat';
30
+ const vatType=pick(2)?'percent':'fixed';
31
+ const vatRate=vatMode==='none'?0:vatType==='percent'?pick(20):1+pick(1000);
32
+ const vat=vatMode==='none'?0:vatType==='percent'?div(net*vatRate):vatRate;
33
+ const grandTotal=net+vat,paymentMethod=pick(2)?'credit':'cash';
34
+ const source={companyId:'COMP_ORACLE',kind:vatMode==='none'?'non_formal':'formal',paymentMethod,
35
+ items,subtotal,discount,discountType,discountInput,vatMode,vatType,vatRate,vat,grandTotal,
36
+ accountingVersion:1,currencyCode:'IRR'};
37
+ const lines=kind==='sale'?
38
+ [{accountId:paymentMethod==='credit'?'AR':'CASH',debit:grandTotal,credit:0},
39
+ {accountId:'REV',debit:0,credit:net},
40
+ ...(vat?[{accountId:'VATP',debit:0,credit:vat}]:[])]:
41
+ [{accountId:'PUR',debit:net,credit:0},
42
+ ...(vat?[{accountId:'VATR',debit:vat,credit:0}]:[]),
43
+ {accountId:paymentMethod==='credit'?'AP':'CASH',debit:0,credit:grandTotal}];
44
+ samples.push({source,lines});
45
+}
46
+const sql=["\\set ON_ERROR_STOP on","BEGIN;"];
47
+sql.push("INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data) VALUES("+quote(uid)+",'00000000-0000-0000-0000-000000000000','authenticated','authenticated','oracle@example.invalid',now(),'{}'::jsonb);");
48
+sql.push("DO $t$ BEGIN PERFORM set_config('oracle.org',(SELECT organization_id::text FROM public.organization_members WHERE user_id="+quote(uid)+" LIMIT 1),true);END $t$;");
49
+const org="current_setting('oracle.org')::uuid";
50
+sql.push("INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES ("+org+","+quote(uid)+",'companies','COMP_ORACLE','{\"name\":\"Oracle Company\"}'::jsonb),("+org+","+quote(uid)+",'fiscalYears','FY_ORACLE','{\"companyId\":\"COMP_ORACLE\",\"startDate\":\"1405/01/01\",\"endDate\":\"1405/12/29\",\"status\":\"open\"}'::jsonb);");
51
+for(const [id,accountCode,role,type,nature] of specs){
52
+ const data={companyId:'COMP_ORACLE',postingAllowed:true,active:true,code:accountCode,
53
+ title:'Oracle '+role,normalBalance:nature,accountType:type,systemRole:role,
54
+ level:'detail',parentId:'PARENT'};
55
+ sql.push("INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES ("+org+","+quote(uid)+",'accounts',"+quote(id)+","+quote(JSON.stringify(data))+"::jsonb);");
56
+}
57
+sql.push("INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode) VALUES("+org+",'enforce');");
58
+const coll=kind==='sale'?'invoices':'purchases';
59
+const sourceRows=samples.map((z,i)=>"("+org+","+quote(uid)+","+quote(coll)+","+quote('SRC_'+kind+'_'+i)+","+quote(JSON.stringify(z.source))+"::jsonb)").join(",\n");
60
+sql.push("INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES "+sourceRows+";");
61
+sql.push("SET LOCAL ROLE authenticated;");
62
+sql.push("DO $t$ BEGIN PERFORM set_config('request.jwt.claim.sub',"+quote(uid)+",true); IF private.finora_phase1a_mode("+org+")<>'enforce' THEN RAISE EXCEPTION 'FINORA_GUARD_NOT_ENFORCE';END IF;RAISE NOTICE 'FINORA_ORACLE_GUARD_ENFORCE_CONFIRMED';END $t$;");
63
+sql.push("DO $t$ BEGIN PERFORM public.finora_phase1a_publish_role_assignments("+org+",'COMP_ORACLE',"+quote(JSON.stringify(binds))+"::jsonb,0,'Owner oracle mapping approved');END $t$;");
64
+for(let i=0;i<N;i++){
65
+ const src='SRC_'+kind+'_'+i;
66
+ const header={companyId:'COMP_ORACLE',fiscalYearId:'FY_ORACLE',date:'1405/07/24',sourceType:kind,sourceId:src,sourceVersion:'1'};
67
+ sql.push("SELECT jsonb_build_object('i',"+i+",'r',public.finora_journal_autopost("+org+","+quote('J_'+kind+'_'+i)+","+quote(coll)+","+quote(src)+","+quote(JSON.stringify(header))+"::jsonb,NULL));");
68
+}
69
+sql.push("DO $t$ BEGIN IF (SELECT count(*) FROM public.records WHERE organization_id="+org+" AND collection='journalVouchers' AND data->>'sourceType'="+quote(kind)+" AND data->>'status'='posted')<>"+N+" THEN RAISE EXCEPTION 'FINORA_ORACLE_COUNT_INVALID';END IF;END $t$;");
70
+sql.push("ROLLBACK;");
71
+const file=path.join(os.tmpdir(),'finora-oracle-'+kind+'-'+process.pid+'.sql');
72
+fs.writeFileSync(file,sql.join('\n')+'\n');
73
+const p=spawnSync('psql',['-X','-qAt','-h','127.0.0.1','-p','54322','-U','postgres','-d','postgres','-v','ON_ERROR_STOP=1','-f',file],{encoding:'utf8',env:{...process.env,PGPASSWORD:'postgres'},timeout:1800000,maxBuffer:15*1024*1024});
74
+fs.rmSync(file,{force:true});
75
+if(p.status!==0||p.error){console.error((p.stderr||'').slice(-5000));throw Error('ORACLE_DATABASE_FAILED '+String(p.error||p.status));}
76
+if(!(p.stderr||'').includes('FINORA_ORACLE_GUARD_ENFORCE_CONFIRMED'))throw Error('GUARD_MODE_NOT_PROVEN');
77
+const rows=(p.stdout||'').trim().split('\n').filter(Boolean).map(s=>JSON.parse(s));
78
+if(rows.length!==N)throw Error('ORACLE_ROW_COUNT '+rows.length);
79
+const normalize=z=>z.map(l=>[l.accountId,l.debit,l.credit].join(':')).sort().join('|');
80
+for(const row of rows){
81
+ const actual=row.r?.computedLines,expected=samples[row.i]?.lines;
82
+ if(!actual||!expected||row.r?.voucher?.status!=='posted'||row.r?.contractVersion!==1||normalize(actual)!==normalize(expected)){
83
+ throw Error('ORACLE_MISMATCH '+JSON.stringify({index:row.i,actual,expected}));
84
+ }
85
+}
86
+console.log(JSON.stringify({result:'INDEPENDENT_ORACLE_PASS',kind,seed,cases:N,guard:'enforce',serverGenerated:true,oracleLanguage:'JavaScript',accountCodes:'realistic'}));
supabase/tests/phase1a_stage1_account_role_controls.sql
new
+170
@@ -0,0 +1,170 @@
1
+-- Stage 1 SQL behavioral suite, disposable Supabase CLI ONLY.
2
+-- Roll back ALL synthetic users and ledger rows after checks.
3
+\set ON_ERROR_STOP on
4
+BEGIN;
5
+INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6
+VALUES
7
+('aaaa1111-1111-4111-8111-111111111111','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-a@example.invalid',now(),'{}'::jsonb),
8
+('bbbb2222-2222-4222-8222-222222222222','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-b@example.invalid',now(),'{}'::jsonb),
9
+('cccc3333-3333-4333-8333-333333333333','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-member-c@example.invalid',now(),'{}'::jsonb);
10
+SELECT set_config('finora_test.org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='aaaa1111-1111-4111-8111-111111111111' LIMIT 1),true);
11
+SELECT set_config('finora_test.org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='bbbb2222-2222-4222-8222-222222222222' LIMIT 1),true);
12
+-- Admin creates synthetic base chart so client/server validations use real scopes.
13
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
14
+SELECT m.organization_id,m.user_id,'companies','COMP_STAGE_1',jsonb_build_object('name','Stage1 Test Co')
15
+FROM public.organization_members m WHERE m.user_id IN
16
+('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
17
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
18
+SELECT m.organization_id,m.user_id,'fiscalYears','FY_STAGE_1',
19
+ jsonb_build_object('companyId','COMP_STAGE_1','startDate','1405/01/01','endDate','1405/12/29','status','open')
20
+FROM public.organization_members m WHERE m.user_id IN
21
+('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
22
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
23
+SELECT m.organization_id,m.user_id,'accounts','ACC_STAGE_'||n,
24
+ jsonb_build_object('companyId','COMP_STAGE_1','postingAllowed',true,'active',true,
25
+ 'code',CASE WHEN n=1 THEN '1101' ELSE '4101' END,
26
+ 'title',CASE WHEN n=1 THEN 'صندوق و بانک' ELSE 'درآمد فروش' END,
27
+ 'normalBalance',CASE WHEN n=1 THEN 'debit' ELSE 'credit' END,
28
+ 'accountType',CASE WHEN n=1 THEN 'asset' ELSE 'revenue' END,
29
+ 'systemRole',CASE WHEN n=1 THEN 'cash_default' ELSE 'revenue_default' END,
30
+ 'level','detail','parentId',CASE WHEN n=1 THEN '11' ELSE '41' END)
31
+FROM public.organization_members m CROSS JOIN generate_series(1,2) n WHERE m.user_id IN
32
+('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
33
+INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
34
+SELECT organization_id,'enforce' FROM public.organization_members
35
+WHERE user_id IN ('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
36
+-- Fixture seat capacity is raised ONLY inside this rolling-back local test;
37
+-- the production license and its max_users are never accessed or changed.
38
+UPDATE public.licenses SET max_users=GREATEST(max_users,3)
39
+ WHERE organization_id=current_setting('finora_test.org_a')::uuid;
40
+-- C joins org A and has commerce:create ONLY; no accounting:approve.
41
+INSERT INTO public.organization_members(organization_id,user_id,status,is_owner)
42
+VALUES (current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333','active',false);
43
+INSERT INTO public.organization_roles(organization_id,role_key,title,is_system,active)
44
+VALUES(current_setting('finora_test.org_a')::uuid,'phase1a_commerce_only','Test commerce create',false,true);
45
+INSERT INTO public.organization_role_permissions(organization_id,role_id,module_key,capabilities)
46
+SELECT organization_id,id,'commerce',ARRAY['create','read']::text[]
47
+FROM public.organization_roles WHERE role_key='phase1a_commerce_only'
48
+AND organization_id=current_setting('finora_test.org_a')::uuid;
49
+INSERT INTO public.organization_member_roles(organization_id,member_id,role_id)
50
+SELECT m.organization_id,m.id,r.id FROM public.organization_members m
51
+JOIN public.organization_roles r ON r.organization_id=m.organization_id
52
+WHERE m.user_id='cccc3333-3333-4333-8333-333333333333'
53
+AND m.organization_id=current_setting('finora_test.org_a')::uuid AND r.role_key='phase1a_commerce_only';
54
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
55
+VALUES(current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333',
56
+'invoices','SOURCE_C_1','{"companyId":"COMP_STAGE_1","kind":"formal","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
57
+-- A pro-forma document must never post as a sale.
58
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
59
+VALUES(current_setting('finora_test.org_a')::uuid,
60
+ 'cccc3333-3333-4333-8333-333333333333',
61
+ 'invoices','SOURCE_C_PROFORMA','{"companyId":"COMP_STAGE_1","kind":"proforma","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
62
+
63
+
64
+INSERT INTO public.records(organization_id,owner_id,collection,id,data)
65
+VALUES(current_setting('finora_test.org_a')::uuid,'aaaa1111-1111-4111-8111-111111111111',
66
+'postingProfiles','PP_TEST',
67
+'{"companyId":"COMP_STAGE_1","kind":"sale","debitAccountId":"ACC_STAGE_1","creditAccountId":"ACC_STAGE_2","active":true}'::jsonb);
68
+INSERT INTO public.member_module_permissions(organization_id,member_id,module_key,capabilities)
69
+SELECT organization_id,id,'accounting',ARRAY['read','create','edit']::text[]
70
+FROM public.organization_members
71
+WHERE organization_id=current_setting('finora_test.org_a')::uuid
72
+AND user_id='cccc3333-3333-4333-8333-333333333333';
73
+DO $q$ BEGIN
74
+ IF private.finora_phase1a_mode(current_setting('finora_test.org_a')::uuid)<>'enforce' THEN
75
+ RAISE EXCEPTION 'FINORA_ROLE_GUARD_NOT_ENFORCE';END IF;END $q$;
76
+SET LOCAL ROLE authenticated;
77
+SELECT set_config('request.jwt.claim.sub','cccc3333-3333-4333-8333-333333333333',true);
78
+DO $q$
79
+DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
80
+BEGIN
81
+ BEGIN
82
+ PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
83
+ 'collection','accounts','id','ACC_STAGE_1','expected_version',1,
84
+ 'data',(SELECT data||'{"normalBalance":"credit"}'::jsonb FROM public.records
85
+ WHERE organization_id=org AND collection='accounts' AND id='ACC_STAGE_1'))),
86
+ '[]'::jsonb,org);
87
+ RAISE EXCEPTION 'FINORA_BAD_ACCOUNT_WRITE_ACCEPTED';
88
+ EXCEPTION WHEN insufficient_privilege THEN
89
+ IF SQLERRM NOT LIKE '%FINORA_ACCOUNT_MAPPING_SYNC_FORBIDDEN%' THEN RAISE;END IF;
90
+ END;
91
+ BEGIN
92
+ PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
93
+ 'collection','postingProfiles','id','PP_TEST','expected_version',1,
94
+ 'data',(SELECT data||'{"creditAccountId":"ACC_STAGE_1"}'::jsonb FROM public.records
95
+ WHERE organization_id=org AND collection='postingProfiles' AND id='PP_TEST'))),
96
+ '[]'::jsonb,org);
97
+ RAISE EXCEPTION 'FINORA_BAD_PROFILE_WRITE_ACCEPTED';
98
+ EXCEPTION WHEN insufficient_privilege THEN
99
+ IF SQLERRM NOT LIKE '%FINORA_ACCOUNT_MAPPING_SYNC_FORBIDDEN%' THEN RAISE;END IF;
100
+ END;
101
+ BEGIN
102
+ PERFORM public.finora_phase1a_publish_role_assignments(org,'COMP_STAGE_1',
103
+ '{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2"}',0,'Member denied');
104
+ RAISE EXCEPTION 'FINORA_NONOWNER_ROLE_PUBLISH_ACCEPTED';
105
+ EXCEPTION WHEN insufficient_privilege THEN
106
+ IF SQLERRM NOT LIKE '%FINORA_ROLE_ASSIGNMENT_OWNER_REQUIRED%' THEN RAISE;END IF;
107
+ END;
108
+END $q$;
109
+RESET ROLE;
110
+UPDATE private.finora_phase1a_guard_modes SET mode='audit'
111
+ WHERE organization_id=current_setting('finora_test.org_a')::uuid;
112
+DO $q$ BEGIN
113
+ IF private.finora_phase1a_mode(current_setting('finora_test.org_a')::uuid)<>'audit' THEN
114
+ RAISE EXCEPTION 'FINORA_ROLE_GUARD_NOT_AUDIT';END IF;END $q$;
115
+SET LOCAL ROLE authenticated;
116
+DO $q$
117
+DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
118
+BEGIN
119
+ PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
120
+ 'collection','accounts','id','ACC_STAGE_1','expected_version',1,
121
+ 'data',(SELECT data||'{"normalBalance":"credit"}'::jsonb FROM public.records
122
+ WHERE organization_id=org AND collection='accounts' AND id='ACC_STAGE_1'))),
123
+ '[]'::jsonb,org);
124
+ PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
125
+ 'collection','postingProfiles','id','PP_TEST','expected_version',1,
126
+ 'data',(SELECT data||'{"debitAccountId":"ACC_STAGE_2"}'::jsonb FROM public.records
127
+ WHERE organization_id=org AND collection='postingProfiles' AND id='PP_TEST'))),
128
+ '[]'::jsonb,org);
129
+END $q$;
130
+RESET ROLE;
131
+DO $q$ BEGIN
132
+ IF (SELECT count(*) FROM private.finora_phase1a_journal_audit
133
+ WHERE organization_id=current_setting('finora_test.org_a')::uuid
134
+ AND action='guard_violation'
135
+ AND reason LIKE 'FINORA_DIRECT_ACCOUNT_MAPPING_WRITE%')<2 THEN
136
+ RAISE EXCEPTION 'FINORA_ROLE_AUDIT_MISSING';END IF;END $q$;
137
+UPDATE public.records SET data=data||'{"normalBalance":"debit"}'::jsonb
138
+WHERE organization_id=current_setting('finora_test.org_a')::uuid
139
+AND collection='accounts' AND id='ACC_STAGE_1';
140
+UPDATE private.finora_phase1a_guard_modes SET mode='enforce'
141
+ WHERE organization_id=current_setting('finora_test.org_a')::uuid;
142
+SET LOCAL ROLE authenticated;
143
+SELECT set_config('request.jwt.claim.sub','aaaa1111-1111-4111-8111-111111111111',true);
144
+DO $q$
145
+DECLARE r jsonb;
146
+BEGIN
147
+ r:=public.finora_phase1a_publish_role_assignments(
148
+ current_setting('finora_test.org_a')::uuid,'COMP_STAGE_1',
149
+ '{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2"}',0,
150
+ 'Owner-approved initial account mapping');
151
+ IF (r->>'version')::bigint<>1 THEN RAISE EXCEPTION 'FINORA_OWNER_PUBLISH_VERSION';END IF;
152
+ BEGIN
153
+ PERFORM public.finora_phase1a_publish_role_assignments(
154
+ current_setting('finora_test.org_a')::uuid,'COMP_STAGE_1',
155
+ '{"cash_default":"ACC_STAGE_2"}',1,'Invalid account role');
156
+ RAISE EXCEPTION 'FINORA_INVALID_ACCOUNT_PUBLISHED';
157
+ EXCEPTION WHEN check_violation THEN
158
+ IF SQLERRM NOT LIKE '%FINORA_POSTING_ACCOUNT_ROLE_INVALID%' THEN RAISE;END IF;
159
+ END;
160
+END $q$;
161
+RESET ROLE;
162
+DO $q$ BEGIN
163
+ IF NOT EXISTS(SELECT 1 FROM private.finora_phase1a_account_role_audit
164
+ WHERE organization_id=current_setting('finora_test.org_a')::uuid
165
+ AND version=1 AND action='publish'
166
+ AND actor_id='aaaa1111-1111-4111-8111-111111111111') THEN
167
+ RAISE EXCEPTION 'FINORA_PUBLISH_AUDIT_MISSING';END IF;
168
+ RAISE NOTICE 'FINORA_ACCOUNT_ROLE_GUARDS_PASS';
169
+END $q$;
170
+ROLLBACK;