checada.html pasa ?registro=1; becario.html lee el parámetro y arranca el componente Acceso en modo "registro". Sin el parámetro sigue abriendo en "Entrar". Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
260 lines
15 KiB
HTML
260 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 — Mis horas</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, useCallback } = 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;
|
|
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";
|
|
|
|
function fmtDT(iso) {
|
|
if (!iso) return "—";
|
|
return new Date(iso).toLocaleString("es-MX", {
|
|
timeZone: "America/Mexico_City", day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit",
|
|
});
|
|
}
|
|
const fmtHoras = (h) => `${(h ?? 0).toLocaleString("es-MX", { maximumFractionDigits: 1 })} h`;
|
|
function localToIso(v) { return v ? new Date(v).toISOString() : null; }
|
|
|
|
const inputStyle = {
|
|
width: "100%", padding: "12px 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", danger: COLORS.danger }[variant];
|
|
const ghost = variant === "ghost";
|
|
return <button type={type} onClick={onClick} disabled={disabled} style={{
|
|
width: "100%", padding: "13px", borderRadius: "10px", background: disabled ? COLORS.border : V,
|
|
color: ghost ? COLORS.primary : "#fff", border: ghost ? `1px solid ${COLORS.border}` : "none",
|
|
fontSize: "15px", fontWeight: 700, fontFamily: FONT, cursor: disabled ? "not-allowed" : "pointer",
|
|
}}>{children}</button>;
|
|
};
|
|
const Card = ({ children, style }) => (
|
|
<div style={{ background: COLORS.surface, borderRadius: "14px", border: `1px solid ${COLORS.border}`,
|
|
padding: "18px", marginBottom: "14px", ...style }}>{children}</div>
|
|
);
|
|
const Badge = ({ children, tone }) => {
|
|
const T = { pendiente: [COLORS.warnBg, COLORS.warn], activo: [COLORS.successBg, COLORS.success], baja: [COLORS.chip, COLORS.inkSoft] }[tone] || [COLORS.chip, COLORS.inkSoft];
|
|
return <span style={{ background: T[0], color: T[1], padding: "3px 10px", borderRadius: "999px", fontSize: "12px", fontWeight: 700 }}>{children}</span>;
|
|
};
|
|
const ErrorBar = ({ error, onClose }) => !error ? null : (
|
|
<div style={{ background: COLORS.dangerBg, color: COLORS.danger, padding: "10px 14px", borderRadius: "10px", fontSize: "14px", marginBottom: "12px", display: "flex", justifyContent: "space-between" }}>
|
|
<span>⚠ {error}</span><span onClick={onClose} style={{ cursor: "pointer", fontWeight: 700 }}>✕</span>
|
|
</div>
|
|
);
|
|
|
|
// ═══════════════ Login / Registro ═══════════════
|
|
function Acceso({ onEntra }) {
|
|
const [modo, setModo] = useState(() =>
|
|
new URLSearchParams(window.location.search).get("registro") === "1" ? "registro" : "login"
|
|
);
|
|
const [f, setF] = useState({ telefono: "", password: "", nombre: "" });
|
|
const [error, setError] = useState(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const set = (k) => (e) => setF({ ...f, [k]: k === "telefono" ? e.target.value.replace(/\D/g, "").slice(0, 10) : e.target.value });
|
|
const submit = async (e) => {
|
|
e.preventDefault(); setBusy(true); setError(null);
|
|
try {
|
|
if (modo === "registro") {
|
|
await apiFetch("/becario/registro", { method: "POST", body: JSON.stringify({ telefono: f.telefono, password: f.password, nombre: f.nombre.trim() }) });
|
|
} else {
|
|
await apiFetch("/becario/login", { method: "POST", body: JSON.stringify({ telefono: f.telefono, password: f.password }) });
|
|
}
|
|
onEntra(await apiFetch("/becario/session"));
|
|
} catch (err) {
|
|
let msg;
|
|
if (err.status === 429) msg = "Demasiados intentos, espera un minuto.";
|
|
else if (err.code === "TELEFONO_YA_REGISTRADO") msg = "Ese número ya está registrado. Inicia sesión.";
|
|
// Motivo específico del backend para errores de datos (4xx): teléfono,
|
|
// contraseña corta, nombre. No se muestra el detalle de errores 5xx.
|
|
else if (modo === "registro" && err.status >= 400 && err.status < 500 && err.message) msg = err.message;
|
|
else if (modo === "registro") msg = "No se pudo registrar. Intenta de nuevo.";
|
|
else msg = "Número o contraseña incorrectos.";
|
|
setError(msg);
|
|
} finally { setBusy(false); }
|
|
};
|
|
return (
|
|
<div style={{ minHeight: "100vh", background: COLORS.bg, display: "flex", alignItems: "center", justifyContent: "center", padding: "20px", fontFamily: FONT }}>
|
|
<div style={{ width: "100%", maxWidth: "380px" }}>
|
|
<h1 style={{ textAlign: "center", color: COLORS.ink, fontSize: "24px", marginBottom: "4px" }}>Taboada</h1>
|
|
<p style={{ textAlign: "center", color: COLORS.inkSoft, marginTop: 0, marginBottom: "18px" }}>Registro de horas de servicio</p>
|
|
<Card>
|
|
<div style={{ display: "flex", gap: "8px", marginBottom: "16px" }}>
|
|
{["login", "registro"].map((m) => (
|
|
<button key={m} onClick={() => { setModo(m); setError(null); }} style={{
|
|
flex: 1, padding: "9px", borderRadius: "9px", border: "none", cursor: "pointer", fontFamily: FONT, fontWeight: 700, fontSize: "14px",
|
|
background: modo === m ? COLORS.primary : COLORS.chip, color: modo === m ? "#fff" : COLORS.inkSoft,
|
|
}}>{m === "login" ? "Entrar" : "Registrarme"}</button>
|
|
))}
|
|
</div>
|
|
<ErrorBar error={error} onClose={() => setError(null)} />
|
|
<form onSubmit={submit}>
|
|
{modo === "registro" && (
|
|
<div style={{ marginBottom: "12px" }}>
|
|
<Input placeholder="Tu nombre" value={f.nombre} onChange={set("nombre")} required />
|
|
</div>
|
|
)}
|
|
<div style={{ marginBottom: "12px" }}>
|
|
<Input placeholder="Celular (10 dígitos)" inputMode="numeric" value={f.telefono} onChange={set("telefono")} required />
|
|
</div>
|
|
<div style={{ marginBottom: "16px" }}>
|
|
<Input type="password" placeholder="Contraseña" value={f.password} onChange={set("password")} required />
|
|
</div>
|
|
<Btn type="submit" disabled={busy || f.telefono.length !== 10 || f.password.length < (modo === "registro" ? 6 : 1) || (modo === "registro" && !f.nombre.trim())}>
|
|
{busy ? "…" : modo === "registro" ? "Crear cuenta" : "Entrar"}
|
|
</Btn>
|
|
</form>
|
|
{modo === "registro" && <p style={{ fontSize: "12px", color: COLORS.inkSoft, marginTop: "12px", marginBottom: 0, textAlign: "center" }}>
|
|
Tu cuenta queda pendiente hasta que la supervisora la apruebe.
|
|
</p>}
|
|
</Card>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ═══════════════ Portal ═══════════════
|
|
function Portal({ session, onSalir }) {
|
|
const [resumen, setResumen] = useState(null);
|
|
const [jornadas, setJornadas] = useState([]);
|
|
const [solicitudes, setSolicitudes] = useState([]);
|
|
const [error, setError] = useState(null);
|
|
const [entradaTs, setEntradaTs] = useState("");
|
|
const [enviando, setEnviando] = useState(false);
|
|
const [okMsg, setOkMsg] = useState(null);
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const [r, j, s] = await Promise.all([
|
|
apiFetch("/becario/resumen"), apiFetch("/becario/jornadas"), apiFetch("/becario/solicitudes"),
|
|
]);
|
|
setResumen(r); setJornadas(j); setSolicitudes(s);
|
|
} catch (e) { setError(e.message); }
|
|
}, []);
|
|
useEffect(() => { load(); }, [load]);
|
|
|
|
const salir = async () => { try { await apiFetch("/becario/logout", { method: "POST" }); } catch {} onSalir(); };
|
|
const crearSolicitud = async (e) => {
|
|
e.preventDefault(); setEnviando(true); setError(null); setOkMsg(null);
|
|
try {
|
|
await apiFetch("/becario/solicitudes", { method: "POST", body: JSON.stringify({ entrada_ts: localToIso(entradaTs) }) });
|
|
setEntradaTs(""); setOkMsg("Solicitud enviada. La supervisora la revisará.");
|
|
await load();
|
|
} catch (err) { setError(err.message); } finally { setEnviando(false); }
|
|
};
|
|
|
|
if (!resumen) return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: FONT, color: COLORS.inkSoft }}>Cargando…</div>;
|
|
const h = resumen.horas;
|
|
const pendiente = resumen.estado === "pendiente";
|
|
return (
|
|
<div style={{ minHeight: "100vh", background: COLORS.bg, fontFamily: FONT }}>
|
|
<header style={{ background: COLORS.surface, borderBottom: `1px solid ${COLORS.border}`, padding: "14px 18px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
|
<div>
|
|
<div style={{ fontWeight: 700, color: COLORS.ink }}>{resumen.nombre}</div>
|
|
<div style={{ fontSize: "12px", color: COLORS.inkSoft }}>{resumen.telefono} · <Badge tone={resumen.estado}>{resumen.estado}</Badge></div>
|
|
</div>
|
|
<button onClick={salir} style={{ background: "none", border: `1px solid ${COLORS.border}`, borderRadius: "8px", padding: "8px 12px", color: COLORS.primary, fontFamily: FONT, fontWeight: 600, cursor: "pointer" }}>Salir</button>
|
|
</header>
|
|
<main style={{ maxWidth: "460px", margin: "0 auto", padding: "18px" }}>
|
|
<ErrorBar error={error} onClose={() => setError(null)} />
|
|
{pendiente && (
|
|
<Card style={{ background: COLORS.warnBg, borderColor: COLORS.warn }}>
|
|
<strong style={{ color: COLORS.warn }}>Cuenta pendiente de aprobación</strong>
|
|
<p style={{ margin: "6px 0 0", fontSize: "14px", color: COLORS.ink }}>Ya puedes ver tu portal, pero aún no puedes checar. Avisa a la supervisora para que apruebe tu cuenta.</p>
|
|
</Card>
|
|
)}
|
|
|
|
<Card>
|
|
<div style={{ fontSize: "13px", color: COLORS.inkSoft, marginBottom: "4px" }}>Horas acumuladas</div>
|
|
<div style={{ fontSize: "30px", fontWeight: 800, color: COLORS.ink }}>
|
|
{fmtHoras(h.total_horas)} <span style={{ fontSize: "15px", fontWeight: 500, color: COLORS.inkSoft }}>de {fmtHoras(h.meta_horas)}</span>
|
|
</div>
|
|
<div style={{ height: "9px", background: COLORS.chip, borderRadius: "999px", overflow: "hidden", margin: "12px 0 6px" }}>
|
|
<div style={{ height: "100%", width: `${Math.min(100, h.porcentaje)}%`, background: h.porcentaje >= 100 ? COLORS.success : COLORS.primary }} />
|
|
</div>
|
|
<div style={{ fontSize: "13px", color: COLORS.inkSoft }}>{h.porcentaje}% de tu meta · jornadas {(h.minutos_jornadas / 60).toFixed(1)} h + ajustes {(h.minutos_ajustes / 60).toFixed(1)} h</div>
|
|
</Card>
|
|
|
|
<h3 style={{ fontSize: "15px", color: COLORS.ink, margin: "18px 0 8px" }}>Mis jornadas</h3>
|
|
{jornadas.length === 0 ? <Card><span style={{ color: COLORS.inkSoft }}>Aún no tienes jornadas.</span></Card> :
|
|
<Card style={{ padding: "6px 0" }}>
|
|
{jornadas.slice(0, 20).map((j) => (
|
|
<div key={j.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 16px", borderBottom: `1px solid ${COLORS.chip}` }}>
|
|
<div style={{ fontSize: "14px", color: COLORS.ink }}>
|
|
{fmtDT(j.entrada_ts)} → {j.salida_ts ? fmtDT(j.salida_ts) : "abierta"}
|
|
<div style={{ fontSize: "12px", color: COLORS.inkSoft }}>{j.estado}{j.duracion_minutos != null ? ` · ${(j.duracion_minutos / 60).toFixed(1)} h` : ""}</div>
|
|
</div>
|
|
<Badge tone={j.estado === "cerrada" ? "activo" : j.estado === "revision" ? "pendiente" : "baja"}>{j.estado}</Badge>
|
|
</div>
|
|
))}
|
|
</Card>}
|
|
|
|
<h3 style={{ fontSize: "15px", color: COLORS.ink, margin: "18px 0 8px" }}>Olvidé marcar mi entrada</h3>
|
|
<Card>
|
|
<p style={{ margin: "0 0 10px", fontSize: "13px", color: COLORS.inkSoft }}>Propón la hora a la que entraste; la supervisora la revisará y autorizará.</p>
|
|
<form onSubmit={crearSolicitud}>
|
|
<div style={{ marginBottom: "10px" }}>
|
|
<Input type="datetime-local" value={entradaTs} onChange={(e) => setEntradaTs(e.target.value)} required />
|
|
</div>
|
|
{okMsg && <p style={{ color: COLORS.success, fontSize: "13px", margin: "0 0 10px" }}>✓ {okMsg}</p>}
|
|
<Btn type="submit" variant="ghost" disabled={enviando || !entradaTs}>{enviando ? "Enviando…" : "Enviar solicitud"}</Btn>
|
|
</form>
|
|
{solicitudes.length > 0 && (
|
|
<div style={{ marginTop: "14px" }}>
|
|
{solicitudes.slice(0, 5).map((s) => (
|
|
<div key={s.id} style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", padding: "6px 0", color: COLORS.inkSoft }}>
|
|
<span>{s.tipo === "olvido_entrada" ? "Olvido de entrada" : "Auto-cierre"} · {fmtDT(s.propuesta?.entrada_ts || s.created_at)}</span>
|
|
<Badge tone={s.estado === "autorizada" ? "activo" : s.estado === "rechazada" ? "baja" : "pendiente"}>{s.estado}</Badge>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Card>
|
|
<div style={{ height: "30px" }} />
|
|
</main>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function App() {
|
|
const [session, setSession] = useState(undefined);
|
|
useEffect(() => { apiFetch("/becario/session").then(setSession).catch(() => setSession(null)); }, []);
|
|
if (session === undefined) return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: FONT, color: COLORS.inkSoft }}>Cargando…</div>;
|
|
if (!session) return <Acceso onEntra={setSession} />;
|
|
return <Portal session={session} onSalir={() => setSession(null)} />;
|
|
}
|
|
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
|
|
</script>
|
|
</body>
|
|
</html>
|