Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Flutter App v1.0 (frozen on 2026-11-23, commit 92290cf7). Switch to Latest →

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 == true via RPC my_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 in my_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 via UserUsageCard in ProfileScreen.
    • Platform Operator (is_platform_operator RPC == true): Active owner/admin of the Planovi operator company; accesses OperatorPanelScreen ("Panel operatora") from MainLayout sidebar (main_layout.dart:59,68-76,958-997).
    • Stripe Webhooks: Calls stripe-webhook (legacy agreement checkout in this repo) and external handle-stripe-webhook (v3 subscriptions & coupon seat-limit enforcement, absent from this repo).

2. All Features & End-to-End Flows (Happy Path + Error Paths)

  • Billing Screen Bootstrap (billing_screen.dart): initState() registers WidgetsBindingObserver and runs _refreshAll(): (1) _fetchBillingAccess() → RPC my_billing_access(p_company_id) (if is_owner, also RPC billing_admins); on RPC failure, falls back to _canBill = _canManage (isAdmin), _isOwner = false. (2) Parallel fetch of companies billing columns, active company_licenses + license_tiers + user_license_assignments, and (if _canBill) get-billing-invoices. (3) AppLifecycleState.resumed silently refreshes to capture changes from external Stripe tabs.
  • Buy New Subscription (_showBuyPlanDialog, billing_screen.dart:1016-1153): Enabled when _canBill && (!_hasSubscription || _subStatus == 'canceled'). Queries paid license_tiers (monthly_price_pln > 0), allows ≤1 main plan + optional add-ons (is_addon == true || id == 'energy_coop') with 1..1000 seats → invokes start-checkout ({company_id, items}) → opens data['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 from user_license_assignments; locks switching away from main tiers with assigned users (lockedMains) and sets seat stepper minimum to max(assigned[id], 1). User clicks "Sprawdź koszt" → invokes preview-plan-change → displays credit notice (total < 0) or amount_now / 100 PLN due now + next_monthly → clicks "Potwierdź i zapłać" → invokes change-plan with {company_id, items, proration_date} → silently refreshes and shows "Plan zmieniony. Faktura pojawi się na liście.". Any seat edit resets preview = null.
  • Auto-Renew Toggle & Cancel Survey (_setAutoRenew, _askCancelReason, billing_screen.dart:399-552): Enabling invokes set-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) → invokes set-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 invokes create-portal-session ({company_id, return_url?} on Web) and launches URL. Invoices invoke get-billing-invoices, display date, number (· Zmiana planu badge if any line has proration == true), amount (amount_due / 100 if open, else amount_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 active company_members not yet assigned to that license (if none, shows "Wszyscy użytkownicy mają już przypisaną licencję <tierName>."); inserts into user_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 toggles SwitchListTile per admin → RPC set_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): CompanyUsageOverviewWidget fetches company_storage_status RPC and company_members + user_token_quotas (sorted by tokensUsed desc), rendering disk bar, warning banner, team AI token total, and expandable per-member DataTable. UserUsageCard fetches my_token_status and company_storage_status RPCs.
  • Platform Operator Panel (operator_panel_screen.dart, operator_coupons_view.dart):
    • Tab 1 (Firmy i licencje): Calls RPC operator_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 RPC operator_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. Postgres 42501 shows "Brak dostępu. Panel jest tylko dla właściciela i administratorów firmy operatora.".
    • Tab 2 (Kody rabatowe): Calls RPC operator_grants() + license_tiers with non-empty stripe_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 returned grant.code to clipboard).
  • In-Repo Transactional Edge Functions:
    • stripe-webhook/index.ts: Verifies stripe-signature via stripe.webhooks.constructEventAsync, handles ONLY checkout.session.completed against agreements by stripe_session_id (idempotent if stripe_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, check company_members.role === 'admin' && is_active === true (NOTE: rejects 'owner'!), skip Resend if user_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 have seats > 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_tiers with .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 with assigned[id] > 0 cannot 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; proration amount_now is in grosze (/ 100), credit when preview['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) = RPC my_billing_access.can_manage_billing (fallback _canManage on 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 & Pay stays hidden until preview != null; any seat/plan change nulls preview, forcing re-preview and sending proration_date to change-plan (billing_screen.dart:650,693-696,765-796).
  • BR-BILL-09 (Invoice Amount & Proration Display): open invoices use amount_due / 100, others amount_paid / 100; currency defaults to 'PLN'; Unix seconds * 1000; proration badge shown if any lines item has proration == true (billing_screen.dart:1891-1905).
  • BR-BILL-10 (AI Token Quota Defaults & Formatting): Default monthly limit fallback 10000; remaining = max(0, limit - used); daysUntilReset defaults to 30 if resetAt == null; counts format as X.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 5368709120 B (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 RPC can_upload and returns true on 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 and operator-coupons; Postgres 42501 displays 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 to dashboard.stripe.com/test/... vs dashboard.stripe.com/... (operator_panel_screen.dart:226-233).
  • BR-BILL-16 (Operator Coupon Validation Rules): Optional code matches ^[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} with duration_months ∈ 1..36 when repeating; redeem_by ∈ [now+1d, now+3y]; max_redemptions ∈ 1..10000 (default 1); per-tier seat_limits ∈ 1..1000; max_total_seats ∈ 1..10000; mandatory note.trim().length >= 3 ('Podaj powód'). Only tiers with non-empty stripe_price_id are 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 with outcome: '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-webhook Verification & Idempotency): Stripe API "2024-06-20"; verifies stripe-signature via constructEventAsync (HTTP 400 {error: "Invalid signature"} on mismatch; 500 on missing env/header/DB error). Idempotent when agreements.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-updated and send-subscription-cancelled require valid Bearer JWT + active company_members with role === "admin" (rejects "owner"!), respect user_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_status uses 'canceled' (1 l, Stripe), while company_licenses.status uses 'cancelled' (2 ls).

5. Technical Contract (Inputs → Processing → Side Effects)

  • Tables: companies, company_licenses, license_tiers, user_license_assignments, company_members, user_token_quotas, user_profiles, agreements (in stripe-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 (uses ENERGY_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 use ENERGY_SUPABASE_*, RESEND_API_KEY, FROM_EMAIL, PORTAL_URL).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact 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 HMACHandles v3 company subscription lifecycle & post-checkout coupon seat-limit cancellation
Stripe -> supabase/functions/stripe-webhook (in-repo)HTTPS / stripe-signature HMACcheckout.session.completed -> updates agreements.stripe_payment_status = 'paid' + Resend email
stripe-webhook, send-subscription-* -> Resend APIHTTPS / Bearer RESEND_API_KEYPOST https://api.resend.com/emails
OperatorPanelScreen -> Stripe DashboardExternal Browser Linkhttps://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 to PermissionProvider.isAdmin on RPC error so admins are never locked out during phased DB migrations (billing_screen.dart:137).
  • Stripe Promotion Codes cannot natively enforce Planovi company_id or per-tier seat caps at checkout, so handle-stripe-webhook enforces them post-checkout (operator_coupons_view.dart:11-12).
  • _DetailSheetListener manually relays _loadDetail state into modal bottom sheets because bottom sheets don’t rebuild from parent setState (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-96 defines isNearCapacity as [0.80, 0.95) and isOverCapacity as >= 0.95, but company_usage_overview_widget.dart:154 only renders the banner for isNearCapacity -> check isNearCapacity || isOverCapacity.
  • Trialing or past-due licenses invisible on BillingScreen -> _fetchLicenses() (billing_screen.dart:232) filters .eq('status', 'active') even though CompanyLicense.isActive includes 'trialing' and _statusBadge styles 'trialing'/'past_due'.
  • Company owner gets 500/Forbidden from send-subscription-updated & send-subscription-cancelled -> both check membership.role !== "admin" (send-subscription-updated:80, send-subscription-cancelled:79), rejecting "owner".
  • stripe-webhook rejected with 401 by Supabase gateway -> supabase/config.toml omits [functions.stripe-webhook] verify_jwt = false; must deploy with --no-verify-jwt or add config block.
  • Unescaped HTML in transactional emails -> stripe-webhook, send-subscription-updated, send-subscription-cancelled interpolate 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.