Skip to content

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

♻️ Replace space server actions with trpc procedures (#2238)

Luke Vellaa1e5138e194c
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/delete-space-button.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/delete-space-button.tsx
index efe91b822..29e1902a4 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/delete-space-button.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/delete-space-button.tsx
@@ -19,18 +19,15 @@ import { TrashIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
-import { deleteSpaceAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
interface DeleteSpaceDialogProps extends DialogProps {
spaceName: string;
- spaceId: string;
}
function DeleteSpaceDialog({
spaceName,
- spaceId,
children,
...rest
}: DeleteSpaceDialogProps) {
@@ -40,7 +37,7 @@ function DeleteSpaceDialog({
},
});
- const deleteSpace = useSafeAction(deleteSpaceAction, {
+ const deleteSpace = trpc.spaces.delete.useMutation({
onSuccess: () => {
toast.success(
t("deletedSpaceSuccess", {
@@ -61,7 +58,7 @@ function DeleteSpaceDialog({
<DialogContent>
<form
onSubmit={form.handleSubmit(() => {
- deleteSpace.execute({ spaceId });
+ deleteSpace.mutate();
})}
>
<DialogHeader>
@@ -120,7 +117,7 @@ function DeleteSpaceDialog({
</DialogClose>
<Button
type="submit"
- loading={deleteSpace.isExecuting}
+ loading={deleteSpace.isPending}
variant="destructive"
>
<Trans
@@ -138,15 +135,11 @@ function DeleteSpaceDialog({
interface DeleteSpaceButtonProps {
spaceName: string;
- spaceId: string;
}
-export function DeleteSpaceButton({
- spaceName,
- spaceId,
-}: DeleteSpaceButtonProps) {
+export function DeleteSpaceButton({ spaceName }: DeleteSpaceButtonProps) {
return (
- <DeleteSpaceDialog spaceName={spaceName} spaceId={spaceId}>
+ <DeleteSpaceDialog spaceName={spaceName}>
<DialogTrigger asChild>
<Button variant="destructive">
<TrashIcon className="size-4" />
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/leave-space-button.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/leave-space-button.tsx
index 925f5180c..121b4a53b 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/leave-space-button.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/leave-space-button.tsx
@@ -26,9 +26,8 @@ import { toast } from "@rallly/ui/sonner";
import { LogOutIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
-import { leaveSpaceAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
interface LeaveSpaceDialogProps extends DialogProps {
spaceName: string;
@@ -49,7 +48,7 @@ function LeaveSpaceDialog({
},
});
- const leaveSpace = useSafeAction(leaveSpaceAction, {
+ const leaveSpace = trpc.spaces.leave.useMutation({
onSuccess: () => {
toast.success(
t("leftSpaceSuccess", {
@@ -83,7 +82,7 @@ function LeaveSpaceDialog({
<form
id={formName}
onSubmit={form.handleSubmit(() => {
- leaveSpace.execute();
+ leaveSpace.mutate();
})}
>
<FormField
@@ -129,7 +128,7 @@ function LeaveSpaceDialog({
<Button
form={formName}
type="submit"
- loading={leaveSpace.isExecuting}
+ loading={leaveSpace.isPending}
variant="destructive"
>
<Trans i18nKey="leaveSpace" defaults="Leave Space" />
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/space-settings-form.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/space-settings-form.tsx
index 8bae92b52..a1ae69ac9 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/space-settings-form.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/general/components/space-settings-form.tsx
@@ -12,7 +12,6 @@ import {
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
-import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import * as z from "zod";
import {
@@ -20,15 +19,10 @@ import {
ImageUploadControl,
ImageUploadPreview,
} from "@/components/image-upload";
-import {
- removeSpaceImageAction,
- updateSpaceAction,
- updateSpaceImageAction,
-} from "@/features/space/actions";
import { SpaceIcon } from "@/features/space/components/space-icon";
import type { SpaceDTO } from "@/features/space/types";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
const spaceSettingsSchema = z.object({
name: z
@@ -47,11 +41,11 @@ export function SpaceSettingsForm({
disabled = false,
}: SpaceSettingsFormProps) {
const { t } = useTranslation();
- const router = useRouter();
- const updateSpace = useSafeAction(updateSpaceAction);
- const updateImage = useSafeAction(updateSpaceImageAction);
- const removeImage = useSafeAction(removeSpaceImageAction);
+ const updateSpace = trpc.spaces.update.useMutation();
+ const getImageUploadUrl = trpc.spaces.getImageUploadUrl.useMutation();
+ const updateImage = trpc.spaces.updateImage.useMutation();
+ const removeImage = trpc.spaces.removeImage.useMutation();
const form = useForm({
resolver: zodResolver(spaceSettingsSchema),
@@ -61,13 +55,11 @@ export function SpaceSettingsForm({
});
const handleImageUploadSuccess = async (imageKey: string) => {
- await updateImage.executeAsync({ imageKey });
- router.refresh();
+ await updateImage.mutateAsync({ imageKey });
};
const handleImageRemoveSuccess = async () => {
- await removeImage.executeAsync();
- router.refresh();
+ await removeImage.mutateAsync();
};
return (
@@ -75,7 +67,7 @@ export function SpaceSettingsForm({
<form
onSubmit={form.handleSubmit(async (data) => {
toast.promise(
- updateSpace.executeAsync({
+ updateSpace.mutateAsync({
name: data.name,
}),
{
@@ -104,7 +96,7 @@ export function SpaceSettingsForm({
<SpaceIcon name={space.name} src={space.image} size="xl" />
</ImageUploadPreview>
<ImageUploadControl
- keyPrefix="spaces"
+ getUploadUrl={(input) => getImageUploadUrl.mutateAsync(input)}
onUploadSuccess={handleImageUploadSuccess}
onRemoveSuccess={handleImageRemoveSuccess}
hasCurrentImage={!!space.image}
@@ -137,9 +129,7 @@ export function SpaceSettingsForm({
<Button
type="submit"
disabled={
- disabled ||
- updateSpace.status === "executing" ||
- !form.formState.isDirty
+ disabled || updateSpace.isPending || !form.formState.isDirty
}
>
<Trans i18nKey="save" defaults="Save" />
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/general/page-client.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/general/page-client.tsx
index a0df42a73..f0e4aeb62 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/general/page-client.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/general/page-client.tsx
@@ -96,7 +96,7 @@ export function GeneralSettingsPageClient() {
</PageSectionDescription>
</PageSectionHeader>
<PageSectionContent>
- <DeleteSpaceButton spaceName={space.name} spaceId={space.id} />
+ <DeleteSpaceButton spaceName={space.name} />
</PageSectionContent>
</PageSection>
) : null}
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-dropdown-menu.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-dropdown-menu.tsx
index b3021fd12..55ece8d0e 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-dropdown-menu.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-dropdown-menu.tsx
@@ -21,10 +21,9 @@ import {
import { Icon } from "@rallly/ui/icon";
import { toast } from "@rallly/ui/sonner";
import { MoreHorizontalIcon, XIcon } from "lucide-react";
-import { cancelInviteAction } from "@/features/space/actions";
import { useSpace } from "@/features/space/client";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
type SpaceMemberInvite = {
id: string;
@@ -35,7 +34,7 @@ type SpaceMemberInvite = {
export function InviteDropdownMenu({ invite }: { invite: SpaceMemberInvite }) {
const space = useSpace();
const cancelInviteDialog = useDialog();
- const cancelInvite = useSafeAction(cancelInviteAction);
+ const cancelInvite = trpc.spaces.cancelInvite.useMutation();
const { t } = useTranslation();
const canCancelInvite = space
@@ -84,7 +83,7 @@ export function InviteDropdownMenu({ invite }: { invite: SpaceMemberInvite }) {
variant="destructive"
onClick={() => {
toast.promise(
- cancelInvite.executeAsync({
+ cancelInvite.mutateAsync({
inviteId: invite.id,
}),
{
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-member-dialog.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-member-dialog.tsx
index 4e06581f0..22524c831 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-member-dialog.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/invite-member-dialog.tsx
@@ -33,11 +33,10 @@ import { InfoIcon } from "lucide-react";
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
-import { inviteMemberAction } from "@/features/space/actions";
import { SpaceRole } from "@/features/space/components/space-role";
import { memberRoleSchema } from "@/features/space/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
function useInviteMemberFormSchema() {
const { t } = useTranslation();
@@ -66,10 +65,9 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {
resolver: zodResolver(formSchema),
});
- const inviteMember = useSafeAction(inviteMemberAction, {
- onSuccess: (result) => {
- const data = result.data;
- if (data.success) {
+ const inviteMember = trpc.spaces.inviteMember.useMutation({
+ onSuccess: (data) => {
+ if (data.ok) {
switch (data.code) {
case "INVITE_SENT":
toast.success(
@@ -122,7 +120,7 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {
});
return (
<Form {...form}>
- <form onSubmit={form.handleSubmit((data) => inviteMember.execute(data))}>
+ <form onSubmit={form.handleSubmit((data) => inviteMember.mutate(data))}>
<fieldset className="space-y-4">
<FormField
control={form.control}
@@ -212,7 +210,7 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {
<div className="mt-4 flex">
<Button
variant="primary"
- loading={inviteMember.isExecuting}
+ loading={inviteMember.isPending}
type="submit"
>
<Trans i18nKey="inviteMember" defaults="Send invite" />
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/member-dropdown-menu.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/member-dropdown-menu.tsx
index a03e95a4a..d24baf78c 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/member-dropdown-menu.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/members/components/member-dropdown-menu.tsx
@@ -22,21 +22,17 @@ import {
import { Icon } from "@rallly/ui/icon";
import { toast } from "@rallly/ui/sonner";
import { MoreHorizontalIcon, ShieldIcon, UserIcon, XIcon } from "lucide-react";
-import {
- changeMemberRoleAction,
- removeMemberAction,
-} from "@/features/space/actions";
import { useSpace } from "@/features/space/client";
import type { MemberDTO } from "@/features/space/member/types";
import type { MemberRole } from "@/features/space/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
export function MemberDropdownMenu({ member }: { member: MemberDTO }) {
const space = useSpace();
const removeMemberDialog = useDialog();
- const removeMember = useSafeAction(removeMemberAction);
- const changeMemberRole = useSafeAction(changeMemberRoleAction);
+ const removeMember = trpc.spaces.removeMember.useMutation();
+ const changeMemberRole = trpc.spaces.changeMemberRole.useMutation();
const { t } = useTranslation();
const canUpdateMember = space
@@ -49,7 +45,7 @@ export function MemberDropdownMenu({ member }: { member: MemberDTO }) {
const handleRoleChange = (newRole: MemberRole) => {
toast.promise(
- changeMemberRole.executeAsync({
+ changeMemberRole.mutateAsync({
memberId: member.id,
role: newRole,
}),
@@ -130,7 +126,7 @@ export function MemberDropdownMenu({ member }: { member: MemberDTO }) {
variant="destructive"
onClick={() => {
toast.promise(
- removeMember.executeAsync({
+ removeMember.mutateAsync({
memberId: member.id,
}),
{
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/profile-picture.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/profile/profile-picture.tsx
index ddcfeac01..06b39cb86 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/profile/profile-picture.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/profile/profile-picture.tsx
@@ -21,6 +21,7 @@ function ProfilePictureUpload({
const router = useRouter();
const posthog = usePostHog();
+ const getAvatarUploadUrl = trpc.user.getAvatarUploadUrl.useMutation();
const updateAvatar = trpc.user.updateAvatar.useMutation();
const removeAvatar = trpc.user.removeAvatar.useMutation();
@@ -42,7 +43,7 @@ function ProfilePictureUpload({
<OptimizedAvatarImage src={image} name={name} size="xl" />
</ImageUploadPreview>
<ImageUploadControl
- keyPrefix="avatars"
+ getUploadUrl={(input) => getAvatarUploadUrl.mutateAsync(input)}
onUploadSuccess={handleUploadSuccess}
onRemoveSuccess={handleRemoveSuccess}
hasCurrentImage={!!image}
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/spaces/components/spaces-list.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/spaces/components/spaces-list.tsx
index 6a2c5b36b..b5e920003 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/spaces/components/spaces-list.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/spaces/components/spaces-list.tsx
@@ -20,12 +20,11 @@ import {
EmptyStateTitle,
} from "@/components/empty-state";
import { StackedList, StackedListItem } from "@/components/stacked-list";
-import { leaveSpaceFromAccountAction } from "@/features/space/actions";
import { SpaceIcon } from "@/features/space/components/space-icon";
import { SpaceRole } from "@/features/space/components/space-role";
import type { SpaceDTO } from "@/features/space/types";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
import { LeaveSpaceDialog } from "./leave-space-dialog";
interface SpacesListProps {
@@ -38,7 +37,7 @@ export function SpacesList({ spaces, currentUserId }: SpacesListProps) {
const leaveSpaceDialog = useDialog();
const [selectedSpace, setSelectedSpace] = useState<SpaceDTO | null>(null);
- const leaveSpace = useSafeAction(leaveSpaceFromAccountAction, {
+ const leaveSpace = trpc.spaces.leaveFromAccount.useMutation({
onSuccess: () => {
toast.success(
t("leftSpaceSuccess", {
@@ -124,7 +123,7 @@ export function SpacesList({ spaces, currentUserId }: SpacesListProps) {
{...leaveSpaceDialog.dialogProps}
spaceName={selectedSpace.name}
onConfirm={async () => {
- await leaveSpace.executeAsync({ spaceId: selectedSpace.id });
+ await leaveSpace.mutateAsync({ spaceId: selectedSpace.id });
}}
/>
)}
diff --git a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
index cf6133270..e7570bc26 100644
--- a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
+++ b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/accept-invite-button.tsx
@@ -3,14 +3,13 @@
import { Button } from "@rallly/ui/button";
import { toast } from "@rallly/ui/sonner";
import { useRouter } from "next/navigation";
-import { acceptInviteAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
export const AcceptInviteButton = ({ spaceId }: { spaceId: string }) => {
const { t } = useTranslation();
const router = useRouter();
- const acceptInvite = useSafeAction(acceptInviteAction, {
+ const acceptInvite = trpc.spaces.acceptInvite.useMutation({
onSuccess: () => {
toast.success(
t("acceptInviteSuccess", {
@@ -24,9 +23,9 @@ export const AcceptInviteButton = ({ spaceId }: { spaceId: string }) => {
<Button
variant="primary"
onClick={() => {
- acceptInvite.execute({ spaceId });
+ acceptInvite.mutate({ spaceId });
}}
- loading={acceptInvite.isExecuting}
+ loading={acceptInvite.isPending}
>
<Trans i18nKey="acceptInvite" defaults="Accept Invite" />
</Button>
diff --git a/apps/web/src/components/image-upload/image-upload.tsx b/apps/web/src/components/image-upload/image-upload.tsx
index b5ff3ad39..b6488c208 100644
--- a/apps/web/src/components/image-upload/image-upload.tsx
+++ b/apps/web/src/components/image-upload/image-upload.tsx
@@ -17,8 +17,6 @@ import {
createImagePreviewUrl,
validateImageFile,
} from "@/lib/image-processing";
-import { useSafeAction } from "@/lib/safe-action/client";
-import { getImageUploadUrlAction } from "@/lib/storage/actions";
import { uploadImage } from "@/lib/storage/upload-client";
export function ImageUpload({ className, children }: ImageUploadProps) {
@@ -28,7 +26,7 @@ export function ImageUpload({ className, children }: ImageUploadProps) {
}
export function ImageUploadControl({
- keyPrefix,
+ getUploadUrl,
onUploadSuccess,
onRemoveSuccess,
hasCurrentImage = false,
@@ -38,7 +36,6 @@ export function ImageUploadControl({
const { t } = useTranslation();
const [isRemoving, startRemoving] = React.useTransition();
const [isUploading, startUploading] = React.useTransition();
- const getUploadUrl = useSafeAction(getImageUploadUrlAction);
// Cropping state
const [showCropDialog, setShowCropDialog] = React.useState(false);
@@ -112,18 +109,11 @@ export function ImageUploadControl({
startUploading(async () => {
try {
- const result = await getUploadUrl.executeAsync({
- keyPrefix,
+ const { url, fields } = await getUploadUrl({
fileType: parsedFileType,
fileSize: croppedFile.size,
});
- if (!result.data) {
- throw new Error("Failed to get upload URL");
- }
-
- const { url, fields } = result.data;
-
await uploadImage({
file: croppedFile,
url,
diff --git a/apps/web/src/components/image-upload/types.ts b/apps/web/src/components/image-upload/types.ts
index 33916f71c..e6e35dc3f 100644
--- a/apps/web/src/components/image-upload/types.ts
+++ b/apps/web/src/components/image-upload/types.ts
@@ -4,7 +4,10 @@ export const allowedMimeTypes = z.enum(["image/jpeg", "image/png"]);
export type AllowedMimeType = z.infer<typeof allowedMimeTypes>;
export interface ImageUploadControlProps {
- keyPrefix: "avatars" | "spaces";
+ getUploadUrl: (input: {
+ fileType: AllowedMimeType;
+ fileSize: number;
+ }) => Promise<{ url: string; fields: { key: string } }>;
onUploadSuccess: (imageKey: string) => Promise<void> | void;
onRemoveSuccess: () => Promise<void> | void;
hasCurrentImage?: boolean;
diff --git a/apps/web/src/features/setup/components/create-space-form.tsx b/apps/web/src/features/setup/components/create-space-form.tsx
index ecfbfb0fe..25e58e0bc 100644
--- a/apps/web/src/features/setup/components/create-space-form.tsx
+++ b/apps/web/src/features/setup/components/create-space-form.tsx
@@ -14,10 +14,8 @@ import { Input } from "@rallly/ui/input";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import * as z from "zod";
-
-import { createSpaceAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
const createSpaceFormSchema = z.object({
name: z.string().min(1).max(100),
@@ -34,21 +32,17 @@ export function CreateSpaceForm() {
},
});
- const createSpace = useSafeAction(createSpaceAction, {
+ const createSpace = trpc.spaces.create.useMutation({
onSuccess: () => {
- // Redirect to the main dashboard after successful space creation
router.push("/");
},
- onError: (error) => {
- console.error("Failed to create space:", error);
- },
});
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(({ name }) => {
- createSpace.execute({ name });
+ createSpace.mutate({ name });
})}
className="space-y-4"
>
@@ -74,14 +68,10 @@ export function CreateSpaceForm() {
)}
/>
- {createSpace.result?.serverError && (
- <FormMessage>{createSpace.result.serverError}</FormMessage>
- )}
-
<Button
type="submit"
variant="primary"
- loading={createSpace.isExecuting}
+ loading={createSpace.isPending}
className="w-full"
>
<Trans i18nKey="createSpace" defaults="Create Space" />
diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.ts
deleted file mode 100644
index 436fb66f3..000000000
--- a/apps/web/src/features/space/actions.ts
+++ /dev/null
@@ -1,901 +0,0 @@
-"use server";
-
-import { subject } from "@casl/ability";
-import { accessibleBy } from "@casl/prisma";
-import { prisma } from "@rallly/database";
-import { createLogger } from "@rallly/logger";
-import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { waitUntil } from "@vercel/functions";
-import { revalidatePath } from "next/cache";
-import * as z from "zod";
-
-const logger = createLogger("space/actions");
-
-import { getMember, getSpaceSeatCount } from "@/features/space/data";
-import { createSpace } from "@/features/space/mutations";
-import { memberRoleSchema } from "@/features/space/schema";
-import { getTotalSeatsForSpace, toDBRole } from "@/features/space/utils";
-import { setActiveSpace } from "@/features/user/mutations";
-import { AppError } from "@/lib/errors";
-import {
- authActionClient,
- createRateLimitMiddleware,
- posthogMiddleware,
- spaceActionClient,
-} from "@/lib/safe-action/server";
-import {
- deleteImageFromS3,
- getImageUploadUrl,
-} from "@/lib/storage/image-upload";
-import { getEmailClient } from "@/utils/emails";
-
-export const setActiveSpaceAction = authActionClient
- .inputSchema(
- z.object({
- spaceId: z.string(),
- }),
- )
- .metadata({
- actionName: "space_set_active",
- })
- .action(async ({ ctx, parsedInput }) => {
- const space = await prisma.space.findFirst({
- where: {
- AND: [accessibleBy(ctx.ability).Space, { id: parsedInput.spaceId }],
- },
- include: {
- members: {
- where: {
- userId: ctx.user.id,
- },
- },
- },
- });
-
- if (!space) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Space not found",
- });
- }
-
- if (!ctx.ability.can("read", subject("Space", space))) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have access to this space",
- });
- }
-
- await setActiveSpace({
- userId: ctx.user.id,
- spaceId: parsedInput.spaceId,
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_set_active",
- properties: {
- space_id: parsedInput.spaceId,
- space_name: space.name,
- },
- groups: {
- space: parsedInput.spaceId,
- },
- });
- });
-
-export const createSpaceAction = authActionClient
- .metadata({
- actionName: "space_create",
- })
- .use(createRateLimitMiddleware(5, "1h"))
- .use(posthogMiddleware)
- .inputSchema(
- z.object({
- name: z.string().min(1).max(100),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const space = await createSpace({
- name: parsedInput.name,
- ownerId: ctx.user.id,
- });
-
- ctx.posthog?.groupIdentify({
- groupType: "space",
- groupKey: space.id,
- properties: {
- name: space.name,
- memberCount: 1,
- seatCount: 1,
- tier: "hobby",
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_create",
- properties: {
- space_name: space.name,
- },
- groups: {
- space: space.id,
- },
- });
-
- revalidatePath("/", "layout");
-
- return space;
- });
-
-export const deleteSpaceAction = spaceActionClient
- .metadata({
- actionName: "space_delete",
- })
- .inputSchema(
- z.object({
- spaceId: z.string(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const space = await prisma.space.findFirst({
- where: {
- id: parsedInput.spaceId,
- },
- select: {
- id: true,
- ownerId: true,
- tier: true,
- subscriptions: {
- where: {
- active: true,
- },
- select: {
- id: true,
- },
- },
- },
- });
-
- if (!space) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Space not found",
- });
- }
-
- if (ctx.getMemberAbility().cannot("delete", subject("Space", space))) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to delete this space",
- });
- }
-
- // Check if space has an active subscription
- if (space.subscriptions.length > 0) {
- throw new AppError({
- code: "FORBIDDEN",
- message:
- "Cannot delete space with an active subscription. Please cancel the subscription first.",
- });
- }
-
- await prisma.space.delete({
- where: {
- id: parsedInput.spaceId,
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_delete",
- properties: {
- space_id: space.id,
- },
- groups: {
- space: space.id,
- },
- });
-
- revalidatePath("/", "layout");
- });
-
-export const inviteMemberAction = spaceActionClient
- .metadata({
- actionName: "space_invite_member",
- })
- .inputSchema(
- z.object({
- email: z.email(),
- role: memberRoleSchema,
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- if (ctx.getSpaceAbility().cannot("invite", "Member")) {
- throw new AppError({
- code: "PAYMENT_REQUIRED",
- message: "You need a Pro subscription to invite members to this space",
- });
- }
-
- if (ctx.getMemberAbility().cannot("create", "SpaceMemberInvite")) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to invite members to this space",
- });
- }
-
- // Check if user is already a member
- const existingUser = await prisma.user.findUnique({
- where: { email: parsedInput.email },
- include: {
- memberOf: {
- where: { spaceId: ctx.space.id },
- },
- },
- });
-
- if (existingUser?.memberOf && existingUser.memberOf.length > 0) {
- return {
- success: false,
- code: "ALREADY_MEMBER" as const,
- message: "This person is already a member of this space",
- };
- }
-
- // Check if there's already a pending invite
- const existingInvite = await prisma.spaceMemberInvite.findUnique({
- where: {
- spaceId_email: {
- spaceId: ctx.space.id,
- email: parsedInput.email,
- },
- },
- });
-
- if (existingInvite) {
- // Update existing invite if role is different (allow regardless of seats)
- if (existingInvite.role !== toDBRole(parsedInput.role)) {
- await prisma.spaceMemberInvite.update({
- where: { id: existingInvite.id },
- data: { role: toDBRole(parsedInput.role) },
- });
-
- return {
- success: true,
- code: "INVITE_UPDATED" as const,
- message: "Invitation updated with new role",
- };
- }
-
- return {
- success: false,
- code: "INVITE_PENDING" as const,
- message: "An invitation has already been sent to this email address",
- };
- }
-
- // Check seat availability only for new invites
- const [currentSeatCount, totalSeats] = await Promise.all([
- getSpaceSeatCount(ctx.space.id),
- getTotalSeatsForSpace(ctx.space.id),
- ]);
-
- if (currentSeatCount >= totalSeats) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "There are not enough available seats to perform this action",
- });
- }
-
- try {
- const invite = await prisma.spaceMemberInvite.create({
- data: {
- spaceId: ctx.space.id,
- email: parsedInput.email,
- role: toDBRole(parsedInput.role),
- inviterId: ctx.user.id,
- },
- });
-
- const emailClient = await getEmailClient(
- existingUser?.locale ?? ctx.user.locale,
- );
-
- await emailClient.sendTemplate("SpaceInviteEmail", {
- to: parsedInput.email,
- props: {
- spaceName: ctx.space.name,
- inviterName: ctx.user.name,
- spaceRole: parsedInput.role,
- inviteUrl: absoluteUrl(`/accept-invite/${invite.id}`),
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_member_invite",
- properties: {
- role: parsedInput.role,
- },
- groups: {
- space: ctx.space.id,
- },
- });
-
- return {
- success: true,
- code: "INVITE_SENT" as const,
- message: "Invitation sent successfully",
- };
- } catch (error) {
- logger.error({ error }, "Failed to send invitation");
- return {
- success: false,
- code: "INVITE_FAILED" as const,
- message: "Unable to send invitation. Please try again.",
- };
- }
- });
-
-export const acceptInviteAction = authActionClient
- .metadata({
- actionName: "space_accept_invite",
- })
- .inputSchema(
- z.object({
- spaceId: z.string(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const spaceMemberInvite = await prisma.spaceMemberInvite.findUnique({
- where: {
- spaceId_email: {
- spaceId: parsedInput.spaceId,
- email: ctx.user.email,
- },
- },
- });
-
- if (!spaceMemberInvite) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "No pending invite found for this space",
- });
- }
-
- const { memberCount } = await prisma.$transaction(async (tx) => {
- // Check seat availability before accepting the invite
- const [usedSeats, totalSeats] = await Promise.all([
- tx.spaceMember.count({ where: { spaceId: parsedInput.spaceId } }),
- getTotalSeatsForSpace(parsedInput.spaceId),
- ]);
-
- if (usedSeats >= totalSeats) {
- throw new AppError({
- code: "FORBIDDEN",
- message:
- "There are not enough available seats to accept this invitation",
- });
- }
-
- await tx.spaceMember.create({
- data: {
- spaceId: parsedInput.spaceId,
- userId: ctx.user.id,
- role: spaceMemberInvite.role,
- },
- });
-
- await tx.spaceMemberInvite.delete({
- where: {
- id: spaceMemberInvite.id,
- },
- });
-
- return { memberCount: usedSeats + 1 };
- });
-
- try {
- await setActiveSpace({
- userId: ctx.user.id,
- spaceId: parsedInput.spaceId,
- });
- } catch (error) {
- logger.warn({ error }, "Failed to update user's active space");
- }
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_member_join",
- properties: {
- member_count: memberCount,
- },
- groups: {
- space: parsedInput.spaceId,
- },
- });
- });
-
-export const removeMemberAction = spaceActionClient
- .metadata({
- actionName: "space_remove_member",
- })
- .inputSchema(
- z.object({
- memberId: z.string(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const member = await getMember(parsedInput.memberId);
- if (!member) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Member not found",
- });
- }
-
- if (
- ctx.getMemberAbility().cannot("delete", subject("SpaceMember", member))
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to remove members from this space",
- });
- }
-
- const deletedMember = await prisma.spaceMember.delete({
- where: {
- id: parsedInput.memberId,
- },
- });
-
- const memberCount = await prisma.spaceMember.count({
- where: {
- spaceId: member.spaceId,
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_member_remove",
- properties: {
- member_count: memberCount,
- deleted_member_user_id: deletedMember.userId,
- },
- groups: {
- space: member.spaceId,
- },
- });
- });
-
-export const changeMemberRoleAction = spaceActionClient
- .metadata({
- actionName: "space_change_member_role",
- })
- .inputSchema(
- z.object({
- memberId: z.string(),
- role: memberRoleSchema,
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const member = await getMember(parsedInput.memberId);
- if (!member) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Member not found",
- });
- }
-
- if (
- ctx.getMemberAbility().cannot("update", subject("SpaceMember", member))
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message:
- "You do not have permission to change member roles in this space",
- });
- }
-
- await prisma.spaceMember.update({
- where: {
- id: parsedInput.memberId,
- },
- data: {
- role: toDBRole(parsedInput.role),
- },
- });
- });
-
-export const cancelInviteAction = spaceActionClient
- .metadata({
- actionName: "space_cancel_invite",
- })
- .inputSchema(
- z.object({
- inviteId: z.string(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const invite = await prisma.spaceMemberInvite.findUnique({
- where: { id: parsedInput.inviteId },
- });
-
- if (!invite) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Invite not found",
- });
- }
-
- if (invite.spaceId !== ctx.space.id) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have access to this invite",
- });
- }
-
- if (ctx.getMemberAbility().cannot("delete", "SpaceMemberInvite")) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to cancel invites",
- });
- }
-
- await prisma.spaceMemberInvite.delete({
- where: { id: parsedInput.inviteId },
- });
- });
-
-export const updateSpaceAction = spaceActionClient
- .metadata({
- actionName: "space_update",
- })
- .inputSchema(
- z.object({
- name: z.string().min(1).max(100),
- image: z.string().optional(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- if (
- ctx
- .getMemberAbility()
- .cannot(
- "update",
- subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
- )
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- const oldImage = ctx.space.image;
-
- await prisma.space.update({
- where: {
- id: ctx.space.id,
- },
- data: {
- name: parsedInput.name,
- image: parsedInput.image,
- },
- });
-
- // Delete old image from S3 if it exists and we're updating to a new image
- if (oldImage && parsedInput.image && oldImage !== parsedInput.image) {
- await deleteImageFromS3(oldImage);
- }
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_update",
- properties: {
- space_name: parsedInput.name,
- },
- groups: {
- space: ctx.space.id,
- },
- });
- });
-
-export const getSpaceImageUploadUrlAction = spaceActionClient
- .metadata({
- actionName: "space_get_image_upload_url",
- })
- .inputSchema(
- z.object({
- fileType: z.enum(["image/jpeg", "image/png"]),
- fileSize: z.number(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- if (
- ctx
- .getMemberAbility()
- .cannot(
- "update",
- subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
- )
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- return await getImageUploadUrl({
- keyPrefix: "spaces",
- entityId: ctx.space.id,
- fileType: parsedInput.fileType,
- fileSize: parsedInput.fileSize,
- });
- });
-
-export const updateSpaceImageAction = spaceActionClient
- .metadata({
- actionName: "space_update_image",
- })
- .inputSchema(
- z.object({
- imageKey: z.string().max(255),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- if (
- ctx
- .getMemberAbility()
- .cannot(
- "update",
- subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
- )
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- const oldImageKey = ctx.space.image;
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: { image: parsedInput.imageKey },
- });
-
- // Delete old image from S3 if it exists
- if (oldImageKey) {
- waitUntil(deleteImageFromS3(oldImageKey));
- }
- });
-
-export const removeSpaceImageAction = spaceActionClient
- .metadata({
- actionName: "space_remove_image",
- })
- .action(async ({ ctx }) => {
- if (
- ctx
- .getMemberAbility()
- .cannot(
- "update",
- subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
- )
- ) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- const oldImageKey = ctx.space.image;
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: { image: null },
- });
-
- // Delete image from S3 if it exists
- if (oldImageKey) {
- await deleteImageFromS3(oldImageKey);
- }
- });
-
-export const leaveSpaceFromAccountAction = authActionClient
- .metadata({
- actionName: "space_leave_from_account",
- })
- .inputSchema(
- z.object({
- spaceId: z.string(),
- }),
- )
- .action(async ({ ctx, parsedInput }) => {
- const space = await prisma.space.findUnique({
- where: {
- id: parsedInput.spaceId,
- },
- select: {
- id: true,
- ownerId: true,
- },
- });
-
- if (!space) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "Space not found",
- });
- }
-
- // Check if user is the space owner
- if (space.ownerId === ctx.user.id) {
- throw new AppError({
- code: "FORBIDDEN",
- message:
- "Space owners cannot leave their space. Transfer ownership first.",
- });
- }
-
- // Get the user's member record
- const member = await prisma.spaceMember.findFirst({
- where: {
- spaceId: parsedInput.spaceId,
- userId: ctx.user.id,
- },
- });
-
- if (!member) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "You are not a member of this space",
- });
- }
-
- // Check if user has other spaces
- const userSpaces = await prisma.spaceMember.findMany({
- where: {
- userId: ctx.user.id,
- NOT: {
- spaceId: parsedInput.spaceId,
- },
- },
- orderBy: {
- lastSelectedAt: "desc",
- },
- });
-
- if (userSpaces.length === 0) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "Cannot leave your last remaining space",
- });
- }
-
- await prisma.$transaction(async (tx) => {
- // Remove the user from the space
- await tx.spaceMember.delete({
- where: {
- id: member.id,
- },
- });
-
- // Update the most recent remaining space to be current
- // (this handles the case where they're leaving their active space)
- await tx.spaceMember.update({
- where: {
- id: userSpaces[0].id,
- },
- data: {
- lastSelectedAt: new Date(),
- },
- });
- });
-
- const memberCount = await prisma.spaceMember.count({
- where: {
- spaceId: parsedInput.spaceId,
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_member_leave",
- properties: {
- member_count: memberCount,
- },
- groups: {
- space: parsedInput.spaceId,
- },
- });
- });
-
-export const leaveSpaceAction = spaceActionClient
- .metadata({
- actionName: "space_leave",
- })
- .action(async ({ ctx }) => {
- // Check if user is the space owner
- if (ctx.space.ownerId === ctx.user.id) {
- throw new AppError({
- code: "FORBIDDEN",
- message:
- "Space owners cannot leave their space. Transfer ownership first.",
- });
- }
-
- // Get the user's member record
- const member = await prisma.spaceMember.findFirst({
- where: {
- spaceId: ctx.space.id,
- userId: ctx.user.id,
- },
- });
-
- if (!member) {
- throw new AppError({
- code: "NOT_FOUND",
- message: "You are not a member of this space",
- });
- }
-
- // Check if user has other spaces
- const userSpaces = await prisma.spaceMember.findMany({
- where: {
- userId: ctx.user.id,
- NOT: {
- spaceId: ctx.space.id,
- },
- },
- orderBy: {
- lastSelectedAt: "desc",
- },
- });
-
- if (userSpaces.length === 0) {
- throw new AppError({
- code: "FORBIDDEN",
- message: "Cannot leave your last remaining space",
- });
- }
-
- await prisma.$transaction(async (tx) => {
- // Remove the user from the space
- await tx.spaceMember.delete({
- where: {
- id: member.id,
- },
- });
-
- // Update the most recent remaining space to be current
- // (this handles the case where they're leaving their active space)
- await tx.spaceMember.update({
- where: {
- id: userSpaces[0].id,
- },
- data: {
- lastSelectedAt: new Date(),
- },
- });
- });
-
- const memberCount = await prisma.spaceMember.count({
- where: {
- spaceId: ctx.space.id,
- },
- });
-
- ctx.posthog?.capture({
- distinctId: ctx.user.id,
- event: "space_member_leave",
- properties: {
- member_count: memberCount,
- },
- groups: {
- space: ctx.space.id,
- },
- });
- });
diff --git a/apps/web/src/features/space/components/create-space-dialog.tsx b/apps/web/src/features/space/components/create-space-dialog.tsx
index 6a19f22e7..3a9ad1160 100644
--- a/apps/web/src/features/space/components/create-space-dialog.tsx
+++ b/apps/web/src/features/space/components/create-space-dialog.tsx
@@ -22,9 +22,8 @@ import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
import { useForm } from "react-hook-form";
import * as z from "zod";
-import { createSpaceAction } from "@/features/space/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
const createSpaceFormSchema = z.object({
name: z.string().min(1).max(100),
@@ -40,7 +39,7 @@ export function CreateSpaceDialog(props: DialogProps) {
},
});
- const createSpace = useSafeAction(createSpaceAction, {
+ const createSpace = trpc.spaces.create.useMutation({
onSuccess: () => {
form.reset();
},
@@ -65,7 +64,7 @@ export function CreateSpaceDialog(props: DialogProps) {
onSubmit={form.handleSubmit(({ name }) => {
props.onOpenChange?.(false);
toast.promise(
- createSpace.executeAsync({
+ createSpace.mutateAsync({
name,
}),
{
diff --git a/apps/web/src/features/space/components/space-dropdown.tsx b/apps/web/src/features/space/components/space-dropdown.tsx
index 6e54cb6c8..8e64bfc84 100644
--- a/apps/web/src/features/space/components/space-dropdown.tsx
+++ b/apps/web/src/features/space/components/space-dropdown.tsx
@@ -21,39 +21,33 @@ import {
UserPlusIcon,
} from "lucide-react";
import Link from "next/link";
-import React from "react";
-import { RouterLoadingIndicator } from "@/components/router-loading-indicator";
-import { setActiveSpaceAction } from "@/features/space/actions";
-import { useSpace } from "@/features/space/client";
import { SpaceTierLabel } from "@/features/space/components/space-tier";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
import { trpc } from "@/trpc/client";
import { CreateSpaceDialog } from "./create-space-dialog";
import { SpaceIcon } from "./space-icon";
export function SpaceDropdown() {
const { data: spaces = [] } = trpc.spaces.list.useQuery();
- const { data: space } = useSpace();
- const [selectedSpaceId, setSelectedSpaceId] = React.useState(space.id);
- const [isPending, startTransition] = React.useTransition();
+ const { data: activeSpace } = trpc.spaces.getCurrent.useQuery();
- const setActiveSpace = useSafeAction(setActiveSpaceAction);
+ const setActiveSpace = trpc.spaces.setActive.useMutation();
const newSpaceDialog = useDialog();
- const activeSpace = spaces.find((space) => space.id === selectedSpaceId);
if (!activeSpace) {
+ // This should never happen
return null;
}
+ const selectedSpaceId = activeSpace?.id;
+
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
<Button
className={cn("flex h-auto w-full gap-2.5 p-2", {
- "pointer-events-none animate-pulse":
- setActiveSpace.isPending || isPending,
+ "pointer-events-none animate-pulse": setActiveSpace.isPending,
})}
variant="ghost"
>
@@ -82,10 +76,7 @@ export function SpaceDropdown() {
value={selectedSpaceId}
onValueChange={(value) => {
if (value === selectedSpaceId) return;
- setSelectedSpaceId(value);
- startTransition(() => {
- setActiveSpace.execute({ spaceId: value });
- });
+ setActiveSpace.mutate({ spaceId: value });
}}
>
{spaces.map((space) => (
@@ -124,7 +115,6 @@ export function SpaceDropdown() {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- {isPending ? <RouterLoadingIndicator /> : null}
<CreateSpaceDialog {...newSpaceDialog.dialogProps} />
</>
);
diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.ts
index cb5e67208..536bcd381 100644
--- a/apps/web/src/features/space/data.ts
+++ b/apps/web/src/features/space/data.ts
@@ -50,7 +50,7 @@ export function createSpaceDTO(space: {
role: DBSpaceMemberRole;
image?: string | null;
tier: DBSpaceTier;
-}) {
+}): SpaceDTO {
return {
id: space.id,
name: space.name,
@@ -58,7 +58,7 @@ export function createSpaceDTO(space: {
tier: isSelfHosted ? "pro" : space.tier,
role: fromDBRole(space.role),
image: space.image ?? undefined,
- } satisfies SpaceDTO;
+ };
}
export const getMember = async (id: string) => {
diff --git a/apps/web/src/features/space/mutations.ts b/apps/web/src/features/space/mutations.ts
index 2b2cbb986..1aef2d6c0 100644
--- a/apps/web/src/features/space/mutations.ts
+++ b/apps/web/src/features/space/mutations.ts
@@ -1,5 +1,6 @@
import type { SpaceTier } from "@rallly/database";
import { prisma } from "@rallly/database";
+import { createSpaceDTO } from "@/features/space/data";
import { isSelfHosted } from "@/utils/constants";
export async function createSpace({
@@ -26,5 +27,5 @@ export async function createSpace({
},
});
- return space;
+ return createSpaceDTO({ ...space, role: "ADMIN" });
}
diff --git a/apps/web/src/lib/storage/actions.ts b/apps/web/src/lib/storage/actions.ts
deleted file mode 100644
index a4ddb001d..000000000
--- a/apps/web/src/lib/storage/actions.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-"use server";
-
-import * as z from "zod";
-import { AppError } from "@/lib/errors";
-import { authActionClient } from "@/lib/safe-action/server";
-import { isStorageEnabled } from "@/lib/storage/constants";
-import { getImageUploadUrl } from "./image-upload";
-
-export const getImageUploadUrlAction = authActionClient
- .metadata({
- actionName: "get_image_upload_url",
- })
- .inputSchema(
- z.object({
- keyPrefix: z.enum(["avatars", "spaces"]),
- fileType: z.enum(["image/jpeg", "image/png"]),
- fileSize: z.number(),
- }),
- )
- .use(async ({ next }) => {
- if (!isStorageEnabled) {
- throw new AppError({
- code: "SERVICE_UNAVAILABLE",
- message:
- "This feature requires an object store to be configured on this instance.",
- });
- }
- return next();
- })
- .action(async ({ ctx, parsedInput }) => {
- return await getImageUploadUrl({
- keyPrefix: parsedInput.keyPrefix,
- entityId: ctx.user.id,
- fileType: parsedInput.fileType,
- fileSize: parsedInput.fileSize,
- });
- });
diff --git a/apps/web/src/lib/storage/image-upload.ts b/apps/web/src/lib/storage/image-upload.ts
index a8c8b4eb7..3502e638a 100644
--- a/apps/web/src/lib/storage/image-upload.ts
+++ b/apps/web/src/lib/storage/image-upload.ts
@@ -63,7 +63,7 @@ export async function getImageUploadUrl({
export async function deleteImageFromS3(imageKey: string) {
const s3Client = getS3Client();
- s3Client?.send(
+ await s3Client?.send(
new DeleteObjectCommand({
Bucket: env.S3_BUCKET_NAME,
Key: imageKey,
diff --git a/apps/web/src/lib/storage/index.ts b/apps/web/src/lib/storage/index.ts
index bffb59158..b04bfcf75 100644
--- a/apps/web/src/lib/storage/index.ts
+++ b/apps/web/src/lib/storage/index.ts
@@ -1,2 +1 @@
-export * from "./actions";
export * from "./constants";
diff --git a/apps/web/src/trpc/client/provider.tsx b/apps/web/src/trpc/client/provider.tsx
index 92fc58166..2453446f0 100644
--- a/apps/web/src/trpc/client/provider.tsx
+++ b/apps/web/src/trpc/client/provider.tsx
@@ -1,5 +1,4 @@
"use client";
-import { usePostHog } from "@rallly/posthog/client";
import { toast } from "@rallly/ui/sonner";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import {
@@ -12,7 +11,7 @@ import { httpBatchLink, TRPCClientError } from "@trpc/client";
import { useState } from "react";
import superjson from "superjson";
import { useTranslation } from "@/i18n/client";
-import { signOut } from "@/lib/auth-client";
+import { authClient } from "@/lib/auth-client";
import { trpc } from "../client";
import type { AppRouter } from "../routers";
@@ -21,64 +20,84 @@ function isTRPCClientError(error: Error): error is TRPCClientError<AppRouter> {
}
export function TRPCProvider(props: { children: React.ReactNode }) {
- const posthog = usePostHog();
const { t } = useTranslation();
- const [queryClient] = useState(
- () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- staleTime: 1000 * 60,
- },
+ const [queryClient] = useState(() => {
+ function handleError(error: Error) {
+ if (!isTRPCClientError(error)) {
+ return;
+ }
+
+ switch (error.data?.code) {
+ case "UNAUTHORIZED":
+ authClient.signOut().finally(() => {
+ window.location.href = "/login";
+ });
+ break;
+ case "FORBIDDEN":
+ toast.error(
+ t("actionErrorForbidden", {
+ defaultValue: "You are not allowed to perform this action",
+ }),
+ );
+ break;
+ case "NOT_FOUND":
+ toast.error(
+ t("actionErrorNotFound", {
+ defaultValue: "The resource was not found",
+ }),
+ );
+ break;
+ case "TOO_MANY_REQUESTS":
+ toast.error(
+ t("actionErrorTooManyRequests", {
+ defaultValue: "You are making too many requests",
+ }),
+ );
+ break;
+ case "PAYLOAD_TOO_LARGE":
+ toast.error(
+ t("actionErrorPayloadTooLarge", {
+ defaultValue:
+ "The file you uploaded is too large. Please try a smaller file.",
+ }),
+ );
+ break;
+ case "PAYMENT_REQUIRED":
+ toast.error(
+ t("actionErrorPaymentRequired", {
+ defaultValue: "You need to upgrade to perform this action",
+ }),
+ );
+ break;
+ case "SERVICE_UNAVAILABLE":
+ toast.error(
+ t("actionErrorServiceUnavailable", {
+ defaultValue:
+ "The service required to perform this action is not available",
+ }),
+ );
+ break;
+ default:
+ toast.error(
+ t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ }),
+ );
+ break;
+ }
+ }
+
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ staleTime: 1000 * 60,
},
- queryCache: new QueryCache({
- onError(error) {
- if (isTRPCClientError(error)) {
- if (error.data?.code === "UNAUTHORIZED") {
- window.location.href = "/login";
- }
- }
- },
- }),
- mutationCache: new MutationCache({
- onError(error) {
- if (isTRPCClientError(error)) {
- posthog.capture("failed api request", {
- path: error.data?.path,
- code: error.data?.code,
- message: error.message,
- });
- switch (error.data?.code) {
- case "UNAUTHORIZED":
- window.location.href = "/login";
- break;
- case "TOO_MANY_REQUESTS":
- toast.error(
- t("tooManyRequests", {
- defaultValue: "Too many requests",
- }),
- {
- description: t("tooManyRequestsDescription", {
- defaultValue: "Please try again later.",
- }),
- },
- );
- break;
- case "FORBIDDEN":
- signOut().then(() => {
- posthog?.reset();
- });
- break;
- default:
- console.error(error);
- break;
- }
- }
- },
- }),
- }),
- );
+ },
+ queryCache: new QueryCache({ onError: handleError }),
+ mutationCache: new MutationCache({ onError: handleError }),
+ });
+ });
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
diff --git a/apps/web/src/trpc/routers/spaces.ts b/apps/web/src/trpc/routers/spaces.ts
index 3dfe78178..ca2232e65 100644
--- a/apps/web/src/trpc/routers/spaces.ts
+++ b/apps/web/src/trpc/routers/spaces.ts
@@ -1,10 +1,42 @@
+import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
-import { createSpaceDTO, getSpaceSeatCount } from "@/features/space/data";
+import { createLogger } from "@rallly/logger";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { TRPCError } from "@trpc/server";
+import { waitUntil } from "@vercel/functions";
+import * as z from "zod";
+import { defineAbilityForSpace } from "@/features/space/ability";
+import {
+ createSpaceDTO,
+ getMember,
+ getSpaceSeatCount,
+} from "@/features/space/data";
+import { defineAbilityForMember } from "@/features/space/member/ability";
+import { createSpace } from "@/features/space/mutations";
+import { memberRoleSchema } from "@/features/space/schema";
import type { SpaceDTO } from "@/features/space/types";
-import { fromDBRole, getTotalSeatsForSpace } from "@/features/space/utils";
-import { privateProcedure, router, spaceProcedure } from "../trpc";
+import {
+ fromDBRole,
+ getTotalSeatsForSpace,
+ toDBRole,
+} from "@/features/space/utils";
+import { setActiveSpace } from "@/features/user/mutations";
+import {
+ deleteImageFromS3,
+ getImageUploadUrl,
+} from "@/lib/storage/image-upload";
+import { getEmailClient } from "@/utils/emails";
+import {
+ createRateLimitMiddleware,
+ privateProcedure,
+ router,
+ spaceProcedure,
+} from "../trpc";
+
+const logger = createLogger("spaces/router");
export const spaces = router({
+ // ── Queries ──────────────────────────────────────────────────────────
list: privateProcedure.query(async ({ ctx }) => {
const { user } = ctx;
@@ -116,4 +148,698 @@ export const spaces = router({
return { total, used };
}),
+
+ // ── Mutations ────────────────────────────────────────────────────────
+ setActive: privateProcedure
+ .input(z.object({ spaceId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const member = await prisma.spaceMember.findUnique({
+ where: {
+ spaceId_userId: {
+ spaceId: input.spaceId,
+ userId: ctx.user.id,
+ },
+ },
+ });
+
+ if (!member) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ }
+
+ await setActiveSpace({
+ userId: ctx.user.id,
+ spaceId: input.spaceId,
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_set_active",
+ properties: {
+ space_id: input.spaceId,
+ },
+ groups: {
+ space: input.spaceId,
+ },
+ });
+ }),
+
+ create: privateProcedure
+ .use(createRateLimitMiddleware("space_create", 5, "1 m"))
+ .input(z.object({ name: z.string().min(1).max(100) }))
+ .mutation(async ({ ctx, input }) => {
+ const space = await createSpace({
+ name: input.name,
+ ownerId: ctx.user.id,
+ });
+
+ ctx.posthog?.groupIdentify({
+ groupType: "space",
+ groupKey: space.id,
+ properties: {
+ name: space.name,
+ memberCount: 1,
+ seatCount: 1,
+ tier: "hobby",
+ },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_create",
+ properties: {
+ space_name: space.name,
+ },
+ groups: {
+ space: space.id,
+ },
+ });
+
+ return space;
+ }),
+
+ delete: spaceProcedure.mutation(async ({ ctx }) => {
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("delete", subject("Space", ctx.space))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to delete this space",
+ });
+ }
+
+ const activeSubscriptionCount = await prisma.subscription.count({
+ where: { spaceId: ctx.space.id, active: true },
+ });
+
+ if (activeSubscriptionCount > 0) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "Cannot delete space with an active subscription. Please cancel the subscription first.",
+ });
+ }
+
+ await prisma.space.delete({
+ where: { id: ctx.space.id },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_delete",
+ properties: {
+ space_id: ctx.space.id,
+ },
+ groups: {
+ space: ctx.space.id,
+ },
+ });
+ }),
+
+ update: spaceProcedure
+ .input(z.object({ name: z.string().min(1).max(100) }))
+ .mutation(async ({ ctx, input }) => {
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("update", subject("Space", ctx.space))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ await prisma.space.update({
+ where: { id: ctx.space.id },
+ data: { name: input.name },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_update",
+ properties: {
+ space_name: input.name,
+ },
+ groups: {
+ space: ctx.space.id,
+ },
+ });
+ }),
+
+ inviteMember: spaceProcedure
+ .input(z.object({ email: z.email(), role: memberRoleSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const spaceAbility = defineAbilityForSpace(ctx.space);
+
+ if (spaceAbility.cannot("invite", "Member")) {
+ throw new TRPCError({
+ code: "PAYMENT_REQUIRED",
+ message:
+ "You need a Pro subscription to invite members to this space",
+ });
+ }
+
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("create", "SpaceMemberInvite")) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to invite members to this space",
+ });
+ }
+
+ // Check if user is already a member
+ const existingUser = await prisma.user.findUnique({
+ where: { email: input.email },
+ include: {
+ memberOf: {
+ where: { spaceId: ctx.space.id },
+ },
+ },
+ });
+
+ if (existingUser?.memberOf && existingUser.memberOf.length > 0) {
+ return {
+ ok: false as const,
+ code: "ALREADY_MEMBER" as const,
+ };
+ }
+
+ // Check if there's already a pending invite
+ const existingInvite = await prisma.spaceMemberInvite.findUnique({
+ where: {
+ spaceId_email: {
+ spaceId: ctx.space.id,
+ email: input.email,
+ },
+ },
+ });
+
+ if (existingInvite) {
+ if (existingInvite.role !== toDBRole(input.role)) {
+ await prisma.spaceMemberInvite.update({
+ where: { id: existingInvite.id },
+ data: { role: toDBRole(input.role) },
+ });
+
+ return {
+ ok: true as const,
+ code: "INVITE_UPDATED" as const,
+ };
+ }
+
+ return {
+ ok: false as const,
+ code: "INVITE_PENDING" as const,
+ };
+ }
+
+ // Check seat availability only for new invites
+ const [currentSeatCount, totalSeats] = await Promise.all([
+ getSpaceSeatCount(ctx.space.id),
+ getTotalSeatsForSpace(ctx.space.id),
+ ]);
+
+ if (currentSeatCount >= totalSeats) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "There are not enough available seats to perform this action",
+ });
+ }
+
+ const invite = await prisma.spaceMemberInvite.create({
+ data: {
+ spaceId: ctx.space.id,
+ email: input.email,
+ role: toDBRole(input.role),
+ inviterId: ctx.user.id,
+ },
+ });
+
+ const emailClient = await getEmailClient(
+ existingUser?.locale ?? ctx.user.locale,
+ );
+
+ try {
+ await emailClient.sendTemplate("SpaceInviteEmail", {
+ to: input.email,
+ props: {
+ spaceName: ctx.space.name,
+ inviterName: ctx.user.name,
+ spaceRole: input.role,
+ inviteUrl: absoluteUrl(`/accept-invite/${invite.id}`),
+ },
+ });
+ } catch {
+ // cleanup invite
+ if (invite) {
+ await prisma.spaceMemberInvite.delete({ where: { id: invite.id } });
+ }
+ return {
+ ok: false as const,
+ code: "INVITE_FAILED" as const,
+ };
+ }
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_member_invite",
+ properties: {
+ role: input.role,
+ },
+ groups: {
+ space: ctx.space.id,
+ },
+ });
+
+ return {
+ ok: true as const,
+ code: "INVITE_SENT" as const,
+ };
+ }),
+
+ acceptInvite: privateProcedure
+ .input(z.object({ spaceId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const spaceMemberInvite = await prisma.spaceMemberInvite.findUnique({
+ where: {
+ spaceId_email: {
+ spaceId: input.spaceId,
+ email: ctx.user.email,
+ },
+ },
+ });
+
+ if (!spaceMemberInvite) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "No pending invite found for this space",
+ });
+ }
+
+ const { memberCount } = await prisma.$transaction(async (tx) => {
+ const [usedSeats, totalSeats] = await Promise.all([
+ tx.spaceMember.count({ where: { spaceId: input.spaceId } }),
+ getTotalSeatsForSpace(input.spaceId),
+ ]);
+
+ if (usedSeats >= totalSeats) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "There are not enough available seats to accept this invitation",
+ });
+ }
+
+ await tx.spaceMember.create({
+ data: {
+ spaceId: input.spaceId,
+ userId: ctx.user.id,
+ role: spaceMemberInvite.role,
+ },
+ });
+
+ await tx.spaceMemberInvite.delete({
+ where: { id: spaceMemberInvite.id },
+ });
+
+ return { memberCount: usedSeats + 1 };
+ });
+
+ try {
+ await setActiveSpace({
+ userId: ctx.user.id,
+ spaceId: input.spaceId,
+ });
+ } catch (error) {
+ logger.warn({ error }, "Failed to update user's active space");
+ }
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_member_join",
+ properties: {
+ member_count: memberCount,
+ },
+ groups: {
+ space: input.spaceId,
+ },
+ });
+ }),
+
+ removeMember: spaceProcedure
+ .input(z.object({ memberId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const member = await getMember(input.memberId);
+ if (!member) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Member not found",
+ });
+ }
+
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("delete", subject("SpaceMember", member))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "You do not have permission to remove members from this space",
+ });
+ }
+
+ const deletedMember = await prisma.spaceMember.delete({
+ where: { id: input.memberId },
+ });
+
+ const memberCount = await prisma.spaceMember.count({
+ where: { spaceId: member.spaceId },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_member_remove",
+ properties: {
+ member_count: memberCount,
+ deleted_member_user_id: deletedMember.userId,
+ },
+ groups: {
+ space: member.spaceId,
+ },
+ });
+ }),
+
+ changeMemberRole: spaceProcedure
+ .input(z.object({ memberId: z.string(), role: memberRoleSchema }))
+ .mutation(async ({ ctx, input }) => {
+ const member = await getMember(input.memberId);
+ if (!member) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Member not found",
+ });
+ }
+
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("update", subject("SpaceMember", member))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "You do not have permission to change member roles in this space",
+ });
+ }
+
+ await prisma.spaceMember.update({
+ where: { id: input.memberId },
+ data: { role: toDBRole(input.role) },
+ });
+ }),
+
+ cancelInvite: spaceProcedure
+ .input(z.object({ inviteId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const invite = await prisma.spaceMemberInvite.findUnique({
+ where: { id: input.inviteId },
+ });
+
+ if (!invite) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Invite not found",
+ });
+ }
+
+ if (invite.spaceId !== ctx.space.id) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have access to this invite",
+ });
+ }
+
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("delete", "SpaceMemberInvite")) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to cancel invites",
+ });
+ }
+
+ await prisma.spaceMemberInvite.delete({
+ where: { id: input.inviteId },
+ });
+ }),
+
+ leave: spaceProcedure.mutation(async ({ ctx }) => {
+ if (ctx.space.ownerId === ctx.user.id) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "Space owners cannot leave their space. Transfer ownership first.",
+ });
+ }
+
+ const member = await prisma.spaceMember.findFirst({
+ where: {
+ spaceId: ctx.space.id,
+ userId: ctx.user.id,
+ },
+ });
+
+ if (!member) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "You are not a member of this space",
+ });
+ }
+
+ const userSpaces = await prisma.spaceMember.findMany({
+ where: {
+ userId: ctx.user.id,
+ NOT: { spaceId: ctx.space.id },
+ },
+ orderBy: { lastSelectedAt: "desc" },
+ });
+
+ if (userSpaces.length === 0) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Cannot leave your last remaining space",
+ });
+ }
+
+ await prisma.$transaction(async (tx) => {
+ await tx.spaceMember.delete({
+ where: { id: member.id },
+ });
+
+ await tx.spaceMember.update({
+ where: { id: userSpaces[0].id },
+ data: { lastSelectedAt: new Date() },
+ });
+ });
+
+ const memberCount = await prisma.spaceMember.count({
+ where: { spaceId: ctx.space.id },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_member_leave",
+ properties: {
+ member_count: memberCount,
+ },
+ groups: {
+ space: ctx.space.id,
+ },
+ });
+ }),
+
+ leaveFromAccount: privateProcedure
+ .input(z.object({ spaceId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const space = await prisma.space.findUnique({
+ where: { id: input.spaceId },
+ select: { id: true, ownerId: true },
+ });
+
+ if (!space) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ }
+
+ if (space.ownerId === ctx.user.id) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message:
+ "Space owners cannot leave their space. Transfer ownership first.",
+ });
+ }
+
+ const member = await prisma.spaceMember.findFirst({
+ where: {
+ spaceId: input.spaceId,
+ userId: ctx.user.id,
+ },
+ });
+
+ if (!member) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "You are not a member of this space",
+ });
+ }
+
+ const userSpaces = await prisma.spaceMember.findMany({
+ where: {
+ userId: ctx.user.id,
+ NOT: { spaceId: input.spaceId },
+ },
+ orderBy: { lastSelectedAt: "desc" },
+ });
+
+ if (userSpaces.length === 0) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Cannot leave your last remaining space",
+ });
+ }
+
+ await prisma.$transaction(async (tx) => {
+ await tx.spaceMember.delete({
+ where: { id: member.id },
+ });
+
+ await tx.spaceMember.update({
+ where: { id: userSpaces[0].id },
+ data: { lastSelectedAt: new Date() },
+ });
+ });
+
+ const memberCount = await prisma.spaceMember.count({
+ where: { spaceId: input.spaceId },
+ });
+
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "space_member_leave",
+ properties: {
+ member_count: memberCount,
+ },
+ groups: {
+ space: input.spaceId,
+ },
+ });
+ }),
+
+ getImageUploadUrl: spaceProcedure
+ .input(
+ z.object({
+ fileType: z.enum(["image/jpeg", "image/png"]),
+ fileSize: z.number(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("update", subject("Space", ctx.space))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ return await getImageUploadUrl({
+ keyPrefix: "spaces",
+ entityId: ctx.space.id,
+ fileType: input.fileType,
+ fileSize: input.fileSize,
+ });
+ }),
+
+ updateImage: spaceProcedure
+ .input(z.object({ imageKey: z.string().max(255) }))
+ .mutation(async ({ ctx, input }) => {
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("update", subject("Space", ctx.space))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ const expectedPrefix = `spaces/${ctx.space.id}-`;
+ if (!input.imageKey.startsWith(expectedPrefix)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid image key",
+ });
+ }
+
+ const oldImageKey = ctx.space.image;
+
+ await prisma.space.update({
+ where: { id: ctx.space.id },
+ data: { image: input.imageKey },
+ });
+
+ if (oldImageKey) {
+ waitUntil(deleteImageFromS3(oldImageKey));
+ }
+ }),
+
+ removeImage: spaceProcedure.mutation(async ({ ctx }) => {
+ const memberAbility = defineAbilityForMember({
+ user: ctx.user,
+ space: ctx.space,
+ });
+
+ if (memberAbility.cannot("update", subject("Space", ctx.space))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ const oldImageKey = ctx.space.image;
+
+ await prisma.space.update({
+ where: { id: ctx.space.id },
+ data: { image: null },
+ });
+
+ if (oldImageKey) {
+ await deleteImageFromS3(oldImageKey);
+ }
+ }),
});
diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.ts
index 5f370db7f..63fb33bde 100644
--- a/apps/web/src/trpc/routers/user.ts
+++ b/apps/web/src/trpc/routers/user.ts
@@ -151,6 +151,15 @@ export const user = router({
.input(z.object({ imageKey: z.string().max(255) }))
.mutation(async ({ ctx, input }) => {
const userId = ctx.user.id;
+
+ const expectedPrefix = `avatars/${userId}-`;
+ if (!input.imageKey.startsWith(expectedPrefix)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid image key",
+ });
+ }
+
const oldImageKey = ctx.user.image;
await prisma.user.update({