Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(billing): keep failed webhooks replayable and preserve subscription dates

Andrejb539c7624fac
diff --git a/apps/api/src/billing/controllers/handle-webhook.ts b/apps/api/src/billing/controllers/handle-webhook.ts
index 6e56eab2e..587932cf6 100644
--- a/apps/api/src/billing/controllers/handle-webhook.ts
+++ b/apps/api/src/billing/controllers/handle-webhook.ts
@@ -32,6 +32,8 @@ export type BillingWebhookEvent = {
data: WebhookObject;
};
+type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
+
function parseDate(value: string | null | undefined) {
if (!value) {
return null;
@@ -51,19 +53,46 @@ const SUBSCRIPTION_EVENT_STATUS: Record<string, string> = {
"subscription.paused": "paused",
};
-async function handleWebhook(event: BillingWebhookEvent) {
- if (event.id) {
- const [claimed] = await db
- .insert(billingEventTable)
- .values({ id: event.id, eventType: event.type })
- .onConflictDoNothing({ target: billingEventTable.id })
- .returning();
+export function buildSubscriptionUpdates(event: BillingWebhookEvent) {
+ const object = event.data;
+ const productId = object.product?.id;
+ const mapped = productId ? planForProductId(productId) : null;
+ const units = object.items?.[0]?.units;
- if (!claimed) {
- return { processed: false, duplicate: true };
- }
+ const updates: Partial<typeof workspaceBillingTable.$inferInsert> = {
+ status: object.status ?? SUBSCRIPTION_EVENT_STATUS[event.type] ?? undefined,
+ };
+
+ const periodEnd =
+ object.current_period_end_date !== undefined
+ ? object.current_period_end_date
+ : object.currentPeriodEndDate;
+ if (periodEnd !== undefined) {
+ updates.currentPeriodEnd = parseDate(periodEnd);
}
+ const canceledAt =
+ object.canceled_at !== undefined ? object.canceled_at : object.canceledAt;
+ if (canceledAt !== undefined) {
+ updates.canceledAt = parseDate(canceledAt);
+ }
+
+ if (productId) {
+ updates.creemProductId = productId;
+ updates.plan = mapped?.plan ?? null;
+ updates.billingInterval = mapped?.interval ?? null;
+ }
+ if (typeof units === "number" && units > 0) {
+ updates.seats = units;
+ }
+ if (object.customer?.id) {
+ updates.creemCustomerId = object.customer.id;
+ }
+
+ return updates;
+}
+
+async function applyEvent(event: BillingWebhookEvent, tx: DbOrTx) {
const object = event.data;
if (event.type === "checkout.completed") {
@@ -78,7 +107,7 @@ async function handleWebhook(event: BillingWebhookEvent) {
const productId = object.product?.id ?? object.subscription?.product?.id;
const mapped = productId ? planForProductId(productId) : null;
- await db
+ await tx
.update(workspaceBillingTable)
.set({
creemCustomerId:
@@ -99,38 +128,16 @@ async function handleWebhook(event: BillingWebhookEvent) {
return { processed: false, duplicate: false };
}
- const productId = object.product?.id;
- const mapped = productId ? planForProductId(productId) : null;
- const units = object.items?.[0]?.units;
-
- const updates: Partial<typeof workspaceBillingTable.$inferInsert> = {
- status:
- object.status ?? SUBSCRIPTION_EVENT_STATUS[event.type] ?? undefined,
- currentPeriodEnd: parseDate(
- object.current_period_end_date ?? object.currentPeriodEndDate,
- ),
- canceledAt: parseDate(object.canceled_at ?? object.canceledAt),
- };
- if (productId) {
- updates.creemProductId = productId;
- updates.plan = mapped?.plan ?? null;
- updates.billingInterval = mapped?.interval ?? null;
- }
- if (typeof units === "number" && units > 0) {
- updates.seats = units;
- }
- if (object.customer?.id) {
- updates.creemCustomerId = object.customer.id;
- }
+ const updates = buildSubscriptionUpdates(event);
- const updated = await db
+ const updated = await tx
.update(workspaceBillingTable)
.set(updates)
.where(eq(workspaceBillingTable.creemSubscriptionId, subscriptionId))
.returning({ id: workspaceBillingTable.id });
if (updated.length === 0 && object.metadata?.workspaceId) {
- await db
+ await tx
.update(workspaceBillingTable)
.set({ ...updates, creemSubscriptionId: subscriptionId })
.where(
@@ -143,4 +150,26 @@ async function handleWebhook(event: BillingWebhookEvent) {
return { processed: true, duplicate: false };
}
+async function handleWebhook(event: BillingWebhookEvent) {
+ const eventId = event.id;
+ if (!eventId) {
+ return applyEvent(event, db);
+ }
+
+ // A claim that outlives a failed apply makes the retry look like a duplicate.
+ return db.transaction(async (tx) => {
+ const [claimed] = await tx
+ .insert(billingEventTable)
+ .values({ id: eventId, eventType: event.type })
+ .onConflictDoNothing({ target: billingEventTable.id })
+ .returning();
+
+ if (!claimed) {
+ return { processed: false, duplicate: true };
+ }
+
+ return applyEvent(event, tx);
+ });
+}
+
export default handleWebhook;
diff --git a/tests/api-integration/billing-webhook.test.ts b/tests/api-integration/billing-webhook.test.ts
new file mode 100644
index 000000000..bf117150e
--- /dev/null
+++ b/tests/api-integration/billing-webhook.test.ts
@@ -0,0 +1,158 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { planForProductId } = vi.hoisted(() => ({
+ planForProductId: vi.fn(() => ({
+ plan: "team" as const,
+ interval: "monthly" as const,
+ })),
+}));
+vi.mock("../../apps/api/src/billing/config", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("../../apps/api/src/billing/config")>();
+ return { ...actual, planForProductId };
+});
+
+import handleWebhook, {
+ type BillingWebhookEvent,
+} from "../../apps/api/src/billing/controllers/handle-webhook";
+import db, { schema } from "../../apps/api/src/database";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+const PERIOD_END = new Date("2026-09-01T00:00:00.000Z");
+
+async function seedBilling(
+ workspaceId: string,
+ overrides: Partial<typeof schema.workspaceBillingTable.$inferInsert> = {},
+) {
+ await db.insert(schema.workspaceBillingTable).values({
+ workspaceId,
+ plan: "team",
+ status: "active",
+ seats: 1,
+ creemSubscriptionId: `sub-${workspaceId}`,
+ creemProductId: "prod_team_monthly",
+ currentPeriodEnd: PERIOD_END,
+ ...overrides,
+ });
+}
+
+async function readBilling(workspaceId: string) {
+ const [row] = await db
+ .select()
+ .from(schema.workspaceBillingTable)
+ .where(eq(schema.workspaceBillingTable.workspaceId, workspaceId));
+ return row;
+}
+
+function subscriptionEvent(
+ id: string,
+ workspaceId: string,
+ data: Record<string, unknown> = {},
+): BillingWebhookEvent {
+ return {
+ id,
+ type: "subscription.canceled",
+ data: {
+ id: `sub-${workspaceId}`,
+ status: "canceled",
+ product: { id: "prod_team_monthly" },
+ ...data,
+ },
+ };
+}
+
+describe("API integration: billing webhooks", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ planForProductId.mockClear();
+ });
+
+ it("applies a subscription event once and suppresses the replay", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ await seedBilling(owner.workspace.id);
+ const event = subscriptionEvent("evt-dup", owner.workspace.id);
+
+ expect(await handleWebhook(event)).toEqual({
+ processed: true,
+ duplicate: false,
+ });
+ expect(await handleWebhook(event)).toEqual({
+ processed: false,
+ duplicate: true,
+ });
+
+ expect((await readBilling(owner.workspace.id)).status).toBe("canceled");
+ });
+
+ it("leaves the event replayable when applying it fails", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ await seedBilling(owner.workspace.id);
+ const event = subscriptionEvent("evt-fail", owner.workspace.id);
+
+ planForProductId.mockImplementationOnce(() => {
+ throw new Error("apply failed");
+ });
+ await expect(handleWebhook(event)).rejects.toThrow("apply failed");
+
+ expect(await db.select().from(schema.billingEventTable)).toHaveLength(0);
+ expect((await readBilling(owner.workspace.id)).status).toBe("active");
+
+ expect(await handleWebhook(event)).toEqual({
+ processed: true,
+ duplicate: false,
+ });
+ expect((await readBilling(owner.workspace.id)).status).toBe("canceled");
+ });
+
+ it("keeps a known period end when a later event omits it", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ await seedBilling(owner.workspace.id);
+
+ await handleWebhook({
+ id: "evt-paid",
+ type: "subscription.paid",
+ data: { id: `sub-${owner.workspace.id}`, status: "active" },
+ });
+
+ expect((await readBilling(owner.workspace.id)).currentPeriodEnd).toEqual(
+ PERIOD_END,
+ );
+ });
+
+ it("keeps a recorded cancellation when a later event omits it", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const canceledAt = new Date("2026-08-20T00:00:00.000Z");
+ await seedBilling(owner.workspace.id, { canceledAt });
+
+ await handleWebhook({
+ id: "evt-active",
+ type: "subscription.active",
+ data: { id: `sub-${owner.workspace.id}`, status: "active" },
+ });
+
+ expect((await readBilling(owner.workspace.id)).canceledAt).toEqual(
+ canceledAt,
+ );
+ });
+
+ it("clears the cancellation when the provider sends an explicit null", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ await seedBilling(owner.workspace.id, {
+ canceledAt: new Date("2026-08-20T00:00:00.000Z"),
+ });
+
+ await handleWebhook({
+ id: "evt-resumed",
+ type: "subscription.active",
+ data: {
+ id: `sub-${owner.workspace.id}`,
+ status: "active",
+ canceled_at: null,
+ },
+ });
+
+ expect((await readBilling(owner.workspace.id)).canceledAt).toBeNull();
+ });
+});
diff --git a/tests/api-integration/helpers/database.ts b/tests/api-integration/helpers/database.ts
index c1b079300..5fdaaf6d4 100644
--- a/tests/api-integration/helpers/database.ts
+++ b/tests/api-integration/helpers/database.ts
@@ -89,6 +89,7 @@ export async function resetTestDatabase() {
"account",
"apikey",
"asset",
+ "billing_event",
"column",
"comment",
"external_link",