Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): lock the removed member and prefer a paid remaining seat

Aditya Garud503194a41817
diff --git a/apps/web/__tests__/unit/remove-organization-member.test.ts b/apps/web/__tests__/unit/remove-organization-member.test.ts
index 69692e866..f5b52345d 100644
--- a/apps/web/__tests__/unit/remove-organization-member.test.ts
+++ b/apps/web/__tests__/unit/remove-organization-member.test.ts
@@ -28,16 +28,30 @@ const tables = {
},
};
+const lockRows = vi.fn();
+
+type SelectQuery = Promise<unknown[]> & {
+ from(): SelectQuery;
+ innerJoin(): SelectQuery;
+ where(): SelectQuery;
+ limit(): SelectQuery;
+ for(mode: string): SelectQuery;
+};
+
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() ?? [],
- };
+ 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;
}
@@ -72,7 +86,7 @@ vi.mock("@/actions/organization/authorization", () => ({
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
async function removeSeat(
- remainingSeat: { stripeSubscriptionId: string | null } | null,
+ remainingSeats: { stripeSubscriptionId: string | null }[],
) {
mocks.selectResults = [
[
@@ -85,7 +99,7 @@ async function removeSeat(
},
],
[],
- remainingSeat ? [remainingSeat] : [],
+ remainingSeats,
];
const { removeOrganizationMember } = await import(
"@/actions/organization/remove-member"
@@ -105,15 +119,16 @@ describe("removeOrganizationMember", () => {
});
it("revokes Pro access when the removed seat was the user's last seat", async () => {
- await removeSeat(null);
+ await removeSeat([]);
+ expect(lockRows).toHaveBeenCalledWith("update");
expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
false,
);
});
it("keeps Pro access through another organization's seat", async () => {
- await removeSeat({ stripeSubscriptionId: "sub_other" });
+ await removeSeat([{ stripeSubscriptionId: "sub_other" }]);
expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
@@ -122,10 +137,19 @@ describe("removeOrganizationMember", () => {
});
it("keeps Pro access when another seat is sponsored by a manager", async () => {
- await removeSeat({ stripeSubscriptionId: null });
+ await removeSeat([{ stripeSubscriptionId: null }]);
expect(userIsPro({ stripeSubscriptionStatus: null, ...mocks.user })).toBe(
true,
);
});
+
+ it("prefers a remaining seat the organization owner pays for", async () => {
+ await removeSeat([
+ { stripeSubscriptionId: null },
+ { stripeSubscriptionId: "sub_other" },
+ ]);
+
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
+ });
});
diff --git a/apps/web/actions/organization/remove-member.ts b/apps/web/actions/organization/remove-member.ts
index c182922e7..01718237f 100644
--- a/apps/web/actions/organization/remove-member.ts
+++ b/apps/web/actions/organization/remove-member.ts
@@ -5,7 +5,6 @@ import { getCurrentUser } from "@cap/database/auth/session";
import {
organizationInvites,
organizationMembers,
- organizations,
spaceMembers,
spaces,
users,
@@ -17,6 +16,7 @@ import {
canRemoveOrganizationMember,
getEffectiveOrganizationRole,
} from "@/lib/permissions/roles";
+import { releaseProSeatSubscription } from "@/lib/pro-seat-subscription";
import { requireOrganizationSettingsManager } from "./authorization";
export async function removeOrganizationMember(
@@ -31,47 +31,48 @@ export async function removeOrganizationMember(
organizationId,
);
- const [member] = await db()
- .select({
- id: organizationMembers.id,
- userId: organizationMembers.userId,
- role: organizationMembers.role,
- hasProSeat: organizationMembers.hasProSeat,
- email: users.email,
- })
- .from(organizationMembers)
- .innerJoin(users, eq(organizationMembers.userId, users.id))
- .where(
- and(
- eq(organizationMembers.id, memberId),
- eq(organizationMembers.organizationId, organizationId),
- ),
- )
- .limit(1);
-
- if (!member) {
- throw new Error("Member not found");
- }
+ await db().transaction(async (tx) => {
+ const [member] = await tx
+ .select({
+ id: organizationMembers.id,
+ userId: organizationMembers.userId,
+ role: organizationMembers.role,
+ hasProSeat: organizationMembers.hasProSeat,
+ email: users.email,
+ })
+ .from(organizationMembers)
+ .innerJoin(users, eq(organizationMembers.userId, users.id))
+ .where(
+ and(
+ eq(organizationMembers.id, memberId),
+ eq(organizationMembers.organizationId, organizationId),
+ ),
+ )
+ .limit(1)
+ .for("update");
- const targetRole = getEffectiveOrganizationRole({
- userId: member.userId,
- ownerId: actor.ownerId,
- memberRole: member.role,
- });
+ if (!member) {
+ throw new Error("Member not found");
+ }
- if (
- !canRemoveOrganizationMember({
- actorRole: actor.role,
- actorUserId: user.id,
- targetUserId: member.userId,
+ const targetRole = getEffectiveOrganizationRole({
+ userId: member.userId,
ownerId: actor.ownerId,
- targetRole,
- })
- ) {
- throw new Error("You do not have permission to remove this member");
- }
+ memberRole: member.role,
+ });
+
+ if (
+ !canRemoveOrganizationMember({
+ actorRole: actor.role,
+ actorUserId: user.id,
+ targetUserId: member.userId,
+ ownerId: actor.ownerId,
+ targetRole,
+ })
+ ) {
+ throw new Error("You do not have permission to remove this member");
+ }
- await db().transaction(async (tx) => {
const organizationSpaces = await tx
.select({ id: spaces.id })
.from(spaces)
@@ -110,31 +111,7 @@ 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));
- }
+ await releaseProSeatSubscription(tx, member.userId);
}
});
diff --git a/apps/web/app/api/v1/[...route]/route.ts b/apps/web/app/api/v1/[...route]/route.ts
index 0b3752937..cca4e6f02 100644
--- a/apps/web/app/api/v1/[...route]/route.ts
+++ b/apps/web/app/api/v1/[...route]/route.ts
@@ -125,6 +125,7 @@ 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,
@@ -5376,38 +5377,7 @@ 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));
- }
+ await releaseProSeatSubscription(tx, member.userId);
}
const now = new Date();
return {
diff --git a/apps/web/lib/pro-seat-subscription.ts b/apps/web/lib/pro-seat-subscription.ts
new file mode 100644
index 000000000..d913f6656
--- /dev/null
+++ b/apps/web/lib/pro-seat-subscription.ts
@@ -0,0 +1,43 @@
+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";
+
+type Transaction = Parameters<
+ Parameters<ReturnType<typeof db>["transaction"]>[0]
+>[0];
+
+// Call after a member's Pro seat row is gone. Seats don't record who sponsored
+// them, so when only manager-sponsored seats remain the current pointer stays.
+export async function releaseProSeatSubscription(
+ tx: Transaction,
+ userId: User.UserId,
+) {
+ const remainingSeats = 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, userId),
+ eq(organizationMembers.hasProSeat, true),
+ ),
+ );
+ const paidSeat = remainingSeats.find((seat) => seat.stripeSubscriptionId);
+ if (!paidSeat && remainingSeats.length > 0) return;
+
+ await tx
+ .update(users)
+ .set({
+ thirdPartyStripeSubscriptionId: paidSeat?.stripeSubscriptionId ?? null,
+ })
+ .where(eq(users.id, userId));
+}