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): give the free trial on an organization's first subscription only (#959)
Gökhan Geyik16b872f161ae
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex f523b53f1..d3c567e77 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -334,6 +334,24 @@ export default function OnboardingPage() {// Step 6 (cloud only)const [checkoutLoading, setCheckoutLoading] = useState<PlanId | null>(null);const [organizationId, setOrganizationId] = useState<string | null>(null);+ // Trial length when the plan step is reached; null once the organization has+ // had a subscription, since checkout then starts the plan without a trial.+ const [trialDays, setTrialDays] = useState<number | null>(14);++ useEffect(() => {+ if (step !== 6) return;+ let cancelled = false;+ fetch('/api/stripe/trial')+ .then((res) => (res.ok ? res.json() : null))+ .then((body: { trialAvailable: boolean; trialDays: number } | null) => {+ if (!cancelled && body) setTrialDays(body.trialAvailable ? body.trialDays : null);+ })+ // Keeps the default copy; checkout itself decides whether there is a trial.+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [step]);const [currentPlanId, setCurrentPlanId] = useState<PlanId>('starter');// What the dashboard preview shows when the plan step is reached by resuming@@ -893,7 +911,7 @@ export default function OnboardingPage() {// Cloud mode → proceed to subscription step (tracking triggered after payment)if (isCloud()) {- toast.success('Almost done! Choose a plan to start your free trial.');+ toast.success('Almost done! Choose a plan to get started.');setSavingCompetitors(false);setStep(6);return;@@ -1671,7 +1689,7 @@ export default function OnboardingPage() {<div className="mb-8 text-center"><p className="text-2xl tracking-tight">Welcome to {siteConfig.name}!</p><h1 className="mt-1 text-3xl font-bold tracking-tight sm:text-4xl">- Start Your 14-Day Free Trial+ {trialDays ? `Start Your ${trialDays}-Day Free Trial` : 'Choose Your Plan'}</h1></div>@@ -1761,7 +1779,11 @@ export default function OnboardingPage() {</div><p className="mt-8 text-center text-lg">Secure payments powered by Stripe.</p>- <p className="mt-1 text-center text-sm">Cancel anytime during your 14-day free trial.</p>+ <p className="mt-1 text-center text-sm">+ {trialDays+ ? `Cancel anytime during your ${trialDays}-day free trial.`+ : 'Your free trial has been used, so your plan starts today. Cancel anytime.'}+ </p></div><div className="flex mx-auto w-full max-w-2xl items-center justify-between mt-8">diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.tsindex 0243a15a6..5417abfd7 100644--- a/web/src/app/api/stripe/checkout/route.ts+++ b/web/src/app/api/stripe/checkout/route.ts@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';import { stripe, PRICE_IDS } from '@/lib/stripe';+import { TRIAL_DAYS, hasUsedTrial } from '@/lib/billing/trial';export async function POST(req: NextRequest) {try {@@ -77,12 +78,17 @@ export async function POST(req: NextRequest) {const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';+ // The free trial is for the organization's first subscription only. A+ // customer who already had one — trial taken and canceled, or a lapsed+ // plan — subscribes without another.+ const trial = !(await hasUsedTrial(stripe, customerId));+const session = await stripe.checkout.sessions.create({mode: 'subscription',customer: customerId,line_items: [{ price: priceId, quantity: 1 }],subscription_data: {- trial_period_days: 14,+ ...(trial ? { trial_period_days: TRIAL_DAYS } : {}),metadata: { organization_id: organizationId, plan_id: planId },},success_url: `${appUrl}/api/stripe/success?session_id={CHECKOUT_SESSION_ID}`,diff --git a/web/src/app/api/stripe/success/route.ts b/web/src/app/api/stripe/success/route.tsindex de8b027e0..ba7a61355 100644--- a/web/src/app/api/stripe/success/route.ts+++ b/web/src/app/api/stripe/success/route.ts@@ -40,7 +40,9 @@ export async function GET(req: NextRequest) {const { error: updateError } = await supabaseAdmin.from('organizations').update({- subscription_status: 'trialing',+ // What Stripe reports: trialing for a first subscription, active+ // for one started without a trial.+ subscription_status: subscription?.status ?? 'trialing',plan: planId || 'starter',stripe_customer_id: customerId,stripe_subscription_id: subscriptionId,diff --git a/web/src/app/api/stripe/trial/route.ts b/web/src/app/api/stripe/trial/route.tsnew file mode 100644index 000000000..83ec4f311--- /dev/null+++ b/web/src/app/api/stripe/trial/route.ts@@ -0,0 +1,38 @@+import { NextResponse } from 'next/server';+import { createClient } from '@/lib/supabase/server';+import { stripe } from '@/lib/stripe';+import { TRIAL_DAYS, hasUsedTrial } from '@/lib/billing/trial';++/**+ * GET /api/stripe/trial+ * Whether the caller's organization would get the free trial at checkout, so+ * the plan step does not promise one it will not give.+ */+export async function GET() {+ try {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });++ const { data: profile } = await supabase+ .from('profiles')+ .select('organization_id')+ .eq('id', user.id)+ .single();+ const { data: org } = profile?.organization_id+ ? await supabase+ .from('organizations')+ .select('stripe_customer_id')+ .eq('id', profile.organization_id)+ .single()+ : { data: null };++ const used = await hasUsedTrial(stripe, org?.stripe_customer_id as string | null);+ return NextResponse.json({ trialAvailable: !used, trialDays: TRIAL_DAYS });+ } catch (err) {+ console.error('[stripe/trial]', err);+ return NextResponse.json({ error: 'Internal error' }, { status: 500 });+ }+}diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.tsindex b43bd512f..9cfd1470b 100644--- a/web/src/app/api/stripe/webhook/route.ts+++ b/web/src/app/api/stripe/webhook/route.ts@@ -68,7 +68,8 @@ export async function POST(req: NextRequest) {const { error } = await supabaseAdmin.from('organizations').update({- subscription_status: 'trialing',+ // trialing for a first subscription, active without a trial.+ subscription_status: subscription.status,plan: planId || 'starter',stripe_customer_id: customerId,stripe_subscription_id: subscriptionId,diff --git a/web/src/lib/billing/trial.test.ts b/web/src/lib/billing/trial.test.tsnew file mode 100644index 000000000..b26d6f199--- /dev/null+++ b/web/src/lib/billing/trial.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from 'vitest';+import type Stripe from 'stripe';+import { hasUsedTrial } from './trial';++const client = (subscriptions: unknown[]) => {+ const list = vi.fn().mockResolvedValue({ data: subscriptions });+ return { client: { subscriptions: { list } } as unknown as Pick<Stripe, 'subscriptions'>, list };+};++describe('hasUsedTrial', () => {+ it('gives a customer with no subscription history the trial', async () => {+ const { client: c } = client([]);+ expect(await hasUsedTrial(c, 'cus_new')).toBe(false);+ });++ it('withholds it once any subscription existed, canceled ones included', async () => {+ const { client: c, list } = client([{ id: 'sub_old', status: 'canceled' }]);+ expect(await hasUsedTrial(c, 'cus_returning')).toBe(true);+ expect(list).toHaveBeenCalledWith({ customer: 'cus_returning', status: 'all', limit: 1 });+ });++ it('does not ask Stripe before a customer exists', async () => {+ const { client: c, list } = client([]);+ expect(await hasUsedTrial(c, null)).toBe(false);+ expect(list).not.toHaveBeenCalled();+ });+});diff --git a/web/src/lib/billing/trial.ts b/web/src/lib/billing/trial.tsnew file mode 100644index 000000000..15acd3c4f--- /dev/null+++ b/web/src/lib/billing/trial.ts@@ -0,0 +1,28 @@+import type Stripe from 'stripe';++/** Length of the free trial a first subscription starts with. */+export const TRIAL_DAYS = 14;++/**+ * Whether this Stripe customer has already had a subscription, and with it+ * the free trial.+ *+ * Checkout used to start every subscription with a trial. An organization+ * could take the trial, cancel before it ended, subscribe again and get+ * another one — indefinitely, with the same account and card. The trial is+ * now for a customer's first subscription only. Every subscription a customer+ * ever had is listed by Stripe (status 'all' includes canceled and expired+ * ones), so one result is enough to know.+ */+export async function hasUsedTrial(+ client: Pick<Stripe, 'subscriptions'>,+ customerId: string | null | undefined,+): Promise<boolean> {+ if (!customerId) return false;+ const { data } = await client.subscriptions.list({+ customer: customerId,+ status: 'all',+ limit: 1,+ });+ return data.length > 0;+}