"use client" import { Badge, Heading, Input, Label, Text } from "@medusajs/ui" import React from "react" import { applyPromotions } from "@lib/data/cart" import { convertToLocale } from "@lib/util/money" import { HttpTypes } from "@medusajs/types" import Trash from "@modules/common/icons/trash" import ErrorMessage from "../error-message" import { SubmitButton } from "../submit-button" type DiscountCodeProps = { cart: HttpTypes.StoreCart & { promotions: HttpTypes.StorePromotion[] } } const DiscountCode: React.FC = ({ cart }) => { const [isOpen, setIsOpen] = React.useState(false) const [errorMessage, setErrorMessage] = React.useState("") const { promotions = [] } = cart const removePromotionCode = async (code: string) => { const validPromotions = promotions.filter( (promotion) => promotion.code !== code ) await applyPromotions( validPromotions.filter((p) => p.code !== undefined).map((p) => p.code!) ) } const addPromotionCode = async (formData: FormData) => { setErrorMessage("") const code = formData.get("code") if (!code) { return } const input = document.getElementById("promotion-input") as HTMLInputElement const codes = promotions .filter((p) => p.code !== undefined) .map((p) => p.code!) codes.push(code.toString()) try { await applyPromotions(codes) } catch (e: any) { setErrorMessage(e.message) } if (input) { input.value = "" } } return (
addPromotionCode(a)} className="w-full mb-5"> {isOpen && ( <>
Apply
)} {promotions.length > 0 && (
Promotion(s) applied: {promotions.map((promotion) => { return (
{promotion.code} {" "} ( {promotion.application_method?.value !== undefined && promotion.application_method.currency_code !== undefined && ( <> {promotion.application_method.type === "percentage" ? `${promotion.application_method.value}%` : convertToLocale({ amount: +promotion.application_method.value, currency_code: promotion.application_method .currency_code, })} )} ) {/* {promotion.is_automatic && ( )} */} {!promotion.is_automatic && ( )}
) })}
)}
) } export default DiscountCode