Skip to content

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

♻️ Replace user & profile server actions with tRPC mutations (RAL-1023) (#2244)

Luke Vella6cdcdc06cb4e
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/actions.ts b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/actions.ts
deleted file mode 100644
index c8af73b19..000000000
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/actions.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-"use server";
-
-import { prisma } from "@rallly/database";
-
-import { getUserIdIfLoggedIn } from "@/lib/auth";
-
-export async function updateLocale(locale: string) {
- const userId = await getUserIdIfLoggedIn();
- if (!userId) {
- throw new Error("User not found");
- }
- await prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- locale,
- },
- });
-}
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/date-time-preferences.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/date-time-preferences.tsx
index f5c993e6a..ac2678641 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/date-time-preferences.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/date-time-preferences.tsx
@@ -29,7 +29,7 @@ const formSchema = z.object({
weekStart: z.number().min(0).max(6),
});
-const DateTimePreferencesForm = () => {
+export const DateTimePreferences = () => {
const { timeFormat, weekStart, timeZone } = useDayjs();
const { updatePreferences } = usePreferences();
@@ -134,7 +134,3 @@ const DateTimePreferencesForm = () => {
</Form>
);
};
-
-export const DateTimePreferences = () => {
- return <DateTimePreferencesForm />;
-};
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/language-preference.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/language-preference.tsx
index 7c262e2c3..3b2cea718 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/language-preference.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/language-preference.tsx
@@ -9,24 +9,27 @@ import {
} from "@rallly/ui/form";
import { ArrowUpRight } from "lucide-react";
import Link from "next/link";
-import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { LanguageSelect } from "@/components/poll/language-selector";
-import { Trans, useTranslation } from "@/i18n/client";
-import { setLocaleCookie } from "@/lib/locale/client";
-import { updateLocale } from "../actions";
+import { Trans } from "@/i18n/client";
+import { useLocale } from "@/lib/locale/client";
+import { trpc } from "@/trpc/client";
const formSchema = z.object({
language: z.string(),
});
export const LanguagePreference = () => {
- const { i18n } = useTranslation();
- const router = useRouter();
+ const { locale, changeLocale } = useLocale();
+ const updateLocale = trpc.user.updateLocale.useMutation({
+ onSuccess: (_data, variables) => {
+ changeLocale(variables.locale);
+ },
+ });
const form = useForm({
defaultValues: {
- language: i18n.language,
+ language: locale,
},
resolver: zodResolver(formSchema),
});
@@ -35,9 +38,7 @@ export const LanguagePreference = () => {
<Form {...form}>
<form
onSubmit={form.handleSubmit(async (data) => {
- await updateLocale(data.language);
- setLocaleCookie(data.language);
- router.refresh();
+ await updateLocale.mutateAsync({ locale: data.language });
})}
>
<FormField
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/theme-preference.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/theme-preference.tsx
index 22caebf97..adb949ff0 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/theme-preference.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/preferences/components/theme-preference.tsx
@@ -2,16 +2,9 @@
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
-import React from "react";
import { useTheme } from "@/features/theme/client";
import { Trans } from "@/i18n/client";
-const themes = [
- { value: "system", icon: MonitorIcon },
- { value: "light", icon: SunIcon },
- { value: "dark", icon: MoonIcon },
-] as const;
-
function ThemeOption({
value,
children,
@@ -37,24 +30,6 @@ function ThemeOptionLabel({ children }: { children: React.ReactNode }) {
export function ThemePreference() {
const { theme, setTheme } = useTheme();
- const [mounted, setMounted] = React.useState(false);
-
- React.useEffect(() => {
- setMounted(true);
- }, []);
-
- if (!mounted) {
- return (
- <div className="flex gap-2">
- {themes.map(({ value }) => (
- <div
- key={value}
- className="h-20 w-24 animate-pulse rounded-lg bg-card"
- />
- ))}
- </div>
- );
- }
return (
<RadioGroup
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(app)/(space)/settings/profile/actions.ts
deleted file mode 100644
index 30bfe35af..000000000
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/actions.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-"use server";
-
-import { subject } from "@casl/ability";
-import { prisma } from "@rallly/database";
-import { signOut } from "@/lib/auth";
-import { AppError } from "@/lib/errors";
-import { authActionClient } from "@/lib/safe-action/server";
-
-export const deleteCurrentUserAction = authActionClient
- .metadata({ actionName: "delete_current_user" })
- .action(async ({ ctx }) => {
- const userId = ctx.user.id;
-
- const user = await prisma.user.findUnique({
- where: { id: userId },
- include: {
- subscriptions: {
- select: {
- active: true,
- },
- },
- },
- });
-
- if (!user) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
-
- if (ctx.ability.cannot("delete", subject("User", user))) {
- throw new AppError({
- code: "UNAUTHORIZED",
- message: "You are not authorized to delete this user",
- });
- }
-
- // Check if user has active subscriptions
- if (user.subscriptions.some((subscription) => subscription.active)) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "User has active subscriptions",
- });
- }
-
- await prisma.user.delete({
- where: {
- id: userId,
- },
- });
-
- await signOut();
-
- return {
- success: true,
- };
- });
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/delete-account-dialog.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/profile/delete-account-dialog.tsx
index bf2c0fd5f..e277c44a8 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/delete-account-dialog.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/profile/delete-account-dialog.tsx
@@ -15,9 +15,7 @@ import { Input } from "@rallly/ui/input";
import { useForm } from "react-hook-form";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { trpc } from "@/trpc/client";
-import { deleteCurrentUserAction } from "./actions";
export function DeleteAccountDialog({ children, ...rest }: DialogProps & {}) {
const [user] = trpc.user.getAuthed.useSuspenseQuery();
@@ -27,7 +25,7 @@ export function DeleteAccountDialog({ children, ...rest }: DialogProps & {}) {
},
});
- const deleteUser = useSafeAction(deleteCurrentUserAction);
+ const deleteUser = trpc.user.deleteMe.useMutation();
const { t } = useTranslation();
return (
@@ -39,7 +37,7 @@ export function DeleteAccountDialog({ children, ...rest }: DialogProps & {}) {
method="POST"
action="/auth/logout"
onSubmit={form.handleSubmit(async () => {
- await deleteUser.executeAsync();
+ await deleteUser.mutateAsync();
})}
>
<DialogHeader>
@@ -97,7 +95,7 @@ export function DeleteAccountDialog({ children, ...rest }: DialogProps & {}) {
</DialogClose>
<Button
type="submit"
- loading={deleteUser.isExecuting}
+ loading={deleteUser.isPending}
variant="destructive"
>
<Trans i18nKey="deleteAccount" defaults="Delete Account" />
diff --git a/apps/web/src/features/feedback/actions.ts b/apps/web/src/features/feedback/actions.ts
deleted file mode 100644
index 6f5a387f2..000000000
--- a/apps/web/src/features/feedback/actions.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-"use server";
-
-import { feedbackSchema } from "@/features/feedback/schema";
-import {
- authActionClient,
- createRateLimitMiddleware,
-} from "@/lib/safe-action/server";
-import { getEmailClient } from "@/utils/emails";
-
-export const submitFeedbackAction = authActionClient
- .metadata({
- actionName: "submit_feedback",
- })
- .use(createRateLimitMiddleware(5, "1 h"))
- .inputSchema(feedbackSchema)
- .action(async ({ ctx, parsedInput }) => {
- try {
- const { content } = parsedInput;
- const emailClient = await getEmailClient();
- emailClient.sendEmail({
- subject: "Feedback",
- text: `User: ${ctx.user.name} (${ctx.user.email})\n\n${content}`,
- });
-
- ctx.posthog?.capture({
- event: "feedback_send",
- distinctId: ctx.user.id,
- });
-
- return {
- success: true,
- };
- } catch {
- return {
- error: "Invalid Form Data" as const,
- };
- }
- });
diff --git a/apps/web/src/features/feedback/components/feedback-dialog.tsx b/apps/web/src/features/feedback/components/feedback-dialog.tsx
index 5c89abf3d..3aeff613a 100644
--- a/apps/web/src/features/feedback/components/feedback-dialog.tsx
+++ b/apps/web/src/features/feedback/components/feedback-dialog.tsx
@@ -16,14 +16,12 @@ import { CheckCircle2Icon } from "lucide-react";
import { useForm } from "react-hook-form";
import { Trans } from "@/i18n/client";
-
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
import { isSelfHosted } from "@/utils/constants";
-import { submitFeedbackAction } from "../actions";
import { feedbackSchema } from "../schema";
export function FeedbackDialog(props: DialogProps) {
- const submitFeedback = useSafeAction(submitFeedbackAction);
+ const submitFeedback = trpc.user.submitFeedback.useMutation();
const form = useForm({
resolver: zodResolver(feedbackSchema),
});
@@ -50,7 +48,11 @@ export function FeedbackDialog(props: DialogProps) {
</DialogHeader>
<Form {...form}>
- <form onSubmit={form.handleSubmit(submitFeedback.executeAsync)}>
+ <form
+ onSubmit={form.handleSubmit((data) =>
+ submitFeedback.mutateAsync(data),
+ )}
+ >
<FormField
control={form.control}
name="content"
diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.ts
index 63fb33bde..d0af7a848 100644
--- a/apps/web/src/trpc/routers/user.ts
+++ b/apps/web/src/trpc/routers/user.ts
@@ -1,7 +1,10 @@
+import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import { TRPCError } from "@trpc/server";
import * as z from "zod";
+import { feedbackSchema } from "@/features/feedback/schema";
+import { defineAbilityFor } from "@/features/user/ability";
import {
deleteImageFromS3,
getImageUploadUrl,
@@ -192,4 +195,69 @@ export const user = router({
return { success: true };
}),
+ deleteMe: privateProcedure.mutation(async ({ ctx }) => {
+ const userId = ctx.user.id;
+
+ const user = await prisma.user.findUnique({
+ where: { id: userId },
+ include: {
+ subscriptions: {
+ select: {
+ active: true,
+ },
+ },
+ },
+ });
+
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
+
+ const ability = defineAbilityFor(ctx.user);
+
+ if (ability.cannot("delete", subject("User", user))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You are not authorized to delete this user",
+ });
+ }
+
+ if (user.subscriptions.some((subscription) => subscription.active)) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "User has active subscriptions",
+ });
+ }
+
+ await prisma.user.delete({
+ where: { id: userId },
+ });
+ }),
+ updateLocale: privateProcedure
+ .input(z.object({ locale: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await prisma.user.update({
+ where: { id: ctx.user.id },
+ data: { locale: input.locale },
+ });
+ }),
+ submitFeedback: privateProcedure
+ .use(createRateLimitMiddleware("submit_feedback", 5, "1 h"))
+ .input(feedbackSchema)
+ .mutation(async ({ input, ctx }) => {
+ const emailClient = await getEmailClient();
+ emailClient.sendEmail({
+ subject: "Feedback",
+ text: `User: ${ctx.user.name} (${ctx.user.email})\n\n${input.content}`,
+ });
+
+ ctx.posthog?.capture({
+ event: "feedback_send",
+ distinctId: ctx.user.id,
+ });
+ }),
});