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): resize Creem seats by subscription item id (#1836)

Andrej01aa59eb398f
diff --git a/apps/api/src/billing/controllers/sync-seats.ts b/apps/api/src/billing/controllers/sync-seats.ts
index c999e067d..4e114cd9c 100644
--- a/apps/api/src/billing/controllers/sync-seats.ts
+++ b/apps/api/src/billing/controllers/sync-seats.ts
@@ -36,16 +36,14 @@ export async function syncWorkspaceSeats(workspaceId: string) {
return;
}
- const result = await updateSubscriptionSeats({
+ await updateSubscriptionSeats({
subscriptionId: billing.creemSubscriptionId,
productId: billing.creemProductId,
units: seats,
});
- if (result.ok) {
- await db
- .update(workspaceBillingTable)
- .set({ seats })
- .where(eq(workspaceBillingTable.workspaceId, workspaceId));
- }
+ await db
+ .update(workspaceBillingTable)
+ .set({ seats })
+ .where(eq(workspaceBillingTable.workspaceId, workspaceId));
}
diff --git a/apps/api/src/billing/creem-client.ts b/apps/api/src/billing/creem-client.ts
index cb6c9a6fd..9c66a220f 100644
--- a/apps/api/src/billing/creem-client.ts
+++ b/apps/api/src/billing/creem-client.ts
@@ -44,16 +44,29 @@ export async function updateSubscriptionSeats(input: {
productId: string;
units: number;
}) {
- try {
- await creemClient().subscriptions.update(input.subscriptionId, {
- items: [{ productId: input.productId, units: input.units }],
- updateBehavior: "proration-charge",
- });
- return { ok: true as const };
- } catch (error) {
- console.error("Creem seat update failed:", error);
- return { ok: false as const };
+ const client = creemClient();
+
+ const subscription = await client.subscriptions.get(input.subscriptionId);
+ const items = subscription.items ?? [];
+ // A stale stored product id still resolves on a single-item subscription,
+ // which is the shape Kaneo sells. Guessing among several items would bill
+ // the wrong product, so that case has to be repaired by hand.
+ const item =
+ items.find((entry) => entry.productId === input.productId) ??
+ (items.length === 1 ? items[0] : undefined);
+
+ if (!item) {
+ throw new Error(
+ `Creem subscription ${input.subscriptionId} has no item for product ${input.productId}`,
+ );
}
+
+ // Creem creates an additional item when the item id is omitted, and rejects
+ // the duplicate product with a 403, so the existing item id must be sent.
+ await client.subscriptions.update(input.subscriptionId, {
+ items: [{ id: item.id, units: input.units }],
+ updateBehavior: "proration-charge",
+ });
}
export async function createCustomerPortalLink(customerId: string) {
diff --git a/tests/api-integration/billing-seat-sync.test.ts b/tests/api-integration/billing-seat-sync.test.ts
index d4fc67c1b..030ab75fb 100644
--- a/tests/api-integration/billing-seat-sync.test.ts
+++ b/tests/api-integration/billing-seat-sync.test.ts
@@ -88,6 +88,23 @@ describe("API integration: seat sync", () => {
expect(row.seats).toBe(2);
});
+ it("leaves the stored seat count alone when the provider rejects the update", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ await teamBilling(owner.workspace.id, 1);
+ await addMember(owner.workspace.id);
+ updateSubscriptionSeats.mockRejectedValueOnce(new Error("Status 403"));
+
+ await expect(syncWorkspaceSeats(owner.workspace.id)).rejects.toThrow(
+ "Status 403",
+ );
+
+ const [row] = await db
+ .select()
+ .from(schema.workspaceBillingTable)
+ .where(eq(schema.workspaceBillingTable.workspaceId, owner.workspace.id));
+ expect(row.seats).toBe(1);
+ });
+
it("does nothing when the seat count already matches", async () => {
const owner = await createWorkspaceMember({ role: "owner" });
await teamBilling(owner.workspace.id, 1); // 1 member, seats already 1
diff --git a/tests/api/billing/creem-seat-update.test.ts b/tests/api/billing/creem-seat-update.test.ts
new file mode 100644
index 000000000..2d0ee57fc
--- /dev/null
+++ b/tests/api/billing/creem-seat-update.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { updateSubscriptionSeats } from "../../../apps/api/src/billing/creem-client";
+
+// Indexed rather than read literally so Biome does not demand a turbo.json
+// env declaration for a key only this test sets.
+const API_KEY = "CREEM_API_KEY";
+const savedApiKey = process.env[API_KEY];
+const realFetch = globalThis.fetch;
+
+type Call = { url: string; method: string; body: unknown };
+let calls: Call[];
+
+function subscription(items: Array<{ id: string; product_id?: string }>) {
+ return {
+ id: "sub_1",
+ mode: "prod",
+ object: "subscription",
+ product: "prod_team",
+ customer: "cust_1",
+ items: items.map((item) => ({
+ ...item,
+ mode: "prod",
+ object: "subscription_item",
+ units: 1,
+ })),
+ collection_method: "charge_automatically",
+ status: "active",
+ created_at: "2026-09-25T09:40:01.887Z",
+ updated_at: "2026-09-25T09:40:01.887Z",
+ };
+}
+
+function respondWith(getBody: unknown) {
+ globalThis.fetch = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = input instanceof Request ? input : null;
+ const url = request ? request.url : String(input);
+ const method = request?.method ?? init?.method ?? "GET";
+ const raw = request
+ ? await request.text()
+ : (init?.body as string | undefined);
+
+ calls.push({ url, method, body: raw ? JSON.parse(raw) : undefined });
+
+ return new Response(
+ JSON.stringify(method === "POST" ? subscription([]) : getBody),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ },
+ );
+ },
+ ) as typeof fetch;
+}
+
+beforeEach(() => {
+ calls = [];
+ process.env[API_KEY] = "creem_test_dummy";
+});
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ if (savedApiKey === undefined) {
+ delete process.env[API_KEY];
+ } else {
+ process.env[API_KEY] = savedApiKey;
+ }
+});
+
+describe("updateSubscriptionSeats", () => {
+ it("resizes the existing item by id instead of creating a second one", async () => {
+ respondWith(
+ subscription([
+ { id: "sitem_other", product_id: "prod_personal" },
+ { id: "sitem_team", product_id: "prod_team" },
+ ]),
+ );
+
+ await updateSubscriptionSeats({
+ subscriptionId: "sub_1",
+ productId: "prod_team",
+ units: 3,
+ });
+
+ const [read, write] = calls;
+ expect(read.url).toContain("subscription_id=sub_1");
+ expect(write.method).toBe("POST");
+ expect(write.url).toContain("/v1/subscriptions/sub_1");
+ expect(write.body).toEqual({
+ items: [{ id: "sitem_team", units: 3 }],
+ update_behavior: "proration-charge",
+ });
+ });
+
+ it("falls back to the only item when the stored product id is stale", async () => {
+ respondWith(
+ subscription([{ id: "sitem_upgraded", product_id: "prod_new" }]),
+ );
+
+ await updateSubscriptionSeats({
+ subscriptionId: "sub_1",
+ productId: "prod_old",
+ units: 4,
+ });
+
+ expect(calls[1].body).toEqual({
+ items: [{ id: "sitem_upgraded", units: 4 }],
+ update_behavior: "proration-charge",
+ });
+ });
+
+ it("refuses to guess when several items exist and none match", async () => {
+ respondWith(
+ subscription([
+ { id: "sitem_personal", product_id: "prod_personal" },
+ { id: "sitem_addon", product_id: "prod_addon" },
+ ]),
+ );
+
+ await expect(
+ updateSubscriptionSeats({
+ subscriptionId: "sub_1",
+ productId: "prod_old",
+ units: 4,
+ }),
+ ).rejects.toThrow("no item for product prod_old");
+
+ expect(calls).toHaveLength(1);
+ });
+
+ it("throws instead of reporting success when the subscription has no items", async () => {
+ respondWith(subscription([]));
+
+ await expect(
+ updateSubscriptionSeats({
+ subscriptionId: "sub_1",
+ productId: "prod_team",
+ units: 2,
+ }),
+ ).rejects.toThrow("no item for product prod_team");
+
+ expect(calls).toHaveLength(1);
+ });
+});