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.

fix(billing): write the subscription's period end at checkout (#1358)

Cihanc1d22999ea10
diff --git a/web/src/app/api/stripe/subscription/route.ts b/web/src/app/api/stripe/subscription/route.ts
index 3a0b7d5e2..2821daa9d 100644
--- a/web/src/app/api/stripe/subscription/route.ts
+++ b/web/src/app/api/stripe/subscription/route.ts
@@ -3,6 +3,7 @@ import { createClient } from '@/lib/supabase/server';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { stripe, priceIdFor } from '@/lib/stripe';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
+import { periodEndIso } from '@/lib/billing/period-end';
import { planChange, planRequestSchema, type BillingInterval } from '@/lib/billing/plan-purchase';
type SubscriptionItem = {
@@ -25,21 +26,6 @@ type SubscriptionRaw = {
current_period_end?: number;
};
-/**
- * Stripe API 2025-03-31 moved `current_period_end` from the subscription
- * onto each subscription item. Read item-level first, fall back to the
- * subscription-level for older API versions, and return null if neither is
- * present (so callers can skip emitting an Invalid Date).
- */
-function getCurrentPeriodEndIso(sub: SubscriptionRaw): string | null {
- const itemEnd = sub.items?.data?.[0]?.current_period_end;
- const subEnd = sub.current_period_end;
- const epochSeconds =
- typeof itemEnd === 'number' ? itemEnd : typeof subEnd === 'number' ? subEnd : null;
- if (epochSeconds == null) return null;
- return new Date(epochSeconds * 1000).toISOString();
-}
-
async function getOrgStripeIds() {
const supabase = await createClient();
const {
@@ -102,7 +88,7 @@ export async function GET() {
return NextResponse.json({
planId: org.plan ?? 'starter',
status: sub.status,
- currentPeriodEnd: getCurrentPeriodEndIso(sub),
+ currentPeriodEnd: periodEndIso(sub),
cancelAtPeriodEnd: sub.cancel_at_period_end,
priceAmount: price?.unit_amount ? price.unit_amount / 100 : null,
interval: price?.recurring?.interval ?? null,
@@ -128,7 +114,7 @@ function subscriptionBody(planId: string, sub: SubscriptionRaw) {
return {
planId,
status: sub.status,
- currentPeriodEnd: getCurrentPeriodEndIso(sub),
+ currentPeriodEnd: periodEndIso(sub),
cancelAtPeriodEnd: sub.cancel_at_period_end,
priceAmount: price?.unit_amount ? price.unit_amount / 100 : null,
interval: price?.recurring?.interval ?? null,
@@ -174,7 +160,7 @@ export async function PATCH(req: NextRequest) {
return NextResponse.json({
status: updated.status,
cancelAtPeriodEnd: false,
- currentPeriodEnd: getCurrentPeriodEndIso(updated),
+ currentPeriodEnd: periodEndIso(updated),
});
}
@@ -315,7 +301,7 @@ export async function DELETE() {
return NextResponse.json({
cancelAtPeriodEnd: true,
- currentPeriodEnd: getCurrentPeriodEndIso(updated),
+ currentPeriodEnd: periodEndIso(updated),
});
} catch (err) {
console.error('[stripe/subscription] DELETE error:', err);
diff --git a/web/src/app/api/stripe/success/route.test.ts b/web/src/app/api/stripe/success/route.test.ts
new file mode 100644
index 000000000..b6b586a63
--- /dev/null
+++ b/web/src/app/api/stripe/success/route.test.ts
@@ -0,0 +1,102 @@
+import type { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Back from Stripe Checkout: the organization gets its plan, status and
+ * period end before the webhook lands, then the dashboard opens.
+ */
+
+const stripeApi = vi.hoisted(() => ({ retrieveSession: vi.fn(), retrieve: vi.fn() }));
+vi.mock('@/lib/stripe', () => ({
+ stripe: {
+ checkout: { sessions: { retrieve: stripeApi.retrieveSession } },
+ subscriptions: { retrieve: stripeApi.retrieve },
+ },
+}));
+
+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 };
+ },
+ // No brand yet: nothing to start tracking for.
+ select: () => {
+ const query = {
+ eq: () => query,
+ order: () => query,
+ limit: () => query,
+ single: async () => ({ data: null }),
+ };
+ return query;
+ },
+ }),
+ },
+}));
+
+const align = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/plan-engines', () => ({ alignPromptsToPlanForOrg: align }));
+
+const { GET } = await import('./route');
+
+const back = () =>
+ GET(new Request('http://localhost/api/stripe/success?session_id=cs_1') as unknown as NextRequest);
+
+/** A Stripe subscription with one item, its period ending at `end` (seconds). */
+const subscription = (end?: number) => ({
+ id: 'sub1',
+ status: 'trialing',
+ metadata: { organization_id: 'org1', plan_id: 'starter' },
+ items: { data: [end == null ? {} : { current_period_end: end }] },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ align.mockResolvedValue({ promptCount: 0, platforms: [], models: [] });
+ db.eq.mockResolvedValue({ error: null });
+});
+
+describe('GET /api/stripe/success', () => {
+ it('writes the period end with the plan, then opens the dashboard', async () => {
+ stripeApi.retrieveSession.mockResolvedValue({
+ payment_status: 'no_payment_required',
+ status: 'complete',
+ customer: 'cus1',
+ subscription: subscription(1_800_000_000),
+ });
+
+ const res = await back();
+
+ expect(stripeApi.retrieveSession).toHaveBeenCalledWith('cs_1', { expand: ['subscription'] });
+ expect(db.update).toHaveBeenCalledWith({
+ subscription_status: 'trialing',
+ plan: 'starter',
+ stripe_customer_id: 'cus1',
+ stripe_subscription_id: 'sub1',
+ subscription_ends_at: '2027-01-15T08:00:00.000Z',
+ });
+ expect(db.eq).toHaveBeenCalledWith('id', 'org1');
+ expect(align).toHaveBeenCalledWith('org1', 'starter');
+ expect(res.headers.get('location')).toMatch(/\/dashboard\/action-center\/actions$/);
+ });
+
+ it('reads an unexpanded subscription, and leaves the period end alone without one', async () => {
+ stripeApi.retrieveSession.mockResolvedValue({
+ payment_status: 'paid',
+ status: 'complete',
+ customer: 'cus1',
+ subscription: 'sub1',
+ });
+ stripeApi.retrieve.mockResolvedValue(subscription());
+
+ await back();
+
+ expect(stripeApi.retrieve).toHaveBeenCalledWith('sub1');
+ expect(db.update).toHaveBeenCalledTimes(1);
+ expect(db.update.mock.calls[0][0]).not.toHaveProperty('subscription_ends_at');
+ });
+});
diff --git a/web/src/app/api/stripe/success/route.ts b/web/src/app/api/stripe/success/route.ts
index 571a15d40..27555a491 100644
--- a/web/src/app/api/stripe/success/route.ts
+++ b/web/src/app/api/stripe/success/route.ts
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
+import { periodEndIso } from '@/lib/billing/period-end';
import { API_BASE_URL } from '@/config/api';
import { DASHBOARD_HOME } from '@/config/home';
@@ -37,6 +38,8 @@ export async function GET(req: NextRequest) {
const planId = (subscription as { metadata?: { plan_id?: string } })?.metadata?.plan_id;
if (orgId && customerId && subscriptionId) {
+ // As the webhook's checkout.session.completed writes it.
+ const endsAt = periodEndIso(subscription);
// Update org subscription (resolves webhook race condition)
const { error: updateError } = await supabaseAdmin
.from('organizations')
@@ -47,6 +50,7 @@ export async function GET(req: NextRequest) {
plan: planId || 'starter',
stripe_customer_id: customerId,
stripe_subscription_id: subscriptionId,
+ ...(endsAt ? { subscription_ends_at: endsAt } : {}),
})
.eq('id', orgId);
diff --git a/web/src/app/api/stripe/webhook/route.test.ts b/web/src/app/api/stripe/webhook/route.test.ts
new file mode 100644
index 000000000..65f0d11c4
--- /dev/null
+++ b/web/src/app/api/stripe/webhook/route.test.ts
@@ -0,0 +1,108 @@
+import type { NextRequest } from 'next/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The Stripe webhook keeps the organization's plan, status and period end in
+ * step with Stripe: from the checkout on, not only from the first update.
+ */
+
+const stripeApi = vi.hoisted(() => ({ constructEvent: vi.fn(), retrieve: vi.fn() }));
+vi.mock('@/lib/stripe', () => ({
+ stripe: {
+ webhooks: { constructEvent: stripeApi.constructEvent },
+ subscriptions: { retrieve: stripeApi.retrieve },
+ },
+}));
+
+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 };
+ },
+ // The plan before an update, to tell a plan change.
+ select: () => ({
+ eq: () => ({ maybeSingle: async () => ({ data: { id: 'org1', plan: 'starter' } }) }),
+ }),
+ }),
+ },
+}));
+
+const align = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/plan-engines', () => ({ alignPromptsToPlanForOrg: align }));
+
+const { POST } = await import('./route');
+
+const deliver = (type: string, object: unknown) => {
+ stripeApi.constructEvent.mockReturnValue({ type, data: { object } });
+ return POST(
+ new Request('http://localhost/api/stripe/webhook', {
+ method: 'POST',
+ body: '{}',
+ headers: { 'stripe-signature': 'sig' },
+ }) as unknown as NextRequest,
+ );
+};
+
+/** A Stripe subscription with one item, its period ending at `end` (seconds). */
+const subscription = (status: string, end?: number) => ({
+ id: 'sub1',
+ status,
+ customer: 'cus1',
+ metadata: { organization_id: 'org1', plan_id: 'growth' },
+ items: { data: [end == null ? {} : { current_period_end: end }] },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ align.mockResolvedValue({ promptCount: 0, platforms: [], models: [] });
+ db.eq.mockResolvedValue({ error: null });
+});
+
+describe('checkout.session.completed', () => {
+ it('writes the period end with the plan, so a new trial has one', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing', 1_800_000_000));
+ const res = await deliver('checkout.session.completed', {
+ customer: 'cus1',
+ subscription: 'sub1',
+ });
+
+ expect(res.status).toBe(200);
+ expect(stripeApi.retrieve).toHaveBeenCalledWith('sub1');
+ expect(db.update).toHaveBeenCalledWith({
+ subscription_status: 'trialing',
+ plan: 'growth',
+ stripe_customer_id: 'cus1',
+ stripe_subscription_id: 'sub1',
+ subscription_ends_at: '2027-01-15T08:00:00.000Z',
+ });
+ expect(db.eq).toHaveBeenCalledWith('id', 'org1');
+ expect(align).toHaveBeenCalledWith('org1', 'growth');
+ });
+
+ it('leaves the period end alone when Stripe gives none', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+ await deliver('checkout.session.completed', { customer: 'cus1', subscription: 'sub1' });
+ expect(db.update.mock.calls[0][0]).not.toHaveProperty('subscription_ends_at');
+ });
+});
+
+describe('customer.subscription.updated', () => {
+ it('still writes the new period end, and leaves it alone without one', async () => {
+ await deliver('customer.subscription.updated', subscription('active', 1_800_000_000));
+ expect(db.update).toHaveBeenCalledWith({
+ subscription_status: 'active',
+ subscription_ends_at: '2027-01-15T08:00:00.000Z',
+ plan: 'growth',
+ });
+ expect(db.eq).toHaveBeenCalledWith('stripe_customer_id', 'cus1');
+
+ db.update.mockClear();
+ await deliver('customer.subscription.updated', subscription('past_due'));
+ expect(db.update).toHaveBeenCalledWith({ subscription_status: 'past_due', plan: 'growth' });
+ });
+});
diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.ts
index 9cfd1470b..8fabc55ed 100644
--- a/web/src/app/api/stripe/webhook/route.ts
+++ b/web/src/app/api/stripe/webhook/route.ts
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
+import { periodEndIso } from '@/lib/billing/period-end';
import type Stripe from 'stripe';
/**
@@ -65,6 +66,10 @@ export async function POST(req: NextRequest) {
);
if (orgId) {
+ // The period end too: no update event follows a new subscription
+ // until it renews or changes, and the quota period and Cancel's
+ // "give us 3 days" read it.
+ const endsAt = periodEndIso(subscription);
const { error } = await supabaseAdmin
.from('organizations')
.update({
@@ -73,6 +78,7 @@ export async function POST(req: NextRequest) {
plan: planId || 'starter',
stripe_customer_id: customerId,
stripe_subscription_id: subscriptionId,
+ ...(endsAt ? { subscription_ends_at: endsAt } : {}),
})
.eq('id', orgId);
if (error) {
@@ -102,22 +108,12 @@ export async function POST(req: NextRequest) {
: subscription.customer?.id;
if (customerId) {
- // Stripe API 2025-03-31 moved current_period_end to the item level.
- // Read item-level first, fall back to subscription-level for older
- // API versions, and skip the field entirely if neither is present.
- const subItems = subscription as unknown as {
- items?: { data?: Array<{ current_period_end?: number }> };
- current_period_end?: number;
- };
- const epochSeconds =
- subItems.items?.data?.[0]?.current_period_end ?? subItems.current_period_end;
-
const updates: Record<string, unknown> = {
subscription_status: subscription.status,
};
- if (typeof epochSeconds === 'number') {
- updates.subscription_ends_at = new Date(epochSeconds * 1000).toISOString();
- }
+ // Skipped when Stripe gives no period end, rather than cleared.
+ const endsAt = periodEndIso(subscription);
+ if (endsAt) updates.subscription_ends_at = endsAt;
// Update plan if metadata has plan_id
const newPlanId = subscription.metadata.plan_id;
diff --git a/web/src/lib/billing/period-end.test.ts b/web/src/lib/billing/period-end.test.ts
new file mode 100644
index 000000000..352706ee5
--- /dev/null
+++ b/web/src/lib/billing/period-end.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { periodEndIso } from './period-end';
+
+describe('periodEndIso', () => {
+ it('reads the first item’s period end, as newer Stripe API versions put it', () => {
+ expect(
+ periodEndIso({
+ items: { data: [{ current_period_end: 1_800_000_000 }] },
+ current_period_end: 1_700_000_000,
+ }),
+ ).toBe('2027-01-15T08:00:00.000Z');
+ });
+
+ it('falls back to the subscription’s own, for older API versions', () => {
+ expect(periodEndIso({ items: { data: [{}] }, current_period_end: 1_800_000_000 })).toBe(
+ '2027-01-15T08:00:00.000Z',
+ );
+ });
+
+ it('is null when Stripe gives none, or there is no subscription', () => {
+ expect(periodEndIso({ items: { data: [] } })).toBeNull();
+ expect(periodEndIso(null)).toBeNull();
+ expect(periodEndIso(undefined)).toBeNull();
+ });
+});
diff --git a/web/src/lib/billing/period-end.ts b/web/src/lib/billing/period-end.ts
new file mode 100644
index 000000000..a7563c605
--- /dev/null
+++ b/web/src/lib/billing/period-end.ts
@@ -0,0 +1,24 @@
+/** The parts of a Stripe subscription that say when its current period ends. */
+export type SubscriptionPeriod = {
+ items?: { data?: Array<{ current_period_end?: number }> };
+ // Some older API versions still return this on the subscription itself.
+ current_period_end?: number;
+};
+
+/**
+ * When the subscription's current period ends (while it trials, the trial's
+ * end), as an ISO string: `organizations.subscription_ends_at`.
+ *
+ * Stripe API 2025-03-31 moved `current_period_end` from the subscription
+ * onto each subscription item. Read item-level first, fall back to the
+ * subscription-level for older API versions, and return null if neither is
+ * present (so callers can skip emitting an Invalid Date).
+ */
+export function periodEndIso(sub: SubscriptionPeriod | null | undefined): string | null {
+ const itemEnd = sub?.items?.data?.[0]?.current_period_end;
+ const subEnd = sub?.current_period_end;
+ const epochSeconds =
+ typeof itemEnd === 'number' ? itemEnd : typeof subEnd === 'number' ? subEnd : null;
+ if (epochSeconds == null) return null;
+ return new Date(epochSeconds * 1000).toISOString();
+}