Skip to content

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

♻️ Serve the invite page from server components and server actions (#3293)

Luke Vellaff90985b3e67
diff --git a/apps/web/biome.json b/apps/web/biome.json
index f8fd43b7b..59257228b 100644
--- a/apps/web/biome.json
+++ b/apps/web/biome.json
@@ -256,10 +256,8 @@
{
"includes": [
"src/app/*/(optional-space)/new/page.tsx",
- "src/app/*/(optional-space)/poll/*/layout.tsx",
"src/app/*/(space)/settings/preferences/components/date-time-preferences.tsx",
"src/app/*/accept-invite/*/page.tsx",
- "src/app/*/invite/*/page.tsx",
"src/app/*/control-panel/users/page.tsx",
"src/app/*/e/*/components/rsvp-area.tsx"
],
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index f20807bcc..2e5cebfcd 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -153,6 +153,7 @@
"comments": "Comments",
"commentsComposerPlaceholder": "Write a comment…",
"commentsComposerVisibility": "Visible to everyone",
+ "commentsDisabledError": "Comments are turned off for this poll.",
"commentsSettingDescription": "Allow participants to post public comments on the poll.",
"commentsSettingTitle": "Comments",
"commentsSheetDescription": "View and add comments on this poll",
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
index 2a32598e4..0b6dca2a1 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
@@ -7,13 +7,11 @@ import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { Link } from "@/components/link";
import { useModalContext } from "@/components/modal/modal-provider";
+import { useParticipants } from "@/features/poll/client";
import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
import { useUpdatePollMutation } from "@/features/poll/components/mutations";
-import {
- filterParticipantsByVote,
- useParticipants,
-} from "@/features/poll/components/participants-provider";
import { usePoll } from "@/features/poll/components/poll-context";
+import { filterParticipantsByVote } from "@/features/poll/utils";
import { Trans, useTranslation } from "@/i18n/client";
import { dayjs } from "@/lib/dayjs";
import {
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
index 5a0414099..387052160 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
@@ -6,10 +6,9 @@ import { Form } from "@rallly/ui/form";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { Link } from "@/components/link";
-import { usePoll } from "@/features/poll/client";
+import { useParticipants, usePoll } from "@/features/poll/client";
import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
import { useUpdatePollMutation } from "@/features/poll/components/mutations";
-import { useParticipants } from "@/features/poll/components/participants-provider";
import { Trans } from "@/i18n/client";
const Page = () => {
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.tsx
index 2140f5623..00bccb116 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,59 +1,57 @@
-import { prisma } from "@rallly/database";
-import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
-import { TRPCError } from "@trpc/server";
import type { Metadata } from "next";
-import { notFound, redirect } from "next/navigation";
-
+import { notFound } from "next/navigation";
+import { Suspense } from "react";
+import { PollProvider } from "@/features/poll/client";
import { PollLayout } from "@/features/poll/components/poll-layout";
-import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";
-
-export default async function Layout(
- props: React.PropsWithChildren<{ params: Promise<{ urlId: string }> }>,
-) {
- const params = await props.params;
-
- const { children } = props;
-
- const trpc = await createPublicSSRHelper();
-
- const poll = await trpc.polls.get
- .fetch({ urlId: params.urlId })
- .catch((e) => {
- if (e instanceof TRPCError && e.code === "NOT_FOUND") {
- notFound();
- }
- throw e;
- });
-
- if (!poll.canManage) {
- redirect(`/invite/${params.urlId}`);
- }
-
- await Promise.all([
- trpc.polls.participants.list.prefetch({ pollId: params.urlId }),
- trpc.polls.comments.list.prefetch({ pollId: params.urlId }),
- ]);
+import { loadAdminPoll, loadPollAvailability } from "@/features/poll/loaders";
+
+async function AdminPollLayout({
+ params,
+ children,
+}: {
+ params: Promise<{ urlId: string }>;
+ children: React.ReactNode;
+}) {
+ const { urlId } = await params;
+ const { poll, participants, comments } = await loadAdminPoll(urlId);
return (
- <HydrationBoundary state={dehydrate(trpc.queryClient)}>
+ <PollProvider
+ poll={poll}
+ participants={participants}
+ comments={comments}
+ viewerRole="admin"
+ >
<PollLayout>{children}</PollLayout>
- </HydrationBoundary>
+ </PollProvider>
+ );
+}
+
+export default function Layout({
+ params,
+ children,
+}: {
+ params: Promise<{ urlId: string }>;
+ children: React.ReactNode;
+}) {
+ return (
+ <Suspense>
+ <AdminPollLayout params={params}>{children}</AdminPollLayout>
+ </Suspense>
);
}
export async function generateMetadata(props: {
params: Promise<{ locale: string; urlId: string }>;
}): Promise<Metadata> {
- const params = await props.params;
- const poll = await prisma.poll.findUnique({
- where: { id: params.urlId },
- select: { title: true },
- });
+ const { urlId } = await props.params;
+ const availability = await loadPollAvailability(urlId);
- if (!poll) {
+ if (!availability) {
notFound();
}
+
return {
- title: poll.title,
+ title: availability.title,
};
}
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/invite-page-loader.tsx b/apps/web/src/app/[locale]/invite/[urlId]/invite-page-loader.tsx
deleted file mode 100644
index 4f0e90cd2..000000000
--- a/apps/web/src/app/[locale]/invite/[urlId]/invite-page-loader.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-"use client";
-import dynamic from "next/dynamic";
-import { PollBrandingFromContext } from "@/features/poll/components/poll-branding";
-
-// Deliberately client-only: the page is built around Intl-formatted dates
-// and the viewer's timezone, neither of which can be rendered on the server
-// (no zone cookie on first visit, and Intl output differs across engines).
-// The page's tRPC prefetches still matter — they seed the client query cache
-// via HydrationBoundary so useSuspenseQuery resolves without a round-trip.
-const InvitePage = dynamic(
- () => import("./invite-page").then((mod) => mod.InvitePage),
- { ssr: false },
-);
-
-export function InvitePageLoader({
- footerLinks,
-}: {
- footerLinks: { label: string; href: string }[];
-}) {
- return (
- <>
- <PollBrandingFromContext />
- <InvitePage footerLinks={footerLinks} />
- </>
- );
-}
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
index e66e872bc..48c2d8041 100644
--- a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
+++ b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
@@ -3,6 +3,7 @@ import { buttonVariants, cn } from "@rallly/ui";
import { Alert, AlertAction, AlertDescription } from "@rallly/ui/alert";
import { ArrowUpRightIcon, CrownIcon } from "lucide-react";
import { Link } from "@/components/link";
+import { Spinner } from "@/components/spinner";
import { usePoll } from "@/features/poll/client";
import { CommentsSheet } from "@/features/poll/components/comments-sheet";
import { EventCard } from "@/features/poll/components/event-card";
@@ -14,6 +15,7 @@ import {
} from "@/features/poll/components/voting-form";
import { useUser } from "@/features/user/client";
import { Trans } from "@/i18n/client";
+import { useHydrated } from "@/lib/datetime/use-hydrated";
const FloatingComments = () => {
const votingForm = useVotingForm();
@@ -66,11 +68,27 @@ const GoToApp = () => {
);
};
+/**
+ * The voting grid depends on two things the server cannot know: the
+ * viewer's zone and Intl output for the option dates, and the viewport
+ * breakpoint that picks the desktop or mobile layout. Rather than render the
+ * rest of the page around a placeholder and let the grid shift it, the
+ * whole page waits for hydration behind the same spinner the route streams
+ * while its data loads, so there is one loader from first byte to
+ * interactive. The page's server props are already in the tree by then, so
+ * nothing else is fetched.
+ */
export function InvitePage({
footerLinks,
}: {
footerLinks: { label: string; href: string }[];
}) {
+ const hydrated = useHydrated();
+
+ if (!hydrated) {
+ return <InvitePageLoading />;
+ }
+
return (
<div className="page-bg-gray-100 h-dvh overflow-auto p-3 lg:p-6 dark:bg-gray-900">
<main
@@ -90,3 +108,11 @@ export function InvitePage({
</div>
);
}
+
+export function InvitePageLoading() {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <Spinner />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/loading.tsx b/apps/web/src/app/[locale]/invite/[urlId]/loading.tsx
deleted file mode 100644
index 7774fe2ac..000000000
--- a/apps/web/src/app/[locale]/invite/[urlId]/loading.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { Spinner } from "@/components/spinner";
-
-export default function Loading() {
- return (
- <div className="flex h-screen items-center justify-center">
- <Spinner />
- </div>
- );
-}
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
index 741c2fc8b..485df399f 100644
--- a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
+++ b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
@@ -1,164 +1,130 @@
-import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
-import { cache } from "react";
+import { Suspense } from "react";
import { SessionRefresher } from "@/components/session-refresher";
import { loadFooterLinks } from "@/features/instance-settings/loaders";
-import { PermissionProvider } from "@/features/poll/client";
+import { PollProvider } from "@/features/poll/client";
+import { PollBrandingFromContext } from "@/features/poll/components/poll-branding";
+import { LegacyPollContextProvider } from "@/features/poll/components/poll-context-provider";
+import { VisibilityProvider } from "@/features/poll/components/visibility";
import { InviteOpenRecorder } from "@/features/poll/invite/components/invite-open-recorder";
-import type { PollUnavailableReason } from "@/features/poll/invite/components/poll-unavailable";
import { PollUnavailable } from "@/features/poll/invite/components/poll-unavailable";
-import { loadParticipantIdsByToken } from "@/features/poll/loaders";
+import { loadInvitePoll, loadPollAvailability } from "@/features/poll/loaders";
import { UserProvider } from "@/features/user/client";
import { getLocale } from "@/i18n/server/get-locale";
-import { getSession } from "@/lib/auth";
import { DeviceDateTimeProvider } from "@/lib/datetime/device";
import { getDeviceDateTimeConfig } from "@/lib/datetime/server";
-import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";
-import { InvitePageLoader } from "./invite-page-loader";
-import Providers from "./providers";
-
-const getPollMetadata = cache(async (urlId: string) => {
- const poll = await prisma.poll.findUnique({
- where: { id: urlId },
- select: {
- id: true,
- title: true,
- deleted: true,
- user: {
- select: {
- name: true,
- banned: true,
- },
- },
- space: {
- select: {
- owner: {
- select: {
- banned: true,
- },
- },
- },
- },
- },
- });
+import { InvitePage, InvitePageLoading } from "./invite-page";
- if (!poll) {
- notFound();
- }
-
- // A poll that exists but must not be served gets its own page instead of
- // a 404: the viewer of a banned creator's poll is usually a scam target
- // and needs to be told so, and a deleted poll's viewer deserves better
- // than "page not found". The space owner counts as a creator too: an API
- // key holder can organize polls under any member, and banning the payer
- // must take every link in the space down with it.
- const unavailable: PollUnavailableReason | null = poll.deleted
- ? "deleted"
- : poll.user?.banned || poll.space?.owner.banned
- ? "removed"
- : null;
-
- return { poll, unavailable };
-});
-
-export default async function Page(props: {
+type PageProps = {
params: Promise<{ urlId: string }>;
searchParams: Promise<{
token?: string | string[];
invite?: string | string[];
}>;
-}) {
- const params = await props.params;
+};
- const [{ unavailable }, searchParams] = await Promise.all([
- getPollMetadata(params.urlId),
- props.searchParams,
- ]);
+async function InvitePageContent({ params, searchParams }: PageProps) {
+ const { urlId } = await params;
- if (unavailable) {
- const footerLinks = await loadFooterLinks();
- return <PollUnavailable reason={unavailable} footerLinks={footerLinks} />;
+ const [availability, { token: tokenParam, invite: inviteParam }] =
+ await Promise.all([loadPollAvailability(urlId), searchParams]);
+
+ if (!availability) {
+ notFound();
}
- // The SSR helper reads the session; an unavailable poll never needs it.
- const trpc = await createPublicSSRHelper();
+ if (availability.unavailable) {
+ const footerLinks = await loadFooterLinks();
+ return (
+ <PollUnavailable
+ reason={availability.unavailable}
+ footerLinks={footerLinks}
+ />
+ );
+ }
// `invite` is the param older invite emails carry; both name the same
// token and the client reads them the same way. A repeated param arrives
// as an array; only a single value is a token.
- const token = [searchParams.token, searchParams.invite].find(
+ const token = [tokenParam, inviteParam].find(
(value): value is string => typeof value === "string",
);
const [
+ { poll, participants, comments, linkedParticipantIds, user },
locale,
- session,
deviceDateTimeConfig,
footerLinks,
- linkedParticipantIds,
] = await Promise.all([
+ loadInvitePoll({ pollId: urlId, token }),
getLocale(),
- getSession(),
getDeviceDateTimeConfig(),
loadFooterLinks(),
- token ? loadParticipantIdsByToken(params.urlId, token) : [],
- trpc.polls.get.prefetch({ urlId: params.urlId }),
- trpc.polls.participants.list.prefetch({ pollId: params.urlId, token }),
- trpc.polls.comments.list.prefetch({ pollId: params.urlId }),
]);
return (
- <HydrationBoundary state={dehydrate(trpc.queryClient)}>
+ <>
<SessionRefresher />
- {token ? (
- <InviteOpenRecorder pollId={params.urlId} token={token} />
- ) : null}
- <UserProvider user={session?.user ?? null}>
+ {token ? <InviteOpenRecorder pollId={urlId} token={token} /> : null}
+ <UserProvider user={user}>
<DeviceDateTimeProvider
locale={locale}
timeZone={deviceDateTimeConfig.timeZone}
timeFormat={deviceDateTimeConfig.timeFormat}
>
- <Providers>
- <PermissionProvider linkedParticipantIds={linkedParticipantIds}>
- <InvitePageLoader footerLinks={footerLinks} />
- </PermissionProvider>
- </Providers>
+ <PollProvider
+ poll={poll}
+ participants={participants}
+ comments={comments}
+ linkedParticipantIds={linkedParticipantIds}
+ viewerRole="participant"
+ >
+ <LegacyPollContextProvider>
+ <VisibilityProvider>
+ <PollBrandingFromContext />
+ <InvitePage footerLinks={footerLinks} />
+ </VisibilityProvider>
+ </LegacyPollContextProvider>
+ </PollProvider>
</DeviceDateTimeProvider>
</UserProvider>
- </HydrationBoundary>
+ </>
+ );
+}
+
+export default function Page(props: PageProps) {
+ return (
+ <Suspense fallback={<InvitePageLoading />}>
+ <InvitePageContent {...props} />
+ </Suspense>
);
}
export async function generateMetadata(props: {
- params: Promise<{
- urlId: string;
- locale: string;
- }>;
+ params: Promise<{ urlId: string; locale: string }>;
}): Promise<Metadata> {
- const params = await props.params;
+ const { urlId } = await props.params;
- const { urlId } = params;
+ const availability = await loadPollAvailability(urlId);
- const { poll, unavailable } = await getPollMetadata(urlId);
+ if (!availability) {
+ notFound();
+ }
- if (unavailable) {
+ if (availability.unavailable) {
return {
title: "Poll unavailable",
robots: { index: false, follow: false },
};
}
- const { title, id, user } = poll;
-
- const author = user?.name || "Guest";
+ const { title, id, authorName } = availability;
const ogImageUrl = absoluteUrl("/api/og-image-poll", {
title,
- author,
+ author: authorName,
});
return {
@@ -166,7 +132,7 @@ export async function generateMetadata(props: {
metadataBase: new URL(absoluteUrl()),
openGraph: {
title,
- description: `By ${author}`,
+ description: `By ${authorName}`,
url: `/invite/${id}`,
images: [
{
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/providers.tsx b/apps/web/src/app/[locale]/invite/[urlId]/providers.tsx
deleted file mode 100644
index 86683dd80..000000000
--- a/apps/web/src/app/[locale]/invite/[urlId]/providers.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-"use client";
-
-import { LegacyPollContextProvider } from "@/features/poll/components/poll-context-provider";
-import { VisibilityProvider } from "@/features/poll/components/visibility";
-
-export default function Providers({ children }: { children: React.ReactNode }) {
- return (
- <LegacyPollContextProvider>
- <VisibilityProvider>{children}</VisibilityProvider>
- </LegacyPollContextProvider>
- );
-}
diff --git a/apps/web/src/features/notifications/mutations.ts b/apps/web/src/features/notifications/mutations.ts
index ce36d7547..1b64ba262 100644
--- a/apps/web/src/features/notifications/mutations.ts
+++ b/apps/web/src/features/notifications/mutations.ts
@@ -2,7 +2,6 @@ import "server-only";
import { Prisma, prisma } from "@rallly/database";
import { env } from "@/env";
-import { setPollMuted } from "@/features/poll/mutations";
import { defaultNotificationPreferences } from "./constants";
import type { ActivityEventType } from "./schema";
@@ -71,12 +70,22 @@ export async function unsubscribeWithToken({ token }: { token: string }) {
switch (target.kind) {
case "poll": {
- const result = await setPollMuted({
- pollId: target.pollId,
- userId: target.userId,
- muted: true,
+ // The same row write as the poll feature's setPollMuted, kept here so
+ // notifications never imports poll: poll depends on this feature for
+ // recipients and tokens, and features must not import each other in
+ // both directions.
+ const { count } = await prisma.poll.updateMany({
+ where: {
+ id: target.pollId,
+ userId: target.userId,
+ deletedAt: null,
+ },
+ data: { muted: true },
});
- return result.ok ? { ok: true as const, target } : result;
+ if (count === 0) {
+ return { ok: false as const, reason: "notFound" as const };
+ }
+ return { ok: true as const, target };
}
}
}
diff --git a/apps/web/src/features/poll/client.tsx b/apps/web/src/features/poll/client.tsx
index e041de333..2d33cfbc3 100644
--- a/apps/web/src/features/poll/client.tsx
+++ b/apps/web/src/features/poll/client.tsx
@@ -1,55 +1,89 @@
"use client";
-import { useParams, usePathname } from "next/navigation";
import React from "react";
-
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useRequiredContext } from "@/components/use-required-context";
+import type {
+ PollComment,
+ PollDetails,
+ PollParticipant,
+} from "@/features/poll/types";
import { useUser } from "@/features/user/client";
-import { trpc } from "@/trpc/client";
-
-export const usePoll = () => {
- const params = useParams<{ urlId: string }>();
- const [poll] = trpc.polls.get.useSuspenseQuery({
- urlId: params?.urlId as string,
- });
+import { useTranslation } from "@/i18n/client";
- return poll;
+type PollContextValue = {
+ poll: PollDetails;
+ participants: PollParticipant[];
+ comments: PollComment[];
+ /**
+ * Responses the emailed link in the URL may edit, resolved on the server
+ * from the same token the actions check.
+ */
+ linkedParticipantIds: string[];
+ /** Which surface the page is: the host's admin page or the invite page. */
+ viewerRole: "admin" | "participant";
};
-export const useRole = () => {
- const pathname = usePathname();
- return pathname?.includes("/poll") ? "admin" : "participant";
-};
+const PollContext = React.createContext<PollContextValue | null>(null);
+
+PollContext.displayName = "PollProvider";
/**
- * Responses the emailed link in the URL may edit, resolved on the server
- * from the same token the tRPC routes check.
+ * Serves the poll a page loaded on the server. Writes go through server
+ * actions followed by router.refresh(), which re-renders the page with new
+ * props; nothing here is patched on the client.
*/
-const PermissionsContext = React.createContext<{
- linkedParticipantIds: string[];
-}>({
- linkedParticipantIds: [],
-});
-
-export const PermissionProvider = ({
+export function PollProvider({
+ poll,
+ participants,
+ comments,
+ linkedParticipantIds = [],
+ viewerRole,
children,
- linkedParticipantIds,
-}: {
+}: Omit<PollContextValue, "linkedParticipantIds"> & {
+ linkedParticipantIds?: string[];
children: React.ReactNode;
- linkedParticipantIds: string[];
-}) => {
- return (
- <PermissionsContext.Provider value={{ linkedParticipantIds }}>
- {children}
- </PermissionsContext.Provider>
+}) {
+ const value = React.useMemo(
+ () => ({ poll, participants, comments, linkedParticipantIds, viewerRole }),
+ [poll, participants, comments, linkedParticipantIds, viewerRole],
);
+
+ return <PollContext.Provider value={value}>{children}</PollContext.Provider>;
+}
+
+export const usePoll = () => useRequiredContext(PollContext).poll;
+
+export const useRole = () => useRequiredContext(PollContext).viewerRole;
+
+export const useComments = () => useRequiredContext(PollContext).comments;
+
+export const useParticipants = () => {
+ const { t } = useTranslation();
+ const { participants: rawParticipants } = useRequiredContext(PollContext);
+
+ const participants = React.useMemo(() => {
+ return rawParticipants.map((participant, index) => {
+ if (!participant.hidden) {
+ return participant;
+ }
+
+ return {
+ ...participant,
+ name: t("hiddenParticipantName", {
+ defaultValue: "Participant #{number}",
+ number: rawParticipants.length - index,
+ }),
+ };
+ });
+ }, [rawParticipants, t]);
+
+ return { participants };
};
export const usePermissions = () => {
- const poll = usePoll();
- const context = React.useContext(PermissionsContext);
+ const { poll, participants, linkedParticipantIds, viewerRole } =
+ useRequiredContext(PollContext);
const { user } = useUser();
- const role = useRole();
- const { participants } = useParticipants();
+
return {
canAddNewParticipant: poll.status === "open",
canEditParticipant: (participantId: string) => {
@@ -57,7 +91,7 @@ export const usePermissions = () => {
return false;
}
- if (role === "admin") {
+ if (viewerRole === "admin") {
return true;
}
@@ -71,7 +105,7 @@ export const usePermissions = () => {
return (
(!!user && participant.userId === user.id) ||
- context.linkedParticipantIds.includes(participantId)
+ linkedParticipantIds.includes(participantId)
);
},
};
diff --git a/apps/web/src/features/poll/comment/actions.ts b/apps/web/src/features/poll/comment/actions.ts
new file mode 100644
index 000000000..df1331c7a
--- /dev/null
+++ b/apps/web/src/features/poll/comment/actions.ts
@@ -0,0 +1,147 @@
+"use server";
+
+import { sendNewCommentEmail } from "@rallly/emails/templates/new-comment";
+import { createLogger } from "@rallly/logger";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { after } from "next/server";
+import { getInstanceBranding } from "@/emails/branding";
+import { env } from "@/env";
+import { getNotificationRecipient } from "@/features/notifications/data";
+import { createUnsubscribeToken } from "@/features/notifications/utils";
+import { getComment } from "@/features/poll/comment/data";
+import { addComment, deleteComment } from "@/features/poll/comment/mutations";
+import {
+ addCommentSchema,
+ deleteCommentSchema,
+} from "@/features/poll/comment/schema";
+import { hasPollAdminAccess } from "@/features/poll/data";
+import { AppError } from "@/lib/errors/app-error";
+import { track } from "@/lib/posthog";
+import {
+ anyUserActionClient,
+ createRateLimitMiddleware,
+} from "@/lib/safe-action/server";
+
+const logger = createLogger("comments");
+
+async function sendNewCommentNotificationEmail({
+ pollId,
+ pollTitle,
+ authorName,
+ content,
+ excludeUserId,
+}: {
+ pollId: string;
+ pollTitle: string;
+ authorName: string;
+ content: string;
+ excludeUserId: string;
+}) {
+ try {
+ const recipient = await getNotificationRecipient({
+ pollId,
+ type: "poll.comment.added",
+ excludeUserId,
+ });
+
+ if (!recipient) {
+ return;
+ }
+
+ const unsubscribeToken = createUnsubscribeToken({
+ target: { kind: "poll", pollId, userId: recipient.id },
+ secret: env.SECRET_PASSWORD,
+ });
+
+ await sendNewCommentEmail({
+ to: recipient.email,
+ locale: recipient.locale ?? undefined,
+ branding: await getInstanceBranding(),
+ listUnsubscribeUrl: absoluteUrl(`/api/unsubscribe/${unsubscribeToken}`),
+ props: {
+ authorName,
+ content,
+ pollUrl: absoluteUrl(`/poll/${pollId}`),
+ unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),
+ disableNotificationsUrl: absoluteUrl("/settings/notifications"),
+ title: pollTitle,
+ },
+ });
+ } catch (err) {
+ logger.error(
+ { error: err, pollId },
+ "Failed to send new comment notification email",
+ );
+ }
+}
+
+export const addCommentAction = anyUserActionClient
+ .metadata({ actionName: "add_comment" })
+ .use(createRateLimitMiddleware(10, "1 m"))
+ .inputSchema(addCommentSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { pollId, authorName, content } = parsedInput;
+
+ const result = await addComment({
+ pollId,
+ userId: ctx.user.id,
+ isGuest: ctx.user.isGuest,
+ authorName,
+ content,
+ });
+
+ if (!result.ok) {
+ return result;
+ }
+
+ const { comment } = result;
+
+ after(() =>
+ sendNewCommentNotificationEmail({
+ pollId,
+ pollTitle: comment.poll.title,
+ authorName: comment.authorName,
+ content: comment.content,
+ excludeUserId: ctx.user.id,
+ }),
+ );
+
+ track(ctx.user, {
+ event: "poll_comment_add",
+ properties: { is_guest: ctx.user.isGuest },
+ groups: { poll: pollId },
+ });
+
+ return { ok: true as const, comment: { id: comment.id } };
+ });
+
+export const deleteCommentAction = anyUserActionClient
+ .metadata({ actionName: "delete_comment" })
+ .inputSchema(deleteCommentSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { commentId } = parsedInput;
+
+ const comment = await getComment({ commentId });
+
+ if (!comment) {
+ throw new AppError({ code: "NOT_FOUND", message: "Comment not found" });
+ }
+
+ const isAuthor = comment.userId === ctx.user.id;
+
+ if (!isAuthor && !(await hasPollAdminAccess(comment.pollId, ctx.user.id))) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You are not allowed to delete this comment",
+ });
+ }
+
+ await deleteComment({ commentId });
+
+ track(ctx.user, {
+ event: "poll_comment_delete",
+ groups: { poll: comment.pollId },
+ });
+
+ return { ok: true as const };
+ });
diff --git a/apps/web/src/features/poll/comment/data.ts b/apps/web/src/features/poll/comment/data.ts
new file mode 100644
index 000000000..c6d81f18b
--- /dev/null
+++ b/apps/web/src/features/poll/comment/data.ts
@@ -0,0 +1,10 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+
+export async function getComment({ commentId }: { commentId: string }) {
+ return prisma.comment.findUnique({
+ where: { id: commentId },
+ select: { pollId: true, userId: true },
+ });
+}
diff --git a/apps/web/src/features/poll/comment/mutations.ts b/apps/web/src/features/poll/comment/mutations.ts
new file mode 100644
index 000000000..05bc4d11d
--- /dev/null
+++ b/apps/web/src/features/poll/comment/mutations.ts
@@ -0,0 +1,119 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+import { revalidatePollPages } from "@/features/poll/mutations";
+import { MAX_COMMENT_AUTHOR_NAME_LENGTH } from "@/features/poll/schema";
+
+type CommentRefusal = "notFound" | "disabled";
+
+class CommentRefusedError extends Error {
+ constructor(public readonly reason: CommentRefusal) {
+ super(reason);
+ }
+}
+
+export type AddCommentResult =
+ | {
+ ok: true;
+ comment: {
+ id: string;
+ content: string;
+ authorName: string;
+ poll: { id: string; title: string };
+ };
+ }
+ | { ok: false; reason: CommentRefusal };
+
+export async function addComment({
+ pollId,
+ userId,
+ isGuest,
+ authorName,
+ content,
+}: {
+ pollId: string;
+ userId: string;
+ isGuest: boolean;
+ authorName: string;
+ content: string;
+}): Promise<AddCommentResult> {
+ const poll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ user: { select: { banned: true } },
+ space: { select: { owner: { select: { banned: true } } } },
+ },
+ });
+
+ // A poll whose creator or space owner was banned never accepts comments.
+ // Bans live on the user rows, so they are checked outside the lock below.
+ if (!poll || poll.user?.banned || poll.space?.owner.banned) {
+ return { ok: false, reason: "notFound" };
+ }
+
+ let name = authorName;
+
+ if (!isGuest) {
+ const user = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { name: true },
+ });
+
+ // Stored names (e.g. from OAuth sign-up) aren't guaranteed to satisfy
+ // the schema cap, so bound them here too.
+ name = user.name.trim().slice(0, MAX_COMMENT_AUTHOR_NAME_LENGTH);
+ }
+
+ try {
+ const comment = await prisma.$transaction(async (tx) => {
+ // Locked so the host's delete or comments-off transition, which
+ // updates the same row, cannot commit between this check and the
+ // insert.
+ const [lockedPoll] = await tx.$queryRaw<
+ { deleted: boolean; disable_comments: boolean }[]
+ >`
+ SELECT deleted, disable_comments
+ FROM polls WHERE id = ${pollId} FOR UPDATE
+ `;
+
+ if (!lockedPoll || lockedPoll.deleted) {
+ throw new CommentRefusedError("notFound");
+ }
+
+ // The comment UI is hidden when the host turns comments off, but the
+ // setting is only real if the mutation enforces it too.
+ if (lockedPoll.disable_comments) {
+ throw new CommentRefusedError("disabled");
+ }
+
+ return tx.comment.create({
+ data: {
+ content,
+ pollId,
+ authorName: name,
+ userId,
+ },
+ select: {
+ id: true,
+ content: true,
+ authorName: true,
+ poll: { select: { id: true, title: true } },
+ },
+ });
+ });
+
+ revalidatePollPages();
+
+ return { ok: true, comment };
+ } catch (error) {
+ if (error instanceof CommentRefusedError) {
+ return { ok: false, reason: error.reason };
+ }
+ throw error;
+ }
+}
+
+export async function deleteComment({ commentId }: { commentId: string }) {
+ await prisma.comment.delete({ where: { id: commentId } });
+ revalidatePollPages();
+}
diff --git a/apps/web/src/features/poll/comment/schema.ts b/apps/web/src/features/poll/comment/schema.ts
new file mode 100644
index 000000000..cb976ba90
--- /dev/null
+++ b/apps/web/src/features/poll/comment/schema.ts
@@ -0,0 +1,15 @@
+import * as z from "zod";
+import {
+ MAX_COMMENT_AUTHOR_NAME_LENGTH,
+ MAX_COMMENT_LENGTH,
+} from "@/features/poll/schema";
+
+export const addCommentSchema = z.object({
+ pollId: z.string(),
+ authorName: z.string().trim().min(1).max(MAX_COMMENT_AUTHOR_NAME_LENGTH),
+ content: z.string().trim().min(1).max(MAX_COMMENT_LENGTH),
+});
+
+export const deleteCommentSchema = z.object({
+ commentId: z.string(),
+});
diff --git a/apps/web/src/features/poll/components/comments-sheet.tsx b/apps/web/src/features/poll/components/comments-sheet.tsx
index 6768eb322..db54fc9d3 100644
--- a/apps/web/src/features/poll/components/comments-sheet.tsx
+++ b/apps/web/src/features/poll/components/comments-sheet.tsx
@@ -43,12 +43,20 @@ import {
EmptyStateTitle,
} from "@/components/empty-state";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
-import { usePoll, useRole } from "@/features/poll/client";
+import {
+ useComments,
+ useParticipants,
+ usePoll,
+ useRole,
+} from "@/features/poll/client";
+import {
+ useAddComment,
+ useDeleteComment,
+} from "@/features/poll/components/mutations";
import {
Participant,
ParticipantName,
} from "@/features/poll/components/participant";
-import { useParticipants } from "@/features/poll/components/participants-provider";
import TruncatedLinkify from "@/features/poll/components/truncated-linkify";
import {
MAX_COMMENT_AUTHOR_NAME_LENGTH,
@@ -58,7 +66,6 @@ import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
import { RelativeTime } from "@/lib/datetime/relative-time";
import { requiredString } from "@/lib/utils/form-validation";
-import { trpc } from "@/trpc/client";
interface CommentForm {
authorName: string;
@@ -94,20 +101,40 @@ function NewCommentForm({ onSubmitted }: { onSubmitted: () => void }) {
const contentLength = watch("content").length;
- const queryClient = trpc.useUtils();
+ const addComment = useAddComment();
+
+ const getCommentErrorMessage = (reason: string) => {
+ switch (reason) {
+ case "disabled":
+ case "notFound":
+ return t("commentsDisabledError", {
+ defaultValue: "Comments are turned off for this poll.",
+ });
+ case "tooManyRequests":
+ return t("actionErrorTooManyRequests", {
+ defaultValue: "You are making too many requests",
+ });
+ default:
+ return t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ });
+ }
+ };
- const addComment = trpc.polls.comments.add.useMutation({
- onError: (error) => {
- toast.error(error.message);
- },
- });
return (
<form
className="w-full"
onSubmit={handleSubmit(async ({ authorName, content }) => {
await createGuestIfNeeded();
- await addComment.mutateAsync({ authorName, content, pollId });
- await queryClient.polls.comments.list.invalidate({ pollId });
+ const result = await addComment.execute({
+ authorName,
+ content,
+ pollId,
+ });
+ if (!result.ok) {
+ toast.error(getCommentErrorMessage(result.reason));
+ return;
+ }
reset({ authorName, content: "" });
onSubmitted();
})}
@@ -201,33 +228,9 @@ function CommentsSheetInner({ className }: { className?: string }) {
const pollId = poll.id;
- const { data: comments } = trpc.polls.comments.list.useQuery({ pollId });
-
- const queryClient = trpc.useUtils();
+ const comments = useComments();
- const deleteComment = trpc.polls.comments.delete.useMutation({
- onMutate: ({ commentId }) => {
- const previousComments = queryClient.polls.comments.list.getData({
- pollId,
- });
- queryClient.polls.comments.list.setData(
- { pollId },
- (existingComments = []) => {
- return existingComments.filter(({ id }) => id !== commentId);
- },
- );
- return { previousComments };
- },
- onError: (_error, _variables, context) => {
- queryClient.polls.comments.list.setData(
- { pollId },
- context?.previousComments,
- );
- },
- onSettled: () => {
- queryClient.polls.comments.list.invalidate({ pollId });
- },
- });
+ const deleteComment = useDeleteComment();
const session = useUser();
@@ -235,16 +238,14 @@ function CommentsSheetInner({ className }: { className?: string }) {
const [hasCommented, setHasCommented] = React.useState(false);
- const count = comments?.length ?? 0;
+ const count = comments.length;
const sortedComments = React.useMemo(
() =>
- comments
- ? [...comments].sort(
- (a, b) =>
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
- )
- : [],
+ [...comments].sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ ),
[comments],
);
@@ -338,10 +339,19 @@ function CommentsSheetInner({ className }: { className?: string }) {
<DropdownMenuContent align="end">
<DropdownMenuItem
variant="destructive"
- onClick={() => {
- deleteComment.mutate({
+ disabled={deleteComment.isPending}
+ onClick={async () => {
+ const result = await deleteComment.execute({
commentId: comment.id,
});
+ if (!result.ok) {
+ toast.error(
+ t("actionErrorInternalServerError", {
+ defaultValue:
+ "An internal server error occurred",
+ }),
+ );
+ }
}}
>
<TrashIcon />
diff --git a/apps/web/src/features/poll/components/desktop-poll.tsx b/apps/web/src/features/poll/components/desktop-poll.tsx
index 2787d27c5..14f78e018 100644
--- a/apps/web/src/features/poll/components/desktop-poll.tsx
+++ b/apps/web/src/features/poll/components/desktop-poll.tsx
@@ -25,8 +25,11 @@ import {
EmptyStateTitle,
} from "@/components/empty-state";
import { ScrollContainer } from "@/components/scroll-container";
-import { usePermissions, usePoll } from "@/features/poll/client";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import {
+ useParticipants,
+ usePermissions,
+ usePoll,
+} from "@/features/poll/client";
import { useVisibleParticipants } from "@/features/poll/components/visibility";
import { VotingFooter } from "@/features/poll/components/voting-footer";
import { useVotingForm } from "@/features/poll/components/voting-form";
diff --git a/apps/web/src/features/poll/components/desktop-poll/participant-row.tsx b/apps/web/src/features/poll/components/desktop-poll/participant-row.tsx
index 0fa0c984e..4a6be9dd3 100644
--- a/apps/web/src/features/poll/components/desktop-poll/participant-row.tsx
+++ b/apps/web/src/features/poll/components/desktop-poll/participant-row.tsx
@@ -16,9 +16,9 @@ import {
import { ParticipantDropdown } from "@/features/poll/components/participant-dropdown";
import { ParticipantNote } from "@/features/poll/components/participant-note";
import { usePoll } from "@/features/poll/components/poll-context";
+import type { Vote } from "@/features/poll/types";
import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
-import type { Vote } from "@/trpc/client/types";
import VoteIcon from "../vote-icon";
import ParticipantRowForm from "./participant-row-form";
diff --git a/apps/web/src/features/poll/components/manage-poll.tsx b/apps/web/src/features/poll/components/manage-poll.tsx
index 6674e6c16..b0ce26f47 100644
--- a/apps/web/src/features/poll/components/manage-poll.tsx
+++ b/apps/web/src/features/poll/components/manage-poll.tsx
@@ -19,6 +19,7 @@ import {
TableIcon,
TrashIcon,
} from "lucide-react";
+import { useRouter } from "next/navigation";
import * as React from "react";
import { DuplicateDialog } from "@/app/[locale]/(optional-space)/poll/[urlId]/duplicate-dialog";
import { Link } from "@/components/link";
@@ -33,48 +34,21 @@ import { useCsvExporter } from "./manage-poll/use-csv-exporter";
function OpenCloseToggle() {
const poll = usePoll();
- const queryClient = trpc.useUtils();
+ const router = useRouter();
+ // 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: (_data, vars) => {
- queryClient.polls.get.setData({ urlId: vars.pollId }, (oldData) => {
- if (!oldData) return oldData;
- return {
- ...oldData,
- status: "open",
- };
- });
- },
+ onSuccess: () => router.refresh(),
});
const closePoll = trpc.polls.close.useMutation({
- onSuccess: (_data, vars) => {
- queryClient.polls.get.setData({ urlId: vars.pollId }, (oldData) => {
- if (!oldData) return oldData;
- return {
- ...oldData,
- status: "closed",
- };
- });
- },
+ onSuccess: () => router.refresh(),
});
if (poll.status === "closed") {
return (
<DropdownMenuItem
onClick={() => {
- openPoll.mutate(
- { pollId: poll.id },
- {
- onSuccess: () => {
- queryClient.polls.get.setData({ urlId: poll.id }, (oldData) => {
- if (!oldData) return oldData;
- return {
- ...oldData,
- status: "open",
- };
- });
- },
- },
- );
+ openPoll.mutate({ pollId: poll.id });
}}
>
<PlayIcon />
@@ -85,20 +59,7 @@ function OpenCloseToggle() {
return (
<DropdownMenuItem
onClick={() => {
- closePoll.mutate(
- { pollId: poll.id },
- {
- onSuccess: () => {
- queryClient.polls.get.setData({ urlId: poll.id }, (oldData) => {
- if (!oldData) return oldData;
- return {
- ...oldData,
- status: "closed",
- };
- });
- },
- },
- );
+ closePoll.mutate({ pollId: poll.id });
}}
>
<CircleStopIcon />
diff --git a/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx b/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx
index bd7a15776..8da68d91d 100644
--- a/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx
+++ b/apps/web/src/features/poll/components/manage-poll/schedule-poll-dialog.tsx
@@ -19,12 +19,12 @@ import {
FormLabel,
} from "@rallly/ui/form";
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
+import { useRouter } from "next/navigation";
import React from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { DateIconInner } from "@/components/date-icon";
-import { usePoll } from "@/features/poll/client";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useParticipants, usePoll } from "@/features/poll/client";
import { ConnectedScoreSummary } from "@/features/poll/components/score-summary";
import { VoteSummaryProgressBar } from "@/features/poll/components/vote-summary-progress-bar";
import {
@@ -218,7 +218,10 @@ export const SchedulePollForm = ({
export function SchedulePollDialog(props: DialogProps) {
const poll = usePoll();
- const scheduleEvent = trpc.polls.book.useMutation();
+ const router = useRouter();
+ const scheduleEvent = trpc.polls.book.useMutation({
+ onSuccess: () => router.refresh(),
+ });
return (
<Dialog {...props}>
<DialogContent size="2xl">
diff --git a/apps/web/src/features/poll/components/manage-poll/use-csv-exporter.ts b/apps/web/src/features/poll/components/manage-poll/use-csv-exporter.ts
index 48016ed4d..bf6756e0f 100644
--- a/apps/web/src/features/poll/components/manage-poll/use-csv-exporter.ts
+++ b/apps/web/src/features/poll/components/manage-poll/use-csv-exporter.ts
@@ -1,4 +1,4 @@
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useParticipants } from "@/features/poll/client";
import { useOptions, usePoll } from "@/features/poll/components/poll-context";
import { useTranslation } from "@/i18n/client";
import { dayjs } from "@/lib/dayjs";
diff --git a/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx b/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
index 655cc6cc0..9c9885469 100644
--- a/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
+++ b/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
@@ -14,11 +14,9 @@ import * as m from "motion/react-m";
import type * as React from "react";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
-import {
- filterParticipantsByVote,
- useParticipants,
-} from "@/features/poll/components/participants-provider";
+import { useParticipants } from "@/features/poll/client";
import { IfScoresVisible } from "@/features/poll/components/visibility";
+import { filterParticipantsByVote } from "@/features/poll/utils";
import { Trans, useTranslation } from "@/i18n/client";
import { ConnectedScoreSummary } from "../score-summary";
import VoteIcon from "../vote-icon";
diff --git a/apps/web/src/features/poll/components/mobile-poll/poll-options.tsx b/apps/web/src/features/poll/components/mobile-poll/poll-options.tsx
index 13338192d..69d113b0e 100644
--- a/apps/web/src/features/poll/components/mobile-poll/poll-options.tsx
+++ b/apps/web/src/features/poll/components/mobile-poll/poll-options.tsx
@@ -1,7 +1,7 @@
import type { VoteType } from "@rallly/database";
import type * as React from "react";
import { Controller } from "react-hook-form";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useParticipants } from "@/features/poll/client";
import { usePoll } from "@/features/poll/components/poll-context";
import { useVotingForm } from "@/features/poll/components/voting-form";
import type { ParsedDateTimeOpton } from "@/lib/utils/date-time-utils";
diff --git a/apps/web/src/features/poll/components/mutations.ts b/apps/web/src/features/poll/components/mutations.ts
index 11f8e5949..c758807b1 100644
--- a/apps/web/src/features/poll/components/mutations.ts
+++ b/apps/web/src/features/poll/components/mutations.ts
@@ -1,7 +1,18 @@
import { toast } from "@rallly/ui/sonner";
-import { useSearchParams } from "next/navigation";
-import { usePoll } from "@/features/poll/components/poll-context";
+import { useRouter, useSearchParams } from "next/navigation";
+import React from "react";
+import {
+ addCommentAction,
+ deleteCommentAction,
+} from "@/features/poll/comment/actions";
+import {
+ addParticipantAction,
+ deleteParticipantAction,
+ renameParticipantAction,
+ updateParticipantVotesAction,
+} from "@/features/poll/participant/actions";
import { useTranslation } from "@/i18n/client";
+import type { AppErrorCode } from "@/lib/errors/app-error";
import { trpc } from "@/trpc/client";
import type { ParticipantForm } from "./types";
@@ -24,58 +35,76 @@ export const useEditToken = () => {
return searchParams.get("token") ?? searchParams.get("invite") ?? undefined;
};
-export const useAddParticipantMutation = () => {
- return trpc.polls.participants.add.useMutation();
-};
+type ActionFailure = "tooManyRequests" | "unauthorized" | "unknown";
-export const useUpdateParticipantMutation = () => {
- const queryClient = trpc.useUtils();
- const token = useEditToken();
- return trpc.polls.participants.update.useMutation({
- onSuccess: (participant) => {
- queryClient.polls.participants.list.setData(
- { pollId: participant.pollId, token },
- (existingParticipants = []) => {
- const newParticipants = [...existingParticipants];
+function toFailureReason(serverError: string | undefined): ActionFailure {
+ switch (serverError as AppErrorCode | undefined) {
+ case "TOO_MANY_REQUESTS":
+ return "tooManyRequests";
+ case "UNAUTHORIZED":
+ return "unauthorized";
+ default:
+ return "unknown";
+ }
+}
- const index = newParticipants.findIndex(
- ({ id }) => id === participant.id,
- );
+type ActionResult<T> = {
+ data?: T;
+ serverError?: string;
+ validationErrors?: unknown;
+};
- if (index !== -1) {
- // The mutation returns the row without the host's edit link;
- // the token behind it is unchanged, so the link is kept.
- newParticipants[index] = {
- ...participant,
- editUrl: newParticipants[index].editUrl,
- };
- }
+/**
+ * Runs an action. A successful write revalidates the poll pages inside the
+ * mutation, so the action response carries the re-rendered page and the
+ * provider holds fresh props by the time this resolves. Expected failures
+ * come back as values from the action; transport and auth failures are
+ * folded into the same shape so callers branch once.
+ */
+function useServerAction<TInput, TData extends { ok: boolean }>(
+ action: (input: TInput) => Promise<ActionResult<TData>>,
+) {
+ const [isPending, setIsPending] = React.useState(false);
- return newParticipants;
- },
- );
+ const execute = React.useCallback(
+ async (
+ input: TInput,
+ ): Promise<TData | { ok: false; reason: ActionFailure }> => {
+ setIsPending(true);
+ try {
+ const result = await action(input);
+ if (!result.data) {
+ return { ok: false, reason: toFailureReason(result.serverError) };
+ }
+ return result.data;
+ } finally {
+ setIsPending(false);
+ }
},
- });
-};
+ [action],
+ );
-export const useDeleteParticipantMutation = () => {
- const queryClient = trpc.useUtils();
- const { poll } = usePoll();
- const token = useEditToken();
- return trpc.polls.participants.delete.useMutation({
- onMutate: ({ participantId }) => {
- queryClient.polls.participants.list.setData(
- { pollId: poll.id, token },
- (existingParticipants = []) => {
- return existingParticipants.filter(({ id }) => id !== participantId);
- },
- );
- },
- });
-};
+ return { execute, isPending };
+}
+
+export const useAddParticipant = () => useServerAction(addParticipantAction);
+
+export const useUpdateParticipantVotes = () =>
+ useServerAction(updateParticipantVotesAction);
+
+export const useRenameParticipant = () =>
+ useServerAction(renameParticipantAction);
+
+export const useDeleteParticipant = () =>
+ useServerAction(deleteParticipantAction);
+
+export const useAddComment = () => useServerAction(addCommentAction);
+
+export const useDeleteComment = () => useServerAction(deleteCommentAction);
export const useUpdatePollMutation = () => {
const { t } = useTranslation();
+ const router = useRouter();
return trpc.polls.modify.useMutation({
onSuccess: (data) => {
if (!data.ok) {
@@ -93,7 +122,11 @@ export const useUpdatePollMutation = () => {
},
},
);
+ return;
}
+ // The poll is served from the layout's server props; the edit pages
+ // navigate back to it, so the refresh has to precede that navigation.
+ router.refresh();
},
});
};
diff --git a/apps/web/src/features/poll/components/new-participant-modal.tsx b/apps/web/src/features/poll/components/new-participant-modal.tsx
index ae6e1384c..68c106fa0 100644
--- a/apps/web/src/features/poll/components/new-participant-modal.tsx
+++ b/apps/web/src/features/poll/components/new-participant-modal.tsx
@@ -22,7 +22,6 @@ import { Input } from "@rallly/ui/input";
import { Label } from "@rallly/ui/label";
import { MaxCharLength } from "@rallly/ui/max-char-length";
import { Textarea } from "@rallly/ui/textarea";
-import { TRPCClientError } from "@trpc/client";
import { CircleCheckIcon, PlusIcon } from "lucide-react";
import * as React from "react";
import { useForm } from "react-hook-form";
@@ -31,7 +30,7 @@ import { IfCloudHosted } from "@/components/environment";
import { Link } from "@/components/link";
import { usePoll } from "@/features/poll/client";
import {
- useAddParticipantMutation,
+ useAddParticipant,
useEditToken,
} from "@/features/poll/components/mutations";
import VoteIcon from "@/features/poll/components/vote-icon";
@@ -149,34 +148,34 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
const { setError, formState, handleSubmit, watch } = form;
- const getSubmitErrorMessage = (error: unknown) => {
- if (error instanceof TRPCClientError && error.data) {
- if (error.data.appError === "POLL_FULL") {
+ const getSubmitErrorMessage = (reason: string) => {
+ switch (reason) {
+ case "full":
+ case "closed":
+ case "notFound":
return t("newParticipantFormErrorPollFull", {
defaultValue: "This poll is no longer accepting responses.",
});
- }
- switch (error.data.code) {
- case "TOO_MANY_REQUESTS":
- return t("newParticipantFormErrorTooManyRequests", {
- defaultValue:
- "You have made too many attempts. Please wait a while and try again.",
- });
- case "UNAUTHORIZED":
- return t("newParticipantFormErrorUnauthorized", {
- defaultValue:
- "We couldn't verify your session. Please refresh the page and try again.",
- });
- }
+ case "tooManyRequests":
+ return t("newParticipantFormErrorTooManyRequests", {
+ defaultValue:
+ "You have made too many attempts. Please wait a while and try again.",
+ });
+ case "unauthorized":
+ return t("newParticipantFormErrorUnauthorized", {
+ defaultValue:
+ "We couldn't verify your session. Please refresh the page and try again.",
+ });
+ default:
+ return t("newParticipantFormSubmitError", {
+ defaultValue:
+ "Your response could not be saved. Please check your connection and try again.",
+ });
}
- return t("newParticipantFormSubmitError", {
- defaultValue:
- "Your response could not be saved. Please check your connection and try again.",
- });
};
const noteLength = watch("note")?.length ?? 0;
const [showNote, setShowNote] = React.useState(false);
- const addParticipant = useAddParticipantMutation();
+ const addParticipant = useAddParticipant();
// An emailed invite link carries the invite token; the response takes it
// over so the host sees who responded and the same link edits it later.
const token = useEditToken();
@@ -264,21 +263,23 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
<form
id="new-participant-form"
onSubmit={handleSubmit(async (data) => {
- try {
- await createGuestIfNeeded();
- const newParticipant = await addParticipant.mutateAsync({
- name: data.name,
- votes: props.votes,
- email: data.email,
- note: data.note,
- pollId: poll.id,
- timeZone,
- token,
+ await createGuestIfNeeded();
+ const result = await addParticipant.execute({
+ name: data.name,
+ votes: props.votes,
+ email: data.email,
+ note: data.note,
+ pollId: poll.id,
+ timeZone,
+ token,
+ });
+ if (!result.ok) {
+ setError("root", {
+ message: getSubmitErrorMessage(result.reason),
});
- props.onSubmit?.(newParticipant);
- } catch (error) {
- setError("root", { message: getSubmitErrorMessage(error) });
+ return;
}
+ props.onSubmit?.(result.participant);
})}
className="space-y-4"
>
diff --git a/apps/web/src/features/poll/components/notification-toggle.tsx b/apps/web/src/features/poll/components/notification-toggle.tsx
index d8f1ecd28..bc1249ca2 100644
--- a/apps/web/src/features/poll/components/notification-toggle.tsx
+++ b/apps/web/src/features/poll/components/notification-toggle.tsx
@@ -9,25 +9,18 @@ import { usePoll } from "@/features/poll/client";
import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
import { useSafeAction } from "@/lib/safe-action/client";
-import { trpc } from "@/trpc/client";
export function NotificationToggle() {
const poll = usePoll();
const { user, ownsObject } = useUser();
const { t } = useTranslation();
- const queryClient = trpc.useUtils();
+ // useSafeAction refreshes the router on success, which is what flips
+ // `poll.muted` in the layout's server props.
const setPollMuted = useSafeAction(setPollMutedAction, {
onSuccess: ({ data, input }) => {
if (!data?.ok) {
return;
}
- queryClient.polls.get.setData({ urlId: input.pollId }, (oldData) => {
- if (!oldData) return oldData;
- return {
- ...oldData,
- muted: input.muted,
- };
- });
if (input.muted) {
toast(
t("notificationToggleMutedToast", {
diff --git a/apps/web/src/features/poll/components/participant-dropdown.tsx b/apps/web/src/features/poll/components/participant-dropdown.tsx
index 78be00f13..572bc0cb5 100644
--- a/apps/web/src/features/poll/components/participant-dropdown.tsx
+++ b/apps/web/src/features/poll/components/participant-dropdown.tsx
@@ -37,12 +37,12 @@ import * as z from "zod";
import { usePoll } from "@/features/poll/client";
import {
- useDeleteParticipantMutation,
+ useDeleteParticipant,
useEditToken,
+ useRenameParticipant,
} from "@/features/poll/components/mutations";
import { Trans, useTranslation } from "@/i18n/client";
import { useFormValidation } from "@/lib/utils/form-validation";
-import { trpc } from "@/trpc/client";
export const ParticipantDropdown = ({
participant,
@@ -195,7 +195,8 @@ const DeleteParticipantModal = ({
participantName: string;
onDelete?: () => void;
}) => {
- const deleteParticipant = useDeleteParticipantMutation();
+ const { t } = useTranslation();
+ const deleteParticipant = useDeleteParticipant();
const token = useEditToken();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -227,10 +228,22 @@ const DeleteParticipantModal = ({
loading={deleteParticipant.isPending}
variant="destructive"
onClick={async () => {
- deleteParticipant.mutate({
+ const result = await deleteParticipant.execute({
participantId,
token,
});
+ if (!result.ok) {
+ toast.error(
+ result.reason === "closed"
+ ? t("pollClosedDescription", {
+ defaultValue: "No more responses are being accepted.",
+ })
+ : t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ }),
+ );
+ return;
+ }
onDelete?.();
onOpenChange(false);
}}
@@ -257,8 +270,9 @@ const ChangeNameModal = (props: {
open: boolean;
onOpenChange: (open: boolean) => void;
}) => {
+ const { t } = useTranslation();
const token = useEditToken();
- const changeName = trpc.polls.participants.rename.useMutation();
+ const renameParticipant = useRenameParticipant();
const form = useForm({
defaultValues: {
name: props.oldName,
@@ -279,21 +293,38 @@ const ChangeNameModal = (props: {
const handler = React.useCallback<SubmitHandler<ChangeNameForm>>(
async ({ name }) => {
if (formState.isDirty) {
- // change name
- await changeName.mutateAsync({
+ const result = await renameParticipant.execute({
participantId,
- newName: name,
+ name,
token,
});
+ if (!result.ok) {
+ toast.error(
+ result.reason === "closed"
+ ? t("pollClosedDescription", {
+ defaultValue: "No more responses are being accepted.",
+ })
+ : t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ }),
+ );
+ return;
+ }
}
onOpenChange(false);
},
- [changeName, formState.isDirty, participantId, token, onOpenChange],
+ [
+ renameParticipant,
+ formState.isDirty,
+ participantId,
+ token,
+ onOpenChange,
+ t,
+ ],
);
const { requiredString } = useFormValidation();
const formName = `change-name-${props.participantId}`;
- const { t } = useTranslation();
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
<DialogContent>
diff --git a/apps/web/src/features/poll/components/participants-provider.tsx b/apps/web/src/features/poll/components/participants-provider.tsx
deleted file mode 100644
index d7fa055a8..000000000
--- a/apps/web/src/features/poll/components/participants-provider.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { VoteType } from "@rallly/database";
-import { useParams, useSearchParams } from "next/navigation";
-import * as React from "react";
-import { useTranslation } from "@/i18n/client";
-import { trpc } from "@/trpc/client";
-
-export function filterParticipantsByVote<
- T extends { votes: { optionId: string; type: VoteType }[] },
->(participants: T[], optionId: string, voteType: VoteType): T[] {
- return participants.filter((participant) => {
- return participant.votes.some((vote) => {
- return vote.optionId === optionId && vote.type === voteType;
- });
- });
-}
-
-export const useParticipants = () => {
- const { t } = useTranslation();
- const urlId = useParams<{ urlId: string }>().urlId;
- const token = useSearchParams().get("token") ?? undefined;
- const [rawParticipants] = trpc.polls.participants.list.useSuspenseQuery({
- pollId: urlId,
- token,
- });
-
- const participants = React.useMemo(() => {
- return rawParticipants.map((participant, index) => {
- if (!participant.hidden) {
- return participant;
- }
-
- return {
- ...participant,
- name: t("hiddenParticipantName", {
- defaultValue: "Participant #{number}",
- number: rawParticipants.length - index,
- }),
- };
- });
- }, [rawParticipants, t]);
-
- return { participants };
-};
diff --git a/apps/web/src/features/poll/components/poll-context-provider.tsx b/apps/web/src/features/poll/components/poll-context-provider.tsx
index 60ca66235..8919ea78a 100644
--- a/apps/web/src/features/poll/components/poll-context-provider.tsx
+++ b/apps/web/src/features/poll/components/poll-context-provider.tsx
@@ -1,3 +1,4 @@
+"use client";
import ModalProvider from "@/components/modal/modal-provider";
import { usePoll } from "@/features/poll/client";
import {
diff --git a/apps/web/src/features/poll/components/poll-context.tsx b/apps/web/src/features/poll/components/poll-context.tsx
index 06d205f45..83b642b15 100644
--- a/apps/web/src/features/poll/components/poll-context.tsx
+++ b/apps/web/src/features/poll/components/poll-context.tsx
@@ -1,7 +1,9 @@
+"use client";
import type { TimeFormat, VoteType } from "@rallly/database";
import React from "react";
import { useRequiredContext } from "@/components/use-required-context";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useParticipants } from "@/features/poll/client";
+import type { PollDetails } from "@/features/poll/types";
import { useDateTimeConfig } from "@/lib/datetime/client";
import {
formatDateParts,
@@ -12,10 +14,9 @@ import type {
ParsedDateOption,
ParsedTimeSlotOption,
} from "@/lib/utils/date-time-utils";
-import type { GetPollApiResponse } from "@/trpc/client/types";
type PollContextValue = {
- poll: GetPollApiResponse;
+ poll: PollDetails;
highScore: number;
optionIds: string[];
getScore: (optionId: string) => {
@@ -37,7 +38,7 @@ export const usePoll = () => {
};
export const PollContextProvider: React.FunctionComponent<{
- poll: GetPollApiResponse;
+ poll: PollDetails;
children?: React.ReactNode;
}> = ({ poll, children }) => {
const { participants } = useParticipants();
diff --git a/apps/web/src/features/poll/components/poll-layout.tsx b/apps/web/src/features/poll/components/poll-layout.tsx
index 94278f0c5..e1ff87df0 100644
--- a/apps/web/src/features/poll/components/poll-layout.tsx
+++ b/apps/web/src/features/poll/components/poll-layout.tsx
@@ -8,7 +8,7 @@ import {
BreadcrumbSeparator,
} from "@rallly/ui/breadcrumb";
import { BarChart2Icon } from "lucide-react";
-import { useParams, usePathname } from "next/navigation";
+import { usePathname } from "next/navigation";
import type React from "react";
import { Link } from "@/components/link";
import { usePoll } from "@/features/poll/client";
@@ -79,15 +79,6 @@ const Layout = ({ children }: React.PropsWithChildren) => {
};
export const PollLayout = ({ children }: React.PropsWithChildren) => {
- const params = useParams();
-
- const urlId = params?.urlId as string;
-
- if (!urlId) {
- // probably navigating away
- return null;
- }
-
return (
<LegacyPollContextProvider>
<Layout>{children}</Layout>
diff --git a/apps/web/src/features/poll/components/visibility.tsx b/apps/web/src/features/poll/components/visibility.tsx
index 56c380b77..ae0578232 100644
--- a/apps/web/src/features/poll/components/visibility.tsx
+++ b/apps/web/src/features/poll/components/visibility.tsx
@@ -1,9 +1,13 @@
+"use client";
/**
* Manage what the user can and cannot see on the page
*/
import React from "react";
-import { usePermissions, usePoll } from "@/features/poll/client";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import {
+ useParticipants,
+ usePermissions,
+ usePoll,
+} from "@/features/poll/client";
export const IfScoresVisible = (props: React.PropsWithChildren) => {
const context = React.useContext(VisibilityContext);
diff --git a/apps/web/src/features/poll/components/vote-summary-progress-bar.tsx b/apps/web/src/features/poll/components/vote-summary-progress-bar.tsx
index 36daf706b..eb8bb2e2d 100644
--- a/apps/web/src/features/poll/components/vote-summary-progress-bar.tsx
+++ b/apps/web/src/features/poll/components/vote-summary-progress-bar.tsx
@@ -1,6 +1,6 @@
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useParticipants } from "@/features/poll/client";
const ListNames = ({ participantIds }: { participantIds: string[] }) => {
const { participants } = useParticipants();
diff --git a/apps/web/src/features/poll/components/voting-form.tsx b/apps/web/src/features/poll/components/voting-form.tsx
index 49a0b9d01..198d024e9 100644
--- a/apps/web/src/features/poll/components/voting-form.tsx
+++ b/apps/web/src/features/poll/components/voting-form.tsx
@@ -1,16 +1,22 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { Dialog, DialogContent } from "@rallly/ui/dialog";
+import { toast } from "@rallly/ui/sonner";
import React from "react";
import { FormProvider, useForm, useFormContext } from "react-hook-form";
import * as z from "zod";
-import { usePermissions, usePoll, useRole } from "@/features/poll/client";
+import {
+ useParticipants,
+ usePermissions,
+ usePoll,
+ useRole,
+} from "@/features/poll/client";
import {
normalizeVotes,
useEditToken,
- useUpdateParticipantMutation,
+ useUpdateParticipantVotes,
} from "@/features/poll/components/mutations";
import { NewParticipantForm } from "@/features/poll/components/new-participant-modal";
-import { useParticipants } from "@/features/poll/components/participants-provider";
+import { useTranslation } from "@/i18n/client";
const formSchema = z.object({
mode: z.enum(["new", "edit", "view"]),
@@ -71,8 +77,9 @@ export const useVotingForm = () => {
};
export const VotingForm = ({ children }: React.PropsWithChildren) => {
- const { id: pollId, options } = usePoll();
- const updateParticipant = useUpdateParticipantMutation();
+ const { options } = usePoll();
+ const { t } = useTranslation();
+ const updateParticipantVotes = useUpdateParticipantVotes();
const token = useEditToken();
const { participants } = useParticipants();
@@ -110,15 +117,26 @@ export const VotingForm = ({ children }: React.PropsWithChildren) => {
id="voting-form"
onSubmit={form.handleSubmit(async (data) => {
if (data.participantId) {
- // update participant
-
- await updateParticipant.mutateAsync({
+ const result = await updateParticipantVotes.execute({
participantId: data.participantId,
- pollId,
votes: normalizeVotes(optionIds, data.votes),
token,
});
+ if (!result.ok) {
+ // Stay in edit mode so the selection is not lost.
+ toast.error(
+ result.reason === "closed"
+ ? t("pollClosedDescription", {
+ defaultValue: "No more responses are being accepted.",
+ })
+ : t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ }),
+ );
+ return;
+ }
+
form.reset({
mode: "view",
participantId: data.participantId,
diff --git a/apps/web/src/features/poll/constants.ts b/apps/web/src/features/poll/constants.ts
index 9bc852347..057c0b2d0 100644
--- a/apps/web/src/features/poll/constants.ts
+++ b/apps/web/src/features/poll/constants.ts
@@ -1,5 +1,7 @@
export const MAX_POLL_OPTIONS = 100;
+export const MAX_PARTICIPANTS = 1000;
+
// Display order of the built-in vote types.
export const VOTE_TYPES = ["yes", "ifNeedBe", "no"] as const;
diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.ts
index bcfecbe47..76e5022b6 100644
--- a/apps/web/src/features/poll/data.ts
+++ b/apps/web/src/features/poll/data.ts
@@ -2,14 +2,24 @@ import "server-only";
import type { PollStatus, Prisma, VoteType } from "@rallly/database";
import { prisma } from "@rallly/database";
+import { shortUrl } from "@rallly/utils/absolute-url";
import { getInstancePolicy } from "@/features/instance-policy/data";
import { VOTE_TYPES } from "@/features/poll/constants";
+import type {
+ PollComment,
+ PollDetails,
+ PollUnavailableReason,
+} from "@/features/poll/types";
import { isLegacyEditToken } from "@/features/poll/utils";
import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";
import type {
AuthorizedSpaceId,
SpaceContentScope,
} from "@/features/space/types";
+import {
+ isSpaceAttributionHidden,
+ isSpaceBrandingActive,
+} from "@/features/space/utils";
import { decryptToken } from "@/lib/session";
export async function getPoll({
@@ -571,3 +581,199 @@ export async function getPollWithOptions({
const { _count, ...rest } = poll;
return { ...rest, participantCount: _count.participants };
}
+
+/**
+ * Whether a poll can be served at all, and why not. A poll that exists but
+ * must not be shown gets its own page instead of a 404: the viewer of a
+ * banned creator's poll is usually a scam target and needs to be told so,
+ * and a deleted poll's viewer deserves better than "page not found". The
+ * space owner counts as a creator too: an API key holder can organize polls
+ * under any member, and banning the payer must take every link in the
+ * space down with it.
+ */
+export async function getPollAvailability({ pollId }: { pollId: string }) {
+ const poll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ id: true,
+ title: true,
+ deleted: true,
+ user: { select: { name: true, banned: true } },
+ space: { select: { owner: { select: { banned: true } } } },
+ },
+ });
+
+ if (!poll) {
+ return null;
+ }
+
+ const unavailable: PollUnavailableReason | null = poll.deleted
+ ? "deleted"
+ : poll.user?.banned || poll.space?.owner.banned
+ ? "removed"
+ : null;
+
+ return {
+ id: poll.id,
+ title: poll.title,
+ authorName: poll.user?.name || "Guest",
+ unavailable,
+ };
+}
+
+/**
+ * The poll as both the invite page and the admin page show it. Null for a
+ * missing poll, a deleted one, or a banned creator's: all three are treated
+ * as if the poll never existed, for everyone including its owner. The space
+ * owner counts as a creator, as in getPollAvailability.
+ */
+export async function getPollDetails({
+ pollId,
+}: {
+ pollId: string;
+}): Promise<PollDetails | null> {
+ const poll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ id: true,
+ timeZone: true,
+ title: true,
+ location: true,
+ description: true,
+ createdAt: true,
+ status: true,
+ closedReason: true,
+ hideParticipants: true,
+ disableComments: true,
+ allowTentativeVotes: true,
+ hideScores: true,
+ requireParticipantEmail: true,
+ muted: true,
+ userId: true,
+ spaceId: true,
+ deleted: true,
+ options: {
+ select: { id: true, startTime: true, duration: true },
+ orderBy: { startTime: "asc" },
+ },
+ user: { select: { id: true, name: true, image: true, banned: true } },
+ space: {
+ select: {
+ name: true,
+ image: true,
+ tier: true,
+ showBranding: true,
+ hideAttribution: true,
+ primaryColor: true,
+ owner: { select: { banned: true } },
+ },
+ },
+ scheduledEvent: {
+ select: {
+ id: true,
+ start: true,
+ end: true,
+ allDay: true,
+ status: true,
+ },
+ },
+ },
+ });
+
+ if (!poll || poll.deleted || poll.user?.banned || poll.space?.owner.banned) {
+ return null;
+ }
+
+ const { spaceBrandingAllowed, spaceAttributionConfigurable } =
+ await getInstancePolicy();
+ const brandingActive = poll.space
+ ? isSpaceBrandingActive({ ...poll.space, spaceBrandingAllowed })
+ : false;
+
+ const {
+ scheduledEvent,
+ deleted: _deleted,
+ user,
+ space,
+ ...pollFields
+ } = poll;
+
+ return {
+ ...pollFields,
+ user: user ? { id: user.id, name: user.name, image: user.image } : null,
+ space: space
+ ? {
+ name: space.name,
+ image: space.image,
+ tier: space.tier,
+ showBranding: brandingActive,
+ primaryColor: brandingActive ? space.primaryColor : null,
+ hideAttribution: isSpaceAttributionHidden({
+ ...space,
+ spaceAttributionConfigurable,
+ }),
+ }
+ : null,
+ event: scheduledEvent
+ ? {
+ id: scheduledEvent.id,
+ start: scheduledEvent.start,
+ duration: scheduledEvent.allDay
+ ? 0
+ : Math.round(
+ (scheduledEvent.end.getTime() -
+ scheduledEvent.start.getTime()) /
+ 60_000,
+ ),
+ status: scheduledEvent.status,
+ }
+ : null,
+ inviteLink: shortUrl(`/invite/${poll.id}`),
+ };
+}
+
+/**
+ * Every response with its votes and edit token. Callers scope the output to
+ * the viewer before it leaves the server: the token is the edit credential
+ * and notes are for the host and their author only.
+ */
+export async function listPollParticipants({ pollId }: { pollId: string }) {
+ const participants = await prisma.participant.findMany({
+ where: { pollId },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ userId: true,
+ note: true,
+ token: true,
+ createdAt: true,
+ votes: { select: { optionId: true, type: true } },
+ user: { select: { image: true } },
+ },
+ orderBy: [{ createdAt: "desc" }, { name: "desc" }],
+ });
+
+ return participants.map(({ user, ...participant }) => ({
+ ...participant,
+ image: user?.image ?? null,
+ }));
+}
+
+export async function listPollComments({
+ pollId,
+}: {
+ pollId: string;
+}): Promise<PollComment[]> {
+ return prisma.comment.findMany({
+ where: { pollId },
+ select: {
+ id: true,
+ content: true,
+ authorName: true,
+ userId: true,
+ createdAt: true,
+ },
+ orderBy: [{ createdAt: "asc" }],
+ });
+}
diff --git a/apps/web/src/features/poll/invite/components/poll-unavailable.tsx b/apps/web/src/features/poll/invite/components/poll-unavailable.tsx
index bb7757968..0cc28250a 100644
--- a/apps/web/src/features/poll/invite/components/poll-unavailable.tsx
+++ b/apps/web/src/features/poll/invite/components/poll-unavailable.tsx
@@ -12,10 +12,9 @@ import {
import { InstanceFooterLinks } from "@/components/instance-footer-links";
import { Link } from "@/components/link";
import { DefaultLogo } from "@/features/branding/components/default-logo";
+import type { PollUnavailableReason } from "@/features/poll/types";
import { getTranslation } from "@/i18n/server";
-export type PollUnavailableReason = "deleted" | "removed";
-
function PollUnavailableShell({
footerLinks,
children,
diff --git a/apps/web/src/features/poll/loaders.ts b/apps/web/src/features/poll/loaders.ts
index bf754d042..b1576e35b 100644
--- a/apps/web/src/features/poll/loaders.ts
+++ b/apps/web/src/features/poll/loaders.ts
@@ -1,13 +1,25 @@
import "server-only";
-import { notFound } from "next/navigation";
+import { shortUrl } from "@rallly/utils/absolute-url";
+import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import {
+ canUserManagePoll,
getPoll,
+ getPollAvailability,
+ getPollDetails,
getPollStatusCounts,
listParticipantIdsByToken,
+ listPollComments,
+ listPollParticipants,
} from "@/features/poll/data";
+import { getPollInvitePath } from "@/features/poll/invite/utils";
+import {
+ filterCommentsForViewer,
+ maskParticipantsForViewer,
+} from "@/features/poll/utils";
import { getActiveSpaceContentScope } from "@/features/space/loaders";
+import { getSession } from "@/lib/auth";
export const loadPollStatusCounts = cache(async () => {
const scope = await getActiveSpaceContentScope();
@@ -33,3 +45,89 @@ export const loadParticipantIdsByToken = cache(
async (pollId: string, token: string) =>
listParticipantIdsByToken({ pollId, token }),
);
+
+export const loadPollAvailability = cache(async (pollId: string) =>
+ getPollAvailability({ pollId }),
+);
+
+/**
+ * The poll as a participant sees it. Deliberately no admin check: the
+ * invite page is the participant view, and the host reads the full list on
+ * the admin page. The emailed link names the viewer's own response, so a
+ * guest still sees it as theirs when opening the link in a fresh browser.
+ */
+export const loadInvitePoll = cache(
+ async ({ pollId, token }: { pollId: string; token?: string }) => {
+ const poll = await getPollDetails({ pollId });
+
+ if (!poll) {
+ notFound();
+ }
+
+ const [session, participants, comments, linkedParticipantIds] =
+ await Promise.all([
+ getSession(),
+ listPollParticipants({ pollId }),
+ listPollComments({ pollId }),
+ token ? listParticipantIdsByToken({ pollId, token }) : [],
+ ]);
+
+ const user = session?.user ?? null;
+ const viewer = { userId: user?.id ?? null, linkedParticipantIds };
+
+ return {
+ poll,
+ participants: maskParticipantsForViewer({
+ participants,
+ viewer,
+ hideParticipants: poll.hideParticipants,
+ }),
+ comments: filterCommentsForViewer({
+ comments,
+ viewerUserId: viewer.userId,
+ hideParticipants: poll.hideParticipants,
+ }),
+ linkedParticipantIds,
+ user,
+ };
+ },
+);
+
+/**
+ * The poll as its host sees it: every response with its note and edit link,
+ * every comment. Access is proven once here, so nothing downstream checks
+ * again. Anyone else lands on the invite page, the same place a guest does.
+ */
+export const loadAdminPoll = cache(async (pollId: string) => {
+ const poll = await getPollDetails({ pollId });
+
+ if (!poll) {
+ notFound();
+ }
+
+ const session = await getSession();
+ const user = session?.user;
+
+ if (!user || !(await canUserManagePoll(user, poll))) {
+ redirect(`/invite/${pollId}`);
+ }
+
+ const [participants, comments] = await Promise.all([
+ listPollParticipants({ pollId }),
+ listPollComments({ pollId }),
+ ]);
+
+ return {
+ poll,
+ // The host gets each response's edit link, the one its confirmation
+ // email carried, to hand to a respondent who left no email. Built from
+ // the same path so the two can never diverge.
+ participants: participants.map(({ token, ...participant }) => ({
+ ...participant,
+ hidden: false,
+ editUrl: shortUrl(getPollInvitePath({ pollId, token })),
+ })),
+ comments,
+ user,
+ };
+});
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 78fe3648f..1dca9f1ea 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -3,6 +3,7 @@ import "server-only";
import type { Prisma } from "@rallly/database";
import { prisma } from "@rallly/database";
import { nanoid } from "@rallly/utils/nanoid";
+import { revalidatePath } from "next/cache";
import { recordPollActivities } from "@/features/poll/activity/mutations";
import type { AuthorizedSpaceId } from "@/features/space/types";
@@ -400,3 +401,13 @@ export async function removeDeletedPolls() {
return totalDeletedPolls;
}
+
+/**
+ * The two pages that render a poll's responses and comments. Nothing they
+ * read is cached, so this only makes the action response carry a fresh
+ * render of the page that called it and drops the router's copy of both.
+ */
+export function revalidatePollPages() {
+ revalidatePath("/[locale]/invite/[urlId]", "page");
+ revalidatePath("/[locale]/(optional-space)/poll/[urlId]", "layout");
+}
diff --git a/apps/web/src/features/poll/participant/actions.ts b/apps/web/src/features/poll/participant/actions.ts
new file mode 100644
index 000000000..8e76ca04b
--- /dev/null
+++ b/apps/web/src/features/poll/participant/actions.ts
@@ -0,0 +1,345 @@
+"use server";
+
+import { sendNewParticipantEmail } from "@rallly/emails/templates/new-participant";
+import { sendNewParticipantConfirmationEmail } from "@rallly/emails/templates/new-participant-confirmation";
+import { createLogger } from "@rallly/logger";
+import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
+import { after } from "next/server";
+import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
+import { env } from "@/env";
+import { getNotificationRecipient } from "@/features/notifications/data";
+import { createUnsubscribeToken } from "@/features/notifications/utils";
+import {
+ getParticipant,
+ hasPollAdminAccess,
+ listParticipantIdsByToken,
+} from "@/features/poll/data";
+import { getPollInvitePath } from "@/features/poll/invite/utils";
+import {
+ addParticipant,
+ deleteParticipant,
+ renameParticipant,
+ updateParticipantVotes,
+} from "@/features/poll/participant/mutations";
+import {
+ addParticipantSchema,
+ deleteParticipantSchema,
+ renameParticipantSchema,
+ updateParticipantVotesSchema,
+} from "@/features/poll/participant/schema";
+import { getLocale } from "@/i18n/server/get-locale";
+import { AppError } from "@/lib/errors/app-error";
+import { track } from "@/lib/posthog";
+import {
+ anyUserActionClient,
+ createRateLimitMiddleware,
+ optionalUserActionClient,
+} from "@/lib/safe-action/server";
+
+const logger = createLogger("participants");
+
+type Actor = { id: string; isGuest: boolean };
+
+/**
+ * Proves the caller may edit a response. Two proofs are accepted: the token
+ * from the emailed link, which names the response itself, and a session that
+ * owns the response or administers its poll. Admin access is bound to the
+ * session only, so a link never unlocks other people's responses.
+ *
+ * A poll that is no longer open accepts no edits from anyone, admins
+ * included — the same rule `canEditParticipant` applies in the client. The
+ * lifecycle check comes first: whether the voting window has closed does not
+ * depend on who is asking.
+ *
+ * The returned actor is for attribution (activity log, analytics): the
+ * session when there is one, otherwise the user the response was created
+ * under, who was a guest at the time.
+ */
+async function authorizeParticipantEdit({
+ participantId,
+ token,
+ user,
+}: {
+ participantId: string;
+ token: string | undefined;
+ user: Actor | null;
+}) {
+ const participant = await getParticipant({ participantId });
+
+ if (!participant || participant.poll.deleted) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "Participant not found",
+ });
+ }
+
+ if (participant.poll.status !== "open") {
+ return { ok: false as const, reason: "closed" as const };
+ }
+
+ const ownedBySession = user
+ ? participant.userId === user.id ||
+ (await hasPollAdminAccess(participant.pollId, user.id))
+ : false;
+
+ const ownedByLink =
+ !ownedBySession && token
+ ? (
+ await listParticipantIdsByToken({ pollId: participant.pollId, token })
+ ).includes(participant.id)
+ : false;
+
+ if (!ownedBySession && !ownedByLink) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You are not allowed to modify this participant",
+ });
+ }
+
+ const actor: Actor | null =
+ user ??
+ (participant.userId ? { id: participant.userId, isGuest: true } : null);
+
+ return { ok: true as const, participant, actor };
+}
+
+async function sendNewResponseNotificationEmail({
+ pollId,
+ pollTitle,
+ participantName,
+ participantEmail,
+ note,
+ excludeUserId,
+}: {
+ pollId: string;
+ pollTitle: string;
+ participantName: string;
+ participantEmail: string | null;
+ note: string | null;
+ excludeUserId: string;
+}) {
+ try {
+ const recipient = await getNotificationRecipient({
+ pollId,
+ type: "poll.response.submitted",
+ excludeUserId,
+ });
+
+ if (!recipient) {
+ return;
+ }
+
+ const unsubscribeToken = createUnsubscribeToken({
+ target: { kind: "poll", pollId, userId: recipient.id },
+ secret: env.SECRET_PASSWORD,
+ });
+
+ await sendNewParticipantEmail({
+ to: recipient.email,
+ locale: recipient.locale ?? undefined,
+ branding: await getInstanceBranding(),
+ replyTo: participantEmail ?? undefined,
+ listUnsubscribeUrl: absoluteUrl(`/api/unsubscribe/${unsubscribeToken}`),
+ props: {
+ participantName,
+ note: note ?? undefined,
+ canReply: !!participantEmail,
+ pollUrl: absoluteUrl(`/poll/${pollId}`),
+ unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),
+ disableNotificationsUrl: absoluteUrl("/settings/notifications"),
+ title: pollTitle,
+ },
+ });
+ } catch (err) {
+ logger.error(
+ { error: err, pollId },
+ "Failed to send new response notification email",
+ );
+ }
+}
+
+export const addParticipantAction = anyUserActionClient
+ .metadata({ actionName: "add_participant" })
+ .use(createRateLimitMiddleware(10, "1 h"))
+ .inputSchema(addParticipantSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { pollId, votes, name, email, note, timeZone, token } = parsedInput;
+ const locale = await getLocale();
+
+ const result = await addParticipant({
+ pollId,
+ userId: ctx.user.id,
+ locale,
+ name,
+ email,
+ note,
+ timeZone,
+ token,
+ votes,
+ });
+
+ if (!result.ok) {
+ return result;
+ }
+
+ const { participant, poll, editToken, viaInvite, totalResponses } = result;
+
+ if (email) {
+ after(async () =>
+ sendNewParticipantConfirmationEmail({
+ to: email,
+ locale,
+ branding: poll.space
+ ? await getSpaceBranding(poll.space)
+ : await getInstanceBranding(),
+ props: {
+ title: poll.title,
+ editSubmissionUrl: shortUrl(
+ getPollInvitePath({ pollId: poll.id, token: editToken }),
+ ),
+ },
+ }),
+ );
+ }
+
+ after(() =>
+ sendNewResponseNotificationEmail({
+ pollId,
+ pollTitle: poll.title,
+ participantName: participant.name,
+ participantEmail: participant.email,
+ note: participant.note,
+ excludeUserId: ctx.user.id,
+ }),
+ );
+
+ const voteCounts = votes.reduce(
+ (acc, { type }) => {
+ acc[type] += 1;
+ return acc;
+ },
+ { yes: 0, ifNeedBe: 0, no: 0 },
+ );
+
+ track(ctx.user, {
+ event: "poll_response_submit",
+ properties: {
+ participant_id: participant.id,
+ // plain properties, not groups: guest events are personless and
+ // PostHog drops group associations without person processing
+ poll_id: pollId,
+ space_id: poll.space?.id,
+ tier: poll.space?.tier,
+ has_email: !!email,
+ via_invite: viaInvite,
+ has_note: !!participant.note,
+ note_length: participant.note?.length,
+ total_responses: totalResponses,
+ // Whether the tentative option is offered at all, so the counts
+ // below can be read against the polls that actually had it.
+ allow_tentative_votes: poll.allowTentativeVotes,
+ yes_count: voteCounts.yes,
+ if_need_be_count: voteCounts.ifNeedBe,
+ no_count: voteCounts.no,
+ },
+ groups: { poll: pollId },
+ });
+
+ return { ok: true as const, participant: { id: participant.id } };
+ });
+
+export const updateParticipantVotesAction = optionalUserActionClient
+ .metadata({ actionName: "update_participant_votes" })
+ .inputSchema(updateParticipantVotesSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { participantId, votes, token } = parsedInput;
+
+ const authorization = await authorizeParticipantEdit({
+ participantId,
+ token,
+ user: ctx.user,
+ });
+
+ if (!authorization.ok) {
+ return authorization;
+ }
+
+ const { participant, actor } = authorization;
+
+ const result = await updateParticipantVotes({
+ participantId,
+ pollId: participant.pollId,
+ actorUserId: actor?.id,
+ votes,
+ });
+
+ if (result.ok && actor) {
+ track(actor, {
+ event: "poll_response_update",
+ groups: { poll: participant.pollId },
+ });
+ }
+
+ return result;
+ });
+
+export const renameParticipantAction = optionalUserActionClient
+ .metadata({ actionName: "rename_participant" })
+ .inputSchema(renameParticipantSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { participantId, name, token } = parsedInput;
+
+ const authorization = await authorizeParticipantEdit({
+ participantId,
+ token,
+ user: ctx.user,
+ });
+
+ if (!authorization.ok) {
+ return authorization;
+ }
+
+ const { participant, actor } = authorization;
+
+ return renameParticipant({
+ participantId,
+ pollId: participant.pollId,
+ actorUserId: actor?.id,
+ name,
+ });
+ });
+
+export const deleteParticipantAction = optionalUserActionClient
+ .metadata({ actionName: "delete_participant" })
+ .inputSchema(deleteParticipantSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { participantId, token } = parsedInput;
+
+ const authorization = await authorizeParticipantEdit({
+ participantId,
+ token,
+ user: ctx.user,
+ });
+
+ if (!authorization.ok) {
+ return authorization;
+ }
+
+ const { participant, actor } = authorization;
+
+ const result = await deleteParticipant({
+ participantId,
+ pollId: participant.pollId,
+ actorUserId: actor?.id,
+ });
+
+ if (result.ok && actor) {
+ track(actor, {
+ event: "poll_response_delete",
+ properties: { participant_id: participant.id },
+ groups: { poll: participant.pollId },
+ });
+ }
+
+ return result;
+ });
diff --git a/apps/web/src/features/poll/participant/mutations.ts b/apps/web/src/features/poll/participant/mutations.ts
new file mode 100644
index 000000000..709bf4539
--- /dev/null
+++ b/apps/web/src/features/poll/participant/mutations.ts
@@ -0,0 +1,438 @@
+import "server-only";
+
+import type { Prisma, VoteType } from "@rallly/database";
+import { prisma } from "@rallly/database";
+import { recordPollActivities } from "@/features/poll/activity/mutations";
+import { MAX_PARTICIPANTS } from "@/features/poll/constants";
+import {
+ attachParticipantToInvite,
+ findPendingPollInvite,
+} from "@/features/poll/invite/mutations";
+import { revalidatePollPages } from "@/features/poll/mutations";
+import { generateAccessToken } from "@/features/poll/utils";
+import type { SpaceTier } from "@/features/space/schema";
+
+type WriteRefusal = "notFound" | "closed" | "full" | "tentativeVotesNotAllowed";
+
+class WriteRefusedError extends Error {
+ constructor(public readonly reason: WriteRefusal) {
+ super(reason);
+ }
+}
+
+/**
+ * Locks the poll row for the rest of the transaction and proves the poll
+ * still accepts writes. The organizer's close, delete and settings
+ * transitions update the same row, so under READ COMMITTED a check made
+ * before the transaction could pass while one of them commits in between.
+ * Bans live on the user rows and are checked by the caller before the
+ * transaction: their writers do not take this lock, and a response that
+ * lands during a ban is removed with the poll anyway.
+ */
+async function lockOpenPoll(
+ tx: Prisma.TransactionClient,
+ pollId: string,
+ votes: { type: VoteType }[],
+) {
+ const [poll] = await tx.$queryRaw<
+ { status: string; deleted: boolean; allow_tentative_votes: boolean }[]
+ >`
+ SELECT status, deleted, allow_tentative_votes
+ FROM polls WHERE id = ${pollId} FOR UPDATE
+ `;
+
+ if (!poll || poll.deleted) {
+ throw new WriteRefusedError("notFound");
+ }
+
+ // The voting window is the organizer's control, so it has to hold here
+ // and not only in the client, which hides the form via
+ // `canAddNewParticipant` and `canEditParticipant`.
+ if (poll.status !== "open") {
+ throw new WriteRefusedError("closed");
+ }
+
+ if (
+ !poll.allow_tentative_votes &&
+ votes.some((vote) => vote.type === "ifNeedBe")
+ ) {
+ throw new WriteRefusedError("tentativeVotesNotAllowed");
+ }
+}
+
+/**
+ * The response may have been deleted between the action's authorization and
+ * this transaction. Every participant write takes the poll row lock first,
+ * so a read under it is current for the rest of the transaction.
+ */
+async function assertParticipantInPoll(
+ tx: Prisma.TransactionClient,
+ participantId: string,
+ pollId: string,
+) {
+ const participant = await tx.participant.findFirst({
+ where: { id: participantId, pollId },
+ select: { id: true },
+ });
+
+ if (!participant) {
+ throw new WriteRefusedError("notFound");
+ }
+}
+
+async function listValidOptionIds(
+ tx: Prisma.TransactionClient,
+ pollId: string,
+) {
+ const options = await tx.option.findMany({
+ where: { pollId },
+ select: { id: true },
+ });
+ return new Set(options.map((option) => option.id));
+}
+
+function refusal(error: unknown) {
+ if (error instanceof WriteRefusedError) {
+ return { ok: false as const, reason: error.reason };
+ }
+ throw error;
+}
+
+export type AddParticipantResult =
+ | {
+ ok: true;
+ participant: {
+ id: string;
+ name: string;
+ email: string | null;
+ note: string | null;
+ };
+ poll: {
+ id: string;
+ title: string;
+ allowTentativeVotes: boolean;
+ space: {
+ id: string;
+ tier: SpaceTier;
+ showBranding: boolean;
+ hideAttribution: boolean;
+ primaryColor: string | null;
+ image: string | null;
+ } | null;
+ };
+ editToken: string;
+ viaInvite: boolean;
+ totalResponses: number;
+ }
+ | { ok: false; reason: WriteRefusal };
+
+export async function addParticipant({
+ pollId,
+ userId,
+ locale,
+ name,
+ email,
+ note,
+ timeZone,
+ token,
+ votes,
+}: {
+ pollId: string;
+ userId: string;
+ locale: string;
+ name: string;
+ email?: string;
+ note?: string;
+ timeZone?: string;
+ token?: string;
+ votes: { optionId: string; type: VoteType }[];
+}): Promise<AddParticipantResult> {
+ const poll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ user: { select: { banned: true } },
+ space: { select: { owner: { select: { banned: true } } } },
+ },
+ });
+
+ // A poll whose creator or space owner was banned never accepts responses.
+ if (!poll || poll.user?.banned || poll.space?.owner.banned) {
+ return { ok: false, reason: "notFound" };
+ }
+
+ try {
+ const result = await prisma.$transaction(async (tx) => {
+ const validOptionIds = await listValidOptionIds(tx, pollId);
+ const validVotes = votes.filter(({ optionId }) =>
+ validOptionIds.has(optionId),
+ );
+
+ await lockOpenPoll(tx, pollId, validVotes);
+
+ // Counted under the lock so two responses cannot both pass at the cap.
+ const participantCount = await tx.participant.count({
+ where: { pollId },
+ });
+
+ if (participantCount >= MAX_PARTICIPANTS) {
+ throw new WriteRefusedError("full");
+ }
+
+ // A response answering an emailed invite takes the invite's token, so
+ // the link the invitee already holds names it.
+ const invite = token
+ ? await findPendingPollInvite(tx, { pollId, token })
+ : null;
+ const editToken = invite?.token ?? generateAccessToken();
+
+ const participant = await tx.participant.create({
+ data: {
+ pollId,
+ name,
+ email,
+ note,
+ timeZone,
+ token: editToken,
+ userId,
+ locale,
+ votes: {
+ createMany: {
+ data: validVotes.map(({ optionId, type }) => ({
+ pollId,
+ optionId,
+ type,
+ })),
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ note: true,
+ poll: {
+ select: {
+ id: true,
+ title: true,
+ allowTentativeVotes: true,
+ space: {
+ select: {
+ id: true,
+ tier: true,
+ showBranding: true,
+ hideAttribution: true,
+ primaryColor: true,
+ image: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_created",
+ userId,
+ participantId: participant.id,
+ payload: { name: participant.name },
+ },
+ ]);
+
+ if (invite) {
+ await attachParticipantToInvite(tx, {
+ inviteId: invite.id,
+ participantId: participant.id,
+ });
+ }
+
+ const { poll, ...participantFields } = participant;
+
+ return {
+ participant: participantFields,
+ poll,
+ editToken,
+ viaInvite: invite !== null,
+ totalResponses: participantCount + 1,
+ };
+ });
+
+ revalidatePollPages();
+
+ return { ok: true, ...result };
+ } catch (error) {
+ return refusal(error);
+ }
+}
+
+export type EditParticipantResult =
+ | { ok: true }
+ | { ok: false; reason: WriteRefusal };
+
+export async function updateParticipantVotes({
+ participantId,
+ pollId,
+ actorUserId,
+ votes,
+}: {
+ participantId: string;
+ pollId: string;
+ actorUserId: string | undefined;
+ votes: { optionId: string; type: VoteType }[];
+}): Promise<EditParticipantResult> {
+ try {
+ await prisma.$transaction(async (tx) => {
+ await lockOpenPoll(tx, pollId, votes);
+ await assertParticipantInPoll(tx, participantId, pollId);
+
+ await tx.vote.deleteMany({ where: { participantId } });
+
+ const validOptionIds = await listValidOptionIds(tx, pollId);
+ const validVotes = votes.filter(({ optionId }) =>
+ validOptionIds.has(optionId),
+ );
+
+ await tx.vote.createMany({
+ data: validVotes.map(({ optionId, type }) => ({
+ optionId,
+ type,
+ pollId,
+ participantId,
+ })),
+ });
+
+ // Bump `updatedAt` so it reflects this vote change; the poll cleanup
+ // job uses it to detect recent activity. An empty `data: {}` update is
+ // a no-op for `@updatedAt`, so set it explicitly.
+ const participant = await tx.participant.update({
+ where: { id: participantId },
+ data: { updatedAt: new Date() },
+ select: { name: true },
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_updated",
+ userId: actorUserId,
+ participantId,
+ payload: { name: participant.name },
+ },
+ ]);
+ });
+ } catch (error) {
+ return refusal(error);
+ }
+
+ revalidatePollPages();
+
+ return { ok: true };
+}
+
+export async function renameParticipant({
+ participantId,
+ pollId,
+ actorUserId,
+ name,
+}: {
+ participantId: string;
+ pollId: string;
+ actorUserId: string | undefined;
+ name: string;
+}): Promise<EditParticipantResult> {
+ try {
+ await prisma.$transaction(async (tx) => {
+ await lockOpenPoll(tx, pollId, []);
+ await assertParticipantInPoll(tx, participantId, pollId);
+
+ await tx.participant.update({
+ where: { id: participantId },
+ data: { name },
+ select: null,
+ });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_updated",
+ userId: actorUserId,
+ participantId,
+ payload: { name },
+ },
+ ]);
+ });
+ } catch (error) {
+ return refusal(error);
+ }
+
+ revalidatePollPages();
+
+ return { ok: true };
+}
+
+export async function deleteParticipant({
+ participantId,
+ pollId,
+ actorUserId,
+}: {
+ participantId: string;
+ pollId: string;
+ actorUserId: string | undefined;
+}): Promise<EditParticipantResult> {
+ try {
+ await prisma.$transaction(async (tx) => {
+ await lockOpenPoll(tx, pollId, []);
+
+ // Snapshot before the delete: the activity payload is the historical
+ // record of the removed response, so it carries the name and votes.
+ const snapshot = await tx.participant.findFirst({
+ where: { id: participantId, pollId },
+ select: {
+ name: true,
+ votes: {
+ select: {
+ optionId: true,
+ type: true,
+ option: { select: { startTime: true, duration: true } },
+ },
+ },
+ },
+ });
+
+ if (!snapshot) {
+ throw new WriteRefusedError("notFound");
+ }
+
+ // Hard delete: votes cascade, the invite's SetNull FK reverts it to
+ // pending, and the response frees the token it took from that invite
+ // so the next response through the same link can take it again. The
+ // activity row above is the historical record.
+ await tx.participant.delete({ where: { id: participantId } });
+
+ await recordPollActivities(tx, [
+ {
+ pollId,
+ type: "response_deleted",
+ userId: actorUserId,
+ participantId,
+ payload: {
+ name: snapshot.name,
+ votes: snapshot.votes.map((vote) => ({
+ optionId: vote.optionId,
+ start: vote.option.startTime.toISOString(),
+ duration: vote.option.duration,
+ type: vote.type,
+ })),
+ },
+ },
+ ]);
+ });
+ } catch (error) {
+ return refusal(error);
+ }
+
+ revalidatePollPages();
+
+ return { ok: true };
+}
diff --git a/apps/web/src/features/poll/participant/schema.test.ts b/apps/web/src/features/poll/participant/schema.test.ts
new file mode 100644
index 000000000..63dd71d68
--- /dev/null
+++ b/apps/web/src/features/poll/participant/schema.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { MAX_RESPONSE_NOTE_LENGTH } from "@/features/poll/schema";
+import { addParticipantSchema, responseNoteInput } from "./schema";
+
+describe("responseNoteInput", () => {
+ it("trims surrounding whitespace", () => {
+ expect(responseNoteInput.parse(" running late ")).toBe("running late");
+ });
+
+ it("collapses a whitespace only note to undefined", () => {
+ expect(responseNoteInput.parse(" \n ")).toBeUndefined();
+ });
+
+ it("keeps undefined as undefined", () => {
+ expect(responseNoteInput.parse(undefined)).toBeUndefined();
+ });
+
+ it("rejects notes over the maximum length", () => {
+ expect(() =>
+ responseNoteInput.parse("a".repeat(MAX_RESPONSE_NOTE_LENGTH + 1)),
+ ).toThrow();
+ });
+
+ it("accepts a note at the maximum length", () => {
+ const note = "a".repeat(MAX_RESPONSE_NOTE_LENGTH);
+ expect(responseNoteInput.parse(note)).toBe(note);
+ });
+});
+
+describe("addParticipantSchema email", () => {
+ it("normalizes a blank email to undefined", () => {
+ expect(
+ addParticipantSchema.parse({
+ pollId: "p",
+ name: "A",
+ email: " ",
+ votes: [],
+ }).email,
+ ).toBeUndefined();
+ });
+
+ it("rejects a malformed email", () => {
+ expect(
+ addParticipantSchema.safeParse({
+ pollId: "p",
+ name: "A",
+ email: "not-an-email",
+ votes: [],
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/poll/participant/schema.ts b/apps/web/src/features/poll/participant/schema.ts
new file mode 100644
index 000000000..49d95a5d0
--- /dev/null
+++ b/apps/web/src/features/poll/participant/schema.ts
@@ -0,0 +1,53 @@
+import * as z from "zod";
+import { MAX_RESPONSE_NOTE_LENGTH } from "@/features/poll/schema";
+
+// Whitespace-only notes collapse to undefined so no empty string is persisted.
+export const responseNoteInput = z
+ .string()
+ .trim()
+ .max(MAX_RESPONSE_NOTE_LENGTH)
+ .optional()
+ .transform((value) => value || undefined);
+
+const participantNameInput = z.string().trim().min(1).max(100);
+
+const voteInput = z.object({
+ optionId: z.string(),
+ type: z.enum(["yes", "no", "ifNeedBe"]),
+});
+
+export type VoteInput = z.infer<typeof voteInput>;
+
+export const addParticipantSchema = z.object({
+ pollId: z.string(),
+ name: participantNameInput,
+ // The form sends "" for a blank optional email.
+ email: z
+ .string()
+ .trim()
+ .optional()
+ .transform((value) => value || undefined)
+ .pipe(z.email().optional()),
+ note: responseNoteInput,
+ timeZone: z.string().optional(),
+ // The token from an emailed invite link; the response takes it over.
+ token: z.string().optional(),
+ votes: voteInput.array(),
+});
+
+export const updateParticipantVotesSchema = z.object({
+ participantId: z.string(),
+ votes: voteInput.array(),
+ token: z.string().optional(),
+});
+
+export const renameParticipantSchema = z.object({
+ participantId: z.string(),
+ name: participantNameInput,
+ token: z.string().optional(),
+});
+
+export const deleteParticipantSchema = z.object({
+ participantId: z.string(),
+ token: z.string().optional(),
+});
diff --git a/apps/web/src/features/poll/types.ts b/apps/web/src/features/poll/types.ts
new file mode 100644
index 000000000..810c9bbd6
--- /dev/null
+++ b/apps/web/src/features/poll/types.ts
@@ -0,0 +1,61 @@
+import type { VoteType } from "@/features/poll/constants";
+import type { PollClosedReason, PollStatus } from "@/features/poll/schema";
+import type { SpaceTier } from "@/features/space/schema";
+
+export type PollUnavailableReason = "deleted" | "removed";
+
+export type PollDetails = {
+ id: string;
+ title: string;
+ location: string | null;
+ description: string | null;
+ createdAt: Date;
+ status: PollStatus;
+ closedReason: PollClosedReason | null;
+ hideParticipants: boolean;
+ disableComments: boolean;
+ allowTentativeVotes: boolean;
+ hideScores: boolean;
+ requireParticipantEmail: boolean;
+ muted: boolean;
+ timeZone: string | null;
+ userId: string | null;
+ spaceId: string | null;
+ options: { id: string; startTime: Date; duration: number }[];
+ user: { id: string; name: string; image: string | null } | null;
+ space: {
+ name: string;
+ image: string | null;
+ tier: SpaceTier;
+ showBranding: boolean;
+ hideAttribution: boolean;
+ primaryColor: string | null;
+ } | null;
+ event: { id: string; start: Date; duration: number; status: string } | null;
+ inviteLink: string;
+};
+
+export type Vote = { optionId: string; type: VoteType };
+
+export type PollParticipant = {
+ id: string;
+ name: string;
+ email: string | null;
+ userId: string | null;
+ note: string | null;
+ image: string | null;
+ createdAt: Date;
+ votes: Vote[];
+ /** Identity withheld from this viewer (hidden participants setting). */
+ hidden: boolean;
+ /** The response's edit link; only the host's list carries it. */
+ editUrl: string | null;
+};
+
+export type PollComment = {
+ id: string;
+ content: string;
+ authorName: string;
+ userId: string | null;
+ createdAt: Date;
+};
diff --git a/apps/web/src/features/poll/utils.test.ts b/apps/web/src/features/poll/utils.test.ts
new file mode 100644
index 000000000..97db8a115
--- /dev/null
+++ b/apps/web/src/features/poll/utils.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it } from "vitest";
+import {
+ filterCommentsForViewer,
+ filterParticipantsByVote,
+ maskParticipantsForViewer,
+} from "./utils";
+
+const participant = (
+ id: string,
+ overrides: Partial<{
+ userId: string | null;
+ note: string | null;
+ email: string | null;
+ }> = {},
+) => ({
+ id,
+ name: `Name ${id}`,
+ email: overrides.email ?? `${id}@example.com`,
+ userId: overrides.userId ?? null,
+ note: overrides.note ?? `Note ${id}`,
+ image: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ token: `token-${id}`,
+ votes: [{ optionId: "opt-1", type: "yes" as const }],
+});
+
+describe("maskParticipantsForViewer", () => {
+ it("keeps notes only for the viewer's own responses", () => {
+ const result = maskParticipantsForViewer({
+ participants: [
+ participant("a", { userId: "user-1" }),
+ participant("b", { userId: "user-2" }),
+ participant("c"),
+ ],
+ viewer: { userId: "user-1", linkedParticipantIds: ["c"] },
+ hideParticipants: false,
+ });
+
+ expect(result.map((p) => p.note)).toEqual(["Note a", null, "Note c"]);
+ });
+
+ it("never exposes the edit token or an edit link", () => {
+ const [result] = maskParticipantsForViewer({
+ participants: [participant("a")],
+ viewer: { userId: null, linkedParticipantIds: [] },
+ hideParticipants: false,
+ });
+
+ expect(result).not.toHaveProperty("token");
+ expect(result.editUrl).toBeNull();
+ expect(result.hidden).toBe(false);
+ });
+
+ it("withholds identity of other participants when hidden", () => {
+ const result = maskParticipantsForViewer({
+ participants: [
+ participant("a", { userId: "user-1" }),
+ participant("b", { userId: "user-2" }),
+ ],
+ viewer: { userId: "user-1", linkedParticipantIds: [] },
+ hideParticipants: true,
+ });
+
+ expect(result[0]).toMatchObject({
+ name: "Name a",
+ email: "[email protected]",
+ userId: "user-1",
+ hidden: false,
+ });
+ expect(result[1]).toMatchObject({
+ name: "",
+ email: null,
+ userId: null,
+ image: null,
+ note: null,
+ hidden: true,
+ });
+ expect(result[1].votes).toEqual([{ optionId: "opt-1", type: "yes" }]);
+ });
+});
+
+describe("filterCommentsForViewer", () => {
+ const comments = [
+ {
+ id: "1",
+ content: "a",
+ authorName: "A",
+ userId: "user-1",
+ createdAt: new Date(),
+ },
+ {
+ id: "2",
+ content: "b",
+ authorName: "B",
+ userId: "user-2",
+ createdAt: new Date(),
+ },
+ ];
+
+ it("returns every comment when participants are visible", () => {
+ expect(
+ filterCommentsForViewer({
+ comments,
+ viewerUserId: null,
+ hideParticipants: false,
+ }),
+ ).toHaveLength(2);
+ });
+
+ it("returns nothing to an anonymous viewer when participants are hidden", () => {
+ expect(
+ filterCommentsForViewer({
+ comments,
+ viewerUserId: null,
+ hideParticipants: true,
+ }),
+ ).toEqual([]);
+ });
+
+ it("returns only the viewer's comments when participants are hidden", () => {
+ expect(
+ filterCommentsForViewer({
+ comments,
+ viewerUserId: "user-2",
+ hideParticipants: true,
+ }).map((c) => c.id),
+ ).toEqual(["2"]);
+ });
+});
+
+describe("filterParticipantsByVote", () => {
+ it("keeps participants who cast the given vote on the option", () => {
+ const result = filterParticipantsByVote(
+ [
+ { id: "a", votes: [{ optionId: "opt-1", type: "yes" as const }] },
+ { id: "b", votes: [{ optionId: "opt-1", type: "no" as const }] },
+ ],
+ "opt-1",
+ "yes",
+ );
+ expect(result.map((p) => p.id)).toEqual(["a"]);
+ });
+});
diff --git a/apps/web/src/features/poll/utils.ts b/apps/web/src/features/poll/utils.ts
index a8b6a6b32..151b79232 100644
--- a/apps/web/src/features/poll/utils.ts
+++ b/apps/web/src/features/poll/utils.ts
@@ -1,4 +1,6 @@
import { customAlphabet } from "nanoid";
+import type { VoteType } from "@/features/poll/constants";
+import type { PollComment, PollParticipant } from "@/features/poll/types";
// Alphanumeric only: url safe with no linkifier edge cases. 32 chars is the
// floor documented on Participant.token and PollInvite.token.
@@ -15,3 +17,80 @@ export const generateAccessToken = customAlphabet(
export function isLegacyEditToken(token: string) {
return token.startsWith("Fe26.2*");
}
+
+export function filterParticipantsByVote<
+ T extends { votes: { optionId: string; type: VoteType }[] },
+>(participants: T[], optionId: string, voteType: VoteType): T[] {
+ return participants.filter((participant) => {
+ return participant.votes.some((vote) => {
+ return vote.optionId === optionId && vote.type === voteType;
+ });
+ });
+}
+
+type RawParticipant = Omit<PollParticipant, "hidden" | "editUrl"> & {
+ token: string;
+};
+
+/**
+ * Scopes the response list to a viewer who is not the host. Notes are for
+ * the host and their author only, so they survive only on the viewer's own
+ * responses: the ones their session created, or the one the emailed link
+ * they opened names. With hidden participants, everyone else's identity is
+ * withheld while their votes still count.
+ */
+export function maskParticipantsForViewer({
+ participants,
+ viewer,
+ hideParticipants,
+}: {
+ participants: RawParticipant[];
+ viewer: { userId: string | null; linkedParticipantIds: string[] };
+ hideParticipants: boolean;
+}): PollParticipant[] {
+ const linkedIds = new Set(viewer.linkedParticipantIds);
+ const isOwn = (participant: { id: string; userId: string | null }) =>
+ linkedIds.has(participant.id) ||
+ (!!viewer.userId && participant.userId === viewer.userId);
+
+ return participants.map(({ token: _token, ...participant }) => {
+ if (isOwn(participant)) {
+ return { ...participant, hidden: false, editUrl: null };
+ }
+ if (hideParticipants) {
+ return {
+ ...participant,
+ userId: null,
+ name: "",
+ email: null,
+ image: null,
+ note: null,
+ hidden: true,
+ editUrl: null,
+ };
+ }
+ return { ...participant, note: null, hidden: false, editUrl: null };
+ });
+}
+
+/**
+ * With hidden participants, a viewer who is not the host sees only their
+ * own comments; the author names would otherwise reveal who responded.
+ */
+export function filterCommentsForViewer({
+ comments,
+ viewerUserId,
+ hideParticipants,
+}: {
+ comments: PollComment[];
+ viewerUserId: string | null;
+ hideParticipants: boolean;
+}): PollComment[] {
+ if (!hideParticipants) {
+ return comments;
+ }
+ if (!viewerUserId) {
+ return [];
+ }
+ return comments.filter((comment) => comment.userId === viewerUserId);
+}
diff --git a/apps/web/src/features/user/loaders.ts b/apps/web/src/features/user/loaders.ts
index 81423023b..18747e5a3 100644
--- a/apps/web/src/features/user/loaders.ts
+++ b/apps/web/src/features/user/loaders.ts
@@ -31,6 +31,28 @@ export const getCurrentUser = cache(async () => {
return user;
});
+/**
+ * The session's user, guest or member, fetched from the database. For
+ * writes a guest may perform (responding to a poll, commenting). Returns
+ * null when there is no session; throws InvalidSessionError when the
+ * session references a user that no longer exists or is banned.
+ */
+export const getCurrentActor = cache(async () => {
+ const session = await getSession();
+
+ if (!session?.user) {
+ return null;
+ }
+
+ const user = await getUser(session.user.id);
+
+ if (!user || user.banned) {
+ throw new InvalidSessionError();
+ }
+
+ return user;
+});
+
/**
* Gate for server pages that require a logged-in (non-guest) user.
* Trusts the session cookie cache (no database read). Redirects to /login
diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.ts
index 30111fdfd..7d5e698b4 100644
--- a/apps/web/src/lib/safe-action/server.ts
+++ b/apps/web/src/lib/safe-action/server.ts
@@ -6,7 +6,7 @@ import { after } from "next/server";
import { createMiddleware, createSafeActionClient } from "next-safe-action";
import * as z from "zod";
import { defineAbilityFor } from "@/features/user/ability";
-import { getCurrentUser } from "@/features/user/loaders";
+import { getCurrentActor, getCurrentUser } from "@/features/user/loaders";
import { signOut } from "@/lib/auth";
import { AppError } from "@/lib/errors/app-error";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
@@ -131,6 +131,38 @@ export const authActionClient = actionClient.use(async ({ next }) => {
});
});
+/**
+ * For writes on public pages: the session user may be a guest, and there
+ * may be none at all when the credential is a token from an emailed link.
+ */
+export const optionalUserActionClient = actionClient.use(async ({ next }) => {
+ const user = await getCurrentActor();
+
+ return next({
+ ctx: { user },
+ });
+});
+
+/**
+ * For writes a guest may perform. The client creates the guest session
+ * first (createGuestIfNeeded), so a missing user is a stale page, not an
+ * anonymous visitor.
+ */
+export const anyUserActionClient = optionalUserActionClient.use(
+ async ({ ctx, next }) => {
+ if (!ctx.user) {
+ throw new AppError({
+ code: "UNAUTHORIZED",
+ message: "You are not authenticated.",
+ });
+ }
+
+ return next({
+ ctx: { user: ctx.user },
+ });
+ },
+);
+
export const adminActionClient = authActionClient.use(async ({ ctx, next }) => {
if (ctx.user.role !== "admin") {
throw new AppError({
diff --git a/apps/web/src/trpc/client/types.ts b/apps/web/src/trpc/client/types.ts
deleted file mode 100644
index ca74755b1..000000000
--- a/apps/web/src/trpc/client/types.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { PollStatus, VoteType } from "@rallly/database";
-
-export type GetPollApiResponse = {
- id: string;
- title: string;
- location: string | null;
- description: string | null;
- options: { id: string; startTime: Date; duration: number }[];
- user: {
- id: string;
- name: string;
- image: string | null;
- banned: boolean;
- } | null;
- timeZone: string | null;
- allowTentativeVotes: boolean;
- canManage: boolean;
- status: PollStatus;
- createdAt: Date;
- deleted: boolean;
- event: {
- id: string;
- start: Date;
- duration: number;
- status: string;
- } | null;
-};
-
-export type Vote = {
- optionId: string;
- type: VoteType;
-};
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 51b017c59..1477cd476 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -36,9 +36,7 @@ import {
router,
spaceProcedure,
} from "../trpc";
-import { comments } from "./polls/comments";
import { invites } from "./polls/invites";
-import { participants } from "./polls/participants";
import { getScheduledEventTimes } from "./polls/scheduled-event-times";
import { timeZoneInput } from "./polls/schema";
@@ -52,8 +50,6 @@ const optionEndsInFuture = (option: { startTime: Date; duration: number }) =>
.isAfter(dayjs());
export const polls = router({
- participants,
- comments,
invites,
infiniteChronological: spaceProcedure
.input(
diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.ts
deleted file mode 100644
index 9367c9f76..000000000
--- a/apps/web/src/trpc/routers/polls/comments.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import { prisma } from "@rallly/database";
-import { sendNewCommentEmail } from "@rallly/emails/templates/new-comment";
-import { createLogger } from "@rallly/logger";
-import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { TRPCError } from "@trpc/server";
-import { after } from "next/server";
-import * as z from "zod";
-import { getInstanceBranding } from "@/emails/branding";
-import { env } from "@/env";
-import { getNotificationRecipient } from "@/features/notifications/data";
-import { createUnsubscribeToken } from "@/features/notifications/utils";
-import { hasPollAdminAccess } from "@/features/poll/data";
-import {
- MAX_COMMENT_AUTHOR_NAME_LENGTH,
- MAX_COMMENT_LENGTH,
-} from "@/features/poll/schema";
-import { track } from "@/lib/posthog";
-import {
- createRateLimitMiddleware,
- publicProcedure,
- requireUserMiddleware,
- router,
-} from "../../trpc";
-
-const logger = createLogger("comments");
-
-export const comments = router({
- list: publicProcedure
- .input(
- z.object({
- pollId: z.string(),
- hideParticipants: z.boolean().optional(), // @deprecated
- }),
- )
- .query(async ({ input: { pollId }, ctx }) => {
- const poll = await prisma.poll.findUnique({
- where: {
- id: pollId,
- },
- select: {
- userId: true,
- hideParticipants: true,
- deleted: true,
- user: { select: { banned: true } },
- },
- });
-
- // A deleted poll, or one whose creator was banned, never exposes its
- // comments.
- if (!poll || poll.deleted || poll.user?.banned) {
- throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });
- }
-
- const isOwner = poll.userId === ctx.user?.id;
-
- const hideParticipants = poll.hideParticipants && !isOwner;
-
- if (hideParticipants && !isOwner) {
- // if hideParticipants is enabled and the user is not the owner
- if (!ctx.user) {
- // cannot see any comments if there is no user
- return [];
- } else {
- // only show comments created by the current users
- return await prisma.comment.findMany({
- where: {
- pollId,
- userId: ctx.user.id,
- },
- orderBy: [
- {
- createdAt: "asc",
- },
- ],
- });
- }
- }
- // return all comments
- return await prisma.comment.findMany({
- where: { pollId },
- orderBy: [
- {
- createdAt: "asc",
- },
- ],
- });
- }),
- add: publicProcedure
- .use(createRateLimitMiddleware("add_comment", 10, "1 m"))
- .use(requireUserMiddleware)
- .input(
- z.object({
- pollId: z.string(),
- authorName: z
- .string()
- .trim()
- .min(1)
- .max(MAX_COMMENT_AUTHOR_NAME_LENGTH),
- content: z.string().trim().min(1).max(MAX_COMMENT_LENGTH),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const targetPoll = await prisma.poll.findUnique({
- where: {
- id: input.pollId,
- },
- select: {
- disableComments: true,
- deleted: true,
- user: { select: { banned: true } },
- },
- });
-
- // A deleted poll, or one whose creator was banned, never accepts new
- // comments.
- if (!targetPoll || targetPoll.deleted || targetPoll.user?.banned) {
- throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });
- }
-
- // The comment UI is hidden when the host turns comments off, but the
- // setting is only real if the mutation enforces it too.
- if (targetPoll.disableComments) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Comments are disabled for this poll",
- });
- }
-
- let authorName = input.authorName;
-
- if (!ctx.user.isGuest) {
- const user = await prisma.user.findUnique({
- where: {
- id: ctx.user.id,
- },
- select: {
- name: true,
- },
- });
-
- if (!user) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "User not found",
- });
- }
-
- // Stored names (e.g. from OAuth sign-up) aren't guaranteed to satisfy
- // the schema cap, so bound them here too.
- authorName = user.name.trim().slice(0, MAX_COMMENT_AUTHOR_NAME_LENGTH);
- }
-
- const { content, pollId } = input;
-
- const newComment = await prisma.comment.create({
- data: {
- content,
- pollId,
- authorName,
- userId: ctx.user.id,
- },
- select: {
- id: true,
- createdAt: true,
- authorName: true,
- content: true,
- poll: {
- select: {
- title: true,
- id: true,
- },
- },
- },
- });
-
- const poll = newComment.poll;
-
- try {
- const recipient = await getNotificationRecipient({
- pollId,
- type: "poll.comment.added",
- excludeUserId: ctx.user.id,
- });
-
- if (recipient) {
- const unsubscribeToken = createUnsubscribeToken({
- target: { kind: "poll", pollId, userId: recipient.id },
- secret: env.SECRET_PASSWORD,
- });
- after(async () =>
- sendNewCommentEmail({
- to: recipient.email,
- locale: recipient.locale ?? undefined,
- branding: await getInstanceBranding(),
- listUnsubscribeUrl: absoluteUrl(
- `/api/unsubscribe/${unsubscribeToken}`,
- ),
- props: {
- authorName,
- content: newComment.content,
- pollUrl: absoluteUrl(`/poll/${poll.id}`),
- unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),
- disableNotificationsUrl: absoluteUrl("/settings/notifications"),
- title: poll.title,
- },
- }),
- );
- }
- } catch (err) {
- logger.error(
- { error: err, pollId },
- "Failed to send new comment notification email",
- );
- }
-
- // Track comment addition analytics
- track(ctx.user, {
- event: "poll_comment_add",
- properties: {
- is_guest: ctx.user.isGuest,
- },
- groups: {
- poll: pollId,
- },
- });
-
- return newComment;
- }),
- delete: publicProcedure
- .use(requireUserMiddleware)
- .input(
- z.object({
- commentId: z.string(),
- }),
- )
- .mutation(async ({ input: { commentId }, ctx }) => {
- const actor = ctx.user;
-
- const comment = await prisma.comment.findUnique({
- where: { id: commentId },
- select: { pollId: true, userId: true },
- });
-
- if (!comment) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Comment not found",
- });
- }
-
- const isAuthor = comment.userId === actor.id;
-
- if (!isAuthor && !(await hasPollAdminAccess(comment.pollId, actor.id))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You are not allowed to delete this comment",
- });
- }
-
- await prisma.comment.delete({
- where: {
- id: commentId,
- },
- });
-
- // Track comment deletion analytics
- track(actor, {
- event: "poll_comment_delete",
- groups: {
- poll: comment.pollId,
- },
- });
- }),
-});
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
deleted file mode 100644
index d980be173..000000000
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ /dev/null
@@ -1,702 +0,0 @@
-import type { Participant, Prisma, VoteType } from "@rallly/database";
-import { prisma } from "@rallly/database";
-import { sendNewParticipantEmail } from "@rallly/emails/templates/new-participant";
-import { sendNewParticipantConfirmationEmail } from "@rallly/emails/templates/new-participant-confirmation";
-import { createLogger } from "@rallly/logger";
-import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
-import { TRPCError } from "@trpc/server";
-import { after } from "next/server";
-import * as z from "zod";
-import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
-import { env } from "@/env";
-import { getNotificationRecipient } from "@/features/notifications/data";
-import { createUnsubscribeToken } from "@/features/notifications/utils";
-import { recordPollActivities } from "@/features/poll/activity/mutations";
-import {
- hasPollAdminAccess,
- listParticipantIdsByToken,
-} from "@/features/poll/data";
-import {
- attachParticipantToInvite,
- findPendingPollInvite,
-} from "@/features/poll/invite/mutations";
-import { getPollInvitePath } from "@/features/poll/invite/utils";
-import { generateAccessToken } from "@/features/poll/utils";
-import { AppError } from "@/lib/errors/app-error";
-import { track } from "@/lib/posthog";
-import {
- createRateLimitMiddleware,
- publicProcedure,
- requireUserMiddleware,
- router,
-} from "../../trpc";
-import { responseNoteInput } from "./schema";
-import { authorizeParticipantEdit } from "./utils";
-
-const logger = createLogger("participants");
-
-const MAX_PARTICIPANTS = 1000;
-
-function createParticipantFullDTO(
- participant: Participant & { user: { image: string | null } | null } & {
- votes: { optionId: string; type: VoteType }[];
- },
-) {
- // The token is the edit credential: the list hands it back only to the
- // host, as a ready made edit link.
- const { votes, user, token: _token, ...rest } = participant;
- return {
- ...rest,
- image: user?.image ?? null,
- votes,
- hidden: false,
- };
-}
-
-async function sendNewResponseNotificationEmail({
- pollId,
- pollTitle,
- participantName,
- participantEmail,
- note,
- excludeUserId,
-}: {
- pollId: string;
- pollTitle: string;
- participantName: string;
- participantEmail: string | null;
- note: string | null;
- excludeUserId: string;
-}) {
- try {
- const recipient = await getNotificationRecipient({
- pollId,
- type: "poll.response.submitted",
- excludeUserId,
- });
-
- if (!recipient) {
- return;
- }
-
- const unsubscribeToken = createUnsubscribeToken({
- target: { kind: "poll", pollId, userId: recipient.id },
- secret: env.SECRET_PASSWORD,
- });
-
- await sendNewParticipantEmail({
- to: recipient.email,
- locale: recipient.locale ?? undefined,
- branding: await getInstanceBranding(),
- replyTo: participantEmail ?? undefined,
- listUnsubscribeUrl: absoluteUrl(`/api/unsubscribe/${unsubscribeToken}`),
- props: {
- participantName,
- note: note ?? undefined,
- canReply: !!participantEmail,
- pollUrl: absoluteUrl(`/poll/${pollId}`),
- unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),
- disableNotificationsUrl: absoluteUrl("/settings/notifications"),
- title: pollTitle,
- },
- });
- } catch (err) {
- logger.error(
- { error: err, pollId },
- "Failed to send new response notification email",
- );
- }
-}
-
-/**
- * Rejects new tentative votes when the poll no longer allows them, locking the
- * poll row for the rest of the transaction.
- *
- * The check runs inside the writing transaction and takes a lock the
- * organizer's disable transition also takes. Under READ COMMITTED a plain read
- * would let a vote that passed an earlier check land after the organizer had
- * already counted zero tentative votes, stranding one on a poll that no longer
- * accepts them.
- */
-const assertTentativeVotesAllowed = async (
- tx: Prisma.TransactionClient,
- pollId: string,
- votes: { type: VoteType }[],
-) => {
- if (!votes.some((vote) => vote.type === "ifNeedBe")) {
- return;
- }
-
- const [poll] = await tx.$queryRaw<{ allow_tentative_votes: boolean }[]>`
- SELECT allow_tentative_votes FROM polls WHERE id = ${pollId} FOR UPDATE
- `;
-
- if (!poll?.allow_tentative_votes) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "This poll does not accept tentative votes",
- });
- }
-};
-
-export const participants = router({
- list: publicProcedure
- .input(
- z.object({
- pollId: z.string(),
- token: z.string().optional(),
- }),
- )
- .query(async ({ ctx, input: { pollId, token } }) => {
- const poll = await prisma.poll.findUnique({
- where: { id: pollId },
- select: {
- hideParticipants: true,
- deleted: true,
- user: { select: { banned: true } },
- },
- });
-
- // A deleted poll, or one whose creator was banned, never exposes its
- // participants.
- if (!poll || poll.deleted || poll.user?.banned) {
- throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });
- }
-
- const rawParticipants = await prisma.participant.findMany({
- where: {
- pollId,
- },
- include: {
- votes: {
- select: {
- optionId: true,
- type: true,
- },
- },
- user: {
- select: {
- image: true,
- },
- },
- },
- orderBy: [
- {
- createdAt: "desc",
- },
- { name: "desc" },
- ],
- });
-
- // Admin check is intentionally bound to ctx.user only — an edit
- // token must never unlock the admin view of other participants.
- const isAdmin = ctx.user
- ? await hasPollAdminAccess(pollId, ctx.user.id)
- : false;
-
- // The emailed link names the viewer's own response, so a guest still
- // sees it as theirs when opening the link in a fresh browser.
- const linkedIds = new Set(
- token && !isAdmin
- ? await listParticipantIdsByToken({ pollId, token })
- : [],
- );
- const isOwn = (participant: { id: string; userId: string | null }) =>
- linkedIds.has(participant.id) ||
- (!!ctx.user && participant.userId === ctx.user.id);
-
- // Response notes are visible to the host and their author only: strip
- // them from every other payload rather than hiding them in the UI.
- // The host also gets each response's edit link, the one its
- // confirmation email carried, to hand to a respondent who left no
- // email. Built from the same path so the two can never diverge.
- const participants = rawParticipants.map((participant) => {
- const dto = createParticipantFullDTO(participant);
- const editUrl = isAdmin
- ? shortUrl(getPollInvitePath({ pollId, token: participant.token }))
- : null;
- if (isAdmin || isOwn(participant)) {
- return { ...dto, editUrl };
- }
- return { ...dto, note: null, editUrl };
- });
-
- // Hide participants if the poll has hideParticipants enabled
- // and the current user is not an admin
- if (poll.hideParticipants) {
- if (!isAdmin) {
- return participants.map((participant) => {
- if (isOwn(participant)) {
- return participant;
- }
-
- return {
- ...participant,
- userId: null,
- name: "",
- email: null,
- image: null,
- hidden: true,
- };
- });
- }
- }
-
- return participants;
- }),
- delete: publicProcedure
- .input(
- z.object({
- participantId: z.string(),
- token: z.string().optional(),
- }),
- )
- .mutation(async ({ input: { participantId, token }, ctx }) => {
- const { participant, actor } = await authorizeParticipantEdit({
- participantId,
- token,
- ctxUser: ctx.user,
- });
-
- await prisma.$transaction(async (tx) => {
- // Snapshot before the delete: the activity payload is the historical
- // record of the removed response, so it carries the name and votes.
- const snapshot = await tx.participant.findUniqueOrThrow({
- where: { id: participantId },
- select: {
- name: true,
- votes: {
- select: {
- optionId: true,
- type: true,
- option: {
- select: { startTime: true, duration: true },
- },
- },
- },
- },
- });
-
- // Hard delete: votes cascade, the invite's SetNull FK reverts it to
- // pending, and the response frees the token it took from that invite
- // so the next response through the same link can take it again. The
- // activity row above is the historical record.
- await tx.participant.delete({
- where: {
- id: participantId,
- },
- });
-
- await recordPollActivities(tx, [
- {
- pollId: participant.pollId,
- type: "response_deleted",
- userId: actor?.id,
- participantId,
- payload: {
- name: snapshot.name,
- votes: snapshot.votes.map((vote) => ({
- optionId: vote.optionId,
- start: vote.option.startTime.toISOString(),
- duration: vote.option.duration,
- type: vote.type,
- })),
- },
- },
- ]);
- });
-
- if (actor) {
- track(actor, {
- event: "poll_response_delete",
- properties: {
- participant_id: participant.id,
- },
- groups: {
- poll: participant.pollId,
- },
- });
- }
- }),
- add: publicProcedure
- .use(createRateLimitMiddleware("add_participant", 10, "1 h"))
- .use(requireUserMiddleware)
- .input(
- z.object({
- pollId: z.string(),
- name: z.string().trim().min(1, "Participant name is required").max(100),
- email: z.string().optional(),
- note: responseNoteInput,
- timeZone: z.string().optional(),
- token: z.string().optional(),
- votes: z
- .object({
- optionId: z.string(),
- type: z.enum(["yes", "no", "ifNeedBe"]),
- })
- .array(),
- }),
- )
- .mutation(
- async ({
- ctx,
- input: { pollId, votes, name, email, note, timeZone, token },
- }) => {
- const poll = await prisma.poll.findUnique({
- where: { id: pollId },
- select: {
- status: true,
- deleted: true,
- user: { select: { banned: true } },
- },
- });
-
- // A deleted poll, or one whose creator was banned, never accepts
- // responses.
- if (!poll || poll.deleted || poll.user?.banned) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Poll not found",
- });
- }
-
- // The voting window is the organizer's control, so it has to hold
- // here and not only in the client, which hides the form via
- // `canAddNewParticipant`.
- if (poll.status !== "open") {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "This poll is no longer accepting responses",
- });
- }
-
- const participantCount = await prisma.participant.count({
- where: {
- pollId,
- },
- });
-
- if (participantCount >= MAX_PARTICIPANTS) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: `This poll has reached its maximum limit of ${MAX_PARTICIPANTS} participants`,
- cause: new AppError({
- code: "POLL_FULL",
- message: "Poll has reached the maximum number of participants",
- }),
- });
- }
-
- const options = await prisma.option.findMany({
- where: {
- pollId,
- },
- select: {
- id: true,
- },
- });
-
- const existingOptionIds = new Set(options.map((option) => option.id));
-
- const validVotes = votes.filter(({ optionId }) =>
- existingOptionIds.has(optionId),
- );
-
- const { participant, editToken, viaInvite } = await prisma.$transaction(
- async (tx) => {
- await assertTentativeVotesAllowed(tx, pollId, validVotes);
-
- // A response answering an emailed invite takes the invite's
- // token, so the link the invitee already holds names it.
- const invite = token
- ? await findPendingPollInvite(tx, { pollId, token })
- : null;
- const editToken = invite?.token ?? generateAccessToken();
-
- const participant = await tx.participant.create({
- data: {
- pollId: pollId,
- name: name,
- email,
- note,
- timeZone,
- token: editToken,
- userId: ctx.user.id,
- locale: ctx.locale,
- votes: {
- createMany: {
- data: validVotes.map(({ optionId, type }) => ({
- pollId,
- optionId,
- type,
- })),
- },
- },
- },
- include: {
- votes: {
- select: {
- optionId: true,
- type: true,
- },
- },
- user: {
- select: {
- image: true,
- },
- },
- poll: {
- select: {
- id: true,
- title: true,
- allowTentativeVotes: true,
- space: {
- select: {
- id: true,
- tier: true,
- showBranding: true,
- hideAttribution: true,
- primaryColor: true,
- image: true,
- },
- },
- },
- },
- },
- });
-
- await recordPollActivities(tx, [
- {
- pollId,
- type: "response_created",
- userId: ctx.user.id,
- participantId: participant.id,
- payload: { name: participant.name },
- },
- ]);
-
- if (invite) {
- await attachParticipantToInvite(tx, {
- inviteId: invite.id,
- participantId: participant.id,
- });
- }
-
- return { participant, editToken, viaInvite: invite !== null };
- },
- );
-
- const totalResponses = participantCount + 1;
-
- if (email) {
- const space = participant.poll.space;
-
- after(async () =>
- sendNewParticipantConfirmationEmail({
- to: email,
- locale: ctx.locale,
- branding: space
- ? await getSpaceBranding(space)
- : await getInstanceBranding(),
- props: {
- title: participant.poll.title,
- editSubmissionUrl: shortUrl(
- `/invite/${participant.poll.id}?token=${editToken}`,
- ),
- },
- }),
- );
- }
-
- after(() =>
- sendNewResponseNotificationEmail({
- pollId,
- pollTitle: participant.poll.title,
- participantName: participant.name,
- participantEmail: participant.email,
- note: participant.note,
- excludeUserId: ctx.user.id,
- }),
- );
-
- const voteCounts = validVotes.reduce(
- (acc, { type }) => {
- acc[type] += 1;
- return acc;
- },
- { yes: 0, ifNeedBe: 0, no: 0 },
- );
-
- track(ctx.user, {
- event: "poll_response_submit",
- properties: {
- participant_id: participant.id,
- // plain properties, not groups: guest events are personless and
- // PostHog drops group associations without person processing
- poll_id: pollId,
- space_id: participant.poll.space?.id,
- tier: participant.poll.space?.tier,
- has_email: !!email,
- via_invite: viaInvite,
- has_note: !!participant.note,
- note_length: participant.note?.length,
- total_responses: totalResponses,
- // Whether the tentative option is offered at all, so the counts
- // below can be read against the polls that actually had it.
- allow_tentative_votes: participant.poll.allowTentativeVotes,
- yes_count: voteCounts.yes,
- if_need_be_count: voteCounts.ifNeedBe,
- no_count: voteCounts.no,
- },
- groups: {
- poll: pollId,
- },
- });
-
- return createParticipantFullDTO(participant);
- },
- ),
- rename: publicProcedure
- .input(
- z.object({
- participantId: z.string(),
- newName: z.string().min(1, "Participant name is required").max(100),
- token: z.string().optional(),
- }),
- )
- .mutation(async ({ input: { participantId, newName, token }, ctx }) => {
- const { participant, actor } = await authorizeParticipantEdit({
- participantId,
- token,
- ctxUser: ctx.user,
- });
-
- await prisma.$transaction(async (tx) => {
- await tx.participant.update({
- where: {
- id: participantId,
- },
- data: {
- name: newName,
- },
- select: null,
- });
-
- await recordPollActivities(tx, [
- {
- pollId: participant.pollId,
- type: "response_updated",
- userId: actor?.id,
- participantId,
- payload: { name: newName },
- },
- ]);
- });
- }),
- update: publicProcedure
- .input(
- z.object({
- pollId: z.string(),
- participantId: z.string(),
- votes: z
- .object({
- optionId: z.string(),
- type: z.enum(["yes", "no", "ifNeedBe"]),
- })
- .array(),
- token: z.string().optional(),
- }),
- )
- .mutation(async ({ input: { participantId, votes, token }, ctx }) => {
- const { participant: existingParticipant, actor } =
- await authorizeParticipantEdit({
- participantId,
- token,
- ctxUser: ctx.user,
- });
-
- const pollId = existingParticipant.pollId;
-
- const participant = await prisma.$transaction(async (tx) => {
- await assertTentativeVotesAllowed(tx, pollId, votes);
-
- // Delete existing votes
- await tx.vote.deleteMany({
- where: {
- participantId,
- },
- });
-
- const options = await tx.option.findMany({
- where: {
- pollId,
- },
- select: {
- id: true,
- },
- });
-
- const existingOptionIds = new Set(options.map((option) => option.id));
-
- const validVotes = votes.filter(({ optionId }) =>
- existingOptionIds.has(optionId),
- );
-
- // Create new votes
- await tx.vote.createMany({
- data: validVotes.map(({ optionId, type }) => ({
- optionId,
- type,
- pollId,
- participantId,
- })),
- });
-
- // Bump `updatedAt` so it reflects this vote change; the poll cleanup
- // job uses it to detect recent activity. An empty `data: {}` update is
- // a no-op for `@updatedAt`, so set it explicitly.
- const updatedParticipant = await tx.participant.update({
- where: {
- id: participantId,
- },
- data: { updatedAt: new Date() },
- include: {
- votes: {
- select: {
- optionId: true,
- type: true,
- },
- },
- user: {
- select: {
- image: true,
- },
- },
- },
- });
-
- await recordPollActivities(tx, [
- {
- pollId,
- type: "response_updated",
- userId: actor?.id,
- participantId,
- payload: { name: updatedParticipant.name },
- },
- ]);
-
- return updatedParticipant;
- });
-
- if (actor) {
- track(actor, {
- event: "poll_response_update",
- groups: {
- poll: pollId,
- },
- });
- }
-
- return createParticipantFullDTO(participant);
- }),
-});
diff --git a/apps/web/src/trpc/routers/polls/schema.test.ts b/apps/web/src/trpc/routers/polls/schema.test.ts
index 8f1d33481..fe13611ed 100644
--- a/apps/web/src/trpc/routers/polls/schema.test.ts
+++ b/apps/web/src/trpc/routers/polls/schema.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
-import { MAX_RESPONSE_NOTE_LENGTH } from "@/features/poll/schema";
-import { responseNoteInput, timeZoneInput } from "./schema";
+import { timeZoneInput } from "./schema";
describe("timeZoneInput", () => {
it("normalizes an empty string to null", () => {
@@ -19,28 +18,3 @@ describe("timeZoneInput", () => {
expect(timeZoneInput.parse(null)).toBeNull();
});
});
-
-describe("responseNoteInput", () => {
- it("trims surrounding whitespace", () => {
- expect(responseNoteInput.parse(" running late ")).toBe("running late");
- });
-
- it("collapses a whitespace only note to undefined", () => {
- expect(responseNoteInput.parse(" \n ")).toBeUndefined();
- });
-
- it("keeps undefined as undefined", () => {
- expect(responseNoteInput.parse(undefined)).toBeUndefined();
- });
-
- it("rejects notes over the maximum length", () => {
- expect(() =>
- responseNoteInput.parse("a".repeat(MAX_RESPONSE_NOTE_LENGTH + 1)),
- ).toThrow();
- });
-
- it("accepts a note at the maximum length", () => {
- const note = "a".repeat(MAX_RESPONSE_NOTE_LENGTH);
- expect(responseNoteInput.parse(note)).toBe(note);
- });
-});
diff --git a/apps/web/src/trpc/routers/polls/schema.ts b/apps/web/src/trpc/routers/polls/schema.ts
index 6cf9db431..88c82d168 100644
--- a/apps/web/src/trpc/routers/polls/schema.ts
+++ b/apps/web/src/trpc/routers/polls/schema.ts
@@ -1,5 +1,4 @@
import * as z from "zod";
-import { MAX_RESPONSE_NOTE_LENGTH } from "@/features/poll/schema";
// A falsy poll timeZone means "floating". Clients historically sent "" for
// floating time polls; normalize it to null at the boundary so it can never
@@ -9,11 +8,3 @@ export const timeZoneInput = z
.string()
.transform((value) => value || null)
.nullish();
-
-// Whitespace-only notes collapse to undefined so no empty string is persisted.
-export const responseNoteInput = z
- .string()
- .trim()
- .max(MAX_RESPONSE_NOTE_LENGTH)
- .optional()
- .transform((value) => value || undefined);
diff --git a/apps/web/src/trpc/routers/polls/utils.ts b/apps/web/src/trpc/routers/polls/utils.ts
deleted file mode 100644
index 8939fdafb..000000000
--- a/apps/web/src/trpc/routers/polls/utils.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { TRPCError } from "@trpc/server";
-import {
- getParticipant,
- hasPollAdminAccess,
- listParticipantIdsByToken,
-} from "@/features/poll/data";
-
-type Actor = { id: string; isGuest: boolean };
-
-/**
- * Proves the caller may edit a response. Two proofs are accepted: the token
- * from the emailed link, which names the response itself, and a session that
- * owns the response or administers its poll. Admin access is bound to the
- * session only, so a link never unlocks other people's responses.
- *
- * A poll that is no longer open accepts no edits from anyone, admins
- * included — the same rule `canEditParticipant` applies in the client. The
- * lifecycle check comes first: whether the voting window has closed does not
- * depend on who is asking.
- *
- * The returned actor is for attribution (activity log, analytics): the
- * session when there is one, otherwise the user the response was created
- * under, who was a guest at the time.
- */
-export async function authorizeParticipantEdit({
- participantId,
- token,
- ctxUser,
-}: {
- participantId: string;
- token: string | undefined;
- ctxUser: Actor | undefined;
-}) {
- const participant = await getParticipant({ participantId });
-
- if (!participant) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Participant not found",
- });
- }
-
- if (participant.poll.deleted) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Participant not found",
- });
- }
-
- if (participant.poll.status !== "open") {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "This poll is no longer accepting changes",
- });
- }
-
- const ownedBySession = ctxUser
- ? participant.userId === ctxUser.id ||
- (await hasPollAdminAccess(participant.pollId, ctxUser.id))
- : false;
-
- const ownedByLink =
- !ownedBySession && token
- ? (
- await listParticipantIdsByToken({ pollId: participant.pollId, token })
- ).includes(participant.id)
- : false;
-
- if (!ownedBySession && !ownedByLink) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You are not allowed to modify this participant",
- });
- }
-
- const actor: Actor | null =
- ctxUser ??
- (participant.userId ? { id: participant.userId, isGuest: true } : null);
-
- return { participant, actor };
-}
diff --git a/apps/web/tests/closed-poll-writes.spec.ts b/apps/web/tests/closed-poll-writes.spec.ts
index 1c3a959df..f8a09d352 100644
--- a/apps/web/tests/closed-poll-writes.spec.ts
+++ b/apps/web/tests/closed-poll-writes.spec.ts
@@ -1,117 +1,145 @@
import type { Page } from "@playwright/test";
import { expect, test } from "@playwright/test";
+import { prisma } from "@rallly/database";
import { NewPollPage } from "./new-poll-page";
+import type { PollPage } from "./poll-page";
-// The client hides the voting form once a poll leaves "open"
+// The client hides the voting controls once a poll leaves "open"
// (`canAddNewParticipant` / `canEditParticipant`). These tests pin the
-// server-side rule behind that, so a caller reaching the mutations directly
-// cannot write to a poll whose voting window the organizer has ended.
-
-async function getPollId(page: Page) {
- const pollId = page.url().match(/\/poll\/([^/?]+)/)?.[1];
- expect(pollId).toBeTruthy();
- return pollId as string;
-}
-
-async function closePoll(page: Page, pollId: string) {
- const response = await page.request.post("/api/trpc/polls.close", {
- data: { json: { pollId } },
- });
- expect(response.ok()).toBe(true);
-}
-
-test.describe("writes to a closed poll", () => {
- test("the API rejects a new response once the poll is closed", async ({
- page,
- }) => {
- const newPollPage = new NewPollPage(page);
- await newPollPage.goto();
- const pollPage = await newPollPage.create({ name: "Closed Poll Meetup" });
- await pollPage.closeShareDialog();
- const pollId = await getPollId(page);
-
- // A response added while the poll is still open, so the edit paths below
- // have a real target that only the poll's status disqualifies.
- await pollPage.addParticipant("Anne");
- const participants = await page.request.get(
- `/api/trpc/polls.participants.list?input=${encodeURIComponent(
- JSON.stringify({ json: { pollId } }),
- )}`,
- );
- expect(participants.ok()).toBe(true);
- const participantId = (await participants.json()).result.data.json[0].id;
- expect(participantId).toBeTruthy();
-
- await closePoll(page, pollId);
-
- const options = await page.request.get(
- `/api/trpc/polls.get?input=${encodeURIComponent(
- JSON.stringify({ json: { urlId: pollId } }),
- )}`,
- );
- const optionId = (await options.json()).result.data.json.options[0].id;
-
- const add = await page.request.post("/api/trpc/polls.participants.add", {
- data: {
- json: {
- pollId,
- name: "Test Participant",
- votes: [{ optionId, type: "yes" }],
- },
- },
+// server-side rule behind that: a page opened while the poll was open goes
+// stale when the organizer closes it, and every write it can still send has
+// to be refused by the action. The database is the witness; the page may or
+// may not have re-rendered by the time the refusal lands, so nothing here
+// depends on what it shows afterwards.
+
+test.describe
+ .serial("writes to a closed poll", () => {
+ let page: Page;
+ let pollPage: PollPage;
+ let pollId: string;
+ let participantId: string;
+
+ const closePoll = () =>
+ prisma.poll.update({
+ where: { id: pollId },
+ data: { status: "closed", closedReason: "manual" },
+ });
+
+ // Each test starts from an open poll and a freshly loaded page, so the
+ // controls it needs are on screen before the poll is closed behind it.
+ const reopenPoll = async () => {
+ await prisma.poll.update({
+ where: { id: pollId },
+ data: { status: "open", closedReason: null },
+ });
+ await page.goto(`/poll/${pollId}`);
+ await expect(page.getByTestId("participant-row")).toBeVisible();
+ };
+
+ const row = () => page.getByTestId("participant-row").first();
+
+ test.beforeAll(async ({ browser }) => {
+ page = await (await browser.newContext()).newPage();
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ pollPage = await newPollPage.create({ name: "Closed Poll Meetup" });
+ await pollPage.closeShareDialog();
+ pollId = page.url().match(/\/poll\/([^/?]+)/)?.[1] as string;
+ expect(pollId).toBeTruthy();
+
+ // A response added while the poll is open, so the edit paths below have
+ // a real target that only the poll's status disqualifies.
+ await pollPage.addParticipant("Anne");
+ const participant = await prisma.participant.findFirstOrThrow({
+ where: { pollId },
+ });
+ participantId = participant.id;
+ });
+
+ test("a rename is refused", async () => {
+ await reopenPoll();
+ await row().getByTestId("participant-menu").click();
+ await page.getByRole("menuitem", { name: "Change name" }).click();
+ const dialog = page.getByRole("dialog", { name: "Change name" });
+ await dialog.getByLabel("Name").fill("Renamed");
+
+ await closePoll();
+ await dialog.getByRole("button", { name: "Save" }).click();
+
+ await expect(
+ page.getByText("No more responses are being accepted.").first(),
+ ).toBeVisible();
+ await expect
+ .poll(async () => {
+ const participant = await prisma.participant.findUniqueOrThrow({
+ where: { id: participantId },
+ });
+ return participant.name;
+ })
+ .toBe("Anne");
+ });
+
+ test("a vote change is refused", async () => {
+ await reopenPoll();
+ const before = await prisma.vote.findMany({
+ where: { participantId },
+ orderBy: { optionId: "asc" },
+ });
+ await row().getByTestId("participant-menu").click();
+ await page.getByRole("menuitem", { name: "Edit votes" }).click();
+
+ await closePoll();
+ await page.getByRole("button", { name: "Save", exact: true }).click();
+
+ await expect(
+ page.getByText("No more responses are being accepted.").first(),
+ ).toBeVisible();
+ const after = await prisma.vote.findMany({
+ where: { participantId },
+ orderBy: { optionId: "asc" },
+ });
+ expect(after).toEqual(before);
+ });
+
+ test("a delete is refused", async () => {
+ await reopenPoll();
+ await row().getByTestId("participant-menu").click();
+ await page.getByRole("menuitem", { name: "Delete" }).click();
+ const dialog = page.getByRole("dialog", { name: "Delete Anne?" });
+
+ await closePoll();
+ await dialog.getByRole("button", { name: "Delete" }).click();
+
+ await expect(
+ page.getByText("No more responses are being accepted.").first(),
+ ).toBeVisible();
+ expect(
+ await prisma.participant.count({ where: { id: participantId } }),
+ ).toBe(1);
+ });
+
+ test("a new response is refused", async () => {
+ await reopenPoll();
+ await page.getByTestId("add-participant-button").click();
+ await page.locator("data-testid=vote-selector >> nth=0").click();
+ await page.click("button >> text='Continue'");
+ await page.type('[placeholder="Jessie Smith"]', "Late");
+
+ await closePoll();
+ await page.click("text='Save availability'");
+
+ await expect(
+ page.getByText("This poll is no longer accepting responses."),
+ ).toBeVisible();
+ expect(await prisma.participant.count({ where: { pollId } })).toBe(1);
});
- expect(add.status()).toBe(400);
-
- // The same rule has to hold for every write path that reaches an existing
- // response, not just the one the report named.
- const update = await page.request.post(
- "/api/trpc/polls.participants.update",
- {
- data: {
- json: { pollId, participantId, votes: [{ optionId, type: "no" }] },
- },
- },
- );
- expect(update.status()).toBe(400);
-
- const rename = await page.request.post(
- "/api/trpc/polls.participants.rename",
- { data: { json: { participantId, newName: "Renamed" } } },
- );
- expect(rename.status()).toBe(400);
-
- const remove = await page.request.post(
- "/api/trpc/polls.participants.delete",
- { data: { json: { participantId } } },
- );
- expect(remove.status()).toBe(400);
- });
- test("the API still accepts a response while the poll is open", async ({
- page,
- }) => {
- const newPollPage = new NewPollPage(page);
- await newPollPage.goto();
- const pollPage = await newPollPage.create({ name: "Open Poll Meetup" });
- await pollPage.closeShareDialog();
- const pollId = await getPollId(page);
-
- const options = await page.request.get(
- `/api/trpc/polls.get?input=${encodeURIComponent(
- JSON.stringify({ json: { urlId: pollId } }),
- )}`,
- );
- const optionId = (await options.json()).result.data.json.options[0].id;
-
- const add = await page.request.post("/api/trpc/polls.participants.add", {
- data: {
- json: {
- pollId,
- name: "Test Participant",
- votes: [{ optionId, type: "yes" }],
- },
- },
+ test("a response is still accepted while the poll is open", async () => {
+ await reopenPoll();
+ await pollPage.addParticipant("Ben");
+ await expect(
+ page.getByTestId("participant-row").filter({ hasText: "Ben" }),
+ ).toBeVisible();
+ expect(await prisma.participant.count({ where: { pollId } })).toBe(2);
});
- expect(add.ok()).toBe(true);
});
-});
diff --git a/apps/web/tests/comments-disabled.spec.ts b/apps/web/tests/comments-disabled.spec.ts
index 6ca236ae7..efb9bf3d9 100644
--- a/apps/web/tests/comments-disabled.spec.ts
+++ b/apps/web/tests/comments-disabled.spec.ts
@@ -1,41 +1,50 @@
import { expect, test } from "@playwright/test";
+import { prisma } from "@rallly/database";
import { NewPollPage } from "./new-poll-page";
// The comment UI is hidden when the host turns comments off. That is a
// presentation choice; these tests pin the server-side rule behind it, so a
-// caller going straight at the mutation cannot write past the setting.
+// page that still shows the composer cannot write past the setting.
test.describe("comments disabled", () => {
- test("the API rejects a comment on a poll with comments off", async ({
+ test("the action rejects a comment once comments are turned off", async ({
page,
}) => {
const newPollPage = new NewPollPage(page);
await newPollPage.goto();
- // Comments are off by default, so this poll has disableComments = true.
- const pollPage = await newPollPage.create({ name: "No Comments Meetup" });
+ const pollPage = await newPollPage.create({
+ name: "No Comments Meetup",
+ enableComments: true,
+ });
await pollPage.closeShareDialog();
const pollId = page.url().match(/\/poll\/([^/?]+)/)?.[1];
expect(pollId).toBeTruthy();
- // page.request shares the page's cookie jar, so this carries the same
- // session the hidden UI would have used.
- const response = await page.request.post("/api/trpc/polls.comments.add", {
- data: {
- json: {
- pollId,
- authorName: "Test User",
- content: "This comment should be rejected",
- },
- },
+ await page.getByRole("button", { name: "Comments" }).click();
+ const sheet = page.getByRole("dialog", { name: "Comments" });
+ await sheet
+ .getByPlaceholder("Write a comment")
+ .fill("This comment should be rejected");
+ await sheet.getByPlaceholder("Your name…").fill("Test user");
+
+ // Turned off behind the page's back: the composer stays on screen.
+ await prisma.poll.update({
+ where: { id: pollId },
+ data: { disableComments: true },
});
- expect(response.status()).toBe(403);
+ await sheet.getByRole("button", { name: "Add comment" }).click();
+ await expect(
+ page.getByText("Comments are turned off for this poll."),
+ ).toBeVisible();
+ await expect(sheet.getByText("Your comment has been added")).toHaveCount(0);
+ expect(await prisma.comment.count({ where: { pollId } })).toBe(0);
await page.reload();
await expect(page.getByRole("button", { name: "Comments" })).toBeHidden();
});
- test("the API still accepts a comment when comments are on", async ({
+ test("the action still accepts a comment when comments are on", async ({
page,
}) => {
const newPollPage = new NewPollPage(page);
@@ -49,16 +58,10 @@ test.describe("comments disabled", () => {
const pollId = page.url().match(/\/poll\/([^/?]+)/)?.[1];
expect(pollId).toBeTruthy();
- const response = await page.request.post("/api/trpc/polls.comments.add", {
- data: {
- json: {
- pollId,
- authorName: "Test User",
- content: "This comment should be accepted",
- },
- },
- });
-
- expect(response.ok()).toBe(true);
+ await pollPage.addComment();
+ await expect(
+ page.getByTestId("comment").getByText("This is a comment!"),
+ ).toBeVisible();
+ expect(await prisma.comment.count({ where: { pollId } })).toBe(1);
});
});
diff --git a/apps/web/tests/unavailable-poll.spec.ts b/apps/web/tests/unavailable-poll.spec.ts
index 621034ae1..99b45e179 100644
--- a/apps/web/tests/unavailable-poll.spec.ts
+++ b/apps/web/tests/unavailable-poll.spec.ts
@@ -6,7 +6,8 @@ import { createTestPoll, createUserInDb, loginWithEmail } from "./test-utils";
// A poll whose creator was banned is usually a scam lure. The person who
// clicks the link is the intended victim, so the page they land on has to
// warn them instead of showing a generic 404, and none of the poll's content
-// may leak through the page or the public tRPC reads.
+// may leak through the page. A page opened before the ban must not be able
+// to keep writing to the poll either.
const scamTitle = "Claim your unclaimed parcel refund";
@@ -33,23 +34,40 @@ test.describe("unavailable poll invite page", () => {
const main = page.locator("#main-content");
+ const voter = await createUserInDb({
+ email: `unavailable-voter-${randomUUID()}@example.com`,
+ name: "Voter",
+ });
+ await loginWithEmail(page, { email: voter.email });
+
+ // A response started while the poll was still served, so the ban lands
+ // between the page and its submit. The database is the witness: the
+ // page may have re-rendered into the removed page by the time the
+ // refusal lands.
await page.goto(`/invite/${poll.id}`);
await expect(main.getByText(scamTitle).first()).toBeVisible();
-
- const optionsBeforeBan = await page.request.get(
- `/api/trpc/polls.get?input=${encodeURIComponent(
- JSON.stringify({ json: { urlId: poll.id } }),
- )}`,
- );
- const optionId = (await optionsBeforeBan.json()).result.data.json.options[0]
- .id;
- expect(optionId).toBeTruthy();
+ await page.locator("data-testid=vote-selector >> nth=0").click();
+ await page.click("button >> text='Continue'");
+ await page.type('[placeholder="Jessie Smith"]', "Victim");
await prisma.user.update({
where: { id: user.id },
data: { banned: true, bannedAt: new Date(), banReason: "scam" },
});
+ await page.click("text='Save availability'");
+ // Either the form reports the refusal, or the page has already
+ // re-rendered into the removed page; both mean the action has settled.
+ await expect(
+ page
+ .getByText("This poll is no longer accepting responses.")
+ .or(main.getByRole("heading", { name: "This poll has been removed" })),
+ ).toBeVisible();
+ await expect(page.getByText("Your response has been saved")).toHaveCount(0);
+ expect(await prisma.participant.count({ where: { pollId: poll.id } })).toBe(
+ 0,
+ );
+
await page.goto(`/invite/${poll.id}`);
await expect(
main.getByRole("heading", { name: "This poll has been removed" }),
@@ -61,53 +79,6 @@ test.describe("unavailable poll invite page", () => {
"content",
/noindex/,
);
-
- const get = await page.request.get(
- `/api/trpc/polls.get?input=${encodeURIComponent(
- JSON.stringify({ json: { urlId: poll.id } }),
- )}`,
- );
- expect(get.status()).toBe(404);
- const participants = await page.request.get(
- `/api/trpc/polls.participants.list?input=${encodeURIComponent(
- JSON.stringify({ json: { pollId: poll.id } }),
- )}`,
- );
- expect(participants.status()).toBe(404);
- const comments = await page.request.get(
- `/api/trpc/polls.comments.list?input=${encodeURIComponent(
- JSON.stringify({ json: { pollId: poll.id } }),
- )}`,
- );
- expect(comments.status()).toBe(404);
-
- // Writes are refused too, so a signed-in caller who kept the poll's
- // option ids from before the ban cannot keep adding responses or
- // comments to it.
- const voter = await createUserInDb({
- email: `unavailable-voter-${randomUUID()}@example.com`,
- name: "Voter",
- });
- await loginWithEmail(page, { email: voter.email });
- const addParticipant = await page.request.post(
- "/api/trpc/polls.participants.add",
- {
- data: {
- json: {
- pollId: poll.id,
- name: "Victim",
- votes: [{ optionId: optionId, type: "yes" }],
- },
- },
- },
- );
- expect(addParticipant.status()).toBe(404);
- const addComment = await page.request.post("/api/trpc/polls.comments.add", {
- data: {
- json: { pollId: poll.id, authorName: "Victim", content: "Hello" },
- },
- });
- expect(addComment.status()).toBe(404);
});
test("a deleted poll shows the deleted page without the scam warning", async ({