Skip to content

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.


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:

Terminal window
python -m scripts.stripe_seed_tiers # inside the backend container

The 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:

FileRole
backend/billing/tiers.jsonCommercial bundle — which module slugs Stripe provisions per plan
backend/billing/module_delivery.jsonProduct 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.

DeliverySubscriptions UI label (when entitled)Example
liveActive / Ready to use in the appMedication dispensing
partialIncluded — rolling outcondition_templates (unlock + Care Start apply on dev; VPS V006–V010 deploy + marketing bundle UI pending)
plannedComing sooncare_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.


TableColumnTypePurpose
stripe_tierslimitsJSONBPer-tier caps populated by seeder
tenants pending_downgrade_to_tier_slugTEXTSlug of scheduled-downgrade targetRemoved in V049__remove_pending_downgrade_columns.sql — see §4 below
tenants pending_downgrade_effective_atTIMESTAMPTZWhen the downgrade firesRemoved in V049

  1. Admin hits POST /api/stripe/upgrade-tier with { new_tier_slug }.
  2. Backend resolves:
    • Current tier from subscriptions (highest active stripe_price_id).
    • Whether the tenant’s current price_id maps to a local-currency row in stripe_tier_local_prices.
  3. Creates a one-time Stripe Coupon with amount_off = old price in the correct billing currency (local if applicable, else USD).
  4. Creates a Stripe Checkout session for the new tier’s price in the same currency, applying the coupon as a discount.
  5. On checkout.session.completed webhook (kind=upgrade):
    • _provision_tier_upgrade cancels the old Stripe subscription.
    • Syncs module subscriptions via sync_subscription_items.
    • Resets tenants.annual_anniversary_at = NOW().

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. The pending_downgrade_to_tier_slug and pending_downgrade_effective_at columns were dropped; the POST/DELETE /api/stripe/schedule-downgrade endpoints, the _run_tenant_pending_downgrade scheduler job, and the bootstrap_all_tenants re-registration call were all removed. The legacy section is preserved in 02-REQUIREMENTS.md REQ-BILL-06 (status: Removed) for traceability.

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.tsx calls POST /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-session returns 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 resyncs subscriptions and tenant.module_subscriptions from the new Stripe state.
  • No backend scheduling job is required — Stripe is the scheduler.
  • 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_tenants skips 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)”
  1. New migration restoring pending_downgrade_to_tier_slug / pending_downgrade_effective_at on tenants.
  2. New POST/DELETE /api/stripe/schedule-downgrade endpoints in routers/stripe.py.
  3. New services/scheduler._run_tenant_pending_downgrade job and bootstrap_all_tenants re-registration.
  4. UI surface (CancelSubscriptionDialog plus a “Schedule downgrade at renewal” surface).
  5. 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.

ComponentLocation
Price catalogbackend/billing/module_prices.json + stripe_module_prices table (migration V095)
Seederpython -m scripts.stripe_seed_module_prices (run after tier seeder in test and live)
Add modulePOST /api/stripe/add-module { module_slug, currency } — appends a Stripe subscription item, webhook syncs subscriptions
Remove moduleDELETE /api/stripe/remove-module?module_slug=… — blocked when the module is included in the current tier bundle
Price discoveryGET /api/billing/module-prices — used by ModuleUpgrade.tsx and Subscriptions.tsx
Locked-module UXModuleGate → ModuleUpgrade.tsx shows Upgrade plan and Add this module — $X/mo
Admin panelSubscriptions.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).

ComponentLocation
Category listGET /api/billing/export/categories — 12 v2 keys
Build ZIPPOST /api/billing/export/download { "categories": ["recipients", …] }
Privacy transformsbackend/services/export_privacy.py
v2 buildersbackend/services/export_v2.py — denormalized user archive
ZIP orchestrationbackend/services/tenant_export_service.py
More menu UIfrontend/src/pages/admin/ExportData.tsx — /admin/export
Cancel flowCancelSubscriptionDialog.tsx — Download my data (all categories) + link to /admin/export
Auditaudit_log row per export (entity_type=tenant_export, action VIEW)
Rate limitRedis — 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).


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.
EndpointLimit keyError code
POST /api/medicinesmax_medicines (active count)LIMIT_MEDICINES
POST /api/reason-typesmax_reason_types (active count per patient_id, V014)LIMIT_REASON_TYPES
POST /api/patientsmax_care_recipients (total count)LIMIT_CARE_RECIPIENTS
POST /api/patients/{id}/members role=carermax_carers (distinct users)LIMIT_CARERS
POST /api/patients/{id}/members role=observermax_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 }
}
}

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):

  1. Join subscriptions.stripe_price_id → stripe_tiers / stripe_tier_local_prices (authoritative when IDs match the live catalogue).
  2. If no row matches, infer tier from active modules — Complete if shopping or pain_tracking is 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:

  1. stripe_tiers.stripe_price_id (USD catalogue row).
  2. stripe_tier_local_prices.stripe_price_id (fixed local-currency checkout).
  3. Stripe Price metadata lyncareos_tier when the DB row was rotated by stripe_seed_tiers but the subscription still bills a grandfathered Price (archived in Stripe, no longer listed in stripe_tiers).
  4. 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):

  1. Confirm tier and currency in Stripe Dashboard → Customer → Subscription.

  2. 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>
  3. If the plan card is wrong but modules look correct, optionally align stripe_price_id on active rows to the current catalogue (Family AUD example):

    UPDATE subscriptions s
    SET stripe_price_id = (
    SELECT stripe_price_id FROM stripe_tier_local_prices
    WHERE tier_slug = 'professional' AND currency = 'AUD' AND active = TRUE
    LIMIT 1
    )
    WHERE tenant_id = <tenant_id> AND status IN ('active','trial','past_due');
  4. Ask the subscriber to sign out and back in (or switch tenant if they have several). Signup now sets users.last_active_tenant_id to the provisioned tenant so JWT tid matches 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_downgrade payload was removed when the pending_downgrade_* columns were dropped in V049. The /api/billing/my-tier response 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.

StepBehaviour
ListGET /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
BuyAdmin 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
StripeAUD tenants use condition_packs.stripe_price_id when seeded; other currencies use Frankfurter FX from price_aud
Webhookcheckout.session.completed with metadata.kind=pack_purchase → record_pack_purchase() inserts tenant_pack_purchases
ReturnSuccess URL /admin/subscriptions?pack_purchased={id} — success toast; apply on People in care
PreviewConditionPackPreviewDialog calls GET /api/condition-packs/{id}/preview (optional, before purchase). cancer_at_home: marketing feature_bullets first; seed lists collapsible (V012)
Care Start applyPOST /api/patients/{id}/care-start — care_start_service.apply_care_start_pack() (idempotent merge). Dev verified 2026-06-04.
Care pattern correctionPATCH /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 inclusiongrant_tier_pack_access() grants free starters only; paid packs require purchase (V029).
Owned stateNot 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.


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} />
}
}

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.
SurfaceTier gateBehaviour
Settings → Medicinesmax_medicines402 → UpgradeGate modal
Settings → Reason Typesmax_reason_types402 → UpgradeGate modal
People (Patients)max_care_recipients / max_carers / max_observers402 → UpgradeGate modal
Historyprescription_management module activeEdit locked → inline lock modal + upgrade link
Manual DoseEssential tierSubtle footnote link to upgrade
Analyticsprescription_management module activeFilter row replaced by locked pill + upgrade link
Subscriptions pageTier modulesUpgrade 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.


Stripe/DB slugPublic display name
essentialEssential
professionalFamily
completeComplete

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.


Terminal window
# Inside backend container
python -m scripts.stripe_seed_tiers

The seeder is idempotent. Running it again after changing limits is safe.

Removed 2026-05-26. There is no pending_downgrade_* state in the LynCareOS database since V049. 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.

Tier slugPublic nameUSD/yrKey limits
essentialEssential$391 person in care · 2 carers · 1 observer · 5 medicines · 5 reason types
professionalFamily$692 persons · 3 carers · 2 observers · unlimited medicines/reasons · prescriptions, sleep, vitals, custom observations, family help, family journal, preventive care
completeComplete$995 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).

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.

BehaviourTodayAfter Phase E
Anonymous visitor with new emailSign up + new tenantUnchanged
Anonymous visitor with existing emailHTTP 409 — dead endRedirect to sign-in → §2.2
Logged-in user starts new paid signupBlocked at email_available()Routes through §2.3
INVITE_ONLY_REGISTRATION=trueBlocks §2.1Blocks §2.1, §2.2, §2.3
Stripe customer per tenantYes (tenants.stripe_customer_id)Unchanged — per-tenant
One identity per emailYes (users.email_idx UNIQUE)Unchanged

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:

SurfaceFileTrigger
Medicine listSettings.tsxUser tries to save a 6th medicine on Essential
Reason type listSettings.tsxUser tries to save a 6th reason type on Essential
People in careadmin/Patients.tsxUser tries to add a 2nd person in care on Essential
Care teamadmin/Patients.tsxUser tries to add a 3rd carer or 2nd observer
Manual dose screenLogDose.tsxSubtle footnote for Essential users at all times
History pageHistory.tsxUser clicks Edit/Delete on a dose record
AnalyticsAnalytics.tsxUser clicks the locked medicine-filter pill
Subscriptions adminadmin/Subscriptions.tsxUser 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:

  1. Which limit was hit and the current cap
  2. What unlocks in the suggested next tier (pulled from upgrade_hint)
  3. “Upgrade plan” CTA button — calls billing.startUpgrade(to_slug)
frontend/src/lib/api.ts
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:

  1. Validate new_tier_slug exists and is active in stripe_tiers.
  2. 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.
  3. Reject if new_tier.usd_cents ≤ current_tier.usd_cents (upgrades only).
  4. 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.
  5. 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.
  6. 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 }
  7. 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":

  1. Read tenant_id, old_subscription_id from metadata.
  2. 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.)
  3. Reset the anniversary: UPDATE tenants SET annual_anniversary_at = NOW(). The user’s next renewal date is exactly 12 months from today.
  4. 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 one subscriptions row 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)

ScenarioUser pays nowNext renewal
Essential → Family (USD)$69 − $39 = $30$69
Essential → Family (AUD)A$99 − A$59 = A$40A$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).


FileRole
backend/billing/tiers.jsonSingle source of truth for tiers, USD prices, local prices, limits
backend/routers/stripe.pySignup, checkout-outcome, upgrade_tier, webhook
backend/services/tier_resolution.pyActive tier row + billing currency; price-ID join, then module inference fallback
backend/services/tier_upgrade_service.pyUpgrade option list with currency-aware diff display
backend/services/condition_pack_billing.pyTier inclusion, purchase guards, price display
backend/services/payment_outcome.pyUser-facing checkout outcomes + operator log codes
backend/scripts/stripe_seed_condition_packs.pyOne-time AUD Stripe prices for paid packs
frontend/src/lib/paymentOutcome.tsParse/fetch payment outcomes on billing pages
frontend/src/components/condition-packs/ConditionPackCard.tsxPack purchase UI with billing currency
backend/tests/test_payment_outcome.pyUnit tests for outcome mapping
backend/tests/test_condition_pack_billing.pyPack billing guard tests
backend/routers/billing.pyget_my_tier — tier status and limits
backend/services/stripe_provisioning.pyprovision_from_checkout — signup + upgrade webhook handling
backend/services/tier_limits.pyget_tenant_limits, get_tenant_upgrade_hint, raise_limit_error
backend/services/scheduler.pyschedule_tenant_jobs, bootstrap_all_tenants
backend/routers/medicines.pyMedicine creation with LIMIT_MEDICINES enforcement
backend/routers/reason_types.pyReason type creation with LIMIT_REASON_TYPES enforcement
backend/routers/patients.pyPatient + member creation with all capacity limit enforcement
frontend/src/components/UpgradeGate.tsxReusable upgrade prompt modal
frontend/src/lib/api.tsLimitError class, billing.startUpgrade (scheduleDowngrade removed alongside the schedule-downgrade endpoint in V049)
frontend/src/pages/Settings.tsxMedicine + reason type upgrade gates
frontend/src/pages/admin/Patients.tsxPatient + team member upgrade gates
frontend/src/pages/History.tsxRead-only lock for Essential users
frontend/src/pages/Analytics.tsxLocked medicine-filter pill for Essential users
frontend/src/pages/LogDose.tsxSubtle upgrade footnote for Essential users
frontend/src/pages/admin/Subscriptions.tsxPlan upgrade, Add a Care Profile purchase grid, module access rows
backend/tests/test_subscription_lifecycle.pyFull E2E test suite (21 tests, groups A–G)

Signup and billing pages must fail gracefully: users see plain language about whether money was taken, not Stripe error codes or stack traces.

backend/services/payment_outcome.py maps a Stripe Checkout session to a stable outcome the SPA can branch on:

FieldPurpose
codeOperator log key (payment_not_taken, provisioning_pending, …)
user_messageShown in the browser — no technical jargon
chargedtrue if Stripe payment_status == paid
session_idSupport 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.

EndpointRole
GET /api/stripe/checkout-outcome?session_id=Read-only lookup for /billing/success and /billing/cancel
POST /api/stripe/complete-signupOn 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.

PageBehaviour
BillingSuccess.tsxParses structured errors from complete-signup; on timeout calls checkout-outcome
BillingCancel.tsxConfirms via checkout-outcome when session_id is in the query string
frontend/src/lib/paymentOutcome.tsShared 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.

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.

SymptomLikely causeFix
Paid on marketing site, modules locked in appWebhook lag/failure, empty subscription at first webhook, or wrong last_active_tenant_idresync_tenant_subscriptions; sign out/in; confirm tid tenant
Subscriptions page shows no planstripe_price_id not in DB catalogueMetadata fallback after 2026-05-30 deploy, or resync + SQL in §5.3
Log: has no module/tier mappingGrandfathered Price id absent from stripe_tiersDeploy metadata fallback; resync tenant
Family tier but only Essential modules workLogged into old tenantSwitch 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.