Open source CapCut alternative.
TypeScript
fix(site): move plans up from what Stripe holds
David Le29c1ac7df184
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.tsindex 703afa44..e94ff074 100644--- a/site/src/app/api/billing/checkout/route.ts+++ b/site/src/app/api/billing/checkout/route.ts@@ -8,9 +8,17 @@ import { introCouponId } from "@/lib/billing/intro-offer";import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";import { PAID_PLANS, PLAN_TERMS, planRank, type PaidPlan } from "@/lib/billing/plans";-import { getActiveSubscription, readPlanPrices, subscriptionPlan, type PlanPrices } from "@/lib/billing/pro-subscription";+import { dropIntroDiscount, INTRO_OFFER_METADATA_KEY, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";+import {+ getActiveSubscription,+ isActiveProStatus,+ livePlan,+ readPlanPrices,+ syncPlanSubscription,+ type PlanPrices,+} from "@/lib/billing/pro-subscription";import { STRIPE_LOCALE } from "@/lib/billing/stripe-locale";-import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";+import { drainStripe, ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";import { contextFromRequest } from "@/lib/config/effective";import { verifyCreditOfferToken } from "@/lib/credits/offers";import { openOfferForSubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";@@ -58,7 +66,7 @@ export const POST = withDonkeyAuth(async (request) => {// would double-bill it.const current = await getActiveSubscription(session.user.id);if (current) {- return upgradeInPlace(current, plan, prices, request.nextUrl.origin);+ return upgradeInPlace(current.stripeSubscriptionId, plan, prices, request.nextUrl.origin);}const customerId = await ensureStripeCustomer({@@ -66,6 +74,14 @@ export const POST = withDonkeyAuth(async (request) => {name: session.user.name,userId: session.user.id,});++ // Stripe can hold a plan the row does not show yet: a checkout paid moments+ // ago whose webhook is still on its way. That account moves up in place too.+ const live = await adoptLiveSubscription(customerId);+ if (live) {+ return upgradeInPlace(live, plan, prices, request.nextUrl.origin);+ }+ await expireOpenCheckouts(customerId);// A Pro checkout started while an offer for subscribing is open carries the// offer, so the webhook lands the credit on the subscription it creates.const offer = plan === "pro" ? await openOfferForSubscribing(session.user.id, namedOfferId) : null;@@ -91,7 +107,7 @@ export const POST = withDonkeyAuth(async (request) => {metadata: {userId: session.user.id,...(offer ? { [SUBSCRIBE_BONUS_METADATA_KEY]: offer.id } : {}),- ...(intro ? { introOffer: introCouponId(intro) } : {}),+ ...(intro ? { [INTRO_OFFER_METADATA_KEY]: introCouponId(intro) } : {}),},},success_url: `${origin}/app/settings?checkout=success`,@@ -108,43 +124,74 @@ export const POST = withDonkeyAuth(async (request) => {return NextResponse.json({ url: checkout.url });});+// A plan subscription Stripe holds for the customer, synced to the account+// so every surface reads it; null when the customer has none.+async function adoptLiveSubscription(customerId: string): Promise<string | null> {+ const subscriptions = await drainStripe(getStripe().subscriptions.list({ customer: customerId, status: "all" }));+ for (const subscription of subscriptions) {+ if (!isActiveProStatus(subscription.status)) {+ continue;+ }+ if (await syncPlanSubscription(subscription)) {+ return subscription.id;+ }+ }+ return null;+}++// One open plan checkout per customer. Two tabs' checkouts, both paid, would+// make two subscriptions; opening a new one closes the last.+async function expireOpenCheckouts(customerId: string): Promise<void> {+ const stripe = getStripe();+ const open = await drainStripe(stripe.checkout.sessions.list({ customer: customerId, status: "open" }));+ await Promise.all(+ open.filter((s) => s.mode === "subscription").map((s) => stripe.checkout.sessions.expire(s.id)),+ );+}++const notAnUpgrade = () =>+ NextResponse.json(+ { error: "plan_not_an_upgrade", message: "This account is already on this plan or a higher one." },+ { status: HTTP_CONFLICT },+ );+// Swap the subscription's plan line to a higher plan. The period restarts// now, so the new plan's credits land at once, and Stripe charges the// difference on the spot; a card that fails leaves the old plan in place.+// The plan held is read from Stripe, since the row trails it until the+// webhook lands, and the result is synced before answering.async function upgradeInPlace(- current: { planKey: string; stripeSubscriptionId: string | null; cancelAt: Date | null },+ subscriptionId: string | null,plan: PaidPlan,prices: PlanPrices,origin: string,): Promise<Response> {- const currentRank = planRank(PAID_PLANS.find((p) => p === current.planKey) ?? "pro");- if (planRank(plan) <= currentRank || !current.stripeSubscriptionId) {- return NextResponse.json(- { error: "plan_not_an_upgrade", message: "This account is already on this plan or a higher one." },- { status: HTTP_CONFLICT },- );+ if (!subscriptionId) {+ return notAnUpgrade();}const stripe = getStripe();- const subscription = await stripe.subscriptions.retrieve(current.stripeSubscriptionId);- const line = subscriptionPlan(subscription, prices);- if (!line) {- return NextResponse.json(- { error: "plan_not_an_upgrade", message: "This account is already on this plan or a higher one." },- { status: HTTP_CONFLICT },- );+ const subscription = await stripe.subscriptions.retrieve(subscriptionId, { expand: ["discounts"] });+ const line = await livePlan(subscription);+ const toPrice = prices[plan]!;+ if (!line || planRank(plan) <= planRank(line.plan)) {+ return notAnUpgrade();}+ let updated: Stripe.Subscription;try {- await stripe.subscriptions.update(subscription.id, {- billing_cycle_anchor: "now",- // Moving up keeps the plan: a scheduled cancel is lifted.- ...(current.cancelAt ? { cancel_at: "" as const } : {}),- cancel_at_period_end: false,- items: [{ id: line.item.id, price: prices[plan]! }],- payment_behavior: "error_if_incomplete",- proration_behavior: "always_invoice",- });+ updated = await stripe.subscriptions.update(+ subscription.id,+ {+ ...liftScheduledCancel(subscription),+ ...dropIntroDiscount(subscription),+ billing_cycle_anchor: "now",+ items: [{ id: line.item.id, price: toPrice }],+ payment_behavior: "error_if_incomplete",+ proration_behavior: "always_invoice",+ },+ { idempotencyKey: upgradeKey(subscription, line.item.price.id, toPrice) },+ );} catch (e) {if (e instanceof Stripe.errors.StripeCardError) {return NextResponse.json(@@ -152,7 +199,16 @@ async function upgradeInPlace({ status: HTTP_PAYMENT_REQUIRED },);}+ // The same upgrade is already on its way from another click.+ if (e instanceof Stripe.errors.StripeIdempotencyError) {+ return NextResponse.json(+ { error: "upgrade_in_progress", message: "This upgrade is already in progress." },+ { status: HTTP_CONFLICT },+ );+ }throw e;}++ await syncPlanSubscription(updated);return NextResponse.json({ url: `${origin}/app/settings?checkout=success` });}diff --git a/site/src/i18n/messages/.source-lock.json b/site/src/i18n/messages/.source-lock.jsonindex 40a70a00..4056411a 100644--- a/site/src/i18n/messages/.source-lock.json+++ b/site/src/i18n/messages/.source-lock.json@@ -337,6 +337,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -3366,6 +3367,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -6395,6 +6397,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -9424,6 +9427,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -12453,6 +12457,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -15482,6 +15487,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"@@ -18511,6 +18517,7 @@"apiErrors.unsupported_image_type": "73cf38d0e3e1","apiErrors.image_too_large": "3fdb4028f18f","apiErrors.plan_not_an_upgrade": "d968260313e6",+ "apiErrors.upgrade_in_progress": "105dee90239b","apiErrors.upgrade_payment_failed": "9f81fe318848","languageSaveFailed": "8d8a247bafe6","languageBlocked": "6cdf84383309"diff --git a/site/src/i18n/messages/de/common.json b/site/src/i18n/messages/de/common.jsonindex 41f4e6ea..e547a203 100644--- a/site/src/i18n/messages/de/common.json+++ b/site/src/i18n/messages/de/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "Nicht unterstütztes Bildformat.","image_too_large": "Bild zu groß.","plan_not_an_upgrade": "Dieses Konto nutzt bereits diesen oder einen höheren Plan.",+ "upgrade_in_progress": "Dieses Upgrade läuft bereits.","upgrade_payment_failed": "Deine Karte wurde abgelehnt, daher wurde dein Plan nicht geändert. Aktualisiere deine Karte unter Abrechnung und versuche es erneut."},"languageSaveFailed": "Deine Sprache konnte nicht gespeichert werden. Versuch es noch einmal.",diff --git a/site/src/i18n/messages/en/common.json b/site/src/i18n/messages/en/common.jsonindex 9d239a39..c759c2c5 100644--- a/site/src/i18n/messages/en/common.json+++ b/site/src/i18n/messages/en/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "Unsupported image type.","image_too_large": "Image too large.","plan_not_an_upgrade": "This account is already on this plan or a higher one.",+ "upgrade_in_progress": "This upgrade is already in progress.","upgrade_payment_failed": "Your card was declined, so your plan didn't change. Update your card in billing and try again."},"languageSaveFailed": "Couldn't save your language. Try again.",diff --git a/site/src/i18n/messages/es/common.json b/site/src/i18n/messages/es/common.jsonindex 467be067..834455c7 100644--- a/site/src/i18n/messages/es/common.json+++ b/site/src/i18n/messages/es/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "Tipo de imagen no compatible.","image_too_large": "Imagen demasiado grande.","plan_not_an_upgrade": "Esta cuenta ya tiene este plan o uno superior.",+ "upgrade_in_progress": "Esta actualización ya está en curso.","upgrade_payment_failed": "Tu tarjeta fue rechazada, así que tu plan no cambió. Actualiza tu tarjeta en facturación e inténtalo de nuevo."},"languageSaveFailed": "No se pudo guardar tu idioma. Inténtalo de nuevo.",diff --git a/site/src/i18n/messages/fr/common.json b/site/src/i18n/messages/fr/common.jsonindex 0c9fbc18..3576ca84 100644--- a/site/src/i18n/messages/fr/common.json+++ b/site/src/i18n/messages/fr/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "Type d'image non pris en charge.","image_too_large": "Image trop volumineuse.","plan_not_an_upgrade": "Ce compte bénéficie déjà de ce forfait ou d'un forfait supérieur.",+ "upgrade_in_progress": "Cette mise à niveau est déjà en cours.","upgrade_payment_failed": "Votre carte a été refusée, votre forfait n'a donc pas changé. Mettez à jour votre carte dans la facturation et réessayez."},"languageSaveFailed": "Impossible d'enregistrer votre langue. Réessayez.",diff --git a/site/src/i18n/messages/ja/common.json b/site/src/i18n/messages/ja/common.jsonindex 912c2309..9cd8e4e7 100644--- a/site/src/i18n/messages/ja/common.json+++ b/site/src/i18n/messages/ja/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "サポートされていない画像形式です。","image_too_large": "画像が大きすぎます。","plan_not_an_upgrade": "このアカウントはすでにこのプラン、または上位プランをご利用中です。",+ "upgrade_in_progress": "このアップグレードはすでに進行中です。","upgrade_payment_failed": "カードの支払いが拒否されたため、プランは変更されませんでした。請求設定でカード情報を更新し、もう一度お試しください。"},"languageSaveFailed": "言語を保存できませんでした。もう一度お試しください。",diff --git a/site/src/i18n/messages/ko/common.json b/site/src/i18n/messages/ko/common.jsonindex e0bf2c0a..b5d882ce 100644--- a/site/src/i18n/messages/ko/common.json+++ b/site/src/i18n/messages/ko/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "지원하지 않는 이미지 형식이에요.","image_too_large": "이미지가 너무 커요.","plan_not_an_upgrade": "이 계정은 이미 이 플랜 또는 더 높은 플랜을 이용 중이에요.",+ "upgrade_in_progress": "이 업그레이드는 이미 진행 중이에요.","upgrade_payment_failed": "카드가 승인 거부되어 플랜이 변경되지 않았어요. 결제 정보에서 카드를 업데이트하고 다시 시도해 주세요."},"languageSaveFailed": "언어를 저장하지 못했어요. 다시 시도해 주세요.",diff --git a/site/src/i18n/messages/pt-BR/common.json b/site/src/i18n/messages/pt-BR/common.jsonindex daf37458..6d8140af 100644--- a/site/src/i18n/messages/pt-BR/common.json+++ b/site/src/i18n/messages/pt-BR/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "Tipo de imagem não suportado.","image_too_large": "Imagem grande demais.","plan_not_an_upgrade": "Esta conta já está neste plano ou em um superior.",+ "upgrade_in_progress": "Este upgrade já está em andamento.","upgrade_payment_failed": "Seu cartão foi recusado, portanto seu plano não mudou. Atualize o cartão no faturamento e tente novamente."},"languageSaveFailed": "Não foi possível salvar seu idioma. Tente novamente.",diff --git a/site/src/i18n/messages/zh-CN/common.json b/site/src/i18n/messages/zh-CN/common.jsonindex a256497d..9e719f1e 100644--- a/site/src/i18n/messages/zh-CN/common.json+++ b/site/src/i18n/messages/zh-CN/common.json@@ -43,6 +43,7 @@"unsupported_image_type": "不支持的图片格式。","image_too_large": "图片过大。","plan_not_an_upgrade": "该账号已在使用此方案或更高级方案。",+ "upgrade_in_progress": "此升级已在进行中。","upgrade_payment_failed": "你的银行卡被拒,方案未作更改。请在账单中更新银行卡并重试。"},"languageSaveFailed": "无法保存语言设置。请重试。",diff --git a/site/src/lib/billing/plan-upgrade.test.ts b/site/src/lib/billing/plan-upgrade.test.tsnew file mode 100644index 00000000..4201732a--- /dev/null+++ b/site/src/lib/billing/plan-upgrade.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from "bun:test";+import type Stripe from "stripe";++import { dropIntroDiscount, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";++const INTRO = "donkey-intro-50-3m";++function subscription(overrides: Record<string, unknown> = {}): Stripe.Subscription {+ return {+ id: "sub_1",+ cancel_at: null,+ cancel_at_period_end: false,+ discounts: [],+ latest_invoice: "in_1",+ metadata: {},+ ...overrides,+ } as unknown as Stripe.Subscription;+}++const discount = (id: string, coupon: string) => ({ id, source: { coupon, type: "coupon" } });++describe("liftScheduledCancel", () => {+ test("a period-end cancel is lifted by its flag alone", () => {+ expect(liftScheduledCancel(subscription({ cancel_at: 1_800_000_000, cancel_at_period_end: true }))).toEqual({+ cancel_at_period_end: false,+ });+ });++ test("a dated cancel is lifted by clearing the date alone", () => {+ expect(liftScheduledCancel(subscription({ cancel_at: 1_800_000_000 }))).toEqual({ cancel_at: "" });+ });++ test("a renewing subscription sends neither field", () => {+ expect(liftScheduledCancel(subscription())).toEqual({});+ });+});++describe("dropIntroDiscount", () => {+ test("drops the intro coupon and keeps the rest", () => {+ const sub = subscription({+ discounts: [discount("di_intro", INTRO), discount("di_promo", "promo")],+ metadata: { introOffer: INTRO },+ });+ expect(dropIntroDiscount(sub)).toEqual({ discounts: [{ discount: "di_promo" }] });+ });++ test("clears the discounts when the intro was the only one", () => {+ const sub = subscription({ discounts: [discount("di_intro", INTRO)], metadata: { introOffer: INTRO } });+ expect(dropIntroDiscount(sub)).toEqual({ discounts: "" });+ });++ test("leaves the discounts alone without the intro", () => {+ expect(dropIntroDiscount(subscription({ discounts: [discount("di_promo", "promo")] }))).toEqual({});+ expect(dropIntroDiscount(subscription({ metadata: { introOffer: INTRO } }))).toEqual({});+ });++ test("refuses unexpanded discounts", () => {+ expect(() => dropIntroDiscount(subscription({ discounts: ["di_1"], metadata: { introOffer: INTRO } }))).toThrow();+ });+});++describe("upgradeKey", () => {+ test("the same state gives the same key", () => {+ expect(upgradeKey(subscription(), "price_plus", "price_max")).toBe(upgradeKey(subscription(), "price_plus", "price_max"));+ });++ test("a new invoice gives a new key", () => {+ expect(upgradeKey(subscription({ latest_invoice: "in_2" }), "price_plus", "price_max")).not.toBe(+ upgradeKey(subscription(), "price_plus", "price_max"),+ );+ });+});diff --git a/site/src/lib/billing/plan-upgrade.ts b/site/src/lib/billing/plan-upgrade.tsnew file mode 100644index 00000000..d7ca28f0--- /dev/null+++ b/site/src/lib/billing/plan-upgrade.ts@@ -0,0 +1,54 @@+import type Stripe from "stripe";++import { stripeId } from "@/lib/billing/stripe";++// The subscription metadata key checkout stamps the intro coupon under.+export const INTRO_OFFER_METADATA_KEY = "introOffer";++type CancelFields = Pick<Stripe.SubscriptionUpdateParams, "cancel_at" | "cancel_at_period_end">;++// Moving up keeps the plan, so a scheduled cancel is lifted. Stripe takes one+// of its two cancel fields per call: the period-end flag when that is how the+// cancel was set, the date otherwise.+export function liftScheduledCancel(subscription: Stripe.Subscription): CancelFields {+ if (subscription.cancel_at_period_end) {+ return { cancel_at_period_end: false };+ }+ if (subscription.cancel_at !== null) {+ return { cancel_at: "" };+ }+ return {};+}++// The intro discount sells Pro alone, so moving up drops it and keeps every+// other discount. Reads the subscription with its discounts expanded; an+// empty result leaves the discounts as they are.+export function dropIntroDiscount(+ subscription: Stripe.Subscription,+): Pick<Stripe.SubscriptionUpdateParams, "discounts"> {+ const intro = subscription.metadata?.[INTRO_OFFER_METADATA_KEY];+ if (!intro) {+ return {};+ }++ const discounts = subscription.discounts.map((d) => {+ if (typeof d === "string") {+ throw new Error("Read the subscription with expand: [\"discounts\"].");+ }+ return d;+ });+ const kept = discounts.filter((d) => stripeId(d.source.coupon) !== intro);+ if (kept.length === discounts.length) {+ return {};+ }+ return { discounts: kept.length ? kept.map((d) => ({ discount: d.id })) : "" };+}++// One upgrade per subscription state. Two clicks that read the same+// subscription send one update; Stripe answers the second with the first's+// result. The latest invoice moves with every upgrade, so a later move from+// the same plan gets a fresh key.+export function upgradeKey(subscription: Stripe.Subscription, fromPrice: string, toPrice: string): string {+ const invoice = stripeId(subscription.latest_invoice) ?? "none";+ return `plan-upgrade:${subscription.id}:${fromPrice}:${toPrice}:${invoice}`;+}