Skip to content

An open-source, faster Devin alternative

TypeScript

Billing funnel events: plan_changed, payment_failed/recovered, credits_purchased

Mohamed Habib via Computer4aec738563b8
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
index 1c9c0cd6..97e22825 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
@@ -3,6 +3,9 @@ import {
autumnPurchase,
autumnSetAutoTopup,
autumnUsagePlanPurchase,
+ billingWebhookEvents,
+ planChangeKind,
+ syncAutumnToD1,
summarizeAutumnCreditBalance,
type AutumnApiEnv,
} from "./autumn_webhook";
@@ -265,3 +268,88 @@ describe("Autumn shared-credit plan purchases", () => {
);
});
});
+
+describe("billing funnel events from Autumn", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("names plan transitions", () => {
+ expect(planChangeKind("base", "pro", false)).toBe("trial_converted");
+ expect(planChangeKind("pro", "max", false)).toBe("upgrade");
+ expect(planChangeKind("max", "pro", false)).toBe("downgrade");
+ expect(planChangeKind("pro", "base", false)).toBe("cancel");
+ expect(planChangeKind("pro", "base", true)).toBe("lapsed");
+ });
+
+ it("maps payment and top-up webhooks to events", () => {
+ expect(
+ billingWebhookEvents({
+ type: "billing.updated",
+ data: {
+ plan_changes: [
+ { action: "updated", subscription: { plan_id: "pro", past_due: true }, previous_attributes: { past_due: false } },
+ { action: "updated", subscription: { plan_id: "max", past_due: false }, previous_attributes: { past_due: true } },
+ { action: "activated", subscription: { plan_id: "pro", past_due: false }, previous_attributes: null },
+ ],
+ },
+ }),
+ ).toEqual([
+ { name: "billing.payment_failed", data: { plan: "pro" } },
+ { name: "billing.payment_recovered", data: { plan: "max" } },
+ ]);
+ expect(billingWebhookEvents({ type: "billing.auto_topup_succeeded", data: { quantity_granted: 50 } })).toEqual([
+ { name: "billing.credits_purchased", data: { amount: 50, auto: true } },
+ ]);
+ expect(billingWebhookEvents({ type: "billing.auto_topup_failed", data: { reason: "charge_failed" } })).toEqual([
+ { name: "billing.payment_failed", data: { plan: "top_up", reason: "charge_failed" } },
+ ]);
+ expect(billingWebhookEvents({ type: "balances.limit_reached", data: {} })).toEqual([]);
+ });
+
+ function planDb(usagePlan: string) {
+ const org = { is_halted: 0, autumn_concurrency_override: null, usage_plan: usagePlan };
+ return {
+ prepare(sql: string) {
+ return {
+ bind(...args: unknown[]) {
+ return {
+ first: async () => ({ ...org }),
+ run: async () => {
+ if (sql.includes("AND usage_plan = ?3")) {
+ if (org.usage_plan !== args[2]) return { meta: { changes: 0 } };
+ org.usage_plan = args[0] as string;
+ }
+ return { meta: { changes: 1 } };
+ },
+ };
+ },
+ };
+ },
+ } as unknown as D1Database;
+ }
+
+ it("emits plan_changed once when the projection moves the plan", async () => {
+ const posted: Array<Record<string, unknown>> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ const url = String(input);
+ if (url.startsWith("https://autumn.test/v1/customers/")) {
+ return Response.json({
+ id: "org_1",
+ subscriptions: [{ plan_id: "pro", add_on: false, status: "active" }],
+ balances: { credits: { remaining: 10 } },
+ });
+ }
+ posted.push(JSON.parse(String(init?.body)));
+ return new Response(null, { status: 200 });
+ });
+ const syncEnv = { ...env, OPENCOMPUTER_DB: planDb("base"), POSTHOG_PROJECT_TOKEN: "phc_test" };
+
+ expect((await syncAutumnToD1(syncEnv, "org_1"))?.usagePlan).toBe("pro");
+ await syncAutumnToD1(syncEnv, "org_1");
+
+ expect(posted).toHaveLength(1);
+ expect(posted[0]).toMatchObject({
+ event: "billing.plan_changed",
+ properties: { from: "base", to: "pro", kind: "trial_converted" },
+ });
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index 811d05ab..f4248c94 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -12,11 +12,13 @@
// to the cells running the org's sandboxes (same HMAC scheme the DO used).
//
// Event catalog (Svix): billing.updated, billing.auto_topup_succeeded,
-// balances.limit_reached, balances.usage_alert_triggered. customer.products.updated
-// is Deprecated and ignored. Because we always re-check, every event is handled
-// uniformly — the type only decides whether we bother projecting at all.
+// billing.auto_topup_failed, balances.limit_reached, balances.usage_alert_triggered.
+// customer.products.updated is Deprecated and ignored. Because we always re-check,
+// every event is handled uniformly — the type only decides whether we bother
+// projecting at all. The payload is read beyond customer_id only for funnel
+// events (billingWebhookEvents), never for the projection.
-import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
+import { emitBillingEvent, type BillingEventName, type BillingEventsEnv } from "./billing_events";
// AutumnApiEnv is the minimal binding set for calling Autumn's REST API
// (GetCustomer / checkout). The dashboard handlers satisfy this without the
@@ -27,12 +29,12 @@ export interface AutumnApiEnv {
}
// AutumnSyncEnv adds D1 — enough to project Autumn state without dispatching.
-export interface AutumnSyncEnv extends AutumnApiEnv {
+export interface AutumnSyncEnv extends AutumnApiEnv, BillingEventsEnv {
OPENCOMPUTER_DB: D1Database;
}
// AutumnEnv adds the secrets needed to dispatch halt to cells + verify webhooks.
-export interface AutumnEnv extends AutumnSyncEnv, BillingEventsEnv {
+export interface AutumnEnv extends AutumnSyncEnv {
CF_ADMIN_SECRET: string;
EVENT_SECRET: string;
AUTUMN_WEBHOOK_SECRET: string;
@@ -90,6 +92,7 @@ export function isPaidUsagePlan(plan: string | null | undefined): boolean {
const HANDLED_EVENTS = new Set([
"billing.updated",
"billing.auto_topup_succeeded",
+ "billing.auto_topup_failed",
"balances.limit_reached",
"balances.usage_alert_triggered",
]);
@@ -238,7 +241,7 @@ export async function autumnWebhook(
return json({ error: "signature mismatch" }, 401);
}
- let evt: { type?: string; data?: { customer_id?: string } };
+ let evt: AutumnWebhookPayload;
try {
evt = JSON.parse(rawBody);
} catch {
@@ -253,16 +256,79 @@ export async function autumnWebhook(
}
try {
- await projectOrg(env, orgID);
+ await projectOrg(env, orgID, { lapsed: subscriptionLapsed(evt) });
} catch (err) {
// 5xx → Svix retries with backoff (the Go reconciler is the longer backstop).
console.error(`autumn-webhook: project ${orgID} (${type}) failed`, err);
return json({ error: "projection failed" }, 502);
}
+ // After the projection, so a 5xx retry does not count the event twice.
+ for (const e of billingWebhookEvents(evt)) await emitBillingEvent(env, e.name, { orgId: orgID, data: e.data });
await afterProject?.(orgID).catch((err) => console.error(`autumn-webhook: after-project ${orgID} (${type}) failed`, err));
return json({ ok: true, type, org_id: orgID });
}
+// The webhook fields the funnel events read (docs.useautumn.com/documentation/webhooks).
+interface AutumnPlanChange {
+ action?: string; // activated | scheduled | updated | expired
+ subscription?: { plan_id?: string; past_due?: boolean };
+ previous_attributes?: { past_due?: boolean } | null;
+}
+interface AutumnWebhookPayload {
+ type?: string;
+ data?: {
+ customer_id?: string;
+ plan_changes?: AutumnPlanChange[];
+ quantity_granted?: number;
+ reason?: string;
+ };
+}
+
+// A subscription that expired while past due lapsed for non-payment; any other
+// expiry is a cancel. Only the webhook knows which, so it hints the projection.
+function subscriptionLapsed(evt: AutumnWebhookPayload): boolean {
+ if (evt.type !== "billing.updated") return false;
+ return (evt.data?.plan_changes ?? []).some((c) => c.action === "expired" && c.subscription?.past_due === true);
+}
+
+// billingWebhookEvents maps one Autumn webhook to its funnel events. Plan changes
+// are not here: syncAutumnToD1 emits those, since checkout-return can project a
+// new plan before its webhook arrives. Autumn reports no retry count, so
+// payment_failed carries no `attempt`.
+export function billingWebhookEvents(
+ evt: AutumnWebhookPayload,
+): Array<{ name: BillingEventName; data: Record<string, string | number | boolean | null> }> {
+ const d = evt.data ?? {};
+ switch (evt.type) {
+ case "billing.auto_topup_succeeded":
+ return [{ name: "billing.credits_purchased", data: { amount: d.quantity_granted ?? null, auto: true } }];
+ case "billing.auto_topup_failed":
+ return [{ name: "billing.payment_failed", data: { plan: "top_up", reason: d.reason ?? null } }];
+ case "billing.updated":
+ return (d.plan_changes ?? []).flatMap((c) => {
+ const was = c.previous_attributes?.past_due;
+ const now = c.subscription?.past_due;
+ if (was === undefined || now === undefined || was === now) return [];
+ return [
+ {
+ name: now ? ("billing.payment_failed" as const) : ("billing.payment_recovered" as const),
+ data: { plan: c.subscription?.plan_id ?? null },
+ },
+ ];
+ });
+ default:
+ return [];
+ }
+}
+
+// planChangeKind names a usage-plan transition for billing.plan_changed. `base`
+// is "no paid plan" (the trial, or a pre-launch free org) until step 5 names it.
+export function planChangeKind(from: UsagePlan, to: UsagePlan, lapsed: boolean): string {
+ if (from === "base") return "trial_converted";
+ if (to === "base") return lapsed ? "lapsed" : "cancel";
+ return USAGE_PLAN_RANK[to] > USAGE_PLAN_RANK[from] ? "upgrade" : "downgrade";
+}
+
// autumnProjectInternal is the cell/reconciler-facing trigger for the SAME
// re-check+project logic, behind the in-house EVENT_SECRET HMAC ({ts}.{body}).
// The cell's inline halt (off track()) and the Go reconciler POST this so they
@@ -542,7 +608,11 @@ export interface AutumnSyncResult {
usagePlan: UsagePlan;
}
-export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise<AutumnSyncResult | null> {
+export async function syncAutumnToD1(
+ env: AutumnSyncEnv,
+ orgID: string,
+ opts: { lapsed?: boolean } = {},
+): Promise<AutumnSyncResult | null> {
const cust = await getAutumnCustomer(env, orgID);
if (!cust) {
console.error(`autumn: customer ${orgID} not found in Autumn`);
@@ -555,12 +625,29 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
const projectedMaxConcurrent = maxConcurrency(cust.subscriptions ?? []);
const nowSec = Math.floor(Date.now() / 1000);
- const prevRow = await env.OPENCOMPUTER_DB.prepare("SELECT is_halted, autumn_concurrency_override FROM orgs WHERE id = ?1")
+ const prevRow = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT is_halted, autumn_concurrency_override, usage_plan FROM orgs WHERE id = ?1",
+ )
.bind(orgID)
- .first<{ is_halted: number; autumn_concurrency_override: number | null }>();
+ .first<{ is_halted: number; autumn_concurrency_override: number | null; usage_plan: UsagePlan }>();
const wasHalted = prevRow?.is_halted === 1;
const maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;
+ // Compare-and-set the plan first: the webhook, checkout-return and the cron can
+ // project the same change concurrently, and only the writer that moves it emits.
+ const fromPlan = prevRow?.usage_plan;
+ if (fromPlan && fromPlan !== usagePlan) {
+ const moved = await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET usage_plan = ?1 WHERE id = ?2 AND usage_plan = ?3")
+ .bind(usagePlan, orgID, fromPlan)
+ .run();
+ if (moved.meta?.changes === 1) {
+ await emitBillingEvent(env, "billing.plan_changed", {
+ orgId: orgID,
+ data: { from: fromPlan, to: usagePlan, kind: planChangeKind(fromPlan, usagePlan, opts.lapsed === true) },
+ });
+ }
+ }
+
await env.OPENCOMPUTER_DB.prepare(
`UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, usage_plan = ?4, updated_at = ?5 WHERE id = ?6`,
)
@@ -614,8 +701,8 @@ export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): P
// do NOT dispatch — D1.is_halted is already cleared, which unblocks the gates;
// hibernated boxes wake lazily on the next request. This is the locked "no
// auto-wake for prepaid" decision: a top-up unblocks but never force-wakes.
-export async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {
- const r = await syncAutumnToD1(env, orgID);
+export async function projectOrg(env: AutumnEnv, orgID: string, opts: { lapsed?: boolean } = {}): Promise<void> {
+ const r = await syncAutumnToD1(env, orgID, opts);
if (!r || !r.halted) return;
// Dispatch halt on the fresh transition, OR whenever a halted org STILL has
// running sandboxes — so a halt is eventually complete even if a single
diff --git a/cloudflare-workers/api-edge/src/billing_events.ts b/cloudflare-workers/api-edge/src/billing_events.ts
index 29589c2c..db4c04c6 100644
--- a/cloudflare-workers/api-edge/src/billing_events.ts
+++ b/cloudflare-workers/api-edge/src/billing_events.ts
@@ -21,7 +21,11 @@ export type BillingEventName =
| "billing.trial_started"
| "billing.work_minutes_recorded"
| "billing.first_work_minute"
- | "billing.checkout_opened";
+ | "billing.checkout_opened"
+ | "billing.plan_changed"
+ | "billing.payment_failed"
+ | "billing.payment_recovered"
+ | "billing.credits_purchased";
export interface BillingEvent {
orgId: string;
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 2f3a063f..bd7d6513 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -1829,7 +1829,7 @@ async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: {
// recharge. Monetary values are integer credits ($1 each). Autumn expresses the
// hard monthly budget as a purchase count, so budget must be a whole multiple of
// quantity. A saved payment method is required for charges to succeed.
-async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: { orgID: string; userID?: string }): Promise<Response> {
if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
let body: { enabled?: boolean; threshold?: number; quantity?: number; budget?: number };
try {
@@ -1871,6 +1871,7 @@ async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: {
quantity,
successUrl: `${origin}/api/dashboard/billing/autumn/finalize-arm?credits=${quantity}`,
});
+ if (!co.url) await emitCreditsPurchased(env, caller, quantity);
return json({ ok: true, url: co.url });
}
return json({ ok: true, url: null });
@@ -1886,7 +1887,7 @@ async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: {
// dropped query params), which both adds the credits and arms auto-recharge, then
// 302 back to the billing page. Authenticated by the session cookie carried on
// the redirect.
-async function handleAutumnFinalizeArm(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+async function handleAutumnFinalizeArm(req: Request, env: DashboardEnv, caller: { orgID: string; userID?: string }): Promise<Response> {
const origin = new URL(req.url).origin;
const billing = `${origin}/dashboard/billing`;
if (!env.AUTUMN_SECRET_KEY) return Response.redirect(billing, 302);
@@ -1901,6 +1902,7 @@ async function handleAutumnFinalizeArm(req: Request, env: DashboardEnv, caller:
productId: "top_up",
options: [{ feature_id: "credits", quantity: credits }],
});
+ await emitCreditsPurchased(env, caller, credits);
} catch (e) {
console.error("billing/autumn finalize-arm:", e);
return Response.redirect(`${billing}?arm=failed`, 302);
@@ -1909,10 +1911,21 @@ async function handleAutumnFinalizeArm(req: Request, env: DashboardEnv, caller:
return Response.redirect(`${billing}?arm=ok`, 302);
}
+// A manual credit pack is charged here, server-side: directly when a card is on
+// file (url null), or in finalize-arm after the hosted card setup. Auto top-ups
+// are counted from Autumn's webhook instead.
+async function emitCreditsPurchased(env: DashboardEnv, caller: { orgID: string; userID?: string }, credits: number) {
+ await emitBillingEvent(env, "billing.credits_purchased", {
+ orgId: caller.orgID,
+ userId: caller.userID,
+ data: { amount: credits, auto: false },
+ });
+}
+
// POST /api/dashboard/billing/autumn/topup { credits } — one-off prepaid credit
// purchase. Returns a Stripe checkout URL; success returns to the billing page
// where handleAutumnBilling re-syncs the new balance.
-async function handleAutumnTopup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+async function handleAutumnTopup(req: Request, env: DashboardEnv, caller: { orgID: string; userID?: string }): Promise<Response> {
if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
let body: { credits?: number };
try {
@@ -1934,6 +1947,7 @@ async function handleAutumnTopup(req: Request, env: DashboardEnv, caller: { orgI
quantity: credits,
successUrl: `${origin}/api/dashboard/billing/autumn/finalize-arm?credits=${credits}`,
});
+ if (!co.url) await emitCreditsPurchased(env, caller, credits);
return json({ url: co.url });
} catch (e) {
console.error("billing/autumn topup:", e);