Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): use the shared Pro seat release for every seat removal path

Richie McIlroy9ef1f603e057
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 926bdcd44..cf1de49bc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -130,12 +130,14 @@ jobs:
__tests__/unit/embed-video-playback-chrome.test.ts
__tests__/unit/folder-videos.test.ts
__tests__/unit/homepage-demo-accessibility.test.ts
+ __tests__/unit/invite-decline.test.ts
__tests__/unit/linkified-text.test.ts
__tests__/unit/loom-import-ui.test.ts
__tests__/unit/media-format-converter-selection.test.ts
__tests__/unit/media-format-converter.test.ts
__tests__/unit/media-player-store-refs.test.ts
__tests__/unit/playback-store.test.ts
+ __tests__/unit/remove-organization-member.test.ts
__tests__/unit/seo-demo-videos.test.ts
__tests__/unit/signed-baa-card.test.ts
__tests__/unit/space-folder-page-access.test.ts
@@ -144,6 +146,7 @@ jobs:
__tests__/unit/speed-controller.test.ts
__tests__/unit/summary-editor.test.ts
__tests__/unit/sso-login-pages.test.ts
+ __tests__/unit/toggle-pro-seat.test.ts
__tests__/unit/transcript-numbers.test.ts
__tests__/unit/video-analytics-access.test.ts
diff --git a/apps/web/__tests__/unit/invite-decline.test.ts b/apps/web/__tests__/unit/invite-decline.test.ts
index 14ed03d80..df8274096 100644
--- a/apps/web/__tests__/unit/invite-decline.test.ts
+++ b/apps/web/__tests__/unit/invite-decline.test.ts
@@ -154,7 +154,7 @@ describe("POST /api/invite/decline", () => {
organizationId: "org-1",
},
]);
- mockDb.limit.mockResolvedValueOnce([]);
+ mockDb.limit.mockReturnValueOnce(mockDb);
const response = await POST(makeRequest({ inviteId: "invite-1" }));
diff --git a/apps/web/__tests__/unit/toggle-pro-seat.test.ts b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
new file mode 100644
index 000000000..8c2b1f72f
--- /dev/null
+++ b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
@@ -0,0 +1,236 @@
+import { userIsPro } from "@cap/utils";
+import { Organisation } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getCurrentUser: vi.fn(),
+ requireManager: vi.fn(),
+ selectResults: [] as unknown[][],
+ user: { thirdPartyStripeSubscriptionId: null as string | null },
+}));
+
+const tables = vi.hoisted(() => ({
+ organizationMembers: {
+ id: "memberId",
+ userId: "memberUserId",
+ organizationId: "memberOrgId",
+ hasProSeat: "hasProSeat",
+ },
+ organizations: { id: "orgId", ownerId: "ownerId" },
+ users: {
+ id: "userId",
+ inviteQuota: "inviteQuota",
+ stripeSubscriptionId: "subscriptionId",
+ stripeSubscriptionStatus: "subscriptionStatus",
+ thirdPartyStripeSubscriptionId: "thirdPartySubscriptionId",
+ },
+}));
+
+const lockRows = vi.fn();
+const updates: { table: unknown; value: Record<string, unknown> }[] = [];
+
+type SelectQuery = Promise<unknown[]> & {
+ from(): SelectQuery;
+ innerJoin(): SelectQuery;
+ where(): SelectQuery;
+ limit(): SelectQuery;
+ for(mode: string): SelectQuery;
+};
+
+function selectQuery() {
+ const query: SelectQuery = Object.assign(
+ Promise.resolve(mocks.selectResults.shift() ?? []),
+ {
+ from: () => query,
+ innerJoin: () => query,
+ where: () => query,
+ limit: () => query,
+ for: (mode: string) => {
+ lockRows(mode);
+ return query;
+ },
+ },
+ );
+ return query;
+}
+
+const database = {
+ select: vi.fn(selectQuery),
+ update: vi.fn((table: unknown) => ({
+ set: (value: Record<string, unknown>) => {
+ updates.push({ table, value });
+ if (table === tables.users && "thirdPartyStripeSubscriptionId" in value) {
+ mocks.user.thirdPartyStripeSubscriptionId =
+ (value.thirdPartyStripeSubscriptionId as string | null) ?? null;
+ }
+ return { where: async () => [{ affectedRows: 1 }] };
+ },
+ })),
+ transaction: vi.fn(async (fn: (tx: typeof database) => Promise<unknown>) =>
+ fn(database),
+ ),
+};
+
+vi.mock("@cap/database", () => ({ db: () => database }));
+vi.mock("@cap/env", () => ({ buildEnv: { NEXT_PUBLIC_IS_CAP: "true" } }));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+vi.mock("@cap/database/schema", () => tables);
+vi.mock("@/actions/organization/authorization", () => ({
+ requireOrganizationProSeatManager: mocks.requireManager,
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+const organizationId = Organisation.OrganisationId.make("org");
+
+async function toggle(enable: boolean) {
+ const { toggleProSeat } = await import(
+ "@/actions/organization/toggle-pro-seat"
+ );
+ return toggleProSeat("member", organizationId, enable);
+}
+
+async function turnSeatOff(
+ remainingSeats: { stripeSubscriptionId: string | null }[],
+) {
+ mocks.selectResults = [
+ [{ id: "member", userId: "teammate", hasProSeat: true }],
+ remainingSeats,
+ ];
+ await toggle(false);
+}
+
+function memberIsPro() {
+ return userIsPro({ stripeSubscriptionStatus: null, ...mocks.user });
+}
+
+describe("toggleProSeat", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updates.length = 0;
+ mocks.selectResults = [];
+ mocks.user.thirdPartyStripeSubscriptionId = "sub_this_org";
+ mocks.getCurrentUser.mockResolvedValue({ id: "owner" });
+ mocks.requireManager.mockResolvedValue({ ownerId: "owner", role: "owner" });
+ });
+
+ describe("turning a seat off", () => {
+ it("clears Pro when the user has no other seat", async () => {
+ await turnSeatOff([]);
+
+ expect(updates[0]).toEqual({
+ table: tables.organizationMembers,
+ value: { hasProSeat: false },
+ });
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBeNull();
+ expect(memberIsPro()).toBe(false);
+ });
+
+ it("keeps Pro when a manager-sponsored seat remains", async () => {
+ await turnSeatOff([{ stripeSubscriptionId: null }]);
+
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_this_org");
+ expect(memberIsPro()).toBe(true);
+ });
+
+ it("moves Pro onto a remaining seat the organization owner pays for", async () => {
+ await turnSeatOff([{ stripeSubscriptionId: "sub_other" }]);
+
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
+ expect(memberIsPro()).toBe(true);
+ });
+
+ it("prefers a paid seat when sponsored and paid seats both remain", async () => {
+ await turnSeatOff([
+ { stripeSubscriptionId: null },
+ { stripeSubscriptionId: "sub_other" },
+ ]);
+
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
+ expect(memberIsPro()).toBe(true);
+ });
+
+ it("locks the member and the remaining seats inside the transaction", async () => {
+ await turnSeatOff([{ stripeSubscriptionId: "sub_other" }]);
+
+ expect(database.transaction).toHaveBeenCalledTimes(1);
+ expect(database.select).toHaveBeenCalledTimes(2);
+ expect(lockRows).toHaveBeenCalledTimes(2);
+ expect(lockRows).toHaveBeenNthCalledWith(1, "update");
+ expect(lockRows).toHaveBeenNthCalledWith(2, "update");
+ });
+
+ it("does nothing when the seat is already off", async () => {
+ mocks.selectResults = [
+ [{ id: "member", userId: "teammate", hasProSeat: false }],
+ ];
+
+ await toggle(false);
+
+ expect(updates).toEqual([]);
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_this_org");
+ });
+ });
+
+ describe("turning a seat on", () => {
+ const owner = {
+ id: "owner",
+ inviteQuota: 3,
+ stripeSubscriptionId: "sub_owner",
+ stripeSubscriptionStatus: "active",
+ };
+ const members = [
+ { id: "owner-member", userId: "owner", hasProSeat: false },
+ { id: "member", userId: "teammate", hasProSeat: false },
+ ];
+
+ it("assigns the seat and points Pro at the seat provider", async () => {
+ mocks.user.thirdPartyStripeSubscriptionId = null;
+ mocks.selectResults = [
+ [{ id: "member", userId: "teammate", hasProSeat: false }],
+ members,
+ [owner],
+ ];
+
+ await toggle(true);
+
+ expect(updates).toEqual([
+ { table: tables.organizationMembers, value: { hasProSeat: true } },
+ {
+ table: tables.users,
+ value: { thirdPartyStripeSubscriptionId: "sub_owner" },
+ },
+ ]);
+ expect(database.select).toHaveBeenCalledTimes(3);
+ expect(lockRows).toHaveBeenCalledTimes(2);
+ expect(memberIsPro()).toBe(true);
+ });
+
+ it("refuses when no Pro seats remain", async () => {
+ mocks.user.thirdPartyStripeSubscriptionId = null;
+ mocks.selectResults = [
+ [{ id: "member", userId: "teammate", hasProSeat: false }],
+ members,
+ [{ ...owner, inviteQuota: 1 }],
+ ];
+
+ await expect(toggle(true)).rejects.toThrow("No Pro seats remaining");
+ expect(updates).toEqual([]);
+ });
+
+ it("refuses without an active subscription to sponsor the seat", async () => {
+ mocks.user.thirdPartyStripeSubscriptionId = null;
+ mocks.selectResults = [
+ [{ id: "member", userId: "teammate", hasProSeat: false }],
+ members,
+ [{ ...owner, stripeSubscriptionStatus: "canceled" }],
+ ];
+
+ await expect(toggle(true)).rejects.toThrow(
+ "An active Cap Pro subscription is required",
+ );
+ expect(updates).toEqual([]);
+ });
+ });
+});
diff --git a/apps/web/actions/organization/remove-member.ts b/apps/web/actions/organization/remove-member.ts
index 01718237f..c08d15ab0 100644
--- a/apps/web/actions/organization/remove-member.ts
+++ b/apps/web/actions/organization/remove-member.ts
@@ -2,6 +2,7 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
+import { releaseProSeatSubscription } from "@cap/database/pro-seat-subscription";
import {
organizationInvites,
organizationMembers,
@@ -16,7 +17,6 @@ import {
canRemoveOrganizationMember,
getEffectiveOrganizationRole,
} from "@/lib/permissions/roles";
-import { releaseProSeatSubscription } from "@/lib/pro-seat-subscription";
import { requireOrganizationSettingsManager } from "./authorization";
export async function removeOrganizationMember(
diff --git a/apps/web/actions/organization/toggle-pro-seat.ts b/apps/web/actions/organization/toggle-pro-seat.ts
index aaaf8762f..8e2131785 100644
--- a/apps/web/actions/organization/toggle-pro-seat.ts
+++ b/apps/web/actions/organization/toggle-pro-seat.ts
@@ -2,11 +2,8 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
-import {
- organizationMembers,
- organizations,
- users,
-} from "@cap/database/schema";
+import { releaseProSeatSubscription } from "@cap/database/pro-seat-subscription";
+import { organizationMembers, users } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
@@ -122,53 +119,7 @@ export async function toggleProSeat(
.set({ hasProSeat: false })
.where(eq(organizationMembers.id, memberId));
- const otherProSeats = await tx
- .select({ id: organizationMembers.id })
- .from(organizationMembers)
- .where(
- and(
- eq(organizationMembers.userId, member.userId),
- eq(organizationMembers.hasProSeat, true),
- ),
- )
- .limit(1);
-
- if (otherProSeats.length === 0) {
- await tx
- .update(users)
- .set({ thirdPartyStripeSubscriptionId: null })
- .where(eq(users.id, member.userId));
- } else {
- const [remainingOrg] = await tx
- .select({ stripeSubscriptionId: users.stripeSubscriptionId })
- .from(organizationMembers)
- .innerJoin(
- organizations,
- eq(organizationMembers.organizationId, organizations.id),
- )
- .innerJoin(users, eq(organizations.ownerId, users.id))
- .where(
- and(
- eq(organizationMembers.userId, member.userId),
- eq(organizationMembers.hasProSeat, true),
- ),
- )
- .limit(1);
-
- if (remainingOrg?.stripeSubscriptionId) {
- await tx
- .update(users)
- .set({
- thirdPartyStripeSubscriptionId: remainingOrg.stripeSubscriptionId,
- })
- .where(eq(users.id, member.userId));
- } else {
- await tx
- .update(users)
- .set({ thirdPartyStripeSubscriptionId: null })
- .where(eq(users.id, member.userId));
- }
- }
+ await releaseProSeatSubscription(tx, member.userId);
}
});
diff --git a/apps/web/app/api/invite/decline/route.ts b/apps/web/app/api/invite/decline/route.ts
index 7aad9a133..1cc09e947 100644
--- a/apps/web/app/api/invite/decline/route.ts
+++ b/apps/web/app/api/invite/decline/route.ts
@@ -1,6 +1,7 @@
import { db } from "@cap/database";
import { isCrossSiteCookieWrite } from "@cap/database/auth/request-site";
import { getCurrentUser } from "@cap/database/auth/session";
+import { releaseProSeatSubscription } from "@cap/database/pro-seat-subscription";
import {
organizationInvites,
organizationMembers,
@@ -60,7 +61,8 @@ export async function POST(request: NextRequest) {
eq(organizationMembers.userId, user.id),
),
)
- .limit(1);
+ .limit(1)
+ .for("update");
if (membership) {
const organizationSpaces = await tx
@@ -100,20 +102,7 @@ export async function POST(request: NextRequest) {
userUpdate.defaultOrgId = remainingMembership?.organizationId ?? null;
}
if (membership.hasProSeat) {
- const [otherProSeat] = await tx
- .select({ id: organizationMembers.id })
- .from(organizationMembers)
- .where(
- and(
- eq(organizationMembers.userId, user.id),
- eq(organizationMembers.hasProSeat, true),
- ),
- )
- .limit(1);
-
- if (!otherProSeat) {
- userUpdate.thirdPartyStripeSubscriptionId = null;
- }
+ await releaseProSeatSubscription(tx, user.id);
}
if (Object.keys(userUpdate).length > 0) {
diff --git a/apps/web/app/api/v1/[...route]/route.ts b/apps/web/app/api/v1/[...route]/route.ts
index 8303a9bde..33be6b8ff 100644
--- a/apps/web/app/api/v1/[...route]/route.ts
+++ b/apps/web/app/api/v1/[...route]/route.ts
@@ -9,6 +9,7 @@ import {
import { sendEmail } from "@cap/database/emails/config";
import { OrganizationInvite } from "@cap/database/emails/organization-invite";
import { nanoId, nanoIdLong } from "@cap/database/helpers";
+import { releaseProSeatSubscription } from "@cap/database/pro-seat-subscription";
import * as Db from "@cap/database/schema";
import { getNewVideoPublic } from "@cap/database/video-sharing-default";
import { buildEnv, serverEnv } from "@cap/env";
@@ -125,7 +126,6 @@ import {
getEffectiveOrganizationRole,
} from "@/lib/permissions/roles";
import { normalizePlaybackSpeed } from "@/lib/playback-speed";
-import { releaseProSeatSubscription } from "@/lib/pro-seat-subscription";
import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";
import {
blockedS3EndpointMessage,
@@ -5209,53 +5209,7 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(
.update(Db.organizationMembers)
.set({ hasProSeat: false })
.where(eq(Db.organizationMembers.id, path.memberId));
- const otherProSeats = await tx
- .select({ id: Db.organizationMembers.id })
- .from(Db.organizationMembers)
- .where(
- and(
- eq(Db.organizationMembers.userId, member.userId),
- eq(Db.organizationMembers.hasProSeat, true),
- ),
- )
- .limit(1);
- if (otherProSeats.length === 0) {
- await tx
- .update(Db.users)
- .set({ thirdPartyStripeSubscriptionId: null })
- .where(eq(Db.users.id, member.userId));
- } else {
- const [remainingOrganization] = await tx
- .select({
- stripeSubscriptionId: Db.users.stripeSubscriptionId,
- })
- .from(Db.organizationMembers)
- .innerJoin(
- Db.organizations,
- eq(
- Db.organizationMembers.organizationId,
- Db.organizations.id,
- ),
- )
- .innerJoin(
- Db.users,
- eq(Db.organizations.ownerId, Db.users.id),
- )
- .where(
- and(
- eq(Db.organizationMembers.userId, member.userId),
- eq(Db.organizationMembers.hasProSeat, true),
- ),
- )
- .limit(1);
- await tx
- .update(Db.users)
- .set({
- thirdPartyStripeSubscriptionId:
- remainingOrganization?.stripeSubscriptionId ?? null,
- })
- .where(eq(Db.users.id, member.userId));
- }
+ await releaseProSeatSubscription(tx, member.userId);
}
const now = new Date();
return {
diff --git a/packages/database/package.json b/packages/database/package.json
index 45a780af1..8367c114e 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -66,6 +66,7 @@
"./auth/sso-state": "./auth/sso-state.ts",
"./schema": "./schema.ts",
"./video-sharing-default": "./video-sharing-default.ts",
+ "./pro-seat-subscription": "./pro-seat-subscription.ts",
"./loops/*": "./loops/*.ts",
"./crypto": "./crypto.ts",
"./helpers": "./helpers.ts",
diff --git a/apps/web/lib/pro-seat-subscription.ts b/packages/database/pro-seat-subscription.ts
similarity index 89%
rename from apps/web/lib/pro-seat-subscription.ts
rename to packages/database/pro-seat-subscription.ts
index d913f6656..1080f201f 100644
--- a/apps/web/lib/pro-seat-subscription.ts
+++ b/packages/database/pro-seat-subscription.ts
@@ -1,11 +1,7 @@
-import type { db } from "@cap/database";
-import {
- organizationMembers,
- organizations,
- users,
-} from "@cap/database/schema";
import type { User } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
+import type { db } from "./index.ts";
+import { organizationMembers, organizations, users } from "./schema.ts";
type Transaction = Parameters<
Parameters<ReturnType<typeof db>["transaction"]>[0]
@@ -30,7 +26,8 @@ export async function releaseProSeatSubscription(
eq(organizationMembers.userId, userId),
eq(organizationMembers.hasProSeat, true),
),
- );
+ )
+ .for("update");
const paidSeat = remainingSeats.find((seat) => seat.stripeSubscriptionId);
if (!paidSeat && remainingSeats.length > 0) return;
diff --git a/packages/web-backend/src/Organisations/index.ts b/packages/web-backend/src/Organisations/index.ts
index 55bf96d66..cbe5d1826 100644
--- a/packages/web-backend/src/Organisations/index.ts
+++ b/packages/web-backend/src/Organisations/index.ts
@@ -1,3 +1,4 @@
+import { releaseProSeatSubscription } from "@cap/database/pro-seat-subscription";
import * as Db from "@cap/database/schema";
import { CurrentUser, Organisation, Policy } from "@cap/web-domain";
import * as Dz from "drizzle-orm";
@@ -162,9 +163,13 @@ export class Organisations extends Effect.Service<Organisations>()(
.from(Db.spaces)
.where(Dz.eq(Db.spaces.organizationId, id));
const memberRows = await tx
- .select({ userId: Db.organizationMembers.userId })
+ .select({
+ userId: Db.organizationMembers.userId,
+ hasProSeat: Db.organizationMembers.hasProSeat,
+ })
.from(Db.organizationMembers)
- .where(Dz.eq(Db.organizationMembers.organizationId, id));
+ .where(Dz.eq(Db.organizationMembers.organizationId, id))
+ .for("update");
const integrationRows = await tx
.select({ id: Db.storageIntegrations.id })
.from(Db.storageIntegrations)
@@ -265,6 +270,12 @@ export class Organisations extends Effect.Service<Organisations>()(
.delete(Db.organizations)
.where(Dz.eq(Db.organizations.id, id));
+ for (const member of memberRows) {
+ if (member.hasProSeat) {
+ await releaseProSeatSubscription(tx, member.userId);
+ }
+ }
+
for (const affectedUserId of affectedUserIds) {
const [otherOrg] = await tx
.select({ id: Db.organizations.id })