Compare commits

...

5 Commits

11 changed files with 419 additions and 193 deletions

View File

@ -7,6 +7,8 @@ import NavbarSm from "@/components/NavbarSm";
import Provider from "../utils/Provider"; import Provider from "../utils/Provider";
import { Toaster as SonnerToaster } from "@/components/ui/sonner"; import { Toaster as SonnerToaster } from "@/components/ui/sonner";
import ProgressBarProviders from "@/components/ProgressBar"; import ProgressBarProviders from "@/components/ProgressBar";
import { unstable_noStore as noStore } from "next/cache";
import { EnvScript, PublicEnvScript } from "next-runtime-env";
const inter = Inter({ subsets: ["latin"] }); const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = { export const metadata: Metadata = {
@ -19,8 +21,12 @@ export default function RootLayout({
}: { }: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
noStore();
return ( return (
<html lang="fa" dir="rtl"> <html lang="fa" dir="rtl">
<head>
<PublicEnvScript />
</head>
<body className="font-[yekan] "> <body className="font-[yekan] ">
<Provider> <Provider>
<Navbar /> <Navbar />

View File

@ -0,0 +1,57 @@
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { X } from "lucide-react";
export default function AttachmentsDialog({
children,
attachments,
deleteFile,
}: {
children: React.ReactNode;
attachments: File[] | [];
deleteFile: (file: any) => void;
}) {
return (
<Dialog>
{children}
<DialogContent>
<DialogHeader>
<DialogTitle>پیوست‌ها</DialogTitle>
<DialogDescription>
{attachments.length == 0 ? (
<div className=" text-center my-5">هیج پیوستی وجود ندارد.</div>
) : (
<div className=" flex flex-col gap-2 mt-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">{item.name}</p>
</div>
<X
onClick={() => deleteFile(item.name)}
className=" cursor-pointer hover:drop-shadow-md"
/>
</div>
</div>
);
})}
</div>
)}
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
);
}

View File

@ -116,8 +116,6 @@ export default function ComplainsDetails({
mutationFn: postComplaintTracking, mutationFn: postComplaintTracking,
onSuccess: (res) => { onSuccess: (res) => {
setOpen(false); setOpen(false);
localStorage.removeItem("trackingNumber2");
localStorage.removeItem("password2");
}, },
onError: (err: any | string) => { onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, { toast(<>{err.response.data.detail}</>, {
@ -149,6 +147,11 @@ export default function ComplainsDetails({
}, []); }, []);
data = getComplaintMutation?.data; data = getComplaintMutation?.data;
const possibleOperations = data?.possibleOperationsWithDescription;
if (possibleOperations?.length == 0) {
localStorage.removeItem("trackingNumber2");
localStorage.removeItem("password2");
}
return ( return (
<> <>
@ -201,11 +204,11 @@ export default function ComplainsDetails({
)} */} )} */}
{/* Editt */} {/* Editt */}
<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 mb-10">
{/* 1 */} {/* 1 */}
<div className="flex flex-col w-full lg:w-1/3 gap-3 lg:sticky top-28 lg:h-[80vh]"> <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="max-lg:hidden bg-[#E9E9E9] rounded-md p-4 px-10 flex flex-col lg:h-full"> <div className=" bg-[#E9E9E9] rounded-md p-4 px-10 flex flex-col lg:h-full">
<p className="text-[#464646] text-base font-bold mb-1"> <p className="text-[#464646] text-base font-bold mb-1">
انجام عملیات انجام عملیات
</p> </p>
@ -340,21 +343,21 @@ export default function ComplainsDetails({
key={item.id} key={item.id}
className="p-4 bg-white rounded-lg shadow-md " className="p-4 bg-white rounded-lg shadow-md "
> >
<div className="flex items-center gap-4 "> <div className="flex items-center gap-4 justify-between">
<p className=""> <p className="">
<Badge> <Badge>
{item.operationWithDescription.description} توسط{" "}
{item.sender == 0 ? "شهروند" : "بازرس"} {item.sender == 0 ? "شهروند" : "بازرس"}
</Badge> </Badge>
</p> </p>
<p className=""> <p className="">
تاریخ : <span className="text-[#7C838A] text-sm">
<span className="text-[#7C838A]"> {convertFullTime(item.dateTime)}
{convertDate(item.dateTime)}
</span> </span>
</p> </p>
</div> </div>
<div className=" text-[#464646] mt-2"> <div className=" text-[#464646] mt-2">
<span className="text-[#7C838A]"> <span className="text-[#7C838A] text-sm">
{item.text ? item.text : "-"} {item.text ? item.text : "-"}
</span> </span>
</div> </div>
@ -408,16 +411,6 @@ export default function ComplainsDetails({
{/* 3 */} {/* 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={() => getComplaintMutation.mutate(storeData)}
role={role}
complaintData={data}
/>
</div>
</div> </div>
</> </>
) : ( ) : (

View File

@ -29,10 +29,16 @@ import {
} from "@/components/ui/select"; } from "@/components/ui/select";
import { Operations } from "@/constants"; import { Operations } from "@/constants";
import useData from "@/store/useData"; import useData from "@/store/useData";
import { useMutation } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import { OperateByInspector } from "@/utils/inspectorApi"; import { OperateByInspector } from "@/utils/inspectorApi";
import { toast } from "sonner"; import { toast } from "sonner";
import { postComplaintsDetails } from "@/utils/citizenApi"; import { postComplaintsDetails } from "@/utils/citizenApi";
import { useState } from "react";
import { DialogTrigger } from "./ui/dialog";
import AttachmentsDialog from "./AttachmentsDialog";
import { Eye, Upload } from "lucide-react";
import { getOptions } from "@/utils/commonApi";
import { bytesToMB, formatBytes } from "@/lib/utils";
export default function InspectorOperations({ export default function InspectorOperations({
complaintData, complaintData,
@ -45,18 +51,63 @@ export default function InspectorOperations({
updateData: (data: any) => any; updateData: (data: any) => any;
password?: string; password?: string;
}) { }) {
const [first, setfirst] = useState<File[]>([]);
// Queries
const { data, isLoading, refetch } = useQuery({
queryKey: ["Options"],
queryFn: () => getOptions(),
refetchOnWindowFocus: false,
});
const OperationMutation = useMutation({
mutationKey: ["Operation"],
mutationFn: postComplaintsDetails,
onSuccess: (res) => {
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
updateData({
trackingNumber: complaintData.trackingNumber,
password: password
? password
: (localStorage.getItem("password2") as string),
});
localStorage.removeItem("trackingNumber2");
localStorage.removeItem("password2");
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const FormSchema = z.object({ const FormSchema = z.object({
text: z.string({ required_error: "لطفا متن خود را وارد نمایید." }), text: z
.string({ required_error: "لطفا متن خود را وارد نمایید." })
.max(
data?.maxTextLength,
`حداکثر ${data?.maxTextLength} کاراکتر می توانید وارد کنید.`
),
operation: z.string({ operation: z.string({
required_error: "لطفا نوع عملیات را انتخاب نمایید.", required_error: "لطفا نوع عملیات را انتخاب نمایید.",
}), }),
media: z media: z
.custom<FileList>((val) => val instanceof FileList, "Required") .custom<File[]>()
// .refine((files) => files.length > 0, `Required`) // .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(), .nullish(),
}); });
const possibleOperations = complaintData?.possibleOperationsWithDescription; const possibleOperations = complaintData?.possibleOperationsWithDescription;
const form = useForm<z.infer<typeof FormSchema>>({ const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema), resolver: zodResolver(FormSchema),
defaultValues: { defaultValues: {
@ -67,29 +118,7 @@ export default function InspectorOperations({
}, },
}); });
const OperationMutation = useMutation({ //Functions
mutationKey: ["Operation"],
mutationFn: postComplaintsDetails,
onSuccess: (res) => {
toast("عملیات شما با موفقیت انجام شد. ", {
className: "!bg-green-500 !text-white",
});
console.log(complaintData.trackingNumber);
console.log(localStorage.getItem("password2") as string);
updateData({
trackingNumber: complaintData.trackingNumber,
password: password
? password
: (localStorage.getItem("password2") as string),
});
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
function onSubmit(data: z.infer<typeof FormSchema>) { function onSubmit(data: z.infer<typeof FormSchema>) {
const formData = new FormData(); const formData = new FormData();
formData.append("text", data.text); formData.append("text", data.text);
@ -107,54 +136,113 @@ export default function InspectorOperations({
OperationMutation.mutate(formData); OperationMutation.mutate(formData);
} }
const deleteFileFromAttachments = (file: any) => {
const filtered = first?.filter((item) => item.name !== file);
setfirst(filtered);
form.setValue("media", filtered);
};
const allowedExtensions = data?.allowedExtensions;
const split = allowedExtensions?.split(",");
const withDot = split?.map((item: string) => "." + item);
const newAllowedExtensions = withDot?.join(",");
const formatSize = (size: number) => {
const string = formatBytes(size);
return (
<span className="" dir="ltr">
{string}
</span>
);
};
return ( return (
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className=""> <form onSubmit={form.handleSubmit(onSubmit)} className="">
<FormField <FormField
control={form.control} control={form.control}
name="text" name="text"
render={({ field }) => ( render={({ field, fieldState: { error } }) => (
<FormItem> <FormItem>
<FormLabel className="">متن</FormLabel> <FormLabel className="">متن</FormLabel>
<FormControl> <FormControl>
<Textarea <Textarea
placeholder="متن خود را وارد نمایید"
className="resize-none bg-white lg:min-h-[20em]" className="resize-none bg-white lg:min-h-[20em]"
{...field} {...field}
// disabled={possibleOperations.length == 0}
readOnly={possibleOperations.length == 0} readOnly={possibleOperations.length == 0}
/> />
</FormControl> </FormControl>
{/* <FormDescription> {!error ? (
You can <span>@mention</span> other users and organizations. <FormDescription className=" text-xs my-1 ">
</FormDescription> */} حداکثر {data?.maxTextLength} کاراکتر می توانید وارد کنید.
</FormDescription>
) : (
<FormMessage /> <FormMessage />
)}
</FormItem> </FormItem>
)} )}
/> />
{/* <div className="grid w-full max-w-sm items-center gap-1.5 mt-1">
<Label htmlFor="picture">پیوست</Label>
<Input multiple id="picture" type="file" className="bg-white " />
</div> */}
<FormField <FormField
control={form.control} control={form.control}
name="media" name="media"
render={({ field }) => ( render={({ field, fieldState: { error } }) => (
<FormItem> <FormItem>
<FormLabel>پیوست</FormLabel> <FormLabel>
<FormControl> پیوست‌ها ({field?.value?.length ? field.value.length : 0})
<Input </FormLabel>
accept=".jpg, .jpeg, .png, .svg, .gif, .mp4 , .pdf" <div className="flex gap-2 w-full items-center mt-1 mb-2">
<AttachmentsDialog
attachments={first}
deleteFile={(item) => deleteFileFromAttachments(item)}
>
<DialogTrigger className=" bg-white rounded-md h-9 text-xs flex-1 flex gap-2 items-center justify-center">
<Eye className=" w-4 h-4" />
<p>مشاهده</p>
</DialogTrigger>
</AttachmentsDialog>
<label
htmlFor="fileInput"
className="cursor-pointer text-sm rounded-md grid place-content-center h-9 px-2 bg-white w-1/2 items-center"
>
<div className=" flex gap-2 justify-center items-center">
<p className="text-xs flex gap-2 items-center">
<Upload className=" w-4 h-4" />
<span>افزودن</span>
</p>
</div>
</label>
<input
id="fileInput"
type="file" type="file"
onChange={(e) => { className="hidden"
field.onChange(e.target.files ? e.target.files : null); accept={newAllowedExtensions}
}}
multiple multiple
className="bg-white " onChange={(e) => {
disabled={possibleOperations.length == 0} // field.onChange(e.target.files ? e.target.files : null);
if (first && e.target.files) {
const fileArray1 = Array.from(first);
const fileArray2 = Array.from(e.target.files);
const mergedArray = fileArray1.concat(fileArray2);
setfirst(mergedArray);
field.onChange(mergedArray);
} else if (!first && e.target.files) {
const fileArray2 = Array.from(e.target.files);
setfirst(fileArray2);
field.onChange(fileArray2);
}
}}
/> />
</FormControl> </div>
{!error ? (
<FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست {formatSize(data?.maxFileSize)}{" "}
مگابایت باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage /> <FormMessage />
)}
</FormItem> </FormItem>
)} )}
/> />

View File

@ -40,20 +40,38 @@ import {
postComplaintSubmit, postComplaintSubmit,
} from "@/utils/citizenApi"; } from "@/utils/citizenApi";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { getCaptcha, getCategory, getOrganizations } from "@/utils/commonApi"; import {
getCaptcha,
getCategory,
getOptions,
getOrganizations,
} from "@/utils/commonApi";
import { Oval, ThreeDots } from "react-loader-spinner"; import { Oval, ThreeDots } from "react-loader-spinner";
import useToken from "@/store/useToken"; import useToken from "@/store/useToken";
import { toast } from "sonner"; import { toast } from "sonner";
import { RefreshCcw } from "lucide-react"; import { Eye, RefreshCcw, Upload } from "lucide-react";
import { getCookie } from "cookies-next"; import { getCookie } from "cookies-next";
import { formatBytes } from "@/lib/utils";
import AttachmentsDialog from "./AttachmentsDialog";
import { DialogTrigger } from "./ui/dialog";
const MAX_IMAGE_SIZE = 5242880; // 5 MB interface Organization {
const ALLOWED_IMAGE_TYPES = [ title: string;
"image/jpeg", description: string;
"image/png", isDeleted: string;
"image/webp", id: string;
"image/jpg", }
];
export default function RequestStep2() {
const router = useRouter();
const [file, setFile] = useState<File[]>([]);
// Queries
const { data: optionsData, isLoading: isLoadingData } = useQuery({
queryKey: ["Options"],
queryFn: () => getOptions(),
refetchOnWindowFocus: false,
});
const FormSchema = z.object({ const FormSchema = z.object({
title: z.string().min(1, { title: z.string().min(1, {
@ -72,21 +90,17 @@ const FormSchema = z.object({
message: "تعداد کاراکترها بیشتر از حد مجاز میباشد.", message: "تعداد کاراکترها بیشتر از حد مجاز میباشد.",
}), }),
uploadFile: z uploadFile: z
.custom<FileList>((val) => val instanceof FileList, "Required") .custom<File[]>()
// .refine((files) => files.length > 0, `Required`) // .refine((files) => files.length > 0, `Required`)
.refine((files) => files.length <= 5, `Maximum of 5 File are allowed.`)
.refine( .refine(
(files) => Array.from(files).every((file) => file.size <= MAX_IMAGE_SIZE), (files) => files.length <= optionsData?.maxFileCount,
`Each file size should be less than 5 MB.` `تعداد فایل های پیوست شده می بایست حداکثر ${optionsData?.maxFileCount} عدد باشد.`
)
.refine(
(files) => files.every((item) => item.size < optionsData?.maxFileSize),
`حجم هر فایل حداکثر می بایست ${optionsData?.maxFileSize} مگابایت باشد.`
) )
.nullish(), .nullish(),
// .refine(
// (files) =>
// Array.from(files).every((file) =>
// ALLOWED_IMAGE_TYPES.includes(file.type)
// ),
// "Only these types are allowed .jpg, .jpeg, .png and .webp"
// ),
categoryId: z.string({ categoryId: z.string({
required_error: "لطفا دسته بندی را انتخاب نمایید.", required_error: "لطفا دسته بندی را انتخاب نمایید.",
}), }),
@ -95,21 +109,6 @@ const FormSchema = z.object({
}), }),
}); });
interface Organization {
title: string;
description: string;
isDeleted: string;
id: string;
}
// Form Hook
export default function RequestStep2() {
// const [trackingComplaint, setTrackingComplaint] = useState({});
const isAuth = useToken((state) => state.token);
const router = useRouter();
useEffect(() => {
useToken.persist.rehydrate();
}, []);
const complaintSubmitMutation = useMutation({ const complaintSubmitMutation = useMutation({
mutationKey: ["complaintSubmit"], mutationKey: ["complaintSubmit"],
mutationFn: postComplaintSubmit, mutationFn: postComplaintSubmit,
@ -217,6 +216,25 @@ export default function RequestStep2() {
const { resetField } = useForm(); const { resetField } = useForm();
const deleteFileFromAttachments = (File: any) => {
const filtered = file?.filter((item) => item.name !== File);
setFile(filtered);
form.setValue("uploadFile", filtered);
};
const allowedExtensions = optionsData?.allowedExtensions;
const split = allowedExtensions?.split(",");
const withDot = split?.map((item: string) => "." + item);
const newAllowedExtensions = withDot?.join(",");
const formatSize = (size: number) => {
const string = formatBytes(size);
return (
<span className="" dir="ltr">
{string}
</span>
);
};
return ( return (
<div className="w-full h-full pt-12 sm:w-2/3 md:w-2/4 max-sm:p-8"> <div className="w-full h-full pt-12 sm:w-2/3 md:w-2/4 max-sm:p-8">
<div className="flex flex-col justify-center h-full space-y-3 md:space-y-4"> <div className="flex flex-col justify-center h-full space-y-3 md:space-y-4">
@ -329,7 +347,7 @@ export default function RequestStep2() {
)} )}
/> />
<div className="flex flex-row flex-wrap justify-between"> <div className="flex flex-row flex-wrap justify-between mb-2">
{/* Select Option */} {/* Select Option */}
<FormField <FormField
control={form.control} control={form.control}
@ -366,7 +384,7 @@ export default function RequestStep2() {
<FormField <FormField
control={form.control} control={form.control}
name="uploadFile" name="uploadFile"
render={({ field: { onChange }, ...field }) => { render={({ fieldState: { error }, field }) => {
// Get current uploadFile value (always watched updated) // Get current uploadFile value (always watched updated)
const uploadFile = form.watch("uploadFile"); const uploadFile = form.watch("uploadFile");
@ -380,44 +398,65 @@ export default function RequestStep2() {
return ( return (
<FormItem className="w-full sm:w-[48%]"> <FormItem className="w-full sm:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7"> <FormLabel className=" text-[#7C838A] text-sm mt-7">
پیوست پیوست‌ها (
{field?.value?.length ? field.value.length : 0})
</FormLabel> </FormLabel>
{/* File Upload */} <div className="flex gap-2 w-full items-center">
<FormControl> <AttachmentsDialog
<Input attachments={file}
deleteFile={(item) => deleteFileFromAttachments(item)}
>
<DialogTrigger className=" bg-slate-200 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-slate-200 w-1/2 items-center"
>
<div className=" flex gap-2 justify-center items-center">
<p className="text-xs flex gap-2 items-center">
<Upload className=" w-4 h-4" />
<span>افزودن</span>
</p>
</div>
</label>
<input
id="fileInput"
type="file" type="file"
className="mb-3" className="hidden"
accept="image/* , .pdf" accept={newAllowedExtensions}
multiple={true} multiple
disabled={form.formState.isSubmitting} onChange={(e) => {
{...field} // field.onChange(e.target.files ? e.target.files : null);
onChange={(event) => { if (file && e.target.files) {
// Triggered when user uploaded a new file const fileArray1 = Array.from(file);
// FileList is immutable, so we need to create a new one const fileArray2 = Array.from(e.target.files);
const dataTransfer = new DataTransfer(); const mergedArray = fileArray1.concat(fileArray2);
setFile(mergedArray);
// Add old images field.onChange(mergedArray);
// if (images) { } else if (!file && e.target.files) {
// Array.from(images).forEach((image) => const fileArray2 = Array.from(e.target.files);
// dataTransfer.items.add(image) setFile(fileArray2);
// ); field.onChange(fileArray2);
// } }
// Add newly uploaded images
Array.from(event.target.files!).forEach((image) =>
dataTransfer.items.add(image)
);
// Validate and update uploaded file
const newFiles = dataTransfer.files;
onChange(newFiles);
}} }}
/> />
</FormControl> </div>
{/* Show File Name */} {/* {!error ? (
{/* <FormDescription>{`${filenames}`}</FormDescription> */} <FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست{" "}
{formatSize(optionsData?.maxFileSize)} مگابایت باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${optionsData?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage /> <FormMessage />
)} */}
</FormItem> </FormItem>
); );
}} }}

View File

@ -13,16 +13,15 @@ export function cn(...inputs: ClassValue[]) {
} }
export function convertDate(date: string) { export function convertDate(date: string) {
const convertedDate = dayjs(date) const convertedDate = dayjs(date + "Z")
.calendar("jalali") .calendar("jalali")
.locale("fa") .locale("fa")
.format("YYYY/M/DD"); .format("YYYY/M/DD");
return convertedDate; return convertedDate;
} }
export function convertFullTime(date: string) { export function convertFullTime(date: string) {
const convertedDate = dayjs(date) const convertedDate = dayjs(date + "Z")
.calendar("jalali") .calendar("jalali")
.locale("fa") .locale("fa")
.format(" HH:mm - YYYY/M/DD"); .format(" HH:mm - YYYY/M/DD");
@ -30,28 +29,12 @@ export function convertFullTime(date: string) {
} }
export function Decrypt(encryptedData: string, privateKey: string) { export function Decrypt(encryptedData: string, privateKey: string) {
const Key = `-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCfmb1aGcWsqJPp+v6e72CPngE6P6FoCZCJESwDTXUXiJiAKshB
WZ9nlN+IIpQr6h8gmxi8SWbofPWmSKZgTyU2MddxUanneuywPTTUj4HQ6/DUaDwF
0Vr6Fk0x4yi1GKpBzhRFPyOYBWVXKIw23j0l+EWw6+JIpR9Kwu0TezHHFQIDAQAB
AoGBAIVxegy3t7vhR6s/HV2uMEJkjgox4banKJ4yKWapgNmocDnZi454bPuiUjP1
FYaSPmx4wXnMtap1sL7Tx6iHBEi10KB1AghDZP5wJHz6nm9ugcrGSSWhVJM74x6C
ThVztAV/rydaZ6/DLaqsBg5lHlo1DjMKq4sxnqrw/LUMGtOBAkEAzt8bnM1Ij/rF
i8oSP3gI0H914vf/0N2xxGGdQvMmJK0oijIm5j8dFDZf02Ft34SFeVJfXyVPapDE
vQ6TRw+1HQJBAMWAwvbypbtl65Dn4qCj3oJUmmnjjxm5080idF1S6ufo34p2gHMF
qLtWjmnGqjh2Shs7ahnfbLF+cxzgBg7yEFkCQFYGl1/0Sel9uepwpHf6PYgeiPJS
ePHtTwBAK3pszH7R9xrI0j5LHpeKKP0o9dzOKgcShxB03nqNKxMHXZ1eXc0CQFhD
Ot3xgm9FFQklF/qCQSYtePRpZcIxcZ3zD93E+IW7ZGsUmkLM/KL8A5jx15B0DJou
6zO0zXZk9DyrQQnc08ECQGy5ti89HmQ6I6Wqq5ADglCY6YPISsNwScVyvu/WxQsX
dEqG/38xFdYTFEekexcHnT/Vt1MW4/j76vBJHYWuAJU=
-----END RSA PRIVATE KEY-----`;
const decryptor = new JSEncrypt(); const decryptor = new JSEncrypt();
decryptor.setPrivateKey(privateKey); decryptor.setPrivateKey(privateKey);
const decrypted = decryptor.decrypt(encryptedData); const decrypted = decryptor.decrypt(encryptedData);
return decrypted; return decrypted;
} }
export function isAuthorized() { export function isAuthorized() {
const token = getCookie("Sootzani_Token"); const token = getCookie("Sootzani_Token");
if (token) { if (token) {
@ -60,3 +43,41 @@ export function isAuthorized() {
false; false;
} }
} }
export function bytesToMB(bytes: number) {
return Math.floor(bytes / (1024 * 1024));
}
export function formatBytes(bytes: number, decimals = 2) {
console.log(bytes);
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 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]}`;
}

18
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "sootzani", "name": "sootzani",
"version": "0.1.13", "version": "0.1.16",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sootzani", "name": "sootzani",
"version": "0.1.13", "version": "0.1.16",
"dependencies": { "dependencies": {
"@hookform/resolvers": "^3.3.2", "@hookform/resolvers": "^3.3.2",
"@radix-ui/react-alert-dialog": "^1.0.5", "@radix-ui/react-alert-dialog": "^1.0.5",
@ -40,6 +40,7 @@
"lucide-react": "^0.292.0", "lucide-react": "^0.292.0",
"next": "14.0.3", "next": "14.0.3",
"next-nprogress-bar": "^2.1.2", "next-nprogress-bar": "^2.1.2",
"next-runtime-env": "^3.2.0",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"npm": "^10.2.5", "npm": "^10.2.5",
"react": "^18.2.0", "react": "^18.2.0",
@ -4834,6 +4835,19 @@
"nprogress": "^0.2.0" "nprogress": "^0.2.0"
} }
}, },
"node_modules/next-runtime-env": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/next-runtime-env/-/next-runtime-env-3.2.0.tgz",
"integrity": "sha512-rwe3flUgSRm51hzRN4Vt5MMSYMS4aDMEPJa0r+CMONA3UyUZl8Y5O8zjHSIlaNb3yquTCttZ0ahObPyPprBj9g==",
"dependencies": {
"next": "^14",
"react": "^18"
},
"peerDependencies": {
"next": "^14",
"react": "^18"
}
},
"node_modules/next-themes": { "node_modules/next-themes": {
"version": "0.2.1", "version": "0.2.1",
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.2.1.tgz", "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.2.1.tgz",

View File

@ -1,6 +1,6 @@
{ {
"name": "sootzani", "name": "sootzani",
"version": "0.1.13", "version": "0.1.16",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@ -41,6 +41,7 @@
"lucide-react": "^0.292.0", "lucide-react": "^0.292.0",
"next": "14.0.3", "next": "14.0.3",
"next-nprogress-bar": "^2.1.2", "next-nprogress-bar": "^2.1.2",
"next-runtime-env": "^3.2.0",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"npm": "^10.2.5", "npm": "^10.2.5",
"react": "^18.2.0", "react": "^18.2.0",

View File

@ -5,8 +5,9 @@ import {
getCookie, getCookie,
setCookie, setCookie,
} from "cookies-next"; } from "cookies-next";
import { env } from "next-runtime-env";
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP; const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP");
axios.defaults.baseURL = NEXT_PUBLIC_BASE_URL_APP;
let isRefreshing = false; let isRefreshing = false;
axios.interceptors.response.use( axios.interceptors.response.use(
@ -22,8 +23,8 @@ axios.interceptors.response.use(
originalRequest._retry = true; originalRequest._retry = true;
const accessToken = getCookie("Sootzani_Token"); const accessToken = getCookie("Sootzani_Token");
const refreshToken = getCookie("Sootzani_Refresh_Token"); const refreshToken = getCookie("Sootzani_Refresh_Token");
//accessToken && refreshToken && !isRefreshing
if (accessToken && refreshToken && !isRefreshing) { if (!isRefreshing) {
isRefreshing = true; isRefreshing = true;
try { try {

View File

@ -1,7 +1,8 @@
import axios from "axios"; import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next"; import { CookieValueTypes, getCookie } from "cookies-next";
import { env } from "next-runtime-env";
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP; 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) { axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Token"); const token = getCookie("Sootzani_Token");

View File

@ -43,3 +43,8 @@ export async function getNewsById(id: number) {
const data = await axios.get(`api/Common/News/${id}`); const data = await axios.get(`api/Common/News/${id}`);
return data.data; return data.data;
} }
export async function getOptions() {
const data = await axios.get("/api/Common/Options");
return data.data;
}