Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Enforce open poll limits behind a kill switch (#3482)

Luke Vella91e69199a56d
diff --git a/apps/web/.env.test b/apps/web/.env.test
index 279d76408..772b1e497 100644
--- a/apps/web/.env.test
+++ b/apps/web/.env.test
@@ -25,3 +25,4 @@ ZOOM_CLIENT_ID=test-zoom
ZOOM_CLIENT_SECRET=test-zoom-secret
ZOOM_WEBHOOK_SECRET_TOKEN=test-zoom-webhook-secret
EMAIL_QUEUE_SCHEDULER_ENABLED=false
+OPEN_POLL_LIMIT_ENABLED=true
diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts
index 4e4a2fc8c..0d29dc097 100644
--- a/apps/web/src/env.ts
+++ b/apps/web/src/env.ts
@@ -185,6 +185,13 @@ export const env = createEnv({
* @default "true"
*/
EMAIL_QUEUE_SCHEDULER_ENABLED: z.enum(["true", "false"]).default("true"),
+ /**
+ * Cap the number of open polls an organizer can have at once by tier.
+ * Only takes effect where billing is enabled. Off until the limit dialog
+ * ships; turning it back off is the rollback.
+ * @default "false"
+ */
+ OPEN_POLL_LIMIT_ENABLED: z.enum(["true", "false"]).default("false"),
/**
* Take the app offline for scheduled maintenance. Page traffic is
@@ -341,6 +348,7 @@ export const env = createEnv({
HIDE_ATTRIBUTION: process.env.HIDE_ATTRIBUTION,
RATE_LIMIT_ENABLED: process.env.RATE_LIMIT_ENABLED,
EMAIL_QUEUE_SCHEDULER_ENABLED: process.env.EMAIL_QUEUE_SCHEDULER_ENABLED,
+ OPEN_POLL_LIMIT_ENABLED: process.env.OPEN_POLL_LIMIT_ENABLED,
MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,
MAINTENANCE_BYPASS_TOKEN: process.env.MAINTENANCE_BYPASS_TOKEN,
TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,
diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsx
index 3ef1e8e26..162f4a4aa 100644
--- a/apps/web/src/features/poll/components/create-poll.tsx
+++ b/apps/web/src/features/poll/components/create-poll.tsx
@@ -230,7 +230,7 @@ export const CreatePoll = ({
setCreatedPollId(res.data.id);
setFlash(SHARE_POLL_FLASH_KEY, res.data.id);
router.push(`/poll/${res.data.id}`);
- } else {
+ } else if (res.error.code === "INAPPROPRIATE_CONTENT") {
toast.error(
t("inappropriateContent", {
defaultValue: "Inappropriate content",
diff --git a/apps/web/src/features/poll/components/duplicate-dialog.tsx b/apps/web/src/features/poll/components/duplicate-dialog.tsx
index b857510d2..b5e6571eb 100644
--- a/apps/web/src/features/poll/components/duplicate-dialog.tsx
+++ b/apps/web/src/features/poll/components/duplicate-dialog.tsx
@@ -47,7 +47,9 @@ export function DuplicateDialog({
{ pollId, newTitle: data.title },
{
onSuccess: async (res) => {
- router.push(`/poll/${res.id}`);
+ if (res.ok) {
+ router.push(`/poll/${res.data.id}`);
+ }
},
},
);
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index 7613ec3dc..f278ed8d0 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -327,6 +327,70 @@ type PollFilters = {
scope: SpaceContentScope;
};
+// The row the poll lists render: the polls page and the open poll limit
+// dialog read the same shape.
+export const pollListItemSelect = {
+ id: true,
+ title: true,
+ status: true,
+ closedReason: true,
+ timeZone: true,
+ createdAt: true,
+ updatedAt: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ },
+ _count: {
+ select: {
+ participants: true,
+ },
+ },
+} satisfies Prisma.PollSelect;
+
+export async function toPollListItems(
+ polls: Prisma.PollGetPayload<{ select: typeof pollListItemSelect }>[],
+) {
+ const optionRanges = await prisma.option.groupBy({
+ by: ["pollId"],
+ where: { pollId: { in: polls.map((poll) => poll.id) } },
+ _min: { startTime: true },
+ _max: { startTime: true },
+ });
+ const rangeByPollId = new Map(
+ optionRanges.map((range) => [range.pollId, range]),
+ );
+
+ return polls.map((poll) => {
+ const range = rangeByPollId.get(poll.id);
+ return {
+ id: poll.id,
+ title: poll.title,
+ status: poll.status,
+ closedReason: poll.closedReason,
+ // Null means the poll's times are floating: shown as stored to everyone
+ timeZone: poll.timeZone,
+ createdAt: poll.createdAt,
+ updatedAt: poll.updatedAt,
+ user: poll.user
+ ? {
+ id: poll.user.id,
+ name: poll.user.name,
+ image: poll.user.image,
+ }
+ : null,
+ participantCount: poll._count.participants,
+ dateRange:
+ range?._min.startTime && range._max.startTime
+ ? { start: range._min.startTime, end: range._max.startTime }
+ : null,
+ };
+ });
+}
+
export const getPolls = async ({
status,
q,
@@ -357,68 +421,14 @@ export const getPolls = async ({
prisma.poll.count({ where }),
prisma.poll.findMany({
where,
- select: {
- id: true,
- title: true,
- status: true,
- closedReason: true,
- timeZone: true,
- createdAt: true,
- updatedAt: true,
- user: {
- select: {
- id: true,
- name: true,
- image: true,
- },
- },
- _count: {
- select: {
- participants: true,
- },
- },
- },
+ select: pollListItemSelect,
orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
skip: (page - 1) * pageSize,
take: pageSize,
}),
]);
- const optionRanges = await prisma.option.groupBy({
- by: ["pollId"],
- where: { pollId: { in: polls.map((poll) => poll.id) } },
- _min: { startTime: true },
- _max: { startTime: true },
- });
- const rangeByPollId = new Map(
- optionRanges.map((range) => [range.pollId, range]),
- );
-
- const transformedPolls = polls.map((poll) => {
- const range = rangeByPollId.get(poll.id);
- return {
- id: poll.id,
- title: poll.title,
- status: poll.status,
- closedReason: poll.closedReason,
- // Null means the poll's times are floating: shown as stored to everyone
- timeZone: poll.timeZone,
- createdAt: poll.createdAt,
- updatedAt: poll.updatedAt,
- user: poll.user
- ? {
- id: poll.user.id,
- name: poll.user.name,
- image: poll.user.image,
- }
- : null,
- participantCount: poll._count.participants,
- dateRange:
- range?._min.startTime && range._max.startTime
- ? { start: range._min.startTime, end: range._max.startTime }
- : null,
- };
- });
+ const transformedPolls = await toPollListItems(polls);
const totalPages = Math.ceil(totalCount / pageSize);
const hasNextPage = page < totalPages;
diff --git a/apps/web/src/features/poll/limit/constants.ts b/apps/web/src/features/poll/limit/constants.ts
new file mode 100644
index 000000000..8ca569ac2
--- /dev/null
+++ b/apps/web/src/features/poll/limit/constants.ts
@@ -0,0 +1,15 @@
+import { isBillingEnabled } from "@/features/billing/constants";
+import type { OpenPollTier } from "./types";
+
+// null is unlimited. Read by the server to refuse and by the client to
+// explain, so the two can never disagree.
+export const OPEN_POLL_LIMITS: Record<OpenPollTier, number | null> = {
+ guest: 1,
+ hobby: 3,
+ pro: null,
+};
+
+// The ladder exists to sell Pro, so it only applies where there is
+// something to buy.
+export const isOpenPollLimitEnabled =
+ isBillingEnabled && process.env.OPEN_POLL_LIMIT_ENABLED === "true";
diff --git a/apps/web/src/features/poll/limit/data.ts b/apps/web/src/features/poll/limit/data.ts
new file mode 100644
index 000000000..c64192d4e
--- /dev/null
+++ b/apps/web/src/features/poll/limit/data.ts
@@ -0,0 +1,64 @@
+import "server-only";
+
+import type { Prisma } from "@rallly/database";
+import { prisma } from "@rallly/database";
+import { pollListItemSelect, toPollListItems } from "@/features/poll/data";
+import { isOpenPollLimitEnabled } from "./constants";
+import type {
+ OpenPollLimitDetails,
+ OpenPollTier,
+ OpenPollUsage,
+} from "./types";
+import { getOpenPollLimit } from "./utils";
+
+// The organizer is the tenant: the space only narrows which of their polls
+// count, so a caller may pass a poll's own space without a session gate.
+type OpenPollScope = {
+ userId: string;
+ /** null scopes to a guest's polls, which have no space */
+ spaceId: string | null;
+};
+
+// Closed, scheduled, canceled and deleted polls all free a slot.
+const openPollsWhere = ({ userId, spaceId }: OpenPollScope) =>
+ ({
+ userId,
+ spaceId,
+ status: "open",
+ deleted: false,
+ }) satisfies Prisma.PollWhereInput;
+
+export function countOpenPolls({
+ db = prisma,
+ ...scope
+}: OpenPollScope & { db?: Prisma.TransactionClient }) {
+ return db.poll.count({ where: openPollsWhere(scope) });
+}
+
+export async function getOpenPollUsage({
+ tier,
+ ...scope
+}: OpenPollScope & { tier: OpenPollTier }): Promise<OpenPollUsage> {
+ return {
+ tier,
+ limit: getOpenPollLimit({ tier, enabled: isOpenPollLimitEnabled }),
+ openCount: await countOpenPolls(scope),
+ };
+}
+
+export async function listOpenPolls(scope: OpenPollScope) {
+ const polls = await prisma.poll.findMany({
+ where: openPollsWhere(scope),
+ select: pollListItemSelect,
+ orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
+ take: 50,
+ });
+ return toPollListItems(polls);
+}
+
+export async function getOpenPollLimitDetails({
+ usage,
+ ...scope
+}: OpenPollScope & { usage: OpenPollUsage }): Promise<OpenPollLimitDetails> {
+ return { usage, polls: await listOpenPolls(scope) };
+}
diff --git a/apps/web/src/features/poll/limit/loaders.ts b/apps/web/src/features/poll/limit/loaders.ts
new file mode 100644
index 000000000..a19c4009c
--- /dev/null
+++ b/apps/web/src/features/poll/limit/loaders.ts
@@ -0,0 +1,44 @@
+import "server-only";
+
+import { cache } from "react";
+import { getActiveSpaceForUser } from "@/features/space/data";
+import { getSessionState } from "@/lib/auth";
+import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
+import { getOpenPollLimitDetails, getOpenPollUsage } from "./data";
+import { getOpenPollTier, isAtOpenPollLimit } from "./utils";
+
+/**
+ * The session organizer's open poll usage in the scope they create into: a
+ * guest's polls without a space, a member's in their active space. The polls
+ * are listed only at the limit, where the dialog shows them. Null without a
+ * session or an active space.
+ */
+export const loadOptionalOpenPollLimit = cache(async () => {
+ const state = await getSessionState();
+
+ if (state.status !== "authenticated") {
+ return null;
+ }
+
+ const { user } = state.session;
+
+ if (user.banned) {
+ throw new InvalidSessionError();
+ }
+
+ const space = user.isGuest ? null : await getActiveSpaceForUser(user.id);
+
+ if (!user.isGuest && !space) {
+ return null;
+ }
+
+ const scope = { userId: user.id, spaceId: space?.id ?? null };
+ const usage = await getOpenPollUsage({
+ ...scope,
+ tier: getOpenPollTier(space?.tier ?? null),
+ });
+
+ return isAtOpenPollLimit(usage)
+ ? getOpenPollLimitDetails({ ...scope, usage })
+ : { usage, polls: [] };
+});
diff --git a/apps/web/src/features/poll/limit/mutations.ts b/apps/web/src/features/poll/limit/mutations.ts
new file mode 100644
index 000000000..22709407e
--- /dev/null
+++ b/apps/web/src/features/poll/limit/mutations.ts
@@ -0,0 +1,63 @@
+import "server-only";
+
+import type { Prisma } from "@rallly/database";
+import { isOpenPollLimitEnabled } from "./constants";
+import { countOpenPolls } from "./data";
+import type { OpenPollUsage } from "./types";
+import { getOpenPollLimit, getOpenPollTier, isAtOpenPollLimit } from "./utils";
+
+export class OpenPollLimitError extends Error {
+ readonly _tag = "OpenPollLimitError";
+ constructor(readonly usage: OpenPollUsage) {
+ super("Open poll limit reached");
+ }
+}
+
+/**
+ * Whether the organizer can open one more poll in this scope. Call it inside
+ * the transaction that opens the poll: it takes a lock held until that
+ * transaction ends, so two concurrent creates can't both see the last slot.
+ */
+export async function checkOpenPollCapacity(
+ tx: Prisma.TransactionClient,
+ { userId, spaceId }: { userId: string; spaceId: string | null },
+): Promise<{ ok: true } | { ok: false; usage: OpenPollUsage }> {
+ if (!isOpenPollLimitEnabled) {
+ return { ok: true };
+ }
+
+ const space = spaceId
+ ? await tx.space.findUnique({
+ where: { id: spaceId },
+ select: { tier: true },
+ })
+ : null;
+ const tier = getOpenPollTier(space?.tier ?? null);
+ const limit = getOpenPollLimit({ tier, enabled: true });
+
+ if (limit === null) {
+ return { ok: true };
+ }
+
+ // $executeRaw because Prisma can't deserialize the void the lock returns.
+ await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`open_polls:${userId}:${spaceId ?? ""}`}))`;
+
+ const usage: OpenPollUsage = {
+ tier,
+ limit,
+ openCount: await countOpenPolls({ db: tx, userId, spaceId }),
+ };
+
+ return isAtOpenPollLimit(usage) ? { ok: false, usage } : { ok: true };
+}
+
+/** Throws so the transaction that would open the poll rolls back. */
+export async function assertOpenPollCapacity(
+ tx: Prisma.TransactionClient,
+ scope: { userId: string; spaceId: string | null },
+) {
+ const capacity = await checkOpenPollCapacity(tx, scope);
+ if (!capacity.ok) {
+ throw new OpenPollLimitError(capacity.usage);
+ }
+}
diff --git a/apps/web/src/features/poll/limit/types.ts b/apps/web/src/features/poll/limit/types.ts
new file mode 100644
index 000000000..92bc25849
--- /dev/null
+++ b/apps/web/src/features/poll/limit/types.ts
@@ -0,0 +1,17 @@
+import type { PollListItem } from "@/features/poll/types";
+import type { SpaceTier } from "@/features/space/schema";
+
+export type OpenPollTier = "guest" | SpaceTier;
+
+export type OpenPollUsage = {
+ tier: OpenPollTier;
+ /** null when the tier is unlimited or enforcement is off */
+ limit: number | null;
+ openCount: number;
+};
+
+/** What the limit dialog shows: the count and the polls holding the slots */
+export type OpenPollLimitDetails = {
+ usage: OpenPollUsage;
+ polls: PollListItem[];
+};
diff --git a/apps/web/src/features/poll/limit/utils.test.ts b/apps/web/src/features/poll/limit/utils.test.ts
new file mode 100644
index 000000000..9d32c719b
--- /dev/null
+++ b/apps/web/src/features/poll/limit/utils.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { getOpenPollLimit, getOpenPollTier, isAtOpenPollLimit } from "./utils";
+
+describe("getOpenPollLimit", () => {
+ it("is 1 for guests, 3 for free and unlimited on Pro", () => {
+ expect(getOpenPollLimit({ tier: "guest", enabled: true })).toBe(1);
+ expect(getOpenPollLimit({ tier: "hobby", enabled: true })).toBe(3);
+ expect(getOpenPollLimit({ tier: "pro", enabled: true })).toBeNull();
+ });
+
+ it("is unlimited for every tier while enforcement is off", () => {
+ for (const tier of ["guest", "hobby", "pro"] as const) {
+ expect(getOpenPollLimit({ tier, enabled: false })).toBeNull();
+ }
+ });
+});
+
+describe("getOpenPollTier", () => {
+ it("treats a poll outside any space as a guest's", () => {
+ expect(getOpenPollTier(null)).toBe("guest");
+ });
+});
+
+describe("isAtOpenPollLimit", () => {
+ it("is reached at the limit and past it", () => {
+ expect(isAtOpenPollLimit({ tier: "hobby", limit: 3, openCount: 2 })).toBe(
+ false,
+ );
+ expect(isAtOpenPollLimit({ tier: "hobby", limit: 3, openCount: 3 })).toBe(
+ true,
+ );
+ expect(isAtOpenPollLimit({ tier: "hobby", limit: 3, openCount: 5 })).toBe(
+ true,
+ );
+ });
+
+ it("is never reached without a limit", () => {
+ expect(
+ isAtOpenPollLimit({ tier: "pro", limit: null, openCount: 1000 }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/poll/limit/utils.ts b/apps/web/src/features/poll/limit/utils.ts
new file mode 100644
index 000000000..42173101a
--- /dev/null
+++ b/apps/web/src/features/poll/limit/utils.ts
@@ -0,0 +1,30 @@
+import { resolveSpaceTier } from "@/features/billing/utils";
+import type { SpaceTier } from "@/features/space/schema";
+import { OPEN_POLL_LIMITS } from "./constants";
+import type { OpenPollTier, OpenPollUsage } from "./types";
+
+/**
+ * A poll outside any space belongs to a guest: registered organizers always
+ * create into a space, and guest polls only gain one when adopted on sign up.
+ */
+export function getOpenPollTier(spaceTier: SpaceTier | null): OpenPollTier {
+ return spaceTier ? resolveSpaceTier(spaceTier) : "guest";
+}
+
+export function getOpenPollLimit({
+ tier,
+ enabled,
+}: {
+ tier: OpenPollTier;
+ enabled: boolean;
+}) {
+ return enabled ? OPEN_POLL_LIMITS[tier] : null;
+}
+
+/**
+ * Adopting guest polls on sign up is never blocked, so an organizer can be
+ * over the limit, not just at it.
+ */
+export function isAtOpenPollLimit({ limit, openCount }: OpenPollUsage) {
+ return limit !== null && openCount >= limit;
+}
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 124f61e1f..092f12873 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -7,6 +7,7 @@ import { revalidatePath } from "next/cache";
import { recordPollActivities } from "@/features/activity/mutations";
import { parsePollConferencing } from "@/features/conferencing/data";
import type { PollConferencing } from "@/features/conferencing/schema";
+import { assertOpenPollCapacity } from "@/features/poll/limit/mutations";
import type { AuthorizedSpaceId } from "@/features/space/types";
import { scheduleWebhookDispatch } from "@/features/webhook/mutations";
@@ -108,6 +109,8 @@ export const createPoll = async ({
const kind = options.some((o) => o.duration > 0) ? "time" : "date";
const poll = await prisma.$transaction(async (tx) => {
+ await assertOpenPollCapacity(tx, { userId, spaceId });
+
const poll = await tx.poll.create({
data: {
id: nanoid(),
diff --git a/apps/web/src/features/poll/types.ts b/apps/web/src/features/poll/types.ts
index 83a6dc59b..024babbcf 100644
--- a/apps/web/src/features/poll/types.ts
+++ b/apps/web/src/features/poll/types.ts
@@ -1,5 +1,6 @@
import type { PollConferencing } from "@/features/conferencing/schema";
import type { VoteType } from "@/features/poll/constants";
+import type { toPollListItems } from "@/features/poll/data";
import type { PollClosedReason, PollStatus } from "@/features/poll/schema";
import type { SpaceTier } from "@/features/space/schema";
@@ -67,3 +68,6 @@ export type PollComment = {
userId: string | null;
createdAt: Date;
};
+
+/** A row of the poll lists: the polls page and the open poll limit dialog */
+export type PollListItem = Awaited<ReturnType<typeof toPollListItems>>[number];
diff --git a/apps/web/src/lib/feature-flags/config.ts b/apps/web/src/lib/feature-flags/config.ts
index 6326c6466..ce3798057 100644
--- a/apps/web/src/lib/feature-flags/config.ts
+++ b/apps/web/src/lib/feature-flags/config.ts
@@ -5,6 +5,7 @@ import { isCalendarsEnabled } from "@/features/calendars/constants";
import { isConferencingEnabled } from "@/features/conferencing/constants";
import { isEventTypesEnabled } from "@/features/event-types/constants";
import { isFeedbackEnabled } from "@/features/feedback/constants";
+import { isOpenPollLimitEnabled } from "@/features/poll/limit/constants";
import { isQuickCreateEnabled } from "@/features/quick-create/constants";
import { isReviewRequestEnabled } from "@/features/review-request/constants";
import { isSelfHosted } from "@/lib/constants";
@@ -49,4 +50,7 @@ export const featureFlagConfig: FeatureFlagConfig = {
updateCheck: isSelfHosted,
// Review sites list the cloud product; nobody to review it for self-hosted.
reviewRequests: isReviewRequestEnabled,
+ // Caps open polls per organizer by tier. Billing only: the ladder sells
+ // Pro, and without billing every space already has every paid feature.
+ openPollLimit: isOpenPollLimitEnabled,
};
diff --git a/apps/web/src/lib/feature-flags/types.ts b/apps/web/src/lib/feature-flags/types.ts
index c00037153..23fec3d3e 100644
--- a/apps/web/src/lib/feature-flags/types.ts
+++ b/apps/web/src/lib/feature-flags/types.ts
@@ -15,6 +15,7 @@ export interface FeatureFlagConfig {
webhooks: boolean;
updateCheck: boolean;
reviewRequests: boolean;
+ openPollLimit: boolean;
}
export type Feature = keyof FeatureFlagConfig;
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index f834bc8c4..c1dadeb8d 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -38,6 +38,12 @@ import {
getPolls,
hasPollAdminAccess,
} from "@/features/poll/data";
+import { getOpenPollLimitDetails } from "@/features/poll/limit/data";
+import {
+ assertOpenPollCapacity,
+ checkOpenPollCapacity,
+ OpenPollLimitError,
+} from "@/features/poll/limit/mutations";
import { MAX_POLL_DESCRIPTION_LENGTH } from "@/features/poll/schema";
import {
getFinalizePlanGate,
@@ -335,50 +341,76 @@ export const polls = router({
const kind = isTimePoll ? "time" : "date";
- const poll = await prisma.$transaction(async (tx) => {
- const poll = await tx.poll.create({
- include: {
- options: {
- select: {
- id: true,
+ const poll = await prisma
+ .$transaction(async (tx) => {
+ await assertOpenPollCapacity(tx, {
+ userId: ctx.user.id,
+ spaceId: spaceId ?? null,
+ });
+
+ const poll = await tx.poll.create({
+ include: {
+ options: {
+ select: {
+ id: true,
+ },
},
},
- },
- data: {
- id: pollId,
- title,
- timeZone,
- location,
- conferencing,
- description,
- userId: ctx.user.id,
- kind,
- options: {
- createMany: {
- data: optionsData,
+ data: {
+ id: pollId,
+ title,
+ timeZone,
+ location,
+ conferencing,
+ description,
+ userId: ctx.user.id,
+ kind,
+ options: {
+ createMany: {
+ data: optionsData,
+ },
},
+ hideParticipants: input.hideParticipants,
+ disableComments: input.disableComments,
+ allowTentativeVotes: input.allowTentativeVotes,
+ hideScores: input.hideScores,
+ requireParticipantEmail: input.requireParticipantEmail,
+ spaceId,
},
- hideParticipants: input.hideParticipants,
- disableComments: input.disableComments,
- allowTentativeVotes: input.allowTentativeVotes,
- hideScores: input.hideScores,
- requireParticipantEmail: input.requireParticipantEmail,
- spaceId,
- },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "poll_created",
+ userId: ctx.user.id,
+ payload: { title },
+ },
+ ]);
+ scheduleWebhookDispatch({ pollId: pollId });
+
+ return poll;
+ })
+ .catch((error) => {
+ if (error instanceof OpenPollLimitError) {
+ return error;
+ }
+ throw error;
});
- await recordPollActivities(tx, [
- {
- pollId,
- type: "poll_created",
- userId: ctx.user.id,
- payload: { title },
+ if (poll instanceof OpenPollLimitError) {
+ return {
+ ok: false as const,
+ error: {
+ code: "OPEN_POLL_LIMIT_REACHED" as const,
+ ...(await getOpenPollLimitDetails({
+ usage: poll.usage,
+ userId: ctx.user.id,
+ spaceId: spaceId ?? null,
+ })),
},
- ]);
- scheduleWebhookDispatch({ pollId: pollId });
-
- return poll;
- });
+ };
+ }
const pollLink = absoluteUrl(`/poll/${pollId}`);
@@ -602,6 +634,10 @@ export const polls = router({
disableComments: true,
allowTentativeVotes: true,
requireParticipantEmail: true,
+ status: true,
+ closedReason: true,
+ userId: true,
+ spaceId: true,
},
});
@@ -635,9 +671,21 @@ export const polls = router({
// Reopen an auto-closed poll when new future dates are added. Manually
// closed polls stay closed — that was the organizer's decision. The
// transition is conditional so concurrent modifies can't both record
- // a poll_reopened event.
+ // a poll_reopened event. An organizer at the active poll limit keeps
+ // the edit but not the reopen; reopening by hand explains the limit.
let reopened = false;
- if (newOptions.some(optionEndsInFuture)) {
+ if (
+ newOptions.some(optionEndsInFuture) &&
+ prior.status === "closed" &&
+ prior.closedReason === "auto" &&
+ (!prior.userId ||
+ (
+ await checkOpenPollCapacity(tx, {
+ userId: prior.userId,
+ spaceId: prior.spaceId,
+ })
+ ).ok)
+ ) {
const { count } = await tx.poll.updateMany({
where: { id: pollId, status: "closed", closedReason: "auto" },
data: { status: "open", closedReason: null },
@@ -1534,7 +1582,36 @@ export const polls = router({
});
}
- await prisma.$transaction(async (tx) => {
+ const refusal = await prisma.$transaction(async (tx) => {
+ // Row lock before the capacity check's advisory lock, the order
+ // modify takes them in, so the two can't deadlock.
+ await tx.$queryRaw`SELECT id FROM polls WHERE id = ${input.pollId} FOR UPDATE`;
+
+ // The slot belongs to the poll's organizer, who may not be the
+ // member reopening it.
+ const target = await tx.poll.findUnique({
+ where: { id: input.pollId },
+ select: { status: true, userId: true, spaceId: true },
+ });
+
+ if (
+ target?.userId &&
+ target.status !== "open" &&
+ target.status !== "scheduled"
+ ) {
+ const capacity = await checkOpenPollCapacity(tx, {
+ userId: target.userId,
+ spaceId: target.spaceId,
+ });
+ if (!capacity.ok) {
+ return {
+ usage: capacity.usage,
+ userId: target.userId,
+ spaceId: target.spaceId,
+ };
+ }
+ }
+
// Conditional transition: only the call that actually flips the
// status appends a lifecycle event, so repeated or concurrent calls
// can't record a reopen that didn't happen. Scheduling is final: the
@@ -1561,7 +1638,7 @@ export const polls = router({
message: "A scheduled poll cannot be reopened",
});
}
- return;
+ return null;
}
const poll = await tx.poll.findUnique({
@@ -1588,14 +1665,29 @@ export const polls = router({
},
]);
scheduleWebhookDispatch({ pollId: input.pollId });
+ return null;
});
+ if (refusal) {
+ // Another member's polls are theirs to list, not the reopener's.
+ const details =
+ refusal.userId === ctx.user.id
+ ? await getOpenPollLimitDetails(refusal)
+ : { usage: refusal.usage, polls: [] };
+ return {
+ ok: false as const,
+ error: { code: "OPEN_POLL_LIMIT_REACHED" as const, ...details },
+ };
+ }
+
track(ctx.user, {
event: "poll_reopen",
groups: {
poll: input.pollId,
},
});
+
+ return { ok: true as const };
}),
close: possiblyPublicProcedure
.input(
@@ -1711,7 +1803,15 @@ export const polls = router({
});
}
- const newPoll = await prisma.$transaction(async (tx) => {
+ const result = await prisma.$transaction(async (tx) => {
+ const capacity = await checkOpenPollCapacity(tx, {
+ userId: ctx.user.id,
+ spaceId: poll.spaceId,
+ });
+ if (!capacity.ok) {
+ return capacity;
+ }
+
const newPoll = await tx.poll.create({
select: {
id: true,
@@ -1746,9 +1846,23 @@ export const polls = router({
]);
scheduleWebhookDispatch({ pollId: newPoll.id });
- return newPoll;
+ return { ok: true as const, newPoll };
});
- return newPoll;
+ if (!result.ok) {
+ return {
+ ok: false as const,
+ error: {
+ code: "OPEN_POLL_LIMIT_REACHED" as const,
+ ...(await getOpenPollLimitDetails({
+ usage: result.usage,
+ userId: ctx.user.id,
+ spaceId: poll.spaceId,
+ })),
+ },
+ };
+ }
+
+ return { ok: true as const, data: result.newPoll };
}),
});
diff --git a/apps/web/tests/open-poll-limit.spec.ts b/apps/web/tests/open-poll-limit.spec.ts
new file mode 100644
index 000000000..7cd6db2c6
--- /dev/null
+++ b/apps/web/tests/open-poll-limit.spec.ts
@@ -0,0 +1,208 @@
+import type { Page } from "@playwright/test";
+import { expect, test } from "@playwright/test";
+import { prisma } from "@rallly/database";
+import { LoginPage } from "./login-page";
+import { NewPollPage } from "./new-poll-page";
+import {
+ createUserInDb,
+ loginWithEmail,
+ upgradeSpaceToPro,
+} from "./test-utils";
+
+// Guests may have 1 open poll, free spaces 3 per organizer, Pro unlimited.
+// The limit is exercised through tRPC: the UI that explains it is not what
+// is under test here.
+
+const runId = Date.now().toString(36);
+const createdUserIds: string[] = [];
+
+test.afterAll(async () => {
+ await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
+});
+
+async function createFreeUser(name: string) {
+ const user = await createUserInDb({
+ email: `${name}-${runId}@example.com`,
+ name,
+ });
+ createdUserIds.push(user.id);
+ const space = await prisma.space.findFirstOrThrow({
+ where: { ownerId: user.id },
+ });
+ return { user, space };
+}
+
+async function seedOpenPolls({
+ userId,
+ spaceId,
+ count,
+}: {
+ userId: string;
+ spaceId: string;
+ count: number;
+}) {
+ const ids = Array.from(
+ { length: count },
+ (_, i) => `limit-${runId}-${userId}-${i}`,
+ );
+ await prisma.poll.createMany({
+ data: ids.map((id) => ({ id, title: id, userId, spaceId })),
+ });
+ return ids;
+}
+
+// The body and response shapes are the superjson transformer's.
+async function makePoll(page: Page) {
+ const res = await page.request.post("/api/trpc/polls.make", {
+ data: {
+ json: {
+ title: "Over the limit",
+ options: [{ startDate: "2099-01-01" }],
+ },
+ },
+ });
+ expect(res.ok()).toBe(true);
+ const body = await res.json();
+ return body.result.data.json as
+ | { ok: true; data: { id: string } }
+ | { ok: false; error: { code: string; usage: unknown; polls: unknown[] } };
+}
+
+async function reopenPoll(page: Page, pollId: string) {
+ const res = await page.request.post("/api/trpc/polls.reopen", {
+ data: { json: { pollId } },
+ });
+ expect(res.ok()).toBe(true);
+ return (await res.json()).result.data.json as
+ | { ok: true }
+ | { ok: false; error: { code: string; usage: unknown; polls: unknown[] } };
+}
+
+function countOpen(userId: string) {
+ return prisma.poll.count({
+ where: { userId, status: "open", deleted: false },
+ });
+}
+
+test.describe("free organizer", () => {
+ let page: Page;
+ let userId: string;
+ let spaceId: string;
+ let pollIds: string[];
+
+ test.beforeEach(async ({ browser }) => {
+ const { user, space } = await createFreeUser(
+ `free-${Math.random().toString(36).slice(2, 8)}`,
+ );
+ userId = user.id;
+ spaceId = space.id;
+ pollIds = await seedOpenPolls({ userId, spaceId, count: 3 });
+ page = await (await browser.newContext()).newPage();
+ await loginWithEmail(page, { email: user.email });
+ });
+
+ test.afterEach(async () => {
+ await page.context().close();
+ });
+
+ test("is refused a fourth open poll", async () => {
+ const result = await makePoll(page);
+ expect(result).toMatchObject({
+ ok: false,
+ error: {
+ code: "OPEN_POLL_LIMIT_REACHED",
+ usage: { tier: "hobby", limit: 3, openCount: 3 },
+ },
+ });
+ expect(!result.ok && result.error.polls).toHaveLength(3);
+ expect(await countOpen(userId)).toBe(3);
+ });
+
+ test("gets a slot back when a poll is closed", async () => {
+ await prisma.poll.update({
+ where: { id: pollIds[0] },
+ data: { status: "closed", closedReason: "manual" },
+ });
+ expect((await makePoll(page)).ok).toBe(true);
+ });
+
+ test("gets a slot back when a poll is scheduled", async () => {
+ await prisma.poll.update({
+ where: { id: pollIds[0] },
+ data: { status: "scheduled" },
+ });
+ expect((await makePoll(page)).ok).toBe(true);
+ });
+
+ test("gets a slot back when a poll is deleted", async () => {
+ await prisma.poll.update({
+ where: { id: pollIds[0] },
+ data: { deleted: true, deletedAt: new Date() },
+ });
+ expect((await makePoll(page)).ok).toBe(true);
+ });
+
+ test("cannot reopen a closed poll while at the limit", async () => {
+ const closedId = `limit-${runId}-${userId}-closed`;
+ await prisma.poll.create({
+ data: {
+ id: closedId,
+ title: closedId,
+ userId,
+ spaceId,
+ status: "closed",
+ closedReason: "manual",
+ },
+ });
+
+ expect(await reopenPoll(page, closedId)).toMatchObject({
+ ok: false,
+ error: { code: "OPEN_POLL_LIMIT_REACHED" },
+ });
+ expect(
+ (await prisma.poll.findUniqueOrThrow({ where: { id: closedId } })).status,
+ ).toBe("closed");
+ });
+
+ test("has no limit on Pro", async () => {
+ await upgradeSpaceToPro({ spaceId, userId, seats: 1 });
+ expect((await makePoll(page)).ok).toBe(true);
+ expect(await countOpen(userId)).toBe(4);
+ });
+});
+
+test("a guest is limited to one poll and keeps every poll on sign in", async ({
+ page,
+}) => {
+ const { user, space } = await createFreeUser(`adopter-${runId}`);
+ await seedOpenPolls({ userId: user.id, spaceId: space.id, count: 3 });
+
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ const pollPage = await newPollPage.create({ name: "Guest poll" });
+ await pollPage.closeShareDialog();
+
+ expect(await makePoll(page)).toMatchObject({
+ ok: false,
+ error: {
+ code: "OPEN_POLL_LIMIT_REACHED",
+ usage: { tier: "guest", limit: 1, openCount: 1 },
+ },
+ });
+
+ await page.getByRole("link", { name: "Login" }).click();
+ await new LoginPage(page).login({ email: user.email });
+ await expect(page.getByRole("heading", { name: "Guest poll" })).toBeVisible();
+
+ // Adoption is never blocked, so the organizer ends up over the limit.
+ expect(
+ await prisma.poll.count({
+ where: {
+ userId: user.id,
+ spaceId: space.id,
+ status: "open",
+ deleted: false,
+ },
+ }),
+ ).toBe(4);
+});