import { Discount } from "@medusajs/medusa" import { useAdminRegions } from "medusa-react" import React, { useEffect, useMemo, useState } from "react" import { Controller, useWatch } from "react-hook-form" import { useTranslation } from "react-i18next" import Checkbox from "../../../../../components/atoms/checkbox" import IconTooltip from "../../../../../components/molecules/icon-tooltip" import InputField from "../../../../../components/molecules/input" import { NextSelect } from "../../../../../components/molecules/select/next-select" import TextArea from "../../../../../components/molecules/textarea" import CurrencyInput from "../../../../../components/organisms/currency-input" import { useDiscountForm } from "../form/discount-form-context" type GeneralProps = { discount?: Discount } const General: React.FC = ({ discount }) => { const initialCurrency = discount?.regions?.[0].currency_code || undefined const { t } = useTranslation() const [fixedRegionCurrency, setFixedRegionCurrency] = useState< string | undefined >(initialCurrency) const { regions: opts, isLoading } = useAdminRegions() const { register, control, type } = useDiscountForm() const regions = useWatch({ control, name: "regions", }) useEffect(() => { if (type === "fixed" && regions) { let id: string if (Array.isArray(regions) && regions.length) { id = regions[0].value } else { id = (regions as unknown as { label: string; value: string }).value // if you change from fixed to percentage, unselect and select a region, and then change back to fixed it is possible to make useForm set regions to an object instead of an array } const reg = opts?.find((r) => r.id === id) if (reg) { setFixedRegionCurrency(reg.currency_code) } } }, [type, opts, regions]) const regionOptions = useMemo(() => { return opts?.map((r) => ({ value: r.id, label: r.name })) || [] }, [opts]) return (
{!isLoading && ( <> Array.isArray(value) ? value.length > 0 : !!value, }} render={({ field: { onChange, value } }) => { return ( { onChange(type === "fixed" ? [value] : value) }} label={t( "sections-choose-valid-regions", "Choose valid regions" )} isMulti={type !== "fixed"} selectAll={type !== "fixed"} isSearchable required options={regionOptions} /> ) }} />
{type !== "free_shipping" && ( <> {type === "fixed" ? (
{ return ( ) }} />
) : (
)} )}
{t( "sections-customer-invoice-code", "The code your customers will enter during checkout. This will appear on your customer\u2019s invoice." )} {t( "sections-uppercase-letters-and-numbers-only", "Uppercase letters and numbers only." )}