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

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

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

Synced Dec 3, 18:15 UTC

Identity: harden signup and seat-member bootstrap

* State: reconcile Wave 4b production rollout * CI: gate dependency review on Dependency Graph availability * Identity: harden signup and seat-member bootstrap * CI: align Wave 5a with Dependency Graph gate * CI: fix Wave 5a release-safety checker newline * CI: fix Wave 5a Dependency Graph safety regex * Tests: add Supabase roles to Wave 5a harness * State: enforce zero-cost infrastructure constraint

davoodmehraban89 committed Oct 2, 2026 at 11:19 UTC cfd15dcf51cf8b9085a5512ded497fe0363ae322
11 files changed +139 -17
.github/workflows/quality.yml
+36 -1
@@ -50,6 +50,8 @@ jobs:
50 run: node scripts/enterprise-invitation-check.mjs
51 - name: Enterprise organization UX invariants
52 run: node scripts/enterprise-org-ux-check.mjs
53 + - name: Wave 5a identity/bootstrap invariants
54 + run: node scripts/identity-wave5a-check.mjs
55 - name: Office Slice C1 invariants
56 run: node scripts/office-slice-c1-check.mjs
57 - name: Office Slice C2 invariants
@@ -87,7 +89,40 @@ jobs:
89 - name: Real DOM smoke
90 run: |
91 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
90 - npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
92 + npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
93 +
94 + identity-wave5a-database:
95 + runs-on: ubuntu-latest
96 + services:
97 + postgres:
98 + image: postgres:17-alpine
99 + env:
100 + POSTGRES_USER: postgres
101 + POSTGRES_PASSWORD: postgres
102 + POSTGRES_DB: finora_identity
103 + ports:
104 + - 5434:5432
105 + options: >-
106 + --health-cmd "pg_isready -U postgres -d finora_identity"
107 + --health-interval 5s
108 + --health-timeout 5s
109 + --health-retries 10
110 + env:
111 + PGPASSWORD: postgres
112 + PGHOST: 127.0.0.1
113 + PGPORT: 5434
114 + PGUSER: postgres
115 + PGDATABASE: finora_identity
116 + steps:
117 + - uses: actions/checkout@v7
118 + - name: Install PostgreSQL client
119 + run: sudo apt-get update -qq && sudo apt-get install -y postgresql-client
120 + - name: Bootstrap disposable identity database
121 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_wave5a_bootstrap.sql
122 + - name: Apply Wave 5a identity bootstrap migration
123 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql
124 + - name: Execute Wave 5a identity bootstrap assertions
125 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_wave5a_behavior.sql
126
127 c8-policy-database:
128 runs-on: ubuntu-latest
PROJECT_STATE.md
+3
@@ -14,9 +14,12 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
14 ## Current change ledger
15 | Date | Request / decision | Status | Evidence / next action |
16 |---|---|---|---|
17 +| 2026-10-02 | Permanent project constraint: user operates from Iran and cannot use paid infrastructure, paid APIs, international-card billing, or services that require a later paid upgrade for essential operation. Railway is excluded from Finora runtime/deployment. | **ACTIVE ARCHITECTURE CONSTRAINT** | Use only genuinely no-cost capabilities for required operation; do not create paid resources or make Finora depend on a service whose essential path later requires billing. GitHub + Supabase remain current sources of truth; any future infrastructure choice must pass this zero-cost/no-billing constraint first. |
18 +| 2026-10-02 | Gmail/GitHub failure review: latest Wave 5a Quality run failed only because the disposable PostgreSQL harness lacked Supabase roles `anon`/`authenticated`; Security latest run is green. | **TEST HARNESS FIXED / RETEST PENDING** | Added the two no-login Supabase compatibility roles to the disposable identity DB bootstrap. Failure occurred before behavior assertions and did not indicate a production migration failure. |
19 | 2026-10-02 | Second CI retest showed the safety-check regex itself was over-escaped. | **REGEX FIXED / RETEST PENDING** | Normalized regex literals to match the workflow labels/variable gate exactly; no runtime/product behavior changed. |
20 | 2026-10-02 | CI retest exposed a literal `\\n` introduced while editing the release-safety checker. | **TEST SYNTAX FIXED / RETEST PENDING** | Replaced the escaped text with a real newline; product/runtime code was unaffected. |
21 | 2026-10-02 | Release-safety invariant initially rejected the explicit Dependency Graph availability gate. | **TEST CONTRACT FIXED / RETEST PENDING** | Safety checker now requires both properties: Dependency Review is conditional on `DEPENDENCY_GRAPH_ENABLED=true`, and remains fail-closed whenever enabled. |
22 +| 2026-10-02 | Wave 5a identity/signup/invitation bootstrap remediation (WS-01, F-121/F-122 and OTP bootstrap boundary). | **IMPLEMENTED ON BRANCH / CI PENDING** | New Auth user bootstrap is transactional profile → personal org → owner membership → org-bound trial license; base client identity no longer requires personal license; OTP login cannot create users; signup is explicit; invitation acceptance occurs before org-context load. Added disposable-DB, static and Real-DOM gates. Production migration and persistent two-user E2E remain NOT VERIFIED. |
23 | 2026-10-02 | PR #29 exposed that Dependency Review now fails hard when GitHub Dependency Graph is disabled. | **CI BOUNDARY FIXED / RETEST PENDING** | Security workflow now runs Dependency Review only when repository variable `DEPENDENCY_GRAPH_ENABLED=true`; when enabled the action remains fail-closed. Release/QA safety and CodeQL remain mandatory. This prevents an unavailable GitHub feature from falsely blocking unrelated PRs while preserving the explicit external-boundary status. |
24 | 2026-10-02 | Owner granted standing approval to continue in-scope project work without repeated confirmation. | **WAVE 4B PRODUCTION APPLIED + VERIFIED** | Supabase production `hcsixhqbyuhpshfwqpjx` recorded `request_wave4b_scheduler_outbox_delivery` as migration version `20261002072526`. Read-only reconciliation confirmed scheduler tables, outbox delivery columns, and all five Wave 4b RPC contracts exist. GitHub main `41aff95d11a66c67e2c64df3eac11a122f94dfd7`: Quality `36975968198`, Security `36975968108`, Release Gate `36976087514`, Deploy `36976115600` succeeded. Automatic external scheduling and D4c destination consumers remain NOT VERIFIED. |
25 | 2026-10-02 | Wave 4b first disposable-DB run exposed an ambiguous PL/pgSQL test variable in the final replay assertion. | **TEST FIX APPLIED / RETEST PENDING** | Product migration executed through all scheduler/outbox assertions; failure was confined to the final test query where local variable `k` shadowed temp-table column `k`. Renamed/qualified the assertion; no production permission or state-machine rollback. |
docs/IDENTITY_WAVE5A_VERIFICATION.md new
+18
@@ -0,0 +1,18 @@
1 +# Wave 5a Identity / Bootstrap Verification
2 +Status: IMPLEMENTED ON BRANCH / CI PENDING
3 +
4 +Scope:
5 +- Transactional new-user bootstrap: profile → personal/default organization → owner membership → organization-bound trial license.
6 +- Seat-member login no longer depends on a personal license row before organization context is loaded.
7 +- Email OTP login uses `shouldCreateUser:false`; account creation is a separate explicit signup action.
8 +- Invitation acceptance runs before organization-context bootstrap so accepted membership is included in the same context load.
9 +
10 +Gates:
11 +- Disposable PostgreSQL bootstrap/rollback assertions.
12 +- Static identity/auth invariants.
13 +- Real-DOM OTP mode assertions.
14 +
15 +NOT VERIFIED:
16 +- Persistent two-real-user production E2E with a legitimate non-owner member.
17 +- Suspension/offboarding client cache/session purge.
18 +- External invitation email delivery.
index.html
+3 -2
@@ -214,9 +214,10 @@ body{background:#f6f9fc}
214 <div class="form-group"><label>رمز عبور (اگر قبلاً تعیین کرده‌اید)</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" autocomplete="current-password" dir="ltr" /></div>
215 <div style="display:flex;gap:10px;margin-top:16px">
216 <button class="btn btn-primary" style="flex:1" onclick="handleLogin()">ورود با رمز</button>
217 -<button class="btn btn-secondary" style="flex:1" onclick="startEmailOtp()">ادامه با کد ایمیل</button>
217 +<button class="btn btn-secondary" style="flex:1" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
218 </div>
219 -<p style="font-size:11.5px;color:var(--text-muted);margin-top:12px;line-height:1.8">کاربر جدید هستید یا رمز را فراموش کرده‌اید؟ «ادامه با کد ایمیل» را بزنید؛ کد یک‌بارمصرف برای شما ایمیل می‌شود.</p>
219 +<button class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="startEmailOtp(false,true)">ثبت‌نام با کد ایمیل</button>
220 +<p style="font-size:11.5px;color:var(--text-muted);margin-top:12px;line-height:1.8">برای ورود به حساب موجود «ورود با کد ایمیل» را بزنید. ایجاد حساب جدید فقط از مسیر صریح «ثبت‌نام با کد ایمیل» انجام می‌شود.</p>
221 </div>
222 <div id="auth-otp-container" style="display:none">
223 <p style="font-size:13px;line-height:1.9;margin-bottom:12px">کد یک‌بارمصرف به <strong dir="ltr" id="auth-otp-email-label"></strong> ارسال شد. پوشه‌ی هرزنامه را هم ببینید.</p>
js/core.js
+11 -13
@@ -44,7 +44,7 @@ let authBusy=false;
44
45 const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
46 const OTP_RE=/^[0-9]{6,10}$/;
47 -let otpEmail='',otpCooldownUntil=0,pendingAuthUser=null;
47 +let otpEmail='',otpCooldownUntil=0,otpCreateUser=false,pendingAuthUser=null;
48
49 function normalizeEmail(raw){return String(raw||'').trim().toLowerCase();}
50 function isStrongPassword(v){const s=String(v||'');return s.length>=8&&/[A-Za-z]/.test(s)&&/[0-9]/.test(s);}
@@ -53,17 +53,14 @@ function toEnDigits(s){
53 }
54 const PROFESSIONAL_ROLE_LABELS={business_owner:'مالک / مدیر کسب‌وکار',financial_manager:'مدیر مالی',chief_accountant:'رئیس حسابداری',accountant:'حسابدار',treasury:'خزانه‌دار',sales:'فروش / بازرگانی',warehouse:'انباردار',auditor:'حسابرس / ناظر',other:'سایر'};
55 function buildUserFromRows(profile,lic){
56 - const sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
57 - return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,maxCompanies:Math.max(1,Number(lic.max_companies||1)),licenseCapacityServerReady:Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
56 + const hasLicense=!!lic;
57 + const sub=hasLicense?{type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status}:{type:'none',startDate:null,endDate:null,status:'unavailable'};
58 + return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,maxCompanies:hasLicense?Math.max(1,Number(lic.max_companies||1)):1,licenseCapacityServerReady:hasLicense&&Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
59 }
60 async function fetchCurrentUser(authUser){
60 - const [p,l]=await Promise.all([
61 - sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single(),
62 - sb.from('licenses').select('*').eq('user_id',authUser.id).single()
63 - ]);
61 + const p=await sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single();
62 if(p.error)throw p.error;
65 - if(l.error)throw l.error;
66 - return buildUserFromRows(p.data,l.data);
63 + return buildUserFromRows(p.data,null);
64 }
65 function canWrite(){
66 if(!currentUser)return false;
@@ -95,7 +92,7 @@ function showAuthPanel(name){
92 const ids={main:'auth-form-container',otp:'auth-otp-container',setpass:'auth-setpass-container'};
93 Object.keys(ids).forEach(k=>{const el=document.getElementById(ids[k]);if(el)el.style.display=(k===name)?'block':'none';});
94 }
98 -function backToAuthMain(){pendingAuthUser=null;showAuthPanel('main');}
95 +function backToAuthMain(){pendingAuthUser=null;otpCreateUser=false;showAuthPanel('main');}
96 function reportOAuthReturnError(){
97 try{
98 const q=new URLSearchParams(window.location.search);
@@ -142,16 +139,17 @@ async function signInWithGoogle(){
139 if(error)throw error;
140 }catch(err){authBusy=false;alert(authMsg(err));}
141 }
145 -async function startEmailOtp(isResend){
142 +async function startEmailOtp(isResend,createUser){
143 if(authBusy)return;
144 const email=normalizeEmail(isResend===true?otpEmail:document.getElementById('auth-email').value);
145 if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
146 if(Date.now()<otpCooldownUntil){alert('لطفاً حدود یک دقیقه بین درخواست‌ها صبر کنید.');return;}
147 + const allowCreate=isResend===true?otpCreateUser:createUser===true;
148 authBusy=true;
149 try{
152 - const {error}=await sb.auth.signInWithOtp({email,options:{shouldCreateUser:true}});
150 + const {error}=await sb.auth.signInWithOtp({email,options:{shouldCreateUser:allowCreate}});
151 if(error)throw error;
154 - otpEmail=email;otpCooldownUntil=Date.now()+60000;
152 + otpEmail=email;otpCreateUser=allowCreate;otpCooldownUntil=Date.now()+60000;
153 document.getElementById('auth-otp-email-label').innerText=email;
154 document.getElementById('auth-otp').value='';
155 showAuthPanel('otp');
js/organization-invitations.js
+4 -1
@@ -62,5 +62,8 @@ window.processFinoraInvitationFromUrl=async function(){
62 return !!data;
63 };
64 const baseEnterAppInvitation=enterApp;
65 -enterApp=async function(authUser){const r=await baseEnterAppInvitation(authUser);await window.processFinoraInvitationFromUrl();return r};
65 +enterApp=async function(authUser){
66 + await window.processFinoraInvitationFromUrl();
67 + return baseEnterAppInvitation(authUser);
68 +};
69 })();
scripts/identity-wave5a-check.mjs new
+8
@@ -0,0 +1,8 @@
1 +import fs from 'node:fs';import assert from 'node:assert/strict';
2 +const core=fs.readFileSync('js/core.js','utf8'),invite=fs.readFileSync('js/organization-invitations.js','utf8'),html=fs.readFileSync('index.html','utf8'),migration=fs.readFileSync('supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql','utf8');
3 +assert(!core.includes("sb.from('licenses').select('*').eq('user_id',authUser.id).single()"),'base identity bootstrap must not require personal license');
4 +assert(core.includes('shouldCreateUser:allowCreate'),'OTP creation must be explicitly mode-bound');
5 +assert(html.includes('startEmailOtp(false,false)')&&html.includes('startEmailOtp(false,true)'),'OTP login/signup actions must be explicit');
6 +assert(invite.indexOf('await window.processFinoraInvitationFromUrl();')<invite.indexOf('return baseEnterAppInvitation(authUser);'),'invitation must be accepted before organization bootstrap');
7 +for(const s of ['insert into public.organizations','insert into public.organization_members','insert into public.licenses','organization_id'])assert(migration.includes(s),s+' missing');
8 +console.log('Wave 5a identity/bootstrap invariants passed');
scripts/identity-wave5a.spec.js new
+4
@@ -0,0 +1,4 @@
1 +const {test,expect}=require('@playwright/test');
2 +test('Wave 5a exposes explicit OTP login and signup modes',async({page})=>{await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>typeof startEmailOtp==='function');expect(await page.getByRole('button',{name:'ورود با کد ایمیل'}).count()).toBe(1);expect(await page.getByRole('button',{name:'ثبت‌نام با کد ایمیل'}).count()).toBe(1);});
3 +test('Wave 5a OTP login cannot silently create a user',async({page})=>{await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>typeof startEmailOtp==='function');const result=await page.evaluate(async()=>{const calls=[],old=sb.auth.signInWithOtp,oldAlert=window.alert;window.alert=()=>{};sb.auth.signInWithOtp=async args=>{calls.push(args);return {error:null}};document.getElementById('auth-email').value='existing@example.com';try{await startEmailOtp(false,false);}finally{sb.auth.signInWithOtp=old;window.alert=oldAlert;}return calls;});expect(result).toEqual([{email:'existing@example.com',options:{shouldCreateUser:false}}]);});
4 +test('Wave 5a explicit signup is the email OTP creation path',async({page})=>{await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>typeof startEmailOtp==='function');const result=await page.evaluate(async()=>{const calls=[],old=sb.auth.signInWithOtp,oldAlert=window.alert;window.alert=()=>{};sb.auth.signInWithOtp=async args=>{calls.push(args);return {error:null}};document.getElementById('auth-email').value='new@example.com';try{await startEmailOtp(false,true);}finally{sb.auth.signInWithOtp=old;window.alert=oldAlert;}return calls;});expect(result).toEqual([{email:'new@example.com',options:{shouldCreateUser:true}}]);});
supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql new
+21
@@ -0,0 +1,21 @@
1 +-- Wave 5a: transactional identity bootstrap for new Auth users.
2 +create or replace function public.handle_new_user()
3 +returns trigger
4 +language plpgsql security definer set search_path=''
5 +as $$
6 +declare v_username text;v_org_name text;v_org_id uuid;
7 +begin
8 + if new.email is null or position('@' in new.email)=0 then raise exception 'Finora requires an email identity for signup';end if;
9 + v_username:=lower(coalesce(nullif(new.raw_user_meta_data->>'username',''),split_part(new.email,'@',1)));
10 + v_org_name:=left(coalesce(nullif(trim(new.raw_user_meta_data->>'full_name'),''),nullif(trim(new.raw_user_meta_data->>'name'),''),nullif(split_part(lower(new.email),'@',1),''),'Finora')||' - شخصی',160);
11 + insert into public.profiles(id,email,username,role,full_name)
12 + values(new.id,lower(new.email),v_username,'user',nullif(trim(coalesce(new.raw_user_meta_data->>'full_name',new.raw_user_meta_data->>'name','')),''));
13 + insert into public.organizations(owner_user_id,name,status) values(new.id,v_org_name,'active') returning id into v_org_id;
14 + insert into public.organization_members(organization_id,user_id,status,is_owner) values(v_org_id,new.id,'active',true);
15 + insert into public.licenses(user_id,organization_id,plan,status,starts_at,ends_at,max_companies,max_users,modules,limits)
16 + values(new.id,v_org_id,'trial','trial',current_date,current_date+15,1,1,array['full_suite']::text[],'{}'::jsonb);
17 + return new;
18 +end $$;
19 +revoke all on function public.handle_new_user() from public,anon,authenticated;
20 +drop trigger if exists on_auth_user_created on auth.users;
21 +create trigger on_auth_user_created after insert on auth.users for each row execute function public.handle_new_user();
supabase/tests/identity_wave5a_behavior.sql new
+19
@@ -0,0 +1,19 @@
1 +\set ON_ERROR_STOP on
2 +insert into auth.users(id,email,raw_user_meta_data) values('11111111-1111-1111-1111-111111111111','owner@example.com','{"full_name":"Owner One"}'::jsonb);
3 +do $$
4 +declare v_org uuid;
5 +begin
6 + if not exists(select 1 from public.profiles where id='11111111-1111-1111-1111-111111111111' and email='owner@example.com') then raise exception 'profile bootstrap missing';end if;
7 + select id into v_org from public.organizations where owner_user_id='11111111-1111-1111-1111-111111111111';
8 + if v_org is null then raise exception 'personal organization bootstrap missing';end if;
9 + if not exists(select 1 from public.organization_members where organization_id=v_org and user_id='11111111-1111-1111-1111-111111111111' and status='active' and is_owner) then raise exception 'owner membership bootstrap missing';end if;
10 + if not exists(select 1 from public.licenses where user_id='11111111-1111-1111-1111-111111111111' and organization_id=v_org and plan='trial' and status='trial') then raise exception 'organization-bound trial license bootstrap missing';end if;
11 +end $$;
12 +do $$
13 +begin
14 + begin
15 + insert into auth.users(id,email,raw_user_meta_data) values('22222222-2222-2222-2222-222222222222',null,'{}'::jsonb);
16 + raise exception 'email-less signup unexpectedly succeeded';
17 + exception when others then if position('requires an email identity' in sqlerrm)=0 then raise;end if;end;
18 + if exists(select 1 from public.profiles where id='22222222-2222-2222-2222-222222222222') then raise exception 'failed signup left partial profile state';end if;
19 +end $$;
supabase/tests/identity_wave5a_bootstrap.sql new
+12
@@ -0,0 +1,12 @@
1 +create extension if not exists pgcrypto;
2 +do $$ begin
3 + if not exists(select 1 from pg_roles where rolname='anon') then create role anon nologin; end if;
4 + if not exists(select 1 from pg_roles where rolname='authenticated') then create role authenticated nologin; end if;
5 +end $$;
6 +create schema if not exists auth;
7 +create table auth.users(id uuid primary key,email text,raw_user_meta_data jsonb not null default '{}'::jsonb);
8 +create table public.profiles(id uuid primary key references auth.users(id) on delete cascade,username text,role text not null default 'user',created_at timestamptz not null default now(),email text not null,full_name text);
9 +create table public.organizations(id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references public.profiles(id) on delete restrict,name text not null check(char_length(trim(name)) between 1 and 160),status text not null default 'active' check(status in('active','suspended')),created_at timestamptz not null default now(),updated_at timestamptz not null default now());
10 +create table public.organization_members(id uuid primary key default gen_random_uuid(),organization_id uuid not null references public.organizations(id) on delete cascade,user_id uuid not null references public.profiles(id) on delete cascade,unit_id uuid,position_title text,status text not null default 'active' check(status in('active','suspended','left')),is_owner boolean not null default false,created_at timestamptz not null default now(),updated_at timestamptz not null default now(),unique(organization_id,user_id));
11 +create table public.licenses(user_id uuid primary key references public.profiles(id) on delete cascade,plan text not null check(plan in('trial','monthly','three_months','annual','lifetime')),status text not null check(status in('trial','active','cancelled')),starts_at date not null default current_date,ends_at date not null,updated_at timestamptz not null default now(),max_companies integer not null default 1 check(max_companies between 1 and 1000),modules text[] not null default array['full_suite']::text[],organization_id uuid not null references public.organizations(id) on delete restrict,max_users integer not null default 1 check(max_users between 1 and 100000),limits jsonb not null default '{}'::jsonb check(jsonb_typeof(limits)='object'));
12 +create unique index licenses_organization_uq on public.licenses(organization_id);