Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions apps/api/src/routes/dev-plans.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1100,3 +1100,90 @@ 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 });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
});
32 changes: 26 additions & 6 deletions apps/api/src/routes/dev-plans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ export const devPlans = new OpenAPIHono<ServerTypes>();
// 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) {
Expand Down Expand Up @@ -1708,6 +1716,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"]),
Expand Down Expand Up @@ -1773,6 +1785,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,
Expand Down Expand Up @@ -1802,6 +1815,17 @@ 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.
const billingTransaction = await db.query.transaction.findFirst({
where: {
organizationId: { eq: personalOrg.id },
type: { in: [...DEV_PLAN_INVOICE_TYPES] },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include legacy DevPass payments in history

Because /dev-plans/status now decides whether an inactive user keeps dashboard chrome by checking only DEV_PLAN_INVOICE_TYPES, it misses pre-rename DevPass purchases recorded as subscription_start (documented in apps/api/src/utils/devpass-filter.ts:64). For any former DevPass subscriber whose only payment is one of those legacy rows and whose subscription has since been cleared to devPlan: "none", hasBillingHistory stays false, so they still get the full-width plan chooser instead of the sidebar/billing/settings access this change is meant to restore. Include the legacy DevPass payment rows in the history check; the query is already scoped to the user's devpass org.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1b846c8 — good catch. hasBillingHistory now matches DEV_PLAN_INVOICE_TYPES plus LEGACY_DEV_PLAN_TX_TYPES; the query is already scoped to the user's devpass-kind personal org, which is the pairing that constant's own doc comment requires. Added a spec covering a legacy subscription_start row on an ended plan.

},
columns: { id: true },
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// 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.
Expand Down Expand Up @@ -1856,6 +1880,7 @@ devPlans.openapi(getStatus, async (c) => {

return c.json({
hasPersonalOrg: true,
hasBillingHistory: Boolean(billingTransaction),
devPlan: personalOrg.devPlan,
devPlanPendingTier: personalOrg.devPlanPendingTier,
devPlanCycle: personalOrg.devPlanCycle,
Expand Down Expand Up @@ -2329,12 +2354,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,
Expand Down
55 changes: 49 additions & 6 deletions apps/code/src/app/dashboard/(main)/billing/BillingClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 (
<div className="space-y-10">
<BillingHeader />

<div className="rounded-xl border bg-card p-6">
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 className="font-semibold">No active plan</h2>
<p className="mt-1 text-sm text-muted-foreground">
{devPlanStatus.hasBillingHistory
? "Your DevPass subscription has ended. Your invoices and receipts stay available here."
: "You don't have a DevPass plan yet."}
</p>
</div>
<Button asChild size="sm">
<Link href="/dashboard">Choose a plan</Link>
</Button>
</div>
</div>

{/* Past invoices */}
<DevPassInvoices />

{/* Billing details (invoice details) */}
<DevPassBillingDetails />
</div>
);
}

const pendingTier = devPlanStatus.devPlanPendingTier ?? null;
const pendingPlanData = plans.find((p) => p.tier === pendingTier);
const cycle = devPlanStatus.devPlanCycle ?? "monthly";
Expand Down Expand Up @@ -314,12 +351,7 @@ export default function BillingClient({

return (
<div className="space-y-10">
<div>
<h1 className="text-lg font-semibold tracking-tight">Billing</h1>
<p className="mt-0.5 text-sm text-muted-foreground">
Manage your DevPass subscription and plan.
</p>
</div>
<BillingHeader />

{/* Current subscription summary */}
<div className="rounded-xl border bg-card p-6">
Expand Down Expand Up @@ -455,6 +487,17 @@ export default function BillingClient({
);
}

function BillingHeader() {
return (
<div>
<h1 className="text-lg font-semibold tracking-tight">Billing</h1>
<p className="mt-0.5 text-sm text-muted-foreground">
Manage your DevPass subscription and plan.
</p>
</div>
);
}

function BillingSkeleton() {
return (
<div className="space-y-10">
Expand Down
14 changes: 10 additions & 4 deletions apps/code/src/app/dashboard/(main)/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,16 @@ export default function SettingsPage() {
</div>
</div>

<DevPlanSettings
devPlanServiceTier={devPlanStatus.devPlanServiceTier ?? "default"}
defaultRoutingStrategy={devPlanStatus.defaultRoutingStrategy ?? "auto"}
/>
{/* Routing and service-tier settings apply to the live plan only — the
endpoint rejects updates once the subscription has ended. */}
{devPlanStatus.devPlan !== "none" && (
<DevPlanSettings
devPlanServiceTier={devPlanStatus.devPlanServiceTier ?? "default"}
defaultRoutingStrategy={
devPlanStatus.defaultRoutingStrategy ?? "auto"
}
/>
)}

<DeleteAccount />
</div>
Expand Down
84 changes: 60 additions & 24 deletions apps/code/src/app/dashboard/DashboardShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Loader2,
LogOut,
Settings,
Sparkles,
Stamp,
UserRound,
} from "lucide-react";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 = (
<div className="space-y-10">
<div className="mx-auto max-w-md text-center pt-4">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
<Code className="h-6 w-6 text-muted-foreground" />
</div>
<h1 className="text-xl font-semibold mb-2">
{devPlanStatus?.hasBillingHistory
? "Choose a new Dev Plan"
: "Choose your Dev Plan"}
</h1>
<p className="text-sm text-muted-foreground leading-relaxed">
Pick a plan to get your API key and start coding with 200+ models.
Every dollar gives you 3x in usage.
</p>
</div>

<InactivePlanChooser
plans={plans}
subscribingTier={subscribingTier}
onSubscribe={handleSubscribe}
/>
</div>
);
const activeSetupActivationStatus =
setupActivationStatus ?? (setupSessionId ? "finalizing" : null);
const activeSetupActivationCopy = activeSetupActivationStatus
Expand Down Expand Up @@ -579,12 +631,12 @@ export default function DashboardShell({
<Skeleton className="h-32 w-full rounded-xl" />
</main>
</div>
) : hasActivePlan ? (
) : showDashboardChrome ? (
<div className="container mx-auto flex flex-col gap-8 px-4 py-8 lg:flex-row">
{/* Sidebar */}
<aside className="lg:w-56 lg:shrink-0">
<nav className="flex gap-1 overflow-x-auto lg:sticky lg:top-8 lg:flex-col lg:overflow-visible">
{navItems.map((item) => {
{mainNavItems.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
return (
Expand Down Expand Up @@ -623,31 +675,15 @@ export default function DashboardShell({
</nav>
</aside>

{/* Page content */}
<main className="min-w-0 flex-1">{children}</main>
{/* Page content — the usage overview needs a plan, the account and
billing pages do not. */}
<main className="min-w-0 flex-1">
{hasActivePlan || isPlanIndependentRoute ? children : planChooser}
</main>
</div>
) : (
<main className="container mx-auto max-w-6xl px-4 py-8">
<div className="space-y-10">
<div className="mx-auto max-w-md text-center pt-4">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
<Code className="h-6 w-6 text-muted-foreground" />
</div>
<h1 className="text-xl font-semibold mb-2">
Choose your Dev Plan
</h1>
<p className="text-sm text-muted-foreground leading-relaxed">
Pick a plan to get your API key and start coding with 200+
models. Every dollar gives you 3x in usage.
</p>
</div>

<InactivePlanChooser
plans={plans}
subscribingTier={subscribingTier}
onSubscribe={handleSubscribe}
/>
</div>
{planChooser}
</main>
)}
</div>
Expand Down
Loading