Admin: gestión de sitios de voto (home_votesite)

- lib/admin-votes.ts: listVoteSites / createVoteSite / deleteVoteSite.
- Routes /api/admin/votes (POST) y /api/admin/votes/[id] (DELETE), guard isAdmin.
- Página /admin/votes (AdminVotesManager: crear/listar/borrar) + enlace en dashboard.
- Conecta con la página de votación (/vote-points) ya existente.

Verificado: guardas (307/403), CRUD del write layer OK (con env cargado).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-13 00:03:06 +00:00
parent 0f71e1f4d9
commit 934bee2aec
8 changed files with 182 additions and 2 deletions
+5
View File
@@ -27,6 +27,11 @@ export default async function AdminPage({ params }: { params: Promise<{ locale:
{t('managePrices')}
</Link>
</li>
<li>
<Link href="/admin/votes" className="text-sky-400 hover:underline">
{t('manageVotes')}
</Link>
</li>
</ul>
</main>
)
@@ -0,0 +1,24 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { listVoteSites } from '@/lib/admin-votes'
import { AdminVotesManager } from '@/components/AdminVotesManager'
export const dynamic = 'force-dynamic'
export default async function AdminVotesPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
setRequestLocale(locale)
const t = await getTranslations('Admin')
const session = await getSession()
if (!session.bnetId) redirect({ href: '/login', locale })
if (!(await isAdmin(session))) redirect({ href: '/', locale })
const sites = await listVoteSites()
return (
<main className="mx-auto max-w-3xl px-4 py-8">
<h1 className="mb-6 text-2xl font-bold text-amber-500">{t('votes')}</h1>
<AdminVotesManager initial={sites} />
</main>
)
}
@@ -0,0 +1,11 @@
import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { deleteVoteSite } from '@/lib/admin-votes'
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const session = await getSession()
if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
const { id } = await params
await deleteVoteSite(Number(id))
return Response.json({ success: true })
}
+17
View File
@@ -0,0 +1,17 @@
import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { createVoteSite } from '@/lib/admin-votes'
export async function POST(request: Request) {
const session = await getSession()
if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
let b: Record<string, unknown> = {}
try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
const name = String(b.name ?? '').trim()
const url = String(b.url ?? '').trim()
const imageUrl = String(b.imageUrl ?? '').trim()
const points = Number(b.points)
if (!name || !url || !(points >= 0)) return Response.json({ success: false, error: 'emptyError' })
const id = await createVoteSite(name, url, imageUrl, points)
return Response.json({ success: true, id })
}
+80
View File
@@ -0,0 +1,80 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import type { VoteSite } from '@/lib/admin-votes'
export function AdminVotesManager({ initial }: { initial: VoteSite[] }) {
const t = useTranslations('Admin')
const [sites, setSites] = useState(initial)
const [form, setForm] = useState({ name: '', url: '', imageUrl: '', points: '1' })
const [busy, setBusy] = useState(false)
function upd(k: string, v: string) {
setForm((f) => ({ ...f, [k]: v }))
}
async function create(e: React.FormEvent) {
e.preventDefault()
if (busy || !form.name.trim() || !form.url.trim()) return
setBusy(true)
try {
const res = await fetch('/api/admin/votes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ ...form, points: Number(form.points) }),
})
const data: { success?: boolean; id?: number } = await res.json()
if (data.success && data.id) {
setSites([
...sites,
{ id: data.id, name: form.name, url: form.url, image_url: form.imageUrl, points: Number(form.points) },
])
setForm({ name: '', url: '', imageUrl: '', points: '1' })
}
} finally {
setBusy(false)
}
}
async function remove(id: number) {
if (!confirm(t('confirmDelete'))) return
const res = await fetch(`/api/admin/votes/${id}`, { method: 'DELETE', credentials: 'same-origin' })
if ((await res.json()).success) setSites(sites.filter((s) => s.id !== id))
}
const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
return (
<div>
<form onSubmit={create} className="mb-8 space-y-3 rounded-lg border border-amber-900/60 bg-[#241812] p-4">
<input value={form.name} onChange={(e) => upd('name', e.target.value)} placeholder={t('voteName')} className={field} />
<input value={form.url} onChange={(e) => upd('url', e.target.value)} placeholder={t('voteUrl')} className={field} />
<input value={form.imageUrl} onChange={(e) => upd('imageUrl', e.target.value)} placeholder={t('voteImage')} className={field} />
<input type="number" min="0" value={form.points} onChange={(e) => upd('points', e.target.value)} placeholder={t('votePoints')} className={field} />
<button type="submit" disabled={busy} className="rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('creating') : t('create')}
</button>
</form>
{sites.length === 0 ? (
<p className="text-amber-200/70">{t('noVotes')}</p>
) : (
<ul className="divide-y divide-amber-900/40">
{sites.map((s) => (
<li key={s.id} className="flex items-center justify-between gap-4 py-3">
<div>
<p className="font-semibold text-amber-300">{s.name}</p>
<p className="text-xs text-amber-200/50">
{s.points} PV · {s.url}
</p>
</div>
<button onClick={() => remove(s.id)} className="rounded border border-red-900/60 px-3 py-1 text-sm text-red-400 hover:bg-red-950/40">
{t('delete')}
</button>
</li>
))}
</ul>
)}
</div>
)
}
+29
View File
@@ -0,0 +1,29 @@
import type { RowDataPacket, ResultSetHeader } from 'mysql2'
import { db, DB } from './db'
export interface VoteSite {
id: number
name: string
url: string
image_url: string
points: number
}
export async function listVoteSites(): Promise<VoteSite[]> {
const [rows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT id, name, url, image_url, points FROM home_votesite ORDER BY id',
)
return rows.map((r) => ({ id: r.id, name: r.name, url: r.url, image_url: r.image_url, points: r.points }))
}
export async function createVoteSite(name: string, url: string, imageUrl: string, points: number): Promise<number> {
const [res] = await db(DB.default).query<ResultSetHeader>(
'INSERT INTO home_votesite (name, url, image_url, points, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
[name, url, imageUrl, points],
)
return res.insertId
}
export async function deleteVoteSite(id: number): Promise<void> {
await db(DB.default).query('DELETE FROM home_votesite WHERE id = ?', [id])
}
+8 -1
View File
@@ -292,6 +292,13 @@
"svc_change-race": "Change race",
"svc_change-faction": "Change faction",
"svc_level-up": "Level up to 80",
"svc_transfer": "Transfer character"
"svc_transfer": "Transfer character",
"manageVotes": "Manage vote sites",
"votes": "Vote sites",
"voteName": "Name",
"voteUrl": "URL",
"voteImage": "Image URL",
"votePoints": "VP per vote",
"noVotes": "No vote sites."
}
}
+8 -1
View File
@@ -292,6 +292,13 @@
"svc_change-race": "Cambiar raza",
"svc_change-faction": "Cambiar facción",
"svc_level-up": "Subir a nivel 80",
"svc_transfer": "Transferir personaje"
"svc_transfer": "Transferir personaje",
"manageVotes": "Gestionar sitios de voto",
"votes": "Sitios de voto",
"voteName": "Nombre",
"voteUrl": "URL",
"voteImage": "URL de la imagen",
"votePoints": "PV por voto",
"noVotes": "No hay sitios de voto."
}
}