Files
co-lite/solvway-admin-portal/app/pos/_components/SplitTenderPanel.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

520 lines
21 KiB
TypeScript

"use client";
import { useState, useEffect, useRef } from "react";
import { QRCodeSVG } from "qrcode.react";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ErrorState } from "@/app/components/ui/states";
import { usePosClientKey } from "@/app/lib/use-pos-client-key";
import { useSplitPoll } from "@/app/lib/hooks/useSplitPoll";
import { type PosLine } from "@/app/pos/shared";
import { useMoney } from "@/app/pos/currency";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { walletLabelCode } from "@/app/lib/walletLabels";
import { WALLET_ORDER, clampWalletAmounts, isWalletRefusal, refusalWallet, walletAmountsKey, walletCap } from "@/app/lib/walletAmounts";
import { WalletAmountLeg } from "@/app/pos/_components/WalletAmountLeg";
import { fulfilmentRefusal } from "@/app/pos/fulfilment";
import type {
AdminMember,
CounterSplitSalePayload,
CounterWalletPreviewPayload,
MemberCheckoutPreviewResult,
PosWalletOption,
PosWalletBalanceView,
SplitSaleResult,
SplitSettlementStatus,
} from "@/app/lib/types";
import { ApiError } from "@/app/lib/clientApi";
import type { MessageParams } from "@/app/lib/i18n/t";
// Shared split-tender panel (split-payment gateway, Task 13) rendered by BOTH `/pos/counter`
// (OUTLET / BO_COUNTER) and `/pos` (EVENT / BO_POS). The operator allocates the order total across
// three legs — the member's Wallet, Cash, and an online-payment Gateway. A gateway leg comes back
// with a redirect URL that is drawn as an on-screen QR for the customer to scan; the panel then
// polls (via `useSplitPoll`) until the settlement completes. When gateway == 0 the sale settles in
// the one request and the receipt is shown immediately.
//
// The member is picked once, in the page's Buyer section (redesign-pos-layout Task 4) — this panel
// no longer renders its own member picker. `walletMember`/`walletInfo` are page-owned state passed in
// as props purely for the panel's own logic (buyerType on submit, the canPlace gate). The candidate PIN is likewise page-owned; it is held only for the submit call and
// cleared from state immediately afterwards — never logged, never persisted.
//
// `place`/`poll`/`cancel` are the channel's own client fns, so the panel is channel-agnostic. The
// page supplies `buildReceipt` (its own receipt shape) + `setReceipt` and `onOrderPlaced` (the
// idempotency-key rotation), keeping receipt/key policy on the page.
interface SplitTenderPanelProps<R> {
/** Order total to allocate across the three legs. */
total: number;
lines: PosLine[];
// Wallet member + PIN — page-owned, picked once in the Buyer section (not duplicated here).
walletMember: AdminMember | null;
walletInfo: PosWalletBalanceView | null;
pin: string;
setPin: (pin: string) => void;
/** The channel's wallet preview; the panel reads the member's per-wallet `walletOptions` from it. */
previewWallet: (payload: CounterWalletPreviewPayload & { eventId?: string }) => Promise<MemberCheckoutPreviewResult>;
/** EVENT split sale only — the event warehouse is resolved from it. Omitted for OUTLET. */
eventId?: string;
/**
* Base cart signature (buyer + channel + lines). The panel appends the wallet amounts + cash + gateway so
* the idempotency key rotates when the allocation changes — a different split is a different attempt.
*/
cartSignature: string;
/** The promo code that is applied to this order. */
promoCode?: string | null;
/** Special-price promotion gifts the operator accepted (add-promotion-reward-lines). */
acceptedRewardCampaignIds?: number[];
extraFields?: Partial<CounterSplitSalePayload>;
/** Called with the refusal when the server refuses the sale as FulfilmentNotAllowed: the page closes
* payment, shows it and re-reads its products. */
onFulfilmentRefused?: (refusal: { code: string; params: { name: string } }) => void;
/**
* Called when the counter rejects the sale with HTTP 412 (an offer changed).
* The page should refresh its quote so the operator sees the updated total.
*/
onOfferChanged?: () => void;
/**
* Called with true while a gateway payment is pending (the QR is showing) and false once it is not,
* so the page can lock the sale's inputs (fix-split-pending-lock).
*/
onPendingChange?: (pending: boolean) => void;
// Channel client fns (counter/* or pos/*).
place: (payload: CounterSplitSalePayload) => Promise<SplitSaleResult>;
poll: (uuid: string) => Promise<SplitSettlementStatus>;
cancel: (uuid: string) => Promise<boolean>;
// Completion — the page builds its own receipt from the settled sale and stores it.
buildReceipt: (sale: { uuid: string; documentNo?: string }) => R;
setReceipt: (receipt: R) => void;
}
/** Parse a money input to a non-negative number; blank/garbage → 0. */
function money(raw: string): number {
const value = Number.parseFloat(raw);
return Number.isFinite(value) && value > 0 ? value : 0;
}
/** Compare at 2dp (cents) to avoid float drift on the remaining-must-be-zero gate. */
function cents(amount: number): number {
return Math.round(amount * 100);
}
export function SplitTenderPanel<R>({
total,
lines,
walletMember,
walletInfo,
pin,
setPin,
previewWallet,
eventId,
cartSignature,
promoCode,
acceptedRewardCampaignIds,
extraFields,
onFulfilmentRefused,
onOfferChanged,
onPendingChange,
place,
poll,
cancel,
buildReceipt,
setReceipt,
}: SplitTenderPanelProps<R>) {
const formatMoney = useMoney();
const t = useT();
const [totalPre, totalPost] = t("PosTotalAmount").split("{amount}");
const [remainingPre, remainingPost] = t("PosRemainingToAllocate").split("{amount}");
// Display-only: the member's enabled wallets, in server order (data already loaded by the page).
const walletBalanceEntries = (walletInfo?.balances ?? [])
.filter((b) => b.enabled === "Y")
.map(
(b) =>
`${t(walletLabelCode(b.walletTypeCode))} ${
b.walletTypeCode === "GIFT" ? formatMoney(b.balance) : b.balance.toFixed(2)
}`,
);
// RM per wallet code; only non-zero entries are sent. `options` are the member's wallets from the preview.
const [walletAmounts, setWalletAmounts] = useState<Record<string, number>>({});
const [options, setOptions] = useState<PosWalletOption[]>([]);
// A refused wallet amount: shown on the named leg, cleared as soon as any amount changes.
const [refusal, setRefusal] = useState<{ code: string; wallet: string | null } | null>(null);
const [cashRaw, setCashRaw] = useState("");
const [gatewayRaw, setGatewayRaw] = useState("");
const [placing, setPlacing] = useState(false);
const [error, setError] = useState<{ code: string; params?: MessageParams } | null>(null);
// The pending gateway sale (uuid + the redirect URL to QR-encode + the receipt snapshot at placement).
// Null when no gateway leg is awaiting the customer's scan.
const [pending, setPending] = useState<{ uuid: string; redirectUrl: string; receipt: R } | null>(null);
const memberCode = walletMember?.memberCode ?? "";
// A different member must not inherit the previous member's legs, amounts or refusal while the new
// preview loads (the amounts would otherwise be sent against the wrong wallets).
const [legsMember, setLegsMember] = useState(memberCode);
if (legsMember !== memberCode) {
setLegsMember(memberCode);
setOptions([]);
setWalletAmounts({});
setRefusal(null);
}
const legs = memberCode
? options
.filter((o) => o.balance > 0)
.sort((a, b) => WALLET_ORDER.indexOf(a.walletTypeCode as never) - WALLET_ORDER.indexOf(b.walletTypeCode as never))
: [];
// Only amounts for wallets the operator can see are ever sent.
const sentAmounts = Object.fromEntries(
Object.entries(walletAmounts).filter(([code, v]) => v > 0 && legs.some((o) => o.walletTypeCode === code)),
);
const walletTotal = Object.values(sentAmounts).reduce((sum, v) => sum + v, 0);
const cashAmount = money(cashRaw);
const gatewayAmount = money(gatewayRaw);
const remaining = total - (walletTotal + cashAmount + gatewayAmount);
const balanced = cents(remaining) === 0;
const walletNeedsAuth = walletTotal > 0;
// Fetch the member's wallet options when the member or cart changes. The latest payload sits in a ref so
// the effect depends only on a stable key, not on the page's per-render lines array and callback.
const latest = useRef({ previewWallet, lines, eventId, promoCode, acceptedRewardCampaignIds });
useEffect(() => {
latest.current = { previewWallet, lines, eventId, promoCode, acceptedRewardCampaignIds };
});
const previewKey = `${memberCode}|${total}|${lines.map((l) => `${l.pPricingId}x${l.qty}`).join(",")}|${promoCode ?? ""}|${(acceptedRewardCampaignIds ?? []).join(",")}`;
useEffect(() => {
if (!memberCode) {
// eslint-disable-next-line react-hooks/set-state-in-effect -- reset when the buyer becomes a walk-in.
setOptions([]);
setWalletAmounts((prev) => (Object.keys(prev).length ? {} : prev));
return;
}
const cur = latest.current;
let cancelled = false;
cur
.previewWallet({
memberCode,
lines: cur.lines.map(({ pPricingId, qty }) => ({ pPricingId, qty })),
...(cur.eventId ? { eventId: cur.eventId } : {}),
...(cur.promoCode ? { promoCode: cur.promoCode } : {}),
...(cur.acceptedRewardCampaignIds?.length ? { acceptedRewardCampaignIds: cur.acceptedRewardCampaignIds } : {}),
})
.then((result) => {
if (cancelled) return;
const next = result.walletOptions ?? [];
setOptions(next);
setWalletAmounts((prev) => clampWalletAmounts(prev, next));
})
// ponytail: a failed preview leaves the member with no wallet legs (cash/gateway still work); add a retry if ops need it.
.catch(() => {
if (!cancelled) setOptions([]);
});
return () => {
cancelled = true;
};
}, [previewKey, memberCode]);
function setWalletAmount(code: string, amount: number) {
if ((walletAmounts[code] ?? 0) === amount) return;
setRefusal(null);
setWalletAmounts((prev) => ({ ...prev, [code]: amount }));
}
// Idempotency key: base cart signature + this allocation. The counter dedups on it, so it stays
// stable across a failed submit and its retry for the SAME allocation, and rotates when the split
// changes or a sale is placed (onOrderPlaced below). remember=true persists the key across the
// unmount/remount cycle of the payment dialog so a retry reuses the same key.
const { clientKey, onOrderPlaced } = usePosClientKey(
`${cartSignature}|${walletAmountsKey(sentAmounts)}|${cashAmount}|${gatewayAmount}`,
{ remember: true },
);
const canPlace =
!placing &&
!pending &&
lines.length > 0 &&
total > 0 &&
balanced &&
(!walletNeedsAuth || (!!walletMember && pin.length > 0));
function reset() {
setPending(null);
setWalletAmounts({});
setCashRaw("");
setGatewayRaw("");
setPin("");
setError(null);
setRefusal(null);
}
function completeSale(sale: { uuid: string; documentNo?: string }) {
onOrderPlaced();
setReceipt(buildReceipt(sale));
}
// Poll the pending gateway sale to completion. No-ops (uuid null) until a gateway sale is placed.
const { polling } = useSplitPoll({
uuid: pending?.uuid ?? null,
poll,
cancel,
onPaid: () => {
if (pending) {
onOrderPlaced();
setReceipt(pending.receipt);
setPending(null);
}
},
onFailed: (state) => {
setError(
state === "EXPIRED"
? { code: "PosSplitExpired" }
: { code: "PosSplitGatewayFailed" },
);
// Rotate the idempotency key: the placed order was cancelled server-side, so a retry must mint
// a new order and never dedup onto the dead one.
onOrderPlaced();
setPending(null);
},
});
// Tell the page whether a gateway payment is pending, so it locks the sale inputs meanwhile.
// Also lock while placing — the page must not close the dialog mid-request.
const isPending = pending !== null || placing;
useEffect(() => {
onPendingChange?.(isPending);
}, [isPending, onPendingChange]);
// Unmounting (the page closes payment, e.g. on a refusal) must never leave the page locked.
useEffect(() => () => onPendingChange?.(false), [onPendingChange]);
async function handleSubmit() {
setError(null);
setRefusal(null);
setPlacing(true);
try {
const result = await place({
...extraFields,
buyerType: walletMember ? "MEMBER" : "GUEST",
...(walletMember ? { memberCode: walletMember.memberCode } : {}),
lines: lines.map(({ pPricingId, qty }) => ({ pPricingId, qty })),
walletAmounts: sentAmounts,
cashAmount,
gatewayAmount,
...(walletNeedsAuth ? { candidatePin: pin } : {}),
clientKey,
...(eventId ? { eventId } : {}),
expectedTotal: total,
...(promoCode ? { promoCode } : {}),
...(acceptedRewardCampaignIds?.length ? { acceptedRewardCampaignIds } : {}),
});
// The PIN is spent — clear it immediately regardless of outcome.
setPin("");
if (!result.success) {
const status = result.pinVerifyStatus;
if (status === "FAIL") {
setError({ code: "PosPinIncorrect" });
} else if (status === "LOCKED") {
setError({ code: "PosPinLockedStatus" });
} else if (status === "NO_PIN") {
setError({ code: "PosPinNoneSet" });
} else {
const reasons = result.messages?.join(", ");
setError(reasons ? { code: "PosSaleIncompleteReasons", params: { reasons } } : { code: "PosSplitFailed" });
}
// Do NOT rotate the key on a structured failure — the retry is the same attempt.
return;
}
// A confirmed sale always carries a uuid — never render a receipt / rotate the key without it.
if (!result.uuid) {
setError({ code: "PosSaleNotConfirmed" });
return;
}
if (result.redirectUrl) {
// Gateway leg pending: show the QR and start polling. Order confirms on PAID (completeSale).
// Snapshot the receipt now: the page's buyer/cart may change before the payment arrives.
setPending({
uuid: result.uuid,
redirectUrl: result.redirectUrl,
receipt: buildReceipt({ uuid: result.uuid, documentNo: result.documentNo }),
});
} else {
// Immediate settlement (gateway == 0): receipt straight away.
completeSale({ uuid: result.uuid, documentNo: result.documentNo });
}
} catch (err) {
setPin("");
const fulfilment = err instanceof ApiError ? fulfilmentRefusal(err.status, err.data, lines) : null;
if (err instanceof ApiError && err.status === 412) {
setError({ code: err.message });
onOrderPlaced();
onOfferChanged?.();
} else if (err instanceof ApiError && err.status === 400 && isWalletRefusal(err.data)) {
setRefusal({ code: (err.data as { code: string }).code, wallet: refusalWallet(err.data) });
} else if (fulfilment) {
setError(fulfilment);
onFulfilmentRefused?.(fulfilment);
} else {
setError(err instanceof Error ? { code: err.message } : { code: "PosSplitPlaceFailed" });
}
} finally {
setPlacing(false);
}
}
// ─── Gateway QR + poll view ────────────────────────────────────────────────
if (pending) {
return (
<div className="space-y-4 rounded-lg border p-4">
<h2 className="text-sm font-semibold">{t("PosGatewayPayment")}</h2>
<p className="text-sm text-muted-foreground">{t("PosScanToPay")}</p>
<div className="flex justify-center rounded-md bg-white p-4" data-testid="split-gateway-qr">
<QRCodeSVG value={pending.redirectUrl} size={220} aria-label={t("PosGatewayQrAria")} />
</div>
<p className="text-center text-xs text-muted-foreground">
{polling ? t("PosWaitingPayment") : t("PosPreparing")}
</p>
{error && <ErrorState message={t(error.code, error.params)} />}
<Button
type="button"
variant="outline"
onClick={() => {
const uuid = pending.uuid;
setPending(null);
// Fire-and-forget the release of the reserved stock; the panel resets regardless.
void cancel(uuid).catch(() => {});
onOrderPlaced();
reset();
}}
>
{t("Cancel")}
</Button>
</div>
);
}
// ─── Allocation form ───────────────────────────────────────────────────────
return (
<div className="space-y-4">
{/* One leg per wallet the member holds; the member and balances are shown in the page's Buyer section. */}
{legs.length > 0 && (
<div className="space-y-3 rounded-lg border p-4">
<h2 className="text-sm font-semibold">{t("PosWallet")}</h2>
{legs.map((option) => (
<WalletAmountLeg
key={option.walletTypeCode}
option={option}
value={walletAmounts[option.walletTypeCode] ?? 0}
cap={walletCap(option, total - cashAmount - gatewayAmount, sentAmounts)}
error={refusal?.wallet === option.walletTypeCode ? refusal.code : null}
onChange={(amount) => setWalletAmount(option.walletTypeCode, amount)}
/>
))}
</div>
)}
{/* Allocation */}
<div className="space-y-3 rounded-lg border p-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold">{t("PosSplitAllocation")}</h2>
<span className="text-sm">
{totalPre}
<span className="font-mono font-semibold">{formatMoney(total)}</span>
{totalPost}
</span>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="split-cash">{t("PosCash")}</Label>
<Input
id="split-cash"
type="number"
min={0}
step={0.01}
inputMode="decimal"
value={cashRaw}
onChange={(e) => {
setRefusal(null);
setCashRaw(e.target.value);
}}
placeholder="0.00"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="split-gateway">{t("PosGateway")}</Label>
<Input
id="split-gateway"
type="number"
min={0}
step={0.01}
inputMode="decimal"
value={gatewayRaw}
onChange={(e) => {
setRefusal(null);
setGatewayRaw(e.target.value);
}}
placeholder="0.00"
/>
</div>
</div>
<p className="text-sm" data-testid="split-remaining">
{remainingPre}
<span className={balanced ? "font-mono font-semibold text-positive" : "font-mono font-semibold text-destructive"}>
{formatMoney(remaining)}
</span>
{remainingPost}
</p>
{walletBalanceEntries.length > 0 && (
<p className="text-sm text-muted-foreground" data-testid="split-wallet-balances">
{t("PosWalletBalance", { balances: walletBalanceEntries.join(" · ") })}
</p>
)}
</div>
{/* PIN — only when the wallet leg is used. Masked, never persisted, cleared after submit. */}
{walletNeedsAuth && (
<div className="space-y-1.5 max-w-xs">
<Label htmlFor="split-pin">{t("PosMemberPin")}</Label>
<Input
id="split-pin"
type="password"
autoComplete="off"
inputMode="numeric"
maxLength={6}
value={pin}
onChange={(e) => setPin(e.target.value)}
placeholder={t("PosEnterMemberPin")}
/>
<p className="text-xs text-muted-foreground">
{t("PosPinHelp")}
</p>
</div>
)}
{refusal && !legs.some((o) => o.walletTypeCode === refusal.wallet) && (
<ErrorState message={t(refusal.code, { wallet: t("PosWallet") })} />
)}
{error && <ErrorState message={t(error.code, error.params)} />}
{/* Sticky so it stays visible at the bottom of the POS order pane's scroll area. The opaque footer
keeps fields scrolled under it (the member PIN) from showing through the half-transparent disabled button. */}
<div className="sticky bottom-0 z-10 bg-background py-2">
<Button
type="button"
className="h-12 w-full"
disabled={!canPlace}
onClick={() => void handleSubmit()}
>
{placing ? t("PosPlacingSplit") : t("PosPlaceSplit")}
</Button>
</div>
</div>
);
}