Skip to content

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.

feat(settings): buy a trial now from Billing, with annual plans and the SAVE50 offer (#1300)

Cihan4259dc6e8de5
diff --git a/web/.env.example b/web/.env.example
index 1297175c6..251a9bbcf 100644
--- a/web/.env.example
+++ b/web/.env.example
@@ -85,6 +85,11 @@ NEXT_PUBLIC_API_URL=http://localhost:80
# STRIPE_WEBHOOK_SECRET=whsec_...
# STRIPE_STARTER_MONTHLY_PRICE_ID=price_...
# STRIPE_GROWTH_MONTHLY_PRICE_ID=price_...
+# Annual prices (a year up front, 20% off twelve months: Starter $470, Growth
+# $2,390 — the amounts in web/src/config/plans.ts). Without them the Billing
+# page's Annual choice can't be bought.
+# STRIPE_STARTER_ANNUAL_PRICE_ID=price_...
+# STRIPE_GROWTH_ANNUAL_PRICE_ID=price_...
# -----------------------------------------------------------------------------
# Supabase Service Role Key (cloud only — for Stripe webhooks)
diff --git a/web/messages/en.json b/web/messages/en.json
index 0a51261cd..be6967e34 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5859,8 +5859,31 @@
"upgradeTo": "Upgrade to {plan}",
"downgradeTo": "Downgrade to {plan}",
"changePlanConfirmTitle": "Change to {plan}?",
- "changePlanConfirmDescription": "You will be switched to the {plan} plan at ${price}/mo. Proration will be applied to your next invoice.",
+ "changePlanConfirmDescription": "You will be switched to the {plan} plan at ${price}/{interval, select, year {yr} other {mo}}. Proration will be applied to your next invoice.",
"changePlanConfirm": "Confirm Change",
+ "changePeriodTitle": "Switch to {interval, select, year {annual} other {monthly}} billing?",
+ "changePeriodDescription": "Your {plan} plan will cost ${price} a {interval, select, year {year} other {month}}. Proration will be applied to your next invoice.",
+ "billingPeriod": "Billing period",
+ "monthly": "Monthly",
+ "annual": "Annual",
+ "savePercent": "Save {percent}%",
+ "popular": "Popular",
+ "regularPrice": "Regular price",
+ "firstMonthOffer": "50% off your first month with code {code}",
+ "buyPlanNow": "Buy {plan} now",
+ "planAdminOnly": "Only admins can buy or change the plan. Ask an admin in your organization.",
+ "switchToAnnual": "Switch to annual billing",
+ "switchToMonthly": "Switch to monthly billing",
+ "buyNowTitle": "Buy {plan} now?",
+ "buyNowDescription": "Your free trial ends today and the card you added is charged ${price} for the first {interval, select, year {year} other {month}}. The plan then renews every {interval, select, year {year} other {month}}.",
+ "promoCode": "Promo code",
+ "firstMonthWithCode": "With {code}, your first month is ${price}.",
+ "buyNowConfirm": "Buy now",
+ "planBought": "Your {plan} plan is active. Thank you!",
+ "paymentFailed": "The payment didn't go through.",
+ "paymentFailedHint": "Your free trial carries on. Update your card on Stripe, then try again.",
+ "updateCard": "Update card",
+ "trialEndsOn": "Your free trial ends on {date}",
"processing": "Processing...",
"cancelSubscription": "Cancel Subscription",
"cancelConfirmTitle": "Cancel your subscription?",
diff --git a/web/src/app/api/stripe/subscription/route.test.ts b/web/src/app/api/stripe/subscription/route.test.ts
new file mode 100644
index 000000000..d139c8f51
--- /dev/null
+++ b/web/src/app/api/stripe/subscription/route.test.ts
@@ -0,0 +1,271 @@
+import type { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * PATCH /api/stripe/subscription: buy a free trial now on any plan and
+ * period (with the first-month code on a monthly plan), or change the plan or
+ * billing period of a paid one. DELETE: cancel at the period's end. Both are
+ * the admins'.
+ */
+
+let org: Record<string, unknown>;
+let role: string;
+
+/** A Supabase query that answers `single()` with the row given. */
+const row = (data: unknown) => {
+ const query = { select: () => query, eq: () => query, single: async () => ({ data }) };
+ return query;
+};
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ from: (table: string) => row(table === 'profiles' ? { organization_id: 'org1', role } : org),
+ }),
+}));
+
+const db = vi.hoisted(() => ({ update: vi.fn(), eq: vi.fn() }));
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: () => ({
+ update: (values: unknown) => {
+ db.update(values);
+ return { eq: db.eq };
+ },
+ }),
+ },
+}));
+
+const stripeApi = vi.hoisted(() => ({
+ retrieve: vi.fn(),
+ update: vi.fn(),
+ listCodes: vi.fn(),
+}));
+vi.mock('@/lib/stripe', () => ({
+ stripe: {
+ subscriptions: { retrieve: stripeApi.retrieve, update: stripeApi.update },
+ promotionCodes: { list: stripeApi.listCodes },
+ },
+ priceIdFor: (planId: string, interval: string) =>
+ planId === 'growth' && interval === 'year' && !process.env.GROWTH_ANNUAL_SET
+ ? undefined
+ : `price_${planId}_${interval}`,
+}));
+
+const align = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/plan-engines', () => ({ alignPromptsToPlanForOrg: align }));
+
+const { DELETE, PATCH } = await import('./route');
+
+const patch = (body: unknown) =>
+ PATCH(
+ new Request('http://localhost/api/stripe/subscription', {
+ method: 'PATCH',
+ body: JSON.stringify(body),
+ }) as unknown as NextRequest,
+ );
+
+/** A Stripe subscription with one item. */
+const subscription = (status: string, interval = 'month', amount = 4900) => ({
+ id: 'sub1',
+ status,
+ cancel_at_period_end: false,
+ metadata: {},
+ items: {
+ data: [
+ {
+ id: 'si1',
+ current_period_end: 1_800_000_000,
+ price: { unit_amount: amount, recurring: { interval } },
+ },
+ ],
+ },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ delete process.env.GROWTH_ANNUAL_SET;
+ org = { id: 'org1', plan: 'starter', stripe_subscription_id: 'sub1' };
+ role = 'admin';
+ align.mockResolvedValue({ promptCount: 0, platforms: [], models: [] });
+ db.eq.mockResolvedValue({});
+});
+
+describe('buying a trial now', () => {
+ it('ends the trial today on the plan asked for, with the first-month code', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ stripeApi.listCodes.mockResolvedValue({ data: [{ id: 'promo_save50' }] });
+ stripeApi.update.mockResolvedValue(subscription('active', 'month', 24900));
+
+ const res = await patch({
+ buyNow: true,
+ newPlanId: 'growth',
+ interval: 'month',
+ promoCode: 'SAVE50',
+ });
+
+ expect(res.status).toBe(200);
+ expect(stripeApi.listCodes).toHaveBeenCalledWith({ code: 'SAVE50', active: true, limit: 1 });
+ expect(stripeApi.update).toHaveBeenCalledWith('sub1', {
+ items: [{ id: 'si1', price: 'price_growth_month' }],
+ trial_end: 'now',
+ cancel_at_period_end: false,
+ proration_behavior: 'none',
+ payment_behavior: 'error_if_incomplete',
+ discounts: [{ promotion_code: 'promo_save50' }],
+ metadata: { plan_id: 'growth', organization_id: 'org1' },
+ });
+ expect(db.update).toHaveBeenCalledWith({ plan: 'growth', subscription_status: 'active' });
+ expect(align).toHaveBeenCalledWith('org1', 'growth');
+ expect(await res.json()).toMatchObject({
+ planId: 'growth',
+ status: 'active',
+ priceAmount: 249,
+ interval: 'month',
+ });
+ });
+
+ it('buys a year without a code', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ stripeApi.update.mockResolvedValue(subscription('active', 'year', 47000));
+
+ const res = await patch({ buyNow: true, interval: 'year', promoCode: 'SAVE50' });
+
+ expect(res.status).toBe(200);
+ expect(stripeApi.listCodes).not.toHaveBeenCalled();
+ const params = stripeApi.update.mock.calls[0][1];
+ expect(params.items).toEqual([{ id: 'si1', price: 'price_starter_year' }]);
+ expect(params.discounts).toBeUndefined();
+ // Same plan: its engines stay as they are.
+ expect(align).not.toHaveBeenCalled();
+ });
+
+ it('refuses an unknown code before charging anything', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ stripeApi.listCodes.mockResolvedValue({ data: [] });
+
+ const res = await patch({ buyNow: true, promoCode: 'NOPE' });
+
+ expect(res.status).toBe(400);
+ expect(await res.json()).toMatchObject({ code: 'invalid_promo_code' });
+ expect(stripeApi.update).not.toHaveBeenCalled();
+ });
+
+ it('reports a declined card and changes nothing', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ stripeApi.update.mockRejectedValue(new Error('Your card was declined.'));
+
+ const res = await patch({ buyNow: true });
+
+ expect(res.status).toBe(402);
+ expect(await res.json()).toEqual({
+ error: 'Your card was declined.',
+ code: 'payment_failed',
+ });
+ expect(db.update).not.toHaveBeenCalled();
+ });
+
+ it('buys without a discount when the code field is left empty', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ stripeApi.update.mockResolvedValue(subscription('active'));
+
+ const res = await patch({ buyNow: true, promoCode: '' });
+
+ expect(res.status).toBe(200);
+ expect(stripeApi.listCodes).not.toHaveBeenCalled();
+ expect(stripeApi.update.mock.calls[0][1].discounts).toBeUndefined();
+ });
+
+ it('leaves buying to admins, before anything is charged', async () => {
+ for (const other of ['manager', 'analyst', 'agency_partner']) {
+ role = other;
+ const res = await patch({ buyNow: true, newPlanId: 'growth' });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'admin_only' });
+ }
+ expect(stripeApi.retrieve).not.toHaveBeenCalled();
+ expect(stripeApi.update).not.toHaveBeenCalled();
+ });
+
+ it('is only for a trial', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+
+ const res = await patch({ buyNow: true, newPlanId: 'growth' });
+
+ expect(res.status).toBe(400);
+ expect(stripeApi.update).not.toHaveBeenCalled();
+ });
+});
+
+describe('changing a paid plan', () => {
+ it('moves the current plan to annual billing, prorated', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+ stripeApi.update.mockResolvedValue(subscription('active', 'year', 47000));
+
+ const res = await patch({ interval: 'year' });
+
+ expect(res.status).toBe(200);
+ expect(stripeApi.update).toHaveBeenCalledWith('sub1', {
+ items: [{ id: 'si1', price: 'price_starter_year' }],
+ metadata: { plan_id: 'starter', organization_id: 'org1' },
+ proration_behavior: 'create_prorations',
+ payment_behavior: 'error_if_incomplete',
+ });
+ expect(await res.json()).toMatchObject({ planId: 'starter', interval: 'year' });
+ });
+
+ it('keeps the plan as it was when the new period’s invoice is declined', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+ stripeApi.update.mockRejectedValue(new Error('Your card was declined.'));
+
+ const res = await patch({ interval: 'year' });
+
+ expect(res.status).toBe(402);
+ expect(await res.json()).toEqual({
+ error: 'Your card was declined.',
+ code: 'payment_failed',
+ });
+ expect(db.update).not.toHaveBeenCalled();
+ });
+
+ it('says so when an annual price is not set up in Stripe', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+
+ const res = await patch({ newPlanId: 'growth', interval: 'year' });
+
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: 'Price not configured' });
+ expect(stripeApi.update).not.toHaveBeenCalled();
+ });
+
+ it('refuses the plan and period it already has, or a malformed request', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+
+ expect((await patch({ newPlanId: 'starter', interval: 'month' })).status).toBe(400);
+ expect((await patch({ newPlanId: 'enterprise' })).status).toBe(400);
+ expect(stripeApi.update).not.toHaveBeenCalled();
+ });
+});
+
+describe('cancelling', () => {
+ it('cancels at the period’s end for an admin, and for no one else', async () => {
+ org = { stripe_subscription_id: 'sub_1' };
+ stripeApi.update.mockReset().mockResolvedValue({
+ items: { data: [{ current_period_end: 1_800_000_000 }] },
+ });
+ for (const other of ['manager', 'analyst', 'agency_partner']) {
+ role = other;
+ const res = await DELETE();
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'admin_only' });
+ }
+ expect(stripeApi.update).not.toHaveBeenCalled();
+
+ role = 'admin';
+ const res = await DELETE();
+ expect(res.status).toBe(200);
+ expect(stripeApi.update).toHaveBeenCalledWith('sub_1', { cancel_at_period_end: true });
+ });
+});
diff --git a/web/src/app/api/stripe/subscription/route.ts b/web/src/app/api/stripe/subscription/route.ts
index 56f5ced48..3a0b7d5e2 100644
--- a/web/src/app/api/stripe/subscription/route.ts
+++ b/web/src/app/api/stripe/subscription/route.ts
@@ -1,9 +1,9 @@
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 { SUBSCRIBABLE_PLANS } from '@/config/plans';
+import { stripe, priceIdFor } from '@/lib/stripe';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
+import { planChange, planRequestSchema, type BillingInterval } from '@/lib/billing/plan-purchase';
type SubscriptionItem = {
id: string;
@@ -50,7 +50,7 @@ async function getOrgStripeIds() {
const { data: profile } = await supabase
.from('profiles')
- .select('organization_id')
+ .select('organization_id, role')
.eq('id', user.id)
.single();
@@ -64,7 +64,13 @@ async function getOrgStripeIds() {
.eq('id', profile.organization_id)
.single();
- return org;
+ return org ? { ...org, role: profile.role as string | null } : null;
+}
+
+/** A card the charge needs was declined, or its bank wants it confirmed. */
+function paymentFailed(err: unknown) {
+ const message = err instanceof Error ? err.message : 'Payment failed';
+ return NextResponse.json({ error: message, code: 'payment_failed' }, { status: 402 });
}
/** GET — current subscription details */
@@ -110,28 +116,58 @@ export async function GET() {
}
}
-/** PATCH — change plan (upgrade/downgrade) or reactivate */
+/** The subscription's billing period, from its first item's price. */
+function intervalOf(sub: SubscriptionRaw): BillingInterval | null {
+ const interval = sub.items.data[0]?.price?.recurring?.interval;
+ return interval === 'month' || interval === 'year' ? interval : null;
+}
+
+/** The subscription as GET returns it, after a change. */
+function subscriptionBody(planId: string, sub: SubscriptionRaw) {
+ const price = sub.items.data[0]?.price;
+ return {
+ planId,
+ status: sub.status,
+ currentPeriodEnd: getCurrentPeriodEndIso(sub),
+ cancelAtPeriodEnd: sub.cancel_at_period_end,
+ priceAmount: price?.unit_amount ? price.unit_amount / 100 : null,
+ interval: price?.recurring?.interval ?? null,
+ };
+}
+
+/**
+ * PATCH — reactivate, change plan or billing period (upgrade/downgrade,
+ * monthly ↔ annual), or buy a free trial now.
+ */
export async function PATCH(req: NextRequest) {
try {
const org = await getOrgStripeIds();
if (!org) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
+ // Buying, changing or reactivating the plan charges the organization's
+ // card: admins only, as the Anthropic key and team management are.
+ if (org.role !== 'admin') {
+ return NextResponse.json(
+ { error: 'Only admins can change the plan', code: 'admin_only' },
+ { status: 403 },
+ );
+ }
if (!org.stripe_subscription_id) {
return NextResponse.json({ error: 'No active subscription' }, { status: 400 });
}
- const body = await req.json();
- const { newPlanId, reactivate } = body as {
- newPlanId?: 'starter' | 'growth';
- reactivate?: boolean;
- };
+ const parsed = planRequestSchema.safeParse(await req.json().catch(() => null));
+ if (!parsed.success) {
+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ }
+ const body = parsed.data;
const subscriptionId = org.stripe_subscription_id as string;
// Reactivate a canceled-at-period-end subscription
- if (reactivate) {
+ if (body.reactivate) {
const updated = (await stripe.subscriptions.update(subscriptionId, {
cancel_at_period_end: false,
})) as unknown as SubscriptionRaw;
@@ -142,20 +178,6 @@ export async function PATCH(req: NextRequest) {
});
}
- // Plan change
- if (!newPlanId || !SUBSCRIBABLE_PLANS.includes(newPlanId)) {
- return NextResponse.json({ error: 'Invalid plan' }, { status: 400 });
- }
-
- if (newPlanId === org.plan) {
- return NextResponse.json({ error: 'Already on this plan' }, { status: 400 });
- }
-
- const priceId = PRICE_IDS[newPlanId]?.monthly;
- if (!priceId) {
- return NextResponse.json({ error: 'Price not configured' }, { status: 400 });
- }
-
const currentSub = (await stripe.subscriptions.retrieve(
subscriptionId,
)) as unknown as SubscriptionRaw;
@@ -165,16 +187,80 @@ export async function PATCH(req: NextRequest) {
return NextResponse.json({ error: 'Subscription item not found' }, { status: 400 });
}
- const updated = (await stripe.subscriptions.update(subscriptionId, {
- items: [{ id: itemId, price: priceId }],
- metadata: { plan_id: newPlanId, organization_id: org.id },
- proration_behavior: 'create_prorations',
- })) as unknown as SubscriptionRaw;
+ const change = planChange(
+ {
+ status: currentSub.status,
+ planId: (org.plan as string | null) ?? 'starter',
+ interval: intervalOf(currentSub),
+ },
+ body,
+ );
+ if (change.kind === 'refused') {
+ return NextResponse.json({ error: change.error }, { status: 400 });
+ }
+
+ const priceId = priceIdFor(change.planId, change.interval);
+ if (!priceId) {
+ return NextResponse.json({ error: 'Price not configured' }, { status: 400 });
+ }
- // Optimistic DB update. Stripe has already accepted the plan change, so
- // this is the server mirroring its own decision, not the caller writing
- // their own plan — hence the service role, same as the webhook.
- await supabaseAdmin.from('organizations').update({ plan: newPlanId }).eq('id', org.id);
+ let updated: SubscriptionRaw;
+ if (change.kind === 'buy_now') {
+ let promotionCodeId: string | null = null;
+ if (change.promoCode) {
+ const { data: codes } = await stripe.promotionCodes.list({
+ code: change.promoCode,
+ active: true,
+ limit: 1,
+ });
+ promotionCodeId = codes[0]?.id ?? null;
+ if (!promotionCodeId) {
+ return NextResponse.json(
+ { error: "That promo code isn't valid", code: 'invalid_promo_code' },
+ { status: 400 },
+ );
+ }
+ }
+ try {
+ // The trial ends today and the first period is invoiced at once on
+ // the card added for the trial. Nothing changes unless it's paid:
+ // a declined card (or one its bank wants confirmed) is an error, and
+ // the trial carries on.
+ updated = (await stripe.subscriptions.update(subscriptionId, {
+ items: [{ id: itemId, price: priceId }],
+ trial_end: 'now',
+ cancel_at_period_end: false,
+ proration_behavior: 'none',
+ payment_behavior: 'error_if_incomplete',
+ ...(promotionCodeId ? { discounts: [{ promotion_code: promotionCodeId }] } : {}),
+ metadata: { plan_id: change.planId, organization_id: org.id },
+ })) as unknown as SubscriptionRaw;
+ } catch (err) {
+ return paymentFailed(err);
+ }
+ } else {
+ try {
+ // A new billing period is invoiced at once: as when buying, nothing
+ // changes unless it's paid, so a declined card leaves the plan as it
+ // was rather than on the new period and past due.
+ updated = (await stripe.subscriptions.update(subscriptionId, {
+ items: [{ id: itemId, price: priceId }],
+ metadata: { plan_id: change.planId, organization_id: org.id },
+ proration_behavior: 'create_prorations',
+ payment_behavior: 'error_if_incomplete',
+ })) as unknown as SubscriptionRaw;
+ } catch (err) {
+ return paymentFailed(err);
+ }
+ }
+
+ // Optimistic DB update. Stripe has already accepted the change, so this
+ // is the server mirroring its own decision, not the caller writing their
+ // own plan — hence the service role, same as the webhook.
+ await supabaseAdmin
+ .from('organizations')
+ .update({ plan: change.planId, subscription_status: updated.status })
+ .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:
@@ -182,26 +268,20 @@ export async function PATCH(req: NextRequest) {
// 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);
+ // would see "plan unchanged" and skip alignment. A period change alone
+ // keeps the plan's engines.
+ if (change.planId !== org.plan) {
+ try {
+ const result = await alignPromptsToPlanForOrg(org.id, change.planId);
+ console.log(
+ `[stripe/subscription] Aligned ${result.promptCount} prompt(s) to plan=${change.planId} (${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({
- planId: newPlanId,
- status: updated.status,
- currentPeriodEnd: getCurrentPeriodEndIso(updated),
- cancelAtPeriodEnd: updated.cancel_at_period_end,
- priceAmount: newPrice?.unit_amount ? newPrice.unit_amount / 100 : null,
- interval: newPrice?.recurring?.interval ?? null,
- });
+ return NextResponse.json(subscriptionBody(change.planId, updated));
} catch (err) {
console.error('[stripe/subscription] PATCH error:', err);
return NextResponse.json(
@@ -211,13 +291,19 @@ export async function PATCH(req: NextRequest) {
}
}
-/** DELETE — cancel subscription at period end */
+/** DELETE — cancel subscription at period end (admins only, as changing the plan is) */
export async function DELETE() {
try {
const org = await getOrgStripeIds();
if (!org) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
+ if (org.role !== 'admin') {
+ return NextResponse.json(
+ { error: 'Only admins can cancel the plan', code: 'admin_only' },
+ { status: 403 },
+ );
+ }
if (!org.stripe_subscription_id) {
return NextResponse.json({ error: 'No active subscription' }, { status: 400 });
diff --git a/web/src/components/settings/billing-section.tsx b/web/src/components/settings/billing-section.tsx
index de2cc7f14..fadafeb54 100644
--- a/web/src/components/settings/billing-section.tsx
+++ b/web/src/components/settings/billing-section.tsx
@@ -179,7 +179,7 @@ export function BillingSection() {
{subscription.currentPeriodEnd && !subscription.cancelAtPeriodEnd && (
<p className="text-sm text-muted-foreground">
- {t('renewsOn', {
+ {t(subscription.status === 'trialing' ? 'trialEndsOn' : 'renewsOn', {
date: new Date(subscription.currentPeriodEnd).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
diff --git a/web/src/components/settings/plan-switcher.test.tsx b/web/src/components/settings/plan-switcher.test.tsx
index 21d618ef9..d99e8747a 100644
--- a/web/src/components/settings/plan-switcher.test.tsx
+++ b/web/src/components/settings/plan-switcher.test.tsx
@@ -3,6 +3,9 @@ import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
+import { toast } from 'sonner';
+import { RoleProvider } from '@/components/providers/role-provider';
+import type { TeamRole } from '@/components/providers/role-provider';
import { PlanSwitcher } from './plan-switcher';
vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
@@ -15,27 +18,55 @@ vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), err
let container: HTMLDivElement;
let root: Root;
+const onUpdate = vi.fn();
-async function render(planId = 'starter') {
+async function render(
+ planId = 'starter',
+ {
+ status = 'active',
+ interval = 'month',
+ role = 'admin',
+ }: { status?: string; interval?: string; role?: TeamRole } = {},
+) {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages}>
- <PlanSwitcher
- subscription={{
- planId,
- status: 'active',
- currentPeriodEnd: null,
- cancelAtPeriodEnd: false,
- priceAmount: 49,
- interval: 'month',
- }}
- onUpdate={vi.fn()}
- />
+ <RoleProvider role={role}>
+ <PlanSwitcher
+ subscription={{
+ planId,
+ status,
+ currentPeriodEnd: null,
+ cancelAtPeriodEnd: false,
+ priceAmount: 49,
+ interval,
+ }}
+ onUpdate={onUpdate}
+ />
+ </RoleProvider>
</NextIntlClientProvider>,
);
});
}
+const button = (label: string) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);
+
+async function click(label: string) {
+ await act(async () => {
+ button(label)!.click();
+ });
+}
+
+/** Each plan card's text, by plan name. */
+const cardText = () =>
+ Object.fromEntries(
+ [...container.querySelectorAll('[data-slot="card"]')].map((card) => [
+ card.querySelector('[data-slot="card-title"]')?.textContent,
+ card.textContent,
+ ]),
+ );
+
/** Each plan card's name and its list, in order. */
const cards = () =>
Object.fromEntries(
@@ -46,6 +77,7 @@ const cards = () =>
);
beforeEach(() => {
+ vi.clearAllMocks();
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -111,3 +143,135 @@ describe('the plan cards', () => {
).toBe('Contact Us');
});
});
+
+describe('the billing period', () => {
+ it('shows a year up front with the full year struck through and the saving', async () => {
+ await render();
+ expect(cardText().Starter).toContain('$49/mo');
+ expect(cardText().Growth).toContain('Popular');
+ expect(cardText().Starter).not.toContain('Popular');
+
+ await click('AnnualSave 20%');
+
+ const starter = container.querySelectorAll('[data-slot="card"]')[0];
+ const struck = starter.querySelector('.line-through');
+ expect(struck?.textContent).toBe('Regular price $588');
+ expect(starter.textContent).toContain('$470/yr');
+ expect(starter.textContent).toContain('Save 20%');
+ const growth = container.querySelectorAll('[data-slot="card"]')[1];
+ expect(growth.querySelector('.line-through')?.textContent).toBe('Regular price $2,988');
+ expect(growth.textContent).toContain('$2,390/yr');
+ });
+
+ it('moves a paid plan to annual billing from its own card', async () => {
+ await render('starter');
+ expect(button('Switch to annual billing')).toBeUndefined();
+
+ await click('AnnualSave 20%');
+ await click('Switch to annual billing');
+
+ expect(document.body.textContent).toContain('Switch to annual billing?');
+ expect(document.body.textContent).toContain('Your Starter plan will cost $470 a year.');
+ });
+});
+
+describe('buying during the free trial', () => {
+ beforeEach(() => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () =>
+ Response.json({ planId: 'growth', status: 'active', interval: 'month', priceAmount: 249 }),
+ ),
+ );
+ });
+
+ it('leaves buying and changing the plan to admins', async () => {
+ await render('starter', { status: 'trialing', role: 'manager' });
+ expect(document.body.textContent).toContain(
+ 'Only admins can buy or change the plan. Ask an admin in your organization.',
+ );
+ expect(
+ [...document.querySelectorAll('button')].filter((b) =>
+ /^(Buy|Upgrade|Downgrade|Switch)/.test(b.textContent?.trim() ?? ''),
+ ),
+ ).toEqual([]);
+ });
+
+ it('leaves cancelling to admins', async () => {
+ const cancel = () =>
+ [...document.querySelectorAll('button')].find(
+ (b) => b.textContent?.trim() === 'Cancel Subscription',
+ );
+ await render('growth', { status: 'active', role: 'manager' });
+ expect(cancel()).toBeUndefined();
+ await render('growth', { status: 'active', role: 'admin' });
+ expect(cancel()).toBeDefined();
+ });
+
+ it('offers every plan now, with the first-month code on monthly', async () => {
+ await render('starter', { status: 'trialing' });
+ expect(button('Buy Starter now')).toBeDefined();
+ expect(button('Buy Growth now')).toBeDefined();
+ expect(container.textContent).toContain('50% off your first month with code SAVE50');
+ });
+
+ it('buys Growth monthly with SAVE50 filled in', async () => {
+ await render('starter', { status: 'trialing' });
+ await click('Buy Growth now');
+
+ expect(document.body.textContent).toContain('Buy Growth now?');
+ expect(document.body.textContent).toContain(
+ 'Your free trial ends today and the card you added is charged $249 for the first month.',
+ );
+ const code = document.querySelector<HTMLInputElement>('#promo-code');
+ expect(code?.value).toBe('SAVE50');
+ expect(document.body.textContent).toContain('With SAVE50, your first month is $124.50.');
+
+ await click('Buy now');
+
+ expect(fetch).toHaveBeenCalledWith('/api/stripe/subscription', {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ newPlanId: 'growth',
+ interval: 'month',
+ buyNow: true,
+ promoCode: 'SAVE50',
+ }),
+ });
+ expect(onUpdate).toHaveBeenCalledWith(expect.objectContaining({ status: 'active' }));
+ });
+
+ it('buys a year without a code', async () => {
+ await render('starter', { status: 'trialing' });
+ await click('AnnualSave 20%');
+ expect(container.textContent).not.toContain('SAVE50');
+ await click('Buy Starter now');
+
+ expect(document.querySelector('#promo-code')).toBeNull();
+ await click('Buy now');
+
+ expect(JSON.parse((vi.mocked(fetch).mock.calls[0][1] as RequestInit).body as string)).toEqual({
+ newPlanId: 'starter',
+ interval: 'year',
+ buyNow: true,
+ });
+ });
+
+ it('offers to update the card when the payment fails', async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(
+ Response.json({ error: 'Your card was declined.', code: 'payment_failed' }, { status: 402 }),
+ );
+ await render('starter', { status: 'trialing' });
+ await click('Buy Starter now');
+ await click('Buy now');
+
+ expect(toast.error).toHaveBeenCalledWith('Your card was declined.', {
+ description: 'Your free trial carries on. Update your card on Stripe, then try again.',
+ action: { label: 'Update card', onClick: expect.any(Function) },
+ });
+ expect(onUpdate).not.toHaveBeenCalled();
+ // The dialog stays open to try again.
+ expect(document.body.textContent).toContain('Buy Starter now?');
+ });
+});
diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsx
index ef998e207..b1ffa4dc5 100644
--- a/web/src/components/settings/plan-switcher.tsx
+++ b/web/src/components/settings/plan-switcher.tsx
@@ -3,10 +3,11 @@
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { Check, ArrowUp, ArrowDown, Mail, ExternalLink } from 'lucide-react';
+import { Check, ArrowUp, ArrowDown, Mail, ExternalLink, Repeat, ShoppingCart } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
+import { Input } from '@/components/ui/input';
import {
Dialog,
DialogContent,
@@ -17,6 +18,15 @@ import {
DialogTrigger,
} from '@/components/ui/dialog';
import { CONTACT_SALES_URL, PLANS, SUBSCRIBABLE_PLANS, type PlanId } from '@/config/plans';
+import {
+ FIRST_MONTH_CODE,
+ annualSaving,
+ periodPrice,
+ type BillingInterval,
+} from '@/lib/billing/plan-purchase';
+import { useUserRole } from '@/hooks/use-user-role';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
interface SubscriptionData {
planId: string;
@@ -35,32 +45,58 @@ interface PlanSwitcherProps {
export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
const t = useTranslations('settings');
const tCards = useTranslations('settings.planCards');
+ // Buying or changing the plan charges the organization's card: admins only,
+ // as the subscription route checks.
+ const { canAdmin } = useUserRole();
const [loading, setLoading] = useState(false);
const [cancelLoading, setCancelLoading] = useState(false);
const [portalLoading, setPortalLoading] = useState(false);
- const [changePlanOpen, setChangePlanOpen] = useState(false);
const [cancelOpen, setCancelOpen] = useState(false);
- const [selectedPlan, setSelectedPlan] = useState<PlanId | null>(null);
+ // The plan a card's button asked for: bought now during a trial, or changed to.
+ const [pending, setPending] = useState<{ planId: PlanId; buy: boolean } | null>(null);
+ const [promoCode, setPromoCode] = useState(FIRST_MONTH_CODE);
const currentPlanId = subscription.planId as PlanId;
+ const currentInterval: BillingInterval = subscription.interval === 'year' ? 'year' : 'month';
+ const [period, setPeriod] = useState<BillingInterval>(currentInterval);
+ // A trial is bought outright: any plan, either period, paid today.
+ const trialing = subscription.status === 'trialing';
+ const saving = Math.max(0, ...SUBSCRIBABLE_PLANS.map((id) => annualSaving(id) ?? 0));
- async function handleChangePlan() {
- if (!selectedPlan) return;
+ async function handleConfirm() {
+ if (!pending) return;
setLoading(true);
try {
const res = await fetch('/api/stripe/subscription', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ newPlanId: selectedPlan }),
+ body: JSON.stringify({
+ newPlanId: pending.planId,
+ interval: period,
+ ...(pending.buy
+ ? { buyNow: true, ...(period === 'month' ? { promoCode: promoCode.trim() } : {}) }
+ : {}),
+ }),
});
if (!res.ok) {
const err = await res.json();
+ // A declined card, or one its bank wants confirmed: the trial carries
+ // on, and Stripe's billing page is where the card is changed.
+ if (err.code === 'payment_failed') {
+ toast.error(err.error || t('paymentFailed'), {
+ description: t('paymentFailedHint'),
+ action: { label: t('updateCard'), onClick: handleOpenPortal },
+ });
+ return;
+ }
throw new Error(err.error || 'Failed to change plan');
}
const data = await res.json();
onUpdate(data);
- toast.success(t('planChanged'));
- setChangePlanOpen(false);
+ toast.success(
+ pending.buy ? t('planBought', { plan: PLANS[pending.planId].name }) : t('planChanged'),
+ );
+ setPending(null);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to change plan');
} finally {
@@ -175,18 +211,70 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
return (
<div className="space-y-4">
+ {!canAdmin && <p className="text-sm text-muted-foreground">{t('planAdminOnly')}</p>}
+ {/* Billing period: a year up front saves 20% */}
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div
+ role="group"
+ aria-label={t('billingPeriod')}
+ className="inline-flex rounded-lg border bg-muted/40 p-0.5"
+ >
+ {(['month', 'year'] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ aria-pressed={period === value}
+ onClick={() => setPeriod(value)}
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-colors',
+ period === value
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {value === 'month' ? t('monthly') : t('annual')}
+ {value === 'year' && saving > 0 && (
+ <span className="rounded-full bg-emerald-100 px-1.5 text-xs font-medium text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-400">
+ {t('savePercent', { percent: saving })}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ {trialing && period === 'month' && (
+ <p className="text-xs text-muted-foreground">
+ {t('firstMonthOffer', { code: FIRST_MONTH_CODE })}
+ </p>
+ )}
+ </div>
+
{/* Plan cards */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{SUBSCRIBABLE_PLANS.map((planId) => {
const plan = PLANS[planId];
const isCurrent = planId === currentPlanId;
const upgrade = isUpgrade(planId);
+ const price = periodPrice(planId, period);
+ const fullYear = plan.pricing ? plan.pricing.monthly * 12 : null;
+ const planSaving = annualSaving(planId);
+ // What its button does: buy it now during a trial; otherwise switch
+ // the period of the current plan, or change to this one.
+ const action = trialing
+ ? 'buy'
+ : isCurrent
+ ? period === currentInterval
+ ? null
+ : 'period'
+ : 'change';
return (
<Card key={planId} className={isCurrent ? 'border-primary' : undefined}>
<CardHeader className="pb-3">
- <div className="flex items-center justify-between">
- <CardTitle className="text-base">{plan.name}</CardTitle>
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <CardTitle className="text-base">{plan.name}</CardTitle>
+ {plan.highlighted && <Badge variant="secondary">{t('popular')}</Badge>}
+ </div>
{isCurrent && (
<Badge variant="default">
<Check className="mr-1 h-3 w-3" />
@@ -197,9 +285,28 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
<p className="text-sm text-muted-foreground">{tCards(`${planId}.tagline`)}</p>
</CardHeader>
<CardContent>
- <div className="mb-4">
- <span className="text-2xl font-bold">${plan.pricing?.monthly}</span>
- <span className="text-sm text-muted-foreground">/{t('month')}</span>
+ <div className="mb-4 flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ {period === 'year' && fullYear != null && price != null && (
+ <span className="text-base text-muted-foreground line-through">
+ <span className="sr-only">{t('regularPrice')} </span>${formatNumber(fullYear)}
+ </span>
+ )}
+ <span>
+ <span className="text-2xl font-bold">
+ {price != null ? `$${formatNumber(price)}` : '—'}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ /{period === 'year' ? t('year') : t('month')}
+ </span>
+ </span>
+ {period === 'year' && planSaving != null && (
+ <Badge
+ variant="outline"
+ className="border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-400"
+ >
+ {t('savePercent', { percent: planSaving })}
+ </Badge>
+ )}
</div>
<ul className="mb-4 space-y-1.5 text-sm">
@@ -220,50 +327,46 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
))}
</ul>
- {!isCurrent && (
- <Dialog
- open={changePlanOpen && selectedPlan === planId}
- onOpenChange={(open) => {
- setChangePlanOpen(open);
- if (open) setSelectedPlan(planId);
+ {action && canAdmin && (
+ <Button
+ className="w-full"
+ variant={
+ action === 'buy'
+ ? isCurrent
+ ? 'default'
+ : 'outline'
+ : upgrade
+ ? 'default'
+ : 'outline'
+ }
+ disabled={price == null}
+ onClick={() => {
+ setPromoCode(FIRST_MONTH_CODE);
+ setPending({ planId, buy: action === 'buy' });
}}
>
- <DialogTrigger
- render={
- <Button className="w-full" variant={upgrade ? 'default' : 'outline'} />
- }
- >
- {upgrade ? (
- <>
- <ArrowUp className="mr-1 h-4 w-4" />
- {t('upgradeTo', { plan: plan.name })}
- </>
- ) : (
- <>
- <ArrowDown className="mr-1 h-4 w-4" />
- {t('downgradeTo', { plan: plan.name })}
- </>
- )}
- </DialogTrigger>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle>
- {t('changePlanConfirmTitle', { plan: plan.name })}
- </DialogTitle>
- <DialogDescription>
- {t('changePlanConfirmDescription', {
- plan: plan.name,
- price: String(plan.pricing?.monthly),
- })}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button onClick={handleChangePlan} disabled={loading}>
- {loading ? t('processing') : t('changePlanConfirm')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ {action === 'buy' ? (
+ <>
+ <ShoppingCart className="mr-1 h-4 w-4" />
+ {t('buyPlanNow', { plan: plan.name })}
+ </>
+ ) : action === 'period' ? (
+ <>
+ <Repeat className="mr-1 h-4 w-4" />
+ {period === 'year' ? t('switchToAnnual') : t('switchToMonthly')}
+ </>
+ ) : upgrade ? (
+ <>
+ <ArrowUp className="mr-1 h-4 w-4" />
+ {t('upgradeTo', { plan: plan.name })}
+ </>
+ ) : (
+ <>
+ <ArrowDown className="mr-1 h-4 w-4" />
+ {t('downgradeTo', { plan: plan.name })}
+ </>
+ )}
+ </Button>
)}
</CardContent>
</Card>
@@ -271,6 +374,87 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
})}
</div>
+ {/* Buy now / change confirmation */}
+ <Dialog open={pending != null} onOpenChange={(open) => !open && setPending(null)}>
+ {pending && (
+ <DialogContent className="max-w-md">
+ {(() => {
+ const plan = PLANS[pending.planId];
+ const price = periodPrice(pending.planId, period) ?? 0;
+ const halfPrice = price / 2;
+ const offer =
+ pending.buy &&
+ period === 'month' &&
+ promoCode.trim().toUpperCase() === FIRST_MONTH_CODE;
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ {pending.buy
+ ? t('buyNowTitle', { plan: plan.name })
+ : pending.planId === currentPlanId
+ ? t('changePeriodTitle', { interval: period })
+ : t('changePlanConfirmTitle', { plan: plan.name })}
+ </DialogTitle>
+ <DialogDescription>
+ {pending.buy
+ ? t('buyNowDescription', {
+ price: formatNumber(price),
+ interval: period,
+ })
+ : pending.planId === currentPlanId
+ ? t('changePeriodDescription', {
+ plan: plan.name,
+ price: formatNumber(price),
+ interval: period,
+ })
+ : t('changePlanConfirmDescription', {
+ plan: plan.name,
+ price: formatNumber(price),
+ interval: period,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ {pending.buy && period === 'month' && (
+ <div className="space-y-1.5">
+ <label htmlFor="promo-code" className="text-sm font-medium">
+ {t('promoCode')}
+ </label>
+ <Input
+ id="promo-code"
+ value={promoCode}
+ onChange={(e) => setPromoCode(e.target.value)}
+ autoComplete="off"
+ className="uppercase"
+ />
+ {offer && (
+ <p className="text-xs text-emerald-700 dark:text-emerald-400">
+ {t('firstMonthWithCode', {
+ code: FIRST_MONTH_CODE,
+ price: Number.isInteger(halfPrice)
+ ? formatNumber(halfPrice)
+ : halfPrice.toFixed(2),
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ <DialogFooter>
+ <Button onClick={handleConfirm} disabled={loading}>
+ {loading
+ ? t('processing')
+ : pending.buy
+ ? t('buyNowConfirm')
+ : t('changePlanConfirm')}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+ })()}
+ </DialogContent>
+ )}
+ </Dialog>
+
{/* Custom plan: what it adds, from the pricing page */}
<div className="space-y-3 rounded-lg border bg-muted/30 p-5">
<div className="flex flex-wrap items-start justify-between gap-4">
@@ -314,13 +498,16 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
})}
</p>
</div>
- <Button variant="outline" size="sm" onClick={handleReactivate} disabled={loading}>
- {t('reactivate')}
- </Button>
+ {canAdmin && (
+ <Button variant="outline" size="sm" onClick={handleReactivate} disabled={loading}>
+ {t('reactivate')}
+ </Button>
+ )}
</div>
)}
<div className="flex items-center justify-between gap-4">
- {subscription.cancelAtPeriodEnd ? (
+ {/* Cancelling is the admins', as changing the plan is. */}
+ {subscription.cancelAtPeriodEnd || !canAdmin ? (
<span />
) : (
<Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 1e22b2d07..fcb2179e5 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -97,6 +97,11 @@ export interface PlanLimits {
export interface PlanPricing {
monthly: number;
+ /**
+ * A year paid up front, in dollars: twelve months less 20%, rounded to the
+ * dollar. Must match the plan's annual Stripe price (STRIPE_*_ANNUAL_PRICE_ID).
+ */
+ annual?: number;
}
export interface Plan {
@@ -154,7 +159,7 @@ export const PLANS: Record<PlanId, Plan> = {
id: 'starter',
name: 'Starter',
tagline: 'Track your brand across AI platforms',
- pricing: { monthly: 49 },
+ pricing: { monthly: 49, annual: 470 },
limits: {
maxBrands: 1,
maxPrompts: 50,
@@ -205,7 +210,7 @@ export const PLANS: Record<PlanId, Plan> = {
id: 'growth',
name: 'Growth',
tagline: 'For brands that need deep insights',
- pricing: { monthly: 249 },
+ pricing: { monthly: 249, annual: 2390 },
highlighted: true,
limits: {
maxBrands: 4,
diff --git a/web/src/lib/billing/plan-purchase.test.ts b/web/src/lib/billing/plan-purchase.test.ts
new file mode 100644
index 000000000..fad548142
--- /dev/null
+++ b/web/src/lib/billing/plan-purchase.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import { annualSaving, periodPrice, planChange, planRequestSchema } from './plan-purchase';
+
+describe('plan prices', () => {
+ it('reads a month or a year up front from the config', () => {
+ expect(periodPrice('starter', 'month')).toBe(49);
+ expect(periodPrice('starter', 'year')).toBe(470);
+ expect(periodPrice('growth', 'month')).toBe(249);
+ expect(periodPrice('growth', 'year')).toBe(2390);
+ expect(periodPrice('enterprise', 'month')).toBeNull();
+ });
+
+ it('saves 20% on a year against twelve months', () => {
+ expect(annualSaving('starter')).toBe(20);
+ expect(annualSaving('growth')).toBe(20);
+ expect(annualSaving('enterprise')).toBeNull();
+ });
+});
+
+describe('planChange', () => {
+ const trial = { status: 'trialing', planId: 'starter', interval: 'month' as const };
+ const paid = { status: 'active', planId: 'starter', interval: 'month' as const };
+
+ it('buys a trial now on any plan and period', () => {
+ expect(planChange(trial, { buyNow: true })).toEqual({
+ kind: 'buy_now',
+ planId: 'starter',
+ interval: 'month',
+ promoCode: null,
+ });
+ expect(
+ planChange(trial, { buyNow: true, newPlanId: 'growth', interval: 'year', promoCode: 'X' }),
+ ).toEqual({ kind: 'buy_now', planId: 'growth', interval: 'year', promoCode: null });
+ });
+
+ it('takes a promo code only with a monthly plan', () => {
+ expect(
+ planChange(trial, {
+ buyNow: true,
+ newPlanId: 'growth',
+ interval: 'month',
+ promoCode: 'SAVE50',
+ }),
+ ).toMatchObject({ kind: 'buy_now', promoCode: 'SAVE50' });
+ });
+
+ it('buys nothing now once the trial is over', () => {
+ expect(planChange(paid, { buyNow: true, newPlanId: 'growth' })).toEqual({
+ kind: 'refused',
+ error: 'Only a free trial can be bought now',
+ });
+ });
+
+ it('changes the plan, the period or both on a paid plan', () => {
+ expect(planChange(paid, { newPlanId: 'growth' })).toEqual({
+ kind: 'change',
+ planId: 'growth',
+ interval: 'month',
+ });
+ expect(planChange(paid, { interval: 'year' })).toEqual({
+ kind: 'change',
+ planId: 'starter',
+ interval: 'year',
+ });
+ expect(planChange(paid, { newPlanId: 'starter', interval: 'month' })).toEqual({
+ kind: 'refused',
+ error: 'Already on this plan',
+ });
+ });
+
+ it('refuses a plan that is not for sale', () => {
+ expect(planChange({ ...paid, planId: 'enterprise' }, { interval: 'year' })).toEqual({
+ kind: 'refused',
+ error: 'Invalid plan',
+ });
+ expect(planRequestSchema.safeParse({ newPlanId: 'enterprise' }).success).toBe(false);
+ expect(planRequestSchema.safeParse({ interval: 'week' }).success).toBe(false);
+ });
+});
diff --git a/web/src/lib/billing/plan-purchase.ts b/web/src/lib/billing/plan-purchase.ts
new file mode 100644
index 000000000..77c63a83d
--- /dev/null
+++ b/web/src/lib/billing/plan-purchase.ts
@@ -0,0 +1,76 @@
+import { z } from 'zod';
+import { PLANS, SUBSCRIBABLE_PLANS, type PlanId } from '@/config/plans';
+
+/** How often a subscription bills, as Stripe's `recurring.interval` names it. */
+export type BillingInterval = 'month' | 'year';
+
+/**
+ * The first-month offer: a Stripe promotion code for a 50% off, once-only
+ * coupon on Starter and Growth. Billing fills it in when a trial is bought
+ * monthly; Checkout takes it in its own promotion code box.
+ */
+export const FIRST_MONTH_CODE = 'SAVE50';
+
+/** A plan's price for one billing period, from the config; null when it has none. */
+export function periodPrice(planId: PlanId, interval: BillingInterval): number | null {
+ const pricing = PLANS[planId].pricing;
+ if (!pricing) return null;
+ return interval === 'year' ? (pricing.annual ?? null) : pricing.monthly;
+}
+
+/** What paying a year up front saves against twelve months, in whole percent. */
+export function annualSaving(planId: PlanId): number | null {
+ const pricing = PLANS[planId].pricing;
+ if (!pricing?.annual) return null;
+ return Math.round((1 - pricing.annual / (pricing.monthly * 12)) * 100);
+}
+
+/** PATCH /api/stripe/subscription's body. */
+export const planRequestSchema = z.object({
+ newPlanId: z.enum(['starter', 'growth']).optional(),
+ interval: z.enum(['month', 'year']).optional(),
+ reactivate: z.boolean().optional(),
+ /** End a free trial today on the chosen plan and period; the card on file pays at once. */
+ buyNow: z.boolean().optional(),
+ promoCode: z.string().trim().max(64).optional(),
+});
+
+export type PlanRequest = z.infer<typeof planRequestSchema>;
+
+export type PlanChange =
+ | { kind: 'buy_now'; planId: PlanId; interval: BillingInterval; promoCode: string | null }
+ | { kind: 'change'; planId: PlanId; interval: BillingInterval }
+ | { kind: 'refused'; error: string };
+
+/**
+ * What a plan request asks of the organization's subscription.
+ *
+ * - buy now: only while it's trialing. The trial ends today on the plan and
+ * period asked for (any of them: a Starter trial can buy Growth, or a
+ * year), and the card added for the trial pays the first period at once.
+ * A promotion code only goes with a monthly plan: a year up front has its
+ * own discount.
+ * - change: another plan or period on the same subscription, prorated. A
+ * trial carries on through it.
+ */
+export function planChange(
+ current: { status: string; planId: string; interval: BillingInterval | null },
+ request: Pick<PlanRequest, 'newPlanId' | 'interval' | 'buyNow' | 'promoCode'>,
+): PlanChange {
+ const planId = (request.newPlanId ?? current.planId) as PlanId;
+ const interval = request.interval ?? current.interval ?? 'month';
+ if (!SUBSCRIBABLE_PLANS.includes(planId)) return { kind: 'refused', error: 'Invalid plan' };
+
+ if (request.buyNow) {
+ if (current.status !== 'trialing') {
+ return { kind: 'refused', error: 'Only a free trial can be bought now' };
+ }
+ const promoCode = interval === 'month' ? request.promoCode || null : null;
+ return { kind: 'buy_now', planId, interval, promoCode };
+ }
+
+ if (planId === current.planId && interval === (current.interval ?? 'month')) {
+ return { kind: 'refused', error: 'Already on this plan' };
+ }
+ return { kind: 'change', planId, interval };
+}
diff --git a/web/src/lib/stripe.ts b/web/src/lib/stripe.ts
index 55ac3b81a..811e8d85d 100644
--- a/web/src/lib/stripe.ts
+++ b/web/src/lib/stripe.ts
@@ -5,8 +5,16 @@ export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export const PRICE_IDS = {
starter: {
monthly: process.env.STRIPE_STARTER_MONTHLY_PRICE_ID!,
+ annual: process.env.STRIPE_STARTER_ANNUAL_PRICE_ID,
},
growth: {
monthly: process.env.STRIPE_GROWTH_MONTHLY_PRICE_ID!,
+ annual: process.env.STRIPE_GROWTH_ANNUAL_PRICE_ID,
},
} as const;
+
+/** The Stripe price for a plan billed monthly or yearly; undefined when it isn't set up. */
+export function priceIdFor(planId: string, interval: 'month' | 'year'): string | undefined {
+ const prices = (PRICE_IDS as Record<string, { monthly?: string; annual?: string }>)[planId];
+ return (interval === 'year' ? prices?.annual : prices?.monthly) || undefined;
+}