"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, useQueryClient } from "@tanstack/react-query"; import { OperateByInspector } from "@/utils/inspectorApi"; import { toast } from "sonner"; 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, role, updateData, id, key2, }: { complaintData: any; role: string; updateData: (data: any) => any; id: any; key2: any; }) { const [file, setFile] = useState([]); const [check, setCheck] = useState(false); const [charCount, setCharCount] = useState(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: "لطفا متن خود را وارد نمایید." }) .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, }, }); // 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) { 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) { const storedData = JSON.parse( localStorage.getItem("CompliantData") as string ); const dcKey = Decrypt( storedData.cipherKeyInspector, localStorage.getItem("privateKey") as string ); const formData = new FormData(); formData.append("text", data.text); formData.append("trackingNumber", complaintData.trackingNumber); formData.append("Operation", data.operation); if (data.type) { formData.append("IsPublic", data.type == "public" ? "true" : "false"); } 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]); } } 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 ( {string} ); }; return (
( متن({charCount}/{data?.maxTextLength})