Añadir /send-gift (Enviar regalo) pagado por SumUp
Envía ítems de la tienda por correo al personaje de un amigo, pagado por SumUp. lib/gift.ts (catálogo por categoría, priceCart con precios reales de BD, sendGiftByMail vía SOAP .send items troceado a 12/correo + anti-inyección); servicio send-gift en PAID_SERVICES; ruta dedicada /api/gift/checkout (origen propio, destino existe, token de seguridad, carrito); SendGiftForm + página con el diseño; i18n Paid[send-gift]; seed_giftitems.sql (4 cat, 8 ítems). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import type { Metadata } from 'next'
|
||||
import { setRequestLocale } from 'next-intl/server'
|
||||
import { redirect, Link } from '@/i18n/navigation'
|
||||
import { getSession } from '@/lib/session'
|
||||
import { getGameCharacters } from '@/lib/characters'
|
||||
import { getGiftCatalog } from '@/lib/gift'
|
||||
import { PageShell } from '@/components/PageShell'
|
||||
import { ServiceBox } from '@/components/ServiceBox'
|
||||
import { SendGiftForm } from '@/components/SendGiftForm'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export const metadata: Metadata = { title: 'Enviar regalo' }
|
||||
|
||||
export default async function SendGiftPage({ params }: { params: Promise<{ locale: string }> }) {
|
||||
const { locale } = await params
|
||||
setRequestLocale(locale)
|
||||
|
||||
const session = await getSession()
|
||||
if (!session.bnetId) redirect({ href: '/login', locale })
|
||||
if (!session.username) redirect({ href: '/select-account', locale })
|
||||
|
||||
const [chars, catalog] = await Promise.all([getGameCharacters(session.accountId!), getGiftCatalog()])
|
||||
const currency = process.env.SUMUP_CURRENCY === 'EUR' ? '€' : process.env.SUMUP_CURRENCY || '€'
|
||||
|
||||
return (
|
||||
<PageShell title="Enviar regalo">
|
||||
<ServiceBox>
|
||||
<br />
|
||||
<p>
|
||||
La herramienta <span>Enviar regalo</span> te permite enviar regalos a tus amigos.
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
Al elegir desde qué personaje se enviará el regalo y el personaje que lo recibirá, podrás ver la lista de
|
||||
objetos disponibles para enviar como regalo.
|
||||
</p>
|
||||
<p>Los objetos disponibles son los mismos de la tienda y puedes enviar varios objetos a la vez.</p>
|
||||
<br />
|
||||
<p>
|
||||
Al usar el botón ENVIAR REGALO se enviará un correo al personaje destino con los ítems seleccionados,
|
||||
indicando quién lo ha regalado. El pago se realiza mediante <span>SumUp</span>.
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
Si aún no tienes Token de seguridad, puedes solicitarlo{' '}
|
||||
<Link href="/security-token" target="_blank">
|
||||
aquí
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<br />
|
||||
<fieldset>
|
||||
<legend>NOTA</legend>
|
||||
<div className="separate2">
|
||||
<p>
|
||||
Por favor, asegúrate de haber escrito el nombre del personaje correcto ya que esta acción no es
|
||||
reversible una vez realizada.
|
||||
</p>
|
||||
</div>
|
||||
</fieldset>
|
||||
<br />
|
||||
|
||||
<SendGiftForm
|
||||
characters={chars.map((c) => ({ name: c.name, classCss: c.classCss }))}
|
||||
catalog={catalog}
|
||||
currency={currency}
|
||||
/>
|
||||
</ServiceBox>
|
||||
</PageShell>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { getSession } from '@/lib/session'
|
||||
import { getGameCharacters, getAccountIdByCharacterName } from '@/lib/characters'
|
||||
import { checkSecurityToken } from '@/lib/security-token'
|
||||
import { createSumUpCheckout, sumupConfigured } from '@/lib/sumup'
|
||||
import { priceCart, isValidCharName, type CartLine } from '@/lib/gift'
|
||||
|
||||
/**
|
||||
* Inicia el pago (SumUp) de un regalo. Condiciones:
|
||||
* - Sesión con cuenta de juego seleccionada.
|
||||
* - Personaje de ORIGEN: uno de tu cuenta.
|
||||
* - Personaje de DESTINO: un nombre válido que exista (el de un amigo).
|
||||
* - Token de seguridad válido.
|
||||
* - Carrito no vacío; el total se calcula con los precios REALES de la BD.
|
||||
* Al pagar, la reconciliación/return envía los ítems por correo (`.send items`).
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession()
|
||||
if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
|
||||
|
||||
let body: { source?: string; destination?: string; cart?: CartLine[]; security_token?: string; provider?: string } = {}
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
|
||||
}
|
||||
|
||||
const source = String(body.source ?? '')
|
||||
const destination = String(body.destination ?? '').trim()
|
||||
const token = String(body.security_token ?? '').trim()
|
||||
const cart = Array.isArray(body.cart) ? body.cart : []
|
||||
|
||||
if (!source || !destination || !token) {
|
||||
return Response.json({ success: false, message: 'Completa el personaje de origen, el de destino y el token de seguridad.' })
|
||||
}
|
||||
if (!isValidCharName(destination)) {
|
||||
return Response.json({ success: false, message: 'El nombre del personaje de destino no es válido.' })
|
||||
}
|
||||
|
||||
// Origen: debe pertenecer a tu cuenta.
|
||||
const chars = await getGameCharacters(session.accountId)
|
||||
if (!chars.find((c) => c.name === source)) {
|
||||
return Response.json({ success: false, message: 'El personaje de origen no pertenece a tu cuenta.' })
|
||||
}
|
||||
|
||||
// Destino: debe existir.
|
||||
const destAccount = await getAccountIdByCharacterName(destination)
|
||||
if (!destAccount) return Response.json({ success: false, message: 'El personaje de destino no existe.' })
|
||||
|
||||
// Token de seguridad.
|
||||
if (!(await checkSecurityToken(session.accountId, token))) {
|
||||
return Response.json({ success: false, message: 'El token de seguridad no es válido.' })
|
||||
}
|
||||
|
||||
// Carrito -> precio real (BD). Nunca se confía en el precio del cliente.
|
||||
const priced = await priceCart(cart)
|
||||
if (!priced || priced.total <= 0) {
|
||||
return Response.json({ success: false, message: 'Tu carrito está vacío o contiene objetos no válidos.' })
|
||||
}
|
||||
|
||||
if (String(body.provider) !== 'sumup' || !sumupConfigured()) {
|
||||
return Response.json({ success: false, error: 'notConfigured', message: 'El método de pago no está disponible ahora mismo.' })
|
||||
}
|
||||
|
||||
const site = process.env.SITE_URL || ''
|
||||
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
|
||||
const reference = randomUUID()
|
||||
const items = priced.lines.map((l) => ({ i: l.itemId, q: l.qty }))
|
||||
const description = `Regalo para ${destination} (${priced.lines.length} objeto${priced.lines.length === 1 ? '' : 's'})`
|
||||
|
||||
const r = await createSumUpCheckout({
|
||||
accountId: session.accountId,
|
||||
username: session.username || '',
|
||||
email: session.bnetEmail || '',
|
||||
acoreIp: ip,
|
||||
amount: priced.total,
|
||||
points: 0,
|
||||
reference,
|
||||
description,
|
||||
returnUrl: `${site}/service-success?service=send-gift&provider=sumup&ref=${reference}`,
|
||||
service: 'send-gift',
|
||||
characterName: destination,
|
||||
metadata: { sender: source, items: JSON.stringify(items), amount: String(priced.total) },
|
||||
})
|
||||
if (!r.success || !r.url) return Response.json({ success: false, error: r.error || 'sumupError', message: 'No se pudo iniciar el pago.' })
|
||||
return Response.json({ success: true, url: r.url })
|
||||
}
|
||||
Reference in New Issue
Block a user