Files
NightSpire/web-next/components/SendGiftForm.tsx
T
Inna 1b0920d11f Permitir pagar los servicios con PD, Stripe o SumUp (elección)
Los 9 servicios con precio en euros (rename, customize, change-race,
change-faction, level-up, gold, transfer, restore-item, send-gift) ahora
ofrecen un selector de forma de pago con las 3 opciones: saldo PD, tarjeta
(Stripe) o tarjeta (SumUp).

- lib/dpoints: spendDPoints() descuenta PD de forma atómica (FOR UPDATE).
- lib/pay-with-dpoints: paga con saldo PD, ejecuta la acción al momento y
  reembolsa si la ejecución falla; 100 PD = 1 €.
- rutas checkout (character/[service] y gift): rama provider='pd' que valida
  saldo, descuenta, ejecuta fulfill y devuelve la URL de éxito (sin pasarela).
- service-success: rama provider='pd' (la entrega ya se hizo en el checkout).
- PaymentMethodSelect: componente compartido con coste por método y saldo;
  desactiva PD si no hay saldo suficiente.
- Formularios (PaidServiceForm, Gold, Transfer, RestoreItems, SendGift) y sus
  páginas pasan el saldo PD y envían el método elegido + locale.
- i18n: namespace Pay (es/en); añadidas claves Paid.restore-item que faltaban.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 21:44:31 +00:00

281 lines
9.4 KiB
TypeScript

'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'
// 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,
}: {
characters: CharOption[]
catalog: GiftCategory[]
currency?: string
pdBalance?: 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}>
<a href={`https://www.wowhead.com/wotlk/item=${it.itemId}`} target="_blank" rel="noreferrer noopener">
<img className="item-img-box" src={it.imageUrl} alt={it.name} />
</a>
<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>
<img className="item-img-box" src={e.item.imageUrl} alt={e.item.name} />
</td>
<td className="second-brown">{e.item.name}</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} />}
<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>
)
}