Skip to content

Open source alternative to Semrush and Ahrefs

Send billing lifecycle emails through Loops on Autumn webhooks (#672)

Ben Senescucb2e84b41017
diff --git a/specs/0015-billing-lifecycle-emails.md b/specs/0015-billing-lifecycle-emails.md
new file mode 100644
index 00000000..63aa769b
--- /dev/null
+++ b/specs/0015-billing-lifecycle-emails.md
@@ -0,0 +1,52 @@
+# Billing lifecycle emails
+
+## Status
+
+Accepted. Builds on the Autumn billing webhook from `specs/0002-hosted-dataforseo-metering-with-autumn.md` and the owner-only billing role from `specs/0011-multi-user-organizations.md`.
+
+## What it does
+
+Three moments in a paid subscription get a personal email from the founder, sent through Loops and addressed to the organization owner only:
+
+- **Subscribed.** A thank-you right after the first paid plan activates, and a one-week check-in that only goes out if the subscription is still in good standing.
+- **Payment failed.** When a renewal charge fails and the subscription goes past due, an email explaining what happened and linking to a page in the app that offers one fix: update the card in the billing portal, where the invoice can also be paid.
+- **Cancelled.** When the owner cancels, an email asking why and offering a call.
+
+Owners are the only recipients because only they can act on billing, and a founder note to three teammates reads as spam. Upgrades between paid plans send nothing. Involuntary churn, where a past-due subscription finally expires, sends nothing either: that person already received the payment email and did not choose to leave.
+
+## How it works
+
+**Signal.** Autumn already posts `billing.updated` to the app on every plan change, and the handler already re-reads the whole customer and stores it. Lifecycle events are derived by comparing the customer as it was at the last webhook with the customer as it is now. Autumn's webhook payload does describe the change, but the stored snapshot is what the app already trusts, it survives out-of-order delivery, and a retried webhook finds no difference and sends nothing. Nothing new is persisted: the two fields the comparison needs, past-due and cancelled-at, come out of the stored customer document.
+
+| Before | After | Event |
+| --------------------- | -------------------------------- | ----------------------- |
+| Not on a priced plan | Active on a priced plan | `subscription_started` |
+| Not past due | Past due | `payment_failed` |
+| Active, not cancelled | Cancelled at period end, or gone | `subscription_canceled` |
+
+"Priced" means the base plan or the YC plan. A plan can grant the paid entitlement without charging, and those customers are not thanked for subscribing.
+
+A customer with no stored snapshot produces no events. Every new organization gets a snapshot on its first webhook, because the free plan auto-enables at signup before anyone can pay, so a missing snapshot means a customer from before the table existed, whose next renewal or top-up must not read as a new subscription.
+
+**Delivery.** Each event is one Loops event, sent to every member whose role can manage billing, carrying the plan id. The same sync refreshes every member's billing properties, including a new `billingState` property with values `none`, `active`, `past_due`, `canceling`, `scheduled` or `expired`, so Loops audience filters can ask whether someone is still in good standing. Loops accepts an idempotency key per event send; the key is built from the event name, the organization, the recipient and the timestamp of the previous snapshot, so a retried webhook cannot send twice even if the snapshot write failed after the send succeeded. A conflict on that key is treated as success.
+
+Event sends happen before the snapshot is written. If Loops is unreachable the webhook fails, Autumn retries, and the comparison produces the same events with the same keys.
+
+**Workflows.** Loops owns timing and copy. Each event triggers one workflow. The subscribed workflow sends the thank-you, waits seven days, then passes the contact through an audience filter requiring `billingState` to be `active` before the check-in. The filter applies to all following nodes, so a cancellation or failed payment during the week removes the contact before the second email. The other two workflows are a trigger and one email. Workflows are created as drafts through the Loops API and only start when a maintainer presses Start in the dashboard.
+
+**Fix-payment page** at `/billing/fix-payment`. Shows whether the subscription is past due and offers one action: open the Stripe billing portal. The portal is the only action because it does two things the hosted invoice page cannot do together: a card added there becomes the default for future renewals, and the open invoice can be paid on the same screen. Paying the hosted invoice with a new card would not save that card when a default already exists, so the next renewal would fail again. The portal returns to the same page with a flag, and the page polls the customer for half a minute and shows a success screen once the subscription is no longer past due, or explains that Stripe's retry can take a few minutes and offers the portal again. Members who cannot manage billing are told to ask the owner. A visitor with nothing outstanding sees that their billing is up to date. The card decline reason is not shown because Autumn does not expose it.
+
+## Alternatives considered
+
+- **Triggering Loops workflows on contact property changes** instead of events. Fires once per member, cannot express "payment failed" without inventing a property for it, and cannot carry the plan or reason into the email.
+- **Deriving events from the webhook payload's `plan_changes`** rather than from the stored snapshot. Needs a dedup store to survive retries, and an upgrade arrives as an activation and an expiry that must be paired by hand. The snapshot diff gets both for free.
+- **Listening to Stripe webhooks directly** for `invoice.payment_failed` and `customer.subscription.deleted`. A second webhook route, a second signature scheme, and a second customer id mapping, for information Autumn already forwards.
+- **Delaying the check-in with a Cloudflare Workflow or cron** instead of a Loops timer. The app would then own send timing for a marketing email and have to re-check billing state itself before sending. Loops already does both.
+- **Embedding a billing portal link in the payment email.** Portal sessions expire in minutes. The app page mints one on click.
+- **A "Pay invoice" button that opens Stripe's hosted invoice page.** Immediate, but a new card entered there is not saved as the default when one already exists, so an expired card fails again next month. The portal fixes both.
+- **Different copy for the YC plan.** Same emails; a Slack alert on YC activations covers the warmer outreach.
+- **Emailing every member.** Only the owner can fix billing or cancel.
+
+## Not in scope
+
+Backfilling current subscribers with the thank-you, a Slack alert on plan activations, showing the card decline reason, a past-due banner inside the app, trial emails, renewal receipts.
diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts
index 7e99f18e..6f94645c 100644
--- a/src/routeTree.gen.ts
+++ b/src/routeTree.gen.ts
@@ -42,6 +42,7 @@ import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
import { Route as AppSettingsOrganizationRouteImport } from './routes/_app/settings/organization'
import { Route as AppHelpOpenrouterApiKeyRouteImport } from './routes/_app/help/openrouter-api-key'
import { Route as AppHelpDataforseoApiKeyRouteImport } from './routes/_app/help/dataforseo-api-key'
+import { Route as AppBillingFixPaymentRouteImport } from './routes/_app/billing_.fix-payment'
import { Route as ProjectPProjectIdRouteRouteImport } from './routes/_project/p/$projectId/route'
import { Route as ProjectPProjectIdIndexRouteImport } from './routes/_project/p/$projectId/index'
import { Route as ApiGscOauthCallbackRouteImport } from './routes/api/gsc/oauth/callback'
@@ -232,6 +233,11 @@ const AppHelpDataforseoApiKeyRoute = AppHelpDataforseoApiKeyRouteImport.update({
path: '/help/dataforseo-api-key',
getParentRoute: () => AppRouteRoute,
} as any)
+const AppBillingFixPaymentRoute = AppBillingFixPaymentRouteImport.update({
+ id: '/billing_/fix-payment',
+ path: '/billing/fix-payment',
+ getParentRoute: () => AppRouteRoute,
+} as any)
const ProjectPProjectIdRouteRoute = ProjectPProjectIdRouteRouteImport.update({
id: '/p/$projectId',
path: '/p/$projectId',
@@ -397,6 +403,7 @@ export interface FileRoutesByFullPath {
'/api/health': typeof ApiHealthRoute
'/r/$reportId': typeof RReportIdRoute
'/p/$projectId': typeof ProjectPProjectIdRouteRouteWithChildren
+ '/billing/fix-payment': typeof AppBillingFixPaymentRoute
'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute
'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute
'/settings/organization': typeof AppSettingsOrganizationRoute
@@ -451,6 +458,7 @@ export interface FileRoutesByTo {
'/accept-invitation/$id': typeof AcceptInvitationIdRoute
'/api/health': typeof ApiHealthRoute
'/r/$reportId': typeof RReportIdRoute
+ '/billing/fix-payment': typeof AppBillingFixPaymentRoute
'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute
'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute
'/settings/organization': typeof AppSettingsOrganizationRoute
@@ -510,6 +518,7 @@ export interface FileRoutesById {
'/r/$reportId': typeof RReportIdRoute
'/_app/': typeof AppIndexRoute
'/_project/p/$projectId': typeof ProjectPProjectIdRouteRouteWithChildren
+ '/_app/billing_/fix-payment': typeof AppBillingFixPaymentRoute
'/_app/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute
'/_app/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute
'/_app/settings/organization': typeof AppSettingsOrganizationRoute
@@ -568,6 +577,7 @@ export interface FileRouteTypes {
| '/api/health'
| '/r/$reportId'
| '/p/$projectId'
+ | '/billing/fix-payment'
| '/help/dataforseo-api-key'
| '/help/openrouter-api-key'
| '/settings/organization'
@@ -622,6 +632,7 @@ export interface FileRouteTypes {
| '/accept-invitation/$id'
| '/api/health'
| '/r/$reportId'
+ | '/billing/fix-payment'
| '/help/dataforseo-api-key'
| '/help/openrouter-api-key'
| '/settings/organization'
@@ -680,6 +691,7 @@ export interface FileRouteTypes {
| '/r/$reportId'
| '/_app/'
| '/_project/p/$projectId'
+ | '/_app/billing_/fix-payment'
| '/_app/help/dataforseo-api-key'
| '/_app/help/openrouter-api-key'
| '/_app/settings/organization'
@@ -971,6 +983,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppHelpDataforseoApiKeyRouteImport
parentRoute: typeof AppRouteRoute
}
+ '/_app/billing_/fix-payment': {
+ id: '/_app/billing_/fix-payment'
+ path: '/billing/fix-payment'
+ fullPath: '/billing/fix-payment'
+ preLoaderRoute: typeof AppBillingFixPaymentRouteImport
+ parentRoute: typeof AppRouteRoute
+ }
'/_project/p/$projectId': {
id: '/_project/p/$projectId'
path: '/p/$projectId'
@@ -1170,6 +1189,7 @@ interface AppRouteRouteChildren {
AppSettingsRoute: typeof AppSettingsRouteWithChildren
AppSupportRoute: typeof AppSupportRoute
AppIndexRoute: typeof AppIndexRoute
+ AppBillingFixPaymentRoute: typeof AppBillingFixPaymentRoute
AppHelpDataforseoApiKeyRoute: typeof AppHelpDataforseoApiKeyRoute
AppHelpOpenrouterApiKeyRoute: typeof AppHelpOpenrouterApiKeyRoute
}
@@ -1181,6 +1201,7 @@ const AppRouteRouteChildren: AppRouteRouteChildren = {
AppSettingsRoute: AppSettingsRouteWithChildren,
AppSupportRoute: AppSupportRoute,
AppIndexRoute: AppIndexRoute,
+ AppBillingFixPaymentRoute: AppBillingFixPaymentRoute,
AppHelpDataforseoApiKeyRoute: AppHelpDataforseoApiKeyRoute,
AppHelpOpenrouterApiKeyRoute: AppHelpOpenrouterApiKeyRoute,
}
diff --git a/src/routes/_app/billing_.fix-payment.tsx b/src/routes/_app/billing_.fix-payment.tsx
new file mode 100644
index 00000000..10818f46
--- /dev/null
+++ b/src/routes/_app/billing_.fix-payment.tsx
@@ -0,0 +1,211 @@
+import { createFileRoute, Link, notFound } from "@tanstack/react-router";
+import { useCustomer } from "autumn-js/react";
+import { useEffect, useState, type ReactNode } from "react";
+import { useSession } from "@/lib/auth-client";
+import { isHostedClientAuthMode } from "@/lib/auth-mode";
+import { useCanManageBilling } from "@/client/features/team/organizationQueries";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import { captureClientError, captureClientEvent } from "@/client/lib/posthog";
+import { getBillingRouteState } from "@/client/features/billing/route-state";
+import { BILLING_ROUTE } from "@/shared/billing";
+
+const SUPPORT_EMAIL = "[email protected]";
+
+// How long the post-portal "checking" screen polls Autumn before telling the
+// user the retry is still pending.
+const CHECKING_TIMEOUT_MS = 30_000;
+
+// Linked from the payment-failed email. Deliberately narrower than /billing:
+// one problem, one fix. The Stripe portal both saves the new card as the
+// default and lets the customer pay the open invoice, so it is the only action.
+export const Route = createFileRoute("/_app/billing_/fix-payment")({
+ validateSearch: (search: Record<string, unknown>): { returned?: true } => ({
+ returned:
+ search.returned === true || search.returned === "true" ? true : undefined,
+ }),
+ beforeLoad: () => {
+ if (!isHostedClientAuthMode()) {
+ throw notFound();
+ }
+ },
+ component: FixPaymentPage,
+});
+
+function FixPaymentPage() {
+ const { returned } = Route.useSearch();
+ const { data: session, isPending: isSessionPending } = useSession();
+ const [isOpeningPortal, setIsOpeningPortal] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [checkingTimedOut, setCheckingTimedOut] = useState(false);
+
+ const customerQuery = useCustomer({
+ queryOptions: { enabled: Boolean(session?.user?.id) },
+ });
+ const canManageBilling = useCanManageBilling();
+
+ const routeState = getBillingRouteState({
+ hasSession: Boolean(session?.user?.id),
+ isSessionPending,
+ isCustomerLoading: customerQuery.isLoading,
+ isCustomerError: customerQuery.isError,
+ });
+ const isPastDue =
+ customerQuery.data?.subscriptions?.some((s) => s.pastDue) ?? false;
+ const isChecking =
+ Boolean(returned) &&
+ routeState === "ready" &&
+ isPastDue &&
+ !checkingTimedOut;
+
+ // Stripe retries the invoice with the new card and Autumn relays the result
+ // a few seconds later; poll until the subscription is no longer past due.
+ const { refetch: refetchCustomer } = customerQuery;
+ useEffect(() => {
+ if (!isChecking) return;
+ const interval = setInterval(() => void refetchCustomer(), 2000);
+ const timeout = setTimeout(() => {
+ setCheckingTimedOut(true);
+ // The user did the right thing and we could not confirm it worked.
+ // Rare enough that every occurrence is worth a look.
+ captureClientError(
+ new Error("Subscription still past due after billing portal return"),
+ { context: "fix_payment_check_timeout" },
+ );
+ }, CHECKING_TIMEOUT_MS);
+ return () => {
+ clearInterval(interval);
+ clearTimeout(timeout);
+ };
+ }, [isChecking, refetchCustomer]);
+
+ useEffect(() => {
+ if (returned && routeState === "ready" && !isPastDue) {
+ captureClientEvent("billing:payment_fixed");
+ }
+ }, [returned, routeState, isPastDue]);
+
+ async function openPortal() {
+ setError(null);
+ setIsOpeningPortal(true);
+ try {
+ const returnUrl = new URL(window.location.href);
+ returnUrl.searchParams.set("returned", "true");
+ await customerQuery.openCustomerPortal({ returnUrl: returnUrl.href });
+ } catch (err) {
+ captureClientError(err, { context: "fix_payment_open_portal" });
+ setError(
+ getStandardErrorMessage(
+ err,
+ "We couldn't open the billing portal. Please try again.",
+ ),
+ );
+ setIsOpeningPortal(false);
+ }
+ }
+
+ if (routeState === "loading") {
+ return null;
+ }
+
+ if (routeState === "error") {
+ return (
+ <Page title="Billing unavailable">
+ <p className="text-sm text-base-content/70">
+ {getStandardErrorMessage(
+ customerQuery.error,
+ "We couldn't load your billing details right now. Please try again.",
+ )}
+ </p>
+ <button
+ type="button"
+ className="btn btn-soft btn-sm"
+ onClick={() => void customerQuery.refetch()}
+ >
+ Try again
+ </button>
+ </Page>
+ );
+ }
+
+ if (isChecking) {
+ return (
+ <Page title="Checking your payment…">
+ <span className="loading loading-spinner loading-md" />
+ <p className="text-sm text-base-content/70">
+ Stripe is retrying the charge with your updated card. This usually
+ takes a few seconds.
+ </p>
+ </Page>
+ );
+ }
+
+ if (!isPastDue) {
+ return (
+ <Page title={returned ? "You're all set" : "Your billing is up to date"}>
+ <p className="text-sm text-base-content/70">
+ {returned
+ ? "The payment went through and your subscription is active again."
+ : "There's nothing outstanding on your account."}{" "}
+ <Link to={BILLING_ROUTE} className="link link-primary font-medium">
+ Back to billing
+ </Link>
+ </p>
+ </Page>
+ );
+ }
+
+ if (!canManageBilling) {
+ return (
+ <Page title="Fix your payment">
+ <p className="text-sm text-base-content/70">
+ A payment for this organization didn&rsquo;t go through. Only the
+ organization owner can update the card, so please ask them to visit
+ this page.
+ </p>
+ </Page>
+ );
+ }
+
+ return (
+ <Page title={returned ? "Still showing as unpaid" : "Fix your payment"}>
+ <p className="text-sm text-base-content/70">
+ {returned
+ ? "Your subscription is still marked past due. Stripe can take a few minutes to retry the charge. If you added a new card but the invoice is still listed as open in the portal, you can pay it there directly."
+ : "Your last payment didn't go through. This usually means the card expired or the bank declined the charge. Nothing has been turned off yet."}
+ </p>
+
+ <div className="rounded-lg border border-base-300 bg-base-100 p-4">
+ <p className="text-sm font-semibold">Update your payment method</p>
+ <p className="mt-1 text-sm text-base-content/60">
+ Add a working card in the billing portal. It becomes your default for
+ future renewals, and the open invoice can be paid on the same screen.
+ </p>
+ <button
+ type="button"
+ className="btn btn-primary btn-sm mt-3"
+ disabled={isOpeningPortal}
+ onClick={() => void openPortal()}
+ >
+ {isOpeningPortal ? "Opening Stripe..." : "Open billing portal"}
+ </button>
+ </div>
+
+ {error ? <p className="text-sm text-error">{error}</p> : null}
+ </Page>
+ );
+}
+
+function Page({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <div className="mx-auto w-full max-w-xl space-y-5 p-4 py-10 md:p-6 md:py-12">
+ <div>
+ <p className="text-sm font-medium text-base-content/40">Billing</p>
+ <h1 className="mt-1 text-2xl font-bold tracking-tight">{title}</h1>
+ </div>
+ {children}
+ <p className="text-xs text-base-content/40">
+ Something look wrong? Email {SUPPORT_EMAIL}.
+ </p>
+ </div>
+ );
+}
diff --git a/src/server/billing/customer-status-model.test.ts b/src/server/billing/customer-status-model.test.ts
index 0c92bde1..121301ab 100644
--- a/src/server/billing/customer-status-model.test.ts
+++ b/src/server/billing/customer-status-model.test.ts
@@ -16,8 +16,23 @@ describe("deriveBillingCustomerStatusSnapshot", () => {
isPaying: true,
paidPlanId: "yc-plan",
paidPlanStatus: "active",
+ pastDue: false,
+ canceledAt: null,
},
},
+ {
+ name: "lifecycle fields come off the paid subscription",
+ flags: paidFlags("base-plan"),
+ subscriptions: [
+ {
+ planId: "base-plan",
+ status: "active",
+ pastDue: true,
+ canceledAt: 1_790_000_000_000,
+ },
+ ],
+ expected: { pastDue: true, canceledAt: 1_790_000_000_000 },
+ },
{
name: "no paid entitlement stays queryable but not paying",
flags: {},
diff --git a/src/server/billing/customer-status-model.ts b/src/server/billing/customer-status-model.ts
index d4e7748b..8636e6af 100644
--- a/src/server/billing/customer-status-model.ts
+++ b/src/server/billing/customer-status-model.ts
@@ -1,32 +1,49 @@
+import { z } from "zod";
import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";
-// The subset of the Autumn SDK's `Customer` we read. The SDK already validates
-// and returns camelCase, so we type against it structurally instead of
-// re-parsing; everything else is preserved verbatim in `customerJson`.
-type AutumnSubscriptionInput = {
- planId?: string | null;
- status?: string | null;
-};
+// The subset of the Autumn SDK's `Customer` we read, in the SDK's camelCase.
+// The same schema parses a fresh SDK object and a `customerJson` row written
+// by an earlier sync; everything else passes through into `customerJson`.
+const autumnSubscriptionSchema = z
+ .object({
+ planId: z.string().nullish(),
+ status: z.string().nullish(),
+ pastDue: z.boolean().nullish(),
+ canceledAt: z.number().nullish(),
+ })
+ .passthrough();
-type AutumnCustomerInput = {
- id?: string | null;
- subscriptions?: AutumnSubscriptionInput[];
- flags?: Record<string, { planId?: string | null } | undefined>;
- [key: string]: unknown;
-};
+const autumnCustomerSchema = z
+ .object({
+ id: z.string().nullish(),
+ subscriptions: z.array(autumnSubscriptionSchema).optional(),
+ flags: z
+ .record(
+ z.string(),
+ z.object({ planId: z.string().nullish() }).passthrough().optional(),
+ )
+ .optional(),
+ })
+ .passthrough();
export type BillingCustomerStatusSnapshot = {
organizationId: string;
isPaying: boolean;
paidPlanId: string | null;
paidPlanStatus: string | null;
+ // Lifecycle detail read from the paid subscription. Not stored as columns:
+ // the previous snapshot is rebuilt from `customerJson`, so these stay
+ // derivable without widening the table.
+ pastDue: boolean;
+ canceledAt: number | null;
customerJson: string;
syncedAt: string;
};
export function deriveBillingCustomerStatusSnapshot(
- customer: AutumnCustomerInput,
+ input: unknown,
): BillingCustomerStatusSnapshot {
+ const customer = autumnCustomerSchema.parse(input);
const organizationId = customer.id;
if (!organizationId) {
throw new Error("Autumn customer is missing an id");
@@ -46,6 +63,8 @@ export function deriveBillingCustomerStatusSnapshot(
isPaying: subscription?.status === "active",
paidPlanId,
paidPlanStatus: subscription?.status ?? null,
+ pastDue: subscription?.pastDue === true,
+ canceledAt: subscription?.canceledAt ?? null,
// Full payload kept verbatim — query rarely-used fields via json_extract.
customerJson: JSON.stringify(customer),
syncedAt: new Date().toISOString(),
@@ -55,7 +74,7 @@ export function deriveBillingCustomerStatusSnapshot(
// Prefer the active row; fall back to any row for the plan so a past-due or
// scheduled state is still recorded.
function selectSubscription(
- subscriptions: AutumnSubscriptionInput[],
+ subscriptions: z.infer<typeof autumnSubscriptionSchema>[],
planId: string,
) {
const rows = subscriptions.filter((s) => s.planId === planId);
diff --git a/src/server/billing/customer-status-sync.ts b/src/server/billing/customer-status-sync.ts
index e61a1c25..f3564a7c 100644
--- a/src/server/billing/customer-status-sync.ts
+++ b/src/server/billing/customer-status-sync.ts
@@ -1,4 +1,4 @@
-import { sql } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { db } from "@/db";
import { billingCustomerStatus } from "@/db/schema";
import { autumn } from "@/server/billing/autumn";
@@ -6,6 +6,7 @@ import {
deriveBillingCustomerStatusSnapshot,
type BillingCustomerStatusSnapshot,
} from "./customer-status-model";
+import { deriveBillingLifecycleEvents } from "./lifecycle-events";
import { syncBillingStatusToLoops } from "./loops-sync";
export async function syncAutumnCustomerStatus(customerId: string) {
@@ -13,11 +14,43 @@ export async function syncAutumnCustomerStatus(customerId: string) {
// references an existing Autumn customer. The SDK returns the camelCase shape.
const customer = await autumn.customers.getOrCreate({ customerId });
const snapshot = deriveBillingCustomerStatusSnapshot(customer);
+
+ // Lifecycle emails are the diff between the last stored customer and this
+ // one. Loops is called before the row is written: an outage fails the
+ // webhook, Autumn retries, and the same diff produces the same idempotency
+ // keys.
+ //
+ // No stored row means no emails. Every new organization gets a row on its
+ // first webhook (the free plan auto-enables at signup, before anyone can
+ // pay), so a missing row is a customer from before the table existed, whose
+ // next renewal or top-up must not read as a new subscription.
+ const previous = await getPreviousSnapshot(customerId);
+ await syncBillingStatusToLoops({
+ snapshot,
+ events: previous ? deriveBillingLifecycleEvents(previous, snapshot) : [],
+ previousSyncedAt: previous?.syncedAt ?? null,
+ });
+
await upsertBillingCustomerStatus(snapshot);
- await syncBillingStatusToLoops(snapshot);
return snapshot;
}
+async function getPreviousSnapshot(organizationId: string) {
+ const [row] = await db
+ .select({
+ customerJson: billingCustomerStatus.customerJson,
+ syncedAt: billingCustomerStatus.syncedAt,
+ })
+ .from(billingCustomerStatus)
+ .where(eq(billingCustomerStatus.organizationId, organizationId))
+ .limit(1);
+ if (!row) return null;
+ return {
+ ...deriveBillingCustomerStatusSnapshot(JSON.parse(row.customerJson)),
+ syncedAt: row.syncedAt,
+ };
+}
+
async function upsertBillingCustomerStatus(
snapshot: BillingCustomerStatusSnapshot,
) {
diff --git a/src/server/billing/lifecycle-events.test.ts b/src/server/billing/lifecycle-events.test.ts
new file mode 100644
index 00000000..c5150cd0
--- /dev/null
+++ b/src/server/billing/lifecycle-events.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "vitest";
+import {
+ deriveBillingLifecycleEvents,
+ getBillingState,
+} from "./lifecycle-events";
+
+const snapshot = (
+ overrides: Partial<Parameters<typeof deriveBillingLifecycleEvents>[1]> = {},
+) => ({
+ paidPlanId: "base-plan",
+ paidPlanStatus: "active",
+ isPaying: true,
+ pastDue: false,
+ canceledAt: null,
+ ...overrides,
+});
+
+const free = snapshot({
+ paidPlanId: null,
+ paidPlanStatus: null,
+ isPaying: false,
+});
+
+describe("deriveBillingLifecycleEvents", () => {
+ it("starts a subscription when a priced plan first activates", () => {
+ expect(deriveBillingLifecycleEvents(free, snapshot())).toEqual([
+ { name: "subscription_started", planId: "base-plan" },
+ ]);
+ });
+
+ it("ignores unpriced paid plans and upgrades between priced plans", () => {
+ expect(
+ deriveBillingLifecycleEvents(
+ free,
+ snapshot({ paidPlanId: "friends_and_family_2" }),
+ ),
+ ).toEqual([]);
+ expect(
+ deriveBillingLifecycleEvents(
+ snapshot(),
+ snapshot({ paidPlanId: "yc-plan" }),
+ ),
+ ).toEqual([]);
+ });
+
+ it("reports a payment failure once when the subscription goes past due", () => {
+ const pastDue = snapshot({ pastDue: true });
+ expect(deriveBillingLifecycleEvents(snapshot(), pastDue)).toEqual([
+ { name: "payment_failed", planId: "base-plan" },
+ ]);
+ expect(deriveBillingLifecycleEvents(pastDue, pastDue)).toEqual([]);
+ });
+
+ it("reports a cancellation once, whether scheduled or immediate", () => {
+ const canceling = snapshot({ canceledAt: 1_790_000_000_000 });
+ const canceled = { name: "subscription_canceled", planId: "base-plan" };
+ expect(deriveBillingLifecycleEvents(snapshot(), canceling)).toEqual([
+ canceled,
+ ]);
+ expect(deriveBillingLifecycleEvents(snapshot(), free)).toEqual([canceled]);
+ // Period end arrives: the cancellation was already reported.
+ expect(deriveBillingLifecycleEvents(canceling, free)).toEqual([]);
+ });
+
+ it("stays silent when a past-due subscription expires", () => {
+ expect(
+ deriveBillingLifecycleEvents(snapshot({ pastDue: true }), free),
+ ).toEqual([]);
+ });
+});
+
+describe("getBillingState", () => {
+ it("summarises the paid subscription for audience filters", () => {
+ expect(getBillingState(free)).toBe("none");
+ expect(getBillingState(snapshot())).toBe("active");
+ expect(getBillingState(snapshot({ pastDue: true }))).toBe("past_due");
+ expect(getBillingState(snapshot({ canceledAt: 1 }))).toBe("canceling");
+ expect(
+ getBillingState(snapshot({ paidPlanStatus: "expired", isPaying: false })),
+ ).toBe("expired");
+ });
+});
diff --git a/src/server/billing/lifecycle-events.ts b/src/server/billing/lifecycle-events.ts
new file mode 100644
index 00000000..ee756dc9
--- /dev/null
+++ b/src/server/billing/lifecycle-events.ts
@@ -0,0 +1,82 @@
+import { AUTUMN_PAID_PLAN_ID, AUTUMN_YC_PLAN_ID } from "@/shared/billing";
+import type { BillingCustomerStatusSnapshot } from "./customer-status-model";
+
+// Leaf module (no runtime imports) so the transition rules are unit-testable.
+
+// Plans that charge money. A plan can grant `paid_plan` without a price
+// (friends and family), and those customers are not thanked for subscribing.
+const PRICED_PLAN_IDS: ReadonlySet<string> = new Set([
+ AUTUMN_PAID_PLAN_ID,
+ AUTUMN_YC_PLAN_ID,
+]);
+
+export type BillingLifecycleEvent = {
+ name: "subscription_started" | "payment_failed" | "subscription_canceled";
+ planId: string;
+};
+
+type LifecycleSnapshot = Pick<
+ BillingCustomerStatusSnapshot,
+ "paidPlanId" | "paidPlanStatus" | "isPaying" | "pastDue" | "canceledAt"
+>;
+
+/**
+ * Compares the customer as it was at the last webhook with the customer as it
+ * is now and names the transitions worth an email. A retried webhook compares
+ * identical snapshots and yields nothing, which is the dedup.
+ *
+ * Silent on purpose: upgrades between priced plans, un-cancelling, and a
+ * past-due subscription finally expiring (they already got the payment email
+ * and did not choose to leave).
+ */
+export function deriveBillingLifecycleEvents(
+ previous: LifecycleSnapshot,
+ next: LifecycleSnapshot,
+): BillingLifecycleEvent[] {
+ const events: BillingLifecycleEvent[] = [];
+
+ if (isPricedSubscriber(next) && !isPricedSubscriber(previous)) {
+ events.push({ name: "subscription_started", planId: next.paidPlanId! });
+ }
+
+ if (next.pastDue && isPricedPlan(next.paidPlanId) && !previous.pastDue) {
+ events.push({ name: "payment_failed", planId: next.paidPlanId! });
+ }
+
+ const wasInGoodStanding =
+ isPricedSubscriber(previous) &&
+ !previous.pastDue &&
+ previous.canceledAt === null;
+ const isInGoodStanding = isPricedSubscriber(next) && next.canceledAt === null;
+ if (wasInGoodStanding && !isInGoodStanding) {
+ events.push({
+ name: "subscription_canceled",
+ planId: previous.paidPlanId!,
+ });
+ }
+
+ return events;
+}
+
+/** Contact-level summary for Loops audience filters. Covers every plan that
+ * grants `paid_plan`, not just priced ones, so segments keep matching the
+ * existing `billingPlanId`/`billingPlanStatus` properties. */
+export function getBillingState(
+ snapshot: Pick<
+ LifecycleSnapshot,
+ "paidPlanId" | "paidPlanStatus" | "pastDue" | "canceledAt"
+ >,
+) {
+ if (!snapshot.paidPlanId) return "none";
+ if (snapshot.pastDue) return "past_due";
+ if (snapshot.canceledAt !== null) return "canceling";
+ return snapshot.paidPlanStatus ?? "none";
+}
+
+function isPricedPlan(planId: string | null) {
+ return planId !== null && PRICED_PLAN_IDS.has(planId);
+}
+
+function isPricedSubscriber(snapshot: LifecycleSnapshot) {
+ return snapshot.isPaying && isPricedPlan(snapshot.paidPlanId);
+}
diff --git a/src/server/billing/loops-contact-properties.test.ts b/src/server/billing/loops-contact-properties.test.ts
index aa6be68f..28801744 100644
--- a/src/server/billing/loops-contact-properties.test.ts
+++ b/src/server/billing/loops-contact-properties.test.ts
@@ -10,10 +10,13 @@ describe("getBillingLoopsContactProperties", () => {
getBillingLoopsContactProperties({
paidPlanId: null,
paidPlanStatus: null,
+ pastDue: false,
+ canceledAt: null,
}),
).toEqual({
billingPlanId: LOOPS_BILLING_PLAN_NONE,
billingPlanStatus: LOOPS_BILLING_PLAN_NONE,
+ billingState: "none",
});
});
});
diff --git a/src/server/billing/loops-contact-properties.ts b/src/server/billing/loops-contact-properties.ts
index caa27f72..580718ce 100644
--- a/src/server/billing/loops-contact-properties.ts
+++ b/src/server/billing/loops-contact-properties.ts
@@ -1,15 +1,18 @@
import type { BillingCustomerStatusSnapshot } from "./customer-status-model";
+import { getBillingState } from "./lifecycle-events";
export const LOOPS_BILLING_PLAN_NONE = "none";
export function getBillingLoopsContactProperties(
snapshot: Pick<
BillingCustomerStatusSnapshot,
- "paidPlanId" | "paidPlanStatus"
+ "paidPlanId" | "paidPlanStatus" | "pastDue" | "canceledAt"
>,
) {
return {
billingPlanId: snapshot.paidPlanId ?? LOOPS_BILLING_PLAN_NONE,
billingPlanStatus: snapshot.paidPlanStatus ?? LOOPS_BILLING_PLAN_NONE,
+ // One property Loops workflows can filter on for "still in good standing".
+ billingState: getBillingState(snapshot),
};
}
diff --git a/src/server/billing/loops-sync.ts b/src/server/billing/loops-sync.ts
index 4b816b76..3dae792c 100644
--- a/src/server/billing/loops-sync.ts
+++ b/src/server/billing/loops-sync.ts
@@ -1,30 +1,65 @@
import { eq } from "drizzle-orm";
import { db } from "@/db";
import { member, user } from "@/db/schema";
+import { hasOrgPermission } from "@/lib/org-permissions";
import {
getContactNameParts,
+ sendLoopsEvent,
updateLoopsContact,
} from "@/server/email/loops-client";
import { getOptionalEnvValue } from "@/server/lib/runtime-env";
import type { BillingCustomerStatusSnapshot } from "./customer-status-model";
+import type { BillingLifecycleEvent } from "./lifecycle-events";
import { getBillingLoopsContactProperties } from "./loops-contact-properties";
-export async function syncBillingStatusToLoops(
- snapshot: BillingCustomerStatusSnapshot,
-) {
+/** Refreshes every member's billing properties in Loops and sends lifecycle
+ * events to the members who can manage billing — the only people who can act
+ * on a failed payment, and the ones who cancelled.
+ *
+ * Each event's idempotency key is the event, organization, recipient and the
+ * previous snapshot's timestamp, which is stable across webhook retries, so a
+ * retried send lands in Loops's 24-hour dedup window. */
+export async function syncBillingStatusToLoops({
+ snapshot,
+ events,
+ previousSyncedAt,
+}: {
+ snapshot: BillingCustomerStatusSnapshot;
+ events: BillingLifecycleEvent[];
+ previousSyncedAt: string | null;
+}) {
const apiKey = await getOptionalEnvValue("LOOPS_API_KEY");
if (!apiKey) {
- console.warn(
- "Skipping Loops billing contact sync: LOOPS_API_KEY is not set",
- );
+ console.warn("Skipping Loops billing sync: LOOPS_API_KEY is not set");
return;
}
const contacts = await getOrganizationContacts(snapshot.organizationId);
const billingProperties = getBillingLoopsContactProperties(snapshot);
+ const logContext = {
+ action: "billing-contact-sync",
+ organizationId: snapshot.organizationId,
+ };
for (const contact of contacts) {
+ const canManageBilling = hasOrgPermission(contact.role, {
+ billing: ["manage"],
+ });
+ for (const event of canManageBilling ? events : []) {
+ await sendLoopsEvent({
+ apiKey,
+ idempotencyKey: `${event.name}:${snapshot.organizationId}:${contact.userId}:${previousSyncedAt}`,
+ payload: {
+ email: contact.email,
+ userId: contact.userId,
+ eventName: event.name,
+ eventProperties: { planId: event.planId },
+ },
+ logContext,
+ });
+ }
+
await updateLoopsContact({
apiKey,
payload: {
@@ -34,10 +69,7 @@ export async function syncBillingStatusToLoops(
...getContactNameParts(contact.name),
...billingProperties,
},
- logContext: {
- action: "billing-contact-sync",
- organizationId: snapshot.organizationId,
- },
+ logContext,
});
}
}
@@ -48,6 +80,7 @@ async function getOrganizationContacts(organizationId: string) {
userId: user.id,
email: user.email,
name: user.name,
+ role: member.role,
})
.from(member)
.innerJoin(user, eq(member.userId, user.id))
diff --git a/src/server/email/loops-client.ts b/src/server/email/loops-client.ts
index aecd3702..cdf52270 100644
--- a/src/server/email/loops-client.ts
+++ b/src/server/email/loops-client.ts
@@ -1,4 +1,5 @@
const LOOPS_CONTACT_UPDATE_URL = "https://app.loops.so/api/v1/contacts/update";
+const LOOPS_EVENT_SEND_URL = "https://app.loops.so/api/v1/events/send";
type LoopsContactProperty =
| string
@@ -28,22 +29,85 @@ export async function updateLoopsContact({
payload: LoopsContactUpdatePayload;
logContext?: Record<string, unknown>;
}) {
- const response = await fetch(LOOPS_CONTACT_UPDATE_URL, {
+ await loopsRequest({
+ apiKey,
method: "PUT",
+ url: LOOPS_CONTACT_UPDATE_URL,
+ payload,
+ label: "update Loops contact",
+ logContext,
+ });
+}
+
+type LoopsEventPayload = {
+ email: string;
+ userId: string;
+ eventName: string;
+ eventProperties?: Record<string, string | number | boolean>;
+};
+
+/** Sends a Loops event, which triggers any workflow listening for it. Loops
+ * honours the idempotency key for 24 hours and answers a replay with 409,
+ * which is a success here: the email was already queued. */
+export async function sendLoopsEvent({
+ apiKey,
+ payload,
+ idempotencyKey,
+ logContext,
+}: {
+ apiKey: string;
+ payload: LoopsEventPayload;
+ idempotencyKey: string;
+ logContext?: Record<string, unknown>;
+}) {
+ await loopsRequest({
+ apiKey,
+ method: "POST",
+ url: LOOPS_EVENT_SEND_URL,
+ payload,
+ headers: { "Idempotency-Key": idempotencyKey },
+ okStatuses: [409],
+ label: "send Loops event",
+ logContext: { ...logContext, eventName: payload.eventName },
+ });
+}
+
+async function loopsRequest({
+ apiKey,
+ method,
+ url,
+ payload,
+ headers,
+ okStatuses = [],
+ label,
+ logContext,
+}: {
+ apiKey: string;
+ method: "PUT" | "POST";
+ url: string;
+ payload: { email?: string; userId?: string };
+ headers?: Record<string, string>;
+ okStatuses?: number[];
+ label: string;
+ logContext?: Record<string, unknown>;
+}) {
+ const response = await fetch(url, {
+ method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
+ ...headers,
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10_000),
});
- if (response.ok) {
+ if (response.ok || okStatuses.includes(response.status)) {
return;
}
const errorPayload = await response.json().catch(() => null);
- console.warn("Loops contact update error:", {
+ console.warn(`Loops error (${label}):`, {
status: response.status,
email: payload.email,
userId: payload.userId,
@@ -51,7 +115,7 @@ export async function updateLoopsContact({
errorPayload,
});
- throw new Error(`Failed to update Loops contact (${response.status})`);
+ throw new Error(`Failed to ${label} (${response.status})`);
}
export function getContactNameParts(name: string | null | undefined) {