feat(panel): panel.html completo + fix perms del dir de estáticos

- panel.html: login con guardia de sesión, vista de becarios (avance vs
  meta calculado por backend, cola de dispositivos pendientes, alta/edición/
  baja) y vista por becario (jornadas editables, cerrar revisión, ajustes)
- fix: el dir /usr/share/nginx/html quedaba en 0644 por COPY --chmod al dir,
  nginx no podía traverse (Permission denied). Bug latente de Fase A (nunca
  se sirvió un estático vía nginx, solo /api/health por proxy).
This commit is contained in:
Collina Systems committed 2026-07-04 19:54:19 -06:00
1 parent a427acdcf2
commit 3f2ff0c563
2 files changed
+520 -16

No files matched your search

+6 -3
View File
@@ -17,9 +17,12 @@ RUN npm ci --omit=dev
COPY --chown=node:node backend/src ./src
# Frontend + config nginx horneados.
# --chmod garantiza lectura por el usuario nginx en runtime,
# independientemente de los permisos del archivo fuente en el host.
COPY --chmod=644 frontend/checada.html frontend/panel.html /usr/share/nginx/html/
# El directorio debe quedar 0755 (traverse) para que el usuario nginx pueda
# stat/leer los archivos; copiar con `--chmod=644 … /dir/` deja el propio
# directorio en 0644 y nginx falla con "Permission denied". Por eso se fijan
# los permisos explícitamente después del COPY.
COPY frontend/checada.html frontend/panel.html /usr/share/nginx/html/
RUN chmod 755 /usr/share/nginx/html && chmod 644 /usr/share/nginx/html/*.html
COPY --chmod=644 backend/nginx-default.conf /etc/nginx/http.d/default.conf
COPY --chmod=755 backend/docker-entrypoint.sh /docker-entrypoint.sh
+514 -13
View File
@@ -1,19 +1,520 @@
<!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>
<style>
body { font-family: -apple-system, system-ui, sans-serif; display: grid;
place-items: center; min-height: 100vh; margin: 0; background: #f4f4f5; }
main { text-align: center; color: #3f3f46; }
</style>
<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>
<main>
<h1>Taboada — Panel de supervisión</h1>
<p>Panel en construcción (Fase B).</p>
</main>
<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) => (e === "activo" ? "success" : "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 dispositivos pendientes ═══════════════════
function ColaDispositivos({ onError, onChange }) {
const [pend, setPend] = useState([]);
const load = useCallback(async () => {
try { setPend(await apiFetch("/dispositivos?estado=pendiente")); } catch (e) { onError(e.message); }
}, [onError]);
useEffect(() => { load(); }, [load]);
const act = async (id, accion) => {
try {
await apiFetch(`/dispositivos/${id}/${accion}`, { method: "POST" });
await load(); onChange && onChange();
} catch (e) { onError(e.message); }
};
if (pend.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 }}>
Dispositivos pendientes de aprobar ({pend.length})
</h3>
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
{pend.map((d) => (
<div key={d.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>{d.becario_nombre}</strong>
{d.checadas_provisionales > 0 &&
<span style={{ color: COLORS.inkSoft }}> · {d.checadas_provisionales} checada(s) provisional(es)</span>}
<div style={{ fontSize: "12px", color: COLORS.inkSoft, marginTop: "2px" }}>{d.user_agent || "dispositivo sin user-agent"}</div>
</div>
<div style={{ display: "flex", gap: "8px" }}>
<Btn size="sm" variant="success" onClick={() => act(d.id, "aprobar")}>Aprobar</Btn>
<Btn size="sm" variant="ghost" onClick={() => confirm("¿Revocar este vínculo?") && act(d.id, "revocar")}>Revocar</Btn>
</div>
</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); }
};
return (
<div>
<ColaDispositivos onError={onError} onChange={load} />
<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>
{b.matricula && <div style={{ fontSize: "12px", color: COLORS.inkSoft }}>{b.matricula}</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" }}>
<Btn size="sm" variant="ghost" onClick={() => onOpen(b.id)}>Ver</Btn>
<Btn size="sm" variant="subtle" onClick={() => setForm(b)}>Editar</Btn>
{b.estado === "activo" && <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 [editJornada, setEditJornada] = useState(null);
const [ajuste, setAjuste] = useState({ minutos: "", motivo: "" });
const [busyAjuste, setBusyAjuste] = useState(false);
const load = useCallback(async () => {
try {
const [d, j, a] = await Promise.all([
apiFetch(`/becarios/${becarioId}`),
apiFetch(`/becarios/${becarioId}/jornadas`),
apiFetch(`/becarios/${becarioId}/ajustes`),
]);
setData(d); setJornadas(j); setAjustes(a);
} 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.matricula, data.institucion].filter(Boolean).join(" · ") || "sin matrícula/institución"}
{" "}<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>
</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(); };
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" }}>
<div style={{ fontWeight: 700, color: COLORS.ink, fontSize: "16px" }}>Taboada · Supervisión</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} />
: <VistaBecario becarioId={view.id} onBack={() => setView({ name: "lista" })} 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>