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:
@@ -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) => (
|
||||
|
||||
Reference in New Issue
Block a user