talos-access / frontend /src /pages /DeveloperPage.tsx
Greg
Claude Sonnet 4.6
feat(developer): UI button + modal to trigger demo purge
47a0040
Raw History Blame Contribute Delete
18.4 kB
import { useEffect, useState } from 'react';
import { useAuthStore } from '../store/authStore';
import LoadingState from '../components/LoadingState';
import PurgeDemoModal from '../components/PurgeDemoModal';
import {
getDeveloperDashboard,
toggleAccountActive,
setAccountTrial,
getSystemLogs,
getExportUrl,
type DeveloperDashboard,
type SystemLogEntry,
type PaginatedLogs,
} from '../services/developerService';
import {
BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, LineChart, Line,
} from 'recharts';
import {
Building2, Users, Activity, Download, ToggleLeft, ToggleRight,
AlertTriangle, Calendar, Search, RefreshCw, Trash2,
} from 'lucide-react';
export default function DeveloperPage() {
const user = useAuthStore((s) => s.user);
const [data, setData] = useState<DeveloperDashboard | null>(null);
const [loading, setLoading] = useState(true);
const [logs, setLogs] = useState<PaginatedLogs | null>(null);
const [logsLoading, setLogsLoading] = useState(false);
const [logPage, setLogPage] = useState(1);
const [logLevel, setLogLevel] = useState('');
const [searchAcct, setSearchAcct] = useState('');
const [trialDays, setTrialDays] = useState<Record<number, string>>({});
const [tab, setTab] = useState<'dashboard' | 'accounts' | 'logs'>('dashboard');
const [showPurge, setShowPurge] = useState(false);
const loadDashboard = async () => {
setLoading(true);
try {
const d = await getDeveloperDashboard();
setData(d);
} catch { /* ignore */ } finally {
setLoading(false);
}
};
const loadLogs = async () => {
setLogsLoading(true);
try {
const l = await getSystemLogs(logPage, 20, logLevel || undefined);
setLogs(l);
} catch { /* ignore */ } finally {
setLogsLoading(false);
}
};
useEffect(() => { loadDashboard(); }, []);
useEffect(() => { if (tab === 'logs') loadLogs(); }, [tab, logPage, logLevel]);
const handleToggleActive = async (id: number) => {
await toggleAccountActive(id);
loadDashboard();
};
const handleSetTrial = async (id: number) => {
const days = parseInt(trialDays[id] || '');
if (!days || days < 1) return;
await setAccountTrial(id, days);
setTrialDays({ ...trialDays, [id]: '' });
loadDashboard();
};
const exportUrl = getExportUrl();
const adminStatCards = data ? [
{ label: 'Colegios', value: data.total_accounts, icon: Building2, color: '#3b82f6' },
{ label: 'Activos', value: data.active_accounts, icon: Activity, color: '#10b981' },
{ label: 'Prueba', value: data.trial_accounts, icon: Calendar, color: '#f59e0b' },
{ label: 'Usuarios', value: data.total_users, icon: Users, color: '#8b5cf6' },
] : [];
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1>Panel de Desarrollo</h1>
<div className="flex gap-2">
<a href={exportUrl} download
className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition text-sm inline-flex items-center gap-2">
<Download size={16} /> Exportar Reporte
</a>
</div>
</div>
<div className="flex gap-1 bg-gray-100 rounded-lg p-1 w-fit">
<button onClick={() => setTab('dashboard')}
className={`px-4 py-2 rounded-md text-sm font-medium transition ${tab === 'dashboard' ? 'bg-white shadow text-gray-900' : 'text-gray-500 hover:text-gray-700'}`}>
Dashboard
</button>
<button onClick={() => setTab('accounts')}
className={`px-4 py-2 rounded-md text-sm font-medium transition ${tab === 'accounts' ? 'bg-white shadow text-gray-900' : 'text-gray-500 hover:text-gray-700'}`}>
Colegios
</button>
<button onClick={() => setTab('logs')}
className={`px-4 py-2 rounded-md text-sm font-medium transition ${tab === 'logs' ? 'bg-white shadow text-gray-900' : 'text-gray-500 hover:text-gray-700'}`}>
Logs de Errores
</button>
</div>
{tab === 'dashboard' && (
<div className="space-y-6">
{adminStatCards.length > 0 && (
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{adminStatCards.map((c) => (
<div key={c.label} className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center gap-3">
<div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${c.color}12` }}>
<c.icon size={20} color={c.color} />
</div>
<div className="min-w-0">
<div className="text-xl font-bold text-gray-800">{c.value}</div>
<div className="text-xs text-gray-400 font-medium uppercase tracking-wider">{c.label}</div>
</div>
</div>
))}
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<h3 className="mb-4">Colegios Registrados (últimos 30 días)</h3>
{data && data.accounts_by_date.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<BarChart data={data.accounts_by_date}>
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
<XAxis dataKey="date" tick={{ fontSize: 10, fill: '#9ca3af' }} tickFormatter={(v: string) => v.slice(5)} />
<YAxis allowDecimals={false} tick={{ fontSize: 11, fill: '#9ca3af' }} />
<Tooltip contentStyle={{ borderRadius: 12, border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.1)' }} />
<Bar dataKey="count" fill="#3b82f6" radius={[6, 6, 0, 0]} name="Colegios" />
</BarChart>
</ResponsiveContainer>
) : (
<p className="text-gray-400 text-sm text-center py-8">Sin datos</p>
)}
</div>
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<h3 className="mb-4">Errores por Día (últimos 30 días)</h3>
{data && data.errors_trend.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<LineChart data={data.errors_trend}>
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
<XAxis dataKey="date" tick={{ fontSize: 10, fill: '#9ca3af' }} tickFormatter={(v: string) => v.slice(5)} />
<YAxis allowDecimals={false} tick={{ fontSize: 11, fill: '#9ca3af' }} />
<Tooltip contentStyle={{ borderRadius: 12, border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.1)' }} />
<Line type="monotone" dataKey="count" stroke="#ef4444" strokeWidth={2} dot={false} name="Errores" />
</LineChart>
</ResponsiveContainer>
) : (
<p className="text-gray-400 text-sm text-center py-8">Sin errores registrados</p>
)}
</div>
</div>
{data && data.accounts.length > 0 && (
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<h3 className="mb-4">Usuarios por Colegio</h3>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={data.accounts.map(a => ({ name: a.name, usuarios: a.user_count }))} layout="vertical">
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
<XAxis type="number" tick={{ fontSize: 11, fill: '#9ca3af' }} />
<YAxis dataKey="name" type="category" tick={{ fontSize: 10, fill: '#9ca3af' }} width={160} />
<Tooltip contentStyle={{ borderRadius: 12, border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.1)' }} />
<Bar dataKey="usuarios" fill="#8b5cf6" radius={[0, 6, 6, 0]} name="Usuarios" />
</BarChart>
</ResponsiveContainer>
</div>
)}
{user?.role === 'developer' && (
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mt-6">
<div className="flex items-center justify-between gap-4">
<div>
<h3 className="font-semibold text-red-700 flex items-center gap-2"><AlertTriangle size={16} /> Zona peligrosa</h3>
<p className="text-sm text-red-600 mt-1">Purga todos los datos subidos al demo y restaura el seeder original. Esta acción NO se puede deshacer.</p>
</div>
<button onClick={() => setShowPurge(true)} className="px-4 py-2 bg-red-600 text-white rounded-lg text-sm hover:bg-red-700 inline-flex items-center gap-2 shrink-0">
<Trash2 size={14} /> Purgar demo
</button>
</div>
</div>
)}
<PurgeDemoModal
open={showPurge}
onClose={() => setShowPurge(false)}
onSuccess={(deleted) => {
const total = Object.values(deleted).reduce((a, b) => a + b, 0);
alert(`Demo purgado y re-sembrado. Total filas eliminadas: ${total}`);
loadDashboard();
}}
/>
</div>
)}
{tab === 'accounts' && (
<div className="space-y-4">
<div className="flex items-center gap-2">
<div className="relative flex-1 max-w-xs">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<input placeholder="Buscar colegio..." value={searchAcct}
onChange={(e) => setSearchAcct(e.target.value)}
className="w-full border border-gray-300 rounded-lg pl-9 pr-3 py-2 text-sm" />
</div>
<button onClick={loadDashboard} className="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg hover:bg-gray-200 transition text-sm inline-flex items-center gap-1">
<RefreshCw size={14} /> Actualizar
</button>
</div>
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 text-left text-gray-500">
<th className="pb-2 font-medium pl-3 pr-2 pt-2">ID</th>
<th className="pb-2 font-medium pr-2 pt-2">Nombre</th>
<th className="pb-2 font-medium pr-2 pt-2">Plan</th>
<th className="pb-2 font-medium pr-2 pt-2">Usuarios</th>
<th className="pb-2 font-medium pr-2 pt-2">Estado</th>
<th className="pb-2 font-medium pr-2 pt-2">Prueba hasta</th>
<th className="pb-2 font-medium pt-2">Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr><td colSpan={7}><LoadingState /></td></tr>
) : null}
{!loading && (data?.accounts || [])
.filter((a) => !searchAcct || a.name.toLowerCase().includes(searchAcct.toLowerCase()))
.map((a) => (
<tr key={a.id} className="border-b border-gray-100">
<td className="py-2 pl-3 pr-2 text-gray-500">{a.id}</td>
<td className="py-2 font-medium pr-2">{a.name}</td>
<td className="py-2 pr-2"><span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 capitalize">{a.plan}</span></td>
<td className="py-2 pr-2 text-gray-500">{a.user_count}</td>
<td className="py-2 pr-2">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${a.is_active ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
{a.is_active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td className="py-2 pr-2 text-gray-500">{a.trial_end_date ? new Date(a.trial_end_date).toLocaleDateString() : '—'}</td>
<td className="py-2 flex gap-1 items-center">
<button onClick={() => handleToggleActive(a.id)}
className="px-2 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors inline-flex items-center gap-1"
title={a.is_active ? 'Desactivar' : 'Activar'}>
{a.is_active ? <ToggleRight size={14} className="text-green-600" /> : <ToggleLeft size={14} className="text-red-600" />}
</button>
<div className="flex items-center gap-1">
<input type="number" min={1} max={365} placeholder="Días"
value={trialDays[a.id] || ''}
onChange={(e) => setTrialDays({ ...trialDays, [a.id]: e.target.value })}
className="w-16 border border-gray-300 rounded px-2 py-1.5 text-xs" />
<button onClick={() => handleSetTrial(a.id)}
className="px-2 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-xs hover:bg-amber-50 hover:border-amber-300 transition-colors inline-flex items-center gap-1">
<Calendar size={12} /> Prueba
</button>
</div>
</td>
</tr>
))}
{!loading && (!data?.accounts || data.accounts.length === 0) && (
<tr><td colSpan={7} className="text-gray-400 text-sm text-center py-8">No hay colegios</td></tr>
)}
</tbody>
</table>
</div>
</div>
</div>
)}
{tab === 'logs' && (
<div className="space-y-4">
<div className="flex items-center gap-2">
<select value={logLevel} onChange={(e) => { setLogLevel(e.target.value); setLogPage(1); }}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm">
<option value="">Todos los niveles</option>
<option value="error">Error</option>
<option value="warning">Warning</option>
<option value="info">Info</option>
</select>
<button onClick={loadLogs} className="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg hover:bg-gray-200 transition text-sm inline-flex items-center gap-1">
<RefreshCw size={14} /> Actualizar
</button>
</div>
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 text-left text-gray-500">
<th className="pb-2 font-medium pl-3 pr-2 pt-2">Fecha</th>
<th className="pb-2 font-medium pr-2 pt-2">Nivel</th>
<th className="pb-2 font-medium pr-2 pt-2">Mensaje</th>
<th className="pb-2 font-medium pr-2 pt-2">Endpoint</th>
<th className="pb-2 font-medium pr-2 pt-2">Método</th>
<th className="pb-2 font-medium pt-2">Cuenta</th>
</tr>
</thead>
<tbody>
{logsLoading ? (
<tr><td colSpan={6}><LoadingState /></td></tr>
) : null}
{!logsLoading && logs?.items.map((l) => (
<tr key={l.id} className="border-b border-gray-100">
<td className="py-2 pl-3 pr-2 text-gray-500 text-xs">
{l.created_at ? new Date(l.created_at).toLocaleString() : '-'}
</td>
<td className="py-2 pr-2">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${l.level === 'error' ? 'bg-red-100 text-red-700' : l.level === 'warning' ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'}`}>
{l.level}
</span>
</td>
<td className="py-2 pr-2 text-gray-700 max-w-xs truncate" title={l.message}>{l.message}</td>
<td className="py-2 pr-2 text-gray-500 text-xs font-mono">{l.endpoint || '-'}</td>
<td className="py-2 pr-2 text-gray-500 text-xs">{l.method || '-'}</td>
<td className="py-2 pr-2 text-gray-500 text-xs">{l.account_id || '-'}</td>
</tr>
))}
{!logsLoading && (!logs || logs.items.length === 0) && (
<tr><td colSpan={6} className="text-gray-400 text-sm text-center py-8">No hay errores registrados</td></tr>
)}
</tbody>
</table>
</div>
</div>
{logs && logs.total_pages > 1 && (
<div className="flex items-center justify-center gap-2 mt-4">
<button disabled={logPage <= 1} onClick={() => setLogPage((p) => p - 1)}
className="px-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors disabled:opacity-30">
Anterior
</button>
<span className="text-sm text-gray-500">Pág {logs.page} de {logs.total_pages} ({logs.total} registros)</span>
<button disabled={logPage >= logs.total_pages} onClick={() => setLogPage((p) => p + 1)}
className="px-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-blue-50 hover:border-blue-300 transition-colors disabled:opacity-30">
Siguiente
</button>
</div>
)}
</div>
)}
</div>
);
}