Sin cambio visual ni de comportamiento — solo elimina la triplicación. - theme.js expone COLORS (unificada), FONT, SPACE, RADIUS y makeUI(flavor) con los componentes compartidos Btn/Card/Input/Badge/Field/Estado - 'flavor' (panel/becario/checada) reproduce las medidas exactas de cada página (escritorio vs móvil) para que se vea idéntico a hoy - los tres HTML cargan theme.js y usan makeUI en vez de sus defs locales; checada renombra su componente Big → Estado (compartido) - Dockerfile hornea theme.js para producción Verificado headless: transpila, monta sin throw y reproduce los estilos originales píxel por píxel (react-dom/server + asserts de estilo).
186 lines
9.6 KiB
HTML
186 lines
9.6 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>
|
|
<script src="theme.js"></script>
|
|
</head>
|
|
<body style="margin:0;padding:0;">
|
|
<div id="root"></div>
|
|
<script type="text/babel" data-presets="react">
|
|
const { useState, useEffect } = React;
|
|
|
|
// Base visual compartida (theme.js), ligada al flavor 'checada'.
|
|
const { COLORS, FONT, SPACE, RADIUS, makeUI } = Theme;
|
|
const { Btn, Card, Input, Badge, Field, Estado } = makeUI("checada");
|
|
|
|
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 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" }) : "");
|
|
|
|
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>
|
|
);
|
|
// ═══════════════ 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 <Estado 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 <Estado 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 <Estado 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 <Estado emoji="⚠️" title="No se pudo registrar" tone={COLORS.danger} sub={error.message} />;
|
|
}
|
|
|
|
if (resultado) {
|
|
// Token de un solo uso ya consumido: no es error del becario, es lo correcto.
|
|
if (resultado.duplicada)
|
|
return <Estado emoji="🔄" title="Este código ya se usó" tone={COLORS.primary}
|
|
sub="Cada código del chip sirve una sola vez (así debe ser). Acerca de nuevo el celular al chip 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);
|
|
if (esEntrada)
|
|
return <Estado emoji="🟢" title={`Entrada registrada${hora ? ` a las ${hora}` : ""}`} tone={COLORS.success}
|
|
sub={`Llevas ${fmtHoras(resultado.acumulado.total_horas)} de ${fmtHoras(resultado.acumulado.meta_horas)}. Cuando termines, vuelve a acercar el celular al chip para registrar tu salida.`} />;
|
|
return <Estado emoji="🔴" title={`Salida registrada${hora ? ` a las ${hora}` : ""}`} tone={COLORS.success}
|
|
sub={`Jornada cerrada. 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><Estado 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><Estado 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>
|