feat: implement user verification and rejection functionality with improved error handling

This commit is contained in:
2025-07-13 22:51:46 +05:00
parent 5809e26593
commit 255c03ae6a
7 changed files with 315 additions and 220 deletions

View File

@ -1,16 +1,20 @@
"use server"; "use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import type { RejectUserFormState } from "@/components/user/user-reject-dialog";
import type { ApiError } from "@/lib/backend-types";
import type { User, UserProfile } from "@/lib/types/user"; import type { User, UserProfile } from "@/lib/types/user";
import { handleApiResponse } from "@/utils/tryCatch"; import { handleApiResponse } from "@/utils/tryCatch";
export async function VerifyUser(userId: string) { export async function VerifyUser(_userId: string) {
// const user = await prisma.user.findUnique({ // const user = await prisma.user.findUnique({
// where: { // where: {
// id: userId, // id: userId,
// }, // },
// include: { // include: {Rejectuser
// atoll: true, // atoll: true,
// island: true, // island: true,
// }, // },
@ -87,3 +91,41 @@ export async function getProfileById(userId: string) {
return handleApiResponse<UserProfile>(response, "getProfilebyId"); return handleApiResponse<UserProfile>(response, "getProfilebyId");
} }
export async function rejectUser(
_prevState: RejectUserFormState,
formData: FormData
): Promise<RejectUserFormState> {
const userId = formData.get("userId") as string;
const rejection_details = formData.get("rejection_details") as string;
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({ rejection_details: rejection_details }),
},
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || errorData.detail || "Failed to reject user");
}
// Handle 204 No Content response (successful deletion)
if (response.status === 204) {
revalidatePath("/users");
redirect("/users");
}
revalidatePath("/users");
const error = await response.json()
return {
message: (error as ApiError).message || (error as ApiError).detail || "An unexpected error occurred.",
fieldErrors: {},
payload: formData
};
}

View File

@ -0,0 +1,14 @@
export default async function UserUpdate({
params,
}: {
params: Promise<{
userId: string;
}>;
}) {
const { userId } = await params;
return (
<div>UserUpdate: {userId}</div>
)
}

View File

@ -1,3 +1,14 @@
import Image from "next/image";
import { redirect } from "next/navigation";
import { getProfileById } from "@/actions/user-actions";
import ClientErrorMessage from "@/components/client-error-message";
import InputReadOnly from "@/components/input-read-only";
import { Badge } from "@/components/ui/badge";
import UserRejectDialog from "@/components/user/user-reject-dialog";
import { UserVerifyDialog } from "@/components/user/user-verify-dialog";
import { getNationalPerson } from "@/lib/person";
import { tryCatch } from "@/utils/tryCatch";
export default async function VerifyUserPage({ export default async function VerifyUserPage({
params, params,
}: { }: {
@ -6,164 +17,168 @@ export default async function VerifyUserPage({
}>; }>;
}) { }) {
const userId = (await params).userId; const userId = (await params).userId;
console.log("userId", userId); const [error, dbUser] = await tryCatch(getProfileById(userId));
// const dbUser = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// island: {
// include: {
// atoll: true
// }
// }
// }
// })
// const nationalData = await getNationalPerson({ idCard: dbUser?.id_card ?? "" }) const [nationalDataEror, nationalData] = await tryCatch(getNationalPerson({ idCard: dbUser?.id_card ?? "" }))
if (nationalDataEror) {
console.warn("Error fetching national data:", nationalDataEror);
}
if (error) {
if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin");
} else {
return <ClientErrorMessage message={error.message} />;
}
}
return null; // return <pre>{JSON.stringify(nationalData, null, 2)}</pre>
// return ( const fullName = `${dbUser?.first_name} ${dbUser?.last_name}`;
// <div> const nationalDob = nationalData?.dob?.split("T")[0];
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4"> const dbUserDob = new Date(dbUser?.dob).toISOString().split("T")[0];
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// <div className="flex gap-2"> return (
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />} <div>
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />} <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
// {dbUser?.verified && ( <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// <Badge variant={"secondary"} className="bg-lime-500">
// Verified
// </Badge>
// )}
// </div>
// </div>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
// <div id="database-information">
// <h4 className="p-2 rounded font-semibold">Database Information</h4>
// <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.id_card === nationalData.nic}
// labelClassName="text-sarLinkOrange"
// label="ID Card"
// value={dbUser?.id_card ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.name === nationalData.name_en}
// labelClassName="text-sarLinkOrange"
// label="Name"
// value={dbUser?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.address === nationalData.house_name_en}
// labelClassName="text-sarLinkOrange"
// label="House Name"
// value={dbUser?.address ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.name === nationalData.island_name_en}
// labelClassName="text-sarLinkOrange"
// label="Island"
// value={dbUser?.island?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en}
// labelClassName="text-sarLinkOrange"
// label="Atoll"
// value={dbUser?.island?.atoll.name ?? ""}
// />
// <InputReadOnly <div className="flex gap-2">
// showCheck {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
// checkTrue={ {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob) {dbUser?.verified && (
// } <Badge variant={"secondary"} className="bg-lime-500">
// labelClassName="text-sarLinkOrange" Verified
// label="DOB" </Badge>
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", { )}
// month: "short", </div>
// day: "2-digit", </div>
// year: "numeric", <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
// })} <div id="database-information">
// /> <h4 className="p-2 rounded font-semibold">Database Information</h4>
// <InputReadOnly <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// showCheck <InputReadOnly
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact} showCheck
// labelClassName="text-sarLinkOrange" checkTrue={dbUser?.id_card === nationalData?.nic}
// label="Phone Number" labelClassName="text-sarLinkOrange"
// value={dbUser?.phoneNumber ?? ""} label="ID Card"
// /> value={dbUser?.id_card ?? ""}
// </div> />
// </div> <InputReadOnly
// <div id="national-information"> showCheck
// <h4 className="p-2 rounded font-semibold">National Information</h4> checkTrue={fullName === nationalData?.name_en}
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2"> labelClassName="text-sarLinkOrange"
// <InputReadOnly label="Name"
// showCheck={false} value={fullName}
// labelClassName="text-green-500" />
// label="ID Card" <InputReadOnly
// value={nationalData?.nic ?? ""} showCheck
// /> checkTrue={dbUser?.address === nationalData?.house_name_en}
// <InputReadOnly labelClassName="text-sarLinkOrange"
// showCheck={false} label="House Name"
// labelClassName="text-green-500" value={dbUser?.address ?? ""}
// label="Name" />
// value={nationalData?.name_en ?? ""} <InputReadOnly
// /> showCheck
// <InputReadOnly checkTrue={dbUser?.island?.name === nationalData?.island_name_en}
// showCheck={false} labelClassName="text-sarLinkOrange"
// labelClassName="text-green-500" label="Island"
// label="House Name" value={dbUser?.island?.name ?? ""}
// value={nationalData?.house_name_en ?? ""} />
// /> <InputReadOnly
// <InputReadOnly showCheck
// showCheck={false} checkTrue={dbUser?.atoll.name === nationalData?.atoll_en}
// labelClassName="text-green-500" labelClassName="text-sarLinkOrange"
// label="Island" label="Atoll"
// value={nationalData?.island_name_en ?? ""} value={dbUser?.island?.name ?? ""}
// /> />
// <InputReadOnly
// showCheck={false} <InputReadOnly
// labelClassName="text-green-500" showCheck
// label="Atoll" checkTrue={
// value={nationalData?.atoll_en ?? ""} dbUserDob === nationalDob
// /> }
// <InputReadOnly labelClassName="text-sarLinkOrange"
// showCheck={false} label="DOB"
// labelClassName="text-green-500" value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
// label="DOB" month: "short",
// value={new Date(nationalData?.dob ?? "").toLocaleDateString( day: "2-digit",
// "en-US", year: "numeric",
// { })}
// month: "short", />
// day: "2-digit", <InputReadOnly
// year: "numeric", showCheck
// }, checkTrue={dbUser?.mobile === nationalData?.primary_contact}
// )} labelClassName="text-sarLinkOrange"
// /> label="Phone Number"
// <InputReadOnly value={dbUser?.mobile ?? ""}
// showCheck={false} />
// labelClassName="text-green-500" </div>
// label="Phone Number" </div>
// value={nationalData?.primary_contact ?? ""} {(
// /> <div id="national-information">
// <div className="flex flex-col col-span-2 items-center justify-center"> <h4 className="p-2 rounded font-semibold">National Information</h4>
// <Image <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// src={nationalData.image_url || "https://i.pravatar.cc/300"} <InputReadOnly
// height={100} showCheck={false}
// width={100} labelClassName="text-green-500"
// className="object-fit aspect-square rounded-full" label="ID Card"
// alt="id photo" value={nationalData?.nic ?? ""}
// /> />
// </div> <InputReadOnly
// </div> showCheck={false}
// </div> labelClassName="text-green-500"
// </div> label="Name"
// </div> value={nationalData?.name_en ?? ""}
// ); />
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="House Name"
value={nationalData?.house_name_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Island"
value={nationalData?.island_name_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Atoll"
value={nationalData?.atoll_en ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="DOB"
value={new Date(nationalData?.dob ?? "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Phone Number"
value={nationalData?.primary_contact ?? ""}
/>
<div className="flex flex-col col-span-2 items-center justify-center">
<Image
src={nationalData?.image_url || "https://i.pravatar.cc/300"}
height={100}
width={100}
className="object-fit aspect-square rounded-full"
alt="id photo"
/>
</div>
</div>
</div>
)}
</div>
</div>
);
} }

View File

@ -1,6 +1,10 @@
"use client"; "use client";
import { Rejectuser } from "@/actions/user-actions"; import { UserX } from "lucide-react";
import { useActionState, useEffect, useState } from "react";
import { toast } from "sonner";
import { rejectUser } from "@/actions/user-actions";
// import { Rejectuser } from "@/actions/user-actions";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
@ -12,68 +16,55 @@ import {
DialogTrigger, DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import type { User } from "@/lib/types/user"; import type { UserProfile } from "@/lib/types/user";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { UserX } from "lucide-react";
import { useState } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Textarea } from "../ui/textarea"; import { Textarea } from "../ui/textarea";
const validationSchema = z.object({
reason: z.string().min(5, { message: "Reason is required" }),
});
export default function UserRejectDialog({ user }: { user: User }) { export type RejectUserFormState = {
const [disabled, setDisabled] = useState(false); message: string;
const [open, setOpen] = useState(false); fieldErrors?: {
const { rejection_details?: string[];
register,
handleSubmit,
formState: { errors },
} = useForm<z.infer<typeof validationSchema>>({
resolver: zodResolver(validationSchema),
});
const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => {
setDisabled(true);
console.log(data);
toast.promise(
Rejectuser({
userId: String(user.id),
reason: data.reason,
}),
{
loading: "Rejecting...",
success: () => {
setDisabled(false);
setOpen((prev) => !prev);
return "Rejected!";
},
error: (error) => {
setDisabled(false);
return error.message || "Something went wrong";
},
},
);
setDisabled(false);
}; };
payload?: FormData;
};
export const initialState: RejectUserFormState = {
message: "",
fieldErrors: {},
};
export default function UserRejectDialog({ user }: { user: UserProfile }) {
const [open, setOpen] = useState(false);
const [state, formAction, isPending] = useActionState(rejectUser, initialState);
useEffect(() => {
if (state.message && state !== initialState) {
if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) {
toast.error(state.message);
} else if (!state.fieldErrors) {
toast.success("User rejected successfully!");
setOpen(false);
} else {
toast.error(state.message);
}
}
}, [state]);
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button disabled={disabled} variant="destructive"> <Button disabled={isPending} variant="destructive">
<UserX /> <UserX />
Reject Reject
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle className="text-muted-foreground">
Are you sure you want to{" "} Are you sure?
<span className="text-red-500">reject</span> this user?
</DialogTitle> </DialogTitle>
<DialogDescription className="py-2"> <DialogDescription className="py-2">
<li> <li>
@ -92,28 +83,30 @@ export default function UserRejectDialog({ user }: { user: User }) {
<li>Phone Number: {user.mobile}</li> <li>Phone Number: {user.mobile}</li>
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}> <form action={formAction}>
<div className="grid gap-4 py-4"> <div className="grid gap-4 py-4">
<div className="flex flex-col items-start gap-1"> <div className="flex flex-col items-start gap-2">
<Label htmlFor="reason" className="text-right"> <input type="hidden" name="userId" value={user.id} />
<Label htmlFor="reason" className="text-right text-muted-foreground">
Rejection details Rejection details
</Label> </Label>
<Textarea <Textarea
rows={10} rows={10}
{...register("reason")} name="rejection_details"
id="reason" id="reason"
defaultValue={state.payload?.get("rejection_details") as string}
className={cn( className={cn(
"col-span-5", "col-span-5",
errors.reason && "ring-2 ring-red-500", state.fieldErrors?.rejection_details && "ring-2 ring-red-500",
)} )}
/> />
<span className="text-sm text-red-500"> <span className="text-sm text-red-500">
{errors.reason?.message} {state.fieldErrors?.rejection_details?.[0]}
</span> </span>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant={"destructive"} disabled={disabled} type="submit"> <Button variant={"destructive"} disabled={isPending} type="submit">
Reject Reject
</Button> </Button>
</DialogFooter> </DialogFooter>

View File

@ -1,4 +1,7 @@
"use client"; "use client";
import { Check, CheckCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { VerifyUser } from "@/actions/user-actions"; import { VerifyUser } from "@/actions/user-actions";
import { import {
AlertDialog, AlertDialog,
@ -12,12 +15,9 @@ import {
AlertDialogTrigger, AlertDialogTrigger,
} from "@/components/ui/alert-dialog"; } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import type { User } from "@/lib/types/user"; import type { UserProfile } from "@/lib/types/user";
import { Check, CheckCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
export function UserVerifyDialog({ user }: { user: User }) { export function UserVerifyDialog({ user }: { user: UserProfile }) {
const userId = user.id; const userId = user.id;
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
return ( return (
@ -33,7 +33,7 @@ export function UserVerifyDialog({ user }: { user: User }) {
</AlertDialogTrigger> </AlertDialogTrigger>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle> <AlertDialogTitle className="text-muted-foreground">Verify User</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
Are you sure you want to verify the following user? Are you sure you want to verify the following user?
<span className="inline-block my-4"> <span className="inline-block my-4">

View File

@ -5,7 +5,7 @@ export async function getNationalPerson({
idCard, idCard,
}: { idCard: string }): Promise<TNationalPerson> { }: { idCard: string }): Promise<TNationalPerson> {
const nationalInformation = await fetch( const nationalInformation = await fetch(
`${process.env.PERSON_VERIFY_API_BASE}/api/person/${idCard}`, `${process.env.PERSON_VERIFY_BASE_URL}/api/person/${idCard}`,
{ {
next: { next: {
revalidate: 60, revalidate: 60,

31
queries/users.ts Normal file
View File

@ -0,0 +1,31 @@
'use server'
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import type { ApiResponse } from "@/lib/backend-types";
import type { UserProfile } from "@/lib/types/user";
import { handleApiResponse } from "@/utils/tryCatch";
type ParamProps = {
[key: string]: string | number | undefined;
};
export async function getUsers(params: ParamProps) {
const session = await getServerSession(authOptions);
const query = Object.entries(params)
.filter(([_, value]) => value !== undefined && value !== "")
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
.join("&");
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/?${query}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<ApiResponse<UserProfile>>(response, "getUsers");
}