Merge pull request #16 from i701/feat/user-verification-handling
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m43s

feat/user verification handling
This commit is contained in:
Abdulla Aidhaan
2025-07-13 22:53:16 +05:00
committed by GitHub
12 changed files with 443 additions and 339 deletions

View File

@ -1,16 +1,20 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getServerSession } from "next-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 { handleApiResponse } from "@/utils/tryCatch";
export async function VerifyUser(userId: string) {
export async function VerifyUser(_userId: string) {
// const user = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// include: {Rejectuser
// atoll: true,
// island: true,
// },
@ -87,3 +91,41 @@ export async function getProfileById(userId: string) {
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({
params,
}: {
@ -6,164 +17,168 @@ export default async function VerifyUserPage({
}>;
}) {
const userId = (await params).userId;
console.log("userId", userId);
// const dbUser = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// island: {
// include: {
// atoll: true
// }
// }
// }
// })
const [error, dbUser] = await tryCatch(getProfileById(userId));
// 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 (
// <div>
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// return <pre>{JSON.stringify(nationalData, null, 2)}</pre>
const fullName = `${dbUser?.first_name} ${dbUser?.last_name}`;
const nationalDob = nationalData?.dob?.split("T")[0];
const dbUserDob = new Date(dbUser?.dob).toISOString().split("T")[0];
// <div className="flex gap-2">
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
// {dbUser?.verified && (
// <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 ?? ""}
// />
return (
<div>
<div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// <InputReadOnly
// showCheck
// checkTrue={
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)
// }
// labelClassName="text-sarLinkOrange"
// label="DOB"
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
// month: "short",
// day: "2-digit",
// year: "numeric",
// })}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact}
// labelClassName="text-sarLinkOrange"
// label="Phone Number"
// value={dbUser?.phoneNumber ?? ""}
// />
// </div>
// </div>
// <div id="national-information">
// <h4 className="p-2 rounded font-semibold">National Information</h4>
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="ID Card"
// value={nationalData?.nic ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Name"
// 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>
// );
<div className="flex gap-2">
{dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
{dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
{dbUser?.verified && (
<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={fullName === nationalData?.name_en}
labelClassName="text-sarLinkOrange"
label="Name"
value={fullName}
/>
<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?.atoll.name === nationalData?.atoll_en}
labelClassName="text-sarLinkOrange"
label="Atoll"
value={dbUser?.island?.name ?? ""}
/>
<InputReadOnly
showCheck
checkTrue={
dbUserDob === nationalDob
}
labelClassName="text-sarLinkOrange"
label="DOB"
value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})}
/>
<InputReadOnly
showCheck
checkTrue={dbUser?.mobile === nationalData?.primary_contact}
labelClassName="text-sarLinkOrange"
label="Phone Number"
value={dbUser?.mobile ?? ""}
/>
</div>
</div>
{(
<div id="national-information">
<h4 className="p-2 rounded font-semibold">National 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={false}
labelClassName="text-green-500"
label="ID Card"
value={nationalData?.nic ?? ""}
/>
<InputReadOnly
showCheck={false}
labelClassName="text-green-500"
label="Name"
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,5 +1,5 @@
import { cn } from '@/lib/utils';
import { CheckCheck, X } from 'lucide-react';
import { cn } from '@/lib/utils';
export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: {
label: string;
@ -10,7 +10,7 @@ export default function InputReadOnly({ label, value, labelClassName, className,
checkTrue?: boolean
}) {
return (
<div className={cn("relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none", className)}>
<div className={cn("relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none col-span-2 sm:col-span-1", className)}>
<div>
<label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}>

View File

@ -1,130 +1,145 @@
"use client"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import * as React from "react"
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
const AlertDialog = AlertDialogPrimitive.Root
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
const AlertDialogPortal = AlertDialogPrimitive.Portal
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 [data-[state=closed]:slide-out-to-top-[48%]] data-[state=open]:slide-in-from-left-1/2 [data-[state=open]:slide-in-from-top-[48%]] sm:rounded-lg",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
)
}
const AlertDialogHeader = ({
function AlertDialogContent({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
const AlertDialogFooter = ({
function AlertDialogHeader({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
}
export {
AlertDialog,

View File

@ -3,9 +3,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { }
const FloatingInput = React.forwardRef<HTMLInputElement, InputProps>(
const FloatingInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, ...props }, ref) => {
return <Input placeholder=" " className={cn('peer', className)} ref={ref} {...props} />;
},
@ -29,7 +27,7 @@ const FloatingLabel = React.forwardRef<
});
FloatingLabel.displayName = 'FloatingLabel';
type FloatingLabelInputProps = InputProps & { label?: string };
type FloatingLabelInputProps = React.InputHTMLAttributes<HTMLInputElement> & { label?: string };
const FloatingLabelInput = React.forwardRef<
React.ElementRef<typeof FloatingInput>,

View File

@ -2,21 +2,17 @@ import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
}
export { Textarea }

View File

@ -1,6 +1,10 @@
"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 {
Dialog,
@ -12,68 +16,55 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
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 { 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";
const validationSchema = z.object({
reason: z.string().min(5, { message: "Reason is required" }),
});
export default function UserRejectDialog({ user }: { user: User }) {
const [disabled, setDisabled] = useState(false);
const [open, setOpen] = useState(false);
const {
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);
export type RejectUserFormState = {
message: string;
fieldErrors?: {
rejection_details?: string[];
};
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 (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button disabled={disabled} variant="destructive">
<Button disabled={isPending} variant="destructive">
<UserX />
Reject
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>
Are you sure you want to{" "}
<span className="text-red-500">reject</span> this user?
<DialogTitle className="text-muted-foreground">
Are you sure?
</DialogTitle>
<DialogDescription className="py-2">
<li>
@ -92,28 +83,30 @@ export default function UserRejectDialog({ user }: { user: User }) {
<li>Phone Number: {user.mobile}</li>
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<form action={formAction}>
<div className="grid gap-4 py-4">
<div className="flex flex-col items-start gap-1">
<Label htmlFor="reason" className="text-right">
<div className="flex flex-col items-start gap-2">
<input type="hidden" name="userId" value={user.id} />
<Label htmlFor="reason" className="text-right text-muted-foreground">
Rejection details
</Label>
<Textarea
rows={10}
{...register("reason")}
name="rejection_details"
id="reason"
defaultValue={state.payload?.get("rejection_details") as string}
className={cn(
"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">
{errors.reason?.message}
{state.fieldErrors?.rejection_details?.[0]}
</span>
</div>
</div>
<DialogFooter>
<Button variant={"destructive"} disabled={disabled} type="submit">
<Button variant={"destructive"} disabled={isPending} type="submit">
Reject
</Button>
</DialogFooter>

View File

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

View File

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

View File

@ -11,7 +11,7 @@ export async function handleApiResponse<T>(
response: Response,
fnName?: string,
) {
const responseData = await response.json();
const responseData = await response.json()
if (response.status === 401) {
console.log('response data', responseData)
throw new Error("UNAUTHORIZED");
@ -32,7 +32,7 @@ export async function handleApiResponse<T>(
if (!response.ok) {
console.log(`API Error Response from ${fnName}:`, responseData);
throw new Error(responseData.message || "Something went wrong.");
throw new Error(responseData.message || responseData.detail || "Something went wrong.");
}
return responseData as T;