File uploader changed

Kahdooie
Hossein Rahmani 2024-02-02 15:49:49 +03:30
parent f35df44436
commit 45099f1dac
6 changed files with 238 additions and 73 deletions

View File

@ -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 (
<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

@ -259,10 +259,10 @@ export default function ComplainsDetails({
<p>بازگشت</p>
</button> */}
<div className="flex items-start w-full gap-2 mt-2 max-lg:flex-col h-[80vh]">
<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-[80vh]">
<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-10 flex flex-col lg:h-full">
<p className="text-[#464646] text-base font-bold mb-1">
انجام عملیات
</p>
@ -437,8 +437,8 @@ export default function ComplainsDetails({
<div className="flex items-center gap-4 justify-between">
<p className="">
<Badge>
{item.operationWithDescription.description} توسط
{" "}{item.sender == 0 ? "شهروند" : "بازرس"}
{item.operationWithDescription.description} توسط{" "}
{item.sender == 0 ? "شهروند" : "بازرس"}
</Badge>
</p>
<p className="">
@ -499,19 +499,6 @@ export default function ComplainsDetails({
</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>
</>
) : (

View File

@ -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<FileList>((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<File[]>([]);
const password = useData((state) => state.data.password);
const possibleOperations = complaintData?.possibleOperationsWithDescription;
const queryClient = useQueryClient();
const form = useForm<z.infer<typeof FormSchema>>({
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<File[]>()
// .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<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
operation:
possibleOperations.length == 1
? String(possibleOperations[0].value)
: undefined,
},
});
function onSubmit(data: z.infer<typeof FormSchema>) {
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 (
<span className="" dir="ltr">
{string}
</span>
);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="">
<FormField
control={form.control}
name="text"
render={({ field }) => (
render={({ field, fieldState: { error } }) => (
<FormItem>
<FormLabel className="">متن</FormLabel>
<FormControl>
@ -146,32 +190,79 @@ export default function InspectorOperations({
disabled={possibleOperations.length == 0}
/>
</FormControl>
{/* <FormDescription>
You can <span>@mention</span> other users and organizations.
</FormDescription> */}
{!error ? (
<FormDescription className=" text-xs my-1 ">
حداکثر {data?.maxTextLength} کاراکتر می توانید وارد کنید.
</FormDescription>
) : (
<FormMessage />
)}
</FormItem>
)}
/>
<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)}
>
<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);
}}
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);
}
}}
/>
</FormControl>
</div>
{!error ? (
<FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست {formatSize(data?.maxFileSize)}{" "}
مگابایت باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage />
)}
</FormItem>
)}
/>
@ -180,7 +271,7 @@ 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}
@ -189,19 +280,27 @@ export default function InspectorOperations({
>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="private" className="ml-2 " disabled={possibleOperations.length == 0}/>
<RadioGroupItem
value="private"
className="ml-2 "
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 " disabled={possibleOperations.length == 0}/>
<RadioGroupItem
value="public"
className="ml-2 "
disabled={possibleOperations.length == 0}
/>
</FormControl>
<FormLabel className="font-normal">عمومی</FormLabel>
</FormItem>
</RadioGroup>
</FormControl>
<FormMessage />
<FormMessage className=" mt-1" />
</FormItem>
)}
/>

View File

@ -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]}`;
}

View File

@ -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 {

View File

@ -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;
}