import { z } from "zod"; import { zValidateAutoComplete, zValidateAutoCompleteOptional, zValidateString, } from "../../data/getFormTypeErrors"; import { useToast } from "../../hooks/useToast"; import { useModalStore } from "../../context/zustand-store/appStore"; import { zodResolver } from "@hookform/resolvers/zod"; import { Controller, useForm } from "react-hook-form"; import { useApiMutation } from "../../utils/useApiRequest"; import { getToastResponse } from "../../data/getToastResponse"; import { Grid } from "../../components/Grid/Grid"; import Textfield from "../../components/Textfeild/Textfeild"; import Button from "../../components/Button/Button"; import { RadioGroup } from "../../components/RadioButton/RadioGroup"; import { useState } from "react"; import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete"; type Props = { getData: () => void; item?: any; }; const attributeProductType = [ { label: "عمومی", value: true }, { label: "به ازای محصول", value: false, }, ]; export const AddAttribute = ({ getData, item }: Props) => { const showToast = useToast(); const { closeModal } = useModalStore(); const [isGlobal, setIsGlobal] = useState(item ? item?.is_global : true); const schema = z.object({ name: zValidateString("نام "), type: zValidateAutoComplete("نوع مولفه"), product: isGlobal ? zValidateAutoCompleteOptional() : zValidateAutoComplete("محصول"), }); type FormValues = z.infer; const { control, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(schema), defaultValues: { name: item?.name || "", type: item?.type ? [item?.type] : [], product: item?.type.id ? [`${item?.type.id}`] : [], }, }); const mutation = useApiMutation({ api: `/product/web/api/v1/attribute/${item ? item?.id + "/" : ""}`, method: item ? "put" : "post", }); const onSubmit = async (data: FormValues) => { try { await mutation.mutateAsync({ name: data?.name, type: data?.type[0], is_global: isGlobal, ...(isGlobal ? { product: null } : { product: data?.product?.[0] }), }); showToast(getToastResponse(item, ""), "success"); getData(); closeModal(); } catch (error: any) { if (error?.status === 403) { showToast("این مولفه تکراری است!", "error"); } else { showToast( error?.response?.data?.message || "خطا در ثبت اطلاعات!", "error" ); } } }; return (
e.target.value === "true" ? setIsGlobal(true) : setIsGlobal(false) } /> {!isGlobal && ( ( <> { setValue("product", [r]); }} /> )} /> )} ( )} /> ( <> { setValue("type", [r]); }} /> )} />
); };