Compare commits

..

No commits in common. "main" and "v0.2.5" have entirely different histories.
main ... v0.2.5

66 changed files with 1477 additions and 3359 deletions

View File

@ -1,8 +0,0 @@
import ChangePhoneNumber from "@/components/ChangePhoneNumber";
import React from "react";
function page() {
return <ChangePhoneNumber />;
}
export default page;

View File

@ -1,6 +0,0 @@
import Profile from "@/components/ui/Profile";
import React from "react";
export default function page() {
return <Profile />;
}

View File

@ -1,6 +1,6 @@
'use client' // Error components must be Client Components 'use client' // Error components must be Client Components
// import { useEffect } from 'react' import { useEffect } from 'react'
export default function Error({ export default function Error({
error, error,
@ -9,20 +9,21 @@ export default function Error({
error: Error & { digest?: string } error: Error & { digest?: string }
reset: () => void reset: () => void
}) { }) {
// useEffect(() => { useEffect(() => {
// // Log the error to an error reporting service // Log the error to an error reporting service
// console.error(error) console.error(error)
// }, [error]) }, [error])
return ( return (
<div className="mx-auto text-gray-700 flex flex-col justify-center items-center gap-y-10 mt-6"> <div>
<h2>مشکلی پیش آمده ...!</h2> <h2>Something went wrong!</h2>
<button <button
className="text-white bg-blue hover:bg-blue50 p-2 w-fit rounded-md transition" onClick={
onClick={() => reset() // Attempt to recover by trying to re-render the segment
() => reset()
} }
> >
تلاش دوباره Try again
</button> </button>
</div> </div>
) )

View File

@ -8,7 +8,7 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const cookieStore = cookies(); const cookieStore = cookies();
const token = cookieStore.get("Sootzani_Admin_Token"); const token = cookieStore.get("Sootzani_Token");
if (!token?.value) { if (!token?.value) {
return redirect("/"); return redirect("/");
} }

View File

@ -1,8 +0,0 @@
import ChangePhoneNumber from "@/components/ChangePhoneNumber";
import React from "react";
function page() {
return <ChangePhoneNumber />;
}
export default page;

View File

@ -5,7 +5,7 @@ export default function page({ params }: { params: any }) {
const id = params.id; const id = params.id;
return ( return (
<div className="w-[90vw] sm:w-[90vw] lg:w-[85vw] xl:w-[75vw] 3xl:w-[70vw] mt-10 sm:mt-8 pt-9 mx-auto mb-6"> <div className="w-[90vw] sm:w-[90vw] lg:w-[85vw] xl:w-[75vw] 3xl:w-[70vw] mt-10 sm:mt-8 pt-9 mx-auto mb-10">
<ComplainsDetails role="Inspector" id={id} /> <ComplainsDetails role="Inspector" id={id} />
</div> </div>
); );

View File

@ -1,6 +0,0 @@
import Profile from "@/components/ui/Profile";
import React from "react";
export default function page() {
return <Profile />;
}

View File

@ -1,6 +1,6 @@
'use client' // Error components must be Client Components 'use client' // Error components must be Client Components
// import { useEffect } from 'react' import { useEffect } from 'react'
export default function Error({ export default function Error({
error, error,
@ -9,20 +9,21 @@ export default function Error({
error: Error & { digest?: string } error: Error & { digest?: string }
reset: () => void reset: () => void
}) { }) {
// useEffect(() => { useEffect(() => {
// // Log the error to an error reporting service // Log the error to an error reporting service
// console.error(error) console.error(error)
// }, [error]) }, [error])
return ( return (
<div className="mx-auto text-gray-700 flex flex-col justify-center items-center gap-y-10 mt-6"> <div>
<h2>مشکلی پیش آمده ...!</h2> <h2>Something went wrong!</h2>
<button <button
className="text-white bg-blue hover:bg-blue50 p-2 w-fit rounded-md transition" onClick={
onClick={() => reset() // Attempt to recover by trying to re-render the segment
() => reset()
} }
> >
تلاش دوباره Try again
</button> </button>
</div> </div>
) )

View File

@ -7,7 +7,7 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const cookieStore = cookies(); const cookieStore = cookies();
const token = cookieStore.get("Sootzani_Admin_Token"); const token = cookieStore.get("Sootzani_Token");
if (!token?.value) { if (!token?.value) {
return redirect("/"); return redirect("/");
} }

View File

@ -1,29 +0,0 @@
'use client' // Error components must be Client Components
// import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
// useEffect(() => {
// // Log the error to an error reporting service
// console.error(error)
// }, [error])
return (
<div className="mx-auto text-gray-700 flex flex-col justify-center items-center gap-y-10 mt-6">
<h2>مشکلی پیش آمده ...!</h2>
<button
className="text-white bg-blue hover:bg-blue50 p-2 w-fit rounded-md transition"
onClick={() => reset()
}
>
تلاش دوباره
</button>
</div>
)
}

View File

@ -1,10 +1,14 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css"; import "./globals.css";
import { Toaster } from "@/components/ui/toaster"; import { Toaster } from "@/components/ui/toaster";
import Provider from "../utils/ReactQuery/Provider"; import Navbar from "@/components/Navbar";
import NavbarSm from "@/components/NavbarSm";
import Provider from "../utils/Provider";
import { Toaster as SonnerToaster } from "@/components/ui/sonner"; import { Toaster as SonnerToaster } from "@/components/ui/sonner";
const inter = Inter({ subsets: ["latin"] });
import { Suspense } from "react";
import ProgressBarProviders from "@/components/PrograssBar"; import ProgressBarProviders from "@/components/PrograssBar";
import { EnvScript, PublicEnvScript } from "next-runtime-env";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "عیون", title: "عیون",
@ -18,14 +22,12 @@ export default function RootLayout({
}) { }) {
return ( return (
<html lang="fa" dir="rtl"> <html lang="fa" dir="rtl">
<head>
<PublicEnvScript />
</head>
<body className="font-[yekan] bg-white"> <body className="font-[yekan] bg-white">
<Provider> <Provider>
{/* <Suspense fallback={<Loading />}>{children}</Suspense> */}
<ProgressBarProviders>{children}</ProgressBarProviders> <ProgressBarProviders>{children}</ProgressBarProviders>
<Toaster /> <Toaster />
<SonnerToaster richColors /> <SonnerToaster />
</Provider> </Provider>
</body> </body>
</html> </html>

View File

@ -68,7 +68,7 @@ const AddCatFormSchema = z.object({
export default function AdminCategories() { export default function AdminCategories() {
const router = useRouter(); const router = useRouter();
// states
const [keyId, setKeyId] = useState(""); const [keyId, setKeyId] = useState("");
const [keyIdDel, setKeyIdDel] = useState(""); const [keyIdDel, setKeyIdDel] = useState("");
const [titleCat, setTitleCat] = useState(""); const [titleCat, setTitleCat] = useState("");
@ -88,6 +88,7 @@ export default function AdminCategories() {
} = useQuery({ } = useQuery({
queryKey: ["CategoriesList"], queryKey: ["CategoriesList"],
queryFn: () => GetAllCategories(), queryFn: () => GetAllCategories(),
// refetchOnWindowFocus: false,
}); });
// Edit // Edit
@ -138,6 +139,8 @@ export default function AdminCategories() {
mutationKey: ["ChangeCat"], mutationKey: ["ChangeCat"],
mutationFn: UpdateCategory, mutationFn: UpdateCategory,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
@ -158,6 +161,8 @@ export default function AdminCategories() {
mutationKey: ["DeleteCat"], mutationKey: ["DeleteCat"],
mutationFn: DeleteCategory, mutationFn: DeleteCategory,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
toast("عملیات شما با موفقیت انجام شد. ", { toast("عملیات شما با موفقیت انجام شد. ", {
@ -177,6 +182,8 @@ export default function AdminCategories() {
mutationKey: ["AddCat"], mutationKey: ["AddCat"],
mutationFn: SubmitCategory, mutationFn: SubmitCategory,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenAdd(false); setOpenAdd(false);
refetch1(); refetch1();
@ -207,18 +214,10 @@ export default function AdminCategories() {
description: data.description, description: data.description,
}); });
} }
const resetFormAdd = () => {
formAdd.reset({
titleCategory: "",
description: "",
});
};
return ( return (
<div className="w-full min-h-[85vh] flex justify-center"> <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 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
<div className="flex flex-row items-center justify-between w-full "> <div className="flex flex-row justify-between w-full ">
{/* 1 */} {/* 1 */}
<div className="w-full my-4 text-lg font-bold text-right text-neutral-600"> <div className="w-full my-4 text-lg font-bold text-right text-neutral-600">
لیست دسته بندی ها لیست دسته بندی ها
@ -243,12 +242,7 @@ export default function AdminCategories() {
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
افزودن دسته بندی افزودن دسته بندی
</p> </p>
<AlertDialogCancel <AlertDialogCancel className="h-auto p-0 border-0">
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose /> <IoMdClose />
</AlertDialogCancel> </AlertDialogCancel>
</AlertDialogTitle> </AlertDialogTitle>
@ -313,12 +307,7 @@ export default function AdminCategories() {
> >
افزودن افزودن
</Button> </Button>
<AlertDialogCancel <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
className="mt-0 text-white bg-blue rounded-xl"
onClick={() => {
resetFormAdd();
}}
>
بستن بستن
</AlertDialogCancel> </AlertDialogCancel>
</div> </div>
@ -339,7 +328,7 @@ export default function AdminCategories() {
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
ویرایش دسته بندی تغییر دسته بندی
</p> </p>
<AlertDialogCancel className="h-auto p-0 border-0"> <AlertDialogCancel className="h-auto p-0 border-0">
<IoMdClose /> <IoMdClose />
@ -395,7 +384,7 @@ export default function AdminCategories() {
type="submit" type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800" className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
> >
ویرایش دسته بندی تغییر دسته بندی
</Button> </Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl"> <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
@ -436,12 +425,16 @@ export default function AdminCategories() {
}); });
}} }}
id={item.id} id={item.id}
// onClick={() => handleClickDelete(item?.id)}
/> />
<AlertDialogTrigger asChild> <AlertDialogTrigger asChild>
{/* <Button variant="outline">Show Dialog</Button> */}
<FaRegEdit <FaRegEdit
aria-hidden="true" aria-hidden="true"
className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer" className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer"
// onClick={() => setKeyId(item?.id)}
onClick={() => onClick={() =>
handleClickEdit( handleClickEdit(
item?.id, item?.id,

View File

@ -1,12 +1,7 @@
"use client"; "use client";
import React, { useState, useRef, useEffect } from "react"; import React, { useState, useRef, useEffect } from "react";
import { import { useMutation, useQuery, RefetchOptions } from "@tanstack/react-query";
useMutation,
useQuery,
RefetchOptions,
useQueryClient,
} from "@tanstack/react-query";
import { GenerateKeyPair, GetKeys, AddKey, ChangeKey } from "@/utils/adminApi"; import { GenerateKeyPair, GetKeys, AddKey, ChangeKey } from "@/utils/adminApi";
import { FaRegEdit } from "react-icons/fa"; import { FaRegEdit } from "react-icons/fa";
import { IoMdClose } from "react-icons/io"; import { IoMdClose } from "react-icons/io";
@ -42,14 +37,28 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import * as z from "zod"; import * as z from "zod";
import { Textarea } from "./ui/textarea"; import { Textarea } from "./ui/textarea";
import { Check, KeyRound } from "lucide-react";
import { Progress } from "./ui/progress";
import { cn } from "@/lib/utils";
const MAX_FILE_SIZE = 5242880; // 5 MB const MAX_FILE_SIZE = 5242880; // 5 MB
// Edit Key Form // Edit Key Form
const FormSchemaEditKey = z.object({ const FormSchemaEditKey = z.object({
uploadPrivateKey: z.any(), 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 // Add Key Form
@ -64,19 +73,14 @@ const FormSchemaAddKey = z.object({
export default function AdminKeysManagement() { export default function AdminKeysManagement() {
const router = useRouter(); const router = useRouter();
const queryClient = useQueryClient();
const [keyId, setKeyId] = useState(""); const [keyId, setKeyId] = useState("");
const [done, setDone] = useState<number>(0);
const [total, setTotal] = useState<number>(0);
const [polling, setPolling] = useState<boolean>(false);
const [openAdd, setOpenAdd] = React.useState(false); const [openAdd, setOpenAdd] = React.useState(false);
const [openEdit, setOpenEdit] = React.useState(false); const [openEdit, setOpenEdit] = React.useState(false);
const inputPubRef = useRef<HTMLTextAreaElement | null>(null); const inputPubRef = useRef<HTMLTextAreaElement | null>(null);
const inputPrvRef = useRef<HTMLTextAreaElement | null>(null); const inputPrvRef = useRef<HTMLTextAreaElement | null>(null);
const intervalRef = useRef<NodeJS.Timeout | null>(null);
// ..............Read .txt
const [selectedFile, setSelectedFile] = useState<any>(null); const [selectedFile, setSelectedFile] = useState<any>(null);
const handleFileChange = (event: any) => { const handleFileChange = (event: any) => {
const file = event.target.files[0]; const file = event.target.files[0];
@ -103,31 +107,14 @@ export default function AdminKeysManagement() {
mutationKey: ["ChangeKey"], mutationKey: ["ChangeKey"],
mutationFn: ChangeKey, mutationFn: ChangeKey,
onSuccess: (res) => { onSuccess: (res) => {
if (res.total == res.done) { console.log(res);
localStorage.removeItem("isChangingKey"); // alert("Success");
setPolling(false); console.log("Success ChangeKey");
queryClient.invalidateQueries({ queryKey: ["KeysList"] });
if (res.failed == 0) {
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
} else if (res.failed > 0) {
toast("مشکلی در تغییر کلید به وجود آمد.", {
className: "!bg-red-500 !text-white",
});
}
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null; // Reset the ref value after clearing
}
} else {
localStorage.setItem("isChangingKey", "true");
setPolling(true);
}
setOpenEdit(false); setOpenEdit(false);
setDone(res.done);
setTotal(res.total); toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
// router.refresh() // router.refresh()
}, },
@ -142,7 +129,6 @@ export default function AdminKeysManagement() {
ChangeKeyMutation.mutate({ ChangeKeyMutation.mutate({
privateKey: selectedFile, privateKey: selectedFile,
publicKeyId: keyId, publicKeyId: keyId,
isPolling: false,
}); });
} }
@ -160,6 +146,9 @@ export default function AdminKeysManagement() {
mutationKey: ["AddKey"], mutationKey: ["AddKey"],
mutationFn: AddKey, mutationFn: AddKey,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success AddKey");
setOpenAdd(false); setOpenAdd(false);
refetch1(); refetch1();
@ -190,7 +179,7 @@ export default function AdminKeysManagement() {
publicKey: data.publicKey, publicKey: data.publicKey,
}); });
} }
// const { resetField } = useForm();
// List Keys // List Keys
const { const {
@ -202,6 +191,7 @@ export default function AdminKeysManagement() {
} = useQuery({ } = useQuery({
queryKey: ["KeysList"], queryKey: ["KeysList"],
queryFn: () => GetKeys(), queryFn: () => GetKeys(),
// refetchOnWindowFocus: false,
}); });
// GenerateKeyPair // GenerateKeyPair
@ -236,27 +226,6 @@ export default function AdminKeysManagement() {
} }
}, [handleClickGenerate]); }, [handleClickGenerate]);
const refethKey = () => {
ChangeKeyMutation.mutate({
privateKey: "",
publicKeyId: "cb7258da-64b0-4f43-b4f7-8ee11799d643",
isPolling: true,
});
};
useEffect(() => {
const isChangingKey = localStorage.getItem("isChangingKey");
if (isChangingKey) {
// setTimeout(() => {}, 1000);
intervalRef.current = setInterval(refethKey, 2000);
return () => {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null; // Reset the ref value after clearing
}
};
}
}, [polling]);
const saveTextFile = () => { const saveTextFile = () => {
const textToSave = data2?.privateKey ?? ""; const textToSave = data2?.privateKey ?? "";
const fileName = "privateKey.txt"; const fileName = "privateKey.txt";
@ -284,25 +253,9 @@ export default function AdminKeysManagement() {
saveTextFile(); saveTextFile();
} }
}, [AddKeyMutation.isSuccess]); }, [AddKeyMutation.isSuccess]);
const resetFormAdd = () => {
formAdd.reset({
title: "",
publicKey: "",
});
};
return ( return (
<div className="w-full min-h-[85vh] flex justify-center"> <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 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
{polling && (
<div className=" w-full md:w-1/2 mx-auto mt-2">
<p className=" font-bold test-sm">
درحال تغییر کلید({Math.floor((done * 100) / total)}%) ...
</p>
<Progress className=" mt-5" value={(done * 100) / total} />
</div>
)}
{/* 1 */} {/* 1 */}
<AlertDialog open={openAdd} onOpenChange={setOpenAdd}> <AlertDialog open={openAdd} onOpenChange={setOpenAdd}>
<AlertDialogContent className=""> <AlertDialogContent className="">
@ -311,12 +264,7 @@ export default function AdminKeysManagement() {
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
افزودن کلید جدید افزودن کلید جدید
</p> </p>
<AlertDialogCancel <AlertDialogCancel className="h-auto p-0 border-0">
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose /> <IoMdClose />
</AlertDialogCancel> </AlertDialogCancel>
</AlertDialogTitle> </AlertDialogTitle>
@ -369,11 +317,11 @@ export default function AdminKeysManagement() {
render={({ field }) => ( render={({ field }) => (
<FormItem className="w-full "> <FormItem className="w-full ">
<FormLabel className="text-[#7C838A] text-sm font-medium "> <FormLabel className="text-[#7C838A] text-sm font-medium ">
کلید خصوصی کلید عمومی
</FormLabel> </FormLabel>
<FormControl> <FormControl>
<Textarea <Textarea
placeholder="کلید خصوصی را وارد نمایید." placeholder="کلید عمومی را وارد کنید"
{...field} {...field}
className="bg-white resize-none" className="bg-white resize-none"
dir="ltr" dir="ltr"
@ -418,107 +366,118 @@ export default function AdminKeysManagement() {
</Button> </Button>
</AlertDialogTrigger> </AlertDialogTrigger>
</div> </div>
<div className="flex flex-row flex-wrap w-full gap-8 md:gap-4"> <div className="flex flex-row flex-wrap justify-between w-full gap-8 md:gap-4 ">
{data1?.map((item: any) => { {data1?.map((item: any) => {
return ( return (
<div <div
key={item.id} key={item.id}
className={cn( 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]
`flex flex-col justify-center gap-2 w-full md:w-[31%] lg:w-[23%] h-28 px-5 rounded-md shadow-md items-start bg-[#F5F5F5] `}
`,
item?.isActive && " border-r-4 border-green-600"
)}
> >
<div className=" flex gap-2 items-center"> <p className="text-sm font-normal leading-normal text-slate-500">
<div className=" p-2 bg-blue rounded-lg"> عنوان کلید:{" "}
<KeyRound className=" text-white" /> <span className=" text-slate-800">{item.title}</span>
</div> </p>
<p className="text-sm font-normal leading-normal text-slate-500"> <p className="text-sm font-normal leading-normal text-slate-500">
{/* عنوان کلید:{" "} */}
<span className=" text-slate-800">{item.title}</span>
</p>
</div>
{/* <p className="text-sm font-normal leading-normal text-slate-500">
آیدی بازرس:{" "} آیدی بازرس:{" "}
<span className="self-end text-slate-800"> <span className="self-end text-slate-800">
{item.inspectorId} {item.inspectorId}
</span> </span>
</p> */} </p>
{item?.isActive ? (
<Check className="self-end w-6 h-6 text-green-600" />
) : (
<AlertDialog open={openEdit} onOpenChange={setOpenEdit}>
<AlertDialogTrigger asChild>
{/* <Button variant="outline">Show Dialog</Button> */}
<FaRegEdit
aria-hidden="true"
className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer"
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="flex flex-col w-full 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="mt-2 bg-slate-300"
// {...field}
onChange={handleFileChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
<Button
type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
>
ویرایش کلید
</Button>
{/* <AlertDialogAction <AlertDialog open={openEdit} onOpenChange={setOpenEdit}>
<AlertDialogTrigger asChild>
{/* <Button variant="outline">Show Dialog</Button> */}
<FaRegEdit
aria-hidden="true"
className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer"
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="flex flex-col w-full 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="mt-2 bg-slate-300"
// {...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="mt-2 bg-slate-300"
value={item?.id}
readOnly={true}
// {...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/> */}
</div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
<Button
// href="/FollowResult"
type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
>
تغییر کلید
</Button>
{/* <AlertDialogAction
type="submit" type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800" className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
> >
تغییر کلید تغییر کلید
</AlertDialogAction> */} </AlertDialogAction> */}
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl"> <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
بستن بستن
</AlertDialogCancel> </AlertDialogCancel>
</div> </div>
</form> </form>
</Form> </Form>
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
{/* <AlertDialogAction>Continue</AlertDialogAction> */} {/* <AlertDialogAction>Continue</AlertDialogAction> */}
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
)}
</div> </div>
); );
})} })}

View File

@ -1,24 +1,24 @@
"use client"; "use client";
import React, { useState, useRef, useEffect } from "react"; import React, { useState, useRef, useEffect } from "react";
import { import { useMutation, useQuery, RefetchOptions } from "@tanstack/react-query";
useMutation,
useQuery,
RefetchOptions,
useQueryClient,
} from "@tanstack/react-query";
import { import {
GetAllNews, GetAllNews,
GetSingleNews, GetSingleNews,
SubmitNews, SubmitNews,
UpdateNews, UpdateNews,
DeleteNews, DeleteNews,
GetAllOrganizations,
GetSingleOrganization,
SubmitOrganization,
UpdateOrganization,
DeleteOrganization,
} from "@/utils/adminApi"; } from "@/utils/adminApi";
import { FaRegEdit } from "react-icons/fa"; import { FaRegEdit } from "react-icons/fa";
import { IoMdClose } from "react-icons/io"; import { IoMdClose } from "react-icons/io";
import { RiDeleteBin6Line } from "react-icons/ri"; import { RiDeleteBin6Line } from "react-icons/ri";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { ThreeDots, Triangle } from "react-loader-spinner"; import { ThreeDots } from "react-loader-spinner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { toast } from "sonner"; import { toast } from "sonner";
@ -51,7 +51,6 @@ import * as z from "zod";
import { Textarea } from "./ui/textarea"; import { Textarea } from "./ui/textarea";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import Image from "next/image"; import Image from "next/image";
import Pagination from "./Pagination";
const MAX_IMAGE_SIZE = 5242880; // 5 MB const MAX_IMAGE_SIZE = 5242880; // 5 MB
const ALLOWED_IMAGE_TYPES = [ const ALLOWED_IMAGE_TYPES = [
@ -124,16 +123,14 @@ export default function AdminNews() {
const [urlNews, setUrlNews] = useState(""); const [urlNews, setUrlNews] = useState("");
const [contentNews, setContentNews] = useState(""); const [contentNews, setContentNews] = useState("");
const [imageNews, setImageNews] = useState(""); const [imageNews, setImageNews] = useState("");
const [page, setPage] = useState<any>(1);
const [totalCount, setTotalCount] = useState<any>(0);
const [totalPages, setTotalPages] = useState<any>(0);
const [keyIdDel, setKeyIdDel] = useState(""); const [keyIdDel, setKeyIdDel] = useState("");
const [openAdd, setOpenAdd] = React.useState(false); const [openAdd, setOpenAdd] = React.useState(false);
const [openEdit, setOpenEdit] = React.useState(false); const [openEdit, setOpenEdit] = React.useState(false);
const [delOrg, setDelOrg] = React.useState(false); const [delOrg, setDelOrg] = React.useState(false);
const queryClient = useQueryClient();
// List News // List News
const { const {
data: data1, data: data1,
@ -141,23 +138,12 @@ export default function AdminNews() {
isLoading: isListLoading, isLoading: isListLoading,
refetch: refetch1, refetch: refetch1,
} = useQuery({ } = useQuery({
queryKey: ["NewsList", page], queryKey: ["NewsList"],
queryFn: () => queryFn: () => GetAllNews(),
GetAllNews({ // queryFn: () => GetAllOrganizations(),
PageNumber: page, // refetchOnWindowFocus: false,
}),
});
const {
data: data2,
error: Error2,
isLoading: isLoading2,
refetch: refetch2,
} = useQuery({
queryKey: ["News", keyId],
queryFn: () => GetSingleNews(keyId),
enabled: false,
}); });
console.log(data1);
// Edit // Edit
const handleClickEdit = ( const handleClickEdit = (
@ -175,26 +161,17 @@ export default function AdminNews() {
setUrlNews(url); setUrlNews(url);
setContentNews(content); setContentNews(content);
setImageNews(image); setImageNews(image);
// Reset the form with new default values // Reset the form with new default values
formEdit.reset({
titleNews: title,
description: description,
urlNews: url,
content: content,
// uploadImg:image
});
}; };
useEffect(() => {
if (keyId) {
refetch2();
}
}, [keyId]);
useEffect(() => {
if (data2) {
formEdit.reset({
titleNews: data2.title,
description: data2.description,
urlNews: data2.url,
content: data2.content,
});
}
}, [data2]);
// Form Edit // Form Edit
type EditNewsFormValues = z.infer<typeof EditNewsFormSchema>; type EditNewsFormValues = z.infer<typeof EditNewsFormSchema>;
// This can come from your database or API. // This can come from your database or API.
@ -233,6 +210,8 @@ export default function AdminNews() {
mutationKey: ["ChangeNews"], mutationKey: ["ChangeNews"],
mutationFn: UpdateNews, mutationFn: UpdateNews,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success Change News");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
@ -253,6 +232,8 @@ export default function AdminNews() {
mutationKey: ["DeleteNews"], mutationKey: ["DeleteNews"],
mutationFn: DeleteNews, mutationFn: DeleteNews,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success Change News");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
toast("عملیات شما با موفقیت انجام شد. ", { toast("عملیات شما با موفقیت انجام شد. ", {
@ -272,6 +253,8 @@ export default function AdminNews() {
mutationKey: ["AddNews"], mutationKey: ["AddNews"],
mutationFn: SubmitNews, mutationFn: SubmitNews,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success Change News");
setOpenAdd(false); setOpenAdd(false);
refetch1(); refetch1();
@ -279,23 +262,11 @@ export default function AdminNews() {
toast("عملیات شما با موفقیت انجام شد. ", { toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white", className: "!bg-green-500 !text-white",
}); });
formAdd.reset({
titleNews: "",
urlNews: "",
content: "",
description: "",
});
}, },
onError: (err: any | string) => { onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, { toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white", className: "!bg-red-500 !text-white",
}); });
formAdd.reset({
titleNews: "",
urlNews: "",
content: "",
description: "",
});
}, },
}); });
@ -315,7 +286,15 @@ export default function AdminNews() {
// } // }
// } // }
ChangeNewsMutation.mutate({ id: keyId, payload: formData }); ChangeNewsMutation.mutate({ id: keyId, payload: formData });
refetch1(); refetch1();
resetField("Title");
resetField("Image");
resetField("Url");
resetField("Description");
resetField("Content");
console.log(data);
} }
const { resetField } = useForm(); const { resetField } = useForm();
@ -331,30 +310,14 @@ export default function AdminNews() {
} }
AddNewsMutation.mutate(formData); AddNewsMutation.mutate(formData);
console.log(data);
} }
useEffect(() => {
if (data1) {
const headersData = JSON.parse(data1.headers["x-pagination"]);
setTotalCount(headersData.TotalCount);
setTotalPages(headersData.TotalPages);
setPage(headersData.CurrentPage);
}
}, [data1]);
const resetFormAdd = () => {
formAdd.reset({
titleNews: "",
urlNews: "",
content: "",
description: "",
});
};
return ( return (
<div className="w-full min-h-[85vh] flex justify-center max-lg:pb-20"> <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 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
<div className="flex flex-row items-center justify-between w-full "> <div className="flex flex-row justify-between w-full ">
{/* 1 */} {/* 1 */}
<div className="w-full my-4 text-lg font-bold text-right text-neutral-600"> <div className="w-full my-4 text-lg font-bold text-right text-neutral-600">
لیست خبر ها لیست خبر ها
@ -379,12 +342,7 @@ export default function AdminNews() {
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
افزودن خبر افزودن خبر
</p> </p>
<AlertDialogCancel <AlertDialogCancel className="h-auto p-0 border-0">
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose /> <IoMdClose />
</AlertDialogCancel> </AlertDialogCancel>
</AlertDialogTitle> </AlertDialogTitle>
@ -537,12 +495,7 @@ export default function AdminNews() {
> >
افزودن افزودن
</Button> </Button>
<AlertDialogCancel <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
className="mt-0 text-white bg-blue rounded-xl"
onClick={() => {
resetFormAdd();
}}
>
بستن بستن
</AlertDialogCancel> </AlertDialogCancel>
</div> </div>
@ -563,7 +516,7 @@ export default function AdminNews() {
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
ویرایش خبر تغییر خبر
</p> </p>
<AlertDialogCancel className="h-auto p-0 border-0"> <AlertDialogCancel className="h-auto p-0 border-0">
<IoMdClose /> <IoMdClose />
@ -714,7 +667,7 @@ export default function AdminNews() {
type="submit" type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800" className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
> >
ویرایش خبر تغییر خبر
</Button> </Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl"> <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
@ -728,80 +681,71 @@ export default function AdminNews() {
<AlertDialogFooter></AlertDialogFooter> <AlertDialogFooter></AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
{data1?.data?.map((item: any) => { {data1?.map((item: any) => {
return ( return (
<div <div
key={item.id} key={item.id}
className={`w-full lg:w-[48%] bg-[#F5F5F5] border rounded-lg flex flex-row shadow-md transition-all className={`flex flex-col justify-center gap-2 w-full lg:w-[49%] h-56 px-5 rounded-md shadow-md items-start bg-[#F5F5F5]
h-[20em] sm:h-[15em] max-sm:flex-col max-sm:gap-[3px]
`} `}
> >
<div className="w-1/2 h-full rounded-r-lg max-sm:h-1/2 max-md:w-1/3 max-sm:w-full"> <p className="text-sm font-normal leading-normal text-slate-500">
<Image عنوان :
alt="picture" <span className=" text-slate-800">{item.title}</span>
</p>
<p className="text-sm font-normal leading-normal text-slate-500">
توضیحات:
<span className="self-end text-slate-800">
{item.description}
</span>
</p>
<p className="text-sm font-normal leading-normal text-slate-500">
محتوا:
<span className="self-end text-slate-800">
{item.content}
</span>
</p>
<Image
alt="img"
src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`} src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`}
height={500} width={100}
width={500} height={100}
quality={100} quality={100}
className="w-full h-full rounded-r-lg bg-cover object-cover" className="object-contain object-right w-full h-20 "
/> />
</div>
<div className="w-1/2 h-full flex flex-col p-3 justify-between max-md:justify-evenly max-md:w-2/3 max-sm:h-1/2 max-sm:w-full">
<div>
<p className="text-sm font-normal leading-normal text-slate-500">
عنوان :
<span className=" text-slate-800">{item.title}</span>
</p>
<p className="text-sm font-normal leading-normal text-slate-500">
توضیحات:
<span className="self-end text-slate-800 line-clamp-4">
{item.description}
</span>
</p>
</div>
<div className="flex items-end justify-end w-full gap-2">
<Switch
dir="ltr"
checked={!item.isDeleted}
onCheckedChange={() => {
DeleteNewsMutation.mutate({ id: item.id });
}}
id={item.id}
/>
<AlertDialogTrigger asChild> <div className="flex items-end justify-end w-full gap-2">
{/* <Button variant="outline">Show Dialog</Button> */} <Switch
<FaRegEdit dir="ltr"
aria-hidden="true" checked={!item.isDeleted}
className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer" onCheckedChange={() => {
// onClick={() => setKeyId(item?.id)} DeleteNewsMutation.mutate({id: item.id});
onClick={() => }}
handleClickEdit( id={item.id}
item?.id, />
item?.title,
item?.description, <AlertDialogTrigger asChild>
item?.content, {/* <Button variant="outline">Show Dialog</Button> */}
item?.url, <FaRegEdit
item?.image aria-hidden="true"
) className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer"
} // onClick={() => setKeyId(item?.id)}
/> onClick={() =>
</AlertDialogTrigger> handleClickEdit(
</div> item?.id,
item?.title,
item?.description,
item?.content,
item?.url,
item?.image
)
}
/>
</AlertDialogTrigger>
</div> </div>
</div> </div>
); );
})} })}
</AlertDialog> </AlertDialog>
{!isListLoading && (
<Pagination
TotalPages={totalPages}
currentPage={page - 1}
PageSize={5}
countPage={totalCount}
Page={(num: number) => setPage(num + 1)}
/>
)}
</div> </div>
</div> </div>
</div> </div>

View File

@ -76,8 +76,10 @@ export default function AdminOrganizations() {
const [keyIdDel, setKeyIdDel] = useState(""); const [keyIdDel, setKeyIdDel] = useState("");
const [titleOrg, setTitleOrg] = useState(""); const [titleOrg, setTitleOrg] = useState("");
const [descOrg, setDescOrg] = useState(""); const [descOrg, setDescOrg] = useState("");
const [openAdd, setOpenAdd] = React.useState(false); const [openAdd, setOpenAdd] = React.useState(false);
const [openEdit, setOpenEdit] = React.useState(false); const [openEdit, setOpenEdit] = React.useState(false);
const [delOrg, setDelOrg] = React.useState(false); const [delOrg, setDelOrg] = React.useState(false);
// List Categories // List Categories
@ -133,12 +135,15 @@ export default function AdminOrganizations() {
defaultValues: defaultValuesAdd, defaultValues: defaultValuesAdd,
mode: "onChange", mode: "onChange",
}); });
// Edit Submit
// ............'Mutation' Change Key Submit
const ChangeOrgMutation = useMutation({ const ChangeOrgMutation = useMutation({
mutationKey: ["ChangeOrg"], mutationKey: ["ChangeOrg"],
mutationFn: UpdateOrganization, mutationFn: UpdateOrganization,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
@ -159,6 +164,8 @@ export default function AdminOrganizations() {
mutationKey: ["DeleteOrg"], mutationKey: ["DeleteOrg"],
mutationFn: DeleteOrganization, mutationFn: DeleteOrganization,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenEdit(false); setOpenEdit(false);
refetch1(); refetch1();
toast("عملیات شما با موفقیت انجام شد. ", { toast("عملیات شما با موفقیت انجام شد. ", {
@ -178,6 +185,8 @@ export default function AdminOrganizations() {
mutationKey: ["AddOrg"], mutationKey: ["AddOrg"],
mutationFn: SubmitOrganization, mutationFn: SubmitOrganization,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setOpenAdd(false); setOpenAdd(false);
refetch1(); refetch1();
@ -202,25 +211,16 @@ export default function AdminOrganizations() {
}, },
}); });
} }
function onSubmitAdd(data: AddOrgFormValues) { function onSubmitAdd(data: AddOrgFormValues) {
AddOrgMutation.mutate({ AddOrgMutation.mutate({
title: data.titleOrg, title: data.titleOrg,
description: data.description, description: data.description,
}); });
} }
const resetFormAdd = () => {
formAdd.reset({
titleOrg: "",
description: "",
});
};
return ( return (
<div className="w-full min-h-[85vh] flex justify-center"> <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 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
<div className="flex flex-row items-center justify-between w-full "> <div className="flex flex-row justify-between w-full ">
{/* 1 */} {/* 1 */}
<div className="w-full my-4 text-lg font-bold text-right text-neutral-600"> <div className="w-full my-4 text-lg font-bold text-right text-neutral-600">
لیست سازمان ها لیست سازمان ها
@ -245,7 +245,7 @@ export default function AdminOrganizations() {
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
افزودن سازمان افزودن سازمان
</p> </p>
<AlertDialogCancel className="h-auto p-0 border-0" onClick={() => { resetFormAdd(); }}> <AlertDialogCancel className="h-auto p-0 border-0">
<IoMdClose /> <IoMdClose />
</AlertDialogCancel> </AlertDialogCancel>
</AlertDialogTitle> </AlertDialogTitle>
@ -310,7 +310,7 @@ export default function AdminOrganizations() {
> >
افزودن افزودن
</Button> </Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl" onClick={() => { resetFormAdd(); }}> <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
بستن بستن
</AlertDialogCancel> </AlertDialogCancel>
</div> </div>

View File

@ -139,6 +139,7 @@ export default function AdminSlider() {
queryFn: () => GetAllSliders(), queryFn: () => GetAllSliders(),
// refetchOnWindowFocus: false, // refetchOnWindowFocus: false,
}); });
console.log(data1);
// Edit // Edit
const handleClickEdit = ( const handleClickEdit = (
@ -195,121 +196,115 @@ export default function AdminSlider() {
}); });
// Edit Submit // Edit Submit
// ............'Mutation' Change Slider Submit
const ChangeSliderMutation = useMutation({
mutationKey: ["ChangeSlider"],
mutationFn: UpdateSlider,
onSuccess: (res) => {
setOpenEdit(false);
refetch1(); // ............'Mutation' Change Slider Submit
const ChangeSliderMutation = useMutation({
toast("عملیات شما با موفقیت انجام شد. ", { mutationKey: ["ChangeSlider"],
className: "!bg-green-500 !text-white", mutationFn: UpdateSlider,
}); onSuccess: (res) => {
}, console.log(res);
onError: (err: any | string) => { console.log("Success Change Slider");
toast(<>{err.response.data.detail}</>, { setOpenEdit(false);
className: "!bg-red-500 !text-white",
});
},
});
//Delete
const DeleteSliderMutation = useMutation({
mutationKey: ["DeleteSlider"],
mutationFn: DeleteSlider,
onSuccess: (res) => {
setOpenEdit(false);
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
// Add
// ............'Mutation' Add Slider Submit
const AddSliderMutation = useMutation({
mutationKey: ["AddSlider"],
mutationFn: SubmitSlider,
onSuccess: (res) => {
setOpenAdd(false);
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
formAdd.reset({
titleSlider: "",
uploadImg: null,
urlSlider: "",
description: "",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
formAdd.reset({
titleSlider: "",
uploadImg: null,
urlSlider: "",
description: "",
});
},
});
function onSubmitEdit(data: EditSliderFormValues) {
const formData = new FormData();
formData.append("Title", data.titleSlider);
if (data?.uploadImg instanceof File) {
formData.append("Image", data.uploadImg);
}
formData.append("Url", data.urlSlider);
formData.append("Description", data.description);
// if (data?.media && data?.media?.length > 0) {
// for (let i = 0; i < data.media.length; i++) {
// formData.append("Medias", data.media[i]);
// }
// }
ChangeSliderMutation.mutate({ id: keyId, payload: formData });
refetch1(); refetch1();
}
function onSubmitAdd(data: AddSliderFormValues) { toast("عملیات شما با موفقیت انجام شد. ", {
const formData = new FormData(); className: "!bg-green-500 !text-white",
formData.append("Title", data.titleSlider);
formData.append("Url", data.urlSlider);
formData.append("Description", data.description);
if (data?.uploadImg instanceof File) {
formData.append("Image", data.uploadImg);
}
AddSliderMutation.mutate(formData);
}
const resetFormAdd = () => {
formAdd.reset({
titleSlider: "",
uploadImg: null,
urlSlider: "",
description: "",
}); });
}; },
const { resetField } = useForm(); onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
//Delete
const DeleteSliderMutation = useMutation({
mutationKey: ["DeleteSlider"],
mutationFn: DeleteSlider,
onSuccess: (res) => {
console.log(res);
console.log("Success Change Slider");
setOpenEdit(false);
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
// Add
// ............'Mutation' Add Slider Submit
const AddSliderMutation = useMutation({
mutationKey: ["AddSlider"],
mutationFn: SubmitSlider,
onSuccess: (res) => {
console.log(res);
console.log("Success Change Slider");
setOpenAdd(false);
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
function onSubmitEdit(data: EditSliderFormValues) {
const formData = new FormData();
formData.append("Title", data.titleSlider);
if (data?.uploadImg instanceof File) {
formData.append("Image", data.uploadImg);
}
formData.append("Url", data.urlSlider);
formData.append("Description", data.description);
// if (data?.media && data?.media?.length > 0) {
// for (let i = 0; i < data.media.length; i++) {
// formData.append("Medias", data.media[i]);
// }
// }
ChangeSliderMutation.mutate({id: keyId, payload: formData});
refetch1();
resetField("Title");
resetField("Image");
resetField("Url");
resetField("Description");
}
const { resetField } = useForm();
function onSubmitAdd(data: AddSliderFormValues) {
const formData = new FormData();
formData.append("Title", data.titleSlider);
formData.append("Url", data.urlSlider);
formData.append("Description", data.description);
if (data?.uploadImg instanceof File) {
formData.append("Image", data.uploadImg);
}
AddSliderMutation.mutate(formData);
}
return ( return (
<div className="w-full min-h-[85vh] flex justify-center"> <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 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
<div className="flex flex-row items-center justify-between w-full "> <div className="flex flex-row justify-between w-full ">
{/* 1 */} {/* 1 */}
<div className="w-full my-4 text-lg font-bold text-right text-neutral-600"> <div className="w-full my-4 text-lg font-bold text-right text-neutral-600">
لیست اسلایدرها لیست اسلایدرها
@ -334,12 +329,7 @@ export default function AdminSlider() {
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
افزودن اسلایدر افزودن اسلایدر
</p> </p>
<AlertDialogCancel <AlertDialogCancel className="h-auto p-0 border-0">
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose /> <IoMdClose />
</AlertDialogCancel> </AlertDialogCancel>
</AlertDialogTitle> </AlertDialogTitle>
@ -466,6 +456,7 @@ export default function AdminSlider() {
</FormItem> </FormItem>
)} )}
/> />
</div> </div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end"> <div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
@ -475,12 +466,7 @@ export default function AdminSlider() {
> >
افزودن افزودن
</Button> </Button>
<AlertDialogCancel <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
className="mt-0 text-white bg-blue rounded-xl"
onClick={() => {
resetFormAdd();
}}
>
بستن بستن
</AlertDialogCancel> </AlertDialogCancel>
</div> </div>
@ -501,7 +487,7 @@ export default function AdminSlider() {
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>
<p className="text-[#464646] text-base font-bold"> <p className="text-[#464646] text-base font-bold">
ویرایش اسلایدر تغییر اسلایدر
</p> </p>
<AlertDialogCancel className="h-auto p-0 border-0"> <AlertDialogCancel className="h-auto p-0 border-0">
<IoMdClose /> <IoMdClose />
@ -628,6 +614,7 @@ export default function AdminSlider() {
</FormItem> </FormItem>
)} )}
/> />
</div> </div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end"> <div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
@ -635,7 +622,7 @@ export default function AdminSlider() {
type="submit" type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800" className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
> >
ویرایش اسلایدر تغییر اسلایدر
</Button> </Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl"> <AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
@ -653,70 +640,64 @@ export default function AdminSlider() {
return ( return (
<div <div
key={item.id} key={item.id}
className={`w-full lg:w-[48%] bg-[#F5F5F5] border rounded-lg flex flex-row shadow-md transition-all className={`flex flex-col justify-around gap-2 w-full lg:w-[49%] h-52 px-5 rounded-md shadow-md items-start bg-[#F5F5F5]
h-[20em] sm:h-[15em] max-sm:flex-col max-sm:gap-[3px]
`} `}
> >
<div className="w-1/2 h-full rounded-r-lg max-sm:h-1/2 max-md:w-1/3 max-sm:w-full"> <p className="text-sm font-normal leading-normal text-slate-500">
<Image عنوان :
alt="picture" <span className=" text-slate-800">{item.title}</span>
</p>
<p className="text-sm font-normal leading-normal text-slate-500">
توضیحات:
<span className="self-end text-slate-800">
{item.description}
</span>
</p>
<Image
alt="img"
src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`} src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`}
height={500} width={100}
width={500} height={100}
quality={100} quality={100}
className="w-full h-full rounded-r-lg bg-cover object-cover" className="object-contain object-right w-full h-20 "
/> />
</div>
<div className="w-1/2 h-full flex flex-col p-3 justify-between max-md:justify-evenly max-md:w-2/3 max-sm:h-1/2 max-sm:w-full"> {/* <p className="text-sm font-normal leading-normal text-slate-500">
<div>
<p className="text-sm font-normal leading-normal text-slate-500">
عنوان :
<span className=" text-slate-800">{item.title}</span>
</p>
<p className="text-sm font-normal leading-normal text-slate-500">
توضیحات:
<span className="self-end text-slate-800 line-clamp-4">
{item.description}
</span>
</p>
</div>
{/* <p className="text-sm font-normal leading-normal text-slate-500">
محتوا: محتوا:
<span className="self-end text-slate-800"> <span className="self-end text-slate-800">
{item.content} {item.content}
</span> </span>
</p> */} </p> */}
<div className="flex items-end justify-end w-full gap-2"> <div className="flex items-end justify-end w-full gap-2">
<Switch <Switch
dir="ltr" dir="ltr"
checked={!item.isDeleted} checked={!item.isDeleted}
onCheckedChange={() => { onCheckedChange={() => {
DeleteSliderMutation.mutate({ DeleteSliderMutation.mutate({
id: item.id, id: item.id
}); })
}} }}
id={item.id} id={item.id}
/> />
<AlertDialogTrigger asChild> <AlertDialogTrigger asChild>
{/* <Button variant="outline">Show Dialog</Button> */} {/* <Button variant="outline">Show Dialog</Button> */}
<FaRegEdit <FaRegEdit
aria-hidden="true" aria-hidden="true"
className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer" className="self-end w-6 h-6 text-slate-600 hover:cursor-pointer"
// onClick={() => setKeyId(item?.id)} // onClick={() => setKeyId(item?.id)}
onClick={() => onClick={() =>
handleClickEdit( handleClickEdit(
item?.id, item?.id,
item?.title, item?.title,
item?.description, item?.description,
item?.url, item?.url,
item?.image item?.image
) )
} }
/> />
</AlertDialogTrigger> </AlertDialogTrigger>
</div>
</div> </div>
</div> </div>
); );

View File

@ -35,7 +35,7 @@ export default function AdminUserManagement() {
<div className="w-full flex flex-col lg:flex-row justify-center items-center gap-6 "> <div className="w-full flex flex-col lg:flex-row justify-center items-center gap-6 ">
<div className="w-full lg:w-3/5 h-11 bg-white rounded-[5px] block"> <div className="w-full lg:w-3/5 h-11 bg-white rounded-[5px] block">
{/* <Search Cancel={} mode="admin" /> */} <Search mode="admin" />
</div> </div>
<div className="w-full lg:w-2/5 flex flex-row justify-between items-center gap-2 "> <div className="w-full lg:w-2/5 flex flex-row justify-between items-center gap-2 ">

View File

@ -9,6 +9,7 @@ import { getContents } from "@/utils/commonApi";
import { toast } from "sonner"; import { toast } from "sonner";
export default function AdminWebContents() { export default function AdminWebContents() {
const [contentValueCall, setContentValueCall] = useState(""); const [contentValueCall, setContentValueCall] = useState("");
const [contentValueAbout, setContentValueAbout] = useState(""); const [contentValueAbout, setContentValueAbout] = useState("");
const [contentValueAfter, setContentValueAfter] = useState(""); const [contentValueAfter, setContentValueAfter] = useState("");
@ -75,37 +76,39 @@ export default function AdminWebContents() {
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
}); });
useEffect(() => { useEffect(() => {
// if (isInitialRender2 && isSuccess1) { // if (isInitialRender2 && isSuccess1) {
if (isSuccess1) { if (isSuccess1) {
// { // {
data1?.map((item: any) => { data1?.map((item: any) => {
if (item.title === "CallUs") { if (item.title === "CallUs") {
setContentValueCall(item.content); setContentValueCall(item.content);
setCallId(item.id); setCallId(item.id);
setCallBtn("Edit"); setCallBtn("Edit");
} }
if (item.title === "AboutUs") { if (item.title === "AboutUs") {
setContentValueAbout(item.content); setContentValueAbout(item.content);
setAboutId(item.id); setAboutId(item.id);
setAboutBtn("Edit"); setAboutBtn("Edit");
} }
if (item.title === "AfterRegistration") { if (item.title === "AfterRegistration") {
setContentValueAfter(item.content); setContentValueAfter(item.content);
setAfterId(item.id); setAfterId(item.id);
setAfterBtn("Edit"); setAfterBtn("Edit");
} }
if (item.title === "BeforeRegistration") { if (item.title === "BeforeRegistration") {
setContentValueBefore(item.content); setContentValueBefore(item.content);
setBeforeId(item.id); setBeforeId(item.id);
setBeforeBtn("Edit"); setBeforeBtn("Edit");
} }
}); });
} }
}, [isSuccess1, refetch1]); }, [isSuccess1]);
// Add // Add
// ............'Mutation' Change Key Submit // ............'Mutation' Change Key Submit
@ -113,6 +116,9 @@ export default function AdminWebContents() {
mutationKey: ["AddWebContents"], mutationKey: ["AddWebContents"],
mutationFn: SubmitWebContents, mutationFn: SubmitWebContents,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success ChangeCat");
setContentValueCall(""); setContentValueCall("");
setContentValueAbout(""); setContentValueAbout("");
setContentValueAfter(""); setContentValueAfter("");
@ -127,7 +133,6 @@ export default function AdminWebContents() {
toast(<>{err.response.data.detail}</>, { toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white", className: "!bg-red-500 !text-white",
}); });
refetch1();
}, },
}); });
@ -136,6 +141,9 @@ export default function AdminWebContents() {
mutationKey: ["EditWebContents"], mutationKey: ["EditWebContents"],
mutationFn: UpdateWebContents, mutationFn: UpdateWebContents,
onSuccess: (res) => { onSuccess: (res) => {
console.log(res);
console.log("Success Change UpdateWebContents");
toast("عملیات ویرایش شما با موفقیت انجام شد . ", { toast("عملیات ویرایش شما با موفقیت انجام شد . ", {
className: "!bg-green-500 !text-white", className: "!bg-green-500 !text-white",
}); });
@ -145,7 +153,6 @@ export default function AdminWebContents() {
toast(<>{err.response.data.detail}</>, { toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white", className: "!bg-red-500 !text-white",
}); });
refetch1();
}, },
}); });
@ -224,7 +231,7 @@ export default function AdminWebContents() {
return ( return (
<div className="w-full min-h-[85vh] flex justify-center"> <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 pb-6 "> <div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
{/* Cull Us */} {/* Cull Us */}
<div className="flex flex-col w-full"> <div className="flex flex-col w-full">
<div className="my-4 text-base font-bold text-right text-neutral-600"> <div className="my-4 text-base font-bold text-right text-neutral-600">
@ -271,9 +278,9 @@ export default function AdminWebContents() {
<Button <Button
type="submit" type="submit"
onClick={() => { onClick={() => {
if (aboutBtn === "Add") { if (callBtn === "Add") {
onSubmitAddAboutUs(); onSubmitAddAboutUs();
} else if (aboutBtn === "Edit") { } else if (callBtn === "Edit") {
onEditAboutUs(); onEditAboutUs();
} }
}} }}
@ -283,34 +290,6 @@ export default function AdminWebContents() {
</Button> </Button>
</div> </div>
{/* BeforeRegistration*/}
<div className="flex flex-col w-full">
<div className="my-4 text-base font-bold text-right text-neutral-600">
محتوای قبل از ثبت گزارش
</div>
<ReactQuill
modules={modules}
theme="snow"
value={contentValueBefore}
onChange={setContentValueBefore}
style={editorStyles}
/>
<Button
type="submit"
onClick={() => {
if (beforeBtn === "Add") {
onSubmitAddBeforeText();
} else if (beforeBtn === "Edit") {
onEditBeforeText();
}
}}
className="self-end w-1/6 my-2"
>
ثبت
</Button>
</div>
{/* AfterRegistration */} {/* AfterRegistration */}
<div className="flex flex-col w-full"> <div className="flex flex-col w-full">
<div className="my-4 text-base font-bold text-right text-neutral-600"> <div className="my-4 text-base font-bold text-right text-neutral-600">
@ -327,9 +306,9 @@ export default function AdminWebContents() {
<Button <Button
type="submit" type="submit"
onClick={() => { onClick={() => {
if (afterBtn === "Add") { if (callBtn === "Add") {
onSubmitAddَAfterText(); onSubmitAddَAfterText();
} else if (afterBtn === "Edit") { } else if (callBtn === "Edit") {
onEditAfterText(); onEditAfterText();
} }
}} }}
@ -338,6 +317,34 @@ export default function AdminWebContents() {
ثبت ثبت
</Button> </Button>
</div> </div>
{/* BeforeRegistration*/}
<div className="flex flex-col w-full">
<div className="my-4 text-base font-bold text-right text-neutral-600">
محتوای قبل از ثبت گزارش
</div>
<ReactQuill
modules={modules}
theme="snow"
value={contentValueBefore}
onChange={setContentValueBefore}
style={editorStyles}
/>
<Button
type="submit"
onClick={() => {
if (callBtn === "Add") {
onSubmitAddBeforeText();
} else if (callBtn === "Edit") {
onEditBeforeText();
}
}}
className="self-end w-1/6 my-2"
>
ثبت
</Button>
</div>
</div> </div>
</div> </div>
); );

View File

@ -1,108 +0,0 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { X } from "lucide-react";
import { Button } from "./ui/button";
export default function AttachmentsDialog({
children,
attachments,
deleteFile,
deleteAllAttachmentsFiles,
}: {
children: React.ReactNode;
attachments: File[] | [];
deleteFile: (file: any) => void;
deleteAllAttachmentsFiles: () => void;
}) {
return (
<Dialog>
{children}
<DialogContent className=" max-h-[95vh] overflow-y-auto max-sm:p-0">
<AlertDialog>
<DialogHeader>
<DialogTitle className=" mt-7">پیوست‌ها</DialogTitle>
<DialogDescription className="max-md:px-2 py-5 w-full">
{attachments.length != 0 && (
<AlertDialogTrigger>
<Button className=" mb-2 absolute right-3 top-1 p-1 bg-white hover:bg-white text-red-600 ">
حذف همه
</Button>{" "}
</AlertDialogTrigger>
)}
{attachments.length == 0 ? (
<div className=" text-center my-5">هیج پیوستی وجود ندارد.</div>
) : (
<div className=" flex flex-col gap-2 mt-2 h-full mx-2">
{attachments?.map((item, index) => {
return (
<div
key={index}
className=" flex gap-2 w-full items-center"
>
<div className=" p-2 bg-blue w-10 grid place-content-center rounded-lg text-white">
{index + 1}
</div>
<div className="bg-gray-200 p-2 rounded-lg max-w-full justify-between flex flex-1">
<div className="">
<p className=" truncate max-w-[16rem]">
{item.name}
</p>
</div>
<X
onClick={() => deleteFile(item.name)}
className=" cursor-pointer hover:drop-shadow-md"
/>
</div>
</div>
);
})}
</div>
)}
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
آیا میخواهید همه ی فایل ها را حذف کنید؟
</AlertDialogTitle>
<AlertDialogDescription></AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter className=" gap-2">
<AlertDialogCancel className=" flex-1">
لغو
</AlertDialogCancel>
<AlertDialogAction
className=" flex-1"
onClick={() => deleteAllAttachmentsFiles()}
>
تایید
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</DialogDescription>
</DialogHeader>
</AlertDialog>
</DialogContent>
</Dialog>
);
}

View File

@ -1,4 +1,3 @@
import { ClipboardList, EyeOff, Info, User, UserCheck } from "lucide-react";
import React from "react"; import React from "react";
export default function BoxDashboard({ export default function BoxDashboard({
@ -7,32 +6,18 @@ export default function BoxDashboard({
}: { }: {
value: string; value: string;
title: string; title: string;
}) { }) {
const boxIcons = {
"گزارش ناشناس": <EyeOff className=" mb-2 mx-auto" />,
"گزارش شناس": <UserCheck className=" mb-2 mx-auto" />,
گزارش: <ClipboardList className=" mb-2 mx-auto" />,
کاربر: <User className=" mb-2 mx-auto" />,
};
const checkIcon = boxIcons[title as keyof typeof boxIcons] ? (
boxIcons[title as keyof typeof boxIcons]
) : (
<Info className=" mb-2 mx-auto" />
);
return ( return (
<div <div
className=" px-7 py-8 bg-zinc-100 rounded-lg shadow flex flex-col justify-evenly items-center text-black className=" px-7 py-8 bg-zinc-100 rounded-lg shadow flex flex-col justify-end items-center text-black
transition duration-200 transition duration-200
hover:text-white hover:bg-blue hover:text-white hover:bg-blue
group h-44 w-44" group h-44 w-44"
> >
{checkIcon ? checkIcon : <Info className=" mb-2 mx-auto" />} <div className="group-hover:-translate-y-2 transition-all duration-300">
{/* <EyeOff className=" mb-2 mx-auto" /> */} <p className="text-center text-xs font-medium">
<div className="group-hover:-translate-y-2 flex flex-col justify-center transition-all duration-300"> {value}
<p className="text-center text-sm font-medium">{value}</p> </p>
<p className="text-center text-xs font-medium">{title}</p> <p className="text-center text-xs font-medium">{title}</p>
</div> </div>
</div> </div>

View File

@ -1,153 +0,0 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { X } from "lucide-react";
import { Button } from "./ui/button";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useMutation } from "@tanstack/react-query";
import { changePassword } from "@/utils/authenticateApi";
import { deleteCookie } from "cookies-next";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
export default function ChangePasswordDialog({
data,
open,
setOpen,
}: {
data?: any;
open: any;
setOpen: (state: any) => any;
}) {
const router = useRouter();
const ChangePasswordMutation = useMutation({
mutationKey: ["ChangePassword"],
mutationFn: changePassword,
onSuccess: (res) => {
deleteCookie("Sootzani_Admin_Token");
localStorage.removeItem("privateKey");
localStorage.removeItem("privatePassword");
router.push("/");
toast("رمز عبور شما با موفقیت تغییر یافت.", {
className: "!bg-green-500 !text-white",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const FormSchema = z.object({
oldPassword: z.string(),
newPassword: z.string(),
repeatedPassword: z.string(),
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
});
function onSubmit(data: z.infer<typeof FormSchema>) {
if (data.newPassword !== data.repeatedPassword) {
toast("رمز عبور شما با هم مطابقت ندارد.", {
className: "!bg-red-500 !text-white",
});
return;
}
ChangePasswordMutation.mutate({
oldPassword: data.oldPassword,
newPassword: data.newPassword,
});
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
{" "}
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col w-full mt-6 "
>
<DialogHeader>
<DialogTitle>تغییر رمز عبور</DialogTitle>
<DialogDescription>
<div className="flex flex-col w-full my-6 ">
<FormField
control={form.control}
name="oldPassword"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور فعلی
</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور جدید
</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="repeatedPassword"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
تکرار رمز عبور
</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</DialogDescription>
</DialogHeader>
<DialogDescription></DialogDescription>
<DialogFooter>
<Button type="submit">تایید و ادامه</Button>
</DialogFooter>{" "}
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@ -1,129 +0,0 @@
"use client";
import { putChangePhoneNumber } from "@/utils/authenticateApi";
import { useMutation } from "@tanstack/react-query";
import React, { useEffect, useState } from "react";
import { toast } from "sonner";
import LoginIcon from "../public/img/login-icon.svg";
import Image from "next/image";
import OTPInput from "react-otp-input";
import { useRouter } from "next/navigation";
import { deleteCookie } from "cookies-next";
export default function ChangePhoneNumber() {
const [otp, setOtp] = useState("");
const [otp2, setOtp2] = useState("");
const [phoneNumber, setPhoneNumber] = useState<any>("");
const [newPhoneNumber, setNewPhoneNumber] = useState<any>("");
const space = "\xa0";
const router = useRouter();
const changePhoneNumberMutation = useMutation({
mutationKey: ["putChangePhoneNumber"],
mutationFn: putChangePhoneNumber,
onSuccess: (res) => {
deleteCookie("Sootzani_Admin_Token");
localStorage.removeItem("privateKey");
localStorage.removeItem("privatePassword");
router.push("/");
toast("شماره موبایل با موفقیت تغییر یافت.", {
className: "!bg-green-500 !text-white",
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
useEffect(() => {
if (otp.length == 6 && otp2.length == 6) {
const payload = {
token1: localStorage.getItem("ph_token") as string,
code1: otp,
token2: localStorage.getItem("ph_newToken") as string,
code2: otp2,
};
changePhoneNumberMutation.mutate(payload);
}
}, [otp,otp2]);
useEffect(() => {
const phoneNumber = localStorage.getItem("ph_phoneNumber");
const newPhoneNumber = localStorage.getItem("ph_newPhoneNumber");
setPhoneNumber(phoneNumber);
setNewPhoneNumber(newPhoneNumber);
}, []);
return (
<div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div
className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-fit relative"
>
<div className="flex flex-col justify-center h-full p-10 space-y-3 md:space-y-4 md:py-10 md:px-12 lg:px-16">
<Image alt="icon" src={LoginIcon} className="self-center w-1/3 " />
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
کد شماره {phoneNumber}
</p>
<div className="w-full " dir="ltr">
<OTPInput
value={otp}
onChange={setOtp}
numInputs={6}
renderSeparator={<span>{space}</span>}
renderInput={(props, idx) => (
<input autoFocus={idx == 0} pattern="[0-9]*" {...props} />
)}
containerStyle=" flex justify-center"
inputStyle={` !w-10 rounded-md h-10 bg-[#F5F5F5] border border-blue/30 text-black `}
/>
</div>
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
کد شماره {newPhoneNumber}
</p>
<div className="w-full " dir="ltr">
<OTPInput
value={otp2}
onChange={setOtp2}
numInputs={6}
renderSeparator={<span>{space}</span>}
renderInput={(props, idx) => (
<input autoFocus={idx == 0} pattern="[0-9]*" {...props} />
)}
containerStyle=" flex justify-center"
inputStyle={` !w-10 rounded-md h-10 bg-[#F5F5F5] border border-blue/30 text-black `}
/>
</div>
<label className="text-center label">
<span className="text-xs text-center text-blue/70 label-text">
کد دریافت شده توسط پیامک را وارد نمایید.
</span>
</label>
{/* <div className="flex justify-end w-full gap-2 mt-14">
<Button
disabled={verifyMutation.isPending}
onClick={handelVerify}
type="submit"
className="w-1/2 p-2 text-white bg-blue hover:bg-blue/90 md:w-1/3 rounded-xl"
>
{verifyMutation.isPending ? (
<div className="flex items-center justify-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
"تایید"
)}
</Button>
</div> */}
</div>
</div>
</div>
);
}

View File

@ -1,199 +0,0 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { RefreshCcw, X } from "lucide-react";
import { Button } from "./ui/button";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getCaptcha } from "@/utils/commonApi";
import { ThreeDots } from "react-loader-spinner";
import Image from "next/image";
import { postChangePhoneNumber } from "@/utils/authenticateApi";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
export default function ChangePhoneNumberDialog({
data,
open,
setOpen,
}: {
data?: any;
open: any;
setOpen: (state: any) => any;
}) {
const router = useRouter();
const {
data: CaptchaData,
isLoading,
refetch,
} = useQuery({
queryKey: ["Captcha"],
queryFn: () => getCaptcha(),
refetchOnWindowFocus: false,
});
const changePhoneNumberMutation = useMutation({
mutationKey: ["postChangePhoneNumber"],
mutationFn: postChangePhoneNumber,
onSuccess: (res) => {
localStorage.setItem("ph_token", res.token);
localStorage.setItem("ph_newToken", res.newToken);
localStorage.setItem("ph_phoneNumber", res.phoneNumber);
localStorage.setItem("ph_newPhoneNumber", res.newPhoneNumber);
const userRole = localStorage.getItem("userRole");
if (userRole === "Admin") {
router.push(`/UserPanel/AdminDashboard/ChangePhoneNumber`);
} else {
router.push(`/UserPanel/ControllerDashboard/ChangePhoneNumber`);
}
},
onError: (err: any | string) => {
refetch();
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const FormSchema = z.object({
phoneNumber: z.string().min(1, {
message: "لطفا شماره موبایل را وارد نمایید.",
}),
captcha: z
.string({ required_error: "لطفا کد امنیتی را وارد نمایید." })
.length(5, { message: "لطفا کد امنیتی را به طور کامل وارد نمایید." }),
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
});
function onSubmit(data: z.infer<typeof FormSchema>) {
const payload = {
newPhoneNumber: data.phoneNumber,
captcha: {
key: CaptchaData?.headers["captcha-key"],
value: data.captcha,
},
};
changePhoneNumberMutation.mutate(payload);
}
const srcForImage = CaptchaData
? URL.createObjectURL(CaptchaData.data)
: null;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
{" "}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<DialogHeader>
<DialogTitle>تغییر شماره موبایل</DialogTitle>
<DialogDescription>
<div className="flex flex-col w-full my-6 ">
<FormField
control={form.control}
name="phoneNumber"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
شماره موبایل جدید
</FormLabel>
<FormControl>
<Input
onClick={() => setOpen(true)}
type="text"
className=" text-base"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-center gap-3 mt-4">
<FormField
control={form.control}
name="captcha"
rules={{ required: true }}
render={({ field }) => (
<FormItem className="items-center flex-1 h-10 ">
{/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور
</FormLabel> */}
<FormControl>
<Input
className=" text-base"
placeholder="کد امنیتی"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isLoading ? (
<div className="flex justify-center text-center w-36">
<ThreeDots
visible={true}
height="50"
width="50"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
<div className="flex items-center justify-center gap-2 text-center ">
<Image
alt="icon"
src={srcForImage as string}
className="h-12 rounded-md shadow-md w-36"
width={150}
height={20}
quality={100}
/>
<RefreshCcw
className="cursor-pointer "
onClick={() => refetch()}
color="#003778"
/>
</div>
)}
</div>
</div>
</DialogDescription>
</DialogHeader>
<DialogDescription></DialogDescription>
<DialogFooter>
<Button type="submit">تایید و ادامه</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@ -49,6 +49,8 @@ export default function ComplainsDetails({
const router = useRouter(); const router = useRouter();
let data; let data;
const getComplaintMutation = useMutation({ const getComplaintMutation = useMutation({
mutationKey: ["Complaint", id], mutationKey: ["Complaint", id],
mutationFn: getComplaint, mutationFn: getComplaint,
@ -69,8 +71,10 @@ export default function ComplainsDetails({
const cipherKeyInspector = data.cipherKeyInspector; const cipherKeyInspector = data.cipherKeyInspector;
const newDcKey = Decrypt(cipherKeyInspector, prvKey); const newDcKey = Decrypt(cipherKeyInspector, prvKey);
// const pw = localStorage.getItem("privatePassword") as string;
const pw = newDcKey as string; const pw = newDcKey as string;
localStorage.setItem("trackingNumber", data.trackingNumber); localStorage.setItem("trackingNumber", data.trackingNumber);
// if (pw != null) {
if (pw) { if (pw) {
getComplaintMutation.mutate({ getComplaintMutation.mutate({
trackingNumber: data.trackingNumber, trackingNumber: data.trackingNumber,
@ -78,6 +82,11 @@ export default function ComplainsDetails({
}); });
setOpen(false); setOpen(false);
} }
// else {
// toast("کلید خصوصی وجود ندارد ، بارگداری کنید.", {
// className: "!bg-red-500 !text-white",
// });
// }
}, []); }, []);
useEffect(() => { useEffect(() => {
@ -90,11 +99,7 @@ export default function ComplainsDetails({
data = getComplaintMutation.data; data = getComplaintMutation.data;
} }
const openFileInNewTab = ( const openFileInNewTab = (base64Data: any, fileType: any) => {
base64Data: any,
fileType: any,
fileName?: string
) => {
const blob = b64toBlob(base64Data, fileType); const blob = b64toBlob(base64Data, fileType);
const blobUrl = URL.createObjectURL(blob); const blobUrl = URL.createObjectURL(blob);
const newTab = window.open(); const newTab = window.open();
@ -113,7 +118,9 @@ export default function ComplainsDetails({
`<iframe width="100%" height="100%" src="${blobUrl}"></iframe>` `<iframe width="100%" height="100%" src="${blobUrl}"></iframe>`
); );
} else { } else {
downloadFile(base64Data, fileName, fileType); newTab.document.write(
`<a href="${blobUrl}" target="_blank">Open in New Tab</a>`
);
} }
newTab.document.write("</body></html>"); newTab.document.write("</body></html>");
@ -168,8 +175,11 @@ export default function ComplainsDetails({
const checkKey2 = (item: any) => { const checkKey2 = (item: any) => {
const dcKey = Decrypt(item.cipherKeyInspector, selectedFile); const dcKey = Decrypt(item.cipherKeyInspector, selectedFile);
if (dcKey != false && dcKey != null) { if (dcKey != false && dcKey != null) {
if (check) { if (check) {
// localStorage.setItem("privateKey", dcKey);
localStorage.setItem("privatePassword", dcKey);
localStorage.setItem("privateKey", selectedFile); localStorage.setItem("privateKey", selectedFile);
} }
localStorage.setItem("trackingNumber", item.trackingNumber); localStorage.setItem("trackingNumber", item.trackingNumber);
@ -248,7 +258,7 @@ export default function ComplainsDetails({
</AlertDialog> </AlertDialog>
{getComplaintMutation.data && !getComplaintMutation.isPending ? ( {getComplaintMutation.data && !getComplaintMutation.isPending ? (
<> <>
{/* <button <button
onClick={() => onClick={() =>
router.push("/UserPanel/ControllerDashboard/Complaints") router.push("/UserPanel/ControllerDashboard/Complaints")
} }
@ -258,12 +268,12 @@ export default function ComplainsDetails({
<ArrowRight /> <ArrowRight />
</span> </span>
<p>بازگشت</p> <p>بازگشت</p>
</button> */} </button>
<div className="flex items-start w-full gap-2 mt-2 max-lg:flex-col lg:h-[80vh] mb-10"> <div className="flex items-start w-full gap-2 mt-2 max-lg:flex-col">
{/* 1 */} {/* 1 */}
<div className="flex flex-col w-full lg:w-1/3 gap-3 lg:sticky top-28 lg:h-[80vh] max-lg:order-3"> <div className="flex flex-col w-full lg:w-1/3 gap-3 lg:sticky top-28 lg:h-[78vh]">
<div className=" bg-[#E9E9E9] rounded-md p-4 px-6 flex flex-col lg:h-full"> <div className=" max-lg:hidden bg-[#E9E9E9] rounded-md p-4 px-10 flex flex-col lg:h-full">
<p className="text-[#464646] text-base font-bold mb-1"> <p className="text-[#464646] text-base font-bold mb-1">
انجام عملیات انجام عملیات
</p> </p>
@ -276,13 +286,13 @@ export default function ComplainsDetails({
/> />
</div> </div>
</div> </div>
{/* 2 */} {/* 2 */}
<div className="flex flex-col self-stretch w-full gap-2 rounded-lg lg:w-2/3 "> <div className="flex flex-col self-stretch w-full gap-2 rounded-lg lg:w-2/3 ">
<div className=" bg-[#E9E9E9] rounded-md py-5 px-6 flex flex-col md:flex-row gap-2 min-h-56 items-stretch justify-center"> <div className=" bg-[#E9E9E9] rounded-md py-4 px-10 flex flex-col md:flex-row gap-2 items-center justify-center lg:sticky top-28">
{data.user == null ? ( {data.user == null ? (
<> <>
<div className="relative flex flex-col w-full p-5 mt-2 border border-gray-400 rounded-md gap-y-1"> <div className="relative flex flex-col w-full p-5 mt-2 border border-gray-400 rounded-md gap-y-1">
<p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-[#464646] font-bold"> <p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-gray-500">
اطلاعات کلی اطلاعات کلی
</p> </p>
<p className="text-[#2e2a2a] text-sm font-medium"> <p className="text-[#2e2a2a] text-sm font-medium">
@ -292,7 +302,7 @@ export default function ComplainsDetails({
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
دستگاه مرتبط:{" "} دستگاه مربوطه:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{data?.complaintOrganization {data?.complaintOrganization
? data?.complaintOrganization.title ? data?.complaintOrganization.title
@ -300,37 +310,23 @@ export default function ComplainsDetails({
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
فرد مرتبط:{" "} فرد مربوطه:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{data.complaining ? data.complaining : "-"} {data.complaining ? data.complaining : "-"}
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium">
کد پیگیری:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data.trackingNumber ? data.trackingNumber : "-"}
</span>
</p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
زمان ثبت:{" "} زمان ثبت:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{convertFullTime(data.registeredAt)} {convertFullTime(data.registeredAt)}
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium">
وضعیت:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data?.statusWithDescription
? data.statusWithDescription.description
: "-"}
</span>
</p>
</div> </div>
</> </>
) : ( ) : (
<> <>
<div className="relative flex flex-col p-5 mt-2 border border-gray-400 rounded-md gap-y-1 md:w-1/2 w-full h-full"> <div className="relative flex flex-col p-5 mt-2 border border-gray-400 rounded-md gap-y-1 md:w-1/2">
<p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-[#464646] font-bold"> <p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-gray-500">
اطلاعات کلی اطلاعات کلی
</p> </p>
<p className="text-[#2e2a2a] text-sm font-medium"> <p className="text-[#2e2a2a] text-sm font-medium">
@ -340,7 +336,7 @@ export default function ComplainsDetails({
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
دستگاه مرتبط:{" "} دستگاه مربوطه:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{data?.complaintOrganization {data?.complaintOrganization
? data?.complaintOrganization.title ? data?.complaintOrganization.title
@ -348,34 +344,20 @@ export default function ComplainsDetails({
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
فرد مرتبط:{" "} فرد مربوطه:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{data.complaining ? data.complaining : "-"} {data.complaining ? data.complaining : "-"}
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium">
کد پیگیری:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data.trackingNumber ? data.trackingNumber : "-"}
</span>
</p>
<p className="text-[#464646] text-sm font-medium"> <p className="text-[#464646] text-sm font-medium">
زمان ثبت:{" "} زمان ثبت:{" "}
<span className="text-[#7C838A] text-sm font-medium"> <span className="text-[#7C838A] text-sm font-medium">
{convertFullTime(data.registeredAt)} {convertFullTime(data.registeredAt)}
</span> </span>
</p>{" "}
<p className="text-[#464646] text-sm font-medium">
وضعیت:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data?.statusWithDescription
? data.statusWithDescription.description
: "-"}
</span>
</p> </p>
</div> </div>
<div className="relative flex flex-col items-start p-5 mt-2 border border-gray-400 rounded-md gap-y-1 md:w-1/2 w-full h-full"> <div className="relative flex flex-col p-5 mt-2 border border-gray-400 rounded-md gap-y-1 md:w-1/2">
<p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-[#464646] font-bold"> <p className=" absolute -top-3 right-2 bg-[#E9E9E9] px-2 text-sm text-gray-500">
اطلاعات شاکی اطلاعات شاکی
</p> </p>
<p className="text-[#2e2a2a] text-sm font-medium"> <p className="text-[#2e2a2a] text-sm font-medium">
@ -404,116 +386,101 @@ export default function ComplainsDetails({
: "-"} : "-"}
</span> </span>
</p> </p>
<p className="text-[#464646] text-sm font-medium">
{/* کد پیگیری:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data.trackingNumber ? data.trackingNumber : "-"}
</span> */}
</p>
<p className="text-[#464646] text-sm font-medium">
{/* کد پیگیری:{" "}
<span className="text-[#7C838A] text-sm font-medium">
{data.trackingNumber ? data.trackingNumber : "-"}
</span> */}
</p>
</div> </div>
</> </>
)} )}
</div> </div>
<div className="h-[calc(80vh-12.8em)] max-h-[calc(80vh-12.8em)] overflow-hidden"> <div className="bg-[#E9E9E9] rounded-md py-4 px-10 flex flex-col">
<div className="bg-[#E9E9E9] rounded-md py-4 px-6 flex flex-col h-full "> <p className="text-[#464646] text-base font-bold">روند شکایت</p>
<p className="text-[#464646] text-base font-bold"> <div className="flex flex-col mt-4 gap-y-4">
روند رسیدگی گزارش{" "} {data.contents?.map((item: any) => {
</p> return (
<div <div
className="flex flex-col mt-4 overflow-y-auto key={item.id}
scrollbar-thin scrollbar-thumb-gray-500 scrollbar-track-gray-100 " className="p-4 bg-white rounded-lg shadow-md "
> >
{data.contents?.map((item: any, index: any, array: any) => { <div className="flex items-center gap-4 ">
return ( <p className="">
<> <Badge>
<div className="flex flex-row gap-2 m-1"> {item.sender == 0 ? "شهروند" : "بازرس"}
<div className="flex"> </Badge>
<span className=" flex items-center justify-center w-7 h-7 mt-1 mr-1 bg-blue-100 rounded-md -start-4 ring-2 ring-blue bg-blue2 text-white bg-blue"> </p>
{array.length - index} <p className="">
</span> تاریخ :
</div> <span className="text-[#7C838A]">
<div {convertDate(item.dateTime)}
key={item.id} </span>
className="p-4 bg-white rounded-lg shadow-md w-full relative" </p>
> </div>
<div className="flex items-center sm:gap-4 justify-between flex-col sm:flex-row gap-1"> <div className=" text-[#464646] mt-2">
<p className=""> <span className="text-[#7C838A]">
<Badge className="bg-blue"> {item.text ? item.text : "-"}
{item.operationWithDescription.description}{" "} </span>
توسط {item.sender == 0 ? "شهروند" : "بازرس"} </div>
</Badge> {item.media.length !== 0 && (
</p> <Separator className="mt-2 mb-1 " />
<p className=""> )}
<span className="text-blue text-sm"> <div className=" text-[#464646] mt-2">
{convertFullTime(item.dateTime)} <div className="flex flex-wrap items-center w-full gap-2 mt-2 text-xs max-md:flex-col">
</span> {item?.media.map((item: any, index: number) => {
</p> return (
</div> <div
<p className="text-[#7C838A] text-sm flex flex-wrap whitespace-normal break-all mt-2"> key={index}
{item.text ? item.text : "-"} className=" bg-gray-100 text-[#7C838A] w-full md:w-[30%] rounded-md h-12 p-2 flex justify-between gap-3 items-center"
</p> >
{item.media.length !== 0 && ( <a
<Separator className="mt-2 mb-1 " /> onClick={() =>
)} openFileInNewTab(item.data, item.mimeType)
<div className=" text-[#464646] mt-2">
<div className="flex flex-wrap items-center w-full gap-2 mt-2 text-xs max-md:flex-col">
{item?.media.map(
(item: any, index: number) => {
return (
<div
key={index}
className=" bg-gray-100 text-[#7C838A] w-full md:w-[30%] rounded-md h-12 p-2 flex justify-between gap-3 items-center cursor-pointer"
onClick={() =>
openFileInNewTab(
item.data,
item.mimeType,
item.title
)
}
>
<a className="flex items-center gap-2 truncate cursor-pointer ">
<File className="w-6 h-6 " />
<p className=" max-w-full truncate">
{item.title}
</p>
</a>
{/* <ArrowDownToLine
className="cursor-pointer "
onClick={() =>
downloadFile(
item.data,
item.title,
item.mimeType
)
}
/> */}
</div>
);
} }
)} className="flex items-center gap-2 truncate cursor-pointer "
>
<File className="w-6 h-6 " />
<p className=" max-w-[5rem] truncate">
{item.title}
</p>
</a>
<ArrowDownToLine
className="cursor-pointer "
onClick={() =>
downloadFile(
item.data,
item.title,
item.mimeType
)
}
/>
</div> </div>
</div> );
</div> })}
</div> </div>
</> </div>
); </div>
})} );
</div> })}
</div> </div>
</div> </div>
</div> </div>
{/* 3 */}
<div className=" lg:hidden order-2 w-full bg-[#E9E9E9] rounded-md py-4 px-10 flex flex-col mt-2">
<p className="text-[#464646] text-base font-bold mb-1">
انجام عملیات
</p>
<InspectorOperations
updateData={(data) => getComplaintMutation.mutate(data)}
role={role}
complaintData={data}
id={id}
key2={key}
/>
</div>
</div> </div>
</> </>
) : ( ) : (
<> <>
{getComplaintMutation.isPending && ( {getComplaintMutation.isPending && (
<div className="flex justify-center w-full h-full mt-20"> <div className="flex justify-center w-full h-full mt-20">
<Triangle <Triangle
visible={true} visible={true}
height="100" height="100"

View File

@ -14,6 +14,9 @@ export default function ControllerDashboard() {
queryFn: () => getInfo(), queryFn: () => getInfo(),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
}); });
const [decryptedMessage, errorMessage] = useDecrypt(
"gJoT9AqK7wk1MZFSD04yXXfF36fzsOL+RYtJfySrEnQeJ7VoaL7pmOU6nB3+0+PQcaxIi3hf1AHjzIB0Cn5oHgKROeoI4XslhAezZk23QhtIU4HUF1wpeOJfA+4hWyRfbh4fI9774sa/KL47VaBbrNM/rvBxk6hjlKx5mTb3hqM="
);
return ( return (
<div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-12 pt-9 mx-auto px-2"> <div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-12 pt-9 mx-auto px-2">
@ -39,6 +42,36 @@ export default function ControllerDashboard() {
})} })}
</div> </div>
</div> </div>
{/* <div className="w-full flex-row gap-6 h-[20vh] hidden lg:flex">
<div className="w-3/5 flex flex-row gap-7">
<BoxDashboard />
<BoxDashboard />
<BoxDashboard />
</div>
</div> */}
{/* max Lg show */}
{/* <div className="w-full mb-6 flex-col gap-12 flex lg:hidden">
<div className="w-full flex flex-row flex-wrap justify-center gap-4 ">
<BoxDashboard />
<BoxDashboard />
<BoxDashboard />
<BoxDashboard />
<BoxDashboard />
</div>
<div className="w-full flex flex-col gap-12 ">
<div className="h-1/2">
<LineChart />
</div>
<hr />
<div className="h-1/2">
<HorizontalChart />
</div>
</div>
</div> */}
</div> </div>
); );
} }

86
components/Footer.tsx Normal file
View File

@ -0,0 +1,86 @@
import React from "react";
import Image from "next/image";
import img1 from "../public/img/footerImg1.png";
import img2 from "../public/img/footerImg2.png";
import { footerItems } from "@/constants";
import { aboutFooterItems } from "@/constants";
import Link from "next/link";
export default function Footer() {
return (
// <div classNameName="flex justify-center items-center w-full bg-blue ">
<footer className="bg-blue dark:bg-gray-900">
<div className="mx-auto w-full max-w-screen-3xl px-4 py-7 md:px-8 md:py-8 lg:pt-14 lg:pb-7 lg:px-11 ">
<div className="md:flex md:justify-between w-full ">
<div className="grid gap-10 sm:gap-16 md:gap-20 lg:gap-28 grid-cols-1 w-full md:grid-cols-2 md:w-3/4 lg:w-2/4">
<div>
<h2 className="text-white text-sm sm:text-base font-bold mb-4 ">
درباره سامانه عیون
</h2>
{aboutFooterItems.map((item) => {
return (
<div key={item.id}>
<p className=" text-white text-xs md:text-sm font-normal md:leading-7">
{item.name}
</p>
</div>
);
})}
</div>
<div>
<h2 className="text-white text-sm sm:text-base font-bold mb-4">
دسترسی سریع
</h2>
<ul className="text-gray-500 dark:text-gray-400 font-medium text-right">
{footerItems.map((item, index, array) => {
return (
<Link key={item.id} href={item.href}>
<div className=" text-white text-xs md:text-sm font-normal leading-6 mb-3">
{item.name}
</div>
</Link>
);
})}
</ul>
</div>
</div>
<div className=" max-md:mt-6 flex flex-row justify-center md:justify-end items-start w-full md:w-1/4 ">
<div className="w-23 h-23 sm:w-36 sm:h-36 ">
<Image
src={img1}
className="h-full w-full object-contain"
alt=" Logo1"
quality={100}
width={100}
height={100}
/>
</div>
<div className="w-23 h-23 sm:w-36 sm:h-36 ">
<Image
src={img2}
className="h-full w-full object-contain"
alt=" Logo2"
quality={100}
width={100}
height={100}
/>
</div>
</div>
</div>
<hr className=" border-gray-200 sm:mx-auto dark:border-gray-700 mt-5 sm:mt-10" />
<div className="sm:flex sm:items-center sm:justify-between">
<p className="text-white text-xs font-normal mt-4">
تمامی حقوق مادی و معنوی این وب سایت متعلق به عیون میباشد.
</p>
</div>
</div>
</footer>
// </div>
);
}

View File

@ -29,15 +29,11 @@ import {
} from "@/components/ui/select"; } from "@/components/ui/select";
import { Operations } from "@/constants"; import { Operations } from "@/constants";
import useData from "@/store/useData"; import useData from "@/store/useData";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { OperateByInspector } from "@/utils/inspectorApi"; import { OperateByInspector } from "@/utils/inspectorApi";
import { toast } from "sonner"; import { toast } from "sonner";
import { Decrypt, formatBytes } from "@/lib/utils"; import secureLocalStorage from "react-secure-storage";
import { useEffect, useRef, useState } from "react"; import { Decrypt } from "@/lib/utils";
import { getOptions } from "@/utils/commonApi";
import AttachmentsDialog from "./AttachmentsDialog";
import { DialogTrigger } from "./ui/dialog";
import { Eye, Upload } from "lucide-react";
export default function InspectorOperations({ export default function InspectorOperations({
complaintData, complaintData,
@ -52,51 +48,8 @@ export default function InspectorOperations({
id: any; id: any;
key2: any; key2: any;
}) { }) {
const [file, setFile] = useState<File[]>([]);
const [check, setCheck] = useState<any>(false);
const [charCount, setCharCount] = useState<any>(0);
// Queries
const { data, isLoading, refetch } = useQuery({
queryKey: ["Options"],
queryFn: () => getOptions(),
refetchOnWindowFocus: false,
});
const OperationMutation = useMutation({
mutationKey: ["Operation"],
mutationFn: OperateByInspector,
onSuccess: (res) => {
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
// const tk = localStorage.getItem("trackingNumber");
const storedData = JSON.parse(
localStorage.getItem("CompliantData") as string
);
const dcKey = Decrypt(
storedData.cipherKeyInspector,
localStorage.getItem("privateKey") as string
);
updateData({
trackingNumber: complaintData.trackingNumber,
password: key2 ? key2 : dcKey,
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const FormSchema = z.object({ const FormSchema = z.object({
text: z text: z.string({ required_error: "لطفا متن خود را وارد نمایید." }),
.string({ required_error: "لطفا متن خود را وارد نمایید." })
.max(
data?.maxTextLength,
`حداکثر ${data?.maxTextLength} کاراکتر می توانید وارد کنید.`
),
...(role == "Inspector" && { ...(role == "Inspector" && {
type: z.enum(["private", "public"], { type: z.enum(["private", "public"], {
required_error: "لطفا وضعیت عملیات را انتخاب نمایید.", required_error: "لطفا وضعیت عملیات را انتخاب نمایید.",
@ -106,21 +59,14 @@ export default function InspectorOperations({
required_error: "لطفا نوع عملیات را انتخاب نمایید.", required_error: "لطفا نوع عملیات را انتخاب نمایید.",
}), }),
media: z media: z
.custom<File[]>() .custom<FileList>((val) => val instanceof FileList, "Required")
// .refine((files) => files.length > 0, `Required`) // .refine((files) => files.length > 0, `Required`)
.refine( .refine((files) => files.length <= 5, `Maximum of 5 File are allowed.`)
(files) => files.length <= data?.maxFileCount,
`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} عدد باشد.`
)
.refine(
(files) => files.every((item) => item.size < data?.maxFileSize),
`حجم هر فایل حداکثر می بایست ${data?.maxFileSize} باشد.`
)
.nullish(), .nullish(),
}); });
const password = useData((state) => state.data.password); const password = useData((state) => state.data.password);
const possibleOperations = complaintData?.possibleOperationsWithDescription; const possibleOperations = complaintData?.possibleOperationsWithDescription;
const queryClient = useQueryClient();
const form = useForm<z.infer<typeof FormSchema>>({ const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema), resolver: zodResolver(FormSchema),
@ -132,30 +78,31 @@ export default function InspectorOperations({
}, },
}); });
// Add the useEffect hook to monitor changes in the description field const OperationMutation = useMutation({
useEffect(() => { mutationKey: ["Operation"],
const text = form.watch("text") as string; mutationFn: OperateByInspector,
if (charCount != 0) { onSuccess: (res) => {
setCharCount(text?.length); toast("عملیات شما با موفقیت انجام شد. ", {
} className: "!bg-green-500 !text-white",
}, [form.watch("text")]); });
const tk = localStorage.getItem("trackingNumber");
function handleTextChange(event: React.ChangeEvent<HTMLTextAreaElement>) { updateData({
const newCharCount = event.target.value.length; trackingNumber: complaintData.trackingNumber,
// Update charCount only when the user types or removes characters password: key2 ? key2 : (localStorage.getItem("privateKey") as string),
if (newCharCount <= data?.maxTextLength) { });
setCharCount(newCharCount); },
} onError: (err: any | string) => {
} toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
function onSubmit(data: z.infer<typeof FormSchema>) { function onSubmit(data: z.infer<typeof FormSchema>) {
const storedData = JSON.parse( const storedData = JSON.parse(
localStorage.getItem("CompliantData") as string localStorage.getItem("CompliantData") as string
); );
const dcKey = Decrypt( const dcKey = Decrypt(storedData.cipherKeyInspector, key2);
storedData.cipherKeyInspector,
localStorage.getItem("privateKey") as string
);
const formData = new FormData(); const formData = new FormData();
formData.append("text", data.text); formData.append("text", data.text);
formData.append("trackingNumber", complaintData.trackingNumber); formData.append("trackingNumber", complaintData.trackingNumber);
@ -163,7 +110,10 @@ export default function InspectorOperations({
if (data.type) { if (data.type) {
formData.append("IsPublic", data.type == "public" ? "true" : "false"); formData.append("IsPublic", data.type == "public" ? "true" : "false");
} }
formData.append("EncodedKey", key2 ? key2 : dcKey); formData.append(
"EncodedKey",
key2 ? key2 : (localStorage.getItem("privateKey") as string)
);
if (data?.media && data?.media?.length > 0) { if (data?.media && data?.media?.length > 0) {
for (let i = 0; i < data.media.length; i++) { for (let i = 0; i < data.media.length; i++) {
formData.append("Medias", data.media[i]); formData.append("Medias", data.media[i]);
@ -171,145 +121,53 @@ export default function InspectorOperations({
} }
OperationMutation.mutate(formData); OperationMutation.mutate(formData);
} }
const deleteAllAttachmentsFiles = () => {
setFile([]);
// @ts-expect-error
form.setValue("media", []);
};
const deleteFileFromAttachments = (File: any) => {
const filtered = file?.filter((item) => item.name !== File);
setFile(filtered);
// @ts-expect-error
form.setValue("media", filtered);
};
const allowedExtensions = data?.allowedExtensions;
const split = allowedExtensions?.split(",");
const withDot = split?.map((item: string) => "." + item);
const newAllowedExtensions = withDot?.join(",");
const formatSize = (size: number) => {
const string = formatBytes(size);
return (
<span className="" dir="ltr">
{string}
</span>
);
};
return ( return (
<Form {...form}> <Form {...form}>
<form <form onSubmit={form.handleSubmit(onSubmit)} className="">
onSubmit={form.handleSubmit(onSubmit)}
className=" flex flex-col h-full"
>
<FormField <FormField
control={form.control} control={form.control}
name="text" name="text"
render={({ field, fieldState: { error } }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel className=""> <FormLabel className="">متن</FormLabel>
متن({charCount}/{data?.maxTextLength})
</FormLabel>
<FormControl> <FormControl>
<Textarea <Textarea
// placeholder="متن خود را وارد نمایید" placeholder="متن خود را وارد نمایید"
className="resize-none bg-white lg:min-h-[18em]" className="resize-none bg-white lg:min-h-[20em]"
{...field} {...field}
disabled={possibleOperations.length == 0}
onChange={(e) => {
const currentValue = e.target.value;
if (currentValue.length <= data?.maxTextLength) {
field.onChange(e);
handleTextChange(e);
} else {
// Truncate the value to the allowed limit
field.onChange(
currentValue.substring(0, data?.maxTextLength)
);
}
}}
/> />
</FormControl> </FormControl>
{!error ? ( {/* <FormDescription>
<FormDescription className=" text-xs my-1 "> You can <span>@mention</span> other users and organizations.
حداکثر {data?.maxTextLength} کاراکتر می توانید وارد کنید. </FormDescription> */}
</FormDescription> <FormMessage />
) : (
<FormMessage />
)}
</FormItem> </FormItem>
)} )}
/> />
{/* <div className="grid w-full max-w-sm items-center gap-1.5 mt-1">
<Label htmlFor="picture">پیوست</Label>
<Input multiple id="picture" type="file" className="bg-white " />
</div> */}
<FormField <FormField
control={form.control} control={form.control}
name="media" name="media"
render={({ field, fieldState: { error } }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel> <FormLabel>پیوست</FormLabel>
پیوست‌ها ({field?.value?.length ? field.value.length : 0}) <FormControl>
</FormLabel> <Input
<div className="flex gap-2 w-full items-center mt-1 mb-2"> accept=".jpg, .jpeg, .png, .svg, .gif, .mp4 , .pdf"
<AttachmentsDialog
attachments={file}
deleteFile={(item) => deleteFileFromAttachments(item)}
deleteAllAttachmentsFiles={deleteAllAttachmentsFiles}
>
<DialogTrigger className=" bg-white rounded-md h-9 text-xs flex-1 flex gap-2 items-center justify-center">
<Eye className=" w-4 h-4" />
<p>مشاهده</p>
</DialogTrigger>
</AttachmentsDialog>
<label
htmlFor="fileInput"
className="cursor-pointer text-sm rounded-md grid place-content-center h-9 px-2 bg-white w-1/2 items-center"
>
<div className=" flex gap-2 justify-center items-center">
<p className="text-xs flex gap-2 items-center">
<Upload className=" w-4 h-4" />
<span>افزودن</span>
</p>
</div>
</label>
<input
id="fileInput"
type="file" type="file"
className="hidden"
accept={newAllowedExtensions}
multiple
onChange={(e) => { onChange={(e) => {
// field.onChange(e.target.files ? e.target.files : null); field.onChange(e.target.files ? e.target.files : null);
if (file && e.target.files) { console.log(e.target.files);
const fileArray1 = Array.from(file);
const fileArray2 = Array.from(e.target.files);
const mergedArray = fileArray1.concat(fileArray2);
const uniqueFiles = Array.from(
new Map(
mergedArray.map((file: any) => [file.name, file])
).values()
);
setFile(uniqueFiles);
field.onChange(uniqueFiles);
} else if (!file && e.target.files) {
const fileArray2 = Array.from(e.target.files);
setFile(fileArray2);
field.onChange(fileArray2);
}
}} }}
multiple
className="bg-white "
/> />
</div> </FormControl>
{!error ? ( <FormMessage />
<FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست {formatSize(data?.maxFileSize)}{" "}
باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage />
)}
</FormItem> </FormItem>
)} )}
/> />
@ -318,51 +176,34 @@ export default function InspectorOperations({
control={form.control} control={form.control}
name="type" name="type"
render={({ field }) => ( render={({ field }) => (
<FormItem className=""> <FormItem className="space-y-3">
<FormControl dir="rtl"> <FormControl dir="rtl">
<RadioGroup <RadioGroup
onValueChange={(value) => { onValueChange={field.onChange}
field.onChange(value);
setCheck(false);
}}
// defaultValue={field.value} // defaultValue={field.value}
className="flex space-y-1 text-sm" className="flex space-y-1 text-sm"
> >
<FormItem className="flex items-center space-x-3 space-y-0"> <FormItem className="flex items-center space-x-3 space-y-0">
<FormControl> <FormControl>
<RadioGroupItem <RadioGroupItem value="private" className="ml-2 " />
onClick={() => {
// @ts-expect-error
form.setValue("type", "private");
}}
value="private"
className="ml-2 "
checked={form.getValues("type") == "private"}
disabled={possibleOperations.length == 0}
/>
</FormControl> </FormControl>
<FormLabel className="font-normal">خصوصی</FormLabel> <FormLabel className="font-normal">خصوصی</FormLabel>
</FormItem> </FormItem>
<FormItem className="flex items-center space-x-3 space-y-0"> <FormItem className="flex items-center space-x-3 space-y-0">
<FormControl> <FormControl>
<RadioGroupItem <RadioGroupItem value="public" className="ml-2 " />
value="public"
className="ml-2 "
checked={form.getValues("type") == "public"}
disabled={possibleOperations.length == 0}
/>
</FormControl> </FormControl>
<FormLabel className="font-normal">گزارشگر</FormLabel> <FormLabel className="font-normal">عمومی</FormLabel>
</FormItem> </FormItem>
</RadioGroup> </RadioGroup>
</FormControl> </FormControl>
<FormMessage className=" mt-1" /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
)} )}
<div className="flex justify-between gap-2 mt-auto "> <div className="flex justify-between gap-2 mt-3 ">
<FormField <FormField
control={form.control} control={form.control}
name="operation" name="operation"
@ -370,15 +211,7 @@ export default function InspectorOperations({
<FormItem className="flex-1 "> <FormItem className="flex-1 ">
{/* <FormLabel>Email</FormLabel> */} {/* <FormLabel>Email</FormLabel> */}
<Select <Select
onValueChange={(value) => { onValueChange={field.onChange}
field.onChange(value);
setCheck(false);
if (value == "2") {
setCheck(true);
// @ts-expect-error
form.setValue("type", "public");
}
}}
defaultValue={field.value} defaultValue={field.value}
dir="rtl" dir="rtl"
> >
@ -386,23 +219,16 @@ export default function InspectorOperations({
<SelectTrigger <SelectTrigger
className=" bg-white h-10 !placeholder:text-xs text-xs" className=" bg-white h-10 !placeholder:text-xs text-xs"
dir="rtl" dir="rtl"
disabled={possibleOperations.length == 0}
> >
<SelectValue <SelectValue
className="text-xs " className="text-xs "
placeholder="نوع عملیات" placeholder="نوع عملیات را انتخاب نمایید."
/> />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent <SelectContent dir="rtl">
ref={(ref) => {
if (!ref) return;
ref.ontouchstart = (e) => e.preventDefault();
}}
dir="rtl"
>
<SelectGroup> <SelectGroup>
<SelectLabel>نوع عملیات</SelectLabel> <SelectLabel>عملیات</SelectLabel>
{possibleOperations.map((item: any) => { {possibleOperations.map((item: any) => {
return ( return (
<SelectItem <SelectItem

View File

@ -100,6 +100,7 @@ export default function LineChart({
anchor: "end", anchor: "end",
font: { size: 12 }, font: { size: 12 },
formatter: function (value, context) { formatter: function (value, context) {
console.log(context.dataset);
return value == 0 ? "" : value; return value == 0 ? "" : value;
}, },
}, },

View File

@ -95,7 +95,7 @@ export default function Login() {
: null; : null;
return ( return (
<div className="grid w-screen h-screen bg-left-top bg-repeat bg-[url('/img/login-pattern.png')] place-content-center"> <div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div <div
className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040] className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-fit" h-fit"

63
components/Navbar.tsx Normal file
View File

@ -0,0 +1,63 @@
"use client";
import React from "react";
import { Input } from "./ui/input";
import Image from "next/image";
import { menuItems } from "@/constants";
import Link from "next/link";
import Login from "./Login";
import { Button } from "./ui/button";
import { usePathname } from 'next/navigation'
import TopNav from "./TopNav";
export default function Navbar() {
const pathname = usePathname()
return (
<div className={`max-md:hidden left-0 right-0 top-0 z-10 ${pathname === "/" ? "absolute" : "sticky"}`}>
<TopNav />
<div className=" bg-white h-16 shadow-md flex items-center justify-between py-2 px-8">
<div className=" flex ">
<div className=" flex items-center ">
<Image
src="/img/logo.png"
quality={100}
alt="log"
width={32}
height={32}
/>
<div className=" text-brown flex flex-col text-center w-40">
<h1 className="text-[21px] w-full">ســــــــوت زن</h1>
<h1 className="text-[9px]">سامانه افشار فساد شهرداری</h1>
</div>
</div>
<div className=" flex gap-5 items-center mr-8">
{menuItems.map((item, index, array) => {
if (array.length - 1 !== index){
return (
<Link key={item.id} href={item.href}>
<div className=" text-sm font-bold">{item.name}</div>
</Link>
);
}else{
return (
<></>
);
}
})}
</div>
</div>
<Link href="/Login" >
<Button className=" bg-blue hover:bg-blue/90 rounded-lg">
ورود به پنل کاربری
</Button>
</Link>
</div>
</div>
);
}

View File

@ -9,9 +9,6 @@ import { getProfile, revoke } from "@/utils/authenticateApi";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import { DoorOpen, LogOut } from "lucide-react"; import { DoorOpen, LogOut } from "lucide-react";
import { deleteCookie, getCookie } from "cookies-next"; import { deleteCookie, getCookie } from "cookies-next";
import useSignalR from "@/hooks/useSignalR";
import ProfileDropDown from "./ProfileDropDown";
export default function NavbarPanel() { export default function NavbarPanel() {
const [isOpen, setOpen] = useState(false); const [isOpen, setOpen] = useState(false);
const ref = useRef(null); const ref = useRef(null);
@ -33,6 +30,7 @@ export default function NavbarPanel() {
const { data, isLoading, refetch } = useQuery({ const { data, isLoading, refetch } = useQuery({
queryKey: ["Profile"], queryKey: ["Profile"],
queryFn: () => getProfile(), queryFn: () => getProfile(),
refetchOnWindowFocus: false,
}); });
const revokeMutation = useMutation({ const revokeMutation = useMutation({
@ -49,14 +47,13 @@ export default function NavbarPanel() {
const logout = () => { const logout = () => {
revokeMutation.mutate({ revokeMutation.mutate({
refreshToken: getCookie("Sootzani_Admin_Refresh_Token"), refreshToken: getCookie("Sootzani_Refresh_Token"),
}); });
deleteCookie("Sootzani_Admin_Token"); deleteCookie("Sootzani_Token");
localStorage.removeItem("privateKey"); localStorage.removeItem("privateKey");
localStorage.removeItem("privatePassword"); localStorage.removeItem("privatePassword");
router.push("/"); router.push("/");
}; };
const signalr = useSignalR();
return ( return (
<div className="fixed top-0 z-10 flex flex-row items-center justify-between w-full gap-3 px-8 py-4 shadow-md sm:items-center sm:gap-0 bg-blue max-md:px-4 "> <div className="fixed top-0 z-10 flex flex-row items-center justify-between w-full gap-3 px-8 py-4 shadow-md sm:items-center sm:gap-0 bg-blue max-md:px-4 ">
@ -142,8 +139,17 @@ export default function NavbarPanel() {
</div> </div>
<div className="flex items-center gap-4 "> <div className="flex items-center gap-4 ">
<h1 className="inline-block text-sm font-bold text-white bg-clip-text before:max-md:hidden max-md:text-xs max-md:font-medium"> <h1 className="inline-block text-sm font-bold text-white bg-clip-text before:max-md:hidden max-md:text-xs max-md:font-medium">
<ProfileDropDown /> {data && (
<>
{role === "Admin"
? `${data?.title ? data.title : data.username} (ادمین)`
: `${data?.title ? data.title : data.username} (بازرس)`}
</>
)}
</h1> </h1>
<div className="p-1 rounded-md hover:bg-white/50">
<LogOut onClick={logout} className="text-white cursor-pointer " />
</div>
</div> </div>
</div> </div>
); );

89
components/NavbarSm.tsx Normal file
View File

@ -0,0 +1,89 @@
"use client";
import React from "react";
import { useRef } from "react";
import { useState, useEffect } from "react";
// import { useClickAway } from "react-use/lib/useClickAway";
import { AnimatePresence, motion } from "framer-motion";
import { Squash as Hamburger } from "hamburger-react";
import { menuItems } from "@/constants";
import Link from "next/link";
import { Button } from "./ui/button";
import TopNav from "./TopNav";
import { usePathname } from "next/navigation";
// import { routes } from "../routes";
export default function NavbarSm() {
const pathname = usePathname();
// useClickAway(ref, () => setOpen(false));
const [isOpen, setOpen] = useState(false);
const ref = useRef(null);
return (
<>
<div
ref={ref}
className={`md:hidden w-full bg-white z-[100] flex flex-row justify-between items-center px-4
sticky top-0
shadow-md`}
>
<Hamburger toggled={isOpen} size={20} toggle={setOpen} />
{/* <Link href="/Login">
<Button className=" bg-blue hover:bg-blue/90 rounded-lg text-xs ">
ورود به پنل کاربری
</Button>
</Link> */}
<div className="md:hidden">
<TopNav />
</div>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed z-[100] left-0 shadow-4xl right-0 top-[3rem] p-5 bg-gradient-to-b from-blue to-white border-b border-b-white/20"
>
<ul className="grid gap-2 ">
{menuItems.map((item, idx, array) => {
// const { Icon } = item;
const lastItem = array.length - 1;
return (
<motion.li
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{
type: "spring",
stiffness: 260,
damping: 20,
delay: 0.1 + idx / 10,
}}
key={item.name}
className=" w-full p-[0.08rem] rounded-xl bg-gradient-to-tr from-neutral-800 via-white to-neutral-700"
>
<Link
onClick={() => setOpen((prev) => !prev)}
className={`flex items-center justify-between w-full p-3 rounded-xl text-white
${lastItem === idx ? "bg-yellow" : "bg-blue"} `}
href={item.href}
>
<span className="flex gap-1 text-sm">{item.name}</span>
{/* <Icon className="text-xl" /> */}
</Link>
</motion.li>
);
})}
</ul>
</motion.div>
)}
</AnimatePresence>
</div>
</>
);
}

View File

@ -3,50 +3,64 @@ import React, { useEffect, useState } from "react";
import ReactPaginate from "react-paginate"; import ReactPaginate from "react-paginate";
import { MdKeyboardArrowRight, MdKeyboardArrowLeft } from "react-icons/md"; import { MdKeyboardArrowRight, MdKeyboardArrowLeft } from "react-icons/md";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
// Example items, to simulate fetching from another resources.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
export default function Pagination({ export default function Pagination({
TotalPages, itemsPerPage,
currentPage,
PageSize,
Page, Page,
countPage, countPage,
length, length,
}: { }: {
TotalPages?: any; itemsPerPage?: any;
currentPage?: any;
PageSize?: number;
Page?: any; Page?: any;
countPage?: any; countPage?: any;
length?: any; length?: any;
}) { }) {
// Here we use item offsets; we could also use page offsets
// following the API or data you're working with.
const [itemOffset, setItemOffset] = useState(0);
// Simulate fetching items from another resources.
// (This could be items from props; or items loaded in a local state
// from an API endpoint with useEffect and useState)
const endOffset = itemOffset + itemsPerPage;
// console.log(`Loading items from ${itemOffset} to ${endOffset}`);
const currentItems = items.slice(itemOffset, endOffset);
const pageCount = Math.ceil(items.length / itemsPerPage);
// Invoke when user click to request another page.
const handlePageClick = (event: any) => { const handlePageClick = (event: any) => {
const newOffset = (event.selected * itemsPerPage) % items.length;
console.log(
`User requested page number ${event.selected}, which is offset ${newOffset}`
);
setItemOffset(newOffset);
// console.log(event.selected);
console.log(event);
Page(event.selected); Page(event.selected);
}; };
console.log(countPage);
// console.log(pageCount, "1111");
return ( return (
<> <>
{/* <Items currentItems={currentItems} /> */}
<ReactPaginate <ReactPaginate
breakLabel="..." breakLabel="..."
onPageActive={(e) => console.log(e)} onPageActive={(e) => console.log(e)}
nextLabel={<MdKeyboardArrowLeft className="w-5 h-5 " />} nextLabel={<MdKeyboardArrowLeft className="w-5 h-5 " />}
onPageChange={handlePageClick} onPageChange={handlePageClick}
pageRangeDisplayed={3} pageRangeDisplayed={3}
forcePage={currentPage} pageCount={Math.ceil(countPage / 5)}
pageCount={
TotalPages
? TotalPages
: Math.ceil(countPage / (PageSize ? PageSize : 5))
}
previousLabel={<MdKeyboardArrowRight className="w-5 h-5 " />} previousLabel={<MdKeyboardArrowRight className="w-5 h-5 " />}
pageClassName=" w-10 h-10 grid place-content-center rounded-lg !text-blue shadow-md" pageClassName=" w-10 h-10 grid place-content-center rounded-lg !text-blue shadow-md"
className={twMerge( className={twMerge(
" flex flex-wrap gap-3 text-sm md:text-base w-full rounded-md p-2 pb-3 bg-white/30 backdrop-blur-lg justify-center fixed text-blue mt-5 left-0 right-0 bottom-0" " flex flex-wrap gap-3 text-sm md:text-base w-full bottom-0 rounded-md p-1 bg-white/30 backdrop-blur-lg justify-center text-blue mt-5"
)} )}
activeClassName=" bg-blue text-blue shadow-md shadow-main" activeClassName=" bg-blue text-blue shadow-md shadow-main"
activeLinkClassName=" text-white w-full p-1 h-full" activeLinkClassName=" text-white w-full p-1 h-full"
previousLinkClassName=" w-10 h-10 grid place-content-center rounded-lg text-sm shadow-md" previousLinkClassName=" w-10 h-10 grid place-content-center rounded-lg text-sm shadow-md"
nextLinkClassName=" w-10 h-10 grid place-content-center rounded-lg text-sm shadow-md" nextLinkClassName=" w-10 h-10 grid place-content-center rounded-lg text-sm shadow-md"
pageLinkClassName="p-4"
/> />
</> </>
); );

View File

@ -1,101 +0,0 @@
import React, { useEffect, useState } from "react";
import { CreditCard, LogOut, User, UserPlus, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuPortal,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { getProfile, revoke } from "@/utils/authenticateApi";
import { useMutation, useQuery } from "@tanstack/react-query";
import Link from "next/link";
import useToken from "@/store/useToken";
import { deleteCookie, getCookie } from "cookies-next";
import { useRouter } from "next/navigation";
export default function ProfileDropDown() {
const router = useRouter();
const [role, setRole] = useState<any>(null);
const {
data: profileData,
isLoading,
refetch,
} = useQuery({
queryKey: ["Profile"],
queryFn: () => getProfile(),
});
const revokeMutation = useMutation({
mutationFn: revoke,
onSuccess: (res) => {},
onError: (err: any | string) => {},
});
const logout = () => {
revokeMutation.mutate({
refreshToken: getCookie("Sootzani_Admin_Refresh_Token"),
});
deleteCookie("Sootzani_Admin_Token");
localStorage.removeItem("privateKey");
localStorage.removeItem("privatePassword");
router.push("/");
};
useEffect(() => {
const userRole = localStorage.getItem("Sootzani_Role");
if (userRole == "Admin") {
setRole("AdminDashboard");
} else {
setRole("ControllerDashboard");
}
}, []);
const saveToken = useToken((state) => state.saveToken);
return (
<DropdownMenu dir="rtl" modal={false}>
<DropdownMenuTrigger
className=" max-sm:-mr-8 max-sm:text-xs w-12"
asChild
>
<Button
// variant="outline"
className=" truncate bg-white text-blue hover:bg-white w-32 flex justify-center items-center gap-2"
>
<User className=" w-5 h-5" />
{/* {profileData?.title ? profileData?.title : profileData?.userName} */}
<p className=" truncate self-end">
{" "}
{profileData?.firstName || profileData?.lastName
? profileData?.firstName + " " + profileData?.lastName
: profileData?.userName}
</p>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56 sm:ml-10">
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() => router.push(`/UserPanel/${role}/Profile`)}
>
<User className="w-4 h-4 ml-2" />
<span>پروفایل</span>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout}>
<LogOut className="w-4 h-4 ml-2" />
<span>خروج</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@ -11,19 +11,18 @@ import { getInfo, getInfoList } from "@/utils/infoApi";
import { useQueries, useQuery } from "@tanstack/react-query"; import { useQueries, useQuery } from "@tanstack/react-query";
export default function Reports({ data }: { data: any }) { export default function Reports({ data }: { data: any }) {
const [first, setfirst] = useState<any>(false);
const Queries: any = useQueries({ const Queries: any = useQueries({
queries: data?.map((item: any) => ({ queries: data?.map((item: any) => ({
queryKey: ["user", item.code], queryKey: ["user", item.code],
queryFn: () => getInfo(item.code), queryFn: () => getInfo(item.code),
})), })),
}); });
const codes = data.map((item: any) => item.code); const codes = data.map((item: any) => item.code);
const charts = Queries.map((item: any) => item.data); const charts = Queries.map((item: any) => item.data);
const successfulRequests = Queries.filter( const successfulRequests = Queries.filter(
(item: any) => item.isSuccess == true (item: any) => item.isSuccess == true
); );
return ( return (
<div className=""> <div className="">
{successfulRequests.length == data.length && ( {successfulRequests.length == data.length && (
@ -43,6 +42,7 @@ export default function Reports({ data }: { data: any }) {
value={item.code} value={item.code}
> >
{item.title} {item.title}
{/* <BsBarChartLineFill /> نمودار شماره یک */}
</TabsTrigger> </TabsTrigger>
); );
})} })}
@ -65,6 +65,22 @@ export default function Reports({ data }: { data: any }) {
</TabsContent> </TabsContent>
); );
})} })}
{/* Tab Content */}
{/* <TabsContent value="tab1" className="w-full h-full ">
<VerticalChart />
</TabsContent>
<TabsContent value="tab2" className="w-full h-full ">
<HorizontalChart />
</TabsContent>
<TabsContent value="tab3" className="w-full h-full ">
<LineChart />
</TabsContent>
<TabsContent value="tab4" className="w-full h-full ">
<HorizontalChart />
</TabsContent> */}
</div> </div>
</Tabs> </Tabs>
)} )}

View File

@ -1,51 +1,44 @@
"use client"; "use client";
import React, { useState, useEffect, useRef } from "react"; import React, { useState, useEffect } from "react";
import { Input } from "./ui/input"; import { Input } from "./ui/input";
import { Label } from "./ui/label"; import { Label } from "./ui/label";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
import { CiSearch } from "react-icons/ci"; import { CiSearch } from "react-icons/ci";
import { X, XCircle } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { IoMdClose } from "react-icons/io";
import { useMediaQuery } from "react-responsive";
export default function Search({ export default function Search({
mode, mode,
value, value,
action, action,
Cancel,
changeValue, changeValue,
}: { }: {
mode?: string; mode?: string;
value?: any; value?: any;
action?: (any: any) => any; action?: (any: any) => any;
Cancel: (any: any) => any; changeValue?: (any: any) => any ;
changeValue?: (any: any) => any;
}) { }) {
const inputRef = useRef<HTMLInputElement>(null); // useEffect(() => {
const [cancel, setCancel] = useState<boolean>(false); // const isMobile = useMediaQuery({ query: "(max-width: 768px)" });
const handleSubmit = (e: any) => { // }, []);
e.preventDefault();
setCancel(true);
};
const cancelSearch = (e: any) => {
e.preventDefault();
setCancel(false);
if (changeValue !== undefined) {
changeValue("");
}
Cancel(true);
};
return ( return (
<form <div className="relative flex items-center w-full bg-gray-300 lg:w-1/5 rounded-xl">
onSubmit={handleSubmit}
className="relative flex items-center w-full bg-gray-300 lg:w-1/5 rounded-xl"
>
<Input <Input
// type="search" // type="search"
ref={inputRef}
id="default-search" id="default-search"
className={`mb-0 h-8 bg-[#E9E9E9] border-none focus-visible:none rounded-lg className={`mb-0 h-8 bg-[#E9E9E9] border-none focus-visible:none rounded-lg
block w-full text-xs md:text-sm text-black block w-full min-w-[13rem] text-xs md:text-sm text-black
text-opacity-60 dark:text-white text-opacity-60 dark:text-white
${mode === "controller" && "h-14 "} ${mode === "controller" && "h-14 "}
${ ${
@ -56,28 +49,20 @@ export default function Search({
value={value} value={value}
onChange={(e) => { onChange={(e) => {
if (changeValue) { if (changeValue) {
setCancel(false);
changeValue(e.target.value); changeValue(e.target.value);
} }
}} }}
placeholder="جستجو..." placeholder="جستجو..."
required
/> />
{cancel ? ( {/* <Button
<button className="absolute left-0 w-auto h-auto bg-transparent text-slate-800"
onClick={cancelSearch} >
type="button" <CiSearch />
className="absolute left-3" </Button> */}
> <button onClick={action} className="absolute left-3">
<X className=" text-gray-600 h-5 w-5" />
</button>
) : (
<button onClick={action} className="absolute left-3">
<CiSearch className="h-4 w-4" />
</button>
)}
{/* <button onClick={action} className="absolute left-3">
<CiSearch /> <CiSearch />
</button> */} </button>
</form> </div>
); );
} }

View File

@ -24,32 +24,44 @@ import useData from "@/store/useData";
import { toast } from "sonner"; import { toast } from "sonner";
import Pagination from "./Pagination"; import Pagination from "./Pagination";
import { Skeleton } from "./ui/skeleton"; import { Skeleton } from "./ui/skeleton";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useMediaQuery } from "react-responsive";
export default function TabController() { export default function TabController() {
const isMobile = useMediaQuery({ maxWidth: 768 }); // Adjust the max width for mobile const saveData = useData((state) => state.saveData);
const [selectedFile, setSelectedFile] = useState<any>(null);
const [search, setSearch] = useState<any>(null); const [search, setSearch] = useState<any>(null);
const [page, setPage] = useState<any>(1); const [page, setPage] = useState<any>(1);
const [totalCount, setTotalCount] = useState<any>(0); const [totalCount, setTotalCount] = useState<any>(0);
const [currentPage, setCurrentPage] = useState<any>(0);
const [pageSize, setPageSize] = useState<any>(0);
const [totalPages, setTotalPages] = useState<any>(0);
const [cancel, setCancel] = useState<boolean>(false);
const router = useRouter(); const router = useRouter();
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);
};
reader.readAsText(file);
};
const checkKey = (item: any) => {
const dcKey = Decrypt(item.cipherKeyInspector, selectedFile);
if (dcKey != false && dcKey != null) {
saveData({
trackingNumber: item.trackingNumber,
password: Decrypt(item.cipherKeyInspector, selectedFile),
});
router.push(`/UserPanel/ControllerDashboard/Complaints/${item.id}`);
} else {
toast("کلید شما معتبر نمی باشد.", {
className: "!bg-red-500 !text-white",
});
}
};
const [psblState, setPsblState] = useState(0); const [psblState, setPsblState] = useState(0);
const [selectedTab, setSelectedTab] = useState<string>("0"); const [selectedTab, setSelectedTab] = useState("0");
const { const {
data: dataState, data: dataState,
@ -61,6 +73,9 @@ export default function TabController() {
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
}); });
// const initialSelectedTab = dataState[0]?.value || '';
// setSelectedTab(initialSelectedTab);
const { data, isLoading, refetch } = useQuery({ const { data, isLoading, refetch } = useQuery({
queryKey: ["ComplaintsList", psblState, dataState, page], queryKey: ["ComplaintsList", psblState, dataState, page],
queryFn: () => queryFn: () =>
@ -73,274 +88,108 @@ export default function TabController() {
}); });
const handelSearch = (event: any) => { const handelSearch = (event: any) => {
setPage(1);
refetch(); refetch();
}; };
useEffect(() => {
if (cancel) {
refetch();
}
}, [cancel]);
useEffect(() => { useEffect(() => {
if (data) { if (data) {
const headersData = JSON.parse(data.headers["x-pagination"]); const headersData = JSON.parse(data.headers["x-pagination"]);
setTotalCount(headersData.TotalCount); setTotalCount(headersData.TotalCount);
setTotalPages(headersData.TotalPages);
setCurrentPage(headersData.CurrentPage);
setPageSize(headersData.PageSize);
setCancel(false);
} }
}, [data]); }, [data]);
useEffect(() => {
const activeTab = localStorage.getItem("ActiveTab");
const activePage = localStorage.getItem("ActivePage");
if (activeTab) {
setSelectedTab(activeTab);
setPsblState(Number(activeTab));
}
if (activePage) {
setCurrentPage(activePage);
}
}, []);
const isZero = totalCount === 0; const isZero = totalCount === 0;
console.log(totalCount);
return ( return (
<div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-16 pt-9 mx-auto"> <div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-16 pt-9 mx-auto">
{isMobile ? ( <p className="my-2 text-xs font-bold 3xl:ml-6 sm:text-sm xl:hidden">
// Render your shadcn Select for mobile لیست شکایت ها
<div> </p>
<Tabs value={String(selectedTab)} className="" dir="rtl"> <Tabs
<div className="flex flex-col-reverse items-center justify-between w-full gap-4 mb-5 lg:flex-row lg:gap-2"> // defaultValue="0"
<Select value={String(selectedTab)}
value={selectedTab} // onClick={(value) => {
onValueChange={(value) => { // setPsblState(value);
setPsblState(Number(value)); // setSelectedTab(value);
setSelectedTab(String(value)); // refetch();
localStorage.setItem("ActiveTab", String(value)); // }}
localStorage.setItem("ActivePage", page); className=""
refetch(); dir="rtl"
setSearch(""); >
setPage(1); <div className="flex flex-col-reverse items-center justify-between w-full gap-4 mb-10 lg:flex-row lg:gap-2">
}} {/* Tab Title */}
> <TabsList className="flex w-full gap-1 h-a max-lg:flex-wrap max lg:w-4/5 md:gap-4 lg:gap-1 p-1">
<SelectTrigger className="w-full h-12 bg-[#E9E9E9] " dir="rtl"> <p className="text-xs font-bold 3xl:ml-6 sm:text-sm max-xl:hidden">
<SelectValue placeholder="انتخاب دسته بندی" /> لیست شکایت ها |
</SelectTrigger> </p>
<SelectContent dir="rtl">
{dataState?.map((item: any) => (
<SelectItem key={item.value} value={String(item.value)}>
{item.title} ({item.count})
</SelectItem>
))}
</SelectContent>
</Select>
{/* Search Box */}
<Search
value={search}
changeValue={(data: any) => setSearch(data)}
mode="controller"
action={handelSearch}
Cancel={() => setCancel(true)}
/>
</div>
{/* Tab Content */} {dataState?.map((item: any) => {
<TabsContent value={selectedTab} key={selectedTab}> // const isActive = item.value === selectedTab;
{data ? ( return (
<TableController <TabsTrigger
data={data?.data} key={item.value}
currentPage={currentPage} className="hover:border-b-2 border-b-blue flex-1 h-10"
pageSize={pageSize} value={String(item.value)}
/> // data-state={isActive ? 'active' : 'inactive'}
) : ( onClick={() => {
<div className="flex flex-col gap-3"> setPsblState(item.value);
<Skeleton className="w-full h-12" /> setSelectedTab(String(item.value));
<Skeleton className="w-full h-12" /> refetch();
<Skeleton className="w-full h-12" /> setPage(0);
<Skeleton className="w-full h-12" /> }}
</div> >
)} <div className="relative w-full ">
{item.title} ({item.count})
</div>
</TabsTrigger>
);
})}
</TabsList>
{!isZero ? ( {/* Search Box */}
<Pagination <Search
TotalPages={totalPages} value={search}
currentPage={currentPage - 1} changeValue={(data: any) => setSearch(data)}
countPage={totalCount} mode="controller"
Page={(num: number) => setPage(num + 1)} action={handelSearch}
/> />
) : (
<>
{" "}
{data?.data.length == 0 && (
<p className="flex justify-center mx-auto mt-10 text-blue/50">
گزارشی وجود ندارد
</p>
)}
</>
)}
</TabsContent>
</Tabs>
</div> </div>
) : (
// Render Tabs for larger screens
// <Tabs value={String(selectedTab)} className="" dir="rtl">
// <div className="flex flex-col-reverse items-center justify-between w-full gap-4 mb-5 lg:flex-row lg:gap-2">
// {/* Tab Title */} {/* Tab Content */}
// <TabsList className="flex w-full gap-1 h-a max-lg:flex-wrap max lg:w-4/5 md:gap-4 lg:gap-1 p-1">
// {/* <p className="text-xs font-bold 3xl:ml-6 sm:text-sm max-xl:hidden">
// لیست شکایت ها |
// </p> */}
// {dataState?.map((item: any) => { <TabsContent value={selectedTab} key={selectedTab}>
// return ( {data ? (
// <TabsTrigger <TableController
// key={item.value} checkKey={(item) => checkKey(item)}
// className="hover:border-b-2 border-b-blue flex-1 h-10" data={data?.data}
// value={String(item.value)} />
// // data-state={isActive ? 'active' : 'inactive'} ) : (
// onClick={() => { <div className="flex flex-col gap-3">
// setPsblState(item.value); <Skeleton className="w-full h-12" />
// setSelectedTab(String(item.value)); <Skeleton className="w-full h-12" />
// localStorage.setItem("ActiveTab", String(item.value)); <Skeleton className="w-full h-12" />
// localStorage.setItem("ActivePage", page); <Skeleton className="w-full h-12" />
// refetch();
// setSearch("");
// setPage(1);
// }}
// >
// <div className="relative w-full ">
// {item.title} ({item.count})
// </div>
// </TabsTrigger>
// );
// })}
// </TabsList>
// {/* Search Box */}
// <Search
// value={search}
// changeValue={(data: any) => setSearch(data)}
// mode="controller"
// action={handelSearch}
// Cancel={() => setCancel(true)}
// />
// </div>
// {/* Tab Content */}
// <TabsContent value={selectedTab} key={selectedTab}>
// {data ? (
// <TableController
// data={data?.data}
// currentPage={currentPage}
// pageSize={pageSize}
// />
// ) : (
// <div className="flex flex-col gap-3">
// <Skeleton className="w-full h-12" />
// <Skeleton className="w-full h-12" />
// <Skeleton className="w-full h-12" />
// <Skeleton className="w-full h-12" />
// </div>
// )}
// {!isZero ? (
// <Pagination
// TotalPages={totalPages}
// currentPage={currentPage - 1}
// countPage={totalCount}
// Page={(num: number) => setPage(num + 1)}
// />
// ) : (
// <>
// {" "}
// {data?.data.length == 0 && (
// <p className="flex justify-center mx-auto mt-10 text-blue/50">
// درخواستی وجود ندارد
// </p>
// )}
// </>
// )}
// </TabsContent>
// </Tabs>
<div>
<Tabs value={String(selectedTab)} className="" dir="rtl">
<div className="flex flex-col-reverse items-center justify-between w-full gap-4 mb-5 lg:flex-row lg:gap-2">
{/* Tab Title */}
<TabsList className="flex w-full gap-1 h-a max-lg:flex-wrap max lg:w-4/5 md:gap-4 lg:gap-1 p-1">
{dataState?.map((item: any) => (
<TabsTrigger
key={item.value}
className="hover:border-b-2 border-b-blue flex-1 h-10"
value={String(item.value)}
onClick={() => {
setPsblState(item.value);
setSelectedTab(String(item.value));
localStorage.setItem("ActiveTab", String(item.value));
localStorage.setItem("ActivePage", String(currentPage));
refetch();
setSearch("");
setPage(1);
}}
>
<div className="relative w-full ">
{item.title} ({item.count})
</div>
</TabsTrigger>
))}
</TabsList>
{/* Search Box */}
<Search
value={search}
changeValue={(data: any) => setSearch(data)}
mode="controller"
action={handelSearch}
Cancel={() => setCancel(true)}
/>
</div> </div>
)}
{/* Tab Content */} {!isZero ? (
<TabsContent value={selectedTab} key={selectedTab}> <Pagination
{data ? ( // length={data3?.data.length}
<TableController // itemsPerPage={1}
data={data?.data} countPage={totalCount}
currentPage={currentPage} Page={(num: number) => setPage(num + 1)}
pageSize={pageSize} />
/> ) : (
) : ( <>
<div className="flex flex-col gap-3"> {" "}
<Skeleton className="w-full h-12" /> {data?.data.length == 0 && (
<Skeleton className="w-full h-12" /> <p className="flex justify-center mx-auto mt-10 text-blue/50">
<Skeleton className="w-full h-12" /> درخواستی وجود ندارد
<Skeleton className="w-full h-12" /> </p>
</div>
)} )}
</>
{!isZero ? ( )}
<Pagination </TabsContent>
TotalPages={totalPages} </Tabs>
currentPage={currentPage - 1}
countPage={totalCount}
Page={(num: number) => setPage(num + 1)}
/>
) : (
<>
{" "}
{data?.data.length == 0 && (
<p className="flex justify-center mx-auto mt-10 text-blue/50">
گزارشی وجود ندارد
</p>
)}
</>
)}
</TabsContent>
</Tabs>
</div>
)}
</div> </div>
); );
} }

View File

@ -21,7 +21,7 @@ import {
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { ControllerTableItems } from "@/constants"; import { ControllerTableItems } from "@/constants";
import Link from "next/link"; import Link from "next/link";
import { Decrypt, convertDate, convertFullTime } from "@/lib/utils"; import { Decrypt, convertDate } from "@/lib/utils";
import useData from "@/store/useData"; import useData from "@/store/useData";
import { Label } from "./ui/label"; import { Label } from "./ui/label";
import { Input } from "./ui/input"; import { Input } from "./ui/input";
@ -53,69 +53,154 @@ interface Complaint {
} }
export default function TableController({ export default function TableController({
data, data,
pageSize, checkKey,
currentPage,
}: { }: {
data: Complaint[]; data: Complaint[];
pageSize: number; checkKey: (item: any) => any;
currentPage: number;
}) { }) {
const saveData = useData((state) => state.saveData);
const [selectedFile, setSelectedFile] = useState<any>(null);
const [open, setOpen] = useState<boolean>(false);
const [rowData, setRowData] = useState<Complaint | null>(null);
const [check, setCheck] = useState<any>(false);
const router = useRouter(); const router = useRouter();
const handleFileChange = (event: any) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const contents = e?.target?.result;
setSelectedFile(contents);
};
reader.readAsText(file);
};
const checkKey2 = (item: any) => {
const dcKey = Decrypt(item.cipherKeyInspector, selectedFile);
if (dcKey != false && dcKey != null) {
saveData({
trackingNumber: item.trackingNumber,
password: Decrypt(item.cipherKeyInspector, selectedFile),
});
secureLocalStorage.setItem("trackingNumber", item.trackingNumber);
secureLocalStorage.setItem("privateKey", selectedFile);
// secureLocalStorage.setItem(
// "privateKey",
// Decrypt(item.cipherKeyInspector, selectedFile)
// );
router.push(`/UserPanel/ControllerDashboard/Complaints/${item.id}`);
} else {
// toast("******کلید شما معتبر نمی باشد.", {
// className: "!bg-red-500 !text-white",
// });
}
};
console.log(check);
return ( return (
<div className=" overflow-hidden"> <div>
<div className="max-h-[50vh] lg:max-h-[65vh] overflow-auto scrollbar-thin scrollbar-thumb-gray-500 scrollbar-track-gray-100"> <Table className="border-[1px] border-solid border-muted rounded-md w-full min-w-[40rem] overflow-y-auto scrollbar-thumb-gray-600 scrollbar-track-gray-100 scrollbar-thin">
<Table className="border-[1px] border-solid border-muted rounded-md w-full min-w-[40rem] mb-8 md:mb-4 2xl:mb-0 "> {/* <TableCaption>A list of your recent invoices.</TableCaption> */}
{/* <TableCaption>A list of your recent invoices.</TableCaption> */} <TableHeader>
<TableHeader> <TableRow>
<TableRow> <TableHead>ردیف</TableHead>
<TableHead>ردیف</TableHead> <TableHead>کد پیگیری</TableHead>
<TableHead>کد پیگیری</TableHead> <TableHead> تاریخ ثبت</TableHead>
<TableHead> تاریخ ثبت</TableHead> <TableHead>تاریخ</TableHead>
<TableHead>تاریخ آخرین تغییر</TableHead> <TableHead>موضوع</TableHead>
<TableHead>موضوع</TableHead> <TableHead>دستگاه مربوطه</TableHead>
<TableHead>دستگاه مرتبط</TableHead> </TableRow>
</TableRow> </TableHeader>
</TableHeader> <TableBody className="bg-[#F5F5F5] min-h-[20rem] ">
<TableBody className="bg-[#F5F5F5] min-h-[20rem] "> {data?.map((item: Complaint, index: number) => {
{data?.map((item: Complaint, index: number) => { return (
<TableRow
onClick={() => {
localStorage.setItem("CompliantData", JSON.stringify(item));
router.push(
`/UserPanel/ControllerDashboard/Complaints/${item.id}`
);
}}
className="cursor-pointer hover:bg-gray-200"
key={item.id}
>
{/* <Link
href={`/UserPanel/ControllerDashboard/Complaints/${item.id}`}
className="contents"
> */}
<TableCell className="w-1/12 font-medium ">
{index + 1}
</TableCell>
<TableCell className="w-1/12">{item.trackingNumber}</TableCell>
<TableCell className="w-2/12">
{convertDate(item.registeredAt)}
</TableCell>
<TableCell className="w-2/12">
{convertDate(item.lastChanged)}
</TableCell>
<TableCell className="w-3/12">
{item?.title ? item.title : "-"}
</TableCell>
<TableCell className="w-3/12">
{item?.complaintOrganization
? item?.complaintOrganization.title
: "-"}
</TableCell>
{/* </Link> */}
</TableRow>
);
})}
{data.length != 0 &&
[...Array(5 - data.length)].map(() => {
return ( return (
<TableRow <TableRow
onClick={() => { key={Math.random()}
localStorage.setItem("CompliantData", JSON.stringify(item)); className="border border-t-0 border-b-0"
router.push( />
`/UserPanel/ControllerDashboard/Complaints/${item.id}`
);
}}
className="cursor-pointer hover:bg-gray-200 "
key={item.id}
>
<TableCell className="w-1/12 font-medium ">
{pageSize * (currentPage - 1) + (index + 1)}
</TableCell>
<TableCell className="w-1/12">
{item.trackingNumber}
</TableCell>
<TableCell className="w-2/12">
{convertFullTime(item.registeredAt)}
</TableCell>
<TableCell className="w-2/12">
{convertFullTime(item.lastChanged)}
</TableCell>
<TableCell className="w-3/12 truncate max-w-[1em]">
{item?.title ? item.title : "-"}
</TableCell>
<TableCell className="w-3/12">
{item?.complaintOrganization
? item?.complaintOrganization.title
: "-"}
</TableCell>
</TableRow>
); );
})} })}
</TableBody> </TableBody>
</Table> </Table>
</div> <Dialog open={open} onOpenChange={setOpen}>
<DialogContent dir="rtl" className="sm:max-w-[425px]">
<DialogHeader dir="rtl">
<DialogTitle dir="rtl">بارگذاری کلید خصوصی</DialogTitle>
<DialogDescription>
لطفا کلید خصوصی خود را آپلود نمایید.
</DialogDescription>
</DialogHeader>
<div className="grid w-full max-w-sm items-center gap-1.5">
{/* <Label htmlFor="picture">Picture</Label> */}
<Input
dir="rtl"
id="picture"
onChange={handleFileChange}
type="file"
accept=".txt"
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
checked={check}
onCheckedChange={setCheck}
id="terms"
className="ml-2 "
/>
<label
htmlFor="terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
ذخیره کلید برای دفعات بعد
</label>
</div>
<DialogFooter>
<DialogClose asChild></DialogClose>
<Button onClick={() => checkKey2(rowData)} type="submit">
ذخیره
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }

60
components/TopNav.tsx Normal file
View File

@ -0,0 +1,60 @@
"use client";
import React from "react";
import { Input } from "./ui/input";
import Link from "next/link";
import Search from "./Search";
import { usePathname } from "next/navigation";
export default function TopNav() {
const pathname = usePathname();
return (
<div
className={`flex justify-between items-center w-full px-8 py-1 z-10 border-b-[#C9CFD7] border-b-[1px] border-solid max-md:bg-gray max-md:bg-transparent max-md:px-0 max-md:justify-end max-md:border-b-0 ${
pathname === "/" ? "bg-transparent" : "bg-white"
} `}
>
<p className="bg-gradient-to-r from-gradient1 to-gradient2 inline-block text-transparent bg-clip-text text-xs max-md:hidden font-bold">
سال 1402 | مهارم تورم، رشد تولید
</p>
{/* <p>Current pathname: {pathname}</p> */}
<div className="flex items-center gap-10">
<div className=" flex items-center gap-3 md:ml-4">
<p className="bg-gradient-to-r from-gradient1 to-gradient2 inline-block text-transparent bg-clip-text text-xs max-md:text-xs font-bold">
امروز: چهارشنبه 24 آبان 1402
</p>
<svg
className="max-md:hidden"
xmlns="http://www.w3.org/2000/svg"
width="18"
height="19"
viewBox="0 0 18 19"
fill="none"
>
<g clip-path="url(#clip0_113_99)">
<path
d="M11.2875 4.25C12.02 4.39292 12.6932 4.75119 13.221 5.27895C13.7488 5.80671 14.107 6.47995 14.2499 7.2125L11.2875 4.25ZM11.2875 1.25C12.8094 1.41908 14.2286 2.10063 15.3121 3.18276C16.3956 4.26488 17.079 5.68326 17.2499 7.205L11.2875 1.25ZM16.4999 13.19V15.44C16.5008 15.6489 16.458 15.8556 16.3743 16.047C16.2907 16.2384 16.1679 16.4102 16.014 16.5514C15.8601 16.6926 15.6784 16.8001 15.4805 16.867C15.2826 16.9339 15.073 16.9588 14.8649 16.94C12.5571 16.6892 10.3402 15.9006 8.39245 14.6375C6.58032 13.486 5.04395 11.9496 3.89245 10.1375C2.62493 8.1809 1.83613 5.95325 1.58995 3.635C1.57121 3.4276 1.59586 3.21857 1.66233 3.02122C1.72879 2.82387 1.83563 2.64252 1.97602 2.48872C2.11642 2.33491 2.2873 2.21203 2.47779 2.12789C2.66828 2.04375 2.87421 2.0002 3.08245 2H5.33245C5.69643 1.99642 6.04929 2.12531 6.32527 2.36265C6.60125 2.59999 6.78151 2.92959 6.83245 3.29C6.92742 4.01005 7.10354 4.71705 7.35745 5.3975C7.45836 5.66594 7.4802 5.95769 7.42038 6.23816C7.36056 6.51863 7.2216 6.77608 7.01995 6.98L6.06745 7.9325C7.13512 9.81016 8.68979 11.3648 10.5675 12.4325L11.5199 11.48C11.7239 11.2784 11.9813 11.1394 12.2618 11.0796C12.5423 11.0198 12.834 11.0416 13.1024 11.1425C13.7829 11.3964 14.4899 11.5725 15.21 11.6675C15.5743 11.7189 15.907 11.9024 16.1448 12.1831C16.3827 12.4638 16.5091 12.8222 16.4999 13.19Z"
stroke="black"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
<defs>
<clipPath id="clip0_113_99">
<rect
width="18"
height="18"
fill="white"
transform="translate(0 0.5)"
/>
</clipPath>
</defs>
</svg>
</div>
</div>
</div>
);
}

View File

@ -23,8 +23,8 @@ export default function Verify() {
mutationFn: verifyStaff, mutationFn: verifyStaff,
onSuccess: (res) => { onSuccess: (res) => {
const decodedToken = jwtDecode<any>(res.jwtToken); const decodedToken = jwtDecode<any>(res.jwtToken);
setCookie("Sootzani_Admin_Token", res.jwtToken); setCookie("Sootzani_Token", res.jwtToken);
setCookie("Sootzani_Admin_Refresh_Token", res.refreshToken); setCookie("Sootzani_Refresh_Token", res.refreshToken);
const userRole = const userRole =
decodedToken[ decodedToken[
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
@ -53,12 +53,13 @@ export default function Verify() {
otpToken: localStorage.getItem("verificationToken"), otpToken: localStorage.getItem("verificationToken"),
verificationCode: otp, verificationCode: otp,
}; };
console.log(userData);
verifyMutation.mutate(payload); verifyMutation.mutate(payload);
} }
}, [otp]); }, [otp]);
return ( return (
<div className="grid w-screen h-screen bg-left-top bg-repeat bg-[url('/img/login-pattern.png')] place-content-center"> <div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div <div
className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040] className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-fit relative" h-fit relative"

View File

@ -70,7 +70,8 @@ function BarChart({
// var value2 = chartData[1].values.map((item) => Number(item.value)); // var value2 = chartData[1].values.map((item) => Number(item.value));
// DataSets.push({ label: label1, data: value1 }); // DataSets.push({ label: label1, data: value1 });
// DataSets.push({ label: label2, data: value2 }); // DataSets.push({ label: label2, data: value2 });
// // console.log(labels);
// // console.log(value1);
// } else if ("گزارش تعداد درخواست ها بر اساس نوع بیمه") { // } else if ("گزارش تعداد درخواست ها بر اساس نوع بیمه") {
// var labels = chartData[0].values.map((item) => { // var labels = chartData[0].values.map((item) => {
// return item.title; // return item.title;
@ -78,8 +79,9 @@ function BarChart({
// var label1 = ""; // var label1 = "";
// var value1 = chartData[0].values.map((item) => Number(item.value)); // var value1 = chartData[0].values.map((item) => Number(item.value));
// DataSets.push({ label: label1, data: value1 }); // DataSets.push({ label: label1, data: value1 });
// console.log(value1);
// } // }
console.log(chartData);
const options: ChartOptions<"bar"> = { const options: ChartOptions<"bar"> = {
scales: { x: { ticks: { autoSkip: false } }, y: { stacked: false } }, scales: { x: { ticks: { autoSkip: false } }, y: { stacked: false } },
responsive: true, responsive: true,
@ -110,10 +112,12 @@ function BarChart({
// // suggestedMax: // // suggestedMax:
// // Math.max( // // Math.max(
// // ...chartData.map((l, j) => { // // ...chartData.map((l, j) => {
// // console.log(l);
// // const a = l.values.map((v) => { // // const a = l.values.map((v) => {
// // return Number(v.value); // // return Number(v.value);
// // }); // // });
// // const b = Math.max(...a); // // const b = Math.max(...a);
// // console.log(b);
// // return l.values.map((v) => Number(v.value)); // // return l.values.map((v) => Number(v.value));
// // }) // // })
// // ) * 1.2, // // ) * 1.2,
@ -136,6 +140,7 @@ function BarChart({
}; };
}), }),
}; };
// console.log(data);
return ( return (
<Bar dir="rtl" className="min-h-[20rem]" options={options} data={data} /> <Bar dir="rtl" className="min-h-[20rem]" options={options} data={data} />
); );

View File

@ -1,202 +0,0 @@
"use client";
import React, { useEffect, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { useMutation, useQuery } from "@tanstack/react-query";
import { editProfile, getProfile } from "@/utils/authenticateApi";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Oval } from "react-loader-spinner";
import ChangePhoneNumberDialog from "../ChangePhoneNumberDialog";
import ChangePasswordDialog from "../ChangePasswordDialog";
const FormSchema = z.object({
firstName: z.string().min(1, {
message: "لطفا نام خود را وارد نمایید.",
}),
lastName: z.string().min(1, {
message: "لطفا نام خانوادگی خود را وارد نمایید.",
}),
phoneNumber: z.string().optional(),
});
export default function Profile() {
const router = useRouter();
const [open, setOpen] = useState<boolean>(false);
const [open2, setOpen2] = useState<boolean>(false);
const {
data: profileData,
isLoading,
refetch,
} = useQuery({
queryKey: ["Profile"],
queryFn: () => getProfile(),
refetchOnWindowFocus: false,
});
const editProfileMutation = useMutation({
mutationKey: ["editProfile"],
mutationFn: editProfile,
onSuccess: (res) => {
refetch();
toast("پروفایل شما با موفقیت ویرایش شد.", {
className: "!bg-green-500 !text-white",
});
router.push("/");
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
});
useEffect(() => {
if (profileData) {
form.setValue("firstName", profileData.firstName);
form.setValue("lastName", profileData.lastName);
form.setValue("phoneNumber", profileData.phoneNumber);
}
}, [profileData]);
function onSubmit(data: z.infer<typeof FormSchema>) {
const payload = data;
editProfileMutation.mutate(payload);
}
return (
<div className=" w-full mx-auto mt-20 h-full pt-12 md:w-2/3 xl:w-1/2 p-8">
<div className="flex flex-col justify-center h-full space-y-4 md:space-y-4">
<h2 className=" w-full font-bold">اطلاعات هویتی</h2>
{profileData && (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col w-full mt-6 "
>
<div className="flex flex-row flex-wrap justify-between border p-4 rounded-md">
<FormField
control={form.control}
name="firstName"
render={({ field }) => (
<FormItem className="w-full sm:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium">
نام
</FormLabel>
<FormControl>
<Input
placeholder="نام خود را وارد نمایید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lastName"
render={({ field }) => (
<FormItem className="w-full sm:w-[48%] ">
<FormLabel className="text-[#7C838A] text-sm font-medium">
نام خانوادگی
</FormLabel>
<FormControl>
<Input
placeholder="نام خانوادگی خود را وارد نمایید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end w-full gap-2 mt-8">
<Button
disabled={editProfileMutation.isPending}
type="submit"
className="w-32 p-2 text-white transition bg-blue hover:bg-blue/90 rounded-xl max-sm:text-xs"
>
{editProfileMutation.isPending ? (
<div className="flex items-center justify-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
"ذخیره"
)}
{/* ورود */}
</Button>
</div>{" "}
</div>
<h2 className=" w-full font-bold mt-5 mb-2">اطلاعات ورود</h2>
<div className=" border p-4 flex max-lg:flex-col justify-between rounded-md items-center">
<FormField
control={form.control}
name="phoneNumber"
render={({ field }) => (
<FormItem className="w-full sm:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
شماره موبایل
</FormLabel>
<FormControl>
<Input type="text" {...field} readOnly />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex gap-2 max-md:justify-center max-md:mt-6 max-md:w-full">
<Button
type="button"
disabled={editProfileMutation.isPending}
onClick={() => setOpen(true)}
className="max-sm:w-1/2 w-32 p-2 max-sm:text-xs text-white transition bg-blue hover:bg-blue/90 rounded-xl"
>
تغییر شماره موبایل
</Button>
<Button
type="button"
disabled={editProfileMutation.isPending}
onClick={() => setOpen2(true)}
className="max-sm:w-1/2 w-32 p-2 text-white transition bg-blue hover:bg-blue/90 rounded-xl max-sm:text-xs"
>
تغییر رمز عبور
</Button>
</div>
</div>
</form>
</Form>
)}
</div>
<ChangePhoneNumberDialog open={open} setOpen={setOpen} />
<ChangePasswordDialog open={open2} setOpen={setOpen2} />
</div>
);
}

View File

@ -115,7 +115,7 @@ const AlertDialogAction = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action <AlertDialogPrimitive.Action
ref={ref} ref={ref}
className={cn(buttonVariants(), "mt-2 sm:mt-0", className)} className={cn(buttonVariants(), className)}
{...props} {...props}
/> />
)); ));

View File

@ -9,7 +9,7 @@ const buttonVariants = cva(
{ {
variants: { variants: {
variant: { variant: {
default: "bg-blue text-primary-foreground hover:bg-blue/90", default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90", "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: outline:

View File

@ -13,7 +13,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
className={cn( className={cn(
`flex w-full rounded-md border border-input px-3 py-2 ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 `flex w-full rounded-md border border-input px-3 py-2 ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50
text-black text-opacity-50 text-xs font-normal bg-slate-200 mb-3 text-black text-opacity-50 text-xs font-normal bg-slate-200 mb-3
h-10 transition-all 3xl:h-9 h-10 transition-all
hover:bg-slate-300 hover:cursor-pointer focus:cursor-auto hover:bg-slate-300 hover:cursor-pointer focus:cursor-auto
focus:outline-4 focus:outline-slate-300 focus:bg-slate-200 focus:outline-4 focus:outline-slate-300 focus:bg-slate-200

View File

@ -1,28 +0,0 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }

View File

@ -10,7 +10,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
return ( return (
<Sonner <Sonner
// theme={theme as ToasterProps["theme"]} theme={theme as ToasterProps["theme"]}
className="toaster group !font-[yekan]" className="toaster group !font-[yekan]"
toastOptions={{ toastOptions={{
classNames: { classNames: {

View File

@ -14,7 +14,7 @@ const TabsList = React.forwardRef<
<TabsPrimitive.List <TabsPrimitive.List
ref={ref} ref={ref}
className={cn( className={cn(
"inline-flex min-h-[3.1rem] items-center justify-start rounded-md bg-[#E9E9E9] p-2 text-muted-foreground", "inline-flex min-h-[3.5rem] items-center justify-start rounded-md bg-[#E9E9E9] p-2 text-muted-foreground",
className className
)} )}
{...props} {...props}

View File

@ -24,7 +24,7 @@ export const boxItems = [
name: "ثبت شکایت", name: "ثبت شکایت",
icon: "/img/box1.svg", icon: "/img/box1.svg",
icon2: "/img/box1-hover.svg", icon2: "/img/box1-hover.svg",
description: "ارسال گزارش نارضایتی از پرسنل", description: "ارسال درخواست نارضایتی از پرسنل",
link: "/RequestStep1", link: "/RequestStep1",
}, },
{ {
@ -32,7 +32,7 @@ export const boxItems = [
name: "پیگیری شکایت", name: "پیگیری شکایت",
icon: "/img/box2.svg", icon: "/img/box2.svg",
icon2: "/img/box2-hover.svg", icon2: "/img/box2-hover.svg",
description: "پیگیری گزارش ارسال شده", description: "پیگیری درخواست ارسال شده",
link: "/FollowUp", link: "/FollowUp",
}, },
{ {
@ -40,7 +40,7 @@ export const boxItems = [
name: "ثبت شکایت(شناس)", name: "ثبت شکایت(شناس)",
icon: "/img/box1.svg", icon: "/img/box1.svg",
icon2: "/img/box1-hover.svg", icon2: "/img/box1-hover.svg",
description: "ارسال گزارش نارضایتی از پرسنل", description: "ارسال درخواست نارضایتی از پرسنل",
link: "/CitizenLogin", link: "/CitizenLogin",
}, },
// { // {

View File

@ -34,6 +34,7 @@ dEqG/38xFdYTFEekexcHnT/Vt1MW4/j76vBJHYWuAJU=
); );
setDecryptedData(decrypted); setDecryptedData(decrypted);
} catch (error) { } catch (error) {
console.log(error);
setError(error); setError(error);
} }
}, [encryptedData]); }, [encryptedData]);

View File

@ -1,82 +0,0 @@
import { useCallback, useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
HttpTransportType,
HubConnectionBuilder,
JsonHubProtocol,
LogLevel,
} from "@microsoft/signalr";
import connection from "../utils/signalrConnection";
import { postConnectionId } from "@/utils/inspectorApi";
import { toast } from "sonner";
import { useParams, usePathname } from "next/navigation";
const useSignalR = () => {
const queryClient = useQueryClient();
const pathname = usePathname();
const param = useParams();
const isInComplaintDetailPage = pathname.includes(
"/UserPanel/ControllerDashboard/Complaints/"
);
const postConnectionIdMutation = useMutation({
mutationKey: ["connectionId"],
mutationFn: postConnectionId,
onSuccess: (res) => {},
onError: (err) => {},
});
useEffect(() => {
const role = localStorage.getItem("Sootzani_Role");
if (role != "Admin") {
const startConnection = async () => {
try {
await connection.start();
postConnectionIdMutation.mutate(connection.connectionId);
connection.on("Created", (message) => {
queryClient.invalidateQueries(["ComplaintsList"]);
toast.info("یک گزارش جدید دارید.");
});
connection.on("Updated", (message, id) => {
toast.info(`${message}`);
if (param.id == id) {
queryClient.invalidateQueries(["Complaint", id]);
}
});
} catch (err) {
console.error("SignalR connection failed: ", err);
}
};
startConnection();
}
// return () => {
// if (connection.state === "Connected") {
// connection.stop();
// console.log("SignalR disconnected");
// }
// };
}, []);
useEffect(() => {
if (connection.connectionId) {
console.log(connection.connectionId);
}
}, [connection]);
// console.log(connection.state);
// useEffect(() => {
// console.log(11111);
// console.log(connection.state);
// // Subscribe to events and update query data accordingly
// // Example: Listen for a "newMessage" event and update a query with the new message data
// console.log(connection.state);
// }, [queryClient]);
// return connection;
};
export default useSignalR;

View File

@ -4,19 +4,15 @@ import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"; import utc from "dayjs/plugin/utc";
import jalaliday from "jalaliday"; import jalaliday from "jalaliday";
import JSEncrypt from "jsencrypt"; import JSEncrypt from "jsencrypt";
import timezone from "dayjs/plugin/timezone";
import moment from "jalali-moment";
dayjs.extend(jalaliday); dayjs.extend(jalaliday);
dayjs.extend(utc); dayjs.extend(utc);
dayjs.extend(timezone);
// dayjs.tz.setDefault("Etc/GMT-3:30");
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)); return twMerge(clsx(inputs));
} }
export function convertDate(date: string) { export function convertDate(date: string) {
const convertedDate = dayjs(date + "Z") const convertedDate = dayjs(date)
.calendar("jalali") .calendar("jalali")
.locale("fa") .locale("fa")
.format("YYYY/M/DD"); .format("YYYY/M/DD");
@ -24,10 +20,10 @@ export function convertDate(date: string) {
} }
export function convertFullTime(date: string) { export function convertFullTime(date: string) {
const convertedDate = dayjs(date + "Z") const convertedDate = dayjs(date)
.calendar("jalali") .calendar("jalali")
.locale("fa") .locale("fa")
.format(" HH:mm - YYYY/M/D"); .format(" HH:mm - YYYY/M/DD");
return convertedDate; return convertedDate;
} }
@ -37,16 +33,3 @@ export function Decrypt(encryptedData: any, privateKey: any) {
const decrypted = decryptor.decrypt(encryptedData); const decrypted = decryptor.decrypt(encryptedData);
return decrypted; return decrypted;
} }
export function formatBytes(bytes: number, decimals = 2) {
if (!+bytes) return "0 Bytes";
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}

View File

@ -1,8 +1,8 @@
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
output: "standalone", output: "standalone",
images: { images: {
domains: ["sootzaniapi.shetabdahi.ir", "oyoonapi.yazd.ir"], domains: ["sootzaniapi.shetabdahi.ir"],
}, },
}; };
module.exports = nextConfig; module.exports = nextConfig;

695
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "sootzani", "name": "sootzani",
"version": "0.2.23", "version": "0.2.5",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@ -10,14 +10,12 @@
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^3.3.2", "@hookform/resolvers": "^3.3.2",
"@microsoft/signalr": "^8.0.0",
"@radix-ui/react-alert-dialog": "^1.0.5", "@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-checkbox": "^1.0.4", "@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5", "@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6", "@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2", "@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-progress": "^1.0.3",
"@radix-ui/react-radio-group": "^1.1.3", "@radix-ui/react-radio-group": "^1.1.3",
"@radix-ui/react-scroll-area": "^1.0.5", "@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0", "@radix-ui/react-select": "^2.0.0",
@ -40,7 +38,6 @@
"framer-motion": "^10.16.16", "framer-motion": "^10.16.16",
"hamburger-react": "^2.5.0", "hamburger-react": "^2.5.0",
"i": "^0.3.7", "i": "^0.3.7",
"jalali-moment": "^3.3.11",
"jalaliday": "^2.3.0", "jalaliday": "^2.3.0",
"jsencrypt": "^3.3.2", "jsencrypt": "^3.3.2",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
@ -49,7 +46,6 @@
"lucide-react": "^0.292.0", "lucide-react": "^0.292.0",
"next": "14.0.3", "next": "14.0.3",
"next-nprogress-bar": "^2.1.2", "next-nprogress-bar": "^2.1.2",
"next-runtime-env": "^3.2.0",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"nextjs-toploader": "^1.6.4", "nextjs-toploader": "^1.6.4",
"npm": "^10.2.5", "npm": "^10.2.5",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 548 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

View File

@ -1,11 +1,10 @@
import axios from "axios"; import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next"; import { CookieValueTypes, getCookie } from "cookies-next";
import { env } from "next-runtime-env";
const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP"); axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
axios.defaults.baseURL = NEXT_PUBLIC_BASE_URL_APP;
axios.interceptors.request.use(function (config) { axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Admin_Token"); const token = getCookie("Sootzani_Token");
config.headers.Authorization = token ? `Bearer ${token}` : ""; config.headers.Authorization = token ? `Bearer ${token}` : "";
return config; return config;
}); });
@ -28,7 +27,6 @@ export async function AddKey(payload: { title: string; publicKey: string }) {
export async function ChangeKey(payload: { export async function ChangeKey(payload: {
privateKey: string; privateKey: string;
publicKeyId: string; publicKeyId: string;
isPolling: boolean;
}) { }) {
const data = await axios.post("api/Admin/ChangeKey", payload); const data = await axios.post("api/Admin/ChangeKey", payload);
return data.data; return data.data;
@ -162,26 +160,18 @@ export async function UpdateWebContents({
} }
// .....News................................................. // .....News.................................................
export async function GetAllNews({ export async function GetAllNews() {
PageNumber = 1, const data = await axios.get("api/News");
PageSize = 4, return data.data;
}: {
PageNumber?: number;
PageSize?: number;
}) {
const data = await axios.get("api/News", {
params: { PageNumber: PageNumber, PageSize: PageSize },
});
return data;
} }
export async function GetSingleNews(id: string) { export async function GetSingleNews({ id }: { id: string }) {
const data = await axios.get(`api/News/${id}`); const data = await axios.get(`api/News/${id}`);
return data.data; return data.data;
} }
export async function SubmitNews(payload: FormData) { export async function SubmitNews(payload: FormData) {
const data = await axios.post("api/News", payload, { const data = await axios.post("api/News", payload , {
headers: { "Content-Type": "multipart/form-data" }, headers: { "Content-Type": "multipart/form-data" },
}); });
return data.data; return data.data;
@ -194,7 +184,7 @@ export async function UpdateNews({
id: string; id: string;
payload: FormData; payload: FormData;
}) { }) {
const data = await axios.put(`api/News/${id}`, payload, { const data = await axios.put(`api/News/${id}`, payload , {
headers: { "Content-Type": "multipart/form-data" }, headers: { "Content-Type": "multipart/form-data" },
}); });
return data.data; return data.data;
@ -217,7 +207,7 @@ export async function GetSingleSlider({ id }: { id: string }) {
} }
export async function SubmitSlider(payload: FormData) { export async function SubmitSlider(payload: FormData) {
const data = await axios.post("api/Sliders", payload, { const data = await axios.post("api/Sliders", payload , {
headers: { "Content-Type": "multipart/form-data" }, headers: { "Content-Type": "multipart/form-data" },
}); });
return data.data; return data.data;
@ -230,7 +220,7 @@ export async function UpdateSlider({
id: string; id: string;
payload: FormData; payload: FormData;
}) { }) {
const data = await axios.put(`api/Sliders/${id}`, payload, { const data = await axios.put(`api/Sliders/${id}`, payload , {
headers: { "Content-Type": "multipart/form-data" }, headers: { "Content-Type": "multipart/form-data" },
}); });
return data.data; return data.data;

View File

@ -5,54 +5,36 @@ import {
getCookie, getCookie,
setCookie, setCookie,
} from "cookies-next"; } from "cookies-next";
import { env } from "next-runtime-env";
const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP");
axios.defaults.baseURL = NEXT_PUBLIC_BASE_URL_APP;
let isRefreshing = false; axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
axios.interceptors.response.use( axios.interceptors.response.use(
(response) => { (response) => {
return response; return response;
}, },
async function (error) { async function (error) {
console.log(error);
const originalRequest = error.config; const originalRequest = error.config;
if (error.response.status === 403) { if (
window.location.href = "/"; error.response.status === 401 &&
deleteCookie("Sootzani_Admin_Token"); originalRequest.url == "api/Authenticate/Profile"
deleteCookie("Sootzani_Admin_Refresh_Token"); ) {
localStorage.removeItem("privateKey"); originalRequest._retry = true;
} const accessToken = getCookie("Sootzani_Token");
if (error.response.status === 401) { const refreshToken = getCookie("Sootzani_Refresh_Token");
if (!originalRequest._retry) { if (accessToken) {
originalRequest._retry = true; const data = await RefreshToken({
const accessToken = getCookie("Sootzani_Admin_Token"); token: accessToken,
const refreshToken = getCookie("Sootzani_Admin_Refresh_Token"); refreshToken: refreshToken,
//accessToken && refreshToken && !isRefreshing });
if (!isRefreshing) {
isRefreshing = true;
try {
// Perform token refresh
const data = await RefreshToken({
token: accessToken,
refreshToken: refreshToken,
});
// Retry the original request
return axios(originalRequest);
} catch (refreshError) {
console.error("Token refresh failed", refreshError);
// Handle refresh error, e.g., redirect to login page
return Promise.reject(refreshError);
} finally {
isRefreshing = false;
}
}
} }
} }
// if (error.response.status === 403 && !originalRequest._retry) {
// For other errors or if refresh token logic is not applicable // originalRequest._retry = true;
// const access_token = await refreshAccessToken();
// axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
// return axiosApiInstance(originalRequest);
// }
return Promise.reject(error); return Promise.reject(error);
} }
); );
@ -96,27 +78,6 @@ export async function verifyCitizen(payload: {
return data.data; return data.data;
} }
export async function postChangePhoneNumber(payload: {
newPhoneNumber: string;
captcha: {
key: string;
value: string;
};
}) {
const data = await axios.post("api/Authenticate/PhoneNumber", payload);
return data.data;
}
export async function putChangePhoneNumber(payload: {
token1: string;
code1: string | null;
token2: string;
code2: string | null;
}) {
const data = await axios.put("api/Authenticate/PhoneNumber", payload);
return data.data;
}
export async function changePassword(payload: { export async function changePassword(payload: {
oldPassword: string; oldPassword: string;
newPassword: string; newPassword: string;
@ -133,9 +94,9 @@ export async function getProfile() {
export async function editProfile(payload: { export async function editProfile(payload: {
firstName: string; firstName: string;
lastName: string; lastName: string;
nationalId?: string; nationalId: string;
phoneNumber2?: string; phoneNumber2: string;
title?: string; title: string;
}) { }) {
const data = await axios.put("api/Authenticate/Profile", payload); const data = await axios.put("api/Authenticate/Profile", payload);
return data.data; return data.data;
@ -144,7 +105,7 @@ export async function editProfile(payload: {
export async function revoke(payload: { export async function revoke(payload: {
refreshToken: string | CookieValueTypes; refreshToken: string | CookieValueTypes;
}) { }) {
const token = getCookie("Sootzani_Admin_Token"); const token = getCookie("Sootzani_Token");
const data = await axios.post("api/Authenticate/Revoke", payload, { const data = await axios.post("api/Authenticate/Revoke", payload, {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
}); });
@ -154,13 +115,12 @@ export async function revoke(payload: {
export async function RefreshToken(payload: { token: any; refreshToken: any }) { export async function RefreshToken(payload: { token: any; refreshToken: any }) {
try { try {
const response = await axios.post("api/Authenticate/Refresh", payload); const response = await axios.post("api/Authenticate/Refresh", payload);
setCookie("Sootzani_Admin_Token", response.data.jwtToken); setCookie("Sootzani_Token", response.data.jwtToken);
setCookie("Sootzani_Admin_Refresh_Token", response.data.refreshToken); setCookie("Sootzani_Refresh_Token", response.data.refreshToken);
return response.data; return response.data;
} catch (error) { } catch (error) {
deleteCookie("Sootzani_Admin_Token"); deleteCookie("Sootzani_Token");
deleteCookie("Sootzani_Admin_Refresh_Token"); deleteCookie("Sootzani_Refresh_Token");
localStorage.removeItem("privateKey");
window.location.href = "/"; window.location.href = "/";
} }
} }

View File

@ -10,18 +10,13 @@ export async function getCategory() {
// Get Captcha // Get Captcha
export async function getCaptcha() { export async function getCaptcha() {
const data = await axios.get("api/Common/Captcha", { responseType: "blob" }); const data = await axios.get("api/Common/Captcha", { responseType: "blob" });
console.log(data);
return data; return data;
} }
// Get Captcha // Get Captcha
export async function getContents() { export async function getContents() {
const data = await axios.get("api/Common/Contents"); const data = await axios.get("api/Common/Contents");
console.log(data);
return data.data; return data.data;
} }
export async function getOptions() {
const data = await axios.get("/api/Common/Options");
return data.data;
}

View File

@ -1,11 +1,10 @@
import axios from "axios"; import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next"; import { CookieValueTypes, getCookie } from "cookies-next";
import { env } from "next-runtime-env";
const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP"); axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
axios.defaults.baseURL = NEXT_PUBLIC_BASE_URL_APP;
axios.interceptors.request.use(function (config) { axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Admin_Token"); const token = getCookie("Sootzani_Token");
config.headers.Authorization = token ? `Bearer ${token}` : ""; config.headers.Authorization = token ? `Bearer ${token}` : "";
return config; return config;
}); });

View File

@ -3,12 +3,11 @@
import axios from "axios"; import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next"; import { CookieValueTypes, getCookie } from "cookies-next";
import { RefreshToken } from "./authenticateApi"; import { RefreshToken } from "./authenticateApi";
import { env } from "next-runtime-env";
const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP"); axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
axios.defaults.baseURL = NEXT_PUBLIC_BASE_URL_APP;
axios.interceptors.request.use(function (config) { axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Admin_Token"); const token = getCookie("Sootzani_Token");
config.headers.Authorization = token ? `Bearer ${token}` : ""; config.headers.Authorization = token ? `Bearer ${token}` : "";
return config; return config;
}); });
@ -22,7 +21,7 @@ export async function getComplaintsList({
states = 0, states = 0,
TrackingNumber, TrackingNumber,
PageNumber = 1, PageNumber = 1,
PageSize = 10, PageSize = 5,
}: { }: {
states: number; states: number;
TrackingNumber?: string; TrackingNumber?: string;
@ -51,10 +50,3 @@ export async function OperateByInspector(payload: FormData) {
}); });
return data.data; return data.data;
} }
export async function postConnectionId(id: string) {
const data = await axios.post("/api/Common/ConnectionId", id, {
headers: { "Content-Type": "application/json" },
});
return data.data;
}

View File

@ -1,27 +0,0 @@
import {
HttpTransportType,
HubConnectionBuilder,
JsonHubProtocol,
LogLevel,
} from "@microsoft/signalr";
import { getCookie } from "cookies-next";
const token = getCookie("Sootzani_Admin_Token");
const connection = new HubConnectionBuilder()
.withUrl("https://sootzaniapi.shetabdahi.ir/notifhub", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.withAutomaticReconnect()
.withHubProtocol(new JsonHubProtocol())
.configureLogging(LogLevel.Debug)
.build();
// Optional: Configure connection options, such as access token or headers
// connection.on("your-event", (data) => {
// // Handle incoming events
// });
export default connection;