send-gift: rediseño al original — es la tienda, pero regalando

El original lo dice en su propio texto ("los objetos disponibles son los mismos
de la tienda") y lo confirma su JS, que usa #store-list y .store-add-button: el
regalo NO tiene catálogo propio, es la tienda con el correo a otro personaje.
Nosotros teníamos una tabla aparte (home_item) con 8 objetos y precios en euros.

Ahora send-gift monta StoreBrowser en modo `gift`: mismo catálogo (3068 ítems,
PD/PV), mismo carrito con cantidades y las cuatro formas de pago. Antes NO tenía
Stripe: solo SumUp, PD y PV.

Dos pasos, como el original: primero #char-select-div (personaje de origen,
destino, confirmación y token) y solo al pulsar "Mostrar Regalos" aparece el
catálogo. Se borran SendGiftForm, /api/gift/checkout y lib/gift (ya no los usa
nadie); la tabla home_item se queda en la BD, sin usar.

Tres cosas que el usuario pidió y que estaban mal:
- El formulario va con `noValidate`: los avisos los damos nosotros en rojo
  (#show-gif-response), no el navegador.
- "Mostrar Regalos" ahora valida contra el SERVIDOR (que el personaje de origen
  sea tuyo, que el destino exista y que el token sea correcto). Antes elegías
  objetos para descubrir al final que el destino no existía.
- BUG REAL: el nombre del destino distinguía mayúsculas. `characters.name` es
  `utf8mb4_bin`, así que "innakh" NO encontraba a "Innakh" (comprobado: 0
  resultados; con COLLATE, 1). `findCharacterByName` busca sin distinguir y
  devuelve el nombre CANÓNICO, que es el que va al comando SOAP.

La validación vive en lib/gift-check y la usan las dos rutas: /api/gift/check (el
botón) y /api/gift/send, que revalida porque el cliente puede saltarse el paso 1.

También se quita del texto "El pago se realiza mediante SumUp": el original no lo
dice y además ya era falso con cuatro formas de pago.

Verificado: innakh / INNAKH / InNaKh resuelven a "Innakh"; token malo y destino
inexistente salen en rojo sin pasar al catálogo. Con 500 PD de saldo de prueba,
2 copias de un ítem de 200 pasan el cobro (deliveryFailed por el worldserver
caído, con su reembolso) y 3 dan insufficientPd: el servidor cobra por copias.
Datos de prueba borrados.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-15 12:45:01 +00:00
parent 2c78489e4d
commit 67faa1a266
15 changed files with 533 additions and 642 deletions
+67
View File
@@ -0,0 +1,67 @@
import { getTranslations } from 'next-intl/server'
import { redirect, Link } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getGameCharacters } from '@/lib/characters'
import { getStoreBalances } from '@/lib/store'
import { PageShell } from '@/components/PageShell'
import { ServiceBox } from '@/components/ServiceBox'
import { NoteLegend } from '@/components/NoteLegend'
import { StoreBrowser } from '@/components/StoreBrowser'
/**
* Enviar regalo. Es la tienda regalando: mismo catálogo y mismo carrito (así lo
* dice el propio texto del original, «los objetos disponibles son los mismos de
* la tienda»), pero el correo lo recibe otro personaje y hace falta el token de
* seguridad. Por eso monta `StoreBrowser` en modo `gift` en vez de duplicarlo.
*/
export async function GiftPage({ locale, realm }: { locale: string; realm: string }) {
const session = await getSession()
if (!session.bnetId) redirect({ href: '/log-in', locale })
if (!session.username) redirect({ href: '/select-account', locale })
const [chars, balances] = await Promise.all([
getGameCharacters(session.accountId!),
getStoreBalances(session.accountId!),
])
const t = await getTranslations('CharService')
return (
<PageShell title={t('sendGift.pageTitle')}>
<ServiceBox>
<br />
<p>{t.rich('sendGift.intro', { s: (c) => <span>{c}</span> })}</p>
<br />
<p>{t('sendGift.explain1')}</p>
<p>{t('sendGift.explain2')}</p>
<br />
<p>{t('sendGift.explain3')}</p>
<br />
<p>
{t.rich('sendGift.securityTokenHint', {
link: (c) => (
<Link href="/security-token" target="_blank">
{c}
</Link>
),
})}
</p>
<br />
<fieldset>
<NoteLegend />
<div className="separate2">
<p>{t('sendGift.noteIrreversible')}</p>
</div>
</fieldset>
<br />
</ServiceBox>
<StoreBrowser
mode="gift"
characters={chars.map((c) => ({ name: c.name, classCss: c.classCss }))}
dp={balances.dp}
vp={balances.vp}
realm={realm}
/>
</PageShell>
)
}
+35
View File
@@ -0,0 +1,35 @@
'use client'
import { useState } from 'react'
/** Campo con ojo para mostrar/ocultar el token de seguridad. */
export function SecretInput({
value,
onChange,
placeholder,
}: {
value: string
onChange: (v: string) => void
placeholder: string
}) {
const [show, setShow] = useState(false)
return (
<>
<input
type={show ? 'text' : 'password'}
id="security-token"
maxLength={6}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
required
/>{' '}
<span
className={`far ${show ? 'fa-eye-slash' : 'fa-eye'} toggle-token`}
role="button"
tabIndex={0}
onClick={() => setShow((s) => !s)}
/>
</>
)
}
-287
View File
@@ -1,287 +0,0 @@
'use client'
import { useMemo, useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import type { GiftCategory, GiftItem } from '@/lib/gift'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
import { PaymentMethodSelect, type PayMethod } from '@/components/PaymentMethodSelect'
import { WowheadLink } from '@/components/WowheadLink'
// Tope de cantidad en la interfaz. El servidor lo revalida en priceCart (fuente de verdad).
const MAX_QTY = 100
interface CartEntry {
item: GiftItem
qty: number
}
/** Campo con ojo para mostrar/ocultar el token de seguridad. */
function SecretInput({
value,
onChange,
placeholder,
}: {
value: string
onChange: (v: string) => void
placeholder: string
}) {
const [show, setShow] = useState(false)
return (
<>
<input
type={show ? 'text' : 'password'}
id="security-token"
maxLength={6}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
required
/>{' '}
<span
className={`far ${show ? 'fa-eye-slash' : 'fa-eye'} toggle-token`}
role="button"
tabIndex={0}
onClick={() => setShow((s) => !s)}
/>
</>
)
}
export function SendGiftForm({
characters,
catalog,
currency = '€',
pdBalance = 0,
vpBalance = 0,
}: {
characters: CharOption[]
catalog: GiftCategory[]
currency?: string
pdBalance?: number
vpBalance?: number
}) {
const t = useTranslations('CharService')
const tpay = useTranslations('Pay')
const locale = useLocale()
const [source, setSource] = useState('')
const [destination, setDestination] = useState('')
const [token, setToken] = useState('')
const [cart, setCart] = useState<Map<number, CartEntry>>(new Map())
const [method, setMethod] = useState<PayMethod>('pd')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const total = useMemo(
() => Math.round([...cart.values()].reduce((s, e) => s + e.item.price * e.qty, 0) * 100) / 100,
[cart],
)
// Catálogo aplanado y paginado: 4 objetos por fila, 2 filas (8) por página.
const PAGE_SIZE = 8
const allItems = useMemo(
() => catalog.flatMap((c) => c.items.map((it) => ({ ...it, category: c.name }))),
[catalog],
)
const [page, setPage] = useState(1)
const totalPages = Math.max(1, Math.ceil(allItems.length / PAGE_SIZE))
const currentPage = Math.min(page, totalPages)
const pageItems = allItems.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
function addItem(item: GiftItem) {
setCart((prev) => {
const next = new Map(prev)
const cur = next.get(item.id)
next.set(item.id, { item, qty: Math.min(MAX_QTY, (cur?.qty ?? 0) + 1) })
return next
})
}
function setQty(id: number, qty: number) {
setCart((prev) => {
const next = new Map(prev)
const cur = next.get(id)
if (!cur) return prev
const q = Math.max(1, Math.min(MAX_QTY, Math.floor(qty) || 1))
next.set(id, { ...cur, qty: q })
return next
})
}
function removeItem(id: number) {
setCart((prev) => {
const next = new Map(prev)
next.delete(id)
return next
})
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy) return
if (!source || !destination.trim() || !token.trim()) {
setError(t('sendGift.errMissingFields'))
return
}
if (cart.size === 0) {
setError(t('sendGift.errEmptyCart'))
return
}
if (
!window.confirm(
t('sendGift.confirm', { destination: destination.trim(), total, currency }),
)
)
return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/gift/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({
source,
destination: destination.trim(),
security_token: token.trim(),
cart: [...cart.values()].map((e) => ({ id: e.item.id, qty: e.qty })),
provider: method,
locale,
}),
})
const data: { success?: boolean; url?: string; message?: string; error?: string } = await res.json()
if (data.success && data.url) window.location.href = data.url
else {
const payErr = data.error && tpay.has(`errors.${data.error}`) ? tpay(`errors.${data.error}`) : undefined
setError(data.message || payErr || t('sendGift.errPayment'))
setBusy(false)
}
} catch {
setError(t('sendGift.errUnexpected'))
setBusy(false)
}
}
if (characters.length === 0) return <p className="second-brown">{t('sendGift.noCharacters')}</p>
if (catalog.length === 0) return <p className="second-brown">{t('sendGift.noItems')}</p>
return (
<div className="centered">
<form noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
<p>{t('sendGift.sourcePrompt')}</p>
<CharacterSelect characters={characters} value={source} onChange={setSource} placeholder={t('sendGift.sourcePlaceholder')} />
<br />
<p>{t('sendGift.destPrompt')}</p>
<input
type="text"
maxLength={12}
placeholder={t('sendGift.destPlaceholder')}
value={destination}
onChange={(e) => setDestination(e.target.value)}
required
/>
<br />
<p>{t('sendGift.tokenPrompt')}</p>
<SecretInput value={token} onChange={setToken} placeholder={t('sendGift.tokenPlaceholder')} />
<hr />
{/* Catálogo de objetos: cuadrícula centrada de 4 por fila + paginación */}
<h3 className="first-brown centered">{t('sendGift.availableItems')}</h3>
<div className="gift-grid">
{pageItems.map((it) => (
<div className="item-box" key={it.id}>
<WowheadLink id={it.itemId}>
<img className="item-img-box" src={it.imageUrl} alt={it.name} />
</WowheadLink>
<div className="third-brown" style={{ fontSize: '12px' }}>{it.category}</div>
<div className="item-name second-brown">{it.name}</div>
<div className="yellow-info">
{it.price} {currency}
</div>
<button type="button" className="store-add-button" onClick={() => addItem(it)}>
{t('sendGift.add')}
</button>
</div>
))}
</div>
{totalPages > 1 && (
<div className="gift-pagination">
<button type="button" onClick={() => setPage((p) => Math.max(1, Math.min(totalPages, p) - 1))} disabled={currentPage === 1}>
{t('sendGift.back')}
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((n) => (
<button
type="button"
key={n}
className={n === currentPage ? 'active-page' : ''}
onClick={() => setPage(n)}
>
{n}
</button>
))}
<button type="button" onClick={() => setPage((p) => Math.min(totalPages, Math.min(totalPages, p) + 1))} disabled={currentPage === totalPages}>
{t('sendGift.next')}
</button>
</div>
)}
<hr />
{/* Carrito */}
<h3 className="first-brown">{t('sendGift.cart')}</h3>
{cart.size === 0 ? (
<p className="second-brown">{t('sendGift.cartEmpty')}</p>
) : (
<table className="cart-list max-center-table">
<tbody>
{[...cart.values()].map((e) => (
<tr key={e.item.id}>
<td>
<WowheadLink id={e.item.itemId}>
<img className="item-img-box" src={e.item.imageUrl} alt={e.item.name} />
</WowheadLink>
</td>
<td className="second-brown">
<WowheadLink id={e.item.itemId}>{e.item.name}</WowheadLink>
</td>
<td>
<input
type="number"
min={1}
max={MAX_QTY}
value={e.qty}
onChange={(ev) => setQty(e.item.id, Number(ev.target.value))}
style={{ width: '4em' }}
/>
</td>
<td className="yellow-info">{Math.round(e.item.price * e.qty * 100) / 100} {currency}</td>
<td>
<button type="button" className="store-remove-button" onClick={() => removeItem(e.item.id)}>
<i className="fas fa-trash" />
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
<div className="centered">
<br />
<p>
{t.rich('sendGift.total', { total, currency, s: (c) => <span className="yellow-info">{c}</span> })}
</p>
{total > 0 && <PaymentMethodSelect value={method} onChange={setMethod} priceEur={total} pdBalance={pdBalance} vpBalance={vpBalance} />}
<br />
<button
type="submit"
className="store-send-button"
disabled={busy || cart.size === 0 || !source || !destination.trim() || !token.trim()}
>
{busy ? t('sendGift.submitting') : t('sendGift.submit')}
</button>
</div>
</form>
<hr />
<div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
{error && <span className="red-form-response">{error}</span>}
</div>
</div>
)
}
+141 -24
View File
@@ -3,6 +3,7 @@
import { Fragment, useEffect, useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
import { SecretInput } from '@/components/SecretInput'
import { WowheadLink } from '@/components/WowheadLink'
import { wowheadIcon } from '@/lib/wowhead'
import { CARD_MIN_EUR, MAX_COPIES, lineEur, storeEuroTotal } from '@/lib/store-pricing'
@@ -154,17 +155,31 @@ interface CartLine {
copies: number
}
/**
* Árbol + carrito de la tienda. En modo `gift` es lo mismo pero regalando: el
* original hace justo esto ("los objetos disponibles son los mismos de la
* tienda"), en dos pasos —primero de quién a quién y el token, y solo después el
* catálogo— y el correo lo recibe otro personaje.
*/
export function StoreBrowser({
characters,
dp,
vp,
realm,
mode = 'store',
}: {
characters: CharOption[]
dp: number
vp: number
realm: string
mode?: 'store' | 'gift'
}) {
const gift = mode === 'gift'
const [destination, setDestination] = useState('')
const [confirmDest, setConfirmDest] = useState('')
const [token, setToken] = useState('')
const [shown, setShown] = useState(false)
const [formError, setFormError] = useState('')
const t = useTranslations('Store')
const locale = useLocale()
const [character, setCharacter] = useState('')
@@ -175,10 +190,8 @@ export function StoreBrowser({
const [sending, setSending] = useState(false)
const [modal, setModal] = useState<{ ok: boolean; text: string } | null>(null)
async function onSelect(name: string) {
setCharacter(name)
setCart(new Map())
if (!name || catalog) return
async function loadCatalog() {
if (catalog) return
setLoading(true)
try {
const res = await fetch(`/api/store/catalog?locale=${encodeURIComponent(locale)}`, { credentials: 'same-origin' })
@@ -191,6 +204,54 @@ export function StoreBrowser({
}
}
async function onSelect(name: string) {
setCharacter(name)
setCart(new Map())
// En la tienda el catálogo sale al elegir personaje; en el regalo hay que
// decir antes a quién y con qué token ("Mostrar Regalos").
if (name && !gift) await loadCatalog()
}
/**
* Paso 1 del regalo: valida y solo entonces enseña el catálogo.
*
* La confirmación del nombre se compara aquí (es cosa de la pantalla), pero
* que el personaje de destino exista y que el token sea correcto lo dice el
* SERVIDOR: si no, elegirías objetos para descubrir al final que el destino no
* existe. El nombre del destino puede ir en mayúsculas o minúsculas; el
* servidor devuelve el canónico y es el que se usa a partir de aquí.
*/
async function showGifts(e: React.FormEvent) {
e.preventDefault()
if (!character || !destination.trim() || !token.trim()) return setFormError(t('gift.errMissing'))
if (destination.trim().toLowerCase() !== confirmDest.trim().toLowerCase()) {
return setFormError(t('gift.errConfirm'))
}
setFormError('')
setLoading(true)
try {
const res = await fetch('/api/gift/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ source: character, destination: destination.trim(), security_token: token }),
})
const data: { success?: boolean; error?: string; destination?: string } = await res.json()
if (!data.success) {
setFormError(t.has(`errors.${data.error}`) ? t(`errors.${data.error}`) : t('errors.generic'))
return
}
if (data.destination) setDestination(data.destination)
} catch {
setFormError(t('errors.generic'))
return
} finally {
setLoading(false)
}
await loadCatalog()
setShown(true)
}
// Volver a añadir un ítem ya en el carrito suma una copia (como send-gift).
function addItem(it: StoreItem) {
setCart((prev) => {
@@ -259,22 +320,23 @@ export function StoreBrowser({
async function send() {
if (sending || cart.size === 0) return
const card = payingCard
const who = gift ? destination.trim() : character
const ok = card
? window.confirm(t('confirmCard', { eur: eurNumber(eurTotal, locale), character }))
: window.confirm(t('confirm', { character, pd: pdTotal, vp: vpTotal }))
? window.confirm(t('confirmCard', { eur: eurNumber(eurTotal, locale), character: who }))
: window.confirm(t('confirm', { character: who, pd: pdTotal, vp: vpTotal }))
if (!ok) return
setSending(true)
try {
const res = await fetch('/api/store/send', {
const items = lines.map((l) => ({ id: l.it.id, copies: l.copies }))
const res = await fetch(gift ? '/api/gift/send' : '/api/store/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({
character,
items: lines.map((l) => ({ id: l.it.id, copies: l.copies })),
provider: activeMethod,
locale,
}),
body: JSON.stringify(
gift
? { source: character, destination: destination.trim(), security_token: token, items, provider: activeMethod, locale }
: { character, items, provider: activeMethod, locale },
),
})
const data: { success?: boolean; error?: string; url?: string; min?: number } = await res.json()
if (data.success && data.url) {
@@ -284,7 +346,7 @@ export function StoreBrowser({
return
}
if (data.success) {
setModal({ ok: true, text: t('successMsg', { character }) })
setModal({ ok: true, text: t(gift ? 'gift.successMsg' : 'successMsg', { character: gift ? destination.trim() : character }) })
setCart(new Map())
} else if (data.error === 'amountTooLow') {
setModal({ ok: false, text: t('errors.amountTooLow', { min: eurNumber(data.min ?? 1, locale) }) })
@@ -300,19 +362,74 @@ export function StoreBrowser({
return (
<>
<div className="centered">
<br />
<p>{t('choosePlayer')}</p>
<br />
<CharacterSelect characters={characters} value={character} onChange={onSelect} placeholder={t('selectPlaceholder')} className="store-select" />
<p className="third-brown pay-method-balance">
<span className="dp-color">PD</span>: {dp} · <span className="vp-color">PV</span>: {vp}
</p>
</div>
{/* Paso 1 del regalo (#char-select-div en el original): de quién a quién y
token. Desaparece al pulsar "Mostrar Regalos" y deja sitio al catálogo. */}
{gift && !shown && (
<div className="centered" id="char-select-div">
<br />
<p>{t('gift.choosePlayer')}</p>
<br />
<form noValidate onSubmit={showGifts} acceptCharset="utf-8">
<CharacterSelect characters={characters} value={character} onChange={onSelect} placeholder={t('selectPlaceholder')} />
<table className="middle-center-table">
<tbody>
<tr>
<td>
<input
type="text"
maxLength={12}
value={destination}
onChange={(e) => setDestination(e.target.value)}
placeholder={t('gift.destPlaceholder')}
/>
</td>
</tr>
<tr>
<td>
<input
type="text"
maxLength={12}
value={confirmDest}
onChange={(e) => setConfirmDest(e.target.value)}
placeholder={t('gift.confirmPlaceholder')}
/>
</td>
</tr>
<tr>
<td>
<SecretInput value={token} onChange={setToken} placeholder={t('gift.tokenPlaceholder')} />
</td>
</tr>
<tr>
<td>
<button type="submit" className="show-gift-button" disabled={loading}>
{loading ? t('gift.showing') : t('gift.show')}
</button>
</td>
</tr>
</tbody>
</table>
</form>
<hr />
{formError && <div className="alert-message red-form-response" id="show-gif-response">{formError}</div>}
</div>
)}
{!gift && (
<div className="centered">
<br />
<p>{t('choosePlayer')}</p>
<br />
<CharacterSelect characters={characters} value={character} onChange={onSelect} placeholder={t('selectPlaceholder')} className="store-select" />
<p className="third-brown pay-method-balance">
<span className="dp-color">PD</span>: {dp} · <span className="vp-color">PV</span>: {vp}
</p>
</div>
)}
{loading && <p className="centered second-brown">{t('loading')}</p>}
{catalog && !loading && (
{catalog && !loading && (!gift || shown) && (
<div className="box-content" id="store-div">
<ul id="store-list">
{catalog.map((c) => (