Reordena el flujo: el chip lleva al becario al login; con la sesión iniciada hereda las credenciales para escanear (el escaneo queda asociado a su cuenta) o para ir a su panel de horas. Antes el escáner era la entrada y el login se pedía después; ahora el login precede a ambas ramas. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
302 lines
16 KiB
HTML
302 lines
16 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." />;
|
|
if (error.code === "CHECADO_CERRADO") // fuera de la ventana horaria
|
|
return <Estado icon="lock" tone="amber" title="Checado cerrado" sub="Estás fuera del horario permitido para checar. Intenta dentro de la ventana horaria." />;
|
|
// 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 && !esEntrada && ( /* C9 · concepto solo en la salida */
|
|
<div style={{ marginBottom: "16px" }}>
|
|
<label style={{ display: "block", fontFamily: fonts.body, fontSize: "13px", fontWeight: 600, color: palette.label, marginBottom: "6px" }}>¿Qué tarea realizaste hoy? (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 && !esEntrada && !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 [escaneando, setEscaneando] = useState(false); // la cámara arranca por botón, no sola
|
|
const [error, setError] = useState(null);
|
|
const scannerRef = useRef(null);
|
|
const yaLeido = useRef(false);
|
|
|
|
// La cámara se abre solo cuando el becario pulsa "Escanear" (escaneando=true).
|
|
useEffect(() => {
|
|
if (!escaneando) return;
|
|
if (!window.Html5Qrcode) { setError("No se pudo cargar el escáner. Recarga la página."); setEscaneando(false); 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."
|
|
);
|
|
setEscaneando(false);
|
|
});
|
|
return () => {
|
|
const s = scannerRef.current;
|
|
if (s && s.isScanning) s.stop().then(() => s.clear()).catch(() => {});
|
|
};
|
|
}, [escaneando, onToken]);
|
|
|
|
const empezar = () => { setError(null); yaLeido.current = false; setEscaneando(true); };
|
|
|
|
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>}
|
|
{escaneando ? (
|
|
<>
|
|
<div id={REGION_ID} style={{ width: "100%", maxWidth: "300px", margin: "0 auto", borderRadius: "18px", overflow: "hidden", border: `1px solid ${palette.cardBorder}` }} />
|
|
<div style={{ marginTop: "14px" }}>
|
|
<Btn variant="ghost" onClick={() => setEscaneando(false)}>Cancelar</Btn>
|
|
</div>
|
|
</>
|
|
) : (
|
|
<>
|
|
<Btn onClick={empezar}>Escanear QR</Btn>
|
|
<div style={{ marginTop: "10px" }}>
|
|
<Btn variant="ghost" onClick={() => { window.location.href = "/becario.html"; }}>Ir a mi panel</Btn>
|
|
</div>
|
|
</>
|
|
)}
|
|
</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
|
|
// El chip lleva al becario aquí → primero LOGIN. Con la sesión ya iniciada,
|
|
// hereda las credenciales para escanear (el escaneo queda asociado a su cuenta)
|
|
// o para ir a su panel. Si llega con ?t=, tras el login va directo a checar.
|
|
if (!session) return <Shell><LoginInline onEntra={setSession} /></Shell>; // A3 — login primero
|
|
const token = tokenUrl || tokenEscaneado;
|
|
if (!token) return <Shell><Escaner onToken={setTokenEscaneado} /></Shell>; // A4 — ya con sesión
|
|
return <Shell><Checar token={token} /></Shell>;
|
|
}
|
|
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
|
|
</script>
|
|
</body>
|
|
</html>
|