- Renombra la sección/labels "día completo" → "jornada pasada". - El formulario pide la actividad realizada (concepto), obligatoria. - becario-portal: POST /becario/solicitudes acepta y valida concepto para jornada_completa (400 CONCEPTO_REQUERIDO); viaja en la propuesta. - solicitudes: al autorizar, el concepto queda en la meta de la checada de salida → aparece en la columna Concepto del panel. La tarjeta de solicitud muestra la actividad propuesta antes de autorizar. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
675 lines
40 KiB
HTML
675 lines
40 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",
|
||
});
|
||
}
|
||
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>;
|
||
|
||
// ── 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", 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 3px", fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, textAlign: "center", letterSpacing: "-.01em" }}>Taboada</h1>
|
||
<p style={{ margin: "0 0 24px", fontFamily: fonts.body, fontSize: "14px", color: palette.inkSoft, textAlign: "center" }}>Panel de supervisión</p>
|
||
{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>
|
||
</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 [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 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");
|
||
const nuevoBtn = (size) => <Btn size={size} onClick={() => setForm({})}>{iconBtn("plus", { size: 16, color: "#fff", sw: 2.2 })}Nuevo becario</Btn>;
|
||
// 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={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
|
||
<h2 style={{ margin: 0, fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Becarios</h2>
|
||
{nuevoBtn()}
|
||
</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="Crea el primero o espera a que se registren desde su celular." action={nuevoBtn()} /> :
|
||
<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>}
|
||
</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)} />}
|
||
</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 [ajustes, setAjustes] = useState([]);
|
||
const [checadas, setChecadas] = useState([]);
|
||
const [editJornada, setEditJornada] = useState(null);
|
||
const [cerrarJornada, setCerrarJornada] = 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) => {
|
||
// 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); }
|
||
};
|
||
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: 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" }}><ProgressBar value={h.porcentaje} height={9} /></div>
|
||
<div style={{ fontFamily: fonts.body, fontSize: "14px", color: palette.inkSoft }}>
|
||
<span style={{ color: palette.ink }}>Checado {(h.minutos_jornadas / 60).toFixed(1)} h</span>
|
||
{" + Ajustes "}
|
||
<span style={{ color: h.minutos_ajustes >= 0 ? palette.green : palette.danger, fontWeight: 600 }}>
|
||
{h.minutos_ajustes >= 0 ? "+" : "−"}{Math.abs(h.minutos_ajustes / 60).toFixed(1)} h
|
||
</span>
|
||
{" = "}
|
||
<strong style={{ color: palette.ink }}>Total {(h.total_minutos / 60).toFixed(1)} h</strong>
|
||
</div>
|
||
<div style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.amber, marginTop: "5px" }}>
|
||
El acumulado de la tabla es solo lo <strong>checado</strong> (coincide con la fila más reciente); las jornadas en revisión no suman.
|
||
</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>{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}>Ajustes</h3>
|
||
<Card style={{ marginBottom: "22px", padding: "20px 22px" }}>
|
||
<form onSubmit={crearAjuste} style={{ display: "flex", gap: "12px", alignItems: "flex-end", flexWrap: "wrap", marginBottom: ajustes.length ? "4px" : 0 }}>
|
||
<div style={{ width: "130px" }}>
|
||
<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: "220px" }}>
|
||
<Field label="Motivo (obligatorio)"><Input value={ajuste.motivo} onChange={(e) => setAjuste({ ...ajuste, motivo: e.target.value })} required /></Field>
|
||
</div>
|
||
<div style={{ marginBottom: "14px" }}>
|
||
<Btn type="submit" loading={busyAjuste} 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 ${palette.cardBorder}`, padding: "12px 0", gap: "10px" }}>
|
||
<div style={{ fontFamily: fonts.body, fontSize: "14px", color: palette.ink }}>
|
||
<strong style={{ color: a.minutos >= 0 ? palette.green : palette.danger, fontWeight: 700 }}>{a.minutos >= 0 ? "+" : ""}{a.minutos} min</strong>
|
||
<span style={{ color: palette.inkSoft }}> · {a.motivo}</span>
|
||
</div>
|
||
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, whiteSpace: "nowrap" }}>{fmtDT(a.created_at)}</span>
|
||
</div>
|
||
))}
|
||
</Card>
|
||
|
||
<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>
|
||
);
|
||
}
|
||
|
||
// ═══════════════════ 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;
|
||
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 === "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: 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>
|