import { Discount } from "@medusajs/medusa" import { useAdminUpdateDiscount } from "medusa-react" import React, { useEffect } from "react" import { useForm } from "react-hook-form" import { useTranslation } from "react-i18next" import DiscountGeneralForm, { DiscountGeneralFormType, } from "../../../../components/forms/discount/discount-general-form" import MetadataForm, { getMetadataFormValues, getSubmittableMetadata, MetadataFormType, } from "../../../../components/forms/general/metadata-form" import Button from "../../../../components/fundamentals/button" import Modal from "../../../../components/molecules/modal" import useNotification from "../../../../hooks/use-notification" import { getErrorMessage } from "../../../../utils/error-messages" import { nestedForm } from "../../../../utils/nested-form" type EditGeneralProps = { discount: Discount open: boolean onClose: () => void } type GeneralForm = { general: DiscountGeneralFormType metadata: MetadataFormType } const EditGeneral: React.FC = ({ discount, open, onClose, }) => { const { t } = useTranslation() const { mutate, isLoading } = useAdminUpdateDiscount(discount.id) const notification = useNotification() const form = useForm({ defaultValues: getDefaultValues(discount), }) const { handleSubmit, reset } = form const onSubmit = handleSubmit((data) => { mutate( { regions: data.general.region_ids.map((r) => r.value), code: data.general.code, rule: { id: discount.rule.id, description: data.general.description, value: data.general.value, allocation: discount.rule.allocation, }, metadata: getSubmittableMetadata(data.metadata), }, { onSuccess: () => { notification( t("general-success", "Success"), t( "general-discount-updated-successfully", "Discount updated successfully" ), "success" ) onClose() }, onError: (error) => { notification( t("general-error", "Error"), getErrorMessage(error), "error" ) }, } ) }) useEffect(() => { if (open) { reset(getDefaultValues(discount)) } }, [discount, reset, open]) return (

{t("general-edit-general-information", "Edit general information")}

{t("general-details", "Details")}

{t("general-metadata", "Metadata")}

) } const getDefaultValues = (discount: Discount): GeneralForm | undefined => { return { general: { code: discount.code, description: discount.rule.description, region_ids: discount.regions.map((r) => ({ label: r.name, value: r.id, currency_code: r.currency_code, })), value: discount.rule.value, }, metadata: getMetadataFormValues(discount.metadata), } } export default EditGeneral