Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): revoke Pro access when removing the last organization seat

Aditya Garud0b1421d397fb
diff --git a/apps/web/__tests__/unit/remove-organization-member.test.ts b/apps/web/__tests__/unit/remove-organization-member.test.ts
new file mode 100644
index 000000000..69692e866
--- /dev/null
+++ b/apps/web/__tests__/unit/remove-organization-member.test.ts
@@ -0,0 +1,131 @@
+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: "sub_owner" as string | null },
+}));
+
+const tables = {
+ organizationMembers: {
+ id: "memberId",
+ userId: "memberUserId",
+ organizationId: "memberOrgId",
+ role: "role",
+ hasProSeat: "hasProSeat",
+ },
+ organizationInvites: { organizationId: "inviteOrgId", invitedEmail: "email" },
+ spaceMembers: { userId: "spaceUserId", spaceId: "spaceId" },
+ spaces: { id: "spaceId", organizationId: "spaceOrgId" },
+ organizations: { id: "orgId", ownerId: "ownerId" },
+ users: {
+ id: "userId",
+ email: "email",
+ stripeSubscriptionId: "subscriptionId",
+ },
+};
+
+function selectQuery() {
+ const query = {
+ from: (table: unknown) =>
+ table === tables.spaces
+ ? { where: async () => mocks.selectResults.shift() ?? [] }
+ : query,
+ innerJoin: () => query,
+ where: () => query,
+ limit: async () => mocks.selectResults.shift() ?? [],
+ };
+ return query;
+}
+
+const updateSet = vi.fn(
+ (value: { thirdPartyStripeSubscriptionId?: string | null }) => {
+ if ("thirdPartyStripeSubscriptionId" in value) {
+ mocks.user.thirdPartyStripeSubscriptionId =
+ value.thirdPartyStripeSubscriptionId ?? null;
+ }
+ return { where: async () => [{ affectedRows: 1 }] };
+ },
+);
+
+const database = {
+ select: vi.fn(selectQuery),
+ delete: vi.fn(() => ({ where: async () => [{ affectedRows: 1 }] })),
+ update: vi.fn(() => ({ set: updateSet })),
+ 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", () => ({
+ requireOrganizationSettingsManager: mocks.requireManager,
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+async function removeSeat(
+ remainingSeat: { stripeSubscriptionId: string | null } | null,
+) {
+ mocks.selectResults = [
+ [
+ {
+ id: "member",
+ userId: "teammate",
+ role: "member",
+ email: "[email protected]",
+ hasProSeat: true,
+ },
+ ],
+ [],
+ remainingSeat ? [remainingSeat] : [],
+ ];
+ const { removeOrganizationMember } = await import(
+ "@/actions/organization/remove-member"
+ );
+ await removeOrganizationMember(
+ "member",
+ Organisation.OrganisationId.make("org"),
+ );
+}
+
+describe("removeOrganizationMember", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.user.thirdPartyStripeSubscriptionId = "sub_owner";
+ mocks.getCurrentUser.mockResolvedValue({ id: "owner" });
+ mocks.requireManager.mockResolvedValue({ ownerId: "owner", role: "owner" });
+ });
+
+ it("revokes Pro access when the removed seat was the user's last seat", async () => {
+ await removeSeat(null);
+
+ expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
+ false,
+ );
+ });
+
+ it("keeps Pro access through another organization's seat", async () => {
+ await removeSeat({ stripeSubscriptionId: "sub_other" });
+
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
+ expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
+ true,
+ );
+ });
+
+ it("keeps Pro access when another seat is sponsored by a manager", async () => {
+ await removeSeat({ stripeSubscriptionId: null });
+
+ expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
+ true,
+ );
+ });
+});
diff --git a/apps/web/actions/organization/remove-member.ts b/apps/web/actions/organization/remove-member.ts
index 8b42405b5..c182922e7 100644
--- a/apps/web/actions/organization/remove-member.ts
+++ b/apps/web/actions/organization/remove-member.ts
@@ -5,6 +5,7 @@ import { getCurrentUser } from "@cap/database/auth/session";
import {
organizationInvites,
organizationMembers,
+ organizations,
spaceMembers,
spaces,
users,
@@ -35,6 +36,7 @@ export async function removeOrganizationMember(
id: organizationMembers.id,
userId: organizationMembers.userId,
role: organizationMembers.role,
+ hasProSeat: organizationMembers.hasProSeat,
email: users.email,
})
.from(organizationMembers)
@@ -106,6 +108,34 @@ export async function removeOrganizationMember(
);
if (result.affectedRows === 0) throw new Error("Member not found");
+
+ if (member.hasProSeat) {
+ 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 || remainingOrg.stripeSubscriptionId) {
+ await tx
+ .update(users)
+ .set({
+ thirdPartyStripeSubscriptionId:
+ remainingOrg?.stripeSubscriptionId ?? null,
+ })
+ .where(eq(users.id, member.userId));
+ }
+ }
});
revalidatePath("/dashboard/settings/organization");
diff --git a/apps/web/app/api/v1/[...route]/route.ts b/apps/web/app/api/v1/[...route]/route.ts
index 70cbf08f5..0b3752937 100644
--- a/apps/web/app/api/v1/[...route]/route.ts
+++ b/apps/web/app/api/v1/[...route]/route.ts
@@ -5301,6 +5301,7 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(
.select({
userId: Db.organizationMembers.userId,
role: Db.organizationMembers.role,
+ hasProSeat: Db.organizationMembers.hasProSeat,
email: Db.users.email,
})
.from(Db.organizationMembers)
@@ -5374,6 +5375,40 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(
),
);
if (affectedRows(result) === 0) return { state: "not_found" };
+ if (member.hasProSeat) {
+ const [remainingOrg] = 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);
+ if (!remainingOrg || remainingOrg.stripeSubscriptionId) {
+ await tx
+ .update(Db.users)
+ .set({
+ thirdPartyStripeSubscriptionId:
+ remainingOrg?.stripeSubscriptionId ?? null,
+ })
+ .where(eq(Db.users.id, member.userId));
+ }
+ }
const now = new Date();
return {
state: "success",