Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat(emails): wave 1 billing emails (downgrade, cancellation, trial) (#2742)
Maximilian Kaske926f31257884
diff --git a/apps/web/src/app/api/webhook/stripe/route.ts b/apps/web/src/app/api/webhook/stripe/route.tsindex 992eae4d8..291d699b6 100644--- a/apps/web/src/app/api/webhook/stripe/route.ts+++ b/apps/web/src/app/api/webhook/stripe/route.ts@@ -33,6 +33,11 @@ export async function POST(req: NextRequest) {event,});break;+ case "customer.subscription.trial_will_end":+ await caller.stripeRouter.webhooks.customerSubscriptionTrialWillEnd({+ event,+ });+ break;case "customer.subscription.deleted":await caller.stripeRouter.webhooks.customerSubscriptionDeleted({event,diff --git a/packages/api/src/router/stripe/webhook.test.ts b/packages/api/src/router/stripe/webhook.test.tsnew file mode 100644index 000000000..42ea398eb--- /dev/null+++ b/packages/api/src/router/stripe/webhook.test.ts@@ -0,0 +1,519 @@+import { db, eq } from "@openstatus/db";+import {+ page,+ user,+ usersToWorkspaces,+ workspace,+} from "@openstatus/db/src/schema";+import {+ addUserToWorkspace,+ createPage,+ createTestWorkspace,+ createUser,+} from "@openstatus/db/src/test/factories";+import { delivery, resend } from "@openstatus/emails/src/send";+import { expect } from "@std/expect";+import { afterEach, beforeEach, describe, test } from "@std/testing/bdd";+import { assertSpyCalls, type Stub, stub } from "@std/testing/mock";+import type Stripe from "stripe";++import { lambdaRouter } from "../../lambda";+import { createInnerTRPCContext } from "../../trpc";+import { stripe } from "./shared";+import { PLANS } from "./utils";++const TEAM_PRICE = PLANS.find((p) => p.plan === "team")?.price.monthly.priceIds+ .test;+const DAY = 86_400;+const now = () => Math.floor(Date.now() / 1000);++// biome-ignore lint/suspicious/noExplicitAny: stubs over the Stripe and Resend clients+type AnyStub = Stub<any>;++function subscription(+ customer: string,+ overrides: Partial<Stripe.Subscription> = {},+) {+ return {+ id: "sub_test_1",+ customer,+ status: "active",+ created: now() - 30 * DAY,+ cancel_at_period_end: false,+ current_period_end: now() + 10 * DAY,+ metadata: {},+ items: { data: [{ price: { id: TEAM_PRICE }, quantity: 1 }] },+ ...overrides,+ } as unknown as Stripe.Subscription;+}++function event(+ type: string,+ object: Stripe.Subscription,+ previous_attributes?: Record<string, unknown>,+ id = `evt_${crypto.randomUUID()}`,+) {+ return {+ event: {+ id,+ created: now(),+ type,+ // biome-ignore lint/suspicious/noExplicitAny: zod record input+ data: { object: object as any, previous_attributes },+ },+ };+}++const caller = () =>+ lambdaRouter.createCaller(createInnerTRPCContext({ session: null }))+ .stripeRouter.webhooks;++describe("stripe webhook emails", () => {+ let live: Stripe.Subscription[];+ let stubs: AnyStub[];+ let send: AnyStub;+ let batch: AnyStub;+ let cancelEmail: AnyStub;+ let updateSubscription: AnyStub;++ beforeEach(() => {+ live = [];+ // biome-ignore lint/suspicious/noExplicitAny: Resend result double+ const ok = { data: { id: "email_reminder_1" }, error: null } as any;+ send = stub(resend.emails, "send", () => Promise.resolve(ok));+ batch = stub(resend.batch, "send", () => Promise.resolve(ok));+ cancelEmail = stub(resend.emails, "cancel", () => Promise.resolve(ok));+ updateSubscription = stub(stripe.subscriptions, "update", () =>+ // biome-ignore lint/suspicious/noExplicitAny: Stripe response double+ Promise.resolve({ cancel_at_period_end: true } as any),+ );+ stubs = [+ send,+ batch,+ cancelEmail,+ updateSubscription,+ stub(delivery, "enabled", () => true),+ stub(+ stripe.subscriptions,+ "list",+ // biome-ignore lint/suspicious/noExplicitAny: auto-paging list double+ () => ({ autoPagingToArray: () => Promise.resolve(live) }) as any,+ ),+ stub(stripe.customers, "retrieve", () =>+ Promise.resolve({+ deleted: false,+ email: "[email protected]",+ // biome-ignore lint/suspicious/noExplicitAny: Stripe customer double+ } as any),+ ),+ ];+ });++ afterEach(() => {+ for (const s of stubs) s.restore();+ });++ function failSends() {+ send.restore();+ batch.restore();+ stubs = stubs.filter((s) => s !== send && s !== batch);+ send = stub(resend.emails, "send", () =>+ Promise.reject(new Error("resend is down")),+ );+ batch = stub(resend.batch, "send", () =>+ Promise.reject(new Error("resend is down")),+ );+ stubs.push(send, batch);+ }++ async function seed() {+ const fixture = await createTestWorkspace();+ const ownerEmail = `owner-${fixture.user.id}@example.test`;+ await db+ .update(user)+ .set({ email: ownerEmail })+ .where(eq(user.id, fixture.user.id));+ return {+ ...fixture,+ ownerEmail,+ stripeId: fixture.workspace.stripeId ?? "",+ };+ }++ describe("customer.subscription.deleted", () => {+ test("live subscriptions left → no downgrade, no email", async () => {+ const s = await seed();+ live = [subscription(s.stripeId)];++ await caller().customerSubscriptionDeleted(+ event("customer.subscription.deleted", subscription(s.stripeId)),+ );++ const ws = await db+ .select()+ .from(workspace)+ .where(eq(workspace.id, s.workspace.id))+ .get();+ expect(ws?.plan).toBe("team");+ assertSpyCalls(send, 0);+ assertSpyCalls(batch, 0);+ });++ test("none left → plan-downgraded to owners + customer, member-removed per trimmed member", async () => {+ const s = await seed();+ const member = await createUser();+ const memberEmail = `member-${member.id}@example.test`;+ await db+ .update(user)+ .set({ email: memberEmail })+ .where(eq(user.id, member.id));+ await addUserToWorkspace(member.id, s.workspace.id, "member");+ // no email on file: cannot be notified, but still counts as removed+ const silent = await createUser({ email: null });+ await addUserToWorkspace(silent.id, s.workspace.id, "member");+ await createPage(s.workspace.id, {+ title: "Kept",+ createdAt: new Date("2020-01-01T00:00:00Z"),+ });+ await createPage(s.workspace.id, {+ title: "Gone",+ createdAt: new Date("2021-01-01T00:00:00Z"),+ });++ const evt = event(+ "customer.subscription.deleted",+ subscription(s.stripeId, { status: "canceled" }),+ );+ await caller().customerSubscriptionDeleted(evt);++ assertSpyCalls(send, 1);+ const [payload, options] = send.calls[0].args;+ expect(payload.to).toEqual([+ s.ownerEmail,+ "[email protected]",+ ]);+ expect(payload.subject).toBe(+ "Your workspace is on the free plan — 1 status page deleted",+ );+ expect(options).toEqual({+ idempotencyKey: `stripe:${evt.event.id}:plan-downgraded`,+ });+ expect(payload.react.props.loss.membersRemoved).toBe(2);++ assertSpyCalls(batch, 1);+ const [emails, batchOptions] = batch.calls[0].args;+ expect(emails.map((e: { to: string }) => e.to)).toEqual([memberEmail]);+ expect(emails[0].html).toContain(s.ownerEmail);+ expect(batchOptions).toEqual({+ idempotencyKey: `stripe:${evt.event.id}:member-removed:0`,+ });++ const pages = await db+ .select()+ .from(page)+ .where(eq(page.workspaceId, s.workspace.id))+ .all();+ expect(pages.length).toBe(1);+ });++ test("a mail failure never fails the handler; the downgrade is committed", async () => {+ const s = await seed();+ const member = await createUser();+ await db+ .update(user)+ .set({ email: `member-${member.id}@example.test` })+ .where(eq(user.id, member.id));+ await addUserToWorkspace(member.id, s.workspace.id, "member");+ failSends();++ await caller().customerSubscriptionDeleted(+ event(+ "customer.subscription.deleted",+ subscription(s.stripeId, { status: "canceled" }),+ ),+ );++ const ws = await db+ .select()+ .from(workspace)+ .where(eq(workspace.id, s.workspace.id))+ .get();+ expect(ws?.plan).toBe("free");+ assertSpyCalls(send, 1);+ assertSpyCalls(batch, 1);+ const members = await db+ .select()+ .from(usersToWorkspaces)+ .where(eq(usersToWorkspaces.workspaceId, s.workspace.id))+ .all();+ expect(members.length).toBe(1);+ });+ });++ describe("customer.subscription.updated", () => {+ test("cancel_at_period_end false → true: confirmation sent, reminder scheduled, id stored", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];+ // The raw payload's period end is not trustworthy; only live state is.+ const raw = subscription(s.stripeId, {+ cancel_at_period_end: true,+ current_period_end: now() + 25 * DAY,+ });++ const evt = event("customer.subscription.updated", raw, {+ cancel_at_period_end: false,+ });+ await caller().customerSubscriptionUpdated(evt);++ assertSpyCalls(send, 2);+ const [confirmation, confirmationOptions] = send.calls[0].args;+ expect(confirmation.subject).toBe("Your openstatus cancellation");+ expect(confirmation.to).toEqual([+ s.ownerEmail,+ "[email protected]",+ ]);+ expect(confirmationOptions).toEqual({+ idempotencyKey: `stripe:${evt.event.id}:cancellation-scheduled`,+ });++ const [reminder, reminderOptions] = send.calls[1].args;+ expect(new Date(reminder.scheduledAt).getTime()).toBe(+ (sub.current_period_end - 3 * DAY) * 1000,+ );+ expect(reminderOptions).toEqual({+ idempotencyKey: `stripe:${evt.event.id}:plan-ending-soon`,+ });++ assertSpyCalls(updateSubscription, 1);+ expect(updateSubscription.calls[0].args).toEqual([+ sub.id,+ { metadata: { reminder_email_id: "email_reminder_1" } },+ ]);+ });++ test("period end beyond 30 days: confirmation only, nothing stored", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, {+ cancel_at_period_end: true,+ current_period_end: now() + 200 * DAY,+ });+ live = [sub];++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: false,+ }),+ );++ assertSpyCalls(send, 1);+ expect(send.calls[0].args[0].scheduledAt).toBeUndefined();+ assertSpyCalls(updateSubscription, 0);+ });++ test("true → false: the scheduled reminder is cancelled and the id cleared", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, {+ metadata: { reminder_email_id: "email_reminder_1" },+ });+ live = [sub];++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: true,+ }),+ );++ assertSpyCalls(send, 0);+ assertSpyCalls(cancelEmail, 1);+ expect(cancelEmail.calls[0].args[0]).toBe("email_reminder_1");+ expect(updateSubscription.calls[0].args).toEqual([+ sub.id,+ { metadata: { reminder_email_id: "" } },+ ]);+ });++ test("a stale cancel event after a resume sends nothing", async () => {+ const s = await seed();+ live = [subscription(s.stripeId, { cancel_at_period_end: false })];++ await caller().customerSubscriptionUpdated(+ event(+ "customer.subscription.updated",+ subscription(s.stripeId, { cancel_at_period_end: true }),+ { cancel_at_period_end: false },+ ),+ );++ assertSpyCalls(send, 0);+ assertSpyCalls(updateSubscription, 0);+ });++ test("a resume racing the metadata write cancels the fresh reminder", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];+ updateSubscription.restore();+ stubs = stubs.filter((x) => x !== updateSubscription);+ updateSubscription = stub(stripe.subscriptions, "update", () =>+ // biome-ignore lint/suspicious/noExplicitAny: Stripe response double+ Promise.resolve({ cancel_at_period_end: false } as any),+ );+ stubs.push(updateSubscription);++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: false,+ }),+ );++ expect(cancelEmail.calls[0].args[0]).toBe("email_reminder_1");+ expect(updateSubscription.calls.map((c) => c.args[1])).toEqual([+ { metadata: { reminder_email_id: "email_reminder_1" } },+ { metadata: { reminder_email_id: "" } },+ ]);+ });++ test("a failed reminder cancel keeps the id for a retry", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, {+ metadata: { reminder_email_id: "email_reminder_1" },+ });+ live = [sub];+ cancelEmail.restore();+ stubs = stubs.filter((x) => x !== cancelEmail);+ cancelEmail = stub(resend.emails, "cancel", () =>+ Promise.resolve({+ data: null,+ error: { name: "application_error" },+ // biome-ignore lint/suspicious/noExplicitAny: Resend error double+ } as any),+ );+ stubs.push(cancelEmail);++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: true,+ }),+ );++ assertSpyCalls(cancelEmail, 1);+ assertSpyCalls(updateSubscription, 0);+ });++ test("a failed confirmation does not suppress the reminder", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];+ send.restore();+ stubs = stubs.filter((x) => x !== send);+ let calls = 0;+ send = stub(resend.emails, "send", () =>+ calls++ === 0+ ? Promise.reject(new Error("resend is down"))+ : // biome-ignore lint/suspicious/noExplicitAny: Resend result double+ Promise.resolve({+ data: { id: "email_reminder_1" },+ error: null,+ } as any),+ );+ stubs.push(send);++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: false,+ }),+ );++ assertSpyCalls(send, 2);+ expect(send.calls[1].args[0].scheduledAt).toBeDefined();+ assertSpyCalls(updateSubscription, 1);+ });++ test("metadata-only update and unrelated updates send nothing", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, { metadata: {} }),+ );+ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub),+ );++ assertSpyCalls(send, 0);+ assertSpyCalls(cancelEmail, 0);+ assertSpyCalls(updateSubscription, 0);+ });++ test("a replayed event reuses the same idempotency keys", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];+ const evt = event("customer.subscription.updated", sub, {+ cancel_at_period_end: false,+ });++ await caller().customerSubscriptionUpdated(evt);+ await caller().customerSubscriptionUpdated(evt);++ const keys = send.calls.map((c) => c.args[1].idempotencyKey);+ expect(keys.slice(0, 2)).toEqual(keys.slice(2, 4));+ });++ test("a mail failure does not fail the plan sync", async () => {+ const s = await seed();+ const sub = subscription(s.stripeId, { cancel_at_period_end: true });+ live = [sub];+ failSends();++ await caller().customerSubscriptionUpdated(+ event("customer.subscription.updated", sub, {+ cancel_at_period_end: false,+ }),+ );++ const ws = await db+ .select()+ .from(workspace)+ .where(eq(workspace.id, s.workspace.id))+ .get();+ expect(ws?.subscriptionId).toBe(sub.id);+ });+ });++ describe("customer.subscription.trial_will_end", () => {+ test("sends trial-ending once per event with trial_end in the body", async () => {+ const s = await seed();+ const trialEnd = Math.floor(+ new Date("2026-09-25T00:00:00Z").getTime() / 1000,+ );+ const evt = event(+ "customer.subscription.trial_will_end",+ subscription(s.stripeId, { status: "trialing", trial_end: trialEnd }),+ );++ await caller().customerSubscriptionTrialWillEnd(evt);++ assertSpyCalls(send, 1);+ const [payload, options] = send.calls[0].args;+ expect(payload.subject).toBe("Your openstatus trial ends soon");+ expect(payload.to).toContain(s.ownerEmail);+ expect(options).toEqual({+ idempotencyKey: `stripe:${evt.event.id}:trial-ending`,+ });+ });++ test("no trial_end → nothing sent", async () => {+ const s = await seed();+ await caller().customerSubscriptionTrialWillEnd(+ event(+ "customer.subscription.trial_will_end",+ subscription(s.stripeId, { trial_end: null }),+ ),+ );+ assertSpyCalls(send, 0);+ });+ });+});diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.tsindex faacd48a2..dbcf101a8 100644--- a/packages/api/src/router/stripe/webhook.ts+++ b/packages/api/src/router/stripe/webhook.ts@@ -1,11 +1,22 @@import { Events, setupAnalytics } from "@openstatus/analytics";import { and, eq } from "@openstatus/db";import { user, usersToWorkspaces } from "@openstatus/db/src/schema";-import { SsoDisabledEmail, sendEmail } from "@openstatus/emails";+import {+ billingRecipients,+ cancelScheduledEmail,+ schedulePlanEndingSoon,+ sendCancellationScheduled,+ sendMemberRemoved,+ sendPlanDowngraded,+ sendTrialEnding,+ stripeIdempotencyKey,+} from "@openstatus/emails";import type { ServiceContext } from "@openstatus/services";import {+ type DowngradeTrim,downgradeWorkspaceToFree,getWorkspaceByStripeId,+ previewWorkspaceDowngrade,updateWorkspacePlan,} from "@openstatus/services/workspace";import { TRPCError } from "@trpc/server";@@ -32,12 +43,115 @@ const webhookProcedure = publicProcedure.input(created: z.number(),data: z.object({object: z.record(z.string(), z.any()),+ previous_attributes: z.record(z.string(), z.any()).optional(),}),type: z.string(),}),}),);+// Stripe subscription metadata key holding the Resend id of the scheduled+// "plan ends in 3 days" reminder, so a resume can cancel it without a schema+// change.+const REMINDER_METADATA_KEY = "reminder_email_id";++type Db = Parameters<typeof getWorkspaceByStripeId>[0]["db"];++async function getOwnerEmails(db: NonNullable<Db>, workspaceId: number) {+ const owners = await db+ .select({ email: user.email })+ .from(usersToWorkspaces)+ .innerJoin(user, eq(user.id, usersToWorkspaces.userId))+ .where(+ and(+ eq(usersToWorkspaces.workspaceId, workspaceId),+ eq(usersToWorkspaces.role, "owner"),+ ),+ )+ .all();+ return owners.map((owner) => owner.email);+}++async function getBillingRecipients(+ db: NonNullable<Db>,+ workspaceId: number,+ customerId: string,+) {+ const owners = await getOwnerEmails(db, workspaceId);+ const customer = await stripe.customers.retrieve(customerId);+ return billingRecipients(owners, customer.deleted ? null : customer.email);+}++function toPlanLoss(+ trim: DowngradeTrim,+ customDomains: string[],+ sso: boolean,+) {+ return {+ monitorsDeactivated: trim.monitorsDeactivated,+ pagesDeleted: trim.pagesDeleted,+ keptPageTitle: trim.keptPageTitle,+ notificationsDeleted: trim.notificationsDeleted,+ invitationsDeleted: trim.invitationsDeleted,+ // the count, not the notifiable emails: members without one still left+ membersRemoved: trim.membersRemovedCount,+ customDomains,+ sso,+ };+}++async function sendCancellationEmails(args: {+ db: NonNullable<Db>;+ ws: NonNullable<Awaited<ReturnType<typeof getWorkspaceByStripeId>>>;+ customerId: string;+ current: Stripe.Subscription;+ plan: string;+ eventId: string;+}) {+ const { db, ws, customerId, current, plan, eventId } = args;+ const endsAt = new Date(current.current_period_end * 1000);+ const to = await getBillingRecipients(db, ws.id, customerId);+ const preview = await previewWorkspaceDowngrade({+ ctx: {+ workspace: ws,+ actor: { type: "system", job: "stripe-subscription-updated" },+ db,+ },+ });+ const loss = toPlanLoss(preview, preview.customDomains, preview.ssoEnabled);++ // Independent: a failed confirmation must not suppress the reminder.+ try {+ await sendCancellationScheduled({ to, eventId, plan, endsAt, loss });+ } catch (err) {+ console.error("Failed to send cancellation confirmation:", err);+ }++ const reminderId = await schedulePlanEndingSoon({+ to,+ eventId,+ workspaceSlug: ws.slug,+ plan,+ endsAt,+ loss,+ });+ if (!reminderId) return;++ const updated = await stripe.subscriptions.update(current.id, {+ metadata: { [REMINDER_METADATA_KEY]: reminderId },+ });+ // A resume handled while we were scheduling found no id to cancel. The+ // update response is the state after our write, so undo the reminder here.+ if (+ !updated.cancel_at_period_end &&+ (await cancelScheduledEmail(reminderId))+ ) {+ await stripe.subscriptions.update(current.id, {+ metadata: { [REMINDER_METADATA_KEY]: "" },+ });+ }+}+export const webhookRouter = createTRPCRouter({customerSubscriptionUpdated: webhookProcedure.mutation(async (opts) => {const eventSubscription = opts.input.event.data@@ -114,6 +228,45 @@ export const webhookRouter = createTRPCRouter({},});+ // Best-effort: the one place the raw event is read instead of live state.+ // The mail is keyed by event id, so a replay cannot re-send, and our own+ // metadata write below fires an update whose `previous_attributes` holds+ // only `metadata`, so it is ignored here.+ const wasCancelling =+ opts.input.event.data.previous_attributes?.cancel_at_period_end;+ const isCancelling = current.cancel_at_period_end;+ // The event must carry a real flip, and live state must agree with it: a+ // late cancel event after a resume (or the reverse) is stale and ignored.+ if (+ eventSubscription.id === current.id &&+ typeof wasCancelling === "boolean" &&+ wasCancelling !== eventSubscription.cancel_at_period_end &&+ eventSubscription.cancel_at_period_end === isCancelling+ ) {+ try {+ if (isCancelling) {+ await sendCancellationEmails({+ db: opts.ctx.db,+ ws,+ customerId,+ current,+ plan: built.plan,+ eventId: opts.input.event.id,+ });+ } else {+ const reminderId = current.metadata?.[REMINDER_METADATA_KEY];+ // Keep the id when the cancel fails, so a retry can still cancel it.+ if (reminderId && (await cancelScheduledEmail(reminderId))) {+ await stripe.subscriptions.update(current.id, {+ metadata: { [REMINDER_METADATA_KEY]: "" },+ });+ }+ }+ } catch (err) {+ console.error("Failed to handle cancellation emails:", err);+ }+ }+const newPlan = built.plan;if (newPlan !== oldPlan) {const customer = await stripe.customers.retrieve(customerId);@@ -229,6 +382,35 @@ export const webhookRouter = createTRPCRouter({await analytics.track(Events.UpgradeWorkspace);}}),+ customerSubscriptionTrialWillEnd: webhookProcedure.mutation(async (opts) => {+ const subscription = opts.input.event.data.object as Stripe.Subscription;+ const customerId =+ typeof subscription.customer === "string"+ ? subscription.customer+ : subscription.customer.id;+ if (!subscription.trial_end) return;++ const ws = await getWorkspaceByStripeId({+ input: { stripeId: customerId },+ db: opts.ctx.db,+ });+ if (!ws) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Workspace not found",+ });+ }++ try {+ await sendTrialEnding({+ to: await getBillingRecipients(opts.ctx.db, ws.id, customerId),+ eventId: opts.input.event.id,+ trialEnd: new Date(subscription.trial_end * 1000),+ });+ } catch (err) {+ console.error("Failed to send trial ending email:", err);+ }+ }),customerSubscriptionDeleted: webhookProcedure.mutation(async (opts) => {const subscription = opts.input.event.data.object as Stripe.Subscription;const customerId =@@ -269,41 +451,37 @@ export const webhookRouter = createTRPCRouter({db: opts.ctx.db,};- const { customDomains, ssoDisabled } = await downgradeWorkspaceToFree({- ctx,- });+ const { customDomains, ssoDisabled, trimmed } =+ await downgradeWorkspaceToFree({ ctx });- // Best-effort after commit: owners must know SSO stopped working, but a- // mail failure must not fail the webhook into Stripe retries.- if (ssoDisabled) {- try {- const owners = await opts.ctx.db- .select({ email: user.email })- .from(usersToWorkspaces)- .innerJoin(user, eq(user.id, usersToWorkspaces.userId))- .where(- and(- eq(usersToWorkspaces.workspaceId, ws.id),- eq(usersToWorkspaces.role, "owner"),- ),- )- .all();-- const to = owners- .map((owner) => owner.email)- .filter((email): email is string => Boolean(email));-- if (to.length > 0) {- await sendEmail({- from: "Thibault from openstatus <[email protected]>",- subject: "SSO has been disabled for your workspace",- to,- react: SsoDisabledEmail(),- });- }- } catch (err) {- console.error("Failed to notify owners about SSO being disabled:", err);- }+ // Best-effort after commit: owners must know what the cascade removed, and+ // removed members that they lost access, but a mail failure must not fail+ // the webhook into Stripe retries — nor one mail suppress the other.+ const eventId = opts.input.event.id;+ let owners: Array<string | null> = [];+ try {+ owners = await getOwnerEmails(opts.ctx.db, ws.id);+ const customer = await stripe.customers.retrieve(customerId);+ await sendPlanDowngraded({+ to: billingRecipients(owners, customer.deleted ? null : customer.email),+ eventId,+ workspaceSlug: ws.slug,+ previousPlan: ws.plan ?? "paid",+ loss: toPlanLoss(trimmed, customDomains, ssoDisabled),+ });+ } catch (err) {+ console.error("Failed to send plan-downgraded email:", err);+ }+ try {+ await sendMemberRemoved({+ to: trimmed.membersRemoved,+ idempotencyKey: stripeIdempotencyKey(eventId, "member-removed"),+ workspaceName: ws.name || ws.slug,+ reason: "downgrade",+ owners: billingRecipients(owners),+ });+ } catch (err) {+ console.error("Failed to send member-removed emails:", err);}// Free plan has no custom-domain feature — release each domain on Verceldiff --git a/packages/emails/emails/_components/plan-loss.ts b/packages/emails/emails/_components/plan-loss.tsnew file mode 100644index 000000000..bafc3efb4--- /dev/null+++ b/packages/emails/emails/_components/plan-loss.ts@@ -0,0 +1,70 @@+import { plural } from "./format";+import type { KeyValueRow } from "./key-value";++export interface PlanLoss {+ monitorsDeactivated: number;+ pagesDeleted: string[];+ keptPageTitle?: string | null;+ notificationsDeleted: number;+ invitationsDeleted: number;+ membersRemoved: number;+ customDomains: string[];+ sso: boolean;+}++/** Rows for what a downgrade removed (`past`) or will remove. Zero rows are dropped. */+export function planLossRows(loss: PlanLoss, past: boolean): KeyValueRow[] {+ const rows: KeyValueRow[] = [];+ if (loss.pagesDeleted.length > 0) {+ rows.push({+ label: past ? "Status pages deleted" : "Status pages that get deleted",+ value: loss.pagesDeleted.join(", "),+ tone: "danger",+ });+ }+ if (loss.keptPageTitle) {+ rows.push({ label: "Status page kept", value: loss.keptPageTitle });+ }+ if (loss.monitorsDeactivated > 0) {+ rows.push({+ label: past ? "Monitors paused" : "Monitors that get paused",+ value: `${plural(loss.monitorsDeactivated, "monitor")}, oldest stays active`,+ });+ }+ if (loss.membersRemoved > 0) {+ rows.push({+ label: past ? "Members removed" : "Members that lose access",+ value: plural(loss.membersRemoved, "member"),+ });+ }+ if (loss.invitationsDeleted > 0) {+ rows.push({+ label: "Pending invitations",+ value: `${loss.invitationsDeleted} ${past ? "deleted" : "get deleted"}`,+ });+ }+ if (loss.notificationsDeleted > 0) {+ rows.push({+ label: "Notification channels",+ value: `${loss.notificationsDeleted} ${past ? "removed" : "get removed"}, one stays`,+ });+ }+ if (loss.customDomains.length > 0) {+ rows.push({+ label: `Custom domain${loss.customDomains.length === 1 ? "" : "s"}${+ past ? " released" : ""+ }`,+ value: loss.customDomains.join(", "),+ mono: true,+ });+ }+ if (loss.sso) {+ rows.push({+ label: "SAML SSO",+ value: past+ ? "Off, IdP configuration kept"+ : "Turns off, IdP configuration kept",+ });+ }+ return rows;+}diff --git a/packages/emails/emails/cancellation-scheduled.tsx b/packages/emails/emails/cancellation-scheduled.tsxnew file mode 100644index 000000000..b19a228a1--- /dev/null+++ b/packages/emails/emails/cancellation-scheduled.tsx@@ -0,0 +1,77 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Body, Head, Html, Preview } from "react-email";++import { formatDay } from "./_components/format";+import { BILLING_URL } from "./plan-downgraded";++export interface CancellationScheduledProps {+ plan: string;+ endsAt: Date;+ /** Short plain-text lines, e.g. "2 status pages get deleted". */+ losses: string[];+}++export const CANCELLATION_SCHEDULED_SUBJECT = "Your openstatus cancellation";++const CancellationScheduledEmail = ({+ plan,+ endsAt,+ losses,+}: CancellationScheduledProps) => {+ return (+ <Html>+ <Head>+ <title>{CANCELLATION_SCHEDULED_SUBJECT}</title>+ </Head>+ <Preview>+ Your plan runs until {formatDay(endsAt)}. One question if you have a+ minute.+ </Preview>+ <Body>+ Hey 👋+ <br />+ <br />I saw you cancelled your {plan} plan. It keeps running until{" "}+ {formatDay(endsAt)}, nothing changes before then.+ <br />+ <br />+ {losses.length > 0 ? (+ <>+ On that day the workspace moves to the free plan, which means:+ <br />+ {losses.map((loss) => (+ <span key={loss}>+ – {loss}+ <br />+ </span>+ ))}+ <br />+ </>+ ) : null}+ Changed your mind? You can{" "}+ <a href={BILLING_URL}>resume the subscription</a> any time before it+ ends.+ <br />+ <br />+ One question, if you have a minute: what made you cancel? Hit reply — I+ read every response, and it is the most useful thing you can tell us.+ <br />+ <br />+ Thibault Le Ouay Ducasse, co-founder of openstatus+ <br />+ </Body>+ </Html>+ );+};++CancellationScheduledEmail.PreviewProps = {+ plan: "team",+ endsAt: new Date("2026-09-25T00:00:00Z"),+ losses: [+ "1 status page gets deleted (Acme API)",+ "11 monitors get paused",+ "4 members lose access",+ ],+} satisfies CancellationScheduledProps;++export default CancellationScheduledEmail;diff --git a/packages/emails/emails/member-removed.tsx b/packages/emails/emails/member-removed.tsxnew file mode 100644index 000000000..c7d2c3d7c--- /dev/null+++ b/packages/emails/emails/member-removed.tsx@@ -0,0 +1,57 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";+import { Layout } from "./_components/layout";++export interface MemberRemovedProps {+ workspaceName: string;+ reason: "downgrade" | "manual";+ /** Who to ask for access again. */+ owners: string[];+}++export function memberRemovedSubject(props: MemberRemovedProps): string {+ return `You no longer have access to ${props.workspaceName} on openstatus`;+}++const MemberRemovedEmail = (props: MemberRemovedProps) => {+ return (+ <Layout+ preview={+ props.owners.length > 0+ ? `Ask ${props.owners[0]} if you need access again.`+ : "Ask a workspace owner if you need access again."+ }+ pill={{ tone: "neutral", label: "Account change" }}+ footer={+ <Footer reason="You get this because you were a member of this workspace." />+ }+ >+ <Heading title={`You were removed from ${props.workspaceName}`}>+ {props.reason === "downgrade"+ ? "The workspace’s subscription ended and the free plan holds a single member, so every other member was removed. Your openstatus account and your other workspaces are unchanged."+ : "A workspace owner removed you. Your openstatus account and your other workspaces are unchanged."}+ </Heading>+ {props.owners.length > 0 ? (+ <KeyValue+ rows={[+ {+ label: "Ask for access",+ value: props.owners.join(", "),+ },+ ]}+ />+ ) : null}+ </Layout>+ );+};++MemberRemovedEmail.PreviewProps = {+ workspaceName: "Acme",+ reason: "downgrade",+ owners: ["[email protected]"],+} satisfies MemberRemovedProps;++export default MemberRemovedEmail;diff --git a/packages/emails/emails/plan-downgraded.tsx b/packages/emails/emails/plan-downgraded.tsxnew file mode 100644index 000000000..db5a5cc9b--- /dev/null+++ b/packages/emails/emails/plan-downgraded.tsx@@ -0,0 +1,96 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Actions } from "./_components/actions";+import { Callout } from "./_components/callout";+import { Footer } from "./_components/footer";+import { Heading, Mono } from "./_components/heading";+import { KeyValue } from "./_components/key-value";+import { Layout } from "./_components/layout";+import { type PlanLoss, planLossRows } from "./_components/plan-loss";+import { Signature } from "./_components/signature";++export interface PlanDowngradedProps {+ workspaceSlug: string;+ /** Plan the workspace was on, e.g. "team". */+ previousPlan: string;+ loss: PlanLoss;+}++export const BILLING_URL = "https://app.openstatus.dev/settings/billing";+export const BILLING_FOOTER_REASON =+ "Sent to workspace owners and the billing contact.";++export function planDowngradedSubject(props: PlanDowngradedProps): string {+ const pages = props.loss.pagesDeleted.length;+ return pages > 0+ ? `Your workspace is on the free plan — ${pages} status page${+ pages === 1 ? "" : "s"+ } deleted`+ : "Your workspace is on the free plan — here is what changed";+}++const PlanDowngradedEmail = (props: PlanDowngradedProps) => {+ const { loss } = props;+ const rows = planLossRows(loss, true);+ return (+ <Layout+ preview="What was removed, what survived, and how to re-subscribe."+ pill={{ tone: "neutral", label: "Account change" }}+ footer={<Footer reason={BILLING_FOOTER_REASON} />}+ >+ <Heading+ title={+ <>+ <Mono>{props.workspaceSlug}</Mono> is back on the free plan+ </>+ }+ >+ Your {props.previousPlan} subscription ended, so the workspace was+ trimmed to what the free plan holds.+ </Heading>+ {loss.pagesDeleted.length > 0 ? (+ <Callout title="Deleted status pages cannot be restored">+ Everything else is reversible: paused monitors keep their history and+ resume when you switch them back on, and re-subscribing lets you+ invite your team again.+ </Callout>+ ) : (+ <Callout title="No status page was deleted">+ Paused monitors keep their history and resume when you switch them+ back on, and re-subscribing lets you invite your team again.+ </Callout>+ )}+ <KeyValue+ rows={[+ { label: "Plan", value: `${props.previousPlan} → free` },+ ...rows,+ ]}+ />+ <Actions+ primary={{ label: "Re-subscribe", href: BILLING_URL }}+ secondary={{+ label: "Compare plans",+ href: "https://www.openstatus.dev/pricing",+ }}+ />+ <Signature />+ </Layout>+ );+};++PlanDowngradedEmail.PreviewProps = {+ workspaceSlug: "acme-dev",+ previousPlan: "team",+ loss: {+ monitorsDeactivated: 11,+ pagesDeleted: ["Acme API", "Acme EU"],+ keptPageTitle: "Acme",+ notificationsDeleted: 3,+ invitationsDeleted: 1,+ membersRemoved: 4,+ customDomains: ["status.acme.dev"],+ sso: true,+ },+} satisfies PlanDowngradedProps;++export default PlanDowngradedEmail;diff --git a/packages/emails/emails/plan-ending-soon.tsx b/packages/emails/emails/plan-ending-soon.tsxnew file mode 100644index 000000000..563f3097b--- /dev/null+++ b/packages/emails/emails/plan-ending-soon.tsx@@ -0,0 +1,73 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Actions } from "./_components/actions";+import { Callout } from "./_components/callout";+import { Footer } from "./_components/footer";+import { formatDay, formatLongDay, formatShortDay } from "./_components/format";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";+import { Layout } from "./_components/layout";+import { type PlanLoss, planLossRows } from "./_components/plan-loss";+import { Signature } from "./_components/signature";+import { BILLING_FOOTER_REASON, BILLING_URL } from "./plan-downgraded";++export interface PlanEndingSoonProps {+ workspaceSlug: string;+ plan: string;+ endsAt: Date;+ /** Counted when the cancellation was scheduled. */+ loss: PlanLoss;+}++export function planEndingSoonSubject(props: PlanEndingSoonProps): string {+ return `Your ${props.plan} plan ends on ${formatShortDay(props.endsAt)} — resume to keep everything`;+}++const PlanEndingSoonEmail = (props: PlanEndingSoonProps) => {+ const rows = planLossRows(props.loss, false);+ return (+ <Layout+ preview="What the workspace loses when it moves to the free plan."+ pill={{ tone: "neutral", label: "Action needed" }}+ footer={<Footer reason={BILLING_FOOTER_REASON} />}+ >+ <Heading+ title={`Your ${props.plan} plan ends on ${formatLongDay(props.endsAt)}`}+ >+ The subscription is set to cancel. On that day the workspace moves to+ the free plan and is trimmed to what it holds.+ </Heading>+ <Callout title="Resuming keeps everything">+ Nothing changes until the plan ends. Resume the subscription before then+ and nothing below happens.+ </Callout>+ <KeyValue+ rows={[+ { label: "Workspace", value: props.workspaceSlug, mono: true },+ { label: "Plan ends", value: formatDay(props.endsAt), bold: true },+ ...rows,+ ]}+ />+ <Actions primary={{ label: "Resume subscription", href: BILLING_URL }} />+ <Signature />+ </Layout>+ );+};++PlanEndingSoonEmail.PreviewProps = {+ workspaceSlug: "acme-dev",+ plan: "team",+ endsAt: new Date("2026-09-25T00:00:00Z"),+ loss: {+ monitorsDeactivated: 11,+ pagesDeleted: ["Acme API"],+ keptPageTitle: "Acme",+ notificationsDeleted: 3,+ invitationsDeleted: 0,+ membersRemoved: 4,+ customDomains: [],+ sso: false,+ },+} satisfies PlanEndingSoonProps;++export default PlanEndingSoonEmail;diff --git a/packages/emails/emails/sso-disabled.tsx b/packages/emails/emails/sso-disabled.tsxdeleted file mode 100644index 05471021b..000000000--- a/packages/emails/emails/sso-disabled.tsx+++ /dev/null@@ -1,47 +0,0 @@-/** @jsxRuntime automatic @jsxImportSource react */--import { Actions } from "./_components/actions";-import { Callout } from "./_components/callout";-import { Footer } from "./_components/footer";-import { Heading } from "./_components/heading";-import { KeyValue } from "./_components/key-value";-import { Layout } from "./_components/layout";-import { Signature } from "./_components/signature";--const SsoDisabledEmail = () => {- return (- <Layout- preview="Owners can still sign in with GitHub or Google. Re-subscribing restores SSO."- pill={{ tone: "neutral", label: "Account change" }}- footer={<Footer reason="Sent to workspace owners." />}- >- <Heading title="SAML single sign-on has been turned off">- Your subscription ended, and SSO is a paid add-on.- </Heading>- <Callout title="Your setup is kept">- You can still sign in with GitHub or Google. Your identity provider- configuration is kept, so re-subscribing restores SSO without- reconnecting anything.- </Callout>- <KeyValue- rows={[- { label: "Sign-in methods left", value: "GitHub, Google" },- { label: "IdP configuration", value: "Kept", tone: "success" },- ]}- />- <Actions- primary={{- label: "View billing",- href: "https://app.openstatus.dev/settings/billing",- }}- secondary={{- label: "Compare plans",- href: "https://www.openstatus.dev/pricing",- }}- />- <Signature />- </Layout>- );-};--export default SsoDisabledEmail;diff --git a/packages/emails/emails/trial-ending.tsx b/packages/emails/emails/trial-ending.tsxnew file mode 100644index 000000000..70f5e6b89--- /dev/null+++ b/packages/emails/emails/trial-ending.tsx@@ -0,0 +1,53 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Body, Head, Html, Preview } from "react-email";++import { formatDay } from "./_components/format";+import { BILLING_URL } from "./plan-downgraded";++export interface TrialEndingProps {+ trialEnd: Date;+}++export const TRIAL_ENDING_SUBJECT = "Your openstatus trial ends soon";++const TrialEndingEmail = ({ trialEnd }: TrialEndingProps) => {+ return (+ <Html>+ <Head>+ <title>{TRIAL_ENDING_SUBJECT}</title>+ </Head>+ <Preview>+ It ends on {formatDay(trialEnd)}. What happens next depends on your+ card.+ </Preview>+ <Body>+ Hey 👋+ <br />+ <br />+ Your openstatus trial ends on {formatDay(trialEnd)}.+ <br />+ <br />+ With a card on file, the plan simply continues. Without one, the+ workspace moves to the free plan that day: all but one status page are+ deleted, all but one monitor are paused, and every member except the+ owner loses access.+ <br />+ <br />👉 <a href={BILLING_URL}>Check your billing settings</a>+ <br />+ <br />+ Need more time or have a question? Hit reply — I read every response.+ <br />+ <br />+ Thibault Le Ouay Ducasse, co-founder of openstatus+ <br />+ </Body>+ </Html>+ );+};++TrialEndingEmail.PreviewProps = {+ trialEnd: new Date("2026-09-25T00:00:00Z"),+} satisfies TrialEndingProps;++export default TrialEndingEmail;diff --git a/packages/emails/src/billing.test.tsx b/packages/emails/src/billing.test.tsxnew file mode 100644index 000000000..a00340bf6--- /dev/null+++ b/packages/emails/src/billing.test.tsx@@ -0,0 +1,469 @@+/** @jsxRuntime automatic @jsxImportSource react */++import "./test-preload.ts";+import { expect } from "@std/expect";+import { afterEach, beforeEach, describe, test } from "@std/testing/bdd";+import { assertSpyCalls, type Stub, stub } from "@std/testing/mock";+import { render } from "react-email";++import type { PlanLoss } from "../emails/_components/plan-loss";+import CancellationScheduledEmail from "../emails/cancellation-scheduled";+import MemberRemovedEmail from "../emails/member-removed";+import PlanDowngradedEmail, {+ planDowngradedSubject,+} from "../emails/plan-downgraded";+import PlanEndingSoonEmail, {+ planEndingSoonSubject,+} from "../emails/plan-ending-soon";+import TrialEndingEmail from "../emails/trial-ending";+import {+ billingRecipients,+ planLossLines,+ reminderScheduledAt,+ schedulePlanEndingSoon,+ sendCancellationScheduled,+ sendMemberRemoved,+ sendPlanDowngraded,+ sendTrialEnding,+} from "./billing";+import { cancelScheduledEmail, delivery, resend, sendEmail } from "./send";++const loss = {+ monitorsDeactivated: 11,+ pagesDeleted: ["Acme API", "Acme EU"],+ keptPageTitle: "Acme",+ notificationsDeleted: 3,+ invitationsDeleted: 1,+ membersRemoved: 4,+ customDomains: ["status.acme.dev"],+ sso: true,+} satisfies PlanLoss;++const nothing = {+ monitorsDeactivated: 0,+ pagesDeleted: [],+ keptPageTitle: null,+ notificationsDeleted: 0,+ invitationsDeleted: 0,+ membersRemoved: 0,+ customDomains: [],+ sso: false,+} satisfies PlanLoss;++const endsAt = new Date("2026-09-25T00:00:00Z");++describe("billing templates", () => {+ test("plan-downgraded names deleted pages and counts everything else", async () => {+ const props = { workspaceSlug: "acme-dev", previousPlan: "team", loss };+ const html = await render(<PlanDowngradedEmail {...props} />);+ expect(html).toContain("ACCOUNT CHANGE");+ expect(html).toContain("acme-dev");+ expect(html).toContain("team → free");+ expect(html).toContain("Acme API, Acme EU");+ expect(html).toContain("Deleted status pages cannot be restored");+ expect(html).toContain("11 monitors, oldest stays active");+ expect(html).toContain("4 members");+ expect(html).toContain("status.acme.dev");+ expect(html).toContain("Off, IdP configuration kept");+ expect(html).toContain("workspace owners and the billing contact");+ expect(html).toContain("Co-founder, openstatus");+ expect(html).toContain(+ 'href="https://app.openstatus.dev/settings/billing"',+ );+ expect(planDowngradedSubject(props)).toBe(+ "Your workspace is on the free plan — 2 status pages deleted",+ );+ });++ test("plan-downgraded with nothing trimmed drops every loss row", async () => {+ const props = {+ workspaceSlug: "acme-dev",+ previousPlan: "starter",+ loss: nothing,+ };+ const html = await render(<PlanDowngradedEmail {...props} />);+ expect(html).toContain("No status page was deleted");+ expect(html).not.toContain("Status pages deleted");+ expect(html).not.toContain("Members removed");+ expect(html).not.toContain("SAML SSO");+ expect(planDowngradedSubject(props)).toBe(+ "Your workspace is on the free plan — here is what changed",+ );+ });++ test("plan-ending-soon is dated and in the future tense", async () => {+ const props = { workspaceSlug: "acme-dev", plan: "team", endsAt, loss };+ const html = await render(<PlanEndingSoonEmail {...props} />);+ expect(html).toContain("ACTION NEEDED");+ expect(html).toContain("Your team plan ends on Friday 25 September");+ expect(html).toContain("Fri 25 Sep 2026");+ expect(html).toContain("Status pages that get deleted");+ expect(html).toContain("Resume subscription");+ expect(planEndingSoonSubject(props)).toBe(+ "Your team plan ends on 25 Sep — resume to keep everything",+ );+ });++ test("member-removed: one line, who to ask, no CTA", async () => {+ const html = await render(+ <MemberRemovedEmail+ workspaceName="Acme"+ reason="downgrade"+ owners={["[email protected]"]}+ />,+ );+ expect(html).toContain("You were removed from Acme");+ expect(html).toContain("subscription ended");+ expect(html).toContain("[email protected]");+ expect(html).not.toContain("app.openstatus.dev");++ const manual = await render(+ <MemberRemovedEmail workspaceName="Acme" reason="manual" owners={[]} />,+ );+ expect(manual).toContain("A workspace owner removed you");+ expect(manual).not.toContain("Ask for access");+ });++ test("cancellation-scheduled is raw: no layout, date, losses, resume link", async () => {+ const html = await render(+ <CancellationScheduledEmail+ plan="team"+ endsAt={endsAt}+ losses={planLossLines(loss)}+ />,+ );+ expect(html).toContain("Fri 25 Sep 2026");+ expect(html).toContain("2 status pages get deleted (Acme API, Acme EU)");+ expect(html).toContain("4 members lose access");+ expect(html).toContain("what made you cancel?");+ expect(html).toContain(+ 'href="https://app.openstatus.dev/settings/billing"',+ );+ expect(html).not.toContain("max-width:600px");++ const bare = await render(+ <CancellationScheduledEmail plan="team" endsAt={endsAt} losses={[]} />,+ );+ expect(bare).not.toContain("moves to the free plan");+ });++ test("trial-ending says what gets removed", async () => {+ const html = await render(<TrialEndingEmail trialEnd={endsAt} />);+ expect(html).toContain("Fri 25 Sep 2026");+ expect(html).toContain("all but one status page are");+ expect(html).not.toContain("max-width:600px");+ });++ test("loss lines use singular forms", () => {+ expect(+ planLossLines({+ ...nothing,+ pagesDeleted: ["A"],+ monitorsDeactivated: 1,+ membersRemoved: 1,+ }),+ ).toEqual([+ "1 status page gets deleted (A)",+ "1 monitor gets paused",+ "1 member loses access",+ ]);+ });++ test("loss lines cover every destructive change", () => {+ expect(+ planLossLines({+ ...nothing,+ invitationsDeleted: 2,+ notificationsDeleted: 1,+ customDomains: ["a.dev", "b.dev"],+ sso: true,+ }),+ ).toEqual([+ "2 pending invitations get deleted",+ "1 notification channel gets removed",+ "the custom domains a.dev, b.dev are released",+ "SAML SSO turns off",+ ]);+ });++ test("custom domain label follows the count", async () => {+ const one = await render(+ <PlanDowngradedEmail+ workspaceSlug="a"+ previousPlan="team"+ loss={{ ...nothing, customDomains: ["a.dev"] }}+ />,+ );+ expect(one).toContain("Custom domain released");+ const two = await render(+ <PlanDowngradedEmail+ workspaceSlug="a"+ previousPlan="team"+ loss={{ ...nothing, customDomains: ["a.dev", "b.dev"] }}+ />,+ );+ expect(two).toContain("Custom domains released");+ });+});++describe("billingRecipients", () => {+ test("owners + customer, case-insensitive dedupe, empties dropped", () => {+ expect(+ billingRecipients(+ ["[email protected]", "", null, " ", "[email protected]"],+ "[email protected]",+ ),+ ).toEqual(["[email protected]", "[email protected]"]);+ expect(billingRecipients([], "[email protected]")).toEqual([+ "[email protected]",+ ]);+ expect(billingRecipients([undefined], null)).toEqual([]);+ });+});++describe("reminderScheduledAt", () => {+ const now = new Date("2026-09-01T00:00:00Z");++ test("period end minus 3 days", () => {+ expect(reminderScheduledAt(endsAt, now)?.toISOString()).toBe(+ "2026-09-22T00:00:00.000Z",+ );+ });++ test("null inside the lead window and beyond Resend's 30 days", () => {+ expect(reminderScheduledAt(new Date("2026-09-03T00:00:00Z"), now)).toBe(+ null,+ );+ expect(reminderScheduledAt(new Date("2027-03-01T00:00:00Z"), now)).toBe(+ null,+ );+ });+});++describe("send plumbing", () => {+ let send: Stub, batch: Stub, cancel: Stub, enabled: Stub;+ // safe because the verbs only read `data.id` and `error.name`+ const result = (value: unknown) => Promise.resolve(value as never);+ const ok = { data: { id: "email_123" }, error: null };++ beforeEach(() => {+ enabled = stub(delivery, "enabled", () => true);+ send = stub(resend.emails, "send", () => result(ok));+ batch = stub(resend.batch, "send", () => result(ok));+ cancel = stub(resend.emails, "cancel", () => result(ok));+ });++ afterEach(() => {+ for (const s of [enabled, send, batch, cancel]) s.restore();+ });++ const email = {+ from: "a <[email protected]>",+ to: ["[email protected]"],+ subject: "s",+ react: <TrialEndingEmail trialEnd={endsAt} />,+ };++ test("sendEmail forwards idempotencyKey and scheduledAt, returns the id", async () => {+ const id = await sendEmail(+ { ...email, reply_to: "[email protected]" },+ { idempotencyKey: "k", scheduledAt: "2026-09-22T00:00:00.000Z" },+ );+ expect(id).toBe("email_123");+ expect(send.calls[0].args[0].scheduledAt).toBe("2026-09-22T00:00:00.000Z");+ expect(send.calls[0].args[0].replyTo).toBe("[email protected]");+ expect(send.calls[0].args[1]).toEqual({ idempotencyKey: "k" });+ });++ test("sendEmail omits both when not given", async () => {+ await sendEmail(email);+ expect("scheduledAt" in send.calls[0].args[0]).toBe(false);+ expect(send.calls[0].args[1]).toBeUndefined();+ });++ test("sendEmail does nothing outside production", async () => {+ enabled.restore();+ enabled = stub(delivery, "enabled", () => false);+ expect(await sendEmail(email)).toBeUndefined();+ assertSpyCalls(send, 0);+ });++ test("an idempotency conflict or Resend error never throws", async () => {+ for (const name of ["invalid_idempotent_request", "application_error"]) {+ send.restore();+ send = stub(resend.emails, "send", () =>+ result({ data: null, error: { name } }),+ );+ expect(await sendEmail(email, { idempotencyKey: "k" })).toBeUndefined();+ assertSpyCalls(send, 1);+ }+ });++ test("cancelScheduledEmail wraps emails.cancel and reports success", async () => {+ expect(await cancelScheduledEmail("email_123")).toBe(true);+ expect(cancel.calls[0].args[0]).toBe("email_123");++ cancel.restore();+ cancel = stub(resend.emails, "cancel", () =>+ result({ data: null, error: { name: "application_error" } }),+ );+ expect(await cancelScheduledEmail("email_123")).toBe(false);+ });++ test("sendMemberRemoved chunks at Resend's 100-email batch limit", async () => {+ await sendMemberRemoved({+ to: Array.from({ length: 250 }, (_, i) => `m${i}@acme.dev`),+ idempotencyKey: "stripe:evt_1:member-removed",+ workspaceName: "Acme",+ reason: "downgrade",+ owners: [],+ });+ assertSpyCalls(batch, 3);+ expect(batch.calls.map((c) => c.args[0].length)).toEqual([100, 100, 50]);+ expect(batch.calls.map((c) => c.args[1].idempotencyKey)).toEqual([+ "stripe:evt_1:member-removed:0",+ "stripe:evt_1:member-removed:1",+ "stripe:evt_1:member-removed:2",+ ]);+ });++ test("a batch error is swallowed, not thrown", async () => {+ batch.restore();+ batch = stub(resend.batch, "send", () =>+ result({ data: null, error: { name: "application_error" } }),+ );+ await sendMemberRemoved({+ to: ["[email protected]"],+ workspaceName: "Acme",+ reason: "downgrade",+ owners: [],+ });+ assertSpyCalls(batch, 1);+ });++ test("sendPlanDowngraded", async () => {+ await sendPlanDowngraded({+ to: ["[email protected]"],+ eventId: "evt_1",+ workspaceSlug: "acme-dev",+ previousPlan: "team",+ loss,+ });+ const [payload, options] = send.calls[0].args;+ expect(payload.to).toEqual(["[email protected]"]);+ expect(payload.from).toBe(+ "Thibault from openstatus <[email protected]>",+ );+ expect(payload.replyTo).toBe("[email protected]");+ expect(payload.subject).toBe(+ "Your workspace is on the free plan — 2 status pages deleted",+ );+ expect(options).toEqual({ idempotencyKey: "stripe:evt_1:plan-downgraded" });+ });++ test("sendMemberRemoved batches one mail per member under one key", async () => {+ await sendMemberRemoved({+ to: ["[email protected]", "[email protected]"],+ idempotencyKey: "stripe:evt_1:member-removed",+ workspaceName: "Acme",+ reason: "downgrade",+ owners: ["[email protected]"],+ });+ const [emails, options] = batch.calls[0].args;+ expect(emails.map((e: { to: string }) => e.to)).toEqual([+ "[email protected]",+ "[email protected]",+ ]);+ expect(emails[0].from).toBe(+ "openstatus <[email protected]>",+ );+ expect(emails[0].replyTo).toBe("[email protected]");+ expect(emails[0].subject).toBe(+ "You no longer have access to Acme on openstatus",+ );+ expect(emails[0].html).toContain("[email protected]");+ expect(options).toEqual({+ idempotencyKey: "stripe:evt_1:member-removed:0",+ });+ });++ test("sendCancellationScheduled is raw, from the root domain", async () => {+ await sendCancellationScheduled({+ to: ["[email protected]"],+ eventId: "evt_2",+ plan: "team",+ endsAt,+ loss,+ });+ const [payload, options] = send.calls[0].args;+ expect(payload.from).toBe(+ "Thibault from openstatus <[email protected]>",+ );+ expect(payload.subject).toBe("Your openstatus cancellation");+ expect(options).toEqual({+ idempotencyKey: "stripe:evt_2:cancellation-scheduled",+ });+ });++ test("schedulePlanEndingSoon schedules 3 days before and returns the id", async () => {+ const id = await schedulePlanEndingSoon({+ to: ["[email protected]"],+ eventId: "evt_2",+ workspaceSlug: "acme-dev",+ plan: "team",+ endsAt,+ loss,+ now: new Date("2026-09-01T00:00:00Z"),+ });+ expect(id).toBe("email_123");+ const [payload, options] = send.calls[0].args;+ expect(payload.scheduledAt).toBe("2026-09-22T00:00:00.000Z");+ expect(options).toEqual({+ idempotencyKey: "stripe:evt_2:plan-ending-soon",+ });+ });++ test("schedulePlanEndingSoon skips a period end beyond 30 days", async () => {+ const id = await schedulePlanEndingSoon({+ to: ["[email protected]"],+ eventId: "evt_2",+ workspaceSlug: "acme-dev",+ plan: "team",+ endsAt: new Date("2027-03-01T00:00:00Z"),+ loss,+ now: new Date("2026-09-01T00:00:00Z"),+ });+ expect(id).toBeUndefined();+ assertSpyCalls(send, 0);+ });++ test("sendTrialEnding", async () => {+ await sendTrialEnding({+ to: ["[email protected]"],+ eventId: "evt_3",+ trialEnd: endsAt,+ });+ const [payload, options] = send.calls[0].args;+ expect(payload.subject).toBe("Your openstatus trial ends soon");+ expect(options).toEqual({ idempotencyKey: "stripe:evt_3:trial-ending" });+ });++ test("no verb sends without recipients", async () => {+ await sendPlanDowngraded({+ to: [],+ eventId: "e",+ workspaceSlug: "a",+ previousPlan: "team",+ loss,+ });+ await sendMemberRemoved({+ to: [],+ workspaceName: "A",+ reason: "downgrade",+ owners: [],+ });+ await sendTrialEnding({ to: [], eventId: "e", trialEnd: endsAt });+ assertSpyCalls(send, 0);+ assertSpyCalls(batch, 0);+ });+});diff --git a/packages/emails/src/billing.tsx b/packages/emails/src/billing.tsxnew file mode 100644index 000000000..f44dd5529--- /dev/null+++ b/packages/emails/src/billing.tsx@@ -0,0 +1,226 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { render } from "react-email";++import { plural } from "../emails/_components/format";+import type { PlanLoss } from "../emails/_components/plan-loss";+import CancellationScheduledEmail, {+ CANCELLATION_SCHEDULED_SUBJECT,+} from "../emails/cancellation-scheduled";+import MemberRemovedEmail, {+ type MemberRemovedProps,+ memberRemovedSubject,+} from "../emails/member-removed";+import PlanDowngradedEmail, {+ type PlanDowngradedProps,+ planDowngradedSubject,+} from "../emails/plan-downgraded";+import PlanEndingSoonEmail, {+ type PlanEndingSoonProps,+ planEndingSoonSubject,+} from "../emails/plan-ending-soon";+import TrialEndingEmail from "../emails/trial-ending";+import { TRIAL_ENDING_SUBJECT } from "../emails/trial-ending";+import { sendBatchEmailHtml, sendEmail } from "./send";++const RAW_FROM = "Thibault from openstatus <[email protected]>";+// Signed hybrid: personal name on the system subdomain, replies to a real inbox.+const SIGNED_FROM =+ "Thibault from openstatus <[email protected]>";+const SIGNED_REPLY_TO = "[email protected]";+const SYSTEM_FROM = "openstatus <[email protected]>";+const SUPPORT_EMAIL = "[email protected]";++const DAY_MS = 86_400_000;+export const REMINDER_LEAD_DAYS = 3;+const RESEND_MAX_SCHEDULE_DAYS = 30;+const RESEND_BATCH_SIZE = 100;++/** `stripe:<event.id>:<template>` — a Stripe redelivery reuses the event id. */+export function stripeIdempotencyKey(eventId: string, template: string) {+ return `stripe:${eventId}:${template}`;+}++/** Workspace owners + Stripe customer email, deduped case-insensitively. */+export function billingRecipients(+ owners: Array<string | null | undefined>,+ customerEmail?: string | null,+): string[] {+ const seen = new Set<string>();+ const result: string[] = [];+ for (const raw of [...owners, customerEmail]) {+ const email = raw?.trim();+ if (!email) continue;+ const key = email.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ result.push(email);+ }+ return result;+}++/** Plain-text loss lines for the raw cancellation email. */+export function planLossLines(loss: PlanLoss): string[] {+ const lines: string[] = [];+ if (loss.pagesDeleted.length > 0) {+ const n = loss.pagesDeleted.length;+ lines.push(+ `${plural(n, "status page")} ${n === 1 ? "gets" : "get"} deleted (${loss.pagesDeleted.join(", ")})`,+ );+ }+ if (loss.monitorsDeactivated > 0) {+ const n = loss.monitorsDeactivated;+ lines.push(`${plural(n, "monitor")} ${n === 1 ? "gets" : "get"} paused`);+ }+ if (loss.membersRemoved > 0) {+ const n = loss.membersRemoved;+ lines.push(`${plural(n, "member")} ${n === 1 ? "loses" : "lose"} access`);+ }+ if (loss.invitationsDeleted > 0) {+ const n = loss.invitationsDeleted;+ lines.push(+ `${plural(n, "pending invitation")} ${n === 1 ? "gets" : "get"} deleted`,+ );+ }+ if (loss.notificationsDeleted > 0) {+ const n = loss.notificationsDeleted;+ lines.push(+ `${plural(n, "notification channel")} ${n === 1 ? "gets" : "get"} removed`,+ );+ }+ if (loss.customDomains.length > 0) {+ const many = loss.customDomains.length > 1;+ lines.push(+ `the custom domain${many ? "s" : ""} ${loss.customDomains.join(", ")} ${+ many ? "are" : "is"+ } released`,+ );+ }+ if (loss.sso) lines.push("SAML SSO turns off");+ return lines;+}++/**+ * When to send the "plan ends in 3 days" reminder, or null when it cannot be+ * scheduled: already inside the lead window, or beyond Resend's 30-day limit.+ */+export function reminderScheduledAt(endsAt: Date, now = new Date()) {+ const at = new Date(endsAt.getTime() - REMINDER_LEAD_DAYS * DAY_MS);+ if (at.getTime() <= now.getTime()) return null;+ if (at.getTime() - now.getTime() > RESEND_MAX_SCHEDULE_DAYS * DAY_MS) {+ return null;+ }+ return at;+}++export async function sendPlanDowngraded(+ req: PlanDowngradedProps & { to: string[]; eventId: string },+) {+ if (req.to.length === 0) return;+ const { to, eventId, ...props } = req;+ return sendEmail(+ {+ from: SIGNED_FROM,+ reply_to: SIGNED_REPLY_TO,+ to,+ subject: planDowngradedSubject(props),+ react: <PlanDowngradedEmail {...props} />,+ },+ { idempotencyKey: stripeIdempotencyKey(eventId, "plan-downgraded") },+ );+}++export async function sendMemberRemoved(+ req: MemberRemovedProps & { to: string[]; idempotencyKey?: string },+) {+ if (req.to.length === 0) return;+ const { to, idempotencyKey, ...props } = req;+ const html = await render(<MemberRemovedEmail {...props} />);+ // Resend's batch API takes at most 100 emails.+ for (let i = 0; i < to.length; i += RESEND_BATCH_SIZE) {+ await sendBatchEmailHtml(+ to.slice(i, i + RESEND_BATCH_SIZE).map((email) => ({+ from: SYSTEM_FROM,+ reply_to: SUPPORT_EMAIL,+ to: email,+ subject: memberRemovedSubject(props),+ html,+ })),+ {+ idempotencyKey: idempotencyKey+ ? `${idempotencyKey}:${i / RESEND_BATCH_SIZE}`+ : undefined,+ },+ );+ }+}++export async function sendCancellationScheduled(req: {+ to: string[];+ eventId: string;+ plan: string;+ endsAt: Date;+ loss: PlanLoss;+}) {+ if (req.to.length === 0) return;+ return sendEmail(+ {+ from: RAW_FROM,+ to: req.to,+ subject: CANCELLATION_SCHEDULED_SUBJECT,+ react: (+ <CancellationScheduledEmail+ plan={req.plan}+ endsAt={req.endsAt}+ losses={planLossLines(req.loss)}+ />+ ),+ },+ {+ idempotencyKey: stripeIdempotencyKey(+ req.eventId,+ "cancellation-scheduled",+ ),+ },+ );+}++/** Returns the Resend id to cancel on resume, or undefined if not scheduled. */+export async function schedulePlanEndingSoon(+ req: PlanEndingSoonProps & { to: string[]; eventId: string; now?: Date },+) {+ if (req.to.length === 0) return;+ const { to, eventId, now, ...props } = req;+ const scheduledAt = reminderScheduledAt(props.endsAt, now);+ if (!scheduledAt) return;+ return sendEmail(+ {+ from: SIGNED_FROM,+ reply_to: SIGNED_REPLY_TO,+ to,+ subject: planEndingSoonSubject(props),+ react: <PlanEndingSoonEmail {...props} />,+ },+ {+ idempotencyKey: stripeIdempotencyKey(eventId, "plan-ending-soon"),+ scheduledAt: scheduledAt.toISOString(),+ },+ );+}++export async function sendTrialEnding(req: {+ to: string[];+ eventId: string;+ trialEnd: Date;+}) {+ if (req.to.length === 0) return;+ return sendEmail(+ {+ from: RAW_FROM,+ to: req.to,+ subject: TRIAL_ENDING_SUBJECT,+ react: <TrialEndingEmail trialEnd={req.trialEnd} />,+ },+ { idempotencyKey: stripeIdempotencyKey(req.eventId, "trial-ending") },+ );+}diff --git a/packages/emails/src/index.ts b/packages/emails/src/index.tsindex c37ac682f..24220f1d4 100644--- a/packages/emails/src/index.ts+++ b/packages/emails/src/index.ts@@ -9,9 +9,22 @@ export { default as MonitorPausedEmail } from "../emails/monitor-paused";export { default as MonitorDeactivationEmail } from "../emails/monitor-deactivation";export { default as PrivateLocationAlertEmail } from "../emails/private-location-alert";export { default as StatusPageMagicLinkEmail } from "../emails/status-page-magic-link";-export { default as SsoDisabledEmail } from "../emails/sso-disabled";export { monitorDeactivationEmail, monitorPausedEmail } from "./render";-export { sendEmail, sendEmailHtml, sendBatchEmailHtml } from "./send";+export {+ cancelScheduledEmail,+ sendEmail,+ sendEmailHtml,+ sendBatchEmailHtml,+} from "./send";+export {+ billingRecipients,+ schedulePlanEndingSoon,+ sendCancellationScheduled,+ sendMemberRemoved,+ sendPlanDowngraded,+ sendTrialEnding,+ stripeIdempotencyKey,+} from "./billing";export { EmailClient } from "./client";diff --git a/packages/emails/src/send.ts b/packages/emails/src/send.tsindex e63f1c422..265521746 100644--- a/packages/emails/src/send.ts+++ b/packages/emails/src/send.ts@@ -26,14 +26,57 @@ export const delivery = {enabled: () => env.NODE_ENV === "production",};-export const sendEmail = async (email: Emails) => {+export interface SendOptions {+ /** Resend keeps keys for 24h; a replay with the same key is a no-op. */+ idempotencyKey?: string;+ /** ISO 8601. Resend schedules at most 30 days out. */+ scheduledAt?: string;+}++/** Returns the Resend email id, or undefined when nothing was sent. */+export const sendEmail = async (+ { reply_to, ...email }: Emails,+ opts: SendOptions = {},+) => {if (!delivery.enabled()) return;- await resend.emails.send(email);+ const { data, error } = await resend.emails.send(+ {+ ...email,+ ...(reply_to ? { replyTo: reply_to } : {}),+ ...(opts.scheduledAt ? { scheduledAt: opts.scheduledAt } : {}),+ },+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,+ );+ // Same key, different body: the first send already went out.+ if (error && error.name !== "invalid_idempotent_request") {+ console.error(`Error sending email "${email.subject}":`, error);+ }+ return data?.id;};-export const sendBatchEmailHtml = async (emails: EmailHtml[]) => {- if (!delivery.enabled()) return;- await resend.batch.send(emails);+/** True when the email is cancelled, so the caller may forget its id. */+export const cancelScheduledEmail = async (id: string) => {+ if (!delivery.enabled()) return false;+ const { error } = await resend.emails.cancel(id);+ if (error) console.error(`Error cancelling scheduled email ${id}:`, error);+ return !error;+};++export const sendBatchEmailHtml = async (+ emails: EmailHtml[],+ opts: Pick<SendOptions, "idempotencyKey"> = {},+) => {+ if (!delivery.enabled() || emails.length === 0) return;+ const { error } = await resend.batch.send(+ emails.map(({ reply_to, ...email }) => ({+ ...email,+ ...(reply_to ? { replyTo: reply_to } : {}),+ })),+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,+ );+ if (error && error.name !== "invalid_idempotent_request") {+ console.error(`Error sending batch of ${emails.length} emails:`, error);+ }};// TODO: delete in favor of sendBatchEmailHtmldiff --git a/packages/emails/src/templates.test.tsx b/packages/emails/src/templates.test.tsxindex 7610b6e94..5dfad5965 100644--- a/packages/emails/src/templates.test.tsx+++ b/packages/emails/src/templates.test.tsx@@ -26,7 +26,6 @@ import PageSubscriptionEmail from "../emails/page-subscription";import PrivateLocationAlertEmail, {privateLocationAlertSubject,} from "../emails/private-location-alert";-import SsoDisabledEmail from "../emails/sso-disabled";import StatusPageMagicLinkEmail from "../emails/status-page-magic-link";import StatusReportEmail, {type StatusReportProps,@@ -592,14 +591,6 @@ describe("inactivity pause", () => {});describe("account and status page mail", () => {- test("sso disabled never claims nobody lost access", async () => {- const html = await render(<SsoDisabledEmail />);- expect(html).toContain("ACCOUNT CHANGE");- expect(html).toContain("IdP configuration");- expect(html).not.toContain("Nobody lost access");- expect(html).not.toContain("Nobody has lost access");- });-test("team invitation", async () => {const html = await render(<TeamInvitationEmail@@ -684,7 +675,6 @@ describe("every transactional template", () => {<MonitorDeactivationEmail deactivateAt={new Date("2026-09-25")} />),paused: <MonitorPausedEmail />,- sso: <SsoDisabledEmail />,invitation: <TeamInvitationEmail token="t" invitedBy="[email protected]" />,subscription: <PageSubscriptionEmail page="Acme" link="https://a.dev" />,magicLink: <StatusPageMagicLinkEmail page="Acme" link="https://a.dev" />,diff --git a/packages/services/src/workspace/__tests__/downgrade.test.ts b/packages/services/src/workspace/__tests__/downgrade.test.tsindex 3dbe8b70b..9723db7f7 100644--- a/packages/services/src/workspace/__tests__/downgrade.test.ts+++ b/packages/services/src/workspace/__tests__/downgrade.test.ts@@ -21,7 +21,10 @@ import {} from "../../../test/helpers";import type { DrizzleTx, ServiceContext } from "../../context";import { ForbiddenError } from "../../errors";-import { downgradeWorkspaceToFree } from "../index.ts";+import {+ downgradeWorkspaceToFree,+ previewWorkspaceDowngrade,+} from "../index.ts";const OLDEST = new Date("2020-01-01T00:00:00Z");const NEWER = new Date("2021-01-01T00:00:00Z");@@ -54,7 +57,11 @@ async function seedTeamWorkspace(tx: DrizzleTx) {const memberBId = 900_003;await tx.insert(user).values([{ id: ownerUserId, tenantId: "svc-downgrade-owner" },- { id: memberAId, tenantId: "svc-downgrade-member-a" },+ {+ id: memberAId,+ tenantId: "svc-downgrade-member-a",+ email: "[email protected]",+ },{ id: memberBId, tenantId: "svc-downgrade-member-b" },]);await tx.insert(usersToWorkspaces).values([@@ -410,6 +417,88 @@ describe("downgradeWorkspaceToFree", () => {});});+ test("returns what the cascade actually trimmed", async () => {+ await withTestTransaction(async (tx) => {+ const s = await seedTeamWorkspace(tx);+ const ctx: ServiceContext = {+ workspace: s.ws,+ actor: { type: "system", job: "stripe-subscription-deleted" },+ db: tx,+ };++ const { trimmed } = await downgradeWorkspaceToFree({ ctx });++ expect(trimmed).toEqual({+ monitorsDeactivated: 1,+ pagesDeleted: ["Deleted Page"],+ keptPageTitle: "Kept Page",+ notificationsDeleted: 1,+ invitationsDeleted: 1,+ membersRemovedCount: 2,+ // member B has no email on file and cannot be notified+ membersRemoved: ["[email protected]"],+ });+ });+ });++ test("preview matches what the downgrade then trims, and changes nothing", async () => {+ await withTestTransaction(async (tx) => {+ const s = await seedTeamWorkspace(tx);+ const ctx: ServiceContext = {+ workspace: s.ws,+ actor: { type: "system", job: "stripe-subscription-updated" },+ db: tx,+ };++ const { customDomains, ssoEnabled, ...preview } =+ await previewWorkspaceDowngrade({ ctx });++ expect(customDomains).toEqual(["status.acme.test"]);+ expect(ssoEnabled).toBe(false);+ const pages = await tx+ .select()+ .from(page)+ .where(eq(page.workspaceId, s.ws.id))+ .all();+ expect(pages.length).toBe(2);++ const { trimmed } = await downgradeWorkspaceToFree({ ctx });+ expect(preview).toEqual(trimmed);+ });+ });++ test("returns an empty trim for a workspace with nothing to remove", async () => {+ await withTestTransaction(async (tx) => {+ const wsRow = await tx+ .insert(workspace)+ .values({+ slug: "svc-downgrade-empty",+ name: "Empty",+ plan: "team",+ limits: JSON.stringify(getLimits("team")),+ })+ .returning()+ .get();+ const ctx: ServiceContext = {+ workspace: selectWorkspaceSchema.parse(wsRow),+ actor: { type: "system", job: "stripe-subscription-deleted" },+ db: tx,+ };++ const { trimmed } = await downgradeWorkspaceToFree({ ctx });++ expect(trimmed).toEqual({+ monitorsDeactivated: 0,+ pagesDeleted: [],+ keptPageTitle: null,+ notificationsDeleted: 0,+ invitationsDeleted: 0,+ membersRemovedCount: 0,+ membersRemoved: [],+ });+ });+ });+test("rejects a read-only api key actor", async () => {await withTestTransaction(async (tx) => {const s = await seedTeamWorkspace(tx);diff --git a/packages/services/src/workspace/downgrade.ts b/packages/services/src/workspace/downgrade.tsindex 035b5fafc..7ffbcc09e 100644--- a/packages/services/src/workspace/downgrade.ts+++ b/packages/services/src/workspace/downgrade.ts@@ -1,9 +1,10 @@-import { and, asc, eq, isNull, ne } from "@openstatus/db";+import { and, asc, db as defaultDb, eq, isNull, ne } from "@openstatus/db";import {invitation,monitor,notification,page,+ user,usersToWorkspaces,} from "@openstatus/db/src/schema";import { getLimits } from "@openstatus/db/src/schema/plan/utils";@@ -41,14 +42,32 @@ import { updateWorkspacePlan } from "./update";** Returns the set of custom domains that were attached to any page, so the* caller can release them on Vercel *after* the transaction commits —- * that cleanup is best-effort and must not roll the downgrade back.+ * that cleanup is best-effort and must not roll the downgrade back. `trimmed`+ * is what the cascade actually removed, for the emails sent after commit.*/+export type DowngradeTrim = {+ monitorsDeactivated: number;+ /** Titles of hard-deleted pages — the one irreversible loss. */+ pagesDeleted: string[];+ keptPageTitle: string | null;+ notificationsDeleted: number;+ invitationsDeleted: number;+ /** Every removed non-owner member, with or without an email on file. */+ membersRemovedCount: number;+ /** Emails of the removed members that can be notified. */+ membersRemoved: string[];+};+// Every trim step routes through an audited entity verb, so the cascade is// fully attributable; the plan flip itself is audited by `updateWorkspacePlan`.// oxlint-disable-next-line openstatus/services-mutation-guardsexport async function downgradeWorkspaceToFree(args: {ctx: ServiceContext;-}): Promise<{ customDomains: string[]; ssoDisabled: boolean }> {+}): Promise<{+ customDomains: string[];+ ssoDisabled: boolean;+ trimmed: DowngradeTrim;+}> {const { ctx } = args;requireScope(ctx, "write");const workspaceId = ctx.workspace.id;@@ -99,7 +118,11 @@ export async function downgradeWorkspaceToFree(args: {}const statusPages = await tx- .select({ id: page.id, customDomain: page.customDomain })+ .select({+ id: page.id,+ title: page.title,+ customDomain: page.customDomain,+ }).from(page).where(eq(page.workspaceId, workspaceId)).orderBy(asc(page.createdAt));@@ -154,8 +177,9 @@ export async function downgradeWorkspaceToFree(args: {}const nonOwnerMembers = await tx- .select({ userId: usersToWorkspaces.userId })+ .select({ userId: usersToWorkspaces.userId, email: user.email }).from(usersToWorkspaces)+ .innerJoin(user, eq(user.id, usersToWorkspaces.userId)).where(and(eq(usersToWorkspaces.workspaceId, workspaceId),@@ -181,6 +205,89 @@ export async function downgradeWorkspaceToFree(args: {await deleteInvitation({ ctx: txCtx, input: { id: inv.id } });}- return { customDomains, ssoDisabled: ssoWasEnabled };+ return {+ customDomains,+ ssoDisabled: ssoWasEnabled,+ trimmed: {+ monitorsDeactivated: monitorIdsToDeactivate.length,+ pagesDeleted: statusPages.slice(1).map((p) => p.title),+ keptPageTitle: keptPage?.title ?? null,+ notificationsDeleted: notifications.filter(+ (n) => n.id !== keepNotification?.id,+ ).length,+ invitationsDeleted: pendingInvitations.length,+ membersRemovedCount: nonOwnerMembers.length,+ membersRemoved: nonOwnerMembers+ .map((m) => m.email)+ .filter((email): email is string => !!email && email.trim() !== ""),+ },+ };});}++export type DowngradePreview = DowngradeTrim & {+ customDomains: string[];+ ssoEnabled: boolean;+};++/** What `downgradeWorkspaceToFree` would trim right now. Read-only. */+export async function previewWorkspaceDowngrade(args: {+ ctx: ServiceContext;+}): Promise<DowngradePreview> {+ const { ctx } = args;+ requireScope(ctx, "read");+ const db = ctx.db ?? defaultDb;+ const workspaceId = ctx.workspace.id;++ const activeMonitors = await db.$count(+ monitor,+ and(+ eq(monitor.workspaceId, workspaceId),+ eq(monitor.active, true),+ isNull(monitor.deletedAt),+ ),+ );+ const pages = await db+ .select({ title: page.title, customDomain: page.customDomain })+ .from(page)+ .where(eq(page.workspaceId, workspaceId))+ .orderBy(asc(page.createdAt));+ const notifications = await db.$count(+ notification,+ eq(notification.workspaceId, workspaceId),+ );+ const invitations = await db.$count(+ invitation,+ and(eq(invitation.workspaceId, workspaceId), isNull(invitation.acceptedAt)),+ );+ const members = await db+ .select({ email: user.email })+ .from(usersToWorkspaces)+ .innerJoin(user, eq(user.id, usersToWorkspaces.userId))+ .where(+ and(+ eq(usersToWorkspaces.workspaceId, workspaceId),+ ne(usersToWorkspaces.role, "owner"),+ ),+ );++ return {+ monitorsDeactivated: Math.max(0, activeMonitors - 1),+ pagesDeleted: pages.slice(1).map((p) => p.title),+ keptPageTitle: pages[0]?.title ?? null,+ notificationsDeleted: Math.max(0, notifications - 1),+ invitationsDeleted: invitations,+ membersRemovedCount: members.length,+ membersRemoved: members+ .map((m) => m.email)+ .filter((email): email is string => !!email && email.trim() !== ""),+ customDomains: [+ ...new Set(+ pages+ .map((p) => p.customDomain)+ .filter((domain): domain is string => !!domain && domain !== ""),+ ),+ ],+ ssoEnabled: ctx.workspace.ssoEnabled,+ };+}diff --git a/packages/services/src/workspace/index.ts b/packages/services/src/workspace/index.tsindex 04d385a1a..52d005980 100644--- a/packages/services/src/workspace/index.ts+++ b/packages/services/src/workspace/index.ts@@ -5,7 +5,12 @@ export {listWorkspaces,type WorkspaceUsage,} from "./list";-export { downgradeWorkspaceToFree } from "./downgrade";+export {+ type DowngradePreview,+ type DowngradeTrim,+ downgradeWorkspaceToFree,+ previewWorkspaceDowngrade,+} from "./downgrade";export { updateWorkspaceName, updateWorkspacePlan } from "./update";export {GetWorkspaceByStripeIdInput,