Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(billing): align prompts to new plan's engine set on every plan-change path (#112)
Gökhan Geyikb5797feabf40
diff --git a/web/src/app/api/stripe/subscription/route.ts b/web/src/app/api/stripe/subscription/route.tsindex f0a96cfd4..52bffc486 100644--- a/web/src/app/api/stripe/subscription/route.ts+++ b/web/src/app/api/stripe/subscription/route.ts@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';import { stripe, PRICE_IDS } from '@/lib/stripe';import { SUBSCRIBABLE_PLANS } from '@/config/plans';+import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';type SubscriptionItem = {id: string;@@ -173,6 +174,22 @@ export async function PATCH(req: NextRequest) {const supabase = await createClient();await supabase.from('organizations').update({ plan: newPlanId }).eq('id', org.id);+ // Align prompts to the new plan's engine set so an upgrade actually+ // expands (Starter → Growth: 2 → 8 engines) or trims (Growth → Starter:+ // 8 → 2) the tracked engines. Same helper used by the Stripe success+ // route (#78) and the webhook (#79). We do it here too because PATCH+ // performs the optimistic plan write itself — by the time the matching+ // `subscription.updated` webhook arrives, the snapshot guard there+ // would see "plan unchanged" and skip alignment.+ try {+ const result = await alignPromptsToPlanForOrg(org.id, newPlanId);+ console.log(+ `[stripe/subscription] Aligned ${result.promptCount} prompt(s) to plan=${newPlanId} (${result.platforms.length} scrapers, ${result.models.length} models) for org ${org.id}`,+ );+ } catch (alignErr) {+ console.error('[stripe/subscription] Plan-engine alignment threw:', alignErr);+ }+const newPrice = updated.items.data[0]?.price;return NextResponse.json({diff --git a/web/src/app/api/stripe/success/route.ts b/web/src/app/api/stripe/success/route.tsindex 92d22f7c9..cc13e3e13 100644--- a/web/src/app/api/stripe/success/route.ts+++ b/web/src/app/api/stripe/success/route.ts@@ -1,7 +1,7 @@import { NextRequest, NextResponse } from 'next/server';import { stripe } from '@/lib/stripe';import { supabaseAdmin } from '@/lib/supabase/admin';-import { getActiveEngineIdsForPlan } from '@/lib/plan-engines';+import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';export async function GET(req: NextRequest) {const { searchParams } = new URL(req.url);@@ -52,52 +52,16 @@ export async function GET(req: NextRequest) {console.log('[stripe/success] DB updated for org:', orgId);// Align onboarding-created prompts to the just-confirmed plan's- // engine set. Onboarding saves prompts at step 4 with whatever- // engines the *current* (pre-checkout, default Starter) plan- // allows — 2 scrapers. Without this, a user who picks Growth at- // step 6 still ends up tracking only those 2 engines instead of- // the 8 Growth allows. Issue #78.- //- // This runs only on the initial checkout-success redirect (i.e.- // onboarding's plan step). Plan changes / upgrades for existing- // orgs flow through the Stripe subscription update path and are- // tracked separately.+ // engine set. Onboarding saves prompts at step 4 with the default+ // Starter set (2 scrapers); without this, a user who picks Growth+ // at step 6 still ends up tracking only those 2 engines (#78).+ // The shared helper is also called from the Stripe webhook so+ // upgrades / downgrades of existing orgs stay in sync (#79).try {- const { platforms, models } = getActiveEngineIdsForPlan(planId || 'starter');-- const { data: orgBrands } = await supabaseAdmin- .from('brands')- .select('id')- .eq('organization_id', orgId);-- const brandIds = (orgBrands ?? []).map((b) => b.id);-- if (brandIds.length > 0) {- const { data: promptSets } = await supabaseAdmin- .from('prompt_sets')- .select('id')- .in('brand_id', brandIds);-- const promptSetIds = (promptSets ?? []).map((p) => p.id);-- if (promptSetIds.length > 0) {- const { error: alignError } = await supabaseAdmin- .from('prompts')- .update({ platforms, models })- .in('prompt_set_id', promptSetIds);-- if (alignError) {- console.error(- '[stripe/success] Failed to align prompts to plan engines:',- alignError,- );- } else {- console.log(- `[stripe/success] Aligned prompts to plan=${planId || 'starter'} engines (${platforms.length} scrapers, ${models.length} models) for org ${orgId}`,- );- }- }- }+ const result = await alignPromptsToPlanForOrg(orgId, planId || 'starter');+ console.log(+ `[stripe/success] Aligned ${result.promptCount} prompt(s) to plan=${planId || 'starter'} (${result.platforms.length} scrapers, ${result.models.length} models) for org ${orgId}`,+ );} catch (alignErr) {console.error('[stripe/success] Plan-engine alignment threw:', alignErr);}diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.tsindex 1399a65ee..b43bd512f 100644--- a/web/src/app/api/stripe/webhook/route.ts+++ b/web/src/app/api/stripe/webhook/route.ts@@ -1,8 +1,26 @@import { NextRequest, NextResponse } from 'next/server';import { stripe } from '@/lib/stripe';import { supabaseAdmin } from '@/lib/supabase/admin';+import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';import type Stripe from 'stripe';+/**+ * Run the shared prompt-engine alignment for an org, logging the result+ * and swallowing errors so a single failed update can't blow up the+ * whole webhook handler (Stripe retries on non-2xx). Each call is+ * idempotent — re-running with the same plan is a no-op write.+ */+async function alignPromptsSafe(orgId: string, planId: string, ctx: string) {+ try {+ const result = await alignPromptsToPlanForOrg(orgId, planId);+ console.log(+ `[webhook:${ctx}] Aligned ${result.promptCount} prompt(s) to plan=${planId} (${result.platforms.length} scrapers, ${result.models.length} models) for org ${orgId}`,+ );+ } catch (err) {+ console.error(`[webhook:${ctx}] Plan-engine alignment threw for org ${orgId}:`, err);+ }+}+export async function POST(req: NextRequest) {const body = await req.text();const signature = req.headers.get('stripe-signature');@@ -56,8 +74,15 @@ export async function POST(req: NextRequest) {stripe_subscription_id: subscriptionId,}).eq('id', orgId);- if (error) console.error('[webhook] DB update error:', error);- else console.log('[webhook] DB updated successfully for org:', orgId);+ if (error) {+ console.error('[webhook] DB update error:', error);+ } else {+ console.log('[webhook] DB updated successfully for org:', orgId);+ // Mirror the success-route alignment so checkouts that race+ // ahead of the redirect (or that happen out-of-band entirely)+ // still get prompts in sync. Idempotent.+ await alignPromptsSafe(orgId, planId || 'starter', 'checkout');+ }}} else {console.log(@@ -94,14 +119,33 @@ export async function POST(req: NextRequest) {}// Update plan if metadata has plan_id- if (subscription.metadata.plan_id) {- updates.plan = subscription.metadata.plan_id;+ const newPlanId = subscription.metadata.plan_id;+ if (newPlanId) {+ updates.plan = newPlanId;}+ // Snapshot the pre-update plan so we can detect plan transitions+ // (Starter → Growth, Growth → Starter, etc.) and only re-align+ // prompts when the plan actually changed. Without this, every+ // routine subscription.updated event (renewal, status flip) would+ // re-run the alignment unnecessarily.+ const { data: orgBefore } = await supabaseAdmin+ .from('organizations')+ .select('id, plan')+ .eq('stripe_customer_id', customerId)+ .maybeSingle();+await supabaseAdmin.from('organizations').update(updates).eq('stripe_customer_id', customerId);++ if (orgBefore && newPlanId && newPlanId !== orgBefore.plan) {+ // Plan changed — re-align prompts. Handles both expansion+ // (Starter → Growth: 2 → 8 engines) and contraction+ // (Growth → Starter: 8 → 2 engines). Issue #79.+ await alignPromptsSafe(orgBefore.id, newPlanId, 'subscription.updated');+ }}break;}@@ -114,6 +158,15 @@ export async function POST(req: NextRequest) {: subscription.customer?.id;if (customerId) {+ // Snapshot to know whether this is an actual downgrade (Growth →+ // Starter) — if they were already on Starter, alignment is a+ // no-op anyway, but skipping the call avoids needless queries.+ const { data: orgBefore } = await supabaseAdmin+ .from('organizations')+ .select('id, plan')+ .eq('stripe_customer_id', customerId)+ .maybeSingle();+await supabaseAdmin.from('organizations').update({@@ -121,6 +174,13 @@ export async function POST(req: NextRequest) {plan: 'starter',}).eq('stripe_customer_id', customerId);++ if (orgBefore && orgBefore.plan !== 'starter') {+ // Trim prompts back to Starter's 2-engine set so a downgraded+ // org doesn't keep paying scraper cost on engines the plan no+ // longer covers. Issue #79.+ await alignPromptsSafe(orgBefore.id, 'starter', 'subscription.deleted');+ }}break;}diff --git a/web/src/lib/plan-engines.ts b/web/src/lib/plan-engines.tsindex 928d39374..5f15e4796 100644--- a/web/src/lib/plan-engines.ts+++ b/web/src/lib/plan-engines.ts@@ -1,3 +1,4 @@+import { supabaseAdmin } from '@/lib/supabase/admin';import { getPlan, type PlanId } from '@/config/plans';import { ALL_MODELS, ALL_SCRAPERS } from '@/config/prompt-options';@@ -34,3 +35,60 @@ export function getActiveEngineIdsForPlan(planId: PlanId | string | null | undefreturn { platforms, models };}++/**+ * Rewrite every prompt in an organisation's brands so its `platforms` and+ * `models` arrays match what the given plan allows. Handles both directions:+ *+ * - **Expansion** (Starter → Growth): Growth has no `allowedScrapers`,+ * so every prompt's platforms array becomes all 8 engine ids. Without+ * this an upgraded Growth customer keeps tracking only 2 engines (#79).+ * - **Contraction** (Growth → Starter on downgrade / cancellation):+ * Starter restricts to `['chatgpt-web', 'perplexity-web']`, so prompts+ * get trimmed down. Without this a downgraded org would keep paying+ * scraper cost on engines the plan no longer covers.+ *+ * Idempotent — re-running with the same plan is a no-op write. Returns the+ * count of prompts rewritten so callers can log it.+ */+export async function alignPromptsToPlanForOrg(+ orgId: string,+ planId: PlanId | string | null | undefined,+): Promise<{+ platforms: string[];+ models: string[];+ promptCount: number;+}> {+ const { platforms, models } = getActiveEngineIdsForPlan(planId);++ const { data: brands, error: brandsErr } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('organization_id', orgId);+ if (brandsErr) throw new Error(`brands lookup: ${brandsErr.message}`);++ const brandIds = (brands ?? []).map((b) => b.id);+ if (brandIds.length === 0) {+ return { platforms, models, promptCount: 0 };+ }++ const { data: promptSets, error: setsErr } = await supabaseAdmin+ .from('prompt_sets')+ .select('id')+ .in('brand_id', brandIds);+ if (setsErr) throw new Error(`prompt_sets lookup: ${setsErr.message}`);++ const promptSetIds = (promptSets ?? []).map((p) => p.id);+ if (promptSetIds.length === 0) {+ return { platforms, models, promptCount: 0 };+ }++ const { data: updatedRows, error: updateErr } = await supabaseAdmin+ .from('prompts')+ .update({ platforms, models })+ .in('prompt_set_id', promptSetIds)+ .select('id');+ if (updateErr) throw new Error(`prompts update: ${updateErr.message}`);++ return { platforms, models, promptCount: (updatedRows ?? []).length };+}