'use client'; import { useCallback, useEffect, useState } from 'react'; import { Wallet } from 'lucide-react'; import type { LoyaltyCreditQuote } from 'brainerce'; import { BrainerceError } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useTranslations } from '@/core/lib/translations'; import { checkCreditAmount, creditControlState } from '@/core/lib/loyalty-credit'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { cn } from '@/core/lib/utils'; interface LoyaltyCreditInputProps { checkoutId: string; /** * Whether the checkout can still change what it spends. False from the moment a payment intent * exists: the server refuses the change then (changing a discount under a created intent would * leave the provider charging the wrong amount), so the control stops offering it. */ locked: boolean; /** Formats a decimal string in the checkout's currency. */ formatAmount: (value: string) => string; /** Re-reads the checkout: the total, the discount and the tax all moved. */ onUpdate: () => void; /** * Anything that changes when the basket's discount or total does (a coupon applied or removed). * The quote's `maxApplicable` depends on what the basket leaves, so it is read again when this changes. */ revision?: string; className?: string; } /** * Spend the signed-in shopper's cashback balance at checkout. * * ## It is a discount, not a payment method * * Unlike a gift card (see `gift-card-input.tsx`), a spent balance lowers the checkout's discount, its * total and its tax, the way a coupon does. Everything shown here comes from the server's answer * (`applied`, `maxApplicable`); this file does no money arithmetic of its own. * * ## It hides itself * * A guest, a store with no cashback club, a customer who is not a member or has nothing to spend gets * no control at all. An empty "0 balance" box would read as a broken feature, and a merchant turns * the club on from the dashboard without touching this code. * * ## Spending is clamped by the server * * The amount is checked against `maxApplicable` before it is sent, and the server clamps again, so a * stale number cannot spend more than the basket leaves or than the member holds. Shipping is priced * before the balance, so using it never loses free shipping. */ export function LoyaltyCreditInput({ checkoutId, locked, formatAmount, onUpdate, revision, className, }: LoyaltyCreditInputProps) { const t = useTranslations('loyaltyCredit'); const tc = useTranslations('common'); const [quote, setQuote] = useState(null); const [amount, setAmount] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const load = useCallback(async () => { try { const next = await getClient().getCheckoutLoyaltyCredit(checkoutId); setQuote(next); setAmount(next.maxApplicable); } catch { // A guest (401), a checkout that is not this shopper's (404) or a store without the club: // nothing to offer, and nothing to complain about. setQuote(null); } }, [checkoutId]); useEffect(() => { void load(); }, [load, revision]); function isCheckoutLocked(err: unknown): boolean { if (!(err instanceof BrainerceError)) return false; const details = err.details as { code?: unknown } | null | undefined; return details?.code === 'CHECKOUT_LOCKED'; } async function handleApply(useAll: boolean) { if (!quote || busy) return; let toSpend: string | undefined; if (!useAll) { const checked = checkCreditAmount(amount, quote.maxApplicable); if (!checked.ok) { setError( checked.reason === 'tooMuch' ? t('tooMuch', { amount: formatAmount(quote.maxApplicable) }) : t('invalidAmount') ); return; } toSpend = checked.amount; } try { setBusy(true); setError(null); const next = await getClient().applyCheckoutLoyaltyCredit(checkoutId, toSpend); setQuote(next); onUpdate(); } catch (err) { setError(isCheckoutLocked(err) ? t('locked') : t('applyFailed')); } finally { setBusy(false); } } async function handleRemove() { if (busy) return; try { setBusy(true); setError(null); await getClient().removeCheckoutLoyaltyCredit(checkoutId); await load(); onUpdate(); } catch (err) { setError(isCheckoutLocked(err) ? t('locked') : t('removeFailed')); } finally { setBusy(false); } } const state = creditControlState(quote); if (state.kind === 'hidden') return null; return (
{state.kind === 'debt' &&

{t('hasDebt')}

} {state.kind === 'applied' && (
{!locked && ( )}
)} {state.kind === 'applied' && locked && (

{t('lockedHint')}

)} {state.kind === 'offer' && !locked && (
{ setAmount(e.target.value); if (error) setError(null); }} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void handleApply(false); } }} aria-label={t('amountLabel')} aria-invalid={!!error} // A number is Latin digits even on an RTL storefront. dir="ltr" autoComplete="off" className={cn('h-9 flex-1 rounded', error && 'border-destructive')} />
)} {error && (

{error}

)}
); }