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
331 lines
16 KiB
TypeScript
331 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import Link from "next/link";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
|
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 { ApiError } from "@/app/lib/clientApi";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { approveRefund, getRefund, rejectRefund, retryRefundEmail, adminRefundPhotoUrl } from "@/app/lib/services/adminRefunds";
|
|
import type { AdminRefundDetail } from "@/app/lib/types";
|
|
import { formatDateTime } from "@/app/lib/format";
|
|
import { paymentTypeLabel } from "@/app/lib/paymentTypes";
|
|
import { channelLabel, effectLabel, money, payoutLabel, reasonLabel, statusLabel, statusVariant } from "./refundLabels";
|
|
import { lineName } from "@/app/lib/lineName";
|
|
|
|
type Confirming = "approve" | "reject" | null;
|
|
|
|
/**
|
|
* Slide-over for one refund request (add-refund-requests, design §8): what was asked, what approval
|
|
* will do, the decision dialogs, and — once decided — the read-only reversal record. Every action
|
|
* is a POST; after any action (success, failure or conflict) the request is re-read, because the
|
|
* server is the only authority on how far an approval got.
|
|
*/
|
|
export function RefundDrawer({
|
|
uuid,
|
|
onClose,
|
|
onChanged,
|
|
}: {
|
|
uuid: string | null;
|
|
onClose: () => void;
|
|
onChanged: () => void;
|
|
}) {
|
|
const t = useT();
|
|
const [detail, setDetail] = useState<AdminRefundDetail | null>(null);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [confirming, setConfirming] = useState<Confirming>(null);
|
|
const [note, setNote] = useState("");
|
|
const [reason, setReason] = useState("");
|
|
const [reasonError, setReasonError] = useState(false);
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
|
|
useEffect(() => {
|
|
if (!uuid) return;
|
|
let cancelled = false;
|
|
getRefund(uuid)
|
|
.then(d => {
|
|
if (!cancelled) {
|
|
setDetail(d);
|
|
setLoadError(null);
|
|
}
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setLoadError(err instanceof Error ? err.message : "Couldn't load this refund request.");
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
// `t` is deliberately not a dependency: useT() returns a new function every render.
|
|
}, [uuid, reloadKey]);
|
|
|
|
const closeConfirm = () => {
|
|
setConfirming(null);
|
|
setNote("");
|
|
setReason("");
|
|
setReasonError(false);
|
|
};
|
|
|
|
const run = useCallback(
|
|
async (action: () => Promise<unknown>) => {
|
|
setBusy(true);
|
|
setActionError(null);
|
|
try {
|
|
await action();
|
|
closeConfirm();
|
|
onChanged();
|
|
} catch (err: unknown) {
|
|
closeConfirm();
|
|
setActionError(err instanceof ApiError || err instanceof Error ? err.message : t("RefundQueueActionFailed"));
|
|
if (err instanceof ApiError && err.status === 409) onChanged();
|
|
} finally {
|
|
setBusy(false);
|
|
setReloadKey(k => k + 1);
|
|
}
|
|
},
|
|
[onChanged, t],
|
|
);
|
|
|
|
const onConfirmReject = () => {
|
|
if (!uuid) return;
|
|
if (!reason.trim()) {
|
|
setReasonError(true);
|
|
return;
|
|
}
|
|
void run(() => rejectRefund(uuid, reason.trim()));
|
|
};
|
|
|
|
const r = detail?.request;
|
|
const giftCard = detail?.request.giftCardRefunded ?? 0;
|
|
const payout = (detail?.request.refundAmount ?? 0) - giftCard;
|
|
const hasGiftCardTender = detail?.tenders.some(x => x.paymentType === "GC" || x.paymentType === "DWG");
|
|
const undecided = r?.status === "P" || r?.status === "I";
|
|
|
|
return (
|
|
<Sheet open={uuid !== null} onOpenChange={open => { if (!open) onClose(); }}>
|
|
<SheetContent>
|
|
<SheetHeader>
|
|
<SheetTitle className="flex items-center gap-2">
|
|
{r?.documentNo ?? t("RefundQueueTitle")}
|
|
{r && <Badge variant={statusVariant(r.status)}>{statusLabel(t, r.status)}</Badge>}
|
|
{r?.source === "ADMIN" && <Badge variant="neutral">{t("RefundQueueSourceAdmin")}</Badge>}
|
|
</SheetTitle>
|
|
</SheetHeader>
|
|
|
|
{loadError && <p role="alert" className="text-sm text-destructive">{loadError}</p>}
|
|
{!detail && !loadError && <Skeleton className="h-64 w-full" />}
|
|
|
|
{detail && r && (
|
|
<div className="flex flex-col gap-5 text-sm">
|
|
{r.source === "ADMIN" && (
|
|
<p className="text-muted-foreground">{t("RefundQueueRaisedBy", { admin: r.submittedBy ?? "—" })}</p>
|
|
)}
|
|
<dl className="grid grid-cols-[8rem_1fr] gap-x-3 gap-y-1">
|
|
<dt className="text-muted-foreground">{t("RefundQueueMember")}</dt>
|
|
<dd>{detail.buyerName ?? "—"} · {r.buyerCode || t("RefundQueueWalkIn")}</dd>
|
|
<dt className="text-muted-foreground">{t("RefundQueueInvoice")}</dt>
|
|
<dd>
|
|
<Link href={`/orders/web/${r.orderUuid}`} className="text-primary underline-offset-4 hover:underline">
|
|
{r.orderDocumentNo}
|
|
</Link>
|
|
{" · "}{formatDateTime(detail.orderDate)}
|
|
</dd>
|
|
<dt className="text-muted-foreground">{t("RefundQueueSubmitted")}</dt>
|
|
<dd>{formatDateTime(r.createDate)}</dd>
|
|
<dt className="text-muted-foreground">{t("RefundQueueReason")}</dt>
|
|
<dd>{reasonLabel(t, r.reasonCode)}{r.remark ? ` — “${r.remark}”` : ""}</dd>
|
|
<dt className="text-muted-foreground">{t("RefundQueuePayout")}</dt>
|
|
<dd>{payoutLabel(t, r, hasGiftCardTender)}</dd>
|
|
{r.windowOverrideReason && (
|
|
<>
|
|
<dt className="text-muted-foreground">{t("RefundQueueOverride")}</dt>
|
|
<dd>{r.windowOverrideReason}</dd>
|
|
</>
|
|
)}
|
|
</dl>
|
|
|
|
{(r.photoRefs ?? []).length > 0 && (
|
|
<div role="group" aria-label={t("RefundQueuePhotos")} className="flex flex-wrap gap-2">
|
|
{(r.photoRefs ?? []).map((_, i) => (
|
|
<a key={i} href={adminRefundPhotoUrl(r.uuid, i)} target="_blank" rel="noreferrer">
|
|
{/* eslint-disable-next-line @next/next/no-img-element -- streamed private image, not optimisable */}
|
|
<img src={adminRefundPhotoUrl(r.uuid, i)} alt={t("RefundQueuePhotoAlt", { n: i + 1 })} className="h-24 w-24 rounded object-cover" />
|
|
</a>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
<section>
|
|
<h3 className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">{t("RefundQueueLines")}</h3>
|
|
<table className="w-full text-left">
|
|
<thead className="text-muted-foreground">
|
|
<tr>
|
|
<th className="py-1 font-normal">{t("RefundQueueProduct")}</th>
|
|
<th className="py-1 text-right font-normal">{t("RefundQueueQty")}</th>
|
|
<th className="py-1 text-right font-normal">{t("RefundQueueNetUnit")}</th>
|
|
<th className="py-1 text-right font-normal">{t("RefundQueueLineRefund")}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{r.lines.map(l => (
|
|
<tr key={l.orderDetailsId} className="border-t">
|
|
<td className="py-1">{lineName(t, l.productName, l.variantLabel)}</td>
|
|
<td className="py-1 text-right tabular">{l.qty}</td>
|
|
<td className="py-1 text-right tabular">{money(l.netUnitPrice)}</td>
|
|
<td className="py-1 text-right tabular">{money(l.amount)}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</section>
|
|
|
|
{undecided && (
|
|
<section className="flex flex-col gap-2 rounded-md bg-muted p-3">
|
|
<h3 className="text-xs uppercase tracking-wide text-muted-foreground">{t("RefundQueueOnApproval")}</h3>
|
|
<p>
|
|
{r.payoutMethod === "MANUAL"
|
|
? hasGiftCardTender
|
|
? t("RefundQueueReturnManuallyAfterGiftCard", { amount: money(r.refundAmount), channel: channelLabel(t, r.payoutChannel) })
|
|
: t("RefundQueueReturnManually", { amount: money(r.refundAmount), channel: channelLabel(t, r.payoutChannel) })
|
|
: hasGiftCardTender
|
|
? t("RefundQueueCreditAcornsAfterGiftCard", { amount: money(r.refundAmount) })
|
|
: t("RefundQueueCreditAcorns", { amount: money(r.refundAmount) })}
|
|
</p>
|
|
<p className="text-muted-foreground">
|
|
{t("RefundQueuePaidWith", {
|
|
tenders: detail.tenders.map(x => `${x.paymentType ? paymentTypeLabel(x.paymentType, t) : "—"} ${money(x.amount)}`).join(" · ") || "—",
|
|
shipping: money(detail.shippingCost),
|
|
})}
|
|
</p>
|
|
{hasGiftCardTender && <p>{t("RefundQueueGiftCardFirst")}</p>}
|
|
{detail.stockEffects.length === 0 ? (
|
|
<p className="text-destructive">{t("RefundQueueNoDeliveryOrder")}</p>
|
|
) : (
|
|
<ul className="list-disc pl-5">
|
|
{detail.stockEffects.map((e, i) => <li key={e.deliveryOrderNo ?? i}>{effectLabel(t, e)}</li>)}
|
|
</ul>
|
|
)}
|
|
<p>{t("RefundQueueEmailMember")}</p>
|
|
</section>
|
|
)}
|
|
|
|
{r.status === "I" && (
|
|
<p className="rounded-md border border-warning/40 bg-warning/10 text-foreground p-3">
|
|
{t("RefundQueueInProgressHint")}
|
|
{r.lastError ? ` ${r.lastError}` : ""}
|
|
</p>
|
|
)}
|
|
{undecided && <p className="text-warning">{t("RefundQueueGoodsWarning")}</p>}
|
|
{actionError && <p role="alert" className="text-destructive">{actionError}</p>}
|
|
|
|
{undecided && (
|
|
<div className="flex gap-2">
|
|
<Button disabled={busy} onClick={() => { setActionError(null); setConfirming("approve"); }}>
|
|
{t("RefundQueueApprove")}
|
|
</Button>
|
|
{r.status === "P" && (
|
|
<Button variant="outline" disabled={busy} onClick={() => { setActionError(null); setConfirming("reject"); }}>
|
|
{t("RefundQueueReject")}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{!undecided && (
|
|
<section className="flex flex-col gap-2">
|
|
<dl className="grid grid-cols-[8rem_1fr] gap-x-3 gap-y-1">
|
|
<dt className="text-muted-foreground">{t("RefundQueueDecided")}</dt>
|
|
<dd>{r.decidedBy ?? "—"} · {formatDateTime(r.decidedAt)}</dd>
|
|
{r.decisionReason && (
|
|
<>
|
|
<dt className="text-muted-foreground">
|
|
{r.status === "R" ? t("RefundQueueRejectReason") : t("RefundQueueNote")}
|
|
</dt>
|
|
<dd>{r.decisionReason}</dd>
|
|
</>
|
|
)}
|
|
</dl>
|
|
{r.status === "A" && (
|
|
<ul className="flex flex-col gap-1 rounded-md bg-muted p-3">
|
|
{giftCard > 0 && <li>{t("RefundQueueRecordGiftCard", { amount: money(giftCard) })}</li>}
|
|
{r.payoutMethod === "MANUAL"
|
|
? payout > 0 && <li>{t("RefundQueueRecordManual", { amount: money(payout), channel: channelLabel(t, r.payoutChannel) })}</li>
|
|
: payout > 0 && <li>{t("RefundQueueRecordCredited", { amount: money(payout), ref: r.walletTrxnRef ?? "—" })}</li>}
|
|
<li>{t("RefundQueueRecordStock", { docs: r.stockDocumentNos || t("RefundQueueRecordNoAdjustment") })}</li>
|
|
</ul>
|
|
)}
|
|
{r.status === "R" && <p className="text-muted-foreground">{t("RefundQueueRejectedHint")}</p>}
|
|
{r.emailSentAt ? (
|
|
<p>{t("RefundQueueEmailSent", { at: formatDateTime(r.emailSentAt) })}</p>
|
|
) : (
|
|
<div className="flex items-center gap-2">
|
|
<span className="text-destructive">{t("RefundQueueEmailNotSent")}</span>
|
|
<Button size="sm" variant="outline" disabled={busy} onClick={() => uuid && run(() => retryRefundEmail(uuid))}>
|
|
{t("RefundQueueRetryEmail")}
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</section>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
<Dialog open={confirming === "approve"} onOpenChange={open => { if (!open) closeConfirm(); }}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{t("RefundQueueConfirmApproveTitle", { no: r?.documentNo ?? "" })}</DialogTitle>
|
|
</DialogHeader>
|
|
<p className="text-sm">{r && r.payoutMethod === "MANUAL"
|
|
? hasGiftCardTender
|
|
? t("RefundQueueConfirmApproveBodyManualGiftCard", { amount: money(r?.refundAmount), channel: channelLabel(t, r.payoutChannel) })
|
|
: t("RefundQueueConfirmApproveBodyManual", { amount: money(r?.refundAmount), channel: channelLabel(t, r.payoutChannel) })
|
|
: hasGiftCardTender
|
|
? t("RefundQueueConfirmApproveBodyGiftCard", { amount: money(r?.refundAmount) })
|
|
: t("RefundQueueConfirmApproveBody", { amount: money(r?.refundAmount) })}</p>
|
|
{hasGiftCardTender && <p className="text-warning text-sm">{t("RefundQueueGiftCardFirst")}</p>}
|
|
<Label className="flex-col items-start gap-1">
|
|
{t("RefundQueueNoteOptional")}
|
|
<Textarea value={note} maxLength={500} onChange={e => setNote(e.target.value)} disabled={busy} />
|
|
</Label>
|
|
<DialogFooter>
|
|
<Button variant="outline" disabled={busy} onClick={closeConfirm}>{t("RefundQueueCancel")}</Button>
|
|
<Button disabled={busy} onClick={() => uuid && run(() => approveRefund(uuid, note.trim() ? { note: note.trim() } : undefined))}>
|
|
{t("RefundQueueConfirmApprove")}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
|
|
<Dialog open={confirming === "reject"} onOpenChange={open => { if (!open) closeConfirm(); }}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{t("RefundQueueConfirmRejectTitle", { no: r?.documentNo ?? "" })}</DialogTitle>
|
|
</DialogHeader>
|
|
<Label className="flex-col items-start gap-1">
|
|
{t("RefundQueueRejectReasonLabel")}
|
|
<Textarea
|
|
value={reason}
|
|
maxLength={500}
|
|
aria-invalid={reasonError}
|
|
onChange={e => { setReason(e.target.value); setReasonError(false); }}
|
|
disabled={busy}
|
|
/>
|
|
</Label>
|
|
{reasonError && <p className="text-sm text-destructive">{t("RefundQueueRequireReason")}</p>}
|
|
<DialogFooter>
|
|
<Button variant="outline" disabled={busy} onClick={closeConfirm}>{t("RefundQueueCancel")}</Button>
|
|
<Button variant="destructive" disabled={busy} onClick={onConfirmReject}>{t("RefundQueueConfirmReject")}</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</SheetContent>
|
|
</Sheet>
|
|
);
|
|
}
|