Skip to content

Open source CapCut alternative.

TypeScript

fix(site): end Pro on its scheduled cancel date and warn only in the last two weeks

David Le294c13c3fdb3
diff --git a/site/prisma/Billing.prisma b/site/prisma/Billing.prisma
index 5a1f7bd7..cb8ca0a5 100644
--- a/site/prisma/Billing.prisma
+++ b/site/prisma/Billing.prisma
@@ -15,6 +15,11 @@ model ProSubscription {
currentPeriodStart DateTime?
currentPeriodEnd DateTime?
cancelAtPeriodEnd Boolean @default(false)
+ // Stripe's cancel_at: when a scheduled cancel ends the subscription. Null
+ // while nothing is scheduled.
+ cancelAt DateTime?
+ // Stripe's ended_at: when the subscription ended. Null while it runs.
+ endedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/site/scripts/backfill-pro-subscription-ends.ts b/site/scripts/backfill-pro-subscription-ends.ts
new file mode 100644
index 00000000..c056a758
--- /dev/null
+++ b/site/scripts/backfill-pro-subscription-ends.ts
@@ -0,0 +1,68 @@
+#!/usr/bin/env bun
+/**
+ * One-off: fill cancelAt and endedAt on the Pro subscription rows synced
+ * before those columns existed. Only rows with a cancel scheduled or an ended
+ * status are read; each one's Stripe subscription is fetched by its stored id
+ * and run through the same sync the webhook uses, so the row lands exactly
+ * where the next webhook would put it. Idempotent: a synced row reads the same
+ * on the next run.
+ *
+ * Run from site/ with production credentials in the environment, after the
+ * columns are migrated:
+ * bun run scripts/backfill-pro-subscription-ends.ts # dry run
+ * bun run scripts/backfill-pro-subscription-ends.ts --apply
+ */
+
+import {
+ ACTIVE_PRO_STATUSES,
+ subscriptionCancelAt,
+ syncProSubscription,
+} from "../src/lib/billing/pro-subscription";
+import { getStripe, unixToDate } from "../src/lib/billing/stripe";
+import { prisma } from "../src/lib/prisma";
+
+const apply = process.argv.includes("--apply");
+
+const rows = await prisma.proSubscription.findMany({
+ select: {
+ cancelAt: true,
+ cancelAtPeriodEnd: true,
+ endedAt: true,
+ status: true,
+ stripeSubscriptionId: true,
+ userId: true,
+ },
+ where: {
+ OR: [
+ { cancelAtPeriodEnd: true },
+ { cancelAt: { not: null } },
+ { status: { notIn: [...ACTIVE_PRO_STATUSES] } },
+ ],
+ stripeSubscriptionId: { not: null },
+ },
+});
+console.log(`${rows.length} rows with a scheduled cancel or an ended status`);
+
+const iso = (date: Date | null) => date?.toISOString() ?? "null";
+const stripe = getStripe();
+let changed = 0;
+for (const row of rows) {
+ const subscription = await stripe.subscriptions.retrieve(row.stripeSubscriptionId!);
+ const cancelAt = subscriptionCancelAt(subscription);
+ const endedAt = unixToDate(subscription.ended_at);
+ const same =
+ row.status === subscription.status &&
+ row.cancelAt?.getTime() === cancelAt?.getTime() &&
+ row.endedAt?.getTime() === endedAt?.getTime();
+ if (same) continue;
+ changed += 1;
+ console.log(
+ `${row.userId} ${subscription.id}: status ${row.status} → ${subscription.status}, ` +
+ `cancelAt ${iso(row.cancelAt)} → ${iso(cancelAt)}, endedAt ${iso(row.endedAt)} → ${iso(endedAt)}`,
+ );
+ if (apply) await syncProSubscription(subscription);
+}
+
+console.log(apply ? `synced ${changed} rows` : `dry run; pass --apply to sync ${changed} rows`);
+
+await prisma.$disconnect();
diff --git a/site/src/app/api/billing/pro/route.ts b/site/src/app/api/billing/pro/route.ts
index 0ec2b29d..a511d59c 100644
--- a/site/src/app/api/billing/pro/route.ts
+++ b/site/src/app/api/billing/pro/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
-import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
+import { getActiveProSubscription, scheduledProEnd } from "@/lib/billing/pro-subscription";
import { creditMicrosToString, zeroCreditMicros } from "@/lib/credits/amounts";
import { withDonkeyAuth } from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
@@ -43,8 +43,9 @@ export const GET = withDonkeyAuth(async (request) => {
return NextResponse.json({
allowanceRemaining: creditMicrosToString(allowanceRemainingMicros),
- cancelAtPeriodEnd: subscription?.cancelAtPeriodEnd ?? false,
currentPeriodEnd: subscription?.currentPeriodEnd?.toISOString() ?? null,
+ // When a scheduled cancel ends Pro; null while the plan renews.
+ endsAt: subscription ? (scheduledProEnd(subscription)?.toISOString() ?? null) : null,
isActive: Boolean(subscription),
monthlyAllowance: subscription
? creditMicrosToString(monthlyAllowanceMicros)
diff --git a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
index d7c1dcdb..62336d65 100644
--- a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
+++ b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
@@ -94,17 +94,18 @@ export function ProCard() {
{formatUsd(data.allowanceRemaining)} of{" "}
{formatUsd(data.monthlyAllowance)} included left this month
</div>
- <div>
- Renews:{" "}
- {data.currentPeriodEnd
- ? new Date(data.currentPeriodEnd).toLocaleDateString()
- : "—"}
- </div>
- {data.cancelAtPeriodEnd ? (
+ {data.endsAt ? (
<div className="text-foreground">
- Cancels at the end of the current period.
+ Cancels on {new Date(data.endsAt).toLocaleDateString()}.
</div>
- ) : null}
+ ) : (
+ <div>
+ Renews:{" "}
+ {data.currentPeriodEnd
+ ? new Date(data.currentPeriodEnd).toLocaleDateString()
+ : "—"}
+ </div>
+ )}
{promotion ? (
<div>
{promotion.lastDay !== null
diff --git a/site/src/cut/components/StoragePill.tsx b/site/src/cut/components/StoragePill.tsx
index 628cbeb7..f67e1eb3 100644
--- a/site/src/cut/components/StoragePill.tsx
+++ b/site/src/cut/components/StoragePill.tsx
@@ -2,8 +2,9 @@
// The top bar's subscription surface for cloud projects, one slot with two
// mutually exclusive faces: free accounts see their storage usage (click →
-// upgrade dialog); a Pro set to cancel sees the days it has left (click →
-// Stripe portal, where Resume lives).
+// upgrade dialog); a Pro set to cancel sees the days it has left once fewer
+// than the `proEndingNotice` days remain (click → Stripe portal, where Resume
+// lives).
import { type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import {
@@ -16,7 +17,9 @@ import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";
import { openStorageUpgrade } from "@/cut/lib/storageQuota";
import { daysUntil } from "@/cut/lib/time";
import { track } from "@/lib/analytics";
+import { SETTINGS } from "@/lib/config/registry";
import { cn } from "@/lib/utils";
+import { useAccountConfig } from "@/queries/accountConfig";
import { useOpenBillingPortal, useProSubscription } from "@/queries/billing";
import { formatBytes } from "@/lib/bytes";
@@ -45,13 +48,19 @@ function CloudStoragePill() {
// The meter has to move as media lands, so this reader is the polling one.
const usage = useCloudUsage(pro.data?.isActive === false, { poll: true });
const portal = useOpenBillingPortal();
+ const config = useAccountConfig({ enabled: true });
if (!pro.data) return null;
if (pro.data.isActive) {
- const end = pro.data.cancelAtPeriodEnd ? pro.data.currentPeriodEnd : null;
+ const end = pro.data.endsAt;
if (!end) return null;
const days = daysUntil(end);
+ // The config read can fail without taking the pill with it: the registry
+ // default stands in until an override arrives.
+ const daysBefore =
+ config.data?.settings.proEndingNotice.daysBefore ?? SETTINGS.proEndingNotice.default.daysBefore;
+ if (days >= daysBefore) return null;
return (
<PillTooltip message="Your Pro plan is set to cancel. Resume it to keep your cloud storage.">
<TooltipTrigger
diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.ts
index edd58655..ec8d0baa 100644
--- a/site/src/cut/server/cloud/gc.ts
+++ b/site/src/cut/server/cloud/gc.ts
@@ -184,7 +184,7 @@ async function reclaimOverQuota() {
// ones the sweep will never touch, and they are not worth a query each.
const subs = await prisma.proSubscription.findMany({
where: { userId: { in: overCap.map((r) => r.userId) } },
- select: { userId: true, status: true, currentPeriodEnd: true },
+ select: { userId: true, status: true, endedAt: true, cancelAt: true, currentPeriodEnd: true },
});
const now = Date.now();
const lapsed = subs.filter((s) => {
diff --git a/site/src/cut/server/cloud/grace.ts b/site/src/cut/server/cloud/grace.ts
index a4b4b6c6..bdfdec8f 100644
--- a/site/src/cut/server/cloud/grace.ts
+++ b/site/src/cut/server/cloud/grace.ts
@@ -12,17 +12,26 @@ const GRACE_MS = 30 * 24 * 60 * 60 * 1000;
// ended long before the sweep existed still get a full warning window.
const RECLAIM_EPOCH_MS = Date.UTC(2026, 6, 26);
-type SubscriptionAnchor = { status: string; currentPeriodEnd: Date | null };
+type SubscriptionAnchor = {
+ status: string;
+ endedAt: Date | null;
+ cancelAt: Date | null;
+ currentPeriodEnd: Date | null;
+};
/** When a lapsed subscription's storage becomes reclaimable, or null when the
* subscription is not one we count as ended. Dunning is not churn: while
* Stripe is still retrying the invoice (`past_due`) a recovered card puts the
* account straight back on Pro, so the deletion clock has not started. */
export function graceDeadline(sub: SubscriptionAnchor): Date | null {
- if (!sub.currentPeriodEnd || isActiveProStatus(sub.status) || sub.status === "past_due") {
+ // Stripe's ended_at is the truth once the subscription ended. Rows synced
+ // before it was stored fall back to the scheduled cancel date, which can sit
+ // before the last billing period closes, then to the period end.
+ const endedAt = sub.endedAt ?? sub.cancelAt ?? sub.currentPeriodEnd;
+ if (!endedAt || isActiveProStatus(sub.status) || sub.status === "past_due") {
return null;
}
- return new Date(Math.max(sub.currentPeriodEnd.getTime(), RECLAIM_EPOCH_MS) + GRACE_MS);
+ return new Date(Math.max(endedAt.getTime(), RECLAIM_EPOCH_MS) + GRACE_MS);
}
/** Non-null when the account is out of Pro, over the free cap, and anchored to
diff --git a/site/src/lib/billing/pro-subscription.test.ts b/site/src/lib/billing/pro-subscription.test.ts
new file mode 100644
index 00000000..d2d4236a
--- /dev/null
+++ b/site/src/lib/billing/pro-subscription.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from "bun:test";
+import type Stripe from "stripe";
+
+import { scheduledProEnd, subscriptionCancelAt } from "@/lib/billing/pro-subscription";
+
+const PERIOD_START = 1_767_225_600; // 2026-01-01T00:00:00Z
+const PERIOD_END = 1_769_904_000; // 2026-02-01T00:00:00Z
+const CANCEL_AT = 1_780_012_800; // 2026-05-29T00:00:00Z
+
+function subscription(overrides: Partial<Stripe.Subscription> = {}): Stripe.Subscription {
+ return {
+ id: "sub_1",
+ cancel_at: null,
+ cancel_at_period_end: false,
+ customer: "cus_1",
+ items: {
+ data: [
+ {
+ current_period_end: PERIOD_END,
+ current_period_start: PERIOD_START,
+ price: { id: "price_pro", unit_amount: 2000 },
+ },
+ ],
+ },
+ metadata: { userId: "user_1" },
+ status: "active",
+ ...overrides,
+ } as unknown as Stripe.Subscription;
+}
+
+describe("subscriptionCancelAt", () => {
+ test("a cancel_at date is the end, however far past the period", () => {
+ expect(subscriptionCancelAt(subscription({ cancel_at: CANCEL_AT }))).toEqual(new Date(CANCEL_AT * 1000));
+ });
+
+ test("a period-end cancel carries Stripe's cancel_at for the period end", () => {
+ expect(subscriptionCancelAt(subscription({ cancel_at: PERIOD_END, cancel_at_period_end: true }))).toEqual(
+ new Date(PERIOD_END * 1000),
+ );
+ });
+
+ test("nothing scheduled is null", () => {
+ expect(subscriptionCancelAt(subscription())).toBeNull();
+ });
+});
+
+describe("scheduledProEnd", () => {
+ const currentPeriodEnd = new Date(PERIOD_END * 1000);
+ const cancelAt = new Date(CANCEL_AT * 1000);
+
+ test("reads the stored end date", () => {
+ expect(scheduledProEnd({ cancelAt, cancelAtPeriodEnd: true, currentPeriodEnd })).toBe(cancelAt);
+ });
+
+ test("a row synced before the end date was stored reads as the period end", () => {
+ expect(scheduledProEnd({ cancelAt: null, cancelAtPeriodEnd: true, currentPeriodEnd })).toBe(
+ currentPeriodEnd,
+ );
+ });
+
+ test("a renewing plan has no end", () => {
+ expect(scheduledProEnd({ cancelAt: null, cancelAtPeriodEnd: false, currentPeriodEnd })).toBeNull();
+ });
+});
diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.ts
index e72c97ac..df2a2f07 100644
--- a/site/src/lib/billing/pro-subscription.ts
+++ b/site/src/lib/billing/pro-subscription.ts
@@ -32,6 +32,27 @@ export function subscriptionCancelScheduled(subscription: Stripe.Subscription):
return subscription.cancel_at_period_end || subscription.cancel_at !== null;
}
+// The date a scheduled cancel ends the subscription. Stripe fills cancel_at
+// for a period-end cancel too, and a portal-scheduled cancel_at can sit months
+// past the current period (a comped run of Pro), so this is the one field.
+export function subscriptionCancelAt(subscription: Stripe.Subscription): Date | null {
+ return unixToDate(subscription.cancel_at);
+}
+
+type ProEndAnchor = {
+ cancelAt: Date | null;
+ cancelAtPeriodEnd: boolean;
+ currentPeriodEnd: Date | null;
+};
+
+// When Pro ends for a row with a cancel scheduled, or null when it renews.
+// Rows synced before cancelAt was stored still carry only the flag; those read
+// as the period end until the next webhook writes the date.
+export function scheduledProEnd(subscription: ProEndAnchor): Date | null {
+ if (subscription.cancelAt) return subscription.cancelAt;
+ return subscription.cancelAtPeriodEnd ? subscription.currentPeriodEnd : null;
+}
+
export function proPriceId(): string | undefined {
return process.env.STRIPE_PRO_PRICE_ID || undefined;
}
@@ -99,6 +120,8 @@ export async function syncProSubscription(
const price = item?.price;
const periodStart = unixToDate(item?.current_period_start ?? null);
const periodEnd = unixToDate(item?.current_period_end ?? null);
+ const cancelAt = subscriptionCancelAt(subscription);
+ const endedAt = unixToDate(subscription.ended_at);
const allowanceMicros = periodStart
? promotedAllowanceMicros(
allowanceMicrosFromPrice(price),
@@ -109,9 +132,11 @@ export async function syncProSubscription(
await prisma.proSubscription.upsert({
create: {
+ cancelAt,
cancelAtPeriodEnd: subscriptionCancelScheduled(subscription),
currentPeriodEnd: periodEnd,
currentPeriodStart: periodStart,
+ endedAt,
monthlyAllowanceMicros: allowanceMicros,
planKey: proPlanKey,
status: subscription.status,
@@ -120,9 +145,11 @@ export async function syncProSubscription(
userId,
},
update: {
+ cancelAt,
cancelAtPeriodEnd: subscriptionCancelScheduled(subscription),
currentPeriodEnd: periodEnd,
currentPeriodStart: periodStart,
+ endedAt,
monthlyAllowanceMicros: allowanceMicros,
status: subscription.status,
stripeCustomerId: customerId,
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index f82d25bb..41ddc90a 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -450,11 +450,25 @@ export const SETTINGS = defineSettings({
description:
"Multiplies the AI allowance a Pro billing period starts with, for periods that start on or before the last day. Later periods start with the plain allowance.",
},
+ proEndingNotice: {
+ schema: z
+ .object({
+ // The editor's top bar shows the days left once fewer than this many
+ // remain before a cancelled Pro plan ends.
+ daysBefore: z.number().int().min(1).max(365),
+ })
+ .strict(),
+ default: { daysBefore: 14 },
+ public: true,
+ title: "Pro ending notice",
+ description:
+ "How many days before a cancelled Pro plan ends the editor starts showing the days left. Until then a plan set to cancel looks like one that renews.",
+ },
});
// The settings su shows on its Product tab: what an account gets. The
// settings tab under Experiments still lists every key.
-export const PRODUCT_SETTING_KEYS = ["signupCredits", "creditExpiryNotice", "manualCreditOffer", "promotionCreditOffer", "subscribeBonus", "proAllowancePromotion"] as const satisfies readonly SettingKey[];
+export const PRODUCT_SETTING_KEYS = ["signupCredits", "creditExpiryNotice", "manualCreditOffer", "promotionCreditOffer", "subscribeBonus", "proAllowancePromotion", "proEndingNotice"] as const satisfies readonly SettingKey[];
export type SettingKey = keyof typeof SETTINGS;
export type Settings = SettingsOf<typeof SETTINGS>;
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index 10a7120a..1819cf94 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -10,8 +10,11 @@ export const proSubscriptionQueryKey = ["billing", "pro"] as const;
export type ProSubscription = {
isActive: boolean;
status: string | null;
- cancelAtPeriodEnd: boolean;
+ // End of the current billing period: the allowance resets and the plan
+ // renews here.
currentPeriodEnd: string | null;
+ // When a scheduled cancel ends Pro; null while the plan renews.
+ endsAt: string | null;
// Included monthly allowance (USD) and how much is left this period.
monthlyAllowance: string | null;
allowanceRemaining: string;