- Se elimina por completo el tipo 'olvido_entrada': fuera del SQL (la consulta
ahora filtra por tipo IN ('autorizar_autocierre','jornada_completa'), así que
no entra al conteo ni al total, y quien solo tuviera ese tipo ya no aparece),
fuera de los KPIs, de las gráficas y de la columna de la tabla. No aplica en
la operación y no hay datos de ese tipo.
- Las dos categorías restantes dejan de ir apiladas y pasan a secciones
independientes, cada una con UNA sola serie (sin leyenda: el título de la
sección nombra la serie):
· "Olvidó salida": podio con los 3 primeros (1º resaltado) y el resto en las
barras horizontales de siempre. Las barras del resto se escalan al máximo
de la sección, no al del resto, para que un 4º con pocos olvidos no pinte
una barra tan larga como la del 1º.
· "Jornada completa": misma estructura de barras de mayor a menor, aparte.
- KPIs y tabla ajustados a las dos categorías.
Sin cambios en la lógica de datos: sigue derivando de solicitudes, excluyendo
las rechazadas, con el selector de periodo semana/mes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
889 lines
52 KiB
HTML
889 lines
52 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8"/>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
|
<title>Taboada — Panel de supervisión</title>
|
|
<link rel="preconnect" href="https://fonts.googleapis.com"/>
|
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
|
|
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700&family=Figtree:wght@400;500;600;700&display=swap" rel="stylesheet"/>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.2/babel.min.js"></script>
|
|
<script src="theme.js"></script>
|
|
<style>
|
|
* { box-sizing: border-box; }
|
|
html, body { margin: 0; padding: 0; }
|
|
body { background: #F3EBDD; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
|
|
input::placeholder { color: #B4A99A; }
|
|
@keyframes tb-spin { to { transform: rotate(360deg); } }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="root"></div>
|
|
<script type="text/babel" data-presets="react">
|
|
const { useState, useEffect, useCallback } = React;
|
|
|
|
// ═══════════════════════════════════════════════════════════
|
|
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
|
|
// tres páginas. El panel se sirve detrás de nginx (mismo origen); la cookie de
|
|
// sesión de la supervisora viaja con credentials:'include'. Mismo mapeo de
|
|
// error por code/status que antes; ahora en un solo sitio.
|
|
const { apiFetch } = Theme;
|
|
|
|
// Piel cream de escritorio (theme.js, flavor 'panel'). Nada de colores inline.
|
|
const UI = Theme.makeUI("panel");
|
|
const { Logo, Card, Btn, Input, Field, Badge, Aviso, ErrorBar, Toggle, ProgressBar,
|
|
Nav, Table, Tr, Td, Modal, EmptyState, palette, fonts, icons } = UI;
|
|
|
|
// ── Formato (presentación en America/Mexico_City) ──
|
|
function fmtDT(iso) {
|
|
if (!iso) return "—";
|
|
return new Date(iso).toLocaleString("es-MX", {
|
|
timeZone: "America/Mexico_City", day: "2-digit", month: "short",
|
|
year: "numeric", hour: "2-digit", minute: "2-digit",
|
|
});
|
|
}
|
|
// Día de la semana (capitalizado) en America/Mexico_City, p.ej. "Martes".
|
|
function fmtDia(iso) {
|
|
if (!iso) return "";
|
|
const d = new Date(iso).toLocaleDateString("es-MX", { timeZone: "America/Mexico_City", weekday: "long" });
|
|
return d.charAt(0).toUpperCase() + d.slice(1);
|
|
}
|
|
function fmtHoras(h) { return `${(h ?? 0).toLocaleString("es-MX", { maximumFractionDigits: 1 })} h`; }
|
|
// ISO(UTC) ↔ valor de <input type="datetime-local"> (zona local del navegador)
|
|
function isoToLocal(iso) {
|
|
if (!iso) return "";
|
|
const d = new Date(iso), p = (n) => String(n).padStart(2, "0");
|
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
}
|
|
function localToIso(v) { return v ? new Date(v).toISOString() : null; }
|
|
|
|
// Mapeo estado → tono del Badge (el Badge cream traduce el tono a color).
|
|
const estadoBecarioTone = (e) => ({ activo: "success", pendiente: "warn", baja: "chip" }[e] || "chip");
|
|
const estadoJornadaTone = (e) => ({ abierta: "primary", cerrada: "success", revision: "warn" }[e] || "chip");
|
|
const estadoDispTone = (e) => ({ pendiente: "warn", aprobado: "success", revocado: "danger" }[e] || "chip");
|
|
|
|
const iconBtn = (name, o) => <span style={{ display: "inline-flex" }}>{icons[name](o)}</span>;
|
|
|
|
// Pie de marca, compartido por login y panel.
|
|
const PoweredBy = () => (
|
|
<div style={{ textAlign: "center", padding: "22px 0 8px", fontFamily: fonts.body, fontSize: "11px", color: palette.inkSoft, letterSpacing: ".02em" }}>
|
|
<div>Powered by <span style={{ fontWeight: 600, color: palette.brand }}>Collina Systems</span></div>
|
|
<svg width="66" height="21" viewBox="0 0 200 64" fill="none" aria-hidden="true" style={{ display: "block", margin: "6px auto 0" }}>
|
|
<path d="M6 45 C 34 45 46 31 64 31 C 82 31 92 41 122 44" stroke={palette.ink} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" opacity="0.82"/>
|
|
<path d="M84 47 C 104 47 118 22 140 21 C 162 20 176 40 196 42" stroke={palette.ink} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" opacity="0.82"/>
|
|
</svg>
|
|
</div>
|
|
);
|
|
|
|
// ── Modal de confirmación (sustituye el diálogo nativo del navegador) ──
|
|
// La llamada al backend vive en `onConfirm` (el padre); aquí solo la UI.
|
|
function ConfirmModal({ title, message, confirmLabel, variant, onConfirm, onCancel }) {
|
|
const [busy, setBusy] = useState(false);
|
|
const go = async () => { setBusy(true); try { await onConfirm(); } finally { setBusy(false); } };
|
|
return (
|
|
<Modal title={title} onClose={onCancel} width={400}>
|
|
<p style={{ margin: "0 0 20px", fontFamily: fonts.body, fontSize: "14px", color: palette.ink, lineHeight: 1.5 }}>{message}</p>
|
|
<div style={{ display: "flex", gap: "9px" }}>
|
|
<Btn variant={variant || "primary"} loading={busy} onClick={go}>{confirmLabel || "Confirmar"}</Btn>
|
|
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Login ═══════════════════
|
|
function Login({ onLogin }) {
|
|
const [usuario, setUsuario] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
const [error, setError] = useState(null); // { text, ic }
|
|
const [busy, setBusy] = useState(false);
|
|
const submit = async (e) => {
|
|
e.preventDefault(); setBusy(true); setError(null);
|
|
try {
|
|
await apiFetch("/auth/login", { method: "POST", body: JSON.stringify({ usuario, password }) });
|
|
onLogin(await apiFetch("/auth/session"));
|
|
} catch (err) {
|
|
// Mismo mapeo por status de siempre; el ícono sólo acompaña.
|
|
setError(err.status === 429
|
|
? { text: "Demasiados intentos. Espera un minuto.", ic: "clock" }
|
|
: { text: "Usuario o contraseña incorrectos.", ic: "alertCircle" });
|
|
} finally { setBusy(false); }
|
|
};
|
|
return (
|
|
<div style={{ minHeight: "100vh", background: palette.bgGradient, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", fontFamily: fonts.body, padding: "24px" }}>
|
|
<Card style={{ width: "100%", maxWidth: "400px", borderRadius: "24px", padding: "36px 34px" }}>
|
|
<div style={{ display: "flex", justifyContent: "center", marginBottom: "18px" }}><Logo style={{ height: "60px" }} /></div>
|
|
<h1 style={{ margin: "0 0 24px", fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, textAlign: "center", letterSpacing: "-.01em" }}>Panel de supervisión</h1>
|
|
{error && <Aviso variant="error" icon={error.ic}>{error.text}</Aviso>}
|
|
<form onSubmit={submit}>
|
|
<Field label="Usuario"><Input value={usuario} onChange={(e) => setUsuario(e.target.value)} autoFocus autoComplete="username" /></Field>
|
|
<Field label="Contraseña"><Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" /></Field>
|
|
<div style={{ marginTop: "8px" }}>
|
|
<Btn type="submit" block loading={busy} disabled={busy || !usuario || !password}>{busy ? "Entrando…" : "Iniciar sesión"}</Btn>
|
|
</div>
|
|
</form>
|
|
</Card>
|
|
<PoweredBy />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Cola de aprobación de becarios ═══════════════════
|
|
function ColaAprobacion({ pendientes, onAprobar }) {
|
|
if (pendientes.length === 0) return null;
|
|
return (
|
|
<div style={{ background: palette.warnBg, border: `1px solid ${palette.warnBorder}`, borderRadius: "18px", padding: "18px 20px", marginBottom: "20px" }}>
|
|
<div style={{ display: "flex", alignItems: "center", gap: "9px", marginBottom: "13px" }}>
|
|
{iconBtn("alertTriangle", { size: 19, color: palette.amber })}
|
|
<span style={{ fontFamily: fonts.title, fontWeight: 600, fontSize: "15px", color: palette.warnText }}>Becarios pendientes de aprobar ({pendientes.length})</span>
|
|
</div>
|
|
<div style={{ display: "flex", flexDirection: "column", gap: "9px" }}>
|
|
{pendientes.map((b) => (
|
|
<div key={b.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: palette.surface, borderRadius: "12px", padding: "11px 14px", gap: "10px", flexWrap: "wrap" }}>
|
|
<div>
|
|
<strong style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.ink }}>{b.nombre}</strong>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, marginTop: "2px" }}>{b.telefono || "sin teléfono"}</div>
|
|
</div>
|
|
<Btn size="sm" variant="success" onClick={() => onAprobar(b)}>Aprobar</Btn>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Formulario de becario (modal alta/edición) ═══════════════════
|
|
function BecarioForm({ inicial, onSaved, onCancel, onError }) {
|
|
const [f, setF] = useState({
|
|
nombre: inicial?.nombre || "", matricula: inicial?.matricula || "",
|
|
institucion: inicial?.institucion || "", meta_horas: inicial?.meta_horas || 480,
|
|
});
|
|
const [busy, setBusy] = useState(false);
|
|
const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
|
|
const submit = async (e) => {
|
|
e.preventDefault(); setBusy(true);
|
|
try {
|
|
const body = {
|
|
nombre: f.nombre.trim(),
|
|
matricula: f.matricula.trim() || undefined,
|
|
institucion: f.institucion.trim() || undefined,
|
|
meta_horas: Number(f.meta_horas),
|
|
};
|
|
if (inicial) await apiFetch(`/becarios/${inicial.id}`, { method: "PATCH", body: JSON.stringify(body) });
|
|
else await apiFetch("/becarios", { method: "POST", body: JSON.stringify(body) });
|
|
onSaved();
|
|
} catch (err) { onError(err.message); } finally { setBusy(false); }
|
|
};
|
|
return (
|
|
<Modal title={inicial ? "Editar becario" : "Nuevo becario"} onClose={onCancel} width={540}>
|
|
<form onSubmit={submit}>
|
|
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 18px" }}>
|
|
<Field label="Nombre"><Input value={f.nombre} onChange={set("nombre")} required autoFocus /></Field>
|
|
<Field label="Matrícula"><Input value={f.matricula} onChange={set("matricula")} placeholder="Opcional" /></Field>
|
|
<Field label="Institución"><Input value={f.institucion} onChange={set("institucion")} placeholder="Opcional" /></Field>
|
|
<Field label="Meta de horas"><Input type="number" min="1" value={f.meta_horas} onChange={set("meta_horas")} required /></Field>
|
|
</div>
|
|
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
|
<Btn type="submit" loading={busy} disabled={busy || !f.nombre.trim()}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
|
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
|
</div>
|
|
</form>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Vista de becarios ═══════════════════
|
|
function VistaBecarios({ onOpen, onError }) {
|
|
const [becarios, setBecarios] = useState(null);
|
|
const [form, setForm] = useState(null); // null | {} (nuevo) | becario (editar)
|
|
const [confirmBaja, setConfirmBaja] = useState(null);
|
|
const [confirmEliminar, setConfirmEliminar] = useState(null);
|
|
const [q, setQ] = useState("");
|
|
const load = useCallback(async () => {
|
|
try { setBecarios(await apiFetch("/becarios")); } catch (e) { onError(e.message); }
|
|
}, [onError]);
|
|
useEffect(() => { load(); }, [load]);
|
|
const doBaja = async (b) => {
|
|
try { await apiFetch(`/becarios/${b.id}/baja`, { method: "POST" }); setConfirmBaja(null); await load(); }
|
|
catch (e) { onError(e.message); setConfirmBaja(null); }
|
|
};
|
|
const doEliminar = async (b) => {
|
|
try { await apiFetch(`/becarios/${b.id}`, { method: "DELETE" }); setConfirmEliminar(null); await load(); }
|
|
catch (e) { onError(e.message); setConfirmEliminar(null); }
|
|
};
|
|
const reactivar = async (b) => {
|
|
try { await apiFetch(`/becarios/${b.id}/reactivar`, { method: "POST" }); await load(); } catch (e) { onError(e.message); }
|
|
};
|
|
const aprobar = async (b) => {
|
|
try { await apiFetch(`/becarios/${b.id}/aprobar`, { method: "POST" }); await load(); } catch (e) { onError(e.message); }
|
|
};
|
|
const pendientes = (becarios || []).filter((b) => b.estado === "pendiente");
|
|
// Buscador local sobre la lista ya cargada (nombre, celular, matrícula, institución).
|
|
const term = q.trim().toLowerCase();
|
|
const filtrados = term
|
|
? (becarios || []).filter((b) =>
|
|
[b.nombre, b.telefono, b.matricula, b.institucion].some((c) => (c || "").toString().toLowerCase().includes(term)))
|
|
: (becarios || []);
|
|
return (
|
|
<div>
|
|
<ColaAprobacion pendientes={pendientes} onAprobar={aprobar} />
|
|
<div style={{ marginBottom: "16px" }}>
|
|
<h2 style={{ margin: 0, fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Becarios</h2>
|
|
</div>
|
|
{becarios === null ? <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p> :
|
|
becarios.length === 0 ? <EmptyState icon="users" tone="blue" title="Aún no hay becarios" sub="Los becarios aparecerán aquí cuando se registren desde su celular." /> :
|
|
<div>
|
|
<div style={{ position: "relative", maxWidth: "440px", marginBottom: "14px" }}>
|
|
<Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar por nombre, celular, matrícula o institución…" style={{ paddingRight: "34px" }} />
|
|
{q && <span onClick={() => setQ("")} title="Limpiar" style={{ position: "absolute", right: "11px", top: "50%", transform: "translateY(-50%)", cursor: "pointer", display: "inline-flex" }}>{icons.x({ size: 15, color: palette.inkSoft, sw: 2.2 })}</span>}
|
|
</div>
|
|
{filtrados.length === 0
|
|
? <p style={{ fontFamily: fonts.body, fontSize: "14px", color: palette.inkSoft }}>Sin resultados para «{q.trim()}».</p>
|
|
: <Table head={["Becario", "Institución", "Avance", "Estado", ""]} minWidth={720}>
|
|
{filtrados.map((b) => {
|
|
const h = b.horas || { total_horas: 0, meta_horas: b.meta_horas, porcentaje: 0 };
|
|
return (
|
|
<Tr key={b.id}>
|
|
<Td>
|
|
<div style={{ fontWeight: 600, color: palette.brand, cursor: "pointer" }} onClick={() => onOpen(b.id)}>{b.nombre}</div>
|
|
<div style={{ fontSize: "12px", color: palette.inkSoft, marginTop: "2px" }}>{[b.telefono, b.matricula].filter(Boolean).join(" · ") || "—"}</div>
|
|
</Td>
|
|
<Td soft>{b.institucion || "—"}</Td>
|
|
<Td style={{ minWidth: "180px" }}>
|
|
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "5px" }}>
|
|
<span style={{ color: palette.ink }}>{fmtHoras(h.total_horas)} / {fmtHoras(h.meta_horas)}</span>
|
|
<span style={{ color: palette.inkSoft }}>{h.porcentaje}%</span>
|
|
</div>
|
|
<ProgressBar value={h.porcentaje} />
|
|
</Td>
|
|
<Td><Badge tone={estadoBecarioTone(b.estado)}>{b.estado}</Badge></Td>
|
|
<Td nowrap>
|
|
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
|
{b.estado === "pendiente" && <Btn size="sm" variant="success" onClick={() => aprobar(b)}>Aprobar</Btn>}
|
|
<Btn size="sm" variant="ghost" onClick={() => onOpen(b.id)}>Ver</Btn>
|
|
<Btn size="sm" variant="subtle" onClick={() => setForm(b)}>Editar</Btn>
|
|
{b.estado !== "baja"
|
|
? <Btn size="sm" variant="link" onClick={() => setConfirmBaja(b)}>Baja</Btn>
|
|
: <>
|
|
<Btn size="sm" variant="success" onClick={() => reactivar(b)}>Reactivar</Btn>
|
|
<Btn size="sm" variant="danger" onClick={() => setConfirmEliminar(b)}>Eliminar</Btn>
|
|
</>}
|
|
</div>
|
|
</Td>
|
|
</Tr>
|
|
);
|
|
})}
|
|
</Table>}
|
|
</div>}
|
|
{form && <BecarioForm inicial={form.id ? form : null} onSaved={() => { setForm(null); load(); }} onCancel={() => setForm(null)} onError={onError} />}
|
|
{confirmBaja && <ConfirmModal title="Dar de baja" variant="danger" confirmLabel="Dar de baja"
|
|
message={`¿Dar de baja a ${confirmBaja.nombre}? Conserva su historial, no se elimina.`}
|
|
onConfirm={() => doBaja(confirmBaja)} onCancel={() => setConfirmBaja(null)} />}
|
|
{confirmEliminar && <ConfirmModal title="Eliminar becario" variant="danger" confirmLabel="Eliminar definitivamente"
|
|
message={`¿Eliminar definitivamente a ${confirmEliminar.nombre}? Esta acción no se puede deshacer. Solo procede si no tiene historial de checadas (esos registros son inmutables); si lo tiene, permanece de baja.`}
|
|
onConfirm={() => doEliminar(confirmEliminar)} onCancel={() => setConfirmEliminar(null)} />}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Editor de jornada (modal) ═══════════════════
|
|
function JornadaEditor({ jornada, onSaved, onCancel, onError }) {
|
|
const [entrada, setEntrada] = useState(isoToLocal(jornada.entrada_ts));
|
|
const [salida, setSalida] = useState(isoToLocal(jornada.salida_ts));
|
|
const [busy, setBusy] = useState(false);
|
|
const save = async () => {
|
|
setBusy(true);
|
|
try {
|
|
const body = {};
|
|
const eIso = localToIso(entrada), sIso = localToIso(salida);
|
|
if (eIso !== jornada.entrada_ts) body.entrada_ts = eIso;
|
|
if (sIso !== jornada.salida_ts && sIso) body.salida_ts = sIso;
|
|
if (Object.keys(body).length === 0) { onCancel(); return; }
|
|
await apiFetch(`/jornadas/${jornada.id}`, { method: "PATCH", body: JSON.stringify(body) });
|
|
onSaved();
|
|
} catch (e) { onError(e.message); } finally { setBusy(false); }
|
|
};
|
|
return (
|
|
<Modal title="Editar tiempos de jornada" sub="El valor original se respalda en la bitácora." onClose={onCancel}>
|
|
<Field label="Entrada"><Input type="datetime-local" value={entrada} onChange={(e) => setEntrada(e.target.value)} /></Field>
|
|
<Field label="Salida"><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
|
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
|
<Btn onClick={save} loading={busy} disabled={busy}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
|
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
// ── Cerrar jornada en revisión sin salida (antes, un diálogo nativo) ──
|
|
function CerrarJornadaModal({ jornada, onDone, onCancel, onError }) {
|
|
const [salida, setSalida] = useState("");
|
|
const [busy, setBusy] = useState(false);
|
|
const go = async () => {
|
|
const iso = localToIso(salida);
|
|
if (!iso) { onError("Fecha inválida"); return; }
|
|
setBusy(true);
|
|
try { await apiFetch(`/jornadas/${jornada.id}/cerrar`, { method: "POST", body: JSON.stringify({ salida_ts: iso }) }); onDone(); }
|
|
catch (e) { onError(e.message); } finally { setBusy(false); }
|
|
};
|
|
return (
|
|
<Modal title="Cerrar jornada" sub="Registra la hora de salida real para cerrar esta jornada en revisión." onClose={onCancel}>
|
|
<Field label="Hora de salida"><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
|
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
|
<Btn variant="success" onClick={go} loading={busy} disabled={busy || !salida}>Cerrar jornada</Btn>
|
|
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Vista por becario (detalle) ═══════════════════
|
|
function VistaBecario({ becarioId, onBack, onError }) {
|
|
const [data, setData] = useState(null);
|
|
const [jornadas, setJornadas] = useState([]);
|
|
const [checadas, setChecadas] = useState([]);
|
|
const [editJornada, setEditJornada] = useState(null);
|
|
const [cerrarJornada, setCerrarJornada] = useState(null);
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const [d, j, c] = await Promise.all([
|
|
apiFetch(`/becarios/${becarioId}`),
|
|
apiFetch(`/becarios/${becarioId}/jornadas`),
|
|
apiFetch(`/becarios/${becarioId}/checadas`),
|
|
]);
|
|
setData(d); setJornadas(j); setChecadas(c);
|
|
} catch (e) { onError(e.message); }
|
|
}, [becarioId, onError]);
|
|
useEffect(() => { load(); }, [load]);
|
|
|
|
const cerrar = async (j) => {
|
|
// Con salida ya registrada, cierra directo (POST {}); sin salida, pide la hora.
|
|
if (j.salida_ts) {
|
|
try { await apiFetch(`/jornadas/${j.id}/cerrar`, { method: "POST", body: JSON.stringify({}) }); await load(); }
|
|
catch (e) { onError(e.message); }
|
|
} else { setCerrarJornada(j); }
|
|
};
|
|
|
|
if (!data) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
|
const h = data.horas;
|
|
const sec = { margin: "0 0 12px", fontFamily: fonts.title, fontWeight: 600, fontSize: "17px", color: palette.brand };
|
|
|
|
// El acumulado corrido por jornada lo calcula el backend (j.acumulado_minutos)
|
|
// sobre TODAS las jornadas cerradas; aquí solo se pinta. metaMin es para el %.
|
|
const metaMin = (h.meta_horas || 0) * 60;
|
|
return (
|
|
<div>
|
|
<Btn variant="subtle" size="sm" onClick={onBack}>{iconBtn("chevronLeft", { size: 15, color: palette.label })}Volver a becarios</Btn>
|
|
<div style={{ margin: "18px 0 6px", display: "flex", alignItems: "center", gap: "12px", flexWrap: "wrap" }}>
|
|
<h2 style={{ margin: 0, fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, letterSpacing: "-.01em" }}>{data.nombre}</h2>
|
|
<Badge tone={estadoBecarioTone(data.estado)}>{data.estado}</Badge>
|
|
</div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, marginBottom: "20px" }}>
|
|
{[data.telefono, data.matricula, data.institucion].filter(Boolean).join(" · ") || "sin datos"}
|
|
</div>
|
|
|
|
<Card style={{ marginBottom: "20px", padding: "22px 24px" }}>
|
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: "10px" }}>
|
|
<span style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink }}>Avance</span>
|
|
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.placeholder }}>calculado por el backend</span>
|
|
</div>
|
|
<div style={{ fontFamily: fonts.title, fontWeight: 700, fontSize: "30px", color: palette.brand, letterSpacing: "-.01em" }}>
|
|
{fmtHoras(h.total_horas)} <span style={{ fontFamily: fonts.body, fontSize: "15px", color: palette.inkSoft, fontWeight: 500 }}>de {fmtHoras(h.meta_horas)} ({h.porcentaje}%)</span>
|
|
</div>
|
|
<div style={{ margin: "14px 0 8px" }}><ProgressBar value={h.porcentaje} height={9} /></div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.amber }}>
|
|
Las jornadas en revisión no suman al total.
|
|
</div>
|
|
</Card>
|
|
|
|
<h3 style={sec}>Jornadas</h3>
|
|
{jornadas.length === 0 ? <div style={{ marginBottom: "22px" }}><EmptyState icon="calendar" tone="neutral" title="Sin jornadas todavía" sub="Este becario aún no registra entradas ni salidas." /></div> :
|
|
<div style={{ marginBottom: "22px" }}>
|
|
<Table head={["Entrada", "Salida", "Concepto", "Duración", "Acumulado", "Estado", ""]} minWidth={880}>
|
|
{jornadas.map((j) => (
|
|
<Tr key={j.id}>
|
|
<Td nowrap>
|
|
<div style={{ fontFamily: fonts.body, fontWeight: 700, fontSize: "12px", color: palette.brand }}>{fmtDia(j.entrada_ts)}</div>
|
|
{fmtDT(j.entrada_ts)}
|
|
</Td>
|
|
<Td nowrap soft={!j.salida_ts}>{fmtDT(j.salida_ts)}</Td>
|
|
<Td ellipsis soft={!j.concepto} title={j.concepto || ""}>{j.concepto || "—"}</Td>
|
|
<Td nowrap soft={j.duracion_minutos == null}>{j.duracion_minutos != null ? `${(j.duracion_minutos / 60).toFixed(1)} h` : "—"}</Td>
|
|
<Td nowrap>
|
|
{((j.acumulado_minutos || 0) / 60).toFixed(1)} h
|
|
<span style={{ color: palette.inkSoft }}> · {metaMin ? Math.round(((j.acumulado_minutos || 0) / metaMin) * 100) : 0}%</span>
|
|
</Td>
|
|
<Td>
|
|
<Badge tone={estadoJornadaTone(j.estado)}>{j.estado}</Badge>
|
|
{j.editada && <span style={{ marginLeft: "6px", fontFamily: fonts.body, fontSize: "11px", color: palette.inkSoft }}>editada</span>}
|
|
</Td>
|
|
<Td nowrap>
|
|
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
|
<Btn size="sm" variant="subtle" onClick={() => setEditJornada(j)}>Editar</Btn>
|
|
{j.estado === "revision" && <Btn size="sm" variant="success" onClick={() => cerrar(j)}>Cerrar</Btn>}
|
|
</div>
|
|
</Td>
|
|
</Tr>
|
|
))}
|
|
</Table>
|
|
</div>}
|
|
|
|
<h3 style={{ ...sec, marginBottom: "6px" }}>Checadas <span style={{ fontFamily: fonts.body, fontWeight: 400, fontSize: "13px", color: palette.inkSoft }}>(con IP / dispositivo)</span></h3>
|
|
<p style={{ margin: "0 0 12px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft }}>
|
|
IP y user-agent son señal secundaria de anomalías, no prueba de ubicación.
|
|
</p>
|
|
{checadas.length === 0 ? <EmptyState icon="clock" tone="neutral" title="Sin checadas" sub="No hay registros de chip NFC para este becario." /> :
|
|
<Table head={["Momento", "Tipo", "Origen", "Concepto", "IP", "User-agent"]} minWidth={780}>
|
|
{checadas.map((c) => (
|
|
<Tr key={c.id}>
|
|
<Td nowrap>{fmtDT(c.ts)}</Td>
|
|
<Td><Badge tone={c.tipo === "entrada" ? "success" : "primary"}>{c.tipo}</Badge></Td>
|
|
<Td soft>{c.origen}</Td>
|
|
<Td soft>{c.concepto || "—"}</Td>
|
|
<Td soft mono>{c.ip || "—"}</Td>
|
|
<Td soft ellipsis title={c.user_agent || ""}>{c.user_agent || "—"}</Td>
|
|
</Tr>
|
|
))}
|
|
</Table>}
|
|
|
|
{editJornada && <JornadaEditor jornada={editJornada} onSaved={() => { setEditJornada(null); load(); }} onCancel={() => setEditJornada(null)} onError={onError} />}
|
|
{cerrarJornada && <CerrarJornadaModal jornada={cerrarJornada} onDone={() => { setCerrarJornada(null); load(); }} onCancel={() => setCerrarJornada(null)} onError={onError} />}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Configuración ═══════════════════
|
|
function VistaConfig({ onError }) {
|
|
const [cfg, setCfg] = useState(null);
|
|
const [f, setF] = useState({ inicio: "", fin: "", tarea_activa: false, meta: "", qr_rotacion: "" });
|
|
const [busy, setBusy] = useState(false);
|
|
const [okMsg, setOkMsg] = useState(null);
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const c = await apiFetch("/config");
|
|
setCfg(c);
|
|
setF({
|
|
inicio: c.ventana_horaria?.inicio || "06:00",
|
|
fin: c.ventana_horaria?.fin || "20:00",
|
|
tarea_activa: c.tarea_activa === true,
|
|
meta: c.meta_horas_default ?? 480,
|
|
qr_rotacion: c.qr_rotacion_seg ?? 45,
|
|
});
|
|
} catch (e) { onError(e.message); }
|
|
}, [onError]);
|
|
useEffect(() => { load(); }, [load]);
|
|
const guardar = async (e) => {
|
|
e.preventDefault(); setBusy(true); setOkMsg(null);
|
|
try {
|
|
await apiFetch("/config", { method: "PATCH", body: JSON.stringify({
|
|
ventana_horaria: { inicio: f.inicio, fin: f.fin },
|
|
tarea_activa: f.tarea_activa,
|
|
meta_horas_default: Number(f.meta),
|
|
qr_rotacion_seg: Number(f.qr_rotacion),
|
|
}) });
|
|
setOkMsg("Configuración guardada."); await load();
|
|
} catch (err) { onError(err.message); } finally { setBusy(false); }
|
|
};
|
|
if (!cfg) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
|
return (
|
|
<div>
|
|
<h2 style={{ margin: "0 0 16px", fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Configuración</h2>
|
|
<Card style={{ maxWidth: "560px" }}>
|
|
<form onSubmit={guardar}>
|
|
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.ink, marginBottom: "5px" }}>Ventana horaria de checado</div>
|
|
<p style={{ margin: "0 0 14px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, lineHeight: 1.5 }}>Fuera de este rango no se emiten tokens y las jornadas abiertas se auto-cierran a revisión.</p>
|
|
<div style={{ display: "flex", gap: "14px" }}>
|
|
<div style={{ flex: 1 }}><Field label="Inicio"><Input type="time" value={f.inicio} onChange={(e) => setF({ ...f, inicio: e.target.value })} /></Field></div>
|
|
<div style={{ flex: 1 }}><Field label="Fin"><Input type="time" value={f.fin} onChange={(e) => setF({ ...f, fin: e.target.value })} /></Field></div>
|
|
</div>
|
|
<div style={{ margin: "6px 0 18px" }}>
|
|
<Toggle checked={f.tarea_activa} onChange={(v) => setF({ ...f, tarea_activa: v })} label="Pedir el concepto de la tarea al checar (switch global)" />
|
|
</div>
|
|
<Field label="Meta de horas por defecto"><Input type="number" min="1" value={f.meta} onChange={(e) => setF({ ...f, meta: e.target.value })} style={{ maxWidth: "160px" }} /></Field>
|
|
|
|
<div style={{ borderTop: `1px solid ${palette.line}`, margin: "6px 0 14px" }} />
|
|
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.ink, marginBottom: "5px" }}>Kiosco de checada (QR)</div>
|
|
<p style={{ margin: "0 0 14px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, lineHeight: 1.5 }}>Cada cuánto rota el código del kiosco. La validez de cada código es el doble de este valor (colchón para quien escanea en el cambio).</p>
|
|
<Field label="Rotación del QR (segundos)"><Input type="number" min="10" max="300" value={f.qr_rotacion} onChange={(e) => setF({ ...f, qr_rotacion: e.target.value })} style={{ maxWidth: "160px" }} /></Field>
|
|
|
|
{okMsg && <Aviso variant="success" icon="check">{okMsg}</Aviso>}
|
|
<div style={{ marginTop: "6px", display: "flex", gap: "9px", flexWrap: "wrap" }}>
|
|
<Btn type="submit" loading={busy} disabled={busy}>{busy ? "Guardando…" : "Guardar configuración"}</Btn>
|
|
<a href="/kiosco.html" target="_blank" rel="noopener" style={{ textDecoration: "none" }}>
|
|
<Btn variant="outline">Abrir pantalla de kiosco ↗</Btn>
|
|
</a>
|
|
</div>
|
|
</form>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Cola de solicitudes ═══════════════════
|
|
// Autorizar/rechazar usan modales propios (antes, diálogos nativos del
|
|
// navegador); la llamada al backend por detrás no cambia.
|
|
function AutorizarModal({ solicitud, onDone, onCancel, onError }) {
|
|
const tipo = solicitud.tipo;
|
|
const conEntrada = tipo === "olvido_entrada" || tipo === "jornada_completa"; // pide hora de entrada
|
|
const salidaOpcional = tipo === "olvido_entrada"; // solo olvido admite salida vacía
|
|
const [entrada, setEntrada] = useState(conEntrada ? isoToLocal(solicitud.propuesta?.entrada_ts) : "");
|
|
const [salida, setSalida] = useState(tipo === "jornada_completa" ? isoToLocal(solicitud.propuesta?.salida_ts) : "");
|
|
const [busy, setBusy] = useState(false);
|
|
const go = async () => {
|
|
setBusy(true);
|
|
try {
|
|
const body = {};
|
|
if (conEntrada) {
|
|
const eIso = localToIso(entrada);
|
|
if (!eIso) { onError("Fecha de entrada inválida"); setBusy(false); return; }
|
|
body.entrada_ts = eIso;
|
|
const sIso = localToIso(salida);
|
|
if (sIso) body.salida_ts = sIso;
|
|
else if (!salidaOpcional) { onError("Fecha de salida inválida"); setBusy(false); return; }
|
|
} else {
|
|
const sIso = localToIso(salida);
|
|
if (!sIso) { onError("Fecha de salida inválida"); setBusy(false); return; }
|
|
body.salida_ts = sIso;
|
|
}
|
|
await apiFetch(`/solicitudes/${solicitud.id}/autorizar`, { method: "POST", body: JSON.stringify(body) });
|
|
onDone();
|
|
} catch (e) { onError(e.message); } finally { setBusy(false); }
|
|
};
|
|
const titulo = tipo === "olvido_entrada" ? "Autorizar olvido de entrada"
|
|
: tipo === "jornada_completa" ? "Autorizar día completo" : "Autorizar auto-cierre";
|
|
const sub = tipo === "olvido_entrada" ? "Confirma la hora de entrada; la salida es opcional (déjala vacía si sigue en curso)."
|
|
: tipo === "jornada_completa" ? "Confirma o corrige la entrada y la salida; al autorizar, el día suma a las horas."
|
|
: "Registra la hora de salida real para cerrar la jornada.";
|
|
const autorizarDisabled = busy || (conEntrada ? (!entrada || (!salidaOpcional && !salida)) : !salida);
|
|
return (
|
|
<Modal title={titulo} sub={sub} onClose={onCancel}>
|
|
{conEntrada && <Field label="Hora de entrada"><Input type="datetime-local" value={entrada} onChange={(e) => setEntrada(e.target.value)} /></Field>}
|
|
<Field label={salidaOpcional ? "Hora de salida (opcional)" : "Hora de salida"}><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
|
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
|
<Btn variant="success" onClick={go} loading={busy} disabled={autorizarDisabled}>Autorizar</Btn>
|
|
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
function VistaSolicitudes({ onError }) {
|
|
const [sols, setSols] = useState(null);
|
|
const [autorizar, setAutorizar] = useState(null);
|
|
const [confirmRechazo, setConfirmRechazo] = useState(null);
|
|
const load = useCallback(async () => {
|
|
try { setSols(await apiFetch("/solicitudes?estado=pendiente")); } catch (e) { onError(e.message); }
|
|
}, [onError]);
|
|
useEffect(() => { load(); }, [load]);
|
|
const doRechazo = async (s) => {
|
|
try { await apiFetch(`/solicitudes/${s.id}/rechazar`, { method: "POST" }); setConfirmRechazo(null); await load(); }
|
|
catch (e) { onError(e.message); setConfirmRechazo(null); }
|
|
};
|
|
if (sols === null) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
|
return (
|
|
<div>
|
|
<h2 style={{ margin: "0 0 16px", fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Solicitudes pendientes</h2>
|
|
{sols.length === 0 ? <EmptyState icon="listCheck" tone="green" title="No hay solicitudes pendientes" sub="Cuando un becario pida un olvido de entrada, un día completo o un auto-cierre, aparecerá aquí." /> :
|
|
sols.map((s) => (
|
|
<Card key={s.id} style={{ marginBottom: "14px", borderRadius: "16px", padding: "18px 20px" }}>
|
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "12px", flexWrap: "wrap" }}>
|
|
<div>
|
|
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink }}>
|
|
{s.tipo === "olvido_entrada" ? "Olvido de entrada"
|
|
: s.tipo === "jornada_completa" ? "Día completo"
|
|
: "Autorizar auto-cierre"}
|
|
</div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, marginTop: "3px" }}>
|
|
{s.becario_nombre} · {s.becario_telefono || "sin tel."}
|
|
</div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.ink, marginTop: "8px" }}>
|
|
{s.tipo === "olvido_entrada"
|
|
? <>Entrada propuesta: <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.entrada_ts)}</strong></>
|
|
: s.tipo === "jornada_completa"
|
|
? <>Propuesto: <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.entrada_ts)}</strong> → <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.salida_ts)}</strong>{s.propuesta?.concepto ? <> · «{s.propuesta.concepto}»</> : null}</>
|
|
: <>Jornada en revisión desde <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.entrada_ts)}</strong></>}
|
|
</div>
|
|
</div>
|
|
<div style={{ display: "flex", gap: "8px" }}>
|
|
<Btn size="sm" variant="success" onClick={() => setAutorizar(s)}>Autorizar</Btn>
|
|
<Btn size="sm" variant="outline" onClick={() => setConfirmRechazo(s)}>Rechazar</Btn>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
))}
|
|
{autorizar && <AutorizarModal solicitud={autorizar} onDone={() => { setAutorizar(null); load(); }} onCancel={() => setAutorizar(null)} onError={onError} />}
|
|
{confirmRechazo && <ConfirmModal title="Rechazar solicitud" variant="danger" confirmLabel="Rechazar"
|
|
message="¿Rechazar esta solicitud? El becario deberá volver a enviarla si fue un error."
|
|
onConfirm={() => doRechazo(confirmRechazo)} onCancel={() => setConfirmRechazo(null)} />}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════════ Dashboard de olvidos ═══════════════════
|
|
// Dos categorías INDEPENDIENTES, cada una en su sección y con UNA sola serie.
|
|
// Al no apilarse ni tocarse, el color ya no hace trabajo de identidad entre
|
|
// series (el título de cada sección la nombra), así que no hay leyenda y la
|
|
// adyacencia CVD deja de aplicar; cada hue solo debe pasar contraste sobre la
|
|
// superficie, y ambos lo hacen (≥3:1 sobre blanco, verificado).
|
|
const TIPO_SALIDA = { key: "olvido_salida", label: "Olvidó salida", color: "#B7791F" };
|
|
const TIPO_JORNADA = { 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>
|
|
);
|
|
}
|
|
|
|
// Barra horizontal de una sola serie: base cuadrada, punta redondeada 4px, alto
|
|
// 18px (≤24), valor directo en la punta. El hover aporta el teléfono —dato que
|
|
// no está en la gráfica— y nunca es la única vía: todo vive también en la tabla.
|
|
function BarraSimple({ nombre, telefono, valor, max, color, unidad }) {
|
|
const [hover, setHover] = useState(false);
|
|
const pct = max > 0 ? (valor / 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={nombre} style={{ width: "180px", flexShrink: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.ink }}>
|
|
{nombre}
|
|
</div>
|
|
<div style={{ flex: 1, display: "flex", alignItems: "center", gap: "9px", minWidth: 0 }}>
|
|
<div style={{ width: pct + "%", minWidth: "4px", height: "18px", background: color, borderRadius: "0 4px 4px 0" }} />
|
|
<span style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 700, color: palette.ink, fontVariantNumeric: "tabular-nums" }}>{valor}</span>
|
|
</div>
|
|
{hover && (
|
|
<div style={{ position: "absolute", right: 0, bottom: "100%", marginBottom: "4px", zIndex: 20, minWidth: "180px", 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 }}>{nombre}</div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "11px", color: palette.inkSoft, marginTop: "2px" }}>{telefono || "sin teléfono"}</div>
|
|
<div style={{ display: "flex", alignItems: "center", gap: "7px", marginTop: "6px" }}>
|
|
<span style={{ width: "9px", height: "9px", borderRadius: "2px", background: color, flexShrink: 0 }} />
|
|
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.ink }}>
|
|
<strong>{valor}</strong> {unidad}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Podio de los 3 que más olvidaron la salida. El color NO codifica el rango
|
|
// (es el mismo de la sección): el rango lo llevan la posición, la etiqueta
|
|
// 1º/2º/3º y el énfasis visual del primero.
|
|
function Podio({ top, color }) {
|
|
return (
|
|
<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
|
|
{top.map((b, i) => {
|
|
const primero = i === 0;
|
|
return (
|
|
<div key={b.becario_id} style={{
|
|
flex: 1, minWidth: "172px",
|
|
background: primero ? palette.amberTint : palette.surface,
|
|
border: `1px solid ${primero ? palette.warnBorder : palette.cardBorder}`,
|
|
borderRadius: "16px", padding: "16px 18px",
|
|
}}>
|
|
<div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "9px" }}>
|
|
{/* El numeral va sobre fondo claro, no sobre el ámbar sólido: ni
|
|
blanco ni tinta clarean 4.5:1 sobre ese relleno (queda a media
|
|
luminancia). El aro ámbar del 1º da la identidad de la sección. */}
|
|
<span style={{
|
|
display: "inline-flex", alignItems: "center", justifyContent: "center",
|
|
width: "24px", height: "24px", borderRadius: "50%", flexShrink: 0,
|
|
background: primero ? palette.surface : palette.neutralTint,
|
|
border: primero ? `1.5px solid ${color}` : "none",
|
|
color: palette.ink,
|
|
fontFamily: fonts.body, fontWeight: 700, fontSize: "12px",
|
|
}}>{i + 1}</span>
|
|
<span style={{ fontFamily: fonts.body, fontSize: "11px", fontWeight: 600, color: palette.label, letterSpacing: ".04em", textTransform: "uppercase" }}>{i + 1}º lugar</span>
|
|
</div>
|
|
<div title={b.nombre} style={{ fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.ink, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{b.nombre}</div>
|
|
<div style={{ fontFamily: fonts.title, fontWeight: 700, fontSize: primero ? "34px" : "28px", color: palette.brand, lineHeight: 1.15, letterSpacing: "-.01em", marginTop: "1px" }}>{b.valor}</div>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "11px", color: palette.placeholder }}>
|
|
{b.valor === 1 ? "olvido de salida" : "olvidos de salida"}
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function SinDatos({ texto }) {
|
|
return <p style={{ margin: 0, fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft }}>{texto}</p>;
|
|
}
|
|
|
|
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 nota = periodo === "semana" ? "últimos 7 días" : "últimos 30 días";
|
|
|
|
// Cada sección se ordena por SU categoría y solo incluye a quien tiene >0.
|
|
const ordenar = (campo) => !data ? [] : data.becarios
|
|
.filter((b) => b[campo] > 0)
|
|
.slice()
|
|
.sort((x, y) => y[campo] - x[campo] || x.nombre.localeCompare(y.nombre));
|
|
const porSalida = ordenar(TIPO_SALIDA.key);
|
|
const porJornada = ordenar(TIPO_JORNADA.key);
|
|
const podio = porSalida.slice(0, 3).map((b) => ({ becario_id: b.becario_id, nombre: b.nombre, valor: b.olvido_salida }));
|
|
const restoSalida = porSalida.slice(3);
|
|
// Las barras del resto se escalan al máximo de la SECCIÓN (el 1º del podio),
|
|
// no al máximo del resto: de otro modo el 4º con 2 olvidos pintaría una barra
|
|
// tan larga como la del 1º con 6 y la sección se leería al revés.
|
|
const maxResto = Math.max.apply(null, porSalida.map((b) => b.olvido_salida).concat([1]));
|
|
const maxJornada = Math.max.apply(null, porJornada.map((b) => b.jornada_completa).concat([1]));
|
|
const tituloSeccion = { fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink, marginBottom: "3px" };
|
|
const subSeccion = { fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, marginBottom: "14px" };
|
|
|
|
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, 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="Olvidó salida" value={t.olvido_salida} nota="jornadas sin marcar salida" />
|
|
<StatTile label="Jornada completa" value={t.jornada_completa} nota="días cargados después" />
|
|
</div>
|
|
|
|
{t.olvidos === 0 ? (
|
|
<EmptyState icon="listCheck" tone="green" title="Ningún olvido en el periodo"
|
|
sub={`Nadie dejó jornadas sin cerrar ni cargó días en los ${data.dias} días anteriores.`} />
|
|
) : (
|
|
<div>
|
|
{/* ── Sección 1: Olvidó salida (podio + resto) ── */}
|
|
<Card style={{ marginBottom: "18px", padding: "20px 22px" }}>
|
|
<div style={tituloSeccion}>Olvidó salida</div>
|
|
<div style={subSeccion}>Jornadas que se auto-cerraron a revisión por no marcar la salida.</div>
|
|
{porSalida.length === 0 ? <SinDatos texto="Nadie dejó jornadas sin cerrar en el periodo." /> : (
|
|
<div>
|
|
<Podio top={podio} color={TIPO_SALIDA.color} />
|
|
{restoSalida.length > 0 && (
|
|
<div style={{ marginTop: "18px", borderTop: `1px solid ${palette.cardBorder}`, paddingTop: "12px" }}>
|
|
<div style={{ fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, color: palette.inkSoft, marginBottom: "4px" }}>El resto</div>
|
|
{restoSalida.map((b) => (
|
|
<BarraSimple key={b.becario_id} nombre={b.nombre} telefono={b.telefono}
|
|
valor={b.olvido_salida} max={maxResto} color={TIPO_SALIDA.color} unidad="olvidos de salida" />
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</Card>
|
|
|
|
{/* ── Sección 2: Jornada completa (barras de mayor a menor) ── */}
|
|
<Card style={{ marginBottom: "20px", padding: "20px 22px" }}>
|
|
<div style={tituloSeccion}>Jornada completa</div>
|
|
<div style={subSeccion}>Días que no se checaron y se cargaron después.</div>
|
|
{porJornada.length === 0 ? <SinDatos texto="Nadie cargó jornadas pasadas en el periodo." /> : (
|
|
porJornada.map((b) => (
|
|
<BarraSimple key={b.becario_id} nombre={b.nombre} telefono={b.telefono}
|
|
valor={b.jornada_completa} max={maxJornada} color={TIPO_JORNADA.color} unidad="jornadas cargadas" />
|
|
))
|
|
)}
|
|
</Card>
|
|
|
|
{/* Tabla gemela: todo valor es legible sin depender del color ni del hover */}
|
|
<Table head={["Becario", "Olvidó salida", "Jornada completa", "Total"]} minWidth={600}>
|
|
{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.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" });
|
|
const [error, setError] = useState(null);
|
|
const logout = async () => { try { await apiFetch("/auth/logout", { method: "POST" }); } catch {} 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;
|
|
return (
|
|
<div style={{ minHeight: "100vh", background: palette.bgGradient, fontFamily: fonts.body }}>
|
|
<Nav tabs={tabs} active={activeTab} onTab={(k) => setView({ name: k })} user={session.usuario} onLogout={logout} />
|
|
<main style={{ maxWidth: "1040px", margin: "0 auto", padding: "26px 24px 60px" }}>
|
|
<ErrorBar error={error} onClose={() => setError(null)} />
|
|
{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>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function App() {
|
|
const [session, setSession] = useState(undefined); // undefined=cargando, null=sin sesión
|
|
useEffect(() => { apiFetch("/auth/session").then(setSession).catch(() => setSession(null)); }, []);
|
|
if (session === undefined)
|
|
return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: fonts.body, color: palette.inkSoft }}>Cargando…</div>;
|
|
if (!session) return <Login onLogin={setSession} />;
|
|
return <Panel session={session} onLogout={() => setSession(null)} />;
|
|
}
|
|
|
|
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
|
|
</script>
|
|
</body>
|
|
</html>
|