feat(panel): dashboard de olvidos con ranking y periodo semana/mes

Backend: GET /api/dashboard/olvidos?periodo=semana|mes (supervisora) agrega
las solicitudes por becario y tipo en un periodo móvil (7/30 días) y devuelve
el ranking más los totales. Excluye las rechazadas: la supervisora ya
determinó que no procedían.

Panel: pestaña "Dashboard" con selector de periodo, fila de KPIs, barras
horizontales apiladas ordenadas de mayor a menor (ámbar=olvidó salida,
azul=olvidó entrada, verde=jornada completa) y tabla gemela con todos los
valores. Paleta validada para daltonismo (peor par adyacente ΔE 15.2 deutan,
16.0 visión normal, contraste ≥3:1); el color sigue al tipo de olvido, no al
rango, así que cambiar de periodo no repinta a nadie.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jorem JuárezandClaude Opus 4.8 committed 2026-07-21 09:46:20 -06:00
1 parent 04a539b6fa
commit 30292d32d9
3 files changed
+227

No files matched your search

+2
View File
@@ -18,6 +18,7 @@ import configRoutes from './routes/config.js';
import kioscoRoutes from './routes/kiosco.js';
import solicitudesRoutes from './routes/solicitudes.js';
import mantenimientoRoutes from './routes/mantenimiento.js';
import dashboardRoutes from './routes/dashboard.js';
import { startTareas } from './services/tareas.js';
import { startDnsProbe } from './services/dns-probe.js';
@@ -149,6 +150,7 @@ await fastify.register(configRoutes, { prefix: '/api' });
await fastify.register(kioscoRoutes, { prefix: '/api' });
await fastify.register(solicitudesRoutes, { prefix: '/api' });
await fastify.register(mantenimientoRoutes, { prefix: '/api' });
await fastify.register(dashboardRoutes, { prefix: '/api' });
// Tareas internas: auto-cierre a revisión + limpieza de tokens (§6, §11.8).
tareasInterval = startTareas(db, fastify.log);
+65
View File
@@ -0,0 +1,65 @@
import { requireSupervisora } from '../services/sessions.js';
// Dashboard de olvidos. Las solicitudes son el registro de cada olvido:
// autorizar_autocierre → se le olvidó registrar la SALIDA (la jornada se
// auto-cerró a revisión al pasar la ventana)
// olvido_entrada → se le olvidó registrar la ENTRADA
// jornada_completa → no checó en todo el día y lo cargó después
// Aquí solo se AGREGAN por becario y tipo dentro de un periodo móvil, para
// rankear a los más olvidadizos. Solo lectura: no muta nada.
//
// Se excluyen las 'rechazada': la supervisora ya determinó que no procedían,
// así que no cuentan como olvido real. Pendientes y autorizadas sí cuentan.
const DIAS = { semana: 7, mes: 30 };
export default async function dashboardRoutes(fastify) {
fastify.addHook('onRequest', requireSupervisora);
// ──────────────── GET /dashboard/olvidos?periodo=semana|mes ────────────────
fastify.get(
'/dashboard/olvidos',
{
schema: {
querystring: {
type: 'object',
properties: { periodo: { type: 'string', enum: ['semana', 'mes'] } },
},
},
},
async (req) => {
const periodo = req.query.periodo || 'semana';
const dias = DIAS[periodo];
const { rows } = await fastify.db.query(
`SELECT b.id AS becario_id, b.nombre, b.telefono, b.estado,
COUNT(*) FILTER (WHERE s.tipo = 'autorizar_autocierre')::int AS olvido_salida,
COUNT(*) FILTER (WHERE s.tipo = 'olvido_entrada')::int AS olvido_entrada,
COUNT(*) FILTER (WHERE s.tipo = 'jornada_completa')::int AS jornada_completa,
COUNT(*)::int AS total
FROM solicitudes s
JOIN becarios b ON b.id = s.becario_id
WHERE s.created_at >= NOW() - make_interval(days => $1::int)
AND s.estado <> 'rechazada'
GROUP BY b.id, b.nombre, b.telefono, b.estado
ORDER BY total DESC, b.nombre ASC`,
[dias]
);
const suma = (clave) => rows.reduce((acc, r) => acc + r[clave], 0);
return {
periodo,
dias,
desde: new Date(Date.now() - dias * 86400000).toISOString(),
becarios: rows,
totales: {
olvidos: suma('total'),
becarios: rows.length,
olvido_salida: suma('olvido_salida'),
olvido_entrada: suma('olvido_entrada'),
jornada_completa: suma('jornada_completa'),
},
};
}
);
}
+160
View File
@@ -622,6 +622,164 @@ function VistaSolicitudes({ onError }) {
);
}
// ═══════════════════ Dashboard de olvidos ═══════════════════
// Forma: barras horizontales apiladas ordenadas de mayor a menor. El trabajo del
// dato es comparar magnitud entre entidades nominales (qué becario olvida más)
// con desglose por tipo; los nombres son largos, así que van horizontales.
// Paleta validada con el validador de la guía (peor par adyacente ΔE 15.2 deutan
// / 16.0 visión normal, contraste ≥3:1 sobre blanco). El color sigue al TIPO de
// olvido, nunca al rango: cambiar de periodo no repinta a nadie.
const SERIES = [
{ key: "olvido_salida", label: "Olvidó salida", color: "#B7791F" },
{ key: "olvido_entrada", label: "Olvidó entrada", color: "#2E77B8" },
{ key: "jornada_completa", label: "Jornada completa", color: "#2F8A63" },
];
const PERIODOS = [
{ key: "semana", label: "Última semana" },
{ key: "mes", label: "Último mes" },
];
function StatTile({ label, value, nota }) {
return (
<Card style={{ padding: "16px 18px", borderRadius: "16px", flex: 1, minWidth: "155px" }}>
<div style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 500, color: palette.inkSoft, marginBottom: "4px" }}>{label}</div>
{/* figuras proporcionales (no tabular) en un número grande y suelto */}
<div style={{ fontFamily: fonts.title, fontWeight: 700, fontSize: "28px", color: palette.brand, lineHeight: 1.1, letterSpacing: "-.01em" }}>{value}</div>
{nota && <div style={{ fontFamily: fonts.body, fontSize: "11px", color: palette.placeholder, marginTop: "3px" }}>{nota}</div>}
</Card>
);
}
// Una barra apilada por becario. Punta redondeada 4px, base cuadrada, 2px de
// hueco (color superficie) entre segmentos, total directo en la punta. El hover
// es a nivel de fila (blanco de ~34px, más grande que la marca) y muestra el
// desglose completo; los mismos valores viven en la tabla de abajo.
function BarraOlvidos({ b, max }) {
const [hover, setHover] = useState(false);
const visibles = SERIES.filter((s) => b[s.key] > 0);
const anchoPct = max > 0 ? (b.total / max) * 100 : 0;
return (
<div
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
style={{ display: "flex", alignItems: "center", gap: "12px", padding: "8px 0", position: "relative" }}
>
<div title={b.nombre} style={{ width: "180px", flexShrink: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.ink }}>
{b.nombre}
</div>
<div style={{ flex: 1, display: "flex", alignItems: "center", gap: "9px", minWidth: 0 }}>
<div style={{ display: "flex", width: anchoPct + "%", height: "18px", minWidth: "4px" }}>
{visibles.map((s, i) => (
<div key={s.key} style={{
flex: b[s.key], background: s.color,
marginRight: i < visibles.length - 1 ? "2px" : 0,
borderRadius: i === visibles.length - 1 ? "0 4px 4px 0" : 0,
}} />
))}
</div>
<span style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 700, color: palette.ink, fontVariantNumeric: "tabular-nums" }}>{b.total}</span>
</div>
{hover && (
<div style={{ position: "absolute", right: 0, bottom: "100%", marginBottom: "4px", zIndex: 20, minWidth: "200px", background: palette.surface, border: `1px solid ${palette.cardBorder}`, borderRadius: "12px", padding: "10px 12px", boxShadow: "0 14px 30px -14px rgba(33,28,22,.45)" }}>
<div style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 700, color: palette.brand, marginBottom: "5px" }}>{b.nombre}</div>
{SERIES.map((s) => (
<div key={s.key} style={{ display: "flex", alignItems: "center", gap: "7px", marginTop: "3px" }}>
<span style={{ width: "9px", height: "9px", borderRadius: "2px", background: s.color, flexShrink: 0 }} />
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, flex: 1 }}>{s.label}</span>
<span style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, color: palette.ink, fontVariantNumeric: "tabular-nums" }}>{b[s.key]}</span>
</div>
))}
</div>
)}
</div>
);
}
function VistaDashboard({ onError }) {
const [periodo, setPeriodo] = useState("semana");
const [data, setData] = useState(null);
const [cargando, setCargando] = useState(false);
const load = useCallback(async (p) => {
setCargando(true);
try { setData(await apiFetch(`/dashboard/olvidos?periodo=${p}`)); }
catch (e) { onError(e.message); }
finally { setCargando(false); }
}, [onError]);
useEffect(() => { load(periodo); }, [load, periodo]);
const t = data && data.totales;
const max = data ? Math.max.apply(null, data.becarios.map((b) => b.total).concat([1])) : 1;
const nota = periodo === "semana" ? "últimos 7 días" : "últimos 30 días";
return (
<div>
<h2 style={{ margin: "0 0 6px", fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Dashboard de olvidos</h2>
<p style={{ margin: "0 0 16px", fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, lineHeight: 1.5, maxWidth: "660px" }}>
Ranking de becarios por olvidos registrados: jornadas que se auto-cerraron por no marcar la salida, entradas olvidadas y días cargados después. No cuentan las solicitudes rechazadas.
</p>
{/* Una sola fila de filtros, arriba de todo lo que afecta */}
<div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "18px", flexWrap: "wrap" }}>
<span style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, color: palette.label }}>Periodo</span>
<select value={periodo} onChange={(e) => setPeriodo(e.target.value)}
style={{ padding: "9px 12px", borderRadius: "11px", border: `1.5px solid ${palette.inputBorder}`, background: palette.inputBg, fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.ink, cursor: "pointer", outline: "none" }}>
{PERIODOS.map((p) => <option key={p.key} value={p.key}>{p.label}</option>)}
</select>
</div>
{!data ? <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p> : (
// Al recargar se sostiene el render anterior atenuado: sin parpadeo de esqueleto.
<div style={{ opacity: cargando ? 0.55 : 1, transition: "opacity .15s" }}>
<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginBottom: "20px" }}>
<StatTile label="Olvidos en el periodo" value={t.olvidos} nota={nota} />
<StatTile label="Becarios involucrados" value={t.becarios} />
<StatTile label="Olvidos de salida" value={t.olvido_salida} nota="jornadas sin marcar salida" />
</div>
{t.olvidos === 0 ? (
<EmptyState icon="listCheck" tone="green" title="Ningún olvido en el periodo"
sub={`Nadie dejó jornadas sin cerrar ni pidió correcciones en los ${data.dias} días anteriores.`} />
) : (
<div>
<Card style={{ marginBottom: "20px", padding: "20px 22px" }}>
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink, marginBottom: "10px" }}>Quién olvida más</div>
{/* Leyenda: siempre presente con 3 series; la identidad nunca es solo color */}
<div style={{ display: "flex", gap: "16px", flexWrap: "wrap", marginBottom: "12px" }}>
{SERIES.map((s) => (
<span key={s.key} style={{ display: "inline-flex", alignItems: "center", gap: "7px" }}>
<span style={{ width: "10px", height: "10px", borderRadius: "2px", background: s.color }} />
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft }}>{s.label}</span>
</span>
))}
</div>
{data.becarios.map((b) => <BarraOlvidos key={b.becario_id} b={b} max={max} />)}
</Card>
{/* Tabla gemela: todo valor es legible sin depender del color ni del hover */}
<Table head={["Becario", "Olvidó salida", "Olvidó entrada", "Jornada completa", "Total"]} minWidth={660}>
{data.becarios.map((b) => (
<Tr key={b.becario_id}>
<Td>
<div style={{ fontWeight: 600, color: palette.brand }}>{b.nombre}</div>
<div style={{ fontSize: "12px", color: palette.inkSoft, marginTop: "2px" }}>{b.telefono || "—"}</div>
</Td>
<Td nowrap style={{ fontVariantNumeric: "tabular-nums" }}>{b.olvido_salida}</Td>
<Td nowrap style={{ fontVariantNumeric: "tabular-nums" }}>{b.olvido_entrada}</Td>
<Td nowrap style={{ fontVariantNumeric: "tabular-nums" }}>{b.jornada_completa}</Td>
<Td nowrap style={{ fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{b.total}</Td>
</Tr>
))}
</Table>
</div>
)}
</div>
)}
</div>
);
}
// ═══════════════════ Shell / router ═══════════════════
function Panel({ session, onLogout }) {
const [view, setView] = useState({ name: "lista" });
@@ -630,6 +788,7 @@ function Panel({ session, onLogout }) {
const tabs = [
{ key: "lista", label: "Becarios" },
{ key: "solicitudes", label: "Solicitudes" },
{ key: "dashboard", label: "Dashboard" },
{ key: "config", label: "Configuración" },
];
const activeTab = view.name === "detalle" ? "lista" : view.name;
@@ -641,6 +800,7 @@ function Panel({ session, onLogout }) {
{view.name === "lista" && <VistaBecarios onOpen={(id) => setView({ name: "detalle", id })} onError={setError} />}
{view.name === "detalle" && <VistaBecario becarioId={view.id} onBack={() => setView({ name: "lista" })} onError={setError} />}
{view.name === "solicitudes" && <VistaSolicitudes onError={setError} />}
{view.name === "dashboard" && <VistaDashboard onError={setError} />}
{view.name === "config" && <VistaConfig onError={setError} />}
<PoweredBy />
</main>