From 45099f1dac4c0c881de4c191008d4b570dded1fc Mon Sep 17 00:00:00 2001 From: Hossein Rahmani Date: Fri, 2 Feb 2024 15:49:49 +0330 Subject: [PATCH] File uploader changed --- components/AttachmentsDialog.tsx | 60 +++++++++ components/ComplainsDetails.tsx | 27 +--- components/InspectorOperations.tsx | 201 +++++++++++++++++++++-------- lib/utils.ts | 14 ++ utils/authenticateApi.ts | 4 +- utils/commonApi.ts | 5 + 6 files changed, 238 insertions(+), 73 deletions(-) create mode 100644 components/AttachmentsDialog.tsx diff --git a/components/AttachmentsDialog.tsx b/components/AttachmentsDialog.tsx new file mode 100644 index 0000000..e4f1dcc --- /dev/null +++ b/components/AttachmentsDialog.tsx @@ -0,0 +1,60 @@ +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 ( + + {children} + + + پیوست‌ها + + {attachments.length == 0 ? ( +
هیج پیوستی وجود ندارد.
+ ) : ( +
+ {attachments?.map((item, index) => { + return ( +
+
+ {index + 1} +
+
+
+

{item.name}

+
+ + deleteFile(item.name)} + className=" cursor-pointer hover:drop-shadow-md" + /> +
+
+ ); + })} +
+ )} +
+
+
+
+ ); +} diff --git a/components/ComplainsDetails.tsx b/components/ComplainsDetails.tsx index 4ff7af2..f1c7bbc 100644 --- a/components/ComplainsDetails.tsx +++ b/components/ComplainsDetails.tsx @@ -259,10 +259,10 @@ export default function ComplainsDetails({

بازگشت

*/} -
+
{/* 1 */} -
-
+
+

انجام عملیات

@@ -436,10 +436,10 @@ export default function ComplainsDetails({ >

- - {item.operationWithDescription.description} توسط - {" "}{item.sender == 0 ? "شهروند" : "بازرس"} - + + {item.operationWithDescription.description} توسط{" "} + {item.sender == 0 ? "شهروند" : "بازرس"} +

@@ -499,19 +499,6 @@ export default function ComplainsDetails({

- {/* 3 */} -
-

- انجام عملیات -

- getComplaintMutation.mutate(data)} - role={role} - complaintData={data} - id={id} - key2={key} - /> -
) : ( diff --git a/components/InspectorOperations.tsx b/components/InspectorOperations.tsx index 358309f..9fe4432 100644 --- a/components/InspectorOperations.tsx +++ b/components/InspectorOperations.tsx @@ -29,10 +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 { Decrypt } from "@/lib/utils"; +import { Decrypt, formatBytes } from "@/lib/utils"; +import { 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, @@ -47,35 +52,13 @@ export default function InspectorOperations({ id: any; key2: any; }) { - const FormSchema = z.object({ - text: z.string({ required_error: "لطفا متن خود را وارد نمایید." }), - ...(role == "Inspector" && { - type: z.enum(["private", "public"], { - required_error: "لطفا وضعیت عملیات را انتخاب نمایید.", - }), - }), - operation: z.string({ - required_error: "لطفا نوع عملیات را انتخاب نمایید.", - }), - media: z - .custom((val) => val instanceof FileList, "Required") - // .refine((files) => files.length > 0, `Required`) - .refine((files) => files.length <= 5, `Maximum of 5 File are allowed.`) - .nullish(), - }); + const [file, setFile] = useState([]); - const password = useData((state) => state.data.password); - const possibleOperations = complaintData?.possibleOperationsWithDescription; - const queryClient = useQueryClient(); - - const form = useForm>({ - resolver: zodResolver(FormSchema), - defaultValues: { - operation: - possibleOperations.length == 1 - ? String(possibleOperations[0].value) - : undefined, - }, + // Queries + const { data, isLoading, refetch } = useQuery({ + queryKey: ["Options"], + queryFn: () => getOptions(), + refetchOnWindowFocus: false, }); const OperationMutation = useMutation({ @@ -105,6 +88,48 @@ export default function InspectorOperations({ }, }); + const FormSchema = z.object({ + text: z + .string({ required_error: "لطفا متن خود را وارد نمایید." }) + .max( + data?.maxTextLength, + `حداکثر ${data?.maxTextLength} کاراکتر می توانید وارد کنید.` + ), + ...(role == "Inspector" && { + type: z.enum(["private", "public"], { + required_error: "لطفا وضعیت عملیات را انتخاب نمایید.", + }), + }), + operation: z.string({ + required_error: "لطفا نوع عملیات را انتخاب نمایید.", + }), + media: z + .custom() + // .refine((files) => files.length > 0, `Required`) + .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 form = useForm>({ + resolver: zodResolver(FormSchema), + defaultValues: { + operation: + possibleOperations.length == 1 + ? String(possibleOperations[0].value) + : undefined, + }, + }); + function onSubmit(data: z.infer) { const storedData = JSON.parse( localStorage.getItem("CompliantData") as string @@ -129,13 +154,32 @@ export default function InspectorOperations({ OperationMutation.mutate(formData); } + const deleteFileFromAttachments = (File: any) => { + const filtered = file?.filter((item) => item.name !== File); + setFile(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 ( + + {string} + + ); + }; + return (
( + render={({ field, fieldState: { error } }) => ( متن @@ -146,32 +190,79 @@ export default function InspectorOperations({ disabled={possibleOperations.length == 0} /> - {/* - You can @mention other users and organizations. - */} - + {!error ? ( + + حداکثر {data?.maxTextLength} کاراکتر می توانید وارد کنید. + + ) : ( + + )} )} /> ( + render={({ field, fieldState: { error } }) => ( - پیوست‌ها - - + پیوست‌ها ({field?.value?.length ? field.value.length : 0}) + +
+ deleteFileFromAttachments(item)} + > + + +

مشاهده

+
+
+ + { - field.onChange(e.target.files ? e.target.files : null); - }} + className="hidden" + accept={newAllowedExtensions} multiple - className="bg-white " - disabled={possibleOperations.length == 0} + 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); + setFile(mergedArray); + field.onChange(mergedArray); + } else if (!file && e.target.files) { + const fileArray2 = Array.from(e.target.files); + setFile(fileArray2); + field.onChange(fileArray2); + } + }} /> - - +
+ {!error ? ( + + + حجم هر فایل حداکثر می بایست {formatSize(data?.maxFileSize)}{" "} + مگابایت باشد + {" "} + و{" "} + {`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} تا باشد.`} + + ) : ( + + )}
)} /> @@ -180,7 +271,7 @@ export default function InspectorOperations({ control={form.control} name="type" render={({ field }) => ( - + - + خصوصی - + عمومی - + )} /> diff --git a/lib/utils.ts b/lib/utils.ts index ff226c9..315a09d 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -37,3 +37,17 @@ export function Decrypt(encryptedData: any, privateKey: any) { const decrypted = decryptor.decrypt(encryptedData); return decrypted; } + +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 i = Math.floor(Math.log(bytes) / Math.log(k)); + + return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; +} + diff --git a/utils/authenticateApi.ts b/utils/authenticateApi.ts index f654540..b422d8d 100644 --- a/utils/authenticateApi.ts +++ b/utils/authenticateApi.ts @@ -22,8 +22,8 @@ axios.interceptors.response.use( originalRequest._retry = true; const accessToken = getCookie("Sootzani_Admin_Token"); const refreshToken = getCookie("Sootzani_Admin_Refresh_Token"); - - if (accessToken && refreshToken && !isRefreshing) { + //accessToken && refreshToken && !isRefreshing + if (!isRefreshing) { isRefreshing = true; try { diff --git a/utils/commonApi.ts b/utils/commonApi.ts index 4fc0b51..2bb73bc 100644 --- a/utils/commonApi.ts +++ b/utils/commonApi.ts @@ -18,3 +18,8 @@ export async function getContents() { const data = await axios.get("api/Common/Contents"); return data.data; } + +export async function getOptions() { + const data = await axios.get("/api/Common/Options"); + return data.data; +} \ No newline at end of file