import { MoneyAmount, ProductVariant } from "@medusajs/medusa" import React from "react" import { Control, Controller, useForm, useWatch } from "react-hook-form" import { useTranslation } from "react-i18next" import Checkbox, { CheckboxProps } from "../../atoms/checkbox" import Button from "../../fundamentals/button" import Modal from "../../molecules/modal" import RadioGroup from "../../organisms/radio-group" import PriceAmount from "./price-amount" const MODES = { APPLY_ALL: "all", SELECTED_ONLY: "selected", } export type PriceOverridesFormValues = { variants: string[] prices: MoneyAmount[] } type PriceOverridesType = { onClose: () => void prices: MoneyAmount[] variants: ProductVariant[] onSubmit: (values: PriceOverridesFormValues) => void defaultVariant?: ProductVariant isEdit?: boolean } // TODO: Clean up this components typing to avoid circular dependencies const PriceOverrides = ({ onClose, prices, variants, onSubmit, defaultVariant, isEdit = false, }: PriceOverridesType) => { const { t } = useTranslation() const [mode, setMode] = React.useState(MODES.SELECTED_ONLY) const { handleSubmit, control, reset, formState: { isSubmitting }, } = useForm({ defaultValues: { variants: [], prices: prices, }, }) const onClick = handleSubmit((values) => { if (mode === MODES.APPLY_ALL) { onSubmit({ ...values, variants: variants?.map((variant) => variant.id), }) } else { onSubmit({ ...values, // remove null or undefined variants: values.variants?.filter(Boolean), }) } }) // set default variant React.useEffect(() => { if (prices.length > 0 && variants?.length > 0) { const selectedVariantId = defaultVariant ? defaultVariant.id : prices[0]?.variant_id const selectedIndex = variants.findIndex( (variant) => variant.id === selectedVariantId ) const variantOptions = Array(variants.length).fill(null) variantOptions[selectedIndex] = selectedVariantId reset({ prices, variants: variantOptions, }) } }, [variants, prices, defaultVariant]) return ( <> {!isEdit && ( setMode(value)} className="flex items-center pt-2" > )} {mode === MODES.SELECTED_ONLY && !isEdit && (
{variants.map((variant, idx) => (
))}
)}
{t("price-overrides-prices", "Prices")}
{prices.map((price, idx) => ( { return ( { field.onChange({ ...field.value, amount, }) }} /> ) }} /> ))}
) } type ControlledCheckboxProps = { control: Control name: string id: string index: number } & CheckboxProps const ControlledCheckbox = ({ control, name, id, index, value, ...props }: ControlledCheckboxProps) => { const variants = useWatch({ control, name, }) return ( { return ( variant === value)} onChange={(e) => { // copy field value const valueCopy = [...(variants || [])] as any[] // update checkbox value valueCopy[index] = e.target.checked ? id : null // update field value field.onChange(valueCopy) }} /> ) }} /> ) } export default PriceOverrides