import React, { useEffect, useMemo } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm, Controller, useFieldArray } from "react-hook-form"; import { z } from "zod"; import { Grid } from "../../components/Grid/Grid"; import Typography from "../../components/Typography/Typography"; import Button from "../../components/Button/Button"; import Textfield from "../../components/Textfeild/Textfeild"; import AutoComplete from "../../components/AutoComplete/AutoComplete"; import { useDrawerStore } from "../../context/zustand-store/appStore"; import { useUserProfileStore } from "../../context/zustand-store/userStore"; import { useApiRequest, useApiMutation } from "../../utils/useApiRequest"; import { useToast } from "../../hooks/useToast"; import { TrashIcon } from "@heroicons/react/24/outline"; import { zValidateString, zValidateStringOptional, zValidateAutoCompleteOptional, } from "../../data/getFormTypeErrors"; interface MainSubmitInspectionProps { item?: any; isEdit?: boolean; inspectId?: string; handleUpdate?: () => void; } const infractionSchema = z.object({ title: zValidateString("عنوان تخلف"), description: zValidateString("توضیحات تخلف"), }); const schema = z.object({ license_type: z.array(z.union([z.string(), z.number()])).min(1, { message: "لطفاً نوع پروانه کسب را انتخاب کنید.", }), document_number: zValidateString("شماره پرونده یا مجوز"), issuer: zValidateString("صادر کننده پروانه"), economic_code: zValidateString("کد اقتصادی"), registration_number: zValidateString("شماره ثبت"), ownership_type: z.array(z.union([z.string(), z.number()])).min(1, { message: "لطفاً نوع مالکیت را انتخاب کنید.", }), unit_type: z.array(z.union([z.string(), z.number()])).min(1, { message: "لطفاً نوع واحد را انتخاب کنید.", }), description: zValidateStringOptional("توضیحات"), inspectors: zValidateAutoCompleteOptional(), infractions: z.array(infractionSchema).optional(), violation_amount: zValidateStringOptional("جمع کل ارزش ریالی تخلف"), plaintiff_damage: zValidateStringOptional("جمع کل خسارت وارده به شاکی"), }); type FormValues = z.infer; const MainSubmitInspection: React.FC = ({ item, isEdit = false, inspectId, handleUpdate, }) => { const { profile } = useUserProfileStore(); const { closeDrawer } = useDrawerStore(); const showToast = useToast(); const { data: usersData } = useApiRequest({ api: `users/${profile?.province}`, enabled: !!profile?.province, }); const licenseTypeOptions = [ { key: "دائم", value: "دائم" }, { key: "موقت", value: "موقت" }, ]; const ownershipTypeOptions = [ { key: "دولتی", value: "دولتی" }, { key: "غیر دولتی", value: "غیر دولتی" }, { key: "استیجاری", value: "استیجاری" }, { key: "شخصی", value: "شخصی" }, { key: "سایر موارد", value: "سایر موارد" }, ]; const unitTypeOptions = [ { key: "وارد کننده", value: "وارد کننده" }, { key: "تولیدی صنعتی", value: "تولیدی صنعتی" }, { key: "تولیدی صنفی", value: "تولیدی صنفی" }, { key: "انبار", value: "انبار" }, { key: "سردخانه", value: "سردخانه" }, { key: "توزیعی", value: "توزیعی" }, { key: "خدماتی", value: "خدماتی" }, { key: "خرده فروش", value: "خرده فروش" }, { key: "عمده فروش", value: "عمده فروش" }, ]; const inspectorOptions = useMemo(() => { if (!usersData?.data) return []; return usersData.data .filter( (user: any) => user.province === profile?.province && !user?.permissions?.includes("admin") ) .map((user: any) => ({ key: `${user.fullname} / ${user.mobile}`, value: `${user.fullname} / ${user.mobile}`, })); }, [usersData, profile]); const defaultInspectorKeys = useMemo(() => { if (!isEdit || !item?.inspectors) return []; return item.inspectors.map((insp: any) => { if (typeof insp === "string") return insp; const user = usersData?.data?.find( (u: any) => u.fullname === insp.fullname ); return user ? `${insp.fullname} / ${user.mobile}` : insp.fullname; }); }, [item, isEdit, usersData]); const { control, handleSubmit, setValue, watch, formState: { errors, isSubmitting }, } = useForm({ resolver: zodResolver(schema), defaultValues: { license_type: item?.license_type ? [item.license_type] : [], document_number: item?.document_number || "", issuer: item?.issuer || "", economic_code: item?.economic_code || "", registration_number: item?.registration_number || "", ownership_type: item?.ownership_type ? [item.ownership_type] : [], unit_type: item?.unit_type ? [item.unit_type] : [], description: item?.description || "", inspectors: defaultInspectorKeys, infractions: item?.infractions || [], violation_amount: item?.violation_amount || "", plaintiff_damage: item?.plaintiff_damage || "", }, }); const { fields, append, remove } = useFieldArray({ control, name: "infractions", }); const watchedInfractions = watch("infractions"); useEffect(() => { if (isEdit && item?.inspectors && usersData?.data) { const inspectorStrings = item.inspectors.map((insp: any) => { if (typeof insp === "string") return insp; const user = usersData.data.find( (u: any) => u.fullname === insp.fullname ); return user ? `${insp.fullname} / ${user.mobile}` : insp.fullname; }); setValue("inspectors", inspectorStrings); } }, [item, isEdit, usersData, setValue]); const submitInspectionMutation = useApiMutation({ api: "inspections", method: "post", }); // Create update mutation with the correct URL including the ID const updateInspectionMutation = useApiMutation({ api: inspectId ? `inspections/${inspectId}` : "inspections", method: "put", }); const onSubmit = async (data: FormValues) => { try { const payload = { user_id: profile?._id || profile?.Id, place_key: item?.key, province: profile?.province, license_type: String(data.license_type[0]), document_number: data.document_number, issuer: data.issuer, economic_code: data.economic_code, registration_number: data.registration_number, ownership_type: String(data.ownership_type[0]), unit_type: String(data.unit_type[0]), description: data.description || "", infractions: data.infractions || [], inspectors: (data.inspectors || []).map((inspector) => { const fullname = String(inspector).split(" / ")[0]; return { fullname }; }), violation_amount: data.violation_amount || "0", plaintiff_damage: data.plaintiff_damage || "0", }; if (isEdit && inspectId) { await updateInspectionMutation.mutateAsync(payload); showToast("ویرایش بازرسی با موفقیت ثبت شد", "success"); handleUpdate?.(); } else { await submitInspectionMutation.mutateAsync(payload); showToast("بازرسی با موفقیت ثبت شد", "success"); handleUpdate?.(); } closeDrawer(); } catch (error: any) { console.error("Error submitting inspection:", error); showToast(error?.response?.data?.message || "بازرسی ثبت نشد!", "error"); } }; return (
( setValue("license_type", keys as any)} title="نوع پروانه کسب" error={!!errors.license_type} helperText={errors.license_type?.message} /> )} /> ( )} /> ( )} /> ( )} /> ( )} /> ( setValue("ownership_type", keys as any)} title="نوع مالکیت" error={!!errors.ownership_type} helperText={errors.ownership_type?.message} /> )} /> ( setValue("unit_type", keys as any)} title="نوع واحد" error={!!errors.unit_type} helperText={errors.unit_type?.message} /> )} /> ( setValue("inspectors", keys as any)} title="بازرسان همراه" error={!!errors.inspectors} helperText={errors.inspectors?.message} /> )} /> تخلفات {fields.map((field, index) => ( تخلف {index + 1} ( )} /> (