Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
290 lines
10 KiB
TypeScript
290 lines
10 KiB
TypeScript
"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<PosGiftCardSaleResult>;
|
|
}
|
|
|
|
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<number | null>(null);
|
|
const [selectedTender, setSelectedTender] = useState<string | null>(null);
|
|
const [reference, setReference] = useState("");
|
|
const [recipientName, setRecipientName] = useState("");
|
|
const [recipientEmail, setRecipientEmail] = useState("");
|
|
const [message, setMessage] = useState("");
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [result, setResult] = useState<PosGiftCardSaleResult | null>(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 = `
|
|
<html>
|
|
<head><title>${tx("PosGcSlipTitle")}</title></head>
|
|
<body style="font-family:sans-serif;padding:2rem;">
|
|
<h2>${tx("PosGcSlipTitle")}</h2>
|
|
<p><strong>${tx("PosGcSlipCode")}</strong> ${formatted}</p>
|
|
<p><strong>${tx("PosGcSlipAmount")}</strong> ${money(result.amount)}</p>
|
|
<p><strong>${tx("PosGcSlipExpires")}</strong> ${expiry(result.expiresAt)}</p>
|
|
<p>${tx("PosGcSlipCheckBalance", { url: balanceUrl })}</p>
|
|
</body>
|
|
</html>
|
|
`;
|
|
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 (
|
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
|
<DialogContent className="sm:max-w-lg">
|
|
<DialogHeader>
|
|
<DialogTitle>{t("PosSellGiftCard")}</DialogTitle>
|
|
<DialogDescription>{t("PosSellGiftCardDesc")}</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{amountsError && !result && (
|
|
<div
|
|
role="alert"
|
|
className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
|
>
|
|
{t(amountsError)}
|
|
</div>
|
|
)}
|
|
|
|
{error && (
|
|
<div
|
|
role="alert"
|
|
className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive whitespace-pre-line"
|
|
>
|
|
{error.split("\n").map((c) => t(c)).join("\n")}
|
|
</div>
|
|
)}
|
|
|
|
{!result && (
|
|
<>
|
|
{/* Amount selection */}
|
|
<div>
|
|
<label className="text-sm font-medium mb-2 block">{t("PosAmount")}</label>
|
|
<div className="grid gap-2 sm:grid-cols-2">
|
|
{activeAmounts.map((a) => {
|
|
const checked = selectedAmount === a.amount;
|
|
return (
|
|
<button
|
|
key={a.id}
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={checked}
|
|
onClick={() => setSelectedAmount(a.amount)}
|
|
className={cn(CARD, checked && ACTIVE)}
|
|
>
|
|
<span className="font-semibold">{money(a.amount)}</span>
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Tender selection */}
|
|
<div>
|
|
<label className="text-sm font-medium mb-2 block">{t("PosPaymentMethod")}</label>
|
|
<div className="grid gap-2 sm:grid-cols-2">
|
|
{tenders
|
|
.filter((tender) => !tender.wallet)
|
|
.map((tender) => {
|
|
const checked = selectedTender === tender.id;
|
|
return (
|
|
<button
|
|
key={tender.id}
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={checked}
|
|
onClick={() => setSelectedTender(tender.id)}
|
|
className={cn(CARD, checked && ACTIVE)}
|
|
>
|
|
<span className="font-semibold">{tender.label}</span>
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Optional fields */}
|
|
<div className="space-y-2">
|
|
<Input
|
|
type="text"
|
|
aria-label={t("PosReference")}
|
|
placeholder={t("PosReferenceOptional")}
|
|
value={reference}
|
|
onChange={(e) => setReference(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="text"
|
|
aria-label={t("PosRecipientName")}
|
|
placeholder={t("GcRecipientNameOpt")}
|
|
value={recipientName}
|
|
onChange={(e) => setRecipientName(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="email"
|
|
aria-label={t("PosRecipientEmail")}
|
|
placeholder={t("GcRecipientEmailOpt")}
|
|
value={recipientEmail}
|
|
onChange={(e) => setRecipientEmail(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="text"
|
|
aria-label={t("PosMessage")}
|
|
placeholder={t("PosMessageOptional")}
|
|
maxLength={200}
|
|
value={message}
|
|
onChange={(e) => setMessage(e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<Button onClick={handleSell} disabled={selling} className="mt-2">
|
|
{selling ? t("PosSelling") : t("PosSell")}
|
|
</Button>
|
|
</>
|
|
)}
|
|
|
|
{/* Success panel */}
|
|
{result && (
|
|
<div className="rounded-lg border bg-muted/40 p-4 space-y-2">
|
|
<div className="font-mono tracking-wider">{formatGiftCardCode(result.code)}</div>
|
|
<div className="text-sm">{money(result.amount)}</div>
|
|
<div className="text-sm">{t("PosGcExpires", { date: expiry(result.expiresAt) })}</div>
|
|
<div className="flex gap-2 mt-2">
|
|
<Button variant="outline" size="sm" onClick={handlePrintSlip}>
|
|
{t("PosPrintSlip")}
|
|
</Button>
|
|
<Button variant="outline" size="sm" onClick={handleDone}>
|
|
{t("GcDone")}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|