Sootzani-Inspector/components/AdminKeysManagement.tsx

509 lines
18 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";
import { Textarea } from "./ui/textarea";
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<HTMLTextAreaElement | null>(null);
const inputPrvRef = useRef<HTMLTextAreaElement | 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);
ChangeKeyMutation.mutate({
privateKey: selectedFile,
publicKeyId: keyId,
});
}
// 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,
isSuccess: isSuccess1,
} = useQuery({
queryKey: ["KeysList"],
queryFn: () => GetKeys(),
// refetchOnWindowFocus: false,
});
console.log(data1);
// GenerateKeyPair
const {
data: data2,
error: Error2,
isLoading: isNewKeyLoading,
refetch: refetch2,
isSuccess: isSuccess2,
} = 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 (isSuccess2) {
formAdd.setValue("publicKey", data2?.publicKey);
}
}, [isSuccess2]);
useEffect(() => {
if (inputPubRef.current && inputPrvRef.current) {
inputPubRef.current.value = data2?.publicKey ?? "";
inputPrvRef.current.value = data2?.privateKey ?? "";
}
}, [handleClickGenerate]);
const saveTextFile = () => {
const textToSave = data2?.privateKey ?? "";
const fileName = "privateKey.txt";
// Create a Blob containing the file data
const blob = new Blob([textToSave], { type: "text/plain" });
// Create a link element
const link = document.createElement("a");
// Set the download attribute and create a URL for the Blob
link.download = fileName;
link.href = window.URL.createObjectURL(blob);
// Append the link to the document and trigger the click event
document.body.appendChild(link);
link.click();
// Remove the link from the document
document.body.removeChild(link);
};
useEffect(() => {
if (AddKeyMutation.isSuccess) {
saveTextFile();
}
}, [AddKeyMutation.isSuccess]);
return (
<div className="w-full 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}>
<AlertDialogContent className=" ">
<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 flex justify-between">
<div className="w-full text-right text-neutral-600 text-lg font-bold mt-4 mb-2">
افزودن کلید جدید
</div>
<Button
variant="outline"
onClick={handleClickGenerate}
disabled={isNewKeyLoading}
className="my-2"
>
{" "}
ایجاد جفت کلید
</Button>
</div>
<Form {...formAdd}>
<form
onSubmit={formAdd.handleSubmit(onSubmitAdd)}
className="w-full flex flex-col mt-6 "
>
<div className="flex flex-col flex-wrap justify-between">
<FormField
control={formAdd.control}
name="title"
render={({ field }) => (
<FormItem className=" w-full ">
<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">
<FormLabel className="text-[#7C838A] text-sm font-medium ">
کلید عمومی
</FormLabel>
<FormControl>
<Textarea
placeholder="کلید عمومی را وارد کنید"
{...field}
className="bg-white resize-none"
dir="ltr"
/>
</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>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
{/* <AlertDialogCancel>بستن</AlertDialogCancel> */}
{/* <AlertDialogAction>Continue</AlertDialogAction> */}
</AlertDialogFooter>
</AlertDialogContent>
{/* 2 */}
<div className=" w-full flex justify-between items-center mt-1">
<div className="w-full text-right text-neutral-600 text-lg font-bold my-4">
لیست کلیدها
</div>
<AlertDialogTrigger asChild>
<Button
variant="outline"
className="bg-orange-500 hover:bg-orange-500/80 text-white hover:text-white"
// disabled={isNewKeyLoading}
>
افزودن کلید جدید
</Button>
</AlertDialogTrigger>
</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 bg-[#F5F5F5]
`}
>
<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>
</AlertDialog>
</div>
</div>
);
}