Sootzani-Inspector/components/AdminKeysManagement.tsx

557 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
import React, { useState, useRef, useEffect } from "react";
import { useMutation, useQuery, RefetchOptions } from "@tanstack/react-query";
import { GenerateKeyPair, GetKeys, AddKey, ChangeKey } from "@/utils/adminApi";
import { FaRegEdit } from "react-icons/fa";
import { IoMdClose } from "react-icons/io";
import { useRouter } from "next/navigation";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { ThreeDots } from "react-loader-spinner";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
const MAX_FILE_SIZE = 5242880; // 5 MB
// Edit Key Form
const FormSchemaEditKey = z.object({
uploadPrivateKey: z.any(),
// .instanceof(File)
// .custom<FileList>((val) => val instanceof FileList, "Required")
// .refine((files) => files.length <= 1, "Maximum of 1 file is allowed.")
// .refine(
// (files) =>
// Array.from(files).every((file) => file.size <= MAX_IMAGE_SIZE),
// "Each file size should be less than 5 MB."
// ),
// .refine((files) => files?.length === 0, "File is required.")
// .refine((files) => files?.length >= 1, "Maximum of 1 file is allowed.")
// .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, `Max file size is 5MB.`)
// publicKeyId: z
// .string()
// .nullable(),
});
// Add Key Form
const FormSchemaAddKey = z.object({
title: z.string().min(2, {
message: "عنوان کلید را وارد کنید",
}),
publicKey: z.string().min(4, {
message: "کلید عمومی را وارد کنید",
}),
});
export default function AdminKeysManagement() {
const router = useRouter();
const [keyId, setKeyId] = useState("");
const [openAdd, setOpenAdd] = React.useState(false);
const [openEdit, setOpenEdit] = React.useState(false);
const inputPubRef = useRef<HTMLInputElement | null>(null);
const inputPrvRef = useRef<HTMLInputElement | null>(null);
// ..............Read .txt
const [selectedFile, setSelectedFile] = useState<any>(null);
const handleFileChange = (event: any) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const contents = e?.target?.result;
// Process the contents of the file here
setSelectedFile(contents);
console.log(contents);
};
reader?.readAsText(file);
console.log(reader);
console.log(selectedFile);
};
// Edit Form
const formEdit = useForm<z.infer<typeof FormSchemaEditKey>>({
resolver: zodResolver(FormSchemaEditKey),
defaultValues: {
// publicKeyId: "",
// uploadFile: null,
},
});
// ............'Mutation' Change Key Submit
const ChangeKeyMutation = useMutation({
mutationKey: ["ChangeKey"],
mutationFn: ChangeKey,
onSuccess: (res) => {
console.log(res);
// alert("Success");
console.log("Success ChangeKey");
setOpenEdit(false);
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
// router.refresh()
},
onError: (error) => {
console.log(error);
console.log(error?.message);
setOpenEdit(false);
toast(error?.message, {
className: "!bg-red-500 !text-black",
});
},
});
function onSubmitEdit(data: z.infer<typeof FormSchemaEditKey>) {
console.log("bcbcbbcbcbc" + data);
console.log("bcbcbbcbcbccc" + selectedFile);
console.log("bcbcbbcbcbccccc" + data1[0]?.id);
// if (keyId) {
ChangeKeyMutation.mutate({
privateKey: selectedFile,
publicKeyId: keyId,
// publicKeyId: data1?.id,
});
// }
// else{
// console.error("keyId is undefined");
// }
}
// Add Form
const formAdd = useForm<z.infer<typeof FormSchemaAddKey>>({
resolver: zodResolver(FormSchemaAddKey),
defaultValues: {
title: "",
publicKey: "",
},
});
// ............'Mutation' Add Key Submit
const AddKeyMutation = useMutation({
mutationKey: ["AddKey"],
mutationFn: AddKey,
onSuccess: (res) => {
console.log(res);
console.log("Success AddKey");
setOpenAdd(false);
refetch1();
formAdd.reset();
if (inputPubRef.current && inputPrvRef.current) {
inputPrvRef.current.value = "";
inputPubRef.current.value = "";
}
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
// inputPubRef.current.clear();
// router.refresh()
},
onError: (error) => {
console.log(error);
console.log(error?.message);
setOpenAdd(false);
toast(error?.message, {
className: "!bg-red-500 !text-black",
});
},
});
function onSubmitAdd(data: z.infer<typeof FormSchemaAddKey>) {
AddKeyMutation.mutate({
title: data.title,
publicKey: data.publicKey,
});
}
// const { resetField } = useForm();
// List Keys
const {
data: data1,
error: Error1,
isLoading: isListLoading,
refetch: refetch1,
} = useQuery({
queryKey: ["KeysList"],
queryFn: () => GetKeys(),
// refetchOnWindowFocus: false,
});
console.log(data1);
// GenerateKeyPair
const {
data: data2,
error: Error2,
isLoading: isNewKeyLoading,
refetch: refetch2,
} = useQuery({
queryKey: ["GenerateKey"],
queryFn: () => GenerateKeyPair(),
enabled: false, // Disable automatic fetching
});
// Define the type for refetch2
// type RefetchFunction = (options?: RefetchOptions) => Promise<void>;
const handleClickGenerate = () => {
refetch2();
console.log(data2);
};
useEffect(() => {
if (inputPubRef.current && inputPrvRef.current) {
inputPubRef.current.value = data2?.publicKey ?? "";
inputPrvRef.current.value = data2?.privateKey ?? "";
}
}, [handleClickGenerate]);
const handleClickAddKey = () => {
// refetch2();
console.log(data1);
};
return (
<div className="w-full bg-[#F5F5F5] min-h-[85vh] flex justify-center">
<div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
{/* 1 */}
<AlertDialog open={openAdd} onOpenChange={setOpenAdd}>
<AlertDialogTrigger asChild>
<Button
variant="outline"
onClick={handleClickAddKey}
className="bg-orange-500 text-white"
// disabled={isNewKeyLoading}
>
افزودن کلید جدید
</Button>
</AlertDialogTrigger>
<AlertDialogContent className=" w-full max-w-6xl h-full max-h-[90vh] lg:max-h-[70vh]">
<AlertDialogHeader>
<AlertDialogTitle>
<p className="text-[#464646] text-base font-bold">
افزودن کلید جدید
</p>
<AlertDialogCancel className="p-0 border-0 h-auto">
<IoMdClose />
</AlertDialogCancel>
</AlertDialogTitle>
<AlertDialogDescription>
<div className="w-full ">
<div className="w-full text-right text-neutral-600 text-lg font-bold mb-4">
ایجاد جفت کلید جدید
</div>
{isNewKeyLoading ? (
<div className="felx justify-center items-center self-center">
<ThreeDots
visible={true}
height="50"
width="100"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
<div>
<Button
variant="outline"
onClick={handleClickGenerate}
disabled={isNewKeyLoading}
className="my-2"
>
{" "}
ایجاد جفت کلید
</Button>
{isNewKeyLoading ? (
<div className="felx justify-center items-center self-center h-full">
<ThreeDots
visible={true}
height="20"
width="50"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
<div
className="flex flex-row flex-wrap justify-between"
id="KeyFetch"
>
<div className=" w-full lg:w-[48%]">
<p className="text-[#7C838A] text-sm font-semibold">
کلید عمومی :
</p>
{/* <p className="text-slate-700 text-sm text-left mb-4">
{data2?.publicKey}
</p> */}
<Input
name="pubKey"
ref={inputPubRef}
// value={data2?.publicKey}
readOnly={true}
className="text-slate-700 text-sm text-left mb-4 w-full bg-white"
/>
</div>
<div className=" w-full lg:w-[48%]">
<p className="text-[#7C838A] text-sm font-semibold">
کلید خصوصی :
</p>
{/* <p className="text-slate-700 text-sm text-left mb-4">
{data2?.privateKey}
</p> */}
<Input
ref={inputPrvRef}
name="privKey"
// value={data2?.privateKey}
readOnly={true}
className="text-slate-700 text-sm text-left mb-4 w-full bg-white"
/>
</div>
</div>
)}
</div>
)}
<div className="w-full text-right text-neutral-600 text-lg font-bold mt-4 mb-2">
افزودن کلید جدید
</div>
<Form {...formAdd}>
<form
onSubmit={formAdd.handleSubmit(onSubmitAdd)}
className="w-full flex flex-col mt-6 "
>
<div className="flex flex-row flex-wrap justify-between">
<FormField
control={formAdd.control}
name="title"
render={({ field }) => (
<FormItem className=" w-full lg:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium">
عنوان کلید
</FormLabel>
<FormControl>
<Input
placeholder="عنوان کلید را وارد نمایید"
{...field}
className="bg-white"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={formAdd.control}
name="publicKey"
render={({ field }) => (
<FormItem className=" w-full lg:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium ">
کلید عمومی
</FormLabel>
<FormControl>
<Input
placeholder="کلید عمومی را وارد کنید"
{...field}
className="bg-white"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-center sm:justify-end gap-2 w-full mt-8">
<Button
type="submit"
className="bg-blue text-white min-w-max w-1/2 sm:w-1/3 lg:w-1/4 p-2 rounded-xl text-center"
>
افزودن کلید
</Button>
</div>
</form>
</Form>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
{/* <AlertDialogCancel>بستن</AlertDialogCancel> */}
{/* <AlertDialogAction>Continue</AlertDialogAction> */}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 2 */}
<div className="w-full text-right text-neutral-600 text-lg font-bold my-4">
لیست کلیدها
</div>
<div className="w-full flex flex-row flex-wrap justify-between gap-8 md:gap-4 ">
{data1?.map((item: any) => {
return (
<div
key={item.id}
className={`flex flex-col justify-center gap-2 w-full lg:w-[49%] h-28 px-5 rounded-md shadow-md items-start
`}
>
<p className=" text-slate-500 text-sm font-normal leading-normal">
عنوان کلید :
<span className=" text-slate-800">{item.title}</span>
</p>
<p className=" text-slate-500 text-sm font-normal leading-normal">
آی دی بازرس :
<span className=" text-slate-800 self-end">
{item.inspectorId}
</span>
</p>
<AlertDialog open={openEdit} onOpenChange={setOpenEdit}>
<AlertDialogTrigger asChild>
{/* <Button variant="outline">Show Dialog</Button> */}
<FaRegEdit
aria-hidden="true"
className="w-6 h-6 text-slate-600 hover:cursor-pointer self-end"
onClick={() => setKeyId(item?.id)}
/>
</AlertDialogTrigger>
<AlertDialogContent className=" w-full max-w-3xl h-full lg:max-h-[20em] max-h-[23em]">
<AlertDialogHeader>
<AlertDialogTitle>تغییر کلید</AlertDialogTitle>
<AlertDialogDescription>
<Form {...formEdit}>
<form
onSubmit={formEdit.handleSubmit(onSubmitEdit)}
className="w-full flex flex-col mt-6 "
>
<div className="flex flex-row flex-wrap justify-between">
<FormField
control={formEdit.control}
name="uploadPrivateKey"
render={({ field }) => (
<FormItem className=" w-full">
<FormLabel className="text-[#7C838A] text-sm font-medium mb-2">
پیوست (کلید خصوصی)
</FormLabel>
<FormControl>
<Input
required={true}
type="file"
accept=".txt"
className="bg-slate-300 mt-2"
// {...field}
onChange={handleFileChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* <FormField
control={formEdit.control}
name="publicKeyId"
render={({ field }) => (
<FormItem className=" w-full lg:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium ">
آی دی کلید عمومی
</FormLabel>
<FormControl>
<Input
className="bg-slate-300 mt-2"
value={item?.id}
readOnly={true}
// {...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/> */}
</div>
<div className="flex justify-center sm:justify-end gap-2 w-full mt-8">
<Button
// href="/FollowResult"
type="submit"
className="bg-blue text-white min-w-max p-2 rounded-xl text-center hover:bg-white hover:text-slate-800"
>
تغییر کلید
</Button>
{/* <AlertDialogAction
type="submit"
className="bg-blue text-white min-w-max p-2 rounded-xl text-center hover:bg-white hover:text-slate-800"
>
تغییر کلید
</AlertDialogAction> */}
<AlertDialogCancel className="bg-blue text-white rounded-xl mt-0">
بستن
</AlertDialogCancel>
</div>
</form>
</Form>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
{/* <AlertDialogAction>Continue</AlertDialogAction> */}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
})}
</div>
</div>
</div>
);
}