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(billing): show the plans in the read-only dialog, with Monthly or Annual and a promo code (#1604)

Cihancbc282e07167
diff --git a/web/messages/en.json b/web/messages/en.json
index 04729a1a6..fa4a66ca2 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -70,17 +70,46 @@
"ended": "Your workspace has no active plan, so it's read-only. Everything you set up is still here: pick a plan to track, write and run your agents again.",
"payment_failed": "Your last payment didn't go through, so your workspace is read-only. Everything you set up is still here: update the payment method to track, write and run your agents again."
},
- "notNow": "Not now"
+ "notNow": "Not now",
+ "readOnlyLabel": "Your workspace is read-only",
+ "memberNote": "Only an admin can choose a plan for your workspace."
},
"ask": {
- "ended": "Ask your workspace admin to choose a plan.",
+ "ended": "Ask your admin to choose a plan.",
"endedNamed": "Ask {name}, your workspace admin, to choose a plan.",
"payment_failed": "Ask your workspace admin to update the payment method.",
"payment_failedNamed": "Ask {name}, your workspace admin, to update the payment method."
},
"choosePlan": "Choose a plan",
"updatePayment": "Update payment method",
- "portalFailed": "Couldn't open the billing page. Try again."
+ "portalFailed": "Couldn't open the billing page. Try again.",
+ "plans": {
+ "perMonthBilledYearly": "{price} a month, billed yearly",
+ "chooseToday": "Choose {plan} · {price} today",
+ "openingCheckout": "Opening checkout…",
+ "payByCard": "You'll pay by card on Stripe's checkout.",
+ "askAdmin": "Ask your admin to choose a plan",
+ "customName": "Custom",
+ "customTagline": "For large companies and agencies managing AI visibility at scale.",
+ "startingAt": "Starting at",
+ "customAiUsage": "Custom AI usage, from {count}x",
+ "contactUs": "Contact us",
+ "pricesInUsd": "Prices in USD.",
+ "promo": {
+ "apply": "Apply",
+ "checking": "Checking…",
+ "remove": "Remove the code",
+ "applied": "{code} · {discount} off {duration, select, once {your first month} repeating {your first {months, plural, one {month} other {# months}}} other {every month}}",
+ "deal": "{code}: {duration, select, once {first month} repeating {first {months, plural, one {month} other {# months}}} other {every month}} {discount} off",
+ "per": "{duration, select, once {first month} repeating {/mo for {months, plural, one {# month} other {# months}}} other {/mo}}",
+ "then": "then {price}/mo",
+ "appliedNote": "{duration, select, once {Code applied. You pay {discount} less for the first month, then the plan’s usual price each month.} repeating {Code applied. You pay {discount} less for the first {months, plural, one {month} other {# months}}, then the plan’s usual price each month.} other {Code applied. You pay {discount} less every month.}}",
+ "monthlyOnly": "{code} is for monthly plans: {discount} off {duration, select, once {the first month} repeating {the first {months, plural, one {month} other {# months}}} other {every month}}.",
+ "switchToMonthly": "Switch to Monthly",
+ "invalid": "“{code}” isn’t a valid code.",
+ "failed": "Couldn't check the code. Try again."
+ }
+ }
},
"common": {
"loading": "Loading...",
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index 19b3ac55f..f12308da9 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -115,7 +115,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
subscriptionStatus={subscriptionStatus}
>
<RoleProvider role={role}>
- <UpgradeDialogProvider adminName={adminName}>
+ <UpgradeDialogProvider adminName={adminName} organizationId={profile.organization_id}>
<MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>
<AiUsageProvider>
<div className="flex h-screen overflow-hidden">
diff --git a/web/src/app/api/stripe/checkout/route.test.ts b/web/src/app/api/stripe/checkout/route.test.ts
index e492c020f..f06512a85 100644
--- a/web/src/app/api/stripe/checkout/route.test.ts
+++ b/web/src/app/api/stripe/checkout/route.test.ts
@@ -29,12 +29,14 @@ vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: vi.fn() } }));
const stripeApi = vi.hoisted(() => ({
createSession: vi.fn(),
listSubscriptions: vi.fn(),
+ listCodes: vi.fn(),
annual: true,
}));
vi.mock('@/lib/stripe', () => ({
stripe: {
checkout: { sessions: { create: stripeApi.createSession } },
subscriptions: { list: stripeApi.listSubscriptions },
+ promotionCodes: { list: stripeApi.listCodes },
customers: { create: vi.fn() },
},
PRICE_IDS: {},
@@ -68,8 +70,31 @@ beforeEach(() => {
stripeApi.createSession.mockResolvedValue({ url: 'https://checkout.stripe.com/c/1' });
// A customer who had a subscription before: no second trial.
stripeApi.listSubscriptions.mockResolvedValue({ data: [{ id: 'sub_old' }] });
+ stripeApi.listCodes.mockResolvedValue({ data: [save50] });
});
+/** SAVE50 as Stripe lists it: 50% off the first invoice. */
+const save50 = {
+ id: 'promo_save50',
+ code: 'SAVE50',
+ active: true,
+ customer: null,
+ expires_at: null,
+ max_redemptions: null,
+ times_redeemed: 0,
+ promotion: {
+ type: 'coupon',
+ coupon: {
+ valid: true,
+ percent_off: 50,
+ amount_off: null,
+ currency: null,
+ duration: 'once',
+ duration_in_months: null,
+ },
+ },
+};
+
describe('POST /api/stripe/checkout', () => {
it("bills monthly and returns to onboarding's plan step by default", async () => {
const res = await post({ planId: 'starter', organizationId: 'org1' });
@@ -147,6 +172,70 @@ describe('POST /api/stripe/checkout', () => {
expect(stripeApi.createSession).not.toHaveBeenCalled();
});
+ it("leaves a code to Stripe's own box when none was applied", async () => {
+ await post({ planId: 'starter', organizationId: 'org1', returnTo: 'billing' });
+ expect(session().allow_promotion_codes).toBe(true);
+ expect(session().discounts).toBeUndefined();
+ expect(stripeApi.listCodes).not.toHaveBeenCalled();
+ });
+
+ it('opens Checkout with a code it checked with Stripe again, on a monthly plan', async () => {
+ const res = await post({
+ planId: 'growth',
+ organizationId: 'org1',
+ interval: 'month',
+ returnTo: 'billing',
+ promotionCode: 'save50',
+ });
+ expect(res.status).toBe(200);
+ expect(stripeApi.listCodes).toHaveBeenCalledWith(
+ expect.objectContaining({ code: 'save50', active: true, limit: 1 }),
+ );
+ expect(session().discounts).toEqual([{ promotion_code: 'promo_save50' }]);
+ // Stripe refuses a code applied and its own code box together.
+ expect(session().allow_promotion_codes).toBeUndefined();
+ expect(session().line_items).toEqual([{ price: 'price_growth_month', quantity: 1 }]);
+ });
+
+ it('refuses a code Stripe does not take, before opening anything', async () => {
+ stripeApi.listCodes.mockResolvedValue({ data: [] });
+ const res = await post({ planId: 'starter', organizationId: 'org1', promotionCode: 'NOPE' });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({
+ error: "That promo code isn't valid",
+ code: 'invalid_promo_code',
+ });
+ expect(stripeApi.createSession).not.toHaveBeenCalled();
+ });
+
+ it('refuses a code kept for another customer', async () => {
+ stripeApi.listCodes.mockResolvedValue({ data: [{ ...save50, customer: 'cus_other' }] });
+ const res = await post({ planId: 'starter', organizationId: 'org1', promotionCode: 'SAVE50' });
+ expect(res.status).toBe(400);
+ expect(stripeApi.createSession).not.toHaveBeenCalled();
+ });
+
+ it('keeps a code to monthly plans: a year has its own discount', async () => {
+ const res = await post({
+ planId: 'starter',
+ organizationId: 'org1',
+ interval: 'year',
+ promotionCode: 'SAVE50',
+ });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toMatchObject({ code: 'promo_code_monthly_only' });
+ expect(stripeApi.listCodes).not.toHaveBeenCalled();
+ expect(stripeApi.createSession).not.toHaveBeenCalled();
+ });
+
+ it('refuses a code that is not a string, or too long', async () => {
+ for (const promotionCode of [50, '', 'X'.repeat(65)]) {
+ const res = await post({ planId: 'starter', organizationId: 'org1', promotionCode });
+ expect(res.status).toBe(400);
+ }
+ expect(stripeApi.createSession).not.toHaveBeenCalled();
+ });
+
it('refuses a year when its price is not set up', async () => {
stripeApi.annual = false;
const res = await post({ planId: 'growth', organizationId: 'org1', interval: 'year' });
diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.ts
index 82d0c305b..debc43f59 100644
--- a/web/src/app/api/stripe/checkout/route.ts
+++ b/web/src/app/api/stripe/checkout/route.ts
@@ -4,7 +4,8 @@ import { createClient } from '@/lib/supabase/server';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { stripe, PRICE_IDS, priceIdFor } from '@/lib/stripe';
import { TRIAL_DAYS, hasUsedTrial } from '@/lib/billing/trial';
-import { subscriptionEnded } from '@/lib/billing/plan-purchase';
+import { subscriptionEnded, takesPromoCode } from '@/lib/billing/plan-purchase';
+import { findPromotionCode } from '@/lib/billing/promo-code';
/** POST /api/stripe/checkout's body. */
const checkoutSchema = z.object({
@@ -14,6 +15,11 @@ const checkoutSchema = z.object({
interval: z.enum(['month', 'year']).optional(),
/** Where a canceled checkout goes back to: Billing, or onboarding's plan step. */
returnTo: z.literal('billing').optional(),
+ /**
+ * A promotion code the plan dialog checked, for a monthly plan: Checkout
+ * opens with it applied. Checked again here; the caller's word isn't taken.
+ */
+ promotionCode: z.string().trim().min(1).max(64).optional(),
});
export async function POST(req: NextRequest) {
@@ -31,7 +37,7 @@ export async function POST(req: NextRequest) {
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
- const { planId, organizationId, interval, returnTo } = parsed.data;
+ const { planId, organizationId, interval, returnTo, promotionCode } = parsed.data;
// The org id arrives in the request body, so confirm the caller is
// actually in it. Row-level security used to be the only thing standing
@@ -88,6 +94,26 @@ export async function POST(req: NextRequest) {
let customerId = org?.stripe_customer_id as string | null;
+ // A code goes with a monthly plan only (a year has its own discount), and
+ // must be one Stripe can redeem now: looked up here, not taken on trust.
+ let promotionCodeId: string | null = null;
+ if (promotionCode) {
+ if (!takesPromoCode(interval ?? 'month')) {
+ return NextResponse.json(
+ { error: 'Promo codes are for monthly plans', code: 'promo_code_monthly_only' },
+ { status: 400 },
+ );
+ }
+ const found = await findPromotionCode(stripe, promotionCode, customerId);
+ if (!found) {
+ return NextResponse.json(
+ { error: "That promo code isn't valid", code: 'invalid_promo_code' },
+ { status: 400 },
+ );
+ }
+ promotionCodeId = found.id;
+ }
+
// Create Stripe customer if none exists
if (!customerId) {
const customer = await stripe.customers.create({
@@ -122,7 +148,10 @@ export async function POST(req: NextRequest) {
},
success_url: `${appUrl}/api/stripe/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${appUrl}${returnTo === 'billing' ? '/dashboard/settings/billing' : '/dashboard/onboarding'}`,
- allow_promotion_codes: true,
+ // Stripe takes either a code applied here or its own code box, not both.
+ ...(promotionCodeId
+ ? { discounts: [{ promotion_code: promotionCodeId }] }
+ : { allow_promotion_codes: true }),
// Collect billing address + VAT/tax ID up front so invoices are
// complete; later edits happen in the Customer Portal (/api/stripe/portal).
billing_address_collection: 'required',
diff --git a/web/src/app/api/stripe/promo-code/route.test.ts b/web/src/app/api/stripe/promo-code/route.test.ts
new file mode 100644
index 000000000..38039d383
--- /dev/null
+++ b/web/src/app/api/stripe/promo-code/route.test.ts
@@ -0,0 +1,114 @@
+import type { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * POST /api/stripe/promo-code: whether a code typed in the plan dialog can be
+ * redeemed, read from Stripe, and what it takes off. Admins only.
+ */
+
+let role: string;
+let user: { id: string } | null;
+
+/** 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 } }) },
+ from: (table: string) =>
+ row(
+ table === 'profiles' ? { organization_id: 'org1', role } : { stripe_customer_id: 'cus_1' },
+ ),
+ }),
+}));
+
+const listCodes = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/stripe', () => ({ stripe: { promotionCodes: { list: listCodes } } }));
+
+const { POST } = await import('./route');
+
+const post = (body: unknown) =>
+ POST(
+ new Request('http://localhost/api/stripe/promo-code', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }) as unknown as NextRequest,
+ );
+
+/** SAVE50 as Stripe lists it: 50% off the first invoice. */
+const save50 = {
+ id: 'promo_save50',
+ code: 'SAVE50',
+ active: true,
+ customer: null,
+ expires_at: null,
+ max_redemptions: null,
+ times_redeemed: 3,
+ promotion: {
+ type: 'coupon',
+ coupon: {
+ valid: true,
+ percent_off: 50,
+ amount_off: null,
+ currency: null,
+ duration: 'once',
+ duration_in_months: null,
+ },
+ },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ role = 'admin';
+ user = { id: 'u1' };
+ listCodes.mockResolvedValue({ data: [save50] });
+});
+
+describe('POST /api/stripe/promo-code', () => {
+ it('reads a valid code from Stripe: 50% off the first month, monthly plans only', async () => {
+ const res = await post({ code: 'save50' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ valid: true,
+ code: 'SAVE50',
+ percentOff: 50,
+ amountOff: null,
+ duration: 'once',
+ durationInMonths: null,
+ monthlyOnly: true,
+ });
+ expect(listCodes).toHaveBeenCalledWith(
+ expect.objectContaining({ code: 'save50', active: true, limit: 1 }),
+ );
+ });
+
+ it('answers not valid for a code Stripe does not have', async () => {
+ listCodes.mockResolvedValue({ data: [] });
+ const res = await post({ code: 'NOPE' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ valid: false });
+ });
+
+ it('answers not valid for a code kept for another customer', async () => {
+ listCodes.mockResolvedValue({ data: [{ ...save50, customer: 'cus_other' }] });
+ expect(await (await post({ code: 'SAVE50' })).json()).toEqual({ valid: false });
+ });
+
+ it('leaves codes to admins, as buying a plan is', async () => {
+ role = 'analyst';
+ const res = await post({ code: 'SAVE50' });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'admin_only' });
+ expect(listCodes).not.toHaveBeenCalled();
+ });
+
+ it('asks for a signed-in caller and a code', async () => {
+ expect((await post({})).status).toBe(400);
+ user = null;
+ expect((await post({ code: 'SAVE50' })).status).toBe(401);
+ expect(listCodes).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/api/stripe/promo-code/route.ts b/web/src/app/api/stripe/promo-code/route.ts
new file mode 100644
index 000000000..a3258936c
--- /dev/null
+++ b/web/src/app/api/stripe/promo-code/route.ts
@@ -0,0 +1,68 @@
+import { NextRequest, NextResponse } from 'next/server';
+import { z } from 'zod';
+import { createClient } from '@/lib/supabase/server';
+import { stripe } from '@/lib/stripe';
+import { takesPromoCode } from '@/lib/billing/plan-purchase';
+import { findPromotionCode } from '@/lib/billing/promo-code';
+
+/** POST /api/stripe/promo-code's body. */
+const promoCodeRequestSchema = z.object({ code: z.string().max(200) });
+
+/**
+ * POST /api/stripe/promo-code
+ * Whether a promotion code typed in the plan dialog can be redeemed, and what
+ * it takes off, read from Stripe: `{ valid: false }`, or the offer with
+ * `monthlyOnly` (a code goes with a monthly plan only). Checkout checks the
+ * code again; this only shows the price. Admins only, as buying a plan is.
+ */
+export async function POST(req: NextRequest) {
+ try {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+
+ const parsed = promoCodeRequestSchema.safeParse(await req.json().catch(() => null));
+ if (!parsed.success) {
+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ }
+
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select('organization_id, role')
+ .eq('id', user.id)
+ .single();
+ if (!profile?.organization_id) {
+ return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
+ }
+ if (profile.role !== 'admin') {
+ return NextResponse.json(
+ { error: 'Only admins can change the plan', code: 'admin_only' },
+ { status: 403 },
+ );
+ }
+
+ // A code kept for one customer is only that customer's.
+ const { data: org } = await supabase
+ .from('organizations')
+ .select('stripe_customer_id')
+ .eq('id', profile.organization_id)
+ .single();
+
+ const found = await findPromotionCode(
+ stripe,
+ parsed.data.code,
+ (org?.stripe_customer_id as string | null) ?? null,
+ );
+ if (!found) return NextResponse.json({ valid: false });
+ return NextResponse.json({
+ valid: true,
+ ...found.offer,
+ monthlyOnly: !takesPromoCode('year'),
+ });
+ } catch (err) {
+ console.error('[stripe/promo-code]', err);
+ return NextResponse.json({ error: 'Internal error' }, { status: 500 });
+ }
+}
diff --git a/web/src/components/billing/choose-plan-dialog.test.tsx b/web/src/components/billing/choose-plan-dialog.test.tsx
new file mode 100644
index 000000000..c7edb6278
--- /dev/null
+++ b/web/src/components/billing/choose-plan-dialog.test.tsx
@@ -0,0 +1,308 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { toast } from 'sonner';
+import messages from '../../../messages/en.json';
+import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
+import { ChoosePlanDialog } from './choose-plan-dialog';
+
+/**
+ * "Choose a plan to keep going" with the plans: Billing's features and
+ * prices, monthly or a year up front, a promotion code checked with Stripe
+ * (monthly only), and Checkout from a card. Members see the plans without
+ * buying.
+ */
+
+vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+const fetchMock = vi.fn();
+
+/** SAVE50 as the promo route reads it from Stripe. */
+const save50 = {
+ valid: true,
+ code: 'SAVE50',
+ percentOff: 50,
+ amountOff: null,
+ duration: 'once',
+ durationInMonths: null,
+ monthlyOnly: true,
+};
+
+async function render({
+ role = 'admin',
+ action = 'Adding prompts needs a plan',
+}: { role?: TeamRole; action?: string | null } = {}) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <RoleProvider role={role}>
+ <ChoosePlanDialog
+ open
+ onOpenChange={() => {}}
+ action={action}
+ askAdmin="Ask your admin to choose a plan."
+ organizationId="org1"
+ />
+ </RoleProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]')!;
+const card = (plan: string) => dialog().querySelector<HTMLElement>(`[data-plan="${plan}"]`)!;
+const price = (plan: string) =>
+ card(plan).querySelector('[data-slot="plan-price"]')!.textContent?.replace(/\s+/g, ' ').trim();
+const button = (label: string) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);
+const codeInput = () => document.querySelector<HTMLInputElement>('#upgrade-promo-code');
+const note = () => document.querySelector('#upgrade-promo-note')!.textContent;
+
+async function click(label: string) {
+ await act(async () => {
+ button(label)!.click();
+ });
+}
+
+/** Types a code and presses Apply. */
+async function apply(code: string) {
+ const input = codeInput()!;
+ await act(async () => {
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setValue.call(input, code);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await click('Apply');
+}
+
+/** The promo route answers with this; Checkout with a URL. */
+function answer(promo: unknown) {
+ fetchMock.mockImplementation(async (url: string) =>
+ url === '/api/stripe/promo-code' ? Response.json(promo) : Response.json({ url: '#checkout' }),
+ );
+}
+
+/** The body the dialog sent to a route. */
+const sent = (url: string) =>
+ JSON.parse(fetchMock.mock.calls.find(([u]) => u === url)![1].body as string);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ answer(save50);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe('ChoosePlanDialog', () => {
+ it('shows what was clicked, the title and the read-only word', async () => {
+ await render();
+ expect(dialog().querySelector('[data-slot="upgrade-action"]')?.textContent).toBe(
+ 'Adding prompts needs a plan',
+ );
+ expect(dialog().textContent).toContain('Choose a plan to keep going');
+ expect(dialog().textContent).toContain(
+ "Your workspace has no active plan, so it's read-only. Everything you set up is still here",
+ );
+ });
+
+ it('says the workspace is read-only when opened from the banner', async () => {
+ await render({ action: null });
+ expect(dialog().querySelector('[data-slot="upgrade-action"]')?.textContent).toBe(
+ 'Your workspace is read-only',
+ );
+ });
+
+ it("lists Billing's plans with their monthly prices, Growth as Popular, and Custom", async () => {
+ await render();
+ expect(price('starter')).toBe('$49/mo');
+ expect(price('growth')).toBe('$249/mo');
+ expect(card('growth').textContent).toContain('Popular');
+ expect(card('starter').textContent).toContain('ChatGPT & Microsoft Copilot tracking');
+ expect(card('starter').textContent).toContain('1x AI usage');
+ expect(card('growth').textContent).toContain('5x AI usage');
+ expect(card('growth').textContent).toContain('White-label reports & Looker Studio');
+ expect(button('Choose Starter')).toBeDefined();
+ expect(button('Choose Growth')).toBeDefined();
+ expect(card('starter').textContent).toContain("You'll pay by card on Stripe's checkout.");
+
+ const custom = card('custom').textContent;
+ expect(custom).toContain('Starting at$499/mo');
+ expect(custom).toContain('Contact us');
+ expect(custom).toContain('Custom AI usage, from 10x');
+ expect(custom).toContain('SSO / SAML and custom feature requests');
+ expect(card('custom').querySelector('a')?.getAttribute('href')).toBe(
+ 'https://www.ansvisor.com/contact-us',
+ );
+
+ expect(dialog().textContent).toContain('Prices in USD.');
+ const pricing = [...dialog().querySelectorAll('a')].find((a) =>
+ a.textContent?.includes('See everything each plan includes'),
+ );
+ expect(pricing?.getAttribute('href')).toBe('https://www.ansvisor.com/pricing');
+ });
+
+ it('shows a year up front against twelve months, and its monthly share', async () => {
+ await render();
+ await click('AnnualSave 20%');
+ expect(button('AnnualSave 20%')?.getAttribute('aria-pressed')).toBe('true');
+ expect(button('Monthly')?.getAttribute('aria-pressed')).toBe('false');
+ expect(price('starter')).toBe('Regular price $588$470/yr$39.17 a month, billed yearly');
+ expect(price('growth')).toBe('Regular price $2,988$2,390/yr$199.17 a month, billed yearly');
+ });
+
+ it('applies a code Stripe takes: first month off on the cards and the buttons', async () => {
+ await render();
+ await apply('save50');
+ expect(sent('/api/stripe/promo-code')).toEqual({ code: 'save50' });
+ expect(dialog().querySelector('[data-slot="promo-applied"]')?.textContent).toBe(
+ 'SAVE50 · 50% off your first month',
+ );
+ expect(codeInput()).toBeNull();
+ expect(price('starter')).toBe(
+ 'SAVE50: first month 50% offRegular price $49$24.50first monththen $49/mo',
+ );
+ expect(price('growth')).toContain('$124.50first month');
+ expect(button('Choose Growth · $124.50 today')).toBeDefined();
+ expect(button('Choose Starter · $24.50 today')).toBeDefined();
+ expect(note()).toContain('Code applied. You pay 50% less for the first month');
+ });
+
+ it('says when a code is not valid, by the field', async () => {
+ answer({ valid: false });
+ await render();
+ await apply('nope10');
+ expect(note()).toBe('“NOPE10” isn’t a valid code.');
+ expect(codeInput()?.getAttribute('aria-invalid')).toBe('true');
+ expect(codeInput()?.getAttribute('aria-describedby')).toBe('upgrade-promo-note');
+ expect(document.querySelector('#upgrade-promo-note')?.getAttribute('aria-live')).toBe('polite');
+ expect(price('starter')).toBe('$49/mo');
+ expect(button('Choose Starter')).toBeDefined();
+ });
+
+ it('says when the code could not be checked', async () => {
+ fetchMock.mockResolvedValue(Response.json({ error: 'Internal error' }, { status: 500 }));
+ await render();
+ await apply('SAVE50');
+ expect(note()).toBe("Couldn't check the code. Try again.");
+ });
+
+ it('keeps a code to monthly plans, with a way back to Monthly', async () => {
+ await render();
+ await apply('SAVE50');
+ await click('AnnualSave 20%');
+ expect(note()).toBe('SAVE50 is for monthly plans: 50% off the first month.Switch to Monthly');
+ expect(price('starter')).toBe('Regular price $588$470/yr$39.17 a month, billed yearly');
+ expect(button('Choose Starter')).toBeDefined();
+
+ await click('Switch to Monthly');
+ expect(button('Monthly')?.getAttribute('aria-pressed')).toBe('true');
+ expect(button('Choose Starter · $24.50 today')).toBeDefined();
+ });
+
+ it('takes the code off with ×', async () => {
+ await render();
+ await apply('SAVE50');
+ await act(async () => {
+ document.querySelector<HTMLButtonElement>('[aria-label="Remove the code"]')!.click();
+ });
+ expect(codeInput()?.value).toBe('');
+ expect(price('growth')).toBe('$249/mo');
+ expect(button('Choose Growth')).toBeDefined();
+ });
+
+ it('opens Checkout for the plan and period, with the code on a monthly plan', async () => {
+ await render();
+ await apply('SAVE50');
+ await click('Choose Growth · $124.50 today');
+ expect(sent('/api/stripe/checkout')).toEqual({
+ planId: 'growth',
+ organizationId: 'org1',
+ interval: 'month',
+ returnTo: 'billing',
+ promotionCode: 'SAVE50',
+ });
+ await vi.waitFor(() => expect(window.location.hash).toBe('#checkout'));
+ });
+
+ it('opens Checkout for a year without the code', async () => {
+ await render();
+ await apply('SAVE50');
+ await click('AnnualSave 20%');
+ await click('Choose Starter');
+ expect(sent('/api/stripe/checkout')).toEqual({
+ planId: 'starter',
+ organizationId: 'org1',
+ interval: 'year',
+ returnTo: 'billing',
+ });
+ });
+
+ it('opens Checkout without a code when none was applied', async () => {
+ await render();
+ await click('Choose Starter');
+ expect(sent('/api/stripe/checkout')).toEqual({
+ planId: 'starter',
+ organizationId: 'org1',
+ interval: 'month',
+ returnTo: 'billing',
+ });
+ });
+
+ it('takes back a code Checkout refused, and says so', async () => {
+ await render();
+ await apply('SAVE50');
+ fetchMock.mockResolvedValue(
+ Response.json(
+ { error: "That promo code isn't valid", code: 'invalid_promo_code' },
+ { status: 400 },
+ ),
+ );
+ await click('Choose Starter · $24.50 today');
+ expect(note()).toBe('“SAVE50” isn’t a valid code.');
+ expect(button('Choose Starter')).toBeDefined();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('reports a Checkout that would not open', async () => {
+ fetchMock.mockResolvedValue(Response.json({ error: 'Stripe is down' }, { status: 500 }));
+ await render();
+ await click('Choose Starter');
+ expect(toast.error).toHaveBeenCalledWith('Stripe is down');
+ expect(button('Choose Starter')?.disabled).toBe(false);
+ });
+
+ it('shows another member the plans without buying, a code or a discount', async () => {
+ await render({ role: 'manager' });
+ expect(dialog().querySelector('[data-slot="member-note"]')?.textContent).toBe(
+ 'Only an admin can choose a plan for your workspace. Ask your admin to choose a plan.',
+ );
+ expect(button('Choose Starter')).toBeUndefined();
+ expect(button('Choose Growth')).toBeUndefined();
+ expect(dialog().textContent).not.toContain("You'll pay by card");
+ expect(dialog().querySelectorAll('[data-slot="ask-admin"]')).toHaveLength(2);
+ expect(card('starter').textContent).toContain('Ask your admin to choose a plan');
+ expect(codeInput()).toBeNull();
+ expect(document.querySelector('#upgrade-promo-note')).toBeNull();
+ expect(price('starter')).toBe('$49/mo');
+ expect(card('custom').textContent).toContain('Contact us');
+
+ // The period still switches, to see the prices.
+ await click('AnnualSave 20%');
+ expect(price('growth')).toContain('$2,390/yr');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/billing/choose-plan-dialog.tsx b/web/src/components/billing/choose-plan-dialog.tsx
new file mode 100644
index 000000000..23a2a42e6
--- /dev/null
+++ b/web/src/components/billing/choose-plan-dialog.tsx
@@ -0,0 +1,526 @@
+'use client';
+
+import { useRef, useState, type FormEvent } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { ArrowUpRight, Check, CreditCard, Loader2, Lock, Mail, Tag, X } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { aiUsageMultiple, usePlanFeatures } from '@/components/settings/plan-features';
+import {
+ CONTACT_SALES_URL,
+ CUSTOM_PLAN_STARTING_PRICE,
+ PLANS,
+ PRICING_URL,
+ SUBSCRIBABLE_PLANS,
+ type PlanId,
+} from '@/config/plans';
+import { useUserRole } from '@/hooks/use-user-role';
+import {
+ FIRST_MONTH_CODE,
+ annualSaving,
+ periodPrice,
+ takesPromoCode,
+ type BillingInterval,
+} from '@/lib/billing/plan-purchase';
+import { discountedPrice, type PromoOffer } from '@/lib/billing/promo-code';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+
+/** Dollars as the cards show them: whole dollars bare, anything else to the cent. */
+function money(value: number): string {
+ return `$${
+ Number.isInteger(value)
+ ? formatNumber(value)
+ : value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
+ }`;
+}
+
+/** What a code takes off, for its texts: "50%" or "$10". */
+function discountOf(offer: PromoOffer): string {
+ return offer.percentOff != null ? `${offer.percentOff}%` : money(offer.amountOff ?? 0);
+}
+
+/** The values every promo text reads. */
+function offerValues(offer: PromoOffer) {
+ return {
+ code: offer.code,
+ discount: discountOf(offer),
+ duration: offer.duration,
+ months: offer.durationInMonths ?? 1,
+ };
+}
+
+type CodeError = { kind: 'invalid'; code: string } | { kind: 'failed' };
+
+const PROMO_INPUT_ID = 'upgrade-promo-code';
+const PROMO_NOTE_ID = 'upgrade-promo-note';
+
+/**
+ * "Choose a plan to keep going", for a workspace whose plan ended: Starter
+ * and Growth with Billing's own features and prices, monthly or a year up
+ * front, and Custom through sales. An admin can apply a promotion code
+ * (checked with Stripe, monthly plans only) and opens Stripe Checkout for a
+ * new subscription from a card; another member is asked to turn to an admin
+ * and sees the plain prices. ×, Escape or a click outside close it.
+ */
+export function ChoosePlanDialog({
+ open,
+ onOpenChange,
+ action,
+ askAdmin,
+ organizationId,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** What was clicked ("Adding prompts needs a plan"); none from the banner. */
+ action: string | null;
+ /** What a member who isn't an admin is asked to do. */
+ askAdmin: string;
+ /** The organization the new subscription is for. */
+ organizationId: string | null;
+}) {
+ const t = useTranslations('readOnly');
+ const tPlans = useTranslations('readOnly.plans');
+ const tSettings = useTranslations('settings');
+ const tCards = useTranslations('settings.planCards');
+ const planFeatures = usePlanFeatures();
+ const { canAdmin } = useUserRole();
+
+ const [period, setPeriod] = useState<BillingInterval>('month');
+ const [codeInput, setCodeInput] = useState('');
+ const [checking, setChecking] = useState(false);
+ const [codeError, setCodeError] = useState<CodeError | null>(null);
+ // The code Stripe took, with what it takes off. Only an admin enters one.
+ const [offer, setOffer] = useState<PromoOffer | null>(null);
+ // The plan whose Checkout is opening.
+ const [checkoutPlan, setCheckoutPlan] = useState<PlanId | null>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const saving = Math.max(0, ...SUBSCRIBABLE_PLANS.map((id) => annualSaving(id) ?? 0));
+ // The code lowers this period's prices: a monthly plan, for an admin.
+ const discounted = canAdmin && offer != null && takesPromoCode(period) ? offer : null;
+
+ async function applyCode(event: FormEvent) {
+ event.preventDefault();
+ const typed = codeInput.trim();
+ if (!typed) {
+ inputRef.current?.focus();
+ return;
+ }
+ setChecking(true);
+ setCodeError(null);
+ try {
+ const res = await fetch('/api/stripe/promo-code', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ code: typed }),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok || !data) throw new Error('promo check failed');
+ if (data.valid) {
+ setOffer({
+ code: data.code,
+ percentOff: data.percentOff ?? null,
+ amountOff: data.amountOff ?? null,
+ duration: data.duration,
+ durationInMonths: data.durationInMonths ?? null,
+ });
+ } else {
+ setCodeError({ kind: 'invalid', code: typed.toUpperCase() });
+ }
+ } catch {
+ setCodeError({ kind: 'failed' });
+ } finally {
+ setChecking(false);
+ }
+ }
+
+ function removeCode() {
+ setOffer(null);
+ setCodeInput('');
+ // The field is back once the chip is gone.
+ setTimeout(() => inputRef.current?.focus(), 0);
+ }
+
+ async function choose(planId: PlanId) {
+ if (!organizationId || checkoutPlan) return;
+ setCheckoutPlan(planId);
+ const promotionCode = discounted?.code;
+ try {
+ const res = await fetch('/api/stripe/checkout', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ planId,
+ organizationId,
+ interval: period,
+ returnTo: 'billing',
+ ...(promotionCode ? { promotionCode } : {}),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.url) {
+ // The code stopped working since it was applied: say so by the field.
+ if (data.code === 'invalid_promo_code' && promotionCode) {
+ setOffer(null);
+ setCodeInput(promotionCode);
+ setCodeError({ kind: 'invalid', code: promotionCode.toUpperCase() });
+ setCheckoutPlan(null);
+ return;
+ }
+ throw new Error(data.error || tSettings('checkoutFailed'));
+ }
+ window.location.href = data.url;
+ // No reset: the page is leaving for Stripe.
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : tSettings('checkoutFailed'));
+ setCheckoutPlan(null);
+ }
+ }
+
+ // The line under the controls: the code's word for this period, or why
+ // the code typed was refused.
+ const note =
+ offer && !takesPromoCode(period) ? (
+ <p className="flex flex-wrap items-center gap-x-1.5 text-amber-700 dark:text-amber-400">
+ {tPlans('promo.monthlyOnly', offerValues(offer))}
+ <button
+ type="button"
+ onClick={() => setPeriod('month')}
+ className="rounded-sm text-foreground underline underline-offset-2 outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ >
+ {tPlans('promo.switchToMonthly')}
+ </button>
+ </p>
+ ) : offer ? (
+ <p className="text-emerald-700 dark:text-emerald-400">
+ {tPlans('promo.appliedNote', offerValues(offer))}
+ </p>
+ ) : codeError ? (
+ <p className="text-destructive">
+ {codeError.kind === 'invalid'
+ ? tPlans('promo.invalid', { code: codeError.code })
+ : tPlans('promo.failed')}
+ </p>
+ ) : null;
+
+ const aiMultiple = aiUsageMultiple('enterprise');
+ const customPoints = tSettings.raw('customPlanPoints') as string[];
+ // Custom's list as the pricing page has it: its AI usage after the data points.
+ const customFeatures = aiMultiple
+ ? [
+ ...customPoints.slice(0, 4),
+ tPlans('customAiUsage', { count: aiMultiple }),
+ ...customPoints.slice(4),
+ ]
+ : customPoints;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto p-5 sm:max-w-[min(62.5rem,calc(100%-2rem))] sm:p-7">
+ <DialogHeader className="gap-1 pr-8">
+ <span
+ data-slot="upgrade-action"
+ className="mb-2 inline-flex w-fit items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs text-muted-foreground"
+ >
+ <Lock className="size-3" aria-hidden />
+ {action ?? t('dialog.readOnlyLabel')}
+ </span>
+ <DialogTitle className="text-xl leading-tight font-bold tracking-tight">
+ {t('dialog.title.ended')}
+ </DialogTitle>
+ <DialogDescription className="max-w-2xl">{t('dialog.body.ended')}</DialogDescription>
+ </DialogHeader>
+
+ {!canAdmin && (
+ <p
+ data-slot="member-note"
+ className="mt-4 flex items-start gap-2 rounded-lg border bg-muted/30 px-3.5 py-2.5 text-sm"
+ >
+ <Lock className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <span>
+ {t('dialog.memberNote')} {askAdmin}
+ </span>
+ </p>
+ )}
+
+ <div className="mt-5 flex flex-wrap items-center justify-between gap-3">
+ {/* Billing period: a year up front saves 20% */}
+ <div
+ role="group"
+ aria-label={tSettings('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 outline-none focus-visible:ring-3 focus-visible:ring-ring/50',
+ period === value
+ ? 'bg-background text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {value === 'month' ? tSettings('monthly') : tSettings('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">
+ {tSettings('savePercent', { percent: saving })}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+
+ {canAdmin &&
+ (offer ? (
+ <span
+ data-slot="promo-applied"
+ className="inline-flex h-8 items-center gap-1.5 rounded-full border border-emerald-200 bg-emerald-50 pr-1 pl-2.5 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-400"
+ >
+ <Tag className="size-3.5" aria-hidden />
+ {tPlans('promo.applied', offerValues(offer))}
+ <button
+ type="button"
+ aria-label={tPlans('promo.remove')}
+ onClick={removeCode}
+ className="grid size-6 place-items-center rounded-full outline-none hover:bg-emerald-100 focus-visible:ring-3 focus-visible:ring-ring/50 dark:hover:bg-emerald-900/40"
+ >
+ <X className="size-3" aria-hidden />
+ </button>
+ </span>
+ ) : (
+ <form onSubmit={applyCode} autoComplete="off" className="flex items-center gap-2">
+ <label htmlFor={PROMO_INPUT_ID} className="text-xs text-muted-foreground">
+ {tSettings('promoCode')}
+ </label>
+ <Input
+ ref={inputRef}
+ id={PROMO_INPUT_ID}
+ value={codeInput}
+ onChange={(e) => {
+ setCodeInput(e.target.value);
+ if (codeError) setCodeError(null);
+ }}
+ placeholder={FIRST_MONTH_CODE}
+ spellCheck={false}
+ aria-invalid={codeError?.kind === 'invalid' || undefined}
+ aria-describedby={PROMO_NOTE_ID}
+ className="w-32 uppercase"
+ />
+ <Button type="submit" variant="outline" disabled={checking}>
+ {checking ? tPlans('promo.checking') : tPlans('promo.apply')}
+ </Button>
+ </form>
+ ))}
+ </div>
+ {/* Always there, so a screen reader hears what the code did. */}
+ {canAdmin && (
+ <div id={PROMO_NOTE_ID} role="status" aria-live="polite" className="text-xs">
+ {note && <div className="mt-2">{note}</div>}
+ </div>
+ )}
+
+ <div className="mt-5 grid grid-cols-1 gap-4 lg:grid-cols-3">
+ {SUBSCRIBABLE_PLANS.map((planId) => {
+ const plan = PLANS[planId];
+ const monthly = periodPrice(planId, 'month');
+ const price = periodPrice(planId, period);
+ const firstPrice =
+ discounted && monthly != null ? discountedPrice(monthly, discounted) : null;
+ const opening = checkoutPlan === planId;
+
+ return (
+ <section
+ key={planId}
+ data-plan={planId}
+ aria-labelledby={`upgrade-plan-${planId}`}
+ className={cn(
+ 'relative flex flex-col gap-4 rounded-xl border bg-card p-5',
+ plan.highlighted && 'border-primary ring-1 ring-primary',
+ )}
+ >
+ {plan.highlighted && (
+ <Badge className="absolute -top-2.5 left-5">{tSettings('popular')}</Badge>
+ )}
+ <div>
+ <h3 id={`upgrade-plan-${planId}`} className="text-base font-semibold">
+ {plan.name}
+ </h3>
+ <p className="mt-0.5 text-xs text-muted-foreground lg:min-h-8">
+ {tCards(`${planId}.tagline`)}
+ </p>
+ </div>
+
+ <div
+ data-slot="plan-price"
+ className="flex flex-wrap content-end items-baseline gap-x-1.5 lg:min-h-20"
+ >
+ {period === 'year' && price != null && monthly != null ? (
+ <>
+ <span className="text-sm text-muted-foreground line-through">
+ <span className="sr-only">{tSettings('regularPrice')} </span>
+ {money(monthly * 12)}
+ </span>
+ <span className="text-3xl font-bold tracking-tight">{money(price)}</span>
+ <span className="text-sm text-muted-foreground">/{tSettings('year')}</span>
+ <span className="w-full text-xs text-muted-foreground">
+ {tPlans('perMonthBilledYearly', {
+ price: money(Math.round((price / 12) * 100) / 100),
+ })}
+ </span>
+ </>
+ ) : discounted && firstPrice != null && monthly != null ? (
+ <>
+ <span className="inline-flex w-full items-center gap-1 text-xs font-semibold text-emerald-700 dark:text-emerald-400">
+ <Check className="size-3" aria-hidden />
+ {tPlans('promo.deal', offerValues(discounted))}
+ </span>
+ <span className="text-sm text-muted-foreground line-through">
+ <span className="sr-only">{tSettings('regularPrice')} </span>
+ {money(monthly)}
+ </span>
+ <span className="text-3xl font-bold tracking-tight">{money(firstPrice)}</span>
+ <span className="text-sm text-muted-foreground">
+ {tPlans('promo.per', offerValues(discounted))}
+ </span>
+ {discounted.duration !== 'forever' && (
+ <span className="w-full text-xs text-muted-foreground">
+ {tPlans('promo.then', { price: money(monthly) })}
+ </span>
+ )}
+ </>
+ ) : (
+ <>
+ <span className="text-3xl font-bold tracking-tight">
+ {price != null ? money(price) : '—'}
+ </span>
+ <span className="text-sm text-muted-foreground">/{tSettings('month')}</span>
+ </>
+ )}
+ </div>
+
+ {canAdmin ? (
+ <div className="space-y-2">
+ <Button
+ className="h-9 w-full"
+ variant={plan.highlighted ? 'default' : 'outline'}
+ disabled={price == null || !organizationId || checkoutPlan != null}
+ onClick={() => void choose(planId)}
+ >
+ {opening ? (
+ <>
+ <Loader2 className="animate-spin" aria-hidden />
+ {tPlans('openingCheckout')}
+ </>
+ ) : firstPrice != null ? (
+ tPlans('chooseToday', { plan: plan.name, price: money(firstPrice) })
+ ) : (
+ tSettings('choosePlanFor', { plan: plan.name })
+ )}
+ </Button>
+ <p className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
+ <CreditCard className="size-3.5" aria-hidden />
+ {tPlans('payByCard')}
+ </p>
+ </div>
+ ) : (
+ <p
+ data-slot="ask-admin"
+ className="flex min-h-9 items-center justify-center gap-1.5 rounded-lg border border-dashed px-3 py-1.5 text-center text-xs text-muted-foreground"
+ >
+ <Lock className="size-3.5 shrink-0" aria-hidden />
+ {tPlans('askAdmin')}
+ </p>
+ )}
+
+ <ul className="space-y-1.5 text-sm">
+ {planFeatures(planId).map((feature) => (
+ <li key={feature.text} className="flex items-start gap-2">
+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ <span
+ title={feature.hint}
+ className={
+ feature.hint
+ ? 'cursor-help underline decoration-dotted underline-offset-4'
+ : undefined
+ }
+ >
+ {feature.text}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+ })}
+
+ {/* Custom: priced with sales, from the pricing page's points */}
+ <section
+ data-plan="custom"
+ aria-labelledby="upgrade-plan-custom"
+ className="flex flex-col gap-4 rounded-xl border bg-muted/30 p-5"
+ >
+ <div>
+ <h3 id="upgrade-plan-custom" className="text-base font-semibold">
+ {tPlans('customName')}
+ </h3>
+ <p className="mt-0.5 text-xs text-muted-foreground lg:min-h-8">
+ {tPlans('customTagline')}
+ </p>
+ </div>
+ <div className="flex flex-wrap content-end items-baseline gap-x-1.5 lg:min-h-20">
+ <span className="w-full text-sm text-muted-foreground">{tPlans('startingAt')}</span>
+ <span className="text-3xl font-bold tracking-tight">
+ {money(CUSTOM_PLAN_STARTING_PRICE)}
+ </span>
+ <span className="text-sm text-muted-foreground">/{tSettings('month')}</span>
+ </div>
+ <a
+ href={CONTACT_SALES_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(buttonVariants({ variant: 'outline' }), 'h-9 w-full')}
+ >
+ <Mail aria-hidden />
+ {tPlans('contactUs')}
+ </a>
+ <ul className="space-y-1.5 text-sm">
+ {customFeatures.map((point) => (
+ <li key={point} className="flex items-start gap-2">
+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ <span>{point}</span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ </div>
+
+ <div className="mt-5 flex flex-wrap items-center justify-between gap-3 text-xs text-muted-foreground">
+ <span>{tPlans('pricesInUsd')}</span>
+ <a
+ href={PRICING_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-foreground underline-offset-4 hover:underline"
+ >
+ {tSettings('seeAllPlanFeatures')}
+ <ArrowUpRight className="size-3.5" aria-hidden />
+ </a>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/components/providers/upgrade-dialog-provider.test.tsx b/web/src/components/providers/upgrade-dialog-provider.test.tsx
index 330615ead..43c3384eb 100644
--- a/web/src/components/providers/upgrade-dialog-provider.test.tsx
+++ b/web/src/components/providers/upgrade-dialog-provider.test.tsx
@@ -120,15 +120,17 @@ describe('useUpgradeGate', () => {
expect(dialog()?.textContent).toContain(
"Your workspace has no active plan, so it\'s read-only. Everything you set up is still here: pick a plan to track, write and run your agents again.",
);
- // No label when the button didn't say what it does.
- expect(document.querySelector('[data-slot="upgrade-action"]')).toBeNull();
+ // The workspace's state when the button didn't say what it does.
+ expect(document.querySelector('[data-slot="upgrade-action"]')?.textContent).toBe(
+ 'Your workspace is read-only',
+ );
});
- it('closes with Not now, and opens again on the next action', async () => {
+ it('closes with its ×, and opens again on the next action', async () => {
await render({ active: false });
await runAll();
await act(async () => {
- button('Not now')!.click();
+ button('Close')!.click();
});
await vi.waitFor(() => expect(dialog()).toBeNull());
@@ -146,11 +148,12 @@ describe('useUpgradeGate', () => {
);
});
- it('takes an admin to Billing to choose a plan', async () => {
+ it('offers an admin the plans, to choose one right there', async () => {
await render({ active: false, status: 'canceled' });
await runAll();
- const link = [...document.querySelectorAll('a')].find((a) => a.textContent === 'Choose a plan');
- expect(link?.getAttribute('href')).toBe('/dashboard/settings/billing');
+ expect(button('Choose Starter')).toBeDefined();
+ expect(button('Choose Growth')).toBeDefined();
+ expect(dialog()?.textContent).toContain("You'll pay by card on Stripe's checkout.");
expect(button('Update payment method')).toBeUndefined();
});
@@ -182,9 +185,9 @@ describe('useUpgradeGate', () => {
await runAll();
expect(dialog()?.textContent).toContain('Your workspace has no active plan');
expect(dialog()?.textContent).toContain(
- 'Ask Jane Owner, your workspace admin, to choose a plan.',
+ 'Only an admin can choose a plan for your workspace. Ask Jane Owner, your workspace admin, to choose a plan.',
);
- expect(document.querySelector('a')).toBeNull();
+ expect(button('Choose Starter')).toBeUndefined();
});
it('asks another member to have the admin update the payment method', async () => {
@@ -199,7 +202,9 @@ describe('useUpgradeGate', () => {
it('asks for the workspace admin without a name', async () => {
await render({ active: false, role: 'analyst' });
await runAll();
- expect(dialog()?.textContent).toContain('Ask your workspace admin to choose a plan.');
+ expect(dialog()?.textContent).toContain(
+ 'Only an admin can choose a plan for your workspace. Ask your admin to choose a plan.',
+ );
});
it('never locks self-hosted', async () => {
diff --git a/web/src/components/providers/upgrade-dialog-provider.tsx b/web/src/components/providers/upgrade-dialog-provider.tsx
index 0b997aa88..5fccf21e5 100644
--- a/web/src/components/providers/upgrade-dialog-provider.tsx
+++ b/web/src/components/providers/upgrade-dialog-provider.tsx
@@ -20,6 +20,7 @@ import { usePlanContext } from '@/components/providers/plan-provider';
import { useUserRole } from '@/hooks/use-user-role';
import { readOnlyReason, type ReadOnlyReason } from '@/lib/billing/subscription-access';
import { openBillingPortal } from '@/lib/billing/portal-client';
+import { ChoosePlanDialog } from '@/components/billing/choose-plan-dialog';
import { CHOOSE_PLAN_HREF, UpgradeDialogContext } from './upgrade-gate';
// The context and its hooks live in ./upgrade-gate, free of this file's UI,
@@ -30,15 +31,20 @@ export { CHOOSE_PLAN_HREF, useUpgradeDialog, useUpgradeGate } from './upgrade-ga
* Ansvisor Cloud's read-only mode: a workspace whose trial ended or whose
* plan was canceled can still open every page, but an action (anything that
* writes, runs or spends) opens "Choose a plan to keep going" instead. The dialog
- * closes with Not now or its ×, and opens again on the next action, until a
- * plan is bought. Admins are taken to Billing; other members are asked to
- * turn to an admin. Self-hosted is never locked.
+ * closes with its ×, Escape or a click outside, and opens again on the next
+ * action, until a plan is bought. Admins choose a plan there and pay on
+ * Stripe's Checkout; other members are asked to turn to an admin. A payment
+ * being retried asks for the payment method instead. Self-hosted is never
+ * locked.
*/
export function UpgradeDialogProvider({
adminName = null,
+ organizationId = null,
children,
}: {
adminName?: string | null;
+ /** The workspace's organization, which a plan chosen in the dialog is for. */
+ organizationId?: string | null;
children: ReactNode;
}) {
const { subscriptionActive, subscriptionStatus } = usePlanContext();
@@ -69,6 +75,7 @@ export function UpgradeDialogProvider({
reason={value.reason}
adminName={adminName}
action={action}
+ organizationId={organizationId}
/>
</UpgradeDialogContext.Provider>
);
@@ -128,9 +135,10 @@ export function ReadOnlyAction({
}
/**
- * "Choose a plan to keep going": the workspace is read-only, what was clicked
- * when the caller said, and the one thing to do. Its plan cards come with
- * Billing's Checkout in the dialog later; for now an admin goes to Billing.
+ * The workspace is read-only: once the plan ended, "Choose a plan to keep
+ * going" with the plans (ChoosePlanDialog); while a payment is being
+ * retried, what was clicked when the caller said and the one thing to do,
+ * update the payment method.
*/
function UpgradeDialog({
open,
@@ -138,17 +146,31 @@ function UpgradeDialog({
reason,
adminName,
action,
+ organizationId,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
reason: ReadOnlyReason;
adminName: string | null;
action: string | null;
+ organizationId: string | null;
}) {
const t = useTranslations('readOnly');
const { canAdmin } = useUserRole();
const ask = useAskAdmin(reason, adminName);
+ if (reason === 'ended') {
+ return (
+ <ChoosePlanDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ action={action}
+ askAdmin={ask}
+ organizationId={organizationId}
+ />
+ );
+ }
+
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
diff --git a/web/src/components/settings/plan-features.ts b/web/src/components/settings/plan-features.ts
new file mode 100644
index 000000000..b3fce9331
--- /dev/null
+++ b/web/src/components/settings/plan-features.ts
@@ -0,0 +1,50 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { PLANS, type PlanId } from '@/config/plans';
+
+export interface PlanFeature {
+ text: string;
+ /** A longer word on it, shown on hover. */
+ hint?: string;
+}
+
+/** A plan's monthly AI allowance as a multiple of Starter's; null when either has none. */
+export function aiUsageMultiple(planId: PlanId): number | null {
+ const starterAi = PLANS.starter.limits.improveMonthlyBudgetUsd;
+ const planAi = PLANS[planId].limits.improveMonthlyBudgetUsd;
+ return starterAi > 0 && planAi > 0 ? Math.round(planAi / starterAi) : null;
+}
+
+/**
+ * A plan card's list, as the pricing page puts it: brands, seats, prompts,
+ * the answer engines it tracks, content briefs and site audits a month,
+ * AI usage as a multiple of Starter's, then what the plan adds. Billing's
+ * cards and the plan dialog show the same list.
+ */
+export function usePlanFeatures(): (planId: PlanId) => PlanFeature[] {
+ const tCards = useTranslations('settings.planCards');
+ return (planId) => {
+ const { limits } = PLANS[planId];
+ const aiUsage = aiUsageMultiple(planId);
+ const items = [
+ limits.maxBrands === -1
+ ? tCards('unlimitedBrands')
+ : tCards('brands', { count: limits.maxBrands }),
+ limits.maxTeamMembers === -1
+ ? tCards('unlimitedSeats')
+ : tCards('seats', { count: limits.maxTeamMembers }),
+ tCards('prompts', { count: limits.maxPrompts }),
+ tCards(`${planId}.engines`),
+ tCards('briefs', { count: limits.maxBriefGenerations }),
+ tCards('audits', { count: limits.maxSiteAudits }),
+ ].map((text) => ({ text }));
+ return [
+ ...items,
+ ...(aiUsage
+ ? [{ text: tCards('aiUsage', { count: aiUsage }), hint: tCards('aiUsageHint') }]
+ : []),
+ ...(tCards.raw(`${planId}.extras`) as string[]).map((text) => ({ text })),
+ ];
+ };
+}
diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsx
index aabd9745e..cdf715db1 100644
--- a/web/src/components/settings/plan-switcher.tsx
+++ b/web/src/components/settings/plan-switcher.tsx
@@ -35,6 +35,7 @@ import { useRouter } from '@/i18n/navigation';
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { CancelSubscriptionDialog } from './cancel-subscription-dialog';
+import { aiUsageMultiple, usePlanFeatures, type PlanFeature } from './plan-features';
interface SubscriptionData {
planId: string;
@@ -55,6 +56,7 @@ interface PlanSwitcherProps {
export function PlanSwitcher({ subscription, onUpdate, organizationId = null }: PlanSwitcherProps) {
const t = useTranslations('settings');
const tCards = useTranslations('settings.planCards');
+ const planFeatures = usePlanFeatures();
// Buying or changing the plan charges the organization's card: admins only,
// as the subscription route checks.
const { canAdmin } = useUserRole();
@@ -207,47 +209,12 @@ export function PlanSwitcher({ subscription, onUpdate, organizationId = null }:
}
}
- /** A plan's AI budget as a multiple of Starter's, as the cards say it; none when unlimited. */
- function aiMultiple(budget: number): number | null {
- const starterAi = PLANS.starter.limits.improveMonthlyBudgetUsd;
- return starterAi > 0 && budget > 0 ? Math.round(budget / starterAi) : null;
- }
-
- /**
- * A plan card's list, as the pricing page puts it: brands, seats, prompts,
- * the answer engines it tracks, content briefs and site audits a month,
- * AI usage as a multiple of Starter's, then what the plan adds.
- */
- function planFeatures(planId: PlanId): { text: string; hint?: string }[] {
- const { limits } = PLANS[planId];
- const aiUsage = aiMultiple(limits.improveMonthlyBudgetUsd);
- const items = [
- limits.maxBrands === -1
- ? tCards('unlimitedBrands')
- : tCards('brands', { count: limits.maxBrands }),
- limits.maxTeamMembers === -1
- ? tCards('unlimitedSeats')
- : tCards('seats', { count: limits.maxTeamMembers }),
- tCards('prompts', { count: limits.maxPrompts }),
- tCards(`${planId}.engines`),
- tCards('briefs', { count: limits.maxBriefGenerations }),
- tCards('audits', { count: limits.maxSiteAudits }),
- ].map((text) => ({ text }));
- return [
- ...items,
- ...(aiUsage
- ? [{ text: tCards('aiUsage', { count: aiUsage }), hint: tCards('aiUsageHint') }]
- : []),
- ...(tCards.raw(`${planId}.extras`) as string[]).map((text) => ({ text })),
- ];
- }
-
/**
* The custom plan's points: its AI usage first, set per customer above
* Enterprise's floor (2026-10-27), then the pricing page's points.
*/
- function customPlanPoints(): { text: string; hint?: string }[] {
- const aiUsage = aiMultiple(PLANS.enterprise.limits.improveMonthlyBudgetUsd);
+ function customPlanPoints(): PlanFeature[] {
+ const aiUsage = aiUsageMultiple('enterprise');
return [
...(aiUsage
? [{ text: tCards('aiUsageCustom', { count: aiUsage }), hint: tCards('aiUsageCustomHint') }]
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 01d332faa..997e0d245 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -313,6 +313,9 @@ export const SUBSCRIBABLE_PLANS: PlanId[] = ['starter', 'growth'];
/** Where a plan the app can't sell by itself (Enterprise, add-ons) is asked for. */
export const CONTACT_SALES_URL = 'https://www.ansvisor.com/contact-us';
+/** What a custom (Enterprise) plan starts at a month, in dollars, as the pricing page has it. */
+export const CUSTOM_PLAN_STARTING_PRICE = 499;
+
/** The pricing page: every plan's features side by side. */
export const PRICING_URL = 'https://www.ansvisor.com/pricing';
diff --git a/web/src/lib/billing/plan-purchase.test.ts b/web/src/lib/billing/plan-purchase.test.ts
index ca4f95436..872088394 100644
--- a/web/src/lib/billing/plan-purchase.test.ts
+++ b/web/src/lib/billing/plan-purchase.test.ts
@@ -5,6 +5,7 @@ import {
planChange,
planRequestSchema,
subscriptionEnded,
+ takesPromoCode,
} from './plan-purchase';
describe('plan prices', () => {
@@ -98,3 +99,10 @@ describe('subscriptionEnded', () => {
expect(subscriptionEnded(undefined)).toBe(true);
});
});
+
+describe('takesPromoCode', () => {
+ it('takes a code with a monthly plan only: a year has its own discount', () => {
+ expect(takesPromoCode('month')).toBe(true);
+ expect(takesPromoCode('year')).toBe(false);
+ });
+});
diff --git a/web/src/lib/billing/plan-purchase.ts b/web/src/lib/billing/plan-purchase.ts
index 97c8af989..bf76d4f20 100644
--- a/web/src/lib/billing/plan-purchase.ts
+++ b/web/src/lib/billing/plan-purchase.ts
@@ -11,6 +11,14 @@ export type BillingInterval = 'month' | 'year';
*/
export const FIRST_MONTH_CODE = 'SAVE50';
+/**
+ * Whether a promotion code goes with this billing period: a monthly plan
+ * only, since a year up front has its own discount.
+ */
+export function takesPromoCode(interval: BillingInterval): boolean {
+ return interval === 'month';
+}
+
/** 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;
@@ -65,7 +73,7 @@ export function planChange(
if (current.status !== 'trialing') {
return { kind: 'refused', error: 'Only a free trial can be bought now' };
}
- const promoCode = interval === 'month' ? request.promoCode || null : null;
+ const promoCode = takesPromoCode(interval) ? request.promoCode || null : null;
return { kind: 'buy_now', planId, interval, promoCode };
}
diff --git a/web/src/lib/billing/promo-code.test.ts b/web/src/lib/billing/promo-code.test.ts
new file mode 100644
index 000000000..87b97de8d
--- /dev/null
+++ b/web/src/lib/billing/promo-code.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it, vi } from 'vitest';
+import type Stripe from 'stripe';
+import { discountedPrice, findPromotionCode, type PromoOffer } from './promo-code';
+
+const offer = (over: Partial<PromoOffer>): PromoOffer => ({
+ code: 'X',
+ percentOff: null,
+ amountOff: null,
+ duration: 'once',
+ durationInMonths: null,
+ ...over,
+});
+
+describe('discountedPrice', () => {
+ it('takes a percentage off, to the cent', () => {
+ expect(discountedPrice(49, offer({ percentOff: 50 }))).toBe(24.5);
+ expect(discountedPrice(249, offer({ percentOff: 50 }))).toBe(124.5);
+ expect(discountedPrice(49, offer({ percentOff: 15 }))).toBe(41.65);
+ });
+
+ it('takes dollars off, never below zero', () => {
+ expect(discountedPrice(49, offer({ amountOff: 10 }))).toBe(39);
+ expect(discountedPrice(49, offer({ amountOff: 100 }))).toBe(0);
+ });
+});
+
+/** A Stripe promotion code on a coupon, as the list expands it. */
+const promo = (over: Record<string, unknown> = {}, coupon: Record<string, unknown> = {}) => ({
+ id: 'promo_1',
+ code: 'SAVE50',
+ active: true,
+ customer: null,
+ expires_at: null,
+ max_redemptions: null,
+ times_redeemed: 0,
+ promotion: {
+ type: 'coupon',
+ coupon: {
+ valid: true,
+ percent_off: 50,
+ amount_off: null,
+ currency: null,
+ duration: 'once',
+ duration_in_months: null,
+ ...coupon,
+ },
+ },
+ ...over,
+});
+
+function stripeWith(data: unknown[]) {
+ const list = vi.fn(async () => ({ data }));
+ return { client: { promotionCodes: { list } } as unknown as Stripe, list };
+}
+
+describe('findPromotionCode', () => {
+ it('reads what an active code takes off, matched in any case', async () => {
+ const { client, list } = stripeWith([promo()]);
+ expect(await findPromotionCode(client, ' save50 ', 'cus_1')).toEqual({
+ id: 'promo_1',
+ offer: {
+ code: 'SAVE50',
+ percentOff: 50,
+ amountOff: null,
+ duration: 'once',
+ durationInMonths: null,
+ },
+ });
+ expect(list).toHaveBeenCalledWith({
+ code: 'save50',
+ active: true,
+ limit: 1,
+ expand: ['data.promotion.coupon'],
+ });
+ });
+
+ it('reads US dollars off in dollars', async () => {
+ const { client } = stripeWith([
+ promo(
+ {},
+ {
+ percent_off: null,
+ amount_off: 1000,
+ currency: 'usd',
+ duration: 'repeating',
+ duration_in_months: 3,
+ },
+ ),
+ ]);
+ expect((await findPromotionCode(client, 'TEN', null))?.offer).toMatchObject({
+ percentOff: null,
+ amountOff: 10,
+ duration: 'repeating',
+ durationInMonths: 3,
+ });
+ });
+
+ it('refuses a code Stripe does not have, without asking for anything not a code', async () => {
+ const { client, list } = stripeWith([]);
+ expect(await findPromotionCode(client, 'NOPE', null)).toBeNull();
+ expect(await findPromotionCode(client, 'not a code!', null)).toBeNull();
+ expect(await findPromotionCode(client, '', null)).toBeNull();
+ expect(list).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses a code that cannot be redeemed now', async () => {
+ const cases = [
+ promo({ active: false }),
+ promo({ expires_at: Math.floor(Date.now() / 1000) - 60 }),
+ promo({ max_redemptions: 5, times_redeemed: 5 }),
+ promo({ customer: 'cus_other' }),
+ promo({}, { valid: false }),
+ promo({}, { percent_off: null, amount_off: 1000, currency: 'eur' }),
+ promo({ promotion: { type: 'coupon', coupon: 'coupon_1' } }),
+ ];
+ for (const code of cases) {
+ const { client } = stripeWith([code]);
+ expect(await findPromotionCode(client, 'SAVE50', 'cus_1')).toBeNull();
+ }
+ });
+
+ it("takes a code kept for this customer, and one that hasn't expired yet", async () => {
+ const { client } = stripeWith([
+ promo({ customer: 'cus_1', expires_at: Math.floor(Date.now() / 1000) + 3600 }),
+ ]);
+ expect(await findPromotionCode(client, 'SAVE50', 'cus_1')).not.toBeNull();
+ });
+});
diff --git a/web/src/lib/billing/promo-code.ts b/web/src/lib/billing/promo-code.ts
new file mode 100644
index 000000000..050ff68b6
--- /dev/null
+++ b/web/src/lib/billing/promo-code.ts
@@ -0,0 +1,86 @@
+import type Stripe from 'stripe';
+import { z } from 'zod';
+
+/**
+ * What a promotion code takes off, as the plan dialog shows it: a percentage
+ * or an amount in dollars, for the first invoice (`once`), a number of
+ * months (`repeating`) or every one (`forever`).
+ */
+export interface PromoOffer {
+ /** The code as Stripe has it, whatever case it was typed in. */
+ code: string;
+ percentOff: number | null;
+ /** Dollars off each discounted invoice; prices are in USD. */
+ amountOff: number | null;
+ duration: 'once' | 'repeating' | 'forever';
+ durationInMonths: number | null;
+}
+
+/** A promotion code as typed: Stripe's own characters, letters, digits and dashes. */
+export const promoCodeSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(64)
+ .regex(/^[A-Za-z0-9-]+$/);
+
+/**
+ * A plan's price for its first discounted period with the offer, rounded to
+ * the cent and never below zero.
+ */
+export function discountedPrice(price: number, offer: PromoOffer): number {
+ const cents = Math.round(price * 100);
+ const off =
+ offer.percentOff != null
+ ? Math.round((cents * offer.percentOff) / 100)
+ : Math.round((offer.amountOff ?? 0) * 100);
+ return Math.max(0, cents - off) / 100;
+}
+
+/**
+ * The Stripe promotion code a customer typed, when it can be redeemed now:
+ * active, not expired or used up, not kept for another customer, on a valid
+ * coupon that takes a percentage or US dollars off. Null otherwise, and for
+ * anything that isn't a code at all. Stripe matches the code in any case.
+ */
+export async function findPromotionCode(
+ client: Pick<Stripe, 'promotionCodes'>,
+ code: string,
+ customerId: string | null | undefined,
+): Promise<{ id: string; offer: PromoOffer } | null> {
+ const typed = promoCodeSchema.safeParse(code);
+ if (!typed.success) return null;
+ const { data } = await client.promotionCodes.list({
+ code: typed.data,
+ active: true,
+ limit: 1,
+ expand: ['data.promotion.coupon'],
+ });
+ const promo = data[0];
+ if (!promo?.active) return null;
+ const now = Math.floor(Date.now() / 1000);
+ if (promo.expires_at != null && promo.expires_at <= now) return null;
+ if (promo.max_redemptions != null && promo.times_redeemed >= promo.max_redemptions) return null;
+ const restrictedTo = typeof promo.customer === 'string' ? promo.customer : promo.customer?.id;
+ if (restrictedTo && restrictedTo !== customerId) return null;
+
+ const coupon = promo.promotion?.coupon;
+ if (!coupon || typeof coupon === 'string' || !coupon.valid) return null;
+ const percentOff = coupon.percent_off ?? null;
+ const amountOff =
+ coupon.amount_off != null && coupon.currency?.toLowerCase() === 'usd'
+ ? coupon.amount_off / 100
+ : null;
+ if (!(percentOff && percentOff > 0) && !(amountOff && amountOff > 0)) return null;
+
+ return {
+ id: promo.id,
+ offer: {
+ code: promo.code,
+ percentOff: percentOff && percentOff > 0 ? percentOff : null,
+ amountOff: percentOff && percentOff > 0 ? null : amountOff,
+ duration: coupon.duration,
+ durationInMonths: coupon.duration_in_months ?? null,
+ },
+ };
+}