"use client" import { Radio, RadioGroup } from "@headlessui/react" import { setShippingMethod } from "@lib/data/cart" import { calculatePriceForShippingOption } from "@lib/data/fulfillment" import { convertToLocale } from "@lib/util/money" import { CheckCircle2 as CheckCircleSolid, Loader2 as Loader } from "lucide-react" import { HttpTypes } from "@medusajs/types" import ErrorMessage from "@modules/checkout/components/error-message" import Divider from "@modules/common/components/divider" import MedusaRadio from "@modules/common/components/radio" import { Button, clx, Heading, Text } from "@modules/common/components/ui" import { usePathname, useRouter, useSearchParams } from "next/navigation" import { useEffect, useState } from "react" const PICKUP_OPTION_ON = "__PICKUP_ON" const PICKUP_OPTION_OFF = "__PICKUP_OFF" type ShippingProps = { cart: HttpTypes.StoreCart availableShippingMethods: HttpTypes.StoreCartShippingOption[] | null } function formatAddress(address: HttpTypes.StoreCartAddress) { if (!address) { return "" } let ret = "" if (address.address_1) { ret += ` ${address.address_1}` } if (address.address_2) { ret += `, ${address.address_2}` } if (address.postal_code) { ret += `, ${address.postal_code} ${address.city}` } if (address.country_code) { ret += `, ${address.country_code.toUpperCase()}` } return ret } const Shipping: React.FC = ({ cart, availableShippingMethods, }) => { const [isLoading, setIsLoading] = useState(false) const [isLoadingPrices, setIsLoadingPrices] = useState(true) const [showPickupOptions, setShowPickupOptions] = useState(PICKUP_OPTION_OFF) const [calculatedPricesMap, setCalculatedPricesMap] = useState< Record >({}) const [error, setError] = useState(null) const [shippingMethodId, setShippingMethodId] = useState( cart.shipping_methods?.at(-1)?.shipping_option_id || null ) const searchParams = useSearchParams() const router = useRouter() const pathname = usePathname() const isOpen = searchParams.get("step") === "delivery" const _shippingMethods = availableShippingMethods?.filter( (sm) => (sm as unknown as { service_zone?: { fulfillment_set?: { type?: string; location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.type !== "pickup" ) const _pickupMethods = availableShippingMethods?.filter( (sm) => (sm as unknown as { service_zone?: { fulfillment_set?: { type?: string; location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.type === "pickup" ) const hasPickupOptions = !!_pickupMethods?.length useEffect(() => { setIsLoadingPrices(true) if (_shippingMethods?.length) { const promises = _shippingMethods .filter((sm) => sm.price_type === "calculated") .map((sm) => calculatePriceForShippingOption(sm.id, cart.id)) if (promises.length) { Promise.allSettled(promises).then((res) => { const pricesMap: Record = {} res .filter((r) => r.status === "fulfilled") .forEach((p) => { if (p.value?.id) { pricesMap[p.value.id] = p.value.amount ?? 0 } }) setCalculatedPricesMap(pricesMap) setIsLoadingPrices(false) }) } } if (_pickupMethods?.find((m) => m.id === shippingMethodId)) { setShowPickupOptions(PICKUP_OPTION_ON) } }, [availableShippingMethods]) const handleEdit = () => { router.push(pathname + "?step=delivery", { scroll: false }) } const handleSubmit = () => { router.push(pathname + "?step=payment", { scroll: false }) } const handleSetShippingMethod = async ( id: string, variant: "shipping" | "pickup" ) => { setError(null) if (variant === "pickup") { setShowPickupOptions(PICKUP_OPTION_ON) } else { setShowPickupOptions(PICKUP_OPTION_OFF) } let currentId: string | null = null setIsLoading(true) setShippingMethodId((prev) => { currentId = prev return id }) await setShippingMethod({ cartId: cart.id, shippingMethodId: id }) .catch((err) => { setShippingMethodId(currentId) setError(err.message) }) .finally(() => { setIsLoading(false) }) } useEffect(() => { setError(null) }, [isOpen]) return (
Delivery {!isOpen && (cart.shipping_methods?.length ?? 0) > 0 && ( )} {!isOpen && cart?.shipping_address && cart?.billing_address && cart?.email && ( )}
{isOpen ? ( <>
Shipping method How would you like you order delivered
{hasPickupOptions && ( { const id = _pickupMethods.find( (option) => !option.insufficient_inventory )?.id if (id) { handleSetShippingMethod(id, "pickup") } }} >
Pick up your order
-
)} { if (v) { return handleSetShippingMethod(v, "shipping") } }} > {_shippingMethods?.map((option) => { const isDisabled = option.price_type === "calculated" && !isLoadingPrices && typeof calculatedPricesMap[option.id] !== "number" return (
{option.name}
{option.price_type === "flat" ? ( convertToLocale({ amount: option.amount!, currency_code: cart?.currency_code, }) ) : calculatedPricesMap[option.id] ? ( convertToLocale({ amount: calculatedPricesMap[option.id], currency_code: cart?.currency_code, }) ) : isLoadingPrices ? ( ) : ( "-" )}
) })}
{showPickupOptions === PICKUP_OPTION_ON && (
Store Choose a store near you
{ if (v) { return handleSetShippingMethod(v, "pickup") } }} > {_pickupMethods?.map((option) => { return (
{option.name} {formatAddress( (option as unknown as { service_zone?: { fulfillment_set?: { location?: { address: HttpTypes.StoreCartAddress } } } }).service_zone?.fulfillment_set?.location ?.address as HttpTypes.StoreCartAddress )}
{convertToLocale({ amount: option.amount!, currency_code: cart?.currency_code, })}
) })}
)}
) : (
{cart && (cart.shipping_methods?.length ?? 0) > 0 && (
Method {cart.shipping_methods!.at(-1)!.name}{" "} {convertToLocale({ amount: cart.shipping_methods!.at(-1)!.amount!, currency_code: cart?.currency_code, })}
)}
)}
) } export default Shipping