Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): serialize Pro seat releases on the user row and test invite decline

Richie McIlroy6233664b608f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cf1de49bc..a442fb39f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -130,6 +130,7 @@ 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-pro-seat.test.ts
__tests__/unit/invite-decline.test.ts
__tests__/unit/linkified-text.test.ts
__tests__/unit/loom-import-ui.test.ts
diff --git a/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts b/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts
new file mode 100644
index 000000000..788d0dfc6
--- /dev/null
+++ b/apps/web/__tests__/unit/invite-decline-pro-seat.test.ts
@@ -0,0 +1,182 @@
+import { userIsPro } from "@cap/utils";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getCurrentUser: vi.fn(),
+ selectResults: [] as unknown[][],
+ user: { thirdPartyStripeSubscriptionId: null as string | null },
+}));
+
+const tables = vi.hoisted(() => ({
+ organizationInvites: {
+ id: "inviteId",
+ invitedEmail: "invitedEmail",
+ organizationId: "inviteOrgId",
+ },
+ organizationMembers: {
+ id: "memberId",
+ userId: "memberUserId",
+ organizationId: "memberOrgId",
+ hasProSeat: "hasProSeat",
+ },
+ organizations: { id: "orgId", ownerId: "ownerId" },
+ spaceMembers: { userId: "spaceUserId", spaceId: "spaceId" },
+ spaces: { id: "spaceId", organizationId: "spaceOrgId" },
+ users: {
+ id: "userId",
+ stripeSubscriptionId: "subscriptionId",
+ thirdPartyStripeSubscriptionId: "thirdPartySubscriptionId",
+ },
+}));
+
+const lockRows = vi.fn();
+const deletes: unknown[] = [];
+
+type SelectQuery = Promise<unknown[]> & {
+ from(table: unknown): SelectQuery;
+ innerJoin(): SelectQuery;
+ where(): SelectQuery;
+ limit(): SelectQuery;
+ for(mode: string): SelectQuery;
+};
+
+function selectQuery() {
+ let source: unknown;
+ const query: SelectQuery = Object.assign(
+ Promise.resolve(mocks.selectResults.shift() ?? []),
+ {
+ from: (table: unknown) => {
+ source = table;
+ return query;
+ },
+ innerJoin: () => query,
+ where: () => query,
+ limit: () => query,
+ for: (mode: string) => {
+ lockRows(mode, source);
+ return query;
+ },
+ },
+ );
+ return query;
+}
+
+const database = {
+ select: vi.fn(selectQuery),
+ delete: vi.fn((table: unknown) => {
+ deletes.push(table);
+ return { where: async () => [{ affectedRows: 1 }] };
+ }),
+ update: vi.fn((table: unknown) => ({
+ set: (value: Record<string, unknown>) => {
+ 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" },
+ serverEnv: () => ({ WEB_URL: "https://cap.test" }),
+}));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+vi.mock("@cap/database/schema", () => tables);
+
+async function declineProSeat(
+ remainingSeats: { stripeSubscriptionId: string | null }[],
+) {
+ mocks.selectResults = [
+ [
+ {
+ id: "invite-1",
+ invitedEmail: "[email protected]",
+ organizationId: "org-1",
+ },
+ ],
+ [{ id: "member-1", hasProSeat: true }],
+ [],
+ [],
+ [{ id: "user-1" }],
+ remainingSeats,
+ ];
+ const { POST } = await import("@/app/api/invite/decline/route");
+ return POST(
+ new Request("https://cap.test/api/invite/decline", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ inviteId: "invite-1" }),
+ }) as unknown as import("next/server").NextRequest,
+ );
+}
+
+function userIsStillPro() {
+ return userIsPro({ stripeSubscriptionStatus: null, ...mocks.user });
+}
+
+describe("POST /api/invite/decline with a Pro seat", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ deletes.length = 0;
+ mocks.user.thirdPartyStripeSubscriptionId = "sub_org_1";
+ mocks.getCurrentUser.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ activeOrganizationId: null,
+ defaultOrgId: null,
+ });
+ });
+
+ it("clears Pro when the declined seat was the last one", async () => {
+ const response = await declineProSeat([]);
+
+ expect(response.status).toBe(200);
+ expect(deletes).toEqual([
+ tables.organizationMembers,
+ tables.organizationInvites,
+ ]);
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBeNull();
+ expect(userIsStillPro()).toBe(false);
+ });
+
+ it("keeps Pro when a manager-sponsored seat remains", async () => {
+ const response = await declineProSeat([{ stripeSubscriptionId: null }]);
+
+ expect(response.status).toBe(200);
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_org_1");
+ expect(userIsStillPro()).toBe(true);
+ });
+
+ it("moves Pro onto a remaining paid seat", async () => {
+ const response = await declineProSeat([
+ { stripeSubscriptionId: null },
+ { stripeSubscriptionId: "sub_other" },
+ ]);
+
+ expect(response.status).toBe(200);
+ expect(deletes).toEqual([
+ tables.organizationMembers,
+ tables.organizationInvites,
+ ]);
+ expect(mocks.user.thirdPartyStripeSubscriptionId).toBe("sub_other");
+ expect(userIsStillPro()).toBe(true);
+ });
+
+ it("locks the invite, the membership and the user row", async () => {
+ await declineProSeat([{ stripeSubscriptionId: "sub_other" }]);
+
+ expect(lockRows.mock.calls).toEqual([
+ ["update", tables.organizationInvites],
+ ["update", tables.organizationMembers],
+ ["update", tables.users],
+ ]);
+ });
+});
diff --git a/apps/web/__tests__/unit/remove-organization-member.test.ts b/apps/web/__tests__/unit/remove-organization-member.test.ts
index f5b52345d..bb187eaa5 100644
--- a/apps/web/__tests__/unit/remove-organization-member.test.ts
+++ b/apps/web/__tests__/unit/remove-organization-member.test.ts
@@ -99,6 +99,7 @@ async function removeSeat(
},
],
[],
+ [{ id: "teammate" }],
remainingSeats,
];
const { removeOrganizationMember } = await import(
diff --git a/apps/web/__tests__/unit/toggle-pro-seat.test.ts b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
index 8c2b1f72f..df4288275 100644
--- a/apps/web/__tests__/unit/toggle-pro-seat.test.ts
+++ b/apps/web/__tests__/unit/toggle-pro-seat.test.ts
@@ -30,7 +30,7 @@ const lockRows = vi.fn();
const updates: { table: unknown; value: Record<string, unknown> }[] = [];
type SelectQuery = Promise<unknown[]> & {
- from(): SelectQuery;
+ from(table: unknown): SelectQuery;
innerJoin(): SelectQuery;
where(): SelectQuery;
limit(): SelectQuery;
@@ -38,15 +38,19 @@ type SelectQuery = Promise<unknown[]> & {
};
function selectQuery() {
+ let source: unknown;
const query: SelectQuery = Object.assign(
Promise.resolve(mocks.selectResults.shift() ?? []),
{
- from: () => query,
+ from: (table: unknown) => {
+ source = table;
+ return query;
+ },
innerJoin: () => query,
where: () => query,
limit: () => query,
for: (mode: string) => {
- lockRows(mode);
+ lockRows(mode, source);
return query;
},
},
@@ -96,6 +100,7 @@ async function turnSeatOff(
) {
mocks.selectResults = [
[{ id: "member", userId: "teammate", hasProSeat: true }],
+ [{ id: "teammate" }],
remainingSeats,
];
await toggle(false);
@@ -151,14 +156,15 @@ describe("toggleProSeat", () => {
expect(memberIsPro()).toBe(true);
});
- it("locks the member and the remaining seats inside the transaction", async () => {
+ it("locks the member row and then the user row 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");
+ expect(database.select).toHaveBeenCalledTimes(3);
+ expect(lockRows.mock.calls).toEqual([
+ ["update", tables.organizationMembers],
+ ["update", tables.users],
+ ]);
});
it("does nothing when the seat is already off", async () => {
diff --git a/packages/database/pro-seat-subscription.ts b/packages/database/pro-seat-subscription.ts
index 1080f201f..2d4ca0549 100644
--- a/packages/database/pro-seat-subscription.ts
+++ b/packages/database/pro-seat-subscription.ts
@@ -9,10 +9,17 @@ type Transaction = Parameters<
// 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.
+// The user row lock serializes releases for one user. Locking the remaining
+// seat rows instead deadlocks two orgs turning off the same user's seats.
export async function releaseProSeatSubscription(
tx: Transaction,
userId: User.UserId,
) {
+ await tx
+ .select({ id: users.id })
+ .from(users)
+ .where(eq(users.id, userId))
+ .for("update");
const remainingSeats = await tx
.select({ stripeSubscriptionId: users.stripeSubscriptionId })
.from(organizationMembers)
@@ -26,8 +33,7 @@ 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 cbe5d1826..715358a3e 100644
--- a/packages/web-backend/src/Organisations/index.ts
+++ b/packages/web-backend/src/Organisations/index.ts
@@ -270,10 +270,15 @@ 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);
- }
+ const proSeatUserIds = [
+ ...new Set(
+ memberRows
+ .filter((member) => member.hasProSeat)
+ .map((member) => member.userId),
+ ),
+ ].sort();
+ for (const proSeatUserId of proSeatUserIds) {
+ await releaseProSeatSubscription(tx, proSeatUserId);
}
for (const affectedUserId of affectedUserIds) {