Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
dashboard: monitor pack (#2649)
Thibault Le Ouay224757e5374d
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/(list)/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/monitors/(list)/nav-actions.tsxindex 79aecaa74..dc20300a9 100644--- a/apps/dashboard/src/app/(dashboard)/monitors/(list)/nav-actions.tsx+++ b/apps/dashboard/src/app/(dashboard)/monitors/(list)/nav-actions.tsx@@ -36,7 +36,11 @@ export function NavActions() {<Link href="/monitors/create">Create Monitor</Link></Button>)}- <UpgradeDialog open={openDialog} onOpenChange={setOpenDialog} />+ <UpgradeDialog+ open={openDialog}+ onOpenChange={setOpenDialog}+ limit="monitors"+ /></div>);}diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsxindex c3182ef09..8c83b4c71 100644--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx@@ -229,6 +229,14 @@ export function Client() {workspace={workspace}/>) : null}+ {planAddons.monitors ? (+ <BillingAddons+ label={planAddons.monitors.title}+ description={planAddons.monitors.description}+ addon="monitors"+ workspace={workspace}+ />+ ) : null}{planAddons.sso ? (<BillingAddonslabel={planAddons.sso.title}diff --git a/apps/dashboard/src/components/content/billing-addons.tsx b/apps/dashboard/src/components/content/billing-addons.tsxindex 246c2979c..6cac3aeb2 100644--- a/apps/dashboard/src/components/content/billing-addons.tsx+++ b/apps/dashboard/src/components/content/billing-addons.tsx@@ -1,7 +1,11 @@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 { getAddonPriceConfig } from "@openstatus/db/src/schema/plan/utils";+import {+ getAddonMaxQuantity,+ getAddonPackSize,+ getAddonPriceConfig,+} from "@openstatus/db/src/schema/plan/utils";import { Check, Remove, Add } from "@openstatus/icons";import {AlertDialog,@@ -41,6 +45,11 @@ interface PriceConfig {locale: string;}+const QUANTITY_UNIT_LABEL: Partial<Record<keyof Addons, string>> = {+ monitors: "monitors",+ "status-pages": "status pages",+};+export function BillingAddons({label,description,@@ -62,12 +71,16 @@ export function BillingAddons({}),);const plan = workspace.plan;+ const packSize = getAddonPackSize(addon);+ const maxPacks = getAddonMaxQuantity(addon);+ const unitLabel = QUANTITY_UNIT_LABEL[addon] ?? "units";const defaultLimit = allPlans[workspace.plan].limits[addon];const workspaceLimit = workspace.limits[addon];const defaultValue =typeof workspaceLimit === "number" && typeof defaultLimit === "number"- ? // current value - default value to evaluate the difference- workspaceLimit - defaultLimit+ ? // packs held today; floored so a hand-edited limit that is not a whole+ // number of packs still renders a sane count+ Math.floor((workspaceLimit - defaultLimit) / packSize): workspaceLimit;const [value, setValue] = useState<number | boolean>(defaultValue);const price = getAddonPriceConfig(plan, addon, currency);@@ -125,13 +138,15 @@ export function BillingAddons({<div className="flex items-center gap-1.5"><span className="text-foreground font-mono text-sm">{formatPrice(price)}- {isQuantity ? "/mo./each" : "/mo."}+ {getPriceSuffix(isQuantity, packSize)}</span>{hasAddon && !isQuantity ? (<Check className="text-success size-4" />) : null}- {hasAddon && isQuantity ? (- <span className="text-success font-mono">+{defaultValue}</span>+ {hasAddon && isQuantity && typeof defaultValue === "number" ? (+ <span className="text-success font-mono">+ +{defaultValue * packSize}+ </span>) : null}</div><div className="col-span-2 flex items-center justify-end gap-1.5 lg:col-span-1">@@ -147,16 +162,23 @@ export function BillingAddons({<AlertDialogHeader><AlertDialogTitle>{label}</AlertDialogTitle><AlertDialogDescription>- {getDialogDescription(label, price, value, hasAddon)}+ {getDialogDescription(+ label,+ price,+ value,+ hasAddon,+ packSize,+ unitLabel,+ )}</AlertDialogDescription></AlertDialogHeader>- {isQuantity &&- typeof value === "number" &&- typeof defaultLimit === "number" ? (+ {isQuantity && typeof value === "number" ? (<QuantityControlvalue={value}setValue={setValue}- defaultLimit={defaultLimit}+ maxValue={maxPacks}+ packSize={packSize}+ unitLabel={unitLabel}/>) : null}<AlertDialogFooter>@@ -182,12 +204,17 @@ export function BillingAddons({}// NOTE: could move to lib/formatter.ts-function formatPrice(price: PriceConfig | null) {+function formatAmount(price: PriceConfig | null, amount: number) {if (!price) return "N/A";return new Intl.NumberFormat(price.locale, {style: "currency",currency: price.currency,- }).format(price.value);+ }).format(amount);+}++function formatPrice(price: PriceConfig | null) {+ if (!price) return "N/A";+ return formatAmount(price, price.value);}function getButtonLabel(@@ -209,16 +236,23 @@ function getButtonLabel(return null;}+function getPriceSuffix(isQuantity: boolean, packSize: number) {+ if (!isQuantity) return "/mo.";+ return packSize > 1 ? `/mo./pack of ${packSize}` : "/mo./each";+}+function getDialogDescription(label: string,price: PriceConfig | null,value: number | boolean,hasAddon: boolean,+ packSize: number,+ unitLabel: string,) {const formattedPrice = formatPrice(price);const isBoolean = typeof value === "boolean";const isQuantity = typeof value === "number";- const priceSuffix = isQuantity ? "/mo./each" : "/mo.";+ const priceSuffix = getPriceSuffix(isQuantity, packSize);if (isBoolean) {if (hasAddon) {@@ -228,37 +262,46 @@ function getDialogDescription(}if (isQuantity) {- return `${label} will be updated to ${value} on your next billing cycle. You will be charged ${formattedPrice}${priceSuffix} on your next billing cycle.`;+ if (value === 0) {+ 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.`;}}function QuantityControl({value,setValue,- defaultLimit,+ maxValue,+ packSize,+ unitLabel,}: {value: number;setValue: (value: number) => void;- defaultLimit: number | boolean;+ maxValue: number | null;+ packSize: number;+ unitLabel: string;}) {+ const clamp = (next: number) => {+ const floored = Math.max(0, next);+ return maxValue === null ? floored : Math.min(maxValue, floored);+ };+const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {const newValue = Number.parseInt(e.target.value);- if (Number.isNaN(newValue)) {- setValue(typeof defaultLimit === "number" ? defaultLimit : 0);- } else {- setValue(- Math.max(typeof defaultLimit === "number" ? defaultLimit : 0, newValue),- );- }+ setValue(Number.isNaN(newValue) ? 0 : clamp(newValue));};+ const atMax = maxValue !== null && value >= maxValue;+return (- <div className="flex items-center justify-center gap-2 py-2">+ <div className="flex flex-col items-center gap-2 py-2"><ButtonGroup aria-label="Quantity" className="h-fit"><Buttonvariant="outline"size="icon"- onClick={() => setValue(value - 1)}+ onClick={() => setValue(clamp(value - 1))}disabled={value <= 0}><Remove />@@ -269,16 +312,31 @@ function QuantityControl({className="w-16 text-right"step={1}min={0}+ max={maxValue ?? undefined}onChange={handleChange}/><Buttonvariant="outline"size="icon"- onClick={() => setValue(value + 1)}+ onClick={() => setValue(clamp(value + 1))}+ disabled={atMax}><Add /></Button></ButtonGroup>+ {atMax && maxValue !== null ? (+ <p className="text-muted-foreground text-xs">+ Need more than {maxValue * packSize} extra {unitLabel}?{" "}+ <a+ href="https://openstatus.dev/cal"+ target="_blank"+ rel="noreferrer"+ className="text-foreground underline underline-offset-4"+ >+ Book a call+ </a>+ </p>+ ) : null}</div>);}diff --git a/apps/dashboard/src/components/data-table/billing/data-table.tsx b/apps/dashboard/src/components/data-table/billing/data-table.tsxindex 9eb8e43b6..4e2e7fcd2 100644--- a/apps/dashboard/src/components/data-table/billing/data-table.tsx+++ b/apps/dashboard/src/components/data-table/billing/data-table.tsx@@ -1,8 +1,12 @@"use client";import type { WorkspacePlan } from "@openstatus/db/src/schema";-import type { BillingInterval } from "@openstatus/db/src/schema/plan/schema";+import type {+ Addons,+ BillingInterval,+} from "@openstatus/db/src/schema/plan/schema";import {+ getAddonPackSize,getAddonPriceConfig,getPriceConfig,} from "@openstatus/db/src/schema/plan/utils";@@ -34,6 +38,11 @@ const BASE_URL =? "https://app.openstatus.dev": "http://localhost:3000";+function getQuantitySuffix(addon: keyof Addons) {+ const packSize = getAddonPackSize(addon);+ return packSize > 1 ? `/mo./${packSize}` : "/mo./each";+}+export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {const [interval, setInterval] = useState<BillingInterval>("monthly");const [currency] = useCookieState("x-currency", "USD");@@ -219,7 +228,11 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {style: "currency",currency: price.currency,}).format(price.value)}- {isNumber ? "/mo./each" : "/mo."}+ {isNumber+ ? getQuantitySuffix(+ value as keyof typeof plan.addons,+ )+ : "/mo."}</span></span></div>diff --git a/apps/web/public/assets/changelog/monitor-pack.png b/apps/web/public/assets/changelog/monitor-pack.pngnew file mode 100644index 000000000..13ed80e49Binary files /dev/null and b/apps/web/public/assets/changelog/monitor-pack.png differdiff --git a/apps/web/src/content/pages/changelog/monitor-pack.mdx b/apps/web/src/content/pages/changelog/monitor-pack.mdxnew file mode 100644index 000000000..ea7b518eb--- /dev/null+++ b/apps/web/src/content/pages/changelog/monitor-pack.mdx@@ -0,0 +1,17 @@+---+title: "Monitor Pack"+description: "Add 10 monitors to your workspace for $15/month."+image: "/assets/changelog/monitor-pack.png"+publishedAt: "2026-09-06"+author: "openstatus"+category: "monitoring"+---++You can now add monitors to your workspace without changing plans. A Monitor Pack adds **10 monitors for $15/month**, and you can stack up to 10 packs on the Starter, Pro and Scale plans.++Packs are billed monthly on top of your plan, alongside the existing add-ons. Your new limit applies immediately β the monitors you add count against your plan's allowance plus every pack you hold, so a Starter workspace with three packs can monitor up to 50 endpoints.++Removing packs works the same way in reverse. If you are still using more monitors than the smaller limit allows, we'll ask you to delete a few first rather than silently stopping checks.++#### Get Started π+Head to Settings β Billing, find **Monitor Pack** under Add-ons, and choose how many packs you need. Need more than 100 extra monitors? [Book a call](https://openstatus.dev/cal) and we'll sort out a plan that fits.diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdxindex fddb736e6..97b771c13 100644--- a/apps/web/src/content/pages/unrelated/pricing.mdx+++ b/apps/web/src/content/pages/unrelated/pricing.mdx@@ -12,7 +12,7 @@ faq:- question: "Do you offer a free plan?"answer: "Yes. Our free Hobby plan includes one monitor, one status page with three components, and a minimum check interval of 10 minutes. No credit card required."- question: "What are add-ons and how are they billed?"- answer: "Add-ons are workspace-level settings like White Label, Email Authentication, IP Restriction, and extra status pages. Once enabled, they apply to your entire workspace. Add-ons are billed monthly regardless of your plan's billing cycle."+ answer: "Add-ons are workspace-level settings like White Label, Email Authentication, IP Restriction, extra status pages, and extra monitors. Once enabled, they apply to your entire workspace. Add-ons are billed monthly regardless of your plan's billing cycle."- question: "Can I upgrade or downgrade my plan?"answer: "Yes. You can upgrade or downgrade at any time from your dashboard. Changes take effect immediately, and billing is prorated."- question: "What currencies do you support?"@@ -22,7 +22,7 @@ faq:- question: "Can I cancel my subscription at any time?"answer: "Yes. You can cancel anytime from your dashboard. Your plan stays active until the end of the current billing period, and you will not be charged again."- question: "What happens if I exceed my plan limits?"- answer: "We will never stop your monitors or status pages without notice. If you approach or exceed a limit, we will reach out to help you pick the right plan. Add-ons like extra status pages are billed per unit as listed in the comparison table."+ answer: "We will never stop your monitors or status pages without notice. If you approach or exceed a limit, we will reach out to help you pick the right plan. Add-ons like extra status pages and monitor packs are billed per unit as listed in the comparison table."- question: "Do you offer custom or enterprise plans?"answer: "Yes. If you need higher limits, custom regions, SSO, a dedicated SLA, or a custom contract, book a call and we will tailor a plan to your needs."- question: "What payment methods do you accept?"@@ -52,7 +52,7 @@ faq:| IP Restriction | $100/mo. | $100/mo. | + || [Monitors](/uptime-monitoring) | | | || Check Interval | 1m | 30s | 30s |-| Number of monitors | 20 | 50 | 50 |+| Number of monitors | 20 +$15/mo./10 | 50 +$15/mo./10 | 50 +$15/mo./10 || Multi-region monitoring | + | + | + || Total regions | 28 | 28 | 28 || Regions per monitor | 6 | 28 | 28 |@@ -110,7 +110,7 @@ Yes. You can switch between monthly and annual billing at any time from your das<Details summary="What are add-ons and how are they billed?">-Add-ons are workspace-level settings like **White Label**, **Email Authentication**, **IP Restriction**, and **extra status pages**. Once enabled, they apply to your entire workspace. Add-ons are billed monthly regardless of your plan's billing cycle.+Add-ons are workspace-level settings like **White Label**, **Email Authentication**, **IP Restriction**, **extra status pages**, and **extra monitors**. Once enabled, they apply to your entire workspace. Add-ons are billed monthly regardless of your plan's billing cycle.</Details>@@ -135,7 +135,7 @@ Yes. You can cancel anytime from your dashboard. Your plan stays active until th<Details summary="What happens if I exceed my plan limits?">-We will never stop your monitors or status pages without notice. If you approach or exceed a limit, we will reach out to help you pick the right plan. Add-ons like extra status pages are billed per unit as listed in the comparison table.+We will never stop your monitors or status pages without notice. If you approach or exceed a limit, we will reach out to help you pick the right plan. Add-ons like extra status pages and monitor packs are billed per unit as listed in the comparison table.</Details>diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.tsindex 9a43c83df..40e7a5826 100644--- a/packages/api/src/router/stripe/index.ts+++ b/packages/api/src/router/stripe/index.ts@@ -1,5 +1,5 @@import { Events } from "@openstatus/analytics";-import { count, eq, schema } from "@openstatus/db";+import { eq } from "@openstatus/db";import {selectWorkspaceSchema,user,@@ -7,21 +7,36 @@ import {workspace,workspacePlans,} from "@openstatus/db/src/schema";-import { allPlans } from "@openstatus/db/src/schema/plan/config";+import type { AddonQuantityKey } from "@openstatus/db/src/schema/plan/schema";import {addons,billingIntervals,} from "@openstatus/db/src/schema/plan/schema";-import { updateAddonInLimits } from "@openstatus/db/src/schema/plan/utils";+import {+ isAddonQuantityKey,+ updateAddonInLimits,+} from "@openstatus/db/src/schema/plan/utils";+import { countWorkspaceUsage } from "@openstatus/services";import { TRPCError } from "@trpc/server";import type { Stripe } from "stripe";import { z } from "zod";import { createTRPCRouter, protectedProcedure } from "../../trpc";import { stripe } from "./shared";-import { getPriceIdForFeature, getPriceIdForPlan } from "./utils";+import {+ getPlanFromPriceId,+ getPriceIdForFeature,+ getPriceIdForPlan,+ resolveAddonQuantity,+} from "./utils";import { webhookRouter } from "./webhook";+// The addon `title` reads wrong in the "you already have N ..." sentence.+const LIMIT_LABEL: Record<AddonQuantityKey, string> = {+ monitors: "monitors",+ "status-pages": "status pages",+};+const url =process.env.NODE_ENV === "production"? "https://www.openstatus.dev"@@ -239,51 +254,85 @@ export const stripeRouter = createTRPCRouter({});}- const quantity =- typeof opts.input.value === "number" ? opts.input.value : 1;+ const subscriptionId = sub.subscriptions.data[0].id;- // We need to check the total of status page- if (opts.input.feature === "status-pages") {- const statusPageCt = await opts.ctx.db- .select({ count: count() })- .from(schema.page)- .where(eq(schema.page.workspaceId, result.id))- .get();- const pageCount = statusPageCt?.count ?? 0;- if (pageCount > quantity + allPlans[ws.plan].limits["status-pages"]) {+ const items = await stripe.subscriptionItems.list({+ subscription: subscriptionId,+ });++ // Stripe rejects mixed billing intervals on one subscription and every+ // addon price is monthly, so a yearly plan cannot hold one.+ const planItem = items.data.find((item) =>+ getPlanFromPriceId(item.price.id),+ );+ if (planItem?.price.recurring?.interval === "year") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Add-ons are billed monthly. Contact us to add them to a yearly plan.",+ });+ }++ let quantity = 1;+ let newValue: boolean | number = opts.input.value;++ if (typeof opts.input.value === "number") {+ let resolved: ReturnType<typeof resolveAddonQuantity>;+ try {+ resolved = resolveAddonQuantity({+ addon: opts.input.feature,+ plan: ws.plan,+ packs: opts.input.value,+ });+ } catch (e) {throw new TRPCError({code: "BAD_REQUEST",- message: `You already have ${pageCount} status pages, please delete some status page first.`,+ message: e instanceof Error ? e.message : "Invalid quantity",});}- }- const items = await stripe.subscriptionItems.list({- subscription: sub.subscriptions?.data[0]?.id,- });+ quantity = resolved.quantity;+ newValue = resolved.newLimit;++ if (!isAddonQuantityKey(opts.input.feature)) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid feature",+ });+ }++ const current = await countWorkspaceUsage(+ opts.ctx.db,+ result.id,+ opts.input.feature,+ );+ if (current > resolved.newLimit) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `You already have ${current} ${LIMIT_LABEL[opts.input.feature]}, please delete some first.`,+ });+ }+ }const item = items.data.find((item) => item.price.id === priceId);+ const isRemoval = opts.input.value === false || quantity === 0;- if (!opts.input.value && typeof opts.input.value === "boolean" && item) {- await stripe.subscriptionItems.del(item.id);- } else if (typeof opts.input.value === "number" && item) {+ if (isRemoval) {+ if (item) {+ await stripe.subscriptionItems.del(item.id);+ }+ } else if (item) {await stripe.subscriptionItems.update(item.id, {quantity,});} else {await stripe.subscriptionItems.create({price: priceId,- subscription: sub.subscriptions?.data[0]?.id,+ subscription: subscriptionId,quantity,});}- const defaultLimit = allPlans[ws.plan].limits[opts.input.feature];- const newValue =- typeof opts.input.value === "number" && typeof defaultLimit === "number"- ? opts.input.value + defaultLimit- : opts.input.value;-const newLimits = updateAddonInLimits(ws.limits,opts.input.feature,diff --git a/packages/api/src/router/stripe/utils.test.ts b/packages/api/src/router/stripe/utils.test.tsindex 048fd6b54..d130af448 100644--- a/packages/api/src/router/stripe/utils.test.ts+++ b/packages/api/src/router/stripe/utils.test.ts@@ -1,9 +1,17 @@-import { getLimits } from "@openstatus/db/src/schema/plan/utils";+import {+ getAddonPackSize,+ getLimits,+} from "@openstatus/db/src/schema/plan/utils";import { expect } from "@std/expect";import { describe, test } from "@std/testing/bdd";import type Stripe from "stripe";-import { FEATURES, PLANS, buildLimitsFromSubscription } from "./utils";+import {+ FEATURES,+ PLANS,+ buildLimitsFromSubscription,+ resolveAddonQuantity,+} from "./utils";// Derive test-env price ids from the source tables so the test breaks loudly// (assertion failure) rather than silently if a price id changes.@@ -15,6 +23,7 @@ const featurePriceId = (feature: string) =>const STARTER = planPriceId("starter");const WHITE_LABEL = featurePriceId("white-label");const STATUS_PAGES = featurePriceId("status-pages");+const MONITORS = featurePriceId("monitors");function subscriptionWith(items: { priceId: string | undefined; quantity?: number }[],@@ -34,6 +43,7 @@ describe("buildLimitsFromSubscription", () => {expect(STARTER).toBeDefined();expect(WHITE_LABEL).toBeDefined();expect(STATUS_PAGES).toBeDefined();+ expect(MONITORS).toBeDefined();});test("returns null when no plan line item is present", () => {@@ -98,4 +108,129 @@ describe("buildLimitsFromSubscription", () => {),).toThrow(/unsupported stripe price/i);});++ test("one pack addon unit grants `packSize` limit units", () => {+ const planDefault = getLimits("starter").monitors;+ const built = buildLimitsFromSubscription(+ subscriptionWith([+ { priceId: STARTER },+ { priceId: MONITORS, quantity: 3 },+ ]),+ );+ expect(built?.limits.monitors).toBe(planDefault + 30);+ });++ test("missing quantity on a pack addon falls back to one pack", () => {+ const planDefault = getLimits("starter").monitors;+ const built = buildLimitsFromSubscription(+ subscriptionWith([{ priceId: STARTER }, { priceId: MONITORS }]),+ );+ expect(built?.limits.monitors).toBe(planDefault + 10);+ });++ test("repeated pack addon items accumulate", () => {+ const planDefault = getLimits("starter").monitors;+ const built = buildLimitsFromSubscription(+ subscriptionWith([+ { priceId: STARTER },+ { priceId: MONITORS, quantity: 2 },+ { priceId: MONITORS, quantity: 3 },+ ]),+ );+ expect(built?.limits.monitors).toBe(planDefault + 50);+ });++ test("a pack addon does not affect unrelated limits", () => {+ const built = buildLimitsFromSubscription(+ subscriptionWith([+ { priceId: STARTER },+ { priceId: MONITORS, quantity: 3 },+ ]),+ );+ expect(built?.limits["synthetic-checks"]).toBe(+ getLimits("starter")["synthetic-checks"],+ );+ expect(built?.limits["status-pages"]).toBe(+ getLimits("starter")["status-pages"],+ );+ });+});++describe("getAddonPackSize", () => {+ test("returns the pack size for a pack addon", () => {+ expect(getAddonPackSize("monitors")).toBe(10);+ });++ test("defaults to 1 for single-unit and boolean addons", () => {+ expect(getAddonPackSize("status-pages")).toBe(1);+ expect(getAddonPackSize("white-label")).toBe(1);+ });+});++describe("resolveAddonQuantity", () => {+ test("packs map to the stripe quantity untouched", () => {+ const resolved = resolveAddonQuantity({+ addon: "monitors",+ plan: "starter",+ packs: 3,+ });+ expect(resolved.quantity).toBe(3);+ expect(resolved.packSize).toBe(10);+ expect(resolved.maxPacks).toBe(10);+ });++ test("newLimit is the plan default plus packs times pack size", () => {+ const planDefault = getLimits("team").monitors;+ const resolved = resolveAddonQuantity({+ addon: "monitors",+ plan: "team",+ packs: 4,+ });+ expect(resolved.newLimit).toBe(planDefault + 40);+ });++ test("zero packs resolves to the plan default", () => {+ const resolved = resolveAddonQuantity({+ addon: "monitors",+ plan: "starter",+ packs: 0,+ });+ expect(resolved.quantity).toBe(0);+ expect(resolved.newLimit).toBe(getLimits("starter").monitors);+ });++ test("single-unit addons are unaffected by the pack multiplier", () => {+ const planDefault = getLimits("starter")["status-pages"];+ const resolved = resolveAddonQuantity({+ addon: "status-pages",+ plan: "starter",+ packs: 3,+ });+ expect(resolved.newLimit).toBe(planDefault + 3);+ expect(resolved.maxPacks).toBeNull();+ });++ test("rejects more packs than the self-serve ceiling", () => {+ expect(() =>+ resolveAddonQuantity({ addon: "monitors", plan: "starter", packs: 11 }),+ ).toThrow(/up to 100/);+ });++ test("allows exactly the ceiling", () => {+ const resolved = resolveAddonQuantity({+ addon: "monitors",+ plan: "starter",+ packs: 10,+ });+ expect(resolved.newLimit).toBe(getLimits("starter").monitors + 100);+ });++ test("rejects negative and fractional pack counts", () => {+ expect(() =>+ resolveAddonQuantity({ addon: "monitors", plan: "starter", packs: -1 }),+ ).toThrow(/whole number of packs/);+ expect(() =>+ resolveAddonQuantity({ addon: "monitors", plan: "starter", packs: 1.5 }),+ ).toThrow(/whole number of packs/);+ });});diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.tsindex 5e0c410a7..fd9e8393e 100644--- a/packages/api/src/router/stripe/utils.ts+++ b/packages/api/src/router/stripe/utils.ts@@ -1,12 +1,15 @@// Shamelessly stolen from dub.coimport type { WorkspacePlan } from "@openstatus/db/src/schema";+import { allPlans } from "@openstatus/db/src/schema/plan/config";import type {Addons,BillingInterval,Limits,} from "@openstatus/db/src/schema/plan/schema";import {+ getAddonMaxQuantity,+ getAddonPackSize,getLimits,updateAddonInLimits,} from "@openstatus/db/src/schema/plan/utils";@@ -40,16 +43,62 @@ export function buildLimitsFromSubscription();}// Accumulate onto the running value so repeated addon items add up; boolean- // addons just flip on.+ // addons just flip on. One unit of a pack addon grants `packSize` units.const current = limits[feature.feature];const value =- typeof current === "number" ? current + (item.quantity ?? 1) : true;+ typeof current === "number"+ ? current + (item.quantity ?? 1) * getAddonPackSize(feature.feature)+ : true;limits = updateAddonInLimits(limits, feature.feature, value);}return { plan: detectedPlan.plan, limits };}+/**+ * Resolve a requested pack count into the Stripe subscription quantity and the+ * workspace limit it produces. Throws when the request is not a whole number of+ * packs or exceeds the self-serve ceiling.+ */+export function resolveAddonQuantity(args: {+ addon: keyof Addons;+ plan: WorkspacePlan;+ packs: number;+}): {+ quantity: number;+ newLimit: number;+ packSize: number;+ maxPacks: number | null;+} {+ const { addon, plan, packs } = args;+ const packSize = getAddonPackSize(addon);+ const maxPacks = getAddonMaxQuantity(addon);++ if (!Number.isInteger(packs) || packs < 0) {+ throw new Error(+ `Quantity must be a whole number of packs, received ${packs}`,+ );+ }++ if (maxPacks !== null && packs > maxPacks) {+ throw new Error(+ `You can add up to ${maxPacks * packSize} with this add-on. Contact us for more.`,+ );+ }++ const planDefault = allPlans[plan].limits[addon];+ if (typeof planDefault !== "number") {+ throw new Error(`${addon} is not a quantity add-on`);+ }++ return {+ quantity: packs,+ newLimit: planDefault + packs * packSize,+ packSize,+ maxPacks,+ };+}+export const getPlanFromPriceId = (priceId: string) => {const env =process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";@@ -201,6 +250,19 @@ export const FEATURES = [},},},+ {+ feature: "monitors",+ price: {+ monthly: {+ priceIds: {+ // TODO: create the "Monitor Pack" product and its monthly+ // multi-currency price (USD 15 / EUR 15) in Stripe, then paste the ids.+ test: "price_1UChsCBXJcTfzsyJgomhUtYY",+ production: "price_1UChsCBXJcTfzsyJgomhUtYY",+ },+ },+ },+ },{feature: "sso",price: {diff --git a/packages/db/src/schema/plan/config.ts b/packages/db/src/schema/plan/config.tsindex 9dad7b549..3f1c9e26c 100644--- a/packages/db/src/schema/plan/config.ts+++ b/packages/db/src/schema/plan/config.ts@@ -122,6 +122,14 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {EUR: 20,},},+ monitors: {+ title: "Monitor Pack",+ description: "Add 10 monitors to your workspace.",+ price: {+ USD: 15,+ EUR: 15,+ },+ },sso: {title: "SAML Single Sign-On",description:@@ -217,6 +225,14 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {EUR: 20,},},+ monitors: {+ title: "Monitor Pack",+ description: "Add 10 monitors to your workspace.",+ price: {+ USD: 15,+ EUR: 15,+ },+ },sso: {title: "SAML Single Sign-On",description:@@ -285,6 +301,14 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {EUR: 20,},},+ monitors: {+ title: "Monitor Pack",+ description: "Add 10 monitors to your workspace.",+ price: {+ USD: 15,+ EUR: 15,+ },+ },sso: {title: "SAML Single Sign-On",description:diff --git a/packages/db/src/schema/plan/schema.ts b/packages/db/src/schema/plan/schema.tsindex 00050b375..deeccba95 100644--- a/packages/db/src/schema/plan/schema.ts+++ b/packages/db/src/schema/plan/schema.ts@@ -94,9 +94,25 @@ export const addons = ["white-label","custom-theme","status-pages",+ "monitors","sso",] as const satisfies Partial<keyof Limits>[];+// Declares which add-ons are sold by quantity, what one subscription unit grants+// and the self-serve ceiling. Both keys are also service `LimitKey`s, which is+// what lets the purchase guard count current usage for them.+export const addonQuantityConfig = {+ "status-pages": { packSize: 1, maxQuantity: null },+ monitors: { packSize: 10, maxQuantity: 10 },+} as const satisfies Partial<+ Record<+ (typeof addons)[number],+ { packSize: number; maxQuantity: number | null }+ >+>;++export type AddonQuantityKey = keyof typeof addonQuantityConfig;+export const addonsSchema = z.partialRecord(z.enum(addons),z.object({diff --git a/packages/db/src/schema/plan/utils.ts b/packages/db/src/schema/plan/utils.tsindex 3b4d9b8bb..015425435 100644--- a/packages/db/src/schema/plan/utils.ts+++ b/packages/db/src/schema/plan/utils.ts@@ -2,6 +2,8 @@ import type { WorkspacePlan } from "../workspaces/validation";import { allPlans } from "./config";import {type Addons,+ type AddonQuantityKey,+ addonQuantityConfig,type BillingInterval,type Limits,limitsSchema,@@ -66,6 +68,24 @@ export function getPriceConfig(return resolvePriceConfig(planConfig.price[interval], currency);}+export function isAddonQuantityKey(+ addon: keyof Addons,+): addon is AddonQuantityKey {+ return addon in addonQuantityConfig;+}++export function getAddonQuantityConfig(addon: keyof Addons) {+ return isAddonQuantityKey(addon) ? addonQuantityConfig[addon] : null;+}++export function getAddonPackSize(addon: keyof Addons): number {+ return getAddonQuantityConfig(addon)?.packSize ?? 1;+}++export function getAddonMaxQuantity(addon: keyof Addons): number | null {+ return getAddonQuantityConfig(addon)?.maxQuantity ?? null;+}+export function getAddonPriceConfig(plan: WorkspacePlan,addon: keyof Addons,diff --git a/packages/services/src/index.ts b/packages/services/src/index.tsindex 839140752..fa50b9f7e 100644--- a/packages/services/src/index.ts+++ b/packages/services/src/index.ts@@ -47,6 +47,7 @@ export { matchesScope, requireScope } from "./auth";export {LIMIT_KEYS,assertWithinLimit,+ countWorkspaceUsage,getPlanLimits,type LimitKey,} from "./limits";diff --git a/packages/services/src/limits.ts b/packages/services/src/limits.tsindex d583afa3d..e8736ba28 100644--- a/packages/services/src/limits.ts+++ b/packages/services/src/limits.ts@@ -93,7 +93,7 @@ export async function getWorkspaceLimit(* The `default` branch is unreachable β `never` makes a new `LimitKey`* without a counter a compile error rather than a runtime surprise.*/-async function countCurrent(+export async function countWorkspaceUsage(tx: DB,workspaceId: number,limit: LimitKey,@@ -148,7 +148,7 @@ async function countCurrent(default: {const unhandled: never = limit;throw new Error(- `assertWithinLimit: counter for "${unhandled}" not implemented. Add a case in countCurrent in packages/services/src/limits.ts.`,+ `assertWithinLimit: counter for "${unhandled}" not implemented. Add a case in countWorkspaceUsage in packages/services/src/limits.ts.`,);}}@@ -163,7 +163,7 @@ export async function assertWithinLimit(args: {const { tx, workspaceId, limit, delta = 1 } = args;const max = await getWorkspaceLimit(tx, workspaceId, limit);- const current = await countCurrent(tx, workspaceId, limit);+ const current = await countWorkspaceUsage(tx, workspaceId, limit);if (current + delta > max) {throw new LimitExceededError(limit, max, current);}