Files
Inna 14125dbd72 Formularios: noValidate en todos para usar red-response del sitio
Desactiva la validación nativa del navegador ("Rellene este campo", formato de
email) en el resto de formularios (recover, reset-password, trade-points,
rename-guild, transfer-dp, gold, promo, transfer, quest, send-gift, 2FA, restore).
Los errores se muestran como red-form-response (por validación en cliente o del
servidor), consistente con login y create-account. Botones ya gateados por campos.

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

84 lines
2.6 KiB
TypeScript

'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
function promoErrorKey(error?: string): string {
switch (error) {
case 'missingCode':
case 'notFound':
case 'expired':
case 'exhausted':
case 'alreadyUsed':
case 'notAuthenticated':
return error
default:
return 'generic'
}
}
export function PromoCodeForm() {
const t = useTranslations('Points')
const promoError = (error?: string) => t(`promo.errors.${promoErrorKey(error)}`)
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(t('promo.rewardPd', { pd: data.pd }))
if (data.pv) parts.push(t('promo.rewardPv', { pv: data.pv }))
const reward = parts.length ? parts.join(` ${t('promo.and')} `) : t('promo.rewardDefault')
setMessage({ ok: true, text: t('promo.success', { 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 noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
<input
type="text"
maxLength={64}
placeholder={t('promo.placeholder')}
value={code}
onChange={(e) => setCode(e.target.value)}
required
/>
<br />
<button type="submit" className="dnt-button" disabled={busy || !code.trim()}>
{busy ? t('promo.redeeming') : t('promo.redeemButton')}
</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>
)
}