⚡ 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
fix(billing): grant the trial once per owner, not per workspace
Andrej14adb9dfd8af
diff --git a/apps/api/src/billing/controllers/get-workspace-billing.ts b/apps/api/src/billing/controllers/get-workspace-billing.tsindex d340f763a..d03b8a6c1 100644--- a/apps/api/src/billing/controllers/get-workspace-billing.ts+++ b/apps/api/src/billing/controllers/get-workspace-billing.ts@@ -1,7 +1,11 @@-import { eq } from "drizzle-orm";+import { and, eq, isNotNull, min } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { workspaceBillingTable, workspaceTable } from "../../database/schema";+import {+ workspaceBillingTable,+ workspaceTable,+ workspaceUserTable,+} from "../../database/schema";import { foundingCutoff, isBillingEnabled, trialDays } from "../config";const ACTIVE_STATUSES = new Set([@@ -11,6 +15,44 @@ const ACTIVE_STATUSES = new Set(["scheduled_cancel",]);+export async function resolveTrialEndsAt(+ workspaceId: string,+): Promise<Date | null> {+ const [owner] = await db+ .select({ userId: workspaceUserTable.userId })+ .from(workspaceUserTable)+ .where(+ and(+ eq(workspaceUserTable.workspaceId, workspaceId),+ eq(workspaceUserTable.role, "owner"),+ ),+ )+ .limit(1);++ if (owner) {+ const [earlier] = await db+ .select({ trialEndsAt: min(workspaceBillingTable.trialEndsAt) })+ .from(workspaceBillingTable)+ .innerJoin(+ workspaceUserTable,+ eq(workspaceUserTable.workspaceId, workspaceBillingTable.workspaceId),+ )+ .where(+ and(+ eq(workspaceUserTable.userId, owner.userId),+ eq(workspaceUserTable.role, "owner"),+ isNotNull(workspaceBillingTable.trialEndsAt),+ ),+ );++ if (earlier?.trialEndsAt) {+ return new Date(earlier.trialEndsAt);+ }+ }++ return new Date(Date.now() + trialDays() * 24 * 60 * 60 * 1000);+}+export async function getOrCreateWorkspaceBilling(workspaceId: string) {const [existing] = await db.select()@@ -31,9 +73,7 @@ export async function getOrCreateWorkspaceBilling(workspaceId: string) {const cutoff = foundingCutoff();const isFounding = cutoff !== null && workspace.createdAt <= cutoff;- const trialEndsAt = isFounding- ? null- : new Date(Date.now() + trialDays() * 24 * 60 * 60 * 1000);+ const trialEndsAt = isFounding ? null : await resolveTrialEndsAt(workspaceId);const [created] = await db.insert(workspaceBillingTable)diff --git a/tests/api-integration/billing-trial-per-user.test.ts b/tests/api-integration/billing-trial-per-user.test.tsnew file mode 100644index 000000000..7f9001209--- /dev/null+++ b/tests/api-integration/billing-trial-per-user.test.ts@@ -0,0 +1,110 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import { getOrCreateWorkspaceBilling } from "../../apps/api/src/billing/controllers/get-workspace-billing";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++const DAY = 24 * 60 * 60 * 1000;++async function addWorkspaceOwnedBy(userId: string) {+ const workspaceId = `workspace-${randomUUID()}`;+ const [workspace] = await db+ .insert(schema.workspaceTable)+ .values({+ id: workspaceId,+ createdAt: new Date(),+ name: "Extra Workspace",+ slug: `workspace-${randomUUID()}`,+ })+ .returning();++ await db.insert(schema.workspaceUserTable).values({+ workspaceId: workspace.id,+ userId,+ role: "owner",+ joinedAt: new Date(),+ });++ return workspace;+}++describe("trial is granted once per owner", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("gives a first workspace a full trial", async () => {+ const { workspace } = await createWorkspaceMember({ role: "owner" });++ const billing = await getOrCreateWorkspaceBilling(workspace.id);++ expect(billing.trialEndsAt).not.toBeNull();+ const remaining = (billing.trialEndsAt as Date).getTime() - Date.now();+ expect(remaining).toBeGreaterThan(13 * DAY);+ expect(remaining).toBeLessThanOrEqual(14 * DAY);+ });++ it("does not extend the trial when the owner makes another workspace", async () => {+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });+ const first = await getOrCreateWorkspaceBilling(workspace.id);++ const second = await addWorkspaceOwnedBy(user.id);+ const secondBilling = await getOrCreateWorkspaceBilling(second.id);++ expect(secondBilling.trialEndsAt?.getTime()).toBe(+ first.trialEndsAt?.getTime(),+ );+ });++ it("starts a later workspace unentitled once the owner's trial has lapsed", async () => {+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });+ await getOrCreateWorkspaceBilling(workspace.id);++ const lapsed = new Date(Date.now() - DAY);+ await db+ .update(schema.workspaceBillingTable)+ .set({ trialEndsAt: lapsed })+ .where(eq(schema.workspaceBillingTable.workspaceId, workspace.id));++ const second = await addWorkspaceOwnedBy(user.id);+ const secondBilling = await getOrCreateWorkspaceBilling(second.id);++ expect(secondBilling.trialEndsAt?.getTime()).toBe(lapsed.getTime());+ expect(secondBilling.trialEndsAt?.getTime()).toBeLessThan(Date.now());+ });++ it("keeps trials separate for different owners", async () => {+ const { workspace: aWorkspace } = await createWorkspaceMember({+ role: "owner",+ });+ await db+ .insert(schema.workspaceBillingTable)+ .values({+ workspaceId: aWorkspace.id,+ trialEndsAt: new Date(Date.now() - DAY),+ })+ .onConflictDoNothing();++ const { workspace: bWorkspace } = await createWorkspaceMember({+ role: "owner",+ });+ const bBilling = await getOrCreateWorkspaceBilling(bWorkspace.id);++ expect(bBilling.trialEndsAt?.getTime()).toBeGreaterThan(Date.now());+ });++ it("leaves an existing billing row untouched", async () => {+ const { workspace } = await createWorkspaceMember({ role: "owner" });+ const pinned = new Date(Date.now() + 99 * DAY);+ await db+ .insert(schema.workspaceBillingTable)+ .values({ workspaceId: workspace.id, trialEndsAt: pinned })+ .onConflictDoNothing();++ const billing = await getOrCreateWorkspaceBilling(workspace.id);++ expect(billing.trialEndsAt?.getTime()).toBe(pinned.getTime());+ });+});