6ca94c2803
- CharacterSelect: componente reutilizable que colorea las opciones por clase (class="priest big-font"…) y el <select> con la clase seleccionada. Usado en unstuck, revive, gold, transfer, trade-points, servicios de pago y recruit. getGameCharacters ahora devuelve classCss. - /unstuck (+revive): diseño del original (info + NOTA, prompt, opciones coloreadas, botón "Desbloqueado"/"Revivido" con refresh). - /vote-points: seed de los 4 sitios con logos y URLs (sql/seed_votesites.sql); botón voted-button para sitios en cooldown; etiqueta "Nota:" separada. - account-info.png (imagen nueva) y CSS de los paneles de cuenta: se añade background-blend-mode: saturation y background-size en #account-settings y .account-fieldset para que la imagen salga como el original. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
307 lines
12 KiB
TypeScript
307 lines
12 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { Turnstile } from '@/components/Turnstile'
|
|
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
|
|
|
|
function tradeError(error?: string): string {
|
|
switch (error) {
|
|
case 'missingFields':
|
|
return 'Rellena todos los campos.'
|
|
case 'invalidAmount':
|
|
return 'Las cantidades deben ser números enteros entre 1 y 99999.'
|
|
case 'characterNotFound':
|
|
case 'characterNotOwned':
|
|
return 'El personaje seleccionado no es válido.'
|
|
case 'captcha':
|
|
return 'Verifica que no eres un robot.'
|
|
case 'wrongPassword':
|
|
return 'La contraseña de tu cuenta es incorrecta.'
|
|
case 'invalidToken':
|
|
return 'El token de seguridad no es válido.'
|
|
case 'insufficientPoints':
|
|
return 'No tienes suficientes PD disponibles para crear este código.'
|
|
case 'codeNotFound':
|
|
return 'No existe ningún código con ese ID.'
|
|
case 'codeUnavailable':
|
|
return 'El código ya no está disponible (canjeado o expirado).'
|
|
case 'cannotRedeemOwn':
|
|
return 'No puedes canjear tu propio código.'
|
|
case 'characterOnline':
|
|
return 'El personaje debe estar desconectado para poder cobrar el oro.'
|
|
case 'insufficientGold':
|
|
return 'El personaje no tiene suficiente oro.'
|
|
case 'creatorInsufficient':
|
|
return 'El creador del código ya no tiene suficientes PD.'
|
|
case 'locked':
|
|
return 'Espera unos segundos antes de canjear otro código.'
|
|
case 'deliveryFailed':
|
|
return 'No se pudo entregar el oro (servidor de juego no disponible). Inténtalo de nuevo más tarde.'
|
|
case 'notAuthenticated':
|
|
return 'Tu sesión ha expirado. Inicia sesión de nuevo.'
|
|
default:
|
|
return 'No se pudo completar la operación. Inténtalo de nuevo.'
|
|
}
|
|
}
|
|
|
|
function PasswordInput({
|
|
id,
|
|
value,
|
|
onChange,
|
|
placeholder,
|
|
maxLength,
|
|
}: {
|
|
id: string
|
|
value: string
|
|
onChange: (v: string) => void
|
|
placeholder: string
|
|
maxLength: number
|
|
}) {
|
|
const [show, setShow] = useState(false)
|
|
return (
|
|
<>
|
|
<input
|
|
type={show ? 'text' : 'password'}
|
|
id={id}
|
|
maxLength={maxLength}
|
|
value={value}
|
|
onChange={(e) => onChange(e.target.value)}
|
|
placeholder={placeholder}
|
|
/>{' '}
|
|
<span
|
|
className={`far ${show ? 'fa-eye-slash' : 'fa-eye'} toggle-password`}
|
|
role="button"
|
|
tabIndex={0}
|
|
onClick={() => setShow((s) => !s)}
|
|
/>
|
|
</>
|
|
)
|
|
}
|
|
|
|
/* ---------------------------------- VENTA ---------------------------------- */
|
|
function SellForm({ characters, visible }: { characters: CharOption[]; visible: boolean }) {
|
|
const [points, setPoints] = useState('')
|
|
const [gold, setGold] = useState('')
|
|
const [character, setCharacter] = useState('')
|
|
const [password, setPassword] = useState('')
|
|
const [token, setToken] = useState('')
|
|
const [captcha, setCaptcha] = useState('')
|
|
const [busy, setBusy] = useState(false)
|
|
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
|
const [created, setCreated] = useState<{ code: string; points: number; gold: number } | null>(null)
|
|
|
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
|
e.preventDefault()
|
|
if (busy) return
|
|
setBusy(true)
|
|
setMessage(null)
|
|
setCreated(null)
|
|
try {
|
|
const res = await fetch('/api/dpoints/trade/create', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify({
|
|
points: Number(points),
|
|
gold: Number(gold),
|
|
character,
|
|
password,
|
|
token: token.trim(),
|
|
turnstile: captcha,
|
|
}),
|
|
})
|
|
const data: { success?: boolean; error?: string; code?: { code: string; points: number; gold: number } } = await res.json()
|
|
if (data.success && data.code) {
|
|
setCreated(data.code)
|
|
setMessage({ ok: true, text: '¡Código creado!' })
|
|
setPoints('')
|
|
setGold('')
|
|
setPassword('')
|
|
setToken('')
|
|
} else {
|
|
setMessage({ ok: false, text: tradeError(data.error) })
|
|
}
|
|
} catch {
|
|
setMessage({ ok: false, text: tradeError() })
|
|
} finally {
|
|
setBusy(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div id="trade-sell-div" style={{ display: visible ? 'block' : 'none' }}>
|
|
<form onSubmit={handleSubmit} acceptCharset="utf-8">
|
|
<table className="middle-center-table">
|
|
<tbody>
|
|
<tr><td>¿Cuánto valdrá el código en PD?</td></tr>
|
|
<tr><td><input type="number" maxLength={5} min="1" max="99999" step="1" value={points} onChange={(e) => setPoints(e.target.value)} placeholder="Valor del código en PD" required /></td></tr>
|
|
<tr><td>¿Cuánto costará el código en oro?</td></tr>
|
|
<tr><td><input type="number" maxLength={5} min="1" max="99999" step="1" value={gold} onChange={(e) => setGold(e.target.value)} placeholder="Valor del código en oro" required /></td></tr>
|
|
<tr><td>¿A qué personaje se enviará el oro?</td></tr>
|
|
<tr><td>
|
|
<CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder="Selecciona un personaje" />
|
|
</td></tr>
|
|
<tr><td><br /><PasswordInput id="password-sell" value={password} onChange={setPassword} placeholder="Contraseña de tu cuenta" maxLength={16} /></td></tr>
|
|
<tr><td><input type="text" maxLength={6} value={token} onChange={(e) => setToken(e.target.value)} placeholder="Token de seguridad" required /></td></tr>
|
|
<tr><td><Turnstile onVerify={setCaptcha} /></td></tr>
|
|
<tr><td><button type="submit" className="trade-points-sell-button" disabled={busy}>{busy ? 'Creando…' : 'Crear código'}</button></td></tr>
|
|
</tbody>
|
|
</table>
|
|
</form>
|
|
<hr />
|
|
<div className="alert-message" id="trade-points-sell-response" style={{ display: message || created ? 'block' : 'none' }}>
|
|
{message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
|
|
{created && (
|
|
<fieldset>
|
|
<legend>Código creado</legend>
|
|
<div className="separate2">
|
|
<p>ID del código: <span className="green-info2">{created.code}</span></p>
|
|
<p>Valor: <span>{created.points} PD</span> por <span>{created.gold} de oro</span></p>
|
|
<p className="second-brown">Envía este ID al comprador. El código caduca en 1 hora.</p>
|
|
</div>
|
|
</fieldset>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
/* ---------------------------------- COMPRA --------------------------------- */
|
|
function BuyForm({ characters, visible }: { characters: CharOption[]; visible: boolean }) {
|
|
const [code, setCode] = useState('')
|
|
const [character, setCharacter] = useState('')
|
|
const [password, setPassword] = useState('')
|
|
const [token, setToken] = useState('')
|
|
const [captcha, setCaptcha] = useState('')
|
|
const [busy, setBusy] = useState(false)
|
|
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
|
const [checkInfo, setCheckInfo] = useState<{ points: number; gold: number } | null>(null)
|
|
|
|
async function handleCheck() {
|
|
if (busy || !code.trim()) return
|
|
setBusy(true)
|
|
setMessage(null)
|
|
setCheckInfo(null)
|
|
try {
|
|
const res = await fetch('/api/dpoints/trade/check', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify({ code: code.trim() }),
|
|
})
|
|
const data: { success?: boolean; error?: string; points?: number; gold?: number } = await res.json()
|
|
if (data.success && data.points != null && data.gold != null) {
|
|
setCheckInfo({ points: data.points, gold: data.gold })
|
|
setMessage({ ok: true, text: `Este código vale ${data.points} PD y cuesta ${data.gold} de oro.` })
|
|
} else {
|
|
setMessage({ ok: false, text: tradeError(data.error) })
|
|
}
|
|
} catch {
|
|
setMessage({ ok: false, text: tradeError() })
|
|
} finally {
|
|
setBusy(false)
|
|
}
|
|
}
|
|
|
|
async function handleRedeem(e: React.FormEvent<HTMLFormElement>) {
|
|
e.preventDefault()
|
|
if (busy) return
|
|
if (!window.confirm('Vas a canjear este código. Esta acción no es reversible. ¿Deseas continuar?')) return
|
|
setBusy(true)
|
|
setMessage(null)
|
|
try {
|
|
const res = await fetch('/api/dpoints/trade/redeem', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify({ code: code.trim(), character, password, token: token.trim(), turnstile: captcha }),
|
|
})
|
|
const data: { success?: boolean; error?: string; points?: number; gold?: number } = await res.json()
|
|
if (data.success) {
|
|
setMessage({ ok: true, text: `¡Canje correcto! Recibiste ${data.points} PD y se retiraron ${data.gold} de oro de ${character}.` })
|
|
setCode('')
|
|
setPassword('')
|
|
setToken('')
|
|
setCheckInfo(null)
|
|
} else {
|
|
setMessage({ ok: false, text: tradeError(data.error) })
|
|
}
|
|
} catch {
|
|
setMessage({ ok: false, text: tradeError() })
|
|
} finally {
|
|
setBusy(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div id="trade-buy-div" style={{ display: visible ? 'block' : 'none' }}>
|
|
<form onSubmit={handleRedeem} acceptCharset="utf-8">
|
|
<table className="middle-center-table">
|
|
<tbody>
|
|
<tr><td>Ingresa el ID del código de PD</td></tr>
|
|
<tr><td><input type="text" maxLength={25} value={code} onChange={(e) => setCode(e.target.value)} placeholder="Código de PD" required /></td></tr>
|
|
{checkInfo && (
|
|
<tr><td><p className="green-info2">Vale {checkInfo.points} PD · Cuesta {checkInfo.gold} de oro</p></td></tr>
|
|
)}
|
|
<tr><td>¿De qué personaje se cobrará el oro?</td></tr>
|
|
<tr><td>
|
|
<CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder="Selecciona un personaje" />
|
|
</td></tr>
|
|
<tr><td><br /><PasswordInput id="password-buy" value={password} onChange={setPassword} placeholder="Contraseña de tu cuenta" maxLength={16} /></td></tr>
|
|
<tr><td><input type="text" maxLength={6} value={token} onChange={(e) => setToken(e.target.value)} placeholder="Token de seguridad" required /></td></tr>
|
|
<tr><td><Turnstile onVerify={setCaptcha} /></td></tr>
|
|
<tr><td><button type="button" className="trade-points-check-button" disabled={busy} onClick={handleCheck}>Chequear código</button></td></tr>
|
|
<tr><td><button type="submit" className="trade-points-buy-button" disabled={busy}>{busy ? 'Procesando…' : 'Canjear código'}</button></td></tr>
|
|
</tbody>
|
|
</table>
|
|
</form>
|
|
<hr />
|
|
<div className="alert-message" id="trade-points-buy-response" style={{ display: message ? 'block' : 'none' }}>
|
|
{message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export function TradePointsForm({ characters }: { characters: CharOption[] }) {
|
|
// Como el original: al cargar no se muestra ningún formulario; se revela al
|
|
// pulsar VENTA o COMPRA.
|
|
const [active, setActive] = useState<'sell' | 'buy' | null>(null)
|
|
|
|
if (characters.length === 0) {
|
|
return (
|
|
<div className="centered">
|
|
<br />
|
|
<span>No tienes personajes en esta cuenta.</span>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="centered">
|
|
<br />
|
|
<br />
|
|
<button
|
|
type="button"
|
|
id="trade-sell-a"
|
|
className={`trade-option-button${active === 'sell' ? ' dnt-selected' : ''}`}
|
|
onClick={() => setActive('sell')}
|
|
>
|
|
VENTA
|
|
</button>
|
|
<button
|
|
type="button"
|
|
id="trade-buy-a"
|
|
className={`trade-option-button${active === 'buy' ? ' dnt-selected' : ''}`}
|
|
onClick={() => setActive('buy')}
|
|
>
|
|
COMPRA
|
|
</button>
|
|
<br />
|
|
<SellForm characters={characters} visible={active === 'sell'} />
|
|
<BuyForm characters={characters} visible={active === 'buy'} />
|
|
<br />
|
|
</div>
|
|
)
|
|
}
|