import { zodResolver } from "@hookform/resolvers/zod"; import Button from "../../../components/Button/Button"; import { Grid } from "../../../components/Grid/Grid"; import Textfield from "../../../components/Textfeild/Textfeild"; import { useForm, Controller } from "react-hook-form"; import { zValidateAutoComplete, zValidateNumber, zValidateString, } from "../../../data/getFormTypeErrors"; import { z } from "zod"; import { useApiMutation } from "../../../utils/useApiRequest"; import { useToast } from "../../../hooks/useToast"; import { useModalStore } from "../../../context/zustand-store/appStore"; import { getToastResponse } from "../../../data/getToastResponse"; import { FormApiBasedAutoComplete } from "../../../components/FormItems/FormApiBasedAutoComplete"; import AutoComplete from "../../../components/AutoComplete/AutoComplete"; import { ImageUploader } from "../../../components/ImageUploader/ImageUploader"; import { useState } from "react"; const schema = z.object({ name: zValidateString("نام "), category: zValidateNumber("دسته بندی"), type: zValidateAutoComplete("نوع محصول"), }); type AddPageProps = { getData: () => void; item?: any; }; type FormValues = z.infer; const productTypes = [ { key: "gov", value: "دولتی", disabled: false }, { key: "free", value: "آزاد", disabled: false }, ]; export const AddProduct = ({ getData, item }: AddPageProps) => { const showToast = useToast(); const { closeModal } = useModalStore(); const [image, setImage] = useState(""); const { control, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(schema), defaultValues: { name: item?.name || "", type: item?.type ? [`${item?.type}`] : ["gov"], }, }); const mutation = useApiMutation({ api: `/product/web/api/v1/product/${item ? item?.id + "/" : ""}`, method: item ? "put" : "post", }); const onSubmit = async (data: FormValues) => { try { await mutation.mutateAsync({ name: data?.name, type: data?.type[0], category: data?.category, image: image || undefined, }); showToast(getToastResponse(item, ""), "success"); getData(); closeModal(); } catch (error: any) { if (error?.status === 403) { showToast( error?.response?.data?.message || "این مورد تکراری است!", "error", ); } else { showToast( error?.response?.data?.message || "خطا در ثبت اطلاعات!", "error", ); } } }; return (
( )} /> ( <> { setValue("category", r); }} /> )} /> ( { setValue("type", keys); }} error={!!errors.type} helperText={errors.type?.message} title="نوع محصول" /> )} /> setImage(base64)} title="تصویر محصول" defaultValue={item?.img} width={430} height={389} />
); };