Skip to content

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

✨ Explain the open poll limit in a dialog (#3484)

Luke Vellaa3a300c5f0ab
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 39923cd2c..45c53d6a6 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -424,6 +424,7 @@
"generalSettingsAdminRoleRequired": "You need to be an admin to make changes to this space.",
"generalSettingsDescription": "Manage your space settings, including name, description, and other general preferences.",
"goTo": "Go to <b>{page}</b>",
+ "goToPolls": "Go to polls",
"guest": "Guest",
"guestPollAlertDescription": "<0>Create an account</0> or <1>login</1> to claim this poll.",
"guestPollAlertTitle": "Your administrator rights can be lost if you clear your cookies",
@@ -550,6 +551,7 @@
"login": "Login",
"loginDescription": "Login to your account to continue",
"loginNotConfigured": "Login is currently not configured.",
+ "logInOrSignUp": "Log in or sign up",
"loginOrSignUpDescription": "Log in to your account or create a new one",
"loginTitle": "Welcome",
"loginVerifyCheckEmail": "If an account exists with this email, you will receive a verification code at <b>{email}</b>",
@@ -681,6 +683,11 @@
"noWebhooksDescription": "Add a webhook to receive events on your own server",
"oidcAutoSignInDescription": "You are being redirected to the login page...",
"openPollCount": "{count, plural, other {# open}}",
+ "openPollLimitFreeDescription": "{planName} includes up to {limit} open polls at a time. Finalize or close polls to make room, or upgrade for unlimited open polls.",
+ "openPollLimitGuestDescription": "Guests can have one open poll at a time. Finalize or close polls to make room, or log in to increase your limit.",
+ "openPollLimitReachedTitle": "Open poll limit reached",
+ "openPollLimitUsage": "{openCount} of {limit}",
+ "openPolls": "Open polls",
"opensInNewTab": "(opens in new tab)",
"optional": "(optional)",
"optionalLabel": "(Optional)",
diff --git a/apps/web/src/app/[locale]/(optional-space)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
index 6dae3805d..96a0a8afc 100644
--- a/apps/web/src/app/[locale]/(optional-space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
@@ -5,6 +5,7 @@ import { TierProvider } from "@/features/billing/client";
import { PayWall } from "@/features/billing/components/pay-wall";
import { loadPayWallPricing } from "@/features/billing/loaders";
import { resolveSpaceTier } from "@/features/billing/utils";
+import { OpenPollLimitDialog } from "@/features/poll/limit/components/open-poll-limit-dialog";
import { isQuickCreateEnabled } from "@/features/quick-create/constants";
import { getActiveSpaceForUser } from "@/features/space/data";
import { loadOnboardingGate } from "@/features/space/loaders";
@@ -58,6 +59,7 @@ async function OptionalSpaceGate({ children }: { children: React.ReactNode }) {
<TierProvider tier={tier}>
{children}
<PayWall pricing={payWallPricing} />
+ <OpenPollLimitDialog />
</TierProvider>
</DeviceDateTimeProvider>
</UserProvider>
diff --git a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx b/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
index e51315f03..43f61676d 100644
--- a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
@@ -14,6 +14,7 @@ import { BrandStyle } from "@/features/branding/components/brand-style";
import { loadConferencingOptions } from "@/features/conferencing/loaders";
import { loadInstancePolicy } from "@/features/instance-policy/loaders";
import { CreatePoll } from "@/features/poll/components/create-poll";
+import { loadOptionalOpenPollUsage } from "@/features/poll/limit/loaders";
import { getActiveSpaceForUser } from "@/features/space/data";
import { isSpaceBrandingActive } from "@/features/space/utils";
import { Trans } from "@/i18n/client";
@@ -31,10 +32,13 @@ export default async function Page() {
redirect("/setup");
}
- const conferencing = await loadConferencingOptions({
- userId,
- email: user?.email ?? null,
- });
+ const [conferencing, openPollUsage] = await Promise.all([
+ loadConferencingOptions({
+ userId,
+ email: user?.email ?? null,
+ }),
+ loadOptionalOpenPollUsage(),
+ ]);
const primaryColor =
space?.primaryColor &&
@@ -50,6 +54,7 @@ export default async function Page() {
{primaryColor ? <BrandStyle primaryColor={primaryColor} /> : null}
<CreatePoll
conferencing={conferencing}
+ openPollUsage={openPollUsage}
nav={
<Breadcrumb>
<BreadcrumbList>
diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsx
index 290089e3e..7d2e255cc 100644
--- a/apps/web/src/app/[locale]/(space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(space)/layout.tsx
@@ -4,6 +4,7 @@ import { SessionRefresher } from "@/components/session-refresher";
import { TierProvider } from "@/features/billing/client";
import { PayWall } from "@/features/billing/components/pay-wall";
import { loadPayWallPricing } from "@/features/billing/loaders";
+import { OpenPollLimitDialog } from "@/features/poll/limit/components/open-poll-limit-dialog";
import { SpaceProvider } from "@/features/space/client";
import { loadActiveSpace } from "@/features/space/loaders";
import { UserProvider } from "@/features/user/client";
@@ -40,6 +41,7 @@ async function SpaceGate({ children }: { children: React.ReactNode }) {
<SpaceProvider space={space}>
{children}
<PayWall pricing={payWallPricing} />
+ <OpenPollLimitDialog />
</SpaceProvider>
</TierProvider>
</DateTimeProvider>
diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsx
index 3a3083489..b8b3cb111 100644
--- a/apps/web/src/features/billing/client.tsx
+++ b/apps/web/src/features/billing/client.tsx
@@ -58,7 +58,8 @@ export type PayWallTrigger = {
| "invite-dialog"
| "finalize-dialog"
| "poll-footer"
- | "polls-list";
+ | "polls-list"
+ | "poll-limit";
setting?: string;
action?: string;
pollId?: string;
diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsx
index 162f4a4aa..bb46b3829 100644
--- a/apps/web/src/features/poll/components/create-poll.tsx
+++ b/apps/web/src/features/poll/components/create-poll.tsx
@@ -26,6 +26,9 @@ import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings
import type { NewEventData } from "@/features/poll/components/forms/types";
import { SelectedOptionsCount } from "@/features/poll/components/selected-options-count";
import { SHARE_POLL_FLASH_KEY } from "@/features/poll/constants";
+import { showOpenPollLimit } from "@/features/poll/limit/client";
+import type { OpenPollUsage } from "@/features/poll/limit/types";
+import { isAtOpenPollLimit } from "@/features/poll/limit/utils";
import { useUser } from "@/features/user/client";
import { UserDropdown } from "@/features/user/components/user-dropdown";
import { Trans, useTranslation } from "@/i18n/client";
@@ -108,9 +111,11 @@ const CreatePollActions = ({
export const CreatePoll = ({
nav,
conferencing,
+ openPollUsage,
}: {
nav?: React.ReactNode;
conferencing?: ConferencingOptions | null;
+ openPollUsage?: OpenPollUsage | null;
}) => {
const { t } = useTranslation();
const router = useRouter();
@@ -160,6 +165,15 @@ export const CreatePoll = ({
const makePoll = trpc.polls.make.useMutation();
+ // Explain the limit before the organizer fills in a form they can't submit.
+ // The form persists, so it survives closing a poll to make room. The count
+ // is the server's at page load, so the poll created here can't trip it.
+ React.useEffect(() => {
+ if (openPollUsage && isAtOpenPollLimit(openPollUsage)) {
+ showOpenPollLimit("create", openPollUsage);
+ }
+ }, [openPollUsage]);
+
return (
<Form {...form}>
<header className="sticky top-0 z-20 bg-gray-100/90 p-3 backdrop-blur-md xl:bg-transparent xl:backdrop-blur-none dark:bg-gray-900/90 dark:xl:bg-transparent">
@@ -230,7 +244,9 @@ export const CreatePoll = ({
setCreatedPollId(res.data.id);
setFlash(SHARE_POLL_FLASH_KEY, res.data.id);
router.push(`/poll/${res.data.id}`);
- } else if (res.error.code === "INAPPROPRIATE_CONTENT") {
+ } else if (res.error.code === "OPEN_POLL_LIMIT_REACHED") {
+ showOpenPollLimit("create", res.error.usage);
+ } else {
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 b5e6571eb..e3a85dee6 100644
--- a/apps/web/src/features/poll/components/duplicate-dialog.tsx
+++ b/apps/web/src/features/poll/components/duplicate-dialog.tsx
@@ -12,6 +12,7 @@ import {
} from "@rallly/ui/dialog";
import { useRouter } from "next/navigation";
import { DuplicateForm } from "@/features/poll/components/duplicate-form";
+import { showOpenPollLimit } from "@/features/poll/limit/client";
import { Trans } from "@/i18n/client";
import { trpc } from "@/trpc/client";
@@ -49,7 +50,10 @@ export function DuplicateDialog({
onSuccess: async (res) => {
if (res.ok) {
router.push(`/poll/${res.data.id}`);
+ return;
}
+ props.onOpenChange?.(false);
+ showOpenPollLimit("duplicate", res.error.usage);
},
},
);
diff --git a/apps/web/src/features/poll/components/manage-poll.tsx b/apps/web/src/features/poll/components/manage-poll.tsx
index f3e8af220..811a4f33f 100644
--- a/apps/web/src/features/poll/components/manage-poll.tsx
+++ b/apps/web/src/features/poll/components/manage-poll.tsx
@@ -23,6 +23,10 @@ import { showPayWall, useIsFree } from "@/features/billing/client";
import { ProBadge } from "@/features/billing/components/pro-badge";
import { usePoll } from "@/features/poll/client";
import { DuplicateDialog } from "@/features/poll/components/duplicate-dialog";
+import {
+ getOpenPollLimitRefusal,
+ showOpenPollLimit,
+} from "@/features/poll/limit/client";
import { Trans } from "@/i18n/client";
import { trpc } from "@/trpc/client";
import { DeletePollDialog } from "./manage-poll/delete-poll-dialog";
@@ -34,7 +38,14 @@ function OpenCloseToggle() {
// The poll is served from the layout's server props; the refresh is
// what makes the new status show.
const openPoll = trpc.polls.reopen.useMutation({
- onSuccess: () => router.refresh(),
+ onSuccess: (res) => {
+ const refusal = getOpenPollLimitRefusal(res);
+ if (refusal) {
+ showOpenPollLimit("reopen", refusal.usage);
+ return;
+ }
+ router.refresh();
+ },
});
const closePoll = trpc.polls.close.useMutation({
onSuccess: () => router.refresh(),
diff --git a/apps/web/src/features/poll/components/poll-admin-menu.tsx b/apps/web/src/features/poll/components/poll-admin-menu.tsx
index bc5cd5f34..bab8347b1 100644
--- a/apps/web/src/features/poll/components/poll-admin-menu.tsx
+++ b/apps/web/src/features/poll/components/poll-admin-menu.tsx
@@ -26,6 +26,10 @@ import { usePoll } from "@/features/poll/client";
import { DuplicateDialog } from "@/features/poll/components/duplicate-dialog";
import { DeletePollDialog } from "@/features/poll/components/manage-poll/delete-poll-dialog";
import { useCsvExporter } from "@/features/poll/components/manage-poll/use-csv-exporter";
+import {
+ getOpenPollLimitRefusal,
+ showOpenPollLimit,
+} from "@/features/poll/limit/client";
import { Trans, useTranslation } from "@/i18n/client";
import { trpc } from "@/trpc/client";
@@ -44,7 +48,14 @@ export function PollAdminMenu() {
// These pages are server rendered, so a status change shows once they are
// fetched again.
const reopenPoll = trpc.polls.reopen.useMutation({
- onSuccess: () => router.refresh(),
+ onSuccess: (res) => {
+ const refusal = getOpenPollLimitRefusal(res);
+ if (refusal) {
+ showOpenPollLimit("reopen", refusal.usage);
+ return;
+ }
+ router.refresh();
+ },
});
const closePoll = trpc.polls.close.useMutation({
onSuccess: () => router.refresh(),
diff --git a/apps/web/src/features/poll/components/polls-infinite-list.tsx b/apps/web/src/features/poll/components/polls-infinite-list.tsx
index 2302732b4..f94f9d536 100644
--- a/apps/web/src/features/poll/components/polls-infinite-list.tsx
+++ b/apps/web/src/features/poll/components/polls-infinite-list.tsx
@@ -49,6 +49,10 @@ import { showPayWall, useIsFree } from "@/features/billing/client";
import { ProBadge } from "@/features/billing/components/pro-badge";
import { DuplicateDialog } from "@/features/poll/components/duplicate-dialog";
import { PollStatusIcon } from "@/features/poll/components/poll-status-icon";
+import {
+ getOpenPollLimitRefusal,
+ showOpenPollLimit,
+} from "@/features/poll/limit/client";
import type { PollClosedReason, PollStatus } from "@/features/poll/schema";
import { Trans, useTranslation } from "@/i18n/client";
import { TimeRange } from "@/lib/datetime/time";
@@ -156,7 +160,7 @@ function PollRowActions({
const refresh = { onSuccess: () => router.refresh() };
const deletePoll = trpc.polls.markAsDeleted.useMutation(refresh);
const closePoll = trpc.polls.close.useMutation(refresh);
- const reopenPoll = trpc.polls.reopen.useMutation(refresh);
+ const reopenPoll = trpc.polls.reopen.useMutation();
return (
<div className="relative z-10 flex items-center gap-x-1">
<CopyLinkButton href={shortUrl(`/invite/${id}`)} className="size-8" />
@@ -223,12 +227,31 @@ function PollRowActions({
{status === "closed" && (
<DropdownMenuItem
onClick={() => {
- toast.promise(reopenPoll.mutateAsync({ pollId: id }), {
- loading: <Trans i18nKey="loading" defaults="Loading..." />,
- success: (
- <Trans i18nKey="pollReopened" defaults="Poll reopened" />
- ),
- });
+ const toastId = toast.loading(
+ <Trans i18nKey="loading" defaults="Loading..." />,
+ );
+ reopenPoll.mutate(
+ { pollId: id },
+ {
+ onSuccess: (res) => {
+ const refusal = getOpenPollLimitRefusal(res);
+ if (refusal) {
+ toast.dismiss(toastId);
+ showOpenPollLimit("reopen", refusal.usage);
+ return;
+ }
+ toast.success(
+ <Trans
+ i18nKey="pollReopened"
+ defaults="Poll reopened"
+ />,
+ { id: toastId },
+ );
+ router.refresh();
+ },
+ onError: () => toast.dismiss(toastId),
+ },
+ );
}}
>
<PlayIcon />
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index f278ed8d0..7613ec3dc 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -327,70 +327,6 @@ 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,
@@ -421,14 +357,68 @@ export const getPolls = async ({
prisma.poll.count({ where }),
prisma.poll.findMany({
where,
- select: pollListItemSelect,
+ 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,
+ },
+ },
+ },
orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
skip: (page - 1) * pageSize,
take: pageSize,
}),
]);
- const transformedPolls = await toPollListItems(polls);
+ 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 totalPages = Math.ceil(totalCount / pageSize);
const hasNextPage = page < totalPages;
diff --git a/apps/web/src/features/poll/limit/client.tsx b/apps/web/src/features/poll/limit/client.tsx
new file mode 100644
index 000000000..2426bb4d0
--- /dev/null
+++ b/apps/web/src/features/poll/limit/client.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { create } from "zustand";
+import type { OpenPollUsage } from "./types";
+
+export type OpenPollLimitSource = "create" | "reopen" | "duplicate";
+
+type OpenPollLimitStore = {
+ open: {
+ source: OpenPollLimitSource;
+ usage: OpenPollUsage;
+ /** The page it was opened on: leaving it closes the dialog */
+ pathname: string;
+ } | null;
+ show: (source: OpenPollLimitSource, usage: OpenPollUsage) => void;
+ hide: () => void;
+};
+
+export const useOpenPollLimitStore = create<OpenPollLimitStore>((set) => ({
+ open: null,
+ show: (source, usage) =>
+ set({ open: { source, usage, pathname: window.location.pathname } }),
+ hide: () => set({ open: null }),
+}));
+
+/**
+ * Opens the app-wide limit dialog with the usage it shows: from a refusal,
+ * or from the page's loader when the organizer is already at the limit.
+ */
+export const showOpenPollLimit = (
+ source: OpenPollLimitSource,
+ usage: OpenPollUsage,
+) => useOpenPollLimitStore.getState().show(source, usage);
+
+/** The refusal a create, reopen or duplicate returned, or null. */
+export function getOpenPollLimitRefusal<E extends { code: string }>(result: {
+ ok: boolean;
+ error?: E;
+}) {
+ return !result.ok && result.error?.code === "OPEN_POLL_LIMIT_REACHED"
+ ? (result.error as Extract<E, { code: "OPEN_POLL_LIMIT_REACHED" }>)
+ : null;
+}
diff --git a/apps/web/src/features/poll/limit/components/open-poll-limit-dialog.tsx b/apps/web/src/features/poll/limit/components/open-poll-limit-dialog.tsx
new file mode 100644
index 000000000..3660839c8
--- /dev/null
+++ b/apps/web/src/features/poll/limit/components/open-poll-limit-dialog.tsx
@@ -0,0 +1,234 @@
+"use client";
+
+import { posthog } from "@rallly/posthog/client";
+import { buttonVariants, cn } from "@rallly/ui";
+import { Button } from "@rallly/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ useDialog,
+} from "@rallly/ui/dialog";
+import { Progress } from "@rallly/ui/progress";
+import { BarChart2Icon } from "lucide-react";
+import { usePathname } from "next/navigation";
+import React from "react";
+import { Link } from "@/components/link";
+import { LoginLink } from "@/components/login-link";
+import { PageIcon } from "@/components/page-icons";
+import { primePayWall, usePayWallStore } from "@/features/billing/client";
+import { PayWallDialog } from "@/features/billing/components/pay-wall-dialog";
+import { PLAN_NAMES } from "@/features/billing/constants";
+import type { OpenPollLimitSource } from "@/features/poll/limit/client";
+import { useOpenPollLimitStore } from "@/features/poll/limit/client";
+import type { OpenPollUsage } from "@/features/poll/limit/types";
+import { Trans, useTranslation } from "@/i18n/client";
+
+/**
+ * Single, app-wide instance. Open it from anywhere with
+ * `showOpenPollLimit()`.
+ */
+export function OpenPollLimitDialog() {
+ const open = useOpenPollLimitStore((state) => state.open);
+ const hide = useOpenPollLimitStore((state) => state.hide);
+ // A refused reopen or duplicate leaves the organizer on a page that still
+ // works, so it can be dismissed. On /new there is nothing left to do but
+ // make room, register or upgrade, so the only ways out are its own links.
+ const dismissible = open !== null && open.source !== "create";
+
+ // The dialog's links close it by leaving the page. Clearing the store on
+ // the route change rather than on click keeps it up if that navigation
+ // fails or is cancelled. Each layout mounts its own instance, so the page
+ // it was opened on comes from the store, not from this instance's mount.
+ const pathname = usePathname();
+ React.useEffect(() => {
+ if (open && pathname !== open.pathname) {
+ hide();
+ }
+ }, [open, pathname, hide]);
+
+ return (
+ <Dialog
+ open={open !== null}
+ disablePointerDismissal={!dismissible}
+ onOpenChange={(open) => {
+ if (!open && dismissible) {
+ hide();
+ }
+ }}
+ >
+ <DialogContent size="md" showCloseButton={dismissible}>
+ {open ? (
+ <OpenPollLimitContent source={open.source} usage={open.usage} />
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function OpenPollLimitContent({
+ source,
+ usage: data,
+}: {
+ source: OpenPollLimitSource;
+ usage: OpenPollUsage;
+}) {
+ // The pay wall nests here so it stacks above this dialog and this dialog
+ // is still there when the pay wall closes.
+ const payWall = useDialog();
+ const payWallPricing = usePayWallStore((state) => state.pricing);
+
+ const eventProperties = React.useMemo(
+ () => ({
+ tier: data.tier,
+ open_count: data.openCount,
+ limit: data.limit,
+ source,
+ }),
+ [data, source],
+ );
+
+ React.useEffect(() => {
+ posthog?.capture("poll_limit:wall_view", eventProperties);
+ }, [eventProperties]);
+
+ if (data.limit === null) {
+ return null;
+ }
+
+ return (
+ <>
+ <DialogHeader>
+ <div className="flex items-center gap-3">
+ <PageIcon size="sm" color="primary">
+ <BarChart2Icon />
+ </PageIcon>
+ <DialogTitle>
+ <Trans
+ i18nKey="openPollLimitReachedTitle"
+ defaults="Open poll limit reached"
+ />
+ </DialogTitle>
+ </div>
+ <DialogDescription className="mt-2">
+ {data.tier === "guest" ? (
+ <Trans
+ i18nKey="openPollLimitGuestDescription"
+ defaults="Guests can have one open poll at a time. Finalize or close polls to make room, or log in to increase your limit."
+ />
+ ) : (
+ <Trans
+ i18nKey="openPollLimitFreeDescription"
+ defaults="{planName} includes up to {limit} open polls at a time. Finalize or close polls to make room, or upgrade for unlimited open polls."
+ values={{ planName: PLAN_NAMES.HOBBY, limit: data.limit }}
+ />
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <OpenPollUsageBar openCount={data.openCount} limit={data.limit} />
+ <DialogFooter>
+ {data.tier !== "guest" ? (
+ <Link
+ href="/polls"
+ className={buttonVariants()}
+ onClick={() => {
+ posthog?.capture("poll_limit:go_to_polls_click", eventProperties);
+ }}
+ >
+ <Trans i18nKey="goToPolls" defaults="Go to polls" />
+ </Link>
+ ) : null}
+ <OpenPollLimitActions
+ usage={data}
+ onRegisterClick={() => {
+ posthog?.capture("poll_limit:register_click", eventProperties);
+ }}
+ onUpgradeClick={() => {
+ posthog?.capture("poll_limit:upgrade_click", eventProperties);
+ primePayWall({ from: "poll-limit" });
+ payWall.trigger();
+ }}
+ />
+ </DialogFooter>
+ <PayWallDialog
+ pricing={payWallPricing}
+ isOpen={payWall.dialogProps.open}
+ onOpenChange={payWall.dialogProps.onOpenChange}
+ />
+ </>
+ );
+}
+
+function OpenPollUsageBar({
+ openCount,
+ limit,
+}: {
+ openCount: number;
+ limit: number;
+}) {
+ const { t } = useTranslation();
+ const isAtLimit = openCount >= limit;
+ const usageText = t("openPollLimitUsage", {
+ defaultValue: "{openCount} of {limit}",
+ openCount,
+ limit,
+ });
+ return (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between gap-4 text-sm">
+ <span className="font-medium">
+ <Trans i18nKey="openPolls" defaults="Open polls" />
+ </span>
+ <span
+ className={cn(
+ "text-muted-foreground tabular-nums",
+ isAtLimit && "text-destructive",
+ )}
+ >
+ {usageText}
+ </span>
+ </div>
+ <Progress
+ value={Math.min((openCount / limit) * 100, 100)}
+ aria-label={t("openPolls", { defaultValue: "Open polls" })}
+ getAriaValueText={() => usageText}
+ className="h-2"
+ indicatorClassName={cn(isAtLimit && "bg-destructive bg-none")}
+ />
+ </div>
+ );
+}
+
+function OpenPollLimitActions({
+ usage,
+ onRegisterClick,
+ onUpgradeClick,
+}: {
+ usage: OpenPollUsage;
+ onRegisterClick: () => void;
+ onUpgradeClick: () => void;
+}) {
+ if (usage.tier === "guest") {
+ return (
+ <LoginLink
+ className={buttonVariants({ variant: "primary" })}
+ onClick={onRegisterClick}
+ >
+ <Trans i18nKey="logInOrSignUp" defaults="Log in or sign up" />
+ </LoginLink>
+ );
+ }
+
+ if (usage.tier === "hobby") {
+ return (
+ <Button variant="primary" onClick={onUpgradeClick}>
+ <Trans i18nKey="upgrade" defaults="Upgrade" />
+ </Button>
+ );
+ }
+
+ return null;
+}
diff --git a/apps/web/src/features/poll/limit/data.ts b/apps/web/src/features/poll/limit/data.ts
index c64192d4e..3de3e062b 100644
--- a/apps/web/src/features/poll/limit/data.ts
+++ b/apps/web/src/features/poll/limit/data.ts
@@ -2,13 +2,8 @@ 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 type { OpenPollTier, OpenPollUsage } from "./types";
import { getOpenPollLimit } from "./utils";
// The organizer is the tenant: the space only narrows which of their polls
@@ -45,20 +40,3 @@ export async function getOpenPollUsage({
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
index a19c4009c..4535a876c 100644
--- a/apps/web/src/features/poll/limit/loaders.ts
+++ b/apps/web/src/features/poll/limit/loaders.ts
@@ -4,16 +4,20 @@ 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";
+import { isOpenPollLimitEnabled } from "./constants";
+import { getOpenPollUsage } from "./data";
+import { getOpenPollTier } 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.
+ * guest's polls without a space, a member's in their active space. Null
+ * without a session or an active space, or while the limit is off.
*/
-export const loadOptionalOpenPollLimit = cache(async () => {
+export const loadOptionalOpenPollUsage = cache(async () => {
+ if (!isOpenPollLimitEnabled) {
+ return null;
+ }
+
const state = await getSessionState();
if (state.status !== "authenticated") {
@@ -32,13 +36,9 @@ export const loadOptionalOpenPollLimit = cache(async () => {
return null;
}
- const scope = { userId: user.id, spaceId: space?.id ?? null };
- const usage = await getOpenPollUsage({
- ...scope,
+ return getOpenPollUsage({
+ userId: user.id,
+ spaceId: space?.id ?? null,
tier: getOpenPollTier(space?.tier ?? null),
});
-
- return isAtOpenPollLimit(usage)
- ? getOpenPollLimitDetails({ ...scope, usage })
- : { usage, polls: [] };
});
diff --git a/apps/web/src/features/poll/limit/types.ts b/apps/web/src/features/poll/limit/types.ts
index 92bc25849..8e5875e7a 100644
--- a/apps/web/src/features/poll/limit/types.ts
+++ b/apps/web/src/features/poll/limit/types.ts
@@ -1,4 +1,3 @@
-import type { PollListItem } from "@/features/poll/types";
import type { SpaceTier } from "@/features/space/schema";
export type OpenPollTier = "guest" | SpaceTier;
@@ -9,9 +8,3 @@ export type OpenPollUsage = {
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/types.ts b/apps/web/src/features/poll/types.ts
index 024babbcf..83a6dc59b 100644
--- a/apps/web/src/features/poll/types.ts
+++ b/apps/web/src/features/poll/types.ts
@@ -1,6 +1,5 @@
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";
@@ -68,6 +67,3 @@ 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/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index c1dadeb8d..c8fe76c84 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -38,7 +38,6 @@ import {
getPolls,
hasPollAdminAccess,
} from "@/features/poll/data";
-import { getOpenPollLimitDetails } from "@/features/poll/limit/data";
import {
assertOpenPollCapacity,
checkOpenPollCapacity,
@@ -403,11 +402,7 @@ export const polls = router({
ok: false as const,
error: {
code: "OPEN_POLL_LIMIT_REACHED" as const,
- ...(await getOpenPollLimitDetails({
- usage: poll.usage,
- userId: ctx.user.id,
- spaceId: spaceId ?? null,
- })),
+ usage: poll.usage,
},
};
}
@@ -1604,11 +1599,7 @@ export const polls = router({
spaceId: target.spaceId,
});
if (!capacity.ok) {
- return {
- usage: capacity.usage,
- userId: target.userId,
- spaceId: target.spaceId,
- };
+ return capacity.usage;
}
}
@@ -1669,14 +1660,9 @@ export const polls = router({
});
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 },
+ error: { code: "OPEN_POLL_LIMIT_REACHED" as const, usage: refusal },
};
}
@@ -1854,11 +1840,7 @@ export const polls = router({
ok: false as const,
error: {
code: "OPEN_POLL_LIMIT_REACHED" as const,
- ...(await getOpenPollLimitDetails({
- usage: result.usage,
- userId: ctx.user.id,
- spaceId: poll.spaceId,
- })),
+ usage: result.usage,
},
};
}
diff --git a/apps/web/tests/open-poll-limit.spec.ts b/apps/web/tests/open-poll-limit.spec.ts
index 7cd6db2c6..489022a72 100644
--- a/apps/web/tests/open-poll-limit.spec.ts
+++ b/apps/web/tests/open-poll-limit.spec.ts
@@ -65,7 +65,7 @@ async function makePoll(page: Page) {
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[] } };
+ | { ok: false; error: { code: string; usage: unknown } };
}
async function reopenPoll(page: Page, pollId: string) {
@@ -75,7 +75,7 @@ async function reopenPoll(page: Page, pollId: string) {
expect(res.ok()).toBe(true);
return (await res.json()).result.data.json as
| { ok: true }
- | { ok: false; error: { code: string; usage: unknown; polls: unknown[] } };
+ | { ok: false; error: { code: string; usage: unknown } };
}
function countOpen(userId: string) {
@@ -106,15 +106,13 @@ test.describe("free organizer", () => {
});
test("is refused a fourth open poll", async () => {
- const result = await makePoll(page);
- expect(result).toMatchObject({
+ expect(await makePoll(page)).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);
});
@@ -164,6 +162,60 @@ test.describe("free organizer", () => {
).toBe("closed");
});
+ test("is shown the limit with the open polls and an upgrade", async () => {
+ await page.goto("/new");
+ const dialog = page.getByRole("dialog", {
+ name: "Open poll limit reached",
+ });
+ await expect(dialog).toBeVisible();
+ await expect(
+ dialog.getByRole("progressbar", { name: "Open polls" }),
+ ).toHaveAttribute("aria-valuetext", "3 of 3");
+ await page.keyboard.press("Escape");
+ await expect(dialog).toBeVisible();
+ await page.screenshot({
+ path: "test-results/open-poll-limit-free.png",
+ });
+
+ await dialog.getByRole("button", { name: "Upgrade" }).click();
+ await expect(
+ page.getByRole("button", { name: "Continue to checkout" }),
+ ).toBeVisible();
+ });
+
+ test("can leave the limit for their polls", async () => {
+ await page.goto("/new");
+ await page
+ .getByRole("dialog", { name: "Open poll limit reached" })
+ .getByRole("link", { name: "Go to polls" })
+ .click();
+ await expect(page).toHaveURL(/\/polls/);
+ await expect(
+ page.getByRole("dialog", { name: "Open poll limit reached" }),
+ ).toBeHidden();
+ });
+
+ test("is shown the limit when reopening from the poll page", async () => {
+ const closedId = `limit-${runId}-${userId}-closed-ui`;
+ await prisma.poll.create({
+ data: {
+ id: closedId,
+ title: "Closed poll",
+ userId,
+ spaceId,
+ status: "closed",
+ closedReason: "manual",
+ },
+ });
+
+ await page.goto(`/poll/${closedId}`);
+ await page.getByRole("button", { name: "Manage" }).click();
+ await page.getByRole("menuitem", { name: "Reopen poll" }).click();
+ await expect(
+ page.getByRole("dialog", { name: "Open poll limit reached" }),
+ ).toBeVisible();
+ });
+
test("has no limit on Pro", async () => {
await upgradeSpaceToPro({ spaceId, userId, seats: 1 });
expect((await makePoll(page)).ok).toBe(true);
@@ -181,6 +233,7 @@ test("a guest is limited to one poll and keeps every poll on sign in", async ({
await newPollPage.goto();
const pollPage = await newPollPage.create({ name: "Guest poll" });
await pollPage.closeShareDialog();
+ const guestPollUrl = page.url();
expect(await makePoll(page)).toMatchObject({
ok: false,
@@ -190,6 +243,23 @@ test("a guest is limited to one poll and keeps every poll on sign in", async ({
},
});
+ await newPollPage.goto();
+ const dialog = page.getByRole("dialog", {
+ name: "Open poll limit reached",
+ });
+ await expect(
+ dialog.getByRole("progressbar", { name: "Open polls" }),
+ ).toHaveAttribute("aria-valuetext", "1 of 1");
+ await expect(
+ dialog.getByRole("link", { name: "Log in or sign up" }),
+ ).toBeVisible();
+ await page.screenshot({ path: "test-results/open-poll-limit-guest.png" });
+ await expect(dialog.getByRole("link", { name: "Go to polls" })).toHaveCount(
+ 0,
+ );
+ await page.goto(guestPollUrl);
+ await expect(page.getByRole("heading", { name: "Guest poll" })).toBeVisible();
+
await page.getByRole("link", { name: "Login" }).click();
await new LoginPage(page).login({ email: user.email });
await expect(page.getByRole("heading", { name: "Guest poll" })).toBeVisible();
@@ -205,4 +275,12 @@ test("a guest is limited to one poll and keeps every poll on sign in", async ({
},
}),
).toBe(4);
+
+ await new NewPollPage(page).goto();
+ await expect(
+ page
+ .getByRole("dialog", { name: "Open poll limit reached" })
+ .getByRole("progressbar", { name: "Open polls" }),
+ ).toHaveAttribute("aria-valuetext", "4 of 3");
+ await page.screenshot({ path: "test-results/open-poll-limit-over.png" });
});
diff --git a/packages/ui/src/progress.tsx b/packages/ui/src/progress.tsx
index 7151f6b6f..86131ead5 100644
--- a/packages/ui/src/progress.tsx
+++ b/packages/ui/src/progress.tsx
@@ -6,9 +6,10 @@ import { cn } from "./lib/utils";
function Progress({
className,
+ indicatorClassName,
value,
...props
-}: ProgressPrimitive.Root.Props) {
+}: ProgressPrimitive.Root.Props & { indicatorClassName?: string }) {
return (
<ProgressPrimitive.Root
data-slot="progress"
@@ -25,7 +26,10 @@ function Progress({
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
- className="h-full bg-linear-to-r from-primary/50 to-primary transition-all"
+ className={cn(
+ "h-full bg-linear-to-r from-primary/50 to-primary transition-all",
+ indicatorClassName,
+ )}
/>
</ProgressPrimitive.Track>
</ProgressPrimitive.Root>