web-next: herramientas de PD (transferir, comercio, códigos de promoción)
- /transfer-d-points: transferir PD a la cuenta dueña de un personaje (requiere token de seguridad; movimiento atómico con FOR UPDATE). - /trade-points: comercio PD<->oro mediante códigos de 1 solo uso (contraseña + token + Turnstile; oro al creador por SOAP; expira 1h; lock de 5s tras canjear; rollback total si falla la entrega). - /promo-code: canje de códigos por PD/PV (sensibles a mayúsculas/minúsculas, usos limitados, 1 canje por cuenta). - /admin/promo: panel para crear / editar / activar / desactivar / borrar códigos de promoción. - Tablas nuevas (sql/): home_tradecode, home_promocode, home_promoredemption. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import type { PromoCode } from '@/lib/admin-promo'
|
||||
|
||||
export function AdminPromoManager({ initial }: { initial: PromoCode[] }) {
|
||||
const t = useTranslations('Admin')
|
||||
const [codes, setCodes] = useState(initial)
|
||||
const [form, setForm] = useState({ code: '', pd: '0', pv: '0', maxUses: '1', expiresAt: '' })
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
function upd(k: string, v: string) {
|
||||
setForm((f) => ({ ...f, [k]: v }))
|
||||
}
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (busy || !form.code.trim()) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch('/api/admin/promo', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({
|
||||
code: form.code.trim(),
|
||||
pd: Number(form.pd),
|
||||
pv: Number(form.pv),
|
||||
maxUses: Number(form.maxUses),
|
||||
expiresAt: form.expiresAt,
|
||||
}),
|
||||
})
|
||||
const data: { success?: boolean; id?: number; error?: string } = await res.json()
|
||||
if (data.success && data.id) {
|
||||
setCodes([
|
||||
{
|
||||
id: data.id,
|
||||
code: form.code.trim(),
|
||||
pd: Number(form.pd),
|
||||
pv: Number(form.pv),
|
||||
max_uses: Number(form.maxUses),
|
||||
uses: 0,
|
||||
active: 1,
|
||||
expires_at: form.expiresAt ? new Date(form.expiresAt).toISOString() : null,
|
||||
redemptions: 0,
|
||||
},
|
||||
...codes,
|
||||
])
|
||||
setForm({ code: '', pd: '0', pv: '0', maxUses: '1', expiresAt: '' })
|
||||
} else {
|
||||
setError(data.error === 'duplicate' ? t('promoDuplicate') : t('promoEmptyError'))
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: number) {
|
||||
if (!confirm(t('promoConfirmDelete'))) return
|
||||
const res = await fetch(`/api/admin/promo/${id}`, { method: 'DELETE', credentials: 'same-origin' })
|
||||
if ((await res.json()).success) setCodes(codes.filter((c) => c.id !== id))
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<form onSubmit={create} className="admin-form info-box-light separate2">
|
||||
<input value={form.code} onChange={(e) => upd('code', e.target.value)} placeholder={t('promoCode')} />
|
||||
<input type="number" min="0" value={form.pd} onChange={(e) => upd('pd', e.target.value)} placeholder={t('promoPd')} />
|
||||
<input type="number" min="0" value={form.pv} onChange={(e) => upd('pv', e.target.value)} placeholder={t('promoPv')} />
|
||||
<input type="number" min="1" value={form.maxUses} onChange={(e) => upd('maxUses', e.target.value)} placeholder={t('promoMaxUses')} />
|
||||
<input type="datetime-local" value={form.expiresAt} onChange={(e) => upd('expiresAt', e.target.value)} placeholder={t('promoExpires')} />
|
||||
<button type="submit" disabled={busy}>{busy ? t('creating') : t('createPromo')}</button>
|
||||
</form>
|
||||
{error && <p className="red-form-response centered">{error}</p>}
|
||||
<br />
|
||||
{codes.length === 0 ? (
|
||||
<p className="second-brown centered">{t('noPromo')}</p>
|
||||
) : (
|
||||
<table className="max-center-table">
|
||||
<tbody>
|
||||
{codes.map((c) => (
|
||||
<PromoRow key={c.id} promo={c} onDelete={() => remove(c.id)} />
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PromoRow({ promo, onDelete }: { promo: PromoCode; onDelete: () => void }) {
|
||||
const t = useTranslations('Admin')
|
||||
const [pd, setPd] = useState(String(promo.pd))
|
||||
const [pv, setPv] = useState(String(promo.pv))
|
||||
const [maxUses, setMaxUses] = useState(String(promo.max_uses))
|
||||
const [active, setActive] = useState(promo.active === 1)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
|
||||
async function save() {
|
||||
setBusy(true)
|
||||
setSaved(false)
|
||||
try {
|
||||
const res = await fetch(`/api/admin/promo/${promo.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ pd: Number(pd), pv: Number(pv), maxUses: Number(maxUses), active }),
|
||||
})
|
||||
if ((await res.json()).success) {
|
||||
setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2000)
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<tr className="team-center-table-tr">
|
||||
<td className="lefted separate">
|
||||
<span className="yellow-info">{promo.code}</span>
|
||||
<p className="third-brown small-font">
|
||||
{t('promoUses')}: {promo.uses}/{promo.max_uses} · {t('promoRedemptions')}: {promo.redemptions}
|
||||
{promo.expires_at ? ` · ${new Date(promo.expires_at).toLocaleString('es-ES')}` : ''}
|
||||
</p>
|
||||
</td>
|
||||
<td className="real-info-box">
|
||||
<label className="small-font">{t('promoPd')} <input type="number" min="0" value={pd} onChange={(e) => setPd(e.target.value)} className="admin-mini-input" /></label>{' '}
|
||||
<label className="small-font">{t('promoPv')} <input type="number" min="0" value={pv} onChange={(e) => setPv(e.target.value)} className="admin-mini-input" /></label>{' '}
|
||||
<label className="small-font">{t('promoMaxUses')} <input type="number" min="1" value={maxUses} onChange={(e) => setMaxUses(e.target.value)} className="admin-mini-input" /></label>{' '}
|
||||
<label className="small-font"><input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} /> {t('promoActive')}</label>
|
||||
</td>
|
||||
<td className="real-info-box">
|
||||
<button onClick={save} disabled={busy} className="nw-tool-btn">{saved ? t('saved') : t('save')}</button>{' '}
|
||||
<button onClick={onDelete} className="nw-tool-btn red-info2">{t('delete')}</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from '@/i18n/navigation'
|
||||
|
||||
function promoError(error?: string): string {
|
||||
switch (error) {
|
||||
case 'missingCode':
|
||||
return 'Escribe un código de promoción.'
|
||||
case 'notFound':
|
||||
return 'El código no existe o ya no está disponible.'
|
||||
case 'expired':
|
||||
return 'Este código ha caducado.'
|
||||
case 'exhausted':
|
||||
return 'Este código ya ha alcanzado su límite de usos.'
|
||||
case 'alreadyUsed':
|
||||
return 'Ya has canjeado este código.'
|
||||
case 'notAuthenticated':
|
||||
return 'Tu sesión ha expirado. Inicia sesión de nuevo.'
|
||||
default:
|
||||
return 'No se pudo canjear el código. Inténtalo de nuevo.'
|
||||
}
|
||||
}
|
||||
|
||||
export function PromoCodeForm() {
|
||||
const router = useRouter()
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault()
|
||||
if (busy || !code.trim()) return
|
||||
setBusy(true)
|
||||
setMessage(null)
|
||||
try {
|
||||
const res = await fetch('/api/promo/redeem', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ code: code.trim() }),
|
||||
})
|
||||
const data: { success?: boolean; error?: string; pd?: number; pv?: number } = await res.json()
|
||||
if (data.success) {
|
||||
const parts: string[] = []
|
||||
if (data.pd) parts.push(`${data.pd} PD`)
|
||||
if (data.pv) parts.push(`${data.pv} PV`)
|
||||
const reward = parts.length ? parts.join(' y ') : 'la recompensa'
|
||||
setMessage({ ok: true, text: `¡Código canjeado! Has recibido ${reward}.` })
|
||||
setCode('')
|
||||
router.refresh()
|
||||
} else {
|
||||
setMessage({ ok: false, text: promoError(data.error) })
|
||||
}
|
||||
} catch {
|
||||
setMessage({ ok: false, text: promoError() })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="centered">
|
||||
<br />
|
||||
<form onSubmit={handleSubmit} acceptCharset="utf-8">
|
||||
<input
|
||||
type="text"
|
||||
maxLength={64}
|
||||
placeholder="Escribe tu código de promoción"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<br />
|
||||
<button type="submit" className="dnt-button" disabled={busy || !code.trim()}>
|
||||
{busy ? 'Canjeando…' : 'CANJEAR CÓDIGO'}
|
||||
</button>
|
||||
</form>
|
||||
<hr />
|
||||
<div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
|
||||
{message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Turnstile } from '@/components/Turnstile'
|
||||
|
||||
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: string[]; 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>
|
||||
<select value={character} onChange={(e) => setCharacter(e.target.value)} required>
|
||||
<option disabled value="">Selecciona un personaje</option>
|
||||
{characters.map((c) => <option key={c} value={c}>{c}</option>)}
|
||||
</select>
|
||||
</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: string[]; 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>
|
||||
<select value={character} onChange={(e) => setCharacter(e.target.value)} required>
|
||||
<option disabled value="">Selecciona un personaje</option>
|
||||
{characters.map((c) => <option key={c} value={c}>{c}</option>)}
|
||||
</select>
|
||||
</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: string[] }) {
|
||||
// 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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from '@/i18n/navigation'
|
||||
|
||||
function transferError(error?: string): string {
|
||||
switch (error) {
|
||||
case 'missingFields':
|
||||
return 'Rellena el personaje de destino, la cantidad y el token de seguridad.'
|
||||
case 'invalidAmount':
|
||||
return 'La cantidad debe ser un número entero mayor que 0.'
|
||||
case 'invalidToken':
|
||||
return 'El token de seguridad no es válido.'
|
||||
case 'characterNotFound':
|
||||
return 'No existe ningún personaje con ese nombre.'
|
||||
case 'sameAccount':
|
||||
return 'No puedes transferirte PD a tu propia cuenta.'
|
||||
case 'insufficientFunds':
|
||||
return 'No tienes suficientes PD para realizar esta transferencia.'
|
||||
case 'notAuthenticated':
|
||||
return 'Tu sesión ha expirado. Inicia sesión de nuevo.'
|
||||
default:
|
||||
return 'No se pudo completar la transferencia. Inténtalo de nuevo.'
|
||||
}
|
||||
}
|
||||
|
||||
export function TransferDPointsForm({ balance }: { balance: number }) {
|
||||
const router = useRouter()
|
||||
const [character, setCharacter] = useState('')
|
||||
const [amount, setAmount] = useState('')
|
||||
const [token, setToken] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
|
||||
if (balance <= 0) {
|
||||
return (
|
||||
<div className="centered">
|
||||
<br />
|
||||
<br />
|
||||
<span>No tienes PD</span>
|
||||
<br />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
const n = Number(amount)
|
||||
if (!character.trim() || !token.trim()) {
|
||||
setMessage({ ok: false, text: transferError('missingFields') })
|
||||
return
|
||||
}
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
setMessage({ ok: false, text: transferError('invalidAmount') })
|
||||
return
|
||||
}
|
||||
if (n > balance) {
|
||||
setMessage({ ok: false, text: transferError('insufficientFunds') })
|
||||
return
|
||||
}
|
||||
if (!window.confirm(`Vas a transferir ${n} PD al personaje "${character.trim()}".\nEsta acción no es reversible. ¿Deseas continuar?`)) return
|
||||
|
||||
setBusy(true)
|
||||
setMessage(null)
|
||||
try {
|
||||
const res = await fetch('/api/dpoints/transfer', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ character: character.trim(), amount: n, token: token.trim() }),
|
||||
})
|
||||
const data: { success?: boolean; error?: string } = await res.json()
|
||||
if (data.success) {
|
||||
setMessage({ ok: true, text: `Has transferido ${n} PD al personaje "${character.trim()}".` })
|
||||
setCharacter('')
|
||||
setAmount('')
|
||||
setToken('')
|
||||
router.refresh()
|
||||
} else {
|
||||
setMessage({ ok: false, text: transferError(data.error) })
|
||||
}
|
||||
} catch {
|
||||
setMessage({ ok: false, text: transferError() })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="centered">
|
||||
<br />
|
||||
<p className="yellow-info centered">Tienes {balance} PD disponibles</p>
|
||||
<br />
|
||||
<form onSubmit={handleSubmit} acceptCharset="utf-8">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Nombre del personaje de destino"
|
||||
value={character}
|
||||
onChange={(e) => setCharacter(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<br />
|
||||
<input
|
||||
type="number"
|
||||
placeholder="Cantidad de PD"
|
||||
min="1"
|
||||
max={balance}
|
||||
step="1"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<br />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Token de seguridad"
|
||||
maxLength={6}
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<br />
|
||||
<button type="submit" className="transfer-button" disabled={busy}>
|
||||
{busy ? 'Transfiriendo…' : 'TRANSFERIR PD'}
|
||||
</button>
|
||||
</form>
|
||||
<hr />
|
||||
<div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
|
||||
{message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user