Files
taboada-registros/frontend/checada.html
T
Jorem JuárezandClaude Fable 5 e188da78a3 feat(checada): la página del becario cae directo al escáner de QR de kiosco
Elimina la pantalla intermedia "Acerca tu celular al chip", del flujo viejo donde
el NFC era el vector de checada. Ahora el chip solo trae al becario a esta URL y,
con sesión iniciada y sin token, la página abre la cámara para escanear el QR
rotativo que muestra la asistente (html5-qrcode). Al leerlo, extrae el token `t` y
sigue el flujo de checada normal — POST /api/checadas y la validación del token NO
se tocan. Si llega con ?t= (cámara nativa/URL del QR) va directo a confirmar.

Copy alineado a la realidad: "Escanea el QR con la asistente" en vez de "acerca tu
celular al chip", también en las pantallas de token expirado/ya usado y el login.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 19:10:52 -06:00

280 lines
15 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 — Checada</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="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.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, useRef } = React;
// Piel visual "cream" del rediseño, servida por theme.js para el flavor 'checada'.
// Colores, tipografías e íconos viven en theme.js — aquí no hay estilos sueltos.
const UI = Theme.makeUI("checada");
const { Logo, IconBadge, Card, Btn, Input, Aviso, Estado, palette, fonts, icons } = UI;
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
// tres páginas. Mismo comportamiento de antes (mapeo de error por code/status/
// data); ahora vive en un solo sitio en vez de duplicado por página.
const { apiFetch } = Theme;
const fmtHoras = (h) => `${(h ?? 0).toLocaleString("es-MX", { maximumFractionDigits: 1 })} h`;
const fmtHM = (iso) => (iso ? new Date(iso).toLocaleTimeString("es-MX", { timeZone: "America/Mexico_City", hour: "2-digit", minute: "2-digit" }) : "");
// Porcentaje para la barra de avance (usa el del backend; si falta, lo deriva).
const pctDe = (a) => (typeof a?.porcentaje === "number" ? a.porcentaje : (a?.meta_horas ? Math.round((a.total_horas / a.meta_horas) * 100) : 0));
// ─────────────────── Piezas visuales locales ───────────────────
const Shell = ({ children }) => (
<div style={{ minHeight: "100vh", background: palette.bgGradient, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "28px 20px", fontFamily: fonts.body }}>
<div style={{ width: "100%", maxWidth: "420px" }}>
<div style={{ display: "flex", justifyContent: "center", marginBottom: "22px" }}>
<Logo />
</div>
{children}
</div>
</div>
);
const Cargando = ({ texto = "Cargando…" }) => (
<Card style={{ textAlign: "center" }}>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px" }}>
<span style={{ display: "inline-flex" }}>{icons.spinner({ size: 24, color: palette.primary, track: palette.line })}</span>
<span style={{ fontFamily: fonts.body, fontSize: "14px", color: palette.inkSoft }}>{texto}</span>
</div>
</Card>
);
// ═══════════════ A3 · Login inline (para no perder el token de la URL) ═══════════════
function LoginInline({ onEntra }) {
const [f, setF] = useState({ telefono: "", password: "" });
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const submit = async (e) => {
e.preventDefault(); setBusy(true); setError(null);
try {
await apiFetch("/becario/login", { method: "POST", body: JSON.stringify(f) });
onEntra(await apiFetch("/becario/session"));
} catch (err) {
// Mismo mapeo de siempre: 429 vs credenciales; el ícono sólo acompaña.
setError(err.status === 429
? { text: "Demasiados intentos, espera un minuto.", ic: "clock" }
: { text: "Número o contraseña incorrectos.", ic: "alertCircle" });
} finally { setBusy(false); }
};
return (
<Card>
<h2 style={{ margin: "0 0 4px", fontFamily: fonts.title, fontWeight: 600, letterSpacing: "-.01em", color: palette.ink, fontSize: "22px", textAlign: "center" }}>Inicia sesión para checar</h2>
<p style={{ margin: "0 0 18px", fontFamily: fonts.body, color: palette.inkSoft, fontSize: "13px", textAlign: "center" }}>Inicia sesión para continuar con tu checada.</p>
{error && <Aviso variant="error" icon={error.ic}>{error.text}</Aviso>}
<form onSubmit={submit}>
<div style={{ marginBottom: "12px" }}>
<Input placeholder="Celular (10 dígitos)" inputMode="numeric" value={f.telefono} onChange={(e) => setF({ ...f, telefono: e.target.value.replace(/\D/g, "").slice(0, 10) })} required />
</div>
<div style={{ marginBottom: "16px" }}>
<Input type="password" placeholder="Contraseña" value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} required />
</div>
<Btn type="submit" loading={busy} disabled={busy || f.telefono.length !== 10 || !f.password}>{busy ? "Entrando…" : "Entrar"}</Btn>
</form>
<p style={{ textAlign: "center", marginTop: "16px", marginBottom: 0, fontSize: "13px", fontFamily: fonts.body }}>
<a href="/becario.html?registro=1" style={{ color: palette.primary, fontWeight: 600, textDecoration: "none" }}>¿No tienes cuenta? Regístrate</a>
</p>
</Card>
);
}
// ═══════════════ Checar (con token válido y sesión) ═══════════════
function Checar({ token }) {
const [ctx, setCtx] = useState(undefined); // contexto o null
const [error, setError] = useState(null); // error de carga (pendiente, etc.)
const [concepto, setConcepto] = useState("");
const [busy, setBusy] = useState(false);
const [resultado, setResultado] = useState(null);
useEffect(() => {
apiFetch("/checadas/contexto")
.then(setCtx)
.catch((e) => { setCtx(null); setError(e); });
}, []);
const registrar = async () => {
setBusy(true);
try {
const r = await apiFetch("/checadas", { method: "POST", body: JSON.stringify({ t: token, tipo: ctx.tipo_sugerido, concepto: concepto || undefined }) });
setResultado(r);
} catch (err) {
if (err.code === "CONFLICTO_TIPO") {
// El backend manda: ajusta el tipo sugerido y pide reconfirmar.
setCtx((c) => ({ ...c, tipo_sugerido: err.data.esperado }));
setError(err);
} else {
setError(err);
}
} finally { setBusy(false); }
};
if (ctx === undefined) return <Cargando />; // C1
// Errores de contexto / registro
if (error && !resultado) {
if (error.code === "BECARIO_NO_ACTIVO") // C2
return <Estado icon="hourglass" tone="amber" title="Cuenta pendiente" sub="Tu cuenta aún no está aprobada; no puedes checar todavía. Avisa a la supervisora." />;
if (error.code === "TOKEN_VENCIDO" || error.code === "TOKEN_INVALIDO") // C3
return <Estado icon="clock" tone="amber" title="El código expiró" sub="Vuelve a escanear el QR que muestra la asistente para generar uno nuevo." />;
if (error.code === "TOKEN_YA_USADO") // C4 (informativo, no rojo)
return <Estado icon="refresh" tone="blue" dashed title="Código ya usado" sub="Ese código ya se utilizó. Escanea de nuevo el QR que muestra la asistente." />;
// CONFLICTO_TIPO cae aquí como aviso, pero seguimos mostrando el formulario abajo.
if (error.code !== "CONFLICTO_TIPO") // C5 genérico
return <Estado icon="alertCircle" tone="danger" title="No se pudo registrar" sub={error.message} />;
}
if (resultado) {
// C6 · Token de un solo uso ya consumido: no es error del becario, es lo correcto.
if (resultado.duplicada)
return <Estado icon="refresh" tone="blue" dashed title="Este código ya se usó"
sub="Cada código sirve una sola vez (así debe ser). Escanea de nuevo el QR con la asistente para registrar tu siguiente movimiento." />;
// El título refleja el tipo REAL que aplicó el backend (toggle), no lo que
// pulsó el becario — si hubo conflicto ya se reconfirmó antes de llegar aquí.
const esEntrada = resultado.tipo === "entrada";
const hora = fmtHM(resultado.ts);
const pct = pctDe(resultado.acumulado);
if (esEntrada) // C11
return <Estado icon="check" tone="green" progress={pct} title={`Entrada registrada${hora ? ` a las ${hora}` : ""}`}
sub={`Llevas ${fmtHoras(resultado.acumulado.total_horas)} de ${fmtHoras(resultado.acumulado.meta_horas)}. Cuando termines, vuelve a escanear el QR con la asistente para registrar tu salida.`} />;
return <Estado icon="check" tone="green" progress={pct} title={`Salida registrada${hora ? ` a las ${hora}` : ""}`} /* C12 */
sub={`Jornada cerrada. Llevas ${fmtHoras(resultado.acumulado.total_horas)} de ${fmtHoras(resultado.acumulado.meta_horas)} (${resultado.acumulado.porcentaje}%).`} />;
}
// C7 / C8 · Formulario de confirmación (amanecer=entrada, luna=salida)
const esEntrada = ctx.tipo_sugerido === "entrada";
return (
<Card>
<IconBadge icon={esEntrada ? "sunrise" : "moon"} tone={esEntrada ? "green" : "blue"} />
<h2 style={{ margin: "0 0 4px", fontFamily: fonts.title, fontWeight: 600, letterSpacing: "-.01em", color: palette.ink, fontSize: "22px", textAlign: "center" }}>
Registrar {esEntrada ? "entrada" : "salida"}
</h2>
<p style={{ margin: "0 0 18px", fontFamily: fonts.body, color: palette.inkSoft, fontSize: "14px", textAlign: "center" }}>
{esEntrada ? "Vas a abrir tu jornada." : "Vas a cerrar tu jornada abierta."}
</p>
{error && error.code === "CONFLICTO_TIPO" && ( /* C10 */
<Aviso variant="warn" icon="alertTriangle">
Ajustamos el registro a <strong>{ctx.tipo_sugerido}</strong> según tu jornada. Confirma.
</Aviso>
)}
{ctx.tarea_activa && ( /* C9 */
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.label, marginBottom: "6px" }}>¿Qué tarea realizas? (obligatorio)</label>
<Input value={concepto} onChange={(e) => setConcepto(e.target.value)} placeholder="Describe la actividad" />
</div>
)}
<Btn onClick={registrar} variant={esEntrada ? "success" : "primary"} loading={busy} disabled={busy || (ctx.tarea_activa && !concepto.trim())}>
{busy ? "Registrando…" : `Confirmar ${esEntrada ? "entrada" : "salida"}`}
</Btn>
</Card>
);
}
// ═══════════════ Escáner del QR de kiosco (cámara del propio becario) ═══════════════
// Reemplaza la vieja pantalla de "acerca tu celular al chip": el chip solo trajo
// al becario a esta URL; a partir de aquí escanea el QR rotativo que muestra la
// asistente. Al leerlo, extrae el token `t` y continúa el flujo de checada normal
// (no toca POST /api/checadas ni la validación del token).
const REGION_ID = "tb-qr-region";
// El QR del kiosco codifica una URL a /checada.html?t=<token>; saca el token.
// Si el QR trajera solo el token (sin URL), lo usa tal cual.
function extraerToken(texto) {
try {
const t = new URL(texto, window.location.origin).searchParams.get("t");
if (t) return t;
} catch (e) { /* no era URL */ }
const limpio = (texto || "").trim();
return /^[A-Za-z0-9_-]{16,}$/.test(limpio) ? limpio : null;
}
function Escaner({ onToken }) {
const [error, setError] = useState(null);
const scannerRef = useRef(null);
const yaLeido = useRef(false);
useEffect(() => {
if (!window.Html5Qrcode) { setError("No se pudo cargar el escáner. Recarga la página."); return; }
const qr = new Html5Qrcode(REGION_ID, { verbose: false });
scannerRef.current = qr;
qr.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: { width: 232, height: 232 } },
(texto) => {
if (yaLeido.current) return;
const t = extraerToken(texto);
if (!t) return; // QR ajeno: sigue escaneando
yaLeido.current = true;
qr.stop().then(() => qr.clear()).catch(() => {}).finally(() => onToken(t));
},
() => {} // fallo de decodificación por frame: ignorar
).catch((e) => {
setError(
e?.name === "NotAllowedError" ? "Permite el acceso a la cámara para escanear el QR."
: e?.name === "NotFoundError" ? "No se encontró una cámara en este dispositivo."
: "No se pudo abrir la cámara. Revisa los permisos e inténtalo de nuevo."
);
});
return () => {
const s = scannerRef.current;
if (s && s.isScanning) s.stop().then(() => s.clear()).catch(() => {});
};
}, [onToken]);
return (
<Card style={{ textAlign: "center" }}>
<IconBadge icon="nfc" tone="blue" />
<h2 style={{ margin: "0 0 4px", fontFamily: fonts.title, fontWeight: 600, letterSpacing: "-.01em", color: palette.ink, fontSize: "22px" }}>Escanea el QR con la asistente</h2>
<p style={{ margin: "0 0 16px", fontFamily: fonts.body, color: palette.inkSoft, fontSize: "14px", lineHeight: 1.5 }}>
Apunta la cámara al código que muestra la asistente en su teléfono.
</p>
{error
? <Aviso variant="error" icon="alertCircle">{error}</Aviso>
: <div id={REGION_ID} style={{ width: "100%", maxWidth: "300px", margin: "0 auto", borderRadius: "18px", overflow: "hidden", border: `1px solid ${palette.cardBorder}` }} />}
</Card>
);
}
function App() {
const params = new URLSearchParams(window.location.search);
const tokenUrl = params.get("t");
const cerrado = params.get("cerrado");
const [session, setSession] = useState(undefined);
const [tokenEscaneado, setTokenEscaneado] = useState(null);
useEffect(() => { apiFetch("/becario/session").then(setSession).catch(() => setSession(null)); }, []);
if (cerrado) return <Shell><Estado icon="lock" tone="amber" title="Checado cerrado" sub="Estás fuera del horario permitido para checar. Intenta dentro de la ventana horaria." /></Shell>; // A2
if (session === undefined) return <Shell><Cargando texto="Verificando sesión…" /></Shell>; // A1
if (!session) return <Shell><LoginInline onEntra={setSession} /></Shell>; // A3
// El chip trae al becario aquí sin token → escanea el QR del kiosco. Si llegó
// con ?t= (escaneó con la cámara nativa o abrió la URL del QR), va directo a checar.
const token = tokenUrl || tokenEscaneado;
if (!token) return <Shell><Escaner onToken={setTokenEscaneado} /></Shell>; // A4 (nuevo)
return <Shell><Checar token={token} /></Shell>;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>