"use client" import React, { useState } from "react" import { applyPromotions } from "@lib/data/cart" import { convertToLocale } from "@lib/util/money" import { HttpTypes } from "@medusajs/types" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Badge } from "@/components/ui/badge" import { Trash2, Tag } from "lucide-react" import ErrorMessage from "../error-message" import { SubmitButton } from "../submit-button" type DiscountCodeProps = { cart: HttpTypes.StoreCart } const DiscountCode: React.FC = ({ cart }) => { const [isOpen, setIsOpen] = useState(false) const [errorMessage, setErrorMessage] = 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) { setErrorMessage(e instanceof Error ? e.message : String(e)) } if (input) { input.value = "" } } return (
addPromotionCode(a)} className="w-full"> {isOpen && (
Primijeni
)}
{promotions.length > 0 && (
Primijenjeni popusti: {promotions.map((promotion) => (
{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 && ( )}
))}
)}
) } export default DiscountCode