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)
This commit is contained in:
Collina Systems committed 2026-07-04 23:18:19 -06:00
1 parent 6eccc8757c
commit 6465bf0cd7
2 files changed
+202 -40

No files matched your search

+4 -3
View File
@@ -14,9 +14,10 @@ services:
api:
volumes:
- ./frontend/checada.html:/usr/share/nginx/html/checada.html:ro
- ./frontend/panel.html:/usr/share/nginx/html/panel.html:ro
- ./frontend/becario.html:/usr/share/nginx/html/becario.html:ro
# Se monta el DIRECTORIO (no archivo por archivo): los bind-mounts de un
# solo archivo se rompen al editar (el editor cambia el inode y el mount
# queda colgado). Montar la carpeta permite hot-edit sin recrear.
- ./frontend:/usr/share/nginx/html:ro
ports:
# 80 → nginx (mismo path que producción: estáticos + proxy /api y /e)
- "127.0.0.1:80:80"
+198 -37
View File
@@ -111,7 +111,7 @@ const ErrorBar = ({ error, onClose }) => !error ? null : (
<span onClick={onClose} style={{ cursor: "pointer", fontWeight: 700, paddingLeft: "12px" }}>✕</span>
</div>
);
const estadoBecarioTone = (e) => (e === "activo" ? "success" : "chip");
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");
@@ -155,39 +155,25 @@ function Login({ onLogin }) {
);
}
// ═══════════════════ 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;
// ═══════════════════ 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 }}>
Dispositivos pendientes de aprobar ({pend.length})
Becarios pendientes de aprobar ({pendientes.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",
{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>{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>
<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>
@@ -248,9 +234,13 @@ function VistaBecarios({ onOpen, onError }) {
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>
<ColaDispositivos onError={onError} onChange={load} />
<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>}
@@ -275,7 +265,7 @@ function VistaBecarios({ onOpen, onError }) {
<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>}
<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" }}>
@@ -291,9 +281,10 @@ function VistaBecarios({ onOpen, onError }) {
<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 === "activo" && <Btn size="sm" variant="ghost" onClick={() => baja(b)}>Baja</Btn>}
{b.estado !== "baja" && <Btn size="sm" variant="ghost" onClick={() => baja(b)}>Baja</Btn>}
</div>
</td>
</tr>
@@ -347,18 +338,20 @@ 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] = await Promise.all([
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);
setData(d); setJornadas(j); setAjustes(a); setChecadas(c);
} catch (e) { onError(e.message); }
}, [becarioId, onError]);
useEffect(() => { load(); }, [load]);
@@ -398,7 +391,7 @@ function VistaBecario({ becarioId, onBack, onError }) {
<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"}
{[data.telefono, data.matricula, data.institucion].filter(Boolean).join(" · ") || "sin datos"}
{" "}<Badge tone={estadoBecarioTone(data.estado)}>{data.estado}</Badge>
</div>
</div>
@@ -476,6 +469,155 @@ function VistaBecario({ becarioId, onBack, onError }) {
</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>
);
}
@@ -485,11 +627,29 @@ 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" }}>
<div style={{ fontWeight: 700, color: COLORS.ink, fontSize: "16px" }}>Taboada · Supervisión</div>
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>
@@ -497,9 +657,10 @@ function Panel({ session, onLogout }) {
</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} />}
{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>
);