hp-prod-tracker/src/hooks/use-users.ts

61 lines
1.8 KiB
TypeScript

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { AssignmentRole } from "@/generated/prisma/client";
export function useUsers() {
return useQuery({
queryKey: ["users"],
queryFn: async () => {
const res = await fetch("/api/users");
if (!res.ok) throw new Error("Failed to fetch users");
return res.json() as Promise<
{ id: string; name: string | null; email: string; role: string }[]
>;
},
staleTime: 5 * 60 * 1000,
});
}
export function useAssignArtist(stageId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
userId,
role = "LEAD",
}: {
userId: string;
role?: AssignmentRole;
}) => {
const res = await fetch(`/api/stages/${stageId}/assignments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, role }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || "Failed to assign artist");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["deliverable"] });
},
});
}
export function useUnassignArtist(stageId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (userId: string) => {
const res = await fetch(`/api/stages/${stageId}/assignments`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId }),
});
if (!res.ok) throw new Error("Failed to remove assignment");
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["deliverable"] });
},
});
}