Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🐛 Gate a poll's paid features on the poll's space, not the active one (#3426)
Luke Vella062a2b63e67a
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsxindex 00bccb116..5097594ee 100644--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx@@ -1,6 +1,8 @@import type { Metadata } from "next";import { notFound } from "next/navigation";import { Suspense } from "react";+import { TierProvider } from "@/features/billing/client";+import { resolveSpaceTier } from "@/features/billing/utils";import { PollProvider } from "@/features/poll/client";import { PollLayout } from "@/features/poll/components/poll-layout";import { loadAdminPoll, loadPollAvailability } from "@/features/poll/loaders";@@ -15,15 +17,21 @@ async function AdminPollLayout({const { urlId } = await params;const { poll, participants, comments } = await loadAdminPoll(urlId);+ // Access is proven against the poll's space, not the active one, so the+ // paid features on these pages follow the poll's space too: the server+ // gates them on the same tier. A poll outside any space keeps the active+ // space's tier from the parent layout.return (- <PollProvider- poll={poll}- participants={participants}- comments={comments}- viewerRole="admin"- >- <PollLayout>{children}</PollLayout>- </PollProvider>+ <TierProvider tier={poll.space ? resolveSpaceTier(poll.space.tier) : null}>+ <PollProvider+ poll={poll}+ participants={participants}+ comments={comments}+ viewerRole="admin"+ >+ <PollLayout>{children}</PollLayout>+ </PollProvider>+ </TierProvider>);}diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsxindex e994664c1..02f78a7e3 100644--- a/apps/web/src/features/billing/client.tsx+++ b/apps/web/src/features/billing/client.tsx@@ -10,14 +10,23 @@ import type { SpaceTier } from "@/features/space/schema";const TierContext = React.createContext<SpaceTier | null>(null);+/**+ * A null tier inherits the enclosing provider's, so a nested provider can+ * override the tier only when it has one of its own.+ */export function TierProvider({tier,children,}: {- tier: SpaceTier;+ tier: SpaceTier | null;children: React.ReactNode;}) {- return <TierContext.Provider value={tier}>{children}</TierContext.Provider>;+ const inherited = React.useContext(TierContext);+ return (+ <TierContext.Provider value={tier ?? inherited}>+ {children}+ </TierContext.Provider>+ );}export function useTier(): SpaceTier {diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 3006fed59..2d8b0ddc0 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -11,6 +11,7 @@ import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";import { toEmailConferencing } from "@/emails/conferencing";import { recordPollActivities } from "@/features/activity/mutations";import { getPollChanges } from "@/features/activity/utils";+import { resolveSpaceTier } from "@/features/billing/utils";import {getConnectedConferencingProviders,parsePollConferencing,@@ -37,6 +38,7 @@ import { MAX_POLL_DESCRIPTION_LENGTH } from "@/features/poll/schema";import { getFinalizePlanGate } from "@/features/poll/utils";import { formatEventDateTime } from "@/features/scheduled-event/utils";import { getActiveSpaceForUser } from "@/features/space/data";+import type { SpaceTier } from "@/features/space/schema";import {isSpaceAttributionHidden,isSpaceBrandingActive,@@ -53,7 +55,6 @@ import {createRateLimitMiddleware,possiblyPublicProcedure,privateProcedure,- proProcedure,publicProcedure,requireUserMiddleware,router,@@ -137,6 +138,22 @@ const toOptionSnapshot = (option: {duration: option.duration,});+// A poll's paid features follow the poll's space, which is not always the+// active one: the admin page authorizes against the poll's space, so a+// member of several spaces can manage a poll outside the space they have+// selected. A poll outside any space falls back to the active space, the+// tier its admin page shows. The active tier is the coerced DTO's, so both+// branches agree with the client gate.+function getPollTier({+ space,+ activeSpaceTier,+}: {+ space: { tier: SpaceTier } | null;+ activeSpaceTier: SpaceTier;+}) {+ return space ? resolveSpaceTier(space.tier) : activeSpaceTier;+}+export const polls = router({invites,infiniteChronological: spaceProcedure@@ -1202,10 +1219,12 @@ export const polls = router({});// Finalizing and notifying are free; a Zoom or Teams meeting is what- // the plan pays for. ctx.space is the coerced DTO, the same tier the- // client gates on.+ // the plan pays for.const planGate = getFinalizePlanGate({- tier: ctx.space.tier,+ tier: getPollTier({+ space: poll.space,+ activeSpaceTier: ctx.space.tier,+ }),conferencing: pollConferencing,});if (planGate) {@@ -1613,7 +1632,7 @@ export const polls = router({},});}),- duplicate: proProcedure+ duplicate: spaceProcedure.input(z.object({pollId: z.string(),@@ -1644,6 +1663,7 @@ export const polls = router({disableComments: true,allowTentativeVotes: true,spaceId: true,+ space: { select: { tier: true } },kind: true,options: {select: {@@ -1658,6 +1678,17 @@ export const polls = router({throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });}+ if (+ getPollTier({ space: poll.space, activeSpaceTier: ctx.space.tier }) !==+ "pro"+ ) {+ throw new TRPCError({+ code: "PAYMENT_REQUIRED",+ message:+ "You must have an active paid subscription to perform this action",+ });+ }+const newPoll = await prisma.$transaction(async (tx) => {const newPoll = await tx.poll.create({select: {diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex 973bb4b3a..2552b4009 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -172,19 +172,6 @@ export const spaceProcedure = privateProcedure.use(async ({ ctx, next }) => {});});-export const proProcedure = spaceProcedure.use(async ({ ctx, next }) => {- // ctx.space is the coerced DTO: without billing every space is pro here- if (ctx.space.tier !== "pro") {- throw new TRPCError({- code: "PAYMENT_REQUIRED",- message:- "You must have an active paid subscription to perform this action",- });- }-- return next();-});-export const spaceOwnerProcedure = spaceProcedure.use(async ({ ctx, next }) => {if (ctx.space.ownerId !== ctx.user.id) {throw new TRPCError({diff --git a/apps/web/tests/poll-space-tier.spec.ts b/apps/web/tests/poll-space-tier.spec.tsnew file mode 100644index 000000000..4a3bec59e--- /dev/null+++ b/apps/web/tests/poll-space-tier.spec.ts@@ -0,0 +1,123 @@+import type { Page } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import {+ createUserInDb,+ loginWithEmail,+ upgradeSpaceToPro,+} from "./test-utils";++// A poll admin page authorizes against the poll's own space, so a member of+// several spaces can open a poll that belongs to a space other than the+// active one. The page's paid features follow the poll's space, both in the+// controls it shows and in what the server allows, and opening it does not+// change which space is active.++// One login shared by both tests: the second checks the state the first+// leaves behind.+test.describe.configure({ mode: "serial" });++const runId = Date.now().toString(36);+const createdUserIds: string[] = [];++let page: Page;+let pollId: string;+let teamName: string;++function emailFor(name: string) {+ return `${name.toLowerCase().replace(/\s/g, "-")}-${runId}@example.com`;+}++test.beforeAll(async ({ browser }) => {+ const owner = await createUserInDb({+ email: emailFor("Team Owner"),+ name: "Team Owner",+ });+ createdUserIds.push(owner.id);+ const team = await prisma.space.findFirstOrThrow({+ where: { ownerId: owner.id },+ });+ teamName = `Marketing ${runId}`;+ await prisma.space.update({+ where: { id: team.id },+ data: { name: teamName },+ });+ await upgradeSpaceToPro({ spaceId: team.id, userId: owner.id, seats: 2 });++ const email = emailFor("Jessie Smith");+ const member = await createUserInDb({ email, name: "Jessie Smith" });+ createdUserIds.push(member.id);++ // The member's own hobby space is the active one: selected now, the team+ // space long ago.+ await prisma.spaceMember.updateMany({+ where: { userId: member.id },+ data: { lastSelectedAt: new Date() },+ });+ await prisma.spaceMember.create({+ data: {+ spaceId: team.id,+ userId: member.id,+ role: "MEMBER",+ lastSelectedAt: new Date(0),+ },+ });++ const tomorrow = new Date();+ tomorrow.setDate(tomorrow.getDate() + 1);+ tomorrow.setMinutes(0, 0, 0);++ const poll = await prisma.poll.create({+ data: {+ id: `space-tier-${runId}`,+ title: "Team offsite",+ userId: member.id,+ spaceId: team.id,+ kind: "time",+ options: {+ create: {+ startTime: tomorrow,+ duration: 60,+ },+ },+ },+ });+ pollId = poll.id;++ page = await browser.newPage();+ await loginWithEmail(page, { email });+});++test.afterAll(async () => {+ await page.close();+ if (createdUserIds.length > 0) {+ await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });+ }+});++test("a poll in a pro space keeps its pro features while a hobby space is active", async () => {+ await page.goto(`/poll/${pollId}`);+ await expect(page).toHaveURL(new RegExp(`/poll/${pollId}$`));++ await page.getByRole("button", { name: "Manage" }).click();+ const duplicateItem = page.getByRole("menuitem", { name: "Duplicate" });+ await expect(duplicateItem).not.toContainText("Pro");+ await duplicateItem.click();++ await page.getByLabel("Title").fill("Team offsite copy");+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Duplicate" })+ .click();++ await expect(page).toHaveURL(/\/poll\/(?!space-tier-)[\w-]+$/);+ await expect(+ page.getByRole("heading", { name: "Team offsite copy" }).first(),+ ).toBeVisible();+});++test("opening the poll leaves the active space unchanged", async () => {+ await page.goto("/polls");+ await expect(page.getByRole("button", { name: /Personal/ })).toBeVisible();+ await expect(page.getByRole("button", { name: teamName })).not.toBeVisible();+});