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"; "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) {
return null; console.warn("Error fetching national data:", nationalDataEror);
// return ( }
// <div> if (error) {
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4"> if (error.message === "UNAUTHORIZED") {
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3> redirect("/auth/signin");
} else {
// <div className="flex gap-2"> return <ClientErrorMessage message={error.message} />;
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />} }
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />} }
// {dbUser?.verified && (
// <Badge variant={"secondary"} className="bg-lime-500"> // return <pre>{JSON.stringify(nationalData, null, 2)}</pre>
// Verified const fullName = `${dbUser?.first_name} ${dbUser?.last_name}`;
// </Badge> const nationalDob = nationalData?.dob?.split("T")[0];
// )} const dbUserDob = new Date(dbUser?.dob).toISOString().split("T")[0];
// </div>
// </div> return (
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start"> <div>
// <div id="database-information"> <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
// <h4 className="p-2 rounded font-semibold">Database Information</h4> <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
// <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 <div className="flex gap-2">
// showCheck {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
// checkTrue={dbUser?.id_card === nationalData.nic} {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
// labelClassName="text-sarLinkOrange" {dbUser?.verified && (
// label="ID Card" <Badge variant={"secondary"} className="bg-lime-500">
// value={dbUser?.id_card ?? ""} Verified
// /> </Badge>
// <InputReadOnly )}
// showCheck </div>
// checkTrue={dbUser?.name === nationalData.name_en} </div>
// labelClassName="text-sarLinkOrange" <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
// label="Name" <div id="database-information">
// value={dbUser?.name ?? ""} <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 <InputReadOnly
// showCheck showCheck
// checkTrue={dbUser?.address === nationalData.house_name_en} checkTrue={dbUser?.id_card === nationalData?.nic}
// labelClassName="text-sarLinkOrange" labelClassName="text-sarLinkOrange"
// label="House Name" label="ID Card"
// value={dbUser?.address ?? ""} value={dbUser?.id_card ?? ""}
// /> />
// <InputReadOnly <InputReadOnly
// showCheck showCheck
// checkTrue={dbUser?.island?.name === nationalData.island_name_en} checkTrue={fullName === nationalData?.name_en}
// labelClassName="text-sarLinkOrange" labelClassName="text-sarLinkOrange"
// label="Island" label="Name"
// value={dbUser?.island?.name ?? ""} value={fullName}
// /> />
// <InputReadOnly <InputReadOnly
// showCheck showCheck
// checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en} checkTrue={dbUser?.address === nationalData?.house_name_en}
// labelClassName="text-sarLinkOrange" labelClassName="text-sarLinkOrange"
// label="Atoll" label="House Name"
// value={dbUser?.island?.atoll.name ?? ""} value={dbUser?.address ?? ""}
// /> />
<InputReadOnly
// <InputReadOnly showCheck
// showCheck checkTrue={dbUser?.island?.name === nationalData?.island_name_en}
// checkTrue={ labelClassName="text-sarLinkOrange"
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob) label="Island"
// } value={dbUser?.island?.name ?? ""}
// labelClassName="text-sarLinkOrange" />
// label="DOB" <InputReadOnly
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", { showCheck
// month: "short", checkTrue={dbUser?.atoll.name === nationalData?.atoll_en}
// day: "2-digit", labelClassName="text-sarLinkOrange"
// year: "numeric", label="Atoll"
// })} value={dbUser?.island?.name ?? ""}
// /> />
// <InputReadOnly
// showCheck <InputReadOnly
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact} showCheck
// labelClassName="text-sarLinkOrange" checkTrue={
// label="Phone Number" dbUserDob === nationalDob
// value={dbUser?.phoneNumber ?? ""} }
// /> labelClassName="text-sarLinkOrange"
// </div> label="DOB"
// </div> value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
// <div id="national-information"> month: "short",
// <h4 className="p-2 rounded font-semibold">National Information</h4> day: "2-digit",
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2"> year: "numeric",
// <InputReadOnly })}
// showCheck={false} />
// labelClassName="text-green-500" <InputReadOnly
// label="ID Card" showCheck
// value={nationalData?.nic ?? ""} checkTrue={dbUser?.mobile === nationalData?.primary_contact}
// /> labelClassName="text-sarLinkOrange"
// <InputReadOnly label="Phone Number"
// showCheck={false} value={dbUser?.mobile ?? ""}
// labelClassName="text-green-500" />
// label="Name" </div>
// value={nationalData?.name_en ?? ""} </div>
// /> {(
// <InputReadOnly <div id="national-information">
// showCheck={false} <h4 className="p-2 rounded font-semibold">National Information</h4>
// labelClassName="text-green-500" <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// label="House Name" <InputReadOnly
// value={nationalData?.house_name_en ?? ""} showCheck={false}
// /> labelClassName="text-green-500"
// <InputReadOnly label="ID Card"
// showCheck={false} value={nationalData?.nic ?? ""}
// labelClassName="text-green-500" />
// label="Island" <InputReadOnly
// value={nationalData?.island_name_en ?? ""} showCheck={false}
// /> labelClassName="text-green-500"
// <InputReadOnly label="Name"
// showCheck={false} value={nationalData?.name_en ?? ""}
// labelClassName="text-green-500" />
// label="Atoll" <InputReadOnly
// value={nationalData?.atoll_en ?? ""} showCheck={false}
// /> labelClassName="text-green-500"
// <InputReadOnly label="House Name"
// showCheck={false} value={nationalData?.house_name_en ?? ""}
// labelClassName="text-green-500" />
// label="DOB" <InputReadOnly
// value={new Date(nationalData?.dob ?? "").toLocaleDateString( showCheck={false}
// "en-US", labelClassName="text-green-500"
// { label="Island"
// month: "short", value={nationalData?.island_name_en ?? ""}
// day: "2-digit", />
// year: "numeric", <InputReadOnly
// }, showCheck={false}
// )} labelClassName="text-green-500"
// /> label="Atoll"
// <InputReadOnly value={nationalData?.atoll_en ?? ""}
// showCheck={false} />
// labelClassName="text-green-500" <InputReadOnly
// label="Phone Number" showCheck={false}
// value={nationalData?.primary_contact ?? ""} labelClassName="text-green-500"
// /> label="DOB"
// <div className="flex flex-col col-span-2 items-center justify-center"> value={new Date(nationalData?.dob ?? "").toLocaleDateString(
// <Image "en-US",
// src={nationalData.image_url || "https://i.pravatar.cc/300"} {
// height={100} month: "short",
// width={100} day: "2-digit",
// className="object-fit aspect-square rounded-full" year: "numeric",
// alt="id photo" },
// /> )}
// </div> />
// </div> <InputReadOnly
// </div> showCheck={false}
// </div> labelClassName="text-green-500"
// </div> 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 { CheckCheck, X } from 'lucide-react';
import { cn } from '@/lib/utils';
export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: { export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: {
label: string; label: string;
@ -10,7 +10,7 @@ export default function InputReadOnly({ label, value, labelClassName, className,
checkTrue?: boolean checkTrue?: boolean
}) { }) {
return ( 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> <div>
<label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}> <label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}>

View File

@ -1,130 +1,145 @@
"use client" "use client"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui" import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import * as React from "react" import * as React from "react"
import { buttonVariants } from "@/components/ui/button" import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils" 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< function AlertDialogOverlay({
React.ElementRef<typeof AlertDialogPrimitive.Overlay>, className,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay> ...props
>(({ className, ...props }, ref) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay <AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn( 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", "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 className
)} )}
{...props} {...props}
ref={ref}
/> />
)) )
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName }
const AlertDialogContent = React.forwardRef< function AlertDialogContent({
React.ElementRef<typeof AlertDialogPrimitive.Content>, className,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content> ...props
>(({ className, ...props }, ref) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal> <AlertDialogPortal>
<AlertDialogOverlay /> <AlertDialogOverlay />
<AlertDialogPrimitive.Content <AlertDialogPrimitive.Content
ref={ref} data-slot="alert-dialog-content"
className={cn( 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", "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 className
)} )}
{...props} {...props}
/> />
</AlertDialogPortal> </AlertDialogPortal>
)) )
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName }
const AlertDialogHeader = ({ function AlertDialogHeader({
className, className,
...props ...props
}: React.HTMLAttributes<HTMLDivElement>) => ( }: React.ComponentProps<"div">) {
return (
<div <div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn( className={cn(
"flex flex-col space-y-2 text-center sm:text-left", "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className className
)} )}
{...props} {...props}
/> />
) )
AlertDialogHeader.displayName = "AlertDialogHeader" }
const AlertDialogFooter = ({ function AlertDialogTitle({
className, className,
...props ...props
}: React.HTMLAttributes<HTMLDivElement>) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
<div return (
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title <AlertDialogPrimitive.Title
ref={ref} data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)} className={cn("text-lg font-semibold", className)}
{...props} {...props}
/> />
)) )
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName }
const AlertDialogDescription = React.forwardRef< function AlertDialogDescription({
React.ElementRef<typeof AlertDialogPrimitive.Description>, className,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description> ...props
>(({ className, ...props }, ref) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description <AlertDialogPrimitive.Description
ref={ref} data-slot="alert-dialog-description"
className={cn("text-sm text-muted-foreground", className)} className={cn("text-muted-foreground text-sm", className)}
{...props} {...props}
/> />
)) )
AlertDialogDescription.displayName = }
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef< function AlertDialogAction({
React.ElementRef<typeof AlertDialogPrimitive.Action>, className,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action> ...props
>(({ className, ...props }, ref) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action <AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)} className={cn(buttonVariants(), className)}
{...props} {...props}
/> />
)) )
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName }
const AlertDialogCancel = React.forwardRef< function AlertDialogCancel({
React.ElementRef<typeof AlertDialogPrimitive.Cancel>, className,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel> ...props
>(({ className, ...props }, ref) => ( }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel <AlertDialogPrimitive.Cancel
ref={ref} className={cn(buttonVariants({ variant: "outline" }), className)}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props} {...props}
/> />
)) )
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName }
export { export {
AlertDialog, AlertDialog,

View File

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

View File

@ -2,21 +2,17 @@ import * as React from "react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
const Textarea = React.forwardRef< function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
return ( return (
<textarea <textarea
data-slot="textarea"
className={cn( 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 className
)} )}
ref={ref}
{...props} {...props}
/> />
) )
}) }
Textarea.displayName = "Textarea"
export { Textarea } export { Textarea }

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");
}

View File

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