feat(phase5): Add admin panel with JWT auth, questions CRUD, and calendar

- Add adminStore with Zustand for authentication state persistence
- Add adminApi service for all admin endpoints
- Add Login page with error handling and redirect
- Add AdminLayout with sidebar navigation and route protection
- Add Dashboard with stats and quick actions
- Add Questions page with full CRUD, filters, and AI generation modal
- Add Calendar page for scheduling questions by date
- Integrate admin routes in App.tsx with nested routing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-26 08:49:28 +00:00
parent 3e91305e46
commit 90fa220890
9 changed files with 1205 additions and 1 deletions

View File

@@ -1,19 +1,30 @@
import { Routes, Route } from 'react-router-dom' import { Routes, Route, Navigate } from 'react-router-dom'
import Home from './pages/Home' import Home from './pages/Home'
import Lobby from './pages/Lobby' import Lobby from './pages/Lobby'
import Game from './pages/Game' import Game from './pages/Game'
import Results from './pages/Results' import Results from './pages/Results'
import Replay from './pages/Replay' import Replay from './pages/Replay'
import { AdminLayout, Login, Dashboard, Questions, Calendar } from './pages/admin'
function App() { function App() {
return ( return (
<div className="min-h-screen"> <div className="min-h-screen">
<Routes> <Routes>
{/* Game routes */}
<Route path="/" element={<Home />} /> <Route path="/" element={<Home />} />
<Route path="/lobby/:roomCode" element={<Lobby />} /> <Route path="/lobby/:roomCode" element={<Lobby />} />
<Route path="/game/:roomCode" element={<Game />} /> <Route path="/game/:roomCode" element={<Game />} />
<Route path="/results/:roomCode" element={<Results />} /> <Route path="/results/:roomCode" element={<Results />} />
<Route path="/replay/:replayCode" element={<Replay />} /> <Route path="/replay/:replayCode" element={<Replay />} />
{/* Admin routes */}
<Route path="/admin/login" element={<Login />} />
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<Navigate to="dashboard" replace />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="questions" element={<Questions />} />
<Route path="calendar" element={<Calendar />} />
</Route>
</Routes> </Routes>
</div> </div>
) )

View File

@@ -0,0 +1,78 @@
import { Outlet, NavLink, useNavigate } from 'react-router-dom'
import { useAdminStore } from '../../stores/adminStore'
import { useEffect } from 'react'
const navItems = [
{ path: '/admin/dashboard', label: 'Dashboard', icon: '📊' },
{ path: '/admin/questions', label: 'Preguntas', icon: '❓' },
{ path: '/admin/calendar', label: 'Calendario', icon: '📅' },
]
export default function AdminLayout() {
const { isAuthenticated, username, logout } = useAdminStore()
const navigate = useNavigate()
// Protect routes
useEffect(() => {
if (!isAuthenticated) {
navigate('/admin/login')
}
}, [isAuthenticated, navigate])
if (!isAuthenticated) {
return null
}
const handleLogout = () => {
logout()
navigate('/admin/login')
}
return (
<div className="min-h-screen bg-gray-900 flex">
{/* Sidebar */}
<aside className="w-64 bg-gray-800 p-4 flex flex-col">
<div className="mb-8">
<h1 className="text-xl font-bold text-white">WebTriviasMulti</h1>
<p className="text-gray-400 text-sm">Admin Panel</p>
</div>
<nav className="flex-1 space-y-2">
{navItems.map((item) => (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) =>
`flex items-center gap-3 px-4 py-2 rounded transition-colors ${
isActive
? 'bg-blue-600 text-white'
: 'text-gray-400 hover:bg-gray-700 hover:text-white'
}`
}
>
<span>{item.icon}</span>
<span>{item.label}</span>
</NavLink>
))}
</nav>
<div className="border-t border-gray-700 pt-4 mt-4">
<div className="text-gray-400 text-sm mb-2">
Conectado como: <span className="text-white">{username}</span>
</div>
<button
onClick={handleLogout}
className="w-full py-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
>
Cerrar Sesión
</button>
</div>
</aside>
{/* Main content */}
<main className="flex-1 p-8 overflow-auto">
<Outlet />
</main>
</div>
)
}

View File

@@ -0,0 +1,236 @@
import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'
import { useAdminStore } from '../../stores/adminStore'
import { getQuestions, updateQuestion } from '../../services/adminApi'
interface Question {
id: number
category_id: number
question_text: string
correct_answer: string
difficulty: number
points: number
date_active: string | null
status: string
}
export default function Calendar() {
const { token } = useAdminStore()
const [questions, setQuestions] = useState<Question[]>([])
const [loading, setLoading] = useState(true)
const [selectedDate, setSelectedDate] = useState<string | null>(null)
const [currentMonth, setCurrentMonth] = useState(new Date())
useEffect(() => {
fetchQuestions()
}, [token])
const fetchQuestions = async () => {
if (!token) return
try {
const data = await getQuestions(token, undefined, 'approved')
setQuestions(data)
} catch (error) {
console.error('Error:', error)
} finally {
setLoading(false)
}
}
const assignDate = async (questionId: number, date: string) => {
if (!token) return
try {
await updateQuestion(token, questionId, { date_active: date })
fetchQuestions()
} catch (error) {
console.error('Error:', error)
}
}
const removeDate = async (questionId: number) => {
if (!token) return
try {
await updateQuestion(token, questionId, { date_active: null })
fetchQuestions()
} catch (error) {
console.error('Error:', error)
}
}
// Calendar helpers
const getDaysInMonth = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth()
const firstDay = new Date(year, month, 1)
const lastDay = new Date(year, month + 1, 0)
const days: Date[] = []
// Add padding for first week
const startPadding = firstDay.getDay()
for (let i = startPadding - 1; i >= 0; i--) {
days.push(new Date(year, month, -i))
}
// Add days of month
for (let d = 1; d <= lastDay.getDate(); d++) {
days.push(new Date(year, month, d))
}
return days
}
const formatDate = (date: Date) => date.toISOString().split('T')[0]
const getQuestionsForDate = (date: string) =>
questions.filter(q => q.date_active === date)
const unassignedQuestions = questions.filter(q => !q.date_active)
const days = getDaysInMonth(currentMonth)
const monthName = currentMonth.toLocaleDateString('es', { month: 'long', year: 'numeric' })
const prevMonth = () => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1))
const nextMonth = () => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1))
return (
<div>
<h1 className="text-2xl font-bold text-white mb-6">Calendario de Preguntas</h1>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Calendar */}
<div className="lg:col-span-2 bg-gray-800 rounded-lg p-4">
{/* Month Navigation */}
<div className="flex justify-between items-center mb-4">
<button onClick={prevMonth} className="text-gray-400 hover:text-white px-2">
Anterior
</button>
<h2 className="text-lg font-semibold text-white capitalize">{monthName}</h2>
<button onClick={nextMonth} className="text-gray-400 hover:text-white px-2">
Siguiente
</button>
</div>
{/* Day Headers */}
<div className="grid grid-cols-7 gap-1 mb-2">
{['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'].map(day => (
<div key={day} className="text-center text-gray-500 text-sm py-2">
{day}
</div>
))}
</div>
{/* Days Grid */}
<div className="grid grid-cols-7 gap-1">
{days.map((day, i) => {
const dateStr = formatDate(day)
const isCurrentMonth = day.getMonth() === currentMonth.getMonth()
const isToday = dateStr === formatDate(new Date())
const dayQuestions = getQuestionsForDate(dateStr)
const isSelected = selectedDate === dateStr
return (
<motion.button
key={i}
onClick={() => setSelectedDate(dateStr)}
whileHover={{ scale: 1.05 }}
className={`p-2 rounded min-h-[60px] text-left transition-colors ${
!isCurrentMonth ? 'opacity-30' :
isSelected ? 'bg-blue-600' :
isToday ? 'bg-blue-500/30' :
'bg-gray-700 hover:bg-gray-600'
}`}
>
<span className={`text-sm ${isCurrentMonth ? 'text-white' : 'text-gray-500'}`}>
{day.getDate()}
</span>
{dayQuestions.length > 0 && (
<div className="mt-1">
<span className={`text-xs px-1 rounded ${
dayQuestions.length >= 5 ? 'bg-green-500/30 text-green-400' :
'bg-yellow-500/30 text-yellow-400'
}`}>
{dayQuestions.length} preg.
</span>
</div>
)}
</motion.button>
)
})}
</div>
</div>
{/* Sidebar */}
<div className="space-y-4">
{/* Selected Date Questions */}
{selectedDate && (
<div className="bg-gray-800 rounded-lg p-4">
<h3 className="font-semibold text-white mb-3">
{new Date(selectedDate + 'T12:00:00').toLocaleDateString('es', {
weekday: 'long', day: 'numeric', month: 'long'
})}
</h3>
{getQuestionsForDate(selectedDate).length === 0 ? (
<p className="text-gray-400 text-sm">No hay preguntas para este día</p>
) : (
<div className="space-y-2 max-h-48 overflow-auto">
{getQuestionsForDate(selectedDate).map(q => (
<div key={q.id} className="p-2 bg-gray-700 rounded text-sm">
<p className="text-white truncate">{q.question_text}</p>
<div className="flex justify-between items-center mt-1">
<span className="text-gray-400">Dif. {q.difficulty}</span>
<button
onClick={() => removeDate(q.id)}
className="text-red-400 hover:text-red-300 text-xs"
>
Quitar
</button>
</div>
</div>
))}
</div>
)}
</div>
)}
{/* Unassigned Questions */}
<div className="bg-gray-800 rounded-lg p-4">
<h3 className="font-semibold text-white mb-3">
Sin asignar ({unassignedQuestions.length})
</h3>
{loading ? (
<p className="text-gray-400 text-sm">Cargando...</p>
) : unassignedQuestions.length === 0 ? (
<p className="text-gray-400 text-sm">Todas las preguntas están asignadas</p>
) : (
<div className="space-y-2 max-h-64 overflow-auto">
{unassignedQuestions.slice(0, 10).map(q => (
<div key={q.id} className="p-2 bg-gray-700 rounded text-sm">
<p className="text-white truncate">{q.question_text}</p>
<div className="flex justify-between items-center mt-1">
<span className="text-gray-400">Dif. {q.difficulty}</span>
{selectedDate && (
<button
onClick={() => assignDate(q.id, selectedDate)}
className="text-blue-400 hover:text-blue-300 text-xs"
>
Asignar
</button>
)}
</div>
</div>
))}
{unassignedQuestions.length > 10 && (
<p className="text-gray-500 text-xs text-center">
+{unassignedQuestions.length - 10} más
</p>
)}
</div>
)}
</div>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,128 @@
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { motion } from 'framer-motion'
import { useAdminStore } from '../../stores/adminStore'
import { getQuestions, getCategories } from '../../services/adminApi'
interface Stats {
pendingQuestions: number
totalQuestions: number
totalCategories: number
}
export default function Dashboard() {
const { token } = useAdminStore()
const [stats, setStats] = useState<Stats>({
pendingQuestions: 0,
totalQuestions: 0,
totalCategories: 0
})
const [loading, setLoading] = useState(true)
useEffect(() => {
const fetchStats = async () => {
if (!token) return
try {
const [pending, all, categories] = await Promise.all([
getQuestions(token, undefined, 'pending'),
getQuestions(token),
getCategories(token)
])
setStats({
pendingQuestions: pending.length,
totalQuestions: all.length,
totalCategories: categories.length
})
} catch (error) {
console.error('Error fetching stats:', error)
} finally {
setLoading(false)
}
}
fetchStats()
}, [token])
const statCards = [
{ label: 'Pendientes', value: stats.pendingQuestions, color: 'yellow', icon: '⏳' },
{ label: 'Total Preguntas', value: stats.totalQuestions, color: 'blue', icon: '❓' },
{ label: 'Categorías', value: stats.totalCategories, color: 'green', icon: '📁' },
]
return (
<div>
<h1 className="text-2xl font-bold text-white mb-8">Dashboard</h1>
{/* Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
{statCards.map((card, i) => (
<motion.div
key={card.label}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.1 }}
className={`p-6 rounded-lg bg-gray-800 border-l-4 ${
card.color === 'yellow' ? 'border-yellow-500' :
card.color === 'blue' ? 'border-blue-500' : 'border-green-500'
}`}
>
<div className="flex items-center justify-between">
<div>
<p className="text-gray-400 text-sm">{card.label}</p>
<p className="text-3xl font-bold text-white">
{loading ? '...' : card.value}
</p>
</div>
<span className="text-3xl">{card.icon}</span>
</div>
</motion.div>
))}
</div>
{/* Quick Actions */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Link
to="/admin/questions"
className="p-6 bg-gray-800 rounded-lg hover:bg-gray-700 transition-colors"
>
<h3 className="text-lg font-semibold text-white mb-2">
Gestionar Preguntas
</h3>
<p className="text-gray-400 text-sm">
Crear, editar, aprobar y generar preguntas con IA
</p>
</Link>
<Link
to="/admin/calendar"
className="p-6 bg-gray-800 rounded-lg hover:bg-gray-700 transition-colors"
>
<h3 className="text-lg font-semibold text-white mb-2">
📅 Ver Calendario
</h3>
<p className="text-gray-400 text-sm">
Programar preguntas para fechas específicas
</p>
</Link>
</div>
{/* Pending Alert */}
{stats.pendingQuestions > 0 && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="mt-8 p-4 bg-yellow-500/20 border border-yellow-500 rounded-lg"
>
<p className="text-yellow-500">
Tienes {stats.pendingQuestions} preguntas pendientes de aprobación.{' '}
<Link to="/admin/questions?status=pending" className="underline">
Revisar ahora
</Link>
</p>
</motion.div>
)}
</div>
)
}

View File

@@ -0,0 +1,91 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { useAdminStore } from '../../stores/adminStore'
import { adminLogin } from '../../services/adminApi'
export default function AdminLogin() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const { setAuth, isAuthenticated } = useAdminStore()
// Redirect if already authenticated
if (isAuthenticated) {
navigate('/admin/dashboard')
return null
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
const { access_token } = await adminLogin(username, password)
setAuth(access_token, username)
navigate('/admin/dashboard')
} catch (err) {
setError(err instanceof Error ? err.message : 'Login failed')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="w-full max-w-md bg-gray-800 rounded-lg p-8"
>
<h1 className="text-2xl font-bold text-white mb-6 text-center">
Panel de Administración
</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-gray-400 text-sm mb-1">Usuario</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-4 py-2 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
required
/>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Contraseña</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-4 py-2 bg-gray-700 text-white rounded border border-gray-600 focus:border-blue-500 outline-none"
required
/>
</div>
{error && (
<p className="text-red-500 text-sm">{error}</p>
)}
<button
type="submit"
disabled={loading}
className="w-full py-2 bg-blue-600 text-white rounded font-semibold hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Iniciando sesión...' : 'Iniciar Sesión'}
</button>
</form>
<p className="text-gray-500 text-sm text-center mt-4">
<a href="/" className="hover:text-gray-400"> Volver al juego</a>
</p>
</motion.div>
</div>
)
}

View File

@@ -0,0 +1,479 @@
import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { useAdminStore } from '../../stores/adminStore'
import {
getQuestions, getCategories, createQuestion, updateQuestion,
deleteQuestion, generateQuestions, approveQuestion, rejectQuestion
} from '../../services/adminApi'
import type { Category } from '../../types'
interface Question {
id: number
category_id: number
question_text: string
correct_answer: string
alt_answers: string[]
difficulty: number
points: number
time_seconds: number
date_active: string | null
status: string
fun_fact: string | null
}
export default function Questions() {
const { token } = useAdminStore()
const [questions, setQuestions] = useState<Question[]>([])
const [categories, setCategories] = useState<Category[]>([])
const [loading, setLoading] = useState(true)
// Filters
const [filterCategory, setFilterCategory] = useState<number | ''>('')
const [filterStatus, setFilterStatus] = useState<string>('')
// Modals
const [showEditModal, setShowEditModal] = useState(false)
const [showGenerateModal, setShowGenerateModal] = useState(false)
const [editingQuestion, setEditingQuestion] = useState<Question | null>(null)
// Form state
const [formData, setFormData] = useState({
category_id: 1,
question_text: '',
correct_answer: '',
alt_answers: '',
difficulty: 3,
fun_fact: ''
})
// Generate state
const [generateData, setGenerateData] = useState({
category_id: 1,
difficulty: 3,
count: 5
})
const [generating, setGenerating] = useState(false)
useEffect(() => {
fetchData()
}, [token, filterCategory, filterStatus])
const fetchData = async () => {
if (!token) return
setLoading(true)
try {
const [qs, cats] = await Promise.all([
getQuestions(token, filterCategory || undefined, filterStatus || undefined),
getCategories(token)
])
setQuestions(qs)
setCategories(cats)
} catch (error) {
console.error('Error fetching data:', error)
} finally {
setLoading(false)
}
}
const handleCreate = () => {
setEditingQuestion(null)
setFormData({
category_id: 1,
question_text: '',
correct_answer: '',
alt_answers: '',
difficulty: 3,
fun_fact: ''
})
setShowEditModal(true)
}
const handleEdit = (q: Question) => {
setEditingQuestion(q)
setFormData({
category_id: q.category_id,
question_text: q.question_text,
correct_answer: q.correct_answer,
alt_answers: q.alt_answers?.join(', ') || '',
difficulty: q.difficulty,
fun_fact: q.fun_fact || ''
})
setShowEditModal(true)
}
const handleSave = async () => {
if (!token) return
const data = {
...formData,
alt_answers: formData.alt_answers.split(',').map(s => s.trim()).filter(Boolean)
}
try {
if (editingQuestion) {
await updateQuestion(token, editingQuestion.id, data)
} else {
await createQuestion(token, data)
}
setShowEditModal(false)
fetchData()
} catch (error) {
console.error('Error saving:', error)
}
}
const handleDelete = async (id: number) => {
if (!token || !confirm('¿Eliminar esta pregunta?')) return
try {
await deleteQuestion(token, id)
fetchData()
} catch (error) {
console.error('Error deleting:', error)
}
}
const handleApprove = async (id: number) => {
if (!token) return
try {
await approveQuestion(token, id)
fetchData()
} catch (error) {
console.error('Error approving:', error)
}
}
const handleReject = async (id: number) => {
if (!token) return
try {
await rejectQuestion(token, id)
fetchData()
} catch (error) {
console.error('Error rejecting:', error)
}
}
const handleGenerate = async () => {
if (!token) return
setGenerating(true)
try {
const result = await generateQuestions(token, generateData)
alert(`Se generaron ${result.generated} preguntas`)
setShowGenerateModal(false)
setFilterStatus('pending')
fetchData()
} catch (error) {
console.error('Error generating:', error)
alert('Error al generar preguntas')
} finally {
setGenerating(false)
}
}
const getCategoryName = (id: number) => categories.find(c => c.id === id)?.name || 'Unknown'
const getStatusBadge = (status: string) => {
switch (status) {
case 'pending': return 'bg-yellow-500/20 text-yellow-500'
case 'approved': return 'bg-green-500/20 text-green-500'
case 'used': return 'bg-gray-500/20 text-gray-400'
default: return 'bg-gray-500/20 text-gray-400'
}
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold text-white">Preguntas</h1>
<div className="flex gap-2">
<button
onClick={() => setShowGenerateModal(true)}
className="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700"
>
Generar con IA
</button>
<button
onClick={handleCreate}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
+ Nueva Pregunta
</button>
</div>
</div>
{/* Filters */}
<div className="flex gap-4 mb-6">
<select
value={filterCategory}
onChange={(e) => setFilterCategory(e.target.value ? Number(e.target.value) : '')}
className="px-4 py-2 bg-gray-800 text-white rounded border border-gray-700"
>
<option value="">Todas las categorias</option>
{categories.map(c => (
<option key={c.id} value={c.id}>{c.icon} {c.name}</option>
))}
</select>
<select
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
className="px-4 py-2 bg-gray-800 text-white rounded border border-gray-700"
>
<option value="">Todos los estados</option>
<option value="pending">Pendientes</option>
<option value="approved">Aprobadas</option>
<option value="used">Usadas</option>
</select>
</div>
{/* Questions List */}
<div className="space-y-4">
{loading ? (
<p className="text-gray-400">Cargando...</p>
) : questions.length === 0 ? (
<p className="text-gray-400">No hay preguntas</p>
) : (
questions.map((q) => (
<motion.div
key={q.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="p-4 bg-gray-800 rounded-lg"
>
<div className="flex justify-between items-start">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<span className={`px-2 py-1 rounded text-xs ${getStatusBadge(q.status)}`}>
{q.status}
</span>
<span className="text-gray-500 text-sm">
{getCategoryName(q.category_id)} - Dif. {q.difficulty} - {q.points}pts
</span>
</div>
<p className="text-white">{q.question_text}</p>
<p className="text-green-400 text-sm mt-1">R: {q.correct_answer}</p>
</div>
<div className="flex gap-2 ml-4">
{q.status === 'pending' && (
<>
<button
onClick={() => handleApprove(q.id)}
className="px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700"
>
Aprobar
</button>
<button
onClick={() => handleReject(q.id)}
className="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700"
>
Rechazar
</button>
</>
)}
<button
onClick={() => handleEdit(q)}
className="px-3 py-1 bg-gray-700 text-white rounded text-sm hover:bg-gray-600"
>
Editar
</button>
<button
onClick={() => handleDelete(q.id)}
className="px-3 py-1 bg-gray-700 text-red-400 rounded text-sm hover:bg-gray-600"
>
Eliminar
</button>
</div>
</div>
</motion.div>
))
)}
</div>
{/* Edit Modal */}
<AnimatePresence>
{showEditModal && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/80 flex items-center justify-center p-4 z-50"
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
exit={{ scale: 0.9 }}
className="w-full max-w-lg bg-gray-800 rounded-lg p-6"
>
<h2 className="text-xl font-bold text-white mb-4">
{editingQuestion ? 'Editar Pregunta' : 'Nueva Pregunta'}
</h2>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-gray-400 text-sm mb-1">Categoria</label>
<select
value={formData.category_id}
onChange={(e) => setFormData({ ...formData, category_id: Number(e.target.value) })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
>
{categories.map(c => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Dificultad</label>
<select
value={formData.difficulty}
onChange={(e) => setFormData({ ...formData, difficulty: Number(e.target.value) })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
>
{[1, 2, 3, 4, 5].map(d => (
<option key={d} value={d}>{d} ({d * 100}pts)</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Pregunta</label>
<textarea
value={formData.question_text}
onChange={(e) => setFormData({ ...formData, question_text: e.target.value })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600 h-24"
/>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Respuesta Correcta</label>
<input
type="text"
value={formData.correct_answer}
onChange={(e) => setFormData({ ...formData, correct_answer: e.target.value })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
/>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Respuestas Alternativas (separadas por coma)</label>
<input
type="text"
value={formData.alt_answers}
onChange={(e) => setFormData({ ...formData, alt_answers: e.target.value })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
placeholder="Variacion 1, Variacion 2"
/>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Dato Curioso (opcional)</label>
<input
type="text"
value={formData.fun_fact}
onChange={(e) => setFormData({ ...formData, fun_fact: e.target.value })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
/>
</div>
</div>
<div className="flex justify-end gap-2 mt-6">
<button
onClick={() => setShowEditModal(false)}
className="px-4 py-2 text-gray-400 hover:text-white"
>
Cancelar
</button>
<button
onClick={handleSave}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Guardar
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
{/* Generate Modal */}
<AnimatePresence>
{showGenerateModal && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/80 flex items-center justify-center p-4 z-50"
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
exit={{ scale: 0.9 }}
className="w-full max-w-md bg-gray-800 rounded-lg p-6"
>
<h2 className="text-xl font-bold text-white mb-4">
Generar Preguntas con IA
</h2>
<div className="space-y-4">
<div>
<label className="block text-gray-400 text-sm mb-1">Categoria</label>
<select
value={generateData.category_id}
onChange={(e) => setGenerateData({ ...generateData, category_id: Number(e.target.value) })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
>
{categories.map(c => (
<option key={c.id} value={c.id}>{c.icon} {c.name}</option>
))}
</select>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Dificultad</label>
<select
value={generateData.difficulty}
onChange={(e) => setGenerateData({ ...generateData, difficulty: Number(e.target.value) })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
>
{[1, 2, 3, 4, 5].map(d => (
<option key={d} value={d}>{d} - {['Muy Facil', 'Facil', 'Media', 'Dificil', 'Muy Dificil'][d - 1]}</option>
))}
</select>
</div>
<div>
<label className="block text-gray-400 text-sm mb-1">Cantidad</label>
<select
value={generateData.count}
onChange={(e) => setGenerateData({ ...generateData, count: Number(e.target.value) })}
className="w-full px-3 py-2 bg-gray-700 text-white rounded border border-gray-600"
>
{[3, 5, 10].map(n => (
<option key={n} value={n}>{n} preguntas</option>
))}
</select>
</div>
</div>
<div className="flex justify-end gap-2 mt-6">
<button
onClick={() => setShowGenerateModal(false)}
className="px-4 py-2 text-gray-400 hover:text-white"
disabled={generating}
>
Cancelar
</button>
<button
onClick={handleGenerate}
disabled={generating}
className="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50"
>
{generating ? 'Generando...' : 'Generar'}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
)
}

View File

@@ -0,0 +1,5 @@
export { default as Login } from './Login'
export { default as AdminLayout } from './AdminLayout'
export { default as Dashboard } from './Dashboard'
export { default as Questions } from './Questions'
export { default as Calendar } from './Calendar'

View File

@@ -0,0 +1,140 @@
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
// Helper para obtener headers con auth
const getAuthHeaders = (token: string | null) => ({
'Content-Type': 'application/json',
...(token ? { 'Authorization': `Bearer ${token}` } : {})
})
// Auth
export const adminLogin = async (username: string, password: string) => {
const formData = new FormData()
formData.append('username', username)
formData.append('password', password)
const response = await fetch(`${API_URL}/api/admin/login`, {
method: 'POST',
body: formData
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Login failed')
}
return response.json()
}
export const adminRegister = async (username: string, password: string) => {
const response = await fetch(`${API_URL}/api/admin/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Registration failed')
}
return response.json()
}
// Questions
export const getQuestions = async (token: string, categoryId?: number, status?: string) => {
const params = new URLSearchParams()
if (categoryId) params.append('category_id', String(categoryId))
if (status) params.append('status', status)
const response = await fetch(`${API_URL}/api/admin/questions?${params}`, {
headers: getAuthHeaders(token)
})
if (!response.ok) throw new Error('Failed to fetch questions')
return response.json()
}
export const createQuestion = async (token: string, data: {
category_id: number
question_text: string
correct_answer: string
alt_answers?: string[]
difficulty: number
date_active?: string
fun_fact?: string
}) => {
const response = await fetch(`${API_URL}/api/admin/questions`, {
method: 'POST',
headers: getAuthHeaders(token),
body: JSON.stringify(data)
})
if (!response.ok) throw new Error('Failed to create question')
return response.json()
}
export const updateQuestion = async (token: string, id: number, data: Record<string, unknown>) => {
const response = await fetch(`${API_URL}/api/admin/questions/${id}`, {
method: 'PUT',
headers: getAuthHeaders(token),
body: JSON.stringify(data)
})
if (!response.ok) throw new Error('Failed to update question')
return response.json()
}
export const deleteQuestion = async (token: string, id: number) => {
const response = await fetch(`${API_URL}/api/admin/questions/${id}`, {
method: 'DELETE',
headers: getAuthHeaders(token)
})
if (!response.ok) throw new Error('Failed to delete question')
return response.json()
}
export const generateQuestions = async (token: string, data: {
category_id: number
difficulty: number
count: number
}) => {
const response = await fetch(`${API_URL}/api/admin/questions/generate`, {
method: 'POST',
headers: getAuthHeaders(token),
body: JSON.stringify(data)
})
if (!response.ok) throw new Error('Failed to generate questions')
return response.json()
}
export const approveQuestion = async (token: string, id: number) => {
const response = await fetch(`${API_URL}/api/admin/questions/${id}/approve`, {
method: 'POST',
headers: getAuthHeaders(token)
})
if (!response.ok) throw new Error('Failed to approve question')
return response.json()
}
export const rejectQuestion = async (token: string, id: number) => {
const response = await fetch(`${API_URL}/api/admin/questions/${id}/reject`, {
method: 'POST',
headers: getAuthHeaders(token)
})
if (!response.ok) throw new Error('Failed to reject question')
return response.json()
}
// Categories
export const getCategories = async (token: string) => {
const response = await fetch(`${API_URL}/api/admin/categories`, {
headers: getAuthHeaders(token)
})
if (!response.ok) throw new Error('Failed to fetch categories')
return response.json()
}

View File

@@ -0,0 +1,36 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface AdminState {
token: string | null
username: string | null
isAuthenticated: boolean
setAuth: (token: string, username: string) => void
logout: () => void
}
export const useAdminStore = create<AdminState>()(
persist(
(set) => ({
token: null,
username: null,
isAuthenticated: false,
setAuth: (token, username) => set({
token,
username,
isAuthenticated: true
}),
logout: () => set({
token: null,
username: null,
isAuthenticated: false
})
}),
{
name: 'admin-auth'
}
)
)