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): Submitssubmit-inquiryfrom marketing/DealFlow site and pays via Stripe Checkout. - Company Owner / Delegated Billing Admin (
canManageBilling): Callsstart-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), managesconverter_orders. Onlyowner/admin(NOTtechnician) may calltoggle_building_billing. - Stripe Webhooks: Signed HTTP POSTs to
handle-stripe-webhook(SaaS) andstripe-webhook(Agreements). - Platform Operator / Service Role: Generates converter serials (
next_edge_converter_serial), runsfn_calculate_billing_records, fulfillsconverter_orders.
- Public Prospect (
2. All Features & End-to-End Flows
handle-stripe-webhookvsstripe-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-v1check,401on failure). Handlescheckout.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,400on bad sig). Handles ONLYcheckout.session.completed, settingagreements.stripe_payment_status = 'paid'bystripe_session_idand emailing Polish confirmation. Zero other files inplanovi-backendreferenceagreements.stripe_session_id.
- Public Purchase Inquiry (
submit-inquiry/index.ts): PublicPOST-> validatesclientName,clientEmail(regex),clientCompany, non-emptypackages[](starter/pro/enterprise/energy_coop,seats >= 1, no duplicates, max 1 non-addon main plan) -> checks 24h duplicatependinginquiry (returns200 { success: false, duplicate: true }) -> verifieslicense_tiers.stripe_price_id-> insertsinquiries(status='pending',source='website_form') -> creates Stripe Checkout (mode=subscription,allow_promotion_codes=true, hardcodedsuccess_url=https://dev-dealflow.planovi.app/payment-success.php?session_id={CHECKOUT_SESSION_ID},cancel_url=${PORTAL_URL}/inquiry?cancelled=1) -> updatesinquiries-> returns200 { success: true, stripeUrl }. - In-App Checkout (
start-checkout/index.ts):POST(405otherwise) ->requireBillingManager-> verifies no active/trialing/past_duecompanies.stripe_subscription_id-> validatesitems(1..1000integer seats, max 1 main plan) -> creates Stripe Checkout (payment_method_collection=if_required,allow_promotion_codes=true,metadata[purpose]=existing_company) -> returns200 { 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 finalitems(0..1000int seats,totalSeats > 0,seats >= assignedinuser_license_assignments, non-empty diff, max 1 main plan), require Stripe sub status in['active','trialing','past_due']. preview-plan-change: callsPOST /v1/invoices/create_preview(fallbackGET /v1/invoices/upcomingon404/resource_missing) withproration_behavior=always_invoiceand returns{ amount_now, total, currency, next_monthly, proration_date, lines }.change-plan: additionally enforceslicense_grants(seat_limits,max_total_seats) from expanded subscription discounts -> honors clientproration_datewithin 1h (now - pd < 3600) -> callsPOST /v1/subscriptions/{id}(proration_behavior=always_invoice,payment_behavior=error_if_incomplete,cancel_at_period_end=false) -> on402/card_declined/subscription_payment_intent_requires_actionreturns HTTP402 { success: false, payment_failed: true, error: "..." }with zero DB changes -> on success immediately syncscompany_licenses&companies.license_tierand returns{ success: true, license_tier, latest_invoice_url }.
- Both enforce
- Auto-Renew (
set-auto-renew/index.ts):requireBillingManager-> updatescancel_at_period_endon ALL active subscription IDs (companies+company_licenses) -> mirrors flag tocompanies-> if disabling andreason/feedbackgiven (200/2000 char caps), saves to activecompany_licenses->404if no active subscription. - Stripe Customer Portal & Invoices (
create-portal-session/index.ts,get-billing-invoices/index.ts):create-portal-session: resolvesstripe_customer_id(companiesthen latestcompany_licenses), allowlistsreturn_urlhost (panel.planovi.app,dev-panel.planovi.app,localhost,127.0.0.1), createsPOST /v1/billing_portal/sessions->404if no Stripe customer.get-billing-invoices:GET/POST, auto-selectscompany_idif user has exactly 1 active membership -> checkscanManageBilling-> fetches up to 50 non-draftStripe invoices across distinctcompany_licenses.stripe_customer_ids, sortedcreated DESC.
- Legacy Subscription Emails (
send-subscription-updated/index.ts,send-subscription-cancelled/index.ts): Bearer JWT + strictrole === "admin"check (blocksowner!) -> fetchescompany_licenses+license_tiers+ calleruser_profiles-> emails via Resend unlessemail_opt_out. All errors return HTTP500. - Hardware Converter Lifecycle, Orders & Building Billing (
20261118140000_converter_lifecycle_orders_billing.sql):next_edge_converter_serial(): generates collision-freePLN-EC-00000001(skippingPLN-EC-*&ASL-EC-*inedge_convertersandconverters).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(): syncsedge_converters->converters,gateway_registry, MAINlogical_points, default MAINcounters(serial||'-M1',modbus_address=1,zamel_lem60), setsbuildings.main_counter_id = COALESCE(main_counter_id, v_lp_id), and notifies activeowner/adminviasystem_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 toMAIN, demotes prior buildingMAINcounter toSUBMETER, updatesbuildings.main_counter_id.toggle_building_billing(building_id, enabled, effective_from, effective_to, note): owner/admin-only toggle updatingbuildings.{is_billing_enabled, billing_started_at, billing_ended_at}and appendingbuilding_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-invoicesgrant access iff caller is activeowner, OR activeadminwithcan_manage_billing = true, OR activeadminin 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_addonplan (starter|pro|enterprise) + optional add-ons (energy_coop). Selecting only an add-on is allowed (400otherwise).BR-SUB-03(Seat Quantity & Assigned-Seat Floor):start-checkout: int1..1000;preview-plan-change/change-plan: int0..1000,totalSeats > 0,want >= assignedinuser_license_assignments, non-empty diff.BR-SUB-04(Single Active Subscription & Multi-Sub Block):start-checkout&handle-stripe-webhookblock adding a second active/trialing/past_due sub;preview-plan-change/change-planblock legacy multi-sub companies ("Ta firma ma kilka starszych subskrypcji. Skontaktuj się z nami: info@planovi.app").BR-SUB-05(companies.license_tierDerivation):recomputeLicenseTier(change-plan,handle-stripe-webhook) maps{ starter:1, pro:2, enterprise:3, energy_coop:4 }, computesbase = Math.max(1, ...nums.filter(n => n <= 3)), returnsnums.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. Violatinggrant.company_id,seat_limits[tier], ormax_total_seatstriggers immediatePOST /v1/refunds+DELETE /v1/subscriptions/{id}and logslicense_grant_redemptions.outcome = 'cancelled_over_limit'. - At in-app
change-plan: blocks over-limit changes with400. - At webhook
customer.subscription.updated: logsoutcome = 'over_limit_update'without cancelling.
- At checkout (
BR-SUB-07(Atomic Proration & 1-Hour Price Lock):change-planusesproration_behavior=always_invoice,payment_behavior=error_if_incomplete, forcescancel_at_period_end=false, and honors clientproration_dateif integer within[now - 3600, now]. Card/3DS failure returns402with zero mutations.BR-SUB-08(14-Day Grace Period Timestamp):handle-stripe-webhooksetssubscription_status='past_due'and preserves firstpayment_failed_at = existing ?? nowoninvoice.payment_failed; clearspayment_failed_at = nulloninvoice.paidor activesubscription.updated.BR-SUB-09(24-Hour Inquiry Dedup):submit-inquiryreturns200 { success: false, duplicate: true }if apendinginquiry for the same lowercased email exists within 24h.BR-SUB-10(Converter Serial & NIP Normalization):next_edge_converter_serial()formatsPLN-EC-XXXXXXXX;normalize_nipstrips[^0-9A-Za-z]and uppercases. Matchingreserved_nippermits reclaiming a converter inclaim_or_assign_converter_to_building.BR-SUB-11(MAIN vs SUBMETER Separation & Building Billing Filter):mr=2ormeter_id > 1->SUBMETER;mr=3->PV; elseMAIN. All building/coop energy RPCs excludeCOALESCE(lp.meter_role, 'MAIN') = 'SUBMETER'.fn_calculate_billing_recordsadditionally excludes buildings withis_billing_enabled = false(defaultfalse).
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, sequenceedge_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 -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-microservices (inquiry.php) -> submit-inquiry | HTTPS POST / anon key | Creates Stripe Checkout redirecting to dev-dealflow.planovi.app/payment-success.php |
planovi-flutter-app -> Module 3 SaaS Functions & SQL RPCs | HTTPS POST + PostgREST / User JWT | start-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-webhook | HTTPS POST / HMAC stripe-signature | STRIPE_INQUIRY_WEBHOOK_SECRET (SaaS) & STRIPE_WEBHOOK_SECRET (Agreements) |
planovi-converter/admin -> next_edge_converter_serial, edge_converters, converter_orders | PostgREST / service_role or admin JWT | Serial provisioning & hardware order fulfillment |
7. Why It Works This Way
- Webhook-only provisioning on
start-checkout: Prevents abandoned Stripe Checkout sessions from creating unpaidcompany_licenses;change-plansyncs synchronously after Stripe succeeds for instant UI feedback. INVITE_LINK_MODE=token_hashinhandle-stripe-webhook: Prevents corporate email link scanners from pre-fetching/auth/v1/verifyand 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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
Resend rejects send-subscription-updated emails when FROM_EMAIL unset | Hardcoded 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 email | send-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 & billing | set_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 telemetry | fn_sync_edge_converter_to_converters (20261118140000:573-585) omits status = EXCLUDED.status on ON CONFLICT (hardware_id) DO UPDATE | SELECT 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-change | preview-plan-change omits license_grants seat limit checks (change-plan enforces them) | Compare license_grants (seat_limits, max_total_seats) vs requested seats | Port grantForSubscription validation to preview-plan-change |
| Subscription emails have invisible white text on white background | Incomplete dark->light migration (#F1F5F9 / #CBD5E0 on #FFFFFF in send-subscription-updated:230-241 & send-subscription-cancelled:192-201) | Inspect rendered HTML in Resend dashboard | Migrate both functions to _shared/email.ts emailShell with #09090B text |