Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add notification settings (#2254)
Luke Vella73af5dd757c2
diff --git a/apps/web/next.config.ts b/apps/web/next.config.tsindex 3d169168b..7c9a17308 100644--- a/apps/web/next.config.ts+++ b/apps/web/next.config.ts@@ -59,9 +59,15 @@ const nextConfig: NextConfig = {destination: "/settings/profile",permanent: true,},+ // Old email unsubscribe links pointed to these routes — redirect to the new settings page{source: "/auth/disable-notifications",- destination: "/api/notifications/unsubscribe",+ destination: "/settings/notifications",+ permanent: true,+ },+ {+ source: "/api/notifications/unsubscribe",+ destination: "/settings/notifications",permanent: true,},{diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 1019bc5f4..a547148a7 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -102,14 +102,10 @@"billing": "Billing","guestPollAlertDescription": "<0>Create an account</0> or <1>login</1> to claim this poll.","guestPollAlertTitle": "Your administrator rights can be lost if you clear your cookies",- "notificationsValue": "Notifications: <b>{value}</b>",- "notificationsOn": "On",- "notificationsOff": "Off","pollStatusOpen": "Open","reopenPoll": "Reopen Poll","allDay": "All day","editDetailsDescription": "Change the details of your event.",- "notificationsGuestTooltip": "Create an account or login to turn on notifications","dateAndTimeDescription": "Change your preferred date and time settings","createdTime": "Created {relativeTime}","planFree": "Free",@@ -192,8 +188,6 @@"featureNameDuplicate": "Duplicate Poll","featureNameAdvancedSettings": "Advanced Settings","featureNameExtendedPollLifetime": "Extended Poll Lifetime",- "unsubscribeToastTitle": "You have disabled notifications",- "unsubscribeToastDescription": "You will no longer receive notifications for this poll","emailChangeSuccess": "Email changed successfully","emailChangeInvalidToken": "The verification link is invalid or has expired. Please try again.","emailChangeRequestSent": "Verify your new email address",@@ -219,8 +213,6 @@"quickCreateGetNotifications": "Get email notifications","quickCreateManagePollsFromAnyDevice": "Manage your polls from any device","loginVerifyTitle": "Finish Logging In",- "tooManyRequests": "Too many requests",- "tooManyRequestsDescription": "Please try again later.","billingSubscriptionDescription": "Manage your current subscription plan.","subscriptionStatusActive": "Active","subscriptionStatusTrialing": "Trialing",@@ -618,5 +610,15 @@"errorLinkGithubDescription": "Report an issue or check for updates.","notFoundLabel": "404","notFoundTitle": "Page not found",- "notFoundDescription": "Sorry, we couldn't find the page you're looking for. Here are some helpful links instead."+ "notFoundDescription": "Sorry, we couldn't find the page you're looking for. Here are some helpful links instead.",+ "notifications": "Notifications",+ "notificationScopeOff": "Off",+ "notificationScopeMine": "Mine",+ "notificationScopeAll": "All",+ "pollNotificationsDescription": "Get notified by email when there is activity on your polls",+ "notifyNewResponse": "New response",+ "notifyNewResponseDescription": "When someone responds to a poll",+ "notifyNewComment": "New comment",+ "notifyNewCommentDescription": "When someone comments on a poll",+ "notificationsDescription": "Choose which email notifications you receive"}diff --git a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/admin-page.tsx b/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/admin-page.tsxindex ab4a51c07..1da1d3d9f 100644--- a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/admin-page.tsx+++ b/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/admin-page.tsx@@ -9,7 +9,6 @@ import { VotingForm } from "@/components/poll/voting-form";import { usePoll } from "@/contexts/poll";import { GuestPollAlert } from "./guest-poll-alert";-import { UnsubscribeAlert } from "./unsubscribe-alert";export function AdminPage() {// Get the poll ID from the context@@ -19,7 +18,6 @@ export function AdminPage() {<div className="space-y-3 lg:space-y-4">{/* Track poll views */}<PollViewTracker pollId={poll.id} />- <UnsubscribeAlert /><GuestPollAlert /><EventCard /><ScheduledEvent />diff --git a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/layout.tsx b/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/layout.tsxindex 8d4d6d7b0..ee213fdf4 100644--- a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/layout.tsx+++ b/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/layout.tsx@@ -24,7 +24,6 @@ export default async function Layout(throw e;}),trpc.polls.participants.list.prefetch({ pollId: params.urlId }),- trpc.polls.getWatchers.prefetch({ pollId: params.urlId }),trpc.polls.comments.list.prefetch({ pollId: params.urlId }),]);diff --git a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/unsubscribe-alert.tsx b/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/unsubscribe-alert.tsxdeleted file mode 100644index 996815181..000000000--- a/apps/web/src/app/[locale]/(app)/(optional-space)/poll/[urlId]/unsubscribe-alert.tsx+++ /dev/null@@ -1,35 +0,0 @@-"use client";--import { toast } from "@rallly/ui/sonner";-import Cookies from "js-cookie";-import { useParams } from "next/navigation";-import { useEffect } from "react";-import { useTranslation } from "@/i18n/client";--export function UnsubscribeAlert() {- const { t } = useTranslation();-- const urlId = useParams<{ urlId: string }>()?.urlId;-- useEffect(() => {- if (!urlId) return;- const cookieName = `notifications-unsubscribed-${urlId}`;- const unsubscribed = Cookies.get(cookieName);- if (unsubscribed) {- Cookies.remove(cookieName);- toast.message(- t("unsubscribeToastTitle", {- defaultValue: "You have disabled notifications",- }),- {- description: t("unsubscribeToastDescription", {- defaultValue:- "You will no longer receive notifications for this poll",- }),- },- );- }- }, [t, urlId]);-- return null;-}diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/components/sidebar.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/components/sidebar.tsxindex 2b472cb39..fae936fdc 100644--- a/apps/web/src/app/[locale]/(app)/(space)/settings/components/sidebar.tsx+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/components/sidebar.tsx@@ -11,6 +11,7 @@ import {SidebarMenuItem,} from "@rallly/ui/sidebar";import {+ BellIcon,BoltIcon,CalendarIcon,CreditCardIcon,@@ -50,6 +51,12 @@ export function AccountSidebarMenu() {icon: <Settings2Icon />,href: "/settings/preferences",},+ {+ id: "notifications",+ label: t("notifications", { defaultValue: "Notifications" }),+ icon: <BellIcon />,+ href: "/settings/notifications",+ },{id: "spaces",label: t("spaces", { defaultValue: "Spaces" }),diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/notifications-page.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/notifications-page.tsxnew file mode 100644index 000000000..ea7305066--- /dev/null+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/notifications-page.tsx@@ -0,0 +1,68 @@+"use client";++import { Switch } from "@rallly/ui/switch";+import {+ PageSection,+ PageSectionContent,+ PageSectionDescription,+ PageSectionGroup,+ PageSectionHeader,+ PageSectionTitle,+} from "@/app/components/page-layout";+import { Trans } from "@/i18n/client";+import { trpc } from "@/trpc/client";++export function NotificationsPage() {+ const [preferences] = trpc.user.getNotificationPreferences.useSuspenseQuery();+ const updatePreference = trpc.user.updateNotificationPreference.useMutation();++ return (+ <PageSectionGroup>+ <PageSection variant="card">+ <PageSectionHeader>+ <PageSectionTitle>+ <Trans i18nKey="polls" defaults="Polls" />+ </PageSectionTitle>+ <PageSectionDescription>+ <Trans+ i18nKey="pollNotificationsDescription"+ defaults="Get notified by email when there is activity on your polls"+ />+ </PageSectionDescription>+ </PageSectionHeader>+ <PageSectionContent>+ <div className="grid gap-4">+ <div className="flex items-center justify-between gap-4">+ <span className="font-medium text-sm">+ <Trans i18nKey="notifyNewResponse" defaults="New response" />+ </span>+ <Switch+ checked={preferences["poll.response.submitted"]}+ onCheckedChange={(enabled) => {+ updatePreference.mutate({+ eventType: "poll.response.submitted",+ enabled,+ });+ }}+ />+ </div>+ <div className="flex items-center justify-between gap-4">+ <span className="font-medium text-sm">+ <Trans i18nKey="notifyNewComment" defaults="New comment" />+ </span>+ <Switch+ checked={preferences["poll.comment.added"]}+ onCheckedChange={(enabled) => {+ updatePreference.mutate({+ eventType: "poll.comment.added",+ enabled,+ });+ }}+ />+ </div>+ </div>+ </PageSectionContent>+ </PageSection>+ </PageSectionGroup>+ );+}diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/page.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/page.tsxnew file mode 100644index 000000000..e8e4925a1--- /dev/null+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/notifications/page.tsx@@ -0,0 +1,50 @@+import { dehydrate, HydrationBoundary } from "@tanstack/react-query";+import type { Metadata } from "next";+import type { Params } from "@/app/[locale]/types";+import {+ SettingsPage,+ SettingsPageContent,+ SettingsPageDescription,+ SettingsPageHeader,+ SettingsPageTitle,+} from "@/app/components/settings-layout";+import { Trans } from "@/i18n/client";+import { getTranslation } from "@/i18n/server";+import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";+import { NotificationsPage } from "./notifications-page";++export default async function Page() {+ const helpers = await createPrivateSSRHelper();+ await helpers.user.getNotificationPreferences.prefetch();++ return (+ <HydrationBoundary state={dehydrate(helpers.queryClient)}>+ <SettingsPage>+ <SettingsPageHeader>+ <SettingsPageTitle>+ <Trans i18nKey="notifications" defaults="Notifications" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="notificationsDescription"+ defaults="Choose which email notifications you receive"+ />+ </SettingsPageDescription>+ </SettingsPageHeader>+ <SettingsPageContent>+ <NotificationsPage />+ </SettingsPageContent>+ </SettingsPage>+ </HydrationBoundary>+ );+}++export async function generateMetadata(props: {+ params: Promise<Params>;+}): Promise<Metadata> {+ const params = await props.params;+ const { t } = await getTranslation(params.locale);+ return {+ title: t("notifications", { defaultValue: "Notifications" }),+ };+}diff --git a/apps/web/src/app/api/notifications/unsubscribe/route.ts b/apps/web/src/app/api/notifications/unsubscribe/route.tsdeleted file mode 100644index 136c1a6f2..000000000--- a/apps/web/src/app/api/notifications/unsubscribe/route.ts+++ /dev/null@@ -1,60 +0,0 @@-import { prisma } from "@rallly/database";-import { cookies } from "next/headers";-import type { NextRequest } from "next/server";-import { NextResponse } from "next/server";--import { getSession } from "@/lib/auth";-import type { DisableNotificationsPayload } from "@/trpc/types";-import { decryptToken } from "@/utils/session";--export const GET = async (req: NextRequest) => {- const token = req.nextUrl.searchParams.get("token");-- if (!token) {- return NextResponse.redirect(new URL("/login", req.url));- }-- const session = await getSession();-- if (!session || !session.user?.email) {- return NextResponse.redirect(new URL("/login", req.url));- }-- const payload = await decryptToken<DisableNotificationsPayload>(token);-- if (!payload) {- return NextResponse.redirect(new URL("/login", req.url));- }-- const watcher = await prisma.watcher.findFirst({- where: {- userId: session.user.id,- pollId: payload.pollId,- },- });-- if (watcher) {- await prisma.watcher.delete({- where: {- id: watcher.id,- },- select: {- pollId: true,- },- });-- // Set a session cookie to indicate that the user has unsubscribed- (await cookies()).set(`notifications-unsubscribed-${watcher.pollId}`, "1", {- path: "/",- httpOnly: false,- secure: false,- sameSite: "lax",- maxAge: 5,- });-- // redirect to poll- return NextResponse.redirect(new URL(`/poll/${watcher.pollId}`, req.url));- }-- return NextResponse.redirect(new URL(`/poll/${payload.pollId}`, req.url));-};diff --git a/apps/web/src/components/layouts/poll-layout.tsx b/apps/web/src/components/layouts/poll-layout.tsxindex 221ae9800..25f8bf8b9 100644--- a/apps/web/src/components/layouts/poll-layout.tsx+++ b/apps/web/src/components/layouts/poll-layout.tsx@@ -8,7 +8,6 @@ import type React from "react";import { InviteDialog } from "@/components/invite-dialog";import ManagePoll from "@/components/poll/manage-poll";-import NotificationsToggle from "@/components/poll/notifications-toggle";import { LegacyPollContextProvider } from "@/components/poll/poll-context-provider";import { usePoll } from "@/contexts/poll";import { Trans } from "@/i18n/client";@@ -16,7 +15,6 @@ import { Trans } from "@/i18n/client";const AdminControls = () => {return (<div className="flex items-center gap-x-2">- <NotificationsToggle /><ManagePoll /><InviteDialog /></div>diff --git a/apps/web/src/components/poll/notifications-toggle.tsx b/apps/web/src/components/poll/notifications-toggle.tsxdeleted file mode 100644index 77ba0819b..000000000--- a/apps/web/src/components/poll/notifications-toggle.tsx+++ /dev/null@@ -1,121 +0,0 @@-import { Button } from "@rallly/ui/button";-import { Icon } from "@rallly/ui/icon";-import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";-import { BellOffIcon, BellRingIcon } from "lucide-react";-import { usePathname, useRouter } from "next/navigation";-import type * as React from "react";-import { useUser } from "@/components/user-provider";-import { Trans, useTranslation } from "@/i18n/client";-import { trpc } from "@/trpc/client";-import { usePoll } from "../poll-context";--const NotificationsToggle: React.FunctionComponent = () => {- const { poll } = usePoll();- const pathname = usePathname();- const router = useRouter();-- const { data: watchers } = trpc.polls.getWatchers.useQuery(- {- pollId: poll.id,- },- {- staleTime: Number.POSITIVE_INFINITY,- },- );-- const { user } = useUser();-- const isWatching = watchers?.some(({ userId }) => userId === user?.id);-- const queryClient = trpc.useUtils();-- const watch = trpc.polls.watch.useMutation({- onSuccess: () => {- queryClient.polls.getWatchers.setData(- { pollId: poll.id },- (oldWatchers) => {- if (!oldWatchers || !user) {- return;- }- return [...oldWatchers, { userId: user.id }];- },- );- },- });-- const unwatch = trpc.polls.unwatch.useMutation({- onSuccess: () => {- queryClient.polls.getWatchers.setData(- { pollId: poll.id },- (oldWatchers) => {- if (!oldWatchers) {- return;- }- return oldWatchers.filter(({ userId }) => userId !== user?.id);- },- );- },- });-- const { t } = useTranslation();-- return (- <Tooltip>- <TooltipTrigger asChild>- <Button- data-testid="notifications-toggle"- variant="ghost"- onClick={async () => {- if (!user || user.isGuest) {- router.push(`/login?redirectTo=${encodeURIComponent(pathname)}`);- return;- }- // toggle- if (isWatching) {- await unwatch.mutateAsync({ pollId: poll.id });- } else {- await watch.mutateAsync({ pollId: poll.id });- }- }}- >- {isWatching ? (- <Icon>- <BellRingIcon />- </Icon>- ) : (- <Icon>- <BellOffIcon />- </Icon>- )}- </Button>- </TooltipTrigger>- <TooltipContent side="bottom">- {!user || user.isGuest ? (- <Trans- i18nKey="notificationsGuestTooltip"- defaults="Create an account or login to turn on notifications"- />- ) : (- <Trans- i18nKey="notificationsValue"- defaults="Notifications: <b>{value}</b>"- components={{- b: <span className="font-semibold" />,- }}- values={{- value: isWatching- ? t("notificationsOn", {- defaultValue: "On",- })- : t("notificationsOff", {- defaultValue: "Off",- }),- }}- />- )}- </TooltipContent>- </Tooltip>- );-};--export default NotificationsToggle;diff --git a/apps/web/src/features/notifications/constants.ts b/apps/web/src/features/notifications/constants.tsnew file mode 100644index 000000000..54ae56c47--- /dev/null+++ b/apps/web/src/features/notifications/constants.ts@@ -0,0 +1,6 @@+import type { NotificationPreferences } from "./schema";++export const defaultNotificationPreferences: NotificationPreferences = {+ "poll.response.submitted": true,+ "poll.comment.added": true,+};diff --git a/apps/web/src/features/notifications/queries.ts b/apps/web/src/features/notifications/queries.tsnew file mode 100644index 000000000..b3b65dae6--- /dev/null+++ b/apps/web/src/features/notifications/queries.ts@@ -0,0 +1,82 @@+import { prisma } from "@rallly/database";++import { defaultNotificationPreferences } from "./constants";+import type { ActivityEventType, NotificationPreferences } from "./schema";+import { notificationPreferencesSchema } from "./schema";++function parsePrefs(prefs: unknown): NotificationPreferences {+ const parsed = notificationPreferencesSchema.safeParse(prefs);+ return {+ ...defaultNotificationPreferences,+ ...(parsed.success ? parsed.data : {}),+ };+}++export async function getNotificationPreferences(+ userId: string,+): Promise<NotificationPreferences> {+ const row = await prisma.userNotificationPreferences.findUnique({+ where: { userId },+ select: { prefs: true },+ });++ return parsePrefs(row?.prefs);+}++type NotificationRecipient = {+ id: string;+ email: string;+ locale: string | null;+};++/**+ * Get the poll creator if they should receive a notification for this event.+ * Returns null if the creator has notifications disabled or is the one who+ * triggered the event.+ */+export async function getNotificationRecipient({+ pollId,+ type,+ excludeUserId,+}: {+ pollId: string;+ type: ActivityEventType;+ excludeUserId: string;+}): Promise<NotificationRecipient | null> {+ const poll = await prisma.poll.findUnique({+ where: { id: pollId },+ select: { userId: true },+ });++ if (!poll?.userId || poll.userId === excludeUserId) {+ return null;+ }++ const creator = await prisma.user.findUnique({+ where: { id: poll.userId },+ select: {+ id: true,+ email: true,+ locale: true,+ notificationPreferences: {+ select: { prefs: true },+ },+ },+ });++ if (!creator) {+ return null;+ }++ const prefs = parsePrefs(creator.notificationPreferences?.prefs);++ if (!prefs[type]) {+ return null;+ }++ return {+ id: creator.id,+ email: creator.email,+ locale: creator.locale,+ };+}diff --git a/apps/web/src/features/notifications/schema.ts b/apps/web/src/features/notifications/schema.tsnew file mode 100644index 000000000..8ed737cc1--- /dev/null+++ b/apps/web/src/features/notifications/schema.ts@@ -0,0 +1,18 @@+import * as z from "zod";++/**+ * Activity event type naming convention: {entity}.{sub-entity}.{past-tense-verb}+ */+export const activityEventTypes = [+ "poll.response.submitted",+ "poll.comment.added",+] as const;++export type ActivityEventType = (typeof activityEventTypes)[number];++export const notificationPreferencesSchema = z.record(+ z.enum(activityEventTypes),+ z.boolean(),+);++export type NotificationPreferences = Record<ActivityEventType, boolean>;diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex ccebd9297..c17e585a2 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -529,6 +529,7 @@ export const polls = router({});}),// END LEGACY ROUTES+ // @deprecated — replaced by global notification preferences in /settings/notificationsgetWatchers: publicProcedure.input(z.object({@@ -545,6 +546,7 @@ export const polls = router({},});}),+ // @deprecated — replaced by global notification preferences in /settings/notificationswatch: privateProcedure.input(z.object({ pollId: z.string() })).mutation(async ({ input, ctx }) => {@@ -576,6 +578,7 @@ export const polls = router({},});}),+ // @deprecated — replaced by global notification preferences in /settings/notificationsunwatch: privateProcedure.input(z.object({ pollId: z.string() })).mutation(async ({ input, ctx }) => {diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex 5ef9edabb..2231d382d 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -1,19 +1,21 @@import { prisma } from "@rallly/database";+import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";+import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";import { getEmailClient } from "@/utils/emails";-import { createToken } from "@/utils/session";import {createRateLimitMiddleware,publicProcedure,requireUserMiddleware,router,} from "../../trpc";-import type { DisableNotificationsPayload } from "../../types";import { resolveUserId } from "./utils";+const logger = createLogger("comments");+export const comments = router({list: publicProcedure.input(@@ -123,46 +125,34 @@ export const comments = router({},});- const watchers = await prisma.watcher.findMany({- where: {- pollId,- },- select: {- id: true,- userId: true,- user: {- select: {- email: true,- name: true,- locale: true,- },- },- },- });-const poll = newComment.poll;- for (const watcher of watchers) {- const email = watcher.user.email;- const token = await createToken<DisableNotificationsPayload>(- { watcherId: watcher.id, pollId },- { ttl: 0 },- );+ try {+ const recipient = await getNotificationRecipient({+ pollId,+ type: "poll.comment.added",+ excludeUserId: ctx.user.id,+ });- const emailClient = await getEmailClient(- watcher.user.locale ?? undefined,+ if (recipient) {+ const emailClient = await getEmailClient(+ recipient.locale ?? undefined,+ );+ emailClient.queueTemplate("NewCommentEmail", {+ to: recipient.email,+ props: {+ authorName,+ pollUrl: absoluteUrl(`/poll/${poll.id}`),+ disableNotificationsUrl: absoluteUrl("/settings/notifications"),+ title: poll.title,+ },+ });+ }+ } catch (err) {+ logger.error(+ { error: err, pollId },+ "Failed to send new comment notification email",);- emailClient.queueTemplate("NewCommentEmail", {- to: email,- props: {- authorName,- pollUrl: absoluteUrl(`/poll/${poll.id}`),- disableNotificationsUrl: absoluteUrl(- `/api/notifications/unsubscribe?token=${token}`,- ),- title: poll.title,- },- });}// Track comment addition analyticsdiff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex af81c9ed5..373843430 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -4,17 +4,15 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { waitUntil } from "@vercel/functions";import * as z from "zod";-+import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";import { getEmailClient } from "@/utils/emails";-import { createToken } from "@/utils/session";import {createRateLimitMiddleware,publicProcedure,requireUserMiddleware,router,} from "../../trpc";-import type { DisableNotificationsPayload } from "../../types";import { createParticipantEditToken, resolveUserId } from "./utils";const logger = createLogger("participants");@@ -46,61 +44,44 @@ async function canModifyParticipant(participantId: string, userId: string) {return participant;}-async function sendNewParticipantNotifcationEmail({+async function sendNewResponseNotificationEmail({pollId,pollTitle,participantName,+ excludeUserId,}: {pollId: string;pollTitle: string;participantName: string;+ excludeUserId: string;}) {- const watchers = await prisma.watcher.findMany({- where: {+ try {+ const recipient = await getNotificationRecipient({pollId,- },- select: {- id: true,- userId: true,- user: {- select: {- email: true,- name: true,- locale: true,- },- },- },- });+ type: "poll.response.submitted",+ excludeUserId,+ });- await Promise.all(- watchers.map(async (watcher) => {- try {- const email = watcher.user.email;- const watcherLocale = watcher.user.locale ?? undefined;- const token = await createToken<DisableNotificationsPayload>(- { watcherId: watcher.id, pollId },- { ttl: 0 },- );- const emailClient = await getEmailClient(watcherLocale);- await emailClient.sendTemplate("NewParticipantEmail", {- to: email,- props: {- participantName,- pollUrl: absoluteUrl(`/poll/${pollId}`),- disableNotificationsUrl: absoluteUrl(- `/api/notifications/unsubscribe?token=${token}`,- ),- title: pollTitle,- },- });- } catch (err) {- logger.error(- { error: err, pollId },- "Failed to send watcher notification email",- );- }- }),- );+ if (!recipient) {+ return;+ }++ const emailClient = await getEmailClient(recipient.locale ?? undefined);+ await emailClient.sendTemplate("NewParticipantEmail", {+ to: recipient.email,+ props: {+ participantName,+ pollUrl: absoluteUrl(`/poll/${pollId}`),+ disableNotificationsUrl: absoluteUrl("/settings/notifications"),+ title: pollTitle,+ },+ });+ } catch (err) {+ logger.error(+ { error: err, pollId },+ "Failed to send new response notification email",+ );+ }}export const participants = router({@@ -297,10 +278,11 @@ export const participants = router({}waitUntil(- sendNewParticipantNotifcationEmail({+ sendNewResponseNotificationEmail({pollId,pollTitle: participant.poll.title,participantName: participant.name,+ excludeUserId: ctx.user.id,}),);diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex d0af7a848..47f201fb6 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -4,6 +4,9 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";import { feedbackSchema } from "@/features/feedback/schema";+import { defaultNotificationPreferences } from "@/features/notifications/constants";+import { getNotificationPreferences } from "@/features/notifications/queries";+import { activityEventTypes } from "@/features/notifications/schema";import { defineAbilityFor } from "@/features/user/ability";import {deleteImageFromS3,@@ -236,6 +239,48 @@ export const user = router({where: { id: userId },});}),+ getNotificationPreferences: privateProcedure.query(async ({ ctx }) => {+ return getNotificationPreferences(ctx.user.id);+ }),+ updateNotificationPreference: privateProcedure+ .input(+ z.object({+ eventType: z.enum(activityEventTypes),+ enabled: z.boolean(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const existing = await prisma.userNotificationPreferences.findUnique({+ where: { userId: ctx.user.id },+ select: { prefs: true },+ });++ const updatedPrefs = {+ ...defaultNotificationPreferences,+ ...(existing?.prefs as object),+ [input.eventType]: input.enabled,+ };++ await prisma.userNotificationPreferences.upsert({+ where: { userId: ctx.user.id },+ create: {+ userId: ctx.user.id,+ prefs: updatedPrefs,+ },+ update: {+ prefs: updatedPrefs,+ },+ });++ ctx.posthog?.capture({+ event: "notification_preference_update",+ distinctId: ctx.user.id,+ properties: {+ eventType: input.eventType,+ enabled: input.enabled,+ },+ });+ }),updateLocale: privateProcedure.input(z.object({ locale: z.string() })).mutation(async ({ input, ctx }) => {diff --git a/apps/web/src/trpc/types.ts b/apps/web/src/trpc/types.tsindex bbf916d32..678f3f3e5 100644--- a/apps/web/src/trpc/types.ts+++ b/apps/web/src/trpc/types.ts@@ -6,11 +6,6 @@ export type RegistrationTokenPayload = {code: string;};-export type DisableNotificationsPayload = {- pollId: string;- watcherId: number;-};-export type RegisteredUserSession = {isGuest: false;id: string;diff --git a/packages/database/prisma/migrations/20260304114245_notification_prefs/migration.sql b/packages/database/prisma/migrations/20260304114245_notification_prefs/migration.sqlnew file mode 100644index 000000000..a5d475136--- /dev/null+++ b/packages/database/prisma/migrations/20260304114245_notification_prefs/migration.sql@@ -0,0 +1,16 @@+-- CreateTable+CREATE TABLE "user_notification_preferences" (+ "id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "prefs" JSONB NOT NULL DEFAULT '{}',+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "user_notification_preferences_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "user_notification_preferences_user_id_key" ON "user_notification_preferences"("user_id");++-- AddForeignKey+ALTER TABLE "user_notification_preferences" ADD CONSTRAINT "user_notification_preferences_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/database/prisma/models/notification.prisma b/packages/database/prisma/models/notification.prismanew file mode 100644index 000000000..d5e61476f--- /dev/null+++ b/packages/database/prisma/models/notification.prisma@@ -0,0 +1,11 @@+model UserNotificationPreferences {+ id String @id @default(cuid())+ userId String @unique @map("user_id")+ prefs Json @default("{}") @map("prefs")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @updatedAt @map("updated_at")++ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@map("user_notification_preferences")+}diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex 8c061dc72..4143a625d 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -60,6 +60,7 @@ model User {comments Comment[]polls Poll[]watcher Watcher[]+ notificationPreferences UserNotificationPreferences?accounts Account[]participants Participant[]paymentMethods PaymentMethod[]diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.jsonindex 318b54c80..ff0d8559b 100644--- a/packages/emails/locales/en/emails.json+++ b/packages/emails/locales/en/emails.json@@ -1,6 +1,6 @@{"common_poweredBy": "Powered by <a>{domain}</a>",- "common_disableNotifications": "If you would like to stop receiving updates you can <a>turn notifications off</a>.",+ "common_disableNotifications": "You can <a>manage your notification settings</a> to stop receiving these emails.","finalizeHost_content": "<b>{title}</b> has been booked for:","finalizeHost_preview": "Final date booked! We've notified participants and sent them calendar invites.","finalizeHost_heading": "Final date booked!",diff --git a/packages/emails/src/components/notification-email.tsx b/packages/emails/src/components/notification-email.tsxindex cccbcf79e..fddff320b 100644--- a/packages/emails/src/components/notification-email.tsx+++ b/packages/emails/src/components/notification-email.tsx@@ -42,7 +42,7 @@ export const NotificationEmail = ({t={ctx.t}i18nKey="common_disableNotifications"ns="emails"- defaults="If you would like to stop receiving updates you can <a>turn notifications off</a>."+ defaults="You can <a>manage your notification settings</a> to stop receiving these emails."components={{a: (<Link