Files
co-lite/solvway-admin-portal/app/gift-cards/GiftCardDrawer.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

200 lines
9.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { DatePicker } from "@/app/components/ui/date-picker";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { Label } from "@/app/components/ui/label";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/app/components/ui/sheet";
import { Skeleton } from "@/app/components/ui/skeleton";
import { Textarea } from "@/app/components/ui/textarea";
import { formatPoints } from "@/app/lib/format";
import {
deactivateGiftCard,
extendGiftCard,
formatGiftCardCode,
getGiftCard,
resendGiftCardEmail,
} from "@/app/lib/services/adminGiftCards";
import type { GiftCardDetail } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { SOURCE_LABEL, STATUS_LABEL, STATUS_TONE, TRXN_LABEL, formatDate, nextDay } from "./giftCardLabels";
// One gift card (add-gift-card-core): full code, details, ledger, and the admin actions. A deactivated card is
// read-only.
export function GiftCardDrawer({ uuid, onClose, onChanged }: { uuid: string; onClose: () => void; onChanged: () => void }) {
const t = useT();
const [detail, setDetail] = useState<GiftCardDetail | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [notice, setNotice] = useState<{ code: string; params?: Record<string, string> } | null>(null);
const [busy, setBusy] = useState(false);
const [newExpiry, setNewExpiry] = useState("");
const [deactivating, setDeactivating] = useState(false);
const [reason, setReason] = useState("");
const [reasonError, setReasonError] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
let cancelled = false;
getGiftCard(uuid)
.then(d => { if (!cancelled) setDetail(d); })
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof Error ? err.message : "GcLoadFailed"); });
return () => { cancelled = true; };
}, [uuid, reloadKey]);
const run = useCallback(async (action: () => Promise<unknown>, code: string, params?: Record<string, string>) => {
setActionError(null);
setNotice(null);
setBusy(true);
try {
await action();
setNotice({ code, params });
setReloadKey(k => k + 1);
onChanged();
} catch (err) {
setActionError(err instanceof Error ? err.message : "GcActionFailed");
} finally {
setBusy(false);
}
}, [onChanged]);
const card = detail?.card;
const editable = card && card.status !== "DEACTIVATED";
return (
<Sheet open onOpenChange={open => { if (!open) onClose(); }}>
<SheetContent className="overflow-y-auto">
<SheetHeader>
<SheetTitle className="flex items-center gap-2">
{card ? t("GcDrawerTitleCard", { last4: card.codeLast4 }) : t("GcDrawerTitle")}
{card && <Badge variant={STATUS_TONE[card.status]}>{STATUS_LABEL[card.status] ? t(STATUS_LABEL[card.status]) : card.status}</Badge>}
</SheetTitle>
</SheetHeader>
{loadError && <p role="alert" className="text-sm text-destructive">{t(loadError)}</p>}
{!detail && !loadError && <Skeleton className="h-64 w-full" />}
{card && detail && (
<div className="flex flex-col gap-5 px-4 pb-6 text-sm">
<p className="rounded-md bg-muted px-3 py-2 text-base tabular tracking-wider" data-testid="gift-card-full-code">
{formatGiftCardCode(card.code ?? "")}
</p>
<dl className="grid grid-cols-[8rem_1fr] gap-x-3 gap-y-1">
<dt className="text-muted-foreground">{t("GcBalance")}</dt>
<dd className="tabular">{t("GcBalanceOf", { balance: formatPoints(card.balance), initial: formatPoints(card.initialValue) })}</dd>
<dt className="text-muted-foreground">{t("GcExpires")}</dt>
<dd>{formatDate(card.expiresAt)}</dd>
<dt className="text-muted-foreground">{t("GcSource")}</dt>
<dd>{SOURCE_LABEL[card.source] ? t(SOURCE_LABEL[card.source]) : card.source}</dd>
<dt className="text-muted-foreground">{t("GcRecipient")}</dt>
<dd>{[card.recipientName, card.recipientEmail].filter(Boolean).join(" · ") || "—"}</dd>
{card.message && (<><dt className="text-muted-foreground">{t("GcMessage")}</dt><dd>{card.message}</dd></>)}
<dt className="text-muted-foreground">{t("GcIssued")}</dt>
<dd>{card.issuedBy} · {formatDate(card.createDate)}</dd>
{card.reason && (<><dt className="text-muted-foreground">{t("GcReason")}</dt><dd>{card.reason}</dd></>)}
{card.recipientEmail && (
<>
<dt className="text-muted-foreground">{t("Email")}</dt>
<dd>{card.emailSentAt ? t("GcEmailSent", { date: formatDate(card.emailSentAt) }) : t("GcEmailNotSent")}</dd>
</>
)}
</dl>
{editable && (
<section className="flex flex-col gap-3 rounded-md border p-3">
<div className="flex flex-wrap items-end gap-2">
<div className="flex flex-col gap-1">
<Label htmlFor="gc-new-expiry">{t("GcNewExpiry")}</Label>
<DatePicker id="gc-new-expiry" value={newExpiry} onChange={setNewExpiry} min={nextDay(card.expiresAt)} />
</div>
<Button
variant="outline"
size="sm"
disabled={busy || !newExpiry}
onClick={() => run(() => extendGiftCard(uuid, newExpiry), "GcExpiryExtendedTo", { date: formatDate(newExpiry) })}
>
{t("GcExtendExpiry")}
</Button>
</div>
<div className="flex flex-wrap gap-2">
{card.recipientEmail && (
<Button variant="outline" size="sm" disabled={busy}
onClick={() => run(() => resendGiftCardEmail(uuid), "GcEmailQueued", { email: card.recipientEmail! })}>
{t("GcResendEmail")}
</Button>
)}
<Button variant="destructive" size="sm" disabled={busy} onClick={() => { setReason(""); setReasonError(false); setDeactivating(true); }}>
{t("CatDeactivate")}
</Button>
</div>
</section>
)}
{notice && <p className="text-positive">{t(notice.code, notice.params)}</p>}
{actionError && <p role="alert" className="text-destructive">{t(actionError)}</p>}
<section>
<h3 className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">{t("GcHistory")}</h3>
<table className="w-full text-left">
<thead className="text-muted-foreground">
<tr>
<th className="py-1 font-normal">{t("Date")}</th>
<th className="py-1 font-normal">{t("Type")}</th>
<th className="py-1 text-right font-normal">{t("GcAmount")}</th>
<th className="py-1 text-right font-normal">{t("GcBalance")}</th>
<th className="py-1 font-normal">{t("GcBy")}</th>
</tr>
</thead>
<tbody>
{detail.trxns.map(tx => (
<tr key={tx.id} className="border-t align-top">
<td className="py-1 tabular">{formatDate(tx.createDate)}</td>
<td className="py-1">
{TRXN_LABEL[tx.trxnType] ? t(TRXN_LABEL[tx.trxnType]) : tx.trxnType}
{tx.remark && <span className="block text-muted-foreground">{tx.remark}</span>}
</td>
<td className="py-1 text-right tabular">
{tx.amountIn > 0 ? `+${formatPoints(tx.amountIn)}` : tx.amountOut > 0 ? `−${formatPoints(tx.amountOut)}` : "—"}
</td>
<td className="py-1 text-right tabular">{formatPoints(tx.balanceAfter)}</td>
<td className="py-1">{tx.doneBy}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
)}
<Dialog open={deactivating} onOpenChange={setDeactivating}>
<DialogContent>
<DialogHeader><DialogTitle>{t("GcDeactivateTitle")}</DialogTitle></DialogHeader>
<p className="text-sm">{t("GcDeactivateBody")}</p>
<div className="flex flex-col gap-1">
<Label htmlFor="gc-deactivate-reason">{t("GcReason")}</Label>
<Textarea id="gc-deactivate-reason" value={reason} maxLength={255} onChange={e => setReason(e.target.value)} />
{reasonError && <p className="text-sm text-destructive">{t("GcReasonRequired")}</p>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDeactivating(false)}>{t("Cancel")}</Button>
<Button
variant="destructive"
disabled={busy}
onClick={() => {
if (!reason.trim()) { setReasonError(true); return; }
setDeactivating(false);
void run(() => deactivateGiftCard(uuid, reason.trim()), "GcDeactivated");
}}
>
{t("GcDeactivateCard")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</SheetContent>
</Sheet>
);
}