Files
NightSpire/web-next/lib/vote.ts
T
Inna f9609aad99 Página de votación de usuario (/vote-points) + enlace en cabecera
- lib/vote.ts: getVoteSites (home_votesite), registerVote (cooldown 12h30 vía
  home_votelog, acredita PV en home_api_points, registra el voto).
- Route /api/vote (POST {url}, guard sesión). Página /vote-points (VotePanel:
  abre el sitio + registra el voto, muestra PV/cooldown). Enlace "Votar" en cabecera.
- Cierra el ciclo con el admin de sitios de voto.

Verificado: /vote-points 200, POST 401 sin sesión; lógica probada: voto -> +PV,
segundo voto -> cooldown 12h29m.

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

69 lines
2.2 KiB
TypeScript

import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
const COOLDOWN_MS = (12 * 60 + 30) * 60 * 1000 // 12h 30m
export interface VoteSite {
id: number
name: string
url: string
image_url: string
points: number
}
export interface VoteResult {
success: boolean
error?: string
points?: number
siteName?: string
hours?: number
minutes?: number
}
export async function getVoteSites(): Promise<VoteSite[]> {
try {
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 }))
} catch {
return []
}
}
export async function registerVote(accountId: number, url: string): Promise<VoteResult> {
const [siteRows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT id, name, points FROM home_votesite WHERE url = ?',
[url],
)
const site = siteRows[0]
if (!site) return { success: false, error: 'siteNotFound' }
const [last] = await db(DB.default).query<RowDataPacket[]>(
'SELECT created_at FROM home_votelog WHERE account_id = ? AND vote_site_id = ? ORDER BY created_at DESC LIMIT 1',
[accountId, site.id],
)
if (last[0]) {
const diff = Date.now() - new Date(last[0].created_at).getTime()
if (diff < COOLDOWN_MS) {
const rem = COOLDOWN_MS - diff
return { success: false, error: 'cooldown', hours: Math.floor(rem / 3600000), minutes: Math.floor((rem % 3600000) / 60000) }
}
}
// Acreditar PV
const [pts] = await db(DB.default).query<RowDataPacket[]>('SELECT id FROM home_api_points WHERE accountID = ?', [accountId])
if (pts[0]) {
await db(DB.default).query('UPDATE home_api_points SET vp = vp + ? WHERE accountID = ?', [site.points, accountId])
} else {
await db(DB.default).query('INSERT INTO home_api_points (accountID, vp, dp) VALUES (?, ?, 0)', [accountId, site.points])
}
await db(DB.default).query(
'INSERT INTO home_votelog (account_id, vote_site_id, created_at, last_vote_time, processed) VALUES (?, ?, NOW(), NOW(), 0)',
[accountId, site.id],
)
return { success: true, points: site.points, siteName: site.name }
}