Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Migrate polls.toggleMuted tRPC mutation to a server action (#2808)
Luke Vella9f52dbe719fb
diff --git a/apps/web/src/features/poll/actions.ts b/apps/web/src/features/poll/actions.tsnew file mode 100644index 000000000..d757e3eb8--- /dev/null+++ b/apps/web/src/features/poll/actions.ts@@ -0,0 +1,31 @@+"use server";++import { setPollMuted } from "@/features/poll/mutations";+import { setPollMutedSchema } from "@/features/poll/schema";+import { identifyGroup } from "@/lib/posthog";+import { authActionClient } from "@/lib/safe-action/server";++export const setPollMutedAction = authActionClient+ .metadata({ actionName: "set_poll_muted" })+ .inputSchema(setPollMutedSchema)+ .action(async ({ ctx, parsedInput }) => {+ const { pollId, muted } = parsedInput;++ const result = await setPollMuted({+ pollId,+ userId: ctx.user.id,+ muted,+ });++ if (result.ok) {+ identifyGroup({+ groupType: "poll",+ groupKey: pollId,+ properties: {+ muted,+ },+ });+ }++ return result;+ });diff --git a/apps/web/src/features/poll/components/notification-toggle.tsx b/apps/web/src/features/poll/components/notification-toggle.tsxindex 6becca15d..7aa16c2e8 100644--- a/apps/web/src/features/poll/components/notification-toggle.tsx+++ b/apps/web/src/features/poll/components/notification-toggle.tsx@@ -4,9 +4,11 @@ import { Button } from "@rallly/ui/button";import { toast } from "@rallly/ui/sonner";import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";import { BellIcon, BellOffIcon } from "lucide-react";+import { setPollMutedAction } from "@/features/poll/actions";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() {@@ -14,16 +16,19 @@ export function NotificationToggle() {const { user, ownsObject } = useUser();const { t } = useTranslation();const queryClient = trpc.useUtils();- const toggleMuted = trpc.polls.toggleMuted.useMutation({- onSuccess: (_data, vars) => {- queryClient.polls.get.setData({ urlId: vars.pollId }, (oldData) => {+ 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: vars.muted,+ muted: input.muted,};});- if (vars.muted) {+ if (input.muted) {toast(t("notificationToggleMutedToast", {defaultValue: "Notifications are off for this poll",@@ -33,7 +38,7 @@ export function NotificationToggle() {action: {label: t("undo", { defaultValue: "Undo" }),onClick: () => {- toggleMuted.mutate({ pollId: vars.pollId, muted: false });+ setPollMuted.execute({ pollId: input.pollId, muted: false });},},},@@ -69,9 +74,9 @@ export function NotificationToggle() {}): t("muteNotifications", { defaultValue: "Mute notifications" })}- loading={toggleMuted.isPending}+ loading={setPollMuted.isExecuting}onClick={() => {- toggleMuted.mutate({ pollId: poll.id, muted: !poll.muted });+ setPollMuted.execute({ pollId: poll.id, muted: !poll.muted });}}>{poll.muted ? <BellOffIcon /> : <BellIcon />}diff --git a/apps/web/src/features/poll/mutations.test.ts b/apps/web/src/features/poll/mutations.test.tsindex f6df36ba1..8ed5afc96 100644--- a/apps/web/src/features/poll/mutations.test.ts+++ b/apps/web/src/features/poll/mutations.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";import type { AuthorizedSpaceId } from "@/features/space/types";-import { closePoll, deleteInactivePolls } from "./mutations";+import { closePoll, deleteInactivePolls, setPollMuted } from "./mutations";const { mockUpdateMany, mockFindFirst, mockUpdate } = vi.hoisted(() => ({mockUpdateMany: vi.fn(),@@ -203,3 +203,37 @@ describe("closePoll", () => {);});});++describe("setPollMuted", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("scopes the update to the owner and excludes deleted polls", async () => {+ mockUpdateMany.mockResolvedValue({ count: 1 });++ const result = await setPollMuted({+ pollId: "p1",+ userId: "u1",+ muted: true,+ });++ expect(mockUpdateMany).toHaveBeenCalledWith({+ where: { id: "p1", userId: "u1", deletedAt: null },+ data: { muted: true },+ });+ expect(result).toEqual({ ok: true });+ });++ it("returns notFound when no poll matches the owner scope", async () => {+ mockUpdateMany.mockResolvedValue({ count: 0 });++ const result = await setPollMuted({+ pollId: "p1",+ userId: "not-the-owner",+ muted: true,+ });++ expect(result).toEqual({ ok: false, reason: "notFound" });+ });+});diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.tsindex 81ba18443..30095409f 100644--- a/apps/web/src/features/poll/mutations.ts+++ b/apps/web/src/features/poll/mutations.ts@@ -149,6 +149,35 @@ export const closePoll = async ({});};+/**+ * Muting is a per-owner notification preference, so the scope is the owner's+ * userId rather than a space.+ */+export const setPollMuted = async ({+ pollId,+ userId,+ muted,+}: {+ pollId: string;+ userId: string;+ muted: boolean;+}) => {+ const { count } = await prisma.poll.updateMany({+ where: {+ id: pollId,+ userId,+ deletedAt: null,+ },+ data: { muted },+ });++ if (count === 0) {+ return { ok: false as const, reason: "notFound" as const };+ }++ return { ok: true as const };+};+export const deletePoll = async (pollId: string,spaceId: AuthorizedSpaceId,diff --git a/apps/web/src/features/poll/schema.ts b/apps/web/src/features/poll/schema.tsindex c4f1633a2..7e73ab32a 100644--- a/apps/web/src/features/poll/schema.ts+++ b/apps/web/src/features/poll/schema.ts@@ -30,3 +30,8 @@ export type PollStatus = z.infer<typeof pollStatusSchema>;export const pollClosedReasonSchema = z.enum(["auto", "manual"]);export type PollClosedReason = z.infer<typeof pollClosedReasonSchema>;++export const setPollMutedSchema = z.object({+ pollId: z.string(),+ muted: z.boolean(),+});diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 9ce40214e..887c7d8d0 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -591,34 +591,6 @@ export const polls = router({);}),// END LEGACY ROUTES- toggleMuted: privateProcedure- .input(z.object({ pollId: z.string(), muted: z.boolean() }))- .mutation(async ({ input, ctx }) => {- const poll = await prisma.poll.findUnique({- where: { id: input.pollId },- select: { userId: true },- });-- if (!poll || poll.userId !== ctx.user.id) {- throw new TRPCError({- code: "FORBIDDEN",- message: "Only the poll owner can mute notifications",- });- }-- await prisma.poll.update({- where: { id: input.pollId },- data: { muted: input.muted },- });-- identifyGroup({- groupType: "poll",- groupKey: input.pollId,- properties: {- muted: input.muted,- },- });- }),get: publicProcedure.input(z.object({