Files
taboada-registros/frontend/panel.html
T
Collina Systems 6465bf0cd7 feat(panel): vistas de aprobar becarios, configuración, solicitudes e ip/ua
- ColaAprobacion reemplaza la cola de dispositivos (obsoleta): aprueba
  becarios pendiente→activo; lista muestra teléfono y botón Aprobar
- VistaConfig: edita ventana horaria + switch de tarea + meta default
- VistaSolicitudes: cola con autorizar (corrige tiempos) / rechazar
- detalle del becario: tabla de checadas con ip/user_agent/concepto
- nav Becarios/Solicitudes/Configuración
- override monta el directorio frontend (hot-edit sin recrear)
2026-07-04 23:18:19 -06:00

682 lines
37 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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>
<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>
</head>
<body style="margin:0;padding:0;">
<div id="root"></div>
<script type="text/babel" data-presets="react">
const { useState, useEffect, useCallback } = React;
// ═══════════════════════════════════════════════════════════
// API — el panel se sirve detrás de nginx (mismo origen); nginx hace
// proxy_pass de /api al servicio node. credentials:'include' manda la
// cookie de sesión de la supervisora en cada request.
// ═══════════════════════════════════════════════════════════
const API_BASE = `${window.location.origin}/api`;
async function apiFetch(path, options = {}) {
const res = await fetch(`${API_BASE}${path}`, {
credentials: "include",
...options,
headers: { "Content-Type": "application/json", ...(options.headers || {}) },
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code;
err.status = res.status;
throw err;
}
return data;
}
const COLORS = {
bg: "#EEF1F4", surface: "#FFFFFF", ink: "#1F2933", inkSoft: "#616E7C",
border: "#DDE2E7", primary: "#2A6FB0", primaryDark: "#1E4E7E",
success: "#2E7D5B", successBg: "#E7F3EC", warn: "#B7791F", warnBg: "#FBF2E1",
danger: "#C0392B", dangerBg: "#FBEBE9", chip: "#F0F2F5", accentBg: "#EAF2FA",
};
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
// ── Formato (presentación en America/Mexico_City, §7) ──
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",
});
}
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; }
// ═══════════════════ UI primitivos ═══════════════════
const Btn = ({ children, onClick, variant = "primary", disabled, size = "md", type = "button" }) => {
const V = {
primary: { bg: COLORS.primary, c: "#fff", bd: "none" },
success: { bg: COLORS.success, c: "#fff", bd: "none" },
danger: { bg: COLORS.danger, c: "#fff", bd: "none" },
ghost: { bg: "transparent", c: COLORS.primary, bd: `1px solid ${COLORS.border}` },
subtle: { bg: COLORS.chip, c: COLORS.ink, bd: "none" },
}[variant];
const pad = size === "sm" ? "6px 12px" : "10px 18px";
return (
<button type={type} onClick={onClick} disabled={disabled} style={{
padding: pad, borderRadius: "8px", background: disabled ? COLORS.border : V.bg,
color: disabled ? COLORS.inkSoft : V.c, border: V.bd, fontFamily: FONT,
fontSize: size === "sm" ? "13px" : "14px", fontWeight: 600,
cursor: disabled ? "not-allowed" : "pointer", transition: "opacity .15s",
}}>{children}</button>
);
};
const Card = ({ children, style }) => (
<div style={{ background: COLORS.surface, borderRadius: "12px", border: `1px solid ${COLORS.border}`,
padding: "20px", boxShadow: "0 1px 3px rgba(0,0,0,0.04)", ...style }}>{children}</div>
);
const Field = ({ label, children }) => (
<label style={{ display: "block", marginBottom: "12px" }}>
<span style={{ display: "block", fontSize: "13px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "5px" }}>{label}</span>
{children}
</label>
);
const inputStyle = {
width: "100%", padding: "9px 11px", borderRadius: "8px", border: `1px solid ${COLORS.border}`,
fontSize: "14px", fontFamily: FONT, color: COLORS.ink, boxSizing: "border-box", outline: "none",
};
const Input = (p) => <input {...p} style={{ ...inputStyle, ...(p.style || {}) }} />;
const Badge = ({ children, tone = "chip" }) => {
const T = {
chip: { bg: COLORS.chip, c: COLORS.inkSoft }, success: { bg: COLORS.successBg, c: COLORS.success },
warn: { bg: COLORS.warnBg, c: COLORS.warn }, danger: { bg: COLORS.dangerBg, c: COLORS.danger },
primary: { bg: COLORS.accentBg, c: COLORS.primaryDark },
}[tone];
return <span style={{ background: T.bg, color: T.c, padding: "2px 9px", borderRadius: "999px",
fontSize: "12px", fontWeight: 700, whiteSpace: "nowrap" }}>{children}</span>;
};
const ErrorBar = ({ error, onClose }) => !error ? null : (
<div style={{ background: COLORS.dangerBg, color: COLORS.danger, padding: "10px 14px", borderRadius: "8px",
fontSize: "14px", marginBottom: "14px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<span>⚠ {error}</span>
<span onClick={onClose} style={{ cursor: "pointer", fontWeight: 700, paddingLeft: "12px" }}>✕</span>
</div>
);
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");
// ═══════════════════ Login ═══════════════════
function Login({ onLogin }) {
const [usuario, setUsuario] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
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 }) });
const s = await apiFetch("/auth/session");
onLogin(s);
} catch (err) {
setError(err.status === 429 ? "Demasiados intentos. Espera un minuto." : "Usuario o contraseña incorrectos.");
} finally { setBusy(false); }
};
return (
<div style={{ minHeight: "100vh", background: COLORS.bg, display: "flex", alignItems: "center",
justifyContent: "center", fontFamily: FONT, padding: "24px" }}>
<Card style={{ width: "100%", maxWidth: "380px" }}>
<h1 style={{ margin: "0 0 4px", fontSize: "22px", color: COLORS.ink }}>Taboada</h1>
<p style={{ margin: "0 0 20px", fontSize: "14px", color: COLORS.inkSoft }}>Panel de supervisión</p>
<ErrorBar error={error} onClose={() => setError(null)} />
<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" disabled={busy || !usuario || !password}>{busy ? "Entrando…" : "Iniciar sesión"}</Btn>
</div>
</form>
</Card>
</div>
);
}
// ═══════════════════ Cola de aprobación de becarios ═══════════════════
// Los becarios se auto-registran (celular+password) y quedan 'pendiente'
// hasta que la supervisora los aprueba (§4). Sin vínculo de dispositivo.
function ColaAprobacion({ pendientes, onAprobar }) {
if (pendientes.length === 0) return null;
return (
<Card style={{ marginBottom: "18px", borderColor: COLORS.warn, background: COLORS.warnBg }}>
<h3 style={{ margin: "0 0 12px", fontSize: "15px", color: COLORS.warn }}>
Becarios pendientes de aprobar ({pendientes.length})
</h3>
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
{pendientes.map((b) => (
<div key={b.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
background: COLORS.surface, borderRadius: "8px", padding: "10px 12px", gap: "10px", flexWrap: "wrap" }}>
<div style={{ fontSize: "14px", color: COLORS.ink }}>
<strong>{b.nombre}</strong>
<div style={{ fontSize: "12px", color: COLORS.inkSoft, marginTop: "2px" }}>{b.telefono || "sin teléfono"}</div>
</div>
<Btn size="sm" variant="success" onClick={() => onAprobar(b)}>Aprobar</Btn>
</div>
))}
</div>
</Card>
);
}
// ═══════════════════ Formulario de becario (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 (
<Card style={{ marginBottom: "18px" }}>
<h3 style={{ margin: "0 0 14px", fontSize: "16px", color: COLORS.ink }}>{inicial ? "Editar becario" : "Nuevo becario"}</h3>
<form onSubmit={submit}>
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: "0 16px" }}>
<Field label="Nombre"><Input value={f.nombre} onChange={set("nombre")} required autoFocus /></Field>
<Field label="Matrícula"><Input value={f.matricula} onChange={set("matricula")} /></Field>
<Field label="Institución"><Input value={f.institucion} onChange={set("institucion")} /></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: "8px", marginTop: "6px" }}>
<Btn type="submit" disabled={busy || !f.nombre.trim()}>{busy ? "Guardando…" : "Guardar"}</Btn>
<Btn variant="subtle" onClick={onCancel}>Cancelar</Btn>
</div>
</form>
</Card>
);
}
// ═══════════════════ Vista de becarios ═══════════════════
function VistaBecarios({ onOpen, onError }) {
const [becarios, setBecarios] = useState(null);
const [form, setForm] = useState(null); // null | {} (nuevo) | becario (editar)
const load = useCallback(async () => {
try { setBecarios(await apiFetch("/becarios")); } catch (e) { onError(e.message); }
}, [onError]);
useEffect(() => { load(); }, [load]);
const baja = async (b) => {
if (!confirm(`¿Dar de baja a ${b.nombre}? Conserva su historial, no se elimina.`)) return;
try { await apiFetch(`/becarios/${b.id}/baja`, { 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");
return (
<div>
<ColaAprobacion pendientes={pendientes} onAprobar={aprobar} />
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "14px" }}>
<h2 style={{ margin: 0, fontSize: "18px", color: COLORS.ink }}>Becarios</h2>
{!form && <Btn onClick={() => setForm({})}>+ Nuevo becario</Btn>}
</div>
{form && <BecarioForm inicial={form.id ? form : null}
onSaved={() => { setForm(null); load(); }} onCancel={() => setForm(null)} onError={onError} />}
{becarios === null ? <p style={{ color: COLORS.inkSoft }}>Cargando…</p> :
becarios.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>Aún no hay becarios. Crea el primero.</p></Card> :
<Card style={{ padding: 0, overflow: "hidden" }}>
<div style={{ overflowX: "auto" }}>
<table style={{ width: "100%", borderCollapse: "collapse", fontFamily: FONT, fontSize: "14px" }}>
<thead>
<tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
{["Becario", "Institución", "Avance", "Estado", ""].map((h, i) =>
<th key={i} style={{ padding: "11px 14px", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}
</tr>
</thead>
<tbody>
{becarios.map((b) => {
const h = b.horas || { total_horas: 0, meta_horas: b.meta_horas, porcentaje: 0 };
return (
<tr key={b.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
<td style={{ padding: "11px 14px" }}>
<div style={{ fontWeight: 600, color: COLORS.ink, cursor: "pointer" }} onClick={() => onOpen(b.id)}>{b.nombre}</div>
<div style={{ fontSize: "12px", color: COLORS.inkSoft }}>{[b.telefono, b.matricula].filter(Boolean).join(" · ") || "—"}</div>
</td>
<td style={{ padding: "11px 14px", color: COLORS.inkSoft }}>{b.institucion || "—"}</td>
<td style={{ padding: "11px 14px", minWidth: "160px" }}>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "4px" }}>
<span style={{ color: COLORS.ink }}>{fmtHoras(h.total_horas)} / {fmtHoras(h.meta_horas)}</span>
<span style={{ color: COLORS.inkSoft }}>{h.porcentaje}%</span>
</div>
<div style={{ height: "6px", background: COLORS.chip, borderRadius: "999px", overflow: "hidden" }}>
<div style={{ height: "100%", width: `${Math.min(100, h.porcentaje)}%`,
background: h.porcentaje >= 100 ? COLORS.success : COLORS.primary }} />
</div>
</td>
<td style={{ padding: "11px 14px" }}><Badge tone={estadoBecarioTone(b.estado)}>{b.estado}</Badge></td>
<td style={{ padding: "11px 14px", whiteSpace: "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="ghost" onClick={() => baja(b)}>Baja</Btn>}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Card>}
</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 (
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", display: "flex",
alignItems: "center", justifyContent: "center", padding: "20px", zIndex: 10 }}>
<Card style={{ width: "100%", maxWidth: "380px" }}>
<h3 style={{ margin: "0 0 6px", fontSize: "16px", color: COLORS.ink }}>Editar tiempos de jornada</h3>
<p style={{ margin: "0 0 14px", fontSize: "12px", color: COLORS.inkSoft }}>
El valor original se respalda en la bitácora.</p>
<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: "8px", marginTop: "6px" }}>
<Btn onClick={save} disabled={busy}>{busy ? "Guardando…" : "Guardar"}</Btn>
<Btn variant="subtle" onClick={onCancel}>Cancelar</Btn>
</div>
</Card>
</div>
);
}
// ═══════════════════ Vista por becario ═══════════════════
function VistaBecario({ becarioId, onBack, onError }) {
const [data, setData] = useState(null); // becario + horas
const [jornadas, setJornadas] = useState([]);
const [ajustes, setAjustes] = useState([]);
const [checadas, setChecadas] = useState([]);
const [editJornada, setEditJornada] = useState(null);
const [ajuste, setAjuste] = useState({ minutos: "", motivo: "" });
const [busyAjuste, setBusyAjuste] = useState(false);
const load = useCallback(async () => {
try {
const [d, j, a, c] = await Promise.all([
apiFetch(`/becarios/${becarioId}`),
apiFetch(`/becarios/${becarioId}/jornadas`),
apiFetch(`/becarios/${becarioId}/ajustes`),
apiFetch(`/becarios/${becarioId}/checadas`),
]);
setData(d); setJornadas(j); setAjustes(a); setChecadas(c);
} catch (e) { onError(e.message); }
}, [becarioId, onError]);
useEffect(() => { load(); }, [load]);
const cerrar = async (j) => {
let salida_ts;
if (!j.salida_ts) {
const v = prompt("Fecha/hora de salida (YYYY-MM-DD HH:MM):");
if (!v) return;
const iso = localToIso(v.replace(" ", "T"));
if (!iso) { onError("Fecha inválida"); return; }
salida_ts = iso;
}
try {
await apiFetch(`/jornadas/${j.id}/cerrar`, { method: "POST", body: JSON.stringify(salida_ts ? { salida_ts } : {}) });
await load();
} catch (e) { onError(e.message); }
};
const crearAjuste = async (e) => {
e.preventDefault(); setBusyAjuste(true);
try {
await apiFetch(`/becarios/${becarioId}/ajustes`, {
method: "POST", body: JSON.stringify({ minutos: Number(ajuste.minutos), motivo: ajuste.motivo.trim() }),
});
setAjuste({ minutos: "", motivo: "" }); await load();
} catch (err) { onError(err.message); } finally { setBusyAjuste(false); }
};
if (!data) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
const h = data.horas;
return (
<div>
{editJornada && <JornadaEditor jornada={editJornada}
onSaved={() => { setEditJornada(null); load(); }} onCancel={() => setEditJornada(null)} onError={onError} />}
<Btn variant="subtle" size="sm" onClick={onBack}>← Volver a becarios</Btn>
<div style={{ margin: "14px 0 18px", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "12px", flexWrap: "wrap" }}>
<div>
<h2 style={{ margin: "0 0 4px", fontSize: "20px", color: COLORS.ink }}>{data.nombre}</h2>
<div style={{ fontSize: "13px", color: COLORS.inkSoft }}>
{[data.telefono, data.matricula, data.institucion].filter(Boolean).join(" · ") || "sin datos"}
{" "}<Badge tone={estadoBecarioTone(data.estado)}>{data.estado}</Badge>
</div>
</div>
</div>
<Card style={{ marginBottom: "18px" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: "8px" }}>
<span style={{ fontSize: "15px", fontWeight: 600, color: COLORS.ink }}>Avance</span>
<span style={{ fontSize: "13px", color: COLORS.inkSoft }}>calculado por el backend</span>
</div>
<div style={{ fontSize: "26px", fontWeight: 700, color: COLORS.ink }}>
{fmtHoras(h.total_horas)} <span style={{ fontSize: "15px", color: COLORS.inkSoft, fontWeight: 500 }}>de {fmtHoras(h.meta_horas)} ({h.porcentaje}%)</span>
</div>
<div style={{ height: "8px", background: COLORS.chip, borderRadius: "999px", overflow: "hidden", margin: "10px 0" }}>
<div style={{ height: "100%", width: `${Math.min(100, h.porcentaje)}%`, background: h.porcentaje >= 100 ? COLORS.success : COLORS.primary }} />
</div>
<div style={{ fontSize: "13px", color: COLORS.inkSoft }}>
Jornadas cerradas: {(h.minutos_jornadas / 60).toFixed(1)} h · Ajustes: {(h.minutos_ajustes / 60).toFixed(1)} h
<span style={{ color: COLORS.warn }}> · las jornadas en revisión no suman</span>
</div>
</Card>
<h3 style={{ margin: "0 0 10px", fontSize: "16px", color: COLORS.ink }}>Jornadas</h3>
{jornadas.length === 0 ? <Card style={{ marginBottom: "18px" }}><p style={{ margin: 0, color: COLORS.inkSoft }}>Sin jornadas.</p></Card> :
<Card style={{ padding: 0, marginBottom: "18px", overflow: "hidden" }}>
<div style={{ overflowX: "auto" }}>
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px", fontFamily: FONT }}>
<thead><tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
{["Entrada", "Salida", "Duración", "Estado", ""].map((c, i) => <th key={i} style={{ padding: "10px 12px", fontWeight: 600, whiteSpace: "nowrap" }}>{c}</th>)}
</tr></thead>
<tbody>
{jornadas.map((j) => (
<tr key={j.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{fmtDT(j.entrada_ts)}</td>
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{fmtDT(j.salida_ts)}</td>
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{j.duracion_minutos != null ? `${(j.duracion_minutos / 60).toFixed(1)} h` : "—"}</td>
<td style={{ padding: "10px 12px" }}>
<Badge tone={estadoJornadaTone(j.estado)}>{j.estado}</Badge>
{j.editada && <span style={{ marginLeft: "6px", fontSize: "11px", color: COLORS.inkSoft }}>editada</span>}
</td>
<td style={{ padding: "10px 12px", whiteSpace: "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>
))}
</tbody>
</table>
</div>
</Card>}
<h3 style={{ margin: "0 0 10px", fontSize: "16px", color: COLORS.ink }}>Ajustes</h3>
<Card>
<form onSubmit={crearAjuste} style={{ display: "flex", gap: "10px", alignItems: "flex-end", flexWrap: "wrap", marginBottom: ajustes.length ? "16px" : 0 }}>
<div style={{ width: "120px" }}>
<Field label="Minutos (+/−)"><Input type="number" value={ajuste.minutos} onChange={(e) => setAjuste({ ...ajuste, minutos: e.target.value })} placeholder="ej. 60 o -30" required /></Field>
</div>
<div style={{ flex: 1, minWidth: "200px" }}>
<Field label="Motivo (obligatorio)"><Input value={ajuste.motivo} onChange={(e) => setAjuste({ ...ajuste, motivo: e.target.value })} required /></Field>
</div>
<div style={{ marginBottom: "12px" }}>
<Btn type="submit" disabled={busyAjuste || !ajuste.minutos || Number(ajuste.minutos) === 0 || !ajuste.motivo.trim()}>Agregar</Btn>
</div>
</form>
{ajustes.map((a) => (
<div key={a.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
borderTop: `1px solid ${COLORS.border}`, padding: "10px 0", gap: "10px" }}>
<div style={{ fontSize: "14px", color: COLORS.ink }}>
<strong style={{ color: a.minutos >= 0 ? COLORS.success : COLORS.danger }}>{a.minutos >= 0 ? "+" : ""}{a.minutos} min</strong>
<span style={{ color: COLORS.inkSoft }}> · {a.motivo}</span>
</div>
<span style={{ fontSize: "12px", color: COLORS.inkSoft, whiteSpace: "nowrap" }}>{fmtDT(a.created_at)}</span>
</div>
))}
</Card>
<h3 style={{ margin: "18px 0 10px", fontSize: "16px", color: COLORS.ink }}>Checadas (con IP / dispositivo)</h3>
<p style={{ margin: "0 0 10px", fontSize: "12px", color: COLORS.inkSoft }}>
IP y user-agent son señal secundaria de anomalías, no prueba de ubicación (§3).
</p>
{checadas.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>Sin checadas.</p></Card> :
<Card style={{ padding: 0, overflow: "hidden" }}>
<div style={{ overflowX: "auto" }}>
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px", fontFamily: FONT }}>
<thead><tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
{["Momento", "Tipo", "Origen", "Concepto", "IP", "User-agent"].map((c, i) => <th key={i} style={{ padding: "10px 12px", fontWeight: 600, whiteSpace: "nowrap" }}>{c}</th>)}
</tr></thead>
<tbody>
{checadas.map((c) => (
<tr key={c.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
<td style={{ padding: "9px 12px", whiteSpace: "nowrap" }}>{fmtDT(c.ts)}</td>
<td style={{ padding: "9px 12px" }}><Badge tone={c.tipo === "entrada" ? "success" : "primary"}>{c.tipo}</Badge></td>
<td style={{ padding: "9px 12px", color: COLORS.inkSoft }}>{c.origen}</td>
<td style={{ padding: "9px 12px", color: COLORS.inkSoft }}>{c.concepto || "—"}</td>
<td style={{ padding: "9px 12px", color: COLORS.inkSoft, fontFamily: "monospace" }}>{c.ip || "—"}</td>
<td style={{ padding: "9px 12px", color: COLORS.inkSoft, maxWidth: "220px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={c.user_agent || ""}>{c.user_agent || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>}
</div>
);
}
// ═══════════════════ Configuración ═══════════════════
function VistaConfig({ onError }) {
const [cfg, setCfg] = useState(null);
const [f, setF] = useState({ inicio: "", fin: "", tarea_activa: false, meta: "" });
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,
});
} 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),
}) });
setOkMsg("Configuración guardada."); await load();
} catch (err) { onError(err.message); } finally { setBusy(false); }
};
if (!cfg) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
return (
<div>
<h2 style={{ margin: "0 0 14px", fontSize: "18px", color: COLORS.ink }}>Configuración</h2>
<Card style={{ maxWidth: "520px" }}>
<form onSubmit={guardar}>
<div style={{ marginBottom: "6px", fontSize: "14px", fontWeight: 600, color: COLORS.ink }}>Ventana horaria de checado</div>
<p style={{ margin: "0 0 10px", fontSize: "12px", color: COLORS.inkSoft }}>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" }}>
<Field label="Inicio"><Input type="time" value={f.inicio} onChange={(e) => setF({ ...f, inicio: e.target.value })} /></Field>
<Field label="Fin"><Input type="time" value={f.fin} onChange={(e) => setF({ ...f, fin: e.target.value })} /></Field>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "10px", margin: "8px 0 16px", cursor: "pointer" }}>
<input type="checkbox" checked={f.tarea_activa} onChange={(e) => setF({ ...f, tarea_activa: e.target.checked })} style={{ width: "18px", height: "18px" }} />
<span style={{ fontSize: "14px", color: COLORS.ink }}>Pedir el concepto de la tarea al checar (switch global)</span>
</label>
<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>
{okMsg && <p style={{ color: COLORS.success, fontSize: "13px" }}>✓ {okMsg}</p>}
<div style={{ marginTop: "6px" }}><Btn type="submit" disabled={busy}>{busy ? "Guardando…" : "Guardar configuración"}</Btn></div>
</form>
</Card>
</div>
);
}
// ═══════════════════ Cola de solicitudes ═══════════════════
function VistaSolicitudes({ onError }) {
const [sols, setSols] = useState(null);
const [busy, setBusy] = useState(null);
const load = useCallback(async () => {
try { setSols(await apiFetch("/solicitudes?estado=pendiente")); } catch (e) { onError(e.message); }
}, [onError]);
useEffect(() => { load(); }, [load]);
const autorizar = async (s) => {
setBusy(s.id);
try {
const body = {};
if (s.tipo === "olvido_entrada") {
const ent = prompt("Hora de entrada a autorizar (YYYY-MM-DD HH:MM):", (s.propuesta?.entrada_ts || "").slice(0, 16).replace("T", " "));
if (!ent) { setBusy(null); return; }
body.entrada_ts = new Date(ent.replace(" ", "T")).toISOString();
const sal = prompt("Hora de salida (opcional, para que sume; deja vacío si sigue en curso):", "");
if (sal) body.salida_ts = new Date(sal.replace(" ", "T")).toISOString();
} else {
const sal = prompt("Hora de salida real para cerrar la jornada (YYYY-MM-DD HH:MM):", "");
if (!sal) { setBusy(null); return; }
body.salida_ts = new Date(sal.replace(" ", "T")).toISOString();
}
await apiFetch(`/solicitudes/${s.id}/autorizar`, { method: "POST", body: JSON.stringify(body) });
await load();
} catch (e) { onError(e.message); } finally { setBusy(null); }
};
const rechazar = async (s) => {
if (!confirm("¿Rechazar esta solicitud?")) return;
setBusy(s.id);
try { await apiFetch(`/solicitudes/${s.id}/rechazar`, { method: "POST" }); await load(); }
catch (e) { onError(e.message); } finally { setBusy(null); }
};
if (sols === null) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
return (
<div>
<h2 style={{ margin: "0 0 14px", fontSize: "18px", color: COLORS.ink }}>Solicitudes pendientes</h2>
{sols.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>No hay solicitudes pendientes.</p></Card> :
sols.map((s) => (
<Card key={s.id} style={{ marginBottom: "12px" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "12px", flexWrap: "wrap" }}>
<div>
<div style={{ fontWeight: 600, color: COLORS.ink }}>
{s.tipo === "olvido_entrada" ? "Olvido de entrada" : "Autorizar auto-cierre"}
</div>
<div style={{ fontSize: "13px", color: COLORS.inkSoft, marginTop: "2px" }}>
{s.becario_nombre} · {s.becario_telefono || "sin tel."}
</div>
<div style={{ fontSize: "13px", color: COLORS.ink, marginTop: "6px" }}>
{s.tipo === "olvido_entrada"
? <>Entrada propuesta: <strong>{fmtDT(s.propuesta?.entrada_ts)}</strong></>
: <>Jornada en revisión desde <strong>{fmtDT(s.propuesta?.entrada_ts)}</strong></>}
</div>
</div>
<div style={{ display: "flex", gap: "8px" }}>
<Btn size="sm" variant="success" disabled={busy === s.id} onClick={() => autorizar(s)}>Autorizar</Btn>
<Btn size="sm" variant="ghost" disabled={busy === s.id} onClick={() => rechazar(s)}>Rechazar</Btn>
</div>
</div>
</Card>
))}
</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: "config", label: "Configuración" },
];
const activeTab = view.name === "detalle" ? "lista" : view.name;
const tabStyle = (active) => ({
padding: "8px 14px", borderRadius: "8px", border: "none", cursor: "pointer", fontFamily: FONT,
fontSize: "14px", fontWeight: 600, background: active ? COLORS.accentBg : "transparent",
color: active ? COLORS.primaryDark : COLORS.inkSoft,
});
return (
<div style={{ minHeight: "100vh", background: COLORS.bg, fontFamily: FONT }}>
<header style={{ background: COLORS.surface, borderBottom: `1px solid ${COLORS.border}`, padding: "12px 20px",
display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "10px" }}>
<div style={{ display: "flex", alignItems: "center", gap: "18px" }}>
<div style={{ fontWeight: 700, color: COLORS.ink, fontSize: "16px" }}>Taboada · Supervisión</div>
<nav style={{ display: "flex", gap: "4px" }}>
{tabs.map((t) => (
<button key={t.key} style={tabStyle(activeTab === t.key)} onClick={() => setView({ name: t.key })}>{t.label}</button>
))}
</nav>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
<span style={{ fontSize: "13px", color: COLORS.inkSoft }}>{session.usuario}</span>
<Btn size="sm" variant="ghost" onClick={logout}>Salir</Btn>
</div>
</header>
<main style={{ maxWidth: "980px", margin: "0 auto", padding: "22px 20px 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 === "config" && <VistaConfig onError={setError} />}
</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: FONT, color: COLORS.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>