24 — Subscription Billing, Tier Limits & Lifecycle
Version: 1.19
Last Updated: 2026-08-03 18:23:23
This document consolidates the engineering changes for subscription tiers, limits, upgrade/downgrade flows, and in-app upgrade surfaces (see §10 for the user-journey and API material formerly in doc 25). It supplements docs/23 (product matrix) and docs/18 (Stripe global pricing) with authoritative implementation details.
1. Tier catalog
Section titled “1. Tier catalog”1.1 Source of truth
Section titled “1.1 Source of truth”backend/billing/tiers.json is the single source of truth for tier names, USD
prices, module slugs, local-currency prices, and per-tier limits.
{ "tiers": [ { "slug": "essential", "name": "Essential", // internal; public label ≡ name "usd": 39, "modules": [ "medication_dispensing", "care_calendar", "prescription_management", "condition_templates" ], // condition_templates: 2 free starter packs (general_palliative, medication_orchestra) // prescription_management: included on every tier; capped by max_medicines "limits": { "max_carers": 2, // admin counts as 1 carer "max_observers": 1, "max_care_recipients": 1, "max_medicines": 2, // active patient_scripts "max_reason_types": 5 }, "local_prices": { "AUD": 59, ... } }, { "slug": "professional", "name": "Family", // public display name "usd": 69, "modules": [ // All Essential modules + "sleep_tracking", "vitals_tracking", "key_contacts", "condition_templates", // 2 free + can purchase additional packs one-time "custom_observations", "family_help", "family_journal", "preventive_care" ], "limits": { "max_carers": 3, "max_observers": 2, "max_care_recipients": 2, "max_medicines": 5, "max_reason_types": null } }, { "slug": "complete", "name": "Complete", "usd": 99, "modules": [ // All Family modules + "shopping", "pain_tracking", "condition_templates", // library + apply; paid profiles purchased à la carte (see doc 25 §3) "care_observations", "goals_of_care", "clinical_episodes", "caregiver_wellbeing", "frailty_tracking", "behaviour_tracking", "care_protocols", "cognitive_tracking", "observational_pain", "swallowing_safety", "falls_tracking", "respiratory_oxygen", "therapy_records", "equipment_management", "patient_voice", "care_intelligence" ], "limits": { "max_carers": 7, "max_observers": 7, "max_care_recipients": 5, "max_medicines": null, "max_reason_types": null // unlimited prescriptions } } ]}After editing tiers.json run the seeder to propagate changes:
python -m scripts.stripe_seed_tiers # inside the backend containerThe seeder writes limits to stripe_tiers.limits (JSONB column added in
V047__tier_limits_and_pending_downgrade.sql).
1.2 Product delivery vs entitlement (2026-05-30)
Section titled “1.2 Product delivery vs entitlement (2026-05-30)”Two artefacts must stay aligned but serve different purposes:
| File | Role |
|---|---|
backend/billing/tiers.json | Commercial bundle — which module slugs Stripe provisions per plan |
backend/billing/module_delivery.json | Product readiness — live / partial / planned UX labels |
Entitlement is written by stripe_service.sync_subscription_items into
subscriptions (one row per module slug on the tenant). Delivery does not
change gates — require_module() still keys off subscriptions.status.
| Delivery | Subscriptions UI label (when entitled) | Example |
|---|---|---|
live | Active / Ready to use in the app | Medication dispensing |
partial | Included — rolling out | condition_templates (unlock + Care Start apply on dev; VPS V006–V010 deploy + marketing bundle UI pending) |
planned | Coming soon | care_intelligence, family_journal, clinical_anatomy, … |
clinical_anatomy (2026-05-31): Registered in module_delivery.json → planned
only. Not in tiers.json, module_prices.json, or Stripe — separate plug-in
package (packages/clinical-anatomy/). Does not affect checkout, provisioning, or
pain_tracking entitlements. When productised: add slug to tier bundles + à la carte
price, then move delivery to live and wire frontend/src/integrations/.
API: GET /api/modules/available returns { slugs, meta, delivery } where
delivery[slug] has status, optional note, and primary_route (when set).
Frontend: frontend/src/lib/moduleDelivery.ts imports the same JSON file.
When moving a module from partial → live, update module_delivery.json (and
primary_routes), then regenerate 31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md via python scripts/generate_delivery_register.py.
Do not show “Subscribed” for partial or planned modules — see
components/billing/ModuleAccessRow.tsx.
2. DB schema additions (V047)
Section titled “2. DB schema additions (V047)”| Table | Column | Type | Purpose |
|---|---|---|---|
stripe_tiers | limits | JSONB | Per-tier caps populated by seeder |
tenants pending_downgrade_to_tier_slug | TEXT | Removed in V049__remove_pending_downgrade_columns.sql — see §4 below | |
tenants pending_downgrade_effective_at | TIMESTAMPTZ | Removed in V049 |
3. Upgrade billing (self-serve)
Section titled “3. Upgrade billing (self-serve)”3.1 Flow
Section titled “3.1 Flow”- Admin hits
POST /api/stripe/upgrade-tierwith{ new_tier_slug }. - Backend resolves:
- Current tier from
subscriptions(highest activestripe_price_id). - Whether the tenant’s current price_id maps to a local-currency row in
stripe_tier_local_prices.
- Current tier from
- Creates a one-time Stripe
Couponwithamount_off = old pricein the correct billing currency (local if applicable, else USD). - Creates a Stripe Checkout session for the new tier’s price in the same currency, applying the coupon as a discount.
- On
checkout.session.completedwebhook (kind=upgrade):_provision_tier_upgradecancels the old Stripe subscription.- Syncs module subscriptions via
sync_subscription_items. - Resets
tenants.annual_anniversary_at = NOW().
3.2 Local-currency fix (implemented)
Section titled “3.2 Local-currency fix (implemented)”Previously the coupon was always denominated in USD regardless of the customer’s billing currency. The fix:
# stripe.py: upgrade_tier()local_row = await db.execute( "SELECT currency, amount_cents FROM stripe_tier_local_prices " "WHERE tier_slug = %s AND stripe_price_id = %s AND active = TRUE", (current_tier["slug"], current_tier["stripe_price_id"]),)if local_row: billing_currency = local_row["currency"].lower() coupon_amount_off = int(local_row["amount_cents"]) new_price_id = await _resolve_tier_price_id(db, new_slug, local_row["currency"])else: billing_currency = "usd" coupon_amount_off = int(current_tier["usd_cents"]) new_price_id = new_tier["stripe_price_id"]Test coverage: test_upgrade_tier_uses_local_currency_coupon in
backend/tests/test_signup_flow.py.
4. Downgrade billing (Stripe Customer Portal at renewal)
Section titled “4. Downgrade billing (Stripe Customer Portal at renewal)”Rewritten 2026-05-26. The original “schedule-downgrade with APScheduler” design was reverted in
V049__remove_pending_downgrade_columns.sql. Thepending_downgrade_to_tier_slugandpending_downgrade_effective_atcolumns were dropped; thePOST/DELETE /api/stripe/schedule-downgradeendpoints, the_run_tenant_pending_downgradescheduler job, and thebootstrap_all_tenantsre-registration call were all removed. The legacy section is preserved in 02-REQUIREMENTS.md REQ-BILL-06 (status: Removed) for traceability.
4.1 Today’s behaviour
Section titled “4.1 Today’s behaviour”Downgrades are subscriber-driven through the Stripe Customer Portal at any time. Stripe applies the change at the customer’s next renewal automatically (deferred-downgrade is a built-in Customer Portal feature when configured to do so).
- Cancel current subscription: the in-app
CancelSubscriptionDialog.tsxcallsPOST /api/stripe/cancel-subscription, which performs immediate cancellation via Stripe. There is no scheduled-cancel-at-period-end UI today. - Downgrade at renewal: subscriber visits the Stripe Customer Portal (
POST /api/stripe/portal-sessionreturns a portal URL); selects the new tier; Stripe schedules the change for the renewal date and emails confirmation. The webhook (customer.subscription.updated) fires on the renewal date, the existing webhook handler resyncssubscriptionsandtenant.module_subscriptionsfrom the new Stripe state. - No backend scheduling job is required — Stripe is the scheduler.
4.2 What this means operationally
Section titled “4.2 What this means operationally”- Operators no longer need a “checking pending downgrades” SQL — there is no such state in the DB.
- APScheduler tenant jobs no longer include
pending_downgrade:{tenant_id}. bootstrap_all_tenantsskips pending-downgrade re-registration (no such jobs exist).- The Stripe Portal handles tax, proration, and currency at renewal; no in-house coupon math is required for downgrades.
4.3 Reinstatement path (if a future product decision restores in-app scheduled downgrade)
Section titled “4.3 Reinstatement path (if a future product decision restores in-app scheduled downgrade)”- New migration restoring
pending_downgrade_to_tier_slug/pending_downgrade_effective_atontenants. - New
POST/DELETE /api/stripe/schedule-downgradeendpoints inrouters/stripe.py. - New
services/scheduler._run_tenant_pending_downgradejob andbootstrap_all_tenantsre-registration. - UI surface (
CancelSubscriptionDialogplus a “Schedule downgrade at renewal” surface). - Re-mark REQ-BILL-06 from Removed back to In progress; re-version doc 24 §4 accordingly.
This work is not on the roadmap today — see 04-ROADMAP.md.
4.5 A la carte module add-ons (Shape 2 / Phase F2)
Section titled “4.5 A la carte module add-ons (Shape 2 / Phase F2)”Tenants on any paid tier may add individual modules as monthly Stripe subscription line items without upgrading the whole bundle.
| Component | Location |
|---|---|
| Price catalog | backend/billing/module_prices.json + stripe_module_prices table (migration V095) |
| Seeder | python -m scripts.stripe_seed_module_prices (run after tier seeder in test and live) |
| Add module | POST /api/stripe/add-module { module_slug, currency } — appends a Stripe subscription item, webhook syncs subscriptions |
| Remove module | DELETE /api/stripe/remove-module?module_slug=… — blocked when the module is included in the current tier bundle |
| Price discovery | GET /api/billing/module-prices — used by ModuleUpgrade.tsx and Subscriptions.tsx |
| Locked-module UX | ModuleGate → ModuleUpgrade.tsx shows Upgrade plan and Add this module — $X/mo |
| Admin panel | Subscriptions.tsx module rows: upgrade CTA, à la carte add, Remove add-on when active outside the tier |
Proration follows Stripe defaults on add/remove. Tier bundles remain the recommended path — à la carte is for single-module unlocks on Essential or partial Family gaps.
4.6 Account data export (Phase F3 — format v2.1 shipped 2026-05-28)
Section titled “4.6 Account data export (Phase F3 — format v2.1 shipped 2026-05-28)”Tenant admins can download a privacy-scoped ZIP of their care account before cancellation or at any time while subscribed. The ZIP is CSV-only (no JSON data files).
| Component | Location |
|---|---|
| Category list | GET /api/billing/export/categories — 12 v2 keys |
| Build ZIP | POST /api/billing/export/download { "categories": ["recipients", …] } |
| Privacy transforms | backend/services/export_privacy.py |
| v2 builders | backend/services/export_v2.py — denormalized user archive |
| ZIP orchestration | backend/services/tenant_export_service.py |
| More menu UI | frontend/src/pages/admin/ExportData.tsx — /admin/export |
| Cancel flow | CancelSubscriptionDialog.tsx — Download my data (all categories) + link to /admin/export |
| Audit | audit_log row per export (entity_type=tenant_export, action VIEW) |
| Rate limit | Redis — 5 exports per admin per hour |
Privacy: See 02-REQUIREMENTS.md §4.6. Care-circle names and full emails never appear; physical addresses show address suppressed for privacy reasons; external key-contact names may appear. Pending invitations are not exported.
ZIP contents: README.txt, export_info.csv, {category}-{table}.csv.
Excluded categories: shopping, mind & wellbeing, care alerts. No internal IDs or notification toggles in export CSVs.
Partial (REQ-BILL-17): binary attachments not in ZIP; category picker not auto-filtered to active modules.
Not shipped: re-import (REQ-PLAT-11 / F3.8); Privacy Policy / T&C export sentence (F3.7 / REQ-ENC-06 counsel).
5. Per-tier enforcement
Section titled “5. Per-tier enforcement”5.1 Backend helper
Section titled “5.1 Backend helper”services/tier_limits.py:
lim = await get_tenant_limits(db, tenant_id)# Returns e.g. { "max_medicines": 5, "max_carers": 2, ... }# None means unlimited.
hint = await get_tenant_upgrade_hint(db, tenant_id)# Returns { "to_slug", "to_name", "diff_usd" } for cheapest next tier.
raise_limit_error("LIMIT_MEDICINES", lim["max_medicines"], hint, "message")# Raises HTTP 402 with structured JSON body.5.2 Enforced endpoints
Section titled “5.2 Enforced endpoints”| Endpoint | Limit key | Error code |
|---|---|---|
POST /api/medicines | max_medicines (active count) | LIMIT_MEDICINES |
POST /api/reason-types | max_reason_types (active count per patient_id, V014) | LIMIT_REASON_TYPES |
POST /api/patients | max_care_recipients (total count) | LIMIT_CARE_RECIPIENTS |
POST /api/patients/{id}/members role=carer | max_carers (distinct users) | LIMIT_CARERS |
POST /api/patients/{id}/members role=observer | max_observers (distinct users) | LIMIT_OBSERVERS |
All return HTTP 402 with:
{ "detail": { "code": "LIMIT_MEDICINES", "detail": "Your plan allows up to 5 medicines. Upgrade to add more.", "limit": 5, "upgrade_hint": { "to_slug": "professional", "to_name": "Family", "diff_usd": 30.0 } }}5.3 Billing API
Section titled “5.3 Billing API”GET /api/billing/my-tier returns tier status, limits, subscription billing currency, and upgrade options:
{ "current_tier": { "slug": "essential", "name": "Essential", "usd": 39, "modules": ["…"] }, "current_limits": { "max_carers": 2, "max_observers": 1, "max_care_recipients": 1, "max_medicines": 5, "max_reason_types": 5 }, "billing_currency": "AUD", "upgrade_options": [ { "to_slug": "professional", "to_name": "Family", "diff_display": "A$40.00", "diff_cents": 4000 } ]}Tier and currency resolution live in services/tier_resolution.py; upgrade option formatting in services/tier_upgrade_service.py. Display prices in the tenant’s billing currency, not browser locale.
Tier resolution order (2026-05-27):
- Join
subscriptions.stripe_price_id→stripe_tiers/stripe_tier_local_prices(authoritative when IDs match the live catalogue). - If no row matches, infer tier from active modules — Complete if
shoppingorpain_trackingis active; else Family (professional) if prescription/sleep/vitals/key_contacts/family_help/custom_observations; else Essential if medication/calendar modules only.
This prevents the Subscriptions page from showing “No active subscription plan found” for tenants whose modules are correct but whose stripe_price_id values were never set or still point at test-mode prices after live switchover.
Module sync resolution (sync_subscription_items, 2026-05-30): for each Stripe
subscription line item, lookup_modules_for_price() expands one tier price into
every module in stripe_tiers.modules. Resolution order:
stripe_tiers.stripe_price_id(USD catalogue row).stripe_tier_local_prices.stripe_price_id(fixed local-currency checkout).- Stripe Price metadata
lyncareos_tierwhen the DB row was rotated bystripe_seed_tiersbut the subscription still bills a grandfathered Price (archived in Stripe, no longer listed instripe_tiers). - Legacy
stripe_price_modules(one price → one module).
When checkout.session.completed fires while the subscription is still
incomplete, every provisioning path passes session.payment_status into sync
so a paid checkout still writes subscriptions.status = 'active'.
Operator repair (paid tenant, modules missing or locked):
-
Confirm tier and currency in Stripe Dashboard → Customer → Subscription.
-
Re-pull module rows from Stripe (preferred — no manual price-id surgery):
Terminal window docker compose --env-file .env.production --profile production \exec app python -m scripts.resync_tenant_subscriptions <tenant_id> -
If the plan card is wrong but modules look correct, optionally align
stripe_price_idon active rows to the current catalogue (Family AUD example):UPDATE subscriptions sSET stripe_price_id = (SELECT stripe_price_id FROM stripe_tier_local_pricesWHERE tier_slug = 'professional' AND currency = 'AUD' AND active = TRUELIMIT 1)WHERE tenant_id = <tenant_id> AND status IN ('active','trial','past_due'); -
Ask the subscriber to sign out and back in (or switch tenant if they have several). Signup now sets
users.last_active_tenant_idto the provisioned tenant so JWTtidmatches the paid account.
Re-run only after confirming the tenant’s real Stripe subscription currency/tier
in the Stripe dashboard. Seeded admin accounts (e.g. master user) may have no
stripe_price_id — inference still shows the plan card from active modules.
Grep app logs for has no module/tier mapping — that line means sync skipped a
price before the metadata fallback; after deploy, the same subscription should
resolve via lyncareos_tier on the Price object.
Note (2026-05-26): the previously documented
pending_downgradepayload was removed when thepending_downgrade_*columns were dropped inV049. The/api/billing/my-tierresponse no longer includes that field. See §4.
5.4 Care Profile one-time purchase (Phase F1)
Section titled “5.4 Care Profile one-time purchase (Phase F1)”Canonical catalogue: Palliative Care Archetypes.md §3.2 & §6 — twelve Care Profiles + checkout bundles. Reconciled in V007; pack content in V008 + universal observation types in V010 (dev + VPS applied 2026-06-04).
Paid Care Profiles use Stripe Checkout (mode=payment), not Payment Intents + Elements.
Production gate: When BILLING_TIER_PLANS_ONLY=true (default in production per config.py), POST /api/condition-packs/{id}/purchase returns 503 — tier subscriptions only. Free starter unlocks (general_palliative, medication_orchestra) and Complete-tier grant_tier_pack_access() still run at provision; only paid checkout is blocked. See 21-STRIPE-LIVE-SWITCHOVER §4.1b.
| Step | Behaviour |
|---|---|
| List | GET /api/condition-packs — each pack includes has_access, can_purchase, price_display, billing_currency. Display FX: one cached AUD→currency rate per request (aud_minor_units_per_aud, Redis fx:pack:aud:*, 12h) — not per-pack Frankfurter calls |
| Buy | Admin clicks Buy once on a buyable pack under Add a Care Profile on Subscriptions.tsx (no owned-pack card grid) → POST /api/condition-packs/{id}/purchase (403 if tier-included or already owned; 503 if tier-plans-only) → redirect to checkout_url |
| Stripe | AUD tenants use condition_packs.stripe_price_id when seeded; other currencies use Frankfurter FX from price_aud |
| Webhook | checkout.session.completed with metadata.kind=pack_purchase → record_pack_purchase() inserts tenant_pack_purchases |
| Return | Success URL /admin/subscriptions?pack_purchased={id} — success toast; apply on People in care |
| Preview | ConditionPackPreviewDialog calls GET /api/condition-packs/{id}/preview (optional, before purchase). cancer_at_home: marketing feature_bullets first; seed lists collapsible (V012) |
| Care Start apply | POST /api/patients/{id}/care-start — care_start_service.apply_care_start_pack() (idempotent merge). Dev verified 2026-06-04. |
| Care pattern correction | PATCH /api/patients/{id}/care-pattern — non-destructive archetype / re-apply; family UI withdrawn 2026-06-26 (C5c API remains). |
| Signup bundle (C4a) | start-signup / start-signup-google optional care_start_pack_slug → metadata + $24.99 one-time line item → pending_care_start_pack_slug → auto-apply on first patient. Marketing modal shipped 2026-06-04. Public catalogue: GET /api/stripe/care-start-offer. |
| Tier inclusion | grant_tier_pack_access() grants free starters only; paid packs require purchase (V029). |
| Owned state | Not shown as a card grid on Subscriptions — unlock is tenant-wide; apply configures each patient on People in care |
| Subscriptions layout (2026-06-26) | Your plan → Module access → Upgrade plan → Unlock with an upgrade → Care Profiles → Coming soon. condition_templates omitted from module-access grids (SUBSCRIPTIONS_MODULE_ACCESS_EXCLUDE). Legacy /care-archetypes → redirect /subscriptions. See 05-DEVELOPER-GUIDE §7.1a. |
Test / UAT only (after catalogue reconciliation): python -m scripts.stripe_seed_condition_packs — do not run in live until 21 §4.1b checklist is satisfied and BILLING_TIER_PLANS_ONLY=false.
6. Frontend enforcement
Section titled “6. Frontend enforcement”6.1 LimitError class
Section titled “6.1 LimitError class”frontend/src/lib/api.ts exports a LimitError class. The request()
helper throws a LimitError (instead of a plain Error) when the server
returns HTTP 402. Callers catch it and render <UpgradeGate>:
try { await api.medicines.create(...)} catch (e: unknown) { if (e instanceof LimitError) { setLimitError(e.detail) // triggers <UpgradeGate detail={limitError} /> }}6.2 UpgradeGate component
Section titled “6.2 UpgradeGate component”frontend/src/components/UpgradeGate.tsx — reusable modal that:
- Displays the limit message.
- Shows upgrade tier name + flat price difference.
- One-click “Upgrade plan” button starts Stripe Checkout.
- “Not now” closes the gate without action.
6.3 Feature surfaces
Section titled “6.3 Feature surfaces”| Surface | Tier gate | Behaviour |
|---|---|---|
| Settings → Medicines | max_medicines | 402 → UpgradeGate modal |
| Settings → Reason Types | max_reason_types | 402 → UpgradeGate modal |
| People (Patients) | max_care_recipients / max_carers / max_observers | 402 → UpgradeGate modal |
| History | prescription_management module active | Edit locked → inline lock modal + upgrade link |
| Manual Dose | Essential tier | Subtle footnote link to upgrade |
| Analytics | prescription_management module active | Filter row replaced by locked pill + upgrade link |
| Subscriptions page | Tier modules | Upgrade CTA replaces Activate button for locked modules |
7. $5/person add-on (scaffold — pending product decision)
Section titled “7. $5/person add-on (scaffold — pending product decision)”The add-on is available on all three tiers. The DB and API scaffold are intentionally deferred until the billing frequency (annual vs monthly) and local-currency handling are confirmed. Tracked in open question §13.4 of docs/23.
8. Naming note
Section titled “8. Naming note”| Stripe/DB slug | Public display name |
|---|---|
essential | Essential |
professional | Family |
complete | Complete |
The slug professional is kept in Stripe and the DB to avoid breaking
existing subscriptions. The name Family is shown everywhere in the app UI
and marketing copy. The change is a display-label change only — no DB or
Stripe migration required.
9. Operations
Section titled “9. Operations”Seeding limits after updating tiers.json
Section titled “Seeding limits after updating tiers.json”# Inside backend containerpython -m scripts.stripe_seed_tiersThe seeder is idempotent. Running it again after changing limits is safe.
Inspecting downgrades (Stripe-side only)
Section titled “Inspecting downgrades (Stripe-side only)”Removed 2026-05-26. There is no
pending_downgrade_*state in the LynCareOS database sinceV049. Pending tier changes are visible only on the Stripe side — use the Stripe dashboard (Customers → <customer> → Subscriptions → Schedule) or the Stripe API (stripe.SubscriptionSchedule.list) to see deferred subscription updates.
The historical “Manual downgrade override” SQL has been removed; if the Stripe webhook for a renewal-day subscription change is ever lost, the operator runbook is to replay the missed customer.subscription.updated event from the Stripe dashboard rather than mutating tenant rows directly.
10. User flows, upgrade surfaces & API (from former doc 25)
Section titled “10. User flows, upgrade surfaces & API (from former doc 25)”Merged 2026-04-28 from 25-SUBSCRIPTION-UPGRADE-FLOWS.md. The product matrix remains 23.
1. Subscription tier overview
Section titled “1. Subscription tier overview”| Tier slug | Public name | USD/yr | Key limits |
|---|---|---|---|
essential | Essential | $39 | 1 person in care · 2 carers · 1 observer · 5 medicines · 5 reason types |
professional | Family | $69 | 2 persons · 3 carers · 2 observers · unlimited medicines/reasons · prescriptions, sleep, vitals, custom observations, family help, family journal, preventive care |
complete | Complete | $99 | 5 persons · 7 carers · 7 observers · unlimited · all modules |
Local-currency equivalents are stored in stripe_tier_local_prices and in tiers.json → local_prices.
2. How a subscription starts — signup flows
Section titled “2. How a subscription starts — signup flows”LynCareOS supports three signup entry points, all of which converge on the same provisioning logic in services/stripe_provisioning.provision_from_checkout(). The current implementation supports only §2.1; §2.2 and §2.3 are planned in 04-ROADMAP.md Phase E (REQ-AUTH-12, REQ-AUTH-13).
2.1 Anonymous signup — new visitor
Section titled “2.1 Anonymous signup — new visitor”The classic flow: a visitor with no LynCareOS account uses the marketing site to register and pay.
User → marketing page (index.html) → selects tier + fills sign-up form (username, email, password / Google) → POST /api/billing/check-availability (live as user types) → 200 available → continue → 409 + reason "existing_user" → branch to §2.2 → POST /api/stripe/start-signup (creates pending_signups row + checkout session) → Stripe Checkout (user pays in their local currency) → Stripe webhook: checkout.session.completed → POST /api/stripe/webhook → stripe_provisioning.provision_from_checkout(kind="signup") … (provisioning steps as below) → Browser lands on `/billing/success?session_id=…` → POST /api/stripe/complete-signup → if webhook already consumed pending row: issue JWT + welcome flow → if Stripe `payment_status=paid` but row still pending: **inline provision** then issue JWT (webhook fallback — see §11) → if unpaid: structured 402 with `charged: false` and user-friendly message → User sees Welcome modal → `/admin/subscriptions`Provisioning steps inside provision_from_checkout(kind="signup"):
① Reads pending_signups (username, email, password_hash, tier_slug) ② Creates `users` row — `email_enc` + `email_idx` (blind index) + `enc_version = 1` via `field_crypto` (no plaintext email after V091) ③ Creates `tenants` row — `stripe_customer_id`, `name_enc` + `enc_version = 1` (tenant display name from checkout metadata) ④ Sets `tenants.annual_anniversary_at = NOW()` ⑤ Seeds per-tenant APScheduler jobs (`schedule_tenant_jobs`) ⑥ Syncs `subscriptions` rows via `sync_subscription_items` (tier price → all modules in `stripe_tiers.modules`; passes `payment_status` from the Checkout session when the Stripe subscription is still `incomplete`) ⑦ Inserts `tenant_memberships` row (role=admin, status=active) ⑧ Sets `users.last_active_tenant_id` to the new tenant (JWT targets paid account) ⑨ `complete-signup` repeats ⑧ and calls `resync_tenant_subscriptions_from_stripe`After the flow completes the user may log in; welcome e-mail is optional product follow-up.
Webhook hardening (2026-05-30): checkout.session.completed re-fetches the
Stripe subscription when line items are empty on first delivery, then runs
resync_tenant_subscriptions_from_stripe if items are still missing after
provision. customer.subscription.updated / invoice.payment_succeeded continue
to call the same sync helper for retries.
The annual_anniversary_at timestamp becomes the anchor for renewal billing.
On an upgrade it is reset to the upgrade date, so the next renewal is exactly
12 months from when the tenant upgraded.
2.2 Returning user signup — existing email (Phase E — REQ-AUTH-12)
Section titled “2.2 Returning user signup — existing email (Phase E — REQ-AUTH-12)”When the marketing form detects an existing email, the visitor is redirected to sign in rather than receiving a hard 409. Once authenticated, they continue to checkout and a new tenant is provisioned alongside their existing user identity.
User → marketing page detects existing email via /api/billing/check-availability → "Welcome back. Sign in to set up a new care account." → POST /api/auth/login (or Google OAuth) → User selects tier + enters new tenant name (e.g. "Smith Family Care") → POST /api/stripe/start-additional-tenant ← new endpoint, Phase E body: { tier_slug, tenant_name } (no username/email/password — identity is already established) → Stripe Checkout → POST /api/stripe/webhook → stripe_provisioning.provision_from_checkout(kind="additional_tenant") ① Existing `users` row reused by id (no new identity) ② Creates `tenants` row — fresh `stripe_customer_id`, `name_enc` from `tenant_name` ③ Sets `tenants.annual_anniversary_at = NOW()` ④ Seeds per-tenant APScheduler jobs ⑤ Syncs `subscriptions` rows from `stripe_tiers.modules` ⑥ Inserts `tenant_memberships` row (role=admin, status=active) linking the user to the new tenant → JWT pair re-issued with `tid = <new tenant>` (REQ-AUTH-13)Original memberships and patient access on any other tenant are untouched.
2.3 In-app “Create another care account” (Phase E — REQ-AUTH-12)
Section titled “2.3 In-app “Create another care account” (Phase E — REQ-AUTH-12)”For an already-logged-in user, an in-app entry (Settings → Accounts → “Create another care account”) routes through the same backend path as §2.2, skipping the marketing site entirely.
[Logged-in user] Settings → "Create another care account" → tier picker + tenant-name input → POST /api/stripe/start-additional-tenant → … (identical to §2.2 from this point on)After provisioning, the user either remains in their current tenant context or switches into the new tenant via the tenant chooser (REQ-AUTH-13). Switching invalidates all per-tenant client caches before applying the new tokens to prevent stale-state leakage.
2.4 What is enforced today vs Phase E
Section titled “2.4 What is enforced today vs Phase E”| Behaviour | Today | After Phase E |
|---|---|---|
| Anonymous visitor with new email | Sign up + new tenant | Unchanged |
| Anonymous visitor with existing email | HTTP 409 — dead end | Redirect to sign-in → §2.2 |
| Logged-in user starts new paid signup | Blocked at email_available() | Routes through §2.3 |
INVITE_ONLY_REGISTRATION=true | Blocks §2.1 | Blocks §2.1, §2.2, §2.3 |
| Stripe customer per tenant | Yes (tenants.stripe_customer_id) | Unchanged — per-tenant |
| One identity per email | Yes (users.email_idx UNIQUE) | Unchanged |
3. Self-serve upgrade flow
Section titled “3. Self-serve upgrade flow”3.1 Upgrade entry points in the application
Section titled “3.1 Upgrade entry points in the application”Upgrade prompts appear at every surface where a tier limit is enforced:
| Surface | File | Trigger |
|---|---|---|
| Medicine list | Settings.tsx | User tries to save a 6th medicine on Essential |
| Reason type list | Settings.tsx | User tries to save a 6th reason type on Essential |
| People in care | admin/Patients.tsx | User tries to add a 2nd person in care on Essential |
| Care team | admin/Patients.tsx | User tries to add a 3rd carer or 2nd observer |
| Manual dose screen | LogDose.tsx | Subtle footnote for Essential users at all times |
| History page | History.tsx | User clicks Edit/Delete on a dose record |
| Analytics | Analytics.tsx | User clicks the locked medicine-filter pill |
| Subscriptions admin | admin/Subscriptions.tsx | User clicks on a locked/inactive module tile |
All capacity surfaces share the same component: UpgradeGate.tsx (modal).
Feature-gate surfaces use inline locked elements with upgrade links.
3.2 UpgradeGate modal (frontend/src/components/UpgradeGate.tsx)
Section titled “3.2 UpgradeGate modal (frontend/src/components/UpgradeGate.tsx)”Shown whenever the backend returns HTTP 402 with a LimitErrorDetail body:
{ "code": "LIMIT_MEDICINES", "detail": "Your plan allows up to 5 medicines. Upgrade to add more.", "limit": 5, "upgrade_hint": { "to_slug": "professional", "to_name": "Family", "diff_usd": 30.0 }}The modal displays:
- Which limit was hit and the current cap
- What unlocks in the suggested next tier (pulled from
upgrade_hint) - “Upgrade plan” CTA button — calls
billing.startUpgrade(to_slug)
3.3 Frontend API call
Section titled “3.3 Frontend API call”billing.startUpgrade("professional") → POST /api/stripe/upgrade-tier body: { new_tier_slug: "professional" }The LimitError class (in api.ts) is thrown for any HTTP 402 response and
carries the structured LimitErrorDetail. Components instanceof-check for it:
try { await api.medicines.create(payload);} catch (err) { if (err instanceof LimitError) { setLimitError(err.detail); // → renders <UpgradeGate> }}3.4 Backend upgrade endpoint — POST /api/stripe/upgrade-tier
Section titled “3.4 Backend upgrade endpoint — POST /api/stripe/upgrade-tier”File: backend/routers/stripe.py → upgrade_tier()
Steps:
- Validate
new_tier_slugexists and is active instripe_tiers. - Resolve the current tier from the tenant’s active subscription row.
- Joins
subscriptions → stripe_tiers(USD billing), or - Joins
subscriptions → stripe_tier_local_prices → stripe_tiers(local-currency billing). - Rejects the request with HTTP 400 if no active subscription found.
- Joins
- Reject if
new_tier.usd_cents ≤ current_tier.usd_cents(upgrades only). - Resolve billing currency:
- If the current subscription is on a local-currency price (e.g. AUD), the coupon and new checkout line both use that currency.
- Otherwise defaults to USD.
- Create one-time Stripe Coupon (
amount_off = current tier price, currency = billing currency, duration = "once"). This means the first invoice for the new tier charges only the difference. - Create Stripe Checkout session with:
price_ids = [new_tier local or USD price_id]customer = tenant.stripe_customer_id(pre-fills saved card)discounts = [{ coupon: <coupon_id> }]allow_promotion_codes = false(discount already applied)metadata = { kind:"upgrade", tenant_id, from_tier, to_tier, old_subscription_id, coupon_id }
- Returns
{ checkout_url, from_tier, to_tier, diff_usd, billing_currency }.
Frontend redirects the user to checkout_url (Stripe-hosted page).
3.5 Currency resolution — how the correct local price is used
Section titled “3.5 Currency resolution — how the correct local price is used”subscriptions.stripe_price_id → stripe_tier_local_prices.stripe_price_id ↓ currency = "AUD" amount_cents = 5900 ↓coupon.amount_off = 5900 coupon.currency = "aud"new checkout price_id = stripe_tier_local_prices WHERE tier_slug='professional' AND currency='AUD'If no local price exists for the tenant’s currency, the system falls back to
the USD price from stripe_tiers.stripe_price_id.
The _resolve_tier_price_id(db, slug, currency) helper in stripe.py performs
this lookup.
3.6 Post-payment provisioning — webhook checkout.session.completed
Section titled “3.6 Post-payment provisioning — webhook checkout.session.completed”File: backend/services/stripe_provisioning.py → provision_from_checkout()
When session.metadata.kind == "upgrade":
- Read
tenant_id,old_subscription_idfrom metadata. - Cancel the old Stripe subscription immediately:
stripe.Subscription.delete(old_subscription_id, prorate=False). (No refund; the coupon already covered the old tier’s price.) - Reset the anniversary:
UPDATE tenants SET annual_anniversary_at = NOW(). The user’s next renewal date is exactly 12 months from today. - Sync modules: call
stripe_service.sync_subscription_items(db, tenant_id, stripe_subscription, checkout_payment_status=session.payment_status)with the new subscription’s items. This upserts onesubscriptionsrow per module in the new tier’s bundle (same expansion rules as signup — see §5.3 tier resolution module-sync list).
After this webhook completes the tenant’s entitlements are immediately live.
4. GET /api/billing/my-tier — the canonical tier status endpoint
Section titled “4. GET /api/billing/my-tier — the canonical tier status endpoint”Used by all upgrade surfaces and the Subscriptions page to reflect current state.
Response shape:
{ "current_tier": { "slug": "essential", "name": "Essential", "usd": 39, "modules": ["medication_dispensing", "care_calendar"] }, "current_limits": { "max_carers": 2, "max_observers": 1, "max_care_recipients": 1, "max_medicines": 5, "max_reason_types": 5 }}current_limits values are null for unlimited fields.
max_care_recipients already includes any purchased extra_care_recipients slots.
5. Upgrade in a local currency — end-to-end example (AUD)
Section titled “5. Upgrade in a local currency — end-to-end example (AUD)”1. Tenant signs up in Australia → Stripe Checkout: price_ess_aud (AUD 59/yr) → subscriptions.stripe_price_id = "price_ess_aud" → tenants.annual_anniversary_at = 2026-04-26
2. Tenant hits 5-medicine limit → UpgradeGate modal shown → clicks "Upgrade plan" → POST /api/stripe/upgrade-tier { to: "professional" }
3. Backend resolves: subscriptions.stripe_price_id="price_ess_aud" → LEFT JOIN stripe_tier_local_prices → currency=AUD, amount_cents=5900 → current tier "essential" confirmed → billing_currency = "AUD" → coupon: { amount_off: 5900, currency: "aud", duration: "once" } → new_price_id: stripe_tier_local_prices WHERE slug="professional" AND currency="AUD" → "price_fam_aud" (AUD 99)
4. Stripe Checkout created: price = price_fam_aud (AUD 99) coupon = cpn_xxx (AUD -59 one-time) First invoice = AUD 40 (the upgrade difference)
5. Webhook fires → provision_from_checkout(kind="upgrade") → old sub (price_ess_aud) cancelled → new sub (price_fam_aud) started → annual_anniversary_at = 2026-04-26 (reset to today) → modules: prescription_management + sleep_tracking now active
6. Next renewal date = 2027-04-26 at AUD 99/yr (full new-tier price)6. Upgrade difference calculation
Section titled “6. Upgrade difference calculation”| Scenario | User pays now | Next renewal |
|---|---|---|
| Essential → Family (USD) | $69 − $39 = $30 | $69 |
| Essential → Family (AUD) | A$99 − A$59 = A$40 | A$99 |
| Essential → Complete (USD) | $99 − $39 = $60 | $99 |
| Family → Complete (USD) | $99 − $69 = $30 | $99 |
The coupon amount_off always equals the old tier’s price in the billing currency.
Stripe applies it to the first invoice of the new subscription, so the net charge
is exactly the difference.
7. Extra care-recipient add-on (+$5/person)
Section titled “7. Extra care-recipient add-on (+$5/person)”A tenant can purchase additional person-in-care slots without changing tier.
Database: tenants.extra_care_recipients INTEGER DEFAULT 0
Effective limit: stripe_tiers.limits.max_care_recipients + tenants.extra_care_recipients
get_tenant_limits() in backend/services/tier_limits.py automatically adds
the purchased slots to the base tier limit before returning.
Billing mechanics: TBD (full Stripe checkout flow for add-ons to be implemented — frequency and local currency handling pending product decision).
8. Key files reference
Section titled “8. Key files reference”| File | Role |
|---|---|
backend/billing/tiers.json | Single source of truth for tiers, USD prices, local prices, limits |
backend/routers/stripe.py | Signup, checkout-outcome, upgrade_tier, webhook |
backend/services/tier_resolution.py | Active tier row + billing currency; price-ID join, then module inference fallback |
backend/services/tier_upgrade_service.py | Upgrade option list with currency-aware diff display |
backend/services/condition_pack_billing.py | Tier inclusion, purchase guards, price display |
backend/services/payment_outcome.py | User-facing checkout outcomes + operator log codes |
backend/scripts/stripe_seed_condition_packs.py | One-time AUD Stripe prices for paid packs |
frontend/src/lib/paymentOutcome.ts | Parse/fetch payment outcomes on billing pages |
frontend/src/components/condition-packs/ConditionPackCard.tsx | Pack purchase UI with billing currency |
backend/tests/test_payment_outcome.py | Unit tests for outcome mapping |
backend/tests/test_condition_pack_billing.py | Pack billing guard tests |
backend/routers/billing.py | get_my_tier — tier status and limits |
backend/services/stripe_provisioning.py | provision_from_checkout — signup + upgrade webhook handling |
backend/services/tier_limits.py | get_tenant_limits, get_tenant_upgrade_hint, raise_limit_error |
backend/services/scheduler.py | schedule_tenant_jobs, bootstrap_all_tenants |
backend/routers/medicines.py | Medicine creation with LIMIT_MEDICINES enforcement |
backend/routers/reason_types.py | Reason type creation with LIMIT_REASON_TYPES enforcement |
backend/routers/patients.py | Patient + member creation with all capacity limit enforcement |
frontend/src/components/UpgradeGate.tsx | Reusable upgrade prompt modal |
frontend/src/lib/api.ts | LimitError class, billing.startUpgrade (scheduleDowngrade removed alongside the schedule-downgrade endpoint in V049) |
frontend/src/pages/Settings.tsx | Medicine + reason type upgrade gates |
frontend/src/pages/admin/Patients.tsx | Patient + team member upgrade gates |
frontend/src/pages/History.tsx | Read-only lock for Essential users |
frontend/src/pages/Analytics.tsx | Locked medicine-filter pill for Essential users |
frontend/src/pages/LogDose.tsx | Subtle upgrade footnote for Essential users |
frontend/src/pages/admin/Subscriptions.tsx | Plan upgrade, Add a Care Profile purchase grid, module access rows |
backend/tests/test_subscription_lifecycle.py | Full E2E test suite (21 tests, groups A–G) |
11. Payment failure UX
Section titled “11. Payment failure UX”Signup and billing pages must fail gracefully: users see plain language about whether money was taken, not Stripe error codes or stack traces.
11.1 Outcome model
Section titled “11.1 Outcome model”backend/services/payment_outcome.py maps a Stripe Checkout session to a stable
outcome the SPA can branch on:
| Field | Purpose |
|---|---|
code | Operator log key (payment_not_taken, provisioning_pending, …) |
user_message | Shown in the browser — no technical jargon |
charged | true if Stripe payment_status == paid |
session_id | Support reference (safe to show the user) |
Every outcome is logged server-side via log_outcome() with context
(checkout-outcome, complete-signup) so operators can grep logs without
exposing PHI in the user message.
11.2 API surfaces
Section titled “11.2 API surfaces”| Endpoint | Role |
|---|---|
GET /api/stripe/checkout-outcome?session_id= | Read-only lookup for /billing/success and /billing/cancel |
POST /api/stripe/complete-signup | On failure returns HTTPException.detail shaped by payment_error_detail() |
When payment was not taken (charged: false), the message explicitly says
so and the UI offers Try again (marketing pricing page).
When payment was taken but provisioning lags or fails, the message says the charge succeeded and offers Sign in or Email support with the session reference pre-filled.
11.3 Frontend pages
Section titled “11.3 Frontend pages”| Page | Behaviour |
|---|---|
BillingSuccess.tsx | Parses structured errors from complete-signup; on timeout calls checkout-outcome |
BillingCancel.tsx | Confirms via checkout-outcome when session_id is in the query string |
frontend/src/lib/paymentOutcome.ts | Shared parser, fetch helper, support mailto builder |
Cancel URLs for signup checkout include ?session_id={CHECKOUT_SESSION_ID} so
the cancel page can confirm no charge was taken.
11.4 Operator review
Section titled “11.4 Operator review”Search application logs for payment_outcome to see:
payment_outcome context=complete-signup code=provisioning_failed charged=True session_id=cs_... username=...Cross-check the session in the Stripe Dashboard if provisioning failed after a
successful charge. The inline provision_from_checkout() fallback in
complete-signup reduces dependence on webhook timing but does not replace
webhook idempotency for the primary path.
| Symptom | Likely cause | Fix |
|---|---|---|
| Paid on marketing site, modules locked in app | Webhook lag/failure, empty subscription at first webhook, or wrong last_active_tenant_id | resync_tenant_subscriptions; sign out/in; confirm tid tenant |
| Subscriptions page shows no plan | stripe_price_id not in DB catalogue | Metadata fallback after 2026-05-30 deploy, or resync + SQL in §5.3 |
Log: has no module/tier mapping | Grandfathered Price id absent from stripe_tiers | Deploy metadata fallback; resync tenant |
| Family tier but only Essential modules work | Logged into old tenant | Switch tenant / check last_active_tenant_id |
Shipped vs tier-bundled: Family and Complete include module slugs in
tiers.json that are not yet product surfaces (family_journal,
preventive_care, and Complete-only clinical slugs). They may appear on
Subscriptions as coming soon — that is not a provisioning failure. See
frontend/src/lib/moduleDelivery.ts.