Sootzani/components/InspectorOperations.tsx

342 lines
12 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
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 { Textarea } from "@/components/ui/textarea";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Operations } from "@/constants";
import useData from "@/store/useData";
import { useMutation, useQuery } from "@tanstack/react-query";
import { OperateByInspector } from "@/utils/inspectorApi";
import { toast } from "sonner";
import { postComplaintsDetails } from "@/utils/citizenApi";
import { useEffect, 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({
complaintData,
role,
updateData,
password,
}: {
complaintData: any;
role: string;
updateData: (data: any) => any;
password?: string;
}) {
const [first, setfirst] = useState<File[]>([]);
const [charCount, setCharCount] = useState(0);
// 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({
text: z
.string({ required_error: "لطفا متن خود را وارد نمایید." })
.max(
data?.maxTextLength,
`حداکثر ${data?.maxTextLength} کاراکتر می توانید وارد کنید.`
),
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 possibleOperations = complaintData?.possibleOperationsWithDescription;
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
operation:
possibleOperations.length == 1
? String(possibleOperations[0].value)
: undefined,
},
});
// Add the useEffect hook to monitor changes in the description field
useEffect(() => {
setCharCount(form.watch("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);
}
}
//Functions
function onSubmit(data: z.infer<typeof FormSchema>) {
const formData = new FormData();
formData.append("text", data.text);
formData.append("trackingNumber", complaintData.trackingNumber);
formData.append("Operation", data.operation);
formData.append(
"password",
password ? password : (localStorage.getItem("password2") as string)
);
if (data?.media && data?.media?.length > 0) {
for (let i = 0; i < data.media.length; i++) {
formData.append("Medias", data.media[i]);
}
}
OperationMutation.mutate(formData);
}
const deleteAllAttachmentsFiles = () => {
setfirst([]);
form.setValue("media", []);
};
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 (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="">
<FormField
control={form.control}
name="text"
render={({ field, fieldState: { error } }) => (
<FormItem>
<FormLabel className="">
متن({charCount}/{data?.maxTextLength})
</FormLabel>
<FormControl>
<Textarea
className="resize-none bg-white lg:min-h-[20em]"
{...field}
readOnly={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>
{!error ? (
<FormDescription className=" text-xs my-1 ">
حداکثر {data?.maxTextLength} کاراکتر می توانید وارد کنید.
</FormDescription>
) : (
<FormMessage />
)}
</FormItem>
)}
/>
<FormField
control={form.control}
name="media"
render={({ field, fieldState: { error } }) => (
<FormItem>
<FormLabel>
پیوست‌ها ({field?.value?.length ? field.value.length : 0})
</FormLabel>
<div className="flex gap-2 w-full items-center mt-1 mb-2">
<AttachmentsDialog
attachments={first}
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"
className="hidden"
accept={newAllowedExtensions}
multiple
onChange={(e) => {
// 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);
}
}}
/>
</div>
{!error ? (
<FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست {formatSize(data?.maxFileSize)}{" "}
باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${data?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage />
)}
</FormItem>
)}
/>
<div className="flex justify-between gap-2 mt-3 ">
<FormField
control={form.control}
name="operation"
render={({ field }) => (
<FormItem className="flex-1 ">
{/* <FormLabel>Email</FormLabel> */}
<Select
onValueChange={field.onChange}
defaultValue={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger
className=" bg-white h-10 !placeholder:text-xs text-xs"
dir="rtl"
disabled={possibleOperations.length == 0}
>
<SelectValue
className="text-xs "
placeholder="نوع عملیات را انتخاب نمایید."
/>
</SelectTrigger>
</FormControl>
<SelectContent dir="rtl">
<SelectGroup>
<SelectLabel>عملیات</SelectLabel>
{possibleOperations.map((item: any) => {
return (
<SelectItem
key={item.value}
value={String(item.value)}
>
{item.description}
</SelectItem>
);
})}
</SelectGroup>
</SelectContent>
</Select>
{/* <FormDescription>
You can manage email addresses in your{" "}
</FormDescription> */}
<FormMessage />
</FormItem>
)}
/>
<Button
disabled={possibleOperations.length == 0}
className="w-1/3 bg-blue"
type="submit"
>
ثبت
</Button>
</div>
</form>
</Form>
);
}