Files
taboada-registros/frontend/checada.html
T
Collina Systems 6eccc8757c feat(checada.html): flujo de checada NFC
Exige sesión de becario (login inline para no perder ?t=). Lee ?t=/?cerrado=1.
Contexto pinta entrada/salida y concepto (si tarea activa). Confirma con
acumulado. Maneja pendiente (403), token vencido/usado, CONFLICTO_TIPO
(reconfirma) y recarga idempotente (ya registrada).
2026-07-04 23:10:01 -06:00

200 lines
10 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>
<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 style="margin:0;padding:0;">
<div id="root"></div>
<script type="text/babel" data-presets="react">
const { useState, useEffect } = React;
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; err.data = data;
throw err;
}
return data;
}
const COLORS = {
bg: "#EEF1F4", surface: "#FFFFFF", ink: "#1F2933", inkSoft: "#616E7C",
border: "#DDE2E7", primary: "#2A6FB0", success: "#2E7D5B", successBg: "#E7F3EC",
warn: "#B7791F", warnBg: "#FBF2E1", danger: "#C0392B", dangerBg: "#FBEBE9", chip: "#F0F2F5",
};
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
const fmtHoras = (h) => `${(h ?? 0).toLocaleString("es-MX", { maximumFractionDigits: 1 })} h`;
const Shell = ({ children }) => (
<div style={{ minHeight: "100vh", background: COLORS.bg, display: "flex", alignItems: "center", justifyContent: "center", padding: "20px", fontFamily: FONT }}>
<div style={{ width: "100%", maxWidth: "400px" }}>{children}</div>
</div>
);
const Card = ({ children, style }) => (
<div style={{ background: COLORS.surface, borderRadius: "16px", border: `1px solid ${COLORS.border}`, padding: "24px", ...style }}>{children}</div>
);
const inputStyle = { width: "100%", padding: "13px 14px", borderRadius: "10px", border: `1px solid ${COLORS.border}`, fontSize: "16px", fontFamily: FONT, color: COLORS.ink, boxSizing: "border-box", outline: "none" };
const Input = (p) => <input {...p} style={{ ...inputStyle, ...(p.style || {}) }} />;
const Btn = ({ children, onClick, variant = "primary", disabled, type = "button" }) => {
const V = { primary: COLORS.primary, success: COLORS.success, ghost: "transparent" }[variant];
const ghost = variant === "ghost";
return <button type={type} onClick={onClick} disabled={disabled} style={{
width: "100%", padding: "14px", borderRadius: "10px", background: disabled ? COLORS.border : V,
color: ghost ? COLORS.primary : "#fff", border: ghost ? `1px solid ${COLORS.border}` : "none",
fontSize: "16px", fontWeight: 700, fontFamily: FONT, cursor: disabled ? "not-allowed" : "pointer",
}}>{children}</button>;
};
const Big = ({ emoji, title, sub, tone = COLORS.ink }) => (
<Card style={{ textAlign: "center" }}>
<div style={{ fontSize: "44px", marginBottom: "8px" }}>{emoji}</div>
<h2 style={{ margin: "0 0 6px", color: tone, fontSize: "20px" }}>{title}</h2>
{sub && <p style={{ margin: 0, color: COLORS.inkSoft, fontSize: "14px", lineHeight: 1.5 }}>{sub}</p>}
</Card>
);
// ═══════════════ 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) {
setError(err.status === 429 ? "Demasiados intentos, espera un minuto." : "Número o contraseña incorrectos.");
} finally { setBusy(false); }
};
return (
<Card>
<h2 style={{ margin: "0 0 4px", color: COLORS.ink, fontSize: "20px", textAlign: "center" }}>Inicia sesión para checar</h2>
<p style={{ margin: "0 0 18px", color: COLORS.inkSoft, fontSize: "13px", textAlign: "center" }}>Tu código sigue activo unos minutos.</p>
{error && <div style={{ background: COLORS.dangerBg, color: COLORS.danger, padding: "10px", borderRadius: "10px", fontSize: "14px", marginBottom: "12px" }}>⚠ {error}</div>}
<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" disabled={busy || f.telefono.length !== 10 || !f.password}>{busy ? "…" : "Entrar"}</Btn>
</form>
<p style={{ textAlign: "center", marginTop: "14px", marginBottom: 0, fontSize: "13px" }}>
<a href="/becario.html" style={{ color: COLORS.primary }}>¿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 <Card style={{ textAlign: "center", color: COLORS.inkSoft }}>Cargando…</Card>;
// Errores de contexto / registro
if (error && !resultado) {
if (error.code === "BECARIO_NO_ACTIVO")
return <Big emoji="⏳" title="Cuenta pendiente" tone={COLORS.warn} 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")
return <Big emoji="⌛" title="El código expiró" tone={COLORS.warn} sub="Vuelve a acercar tu celular al chip para generar uno nuevo." />;
if (error.code === "TOKEN_YA_USADO")
return <Big emoji="↩️" title="Código ya usado" sub="Ese código ya se utilizó. Acerca tu celular al chip de nuevo." />;
// CONFLICTO_TIPO cae aquí como aviso, pero seguimos mostrando el formulario abajo.
if (error.code !== "CONFLICTO_TIPO")
return <Big emoji="⚠️" title="No se pudo registrar" tone={COLORS.danger} sub={error.message} />;
}
if (resultado) {
if (resultado.duplicada)
return <Big emoji="✓" title="Ya estaba registrada" tone={COLORS.success} sub={`Tu ${resultado.tipo || "checada"} ya se había registrado. Llevas ${fmtHoras(resultado.acumulado.total_horas)} de ${fmtHoras(resultado.acumulado.meta_horas)}.`} />;
const esEntrada = resultado.tipo === "entrada";
return <Big emoji={esEntrada ? "🟢" : "🔴"} title={esEntrada ? "Entrada registrada" : "Salida registrada"} tone={COLORS.success}
sub={`Llevas ${fmtHoras(resultado.acumulado.total_horas)} de ${fmtHoras(resultado.acumulado.meta_horas)} (${resultado.acumulado.porcentaje}%).`} />;
}
const esEntrada = ctx.tipo_sugerido === "entrada";
return (
<Card>
<h2 style={{ margin: "0 0 4px", color: COLORS.ink, fontSize: "20px", textAlign: "center" }}>
Registrar {esEntrada ? "entrada" : "salida"}
</h2>
<p style={{ margin: "0 0 18px", color: COLORS.inkSoft, fontSize: "14px", textAlign: "center" }}>
{esEntrada ? "Vas a abrir tu jornada." : "Vas a cerrar tu jornada abierta."}
</p>
{error && error.code === "CONFLICTO_TIPO" && (
<div style={{ background: COLORS.warnBg, color: COLORS.warn, padding: "10px", borderRadius: "10px", fontSize: "13px", marginBottom: "12px" }}>
Ajustamos el registro a <strong>{ctx.tipo_sugerido}</strong> según tu jornada. Confirma.
</div>
)}
{ctx.tarea_activa && (
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontSize: "13px", fontWeight: 600, color: COLORS.inkSoft, 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"} disabled={busy || (ctx.tarea_activa && !concepto.trim())}>
{busy ? "Registrando…" : `Confirmar ${esEntrada ? "entrada" : "salida"}`}
</Btn>
</Card>
);
}
function App() {
const params = new URLSearchParams(window.location.search);
const token = params.get("t");
const cerrado = params.get("cerrado");
const [session, setSession] = useState(undefined);
useEffect(() => { apiFetch("/becario/session").then(setSession).catch(() => setSession(null)); }, []);
if (cerrado) return <Shell><Big emoji="🚫" title="Checado cerrado" tone={COLORS.warn} sub="Estás fuera del horario permitido para checar. Intenta dentro de la ventana horaria." /></Shell>;
if (session === undefined) return <Shell><Card style={{ textAlign: "center", color: COLORS.inkSoft }}>Cargando…</Card></Shell>;
if (!session) return <Shell><LoginInline onEntra={setSession} /></Shell>;
if (!token) return <Shell><Big emoji="📲" title="Acerca tu celular al chip" sub="Para checar, escanea el chip NFC en la oficina de la supervisora." /></Shell>;
return <Shell><Checar token={token} /></Shell>;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>