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
207 lines
9.2 KiB
TypeScript
207 lines
9.2 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState } from "react";
|
||
import { Button } from "@/app/components/ui/button";
|
||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||
import { Input } from "@/app/components/ui/input";
|
||
import { Label } from "@/app/components/ui/label";
|
||
import { Textarea } from "@/app/components/ui/textarea";
|
||
import { formatGiftCardCode, issueGiftCards } from "@/app/lib/services/adminGiftCards";
|
||
import { listSellableCountries } from "@/app/lib/services/sellableCountries";
|
||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
||
import { downloadXlsx, toXlsx } from "@/app/lib/xlsx";
|
||
import type { GiftCard, SellableCountry } from "@/app/lib/types";
|
||
import { formatDate } from "./giftCardLabels";
|
||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||
|
||
// Issue 1–50 gift cards (add-gift-card-core). The issue reference is fixed per dialog, so a retried submit
|
||
// returns the same batch instead of issuing twice. Full codes are shown once, here, with an Excel export.
|
||
|
||
const MAX_VALUE = 5000;
|
||
const MAX_QUANTITY = 50;
|
||
|
||
export function IssueGiftCardsDialog({ onClose, onIssued }: { onClose: () => void; onIssued: () => void }) {
|
||
const t = useT();
|
||
const [issueRef] = useState(() => `GCB-${Date.now().toString(36).toUpperCase()}-${Math.random().toString(36).slice(2, 6).toUpperCase()}`);
|
||
const [value, setValue] = useState("");
|
||
const [quantity, setQuantity] = useState("1");
|
||
const [recipientName, setRecipientName] = useState("");
|
||
const [recipientEmail, setRecipientEmail] = useState("");
|
||
const [message, setMessage] = useState("");
|
||
const [reason, setReason] = useState("");
|
||
const [errors, setErrors] = useState<string[]>([]);
|
||
const [serverError, setServerError] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [issued, setIssued] = useState<GiftCard[] | null>(null);
|
||
const [copied, setCopied] = useState<string | null>(null);
|
||
// The country picker shows only with 2+ sellable countries; a failed fetch is treated as one country.
|
||
const [countries, setCountries] = useState<SellableCountry[]>([]);
|
||
const [country, setCountry] = useState("MY");
|
||
useEffect(() => {
|
||
let cancelled = false;
|
||
Promise.resolve().then(listSellableCountries).then((c) => { if (!cancelled) setCountries(c ?? []); }).catch(() => {});
|
||
return () => { cancelled = true; };
|
||
}, []);
|
||
|
||
const qty = Number(quantity);
|
||
const single = qty === 1;
|
||
|
||
function validate(): string[] {
|
||
const found: string[] = [];
|
||
const amount = Number(value);
|
||
if (!value.trim() || !Number.isFinite(amount) || amount <= 0 || amount > MAX_VALUE || !/^\d+(\.\d{1,2})?$/.test(value.trim())) {
|
||
found.push("GcAmountRange");
|
||
}
|
||
if (!Number.isInteger(qty) || qty < 1 || qty > MAX_QUANTITY) found.push("GcQuantityRange");
|
||
if (single && recipientEmail.trim() && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(recipientEmail.trim())) {
|
||
found.push("GcRecipientEmailInvalid");
|
||
}
|
||
if (!reason.trim()) found.push("GcReasonRequired");
|
||
return found;
|
||
}
|
||
|
||
async function submit() {
|
||
setServerError(null);
|
||
const found = validate();
|
||
setErrors(found);
|
||
if (found.length > 0) return;
|
||
setBusy(true);
|
||
try {
|
||
const cards = await issueGiftCards({
|
||
issueRef,
|
||
value: Number(value),
|
||
quantity: qty,
|
||
...(single && recipientName.trim() ? { recipientName: recipientName.trim() } : {}),
|
||
...(single && recipientEmail.trim() ? { recipientEmail: recipientEmail.trim() } : {}),
|
||
...(message.trim() ? { message: message.trim() } : {}),
|
||
reason: reason.trim(),
|
||
...(countries.length > 1 ? { countryCode: country } : {}),
|
||
});
|
||
setIssued(cards);
|
||
onIssued();
|
||
} catch (err) {
|
||
setServerError(err instanceof Error ? err.message : "GcIssueFailed");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function exportBatch(cards: GiftCard[]) {
|
||
const rows = cards.map(c => ({ code: formatGiftCardCode(c.code ?? ""), amount: c.initialValue, expiresAt: formatDate(c.expiresAt) }));
|
||
downloadXlsx(
|
||
`gift-cards-${issueRef}.xlsx`,
|
||
await toXlsx(rows, [
|
||
{ key: "code", title: "Code" },
|
||
{ key: "amount", title: "Amount (RM)" },
|
||
{ key: "expiresAt", title: "Expires" },
|
||
], "Gift cards"),
|
||
);
|
||
}
|
||
|
||
async function copy(code: string) {
|
||
await navigator.clipboard?.writeText(code);
|
||
setCopied(code);
|
||
}
|
||
|
||
return (
|
||
<Dialog open onOpenChange={o => { if (!o) onClose(); }}>
|
||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
|
||
<DialogHeader>
|
||
<DialogTitle>{t("GcIssueTitle")}</DialogTitle>
|
||
</DialogHeader>
|
||
|
||
{issued ? (
|
||
<div className="flex flex-col gap-3 text-sm">
|
||
<p>{t(issued.length === 1 ? "GcIssuedOne" : "GcIssuedMany", { count: issued.length })}</p>
|
||
<ul className="flex max-h-72 flex-col gap-1 overflow-y-auto">
|
||
{issued.map(c => (
|
||
<li key={c.uuid} className="flex items-center justify-between gap-2 rounded-md bg-muted px-3 py-1.5">
|
||
<span className="tabular tracking-wider">{formatGiftCardCode(c.code ?? "")}</span>
|
||
<Button type="button" variant="ghost" size="sm" onClick={() => copy(formatGiftCardCode(c.code ?? ""))}>
|
||
{copied === formatGiftCardCode(c.code ?? "") ? t("GcCopied") : t("GcCopy")}
|
||
</Button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{issued.length === 1 && issued[0].recipientEmail && (
|
||
<p className="text-muted-foreground">
|
||
{issued[0].emailSentAt
|
||
? t("GcEmailedTo", { email: issued[0].recipientEmail })
|
||
: t("GcEmailNotSentYet", { email: issued[0].recipientEmail })}
|
||
</p>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<div className="flex flex-col gap-3 text-sm">
|
||
{countries.length > 1 && (
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-country">{t("Country")}</Label>
|
||
<Select value={country} onValueChange={setCountry}>
|
||
<SelectTrigger id="gc-country" aria-label={t("Country")}>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{countries.map((c) => <SelectItem key={c.code} value={c.code}>{c.name}</SelectItem>)}
|
||
</SelectContent>
|
||
</Select>
|
||
</div>
|
||
)}
|
||
<div className="grid gap-3 sm:grid-cols-2">
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-value">{t("GcAmountRm")}</Label>
|
||
<Input id="gc-value" inputMode="decimal" value={value} onChange={e => setValue(e.target.value)} />
|
||
</div>
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-quantity">{t("Quantity")}</Label>
|
||
<Input id="gc-quantity" type="number" min={1} max={MAX_QUANTITY} value={quantity} onChange={e => setQuantity(e.target.value)} />
|
||
</div>
|
||
</div>
|
||
{single ? (
|
||
<div className="grid gap-3 sm:grid-cols-2">
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-recipient-name">{t("GcRecipientNameOpt")}</Label>
|
||
<Input id="gc-recipient-name" value={recipientName} maxLength={100} onChange={e => setRecipientName(e.target.value)} />
|
||
</div>
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-recipient-email">{t("GcRecipientEmailOpt")}</Label>
|
||
<Input id="gc-recipient-email" type="email" value={recipientEmail} maxLength={150} onChange={e => setRecipientEmail(e.target.value)} />
|
||
</div>
|
||
</div>
|
||
) : (
|
||
<p className="text-muted-foreground">{t("GcBatchHint")}</p>
|
||
)}
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-message">{t("GcMessageOpt")}</Label>
|
||
<Textarea id="gc-message" value={message} maxLength={500} onChange={e => setMessage(e.target.value)} />
|
||
</div>
|
||
<div className="flex flex-col gap-1">
|
||
<Label htmlFor="gc-reason">{t("GcReasonInternal")}</Label>
|
||
<Input id="gc-reason" value={reason} maxLength={255} onChange={e => setReason(e.target.value)} />
|
||
</div>
|
||
{errors.length > 0 && (
|
||
<ul className="flex flex-col gap-1 text-destructive">
|
||
{errors.map(e => <li key={e}>{t(e)}</li>)}
|
||
</ul>
|
||
)}
|
||
{serverError && <p role="alert" className="text-destructive">{t(serverError)}</p>}
|
||
</div>
|
||
)}
|
||
|
||
<DialogFooter>
|
||
{issued ? (
|
||
<>
|
||
<Button variant="outline" onClick={() => exportBatch(issued)}>{t("GcExportExcel")}</Button>
|
||
<Button onClick={onClose}>{t("GcDone")}</Button>
|
||
</>
|
||
) : (
|
||
<>
|
||
<Button variant="outline" disabled={busy} onClick={onClose}>{t("Cancel")}</Button>
|
||
<Button disabled={busy} onClick={submit}>{busy ? t("GcIssuing") : t("GcIssue")}</Button>
|
||
</>
|
||
)}
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|