"use client"; import { useState } from "react"; import { formatGiftCardCode } from "@/app/lib/services/adminGiftCards"; import { useStorefrontOrigin } from "@/app/lib/storefront"; import { useMoney } from "@/app/pos/currency"; import type { GiftCardAmount, PosGiftCardSaleBody, PosGiftCardSaleResult, PosTender } from "@/app/lib/types"; import { cn } from "@/app/lib/utils"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { MessageParams } from "@/app/lib/i18n/t"; // add-gift-card-counter: sell a gift card at the POS — pick amount, payment method, // optionally fill recipient details, then print a slip with the code. interface SellGiftCardDialogProps { open: boolean; onOpenChange: (open: boolean) => void; tenders: PosTender[]; amounts: GiftCardAmount[]; /** Shown instead of an empty amount list when it could not be loaded. */ amountsError?: string | null; sell: (body: PosGiftCardSaleBody) => Promise; } const CARD = "flex items-center gap-3 rounded-lg border bg-background p-3 text-left transition-colors hover:border-primary/60 disabled:cursor-not-allowed disabled:opacity-50"; const ACTIVE = "border-primary ring-2 ring-primary/30"; export function SellGiftCardDialog({ open, onOpenChange, tenders, amounts, amountsError, sell, }: SellGiftCardDialogProps) { const money = useMoney(); const storefrontOrigin = useStorefrontOrigin(); const t = useT(); // One client key per sale: kept across retries so a retry after an error issues at most one card, // replaced when the dialog closes. const [clientKey, setClientKey] = useState(() => crypto.randomUUID()); const activeAmounts = amounts.filter((a) => a.active === "Y"); const [selectedAmount, setSelectedAmount] = useState(null); const [selectedTender, setSelectedTender] = useState(null); const [reference, setReference] = useState(""); const [recipientName, setRecipientName] = useState(""); const [recipientEmail, setRecipientEmail] = useState(""); const [message, setMessage] = useState(""); const [error, setError] = useState(null); const [result, setResult] = useState(null); const [selling, setSelling] = useState(false); function resetState() { setClientKey(crypto.randomUUID()); setSelectedAmount(null); setSelectedTender(null); setReference(""); setRecipientName(""); setRecipientEmail(""); setMessage(""); setError(null); setResult(null); } async function handleSell() { // Validate all at once const errors: string[] = []; if (selectedAmount == null) errors.push("PosGcChooseAmount"); if (selectedTender == null) errors.push("PosGcChoosePayment"); if (recipientEmail.trim()) { const emailRegex = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; if (!emailRegex.test(recipientEmail.trim())) { errors.push("PosGcValidEmail"); } } if (errors.length > 0) { setError(errors.join("\n")); return; } const body: PosGiftCardSaleBody = { clientKey, amount: selectedAmount!, paymentMethodId: selectedTender!, }; if (reference.trim()) body.reference = reference.trim(); if (recipientName.trim()) body.recipientName = recipientName.trim(); if (recipientEmail.trim()) body.recipientEmail = recipientEmail.trim(); if (message.trim()) body.message = message.trim(); setSelling(true); setError(null); try { const saleResult = await sell(body); setResult(saleResult); } catch (err) { setError(err instanceof Error && err.message ? err.message : "PosGcSellFailed"); } finally { setSelling(false); } } function handlePrintSlip() { if (!result) return; const formatted = formatGiftCardCode(result.code); const balanceUrl = `${storefrontOrigin}/gift-cards/balance`; // Catalog text is admin-editable: escape it before it goes into the slip's HTML. const tx = (code: string, params?: MessageParams) => t(code, params).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); const html = ` ${tx("PosGcSlipTitle")}

${tx("PosGcSlipTitle")}

${tx("PosGcSlipCode")} ${formatted}

${tx("PosGcSlipAmount")} ${money(result.amount)}

${tx("PosGcSlipExpires")} ${expiry(result.expiresAt)}

${tx("PosGcSlipCheckBalance", { url: balanceUrl })}

`; const win = window.open("", "_blank", "width=400,height=500"); if (!win) { setError("PosGcSlipBlocked"); return; } win.document.write(html); win.document.close(); win.focus(); win.print(); win.close(); } // Closing the dialog any way (Done, X, Escape) forgets the code: it is shown once. function handleOpenChange(next: boolean) { if (!next) resetState(); onOpenChange(next); } function handleDone() { handleOpenChange(false); } const expiry = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString("en-MY", { day: "numeric", month: "short", year: "numeric", }); return ( {t("PosSellGiftCard")} {t("PosSellGiftCardDesc")} {amountsError && !result && (
{t(amountsError)}
)} {error && (
{error.split("\n").map((c) => t(c)).join("\n")}
)} {!result && ( <> {/* Amount selection */}
{activeAmounts.map((a) => { const checked = selectedAmount === a.amount; return ( ); })}
{/* Tender selection */}
{tenders .filter((tender) => !tender.wallet) .map((tender) => { const checked = selectedTender === tender.id; return ( ); })}
{/* Optional fields */}
setReference(e.target.value)} /> setRecipientName(e.target.value)} /> setRecipientEmail(e.target.value)} /> setMessage(e.target.value)} />
)} {/* Success panel */} {result && (
{formatGiftCardCode(result.code)}
{money(result.amount)}
{t("PosGcExpires", { date: expiry(result.expiresAt) })}
)}
); }