Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Backend (Edge Functions) v1.0 (frozen on 2026-11-23, commit f026e3b). Switch to Latest →

3. SaaS Subscriptions, Stripe Billing & Hardware Orders

Repository: Backend (planovi-backend) • Rule Prefix: BR-SUB • Documented Rules: 11 • Open [TEAM_WHY_NEEDED] Questions: 5

1. Business Purpose & Actors

Manages Planovi’s commercial SaaS lifecycle (public purchase inquiries, in-app Stripe checkout, mid-cycle prorated plan/seat updates, auto-renew toggling, Stripe Customer Portal, invoice retrieval, webhook-driven provisioning/grace-period/discount enforcement, legacy agreement checkout webhook, and subscription emails) PLUS hardware converter provisioning/lifecycle, NIP-based converter claiming, MAIN vs SUBMETER/PV meter separation, hardware production/service orders (converter_orders), and per-building billing switches (building_billing_logs).

  • Actors:
    • Public Prospect (anon): Submits submit-inquiry from marketing/DealFlow site and pays via Stripe Checkout.
    • Company Owner / Delegated Billing Admin (canManageBilling): Calls start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices.
    • Company Owner / Admin / Technician: Claims/assigns converters (claim_or_assign_converter_to_building), selects main counter (set_building_main_counter), manages converter_orders. Only owner/admin (NOT technician) may call toggle_building_billing.
    • Stripe Webhooks: Signed HTTP POSTs to handle-stripe-webhook (SaaS) and stripe-webhook (Agreements).
    • Platform Operator / Service Role: Generates converter serials (next_edge_converter_serial), runs fn_calculate_billing_records, fulfills converter_orders.

2. All Features & End-to-End Flows

  • handle-stripe-webhook vs stripe-webhook (Two Distinct Webhooks):
    • supabase/functions/handle-stripe-webhook/index.ts: Active SaaS subscription & inquiry webhook (STRIPE_INQUIRY_WEBHOOK_SECRET, manual Web Crypto HMAC-SHA256 with 300s replay window & multi-v1 check, 401 on failure). Handles checkout.session.completed (existing company OR new inquiry provisioning + owner invite), customer.subscription.updated, customer.subscription.deleted, invoice.paid, invoice.payment_failed.
    • supabase/functions/stripe-webhook/index.ts: Separate/legacy Agreements checkout webhook (STRIPE_WEBHOOK_SECRET, https://esm.sh/stripe@14, apiVersion: "2024-06-20", constructEventAsync, 400 on bad sig). Handles ONLY checkout.session.completed, setting agreements.stripe_payment_status = 'paid' by stripe_session_id and emailing Polish confirmation. Zero other files in planovi-backend reference agreements.stripe_session_id.
  • Public Purchase Inquiry (submit-inquiry/index.ts): Public POST -> validates clientName, clientEmail (regex), clientCompany, non-empty packages[] (starter/pro/enterprise/energy_coop, seats >= 1, no duplicates, max 1 non-addon main plan) -> checks 24h duplicate pending inquiry (returns 200 { success: false, duplicate: true }) -> verifies license_tiers.stripe_price_id -> inserts inquiries (status='pending', source='website_form') -> creates Stripe Checkout (mode=subscription, allow_promotion_codes=true, hardcoded success_url=https://dev-dealflow.planovi.app/payment-success.php?session_id={CHECKOUT_SESSION_ID}, cancel_url=${PORTAL_URL}/inquiry?cancelled=1) -> updates inquiries -> returns 200 { success: true, stripeUrl }.
  • In-App Checkout (start-checkout/index.ts): POST (405 otherwise) -> requireBillingManager -> verifies no active/trialing/past_due companies.stripe_subscription_id -> validates items (1..1000 integer seats, max 1 main plan) -> creates Stripe Checkout (payment_method_collection=if_required, allow_promotion_codes=true, metadata[purpose]=existing_company) -> returns 200 { success: true, url }. Does NOT mutate licenses directly (webhook-only).
  • Preview & Execute Plan Change (preview-plan-change/index.ts, change-plan/index.ts):
    • Both enforce requireBillingManager, reject legacy multi-sub companies, validate final items (0..1000 int seats, totalSeats > 0, seats >= assigned in user_license_assignments, non-empty diff, max 1 main plan), require Stripe sub status in ['active','trialing','past_due'].
    • preview-plan-change: calls POST /v1/invoices/create_preview (fallback GET /v1/invoices/upcoming on 404/resource_missing) with proration_behavior=always_invoice and returns { amount_now, total, currency, next_monthly, proration_date, lines }.
    • change-plan: additionally enforces license_grants (seat_limits, max_total_seats) from expanded subscription discounts -> honors client proration_date within 1h (now - pd < 3600) -> calls POST /v1/subscriptions/{id} (proration_behavior=always_invoice, payment_behavior=error_if_incomplete, cancel_at_period_end=false) -> on 402/card_declined/subscription_payment_intent_requires_action returns HTTP 402 { success: false, payment_failed: true, error: "..." } with zero DB changes -> on success immediately syncs company_licenses & companies.license_tier and returns { success: true, license_tier, latest_invoice_url }.
  • Auto-Renew (set-auto-renew/index.ts): requireBillingManager -> updates cancel_at_period_end on ALL active subscription IDs (companies + company_licenses) -> mirrors flag to companies -> if disabling and reason/feedback given (200/2000 char caps), saves to active company_licenses -> 404 if no active subscription.
  • Stripe Customer Portal & Invoices (create-portal-session/index.ts, get-billing-invoices/index.ts):
    • create-portal-session: resolves stripe_customer_id (companies then latest company_licenses), allowlists return_url host (panel.planovi.app, dev-panel.planovi.app, localhost, 127.0.0.1), creates POST /v1/billing_portal/sessions -> 404 if no Stripe customer.
    • get-billing-invoices: GET/POST, auto-selects company_id if user has exactly 1 active membership -> checks canManageBilling -> fetches up to 50 non-draft Stripe invoices across distinct company_licenses.stripe_customer_ids, sorted created DESC.
  • Legacy Subscription Emails (send-subscription-updated/index.ts, send-subscription-cancelled/index.ts): Bearer JWT + strict role === "admin" check (blocks owner!) -> fetches company_licenses + license_tiers + caller user_profiles -> emails via Resend unless email_opt_out. All errors return HTTP 500.
  • Hardware Converter Lifecycle, Orders & Building Billing (20261118140000_converter_lifecycle_orders_billing.sql):
    • next_edge_converter_serial(): generates collision-free PLN-EC-00000001 (skipping PLN-EC-* & ASL-EC-* in edge_converters and converters).
    • fn_resolve_reserved_nip_before_edge_write() & fn_claim_reserved_converters_on_company_nip(): bidirectional NIP-based converter reservation and automatic company claiming (normalize_nip).
    • fn_sync_edge_converter_to_converters(): syncs edge_converters -> converters, gateway_registry, MAIN logical_points, default MAIN counters (serial||'-M1', modbus_address=1, zamel_lem60), sets buildings.main_counter_id = COALESCE(main_counter_id, v_lp_id), and notifies active owner/admin via system_notifications (type='converter_ready').
    • claim_or_assign_converter_to_building(hardware_id, company_id, building_id): owner/admin/technician claims unassigned or NIP-reserved converter into org/building.
    • set_building_main_counter(building_id, counter_id): owner/admin/technician promotes target counter to MAIN, demotes prior building MAIN counter to SUBMETER, updates buildings.main_counter_id.
    • toggle_building_billing(building_id, enabled, effective_from, effective_to, note): owner/admin-only toggle updating buildings.{is_billing_enabled, billing_started_at, billing_ended_at} and appending building_billing_logs.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-SUB)

  • BR-SUB-01 (Billing RBAC): start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices grant access iff caller is active owner, OR active admin with can_manage_billing = true, OR active admin in a company with 0 active owners (403 "Płatnościami zarządza właściciel firmy. Poproś właściciela o dostęp do płatności.").
  • BR-SUB-02 (Max One Main Plan): At most one !license_tiers.is_addon plan (starter|pro|enterprise) + optional add-ons (energy_coop). Selecting only an add-on is allowed (400 otherwise).
  • BR-SUB-03 (Seat Quantity & Assigned-Seat Floor): start-checkout: int 1..1000; preview-plan-change/change-plan: int 0..1000, totalSeats > 0, want >= assigned in user_license_assignments, non-empty diff.
  • BR-SUB-04 (Single Active Subscription & Multi-Sub Block): start-checkout & handle-stripe-webhook block adding a second active/trialing/past_due sub; preview-plan-change/change-plan block legacy multi-sub companies ("Ta firma ma kilka starszych subskrypcji. Skontaktuj się z nami: info@planovi.app").
  • BR-SUB-05 (companies.license_tier Derivation): recomputeLicenseTier (change-plan, handle-stripe-webhook) maps { starter:1, pro:2, enterprise:3, energy_coop:4 }, computes base = Math.max(1, ...nums.filter(n => n <= 3)), returns nums.includes(4) ? [base, 4] : [base] (floors at [1] even with 0 active licenses).
  • BR-SUB-06 (Discount Grant Enforcement — Decision A):
    • At checkout (handle-stripe-webhook): validated BEFORE company/license creation. Violating grant.company_id, seat_limits[tier], or max_total_seats triggers immediate POST /v1/refunds + DELETE /v1/subscriptions/{id} and logs license_grant_redemptions.outcome = 'cancelled_over_limit'.
    • At in-app change-plan: blocks over-limit changes with 400.
    • At webhook customer.subscription.updated: logs outcome = 'over_limit_update' without cancelling.
  • BR-SUB-07 (Atomic Proration & 1-Hour Price Lock): change-plan uses proration_behavior=always_invoice, payment_behavior=error_if_incomplete, forces cancel_at_period_end=false, and honors client proration_date if integer within [now - 3600, now]. Card/3DS failure returns 402 with zero mutations.
  • BR-SUB-08 (14-Day Grace Period Timestamp): handle-stripe-webhook sets subscription_status='past_due' and preserves first payment_failed_at = existing ?? now on invoice.payment_failed; clears payment_failed_at = null on invoice.paid or active subscription.updated.
  • BR-SUB-09 (24-Hour Inquiry Dedup): submit-inquiry returns 200 { success: false, duplicate: true } if a pending inquiry for the same lowercased email exists within 24h.
  • BR-SUB-10 (Converter Serial & NIP Normalization): next_edge_converter_serial() formats PLN-EC-XXXXXXXX; normalize_nip strips [^0-9A-Za-z] and uppercases. Matching reserved_nip permits reclaiming a converter in claim_or_assign_converter_to_building.
  • BR-SUB-11 (MAIN vs SUBMETER Separation & Building Billing Filter): mr=2 or meter_id > 1 -> SUBMETER; mr=3 -> PV; else MAIN. All building/coop energy RPCs exclude COALESCE(lp.meter_role, 'MAIN') = 'SUBMETER'. fn_calculate_billing_records additionally excludes buildings with is_billing_enabled = false (default false).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Unlicensed : company created
    Unlicensed --> Active : checkout.session.completed (grant ok)
    Unlicensed --> Unlicensed : grant violated -> refund + DELETE sub
    Active --> PastDue : invoice.payment_failed (set payment_failed_at)
    PastDue --> Active : invoice.paid (clear payment_failed_at)
    Active --> Canceled : subscription.deleted / unpaid / incomplete_expired
    PastDue --> Canceled : subscription.deleted
    Canceled --> Active : start-checkout
  • converter_orders.status (CHECK constraint, no transition trigger): 'NEW' -> 'IN_PRODUCTION' -> 'READY' -> 'ASSIGNED' -> 'COMPLETED' | 'CANCELLED'. order_type: 'PRODUCTION' | 'SERVICE'.
  • inquiries.status: 'pending' -> 'paid' (stays 'pending' if grant-cancelled at checkout!).
  • building_billing_logs.action: 'ENABLED' | 'DISABLED' | 'UPDATED_DATES'.

5. Technical Contract

  • Endpoints: submit-inquiry, start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices, handle-stripe-webhook, stripe-webhook, send-subscription-updated, send-subscription-cancelled.
  • Tables Created/Altered (20261118140000): New: building_billing_logs, converter_orders, sequence edge_converter_serial_seq. Altered: edge_converters, storage_streams (facility_id DROP NOT NULL), edge_device_commands, energy_meters, converters, gateway_registry, logical_points, counters, devices (+counter_id), buildings (+main_counter_id, +is_billing_enabled, +billing_started_at, +billing_ended_at).
  • Tables Touched by SaaS Functions: companies, company_licenses, license_tiers, user_license_assignments, company_members, user_profiles, inquiries, license_grants, license_grant_redemptions, agreements.
  • External APIs: Stripe REST API (/v1/checkout/sessions, /v1/subscriptions/{id}, /v1/invoices/create_preview, /v1/invoices/upcoming, /v1/invoices, /v1/refunds, /v1/billing_portal/sessions), Resend API.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-microservices (inquiry.php) -> submit-inquiryHTTPS POST / anon keyCreates Stripe Checkout redirecting to dev-dealflow.planovi.app/payment-success.php
planovi-flutter-app -> Module 3 SaaS Functions & SQL RPCsHTTPS POST + PostgREST / User JWTstart-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices, send-subscription-*; RPCs claim_or_assign_converter_to_building, set_building_main_counter, toggle_building_billing
Stripe -> handle-stripe-webhook / stripe-webhookHTTPS POST / HMAC stripe-signatureSTRIPE_INQUIRY_WEBHOOK_SECRET (SaaS) & STRIPE_WEBHOOK_SECRET (Agreements)
planovi-converter/admin -> next_edge_converter_serial, edge_converters, converter_ordersPostgREST / service_role or admin JWTSerial provisioning & hardware order fulfillment

7. Why It Works This Way

  • Webhook-only provisioning on start-checkout: Prevents abandoned Stripe Checkout sessions from creating unpaid company_licenses; change-plan syncs synchronously after Stripe succeeds for instant UI feedback.
  • INVITE_LINK_MODE=token_hash in handle-stripe-webhook: Prevents corporate email link scanners from pre-fetching /auth/v1/verify and burning single-use owner invite tokens before the customer clicks.
  • Dual preview endpoints (create_preview -> upcoming): Maintains compatibility across older and newer Stripe API versions.
  • [TEAM_WHY_NEEDED: Is stripe-webhook/index.ts (agreements payment webhook) still used in production/DealFlow, or dead code?]
  • [TEAM_WHY_NEEDED: Why does submit-inquiry hardcode dev-dealflow.planovi.app for success_url and omit payment_method_collection=if_required?]
  • [TEAM_WHY_NEEDED: Why are send-subscription-updated and send-subscription-cancelled client-triggered (admin-only) instead of triggered server-side from change-plan / handle-stripe-webhook?]
  • [TEAM_WHY_NEEDED: Why does recomputeLicenseTier floor base license_tier at [1] (Starter) even when a company has 0 active licenses after cancellation?]
  • [TEAM_WHY_NEEDED: Where is the 14-day companies.payment_failed_at grace cutoff actually enforced?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Resend rejects send-subscription-updated emails when FROM_EMAIL unsetHardcoded fallback typo "noreply@planowi.app" (send-subscription-updated/index.ts:139)Check send-subscription-updated logs (SEND SUBSCRIPTION UPDATED)Change fallback to "noreply@planovi.app" and set FROM_EMAIL
Company owner gets HTTP 500 "Forbidden: only company admins can request this" on subscription emailsend-subscription-updated:80 & send-subscription-cancelled:79 check membership.role !== "admin"Inspect company_members.role (owner since webhook v8)Allow owner + canManageBilling (or retire client-triggered email endpoints)
Demoted building counter still double-counted in energy charts & billingset_building_main_counter (20261118140000:1584-1606) demotes counters.role = 'SUBMETER' but forgets to update old counter’s logical_points.meter_role = 'SUBMETER'SELECT c.id, c.role, lp.meter_role FROM counters c JOIN logical_points lp ON lp.id=c.id WHERE c.building_id='<id>';Update logical_points.meter_role = 'SUBMETER' for demoted counters in set_building_main_counter
Putting converter in MAINTENANCE in edge_converters does not block telemetryfn_sync_edge_converter_to_converters (20261118140000:573-585) omits status = EXCLUDED.status on ON CONFLICT (hardware_id) DO UPDATESELECT e.status, c.status FROM edge_converters e JOIN converters c ON c.hardware_id=e.serial_number;Add status = EXCLUDED.status to ON CONFLICT in fn_sync_edge_converter_to_converters
User gets 400 in change-plan after valid preview-plan-changepreview-plan-change omits license_grants seat limit checks (change-plan enforces them)Compare license_grants (seat_limits, max_total_seats) vs requested seatsPort grantForSubscription validation to preview-plan-change
Subscription emails have invisible white text on white backgroundIncomplete dark->light migration (#F1F5F9 / #CBD5E0 on #FFFFFF in send-subscription-updated:230-241 & send-subscription-cancelled:192-201)Inspect rendered HTML in Resend dashboardMigrate both functions to _shared/email.ts emailShell with #09090B text