diff --git a/apps/api/src/routes/dev-plans.spec.ts b/apps/api/src/routes/dev-plans.spec.ts index 65f39a6256..867637c810 100644 --- a/apps/api/src/routes/dev-plans.spec.ts +++ b/apps/api/src/routes/dev-plans.spec.ts @@ -1100,3 +1100,122 @@ describe("dev plan tier changes", () => { expect(stripeMock.subscriptions.update).not.toHaveBeenCalled(); }); }); + +describe("dev plan status billing history", () => { + let token: string; + + beforeEach(async () => { + vi.clearAllMocks(); + token = await createTestUser(); + + await db.insert(tables.organization).values({ + id: ORG_ID, + name: "Personal Org", + billingEmail: "admin@example.com", + kind: "devpass", + devPlan: "lite", + devPlanStripeSubscriptionId: SUBSCRIPTION_ID, + }); + await db.insert(tables.userOrganization).values({ + userId: "test-user-id", + organizationId: ORG_ID, + role: "owner", + }); + }); + + afterEach(async () => { + await db.delete(tables.transaction); + await deleteAll(); + }); + + async function getStatus() { + const res = await app.request("/dev-plans/status", { + headers: { Cookie: token }, + }); + expect(res.status).toBe(200); + return await res.json(); + } + + it("reports no billing history before the first charge", async () => { + expect(await getStatus()).toMatchObject({ + hasPersonalOrg: true, + hasBillingHistory: false, + }); + }); + + it("reports billing history once a plan payment exists", async () => { + await db.insert(tables.transaction).values({ + organizationId: ORG_ID, + type: "dev_plan_start", + amount: "29", + currency: "USD", + status: "completed", + }); + + expect(await getStatus()).toMatchObject({ hasBillingHistory: true }); + }); + + it("keeps reporting billing history after the plan ends", async () => { + // Ending a plan clears every devPlan* column, so the invoices are the only + // remaining signal that this user still needs the billing page. + await db.insert(tables.transaction).values({ + organizationId: ORG_ID, + type: "dev_plan_start", + amount: "29", + currency: "USD", + status: "completed", + }); + await db + .update(tables.organization) + .set({ devPlan: "none", devPlanStripeSubscriptionId: null }) + .where(eq(tables.organization.id, ORG_ID)); + + expect(await getStatus()).toMatchObject({ + devPlan: "none", + hasBillingHistory: true, + }); + }); + + it("ignores non-invoice bookkeeping rows", async () => { + await db.insert(tables.transaction).values({ + organizationId: ORG_ID, + type: "dev_plan_cancel", + currency: "USD", + status: "completed", + }); + + expect(await getStatus()).toMatchObject({ hasBillingHistory: false }); + }); + + it("counts legacy pre-rename subscription rows", async () => { + // Dev plans were billed as `subscription_*` before the DevPass rename; on + // a devpass-kind org those rows are a past DevPass subscriber. + await db.insert(tables.transaction).values({ + organizationId: ORG_ID, + type: "subscription_start", + amount: "50", + currency: "USD", + status: "completed", + }); + await db + .update(tables.organization) + .set({ devPlan: "none", devPlanStripeSubscriptionId: null }) + .where(eq(tables.organization.id, ORG_ID)); + + expect(await getStatus()).toMatchObject({ hasBillingHistory: true }); + }); + + it("counts an unsettled charge, matching the invoice list", async () => { + // The invoices endpoint renders pending and failed charges too (with a + // status badge), so the page has content to show and must stay reachable. + await db.insert(tables.transaction).values({ + organizationId: ORG_ID, + type: "dev_plan_start", + amount: "29", + currency: "USD", + status: "failed", + }); + + expect(await getStatus()).toMatchObject({ hasBillingHistory: true }); + }); +}); diff --git a/apps/api/src/routes/dev-plans.ts b/apps/api/src/routes/dev-plans.ts index 5ca4888729..bd9b8e6106 100644 --- a/apps/api/src/routes/dev-plans.ts +++ b/apps/api/src/routes/dev-plans.ts @@ -19,6 +19,7 @@ import { isDevPlanCardDedupeEnforced, } from "@/stripe.js"; import { findDefaultOrganization } from "@/utils/default-org.js"; +import { LEGACY_DEV_PLAN_TX_TYPES } from "@/utils/devpass-filter.js"; import { buildInvoiceDataForTransaction, generateAndEmailInvoice, @@ -74,6 +75,14 @@ export const devPlans = new OpenAPIHono(); // lease this old cannot still have an upgrade charge in flight. const STALE_TIER_CHANGE_CLAIM_MS = 15 * 60 * 1000; +// Transaction types that surface as invoices on the DevPass billing page. +const DEV_PLAN_INVOICE_TYPES = [ + "dev_plan_start", + "dev_plan_renewal", + "dev_plan_upgrade", + "dev_plan_reset_pass", +] as const; + // A failed release is swallowed: the lease then simply expires via the // staleness window instead of blocking upgrades until renewal. async function releaseTierChangeLease(organizationId: string) { @@ -1708,6 +1717,10 @@ const getStatus = createRoute({ "application/json": { schema: z.object({ hasPersonalOrg: z.boolean(), + // Whether the org ever produced a DevPass invoice. Stays true + // after a plan ends, so the dashboard keeps showing billing to + // past subscribers (invoices, receipts, Reset Pass refunds). + hasBillingHistory: z.boolean(), devPlan: z.enum(["none", "lite", "pro", "max"]), devPlanPendingTier: z.enum(["lite", "pro", "max"]).nullable(), devPlanCycle: z.enum(["monthly", "annual"]), @@ -1773,6 +1786,7 @@ devPlans.openapi(getStatus, async (c) => { if (!personalOrg) { return c.json({ hasPersonalOrg: false, + hasBillingHistory: false, devPlan: "none" as const, devPlanPendingTier: null, devPlanCycle: "monthly" as const, @@ -1802,6 +1816,21 @@ devPlans.openapi(getStatus, async (c) => { const creditsLimit = parseFloat(personalOrg.devPlanCreditsLimit); const creditsRemaining = Math.max(0, creditsLimit - creditsUsed); + // Ending a dev plan clears every devPlan* column on the org, so the billing + // transactions are the only lasting record that the user was ever a + // subscriber — and the dashboard needs it to keep the billing page reachable. + // The legacy `subscription_*` rows predate the DevPass rename and mean a dev + // plan only on a devpass-kind org, which `personalOrg` always is. Status is + // deliberately not filtered: this mirrors the invoice list, which also + // renders pending and failed charges. + const billingTransaction = await db.query.transaction.findFirst({ + where: { + organizationId: { eq: personalOrg.id }, + type: { in: [...DEV_PLAN_INVOICE_TYPES, ...LEGACY_DEV_PLAN_TX_TYPES] }, + }, + columns: { id: true }, + }); + // Weekly premium fair-use allowance, computed with the same helpers the // gateway uses for enforcement. An expired window reports zero usage and no // reset date — the full allowance is already available again. @@ -1856,6 +1885,7 @@ devPlans.openapi(getStatus, async (c) => { return c.json({ hasPersonalOrg: true, + hasBillingHistory: Boolean(billingTransaction), devPlan: personalOrg.devPlan, devPlanPendingTier: personalOrg.devPlanPendingTier, devPlanCycle: personalOrg.devPlanCycle, @@ -2329,12 +2359,7 @@ devPlans.openapi(getInvoices, async (c) => { const invoices = transactions .filter((t) => - [ - "dev_plan_start", - "dev_plan_renewal", - "dev_plan_upgrade", - "dev_plan_reset_pass", - ].includes(t.type), + (DEV_PLAN_INVOICE_TYPES as readonly string[]).includes(t.type), ) .map((t) => ({ id: t.id, diff --git a/apps/code/src/app/dashboard/(main)/billing/BillingClient.tsx b/apps/code/src/app/dashboard/(main)/billing/BillingClient.tsx index 6c92a8e303..7cb30b8e5f 100644 --- a/apps/code/src/app/dashboard/(main)/billing/BillingClient.tsx +++ b/apps/code/src/app/dashboard/(main)/billing/BillingClient.tsx @@ -4,6 +4,7 @@ import { useQueryClient } from "@tanstack/react-query"; import { format, formatDistanceToNowStrict } from "date-fns"; import { Info, Loader2 } from "lucide-react"; import dynamic from "next/dynamic"; +import Link from "next/link"; import { usePostHog } from "posthog-js/react"; import { useState } from "react"; import { toast } from "sonner"; @@ -262,7 +263,43 @@ export default function BillingClient({ } const currentPlan = devPlanStatus.devPlan ?? null; + const hasActivePlan = currentPlan !== null && currentPlan !== "none"; const currentPlanData = plans.find((p) => p.tier === currentPlan); + // A plan that ended — or was refunded, which cancels immediately — clears the + // tier, but this page stays useful: invoices and receipts remain + // downloadable and an unused Reset Pass is still refundable. Everything that + // acts on a live subscription (payment method, tier changes, cancel/resume) + // is dropped, since those endpoints require one. + if (!hasActivePlan) { + return ( +
+ + +
+
+
+

No active plan

+

+ {devPlanStatus.hasBillingHistory + ? "Your DevPass subscription has ended. Your invoices and receipts stay available here." + : "You don't have a DevPass plan yet."} +

+
+ +
+
+ + {/* Past invoices */} + + + {/* Billing details (invoice details) */} + +
+ ); + } + const pendingTier = devPlanStatus.devPlanPendingTier ?? null; const pendingPlanData = plans.find((p) => p.tier === pendingTier); const cycle = devPlanStatus.devPlanCycle ?? "monthly"; @@ -314,12 +351,7 @@ export default function BillingClient({ return (
-
-

Billing

-

- Manage your DevPass subscription and plan. -

-
+ {/* Current subscription summary */}
@@ -455,6 +487,17 @@ export default function BillingClient({ ); } +function BillingHeader() { + return ( +
+

Billing

+

+ Manage your DevPass subscription and plan. +

+
+ ); +} + function BillingSkeleton() { return (
diff --git a/apps/code/src/app/dashboard/(main)/settings/page.tsx b/apps/code/src/app/dashboard/(main)/settings/page.tsx index 8cbc499714..35b490f439 100644 --- a/apps/code/src/app/dashboard/(main)/settings/page.tsx +++ b/apps/code/src/app/dashboard/(main)/settings/page.tsx @@ -43,10 +43,16 @@ export default function SettingsPage() {
- + {/* Routing and service-tier settings apply to the live plan only — the + endpoint rejects updates once the subscription has ended. */} + {devPlanStatus.devPlan !== "none" && ( + + )}
diff --git a/apps/code/src/app/dashboard/DashboardShell.tsx b/apps/code/src/app/dashboard/DashboardShell.tsx index 4bd5d24c06..5ce9fdc6ed 100644 --- a/apps/code/src/app/dashboard/DashboardShell.tsx +++ b/apps/code/src/app/dashboard/DashboardShell.tsx @@ -9,6 +9,7 @@ import { Loader2, LogOut, Settings, + Sparkles, Stamp, UserRound, } from "lucide-react"; @@ -65,6 +66,15 @@ const navItems: Array<{ label: string; href: Route; icon: typeof BarChart3 }> = { label: "Settings", href: "/dashboard/settings" as Route, icon: Settings }, ]; +// Pages that stay usable without an active plan: past invoices, receipts and +// self-refunds, the public profile, and account settings all outlive the +// subscription. Only the usage overview is replaced by the plan chooser. +const planIndependentRoutes: string[] = [ + "/dashboard/billing", + "/dashboard/profile", + "/dashboard/settings", +]; + // Pages that live on the DevPass site but outside the dashboard shell, so // they're rendered in their own subtle nav section with a link-out marker. // The census link is appended per render so its year stays current. @@ -442,7 +452,49 @@ export default function DashboardShell({ const hasActivePlan = devPlanStatus?.devPlan && devPlanStatus.devPlan !== "none"; + const isPlanIndependentRoute = planIndependentRoutes.includes(pathname); + // A plan that ended (or was refunded) clears the tier, but the user still + // needs billing: past invoices, receipts, unused Reset Pass refunds. Keep the + // full dashboard chrome for anyone who has ever been billed, and for the + // account pages themselves — brand-new visitors still land on the focused, + // full-width plan chooser. + const showDashboardChrome = + hasActivePlan || + Boolean(devPlanStatus?.hasBillingHistory) || + isPlanIndependentRoute; const currentPlanName = devPlanStatus?.devPlan?.toUpperCase() ?? ""; + // Without a plan the usage tab is the plan chooser, so label it as such. + const mainNavItems = hasActivePlan + ? navItems + : navItems.map((item) => + item.href === "/dashboard" + ? { ...item, label: "Plans", icon: Sparkles } + : item, + ); + const planChooser = ( +
+
+
+ +
+

+ {devPlanStatus?.hasBillingHistory + ? "Choose a new Dev Plan" + : "Choose your Dev Plan"} +

+

+ Pick a plan to get your API key and start coding with 200+ models. + Every dollar gives you 3x in usage. +

+
+ + +
+ ); const activeSetupActivationStatus = setupActivationStatus ?? (setupSessionId ? "finalizing" : null); const activeSetupActivationCopy = activeSetupActivationStatus @@ -579,12 +631,12 @@ export default function DashboardShell({ - ) : hasActivePlan ? ( + ) : showDashboardChrome ? (
{/* Sidebar */} - {/* Page content */} -
{children}
+ {/* Page content — the usage overview needs a plan, the account and + billing pages do not. */} +
+ {hasActivePlan || isPlanIndependentRoute ? children : planChooser} +
) : (
-
-
-
- -
-

- Choose your Dev Plan -

-

- Pick a plan to get your API key and start coding with 200+ - models. Every dollar gives you 3x in usage. -

-
- - -
+ {planChooser}
)}