Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Migrate notification preferences settings off tRPC (#2865)
Luke Vella8171c62c6d59
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex a1fe33d2c..23eda2788 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -494,7 +494,6 @@"notFoundDescription": "Sorry, we couldn't find the page you're looking for. Here are some helpful links instead.","notFoundLabel": "404","notFoundTitle": "Page not found",- "notificationPreferenceSaveError": "Failed to save your notification preference","notifications": "Notifications","notificationsDescription": "Choose which email notifications you receive","notificationToggleMutedToast": "Notifications are off for this poll",diff --git a/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx b/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsxindex 2fd6ae77c..8b609624b 100644--- a/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/notifications/notifications-page.tsx@@ -3,6 +3,7 @@import { toast } from "@rallly/ui/sonner";import { Switch } from "@rallly/ui/switch";import { InboxIcon, MessageCircleIcon } from "lucide-react";+import React from "react";import {PageSection,PageSectionContent,@@ -19,39 +20,38 @@ import {SettingsGroup,SettingTitle,} from "@/components/setting";+import { updateNotificationPreferenceAction } from "@/features/notifications/actions";+import type {+ ActivityEventType,+ NotificationPreferences,+} from "@/features/notifications/schema";import { Trans, useTranslation } from "@/i18n/client";-import { trpc } from "@/trpc/client";+import { useSafeAction } from "@/lib/safe-action/client";-export function NotificationsPage() {+export function NotificationsPage({+ initialPreferences,+}: {+ initialPreferences: NotificationPreferences;+}) {const { t } = useTranslation();- const utils = trpc.useUtils();- const [preferences] = trpc.user.getNotificationPreferences.useSuspenseQuery();- const updatePreference = trpc.user.updateNotificationPreference.useMutation({- onMutate: async ({ eventType, enabled }) => {- await utils.user.getNotificationPreferences.cancel();- const previous = utils.user.getNotificationPreferences.getData();- utils.user.getNotificationPreferences.setData(undefined, (old) =>- old ? { ...old, [eventType]: enabled } : old,- );- return { previous };- },- onSuccess: () => {+ const [preferences, setPreferences] = React.useState(initialPreferences);+ const updatePreference = useSafeAction(updateNotificationPreferenceAction);++ const setPreference = async (+ eventType: ActivityEventType,+ enabled: boolean,+ ) => {+ const previous = preferences[eventType];+ setPreferences((old) => ({ ...old, [eventType]: enabled }));+ const result = await updatePreference.executeAsync({ eventType, enabled });+ if (result?.serverError || result?.validationErrors) {+ // Roll back only the toggled field — a full-snapshot restore could+ // clobber another toggle that succeeded while this one was in flight.+ setPreferences((old) => ({ ...old, [eventType]: previous }));+ } else {toast.success(t("saved", { defaultValue: "Saved" }));- },- onError: (_err, _vars, context) => {- if (context?.previous) {- utils.user.getNotificationPreferences.setData(- undefined,- context.previous,- );- }- toast.error(- t("notificationPreferenceSaveError", {- defaultValue: "Failed to save your notification preference",- }),- );- },- });+ }+ };return (<PageSectionGroup>@@ -86,10 +86,7 @@ export function NotificationsPage() {<Switchchecked={preferences["poll.response.submitted"]}onCheckedChange={(enabled) => {- updatePreference.mutate({- eventType: "poll.response.submitted",- enabled,- });+ setPreference("poll.response.submitted", enabled);}}/></SettingControl>@@ -111,10 +108,7 @@ export function NotificationsPage() {<Switchchecked={preferences["poll.comment.added"]}onCheckedChange={(enabled) => {- updatePreference.mutate({- eventType: "poll.comment.added",- enabled,- });+ setPreference("poll.comment.added", enabled);}}/></SettingControl>diff --git a/apps/web/src/app/[locale]/(space)/settings/notifications/page.tsx b/apps/web/src/app/[locale]/(space)/settings/notifications/page.tsxindex a9107aa09..c8014babb 100644--- a/apps/web/src/app/[locale]/(space)/settings/notifications/page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/notifications/page.tsx@@ -1,4 +1,3 @@-import { dehydrate, HydrationBoundary } from "@tanstack/react-query";import type { Metadata } from "next";import type { Params } from "@/app/[locale]/types";import {@@ -8,34 +7,31 @@ import {SettingsPageHeader,SettingsPageTitle,} from "@/components/settings-layout";+import { loadNotificationPreferences } from "@/features/notifications/loaders";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();+ const preferences = await loadNotificationPreferences();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>+ <SettingsPage>+ <SettingsPageHeader>+ <SettingsPageTitle>+ <Trans i18nKey="notifications" defaults="Notifications" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="notificationsDescription"+ defaults="Choose which email notifications you receive"+ />+ </SettingsPageDescription>+ </SettingsPageHeader>+ <SettingsPageContent>+ <NotificationsPage initialPreferences={preferences} />+ </SettingsPageContent>+ </SettingsPage>);}diff --git a/apps/web/src/features/notifications/actions.ts b/apps/web/src/features/notifications/actions.tsnew file mode 100644index 000000000..5edf111ee--- /dev/null+++ b/apps/web/src/features/notifications/actions.ts@@ -0,0 +1,25 @@+"use server";++import { updateNotificationPreference } from "@/features/notifications/mutations";+import { updateNotificationPreferenceSchema } from "@/features/notifications/schema";+import { track } from "@/lib/posthog";+import { authActionClient } from "@/lib/safe-action/server";++export const updateNotificationPreferenceAction = authActionClient+ .metadata({ actionName: "update_notification_preference" })+ .inputSchema(updateNotificationPreferenceSchema)+ .action(async ({ ctx, parsedInput }) => {+ await updateNotificationPreference({+ userId: ctx.user.id,+ eventType: parsedInput.eventType,+ enabled: parsedInput.enabled,+ });++ track(ctx.user, {+ event: "notification_preference_update",+ properties: {+ eventType: parsedInput.eventType,+ enabled: parsedInput.enabled,+ },+ });+ });diff --git a/apps/web/src/features/notifications/loaders.ts b/apps/web/src/features/notifications/loaders.tsnew file mode 100644index 000000000..b44514391--- /dev/null+++ b/apps/web/src/features/notifications/loaders.ts@@ -0,0 +1,10 @@+import "server-only";++import { cache } from "react";+import { getNotificationPreferences } from "@/features/notifications/data";+import { requireUser } from "@/features/user/loaders";++export const loadNotificationPreferences = cache(async () => {+ const user = await requireUser();+ return getNotificationPreferences(user.id);+});diff --git a/apps/web/src/features/notifications/mutations.ts b/apps/web/src/features/notifications/mutations.tsnew file mode 100644index 000000000..b3469bc8b--- /dev/null+++ b/apps/web/src/features/notifications/mutations.ts@@ -0,0 +1,51 @@+import "server-only";++import { Prisma, prisma } from "@rallly/database";++import { defaultNotificationPreferences } from "./constants";+import type { ActivityEventType } from "./schema";++export async function updateNotificationPreference({+ userId,+ eventType,+ enabled,+}: {+ userId: string;+ eventType: ActivityEventType;+ enabled: boolean;+}) {+ const patch = JSON.stringify({ [eventType]: enabled });++ // The merge happens in the database (jsonb ||) so concurrent toggles of+ // different keys can't clobber each other the way a read-merge-replace+ // upsert would.+ const mergeIntoExistingRow = () => prisma.$executeRaw`+ UPDATE user_notification_preferences+ SET prefs = prefs || ${patch}::jsonb, updated_at = now()+ WHERE user_id = ${userId}+ `;++ if ((await mergeIntoExistingRow()) > 0) {+ return;+ }++ // No row yet — create through Prisma for the client-generated cuid. A+ // concurrent create surfaces as P2002 and falls back to the atomic merge.+ try {+ await prisma.userNotificationPreferences.create({+ data: {+ userId,+ prefs: { ...defaultNotificationPreferences, [eventType]: enabled },+ },+ });+ } catch (e) {+ if (+ e instanceof Prisma.PrismaClientKnownRequestError &&+ e.code === "P2002"+ ) {+ await mergeIntoExistingRow();+ return;+ }+ throw e;+ }+}diff --git a/apps/web/src/features/notifications/schema.ts b/apps/web/src/features/notifications/schema.tsindex 8ed737cc1..94608d5d2 100644--- a/apps/web/src/features/notifications/schema.ts+++ b/apps/web/src/features/notifications/schema.ts@@ -15,4 +15,9 @@ export const notificationPreferencesSchema = z.record(z.boolean(),);+export const updateNotificationPreferenceSchema = z.object({+ eventType: z.enum(activityEventTypes),+ enabled: z.boolean(),+});+export type NotificationPreferences = Record<ActivityEventType, boolean>;diff --git a/apps/web/src/trpc/routers/index.ts b/apps/web/src/trpc/routers/index.tsindex 79d07712c..91dd7fe9e 100644--- a/apps/web/src/trpc/routers/index.ts+++ b/apps/web/src/trpc/routers/index.ts@@ -10,7 +10,6 @@ import { events } from "./events";import { polls } from "./polls";import { spaces } from "./spaces";import { system } from "./system";-import { user } from "./user";export const appRouter = mergeRouters(router({@@ -22,7 +21,6 @@ export const appRouter = mergeRouters(polls,spaces,system,- user,calendars,}),);diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsdeleted file mode 100644index 73879146f..000000000--- a/apps/web/src/trpc/routers/user.ts+++ /dev/null@@ -1,51 +0,0 @@-import { prisma } from "@rallly/database";-import * as z from "zod";-import { defaultNotificationPreferences } from "@/features/notifications/constants";-import { getNotificationPreferences } from "@/features/notifications/data";-import { activityEventTypes } from "@/features/notifications/schema";-import { track } from "@/lib/posthog";-import { privateProcedure, router } from "../trpc";--export const user = router({- 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,- },- });-- track(ctx.user, {- event: "notification_preference_update",- properties: {- eventType: input.eventType,- enabled: input.enabled,- },- });- }),-});