Skip to content

Open-source status page, incident response and uptime monitoring

chore: improve trial ending email template (#2775)

Maximilian Kaskeadcf7dec7c20
diff --git a/packages/api/src/router/stripe/shared.ts b/packages/api/src/router/stripe/shared.ts
index 6c3a9d551..134ed0ca3 100644
--- a/packages/api/src/router/stripe/shared.ts
+++ b/packages/api/src/router/stripe/shared.ts
@@ -176,7 +176,7 @@ export async function hasPaymentMethod(subscription: Stripe.Subscription) {
const customer = await stripe.customers.retrieve(customerIdOf(subscription));
return (
!customer.deleted &&
- Boolean(customer.invoice_settings.default_payment_method)
+ Boolean(customer.invoice_settings?.default_payment_method)
);
}
diff --git a/packages/api/src/router/stripe/webhook.test.ts b/packages/api/src/router/stripe/webhook.test.ts
index 43ad0145f..212f5c058 100644
--- a/packages/api/src/router/stripe/webhook.test.ts
+++ b/packages/api/src/router/stripe/webhook.test.ts
@@ -488,11 +488,18 @@ describe("stripe webhook emails", () => {
});
describe("customer.subscription.trial_will_end", () => {
- test("sends trial-ending once per event with trial_end in the body", async () => {
+ const trialEnd = now() + 3 * DAY;
+
+ test("no card → lists what the free plan trims, once per event", async () => {
const s = await seed();
- const trialEnd = Math.floor(
- new Date("2026-09-25T00:00:00Z").getTime() / 1000,
- );
+ 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.trial_will_end",
subscription(s.stripeId, { status: "trialing", trial_end: trialEnd }),
@@ -502,13 +509,58 @@ describe("stripe webhook emails", () => {
assertSpyCalls(send, 1);
const [payload, options] = send.calls[0].args;
- expect(payload.subject).toBe("Your openstatus trial ends soon");
+ expect(payload.subject).toContain("add a payment method to keep");
expect(payload.to).toContain(s.ownerEmail);
+ expect(payload.react.props).toMatchObject({
+ workspaceSlug: s.workspace.slug,
+ plan: s.workspace.plan,
+ hasPaymentMethod: false,
+ loss: { pagesDeleted: ["Gone"], keptPageTitle: "Kept" },
+ });
expect(options).toEqual({
idempotencyKey: `stripe:${evt.event.id}:trial-ending`,
});
});
+ test("card on file → plan continues, no loss lines", async () => {
+ const s = await seed();
+ 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"),
+ });
+
+ await caller().customerSubscriptionTrialWillEnd(
+ event(
+ "customer.subscription.trial_will_end",
+ subscription(s.stripeId, {
+ status: "trialing",
+ trial_end: trialEnd,
+ default_payment_method: "pm_test_1",
+ }),
+ ),
+ );
+
+ assertSpyCalls(send, 1);
+ const [payload] = send.calls[0].args;
+ expect(payload.subject).toContain("plan continues");
+ expect(payload.react.props).toMatchObject({ hasPaymentMethod: true });
+ expect(payload.react.props.loss).toBeUndefined();
+ });
+
+ test("trial ended early (trial_end: now) → nothing sent", async () => {
+ const s = await seed();
+ const evt = event(
+ "customer.subscription.trial_will_end",
+ subscription(s.stripeId, { status: "active", trial_end: now() - 1 }),
+ );
+ await caller().customerSubscriptionTrialWillEnd(evt);
+ assertSpyCalls(send, 0);
+ });
+
test("no trial_end → nothing sent", async () => {
const s = await seed();
await caller().customerSubscriptionTrialWillEnd(
diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts
index c884894fe..693775fab 100644
--- a/packages/api/src/router/stripe/webhook.ts
+++ b/packages/api/src/router/stripe/webhook.ts
@@ -32,6 +32,7 @@ import {
customerIdOf,
getCurrentPeriodEnd,
getCurrentSubscription,
+ hasPaymentMethod,
isNewerSubscription,
listLiveSubscriptions,
stripe,
@@ -451,11 +452,16 @@ export const webhookRouter = createTRPCRouter({
}),
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 customerId = customerIdOf(subscription);
+ // Stripe also fires this when a trial is cut short with `trial_end: now`,
+ // which is how a mid-trial upgrade starts billing — no reminder then.
+ if (
+ !subscription.trial_end ||
+ subscription.status !== "trialing" ||
+ subscription.trial_end <= opts.input.event.created
+ ) {
+ return;
+ }
const ws = await getWorkspaceByStripeId({
input: { stripeId: customerId },
@@ -469,10 +475,26 @@ export const webhookRouter = createTRPCRouter({
}
try {
+ const withCard = await hasPaymentMethod(subscription);
+ const preview = withCard
+ ? undefined
+ : await previewWorkspaceDowngrade({
+ ctx: {
+ workspace: ws,
+ actor: { type: "system", job: "stripe-trial-will-end" },
+ db: opts.ctx.db,
+ },
+ });
await sendTrialEnding({
to: await getBillingRecipients(opts.ctx.db, ws.id, customerId),
eventId: opts.input.event.id,
+ workspaceSlug: ws.slug,
trialEnd: new Date(subscription.trial_end * 1000),
+ plan: ws.plan ?? "starter",
+ hasPaymentMethod: withCard,
+ loss: preview
+ ? toPlanLoss(preview, preview.customDomains, preview.ssoEnabled)
+ : undefined,
});
} catch (err) {
console.error("Failed to send trial ending email:", err);
diff --git a/packages/emails/emails/trial-ending.tsx b/packages/emails/emails/trial-ending.tsx
index 70f5e6b89..88f8590a5 100644
--- a/packages/emails/emails/trial-ending.tsx
+++ b/packages/emails/emails/trial-ending.tsx
@@ -1,53 +1,110 @@
/** @jsxRuntime automatic @jsxImportSource react */
-import { Body, Head, Html, Preview } from "react-email";
-
-import { formatDay } from "./_components/format";
-import { BILLING_URL } from "./plan-downgraded";
+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 TrialEndingProps {
+ workspaceSlug: string;
+ plan: string;
trialEnd: Date;
+ hasPaymentMethod: boolean;
+ /** What the free plan would trim; only rendered without a card on file. */
+ loss?: PlanLoss;
+}
+
+export function trialEndingSubject(props: TrialEndingProps): string {
+ const day = formatShortDay(props.trialEnd);
+ return props.hasPaymentMethod
+ ? `Your trial ends on ${day} — your ${props.plan} plan continues`
+ : `Your trial ends on ${day} — add a payment method to keep ${props.plan}`;
}
-export const TRIAL_ENDING_SUBJECT = "Your openstatus trial ends soon";
+const TrialEndingEmail = (props: TrialEndingProps) => {
+ const title = `Your trial ends on ${formatLongDay(props.trialEnd)}`;
+ const base = [
+ { label: "Workspace", value: props.workspaceSlug, mono: true },
+ { label: "Trial ends", value: formatDay(props.trialEnd), bold: true },
+ ];
+
+ if (props.hasPaymentMethod) {
+ return (
+ <Layout
+ preview={`Your ${props.plan} plan continues, nothing to do.`}
+ pill={{ tone: "neutral", label: "Trial" }}
+ footer={<Footer reason={BILLING_FOOTER_REASON} />}
+ >
+ <Heading title={title}>
+ You have a payment method on file, so the {props.plan} plan continues
+ without interruption. The first invoice is charged on that day.
+ </Heading>
+ <Callout tone="success" title="Nothing to do">
+ Monitors, status pages and members stay exactly as they are. If you
+ would rather not continue, cancel before the trial ends.
+ </Callout>
+ <KeyValue
+ rows={[...base, { label: "Plan", value: `${props.plan}, continues` }]}
+ />
+ <Actions
+ primary={{ label: "Manage subscription", href: BILLING_URL }}
+ />
+ <Signature />
+ </Layout>
+ );
+ }
-const TrialEndingEmail = ({ trialEnd }: TrialEndingProps) => {
+ const rows = props.loss ? planLossRows(props.loss, false) : [];
+ const consequence = `Without one, the workspace moves to the free plan on that day${
+ rows.length > 0 ? " and is trimmed to what it holds." : "."
+ }`;
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>
+ <Layout
+ preview={`Add a payment method to keep ${props.plan}.`}
+ pill={{ tone: "neutral", label: "Action needed" }}
+ footer={<Footer reason={BILLING_FOOTER_REASON} />}
+ >
+ <Heading title={title}>
+ There is no payment method on file. {consequence}
+ </Heading>
+ <Callout title="Adding a card keeps everything">
+ Nothing changes until the trial ends. Add a payment method before then
+ and the {props.plan} plan simply continues.
+ </Callout>
+ <KeyValue
+ rows={[
+ ...base,
+ { label: "Plan", value: `${props.plan} → free` },
+ ...rows,
+ ]}
+ />
+ <Actions primary={{ label: "Add payment method", href: BILLING_URL }} />
+ <Signature />
+ </Layout>
);
};
TrialEndingEmail.PreviewProps = {
+ workspaceSlug: "acme-dev",
+ plan: "starter",
trialEnd: new Date("2026-09-25T00:00:00Z"),
+ hasPaymentMethod: false,
+ loss: {
+ monitorsDeactivated: 4,
+ pagesDeleted: ["Acme API"],
+ keptPageTitle: "Acme",
+ notificationsDeleted: 0,
+ invitationsDeleted: 0,
+ membersRemoved: 2,
+ customDomains: [],
+ sso: false,
+ },
} satisfies TrialEndingProps;
export default TrialEndingEmail;
diff --git a/packages/emails/src/billing.test.tsx b/packages/emails/src/billing.test.tsx
index a00340bf6..3601fae5b 100644
--- a/packages/emails/src/billing.test.tsx
+++ b/packages/emails/src/billing.test.tsx
@@ -15,7 +15,7 @@ import PlanDowngradedEmail, {
import PlanEndingSoonEmail, {
planEndingSoonSubject,
} from "../emails/plan-ending-soon";
-import TrialEndingEmail from "../emails/trial-ending";
+import TrialEndingEmail, { trialEndingSubject } from "../emails/trial-ending";
import {
billingRecipients,
planLossLines,
@@ -147,11 +147,58 @@ describe("billing templates", () => {
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("trial-ending without a card lists what gets removed", async () => {
+ const props = {
+ workspaceSlug: "acme-dev",
+ plan: "starter",
+ trialEnd: endsAt,
+ hasPaymentMethod: false,
+ loss,
+ };
+ const html = await render(<TrialEndingEmail {...props} />);
+ expect(trialEndingSubject(props)).toBe(
+ "Your trial ends on 25 Sep — add a payment method to keep starter",
+ );
+ expect(html).toContain("ACTION NEEDED");
+ expect(html).toContain("Your trial ends on Friday 25 September");
+ expect(html).toContain("acme-dev");
+ expect(html).toContain("starter → free");
+ expect(html).toContain("Acme API, Acme EU");
+ expect(html).toContain("Add payment method");
+ expect(html).not.toContain("on file, so");
+ });
+
+ test("trial-ending with a card says the plan continues", async () => {
+ const props = {
+ workspaceSlug: "acme-dev",
+ plan: "starter",
+ trialEnd: endsAt,
+ hasPaymentMethod: true,
+ loss,
+ };
+ const html = await render(<TrialEndingEmail {...props} />);
+ expect(trialEndingSubject(props)).toBe(
+ "Your trial ends on 25 Sep — your starter plan continues",
+ );
+ expect(html).toContain("Nothing to do");
+ expect(html).toContain("starter, continues");
+ expect(html).toContain("Manage subscription");
+ expect(html).not.toContain("Acme API, Acme EU");
+ expect(html).not.toContain("Add payment method");
+ });
+
+ test("trial-ending without a card and nothing to trim", async () => {
+ const html = await render(
+ <TrialEndingEmail
+ workspaceSlug="acme-dev"
+ plan="starter"
+ trialEnd={endsAt}
+ hasPaymentMethod={false}
+ loss={nothing}
+ />,
+ );
+ expect(html).toContain("free plan on that day.");
+ expect(html).not.toContain("trimmed");
});
test("loss lines use singular forms", () => {
@@ -261,7 +308,14 @@ describe("send plumbing", () => {
from: "a <[email protected]>",
subject: "s",
- react: <TrialEndingEmail trialEnd={endsAt} />,
+ react: (
+ <TrialEndingEmail
+ workspaceSlug="acme-dev"
+ plan="starter"
+ trialEnd={endsAt}
+ hasPaymentMethod={false}
+ />
+ ),
};
test("sendEmail forwards idempotencyKey and scheduledAt, returns the id", async () => {
@@ -441,10 +495,20 @@ describe("send plumbing", () => {
await sendTrialEnding({
eventId: "evt_3",
+ workspaceSlug: "acme-dev",
trialEnd: endsAt,
+ plan: "starter",
+ hasPaymentMethod: false,
+ loss,
});
const [payload, options] = send.calls[0].args;
- expect(payload.subject).toBe("Your openstatus trial ends soon");
+ expect(payload.from).toBe(
+ "Thibault from openstatus <[email protected]>",
+ );
+ expect(payload.replyTo).toBe("[email protected]");
+ expect(payload.subject).toBe(
+ "Your trial ends on 25 Sep — add a payment method to keep starter",
+ );
expect(options).toEqual({ idempotencyKey: "stripe:evt_3:trial-ending" });
});
@@ -462,7 +526,14 @@ describe("send plumbing", () => {
reason: "downgrade",
owners: [],
});
- await sendTrialEnding({ to: [], eventId: "e", trialEnd: endsAt });
+ await sendTrialEnding({
+ to: [],
+ eventId: "e",
+ workspaceSlug: "a",
+ trialEnd: endsAt,
+ plan: "starter",
+ hasPaymentMethod: false,
+ });
assertSpyCalls(send, 0);
assertSpyCalls(batch, 0);
});
diff --git a/packages/emails/src/billing.tsx b/packages/emails/src/billing.tsx
index f44dd5529..037818070 100644
--- a/packages/emails/src/billing.tsx
+++ b/packages/emails/src/billing.tsx
@@ -19,8 +19,10 @@ 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 TrialEndingEmail, {
+ type TrialEndingProps,
+ trialEndingSubject,
+} from "../emails/trial-ending";
import { sendBatchEmailHtml, sendEmail } from "./send";
const RAW_FROM = "Thibault from openstatus <[email protected]>";
@@ -208,19 +210,19 @@ export async function schedulePlanEndingSoon(
);
}
-export async function sendTrialEnding(req: {
- to: string[];
- eventId: string;
- trialEnd: Date;
-}) {
+export async function sendTrialEnding(
+ req: TrialEndingProps & { to: string[]; eventId: string },
+) {
if (req.to.length === 0) return;
+ const { to, eventId, ...props } = req;
return sendEmail(
{
- from: RAW_FROM,
- to: req.to,
- subject: TRIAL_ENDING_SUBJECT,
- react: <TrialEndingEmail trialEnd={req.trialEnd} />,
+ from: SIGNED_FROM,
+ reply_to: SIGNED_REPLY_TO,
+ to,
+ subject: trialEndingSubject(props),
+ react: <TrialEndingEmail {...props} />,
},
- { idempotencyKey: stripeIdempotencyKey(req.eventId, "trial-ending") },
+ { idempotencyKey: stripeIdempotencyKey(eventId, "trial-ending") },
);
}