1
+-- F0-01/F0-07: Repair Auth bootstrap order after organization member-seat guard.
2
+-- Verified live error (2026-10-12): 'organization license not found' (23503).
3
+-- Minimal semantics: profiles -> organization -> trial license -> owner membership.
4
+-- Preserve existing email/phone identities, ordinary role and unmodified seat policy.
5
+-- This CREATE OR REPLACE does not rewrite any existing users, organizations, or licenses.
6
+create or replace function public.handle_new_user()
7
+returns trigger
8
+language plpgsql security definer set search_path=''
9
+as $function$
10
+declare v_username text; v_org_name text; v_org_id uuid; v_identity text;
11
+begin
12
+ v_identity:=coalesce(nullif(lower(new.email),''),nullif(new.phone,''));
13
+ if v_identity is null then
14
+ raise exception 'Finora requires an email or phone identity for signup';
15
+ end if;
16
+ v_username:=lower(coalesce(
17
+ nullif(new.raw_user_meta_data->>'username',''),
18
+ case when new.email is not null then split_part(new.email,'@',1)
19
+ else regexp_replace(new.phone,'[^0-9+]','','g') end
20
+ ));
21
+ v_org_name:=left(
22
+ coalesce(
23
+ nullif(trim(new.raw_user_meta_data->>'full_name'),''),
24
+ nullif(trim(new.raw_user_meta_data->>'name'),''),
25
+ nullif(v_username,''),
26
+ 'Finora'
27
+ )||' - شخصی',
28
+ 160
29
+ );
30
+ insert into public.profiles(id,email,phone,username,role,full_name)
31
+ values(
32
+ new.id,
33
+ case when new.email is null then null else lower(new.email) end,
34
+ new.phone,
35
+ v_username,
36
+ 'user',
37
+ nullif(trim(coalesce(new.raw_user_meta_data->>'full_name',new.raw_user_meta_data->>'name','')),'')
38
+ );
39
+ insert into public.organizations(owner_user_id,name,status)
40
+ values(new.id,v_org_name,'active') returning id into v_org_id;
41
+
42
+ -- The BEFORE INSERT seat guard on organization_members checks this row.
43
+ -- Seed the trial license FIRST, without weakening or disabling that guard.
44
+ insert into public.licenses(user_id,organization_id,plan,status,starts_at,ends_at,max_companies,max_users,modules,limits)
45
+ values(new.id,v_org_id,'trial','trial',current_date,current_date+15,1,1,array['full_suite']::text[],'{}'::jsonb);
46
+
47
+ insert into public.organization_members(organization_id,user_id,status,is_owner)
48
+ values(v_org_id,new.id,'active',true);
49
+ return new;
50
+end $function$;
51
+
52
+-- Keep direct calls unavailable to browser-level roles.
53
+revoke all on function public.handle_new_user() from public, anon, authenticated;