send-gift: permitir pagar con PV (puntos de voto), más caro que PD
Solo en /send-gift se añade una 4ª forma de pago: PV (vote points, gratis por votar). Cuesta más que PD para preservar su valor: coste_PV = coste_PD × VP_PRICE_FACTOR (=2, configurable en lib/pay-with-dpoints). - lib/dpoints: getVPointsBalance, creditVPoints y spendVPoints (débito atómico del campo vp, con FOR UPDATE), espejo de las de PD. - lib/pay-with-dpoints: VP_PRICE_FACTOR, vpointsCost() y payServiceWithVPoints() (descuenta PV, ejecuta el envío y reembolsa si falla). - gift/checkout: rama provider='vp' (además de 'pd'). - service-success: la entrega inmediata cubre 'pd' y 'vp'. - PaymentMethodSelect: opción VP opcional (solo si el form pasa vpBalance); muestra coste en PV, insuficiencia y el saldo VP. - SendGiftForm + página: pasan el saldo VP. - i18n Pay: vp, vpCost, insufficientVp, balanceVp, errors.insufficientVp (es/en). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,7 @@ import { getTranslations, setRequestLocale } from 'next-intl/server'
|
||||
import { redirect, Link } from '@/i18n/navigation'
|
||||
import { getSession } from '@/lib/session'
|
||||
import { getGameCharacters } from '@/lib/characters'
|
||||
import { getDPointsBalance } from '@/lib/dpoints'
|
||||
import { getDPointsBalance, getVPointsBalance } from '@/lib/dpoints'
|
||||
import { getGiftCatalog } from '@/lib/gift'
|
||||
import { PageShell } from '@/components/PageShell'
|
||||
import { ServiceBox } from '@/components/ServiceBox'
|
||||
@@ -27,10 +27,11 @@ export default async function SendGiftPage({ params }: { params: Promise<{ local
|
||||
if (!session.bnetId) redirect({ href: '/log-in', locale })
|
||||
if (!session.username) redirect({ href: '/select-account', locale })
|
||||
|
||||
const [chars, catalog, pdBalance] = await Promise.all([
|
||||
const [chars, catalog, pdBalance, vpBalance] = await Promise.all([
|
||||
getGameCharacters(session.accountId!),
|
||||
getGiftCatalog(),
|
||||
getDPointsBalance(session.accountId!),
|
||||
getVPointsBalance(session.accountId!),
|
||||
])
|
||||
const currency = process.env.SUMUP_CURRENCY === 'EUR' ? '€' : process.env.SUMUP_CURRENCY || '€'
|
||||
|
||||
@@ -70,6 +71,7 @@ export default async function SendGiftPage({ params }: { params: Promise<{ local
|
||||
catalog={catalog}
|
||||
currency={currency}
|
||||
pdBalance={pdBalance}
|
||||
vpBalance={vpBalance}
|
||||
/>
|
||||
</ServiceBox>
|
||||
</PageShell>
|
||||
|
||||
@@ -22,8 +22,8 @@ export default async function ServiceSuccessPage({
|
||||
let status: 'delivered' | 'already' | 'error' = 'error'
|
||||
let okName: string | null = null
|
||||
let service = urlService ?? null
|
||||
if (provider === 'pd') {
|
||||
// Pago con saldo PD: la entrega ya se ejecutó en el checkout; aquí solo se muestra.
|
||||
if (provider === 'pd' || provider === 'vp') {
|
||||
// Pago con saldo PD/PV: la entrega ya se ejecutó en el checkout; aquí solo se muestra.
|
||||
status = 'delivered'
|
||||
okName = name ?? null
|
||||
} else if (provider === 'sumup' && ref) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { getGameCharacters, getAccountIdByCharacterName } from '@/lib/characters
|
||||
import { checkSecurityToken } from '@/lib/security-token'
|
||||
import { createSumUpCheckout, sumupConfigured } from '@/lib/sumup'
|
||||
import { priceCart, isValidCharName, sendGiftByMail, type CartLine } from '@/lib/gift'
|
||||
import { payServiceWithDPoints } from '@/lib/pay-with-dpoints'
|
||||
import { payServiceWithDPoints, payServiceWithVPoints } from '@/lib/pay-with-dpoints'
|
||||
|
||||
/**
|
||||
* Inicia el pago (SumUp) de un regalo. Condiciones:
|
||||
@@ -62,16 +62,18 @@ export async function POST(request: Request) {
|
||||
const site = process.env.SITE_URL || ''
|
||||
const items = priced.lines.map((l) => ({ i: l.itemId, q: l.qty }))
|
||||
|
||||
// Pago con saldo PD: se descuenta el saldo y se envía el regalo al momento.
|
||||
if (String(body.provider) === 'pd') {
|
||||
const r = await payServiceWithDPoints(session.accountId, priced.total, () =>
|
||||
sendGiftByMail(destination, source, items),
|
||||
)
|
||||
if (!r.success) return Response.json({ success: false, error: r.error, message: 'No se pudo completar el pago con PD.' })
|
||||
// Pago con saldo PD o PV: se descuenta el saldo y se envía el regalo al momento.
|
||||
// PV es más caro que PD (son puntos gratis por votar).
|
||||
if (String(body.provider) === 'pd' || String(body.provider) === 'vp') {
|
||||
const useVp = String(body.provider) === 'vp'
|
||||
const r = useVp
|
||||
? await payServiceWithVPoints(session.accountId, priced.total, () => sendGiftByMail(destination, source, items))
|
||||
: await payServiceWithDPoints(session.accountId, priced.total, () => sendGiftByMail(destination, source, items))
|
||||
if (!r.success) return Response.json({ success: false, error: r.error, message: 'No se pudo completar el pago.' })
|
||||
const locale = String(body.locale) === 'en' ? 'en' : 'es'
|
||||
return Response.json({
|
||||
success: true,
|
||||
url: `${site}/${locale}/service-success?service=send-gift&provider=pd&name=${encodeURIComponent(destination)}`,
|
||||
url: `${site}/${locale}/service-success?service=send-gift&provider=${useVp ? 'vp' : 'pd'}&name=${encodeURIComponent(destination)}`,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -2,17 +2,25 @@
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
export type PayMethod = 'pd' | 'stripe' | 'sumup'
|
||||
export type PayMethod = 'pd' | 'stripe' | 'sumup' | 'vp'
|
||||
|
||||
// 100 PD = 1 € (igual que PD_PER_UNIT en lib/dpoints, que no se importa aquí
|
||||
// para no arrastrar el acceso a BD al bundle del cliente).
|
||||
const PD_PER_UNIT = 100
|
||||
// Los PV cuestan este factor por el coste en PD (igual que VP_PRICE_FACTOR en
|
||||
// lib/pay-with-dpoints). Mantener sincronizados.
|
||||
const VP_PRICE_FACTOR = 2
|
||||
|
||||
/** Coste en PD (redondeado) de un precio en euros. */
|
||||
export function pdCostOf(priceEur: number): number {
|
||||
return Math.round(priceEur * PD_PER_UNIT)
|
||||
}
|
||||
|
||||
/** Coste en PV de un precio en euros (más caro que en PD). */
|
||||
export function vpCostOf(priceEur: number): number {
|
||||
return pdCostOf(priceEur) * VP_PRICE_FACTOR
|
||||
}
|
||||
|
||||
/**
|
||||
* Selector de forma de pago: saldo PD, tarjeta (Stripe) o tarjeta (SumUp).
|
||||
* Muestra el coste de cada método y desactiva PD si no hay saldo suficiente.
|
||||
@@ -22,11 +30,13 @@ export function PaymentMethodSelect({
|
||||
onChange,
|
||||
priceEur,
|
||||
pdBalance,
|
||||
vpBalance,
|
||||
}: {
|
||||
value: PayMethod
|
||||
onChange: (m: PayMethod) => void
|
||||
priceEur: number
|
||||
pdBalance: number
|
||||
vpBalance?: number // si se pasa, muestra la opción de pagar con PV (solo /send-gift)
|
||||
}) {
|
||||
const t = useTranslations('Pay')
|
||||
const cost = pdCostOf(priceEur)
|
||||
@@ -39,9 +49,24 @@ export function PaymentMethodSelect({
|
||||
sub: canPd ? t('pdCost', { cost }) : t('insufficient', { cost }),
|
||||
disabled: !canPd,
|
||||
},
|
||||
]
|
||||
|
||||
// Opción PV: solo cuando el formulario la habilita pasando el saldo VP.
|
||||
if (vpBalance !== undefined) {
|
||||
const vCost = vpCostOf(priceEur)
|
||||
const canVp = vpBalance >= vCost && vCost > 0
|
||||
options.push({
|
||||
id: 'vp',
|
||||
label: t('vp'),
|
||||
sub: canVp ? t('vpCost', { cost: vCost }) : t('insufficientVp', { cost: vCost }),
|
||||
disabled: !canVp,
|
||||
})
|
||||
}
|
||||
|
||||
options.push(
|
||||
{ id: 'stripe', label: t('stripe'), sub: t('eur', { price: priceEur }) },
|
||||
{ id: 'sumup', label: t('sumup'), sub: t('eur', { price: priceEur }) },
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="pay-method-select">
|
||||
@@ -65,7 +90,10 @@ export function PaymentMethodSelect({
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="third-brown pay-method-balance">{t('balance', { balance: pdBalance })}</p>
|
||||
<p className="third-brown pay-method-balance">
|
||||
{t('balance', { balance: pdBalance })}
|
||||
{vpBalance !== undefined ? ` · ${t('balanceVp', { balance: vpBalance })}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -51,11 +51,13 @@ export function SendGiftForm({
|
||||
catalog,
|
||||
currency = '€',
|
||||
pdBalance = 0,
|
||||
vpBalance = 0,
|
||||
}: {
|
||||
characters: CharOption[]
|
||||
catalog: GiftCategory[]
|
||||
currency?: string
|
||||
pdBalance?: number
|
||||
vpBalance?: number
|
||||
}) {
|
||||
const t = useTranslations('CharService')
|
||||
const tpay = useTranslations('Pay')
|
||||
@@ -260,7 +262,7 @@ export function SendGiftForm({
|
||||
<p>
|
||||
{t.rich('sendGift.total', { total, currency, s: (c) => <span className="yellow-info">{c}</span> })}
|
||||
</p>
|
||||
{total > 0 && <PaymentMethodSelect value={method} onChange={setMethod} priceEur={total} pdBalance={pdBalance} />}
|
||||
{total > 0 && <PaymentMethodSelect value={method} onChange={setMethod} priceEur={total} pdBalance={pdBalance} vpBalance={vpBalance} />}
|
||||
<br />
|
||||
<button
|
||||
type="submit"
|
||||
|
||||
@@ -40,6 +40,73 @@ export async function getDPointsBalance(accountId: number): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Saldo de PV (vote points, ganados al votar) de una cuenta. 0 si no tiene fila. */
|
||||
export async function getVPointsBalance(accountId: number): Promise<number> {
|
||||
if (!accountId) return 0
|
||||
try {
|
||||
const [rows] = await db(DB.default).query<RowDataPacket[]>(
|
||||
'SELECT vp FROM home_api_points WHERE accountID = ?',
|
||||
[accountId],
|
||||
)
|
||||
return rows[0] ? Number(rows[0].vp) : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/** Acredita PV (vote points) a una cuenta (upsert). Se usa para reembolsos. */
|
||||
export async function creditVPoints(accountId: number, points: number): Promise<boolean> {
|
||||
if (!accountId || !(points > 0)) return false
|
||||
try {
|
||||
await db(DB.default).query(
|
||||
'INSERT INTO home_api_points (accountID, vp, dp) VALUES (?, ?, 0) ON DUPLICATE KEY UPDATE vp = vp + ?',
|
||||
[accountId, points, points],
|
||||
)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Descuenta `points` PV del saldo de una cuenta de forma atómica (bloqueo de
|
||||
* fila). Devuelve `insufficientFunds` si no hay saldo suficiente. Si la acción
|
||||
* posterior falla, reembolsa con `creditVPoints`.
|
||||
*/
|
||||
export async function spendVPoints(
|
||||
accountId: number,
|
||||
points: number,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
if (!accountId || !Number.isInteger(points) || points <= 0) {
|
||||
return { success: false, error: 'invalidRequest' }
|
||||
}
|
||||
const conn = await db(DB.default).getConnection()
|
||||
try {
|
||||
await conn.beginTransaction()
|
||||
const [src] = await conn.query<RowDataPacket[]>(
|
||||
'SELECT vp FROM home_api_points WHERE accountID = ? FOR UPDATE',
|
||||
[accountId],
|
||||
)
|
||||
const balance = src[0] ? Number(src[0].vp) : 0
|
||||
if (balance < points) {
|
||||
await conn.rollback()
|
||||
return { success: false, error: 'insufficientFunds' }
|
||||
}
|
||||
await conn.query('UPDATE home_api_points SET vp = vp - ? WHERE accountID = ?', [points, accountId])
|
||||
await conn.commit()
|
||||
return { success: true }
|
||||
} catch {
|
||||
try {
|
||||
await conn.rollback()
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return { success: false, error: 'genericError' }
|
||||
} finally {
|
||||
conn.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfiere `points` PD desde una cuenta de origen a una de destino de forma
|
||||
* atómica (transacción con bloqueo de fila del origen). Es irreversible.
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import { spendDPoints, creditDPoints, PD_PER_UNIT } from './dpoints'
|
||||
import { spendDPoints, creditDPoints, spendVPoints, creditVPoints, PD_PER_UNIT } from './dpoints'
|
||||
|
||||
/**
|
||||
* Los PV (vote points) son gratis (se ganan votando), así que pagar con PV es
|
||||
* más caro que con PD: cuesta este factor por el coste en PD. Cambiar aquí.
|
||||
*/
|
||||
export const VP_PRICE_FACTOR = 2
|
||||
|
||||
/** Coste en PD de un precio en euros (100 PD = 1 €). */
|
||||
export function dpointsCost(priceEur: number): number {
|
||||
return Math.round(priceEur * PD_PER_UNIT)
|
||||
}
|
||||
|
||||
/** Coste en PV de un precio en euros (coste PD × VP_PRICE_FACTOR). */
|
||||
export function vpointsCost(priceEur: number): number {
|
||||
return dpointsCost(priceEur) * VP_PRICE_FACTOR
|
||||
}
|
||||
|
||||
/**
|
||||
* Paga un servicio con el saldo PD: descuenta el coste de forma atómica y
|
||||
* ejecuta la acción al momento (sin pasarela). Si la ejecución falla, reembolsa
|
||||
@@ -33,3 +44,32 @@ export async function payServiceWithDPoints(
|
||||
}
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Paga un servicio con el saldo PV: descuenta el coste (más caro que en PD) y
|
||||
* ejecuta la acción al momento. Reembolsa si falla. Devuelve `insufficientVp`
|
||||
* si no hay saldo suficiente.
|
||||
*/
|
||||
export async function payServiceWithVPoints(
|
||||
accountId: number,
|
||||
priceEur: number,
|
||||
fulfill: () => Promise<boolean>,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
const cost = vpointsCost(priceEur)
|
||||
if (!(cost > 0)) return { success: false, error: 'invalidRequest' }
|
||||
const spent = await spendVPoints(accountId, cost)
|
||||
if (!spent.success) {
|
||||
return { success: false, error: spent.error === 'insufficientFunds' ? 'insufficientVp' : 'genericError' }
|
||||
}
|
||||
let ok = false
|
||||
try {
|
||||
ok = await fulfill()
|
||||
} catch {
|
||||
ok = false
|
||||
}
|
||||
if (!ok) {
|
||||
await creditVPoints(accountId, cost) // reembolso si no se pudo ejecutar
|
||||
return { success: false, error: 'fulfillFailed' }
|
||||
}
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
@@ -1920,7 +1920,12 @@
|
||||
"fulfillFailed": "The service could not be completed. Your PD balance has been refunded.",
|
||||
"notConfigured": "This payment method is not available right now.",
|
||||
"invalidRequest": "Invalid request.",
|
||||
"genericError": "An error occurred. Please try again."
|
||||
}
|
||||
"genericError": "An error occurred. Please try again.",
|
||||
"insufficientVp": "You don't have enough vote points for this service."
|
||||
},
|
||||
"vp": "Vote points",
|
||||
"vpCost": "{cost} VP",
|
||||
"insufficientVp": "Insufficient balance ({cost} VP)",
|
||||
"balanceVp": "VP: {balance}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1920,7 +1920,12 @@
|
||||
"fulfillFailed": "No se pudo completar el servicio. Se te ha devuelto el saldo PD.",
|
||||
"notConfigured": "Esta forma de pago no está disponible ahora mismo.",
|
||||
"invalidRequest": "Solicitud no válida.",
|
||||
"genericError": "Ha ocurrido un error. Inténtalo de nuevo."
|
||||
}
|
||||
"genericError": "Ha ocurrido un error. Inténtalo de nuevo.",
|
||||
"insufficientVp": "No tienes saldo PV suficiente para este servicio."
|
||||
},
|
||||
"vp": "Saldo PV",
|
||||
"vpCost": "{cost} PV",
|
||||
"insufficientVp": "Saldo insuficiente ({cost} PV)",
|
||||
"balanceVp": "PV: {balance}"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user