سامانه صدور فاکتور و حسابداری
Enforce real-DOM and accounting verification gates
davoodmehraban89 committed
Sep 29, 2026 at 20:22 UTC
55b62db07fe31f6ebd3d45f22ce510946cd02ba8
18 files changed
+484
-17
.github/workflows/quality.yml
+10
-1
@@ -24,4 +24,13 @@ jobs:
24
run: node scripts/phase3-check.mjs
25
- name: Phase 3 behavioral accounting scenarios
26
run: node scripts/phase3-behavior-check.mjs
27
- node scripts/phase4-behavior-check.mjs
27
+ - name: Phase 4 accounting invariants
28
+ run: node scripts/phase4-behavior-check.mjs
29
+ - name: Install browser smoke-test runtime
30
+ run: |
31
+ npm install --no-save @playwright/test@1.55.0
32
+ npx playwright install --with-deps chromium
33
+ - name: Real DOM smoke
34
+ run: |
35
+ python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
36
+ npx playwright test scripts/dom-smoke.spec.js --reporter=line --workers=1
PROJECT_STATE.md
+2
-2
@@ -32,7 +32,7 @@ Before doing any project work:
32
10. If this file conflicts with verified remote code/database evidence, correct this file immediately and record the correction in the change ledger.
33
34
## Current change ledger
35
-| 2026-09-29 | Adopt owner-specified high-assurance execution protocol: verify live GitHub/Supabase before work; latest chat is the only source of new instructions; record requests before implementation; vertical slices; PROJECT_STATE in every durable commit; archive every future Supabase migration SQL; require real-DOM smoke + accounting-invariant tests before COMPLETED; explicitly list NOT VERIFIED items. | IN PROGRESS | Live reconciliation found head `7d054dfa` (post-login/admin-shell fix) was not recorded here; its CI is green but real-DOM smoke was not run. Phase 4 CI workflow also did not actually execute `phase4-behavior-check.mjs` because the command was folded onto the Phase 3 command, and no `supabase/migrations/` SQL archive exists. Phase 4 completion is therefore reopened pending real-DOM + accounting-invariant verification. No schema/RLS/auth/role change authorized by this request. |
35
+| 2026-09-29 | Adopt owner-specified high-assurance execution protocol: verify live GitHub/Supabase before work; latest chat is the only source of new instructions; record requests before implementation; vertical slices; PROJECT_STATE in every durable commit; archive every future Supabase migration SQL; require real-DOM smoke + accounting-invariant tests before COMPLETED; explicitly list NOT VERIFIED items. | IN PROGRESS | Live reconciliation found head `7d054dfa` (post-login/admin-shell fix) was not recorded here; its CI is green but real-DOM smoke was not run. Phase 4 CI workflow also did not actually execute `phase4-behavior-check.mjs` because the command was folded onto the Phase 3 command, and no `supabase/migrations/` SQL archive exists. Phase 4 completion is therefore reopened pending real-DOM + accounting-invariant verification. Verification slice prepared atomically: corrected CI command separation, strengthened Phase 4 posting/reversal accounting test, added Playwright real-DOM post-login/shell smoke, and backfilled exact historical SQL files from `supabase_migrations.schema_migrations`. No database/schema/RLS/auth/role mutation was performed. CI for this slice is pending. |
36
| 2026-09-29 | Execute master roadmap Phase 4 end-to-end: projects/contracts, amendments/lifecycle, employer/contractor/subcontractor links, deductions, guarantees, contractor statements/accounting, traceability, reporting, permissions/audit/sync/backup/migration/tests/reconciliation. | IN PROGRESS | Phase 4 implementation exists, but completion was reopened under the owner’s stricter acceptance rule: real-DOM smoke and actual Phase 4 accounting-invariant execution are still required. Prior evidence: domain/UI `c2100228`; persistence/navigation/backup through `172aeb59`; referential guards `44154769`; behavioral CI gate `fe29b817`; deduction-specific accounting/template migration `dd3b78ed`; verification doc `e5b814a7`. Supabase migration `20260929091743 phase4_contracting_collections` applied; RLS owner isolation verified; production had zero pre-existing Phase 4 rows requiring backfill; performance advisor clean; known pre-existing security warnings unchanged. Acceptance checkpoint `95e6de99`: Quality 36549015911 success; Security/CodeQL 36549015935 success; Pages 36549015796 success. |
37
| 2026-09-29 | Consolidate top-level Sales, Purchases, and People navigation into a single `بازرگانی` module while preserving the underlying views and workflows. | COMPLETED | Top-level `sales`, `purchases`, `people` rail entries removed; `commerce`/بازرگانی added with فروش، خرید، اشخاص submenu and canonical view mappings. Quality run 36545021724 success; Pages run 36545024472 success; Security/CodeQL run 36545021744 success. |
38
| 2026-09-29 | Restore invoice print contract: formal sales invoice = A4 landscape, pre-invoice = A4 landscape, non-formal invoice = A5 landscape; preserve standard print margins and page fit. | COMPLETED | `js/print.js` fixed on main: formal/pre-invoice A4 landscape with 5mm print margin; non-formal A5 landscape with 5mm margin; page-fit widths set to printable landscape areas. Regression gates updated in `scripts/quality-check.mjs` and `scripts/phase3-check.mjs`. Implementation commits `a7e14ec1`, `baa46715`, gate correction `4550f239`; Quality run 36544154873 success; Pages run 36544154397 success. Final checkpoint head `75cf79e5` re-verified: Quality run 36544278076 success; Security/CodeQL run 36544278147 success; Pages deployment run 36544277692 success. |\n
@@ -288,7 +288,7 @@ Complementary ERP/integration:
288
- no destructive historical migration without preview/reconciliation/rollback
289
290
## Known verification boundary
291
-The execution environment used for these phases did not provide an authenticated interactive browser/device walkthrough. Do not claim browser E2E or physical-printer validation unless actually performed. CI, source verification, Supabase checks and Pages deployment were used as release evidence.
291
+A real Chromium DOM smoke is now required in CI for completion claims; it exercises the rendered login shell and a stubbed post-login transition without production credentials. Authenticated production-user E2E and physical-printer validation remain NOT VERIFIED unless explicitly run.
292
293
## Successor startup procedure
294
1. Connect official GitHub and Supabase tools.
scripts/dom-smoke.spec.js
new
+2
@@ -0,0 +1,2 @@
1
+const {test,expect}=require('@playwright/test');
2
+test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('#view-contracting')).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
scripts/phase4-behavior-check.mjs
+11
-14
@@ -1,16 +1,13 @@
1
import fs from 'node:fs';import vm from 'node:vm';
2
const code=fs.readFileSync('js/phase4-contracting.js','utf8');
3
-const ds={contracts:[],contractAmendments:[],contractParties:[],contractDeductions:[],guarantees:[],guaranteeEvents:[],contractStatements:[],phase4Audit:[],expenses:[],purchases:[]};
4
-const ctx={console,datastore:ds,currentUser:{id:'u1'},afCompanyId:()=> 'c1',getMyGlobalProjects:()=>[{id:'p1',name:'P'}],getMyContacts:()=>[{id:'e1',name:'E'},{id:'k1',name:'K'}],getMyJournalVouchers:()=>[],getMyExpenses:()=>ds.expenses,getMyPurchases:()=>ds.purchases,esc:String,requireWrite:()=>true,saveDatastore:()=>true,renderPhase4:()=>{},alert:()=>{},getJalaliNumeric:()=> '1405/07/07',toEnDigits:String,document:{getElementById:()=>null},afNeedCompany:()=> 'c1',jeAccountByCode:()=>null,jeRevenueAccount:()=>null,jeDimensionAssignmentsForContext:()=>[],jeCreateDraft:()=>{},jePost:()=>{},jeReverse:()=>{},prompt:()=>null,Date,Math};
5
-vm.createContext(ctx);vm.runInContext(code,ctx);
6
-ds.contracts.push({id:'c',ownerUserId:'u1',companyId:'c1',baseAmount:1000,status:'active',projectId:'p1',employerId:'e1',contractorId:'k1'});
7
-ds.contractAmendments.push({id:'a',ownerUserId:'u1',companyId:'c1',contractId:'c',amountDelta:250,status:'approved'},{id:'b',ownerUserId:'u1',companyId:'c1',contractId:'c',amountDelta:500,status:'draft'});
8
-if(ctx.p4EffectiveValue(ds.contracts[0])!==1250)throw new Error('approved amendment value failed');
9
-if(ctx.p4StatementNet({grossAmount:1000,deductionAmount:150})!==850)throw new Error('statement net failed');
10
-if(ctx.p4ContractLocked(ds.contracts[0]))throw new Error('active contract locked');
11
-ds.expenses.push({ownerUserId:'u1',projectId:'p1',kind:'expense',amount:100});ds.purchases.push({ownerUserId:'u1',projectId:'p1',grandTotal:200});
12
-ds.contractStatements.push({ownerUserId:'u1',companyId:'c1',contractId:'c',status:'posted',grossAmount:1000});
13
-const pr=ctx.p4ContractProfit(ds.contracts[0]);if(pr.revenue!==1000||pr.cost!==300||pr.profit!==700)throw new Error('profitability reconciliation failed');
14
-for(const accountCode of ["'1105'","'1106'","'1107'","'2105'","'6109'"])if(!code.includes(accountCode))throw new Error('deduction account mapping missing '+accountCode);
15
-for(const token of ['p4PostStatement','p4ReverseStatement','p4Audit','contractDeductions','guaranteeEvents'])if(!code.includes(token))throw new Error('missing '+token);
16
-console.log('Phase 4 behavior checks passed');
3
+const ds={contracts:[],contractAmendments:[],contractParties:[],contractDeductions:[],guarantees:[],guaranteeEvents:[],contractStatements:[],phase4Audit:[],expenses:[],purchases:[]},vouchers=[];let draftArgs=null,alertMessage='';
4
+const accounts=Object.fromEntries([['1102','AR'],['4301','CONTRACT_REVENUE'],['1105','RETENTION'],['1106','INSURANCE'],['1107','WITHHOLDING_TAX'],['2105','ADVANCE'],['6109','PENALTY']].map(([code,id])=>[code,{id,code,postingAllowed:true,active:true}]));
5
+const ctx={console,datastore:ds,currentUser:{id:'u1'},afCompanyId:()=> 'c1',getMyGlobalProjects:()=>[{id:'p1',name:'P'}],getMyContacts:()=>[{id:'e1',name:'Employer'},{id:'k1',name:'Contractor'}],getMyJournalVouchers:()=>vouchers,getMyExpenses:()=>ds.expenses,getMyPurchases:()=>ds.purchases,esc:String,requireWrite:()=>true,saveDatastore:()=>true,renderPhase4:()=>{},alert:m=>{alertMessage=String(m)},getJalaliNumeric:()=> '1405/07/07',toEnDigits:String,document:{getElementById:()=>null},afNeedCompany:()=> 'c1',jeAccountByCode:c=>accounts[c]||null,jeRevenueAccount:()=>accounts['4301'],jeDimensionAssignmentsForContext:(accountId,context)=>[{dimensionTypeId:'project',dimensionValueId:context.projectId},{dimensionTypeId:'contact',dimensionValueId:context.contactId}],jeCreateDraft:args=>{draftArgs=args;const d=args.lines.reduce((s,x)=>s+Number(x.debit||0),0),c=args.lines.reduce((s,x)=>s+Number(x.credit||0),0);if(d!==c)throw new Error('unbalanced draft');const v={id:'JV1',status:'draft',...args};vouchers.push(v);return v},jePost:id=>{const v=vouchers.find(x=>x.id===id);if(!v)throw new Error('voucher missing');v.status='posted';v.postedAt='2026-09-29T00:00:00Z';return v},jeReverse:(id,date,reason)=>{const v=vouchers.find(x=>x.id===id);if(!v||v.status!=='posted')throw new Error('invalid reversal');v.status='reversed';const rv={id:'JV2',status:'posted',reversalOf:id,date,reason,postedAt:'2026-09-29T00:01:00Z'};vouchers.push(rv);return rv},prompt:()=>null,Date,Math};
6
+vm.createContext(ctx);vm.runInContext(code,ctx);const assert=(ok,msg)=>{if(!ok)throw new Error(msg)};
7
+const contract={id:'c',ownerUserId:'u1',companyId:'c1',number:'CTR-1',baseAmount:1000,status:'active',projectId:'p1',employerId:'e1',contractorId:'k1'};ds.contracts.push(contract);ds.contractAmendments.push({id:'a',ownerUserId:'u1',companyId:'c1',contractId:'c',amountDelta:250,status:'approved'},{id:'b',ownerUserId:'u1',companyId:'c1',contractId:'c',amountDelta:500,status:'draft'});assert(ctx.p4EffectiveValue(contract)===1250,'approved amendment value failed');
8
+const deductionLines=[{type:'retention',title:'retention',amount:50},{type:'insurance',title:'insurance',amount:20},{type:'withholding_tax',title:'tax',amount:30},{type:'advance_recovery',title:'advance',amount:40},{type:'penalty',title:'penalty',amount:10}],statement={id:'s1',ownerUserId:'u1',companyId:'c1',contractId:'c',projectId:'p1',number:'CTR-1-1',date:'1405/07/07',grossAmount:1000,deductionLines,deductionAmount:150,netAmount:850,status:'draft',accountingVersion:1};ds.contractStatements.push(statement);
9
+ctx.p4PostStatement('s1');assert(!alertMessage,'posting raised alert: '+alertMessage);assert(statement.status==='posted'&&statement.journalVoucherId==='JV1','statement posting lifecycle failed');assert(draftArgs.sourceType==='contract_statement'&&draftArgs.sourceId==='s1'&&draftArgs.sourceVersion===1,'source traceability failed');
10
+const debits=draftArgs.lines.reduce((s,x)=>s+Number(x.debit||0),0),credits=draftArgs.lines.reduce((s,x)=>s+Number(x.credit||0),0);assert(debits===1000&&credits===1000,'contract statement must balance');
11
+for(const id of ['AR','CONTRACT_REVENUE','RETENTION','INSURANCE','WITHHOLDING_TAX','ADVANCE','PENALTY'])assert(draftArgs.lines.some(x=>x.accountId===id),'missing posting account '+id);assert(draftArgs.lines.every(x=>x.dimensions.some(d=>d.dimensionValueId==='p1')),'project dimension traceability missing');
12
+ctx.p4ReverseStatement('s1');assert(statement.status==='reversed'&&statement.reversalVoucherId==='JV2','reversal lifecycle failed');assert(vouchers[0].status==='reversed'&&vouchers[1].reversalOf==='JV1','voucher reversal traceability failed');
13
+ds.expenses.push({ownerUserId:'u1',projectId:'p1',kind:'expense',amount:100});ds.purchases.push({ownerUserId:'u1',projectId:'p1',grandTotal:200});statement.status='posted';const pr=ctx.p4ContractProfit(contract);assert(pr.revenue===1000&&pr.cost===300&&pr.profit===700,'profitability reconciliation failed');assert(ds.phase4Audit.some(x=>x.entityId==='s1'&&x.action==='posted')&&ds.phase4Audit.some(x=>x.entityId==='s1'&&x.action==='reversed'),'audit lifecycle missing');console.log('Phase 4 accounting invariants passed.');
supabase/migrations/20260921082958_finora_core_schema_auth_licenses_rls.sql
new
+219
@@ -0,0 +1,219 @@
1
+-- ============ Identity & licensing ============
2
+create table public.profiles (
3
+ id uuid primary key references auth.users(id) on delete cascade,
4
+ username text not null unique check (username ~ '^[a-z0-9_.]{3,32}$'),
5
+ role text not null default 'user' check (role in ('user','admin')),
6
+ created_at timestamptz not null default now()
7
+);
8
+
9
+create table public.licenses (
10
+ user_id uuid primary key references public.profiles(id) on delete cascade,
11
+ plan text not null check (plan in ('trial','monthly','three_months','annual','lifetime')),
12
+ status text not null check (status in ('trial','active','cancelled')),
13
+ starts_at date not null default current_date,
14
+ ends_at date not null,
15
+ updated_at timestamptz not null default now()
16
+);
17
+
18
+create or replace function public.is_admin() returns boolean
19
+language sql stable security definer set search_path = public as $$
20
+ select exists (select 1 from public.profiles where id = auth.uid() and role = 'admin');
21
+$$;
22
+
23
+create or replace function public.has_active_license() returns boolean
24
+language sql stable security definer set search_path = public as $$
25
+ select exists (
26
+ select 1 from public.licenses l
27
+ where l.user_id = auth.uid()
28
+ and l.status in ('trial','active')
29
+ and (l.plan = 'lifetime' or l.ends_at >= (now() at time zone 'Asia/Tehran')::date)
30
+ );
31
+$$;
32
+
33
+-- Role is NEVER read from client-controlled metadata.
34
+create or replace function public.handle_new_user() returns trigger
35
+language plpgsql security definer set search_path = public as $$
36
+declare uname text;
37
+begin
38
+ uname := lower(coalesce(nullif(new.raw_user_meta_data->>'username',''), split_part(new.email,'@',1)));
39
+ insert into public.profiles (id, username, role) values (new.id, uname, 'user');
40
+ insert into public.licenses (user_id, plan, status, starts_at, ends_at)
41
+ values (new.id, 'trial', 'trial', current_date, current_date + 15);
42
+ return new;
43
+end $$;
44
+
45
+create trigger on_auth_user_created
46
+ after insert on auth.users for each row execute function public.handle_new_user();
47
+
48
+create or replace function public.admin_set_license(target uuid, new_plan text, days int default null, new_status text default 'active')
49
+returns void language plpgsql security definer set search_path = public as $$
50
+declare d int;
51
+begin
52
+ if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;
53
+ if new_plan not in ('trial','monthly','three_months','annual','lifetime') then raise exception 'invalid plan'; end if;
54
+ d := coalesce(days, case new_plan when 'trial' then 15 when 'monthly' then 30 when 'three_months' then 90 when 'annual' then 365 else 0 end);
55
+ update public.licenses
56
+ set plan = new_plan,
57
+ status = new_status,
58
+ starts_at = current_date,
59
+ ends_at = case when new_plan = 'lifetime' then date '2099-01-01' else current_date + d end,
60
+ updated_at = now()
61
+ where user_id = target;
62
+ if not found then raise exception 'user not found'; end if;
63
+end $$;
64
+
65
+create or replace function public.admin_extend_license(target uuid, days int)
66
+returns void language plpgsql security definer set search_path = public as $$
67
+begin
68
+ if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;
69
+ if days is null or days < 1 or days > 3650 then raise exception 'invalid days'; end if;
70
+ update public.licenses
71
+ set ends_at = greatest(ends_at, current_date) + days,
72
+ status = case when status = 'trial' then 'trial' else 'active' end,
73
+ updated_at = now()
74
+ where user_id = target and plan <> 'lifetime';
75
+ if not found then raise exception 'user not found or lifetime'; end if;
76
+end $$;
77
+
78
+revoke all on function public.is_admin() from public, anon;
79
+revoke all on function public.has_active_license() from public, anon;
80
+revoke all on function public.admin_set_license(uuid,text,int,text) from public, anon;
81
+revoke all on function public.admin_extend_license(uuid,int) from public, anon;
82
+revoke all on function public.handle_new_user() from public, anon, authenticated;
83
+grant execute on function public.is_admin() to authenticated;
84
+grant execute on function public.has_active_license() to authenticated;
85
+grant execute on function public.admin_set_license(uuid,text,int,text) to authenticated;
86
+grant execute on function public.admin_extend_license(uuid,int) to authenticated;
87
+
88
+alter table public.profiles enable row level security;
89
+alter table public.licenses enable row level security;
90
+create policy profiles_select on public.profiles for select to authenticated
91
+ using (id = (select auth.uid()) or public.is_admin());
92
+create policy licenses_select on public.licenses for select to authenticated
93
+ using (user_id = (select auth.uid()) or public.is_admin());
94
+-- No insert/update/delete policies: licenses change only via trigger or admin RPCs.
95
+
96
+-- ============ Business data ============
97
+create table public.companies (
98
+ id uuid primary key default gen_random_uuid(),
99
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
100
+ person_type text not null default 'legal' check (person_type in ('legal','natural')),
101
+ name text not null,
102
+ phone text, national_id text, economic_code text, reg_no text, postal_code text,
103
+ address text, footer text,
104
+ is_default boolean not null default false,
105
+ created_at timestamptz not null default now(),
106
+ unique (id, owner_id)
107
+);
108
+
109
+create table public.parties (
110
+ id uuid primary key default gen_random_uuid(),
111
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
112
+ person_type text not null default 'natural' check (person_type in ('legal','natural')),
113
+ prefix text,
114
+ name text not null,
115
+ role text not null default 'customer' check (role in ('customer','supplier')),
116
+ mobile text, national_id text, economic_code text, reg_no text, postal_code text, address text,
117
+ created_at timestamptz not null default now(),
118
+ unique (id, owner_id)
119
+);
120
+
121
+create table public.items (
122
+ id uuid primary key default gen_random_uuid(),
123
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
124
+ code text,
125
+ title text not null,
126
+ spec text, unit text,
127
+ buy_price bigint not null default 0 check (buy_price >= 0),
128
+ sell_price bigint not null default 0 check (sell_price >= 0),
129
+ internal_id text,
130
+ created_at timestamptz not null default now()
131
+);
132
+create unique index items_owner_code_uq on public.items (owner_id, code) where code is not null and code <> '';
133
+
134
+create table public.invoices (
135
+ id uuid primary key default gen_random_uuid(),
136
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
137
+ company_id uuid,
138
+ party_id uuid,
139
+ number text not null,
140
+ kind text not null default 'informal' check (kind in ('informal','formal','proforma')),
141
+ invoice_date date not null,
142
+ vat_mode text not null default 'none' check (vat_mode in ('none','with_vat')),
143
+ vat_type text not null default 'percent' check (vat_type in ('percent','fixed')),
144
+ vat_rate numeric(8,2) not null default 0 check (vat_rate >= 0),
145
+ discount_type text not null default 'fixed' check (discount_type in ('percent','fixed')),
146
+ discount_input numeric(18,2) not null default 0 check (discount_input >= 0),
147
+ subtotal bigint not null default 0 check (subtotal >= 0),
148
+ discount bigint not null default 0 check (discount >= 0),
149
+ vat bigint not null default 0 check (vat >= 0),
150
+ total bigint not null default 0 check (total >= 0),
151
+ notes text,
152
+ moodian jsonb,
153
+ created_at timestamptz not null default now(),
154
+ updated_at timestamptz not null default now(),
155
+ unique (owner_id, number),
156
+ unique (id, owner_id),
157
+ foreign key (company_id, owner_id) references public.companies (id, owner_id) on delete set null (company_id),
158
+ foreign key (party_id, owner_id) references public.parties (id, owner_id) on delete set null (party_id)
159
+);
160
+
161
+create table public.invoice_lines (
162
+ id uuid primary key default gen_random_uuid(),
163
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
164
+ invoice_id uuid not null,
165
+ position int not null default 0,
166
+ description text not null,
167
+ unit text,
168
+ qty numeric(18,3) not null default 1 check (qty >= 0),
169
+ unit_price bigint not null default 0 check (unit_price >= 0),
170
+ vat_rate numeric(8,2) not null default 0 check (vat_rate >= 0),
171
+ line_total bigint not null default 0 check (line_total >= 0),
172
+ foreign key (invoice_id, owner_id) references public.invoices (id, owner_id) on delete cascade
173
+);
174
+
175
+create table public.cheques (
176
+ id uuid primary key default gen_random_uuid(),
177
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
178
+ direction text not null check (direction in ('received','paid')),
179
+ party_id uuid,
180
+ party_name text,
181
+ sayad_id text check (sayad_id is null or sayad_id ~ '^[0-9]{16}$'),
182
+ bank text,
183
+ amount bigint not null default 0 check (amount >= 0),
184
+ due_date date,
185
+ status text not null default 'open' check (status in ('open','cleared')),
186
+ created_at timestamptz not null default now(),
187
+ foreign key (party_id, owner_id) references public.parties (id, owner_id) on delete set null (party_id)
188
+);
189
+
190
+create table public.ledger_entries (
191
+ id uuid primary key default gen_random_uuid(),
192
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
193
+ kind text not null check (kind in ('expense','income')),
194
+ category text,
195
+ description text,
196
+ amount bigint not null default 0 check (amount >= 0),
197
+ entry_date date not null default current_date,
198
+ created_at timestamptz not null default now()
199
+);
200
+
201
+-- RLS: read always allowed for owner (so expired users can still export);
202
+-- any write requires an ACTIVE license, enforced server-side.
203
+do $$
204
+declare t text;
205
+begin
206
+ foreach t in array array['companies','parties','items','invoices','invoice_lines','cheques','ledger_entries'] loop
207
+ execute format('alter table public.%I enable row level security', t);
208
+ execute format('create index %I on public.%I (owner_id)', t || '_owner_idx', t);
209
+ execute format('create policy %I on public.%I for select to authenticated using (owner_id = (select auth.uid()))', t || '_select', t);
210
+ execute format('create policy %I on public.%I for insert to authenticated with check (owner_id = (select auth.uid()) and public.has_active_license())', t || '_insert', t);
211
+ execute format('create policy %I on public.%I for update to authenticated using (owner_id = (select auth.uid()) and public.has_active_license()) with check (owner_id = (select auth.uid()) and public.has_active_license())', t || '_update', t);
212
+ execute format('create policy %I on public.%I for delete to authenticated using (owner_id = (select auth.uid()) and public.has_active_license())', t || '_delete', t);
213
+ end loop;
214
+end $$;
215
+
216
+create index invoice_lines_invoice_idx on public.invoice_lines (invoice_id);
217
+create index invoices_party_idx on public.invoices (party_id);
218
+create index invoices_company_idx on public.invoices (company_id);
219
+create index cheques_party_idx on public.cheques (party_id);\n
\ No newline at end of file
supabase/migrations/20260921083540_finora_records_store_replace_relational.sql
new
+40
@@ -0,0 +1,40 @@
1
+-- Safety: refuse to drop anything that holds data.
2
+do $$
3
+declare t text; n bigint;
4
+begin
5
+ foreach t in array array['invoice_lines','invoices','cheques','ledger_entries','items','parties','companies'] loop
6
+ execute format('select count(*) from public.%I', t) into n;
7
+ if n > 0 then raise exception 'table % is not empty, aborting', t; end if;
8
+ end loop;
9
+end $$;
10
+
11
+drop table public.invoice_lines, public.invoices, public.cheques, public.ledger_entries,
12
+ public.items, public.parties, public.companies;
13
+
14
+-- One generic per-user record store. Keeps every client field losslessly (accounting data must never be dropped silently).
15
+create table public.records (
16
+ owner_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
17
+ collection text not null check (collection in ('companies','contacts','products','invoices','cheques','expenses','settings')),
18
+ id text not null check (id ~ '^[A-Za-z0-9_-]{1,64}$'),
19
+ data jsonb not null check (octet_length(data::text) < 1000000),
20
+ updated_at timestamptz not null default now(),
21
+ primary key (owner_id, collection, id)
22
+);
23
+
24
+alter table public.records enable row level security;
25
+
26
+create policy records_select on public.records for select to authenticated
27
+ using (owner_id = (select auth.uid()));
28
+create policy records_insert on public.records for insert to authenticated
29
+ with check (owner_id = (select auth.uid()) and public.has_active_license());
30
+create policy records_update on public.records for update to authenticated
31
+ using (owner_id = (select auth.uid()) and public.has_active_license())
32
+ with check (owner_id = (select auth.uid()) and public.has_active_license());
33
+create policy records_delete on public.records for delete to authenticated
34
+ using (owner_id = (select auth.uid()) and public.has_active_license());
35
+
36
+create or replace function public.touch_updated_at() returns trigger
37
+language plpgsql set search_path = public as $$
38
+begin new.updated_at := now(); return new; end $$;
39
+create trigger records_touch before update on public.records
40
+ for each row execute function public.touch_updated_at();\n
\ No newline at end of file
supabase/migrations/20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql
new
+26
@@ -0,0 +1,26 @@
1
+create or replace function public.admin_extend_license(target uuid, days int)
2
+returns void language plpgsql security definer set search_path = public as $$
3
+begin
4
+ if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;
5
+ if days is null or days < 1 or days > 3650 then raise exception 'invalid days'; end if;
6
+ update public.licenses
7
+ set ends_at = greatest(ends_at, current_date) + days,
8
+ plan = case when plan = 'trial' then 'monthly' else plan end,
9
+ status = 'active',
10
+ updated_at = now()
11
+ where user_id = target and plan <> 'lifetime';
12
+ if not found then raise exception 'user not found or lifetime'; end if;
13
+end $$;
14
+
15
+create or replace function public.admin_cancel_license(target uuid)
16
+returns void language plpgsql security definer set search_path = public as $$
17
+begin
18
+ if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;
19
+ update public.licenses set status = 'cancelled', updated_at = now() where user_id = target;
20
+ if not found then raise exception 'user not found'; end if;
21
+end $$;
22
+
23
+revoke all on function public.admin_extend_license(uuid,int) from public, anon;
24
+revoke all on function public.admin_cancel_license(uuid) from public, anon;
25
+grant execute on function public.admin_extend_license(uuid,int) to authenticated;
26
+grant execute on function public.admin_cancel_license(uuid) to authenticated;\n
\ No newline at end of file
supabase/migrations/20260922035848_decouple_profile_email_add_email_col.sql
new
+34
@@ -0,0 +1,34 @@
1
+-- 1) email column on profiles, decoupled from the client-chosen username
2
+alter table public.profiles add column if not exists email text;
3
+
4
+-- backfill (table is empty right now, but safe if it isn't)
5
+update public.profiles p
6
+set email = u.email
7
+from auth.users u
8
+where p.id = u.id and p.email is null;
9
+
10
+alter table public.profiles alter column email set not null;
11
+create unique index if not exists profiles_email_unique_idx on public.profiles (lower(email));
12
+
13
+-- username stays for display only; no longer the identity/derivation key
14
+alter table public.profiles alter column username drop not null;
15
+
16
+-- 2) trigger: populate email from auth.users; username becomes a best-effort,
17
+-- non-unique display label derived from the email's local part (collisions allowed)
18
+create or replace function public.handle_new_user()
19
+returns trigger
20
+language plpgsql
21
+security definer
22
+set search_path to 'public'
23
+as $function$
24
+declare uname text;
25
+begin
26
+ uname := lower(coalesce(nullif(new.raw_user_meta_data->>'username',''), split_part(new.email,'@',1)));
27
+ insert into public.profiles (id, email, username, role)
28
+ values (new.id, lower(new.email), uname, 'user')
29
+ on conflict (id) do update set email = excluded.email;
30
+ insert into public.licenses (user_id, plan, status, starts_at, ends_at)
31
+ values (new.id, 'trial', 'trial', current_date, current_date + 15)
32
+ on conflict (user_id) do nothing;
33
+ return new;
34
+end $function$;\n
\ No newline at end of file
supabase/migrations/20260922035916_drop_username_unique_and_format_constraints.sql
new
+8
@@ -0,0 +1,8 @@
1
+-- username is now a cosmetic display label only, not an identity key;
2
+-- the real identity is auth.users.email / profiles.email (unique, verified by Supabase Auth).
3
+alter table public.profiles drop constraint if exists profiles_username_key;
4
+alter table public.profiles drop constraint if exists profiles_username_check;
5
+
6
+-- keep username reasonably short/sane if present, but never unique and never required
7
+alter table public.profiles add constraint profiles_username_check
8
+ check (username is null or char_length(username) between 1 and 64);\n
\ No newline at end of file
supabase/migrations/20260923210625_add_full_name_to_profiles.sql
new
+1
@@ -0,0 +1 @@
1
+ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS full_name text;\n
\ No newline at end of file
supabase/migrations/20260928025331_allow_purchases_collection.sql
new
+2
@@ -0,0 +1,2 @@
1
+ALTER TABLE public.records DROP CONSTRAINT records_collection_check;
2
+ALTER TABLE public.records ADD CONSTRAINT records_collection_check CHECK (collection = ANY (ARRAY['companies','contacts','products','invoices','cheques','expenses','settings','purchases']));\n
\ No newline at end of file
supabase/migrations/20260928113755_allow_payment_settlement_records.sql
new
+6
@@ -0,0 +1,6 @@
1
+alter table public.records drop constraint if exists records_collection_check;
2
+alter table public.records add constraint records_collection_check
3
+check (collection = any (array[
4
+ 'companies'::text,'contacts'::text,'products'::text,'invoices'::text,
5
+ 'cheques'::text,'expenses'::text,'settings'::text,'purchases'::text,'payments'::text
6
+]));\n
\ No newline at end of file
supabase/migrations/20260928115233_repair_legacy_invoice_contact_ids.sql
new
+11
@@ -0,0 +1,11 @@
1
+update public.records i
2
+set data = jsonb_set(i.data,'{contactId}',to_jsonb(c.id),true)
3
+from public.records c
4
+where i.collection='invoices'
5
+ and c.collection='contacts'
6
+ and c.owner_id=i.owner_id
7
+ and lower(trim(c.data->>'name'))=lower(trim(i.data->>'contactName'))
8
+ and not exists (
9
+ select 1 from public.records x
10
+ where x.owner_id=i.owner_id and x.collection='contacts' and x.id=i.data->>'contactId'
11
+ );\n
\ No newline at end of file
supabase/migrations/20260928115616_restrict_internal_license_helpers.sql
new
+10
@@ -0,0 +1,10 @@
1
+revoke execute on function public.has_active_license() from anon, public;
2
+revoke execute on function public.is_admin() from anon, public;
3
+grant execute on function public.has_active_license() to authenticated;
4
+grant execute on function public.is_admin() to authenticated;
5
+revoke execute on function public.admin_cancel_license(uuid) from anon, public;
6
+revoke execute on function public.admin_extend_license(uuid, integer) from anon, public;
7
+revoke execute on function public.admin_set_license(uuid, text, integer, text) from anon, public;
8
+grant execute on function public.admin_cancel_license(uuid) to authenticated;
9
+grant execute on function public.admin_extend_license(uuid, integer) to authenticated;
10
+grant execute on function public.admin_set_license(uuid, text, integer, text) to authenticated;\n
\ No newline at end of file
supabase/migrations/20260928141512_allow_accounting_foundation_collections.sql
new
+7
@@ -0,0 +1,7 @@
1
+alter table public.records drop constraint if exists records_collection_check;
2
+alter table public.records add constraint records_collection_check check (
3
+ collection = any (array[
4
+ 'companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments',
5
+ 'fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks'
6
+ ]::text[])
7
+);\n
\ No newline at end of file
supabase/migrations/20260928145306_allow_phase3_double_entry_collections.sql
new
+6
@@ -0,0 +1,6 @@
1
+alter table public.records drop constraint if exists records_collection_check;
2
+alter table public.records add constraint records_collection_check check (collection = any (array[
3
+'companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments',
4
+'fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks',
5
+'postingProfiles','journalVouchers','journalLines','journalLineDimensions'
6
+]::text[]));\n
\ No newline at end of file
supabase/migrations/20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql
new
+82
@@ -0,0 +1,82 @@
1
+create or replace function public.finora_sync_records(p_upserts jsonb default '[]'::jsonb, p_deletes jsonb default '[]'::jsonb)
2
+returns void
3
+language plpgsql
4
+security invoker
5
+set search_path = public
6
+as $$
7
+begin
8
+ if auth.uid() is null then raise exception 'authentication required'; end if;
9
+ if not public.has_active_license() then raise exception 'active license required'; end if;
10
+
11
+ insert into public.records(owner_id, collection, id, data)
12
+ select auth.uid(), x.collection, x.id, x.data
13
+ from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)
14
+ on conflict (owner_id,collection,id) do update set data=excluded.data;
15
+
16
+ delete from public.records r
17
+ using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)
18
+ where r.owner_id=auth.uid() and r.collection=d.collection and r.id=d.id;
19
+end $$;
20
+
21
+revoke all on function public.finora_sync_records(jsonb,jsonb) from public, anon;
22
+grant execute on function public.finora_sync_records(jsonb,jsonb) to authenticated;
23
+
24
+create or replace function public.finora_guard_posted_journal()
25
+returns trigger
26
+language plpgsql
27
+security invoker
28
+set search_path = public
29
+as $$
30
+declare
31
+ old_status text := old.data->>'status';
32
+ new_status text;
33
+begin
34
+ if old.collection <> 'journalVouchers' or old_status not in ('posted','reversed') then
35
+ return case when tg_op='DELETE' then old else new end;
36
+ end if;
37
+ if tg_op='DELETE' then raise exception 'posted/reversed journal voucher is immutable'; end if;
38
+ new_status := new.data->>'status';
39
+ if old_status='posted' and new_status='reversed'
40
+ and (old.data - array['status','reversalVoucherId','reversedAt']) =
41
+ (new.data - array['status','reversalVoucherId','reversedAt'])
42
+ and coalesce(new.data->>'reversalVoucherId','') <> '' then
43
+ return new;
44
+ end if;
45
+ if new.data = old.data then return new; end if;
46
+ raise exception 'posted/reversed journal voucher is immutable';
47
+end $$;
48
+
49
+drop trigger if exists trg_finora_guard_posted_journal on public.records;
50
+create trigger trg_finora_guard_posted_journal
51
+before update or delete on public.records
52
+for each row execute function public.finora_guard_posted_journal();
53
+
54
+create or replace function public.finora_guard_posted_journal_children()
55
+returns trigger
56
+language plpgsql
57
+security invoker
58
+set search_path = public
59
+as $$
60
+declare vid text; parent_status text;
61
+begin
62
+ if old.collection not in ('journalLines','journalLineDimensions') then return case when tg_op='DELETE' then old else new end; end if;
63
+ vid := old.data->>'voucherId';
64
+ select r.data->>'status' into parent_status
65
+ from public.records r
66
+ where r.owner_id=old.owner_id and r.collection='journalVouchers' and r.id=vid;
67
+ if parent_status in ('posted','reversed') then raise exception 'posted/reversed journal lines are immutable'; end if;
68
+ return case when tg_op='DELETE' then old else new end;
69
+end $$;
70
+
71
+drop trigger if exists trg_finora_guard_posted_journal_children on public.records;
72
+create trigger trg_finora_guard_posted_journal_children
73
+before update or delete on public.records
74
+for each row execute function public.finora_guard_posted_journal_children();
75
+
76
+create unique index if not exists ux_finora_journal_number
77
+on public.records(owner_id,(data->>'companyId'),(data->>'fiscalYearId'),(data->>'number'))
78
+where collection='journalVouchers' and data->>'status' in ('posted','reversed');
79
+
80
+create unique index if not exists ux_finora_journal_source_version
81
+on public.records(owner_id,(data->>'companyId'),(data->>'sourceType'),(data->>'sourceId'),((coalesce(data->>'sourceVersion','1'))::integer))
82
+where collection='journalVouchers' and data->>'status' in ('posted','reversed') and coalesce(data->>'sourceId','') <> '';\n
\ No newline at end of file
supabase/migrations/20260929091743_phase4_contracting_collections.sql
new
+7
@@ -0,0 +1,7 @@
1
+alter table public.records drop constraint if exists records_collection_check;
2
+alter table public.records add constraint records_collection_check check (collection = any (array[
3
+'companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments',
4
+'fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks',
5
+'postingProfiles','journalVouchers','journalLines','journalLineDimensions',
6
+'contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit'
7
+]::text[]));\n
\ No newline at end of file