⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
test(billing): live-verify entitlement enforcement and seat sync
Andrej6813f3b34813
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.tsindex 1c5764b0e..487211735 100644--- a/apps/api/src/database/index.ts+++ b/apps/api/src/database/index.ts@@ -37,6 +37,7 @@ import {activityTable,apikeyTable,assetTable,+ billingEventTable,columnTable,commentTable,deviceCodeTable,@@ -59,6 +60,7 @@ import {userTable,verificationTable,workflowRuleTable,+ workspaceBillingTable,workspaceRoleTable,workspaceTable,workspaceUserTable,@@ -71,6 +73,8 @@ export const schema = {assetTable,activityTable,apikeyTable,+ billingEventTable,+ workspaceBillingTable,columnTable,commentTable,deviceCodeTable,diff --git a/tests/api-integration/billing-enforcement.test.ts b/tests/api-integration/billing-enforcement.test.tsnew file mode 100644index 000000000..9fadd3c46--- /dev/null+++ b/tests/api-integration/billing-enforcement.test.ts@@ -0,0 +1,136 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const CLOUD_ENV = {+ KANEO_CLOUD: "true",+ CREEM_API_KEY: "creem_test_dummy",+ CREEM_WEBHOOK_SECRET: "whsec_dummy",+};+const saved: Record<string, string | undefined> = {};++function createTask(+ app: ReturnType<typeof createApp>["app"],+ projectId: string,+) {+ return app.request(`/api/task/${projectId}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ title: "Billing gate task",+ description: "",+ priority: "low",+ status: "to-do",+ }),+ });+}++async function setBilling(+ workspaceId: string,+ values: Partial<typeof schema.workspaceBillingTable.$inferInsert>,+) {+ await db+ .insert(schema.workspaceBillingTable)+ .values({ workspaceId, ...values })+ .onConflictDoUpdate({+ target: schema.workspaceBillingTable.workspaceId,+ set: values,+ });+}++describe("API integration: billing enforcement", () => {+ beforeAll(() => {+ for (const [k, v] of Object.entries(CLOUD_ENV)) {+ saved[k] = process.env[k];+ process.env[k] = v;+ }+ });++ afterAll(() => {+ for (const k of Object.keys(CLOUD_ENV)) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ });++ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("blocks task creation with 402 when the trial has expired", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await setBilling(member.workspace.id, {+ foundingFree: false,+ trialEndsAt: new Date(Date.now() - 60_000),+ });++ mockAuthenticatedSession(member.user);+ const { app } = createApp();++ const response = await createTask(app, project.id);+ expect(response.status).toBe(402);+ });++ it("allows task creation during an active trial", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await setBilling(member.workspace.id, {+ foundingFree: false,+ trialEndsAt: new Date(Date.now() + 60_000),+ });++ mockAuthenticatedSession(member.user);+ const { app } = createApp();++ const response = await createTask(app, project.id);+ expect(response.status).toBe(200);+ });++ it("allows task creation for founding-free workspaces", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await setBilling(member.workspace.id, {+ foundingFree: true,+ trialEndsAt: new Date(Date.now() - 60_000),+ });++ mockAuthenticatedSession(member.user);+ const { app } = createApp();++ const response = await createTask(app, project.id);+ expect(response.status).toBe(200);+ });++ it("allows task creation with an active subscription", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await setBilling(member.workspace.id, {+ foundingFree: false,+ trialEndsAt: new Date(Date.now() - 60_000),+ status: "active",+ plan: "personal",+ creemSubscriptionId: `sub-${member.workspace.id}`,+ });++ mockAuthenticatedSession(member.user);+ const { app } = createApp();++ const response = await createTask(app, project.id);+ expect(response.status).toBe(200);+ });+});diff --git a/tests/api-integration/billing-seat-sync.test.ts b/tests/api-integration/billing-seat-sync.test.tsnew file mode 100644index 000000000..d4fc67c1b--- /dev/null+++ b/tests/api-integration/billing-seat-sync.test.ts@@ -0,0 +1,130 @@+import { eq } from "drizzle-orm";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++const { updateSubscriptionSeats } = vi.hoisted(() => ({+ updateSubscriptionSeats: vi.fn(async () => ({ ok: true as const })),+}));+vi.mock("../../apps/api/src/billing/creem-client", () => ({+ updateSubscriptionSeats,+ createCheckoutSession: vi.fn(),+ createCustomerPortalLink: vi.fn(),+}));++import { syncWorkspaceSeats } from "../../apps/api/src/billing/controllers/sync-seats";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++const CLOUD_ENV = {+ KANEO_CLOUD: "true",+ CREEM_API_KEY: "creem_test_dummy",+ CREEM_WEBHOOK_SECRET: "whsec_dummy",+};+const saved: Record<string, string | undefined> = {};++async function addMember(workspaceId: string) {+ const member = await createWorkspaceMember();+ await db.insert(schema.workspaceUserTable).values({+ workspaceId,+ userId: member.user.id,+ role: "member",+ joinedAt: new Date(),+ });+}++async function teamBilling(workspaceId: string, seats: number) {+ await db.insert(schema.workspaceBillingTable).values({+ workspaceId,+ plan: "team",+ status: "active",+ seats,+ creemSubscriptionId: `sub-${workspaceId}`,+ creemProductId: "prod_team_monthly",+ });+}++describe("API integration: seat sync", () => {+ beforeAll(() => {+ for (const [k, v] of Object.entries(CLOUD_ENV)) {+ saved[k] = process.env[k];+ process.env[k] = v;+ }+ });+ afterAll(() => {+ for (const k of Object.keys(CLOUD_ENV)) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ });+ beforeEach(async () => {+ await resetTestDatabase();+ updateSubscriptionSeats.mockClear();+ });++ it("updates Creem and persists the new seat count when members change", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ await teamBilling(owner.workspace.id, 1);+ await addMember(owner.workspace.id); // now 2 members++ await syncWorkspaceSeats(owner.workspace.id);++ expect(updateSubscriptionSeats).toHaveBeenCalledWith({+ subscriptionId: `sub-${owner.workspace.id}`,+ productId: "prod_team_monthly",+ units: 2,+ });+ const [row] = await db+ .select()+ .from(schema.workspaceBillingTable)+ .where(eq(schema.workspaceBillingTable.workspaceId, owner.workspace.id));+ expect(row.seats).toBe(2);+ });++ 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++ await syncWorkspaceSeats(owner.workspace.id);+ expect(updateSubscriptionSeats).not.toHaveBeenCalled();+ });++ it("skips personal plans", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ await db.insert(schema.workspaceBillingTable).values({+ workspaceId: owner.workspace.id,+ plan: "personal",+ status: "active",+ seats: 1,+ creemSubscriptionId: `sub-${owner.workspace.id}`,+ creemProductId: "prod_personal_monthly",+ });+ await addMember(owner.workspace.id);++ await syncWorkspaceSeats(owner.workspace.id);+ expect(updateSubscriptionSeats).not.toHaveBeenCalled();+ });++ it("skips workspaces without an active subscription", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ await db.insert(schema.workspaceBillingTable).values({+ workspaceId: owner.workspace.id,+ plan: "team",+ status: "canceled",+ seats: 1,+ creemSubscriptionId: `sub-${owner.workspace.id}`,+ creemProductId: "prod_team_monthly",+ });+ await addMember(owner.workspace.id);++ await syncWorkspaceSeats(owner.workspace.id);+ expect(updateSubscriptionSeats).not.toHaveBeenCalled();+ });+});