Skip to content

Open-source status page, incident response and uptime monitoring

stripe: yearly for everything (#2761)

Thibault Le Ouay0272f2b55adb
diff --git a/apps/dashboard/src/components/content/billing-addons.tsx b/apps/dashboard/src/components/content/billing-addons.tsx
index aa0f966bc..55f9cb7f7 100644
--- a/apps/dashboard/src/components/content/billing-addons.tsx
+++ b/apps/dashboard/src/components/content/billing-addons.tsx
@@ -1,6 +1,9 @@
import type { RouterOutputs } from "@openstatus/api";
import { allPlans } from "@openstatus/db/src/schema/plan/config";
-import type { Addons } from "@openstatus/db/src/schema/plan/schema";
+import type {
+ Addons,
+ BillingInterval,
+} from "@openstatus/db/src/schema/plan/schema";
import {
getAddonMaxQuantity,
getAddonPackSize,
@@ -23,7 +26,7 @@ import { ButtonGroup } from "@openstatus/ui/components/ui/button-group";
import { Input } from "@openstatus/ui/components/ui/input";
import { Label } from "@openstatus/ui/components/ui/label";
import { useCookieState } from "@openstatus/ui/hooks/use-cookie-state";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isTRPCClientError } from "@trpc/client";
import { useEffect, useState, useTransition } from "react";
import { toast } from "sonner";
@@ -61,6 +64,14 @@ export function BillingAddons({
const [currency] = useCookieState("x-currency", "USD");
const trpc = useTRPC();
const queryClient = useQueryClient();
+ // Addons are billed on the plan's interval, so a yearly plan pays the
+ // yearly addon price.
+ // Until it resolves the price is unknown: showing the monthly one to a
+ // yearly customer would misstate what they are charged.
+ const intervalQuery = useQuery(
+ trpc.stripeRouter.getBillingInterval.queryOptions(),
+ );
+ const interval: BillingInterval = intervalQuery.data ?? "monthly";
const checkoutSessionMutation = useMutation(
trpc.stripeRouter.addAddon.mutationOptions({
onSuccess: () => {
@@ -92,7 +103,9 @@ export function BillingAddons({
Math.floor((workspaceLimit - defaultLimit) / packSize)
: workspaceLimit;
const [value, setValue] = useState<number | boolean>(defaultValue);
- const price = getAddonPriceConfig(plan, addon, currency);
+ const price = intervalQuery.isSuccess
+ ? getAddonPriceConfig(plan, addon, currency, interval)
+ : null;
// Reset value when modal opens
useEffect(() => {
@@ -161,8 +174,11 @@ export function BillingAddons({
</div>
<div className="flex items-center gap-1.5">
<span className="text-foreground font-mono text-sm">
- {formatPrice(price)}
- {getPriceSuffix(isQuantity, packSize)}
+ {price
+ ? `${formatPrice(price)}${getPriceSuffix(isQuantity, packSize, interval)}`
+ : intervalQuery.isPending
+ ? "Loading..."
+ : "N/A"}
</span>
{hasAddon && !isQuantity ? (
<Check className="text-success size-4" />
@@ -175,7 +191,7 @@ export function BillingAddons({
</div>
<div className="col-span-2 flex items-center justify-end gap-1.5 lg:col-span-1">
<AlertDialogTrigger asChild>
- <Button size="sm" variant="secondary">
+ <Button size="sm" variant="secondary" disabled={!price}>
{getButtonLabel(hasAddon, value)}
</Button>
</AlertDialogTrigger>
@@ -193,6 +209,7 @@ export function BillingAddons({
hasAddon,
packSize,
unitLabel,
+ interval,
)}
{isTrialing && !isRemoval
? " Adding it ends your Starter trial and charges your card today."
@@ -263,9 +280,18 @@ function getButtonLabel(
return null;
}
-function getPriceSuffix(isQuantity: boolean, packSize: number) {
- if (!isQuantity) return "/mo.";
- return packSize > 1 ? `/mo./pack of ${packSize}` : "/mo./each";
+function getPeriodSuffix(interval: BillingInterval) {
+ return interval === "yearly" ? "/yr." : "/mo.";
+}
+
+function getPriceSuffix(
+ isQuantity: boolean,
+ packSize: number,
+ interval: BillingInterval,
+) {
+ const period = getPeriodSuffix(interval);
+ if (!isQuantity) return period;
+ return packSize > 1 ? `${period}/pack of ${packSize}` : `${period}/each`;
}
function getDialogDescription(
@@ -275,11 +301,12 @@ function getDialogDescription(
hasAddon: boolean,
packSize: number,
unitLabel: string,
+ interval: BillingInterval,
) {
const formattedPrice = formatPrice(price);
const isBoolean = typeof value === "boolean";
const isQuantity = typeof value === "number";
- const priceSuffix = getPriceSuffix(isQuantity, packSize);
+ const priceSuffix = getPriceSuffix(isQuantity, packSize, interval);
if (isBoolean) {
if (hasAddon) {
@@ -293,7 +320,7 @@ function getDialogDescription(
return `${label} will be removed from your subscription. You will stop being charged for it on your next billing cycle.`;
}
const total = formatAmount(price, price ? price.value * value : 0);
- return `Your workspace will get ${value * packSize} extra ${unitLabel}. You will be charged ${total}/mo., starting on your next billing cycle.`;
+ return `Your workspace will get ${value * packSize} extra ${unitLabel}. You will be charged ${total}${getPeriodSuffix(interval)}, starting on your next billing cycle.`;
}
}
diff --git a/apps/dashboard/src/components/data-table/billing/data-table.tsx b/apps/dashboard/src/components/data-table/billing/data-table.tsx
index 0c89c99f8..28b7e2aa7 100644
--- a/apps/dashboard/src/components/data-table/billing/data-table.tsx
+++ b/apps/dashboard/src/components/data-table/billing/data-table.tsx
@@ -39,9 +39,14 @@ const BASE_URL =
? "https://app.openstatus.dev"
: "http://localhost:3000";
-function getQuantitySuffix(addon: keyof Addons) {
+function getPeriodSuffix(interval: BillingInterval) {
+ return interval === "yearly" ? "/yr." : "/mo.";
+}
+
+function getQuantitySuffix(addon: keyof Addons, interval: BillingInterval) {
const packSize = getAddonPackSize(addon);
- return packSize > 1 ? `/mo./${packSize}` : "/mo./each";
+ const period = getPeriodSuffix(interval);
+ return packSize > 1 ? `${period}/${packSize}` : `${period}/each`;
}
export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
@@ -52,6 +57,10 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
const queryClient = useQueryClient();
const [isPending, startTransition] = useTransition();
const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
+ const intervalQuery = useQuery(
+ trpc.stripeRouter.getBillingInterval.queryOptions(),
+ );
+ const currentInterval = intervalQuery.data;
const checkoutSessionMutation = useMutation(
trpc.stripeRouter.getCheckoutSession.mutationOptions({
@@ -62,9 +71,14 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
// already have, so there is no checkout to redirect to — only the
// refreshed workspace to pick up.
if (data.type === "updated") {
- await queryClient.invalidateQueries({
- queryKey: trpc.workspace.get.queryKey(),
- });
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.workspace.get.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.stripeRouter.getBillingInterval.queryKey(),
+ }),
+ ]);
toast.success("Your plan has been updated");
return;
}
@@ -115,9 +129,27 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
Features comparison
</TableHead>
{filteredPlans.map(({ id, ...plan }) => {
- const isCurrentPlan = workspace.plan === id;
- const price = getPriceConfig(id, currency, interval);
const isFreePlan = id === "free";
+ const isSamePlan = workspace.plan === id;
+ // Hold the paid plan's button until the interval is known, so it
+ // never flashes "Current Plan" on the wrong tab.
+ const isIntervalLoading =
+ isSamePlan && !isFreePlan && intervalQuery.isPending;
+ // A resolved `null` (no subscription, legacy price) matches on the
+ // plan alone. A failed fetch leaves both intervals selectable:
+ // re-applying the price the customer already pays is a no-op.
+ const isCurrentPlan =
+ isSamePlan &&
+ (isFreePlan ||
+ (intervalQuery.isSuccess &&
+ (currentInterval === null ||
+ currentInterval === interval)));
+ const isIntervalSwitch =
+ isSamePlan &&
+ intervalQuery.isSuccess &&
+ currentInterval !== null &&
+ currentInterval !== interval;
+ const price = getPriceConfig(id, currency, interval);
return (
<TableHead
key={id}
@@ -181,17 +213,21 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
}
});
}}
- disabled={isPending || isCurrentPlan}
+ disabled={isPending || isCurrentPlan || isIntervalLoading}
>
- {isCurrentPlan
- ? isTrialing
- ? "On Trial"
- : "Current Plan"
- : isPending
- ? "Choosing..."
- : isTrialing && !isFreePlan
- ? "Upgrade now"
- : "Choose"}
+ {isIntervalLoading
+ ? "Loading..."
+ : isCurrentPlan
+ ? isTrialing
+ ? "On Trial"
+ : "Current Plan"
+ : isPending
+ ? "Choosing..."
+ : isIntervalSwitch
+ ? `Switch to ${interval}`
+ : isTrialing && !isFreePlan
+ ? "Upgrade now"
+ : "Choose"}
</Button>
</div>
</TableHead>
@@ -233,6 +269,7 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
plan.id,
value as keyof typeof plan.addons,
currency,
+ interval,
);
if (!price) return null;
@@ -258,8 +295,9 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
{isNumber
? getQuantitySuffix(
value as keyof typeof plan.addons,
+ interval,
)
- : "/mo."}
+ : getPeriodSuffix(interval)}
</span>
</span>
</div>
diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.ts
index b1d7f9e05..90ac92837 100644
--- a/packages/api/src/router/stripe/index.ts
+++ b/packages/api/src/router/stripe/index.ts
@@ -1,6 +1,9 @@
import { Events } from "@openstatus/analytics";
import { workspacePlans } from "@openstatus/db/src/schema";
-import type { AddonQuantityKey } from "@openstatus/db/src/schema/plan/schema";
+import type {
+ AddonQuantityKey,
+ BillingInterval,
+} from "@openstatus/db/src/schema/plan/schema";
import {
addons,
billingIntervals,
@@ -19,6 +22,7 @@ import {
updateWorkspaceStripeId,
} from "@openstatus/services/workspace";
import { TRPCError } from "@trpc/server";
+import type Stripe from "stripe";
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "../../trpc";
@@ -31,6 +35,7 @@ import {
trialEndsAtOf,
} from "./shared";
import {
+ buildPlanChangeItems,
getPlanFromPriceId,
getPriceIdForFeature,
getPriceIdForPlan,
@@ -105,6 +110,24 @@ async function createPaymentMethodSetupSession(args: {
}
export const stripeRouter = createTRPCRouter({
+ // The workspace only stores the plan, not the interval it is billed on, so
+ // the plan table asks Stripe to tell "Pro monthly" apart from "Pro yearly".
+ getBillingInterval: protectedProcedure.query(
+ async ({ ctx }): Promise<BillingInterval | null> => {
+ const stripeId = ctx.workspace.stripeId;
+ if (!stripeId) return null;
+
+ const { current } = await getCurrentSubscription(stripeId);
+ const planItem = current?.items.data.find((item) =>
+ getPlanFromPriceId(item.price.id),
+ );
+ const interval = planItem?.price.recurring?.interval;
+ if (interval === "year") return "yearly";
+ if (interval === "month") return "monthly";
+ return null;
+ },
+ ),
+
getUserCustomerPortal: protectedProcedure
.input(
z.object({ workspaceSlug: z.string(), returnUrl: z.string().optional() }),
@@ -193,17 +216,19 @@ export const stripeRouter = createTRPCRouter({
});
}
- // Stripe rejects mixed billing intervals on one subscription and every
- // addon price is monthly, so a yearly plan cannot hold the addon items.
- const hasAddons = current.items.data.some(
- (item) => item.id !== planItem.id,
- );
-
- if (opts.input.interval === "yearly" && hasAddons) {
+ let items: Stripe.SubscriptionUpdateParams.Item[];
+ try {
+ items = buildPlanChangeItems({
+ subscription: current,
+ planItemId: planItem.id,
+ planPriceId: priceId,
+ interval: opts.input.interval,
+ });
+ } catch {
throw new TRPCError({
code: "BAD_REQUEST",
message:
- "Add-ons are billed monthly. Remove them before switching to a yearly plan, or contact us.",
+ "Your subscription has an add-on that cannot be moved to this billing interval. Contact us and we will switch it for you.",
});
}
@@ -214,13 +239,13 @@ export const stripeRouter = createTRPCRouter({
// same item.
buildFromSubscriptionOrThrow(current);
- // Only the plan item is listed, so Stripe leaves every other item
- // untouched and the addons survive the plan change. Clearing
+ // Every existing item is listed by id, so Stripe re-prices it in place
+ // instead of dropping it, and the addons survive the change. Clearing
// `cancel_at_period_end` resumes a subscription the customer had
// scheduled to cancel — choosing a paid plan says they mean to keep
// paying.
const updated = await stripe.subscriptions.update(current.id, {
- items: [{ id: planItem.id, price: priceId }],
+ items,
proration_behavior: "create_prorations",
cancel_at_period_end: false,
...(isTrialing && {
@@ -362,30 +387,26 @@ export const stripeRouter = createTRPCRouter({
});
}
- const priceId = getPriceIdForFeature(opts.input.feature);
-
- if (!priceId) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Invalid feature",
- });
- }
-
const items = await stripe.subscriptionItems.list({
subscription: current.id,
limit: 100,
});
- // Stripe rejects mixed billing intervals on one subscription and every
- // addon price is monthly, so a yearly plan cannot hold one.
+ // Stripe rejects mixed billing intervals on one subscription, so the
+ // addon is billed on the same interval as the plan.
const planItem = items.data.find((item) =>
getPlanFromPriceId(item.price.id),
);
- if (planItem?.price.recurring?.interval === "year") {
+ const isYearly = planItem?.price.recurring?.interval === "year";
+ const priceId = getPriceIdForFeature(
+ opts.input.feature,
+ isYearly ? "yearly" : "monthly",
+ );
+
+ if (!priceId) {
throw new TRPCError({
code: "BAD_REQUEST",
- message:
- "Add-ons are billed monthly. Contact us to add them to a yearly plan.",
+ message: "Invalid feature",
});
}
diff --git a/packages/api/src/router/stripe/utils.test.ts b/packages/api/src/router/stripe/utils.test.ts
index d130af448..54be41d5c 100644
--- a/packages/api/src/router/stripe/utils.test.ts
+++ b/packages/api/src/router/stripe/utils.test.ts
@@ -10,6 +10,8 @@ import {
FEATURES,
PLANS,
buildLimitsFromSubscription,
+ buildPlanChangeItems,
+ getPriceIdForFeature,
resolveAddonQuantity,
} from "./utils";
@@ -234,3 +236,116 @@ describe("resolveAddonQuantity", () => {
).toThrow(/whole number of packs/);
});
});
+
+describe("getPriceIdForFeature", () => {
+ test("defaults to the monthly price", () => {
+ expect(getPriceIdForFeature("status-pages")).toBe(STATUS_PAGES);
+ });
+
+ test("returns the yearly price when the addon has one", () => {
+ const yearly = getPriceIdForFeature("status-pages", "yearly");
+ expect(yearly).toBeDefined();
+ expect(yearly).not.toBe(STATUS_PAGES);
+ });
+
+ test("every addon has a yearly price", () => {
+ for (const { feature } of FEATURES) {
+ expect(getPriceIdForFeature(feature, "yearly")).toBeDefined();
+ }
+ });
+
+ test("a yearly addon item still counts towards the limits", () => {
+ const built = buildLimitsFromSubscription(
+ subscriptionWith([
+ { priceId: STARTER },
+ {
+ priceId: getPriceIdForFeature("status-pages", "yearly"),
+ quantity: 2,
+ },
+ ]),
+ );
+ expect(built?.limits["status-pages"]).toBe(
+ getLimits("starter")["status-pages"] +
+ 2 * getAddonPackSize("status-pages"),
+ );
+ });
+});
+
+describe("buildPlanChangeItems", () => {
+ const yearlyPlanPrice = PLANS.find((p) => p.plan === "starter")?.price.yearly
+ .priceIds.test as string;
+ const monthlyFeature = (feature: string) =>
+ FEATURES.find((f) => f.feature === feature)?.price.monthly.priceIds.test;
+ const yearlyFeature = (feature: string) =>
+ FEATURES.find((f) => f.feature === feature)?.price.yearly.priceIds.test;
+
+ function subscription(
+ items: { id: string; priceId: string | undefined; quantity?: number }[],
+ ) {
+ return {
+ items: {
+ data: items.map(({ id, priceId, quantity }) => ({
+ id,
+ price: { id: priceId },
+ quantity,
+ })),
+ },
+ } as unknown as Stripe.Subscription;
+ }
+
+ test("monthly → yearly moves the plan and every addon to yearly", () => {
+ const items = buildPlanChangeItems({
+ subscription: subscription([
+ { id: "si_plan", priceId: STARTER, quantity: 1 },
+ ...FEATURES.map(({ feature }, i) => ({
+ id: `si_${feature}`,
+ priceId: monthlyFeature(feature),
+ quantity: i + 1,
+ })),
+ ]),
+ planItemId: "si_plan",
+ planPriceId: yearlyPlanPrice,
+ interval: "yearly",
+ });
+
+ expect(items).toEqual([
+ { id: "si_plan", price: yearlyPlanPrice },
+ ...FEATURES.map(({ feature }, i) => ({
+ id: `si_${feature}`,
+ price: yearlyFeature(feature),
+ quantity: i + 1,
+ })),
+ ]);
+ });
+
+ test("yearly → monthly moves every addon back to monthly", () => {
+ const items = buildPlanChangeItems({
+ subscription: subscription([
+ { id: "si_plan", priceId: yearlyPlanPrice },
+ { id: "si_pages", priceId: yearlyFeature("status-pages"), quantity: 3 },
+ ]),
+ planItemId: "si_plan",
+ planPriceId: STARTER as string,
+ interval: "monthly",
+ });
+
+ expect(items).toEqual([
+ { id: "si_plan", price: STARTER },
+ { id: "si_pages", price: STATUS_PAGES, quantity: 3 },
+ ]);
+ });
+
+ test("throws on an addon item with an unknown price", () => {
+ expect(() =>
+ buildPlanChangeItems({
+ subscription: subscription([
+ { id: "si_plan", priceId: STARTER },
+ { id: "si_legacy", priceId: "price_legacy" },
+ ]),
+ planItemId: "si_plan",
+ planPriceId: yearlyPlanPrice,
+ interval: "yearly",
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.ts
index fd9e8393e..2ba1f6665 100644
--- a/packages/api/src/router/stripe/utils.ts
+++ b/packages/api/src/router/stripe/utils.ts
@@ -15,6 +15,8 @@ import {
} from "@openstatus/db/src/schema/plan/utils";
import type Stripe from "stripe";
+type PriceIds = { priceIds: { test: string; production: string } };
+
/**
* Rebuild a workspace's limits from the full set of subscription line items.
* The plan item sets the baseline; each addon item then re-applies its flag or
@@ -126,14 +128,47 @@ export const getPriceIdForPlan = (
return PLANS.find((p) => p.plan === plan)?.price[interval].priceIds[env];
};
-export const getPriceIdForFeature = (feature: keyof Addons) => {
+export const getPriceIdForFeature = (
+ feature: keyof Addons,
+ interval: BillingInterval = "monthly",
+) => {
const env =
process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";
- return FEATURES.find((f) => f.feature === feature)?.price.monthly.priceIds[
+ return FEATURES.find((f) => f.feature === feature)?.price[interval].priceIds[
env
];
};
+/**
+ * The item list for a plan or interval change. Every item already on the
+ * subscription is listed by id so Stripe re-prices it in place instead of
+ * dropping it: the plan item takes the new plan price, and each addon moves to
+ * its price for the target interval with its quantity kept — Stripe rejects
+ * mixed intervals on one subscription, so a yearly plan takes yearly addons.
+ * Throws on an addon item whose price is unknown rather than dropping it.
+ */
+export function buildPlanChangeItems(args: {
+ subscription: Stripe.Subscription;
+ planItemId: string;
+ planPriceId: string;
+ interval: BillingInterval;
+}): Stripe.SubscriptionUpdateParams.Item[] {
+ const { subscription, planItemId, planPriceId, interval } = args;
+ return subscription.items.data.map((item) => {
+ if (item.id === planItemId) return { id: item.id, price: planPriceId };
+ const feature = getFeatureFromPriceId(item.price.id);
+ const price = feature
+ ? getPriceIdForFeature(feature.feature, interval)
+ : undefined;
+ if (!price) {
+ throw new Error(
+ `Unsupported Stripe price on subscription: ${item.price.id}`,
+ );
+ }
+ return { id: item.id, price, quantity: item.quantity ?? 1 };
+ });
+}
+
export const PLANS = [
{
plan: "team",
@@ -204,6 +239,12 @@ export const FEATURES = [
production: "price_1Sl6oqBXJcTfzsyJCxtzDIx5",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ7bhBXJcTfzsyJhHuuQjr2",
+ production: "price_1UJ7bhBXJcTfzsyJhHuuQjr2",
+ },
+ },
},
},
{
@@ -212,7 +253,13 @@ export const FEATURES = [
monthly: {
priceIds: {
test: "price_1TMpxlBXJcTfzsyJ1woQtafW",
- production: "price_1TMq0GBXJcTfzsyJrIVx9KPL",
+ production: "price_1TMpxlBXJcTfzsyJ1woQtafW",
+ },
+ },
+ yearly: {
+ priceIds: {
+ test: "price_1UJ7akBXJcTfzsyJzDrC8hdK",
+ production: "price_1UJ7akBXJcTfzsyJzDrC8hdK",
},
},
},
@@ -226,6 +273,12 @@ export const FEATURES = [
production: "price_1SlbSdBXJcTfzsyJahJiFE8D",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ74MBXJcTfzsyJ17ksU7wm",
+ production: "price_1UJ74MBXJcTfzsyJ17ksU7wm",
+ },
+ },
},
},
{
@@ -237,6 +290,12 @@ export const FEATURES = [
production: "price_1Tvv0zBXJcTfzsyJseLIjNnz",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ76GBXJcTfzsyJ6BGJ3ZJd",
+ production: "price_1UJ76GBXJcTfzsyJ6BGJ3ZJd",
+ },
+ },
},
},
{
@@ -248,6 +307,12 @@ export const FEATURES = [
production: "price_1SlrkHBXJcTfzsyJIxHeKUYe",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ70tBXJcTfzsyJRDDnbXcP",
+ production: "price_1UJ70tBXJcTfzsyJRDDnbXcP",
+ },
+ },
},
},
{
@@ -261,6 +326,12 @@ export const FEATURES = [
production: "price_1UChsCBXJcTfzsyJgomhUtYY",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ7YkBXJcTfzsyJdklvON8r",
+ production: "price_1UJ7YkBXJcTfzsyJdklvON8r",
+ },
+ },
},
},
{
@@ -272,11 +343,20 @@ export const FEATURES = [
production: "price_1TySGYBXJcTfzsyJQFVFJi6N",
},
},
+ yearly: {
+ priceIds: {
+ test: "price_1UJ7ZcBXJcTfzsyJ78fA9RFp",
+ production: "price_1UJ7ZcBXJcTfzsyJ78fA9RFp",
+ },
+ },
},
},
] satisfies Array<{
feature: keyof Addons;
+ // Stripe rejects mixed intervals on one subscription, so every addon needs a
+ // price on each interval a plan is sold on.
price: {
- monthly: { priceIds: { test: string; production: string } };
+ monthly: PriceIds;
+ yearly: PriceIds;
};
}>;
diff --git a/packages/db/src/schema/plan/utils.test.ts b/packages/db/src/schema/plan/utils.test.ts
new file mode 100644
index 000000000..620af10cb
--- /dev/null
+++ b/packages/db/src/schema/plan/utils.test.ts
@@ -0,0 +1,34 @@
+import { expect } from "@std/expect";
+import { describe, it } from "@std/testing/bdd";
+
+import { allPlans } from "./config";
+import { YEARLY_ADDON_MULTIPLIER, getAddonPriceConfig } from "./utils";
+
+describe("getAddonPriceConfig", () => {
+ it("defaults to the monthly price", () => {
+ const monthly = getAddonPriceConfig("starter", "white-label", "USD");
+ expect(monthly?.value).toBe(
+ allPlans.starter.addons["white-label"]?.price.USD,
+ );
+ });
+
+ it("charges the yearly price on a yearly plan", () => {
+ const monthly = getAddonPriceConfig("starter", "status-pages", "EUR");
+ const yearly = getAddonPriceConfig(
+ "starter",
+ "status-pages",
+ "EUR",
+ "yearly",
+ );
+ expect(yearly).toEqual({
+ ...monthly,
+ value: (monthly?.value ?? 0) * YEARLY_ADDON_MULTIPLIER,
+ });
+ });
+
+ it("returns null for an addon the plan does not sell", () => {
+ expect(getAddonPriceConfig("free", "white-label", "USD", "yearly")).toBe(
+ null,
+ );
+ });
+});
diff --git a/packages/db/src/schema/plan/utils.ts b/packages/db/src/schema/plan/utils.ts
index 015425435..1e6c39119 100644
--- a/packages/db/src/schema/plan/utils.ts
+++ b/packages/db/src/schema/plan/utils.ts
@@ -86,16 +86,24 @@ export function getAddonMaxQuantity(addon: keyof Addons): number | null {
return getAddonQuantityConfig(addon)?.maxQuantity ?? null;
}
+// Yearly addon prices in Stripe are the monthly price ×10 — the same "2 months
+// free" as the plans — so they are derived rather than stored per addon.
+export const YEARLY_ADDON_MULTIPLIER = 10;
+
export function getAddonPriceConfig(
plan: WorkspacePlan,
addon: keyof Addons,
currency?: string,
+ interval: BillingInterval = "monthly",
) {
const addonConfig = allPlans[plan].addons[addon];
if (!addonConfig) {
return null;
}
- return resolvePriceConfig(addonConfig.price, currency);
+ const price = resolvePriceConfig(addonConfig.price, currency);
+ return interval === "yearly"
+ ? { ...price, value: price.value * YEARLY_ADDON_MULTIPLIER }
+ : price;
}
export function getPlansForLimit(