Compare commits

...

51 Commits
v0.2.5 ... main

Author SHA1 Message Date
Hossein Rahmani 074fa67d7a Code Cleaned 2024-08-03 14:26:51 +03:30
Hossein Rahmani dd0f39591b packages v updated 2024-07-21 13:07:54 +03:30
Hossein Rahmani a97d4ae1a9 a bug fixed 2024-07-21 13:06:31 +03:30
Hossein Rahmani 5ecf47e3d1 packages v updated 2024-07-20 17:40:21 +03:30
Hossein Rahmani 2abf0edf4c Other bugs of meeting fixed 2024-07-20 17:39:15 +03:30
Hossein Rahmani 9eb39d9410 Merge branch 'main' into Kahdooie 2024-07-18 12:45:47 +03:30
Hossein Rahmani f124cc4cdb Other bugs of meeting fixed 2024-07-18 12:45:23 +03:30
YasamanKahdooei eb22ab92f4 Some styles have been changed 2024-07-18 11:25:51 +03:30
Hossein Rahmani 6863560faa Other bugs of meeting fixed 2024-07-18 10:41:41 +03:30
YasamanKahdooei 00cd74a9c5 a bug fixed 2024-07-17 15:39:21 +03:30
Hossein Rahmani bb86584422 Bugs of meeting fixed 2024-07-17 13:15:09 +03:30
Hossein Rahmani e6194009d5 packages v updated 2024-07-07 15:39:42 +03:30
Hossein Rahmani 73371b5aa3 packages v updated 2024-07-07 11:43:29 +03:30
Hossein Rahmani 37feebe4f4 Bugs in meeting fixed 2024-07-07 11:41:44 +03:30
Hossein Rahmani c3e22fae22 Inspector operation changed 2024-02-10 09:55:19 +03:30
Hossein Rahmani 74246639e3 A bug fixed 2024-02-03 23:49:41 +03:30
Hossein Rahmani 13758eff56 packages v updated 2024-02-03 23:32:07 +03:30
Hossein Rahmani 4075917927 Change Password & Change PhoneNumber Added 2024-02-03 23:31:21 +03:30
Hossein Rahmani 7e8e3b6b9f Bugs fixed 2024-02-03 11:16:01 +03:30
Hossein Rahmani 2fc9cc9951 packages v updated 2024-02-03 01:13:04 +03:30
Hossein Rahmani bc1b30bc9a Change Key improved + Runtime Environment Variable added 2024-02-03 01:12:12 +03:30
Hossein Rahmani 45099f1dac File uploader changed 2024-02-02 15:49:49 +03:30
Hossein Rahmani f35df44436 Merge branch 'Kahdooie' of https://gitea.shetabdahi.ir/Hossein-Rahmani/Sootzani-Inspector into Kahdooie 2024-02-02 12:58:39 +03:30
Hossein Rahmani 366f07ce11 Bugs fixed 2024-02-02 12:58:36 +03:30
yasaman 6b7a4028ce bug fixed 2024-02-01 14:33:24 +03:30
yasaman 2d10412137 a bug fixed 2024-02-01 14:24:21 +03:30
yasaman 56184f2ebe TabController , AdminNews , AdminSlider , WebContent Modified 2024-01-31 14:11:06 +03:30
Hossein Rahmani a11c92fbef Api changed 2024-01-29 23:17:17 +03:30
Hossein Rahmani acf61507f5 Merge branch 'Kahdooie' 2024-01-29 20:24:38 +03:30
Hossein Rahmani 880c114525 packages v updated 2024-01-29 20:22:40 +03:30
Hossein Rahmani a378254239 Bugs fixed 2024-01-29 20:17:14 +03:30
yasaman 6a86af4d88 Merge branch 'Kahdooie' of https://gitea.shetabdahi.ir/Hossein-Rahmani/Sootzani-Inspector into Kahdooie 2024-01-29 16:48:41 +03:30
yasaman ecb5290e49 bugs in Inspector Fixed 2024-01-29 16:48:32 +03:30
Hossein Rahmani 4353b725b0 packages v updated 2024-01-29 14:16:39 +03:30
Hossein Rahmani 95649452be package v updated 2024-01-29 14:12:54 +03:30
Hossein Rahmani a190f8c301 Bugs fixed 2024-01-29 13:48:16 +03:30
Hossein Rahmani dc03495f73 a bug fixed 2024-01-28 17:49:49 +03:30
Hossein Rahmani 76e406efc2 Search and pagination bugs fixed 2024-01-28 17:32:06 +03:30
Hossein Rahmani d10cf03f98 Merge branch 'Kahdooie' of https://gitea.shetabdahi.ir/Hossein-Rahmani/Sootzani-Inspector into Kahdooie 2024-01-28 15:50:59 +03:30
Hossein Rahmani d97c13b565 Bug fixed 2024-01-28 15:49:16 +03:30
yasaman d1e7405780 a bug fixed + Cleaned Code 2024-01-28 15:20:09 +03:30
Hossein Rahmani 7caef19713 packages v updated 2024-01-27 15:49:54 +03:30
Hossein Rahmani fa6c67d3f5 Codes Cleaned 2024-01-27 11:58:45 +03:30
Hossein Rahmani 08872f04b9 Bugs Fixed 2024-01-27 00:09:46 +03:30
yasaman dae4ec5264 ComplaintDetails Modified + Bugs Fixed 2024-01-26 16:46:50 +03:30
Hossein Rahmani 24350884fd Bugs fixed 2024-01-25 20:36:20 +03:30
Hossein Rahmani 82ebc3c611 Merge branch 'Kahdooie' 2024-01-24 16:09:11 +03:30
Hossein Rahmani 7606d2cb34 a bug fixed 2024-01-24 16:08:35 +03:30
yasaman 6baeccf126 "AdminWebContent" Page Modified 2024-01-24 14:31:39 +03:30
yasaman 7dc91fc6a7 CoplainsDetails Modified 2024-01-23 14:36:01 +03:30
yasaman 40b6b6dc48 Error page Modified 2024-01-23 11:26:37 +03:30
66 changed files with 3366 additions and 1484 deletions

View File

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

View File

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

View File

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

View File

@ -0,0 +1,8 @@
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;
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-10">
<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">
<ComplainsDetails role="Inspector" id={id} />
</div>
);

View File

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

View File

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

29
app/error.tsx Normal file
View File

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

View File

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

View File

@ -1,7 +1,12 @@
"use client";
import React, { useState, useRef, useEffect } from "react";
import { useMutation, useQuery, RefetchOptions } from "@tanstack/react-query";
import {
useMutation,
useQuery,
RefetchOptions,
useQueryClient,
} from "@tanstack/react-query";
import { GenerateKeyPair, GetKeys, AddKey, ChangeKey } from "@/utils/adminApi";
import { FaRegEdit } from "react-icons/fa";
import { IoMdClose } from "react-icons/io";
@ -37,28 +42,14 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
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
// Edit Key Form
const FormSchemaEditKey = z.object({
uploadPrivateKey: z.any(),
// .instanceof(File)
// .custom<FileList>((val) => val instanceof FileList, "Required")
// .refine((files) => files.length <= 1, "Maximum of 1 file is allowed.")
// .refine(
// (files) =>
// Array.from(files).every((file) => file.size <= MAX_IMAGE_SIZE),
// "Each file size should be less than 5 MB."
// ),
// .refine((files) => files?.length === 0, "File is required.")
// .refine((files) => files?.length >= 1, "Maximum of 1 file is allowed.")
// .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, `Max file size is 5MB.`)
// publicKeyId: z
// .string()
// .nullable(),
});
// Add Key Form
@ -73,14 +64,19 @@ const FormSchemaAddKey = z.object({
export default function AdminKeysManagement() {
const router = useRouter();
const queryClient = useQueryClient();
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 [openEdit, setOpenEdit] = React.useState(false);
const inputPubRef = 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 handleFileChange = (event: any) => {
const file = event.target.files[0];
@ -107,14 +103,31 @@ export default function AdminKeysManagement() {
mutationKey: ["ChangeKey"],
mutationFn: ChangeKey,
onSuccess: (res) => {
console.log(res);
// alert("Success");
console.log("Success ChangeKey");
setOpenEdit(false);
if (res.total == res.done) {
localStorage.removeItem("isChangingKey");
setPolling(false);
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);
setDone(res.done);
setTotal(res.total);
// router.refresh()
},
@ -129,6 +142,7 @@ export default function AdminKeysManagement() {
ChangeKeyMutation.mutate({
privateKey: selectedFile,
publicKeyId: keyId,
isPolling: false,
});
}
@ -146,9 +160,6 @@ export default function AdminKeysManagement() {
mutationKey: ["AddKey"],
mutationFn: AddKey,
onSuccess: (res) => {
console.log(res);
console.log("Success AddKey");
setOpenAdd(false);
refetch1();
@ -179,7 +190,7 @@ export default function AdminKeysManagement() {
publicKey: data.publicKey,
});
}
// const { resetField } = useForm();
// List Keys
const {
@ -191,7 +202,6 @@ export default function AdminKeysManagement() {
} = useQuery({
queryKey: ["KeysList"],
queryFn: () => GetKeys(),
// refetchOnWindowFocus: false,
});
// GenerateKeyPair
@ -226,6 +236,27 @@ export default function AdminKeysManagement() {
}
}, [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 textToSave = data2?.privateKey ?? "";
const fileName = "privateKey.txt";
@ -253,9 +284,25 @@ export default function AdminKeysManagement() {
saveTextFile();
}
}, [AddKeyMutation.isSuccess]);
const resetFormAdd = () => {
formAdd.reset({
title: "",
publicKey: "",
});
};
return (
<div className="w-full min-h-[85vh] flex justify-center">
<div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
{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 */}
<AlertDialog open={openAdd} onOpenChange={setOpenAdd}>
<AlertDialogContent className="">
@ -264,7 +311,12 @@ export default function AdminKeysManagement() {
<p className="text-[#464646] text-base font-bold">
افزودن کلید جدید
</p>
<AlertDialogCancel className="h-auto p-0 border-0">
<AlertDialogCancel
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose />
</AlertDialogCancel>
</AlertDialogTitle>
@ -317,11 +369,11 @@ export default function AdminKeysManagement() {
render={({ field }) => (
<FormItem className="w-full ">
<FormLabel className="text-[#7C838A] text-sm font-medium ">
کلید عمومی
کلید خصوصی
</FormLabel>
<FormControl>
<Textarea
placeholder="کلید عمومی را وارد کنید"
placeholder="کلید خصوصی را وارد نمایید."
{...field}
className="bg-white resize-none"
dir="ltr"
@ -366,25 +418,36 @@ export default function AdminKeysManagement() {
</Button>
</AlertDialogTrigger>
</div>
<div className="flex flex-row flex-wrap justify-between w-full gap-8 md:gap-4 ">
<div className="flex flex-row flex-wrap w-full gap-8 md:gap-4">
{data1?.map((item: any) => {
return (
<div
key={item.id}
className={`flex flex-col justify-center gap-2 w-full lg:w-[49%] h-28 px-5 rounded-md shadow-md items-start bg-[#F5F5F5]
`}
className={cn(
`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">
<div className=" p-2 bg-blue rounded-lg">
<KeyRound className=" text-white" />
</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">
</div>
{/* <p className="text-sm font-normal leading-normal text-slate-500">
آیدی بازرس:{" "}
<span className="self-end text-slate-800">
{item.inspectorId}
</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> */}
@ -426,36 +489,13 @@ export default function AdminKeysManagement() {
</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
@ -478,6 +518,7 @@ export default function AdminKeysManagement() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</div>
);
})}

View File

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

View File

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

View File

@ -139,7 +139,6 @@ export default function AdminSlider() {
queryFn: () => GetAllSliders(),
// refetchOnWindowFocus: false,
});
console.log(data1);
// Edit
const handleClickEdit = (
@ -196,14 +195,11 @@ export default function AdminSlider() {
});
// Edit Submit
// ............'Mutation' Change Slider Submit
const ChangeSliderMutation = useMutation({
// ............'Mutation' Change Slider Submit
const ChangeSliderMutation = useMutation({
mutationKey: ["ChangeSlider"],
mutationFn: UpdateSlider,
onSuccess: (res) => {
console.log(res);
console.log("Success Change Slider");
setOpenEdit(false);
refetch1();
@ -217,15 +213,13 @@ const ChangeSliderMutation = useMutation({
className: "!bg-red-500 !text-white",
});
},
});
});
//Delete
const DeleteSliderMutation = useMutation({
//Delete
const DeleteSliderMutation = useMutation({
mutationKey: ["DeleteSlider"],
mutationFn: DeleteSlider,
onSuccess: (res) => {
console.log(res);
console.log("Success Change Slider");
setOpenEdit(false);
refetch1();
toast("عملیات شما با موفقیت انجام شد. ", {
@ -237,32 +231,41 @@ const DeleteSliderMutation = useMutation({
className: "!bg-red-500 !text-white",
});
},
});
});
// Add
// ............'Mutation' Add Slider Submit
const AddSliderMutation = useMutation({
// 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",
});
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) {
function onSubmitEdit(data: EditSliderFormValues) {
const formData = new FormData();
formData.append("Title", data.titleSlider);
if (data?.uploadImg instanceof File) {
@ -275,18 +278,12 @@ function onSubmitEdit(data: EditSliderFormValues) {
// formData.append("Medias", data.media[i]);
// }
// }
ChangeSliderMutation.mutate({id: keyId, payload: formData});
ChangeSliderMutation.mutate({ id: keyId, payload: formData });
refetch1();
resetField("Title");
resetField("Image");
resetField("Url");
resetField("Description");
}
}
const { resetField } = useForm();
function onSubmitAdd(data: AddSliderFormValues) {
function onSubmitAdd(data: AddSliderFormValues) {
const formData = new FormData();
formData.append("Title", data.titleSlider);
formData.append("Url", data.urlSlider);
@ -297,14 +294,22 @@ function onSubmitAdd(data: AddSliderFormValues) {
}
AddSliderMutation.mutate(formData);
}
}
const resetFormAdd = () => {
formAdd.reset({
titleSlider: "",
uploadImg: null,
urlSlider: "",
description: "",
});
};
const { resetField } = useForm();
return (
<div className="w-full min-h-[85vh] flex justify-center">
<div className="w-[95vw] lg:w-[85vw] 3xl:w-[70vw] mt-8 max-sm:mt-16 pt-9 ">
<div className="flex flex-row justify-between w-full ">
<div className="flex flex-row items-center justify-between w-full ">
{/* 1 */}
<div className="w-full my-4 text-lg font-bold text-right text-neutral-600">
لیست اسلایدرها
@ -329,7 +334,12 @@ function onSubmitAdd(data: AddSliderFormValues) {
<p className="text-[#464646] text-base font-bold">
افزودن اسلایدر
</p>
<AlertDialogCancel className="h-auto p-0 border-0">
<AlertDialogCancel
className="h-auto p-0 border-0"
onClick={() => {
resetFormAdd();
}}
>
<IoMdClose />
</AlertDialogCancel>
</AlertDialogTitle>
@ -456,7 +466,6 @@ function onSubmitAdd(data: AddSliderFormValues) {
</FormItem>
)}
/>
</div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
@ -466,7 +475,12 @@ function onSubmitAdd(data: AddSliderFormValues) {
>
افزودن
</Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
<AlertDialogCancel
className="mt-0 text-white bg-blue rounded-xl"
onClick={() => {
resetFormAdd();
}}
>
بستن
</AlertDialogCancel>
</div>
@ -487,7 +501,7 @@ function onSubmitAdd(data: AddSliderFormValues) {
<AlertDialogHeader>
<AlertDialogTitle>
<p className="text-[#464646] text-base font-bold">
تغییر اسلایدر
ویرایش اسلایدر
</p>
<AlertDialogCancel className="h-auto p-0 border-0">
<IoMdClose />
@ -614,7 +628,6 @@ function onSubmitAdd(data: AddSliderFormValues) {
</FormItem>
)}
/>
</div>
<div className="flex justify-center w-full gap-2 mt-8 sm:justify-end">
@ -622,7 +635,7 @@ function onSubmitAdd(data: AddSliderFormValues) {
type="submit"
className="p-2 text-center text-white bg-blue min-w-max rounded-xl hover:bg-white hover:text-slate-800"
>
تغییر اسلایدر
ویرایش اسلایدر
</Button>
<AlertDialogCancel className="mt-0 text-white bg-blue rounded-xl">
@ -640,28 +653,33 @@ function onSubmitAdd(data: AddSliderFormValues) {
return (
<div
key={item.id}
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]
className={`w-full lg:w-[48%] bg-[#F5F5F5] border rounded-lg flex flex-row shadow-md transition-all
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">
<Image
alt="picture"
src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`}
height={500}
width={500}
quality={100}
className="w-full h-full rounded-r-lg bg-cover object-cover"
/>
</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">
<span className="self-end text-slate-800 line-clamp-4">
{item.description}
</span>
</p>
<Image
alt="img"
src={`${process.env.NEXT_PUBLIC_BASE_URL_APP}${item?.image?.url}`}
width={100}
height={100}
quality={100}
className="object-contain object-right w-full h-20 "
/>
</div>
{/* <p className="text-sm font-normal leading-normal text-slate-500">
محتوا:
<span className="self-end text-slate-800">
@ -675,8 +693,8 @@ function onSubmitAdd(data: AddSliderFormValues) {
checked={!item.isDeleted}
onCheckedChange={() => {
DeleteSliderMutation.mutate({
id: item.id
})
id: item.id,
});
}}
id={item.id}
/>
@ -700,6 +718,7 @@ function onSubmitAdd(data: AddSliderFormValues) {
</AlertDialogTrigger>
</div>
</div>
</div>
);
})}
</AlertDialog>

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 lg:w-3/5 h-11 bg-white rounded-[5px] block">
<Search mode="admin" />
{/* <Search Cancel={} mode="admin" /> */}
</div>
<div className="w-full lg:w-2/5 flex flex-row justify-between items-center gap-2 ">

View File

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

View File

@ -0,0 +1,108 @@
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,3 +1,4 @@
import { ClipboardList, EyeOff, Info, User, UserCheck } from "lucide-react";
import React from "react";
export default function BoxDashboard({
@ -6,18 +7,32 @@ export default function BoxDashboard({
}: {
value: 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 (
<div
className=" px-7 py-8 bg-zinc-100 rounded-lg shadow flex flex-col justify-end items-center text-black
className=" px-7 py-8 bg-zinc-100 rounded-lg shadow flex flex-col justify-evenly items-center text-black
transition duration-200
hover:text-white hover:bg-blue
group h-44 w-44"
>
<div className="group-hover:-translate-y-2 transition-all duration-300">
<p className="text-center text-xs font-medium">
{value}
</p>
{checkIcon ? checkIcon : <Info className=" mb-2 mx-auto" />}
{/* <EyeOff className=" mb-2 mx-auto" /> */}
<div className="group-hover:-translate-y-2 flex flex-col justify-center transition-all duration-300">
<p className="text-center text-sm font-medium">{value}</p>
<p className="text-center text-xs font-medium">{title}</p>
</div>
</div>

View File

@ -0,0 +1,153 @@
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

@ -0,0 +1,129 @@
"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

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

View File

@ -14,9 +14,6 @@ export default function ControllerDashboard() {
queryFn: () => getInfo(),
refetchOnWindowFocus: false,
});
const [decryptedMessage, errorMessage] = useDecrypt(
"gJoT9AqK7wk1MZFSD04yXXfF36fzsOL+RYtJfySrEnQeJ7VoaL7pmOU6nB3+0+PQcaxIi3hf1AHjzIB0Cn5oHgKROeoI4XslhAezZk23QhtIU4HUF1wpeOJfA+4hWyRfbh4fI9774sa/KL47VaBbrNM/rvBxk6hjlKx5mTb3hqM="
);
return (
<div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-12 pt-9 mx-auto px-2">
@ -42,36 +39,6 @@ export default function ControllerDashboard() {
})}
</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>
);
}

View File

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

View File

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

View File

@ -95,7 +95,7 @@ export default function Login() {
: null;
return (
<div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div className="grid w-screen h-screen bg-left-top bg-repeat bg-[url('/img/login-pattern.png')] 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"

View File

@ -1,63 +0,0 @@
"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,6 +9,9 @@ import { getProfile, revoke } from "@/utils/authenticateApi";
import { useMutation, useQuery } from "@tanstack/react-query";
import { DoorOpen, LogOut } from "lucide-react";
import { deleteCookie, getCookie } from "cookies-next";
import useSignalR from "@/hooks/useSignalR";
import ProfileDropDown from "./ProfileDropDown";
export default function NavbarPanel() {
const [isOpen, setOpen] = useState(false);
const ref = useRef(null);
@ -30,7 +33,6 @@ export default function NavbarPanel() {
const { data, isLoading, refetch } = useQuery({
queryKey: ["Profile"],
queryFn: () => getProfile(),
refetchOnWindowFocus: false,
});
const revokeMutation = useMutation({
@ -47,13 +49,14 @@ export default function NavbarPanel() {
const logout = () => {
revokeMutation.mutate({
refreshToken: getCookie("Sootzani_Refresh_Token"),
refreshToken: getCookie("Sootzani_Admin_Refresh_Token"),
});
deleteCookie("Sootzani_Token");
deleteCookie("Sootzani_Admin_Token");
localStorage.removeItem("privateKey");
localStorage.removeItem("privatePassword");
router.push("/");
};
const signalr = useSignalR();
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 ">
@ -139,17 +142,8 @@ export default function NavbarPanel() {
</div>
<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">
{data && (
<>
{role === "Admin"
? `${data?.title ? data.title : data.username} (ادمین)`
: `${data?.title ? data.title : data.username} (بازرس)`}
</>
)}
<ProfileDropDown />
</h1>
<div className="p-1 rounded-md hover:bg-white/50">
<LogOut onClick={logout} className="text-white cursor-pointer " />
</div>
</div>
</div>
);

View File

@ -1,89 +0,0 @@
"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,64 +3,50 @@ import React, { useEffect, useState } from "react";
import ReactPaginate from "react-paginate";
import { MdKeyboardArrowRight, MdKeyboardArrowLeft } from "react-icons/md";
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({
itemsPerPage,
TotalPages,
currentPage,
PageSize,
Page,
countPage,
length,
}: {
itemsPerPage?: any;
TotalPages?: any;
currentPage?: any;
PageSize?: number;
Page?: any;
countPage?: 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 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);
};
console.log(countPage);
// console.log(pageCount, "1111");
return (
<>
{/* <Items currentItems={currentItems} /> */}
<ReactPaginate
breakLabel="..."
onPageActive={(e) => console.log(e)}
nextLabel={<MdKeyboardArrowLeft className="w-5 h-5 " />}
onPageChange={handlePageClick}
pageRangeDisplayed={3}
pageCount={Math.ceil(countPage / 5)}
forcePage={currentPage}
pageCount={
TotalPages
? TotalPages
: Math.ceil(countPage / (PageSize ? PageSize : 5))
}
previousLabel={<MdKeyboardArrowRight className="w-5 h-5 " />}
pageClassName=" w-10 h-10 grid place-content-center rounded-lg !text-blue shadow-md"
className={twMerge(
" 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"
" 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"
)}
activeClassName=" bg-blue text-blue shadow-md shadow-main"
activeLinkClassName=" text-white w-full p-1 h-full"
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"
pageLinkClassName="p-4"
/>
</>
);

View File

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

View File

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

View File

@ -24,44 +24,32 @@ import useData from "@/store/useData";
import { toast } from "sonner";
import Pagination from "./Pagination";
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() {
const saveData = useData((state) => state.saveData);
const [selectedFile, setSelectedFile] = useState<any>(null);
const isMobile = useMediaQuery({ maxWidth: 768 }); // Adjust the max width for mobile
const [search, setSearch] = useState<any>(null);
const [page, setPage] = useState<any>(1);
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 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 [selectedTab, setSelectedTab] = useState("0");
const [selectedTab, setSelectedTab] = useState<string>("0");
const {
data: dataState,
@ -73,9 +61,6 @@ export default function TabController() {
refetchOnWindowFocus: false,
});
// const initialSelectedTab = dataState[0]?.value || '';
// setSelectedTab(initialSelectedTab);
const { data, isLoading, refetch } = useQuery({
queryKey: ["ComplaintsList", psblState, dataState, page],
queryFn: () =>
@ -88,79 +73,86 @@ export default function TabController() {
});
const handelSearch = (event: any) => {
setPage(1);
refetch();
};
useEffect(() => {
if (cancel) {
refetch();
}
}, [cancel]);
useEffect(() => {
if (data) {
const headersData = JSON.parse(data.headers["x-pagination"]);
setTotalCount(headersData.TotalCount);
setTotalPages(headersData.TotalPages);
setCurrentPage(headersData.CurrentPage);
setPageSize(headersData.PageSize);
setCancel(false);
}
}, [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;
console.log(totalCount);
return (
<div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-16 pt-9 mx-auto">
<p className="my-2 text-xs font-bold 3xl:ml-6 sm:text-sm xl:hidden">
لیست شکایت ها
</p>
<Tabs
// defaultValue="0"
value={String(selectedTab)}
// onClick={(value) => {
// setPsblState(value);
// setSelectedTab(value);
// refetch();
// }}
className=""
dir="rtl"
>
<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">
<p className="text-xs font-bold 3xl:ml-6 sm:text-sm max-xl:hidden">
لیست شکایت ها |
</p>
{dataState?.map((item: any) => {
// const isActive = item.value === selectedTab;
return (
<TabsTrigger
key={item.value}
className="hover:border-b-2 border-b-blue flex-1 h-10"
value={String(item.value)}
// data-state={isActive ? 'active' : 'inactive'}
onClick={() => {
setPsblState(item.value);
setSelectedTab(String(item.value));
{isMobile ? (
// Render your shadcn Select for mobile
<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">
<Select
value={selectedTab}
onValueChange={(value) => {
setPsblState(Number(value));
setSelectedTab(String(value));
localStorage.setItem("ActiveTab", String(value));
localStorage.setItem("ActivePage", page);
refetch();
setPage(0);
setSearch("");
setPage(1);
}}
>
<div className="relative w-full ">
<SelectTrigger className="w-full h-12 bg-[#E9E9E9] " dir="rtl">
<SelectValue placeholder="انتخاب دسته بندی" />
</SelectTrigger>
<SelectContent dir="rtl">
{dataState?.map((item: any) => (
<SelectItem key={item.value} value={String(item.value)}>
{item.title} ({item.count})
</div>
</TabsTrigger>
);
})}
</TabsList>
</SelectItem>
))}
</SelectContent>
</Select>
{/* 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
checkKey={(item) => checkKey(item)}
data={data?.data}
currentPage={currentPage}
pageSize={pageSize}
/>
) : (
<div className="flex flex-col gap-3">
@ -173,8 +165,8 @@ export default function TabController() {
{!isZero ? (
<Pagination
// length={data3?.data.length}
// itemsPerPage={1}
TotalPages={totalPages}
currentPage={currentPage - 1}
countPage={totalCount}
Page={(num: number) => setPage(num + 1)}
/>
@ -183,7 +175,7 @@ export default function TabController() {
{" "}
{data?.data.length == 0 && (
<p className="flex justify-center mx-auto mt-10 text-blue/50">
درخواستی وجود ندارد
گزارشی وجود ندارد
</p>
)}
</>
@ -191,5 +183,164 @@ export default function TabController() {
</TabsContent>
</Tabs>
</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 */}
// <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) => {
// return (
// <TabsTrigger
// key={item.value}
// className="hover:border-b-2 border-b-blue flex-1 h-10"
// value={String(item.value)}
// // data-state={isActive ? 'active' : 'inactive'}
// onClick={() => {
// setPsblState(item.value);
// setSelectedTab(String(item.value));
// localStorage.setItem("ActiveTab", String(item.value));
// localStorage.setItem("ActivePage", page);
// 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>
{/* 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>
)}
</div>
);
}

View File

@ -21,7 +21,7 @@ import {
} from "@/components/ui/dialog";
import { ControllerTableItems } from "@/constants";
import Link from "next/link";
import { Decrypt, convertDate } from "@/lib/utils";
import { Decrypt, convertDate, convertFullTime } from "@/lib/utils";
import useData from "@/store/useData";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
@ -53,62 +53,28 @@ interface Complaint {
}
export default function TableController({
data,
checkKey,
pageSize,
currentPage,
}: {
data: Complaint[];
checkKey: (item: any) => any;
pageSize: number;
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 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 (
<div>
<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">
<div className=" overflow-hidden">
<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] mb-8 md:mb-4 2xl:mb-0 ">
{/* <TableCaption>A list of your recent invoices.</TableCaption> */}
<TableHeader>
<TableRow>
<TableHead>ردیف</TableHead>
<TableHead>کد پیگیری</TableHead>
<TableHead> تاریخ ثبت</TableHead>
<TableHead>تاریخ</TableHead>
<TableHead>تاریخ آخرین تغییر</TableHead>
<TableHead>موضوع</TableHead>
<TableHead>دستگاه مربوطه</TableHead>
<TableHead>دستگاه مرتبط</TableHead>
</TableRow>
</TableHeader>
<TableBody className="bg-[#F5F5F5] min-h-[20rem] ">
@ -121,24 +87,22 @@ export default function TableController({
`/UserPanel/ControllerDashboard/Complaints/${item.id}`
);
}}
className="cursor-pointer hover:bg-gray-200"
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}
{pageSize * (currentPage - 1) + (index + 1)}
</TableCell>
<TableCell className="w-1/12">{item.trackingNumber}</TableCell>
<TableCell className="w-2/12">
{convertDate(item.registeredAt)}
<TableCell className="w-1/12">
{item.trackingNumber}
</TableCell>
<TableCell className="w-2/12">
{convertDate(item.lastChanged)}
{convertFullTime(item.registeredAt)}
</TableCell>
<TableCell className="w-3/12">
<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">
@ -146,61 +110,12 @@ export default function TableController({
? item?.complaintOrganization.title
: "-"}
</TableCell>
{/* </Link> */}
</TableRow>
);
})}
{data.length != 0 &&
[...Array(5 - data.length)].map(() => {
return (
<TableRow
key={Math.random()}
className="border border-t-0 border-b-0"
/>
);
})}
</TableBody>
</Table>
<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>
);
}

View File

@ -1,60 +0,0 @@
"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,
onSuccess: (res) => {
const decodedToken = jwtDecode<any>(res.jwtToken);
setCookie("Sootzani_Token", res.jwtToken);
setCookie("Sootzani_Refresh_Token", res.refreshToken);
setCookie("Sootzani_Admin_Token", res.jwtToken);
setCookie("Sootzani_Admin_Refresh_Token", res.refreshToken);
const userRole =
decodedToken[
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
@ -53,13 +53,12 @@ export default function Verify() {
otpToken: localStorage.getItem("verificationToken"),
verificationCode: otp,
};
console.log(userData);
verifyMutation.mutate(payload);
}
}, [otp]);
return (
<div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div className="grid w-screen h-screen bg-left-top bg-repeat bg-[url('/img/login-pattern.png')] 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"

View File

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

202
components/ui/Profile.tsx Normal file
View File

@ -0,0 +1,202 @@
"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) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
className={cn(buttonVariants(), "mt-2 sm:mt-0", className)}
{...props}
/>
));

View File

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

View File

@ -13,7 +13,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
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
text-black text-opacity-50 text-xs font-normal bg-slate-200 mb-3
3xl:h-9 h-10 transition-all
h-10 transition-all
hover:bg-slate-300 hover:cursor-pointer focus:cursor-auto
focus:outline-4 focus:outline-slate-300 focus:bg-slate-200

View File

@ -0,0 +1,28 @@
"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 (
<Sonner
theme={theme as ToasterProps["theme"]}
// theme={theme as ToasterProps["theme"]}
className="toaster group !font-[yekan]"
toastOptions={{
classNames: {

View File

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

View File

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

View File

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

82
hooks/useSignalR.jsx Normal file
View File

@ -0,0 +1,82 @@
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,15 +4,19 @@ import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import jalaliday from "jalaliday";
import JSEncrypt from "jsencrypt";
import timezone from "dayjs/plugin/timezone";
import moment from "jalali-moment";
dayjs.extend(jalaliday);
dayjs.extend(utc);
dayjs.extend(timezone);
// dayjs.tz.setDefault("Etc/GMT-3:30");
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function convertDate(date: string) {
const convertedDate = dayjs(date)
const convertedDate = dayjs(date + "Z")
.calendar("jalali")
.locale("fa")
.format("YYYY/M/DD");
@ -20,10 +24,10 @@ export function convertDate(date: string) {
}
export function convertFullTime(date: string) {
const convertedDate = dayjs(date)
const convertedDate = dayjs(date + "Z")
.calendar("jalali")
.locale("fa")
.format(" HH:mm - YYYY/M/DD");
.format(" HH:mm - YYYY/M/D");
return convertedDate;
}
@ -33,3 +37,16 @@ export function Decrypt(encryptedData: any, privateKey: any) {
const decrypted = decryptor.decrypt(encryptedData);
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

@ -2,7 +2,7 @@
const nextConfig = {
output: "standalone",
images: {
domains: ["sootzaniapi.shetabdahi.ir"],
domains: ["sootzaniapi.shetabdahi.ir", "oyoonapi.yazd.ir"],
},
};
};
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",
"version": "0.2.5",
"version": "0.2.23",
"private": true,
"scripts": {
"dev": "next dev",
@ -10,12 +10,14 @@
},
"dependencies": {
"@hookform/resolvers": "^3.3.2",
"@microsoft/signalr": "^8.0.0",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0",
"@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-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0",
@ -38,6 +40,7 @@
"framer-motion": "^10.16.16",
"hamburger-react": "^2.5.0",
"i": "^0.3.7",
"jalali-moment": "^3.3.11",
"jalaliday": "^2.3.0",
"jsencrypt": "^3.3.2",
"jwt-decode": "^4.0.0",
@ -46,6 +49,7 @@
"lucide-react": "^0.292.0",
"next": "14.0.3",
"next-nprogress-bar": "^2.1.2",
"next-runtime-env": "^3.2.0",
"next-themes": "^0.2.1",
"nextjs-toploader": "^1.6.4",
"npm": "^10.2.5",

Binary file not shown.

After

Width:  |  Height:  |  Size: 548 KiB

BIN
public/img/logo2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

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

View File

@ -5,36 +5,54 @@ import {
getCookie,
setCookie,
} 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;
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
let isRefreshing = false;
axios.interceptors.response.use(
(response) => {
return response;
},
async function (error) {
console.log(error);
const originalRequest = error.config;
if (
error.response.status === 401 &&
originalRequest.url == "api/Authenticate/Profile"
) {
if (error.response.status === 403) {
window.location.href = "/";
deleteCookie("Sootzani_Admin_Token");
deleteCookie("Sootzani_Admin_Refresh_Token");
localStorage.removeItem("privateKey");
}
if (error.response.status === 401) {
if (!originalRequest._retry) {
originalRequest._retry = true;
const accessToken = getCookie("Sootzani_Token");
const refreshToken = getCookie("Sootzani_Refresh_Token");
if (accessToken) {
const accessToken = getCookie("Sootzani_Admin_Token");
const refreshToken = getCookie("Sootzani_Admin_Refresh_Token");
//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) {
// originalRequest._retry = true;
// const access_token = await refreshAccessToken();
// axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
// return axiosApiInstance(originalRequest);
// }
}
}
// For other errors or if refresh token logic is not applicable
return Promise.reject(error);
}
);
@ -78,6 +96,27 @@ export async function verifyCitizen(payload: {
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: {
oldPassword: string;
newPassword: string;
@ -94,9 +133,9 @@ export async function getProfile() {
export async function editProfile(payload: {
firstName: string;
lastName: string;
nationalId: string;
phoneNumber2: string;
title: string;
nationalId?: string;
phoneNumber2?: string;
title?: string;
}) {
const data = await axios.put("api/Authenticate/Profile", payload);
return data.data;
@ -105,7 +144,7 @@ export async function editProfile(payload: {
export async function revoke(payload: {
refreshToken: string | CookieValueTypes;
}) {
const token = getCookie("Sootzani_Token");
const token = getCookie("Sootzani_Admin_Token");
const data = await axios.post("api/Authenticate/Revoke", payload, {
headers: { Authorization: `Bearer ${token}` },
});
@ -115,12 +154,13 @@ export async function revoke(payload: {
export async function RefreshToken(payload: { token: any; refreshToken: any }) {
try {
const response = await axios.post("api/Authenticate/Refresh", payload);
setCookie("Sootzani_Token", response.data.jwtToken);
setCookie("Sootzani_Refresh_Token", response.data.refreshToken);
setCookie("Sootzani_Admin_Token", response.data.jwtToken);
setCookie("Sootzani_Admin_Refresh_Token", response.data.refreshToken);
return response.data;
} catch (error) {
deleteCookie("Sootzani_Token");
deleteCookie("Sootzani_Refresh_Token");
deleteCookie("Sootzani_Admin_Token");
deleteCookie("Sootzani_Admin_Refresh_Token");
localStorage.removeItem("privateKey");
window.location.href = "/";
}
}

View File

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

View File

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

View File

@ -3,11 +3,12 @@
import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next";
import { RefreshToken } from "./authenticateApi";
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
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;
axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Token");
const token = getCookie("Sootzani_Admin_Token");
config.headers.Authorization = token ? `Bearer ${token}` : "";
return config;
});
@ -21,7 +22,7 @@ export async function getComplaintsList({
states = 0,
TrackingNumber,
PageNumber = 1,
PageSize = 5,
PageSize = 10,
}: {
states: number;
TrackingNumber?: string;
@ -50,3 +51,10 @@ export async function OperateByInspector(payload: FormData) {
});
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

@ -0,0 +1,27 @@
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;