Skip to content

fix(billing): align prompts to new plan's engine set on every plan-change path - #112

Merged
gkhngyk merged 1 commit into
mainfrom
fix/plan-upgrade-align-prompts
May 26, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
fix/plan-upgrade-align-prompts

Conversation

@gkhngyk

@gkhngyk gkhngyk commented May 26, 2026

Copy link
Copy Markdown
Contributor

Bug

#78 fixed onboarding's initial-checkout case. Existing orgs that upgrade from Starter to Growth (or downgrade back) still kept their prompts on the original engine set — a paying Growth customer would track only 2 of the 7 engines until they manually edited every prompt.

Live-verified during testing: a real upgrade in the dashboard left `organizations.plan = 'growth'` but `prompts.platforms = ['chatgpt-web', 'perplexity-web']`. Tracking worker only consults `prompt.platforms` at runtime — never the plan, `allowedScrapers`, or `brand_platforms` — so the bill goes up while the engine coverage doesn't.

Why the in-app upgrade was the missing path

The in-app upgrade flow goes `PATCH /api/stripe/subscription`:

```ts
// Stripe update + optimistic plan write
await stripe.subscriptions.update(subscriptionId, { items: [...], metadata: { plan_id: newPlanId, ... } });
await supabase.from('organizations').update({ plan: newPlanId }).eq('id', org.id);
```

By the time Stripe fires the matching `customer.subscription.updated` webhook, the snapshot guard added there sees `orgBefore.plan === newPlanId` (because the optimistic write already landed) and skips alignment. So the webhook fix alone wasn't enough — the PATCH route itself needs to trigger alignment immediately after its own optimistic write.

Shape of the fix

Three plan-change entry points, one shared helper:

Entry point When What it does
`PATCH /api/stripe/subscription` In-app upgrade / downgrade (the primary path users hit) After the optimistic plan write, align prompts to the new plan
Webhook `checkout.session.completed` Initial checkout, resubscribe after cancel After the org update, align
Webhook `customer.subscription.updated` Out-of-band changes (Stripe Dashboard, customer portal, admin) Snapshot the pre-update plan; only align if `newPlanId !== orgBefore.plan` so routine renewal events skip the work
Webhook `customer.subscription.deleted` Cancellation Align to `'starter'` so prompts trim back to 2 engines and we don't keep paying scraper cost on engines the plan no longer covers
`GET /api/stripe/success` (refactor of #78) Already shipped — now uses the same helper instead of duplicate inline SQL Same as before, identical behavior

Files

File Change
`web/src/lib/plan-engines.ts` New `alignPromptsToPlanForOrg(orgId, planId)`. Walks brands → prompt_sets → prompts and bulk-updates `platforms` + `models` to match the plan's `allowedScrapers` / `allowedModels`. Idempotent. Returns the rewritten count
`web/src/app/api/stripe/subscription/route.ts` After the existing optimistic `plan` write, call `alignPromptsToPlanForOrg`
`web/src/app/api/stripe/webhook/route.ts` Internal `alignPromptsSafe()` wrapper that swallows errors (so Stripe doesn't retry on a single failed alignment) + alignment calls at three event handlers; snapshot guard on `subscription.updated`
`web/src/app/api/stripe/success/route.ts` Refactor #78's inline alignment SQL to use the shared helper — identical behavior, one less duplicate

How verified

Local e2e against cloud Stripe test mode with localhost web + Stripe CLI:

  1. Reset test account → fresh state
  2. Sign-in → onboarding → picked Starter at step 6
  3. `prompts.platforms` = 2 engines, `organizations.plan` = `'starter'` ✓
  4. Upgrade in-app Settings → Plan → Growth
  5. Server log:
    ```
    [stripe/subscription] Aligned 1 prompt(s) to plan=growth (7 scrapers, 1 models) for org ...
    ```
  6. `prompts.platforms` = 7 engines, `prompts.models` = `['claude-sonnet-4-6']` ✓
  7. Downgrade in-app Growth → Starter → log shows alignment fired with starter; prompts trimmed back to 2 ✓
  8. `yarn typecheck` + `yarn format:check` clean

Acceptance (from #79)

  • After upgrading to Growth, existing prompts can track the full set of Growth engines without manually editing each prompt
  • Downgrades stay consistent (no tracking beyond the new plan's limit)

Closes #79.

…ange path

Issue #78 only fixed the initial-checkout case. Existing orgs that upgrade
from Starter to Growth (or downgrade back) still kept their prompts on
the original engine set — a paying Growth customer would track only 2
of the 7 engines until they manually edited every prompt.

Three plan-change entry points all converge on a shared helper now:

- web/src/lib/plan-engines.ts: extract alignPromptsToPlanForOrg(orgId,
  planId) as the single SQL surface — walks brands → prompt_sets →
  prompts and rewrites platforms + models to match the plan's
  allowedScrapers / allowedModels. Idempotent; handles both expansion
  (Starter → Growth: 2 → 7 engines) and contraction (Growth → Starter:
  7 → 2). Returns the rewritten count so callers can log it.

- web/src/app/api/stripe/subscription/route.ts (PATCH): the in-app
  upgrade / downgrade path optimistically writes the new plan to the
  org row itself. Without this call, the matching subscription.updated
  webhook below would see plan-unchanged (because the optimistic write
  already landed) and skip alignment. Now PATCH triggers alignment
  directly after the optimistic write, so the engine set follows the
  plan immediately.

- web/src/app/api/stripe/webhook/route.ts: defense-in-depth for
  out-of-band plan changes (Stripe Dashboard edits, customer portal,
  manual admin moves). Three paths covered:
    - checkout.session.completed → align after the org update
    - customer.subscription.updated → snapshot pre-update plan, only
      align when newPlanId !== orgBefore.plan (skips routine renewal
      events)
    - customer.subscription.deleted → align to 'starter' so a
      downgraded org doesn't keep paying scraper cost on engines the
      plan no longer covers

- web/src/app/api/stripe/success/route.ts: refactor #78's inline
  alignment SQL to use the shared helper so all four call sites have
  identical behavior.

Verified locally with Stripe CLI forwarding + an in-app downgrade →
upgrade roundtrip on a test account; logs and prompt rows reflect the
expected engine sets at every transition.

Closes #79.
@gkhngyk
gkhngyk merged commit b5797fe into main May 26, 2026
3 checks passed

This branch was successfully deployed

1 active deployment
Preview — 03ea1d9b Deployed May 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Upgrading Starter→Growth doesn't expand existing prompts' tracked engines (stay at 2 of 8)

1 participant