Files
NightSpire/web-next/components/PaidServiceForm.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

80 lines
3.0 KiB
TypeScript

'use client'
import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
import { PaymentMethodSelect, pdCostOf, type PayMethod } from '@/components/PaymentMethodSelect'
interface Props {
characters: CharOption[]
checkoutEndpoint: string
payLabel: string // texto de acción del botón
priceEur: number // precio del servicio en euros (para calcular el coste en PD)
pdBalance: number // saldo PD de la cuenta
buttonClass?: string
}
/** Selector de personaje + forma de pago (PD / Stripe / SumUp) + botón. */
export function PaidServiceForm({ characters, checkoutEndpoint, payLabel, priceEur, pdBalance, buttonClass = '' }: Props) {
const t = useTranslations('Services')
const tp = useTranslations('Pay')
const locale = useLocale()
const [character, setCharacter] = useState('')
const [method, setMethod] = useState<PayMethod>(pdBalance >= pdCostOf(priceEur) ? 'pd' : 'sumup')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
function msgFor(err?: string): string {
return err && tp.has(`errors.${err}`) ? tp(`errors.${err}`) : t('genericError')
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || !character) return
const amount = method === 'pd' ? tp('pdCost', { cost: pdCostOf(priceEur) }) : tp('eur', { price: priceEur })
if (!window.confirm(tp('confirm', { amount }))) return
setBusy(true)
setError(null)
try {
const res = await fetch(checkoutEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ character, 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 // éxito PD, o Checkout (Stripe/SumUp)
} else {
setError(data.message || msgFor(data.error))
setBusy(false)
}
} catch {
setError(t('genericError'))
setBusy(false)
}
}
if (characters.length === 0) {
return <p className="second-brown">{t('noCharactersYet')}</p>
}
return (
<div className="centered">
<p>{t('choose')}</p>
<br />
<form onSubmit={handleSubmit} acceptCharset="utf-8" noValidate>
<CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('selectCharacter')} />
<PaymentMethodSelect value={method} onChange={setMethod} priceEur={priceEur} pdBalance={pdBalance} />
<button type="submit" className={buttonClass} disabled={busy || !character}>
{busy ? t('processing') : payLabel}
</button>
</form>
<hr />
<div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
{error && <span className="red-form-response">{error}</span>}
</div>
</div>
)
}