4. Billing, Usage Quotas & Platform Operator Panel
Repository:
Flutter App (planovi-flutter-app)• Rule Prefix:BR-BILL• Documented Rules: 20 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
Manages per-company SaaS subscriptions (Stripe-backed), seat licensing per main plan and add-on tier, company/member resource quotas (disk storage and monthly Jarvis AI tokens), Stripe Customer Portal & invoice history, delegated billing permissions, and the internal Planovi Platform Operator Panel (cross-tenant oversight + Stripe discount/promo code generation and revocation).
- Actors:
- Company Owner (
is_owner == truevia RPCmy_billing_access): Full billing control (buy plan, change plan/seats, toggle auto-renew, open Stripe Portal, view/pay invoices), seat assignments, AND delegation/revocation of billing access to admins (billing_admins/set_billing_manager). - Billing-Delegated Admin (
can_manage_billing == true, is_owner == false): Same billing and seat actions as Owner (also granted automatically to admins of a company without an active owner, enforced server-side inmy_billing_access), except cannot manage the"Dostęp do płatności"delegation card. - Standard Company Admin (
PermissionProvider.isAdmin == true, can_manage_billing == false): Can assign/disconnect license seats (_canManage) and view usage overview; blocked from financial actions (_buildNoBillingNotice). - Regular Company Member (
isAdmin == false): Read-only view of subscription card, active licenses & seat holders, and organization usage (_buildReadOnlyNotice); views personal AI token & company storage quotas viaUserUsageCardinProfileScreen. - Platform Operator (
is_platform_operatorRPC ==true): Active owner/admin of the Planovi operator company; accessesOperatorPanelScreen("Panel operatora") fromMainLayoutsidebar (main_layout.dart:59,68-76,958-997). - Stripe Webhooks: Calls
stripe-webhook(legacy agreement checkout in this repo) and externalhandle-stripe-webhook(v3 subscriptions & coupon seat-limit enforcement, absent from this repo).
- Company Owner (
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Billing Screen Bootstrap (
billing_screen.dart):initState()registersWidgetsBindingObserverand runs_refreshAll(): (1)_fetchBillingAccess()→ RPCmy_billing_access(p_company_id)(ifis_owner, also RPCbilling_admins); on RPC failure, falls back to_canBill = _canManage(isAdmin),_isOwner = false. (2) Parallel fetch ofcompaniesbilling columns, activecompany_licenses+license_tiers+user_license_assignments, and (if_canBill)get-billing-invoices. (3)AppLifecycleState.resumedsilently refreshes to capture changes from external Stripe tabs. - Buy New Subscription (
_showBuyPlanDialog,billing_screen.dart:1016-1153): Enabled when_canBill && (!_hasSubscription || _subStatus == 'canceled'). Queries paidlicense_tiers(monthly_price_pln > 0), allows ≤1 main plan + optional add-ons (is_addon == true || id == 'energy_coop') with 1..1000 seats → invokesstart-checkout({company_id, items}) → opensdata['url']externally (_blank). Failures show inline red error text in dialog or snackbar ("Brak linku."). - Change Plan / Adjust Seats with Proration (
_showChangePlanDialog,billing_screen.dart:555-801): Enabled when_canBill && _hasSubscription && _subStatus != 'canceled'. Counts current seat assignments per tier fromuser_license_assignments; locks switching away from main tiers with assigned users (lockedMains) and sets seat stepper minimum tomax(assigned[id], 1). User clicks"Sprawdź koszt"→ invokespreview-plan-change→ displays credit notice (total < 0) oramount_now / 100PLN due now +next_monthly→ clicks"Potwierdź i zapłać"→ invokeschange-planwith{company_id, items, proration_date}→ silently refreshes and shows"Plan zmieniony. Faktura pojawi się na liście.". Any seat edit resetspreview = null. - Auto-Renew Toggle & Cancel Survey (
_setAutoRenew,_askCancelReason,billing_screen.dart:399-552): Enabling invokesset-auto-renew(enabled: true) →"Automatyczne odnawianie włączone.". Disabling opens non-dismissible mandatory survey (5 radio reasons + optional 3-line feedback; submit disabled until reason selected) → invokesset-auto-renew(enabled: false, reason, feedback?) →"Odnawianie wyłączone. Dostęp pozostaje do <dd.MM.yyyy | końca okresu>.". - Stripe Customer Portal & Invoices (
_openPortal,_fetchInvoices): Portal invokescreate-portal-session({company_id, return_url?}on Web) and launches URL. Invoices invokeget-billing-invoices, display date, number (· Zmiana planubadge if any line hasproration == true), amount (amount_due / 100ifopen, elseamount_paid / 100), status pill (paid/open/void/uncollectible), Pay button (open+hosted_invoice_url), Open link, and PDF download (invoice_pdf). - Seat Assignment & Disconnection (
_showAssignUserDialog,_unassignSeat): Assign requires_canManage && license.hasSeatsAvailable; filters activecompany_membersnot yet assigned to that license (if none, shows"Wszyscy użytkownicy mają już przypisaną licencję <tierName>."); inserts intouser_license_assignments. Disconnect confirms (different notice for self vs other), runs.delete().eq('id', ...).select('id'); if empty (RLS silently blocked), throws"Brak uprawnień do odłączenia licencji.". - Billing Access Delegation (
_setBillingManager): Owner togglesSwitchListTileper admin → RPCset_billing_manager(p_member_id, p_enabled)→ snackbar"'$who może teraz zarządzać płatnościami.'"/"'$who nie zarządza już płatnościami.'". - Company & Personal Resource Quotas (
usage_service.dart,company_usage_overview_widget.dart,user_usage_card.dart):CompanyUsageOverviewWidgetfetchescompany_storage_statusRPC andcompany_members+user_token_quotas(sorted bytokensUseddesc), rendering disk bar, warning banner, team AI token total, and expandable per-memberDataTable.UserUsageCardfetchesmy_token_statusandcompany_storage_statusRPCs. - Platform Operator Panel (
operator_panel_screen.dart,operator_coupons_view.dart):- Tab 1 (
Firmy i licencje): Calls RPCoperator_companies(). Renders 5 KPI tiles, status filter chips (Wszystkie,Aktywne,Bez licencji,Nieopłacone,Zakończone), search (name/NIP/owner_email), and type dropdown (Firma standardowa/Spółdzielnia). Selecting a row loads RPCoperator_company_detail(p_company_id)in a 420px side pane (>= 1100px) or 90%-height bottom sheet (< 1100px), with Stripe Dashboard links and a preset “Create Coupon” CTA. Postgres42501shows"Brak dostępu. Panel jest tylko dla właściciela i administratorów firmy operatora.". - Tab 2 (
Kody rabatowe): Calls RPCoperator_grants()+license_tierswith non-emptystripe_price_id. Lists active codes by default ("Pokaż też nieaktywne"toggle), redemption logs (ok,cancelled_over_limit), Revoke button (operator-coupons {action: 'revoke', grant_id}), and Create Coupon dialog (operator-coupons {action: 'create', ...}→ copies returnedgrant.codeto clipboard).
- Tab 1 (
- In-Repo Transactional Edge Functions:
stripe-webhook/index.ts: Verifiesstripe-signatureviastripe.webhooks.constructEventAsync, handles ONLYcheckout.session.completedagainstagreementsbystripe_session_id(idempotent ifstripe_payment_status === 'paid'), updates to'paid', sends Resend email (non-fatal on failure); returns HTTP 200{received: true}.send-subscription-updated/index.ts&send-subscription-cancelled/index.ts: Authenticate JWT, checkcompany_members.role === 'admin' && is_active === true(NOTE: rejects'owner'!), skip Resend ifuser_profiles.email_opt_out === true, send Polish Resend email.
3. Hard Business Rules (BR-BILL-01..20)
- BR-BILL-01 (Main Plan Exclusivity + Optional Add-ons): Max ONE main plan (
is_addon != true && id != 'energy_coop') plus optional add-ons; at least one tier must haveseats > 0(billing_screen.dart:15-16,804-822,company_license.dart:23,85). Errors:'Wybierz jeden plan główny (Starter, Pro lub Enterprise).'and'Wybierz plan główny lub moduł.'. - BR-BILL-02 (Basic 0 PLN Not Sold): Buy/Change Plan dialogs query
license_tierswith.gt('monthly_price_pln', 0)(billing_screen.dart:16,568,1028). - BR-BILL-03 (Seat Bounds & Assigned-Seat Floor): Stepper bounded
[max(assigned[id], 1), 1000]. Tiers withassigned[id] > 0cannot be deselected/switched (lockedMains,billing_screen.dart:842-846,860,879,954-997). Hint:'Aby zmienić plan główny, najpierw odepnij użytkowników z planu <names>.'. - BR-BILL-04 (Seat & Pricing Formulas):
seatsRemaining = seatCount - seatsUsed;hasSeatsAvailable = seatsRemaining > 0;isActive = status == 'active' || status == 'trialing';totalMonthly = (tierMonthlyPrice ?? 0) * seatCount; prorationamount_nowis in grosze (/ 100), credit whenpreview['total'] < 0(company_license.dart:60-63,billing_screen.dart:721-723,1759). - BR-BILL-05 (14-Day Payment Failure Grace Period):
_graceDays = 14;pastDue = _subStatus == 'past_due' || _paymentFailedAt != null; remaining days =(14 - now.difference(failedAt).inDays).clamp(0, 14)(billing_screen.dart:41,1487-1492). - BR-BILL-06 (Two-Tier Billing Authorization): Seat assignment (
_canManage) =PermissionProvider.isAdmin; financial mutations (_canBill) = RPCmy_billing_access.can_manage_billing(fallback_canManageon RPC error); delegation (_isOwner) =my_billing_access.is_owner(billing_screen.dart:85-91,113-166). - BR-BILL-07 (Mandatory Cancellation Survey): Disabling auto-renew requires selecting 1 of 5 reasons; submit stays disabled while
selected == null(billing_screen.dart:434-552). - BR-BILL-08 (Two-Step Proration Preview):
Confirm & Paystays hidden untilpreview != null; any seat/plan change nullspreview, forcing re-preview and sendingproration_datetochange-plan(billing_screen.dart:650,693-696,765-796). - BR-BILL-09 (Invoice Amount & Proration Display):
openinvoices useamount_due / 100, othersamount_paid / 100; currency defaults to'PLN'; Unix seconds* 1000; proration badge shown if anylinesitem hasproration == true(billing_screen.dart:1891-1905). - BR-BILL-10 (AI Token Quota Defaults & Formatting): Default monthly limit fallback
10000;remaining = max(0, limit - used);daysUntilResetdefaults to30ifresetAt == null; counts format asX.XM(>= 1M),X.Xk(>= 1k), else integer (usage_quota_model.dart:27-59,usage_service.dart:113). - BR-BILL-11 (Storage Quota Thresholds & Formatting): Default limit fallback
5368709120B (5 GiB);isNearCapacity = percentUsed >= 0.80 && percentUsed < 0.95;isOverCapacity = percentUsed >= 0.95; progress bar turns red at>= 0.90, orange at>= 0.75; base-1024 formatting (B/KB/MB/GB/TB) (usage_quota_model.dart:80-111,company_usage_overview_widget.dart:85-90,272-277). - BR-BILL-12 (Upload Quota Pre-Check Fail-Open):
UsageService.canUpload(companyId, bytes)calls RPCcan_uploadand returnstrueon any exception (currently unreferenced dead code) (usage_service.dart:49-63). - BR-BILL-13 (Operator Access Gate): Sidebar menu item gated by RPC
is_platform_operator(main_layout.dart:70-72); server enforces in operator RPCs andoperator-coupons; Postgres42501displays access-denied state (operator_panel_screen.dart:90-91). - BR-BILL-14 (Operator Company State Priority): Strict order: (1)
hasLic && (past_due|unpaid|payment_failed_at!=null)→'unpaid'; (2)hasLic && trialing→'trial'; (3)hasLic→'active'; (4)canceled|incomplete_expired→'ended'; (5) else'none'(operator_panel_screen.dart:144-155). - BR-BILL-15 (Stripe Test vs Live Dashboard Routing):
_stripeTestMode = Supabase.instance.client.rest.url.contains('dev-')routes links todashboard.stripe.com/test/...vsdashboard.stripe.com/...(operator_panel_screen.dart:226-233). - BR-BILL-16 (Operator Coupon Validation Rules): Optional
codematches^[A-Z0-9][A-Z0-9_-]{2,39}$('3–40 znaków: litery, cyfry, - lub _');0 < percent_off <= 100('0,01–100', accepts,/.);duration ∈ {once, repeating, forever}withduration_months ∈ 1..36whenrepeating;redeem_by ∈ [now+1d, now+3y];max_redemptions ∈ 1..10000(default 1); per-tierseat_limits ∈ 1..1000;max_total_seats ∈ 1..10000; mandatorynote.trim().length >= 3('Podaj powód'). Only tiers with non-emptystripe_price_idare eligible (operator_coupons_view.dart:44,445-773). - BR-BILL-17 (Coupon Post-Checkout Enforcement): Seat limits and company restrictions are enforced post-checkout by external
handle-stripe-webhook, which cancels over-limit subscriptions withoutcome: 'cancelled_over_limit'(operator_coupons_view.dart:11-12,266). - BR-BILL-18 (Coupon Status Priority): (1)
revoked_at != null→'revoked'; (2)redeem_by < now→'expired'; (3)max_redemptions != null && used >= max_redemptions→'used_up'; (4) else'active'(operator_coupons_view.dart:165-173). - BR-BILL-19 (
stripe-webhookVerification & Idempotency): Stripe API"2024-06-20"; verifiesstripe-signatureviaconstructEventAsync(HTTP 400{error: "Invalid signature"}on mismatch; 500 on missing env/header/DB error). Idempotent whenagreements.stripe_payment_status === "paid"; Resend email errors are non-fatal (returns 200{received: true}) (stripe-webhook/index.ts). - BR-BILL-20 (Subscription Email Auth & Opt-Out):
send-subscription-updatedandsend-subscription-cancelledrequire valid Bearer JWT + activecompany_memberswithrole === "admin"(rejects"owner"!), respectuser_profiles.email_opt_out(returns HTTP 200{success: true, email_sent: false}), and return HTTP 500 on all thrown errors including auth/403 (send-subscription-updated/index.ts,send-subscription-cancelled/index.ts).
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> NoSubscription
NoSubscription --> Active: start-checkout -> Stripe webhook
NoSubscription --> Trialing: trial checkout
Trialing --> Active: trial converts
Active --> CancelScheduled: set-auto-renew(false)
CancelScheduled --> Active: set-auto-renew(true)
CancelScheduled --> Canceled: period ends
Active --> PastDue: payment fails (14d grace)
PastDue --> Active: card updated & paid
PastDue --> Canceled: grace expires
Canceled --> Active: Buy plan again
- Coupon Lifecycle (
OperatorCouponsView._status):active→revoked(existing subscribers keep discount) |expired(now > redeem_by) |used_up(used >= max_redemptions). - Spelling Divergence:
companies.subscription_statususes'canceled'(1l, Stripe), whilecompany_licenses.statususes'cancelled'(2ls).
5. Technical Contract (Inputs → Processing → Side Effects)
- Tables:
companies,company_licenses,license_tiers,user_license_assignments,company_members,user_token_quotas,user_profiles,agreements(instripe-webhook). - PostgreSQL RPCs:
my_billing_access(p_company_id),billing_admins(p_company_id),set_billing_manager(p_member_id, p_enabled),my_token_status(p_company),company_storage_status(p_company),can_upload(p_company, p_bytes),is_platform_operator(),operator_companies(),operator_company_detail(p_company_id),operator_grants(). - In-Repo Edge Functions:
stripe-webhook(usesENERGY_SUPABASE_URL,ENERGY_SUPABASE_SERVICE_ROLE_KEY,STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET,RESEND_API_KEY,FROM_EMAIL),send-subscription-updated,send-subscription-cancelled(both useENERGY_SUPABASE_*,RESEND_API_KEY,FROM_EMAIL,PORTAL_URL).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
BillingScreen -> External Edge Functions (absent from this repo!) | HTTPS / User JWT (invokeEdgeFunction) | start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices |
OperatorCouponsView -> External Edge Function operator-coupons (absent from this repo!) | HTTPS / Operator JWT (invokeEdgeFunction) | {action: 'create', ...} / {action: 'revoke', grant_id} -> {success, grant?} |
Stripe -> External Edge Function handle-stripe-webhook (absent from this repo!) | HTTPS / Stripe HMAC | Handles v3 company subscription lifecycle & post-checkout coupon seat-limit cancellation |
Stripe -> supabase/functions/stripe-webhook (in-repo) | HTTPS / stripe-signature HMAC | checkout.session.completed -> updates agreements.stripe_payment_status = 'paid' + Resend email |
stripe-webhook, send-subscription-* -> Resend API | HTTPS / Bearer RESEND_API_KEY | POST https://api.resend.com/emails |
OperatorPanelScreen -> Stripe Dashboard | External Browser Link | https://dashboard.stripe.com[/test]/customers/<id> & subscriptions/<id> |
7. Why It Works This Way
- v3 billing moved cancellation to Stripe
cancel_at_period_end(set-auto-renew) because earlier per-license DB cancellation left Stripe billing active (billing_screen.dart:8). _fetchBillingAccess()falls back toPermissionProvider.isAdminon RPC error so admins are never locked out during phased DB migrations (billing_screen.dart:137).- Stripe Promotion Codes cannot natively enforce Planovi
company_idor per-tier seat caps at checkout, sohandle-stripe-webhookenforces them post-checkout (operator_coupons_view.dart:11-12). _DetailSheetListenermanually relays_loadDetailstate into modal bottom sheets because bottom sheets don’t rebuild from parentsetState(operator_panel_screen.dart:602-619,829-857).[TEAM_WHY_NEEDED: Where are the v3 Stripe billing/operator Edge Functions (start-checkout, change-plan, operator-coupons, handle-stripe-webhook, etc.) and their SQL RPCs version-controlled, and are in-repo stripe-webhook, send-subscription-updated, and send-subscription-cancelled still deployed/active?][TEAM_WHY_NEEDED: Why do stripe-webhook, send-subscription-updated, and send-subscription-cancelled read ENERGY_SUPABASE_URL / ENERGY_SUPABASE_SERVICE_ROLE_KEY instead of standard SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY?]
8. Debugging, Logs & Common Failure Modes
- Storage warning banner vanishes at
>= 95%capacity ->usage_quota_model.dart:95-96definesisNearCapacityas[0.80, 0.95)andisOverCapacityas>= 0.95, butcompany_usage_overview_widget.dart:154only renders the banner forisNearCapacity-> checkisNearCapacity || isOverCapacity. - Trialing or past-due licenses invisible on
BillingScreen->_fetchLicenses()(billing_screen.dart:232) filters.eq('status', 'active')even thoughCompanyLicense.isActiveincludes'trialing'and_statusBadgestyles'trialing'/'past_due'. - Company
ownergets 500/Forbidden fromsend-subscription-updated&send-subscription-cancelled-> both checkmembership.role !== "admin"(send-subscription-updated:80,send-subscription-cancelled:79), rejecting"owner". stripe-webhookrejected with 401 by Supabase gateway ->supabase/config.tomlomits[functions.stripe-webhook] verify_jwt = false; must deploy with--no-verify-jwtor add config block.- Unescaped HTML in transactional emails ->
stripe-webhook,send-subscription-updated,send-subscription-cancelledinterpolate DB strings (client_name,companyName,tierName, etc.) raw into HTML. - Seat disconnect silently fails -> RLS returns
[]on delete -> throws'Brak uprawnień do odłączenia licencji.'(billing_screen.dart:339-341). - Log grep:
[UsageService],BillingScreen,OperatorPanel,OperatorCoupons,STRIPE WEBHOOK,SEND SUBSCRIPTION UPDATED,SEND SUBSCRIPTION CANCELLED.