Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion web/src/app/(app)/billing/page.addon.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ describe("BillingPage — total-vs-delta clarity", () => {
expect(
screen.getByRole("button", { name: "Update to 2 add-ons" }),
).toBeInTheDocument();
expect(screen.getByText(/At next renewal:/)).toHaveTextContent(
expect(screen.getByText(/New monthly total:/)).toHaveTextContent(
"$4/mo (\u22121 add-on, \u2212$2/mo)",
);
});
Expand Down
48 changes: 3 additions & 45 deletions web/src/app/(app)/billing/page.catalog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ beforeEach(() => {
// unexpected error path doesn't surface a jsdom dialog.
beforeAll(() => {
window.alert = jest.fn();
window.confirm = jest.fn(() => true);
});

type StageOpts = {
Expand Down Expand Up @@ -216,14 +215,14 @@ describe("BillingPage — tier comparison", () => {
expect(screen.getByRole("button", { name: "Downgrade" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Switch to Pro|Upgrade/ })).not.toBeInTheDocument();

// Existing plan changes use the controlled subscription-change endpoint.
// A switch routes to the Stripe portal (upgrade_url), not checkout.
await userEvent.click(switchBtn);
await waitFor(() =>
expect(
mockFetch.mock.calls.some(([u, i]) => u === CHECKOUT_URL && i?.method === "POST"),
mockFetch.mock.calls.some(([u, i]) => u === PORTAL_URL && i?.method === "POST"),
).toBe(true),
);
expect(mockFetch.mock.calls.some(([u]) => u === PORTAL_URL)).toBe(false);
expect(mockFetch.mock.calls.some(([u]) => u === CHECKOUT_URL)).toBe(false);
});

it("offers no plan-change actions when the current plan can't be determined", async () => {
Expand Down Expand Up @@ -255,44 +254,3 @@ describe("BillingPage — tier comparison", () => {
expect(screen.queryByText("Scale")).not.toBeInTheDocument();
});
});


describe("Stripe-owned pending changes", () => {
it("keeps the effective plan and billing management available while payment is pending", async () => {
stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: {
code: "pro", status: "active", has_stripe_customer: true,
change: { status: "payment_required", plan_code: "scale", addon_quantity: 0, url: "https://invoice.stripe.com/i/synthetic" },
} } });
renderPage();
await screen.findByRole("button", {name: "Manage billing"});
expect(screen.queryByText(/Payment is required to complete/)).not.toBeInTheDocument();
expect(screen.queryByRole("link", {name: "Complete payment"})).not.toBeInTheDocument();
expect(screen.getByRole("button", {name: "Manage billing"})).toBeEnabled();
expect(screen.getByRole("button", {name: "Switch to Scale"})).toBeEnabled();
await userEvent.click(screen.getByRole("button", {name: "Switch to Scale"}));
expect(mockFetch.mock.calls.some(([url, init]) => url === CHECKOUT_URL && JSON.parse(init.body).plan === "scale")).toBe(true);
expect(screen.getAllByText("Pro").length).toBeGreaterThan(0);
});
it("explains a conflicting change only when selected and leaves it untouched if declined", async () => {
stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: {
code: "pro", status: "active", has_stripe_customer: true,
change: { status: "payment_required", plan_code: "scale", addon_quantity: 0 },
} } });
const confirm = jest.spyOn(window, "confirm").mockReturnValueOnce(false);
renderPage();
await userEvent.click(await screen.findByRole("button", {name: "Downgrade"}));
expect(confirm).toHaveBeenCalledWith(expect.stringContaining("unfinished subscription change"));
expect(mockFetch.mock.calls.some(([, init]) => init?.method === "POST")).toBe(false);
confirm.mockReturnValue(true);
});
it("shows a renewal change separately from current capacity and offers cancellation", async () => {
stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: {
code: "pro", status: "active", has_stripe_customer: true,
change: { status: "scheduled", plan_code: "free", addon_quantity: 0, effective_at: "2030-01-01T00:00:00Z" },
} } });
renderPage();
expect(await screen.findByText(/Your subscription change is scheduled/)).toHaveTextContent("Your current plan and limits remain active");
expect(screen.getByRole("button", {name: "Cancel pending change"})).toBeEnabled();
expect(screen.queryByRole("link", {name: "Complete payment"})).not.toBeInTheDocument();
});
});
115 changes: 19 additions & 96 deletions web/src/app/(app)/billing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,7 @@ type PlanEntry = {
max_storage_bytes: number;
};

type BillingChange = {
status: "payment_required" | "scheduled";
url?: string;
effective_at?: string;
expires_at?: string;
plan_code?: string;
addon_quantity?: number;
};

type CurrentState = {
change?: BillingChange;
code: string;
status: string;
current_period_end?: string;
Expand Down Expand Up @@ -325,30 +315,6 @@ export default function BillingPage() {
// while the others disable. Tier CTAs are keyed `tier-<code>`; the
// banner's Manage-billing button is "manage".
const [actionPending, setActionPending] = useState<string | null>(null);
const [submittedChange, setSubmittedChange] = useState<BillingChange | null>(null);
const planTargetRef = useRef<string | null>(null);
const upcomingChange = planData?.current.change ?? submittedChange;
useEffect(() => { setSubmittedChange(null); }, [planData]);

// Keep unfinished payments out of the normal page presentation. The same
// action resumes Stripe's existing invoice; a different action explains the
// conflict and lets the customer discard it before making a new request.
async function prepareChange(plan: string, quantity: number): Promise<boolean> {
if (upcomingChange?.status !== "payment_required" ||
(upcomingChange.plan_code === plan && upcomingChange.addon_quantity === quantity)) return true;
if (!window.confirm("You have an unfinished subscription change. Cancel it and continue with this change? Your current plan stays active.")) return false;
setActionPending("cancel-change");
try {
const response = await fetch(`${BILLING_API}/api/billing/change/cancel`, { method: "POST", credentials: "include" });
if (!response.ok) throw new Error("Could not cancel the unfinished change. Please retry.");
setSubmittedChange(null);
await mutatePlan();
return true;
} catch (error) {
alert(error instanceof Error ? error.message : "Could not cancel the unfinished change.");
return false;
} finally { setActionPending(null); }
}

// Both Upgrade and Manage Billing POST to the sidecar and follow the
// returned `url`. POST (not GET) because the OSS session cookie is
Expand All @@ -373,23 +339,11 @@ export default function BillingPage() {
const text = await res.text().catch(() => "");
throw new Error(`HTTP ${res.status}${text ? `: ${text}` : ""}`);
}
const json = (await res.json()) as { url?: string; updated?: boolean; status?: string } & Omit<Partial<BillingChange>, "status">;
if (json.url) {
window.location.href = json.url;
return;
const json = (await res.json()) as { url?: string };
if (!json.url) {
throw new Error("billing endpoint returned no url");
}
if (json.status === "scheduled") {
setSubmittedChange(json as BillingChange);
} else if (json.status === "applied" || json.updated) {
setSubmittedChange(null);
planTargetRef.current = (body as { plan?: string } | undefined)?.plan ?? null;
if (planTargetRef.current) setReconcile("pending");
} else {
throw new Error("billing endpoint returned no change outcome");
}
setActionPending(null);
void mutate();
void mutatePlan();
window.location.href = json.url;
} catch (err) {
// Best-effort recovery: surface the error to the user, clear
// the pending state, and let them retry. We don't reset SWR
Expand Down Expand Up @@ -485,7 +439,7 @@ export default function BillingPage() {

// Webhook landed — stop polling and let the page render normally.
useEffect(() => {
if (reconcile === "pending" && planData?.current.status === "active" && (!planTargetRef.current || planData.current.code === planTargetRef.current)) {
if (reconcile === "pending" && planData?.current.status === "active") {
setReconcile("idle");
}
}, [reconcile, planData]);
Expand Down Expand Up @@ -562,7 +516,6 @@ export default function BillingPage() {
async function applyAddon(target: number) {
const addon = planData?.addon;
if (!addon) return;
if (!(await prepareChange(planData?.current.code ?? "free", target))) return;
// In-place increases charge the subscription immediately (prorated
// by Stripe) with no hosted page in between — the one money action
// on this page without a Stripe-owned review step. Make the total
Expand Down Expand Up @@ -593,20 +546,13 @@ export default function BillingPage() {
const text = await res.text().catch(() => "");
throw new Error(`HTTP ${res.status}${text ? `: ${text}` : ""}`);
}
const json = (await res.json()) as { url?: string; updated?: boolean; status?: string } & Omit<Partial<BillingChange>, "status">;
const json = (await res.json()) as { url?: string; updated?: boolean };
if (json.url) {
// Keep the pending state through navigation, like postBilling.
window.location.href = json.url;
return;
}
if (json.status === "scheduled") {
setSubmittedChange(json as BillingChange);
setAddonDesired(null);
setActionPending(null);
void mutatePlan();
return;
}
if (json.updated || json.status === "applied") {
if (json.updated) {
addonTargetRef.current = target;
// Stamp a FRESH deadline here rather than relying on the sync
// effect's `??=`: a second update issued while the first is
Expand Down Expand Up @@ -659,27 +605,16 @@ export default function BillingPage() {
return null;
}
if (hasSub) {
// Paid plan changes use Stripe pending updates/schedules through the
// sidecar. Cancellation to Free remains in the billing portal.
// Existing subscribers change or cancel their plan through the
// Stripe Billing Portal (it owns proration). Both "switch up/down"
// and "downgrade to Free" route there.
const label =
tier.monthly_price_cents <= 0 ? "Downgrade" : `Switch to ${tier.display_name}`;
const key = `tier-${tier.code}`;
return {
label: actionPending === key ? "Opening…" : label,
onClick: async () => {
if (!(await prepareChange(tier.code, planData?.current.addon_quantity ?? 0))) return;
if (tier.monthly_price_cents <= 0) {
void postBilling(data!.upgrade_url, key);
return;
}
const current = planData?.catalog.find((p) => p.code === currentCode);
const increase = tier.monthly_price_cents > (current?.monthly_price_cents ?? 0);
const message = increase
? `Switch to ${tier.display_name} (${formatPrice(tier.monthly_price_cents)})? The prorated difference is charged now. Your plan changes after payment succeeds.`
: `Switch to ${tier.display_name} at your next renewal? Your current plan remains available until then.`;
if (window.confirm(message)) void postBilling(`${BILLING_API}/api/billing/checkout`, key, { plan: tier.code });
},
disabled: actionPending !== null || (upcomingChange?.status === "scheduled"),
onClick: () => postBilling(data!.upgrade_url, key),
disabled: actionPending !== null,
};
}
// No subscription yet. The Free tier is already their plan (handled
Expand All @@ -692,7 +627,7 @@ export default function BillingPage() {
label: actionPending === key ? "Opening…" : `Upgrade to ${tier.display_name}`,
onClick: () =>
postBilling(`${BILLING_API}/api/billing/checkout`, key, { plan: tier.code }),
disabled: actionPending !== null || (upcomingChange?.status === "scheduled"),
disabled: actionPending !== null,
};
}

Expand Down Expand Up @@ -752,18 +687,6 @@ export default function BillingPage() {
</div>
)}

{upcomingChange?.status === "scheduled" && (
<section role="status" className="rounded-xl border p-4 space-y-3">
<p>
{`Your subscription change is scheduled for ${upcomingChange.effective_at ? new Date(upcomingChange.effective_at).toLocaleDateString() : "your next renewal"}. Your current plan and limits remain active until then.`}
</p>
{upcomingChange.plan_code && <p className="text-sm text-muted">Requested plan: {planData?.catalog.find((p) => p.code === upcomingChange.plan_code)?.display_name ?? upcomingChange.plan_code}{typeof upcomingChange.addon_quantity === "number" ? ` · ${upcomingChange.addon_quantity} inbox add-ons` : ""}</p>}
<button type="button" disabled={actionPending !== null} onClick={() => void postBilling(`${BILLING_API}/api/billing/change/cancel`, "cancel-change")} className="text-sm underline">
{actionPending === "cancel-change" ? "Cancelling…" : "Cancel pending change"}
</button>
</section>
)}

{/* Post-checkout reconciliation. Rendered outside the `data` gate so
it shows even if the usage read is slow or failing — the user
just paid, and silence is the worst response. A late webhook
Expand Down Expand Up @@ -840,7 +763,7 @@ export default function BillingPage() {
// upgrade_url present → user has an active Stripe
// subscription. Clicking POSTs to the sidecar, which
// returns a fresh Stripe Billing Portal URL. From the
// Portal, users manage cards, invoices and cancellation.
// Portal, users switch plans (Pro ↔ Scale) and cancel.
<div className="flex items-center gap-2 flex-wrap justify-end">
<button
type="button"
Expand Down Expand Up @@ -1043,7 +966,7 @@ export default function BillingPage() {
<button
type="button"
aria-label="Decrease add-on quantity"
disabled={(upcomingChange?.status === "scheduled") || actionPending !== null || addonQty <= 0}
disabled={actionPending !== null || addonQty <= 0}
onClick={() => stageAddonQty(Math.max(0, addonQty - 1))}
className="px-3 py-1.5 text-sm hover:bg-background transition disabled:opacity-50 disabled:cursor-not-allowed"
>
Expand All @@ -1057,7 +980,7 @@ export default function BillingPage() {
min={0}
max={planData.addon.max_quantity}
value={addonQty}
disabled={(upcomingChange?.status === "scheduled") || actionPending !== null}
disabled={actionPending !== null}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10);
// A cleared field mid-retype must NOT stage 0 —
Expand All @@ -1075,7 +998,7 @@ export default function BillingPage() {
type="button"
aria-label="Increase add-on quantity"
disabled={
(upcomingChange?.status === "scheduled") || actionPending !== null ||
actionPending !== null ||
addonQty >= planData.addon.max_quantity
}
onClick={() =>
Expand All @@ -1096,7 +1019,7 @@ export default function BillingPage() {
<button
type="button"
disabled={
(upcomingChange?.status === "scheduled") || actionPending !== null ||
actionPending !== null ||
addonSync === "pending" ||
addonQty === addonServerQty
}
Expand Down Expand Up @@ -1127,7 +1050,7 @@ export default function BillingPage() {
and the delta says what this click actually changes. */}
{addonQty !== addonServerQty && (
<span className="text-xs text-foreground font-medium">
{addonQty < addonServerQty ? "At next renewal: " : "New monthly total: "}
New monthly total:{" "}
{addonQty === 0
? "$0/mo"
: formatPrice(
Expand Down
Loading