2. RBAC, Licensing, Quotas, Operator Panel & Team Access
Repository:
Backend (planovi-backend)• Rule Prefix:BR-RBAC• Documented Rules: 17 • Open[TEAM_WHY_NEEDED]Questions: 3
1. Business Purpose & Actors
Controls multi-tenant authorization, plan/module gating, license seat allocation, billing manager delegation, platform operator governance (company inspection & Stripe discount grants), company storage & per-user monthly AI token quotas, team invitations, cooperative member portal onboarding, 2FA policy enforcement, and self-service GDPR account deletion/update notifications.
- Actors:
- Platform Operator (
public.platform_operatorsactiveowner/admin): Views all tenants/licenses (operator_companies,operator_company_detail,operator_grants) and creates/revokes Stripe coupons (operator-coupons). - Company Owner (
company_members.role = 'owner',is_active = true): Only role bypassing RBAC role/override checks inside their company (still bounded bycompany_has_module). Manages billing, delegatescan_manage_billing(set_billing_manager), invites/modifiesowners, and edits any RBAC role/override. - Company Admin (
role = 'admin',is_active = true): Bound by their auto-seeded'Admin'RBAC role (20261116150000), cannot edit their own role or manage admins/owners, cannot manage billing unlesscan_manage_billing = trueor company has 0 active owners. - RBAC-Delegated Staff / Coop Staff (
technician,auditor, or custom RBAC roles): Access governed byhas_permission()andOTHERS/full_scope. - Plain Member (
role = 'member'): Scoped to own buildings, own telemetry/devices, own invoices/wallet transactions; requires an active seat inuser_license_assignments. - Unauthenticated User: Can cancel scheduled deletion via
GET /functions/v1/cancel-account-deletion?token=<user_profile_id>.
- Platform Operator (
2. All Features & End-to-End Flows
- Invite Team Member (
supabase/functions/invite-team-member/index.ts):POST-> Bearer JWT + activecompany_members(admin/owner) -> validates email regex,first_name/last_name(max 80),phone(max 30),license_ids(deduped with legacylicense_id, max 5, max 1 non-addon main plan, active &assigned < seat_count), optionalrole_idbelonging tocompany_id(onlyownermay assign/re-inviteownerrole ->403).- Reuses existing
user_profilesby exact lowercaseemail(setsactionUrl = PANEL_URL) OR creates new user viaauth.admin.generateLink({ type: "invite", ... })(actionUrl = ${PANEL_URL}/?token_hash=...&type=invite). - Rejects active existing members (
400), updatesuser_profiles, upsertscompany_members(is_active: true), replacesuser_rolesifrole_idprovided, insertsuser_license_assignments, emails invite via Resend ("Planovi – zaproszenie do zespołu ${companyName}", non-fatal on failure), returns200 { success: true, is_new_user, user_id, license_assigned, licenses_assigned }.
- Grant Portal Access (
supabase/functions/grant-portal-access/index.ts):POST-> Bearer JWT +requireStaff(company_id, "OTHERS")-> verifies target belongs to company (onboarding_sessionsmatchingsession_id, or row incompany_members/onboarding_sessions) -> insertscompany_members(role: "member", ignoring Postgres23505) -> updatesuser_profiles(onboarding_status: "approved",is_energy_coop_member: true) -> sends Resend welcome email unlessemail_opt_out === true(non-fatal warning on failure).
- Schedule Account Deletion Notice (
supabase/functions/send-account-deletion-notice/index.ts):POST-> Bearer JWT -> verifiesuser.id === user_profile_id-> idempotently setsuser_profiles.deletion_scheduled_at = now() + 30 days(if null) -> sends Polish notice email with?token=${user_profile_id}cancellation link, ignoringemail_opt_out. All errors return HTTP500.
- Cancel Account Deletion (
supabase/functions/cancel-account-deletion/index.ts):- Public
GET ?token=<user_profile_id>-> looks upuser_profiles-> ifdeletion_scheduled_atis null returns200HTML"Usunięcie już anulowane", else clears tonulland returns200HTML"Usunięcie anulowane"with CTA toPORTAL_URL. Missing token ->400HTML; not found ->404HTML; DB error ->500HTML.
- Public
- Account Updated Notice (
supabase/functions/send-account-updated-notice/index.ts):POST-> Bearer JWT -> verifiesuser.id === user_profile_idand non-emptychanged_fields[]-> maps keys (first_name,last_name,email,phone,avatar_url,password,"2fa") to Polish labels -> emails user via Resend unlessemail_opt_out === true. All errors return HTTP500.
- Operator Coupons (
supabase/functions/operator-coupons/index.ts):POST(405otherwise) -> Bearer JWT verified against activeowner/admininplatform_operators(403"Brak dostępu: tylko operator platformy").action: "create": validatescode(auto-generatesPLANOVI-XXXXXXXXif omitted),percent_off(0.01..100),duration(once|repeating[1..36mo]|forever),redeem_by(> now + 60s),max_redemptions(1..10000),company_id,allowed_tiers,seat_limits(1..1000/tier),max_total_seats(1..10000),note(>= 3 chars), uniquecode-> creates StripePOST /v1/coupons(resolving product IDs fromGET /v1/prices/{id}) -> creates StripePOST /v1/promotion_codes(dual-payload fallbackcoupon=->promotion[type]=coupon) -> insertslicense_grants(deactivates Stripe promo code on DB failure).action: "revoke": idempotently deactivates Stripe promo code (active=false) and setslicense_grants.revoked_at,revoked_by.
- Database RBAC, License, Billing & Quota RPCs/Triggers:
trg_guard_company_license_tier,trg_guard_company_licenses,trg_guard_user_license_assignments,trg_sync_seats_used,trg_company_members_billing_guard,trg_access_levels_grant_admin,trg_sync_company_storage_usage.- RPCs:
has_permission,company_has_module,planovi_has_module_full_scope,planovi_has_full_scope_any,my_license_access,my_billing_access,billing_admins,set_billing_manager,company_admin_contacts,company_storage_status,can_upload,recalculate_company_storage,my_token_status,get_user_token_status,record_ai_token_usage,is_platform_operator,operator_companies,operator_company_detail,operator_grants.
3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-RBAC)
BR-RBAC-01(Payment-System-Only License Mutation):20261029120000_license_guard.sql: Authenticated callers (auth.uid() IS NOT NULL) cannot updatecompanies.license_tier, insert/deletecompany_licenses, or update anycompany_licensescolumn other thanseats_usedandupdated_at(42501).BR-RBAC-02(Tier Quota Matrix):20261102110000&20261102130000:starter(1,is_addon=false):5 GiB(5,368,709,120B),10,000AI tokens/mo, margin1.50, GA4false.pro(2,is_addon=false):10 GiB(10,737,418,240B),100,000AI tokens/mo, margin1.50, GA4true.enterprise(3,is_addon=false):25 GiB(26,843,545,600B),100,000AI tokens/mo, margin1.50, GA4true.energy_coop(4,is_addon=true):10 GiB(10,737,418,240B),0AI tokens/mo, margin1.50, GA4false.
BR-RBAC-03(Quota Aggregation & Legacy Fallback):fn_company_tier_limits(20261102130000) reads active/trialingcompany_licenses; ONLY if 0 exist, falls back tocompanies.license_tier::int[]. Computesdisk_limit_bytes = MAX(base) + SUM(addon)(+purchased_storage_addon_bytes),token_limit = MAX(user_token_monthly_limit)(+purchased_token_addon),margin = MAX(token_margin_multiplier)(default1.50).BR-RBAC-04(Storage Quota Scope):trg_sync_company_storage_usage(20261102120000) tracks ONLY 6 buckets (documents,invoices,governance_documents,buildings,company-media,coop_reports) whensplit_part(name, '/', 1)is a validcompanies.idUUID. Exceptions downgrade toWARNING(never blocks uploads); enforcement relies on callers invokingcan_upload(company_id, bytes).BR-RBAC-05(AI Token Billing & Monthly Rollover):fn_token_quota_locked(20261102120000) locksuser_token_quotasFOR UPDATE, resetscurrent_tokens_used = 0lazily whennow() >= token_cycle_reset_at(advancing by elapsed whole months + 1), checksremaining > 0, billsceil((max(prompt,0) + max(completion,0)) * margin), and logsai_token_logs(p_featuremax 50 chars).BR-RBAC-06(Serialized Seat Allocation):trg_guard_user_license_assignments(20261103100000) lockscompany_licensesFOR UPDATE, requiresstatus = 'active', same-company activecompany_member_id, unique(company_license_id, company_member_id)(23505), andcount < seat_count(42501). NoUPDATERLS policy exists onuser_license_assignmentssotrg_sync_seats_used(SECURITY DEFINER) cannot drift.BR-RBAC-07(Multi-License Invite Constraints):invite-team-member/index.tscaps requests at<= 5license IDs, max 1 non-addon main plan (!is_addon), and blocks non-owners from inviting or reactivatingrole = 'owner'(403).BR-RBAC-08(Owner-Only Billing Delegation + Ownerless Fallback):20261110190000: Only activeowners may callbilling_admins,set_billing_manager(targeting activeadmins only,22023otherwise), or mutatecompany_members.can_manage_billing(42501). If a company has0active owners, any activeadminreceivescan_manage_billing = true.BR-RBAC-09(Blocked-Seat Admin Contacts):company_admin_contacts(p_company_id)(20261110210000) returns up to 5 activeadmins (excludingowners andauth.uid()).BR-RBAC-10(Canonical RBAC Precedence):has_permission(p_company, p_module, p_action)(20261116160000) checks strictly in order: (1)auth.uid() IS NOT NULL; (2) activecompany_members; (3)company_has_module(p_company, p_module)(gates owners too); (4)rbac_is_owner(p_company)(only owner bypasses; admin does NOT); (5)user_overridesis_granted = false(deny wins); (6)user_overridesis_granted = true; (7)user_roles -> role_permissions -> access_levels.BR-RBAC-11(Modulemin_planMatrix):20261116160000,20261117090000,20261117130000:min_plan = 1(Starter):dashboard,documents.*,sales,clients.*,dealflow*,schedules*,calendar,scheduler_bookings,settings,config,team,custom_enums,offer_templates,agreement_templates,offers,agreements,team_calendars(and unknown modules).min_plan = 2(Pro):jarvis,operations.min_plan = 3(Enterprise):strategy.min_plan = 4(Energy add-on /is_cooperative = true):energy_devices,energy_balance,knowledge_base.*,team_declarations.*,governance.*,wallet,technician_queue,ledger.*,coop_settings.
BR-RBAC-12(Anti-Privilege-Escalation RESTRICTIVE RLS):20261116150000:roles/role_permissionswrites requirerbac_may_edit_role(owner OR caller doesn’t hold that role);user_roleswrites requirerbac_may_manage_member(owner OR target != self AND target not admin/owner);user_overrideswrites requirerbac_may_manage_overrides_of(target != self AND owner in every shared company where target is admin/owner).trg_access_levels_grant_adminauto-grants every newaccess_levelsrow to all roles named'Admin'.BR-RBAC-13(Full-Scope Visibility & Member Data Isolation):20261105120000,20261105130000,20261117120000,20261117130000,20261117140000: Plain members (role = 'member') withoutOTHERS/full_scopesee ONLY own buildings (buildings.client_id = auth.uid()), own converters/gateways/telemetry/live-state, own buildingbilling_records(not coop-levelbuilding_id IS NULL), and ownmember_wallet_transactions.full_scopeapplies to 5 modules (dashboard,energy_devices,energy_balance,wallet,ledger).BR-RBAC-14(Pilot Declarations Write RLS):20261116100000&20261116150000drop legacy admin write policies and enforcehas_permission()ondeclaration_templates,declaration_fields,declaration_steps,onboarding_sessions,member_declaration_reviews,onboarding_tokens, andcompany_membersDELETE (blocks deletingowner,admin, or self).BR-RBAC-15(2FA Enforcement Setting):20261118180000:company_settings.enforce_2fa(defaultfalse) readable by active members; writable byrbac_is_ownerORhas_permission(company_id, 'coop_settings', 'UPDATE').BR-RBAC-16(Operator & Grant Constraints):platform_operators,license_grants,license_grant_redemptionshave RLS enabled with ZERO policies +REVOKE ALLfromanon, authenticated.license_grantschecks:code ~ '^[A-Z0-9][A-Z0-9_-]{2,39}$',percent_off ∈ (0, 100],duration_months ∈ [1, 36]iff'repeating',max_redemptions ∈ [1, 10000],max_total_seats ∈ [1, 10000].BR-RBAC-17(Self-Only Account Notices & Opt-Out Override):send-account-deletion-notice&send-account-updated-noticeenforceuser.id === user_profile_id. Deletion notice ALWAYS ignoresemail_opt_out; update & welcome emails honoremail_opt_out === true.
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> Pending : invite / onboarding created
Pending --> Filled : member submits declaration
Pending --> Expired : token expires on submit
Filled --> CorrectionRequired : board requests fixes
CorrectionRequired --> Filled : member resubmits
Filled --> Approved : grant-portal-access
Filled --> Rejected : send-rejection-notice
Approved --> [*]
Rejected --> [*]
license_grants: Active (revoked_at IS NULL, bounded byredeem_by&max_redemptions) -> Revoked (revoked_at,revoked_byviaoperator-coupons).license_grant_redemptions.outcome:'ok'|'cancelled_over_limit'|'over_limit_update'.user_profiles.deletion_scheduled_at:NULL(active) <->now() + 30 days(send-account-deletion-notice/cancel-account-deletion).- RBAC Realtime Tables (
20261117100000):role_permissions,user_overrides,user_roles,company_membersstream live changes viasupabase_realtime.
5. Technical Contract
- Endpoints:
POST invite-team-member,POST grant-portal-access,POST send-account-deletion-notice,GET cancel-account-deletion?token=,POST send-account-updated-notice,POST operator-coupons. - Tables Created/Altered:
company_storage_quotas,user_token_quotas,ai_token_logs,platform_operators,license_grants,license_grant_redemptions,company_settings(+enforce_2fa),license_tiers(+company_disk_limit_bytes,+user_token_monthly_limit,+token_margin_multiplier,+allow_ga4_integration,+is_addon),company_members(+can_manage_billing),app_modules(+parent_module_name,+sort_order,+min_plan). - External APIs: Resend API (
invite-team-member,grant-portal-access,send-account-deletion-notice,send-account-updated-notice), Stripe REST API (GET prices/{id},POST coupons,POST promotion_codes,POST promotion_codes/{id}inoperator-coupons).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-flutter-app (LicenseGate, PermissionProvider, OperatorPanel, Settings) -> PostgreSQL RPCs & Realtime | PostgREST + Supabase Realtime / User JWT | my_license_access, company_admin_contacts, my_billing_access, billing_admins, set_billing_manager, company_storage_status, can_upload, my_token_status, is_platform_operator, operator_companies, operator_company_detail, operator_grants, Realtime on 4 RBAC tables |
planovi-flutter-app -> Module 2 Edge Functions | HTTPS POST / User JWT | invite-team-member, grant-portal-access, send-account-deletion-notice, send-account-updated-notice, operator-coupons |
operator-coupons -> Stripe API | HTTPS form-urlencoded / STRIPE_SECRET_KEY | /v1/prices/{id}, /v1/coupons, /v1/promotion_codes |
handle-stripe-webhook, change-plan -> license_grants / license_grant_redemptions | PostgREST / Service Role | Enforces grant limits created by operator-coupons |
jarvis/index.ts -> get_user_token_status / record_ai_token_usage | PostgREST RPC / Service Role | Pre-check & post-LLM token billing |
7. Why It Works This Way
auth.uid() IS NULLtrigger bypasses: Enables webhooks/service-role/Studio SQL to manage billing/seats while blocking PostgREST client tampering.sync_seats_used()madeSECURITY DEFINER(20261103100000): Previously ran as caller; legacy RLS only allowedadmin(notowner), causingseats_useddrift whenever anownerremoved a seat.fn_company_tier_limitscompanies.license_tierfallback (20261102130000): 19 legacy DEV companies had nocompany_licensesrows and would otherwise get 0 storage/token quota.- Additive
rbac_full_scope_selectpolicies (20261117120000/130000): Intentionally OR-ed with legacyplanovi_coop_staff_company_ids()during phased rollout so no existing staff lose access before legacy policies are dropped. - Explicit
null::uuidforapp_modules.created_by/updated_by: Avoids FK violation against non-existent default system user UUID inpublic.users. [TEAM_WHY_NEEDED: user_overrides lacks a company_id column, so revoking/granting an override for a user in Company A mutates their permissions in Company B. Is a schema migration adding company_id planned?][TEAM_WHY_NEEDED: user_token_quotas.purchased_token_addon is permanently added to every monthly cycle reset instead of decrementing as a one-time top-up. Is it intended to be a recurring monthly add-on or an unfinished consumption model?][TEAM_WHY_NEEDED: send-account-deletion-notice comments describe a 30-day permanent purge & encryption cron job, which does not exist in this repository. Where is it implemented?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
Operator panel returns 403 / 42501 "Brak dostępu: tylko operator platformy" | public.platform_operators is not seeded by migrations (20261110150000:15-17) | SELECT * FROM public.platform_operators; (as service_role) | INSERT INTO public.platform_operators (company_id) VALUES ('<planovi-company-uuid>') ON CONFLICT DO NOTHING; |
Unsubscribe link from grant-portal-access or send-account-updated-notice returns 404 | Both pass ?token=${user_profile_id} instead of an onboarding_tokens.token, which unsubscribe/index.ts:57 cannot match | Inspect grant-portal-access/index.ts:207 & send-account-updated-notice/index.ts:107 | Update unsubscribe or mint signed/dedicated opt-out tokens |
| Storage quota numbers drift from actual Storage usage | trg_sync_company_storage_usage swallowed a failure (WARNING) or legacy files predated trigger | Postgres logs for storage usage tracking skipped; compare company_storage_quotas vs storage.objects | Run SELECT public.recalculate_company_storage(); as service_role |
Deactivated member cannot regain access via grant-portal-access | grant-portal-access/index.ts:166-173 ignores 23505 on company_members insert without flipping is_active = true | SELECT is_active, role FROM company_members WHERE company_id=... AND user_id=...; | Update grant-portal-access to upsert is_active = true |
Non-owner admin still bypasses RBAC in Edge Functions or sees full telemetry after full_scope revoke | invite-team-member/grant-portal-access/_shared/auth.ts still bypass for admin, and legacy planovi_coop_staff_company_ids() SELECT policies remain active | Check pg_policies on raw_telemetry/billing_records and _shared/auth.ts:70 | Drop legacy staff SELECT policies once RBAC rollout completes; align _shared/auth.ts to owner-only bypass |
has_permission(co, mod, 'OTHERS') unexpectedly returns true | has_permission (20261116160000) omits al.granular_action IS NULL, matching full_scope/vote/generate | SELECT * FROM access_levels WHERE action_type='OTHERS'; | Filter al.granular_action IS NULL in has_permission or add p_granular parameter |