Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add PATCH endpoint for updating user roles in partner profile and refactor modal for role updates

Kiran K71a789d7ce71
diff --git a/apps/web/app/(ee)/api/partner-profile/users/route.ts b/apps/web/app/(ee)/api/partner-profile/users/route.ts
index c8e3655fa7..841e5a322c 100644
--- a/apps/web/app/(ee)/api/partner-profile/users/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/users/route.ts
@@ -1,4 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
import { withPartnerProfile } from "@/lib/auth/partner";
import { getPartnerUsersQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { prisma } from "@dub/prisma";
@@ -17,6 +18,11 @@ const partnerUserSchema = z.array(
}),
);
+const updateRoleSchema = z.object({
+ userId: z.string(),
+ role: z.nativeEnum(PartnerRole),
+});
+
const removeUserSchema = z.object({
userId: z.string(),
});
@@ -82,6 +88,84 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
return NextResponse.json(response);
});
+// PATCH /api/partner-profile/users - update a user's role
+export const PATCH = withPartnerProfile(async ({ req, partner, session }) => {
+ const { userId, role } = updateRoleSchema.parse(await parseRequestBody(req));
+
+ if (userId === session.user.id) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You cannot change your own role.",
+ });
+ }
+
+ const [currentUser, partnerUser, totalOwners] = await Promise.all([
+ prisma.partnerUser.findUniqueOrThrow({
+ where: {
+ userId_partnerId: {
+ userId: session.user.id,
+ partnerId: partner.id,
+ },
+ },
+ select: {
+ role: true,
+ },
+ }),
+
+ prisma.partnerUser.findUnique({
+ where: {
+ userId_partnerId: {
+ userId,
+ partnerId: partner.id,
+ },
+ },
+ }),
+
+ prisma.partnerUser.count({
+ where: {
+ partnerId: partner.id,
+ role: "owner",
+ },
+ }),
+ ]);
+
+ if (currentUser.role !== "owner") {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Only owners can change member roles.",
+ });
+ }
+
+ if (!partnerUser) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "The user you're trying to update was not found.",
+ });
+ }
+
+ if (totalOwners === 1 && partnerUser.role === "owner" && role !== "owner") {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Cannot change the role of the last owner. Please assign another owner first.",
+ });
+ }
+
+ const response = await prisma.partnerUser.update({
+ where: {
+ userId_partnerId: {
+ userId,
+ partnerId: partner.id,
+ },
+ },
+ data: {
+ role,
+ },
+ });
+
+ return NextResponse.json(response);
+});
+
// DELETE /api/partner-profile/users?email={email} - remove an invite
export const DELETE = withPartnerProfile(
async ({ searchParams, partner, session }) => {
@@ -112,14 +196,11 @@ export const DELETE = withPartnerProfile(
});
}
- if (
- (totalOwners === 1 && partnerUser.role === "owner",
- userId === session.user.id)
- ) {
+ if (totalOwners === 1 && partnerUser.role === "owner") {
throw new DubApiError({
code: "bad_request",
message:
- "Cannot remove owner from partner profile. Please transfer ownership to another user first.",
+ "Cannot remove the last owner from partner profile. Please assign another owner first.",
});
}
diff --git a/apps/web/ui/modals/edit-partner-user-modal.tsx b/apps/web/ui/modals/edit-partner-user-modal.tsx
deleted file mode 100644
index 88b169629f..0000000000
--- a/apps/web/ui/modals/edit-partner-user-modal.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { mutatePrefix } from "@/lib/swr/mutate";
-import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import { PartnerUserProps } from "@/lib/swr/use-partner-profile-users";
-import { PartnerRole } from "@dub/prisma/client";
-import { Avatar, BlurImage, Button, Logo, Modal } from "@dub/ui";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useMemo,
- useState,
-} from "react";
-import { toast } from "sonner";
-
-function UpdatePartnerUserModal({
- showUpdateUserModal,
- setShowUpdateUserModal,
- user,
- role,
-}: {
- showUpdateUserModal: boolean;
- setShowUpdateUserModal: Dispatch<SetStateAction<boolean>>;
- user: PartnerUserProps;
- role: PartnerRole;
-}) {
- const [updating, setUpdating] = useState(false);
- const { partner } = usePartnerProfile();
- const { id: userId, name, email } = user;
-
- const updateRole = async () => {
- setUpdating(true);
-
- try {
- const response = await fetch("/api/partner-profile/users", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- userId,
- role,
- }),
- });
-
- if (!response.ok) {
- const { error } = await response.json();
- throw new Error(error.message);
- }
-
- await mutatePrefix("/api/partner-profile/users");
- setShowUpdateUserModal(false);
- toast.success(`Successfully updated the role to ${role}.`);
- } catch (error) {
- toast.error(error.message || "Failed to update role");
- } finally {
- setUpdating(false);
- }
- };
-
- return (
- <Modal
- showModal={showUpdateUserModal}
- setShowModal={setShowUpdateUserModal}
- >
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 sm:px-16">
- {partner?.image ? (
- <BlurImage
- src={partner.image}
- alt="Partner logo"
- className="h-10 w-10 rounded-full"
- width={20}
- height={20}
- />
- ) : (
- <Logo />
- )}
- <h3 className="text-lg font-medium">Change Partner Role</h3>
- <p className="text-center text-sm text-neutral-500">
- This will change <b className="text-neutral-800">{name || email}</b>'s
- role in <b className="text-neutral-800">{partner?.name}</b> to{" "}
- <b className="text-neutral-800">{role}</b>. Are you sure you want to
- continue?
- </p>
- </div>
-
- <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-8 text-left sm:px-16">
- <div className="flex items-center space-x-3 rounded-md border border-neutral-300 bg-white p-3">
- <Avatar user={user} />
- <div className="flex flex-col">
- <h3 className="text-sm font-medium">{name || email}</h3>
- <p className="text-xs text-neutral-500">{email}</p>
- </div>
- </div>
- <Button text="Confirm" loading={updating} onClick={updateRole} />
- </div>
- </Modal>
- );
-}
-
-export function useUpdatePartnerUserModal({
- user,
- role,
-}: {
- user: PartnerUserProps;
- role: PartnerRole;
-}) {
- const [showUpdateUserModal, setShowUpdateUserModal] = useState(false);
-
- const UpdateUserModalCallback = useCallback(() => {
- return (
- <UpdatePartnerUserModal
- showUpdateUserModal={showUpdateUserModal}
- setShowUpdateUserModal={setShowUpdateUserModal}
- user={user}
- role={role}
- />
- );
- }, [showUpdateUserModal, setShowUpdateUserModal, user, role]);
-
- return useMemo(
- () => ({
- setShowUpdateUserModal,
- UpdateUserModal: UpdateUserModalCallback,
- }),
- [setShowUpdateUserModal, UpdateUserModalCallback],
- );
-}
diff --git a/apps/web/ui/modals/update-partner-user-modal.tsx b/apps/web/ui/modals/update-partner-user-modal.tsx
index 2085189abe..68921010de 100644
--- a/apps/web/ui/modals/update-partner-user-modal.tsx
+++ b/apps/web/ui/modals/update-partner-user-modal.tsx
@@ -1,8 +1,7 @@
import { mutatePrefix } from "@/lib/swr/mutate";
-import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { PartnerUserProps } from "@/lib/swr/use-partner-profile-users";
import { PartnerRole } from "@dub/prisma/client";
-import { Avatar, BlurImage, Button, Logo, Modal } from "@dub/ui";
+import { Avatar, Button, Modal, useMediaQuery } from "@dub/ui";
import {
Dispatch,
SetStateAction,
@@ -11,7 +10,6 @@ import {
useState,
} from "react";
import { toast } from "sonner";
-import { mutate } from "swr";
function UpdatePartnerUserModal({
showUpdateUserModal,
@@ -24,8 +22,8 @@ function UpdatePartnerUserModal({
user: PartnerUserProps;
role: PartnerRole;
}) {
+ const { isMobile } = useMediaQuery();
const [updating, setUpdating] = useState(false);
- const { partner } = usePartnerProfile();
const { id: userId, name, email } = user;
const updateRole = async () => {
@@ -33,63 +31,64 @@ function UpdatePartnerUserModal({
try {
const response = await fetch("/api/partner-profile/users", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
body: JSON.stringify({
userId,
role,
}),
});
- if (response.ok) {
- await mutatePrefix("/api/partner-profile/users");
- setShowUpdateUserModal(false);
- toast.success(
- `Successfully changed ${name || email}'s role to ${role}.`,
- );
- } else {
+ if (!response.ok) {
const { error } = await response.json();
- toast.error(error.message);
+ throw new Error(error.message);
}
+
+ await mutatePrefix("/api/partner-profile/users");
+ setShowUpdateUserModal(false);
+ toast.success(`Successfully updated the role to ${role}.`);
} catch (error) {
- toast.error("Failed to update role");
+ toast.error(error.message || "Failed to update role");
} finally {
setUpdating(false);
}
};
return (
- <Modal showModal={showUpdateUserModal} setShowModal={setShowUpdateUserModal}>
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 sm:px-16">
- {partner?.image ? (
- <BlurImage
- src={partner.image}
- alt="Partner logo"
- className="h-10 w-10 rounded-full"
- width={20}
- height={20}
- />
- ) : (
- <Logo />
- )}
- <h3 className="text-lg font-medium">Change Partner Role</h3>
- <p className="text-center text-sm text-neutral-500">
- This will change <b className="text-neutral-800">{name || email}</b>'s
- role in <b className="text-neutral-800">{partner?.name}</b> to{" "}
- <b className="text-neutral-800">{role}</b>. Are you sure you want to
- continue?
+ <Modal
+ showModal={showUpdateUserModal}
+ setShowModal={setShowUpdateUserModal}
+ className="max-w-md"
+ >
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="text-lg font-medium">Update Member Role</h3>
+ <p className="text-sm text-neutral-500">
+ This will change{" "}
+ <span className="font-semibold text-black">{name || email}</span>
+ 's role to <span className="font-semibold text-black">{role}</span>.
+ Are you sure you want to continue?
</p>
</div>
- <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-8 text-left sm:px-16">
- <div className="flex items-center space-x-3 rounded-md border border-neutral-300 bg-white p-3">
- <Avatar user={user} />
- <div className="flex flex-col">
- <h3 className="text-sm font-medium">{name || email}</h3>
- <p className="text-xs text-neutral-500">{email}</p>
+ <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-4 sm:px-6">
+ <div className="relative flex items-center gap-2 space-x-3 rounded-md border border-neutral-300 bg-white px-4 py-2">
+ <div className="flex items-center gap-2">
+ <Avatar user={user} className="size-10" />
+ <div className="flex flex-col">
+ <p className="text-sm font-medium">{name || email}</p>
+ <p className="text-content-subtle text-sm">{email}</p>
+ </div>
</div>
</div>
- <Button text="Confirm" loading={updating} onClick={updateRole} />
+
+ <Button
+ text="Confirm"
+ autoFocus={!isMobile}
+ loading={updating}
+ onClick={updateRole}
+ />
</div>
</Modal>
);
@@ -123,4 +122,3 @@ export function useUpdatePartnerUserModal({
[setShowUpdateUserModal, UpdateUserModalCallback],
);
}
-