Merge rediseno: rediseño visual cream (checada/becario/panel) + arreglos de backend
Integra la rama rediseno en main con --no-ff: - rediseño visual de las tres pantallas sobre theme.js compartido (piel cream) - arreglo aprobar/baja/rechazar (Content-Type solo cuando hay body) - parser de Fastify que tolera cuerpos JSON vacíos (elimina FST_ERR_CTP_EMPTY_JSON_BODY) - apiFetch unificado en theme.js (fin de la triplicación) Resolución de conflictos: main había avanzado con 2 features frontend escritas sobre las pantallas viejas. Se toma el rediseño en los 3 HTML. El BACKEND de esas features se conserva intacto (migración 003_jornada_completa, salida_ts en becario-portal, autorización de jornada_completa en solicitudes). El FRONTEND de esas features NO está en las pantallas cream y se re-agregará por separado: - tarjeta "Cargar un día completo" (becario) + su autorización (panel) [aedb8a8] - link de registro directo ?registro=1 (checada -> becario) [74fb2d1]
This commit is contained in:
commit
faec466f79
8 files changed
+1285
-638
No files matched your search
+2
-2
@@ -21,8 +21,8 @@ COPY --chown=node:node backend/src ./src
|
||||
# stat/leer los archivos; copiar con `--chmod=644 … /dir/` deja el propio
|
||||
# directorio en 0644 y nginx falla con "Permission denied". Por eso se fijan
|
||||
# los permisos explícitamente después del COPY.
|
||||
COPY frontend/checada.html frontend/panel.html frontend/becario.html /usr/share/nginx/html/
|
||||
RUN chmod 755 /usr/share/nginx/html && chmod 644 /usr/share/nginx/html/*.html
|
||||
COPY frontend/checada.html frontend/panel.html frontend/becario.html frontend/theme.js frontend/logo-taboada.png /usr/share/nginx/html/
|
||||
RUN chmod 755 /usr/share/nginx/html && chmod 644 /usr/share/nginx/html/*
|
||||
COPY --chmod=644 backend/nginx-default.conf /etc/nginx/http.d/default.conf
|
||||
COPY --chmod=755 backend/docker-entrypoint.sh /docker-entrypoint.sh
|
||||
|
||||
|
||||
@@ -39,6 +39,27 @@ const fastify = Fastify({
|
||||
},
|
||||
});
|
||||
|
||||
// Fastify rechaza por defecto un cuerpo vacío cuando el Content-Type es JSON
|
||||
// (FST_ERR_CTP_EMPTY_JSON_BODY → 400). Pero un POST sin body con ese header es
|
||||
// una petición válida —aprobar/baja/rechazar/logout, y cualquier script o app
|
||||
// futura— así que reemplazamos el parser de JSON para tratar el cuerpo vacío
|
||||
// como "sin body" (undefined) en lugar de un error. Un JSON malformado sigue
|
||||
// dando 400, igual que el parser por defecto. No depende de ninguna env var.
|
||||
fastify.removeContentTypeParser('application/json');
|
||||
fastify.addContentTypeParser(
|
||||
'application/json',
|
||||
{ parseAs: 'string' },
|
||||
(req, body, done) => {
|
||||
if (body === '' || body == null) return done(null, undefined);
|
||||
try {
|
||||
done(null, JSON.parse(body));
|
||||
} catch (err) {
|
||||
err.statusCode = 400;
|
||||
done(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ¿origen de localhost o de una IP privada (LAN)? Solo se usa en modo dev.
|
||||
function esOrigenLanDev(origin) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# Inventario de estados de UI — para el rediseño visual (rama `rediseno`)
|
||||
|
||||
Todas las pantallas y **cada estado condicional** de los tres HTML, con cómo
|
||||
forzar cada uno para verlo en el navegador. La lógica de negocio y las llamadas
|
||||
al backend **no cambian** en el rediseño: solo el diseño visual.
|
||||
|
||||
## Terreno y accesos
|
||||
|
||||
- **Desde la Mac:** `http://localhost/…` · **Desde el celular (LAN):** `http://192.168.1.205/…`
|
||||
- **Panel (supervisora):** `http://localhost/panel.html` — usuario `supervisora`, contraseña en `.env` (`SUPERVISORA_PASSWORD_INICIAL`).
|
||||
- **Portal (becario):** `http://localhost/becario.html` · **Checada:** `http://localhost/checada.html`
|
||||
- Las cookies de supervisora y becario son **distintas**: puedes estar logueado como ambos en el mismo navegador a la vez.
|
||||
- **Cuentas demo** (contraseña `demo1234`): `5550000001` **Demo Activo** · `5550000002` **Demo Pendiente**.
|
||||
- Terreno activo: `COOKIE_INSECURE=true`, puerto 80 en la LAN, ventana `00:00–23:59`, tarea desactivada.
|
||||
|
||||
### Recetas reutilizables
|
||||
|
||||
- **Token fresco:** navega a `http://localhost/e/nfc` → redirige a `/checada.html?t=<token>` (cada visita = token nuevo).
|
||||
- **Token inválido:** `http://localhost/checada.html?t=zzz`.
|
||||
- **Token vencido:** `docker compose exec postgres psql -U taboada_app -d taboada -c "INSERT INTO tokens_checada (token,origen,ventana_ts,expira_ts) VALUES ('vencido1','nfc',NOW()-interval '10 min',NOW()-interval '5 min');"` → usa `/checada.html?t=vencido1`.
|
||||
- **Cambiar ventana / switch de tarea:** Panel → Configuración (o `PATCH /api/config`).
|
||||
- **Reset de una cuenta a pendiente** (para ver estados pendiente): `docker compose exec postgres psql -U taboada_app -d taboada -c "UPDATE becarios SET estado='pendiente' WHERE telefono='5550000001';"` (revertir con la vista de aprobación o `estado='activo'`).
|
||||
- **Cerrar/limpiar la jornada abierta de un becario** (para volver del form "salida" al form "entrada"): `docker compose exec postgres psql -U taboada_app -d taboada -c "DELETE FROM jornadas WHERE becario_id=(SELECT id FROM becarios WHERE telefono='5550000001') AND estado='abierta';"`
|
||||
|
||||
---
|
||||
|
||||
## 1) `checada.html` — flujo de checada (móvil)
|
||||
|
||||
Enrutado por parámetros de URL (`?t=`, `?cerrado=1`) + sesión de becario + respuestas del backend.
|
||||
|
||||
| # | Estado | Cómo forzarlo |
|
||||
|---|---|---|
|
||||
| A1 | **Cargando** (verificando sesión) | Transitorio al cargar; throttle de red para congelarlo. |
|
||||
| A2 | **Checado cerrado** (fuera de ventana) | `http://localhost/checada.html?cerrado=1` (real: tap a `/e/nfc` con la ventana ajustada para excluir la hora actual). |
|
||||
| A3 | **Login integrado** (sin sesión de becario) | Abre `/checada.html?t=algo` en incógnito o tras "Salir". Sub-estados: L1 formulario · L2 error credenciales (clave mala) · L3 error 429 (>5 intentos/min) · L4 "…" enviando. Incluye link "¿No tienes cuenta? Regístrate". |
|
||||
| A4 | **Sin token** ("Acerca tu celular al chip") | Con sesión de becario, abre `/checada.html` **sin** `?t=`. |
|
||||
| C1 | **Contexto cargando** | Transitorio dentro de Checar. |
|
||||
| C2 | **Cuenta pendiente** (no puede checar) | Loguéate como **Demo Pendiente**, luego visita `/e/nfc`. El contexto responde 403. |
|
||||
| C3 | **El código expiró** (token vencido/inválido) | `/checada.html?t=zzz` logueado, o usa un token vencido (receta arriba). |
|
||||
| C4 | **Código ya usado** (de **otro** becario) | Becario A consume un token; con sesión de becario B abre `/checada.html?t=<token de A>` y pulsa Confirmar. |
|
||||
| C5 | **No se pudo registrar** (error genérico) | Otros errores del backend (poco común). |
|
||||
| C6 | **"Este código ya se usó"** (mismo becario, idempotente) | Haz una checada; **recarga** `/checada.html?t=<ese mismo token>` y pulsa Confirmar. |
|
||||
| C7 | **Confirmar ENTRADA** (form) | Demo Activo **sin** jornada abierta + token fresco (`/e/nfc`). |
|
||||
| C8 | **Confirmar SALIDA** (form) | Demo Activo **con** jornada abierta (haz una entrada primero), pide **otro** token (`/e/nfc`). |
|
||||
| C9 | **Form con campo de tarea** | Activa el switch de tarea en Configuración; el form C7/C8 muestra el input "¿Qué tarea realizas?" (obligatorio). |
|
||||
| C10 | **Aviso CONFLICTO_TIPO** (banner amarillo en el form) | Edge: dos pestañas/dispositivos; una cambia el estado de la jornada entre el contexto y el POST. Difícil de forzar a mano. |
|
||||
| C11 | **Éxito: Entrada registrada** (guía al 2º tap) | Pulsa Confirmar en C7. |
|
||||
| C12 | **Éxito: Salida registrada** (jornada cerrada) | Pulsa Confirmar en C8. |
|
||||
| C13 | **"Registrando…"** (botón ocupado) | Transitorio al confirmar. |
|
||||
|
||||
---
|
||||
|
||||
## 2) `becario.html` — portal del becario (móvil)
|
||||
|
||||
| # | Estado | Cómo forzarlo |
|
||||
|---|---|---|
|
||||
| B-A1 | **Cargando** (verificando sesión) | Transitorio. |
|
||||
| AC1 | **Acceso — pestaña Entrar** (login) | Estado por defecto sin sesión. |
|
||||
| AC2 | **Acceso — pestaña Registrarme** | Toca "Registrarme": añade campo Nombre + nota "queda pendiente". |
|
||||
| AC3 | **Acceso — error de login** | Login con clave incorrecta → "Número o contraseña incorrectos". |
|
||||
| AC4 | **Acceso — error de registro específico** | Registrarse con teléfono ≠ 10 dígitos, contraseña < 6, nombre vacío, o número repetido → mensaje puntual del backend. |
|
||||
| AC5 | **Acceso — error 429** | >5 intentos de login/registro en 1 min. |
|
||||
| AC6 | **Acceso — enviando** | Transitorio ("…"). |
|
||||
| P1 | **Portal — cargando** (resumen) | Transitorio. |
|
||||
| P2 | **Portal — banner "cuenta pendiente"** | Loguéate como **Demo Pendiente**. |
|
||||
| P3 | **Portal — header** (nombre, teléfono, badge de estado) | Cualquier sesión. |
|
||||
| P4 | **Portal — tarjeta de horas** (barra) | 0 h (cuenta nueva), >0 h (con jornadas), ≥100% (barra verde llena — sube meta baja o crea jornadas). |
|
||||
| P5 | **Portal — jornadas: vacío vs lista** | Vacío: cuenta sin jornadas. Lista: con jornadas (badges cerrada/abierta/revisión). |
|
||||
| P6 | **Portal — "olvidé marcar entrada" + confirmación** | Envía el formulario → aparece "✓ Solicitud enviada". |
|
||||
| P7 | **Portal — lista de solicitudes** | Tras enviar solicitudes (badges pendiente/autorizada/rechazada). |
|
||||
| P8 | **Portal — barra de error** | Provoca un error de red o del backend. |
|
||||
|
||||
---
|
||||
|
||||
## 3) `panel.html` — panel de la supervisora (escritorio)
|
||||
|
||||
| # | Estado | Cómo forzarlo |
|
||||
|---|---|---|
|
||||
| PN-A1 | **Cargando** (verificando sesión) | Transitorio. |
|
||||
| PN-A2 | **Login** | Sin sesión. Sub: error credenciales · error 429 · "Entrando…". |
|
||||
| PN-A3 | **Panel con navegación** (Becarios / Solicitudes / Configuración) | Tras login. |
|
||||
| **Becarios** | | |
|
||||
| VB1 | **Cargando** | Transitorio. |
|
||||
| VB2 | **Vacío** ("aún no hay becarios") | Base sin becarios (no aplica ahora; hay varios). |
|
||||
| VB3 | **Cola de aprobación** (banner) | Solo si hay pendientes → hay **Demo Pendiente**. Botón Aprobar. |
|
||||
| VB4 | **Tabla de becarios** | Filas con badges activo/pendiente/baja, barra de avance, acciones (Aprobar si pendiente, Ver, Editar, Baja). |
|
||||
| VB5 | **Formulario — Nuevo becario** | Botón "+ Nuevo becario". |
|
||||
| VB6 | **Formulario — Editar becario** | Botón "Editar" en una fila. |
|
||||
| **Detalle de becario** | | |
|
||||
| VD1 | **Cargando** | Transitorio. |
|
||||
| VD2 | **Header + tarjeta de avance** | Toca "Ver" en un becario. |
|
||||
| VD3 | **Jornadas: vacío vs lista** | Lista con acciones Editar y (Cerrar si está en revisión), flag "editada". |
|
||||
| VD4 | **Editor de jornada** (modal) | Botón "Editar" en una jornada. |
|
||||
| VD5 | **Ajustes: formulario + lista** | Siempre visible; agrega un ajuste para ver la lista. |
|
||||
| VD6 | **Checadas: vacío vs lista** (ip/user-agent/concepto) | Un becario que ya checó (Fernando) muestra la tabla. |
|
||||
| **Configuración** | | |
|
||||
| VC1 | **Cargando** | Transitorio. |
|
||||
| VC2 | **Formulario** (ventana, switch de tarea, meta) + "✓ guardada" | Pestaña Configuración; guarda para ver el mensaje. |
|
||||
| **Solicitudes** | | |
|
||||
| VS1 | **Cargando** | Transitorio. |
|
||||
| VS2 | **Vacío** ("no hay solicitudes pendientes") | Sin solicitudes pendientes. |
|
||||
| VS3 | **Lista** (olvido_entrada / autorizar_autocierre) | Crea una solicitud desde el portal, o dispara un auto-cierre. Botones Autorizar / Rechazar (usan `prompt()` — candidato a rediseño a modal). |
|
||||
| — | **Barra de error global** | Provoca un error en cualquier acción. |
|
||||
|
||||
---
|
||||
|
||||
## Notas para el rediseño
|
||||
|
||||
- Los tres HTML comparten un lenguaje visual (objeto `COLORS`, componentes `Btn`/`Card`/`Badge`/`Input`, tipografía del sistema). Conviene rediseñarlos como **un sistema**, no tres estilos sueltos.
|
||||
- `panel.html` es de **escritorio** (tablas anchas); `becario.html` y `checada.html` son **móvil** (una columna, targets grandes para el pulgar).
|
||||
- Estados que hoy usan `prompt()`/`confirm()` del navegador (cerrar jornada, autorizar solicitud, baja) son buenos candidatos a modal propio en el rediseño — pero **la lógica de las llamadas no debe cambiar**.
|
||||
- Al integrar, cada pantalla debe conservar: los mismos endpoints, los mismos campos de formulario, y el mismo mapeo de errores por `code`.
|
||||
+157
-174
@@ -4,37 +4,35 @@
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Taboada — Mis horas</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="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 style="margin:0;padding:0;">
|
||||
<body>
|
||||
<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;
|
||||
}
|
||||
// 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);
|
||||
// ahora vive en un solo sitio en vez de duplicado por página.
|
||||
const { apiFetch } = Theme;
|
||||
|
||||
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";
|
||||
// Piel visual "cream" del rediseño, servida por theme.js (flavor 'becario' =
|
||||
// móvil, mismos componentes y tokens que checada). Nada de colores inline.
|
||||
const UI = Theme.makeUI("becario");
|
||||
const { Logo, Card, Btn, Input, Aviso, IconBadge, StatusBadge, HorasCard, palette, fonts, icons } = UI;
|
||||
|
||||
function fmtDT(iso) {
|
||||
if (!iso) return "—";
|
||||
@@ -45,41 +43,43 @@ function fmtDT(iso) {
|
||||
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>
|
||||
// ─────────────────── Piezas visuales locales ───────────────────
|
||||
const Cargando = ({ texto = "Cargando…" }) => (
|
||||
<div style={{ minHeight: "100vh", background: palette.bgGradient, display: "grid", placeItems: "center", fontFamily: fonts.body }}>
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "12px", color: palette.inkSoft }}>
|
||||
<span style={{ display: "inline-flex" }}>{icons.spinner({ size: 24, color: palette.primary, track: palette.line })}</span>
|
||||
<span style={{ fontFamily: fonts.body, fontSize: "14px" }}>{texto}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ═══════════════ Login / Registro ═══════════════
|
||||
// Header de marca para la pantalla de acceso (logo con las mismas proporciones
|
||||
// que checada, + wordmark y subtítulo del diseño).
|
||||
const Marca = () => (
|
||||
<div style={{ textAlign: "center", marginBottom: "18px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "center", marginBottom: "10px" }}><Logo /></div>
|
||||
<h1 style={{ margin: "0 0 3px", fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, letterSpacing: "-.01em" }}>Taboada</h1>
|
||||
<p style={{ margin: 0, fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft }}>Registro de horas de servicio</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Barra de error global, descartable (estado P8 del inventario).
|
||||
const ErrorBar = ({ error, onClose }) => !error ? null : (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "10px",
|
||||
background: palette.errBg, border: `1px solid ${palette.errBorder}`, borderRadius: "14px", padding: "12px 14px", marginBottom: "16px" }}>
|
||||
<span style={{ display: "flex", alignItems: "center", gap: "9px" }}>
|
||||
<span style={{ display: "inline-flex", flexShrink: 0 }}>{icons.alertTriangle({ size: 18, color: palette.danger })}</span>
|
||||
<span style={{ fontFamily: fonts.body, fontSize: "13px", fontWeight: 500, color: palette.errText, lineHeight: 1.35 }}>{error}</span>
|
||||
</span>
|
||||
<span onClick={onClose} style={{ cursor: "pointer", flexShrink: 0, fontWeight: 700, color: palette.errText, fontSize: "16px", lineHeight: 1, padding: "0 2px" }}>✕</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ═══════════════ Acceso · login / registro ═══════════════
|
||||
function Acceso({ onEntra }) {
|
||||
const [modo, setModo] = useState(() =>
|
||||
new URLSearchParams(window.location.search).get("registro") === "1" ? "registro" : "login"
|
||||
);
|
||||
const [modo, setModo] = useState("login");
|
||||
const [f, setF] = useState({ telefono: "", password: "", nombre: "" });
|
||||
const [error, setError] = useState(null);
|
||||
const [error, setError] = useState(null); // { text, ic }
|
||||
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) => {
|
||||
@@ -92,34 +92,36 @@ function Acceso({ onEntra }) {
|
||||
}
|
||||
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.";
|
||||
// Mismo mapeo por code/status de siempre; el ícono sólo acompaña.
|
||||
let text, ic = "alertCircle";
|
||||
if (err.status === 429) { text = "Demasiados intentos, espera un minuto."; ic = "clock"; }
|
||||
else if (err.code === "TELEFONO_YA_REGISTRADO") text = "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);
|
||||
else if (modo === "registro" && err.status >= 400 && err.status < 500 && err.message) text = err.message;
|
||||
else if (modo === "registro") text = "No se pudo registrar. Intenta de nuevo.";
|
||||
else text = "Número o contraseña incorrectos.";
|
||||
setError({ text, ic });
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
const reg = modo === "registro";
|
||||
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>
|
||||
<div style={{ minHeight: "100vh", background: palette.bgGradient, display: "flex", flexDirection: "column", justifyContent: "center", padding: "32px 20px", fontFamily: fonts.body }}>
|
||||
<div style={{ width: "100%", maxWidth: "420px", margin: "0 auto" }}>
|
||||
<Marca />
|
||||
<Card>
|
||||
<div style={{ display: "flex", gap: "8px", marginBottom: "16px" }}>
|
||||
<div style={{ display: "flex", gap: "7px", background: palette.softTint, borderRadius: "13px", padding: "4px", marginBottom: "18px" }}>
|
||||
{["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,
|
||||
<button key={m} type="button" onClick={() => { setModo(m); setError(null); }} style={{
|
||||
flex: 1, textAlign: "center", padding: "9px", borderRadius: "10px", border: "none", cursor: "pointer",
|
||||
fontFamily: fonts.body, fontWeight: 700, fontSize: "14px",
|
||||
background: modo === m ? palette.primary : "transparent", color: modo === m ? "#fff" : palette.inkSoft,
|
||||
}}>{m === "login" ? "Entrar" : "Registrarme"}</button>
|
||||
))}
|
||||
</div>
|
||||
<ErrorBar error={error} onClose={() => setError(null)} />
|
||||
{error && <Aviso variant="error" icon={error.ic}>{error.text}</Aviso>}
|
||||
<form onSubmit={submit}>
|
||||
{modo === "registro" && (
|
||||
{reg && (
|
||||
<div style={{ marginBottom: "12px" }}>
|
||||
<Input placeholder="Tu nombre" value={f.nombre} onChange={set("nombre")} required />
|
||||
</div>
|
||||
@@ -127,16 +129,18 @@ function Acceso({ onEntra }) {
|
||||
<div style={{ marginBottom: "12px" }}>
|
||||
<Input placeholder="Celular (10 dígitos)" inputMode="numeric" value={f.telefono} onChange={set("telefono")} required />
|
||||
</div>
|
||||
<div style={{ marginBottom: "16px" }}>
|
||||
<div style={{ marginBottom: "18px" }}>
|
||||
<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 type="submit" loading={busy} disabled={busy || f.telefono.length !== 10 || f.password.length < (reg ? 6 : 1) || (reg && !f.nombre.trim())}>
|
||||
{busy ? (reg ? "Creando…" : "Entrando…") : (reg ? "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>}
|
||||
{reg && (
|
||||
<p style={{ margin: "12px 0 0", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, textAlign: "center", lineHeight: 1.5 }}>
|
||||
Tu cuenta queda pendiente hasta que la supervisora la apruebe.
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -152,9 +156,6 @@ function Portal({ session, onSalir }) {
|
||||
const [entradaTs, setEntradaTs] = useState("");
|
||||
const [enviando, setEnviando] = useState(false);
|
||||
const [okMsg, setOkMsg] = useState(null);
|
||||
const [dia, setDia] = useState({ fecha: "", entrada: "", salida: "" });
|
||||
const [enviandoDia, setEnviandoDia] = useState(false);
|
||||
const [okDia, setOkDia] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@@ -176,118 +177,100 @@ function Portal({ session, onSalir }) {
|
||||
} catch (err) { setError(err.message); } finally { setEnviando(false); }
|
||||
};
|
||||
|
||||
// Día completo: fecha + entrada + salida (horas en múltiplos de 5 min por el
|
||||
// step de los inputs). Se combinan en timestamps locales → ISO. El backend
|
||||
// valida rango y múltiplos; suma solo tras la autorización de la supervisora.
|
||||
const diaValido = dia.fecha && dia.entrada && dia.salida && dia.salida > dia.entrada;
|
||||
const crearJornadaCompleta = async (e) => {
|
||||
e.preventDefault(); setEnviandoDia(true); setError(null); setOkDia(null);
|
||||
try {
|
||||
await apiFetch("/becario/solicitudes", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
entrada_ts: localToIso(`${dia.fecha}T${dia.entrada}`),
|
||||
salida_ts: localToIso(`${dia.fecha}T${dia.salida}`),
|
||||
}),
|
||||
});
|
||||
setDia({ fecha: "", entrada: "", salida: "" });
|
||||
setOkDia("Día enviado. Sumará a tus horas cuando la supervisora lo autorice.");
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err.code === "MINUTOS_INVALIDOS" ? "Las horas deben ir en múltiplos de 5 minutos."
|
||||
: err.code === "RANGO_INVALIDO" ? "La salida debe ser posterior a la entrada."
|
||||
: err.message);
|
||||
} finally { setEnviandoDia(false); }
|
||||
};
|
||||
|
||||
if (!resumen) return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: FONT, color: COLORS.inkSoft }}>Cargando…</div>;
|
||||
if (!resumen) return <Cargando texto="Cargando tu portal…" />;
|
||||
// Horas y avance vienen calculados del backend (resumen.horas); aquí sólo se pintan.
|
||||
const h = resumen.horas;
|
||||
const pendiente = resumen.estado === "pendiente";
|
||||
const meta = h.porcentaje >= 100;
|
||||
const secTitle = { margin: "20px 0 9px", fontFamily: fonts.title, fontWeight: 600, fontSize: "15px", color: palette.brand };
|
||||
|
||||
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 style={{ minHeight: "100vh", background: palette.bgGradient, fontFamily: fonts.body }}>
|
||||
<header style={{ maxWidth: "440px", margin: "0 auto", padding: "16px 18px 14px", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: `1px solid ${palette.cardBorder}` }}>
|
||||
<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 style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.brand }}>{resumen.nombre}</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "6px", marginTop: "2px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft }}>
|
||||
{resumen.telefono} <StatusBadge tone={resumen.estado}>{resumen.estado}</StatusBadge>
|
||||
</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>
|
||||
<button onClick={salir} style={{ padding: "7px 12px", background: "transparent", border: `1px solid ${palette.line}`, borderRadius: "11px", fontFamily: fonts.body, fontWeight: 600, fontSize: "12px", color: palette.primary, cursor: "pointer" }}>Salir</button>
|
||||
</header>
|
||||
<main style={{ maxWidth: "460px", margin: "0 auto", padding: "18px" }}>
|
||||
|
||||
<main style={{ maxWidth: "440px", 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>
|
||||
<div style={{ background: palette.warnBg, border: `1px solid ${palette.warnBorder}`, borderRadius: "18px", padding: "16px 18px", marginBottom: "18px" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "6px" }}>
|
||||
<span style={{ display: "inline-flex", flexShrink: 0 }}>{icons.clock({ size: 17, color: palette.amber })}</span>
|
||||
<strong style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.warnText }}>Cuenta pendiente de aprobación</strong>
|
||||
</div>
|
||||
<p style={{ margin: 0, fontFamily: fonts.body, fontSize: "13px", color: palette.warnText, lineHeight: 1.5 }}>
|
||||
Ya puedes ver tu portal, pero aún no puedes checar. Avisa a la supervisora para que apruebe tu cuenta.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<HorasCard
|
||||
total={fmtHoras(h.total_horas)} meta={fmtHoras(h.meta_horas)} porcentaje={h.porcentaje}
|
||||
sub={`${h.porcentaje}% de tu meta · jornadas ${(h.minutos_jornadas / 60).toFixed(1)} h + ajustes ${(h.minutos_ajustes / 60).toFixed(1)} h`}
|
||||
/>
|
||||
|
||||
{meta && (
|
||||
<div style={{ marginTop: "16px" }}>
|
||||
<Aviso variant="success">Completaste tus horas de servicio social. La supervisora recibirá la constancia para tu liberación. ¡Gracias por tu compromiso!</Aviso>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h3 style={secTitle}>Mis jornadas</h3>
|
||||
{jornadas.length === 0 ? (
|
||||
<Card style={{ textAlign: "center", padding: "26px 20px" }}>
|
||||
<IconBadge icon="calendar" tone="neutral" size={52} />
|
||||
<p style={{ margin: 0, fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, lineHeight: 1.5 }}>
|
||||
Aún no tienes jornadas.<br/>Empezarán a aparecer cuando puedas checar.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<Card style={{ padding: 0, borderRadius: "18px", overflow: "hidden" }}>
|
||||
{jornadas.slice(0, 20).map((j, i, arr) => (
|
||||
<div key={j.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 15px", borderBottom: i < arr.length - 1 ? `1px solid ${palette.line}` : "none" }}>
|
||||
<div>
|
||||
<div style={{ fontFamily: fonts.body, fontWeight: 500, fontSize: "13px", color: palette.ink }}>
|
||||
{fmtDT(j.entrada_ts)} → {j.salida_ts ? fmtDT(j.salida_ts) : "sin salida"}
|
||||
</div>
|
||||
<div style={{ fontFamily: fonts.body, fontWeight: 400, fontSize: "11px", color: palette.inkSoft, marginTop: "2px" }}>
|
||||
{j.estado}{j.duracion_minutos != null ? ` · ${(j.duracion_minutos / 60).toFixed(1)} h` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge tone={j.estado}>{j.estado}</StatusBadge>
|
||||
</div>
|
||||
))}
|
||||
</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" }}>Cargar un día completo</h3>
|
||||
<Card>
|
||||
<p style={{ margin: "0 0 10px", fontSize: "13px", color: COLORS.inkSoft }}>Registra un día que no checaste: fecha, hora de entrada y de salida. La supervisora lo revisa y, al autorizarlo, suma a tus horas.</p>
|
||||
<form onSubmit={crearJornadaCompleta}>
|
||||
<div style={{ marginBottom: "10px" }}>
|
||||
<label style={{ display: "block", fontSize: "12px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "4px" }}>Fecha</label>
|
||||
<Input type="date" value={dia.fecha} onChange={(e) => setDia({ ...dia, fecha: e.target.value })} required />
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "10px", marginBottom: "10px" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<label style={{ display: "block", fontSize: "12px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "4px" }}>Entrada</label>
|
||||
<Input type="time" step="300" value={dia.entrada} onChange={(e) => setDia({ ...dia, entrada: e.target.value })} required />
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<label style={{ display: "block", fontSize: "12px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "4px" }}>Salida</label>
|
||||
<Input type="time" step="300" value={dia.salida} onChange={(e) => setDia({ ...dia, salida: e.target.value })} required />
|
||||
</div>
|
||||
</div>
|
||||
{dia.entrada && dia.salida && dia.salida <= dia.entrada && (
|
||||
<p style={{ color: COLORS.warn, fontSize: "12px", margin: "0 0 10px" }}>La salida debe ser posterior a la entrada.</p>
|
||||
)}
|
||||
{okDia && <p style={{ color: COLORS.success, fontSize: "13px", margin: "0 0 10px" }}>✓ {okDia}</p>}
|
||||
<Btn type="submit" disabled={enviandoDia || !diaValido}>{enviandoDia ? "Enviando…" : "Enviar día completo"}</Btn>
|
||||
</form>
|
||||
</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>
|
||||
<h3 style={secTitle}>Olvidé marcar mi entrada</h3>
|
||||
<Card style={{ borderRadius: "18px", padding: "18px" }}>
|
||||
<p style={{ margin: "0 0 11px", fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, lineHeight: 1.5 }}>
|
||||
Propón la hora a la que entraste; la supervisora la revisará y autorizará.
|
||||
</p>
|
||||
<form onSubmit={crearSolicitud}>
|
||||
<div style={{ marginBottom: "10px" }}>
|
||||
<label style={{ display: "block", fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, color: palette.label, marginBottom: "6px" }}>Fecha y hora de entrada</label>
|
||||
<div style={{ marginBottom: "12px" }}>
|
||||
<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>
|
||||
{okMsg && <Aviso variant="success" icon="check">{okMsg}</Aviso>}
|
||||
<Btn type="submit" variant="ghost" loading={enviando} disabled={enviando || !entradaTs}>
|
||||
{enviando ? "Enviando…" : "Enviar solicitud"}
|
||||
</Btn>
|
||||
</form>
|
||||
{solicitudes.length > 0 && (
|
||||
<div style={{ marginTop: "14px" }}>
|
||||
<div style={{ marginTop: "14px", borderTop: `1px solid ${palette.line}`, paddingTop: "6px" }}>
|
||||
{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" : s.tipo === "jornada_completa" ? "Día completo" : "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 key={s.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "9px 0" }}>
|
||||
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft }}>
|
||||
{s.tipo === "olvido_entrada" ? "Olvido de entrada" : "Auto-cierre"} · {fmtDT(s.propuesta?.entrada_ts || s.created_at)}
|
||||
</span>
|
||||
<StatusBadge tone={s.estado}>{s.estado}</StatusBadge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -302,7 +285,7 @@ function Portal({ session, onSalir }) {
|
||||
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 === undefined) return <Cargando texto="Verificando sesión…" />;
|
||||
if (!session) return <Acceso onEntra={setSession} />;
|
||||
return <Portal session={session} onSalir={() => setSession(null)} />;
|
||||
}
|
||||
|
||||
+77
-76
@@ -4,68 +4,63 @@
|
||||
<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="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 style="margin:0;padding:0;">
|
||||
<body>
|
||||
<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;
|
||||
}
|
||||
// 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 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 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: COLORS.bg, display: "flex", alignItems: "center", justifyContent: "center", padding: "20px", fontFamily: FONT }}>
|
||||
<div style={{ width: "100%", maxWidth: "400px" }}>{children}</div>
|
||||
<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 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 }) => (
|
||||
|
||||
const Cargando = ({ texto = "Cargando…" }) => (
|
||||
<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>}
|
||||
<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>
|
||||
);
|
||||
|
||||
// ═══════════════ Login inline (para no perder el token de la URL) ═══════════════
|
||||
// ═══════════════ 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);
|
||||
@@ -76,14 +71,17 @@ function LoginInline({ onEntra }) {
|
||||
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.");
|
||||
// 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", 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>}
|
||||
<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" }}>Tu código sigue activo unos minutos.</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 />
|
||||
@@ -91,10 +89,10 @@ function LoginInline({ onEntra }) {
|
||||
<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>
|
||||
<Btn type="submit" loading={busy} disabled={busy || f.telefono.length !== 10 || !f.password}>{busy ? "Entrando…" : "Entrar"}</Btn>
|
||||
</form>
|
||||
<p style={{ textAlign: "center", marginTop: "14px", marginBottom: 0, fontSize: "13px" }}>
|
||||
<a href="/becario.html?registro=1" style={{ color: COLORS.primary }}>¿No tienes cuenta? Regístrate</a>
|
||||
<p style={{ textAlign: "center", marginTop: "16px", marginBottom: 0, fontSize: "13px", fontFamily: fonts.body }}>
|
||||
<a href="/becario.html" style={{ color: palette.primary, fontWeight: 600, textDecoration: "none" }}>¿No tienes cuenta? Regístrate</a>
|
||||
</p>
|
||||
</Card>
|
||||
);
|
||||
@@ -130,58 +128,61 @@ function Checar({ token }) {
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
|
||||
if (ctx === undefined) return <Card style={{ textAlign: "center", color: COLORS.inkSoft }}>Cargando…</Card>;
|
||||
if (ctx === undefined) return <Cargando />; // C1
|
||||
|
||||
// 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." />;
|
||||
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 acercar tu celular al chip 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ó. 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 (error.code !== "CONFLICTO_TIPO") // C5 genérico
|
||||
return <Estado icon="alertCircle" tone="danger" title="No se pudo registrar" sub={error.message} />;
|
||||
}
|
||||
|
||||
if (resultado) {
|
||||
// Token de un solo uso ya consumido: no es error del becario, es lo correcto.
|
||||
// C6 · Token de un solo uso ya consumido: no es error del becario, es lo correcto.
|
||||
if (resultado.duplicada)
|
||||
return <Big emoji="🔄" title="Este código ya se usó" tone={COLORS.primary}
|
||||
return <Estado icon="refresh" tone="blue" dashed title="Este código ya se usó"
|
||||
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 <Big emoji="🟢" title={`Entrada registrada${hora ? ` a las ${hora}` : ""}`} tone={COLORS.success}
|
||||
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 acercar el celular al chip para registrar tu salida.`} />;
|
||||
return <Big emoji="🔴" title={`Salida registrada${hora ? ` a las ${hora}` : ""}`} tone={COLORS.success}
|
||||
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>
|
||||
<h2 style={{ margin: "0 0 4px", color: COLORS.ink, fontSize: "20px", textAlign: "center" }}>
|
||||
<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", color: COLORS.inkSoft, fontSize: "14px", textAlign: "center" }}>
|
||||
<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" && (
|
||||
<div style={{ background: COLORS.warnBg, color: COLORS.warn, padding: "10px", borderRadius: "10px", fontSize: "13px", marginBottom: "12px" }}>
|
||||
{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.
|
||||
</div>
|
||||
</Aviso>
|
||||
)}
|
||||
{ctx.tarea_activa && (
|
||||
{ctx.tarea_activa && ( /* C9 */
|
||||
<div style={{ marginBottom: "16px" }}>
|
||||
<label style={{ display: "block", fontSize: "13px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "6px" }}>¿Qué tarea realizas? (obligatorio)</label>
|
||||
<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"} disabled={busy || (ctx.tarea_activa && !concepto.trim())}>
|
||||
<Btn onClick={registrar} variant={esEntrada ? "success" : "primary"} loading={busy} disabled={busy || (ctx.tarea_activa && !concepto.trim())}>
|
||||
{busy ? "Registrando…" : `Confirmar ${esEntrada ? "entrada" : "salida"}`}
|
||||
</Btn>
|
||||
</Card>
|
||||
@@ -196,10 +197,10 @@ function App() {
|
||||
|
||||
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>;
|
||||
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
|
||||
if (!token) return <Shell><Estado icon="nfc" tone="blue" title="Acerca tu celular al chip" sub="Para checar, escanea el chip NFC en la oficina de la supervisora." /></Shell>; // A4
|
||||
return <Shell><Checar token={token} /></Shell>;
|
||||
}
|
||||
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
+309
-386
@@ -4,47 +4,39 @@
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Taboada — Panel de supervisión</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="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 style="margin:0;padding:0;">
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="text/babel" data-presets="react">
|
||||
const { useState, useEffect, useCallback } = React;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// API — el panel se sirve detrás de nginx (mismo origen); nginx hace
|
||||
// proxy_pass de /api al servicio node. credentials:'include' manda la
|
||||
// cookie de sesión de la supervisora en cada request.
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
const API_BASE = `${window.location.origin}/api`;
|
||||
// Cableado al backend: cliente HTTP compartido en theme.js, el mismo para las
|
||||
// tres páginas. El panel se sirve detrás de nginx (mismo origen); la cookie de
|
||||
// sesión de la supervisora viaja con credentials:'include'. Mismo mapeo de
|
||||
// error por code/status que antes; ahora en un solo sitio.
|
||||
const { apiFetch } = Theme;
|
||||
|
||||
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;
|
||||
}
|
||||
// Piel cream de escritorio (theme.js, flavor 'panel'). Nada de colores inline.
|
||||
const UI = Theme.makeUI("panel");
|
||||
const { Logo, Card, Btn, Input, Field, Badge, Aviso, ErrorBar, Toggle, ProgressBar,
|
||||
Nav, Table, Tr, Td, Modal, EmptyState, palette, fonts, icons } = UI;
|
||||
|
||||
const COLORS = {
|
||||
bg: "#EEF1F4", surface: "#FFFFFF", ink: "#1F2933", inkSoft: "#616E7C",
|
||||
border: "#DDE2E7", primary: "#2A6FB0", primaryDark: "#1E4E7E",
|
||||
success: "#2E7D5B", successBg: "#E7F3EC", warn: "#B7791F", warnBg: "#FBF2E1",
|
||||
danger: "#C0392B", dangerBg: "#FBEBE9", chip: "#F0F2F5", accentBg: "#EAF2FA",
|
||||
};
|
||||
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
|
||||
|
||||
// ── Formato (presentación en America/Mexico_City, §7) ──
|
||||
// ── Formato (presentación en America/Mexico_City) ──
|
||||
function fmtDT(iso) {
|
||||
if (!iso) return "—";
|
||||
return new Date(iso).toLocaleString("es-MX", {
|
||||
@@ -61,93 +53,59 @@ function isoToLocal(iso) {
|
||||
}
|
||||
function localToIso(v) { return v ? new Date(v).toISOString() : null; }
|
||||
|
||||
// ═══════════════════ UI primitivos ═══════════════════
|
||||
const Btn = ({ children, onClick, variant = "primary", disabled, size = "md", type = "button" }) => {
|
||||
const V = {
|
||||
primary: { bg: COLORS.primary, c: "#fff", bd: "none" },
|
||||
success: { bg: COLORS.success, c: "#fff", bd: "none" },
|
||||
danger: { bg: COLORS.danger, c: "#fff", bd: "none" },
|
||||
ghost: { bg: "transparent", c: COLORS.primary, bd: `1px solid ${COLORS.border}` },
|
||||
subtle: { bg: COLORS.chip, c: COLORS.ink, bd: "none" },
|
||||
}[variant];
|
||||
const pad = size === "sm" ? "6px 12px" : "10px 18px";
|
||||
return (
|
||||
<button type={type} onClick={onClick} disabled={disabled} style={{
|
||||
padding: pad, borderRadius: "8px", background: disabled ? COLORS.border : V.bg,
|
||||
color: disabled ? COLORS.inkSoft : V.c, border: V.bd, fontFamily: FONT,
|
||||
fontSize: size === "sm" ? "13px" : "14px", fontWeight: 600,
|
||||
cursor: disabled ? "not-allowed" : "pointer", transition: "opacity .15s",
|
||||
}}>{children}</button>
|
||||
);
|
||||
};
|
||||
const Card = ({ children, style }) => (
|
||||
<div style={{ background: COLORS.surface, borderRadius: "12px", border: `1px solid ${COLORS.border}`,
|
||||
padding: "20px", boxShadow: "0 1px 3px rgba(0,0,0,0.04)", ...style }}>{children}</div>
|
||||
);
|
||||
const Field = ({ label, children }) => (
|
||||
<label style={{ display: "block", marginBottom: "12px" }}>
|
||||
<span style={{ display: "block", fontSize: "13px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "5px" }}>{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
const inputStyle = {
|
||||
width: "100%", padding: "9px 11px", borderRadius: "8px", border: `1px solid ${COLORS.border}`,
|
||||
fontSize: "14px", fontFamily: FONT, color: COLORS.ink, boxSizing: "border-box", outline: "none",
|
||||
};
|
||||
const Input = (p) => <input {...p} style={{ ...inputStyle, ...(p.style || {}) }} />;
|
||||
const Badge = ({ children, tone = "chip" }) => {
|
||||
const T = {
|
||||
chip: { bg: COLORS.chip, c: COLORS.inkSoft }, success: { bg: COLORS.successBg, c: COLORS.success },
|
||||
warn: { bg: COLORS.warnBg, c: COLORS.warn }, danger: { bg: COLORS.dangerBg, c: COLORS.danger },
|
||||
primary: { bg: COLORS.accentBg, c: COLORS.primaryDark },
|
||||
}[tone];
|
||||
return <span style={{ background: T.bg, color: T.c, padding: "2px 9px", borderRadius: "999px",
|
||||
fontSize: "12px", fontWeight: 700, whiteSpace: "nowrap" }}>{children}</span>;
|
||||
};
|
||||
const ErrorBar = ({ error, onClose }) => !error ? null : (
|
||||
<div style={{ background: COLORS.dangerBg, color: COLORS.danger, padding: "10px 14px", borderRadius: "8px",
|
||||
fontSize: "14px", marginBottom: "14px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<span>⚠ {error}</span>
|
||||
<span onClick={onClose} style={{ cursor: "pointer", fontWeight: 700, paddingLeft: "12px" }}>✕</span>
|
||||
</div>
|
||||
);
|
||||
// Mapeo estado → tono del Badge (el Badge cream traduce el tono a color).
|
||||
const estadoBecarioTone = (e) => ({ activo: "success", pendiente: "warn", baja: "chip" }[e] || "chip");
|
||||
const estadoJornadaTone = (e) => ({ abierta: "primary", cerrada: "success", revision: "warn" }[e] || "chip");
|
||||
const estadoDispTone = (e) => ({ pendiente: "warn", aprobado: "success", revocado: "danger" }[e] || "chip");
|
||||
|
||||
const iconBtn = (name, o) => <span style={{ display: "inline-flex" }}>{icons[name](o)}</span>;
|
||||
|
||||
// ── Modal de confirmación (sustituye el diálogo nativo del navegador) ──
|
||||
// La llamada al backend vive en `onConfirm` (el padre); aquí solo la UI.
|
||||
function ConfirmModal({ title, message, confirmLabel, variant, onConfirm, onCancel }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const go = async () => { setBusy(true); try { await onConfirm(); } finally { setBusy(false); } };
|
||||
return (
|
||||
<Modal title={title} onClose={onCancel} width={400}>
|
||||
<p style={{ margin: "0 0 20px", fontFamily: fonts.body, fontSize: "14px", color: palette.ink, lineHeight: 1.5 }}>{message}</p>
|
||||
<div style={{ display: "flex", gap: "9px" }}>
|
||||
<Btn variant={variant || "primary"} loading={busy} onClick={go}>{confirmLabel || "Confirmar"}</Btn>
|
||||
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════ Login ═══════════════════
|
||||
function Login({ onLogin }) {
|
||||
const [usuario, setUsuario] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState(null);
|
||||
const [error, setError] = useState(null); // { text, ic }
|
||||
const [busy, setBusy] = useState(false);
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true); setError(null);
|
||||
e.preventDefault(); setBusy(true); setError(null);
|
||||
try {
|
||||
await apiFetch("/auth/login", { method: "POST", body: JSON.stringify({ usuario, password }) });
|
||||
const s = await apiFetch("/auth/session");
|
||||
onLogin(s);
|
||||
onLogin(await apiFetch("/auth/session"));
|
||||
} catch (err) {
|
||||
setError(err.status === 429 ? "Demasiados intentos. Espera un minuto." : "Usuario o contraseña incorrectos.");
|
||||
// Mismo mapeo por status de siempre; el ícono sólo acompaña.
|
||||
setError(err.status === 429
|
||||
? { text: "Demasiados intentos. Espera un minuto.", ic: "clock" }
|
||||
: { text: "Usuario o contraseña incorrectos.", ic: "alertCircle" });
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<div style={{ minHeight: "100vh", background: COLORS.bg, display: "flex", alignItems: "center",
|
||||
justifyContent: "center", fontFamily: FONT, padding: "24px" }}>
|
||||
<Card style={{ width: "100%", maxWidth: "380px" }}>
|
||||
<h1 style={{ margin: "0 0 4px", fontSize: "22px", color: COLORS.ink }}>Taboada</h1>
|
||||
<p style={{ margin: "0 0 20px", fontSize: "14px", color: COLORS.inkSoft }}>Panel de supervisión</p>
|
||||
<ErrorBar error={error} onClose={() => setError(null)} />
|
||||
<div style={{ minHeight: "100vh", background: palette.bgGradient, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: fonts.body, padding: "24px" }}>
|
||||
<Card style={{ width: "100%", maxWidth: "400px", borderRadius: "24px", padding: "36px 34px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "center", marginBottom: "18px" }}><Logo style={{ height: "60px" }} /></div>
|
||||
<h1 style={{ margin: "0 0 3px", fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, textAlign: "center", letterSpacing: "-.01em" }}>Taboada</h1>
|
||||
<p style={{ margin: "0 0 24px", fontFamily: fonts.body, fontSize: "14px", color: palette.inkSoft, textAlign: "center" }}>Panel de supervisión</p>
|
||||
{error && <Aviso variant="error" icon={error.ic}>{error.text}</Aviso>}
|
||||
<form onSubmit={submit}>
|
||||
<Field label="Usuario">
|
||||
<Input value={usuario} onChange={(e) => setUsuario(e.target.value)} autoFocus autoComplete="username" />
|
||||
</Field>
|
||||
<Field label="Contraseña">
|
||||
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
|
||||
</Field>
|
||||
<Field label="Usuario"><Input value={usuario} onChange={(e) => setUsuario(e.target.value)} autoFocus autoComplete="username" /></Field>
|
||||
<Field label="Contraseña"><Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" /></Field>
|
||||
<div style={{ marginTop: "8px" }}>
|
||||
<Btn type="submit" disabled={busy || !usuario || !password}>{busy ? "Entrando…" : "Iniciar sesión"}</Btn>
|
||||
<Btn type="submit" block loading={busy} disabled={busy || !usuario || !password}>{busy ? "Entrando…" : "Iniciar sesión"}</Btn>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
@@ -156,32 +114,30 @@ function Login({ onLogin }) {
|
||||
}
|
||||
|
||||
// ═══════════════════ Cola de aprobación de becarios ═══════════════════
|
||||
// Los becarios se auto-registran (celular+password) y quedan 'pendiente'
|
||||
// hasta que la supervisora los aprueba (§4). Sin vínculo de dispositivo.
|
||||
function ColaAprobacion({ pendientes, onAprobar }) {
|
||||
if (pendientes.length === 0) return null;
|
||||
return (
|
||||
<Card style={{ marginBottom: "18px", borderColor: COLORS.warn, background: COLORS.warnBg }}>
|
||||
<h3 style={{ margin: "0 0 12px", fontSize: "15px", color: COLORS.warn }}>
|
||||
Becarios pendientes de aprobar ({pendientes.length})
|
||||
</h3>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
|
||||
<div style={{ background: palette.warnBg, border: `1px solid ${palette.warnBorder}`, borderRadius: "18px", padding: "18px 20px", marginBottom: "20px" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "9px", marginBottom: "13px" }}>
|
||||
{iconBtn("alertTriangle", { size: 19, color: palette.amber })}
|
||||
<span style={{ fontFamily: fonts.title, fontWeight: 600, fontSize: "15px", color: palette.warnText }}>Becarios pendientes de aprobar ({pendientes.length})</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "9px" }}>
|
||||
{pendientes.map((b) => (
|
||||
<div key={b.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
|
||||
background: COLORS.surface, borderRadius: "8px", padding: "10px 12px", gap: "10px", flexWrap: "wrap" }}>
|
||||
<div style={{ fontSize: "14px", color: COLORS.ink }}>
|
||||
<strong>{b.nombre}</strong>
|
||||
<div style={{ fontSize: "12px", color: COLORS.inkSoft, marginTop: "2px" }}>{b.telefono || "sin teléfono"}</div>
|
||||
<div key={b.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: palette.surface, borderRadius: "12px", padding: "11px 14px", gap: "10px", flexWrap: "wrap" }}>
|
||||
<div>
|
||||
<strong style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.ink }}>{b.nombre}</strong>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, marginTop: "2px" }}>{b.telefono || "sin teléfono"}</div>
|
||||
</div>
|
||||
<Btn size="sm" variant="success" onClick={() => onAprobar(b)}>Aprobar</Btn>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════ Formulario de becario (alta/edición) ═══════════════════
|
||||
// ═══════════════════ Formulario de becario (modal alta/edición) ═══════════════════
|
||||
function BecarioForm({ inicial, onSaved, onCancel, onError }) {
|
||||
const [f, setF] = useState({
|
||||
nombre: inicial?.nombre || "", matricula: inicial?.matricula || "",
|
||||
@@ -204,96 +160,84 @@ function BecarioForm({ inicial, onSaved, onCancel, onError }) {
|
||||
} catch (err) { onError(err.message); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Card style={{ marginBottom: "18px" }}>
|
||||
<h3 style={{ margin: "0 0 14px", fontSize: "16px", color: COLORS.ink }}>{inicial ? "Editar becario" : "Nuevo becario"}</h3>
|
||||
<Modal title={inicial ? "Editar becario" : "Nuevo becario"} onClose={onCancel} width={540}>
|
||||
<form onSubmit={submit}>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: "0 16px" }}>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 18px" }}>
|
||||
<Field label="Nombre"><Input value={f.nombre} onChange={set("nombre")} required autoFocus /></Field>
|
||||
<Field label="Matrícula"><Input value={f.matricula} onChange={set("matricula")} /></Field>
|
||||
<Field label="Institución"><Input value={f.institucion} onChange={set("institucion")} /></Field>
|
||||
<Field label="Matrícula"><Input value={f.matricula} onChange={set("matricula")} placeholder="Opcional" /></Field>
|
||||
<Field label="Institución"><Input value={f.institucion} onChange={set("institucion")} placeholder="Opcional" /></Field>
|
||||
<Field label="Meta de horas"><Input type="number" min="1" value={f.meta_horas} onChange={set("meta_horas")} required /></Field>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "8px", marginTop: "6px" }}>
|
||||
<Btn type="submit" disabled={busy || !f.nombre.trim()}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
||||
<Btn variant="subtle" onClick={onCancel}>Cancelar</Btn>
|
||||
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
||||
<Btn type="submit" loading={busy} disabled={busy || !f.nombre.trim()}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
||||
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════ Vista de becarios ═══════════════════
|
||||
function VistaBecarios({ onOpen, onError }) {
|
||||
const [becarios, setBecarios] = useState(null);
|
||||
const [form, setForm] = useState(null); // null | {} (nuevo) | becario (editar)
|
||||
const [form, setForm] = useState(null); // null | {} (nuevo) | becario (editar)
|
||||
const [confirmBaja, setConfirmBaja] = useState(null);
|
||||
const load = useCallback(async () => {
|
||||
try { setBecarios(await apiFetch("/becarios")); } catch (e) { onError(e.message); }
|
||||
}, [onError]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
const baja = async (b) => {
|
||||
if (!confirm(`¿Dar de baja a ${b.nombre}? Conserva su historial, no se elimina.`)) return;
|
||||
try { await apiFetch(`/becarios/${b.id}/baja`, { method: "POST" }); await load(); } catch (e) { onError(e.message); }
|
||||
const doBaja = async (b) => {
|
||||
try { await apiFetch(`/becarios/${b.id}/baja`, { method: "POST" }); setConfirmBaja(null); await load(); }
|
||||
catch (e) { onError(e.message); setConfirmBaja(null); }
|
||||
};
|
||||
const aprobar = async (b) => {
|
||||
try { await apiFetch(`/becarios/${b.id}/aprobar`, { method: "POST" }); await load(); } catch (e) { onError(e.message); }
|
||||
};
|
||||
const pendientes = (becarios || []).filter((b) => b.estado === "pendiente");
|
||||
const nuevoBtn = (size) => <Btn size={size} onClick={() => setForm({})}>{iconBtn("plus", { size: 16, color: "#fff", sw: 2.2 })}Nuevo becario</Btn>;
|
||||
return (
|
||||
<div>
|
||||
<ColaAprobacion pendientes={pendientes} onAprobar={aprobar} />
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "14px" }}>
|
||||
<h2 style={{ margin: 0, fontSize: "18px", color: COLORS.ink }}>Becarios</h2>
|
||||
{!form && <Btn onClick={() => setForm({})}>+ Nuevo becario</Btn>}
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "16px" }}>
|
||||
<h2 style={{ margin: 0, fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Becarios</h2>
|
||||
{nuevoBtn()}
|
||||
</div>
|
||||
{form && <BecarioForm inicial={form.id ? form : null}
|
||||
onSaved={() => { setForm(null); load(); }} onCancel={() => setForm(null)} onError={onError} />}
|
||||
{becarios === null ? <p style={{ color: COLORS.inkSoft }}>Cargando…</p> :
|
||||
becarios.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>Aún no hay becarios. Crea el primero.</p></Card> :
|
||||
<Card style={{ padding: 0, overflow: "hidden" }}>
|
||||
<div style={{ overflowX: "auto" }}>
|
||||
<table style={{ width: "100%", borderCollapse: "collapse", fontFamily: FONT, fontSize: "14px" }}>
|
||||
<thead>
|
||||
<tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
|
||||
{["Becario", "Institución", "Avance", "Estado", ""].map((h, i) =>
|
||||
<th key={i} style={{ padding: "11px 14px", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{becarios.map((b) => {
|
||||
const h = b.horas || { total_horas: 0, meta_horas: b.meta_horas, porcentaje: 0 };
|
||||
return (
|
||||
<tr key={b.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
|
||||
<td style={{ padding: "11px 14px" }}>
|
||||
<div style={{ fontWeight: 600, color: COLORS.ink, cursor: "pointer" }} onClick={() => onOpen(b.id)}>{b.nombre}</div>
|
||||
<div style={{ fontSize: "12px", color: COLORS.inkSoft }}>{[b.telefono, b.matricula].filter(Boolean).join(" · ") || "—"}</div>
|
||||
</td>
|
||||
<td style={{ padding: "11px 14px", color: COLORS.inkSoft }}>{b.institucion || "—"}</td>
|
||||
<td style={{ padding: "11px 14px", minWidth: "160px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "4px" }}>
|
||||
<span style={{ color: COLORS.ink }}>{fmtHoras(h.total_horas)} / {fmtHoras(h.meta_horas)}</span>
|
||||
<span style={{ color: COLORS.inkSoft }}>{h.porcentaje}%</span>
|
||||
</div>
|
||||
<div style={{ height: "6px", background: COLORS.chip, borderRadius: "999px", overflow: "hidden" }}>
|
||||
<div style={{ height: "100%", width: `${Math.min(100, h.porcentaje)}%`,
|
||||
background: h.porcentaje >= 100 ? COLORS.success : COLORS.primary }} />
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: "11px 14px" }}><Badge tone={estadoBecarioTone(b.estado)}>{b.estado}</Badge></td>
|
||||
<td style={{ padding: "11px 14px", whiteSpace: "nowrap" }}>
|
||||
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
||||
{b.estado === "pendiente" && <Btn size="sm" variant="success" onClick={() => aprobar(b)}>Aprobar</Btn>}
|
||||
<Btn size="sm" variant="ghost" onClick={() => onOpen(b.id)}>Ver</Btn>
|
||||
<Btn size="sm" variant="subtle" onClick={() => setForm(b)}>Editar</Btn>
|
||||
{b.estado !== "baja" && <Btn size="sm" variant="ghost" onClick={() => baja(b)}>Baja</Btn>}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>}
|
||||
{becarios === null ? <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p> :
|
||||
becarios.length === 0 ? <EmptyState icon="users" tone="blue" title="Aún no hay becarios" sub="Crea el primero o espera a que se registren desde su celular." action={nuevoBtn()} /> :
|
||||
<Table head={["Becario", "Institución", "Avance", "Estado", ""]} minWidth={720}>
|
||||
{becarios.map((b) => {
|
||||
const h = b.horas || { total_horas: 0, meta_horas: b.meta_horas, porcentaje: 0 };
|
||||
return (
|
||||
<Tr key={b.id}>
|
||||
<Td>
|
||||
<div style={{ fontWeight: 600, color: palette.brand, cursor: "pointer" }} onClick={() => onOpen(b.id)}>{b.nombre}</div>
|
||||
<div style={{ fontSize: "12px", color: palette.inkSoft, marginTop: "2px" }}>{[b.telefono, b.matricula].filter(Boolean).join(" · ") || "—"}</div>
|
||||
</Td>
|
||||
<Td soft>{b.institucion || "—"}</Td>
|
||||
<Td style={{ minWidth: "180px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "5px" }}>
|
||||
<span style={{ color: palette.ink }}>{fmtHoras(h.total_horas)} / {fmtHoras(h.meta_horas)}</span>
|
||||
<span style={{ color: palette.inkSoft }}>{h.porcentaje}%</span>
|
||||
</div>
|
||||
<ProgressBar value={h.porcentaje} />
|
||||
</Td>
|
||||
<Td><Badge tone={estadoBecarioTone(b.estado)}>{b.estado}</Badge></Td>
|
||||
<Td nowrap>
|
||||
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
||||
{b.estado === "pendiente" && <Btn size="sm" variant="success" onClick={() => aprobar(b)}>Aprobar</Btn>}
|
||||
<Btn size="sm" variant="ghost" onClick={() => onOpen(b.id)}>Ver</Btn>
|
||||
<Btn size="sm" variant="subtle" onClick={() => setForm(b)}>Editar</Btn>
|
||||
{b.estado !== "baja" && <Btn size="sm" variant="link" onClick={() => setConfirmBaja(b)}>Baja</Btn>}
|
||||
</div>
|
||||
</Td>
|
||||
</Tr>
|
||||
);
|
||||
})}
|
||||
</Table>}
|
||||
{form && <BecarioForm inicial={form.id ? form : null} onSaved={() => { setForm(null); load(); }} onCancel={() => setForm(null)} onError={onError} />}
|
||||
{confirmBaja && <ConfirmModal title="Dar de baja" variant="danger" confirmLabel="Dar de baja"
|
||||
message={`¿Dar de baja a ${confirmBaja.nombre}? Conserva su historial, no se elimina.`}
|
||||
onConfirm={() => doBaja(confirmBaja)} onCancel={() => setConfirmBaja(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -316,30 +260,47 @@ function JornadaEditor({ jornada, onSaved, onCancel, onError }) {
|
||||
} catch (e) { onError(e.message); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", display: "flex",
|
||||
alignItems: "center", justifyContent: "center", padding: "20px", zIndex: 10 }}>
|
||||
<Card style={{ width: "100%", maxWidth: "380px" }}>
|
||||
<h3 style={{ margin: "0 0 6px", fontSize: "16px", color: COLORS.ink }}>Editar tiempos de jornada</h3>
|
||||
<p style={{ margin: "0 0 14px", fontSize: "12px", color: COLORS.inkSoft }}>
|
||||
El valor original se respalda en la bitácora.</p>
|
||||
<Field label="Entrada"><Input type="datetime-local" value={entrada} onChange={(e) => setEntrada(e.target.value)} /></Field>
|
||||
<Field label="Salida"><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
||||
<div style={{ display: "flex", gap: "8px", marginTop: "6px" }}>
|
||||
<Btn onClick={save} disabled={busy}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
||||
<Btn variant="subtle" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
<Modal title="Editar tiempos de jornada" sub="El valor original se respalda en la bitácora." onClose={onCancel}>
|
||||
<Field label="Entrada"><Input type="datetime-local" value={entrada} onChange={(e) => setEntrada(e.target.value)} /></Field>
|
||||
<Field label="Salida"><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
||||
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
||||
<Btn onClick={save} loading={busy} disabled={busy}>{busy ? "Guardando…" : "Guardar"}</Btn>
|
||||
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════ Vista por becario ═══════════════════
|
||||
// ── Cerrar jornada en revisión sin salida (antes, un diálogo nativo) ──
|
||||
function CerrarJornadaModal({ jornada, onDone, onCancel, onError }) {
|
||||
const [salida, setSalida] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const go = async () => {
|
||||
const iso = localToIso(salida);
|
||||
if (!iso) { onError("Fecha inválida"); return; }
|
||||
setBusy(true);
|
||||
try { await apiFetch(`/jornadas/${jornada.id}/cerrar`, { method: "POST", body: JSON.stringify({ salida_ts: iso }) }); onDone(); }
|
||||
catch (e) { onError(e.message); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title="Cerrar jornada" sub="Registra la hora de salida real para cerrar esta jornada en revisión." onClose={onCancel}>
|
||||
<Field label="Hora de salida"><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
||||
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
||||
<Btn variant="success" onClick={go} loading={busy} disabled={busy || !salida}>Cerrar jornada</Btn>
|
||||
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════ Vista por becario (detalle) ═══════════════════
|
||||
function VistaBecario({ becarioId, onBack, onError }) {
|
||||
const [data, setData] = useState(null); // becario + horas
|
||||
const [data, setData] = useState(null);
|
||||
const [jornadas, setJornadas] = useState([]);
|
||||
const [ajustes, setAjustes] = useState([]);
|
||||
const [checadas, setChecadas] = useState([]);
|
||||
const [editJornada, setEditJornada] = useState(null);
|
||||
const [cerrarJornada, setCerrarJornada] = useState(null);
|
||||
const [ajuste, setAjuste] = useState({ minutos: "", motivo: "" });
|
||||
const [busyAjuste, setBusyAjuste] = useState(false);
|
||||
|
||||
@@ -357,18 +318,11 @@ function VistaBecario({ becarioId, onBack, onError }) {
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const cerrar = async (j) => {
|
||||
let salida_ts;
|
||||
if (!j.salida_ts) {
|
||||
const v = prompt("Fecha/hora de salida (YYYY-MM-DD HH:MM):");
|
||||
if (!v) return;
|
||||
const iso = localToIso(v.replace(" ", "T"));
|
||||
if (!iso) { onError("Fecha inválida"); return; }
|
||||
salida_ts = iso;
|
||||
}
|
||||
try {
|
||||
await apiFetch(`/jornadas/${j.id}/cerrar`, { method: "POST", body: JSON.stringify(salida_ts ? { salida_ts } : {}) });
|
||||
await load();
|
||||
} catch (e) { onError(e.message); }
|
||||
// Con salida ya registrada, cierra directo (POST {}); sin salida, pide la hora.
|
||||
if (j.salida_ts) {
|
||||
try { await apiFetch(`/jornadas/${j.id}/cerrar`, { method: "POST", body: JSON.stringify({}) }); await load(); }
|
||||
catch (e) { onError(e.message); }
|
||||
} else { setCerrarJornada(j); }
|
||||
};
|
||||
const crearAjuste = async (e) => {
|
||||
e.preventDefault(); setBusyAjuste(true);
|
||||
@@ -380,122 +334,103 @@ function VistaBecario({ becarioId, onBack, onError }) {
|
||||
} catch (err) { onError(err.message); } finally { setBusyAjuste(false); }
|
||||
};
|
||||
|
||||
if (!data) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
|
||||
if (!data) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
||||
const h = data.horas;
|
||||
const sec = { margin: "0 0 12px", fontFamily: fonts.title, fontWeight: 600, fontSize: "17px", color: palette.brand };
|
||||
return (
|
||||
<div>
|
||||
{editJornada && <JornadaEditor jornada={editJornada}
|
||||
onSaved={() => { setEditJornada(null); load(); }} onCancel={() => setEditJornada(null)} onError={onError} />}
|
||||
<Btn variant="subtle" size="sm" onClick={onBack}>← Volver a becarios</Btn>
|
||||
<div style={{ margin: "14px 0 18px", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "12px", flexWrap: "wrap" }}>
|
||||
<div>
|
||||
<h2 style={{ margin: "0 0 4px", fontSize: "20px", color: COLORS.ink }}>{data.nombre}</h2>
|
||||
<div style={{ fontSize: "13px", color: COLORS.inkSoft }}>
|
||||
{[data.telefono, data.matricula, data.institucion].filter(Boolean).join(" · ") || "sin datos"}
|
||||
{" "}<Badge tone={estadoBecarioTone(data.estado)}>{data.estado}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<Btn variant="subtle" size="sm" onClick={onBack}>{iconBtn("chevronLeft", { size: 15, color: palette.label })}Volver a becarios</Btn>
|
||||
<div style={{ margin: "18px 0 6px", display: "flex", alignItems: "center", gap: "12px", flexWrap: "wrap" }}>
|
||||
<h2 style={{ margin: 0, fontFamily: fonts.title, fontWeight: 600, fontSize: "24px", color: palette.brand, letterSpacing: "-.01em" }}>{data.nombre}</h2>
|
||||
<Badge tone={estadoBecarioTone(data.estado)}>{data.estado}</Badge>
|
||||
</div>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, marginBottom: "20px" }}>
|
||||
{[data.telefono, data.matricula, data.institucion].filter(Boolean).join(" · ") || "sin datos"}
|
||||
</div>
|
||||
|
||||
<Card style={{ marginBottom: "18px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: "8px" }}>
|
||||
<span style={{ fontSize: "15px", fontWeight: 600, color: COLORS.ink }}>Avance</span>
|
||||
<span style={{ fontSize: "13px", color: COLORS.inkSoft }}>calculado por el backend</span>
|
||||
<Card style={{ marginBottom: "20px", padding: "22px 24px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: "10px" }}>
|
||||
<span style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink }}>Avance</span>
|
||||
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.placeholder }}>calculado por el backend</span>
|
||||
</div>
|
||||
<div style={{ fontSize: "26px", fontWeight: 700, color: COLORS.ink }}>
|
||||
{fmtHoras(h.total_horas)} <span style={{ fontSize: "15px", color: COLORS.inkSoft, fontWeight: 500 }}>de {fmtHoras(h.meta_horas)} ({h.porcentaje}%)</span>
|
||||
<div style={{ fontFamily: fonts.title, fontWeight: 700, fontSize: "30px", color: palette.brand, letterSpacing: "-.01em" }}>
|
||||
{fmtHoras(h.total_horas)} <span style={{ fontFamily: fonts.body, fontSize: "15px", color: palette.inkSoft, fontWeight: 500 }}>de {fmtHoras(h.meta_horas)} ({h.porcentaje}%)</span>
|
||||
</div>
|
||||
<div style={{ height: "8px", background: COLORS.chip, borderRadius: "999px", overflow: "hidden", margin: "10px 0" }}>
|
||||
<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 }}>
|
||||
<div style={{ margin: "14px 0" }}><ProgressBar value={h.porcentaje} height={9} /></div>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft }}>
|
||||
Jornadas cerradas: {(h.minutos_jornadas / 60).toFixed(1)} h · Ajustes: {(h.minutos_ajustes / 60).toFixed(1)} h
|
||||
<span style={{ color: COLORS.warn }}> · las jornadas en revisión no suman</span>
|
||||
<span style={{ color: palette.amber }}> · las jornadas en revisión no suman</span>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<h3 style={{ margin: "0 0 10px", fontSize: "16px", color: COLORS.ink }}>Jornadas</h3>
|
||||
{jornadas.length === 0 ? <Card style={{ marginBottom: "18px" }}><p style={{ margin: 0, color: COLORS.inkSoft }}>Sin jornadas.</p></Card> :
|
||||
<Card style={{ padding: 0, marginBottom: "18px", overflow: "hidden" }}>
|
||||
<div style={{ overflowX: "auto" }}>
|
||||
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px", fontFamily: FONT }}>
|
||||
<thead><tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
|
||||
{["Entrada", "Salida", "Duración", "Estado", ""].map((c, i) => <th key={i} style={{ padding: "10px 12px", fontWeight: 600, whiteSpace: "nowrap" }}>{c}</th>)}
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{jornadas.map((j) => (
|
||||
<tr key={j.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
|
||||
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{fmtDT(j.entrada_ts)}</td>
|
||||
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{fmtDT(j.salida_ts)}</td>
|
||||
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>{j.duracion_minutos != null ? `${(j.duracion_minutos / 60).toFixed(1)} h` : "—"}</td>
|
||||
<td style={{ padding: "10px 12px" }}>
|
||||
<Badge tone={estadoJornadaTone(j.estado)}>{j.estado}</Badge>
|
||||
{j.editada && <span style={{ marginLeft: "6px", fontSize: "11px", color: COLORS.inkSoft }}>editada</span>}
|
||||
</td>
|
||||
<td style={{ padding: "10px 12px", whiteSpace: "nowrap" }}>
|
||||
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
||||
<Btn size="sm" variant="subtle" onClick={() => setEditJornada(j)}>Editar</Btn>
|
||||
{j.estado === "revision" && <Btn size="sm" variant="success" onClick={() => cerrar(j)}>Cerrar</Btn>}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>}
|
||||
<h3 style={sec}>Jornadas</h3>
|
||||
{jornadas.length === 0 ? <div style={{ marginBottom: "22px" }}><EmptyState icon="calendar" tone="neutral" title="Sin jornadas todavía" sub="Este becario aún no registra entradas ni salidas." /></div> :
|
||||
<div style={{ marginBottom: "22px" }}>
|
||||
<Table head={["Entrada", "Salida", "Duración", "Estado", ""]} minWidth={640}>
|
||||
{jornadas.map((j) => (
|
||||
<Tr key={j.id}>
|
||||
<Td nowrap>{fmtDT(j.entrada_ts)}</Td>
|
||||
<Td nowrap soft={!j.salida_ts}>{fmtDT(j.salida_ts)}</Td>
|
||||
<Td nowrap soft={j.duracion_minutos == null}>{j.duracion_minutos != null ? `${(j.duracion_minutos / 60).toFixed(1)} h` : "—"}</Td>
|
||||
<Td>
|
||||
<Badge tone={estadoJornadaTone(j.estado)}>{j.estado}</Badge>
|
||||
{j.editada && <span style={{ marginLeft: "6px", fontFamily: fonts.body, fontSize: "11px", color: palette.inkSoft }}>editada</span>}
|
||||
</Td>
|
||||
<Td nowrap>
|
||||
<div style={{ display: "flex", gap: "6px", justifyContent: "flex-end" }}>
|
||||
<Btn size="sm" variant="subtle" onClick={() => setEditJornada(j)}>Editar</Btn>
|
||||
{j.estado === "revision" && <Btn size="sm" variant="success" onClick={() => cerrar(j)}>Cerrar</Btn>}
|
||||
</div>
|
||||
</Td>
|
||||
</Tr>
|
||||
))}
|
||||
</Table>
|
||||
</div>}
|
||||
|
||||
<h3 style={{ margin: "0 0 10px", fontSize: "16px", color: COLORS.ink }}>Ajustes</h3>
|
||||
<Card>
|
||||
<form onSubmit={crearAjuste} style={{ display: "flex", gap: "10px", alignItems: "flex-end", flexWrap: "wrap", marginBottom: ajustes.length ? "16px" : 0 }}>
|
||||
<div style={{ width: "120px" }}>
|
||||
<h3 style={sec}>Ajustes</h3>
|
||||
<Card style={{ marginBottom: "22px", padding: "20px 22px" }}>
|
||||
<form onSubmit={crearAjuste} style={{ display: "flex", gap: "12px", alignItems: "flex-end", flexWrap: "wrap", marginBottom: ajustes.length ? "4px" : 0 }}>
|
||||
<div style={{ width: "130px" }}>
|
||||
<Field label="Minutos (+/−)"><Input type="number" value={ajuste.minutos} onChange={(e) => setAjuste({ ...ajuste, minutos: e.target.value })} placeholder="ej. 60 o -30" required /></Field>
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: "200px" }}>
|
||||
<div style={{ flex: 1, minWidth: "220px" }}>
|
||||
<Field label="Motivo (obligatorio)"><Input value={ajuste.motivo} onChange={(e) => setAjuste({ ...ajuste, motivo: e.target.value })} required /></Field>
|
||||
</div>
|
||||
<div style={{ marginBottom: "12px" }}>
|
||||
<Btn type="submit" disabled={busyAjuste || !ajuste.minutos || Number(ajuste.minutos) === 0 || !ajuste.motivo.trim()}>Agregar</Btn>
|
||||
<div style={{ marginBottom: "14px" }}>
|
||||
<Btn type="submit" loading={busyAjuste} disabled={busyAjuste || !ajuste.minutos || Number(ajuste.minutos) === 0 || !ajuste.motivo.trim()}>Agregar</Btn>
|
||||
</div>
|
||||
</form>
|
||||
{ajustes.map((a) => (
|
||||
<div key={a.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||
borderTop: `1px solid ${COLORS.border}`, padding: "10px 0", gap: "10px" }}>
|
||||
<div style={{ fontSize: "14px", color: COLORS.ink }}>
|
||||
<strong style={{ color: a.minutos >= 0 ? COLORS.success : COLORS.danger }}>{a.minutos >= 0 ? "+" : ""}{a.minutos} min</strong>
|
||||
<span style={{ color: COLORS.inkSoft }}> · {a.motivo}</span>
|
||||
<div key={a.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: `1px solid ${palette.cardBorder}`, padding: "12px 0", gap: "10px" }}>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "14px", color: palette.ink }}>
|
||||
<strong style={{ color: a.minutos >= 0 ? palette.green : palette.danger, fontWeight: 700 }}>{a.minutos >= 0 ? "+" : ""}{a.minutos} min</strong>
|
||||
<span style={{ color: palette.inkSoft }}> · {a.motivo}</span>
|
||||
</div>
|
||||
<span style={{ fontSize: "12px", color: COLORS.inkSoft, whiteSpace: "nowrap" }}>{fmtDT(a.created_at)}</span>
|
||||
<span style={{ fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, whiteSpace: "nowrap" }}>{fmtDT(a.created_at)}</span>
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
|
||||
<h3 style={{ margin: "18px 0 10px", fontSize: "16px", color: COLORS.ink }}>Checadas (con IP / dispositivo)</h3>
|
||||
<p style={{ margin: "0 0 10px", fontSize: "12px", color: COLORS.inkSoft }}>
|
||||
IP y user-agent son señal secundaria de anomalías, no prueba de ubicación (§3).
|
||||
<h3 style={{ ...sec, marginBottom: "6px" }}>Checadas <span style={{ fontFamily: fonts.body, fontWeight: 400, fontSize: "13px", color: palette.inkSoft }}>(con IP / dispositivo)</span></h3>
|
||||
<p style={{ margin: "0 0 12px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft }}>
|
||||
IP y user-agent son señal secundaria de anomalías, no prueba de ubicación.
|
||||
</p>
|
||||
{checadas.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>Sin checadas.</p></Card> :
|
||||
<Card style={{ padding: 0, overflow: "hidden" }}>
|
||||
<div style={{ overflowX: "auto" }}>
|
||||
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px", fontFamily: FONT }}>
|
||||
<thead><tr style={{ background: COLORS.chip, textAlign: "left", color: COLORS.inkSoft }}>
|
||||
{["Momento", "Tipo", "Origen", "Concepto", "IP", "User-agent"].map((c, i) => <th key={i} style={{ padding: "10px 12px", fontWeight: 600, whiteSpace: "nowrap" }}>{c}</th>)}
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{checadas.map((c) => (
|
||||
<tr key={c.id} style={{ borderTop: `1px solid ${COLORS.border}` }}>
|
||||
<td style={{ padding: "9px 12px", whiteSpace: "nowrap" }}>{fmtDT(c.ts)}</td>
|
||||
<td style={{ padding: "9px 12px" }}><Badge tone={c.tipo === "entrada" ? "success" : "primary"}>{c.tipo}</Badge></td>
|
||||
<td style={{ padding: "9px 12px", color: COLORS.inkSoft }}>{c.origen}</td>
|
||||
<td style={{ padding: "9px 12px", color: COLORS.inkSoft }}>{c.concepto || "—"}</td>
|
||||
<td style={{ padding: "9px 12px", color: COLORS.inkSoft, fontFamily: "monospace" }}>{c.ip || "—"}</td>
|
||||
<td style={{ padding: "9px 12px", color: COLORS.inkSoft, maxWidth: "220px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={c.user_agent || ""}>{c.user_agent || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>}
|
||||
{checadas.length === 0 ? <EmptyState icon="clock" tone="neutral" title="Sin checadas" sub="No hay registros de chip NFC para este becario." /> :
|
||||
<Table head={["Momento", "Tipo", "Origen", "Concepto", "IP", "User-agent"]} minWidth={780}>
|
||||
{checadas.map((c) => (
|
||||
<Tr key={c.id}>
|
||||
<Td nowrap>{fmtDT(c.ts)}</Td>
|
||||
<Td><Badge tone={c.tipo === "entrada" ? "success" : "primary"}>{c.tipo}</Badge></Td>
|
||||
<Td soft>{c.origen}</Td>
|
||||
<Td soft>{c.concepto || "—"}</Td>
|
||||
<Td soft mono>{c.ip || "—"}</Td>
|
||||
<Td soft ellipsis title={c.user_agent || ""}>{c.user_agent || "—"}</Td>
|
||||
</Tr>
|
||||
))}
|
||||
</Table>}
|
||||
|
||||
{editJornada && <JornadaEditor jornada={editJornada} onSaved={() => { setEditJornada(null); load(); }} onCancel={() => setEditJornada(null)} onError={onError} />}
|
||||
{cerrarJornada && <CerrarJornadaModal jornada={cerrarJornada} onDone={() => { setCerrarJornada(null); load(); }} onCancel={() => setCerrarJornada(null)} onError={onError} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -530,25 +465,24 @@ function VistaConfig({ onError }) {
|
||||
setOkMsg("Configuración guardada."); await load();
|
||||
} catch (err) { onError(err.message); } finally { setBusy(false); }
|
||||
};
|
||||
if (!cfg) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
|
||||
if (!cfg) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
||||
return (
|
||||
<div>
|
||||
<h2 style={{ margin: "0 0 14px", fontSize: "18px", color: COLORS.ink }}>Configuración</h2>
|
||||
<Card style={{ maxWidth: "520px" }}>
|
||||
<h2 style={{ margin: "0 0 16px", fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Configuración</h2>
|
||||
<Card style={{ maxWidth: "560px" }}>
|
||||
<form onSubmit={guardar}>
|
||||
<div style={{ marginBottom: "6px", fontSize: "14px", fontWeight: 600, color: COLORS.ink }}>Ventana horaria de checado</div>
|
||||
<p style={{ margin: "0 0 10px", fontSize: "12px", color: COLORS.inkSoft }}>Fuera de este rango no se emiten tokens y las jornadas abiertas se auto-cierran a revisión.</p>
|
||||
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "14px", color: palette.ink, marginBottom: "5px" }}>Ventana horaria de checado</div>
|
||||
<p style={{ margin: "0 0 14px", fontFamily: fonts.body, fontSize: "12px", color: palette.inkSoft, lineHeight: 1.5 }}>Fuera de este rango no se emiten tokens y las jornadas abiertas se auto-cierran a revisión.</p>
|
||||
<div style={{ display: "flex", gap: "14px" }}>
|
||||
<Field label="Inicio"><Input type="time" value={f.inicio} onChange={(e) => setF({ ...f, inicio: e.target.value })} /></Field>
|
||||
<Field label="Fin"><Input type="time" value={f.fin} onChange={(e) => setF({ ...f, fin: e.target.value })} /></Field>
|
||||
<div style={{ flex: 1 }}><Field label="Inicio"><Input type="time" value={f.inicio} onChange={(e) => setF({ ...f, inicio: e.target.value })} /></Field></div>
|
||||
<div style={{ flex: 1 }}><Field label="Fin"><Input type="time" value={f.fin} onChange={(e) => setF({ ...f, fin: e.target.value })} /></Field></div>
|
||||
</div>
|
||||
<div style={{ margin: "6px 0 18px" }}>
|
||||
<Toggle checked={f.tarea_activa} onChange={(v) => setF({ ...f, tarea_activa: v })} label="Pedir el concepto de la tarea al checar (switch global)" />
|
||||
</div>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", margin: "8px 0 16px", cursor: "pointer" }}>
|
||||
<input type="checkbox" checked={f.tarea_activa} onChange={(e) => setF({ ...f, tarea_activa: e.target.checked })} style={{ width: "18px", height: "18px" }} />
|
||||
<span style={{ fontSize: "14px", color: COLORS.ink }}>Pedir el concepto de la tarea al checar (switch global)</span>
|
||||
</label>
|
||||
<Field label="Meta de horas por defecto"><Input type="number" min="1" value={f.meta} onChange={(e) => setF({ ...f, meta: e.target.value })} style={{ maxWidth: "160px" }} /></Field>
|
||||
{okMsg && <p style={{ color: COLORS.success, fontSize: "13px" }}>✓ {okMsg}</p>}
|
||||
<div style={{ marginTop: "6px" }}><Btn type="submit" disabled={busy}>{busy ? "Guardando…" : "Guardar configuración"}</Btn></div>
|
||||
{okMsg && <Aviso variant="success" icon="check">{okMsg}</Aviso>}
|
||||
<div style={{ marginTop: "6px" }}><Btn type="submit" loading={busy} disabled={busy}>{busy ? "Guardando…" : "Guardar configuración"}</Btn></div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -556,82 +490,90 @@ function VistaConfig({ onError }) {
|
||||
}
|
||||
|
||||
// ═══════════════════ Cola de solicitudes ═══════════════════
|
||||
// Autorizar/rechazar usan modales propios (antes, diálogos nativos del
|
||||
// navegador); la llamada al backend por detrás no cambia.
|
||||
function AutorizarModal({ solicitud, onDone, onCancel, onError }) {
|
||||
const olvido = solicitud.tipo === "olvido_entrada";
|
||||
const [entrada, setEntrada] = useState(olvido ? isoToLocal(solicitud.propuesta?.entrada_ts) : "");
|
||||
const [salida, setSalida] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const go = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const body = {};
|
||||
if (olvido) {
|
||||
const eIso = localToIso(entrada);
|
||||
if (!eIso) { onError("Fecha de entrada inválida"); setBusy(false); return; }
|
||||
body.entrada_ts = eIso;
|
||||
const sIso = localToIso(salida);
|
||||
if (sIso) body.salida_ts = sIso;
|
||||
} else {
|
||||
const sIso = localToIso(salida);
|
||||
if (!sIso) { onError("Fecha de salida inválida"); setBusy(false); return; }
|
||||
body.salida_ts = sIso;
|
||||
}
|
||||
await apiFetch(`/solicitudes/${solicitud.id}/autorizar`, { method: "POST", body: JSON.stringify(body) });
|
||||
onDone();
|
||||
} catch (e) { onError(e.message); } finally { setBusy(false); }
|
||||
};
|
||||
return (
|
||||
<Modal title={olvido ? "Autorizar olvido de entrada" : "Autorizar auto-cierre"}
|
||||
sub={olvido ? "Confirma la hora de entrada; la salida es opcional (déjala vacía si sigue en curso)." : "Registra la hora de salida real para cerrar la jornada."}
|
||||
onClose={onCancel}>
|
||||
{olvido && <Field label="Hora de entrada"><Input type="datetime-local" value={entrada} onChange={(e) => setEntrada(e.target.value)} /></Field>}
|
||||
<Field label={olvido ? "Hora de salida (opcional)" : "Hora de salida"}><Input type="datetime-local" value={salida} onChange={(e) => setSalida(e.target.value)} /></Field>
|
||||
<div style={{ display: "flex", gap: "9px", marginTop: "4px" }}>
|
||||
<Btn variant="success" onClick={go} loading={busy} disabled={busy || (olvido ? !entrada : !salida)}>Autorizar</Btn>
|
||||
<Btn variant="outline" onClick={onCancel}>Cancelar</Btn>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function VistaSolicitudes({ onError }) {
|
||||
const [sols, setSols] = useState(null);
|
||||
const [busy, setBusy] = useState(null);
|
||||
const [autorizar, setAutorizar] = useState(null);
|
||||
const [confirmRechazo, setConfirmRechazo] = useState(null);
|
||||
const load = useCallback(async () => {
|
||||
try { setSols(await apiFetch("/solicitudes?estado=pendiente")); } catch (e) { onError(e.message); }
|
||||
}, [onError]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// prompts en hora local (America/Mexico_City del navegador) ↔ ISO(UTC).
|
||||
const toPrompt = (iso) => isoToLocal(iso).replace("T", " "); // "YYYY-MM-DD HH:MM"
|
||||
const fromPrompt = (v) => localToIso(v.trim().replace(" ", "T"));
|
||||
const autorizar = async (s) => {
|
||||
setBusy(s.id);
|
||||
try {
|
||||
const body = {};
|
||||
if (s.tipo === "olvido_entrada" || s.tipo === "jornada_completa") {
|
||||
const ent = prompt("Hora de entrada a autorizar (YYYY-MM-DD HH:MM):", toPrompt(s.propuesta?.entrada_ts));
|
||||
if (!ent) { setBusy(null); return; }
|
||||
body.entrada_ts = fromPrompt(ent);
|
||||
if (s.tipo === "jornada_completa") {
|
||||
// Día completo: la salida ya viene propuesta y es obligatoria para que sume.
|
||||
const sal = prompt("Hora de salida a autorizar (YYYY-MM-DD HH:MM):", toPrompt(s.propuesta?.salida_ts));
|
||||
if (!sal) { setBusy(null); return; }
|
||||
body.salida_ts = fromPrompt(sal);
|
||||
} else {
|
||||
const sal = prompt("Hora de salida (opcional, para que sume; deja vacío si sigue en curso):", "");
|
||||
if (sal) body.salida_ts = fromPrompt(sal);
|
||||
}
|
||||
} else {
|
||||
const sal = prompt("Hora de salida real para cerrar la jornada (YYYY-MM-DD HH:MM):", "");
|
||||
if (!sal) { setBusy(null); return; }
|
||||
body.salida_ts = fromPrompt(sal);
|
||||
}
|
||||
await apiFetch(`/solicitudes/${s.id}/autorizar`, { method: "POST", body: JSON.stringify(body) });
|
||||
await load();
|
||||
} catch (e) { onError(e.message); } finally { setBusy(null); }
|
||||
const doRechazo = async (s) => {
|
||||
try { await apiFetch(`/solicitudes/${s.id}/rechazar`, { method: "POST" }); setConfirmRechazo(null); await load(); }
|
||||
catch (e) { onError(e.message); setConfirmRechazo(null); }
|
||||
};
|
||||
const rechazar = async (s) => {
|
||||
if (!confirm("¿Rechazar esta solicitud?")) return;
|
||||
setBusy(s.id);
|
||||
try { await apiFetch(`/solicitudes/${s.id}/rechazar`, { method: "POST" }); await load(); }
|
||||
catch (e) { onError(e.message); } finally { setBusy(null); }
|
||||
};
|
||||
|
||||
if (sols === null) return <p style={{ color: COLORS.inkSoft }}>Cargando…</p>;
|
||||
if (sols === null) return <p style={{ color: palette.inkSoft, fontFamily: fonts.body }}>Cargando…</p>;
|
||||
return (
|
||||
<div>
|
||||
<h2 style={{ margin: "0 0 14px", fontSize: "18px", color: COLORS.ink }}>Solicitudes pendientes</h2>
|
||||
{sols.length === 0 ? <Card><p style={{ margin: 0, color: COLORS.inkSoft }}>No hay solicitudes pendientes.</p></Card> :
|
||||
<h2 style={{ margin: "0 0 16px", fontFamily: fonts.title, fontWeight: 600, fontSize: "22px", color: palette.brand, letterSpacing: "-.01em" }}>Solicitudes pendientes</h2>
|
||||
{sols.length === 0 ? <EmptyState icon="listCheck" tone="green" title="No hay solicitudes pendientes" sub="Cuando un becario pida un olvido de entrada o auto-cierre, aparecerá aquí." /> :
|
||||
sols.map((s) => (
|
||||
<Card key={s.id} style={{ marginBottom: "12px" }}>
|
||||
<Card key={s.id} style={{ marginBottom: "14px", borderRadius: "16px", padding: "18px 20px" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "12px", flexWrap: "wrap" }}>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, color: COLORS.ink }}>
|
||||
{s.tipo === "olvido_entrada" ? "Olvido de entrada"
|
||||
: s.tipo === "jornada_completa" ? "Día completo"
|
||||
: "Autorizar auto-cierre"}
|
||||
<div style={{ fontFamily: fonts.body, fontWeight: 600, fontSize: "15px", color: palette.ink }}>
|
||||
{s.tipo === "olvido_entrada" ? "Olvido de entrada" : "Autorizar auto-cierre"}
|
||||
</div>
|
||||
<div style={{ fontSize: "13px", color: COLORS.inkSoft, marginTop: "2px" }}>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.inkSoft, marginTop: "3px" }}>
|
||||
{s.becario_nombre} · {s.becario_telefono || "sin tel."}
|
||||
</div>
|
||||
<div style={{ fontSize: "13px", color: COLORS.ink, marginTop: "6px" }}>
|
||||
<div style={{ fontFamily: fonts.body, fontSize: "13px", color: palette.ink, marginTop: "8px" }}>
|
||||
{s.tipo === "olvido_entrada"
|
||||
? <>Entrada propuesta: <strong>{fmtDT(s.propuesta?.entrada_ts)}</strong></>
|
||||
: s.tipo === "jornada_completa"
|
||||
? <>Propuesto: <strong>{fmtDT(s.propuesta?.entrada_ts)}</strong> → <strong>{fmtDT(s.propuesta?.salida_ts)}</strong></>
|
||||
: <>Jornada en revisión desde <strong>{fmtDT(s.propuesta?.entrada_ts)}</strong></>}
|
||||
? <>Entrada propuesta: <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.entrada_ts)}</strong></>
|
||||
: <>Jornada en revisión desde <strong style={{ color: palette.brand }}>{fmtDT(s.propuesta?.entrada_ts)}</strong></>}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "8px" }}>
|
||||
<Btn size="sm" variant="success" disabled={busy === s.id} onClick={() => autorizar(s)}>Autorizar</Btn>
|
||||
<Btn size="sm" variant="ghost" disabled={busy === s.id} onClick={() => rechazar(s)}>Rechazar</Btn>
|
||||
<Btn size="sm" variant="success" onClick={() => setAutorizar(s)}>Autorizar</Btn>
|
||||
<Btn size="sm" variant="outline" onClick={() => setConfirmRechazo(s)}>Rechazar</Btn>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
{autorizar && <AutorizarModal solicitud={autorizar} onDone={() => { setAutorizar(null); load(); }} onCancel={() => setAutorizar(null)} onError={onError} />}
|
||||
{confirmRechazo && <ConfirmModal title="Rechazar solicitud" variant="danger" confirmLabel="Rechazar"
|
||||
message="¿Rechazar esta solicitud? El becario deberá volver a enviarla si fue un error."
|
||||
onConfirm={() => doRechazo(confirmRechazo)} onCancel={() => setConfirmRechazo(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -647,29 +589,10 @@ function Panel({ session, onLogout }) {
|
||||
{ key: "config", label: "Configuración" },
|
||||
];
|
||||
const activeTab = view.name === "detalle" ? "lista" : view.name;
|
||||
const tabStyle = (active) => ({
|
||||
padding: "8px 14px", borderRadius: "8px", border: "none", cursor: "pointer", fontFamily: FONT,
|
||||
fontSize: "14px", fontWeight: 600, background: active ? COLORS.accentBg : "transparent",
|
||||
color: active ? COLORS.primaryDark : COLORS.inkSoft,
|
||||
});
|
||||
return (
|
||||
<div style={{ minHeight: "100vh", background: COLORS.bg, fontFamily: FONT }}>
|
||||
<header style={{ background: COLORS.surface, borderBottom: `1px solid ${COLORS.border}`, padding: "12px 20px",
|
||||
display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "10px" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "18px" }}>
|
||||
<div style={{ fontWeight: 700, color: COLORS.ink, fontSize: "16px" }}>Taboada · Supervisión</div>
|
||||
<nav style={{ display: "flex", gap: "4px" }}>
|
||||
{tabs.map((t) => (
|
||||
<button key={t.key} style={tabStyle(activeTab === t.key)} onClick={() => setView({ name: t.key })}>{t.label}</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
|
||||
<span style={{ fontSize: "13px", color: COLORS.inkSoft }}>{session.usuario}</span>
|
||||
<Btn size="sm" variant="ghost" onClick={logout}>Salir</Btn>
|
||||
</div>
|
||||
</header>
|
||||
<main style={{ maxWidth: "980px", margin: "0 auto", padding: "22px 20px 60px" }}>
|
||||
<div style={{ minHeight: "100vh", background: palette.bgGradient, fontFamily: fonts.body }}>
|
||||
<Nav tabs={tabs} active={activeTab} onTab={(k) => setView({ name: k })} user={session.usuario} onLogout={logout} />
|
||||
<main style={{ maxWidth: "1040px", margin: "0 auto", padding: "26px 24px 60px" }}>
|
||||
<ErrorBar error={error} onClose={() => setError(null)} />
|
||||
{view.name === "lista" && <VistaBecarios onOpen={(id) => setView({ name: "detalle", id })} onError={setError} />}
|
||||
{view.name === "detalle" && <VistaBecario becarioId={view.id} onBack={() => setView({ name: "lista" })} onError={setError} />}
|
||||
@@ -684,7 +607,7 @@ function App() {
|
||||
const [session, setSession] = useState(undefined); // undefined=cargando, null=sin sesión
|
||||
useEffect(() => { apiFetch("/auth/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>;
|
||||
return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", fontFamily: fonts.body, color: palette.inkSoft }}>Cargando…</div>;
|
||||
if (!session) return <Login onLogin={setSession} />;
|
||||
return <Panel session={session} onLogout={() => setSession(null)} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
/*
|
||||
* theme.js — base visual compartida de las tres pantallas (panel/becario/checada).
|
||||
*
|
||||
* Sin build step: se carga como <script src="theme.js"> DESPUÉS de React/ReactDOM
|
||||
* y ANTES del <script type="text/babel"> de cada página. Expone window.Theme con:
|
||||
* - COLORS paleta unificada (base común de los tres + primaryDark/accentBg del panel)
|
||||
* - FONT stack tipográfico del sistema
|
||||
* - SPACE escala de espaciado (para el rediseño)
|
||||
* - RADIUS escala de radios
|
||||
* - makeUI(flavor) → { Btn, Card, Input, Badge, Field, Estado }
|
||||
*
|
||||
* Los componentes viven UNA sola vez aquí; makeUI(flavor) los liga a las medidas
|
||||
* exactas de cada página ('panel' escritorio, 'becario'/'checada' móvil) para que
|
||||
* el resultado se vea idéntico al de hoy. El rediseño se hace tocando este archivo.
|
||||
*/
|
||||
window.Theme = (function () {
|
||||
var COLORS = {
|
||||
bg: "#EEF1F4", surface: "#FFFFFF", ink: "#1F2933", inkSoft: "#616E7C",
|
||||
border: "#DDE2E7", primary: "#2A6FB0", primaryDark: "#1E4E7E",
|
||||
success: "#2E7D5B", successBg: "#E7F3EC", warn: "#B7791F", warnBg: "#FBF2E1",
|
||||
danger: "#C0392B", dangerBg: "#FBEBE9", chip: "#F0F2F5", accentBg: "#EAF2FA",
|
||||
};
|
||||
|
||||
var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
|
||||
|
||||
var SPACE = { none: "0", xs: "4px", sm: "8px", md: "12px", lg: "16px", xl: "20px", "2xl": "24px", "3xl": "32px" };
|
||||
var RADIUS = { sm: "8px", md: "10px", lg: "12px", xl: "14px", "2xl": "16px", pill: "999px" };
|
||||
|
||||
// ── Rediseño móvil: paleta crema + fuentes de marca (flavors 'checada' y 'becario') ──
|
||||
// No afecta a panel: sus componentes siguen usando COLORS/FONT.
|
||||
var CREAM = {
|
||||
bg: "#F3EBDD",
|
||||
bgGradient: "radial-gradient(120% 80% at 50% -10%, #FBF5EA 0%, #F3EBDD 55%, #EFE5D3 100%)",
|
||||
surface: "#FFFFFF", cardBorder: "#F0E8DA",
|
||||
ink: "#2E2A24", inkSoft: "#8A8175", label: "#6E6559", placeholder: "#B4A99A", line: "#E4D9C6",
|
||||
brand: "#16406B", primary: "#2E77B8", primaryDark: "#25689F",
|
||||
green: "#2F8A63", greenDark: "#287854", amber: "#B7791F", danger: "#C0392B",
|
||||
greenTint: "#E4F1E9", blueTint: "#E7F0F8", amberTint: "#FBF0DC", dangerTint: "#FBEBE8",
|
||||
errBg: "#FBEBE8", errBorder: "#F3D3CC", errText: "#B4362A",
|
||||
warnBg: "#FBF0DC", warnBorder: "#EFD9A8", warnText: "#8A5A12",
|
||||
inputBorder: "#ECE3D4", inputBg: "#FBF8F2", track: "#EDE4D5", dashed: "#C7DBEC",
|
||||
// Portal del becario:
|
||||
neutralTint: "#EEE7D9", softTint: "#F1EADC", // píldora neutra / círculos y toggle
|
||||
okBorder: "#C4E3D2", okText: "#207A52", // nota de éxito verde
|
||||
metaBorder: "#CDE7D9", gold: "#F2B705", goldDark: "#E0A800", // "meta cumplida" + estrella
|
||||
};
|
||||
var FONT_TITLE = "'Bricolage Grotesque', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";
|
||||
var FONT_BODY = "'Figtree', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";
|
||||
|
||||
// Vocabulario de tonos de Badge, unión de los dos que usaban panel y becario.
|
||||
var TONES = {
|
||||
chip: { bg: COLORS.chip, color: COLORS.inkSoft },
|
||||
success: { bg: COLORS.successBg, color: COLORS.success },
|
||||
warn: { bg: COLORS.warnBg, color: COLORS.warn },
|
||||
danger: { bg: COLORS.dangerBg, color: COLORS.danger },
|
||||
primary: { bg: COLORS.accentBg, color: COLORS.primaryDark },
|
||||
pendiente: { bg: COLORS.warnBg, color: COLORS.warn },
|
||||
activo: { bg: COLORS.successBg, color: COLORS.success },
|
||||
baja: { bg: COLORS.chip, color: COLORS.inkSoft },
|
||||
};
|
||||
|
||||
// Medidas exactas por página (reproducen el look actual, píxel por píxel).
|
||||
var FLAVORS = {
|
||||
panel: {
|
||||
card: { radius: RADIUS.lg, pad: "20px", shadow: "0 1px 3px rgba(0,0,0,0.04)", mb: undefined },
|
||||
input: { pad: "9px 11px", radius: RADIUS.sm, font: "14px" },
|
||||
badge: { pad: "2px 9px", nowrap: true },
|
||||
btn: {
|
||||
block: false, weight: 600, radius: RADIUS.sm, disabledInk: true, transition: "opacity .15s",
|
||||
sizes: { sm: { pad: "6px 12px", font: "13px" }, md: { pad: "10px 18px", font: "14px" } },
|
||||
defaultSize: "md",
|
||||
},
|
||||
},
|
||||
becario: {
|
||||
card: { radius: RADIUS.xl, pad: "18px", shadow: undefined, mb: "14px" },
|
||||
input: { pad: "12px 14px", radius: RADIUS.md, font: "16px" },
|
||||
badge: { pad: "3px 10px", nowrap: false },
|
||||
btn: {
|
||||
block: true, weight: 700, radius: RADIUS.md, disabledInk: false, transition: undefined,
|
||||
sizes: { md: { pad: "13px", font: "15px" } }, defaultSize: "md",
|
||||
},
|
||||
},
|
||||
checada: {
|
||||
card: { radius: RADIUS["2xl"], pad: "24px", shadow: undefined, mb: undefined },
|
||||
input: { pad: "13px 14px", radius: RADIUS.md, font: "16px" },
|
||||
badge: { pad: "3px 10px", nowrap: false },
|
||||
btn: {
|
||||
block: true, weight: 700, radius: RADIUS.md, disabledInk: false, transition: undefined,
|
||||
sizes: { md: { pad: "14px", font: "16px" } }, defaultSize: "md",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function btnVariant(v) {
|
||||
switch (v) {
|
||||
case "success": return { bg: COLORS.success, color: "#fff", border: "none" };
|
||||
case "danger": return { bg: COLORS.danger, color: "#fff", border: "none" };
|
||||
case "ghost": return { bg: "transparent", color: COLORS.primary, border: "1px solid " + COLORS.border };
|
||||
case "subtle": return { bg: COLORS.chip, color: COLORS.ink, border: "none" };
|
||||
default: return { bg: COLORS.primary, color: "#fff", border: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
// ── Íconos de línea del rediseño (name -> función(opts) -> <svg>) ──
|
||||
// opts: { size, color, sw (stroke-width), style }. Sin dependencias externas.
|
||||
function makeIcons(React) {
|
||||
var h = React.createElement;
|
||||
function ic(paths, o) {
|
||||
o = o || {};
|
||||
var kids = paths.map(function (p, i) { return h(p[0], Object.assign({ key: i }, p[1])); });
|
||||
return h("svg", {
|
||||
width: o.size || 28, height: o.size || 28, viewBox: "0 0 24 24", fill: "none",
|
||||
stroke: o.color || "currentColor", strokeWidth: o.sw || 1.7,
|
||||
strokeLinecap: "round", strokeLinejoin: "round", style: o.style,
|
||||
}, kids);
|
||||
}
|
||||
return {
|
||||
nfc: function (o) { return ic([["rect",{x:6,y:2.5,width:9,height:19,rx:2.5}],["path",{d:"M18 8a5 5 0 0 1 0 8"}],["path",{d:"M20.6 5.4a8.5 8.5 0 0 1 0 13.2"}]], o); },
|
||||
sunrise: function (o) { return ic([["path",{d:"M12 2.6v2.6"}],["path",{d:"M4.7 8 6.3 9.6"}],["path",{d:"M19.3 8 17.7 9.6"}],["path",{d:"M2.4 15h3"}],["path",{d:"M18.6 15h3"}],["path",{d:"M8 15a4 4 0 0 1 8 0"}],["path",{d:"M1.6 19h20.8"}]], o); },
|
||||
moon: function (o) { return ic([["path",{d:"M20 14.6A8 8 0 1 1 9.4 4a6.5 6.5 0 0 0 10.6 10.6z"}]], o); },
|
||||
check: function (o) { return ic([["path",{d:"M21.6 11.1V12a9.6 9.6 0 1 1-5.7-8.8"}],["path",{d:"M8.6 11.5 12 15l9.6-9.6"}]], o); },
|
||||
hourglass: function (o) { return ic([["path",{d:"M6.5 3h11"}],["path",{d:"M6.5 21h11"}],["path",{d:"M7.5 3v3.1a5 5 0 0 0 2.8 4.5L12 12l1.7-1.4A5 5 0 0 0 16.5 6.1V3"}],["path",{d:"M7.5 21v-3.1a5 5 0 0 1 2.8-4.5L12 12l1.7 1.4a5 5 0 0 1 2.5 4.5V21"}]], o); },
|
||||
clock: function (o) { return ic([["circle",{cx:12,cy:12,r:8.6}],["path",{d:"M12 7.2V12l3.2 2"}]], o); },
|
||||
refresh: function (o) { return ic([["path",{d:"M3.2 12a8.8 8.8 0 0 1 15.1-6.1L21 8"}],["path",{d:"M21 3.6V8h-4.4"}],["path",{d:"M20.8 12a8.8 8.8 0 0 1-15.1 6.1L3 16"}],["path",{d:"M3 20.4V16h4.4"}]], o); },
|
||||
lock: function (o) { o = o || {}; return ic([["rect",{x:4.5,y:10.5,width:15,height:10.5,rx:3}],["path",{d:"M8 10.5V7a4 4 0 0 1 8 0v3.5"}],["circle",{cx:12,cy:15.6,r:1.4,fill:o.color||"currentColor",stroke:"none"}]], o); },
|
||||
alertCircle: function (o) { return ic([["circle",{cx:12,cy:12,r:9.2}],["path",{d:"M12 7.6v5"}],["path",{d:"M12 16.2h.01"}]], o); },
|
||||
alertTriangle: function (o) { return ic([["path",{d:"M12 3 2.6 20h18.8L12 3z"}],["path",{d:"M12 9.6v4"}],["path",{d:"M12 17h.01"}]], o); },
|
||||
calendar: function (o) { return ic([["rect",{x:3.5,y:5,width:17,height:16,rx:3}],["path",{d:"M3.5 9.5h17"}],["path",{d:"M8 3v4"}],["path",{d:"M16 3v4"}]], o); },
|
||||
star: function (o) {
|
||||
o = o || {};
|
||||
return h("svg", { width: o.size || 20, height: o.size || 20, viewBox: "0 0 24 24",
|
||||
fill: o.color || CREAM.gold, stroke: o.stroke || CREAM.goldDark, strokeWidth: 1, strokeLinejoin: "round", style: o.style },
|
||||
h("path", { d: "M12 2.4l2.9 5.9 6.5.95-4.7 4.57 1.1 6.48L12 17.8l-5.8 3.06 1.1-6.48L2.6 9.25l6.5-.95z" }));
|
||||
},
|
||||
plus: function (o) { return ic([["path",{d:"M12 5v14"}],["path",{d:"M5 12h14"}]], o); },
|
||||
chevronLeft: function (o) { return ic([["path",{d:"M14 6l-6 6 6 6"}]], o); },
|
||||
x: function (o) { return ic([["path",{d:"M6 6l12 12"}],["path",{d:"M18 6 6 18"}]], o); },
|
||||
users: function (o) { return ic([["circle",{cx:9,cy:8,r:3.4}],["path",{d:"M3.5 20a5.5 5.5 0 0 1 11 0"}],["path",{d:"M17 8h4"}],["path",{d:"M19 6v4"}]], o); },
|
||||
listCheck: function (o) { return ic([["path",{d:"M4 6h11"}],["path",{d:"M4 11h8"}],["path",{d:"M4 16h6"}],["path",{d:"m14.5 16.5 2 2 4-4"}]], o); },
|
||||
spinner: function (o) {
|
||||
o = o || {};
|
||||
return h("svg", { width: o.size || 18, height: o.size || 18, viewBox: "0 0 24 24", fill: "none",
|
||||
style: Object.assign({ animation: "tb-spin .8s linear infinite" }, o.style || {}) },
|
||||
[ h("circle", { key: 0, cx: 12, cy: 12, r: 9, stroke: o.track || "rgba(255,255,255,.35)", strokeWidth: 3 }),
|
||||
h("path", { key: 1, d: "M21 12a9 9 0 0 0-9-9", stroke: o.color || "#fff", strokeWidth: 3, strokeLinecap: "round" }) ]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ── Set de componentes "cream" para el flavor 'checada' (rediseño visual) ──
|
||||
// Devuelve su propia API (Logo, IconBadge, Card, Btn, Input, Aviso, Estado,
|
||||
// palette, fonts, icons). Independiente del camino panel/becario.
|
||||
function makeCream(React) {
|
||||
var h = React.createElement;
|
||||
var C = CREAM;
|
||||
var fonts = { title: FONT_TITLE, body: FONT_BODY };
|
||||
var icons = makeIcons(React);
|
||||
// tone (string) -> stroke del glifo, tinte del círculo, color del título.
|
||||
var STATE = {
|
||||
green: { stroke: C.green, tint: C.greenTint, title: C.green },
|
||||
blue: { stroke: C.primary, tint: C.blueTint, title: C.ink },
|
||||
amber: { stroke: C.amber, tint: C.amberTint, title: C.amber },
|
||||
danger: { stroke: C.danger, tint: C.dangerTint, title: C.danger },
|
||||
neutral: { stroke: C.inkSoft, tint: C.softTint, title: C.ink },
|
||||
};
|
||||
|
||||
function Logo(props) {
|
||||
return h("img", { src: "logo-taboada.png", alt: "Fundación Taboada",
|
||||
style: Object.assign({ height: "108px", width: "auto", display: "block" }, (props && props.style) || {}) });
|
||||
}
|
||||
|
||||
function IconBadge(props) {
|
||||
var t = STATE[props.tone] || STATE.blue;
|
||||
var sz = props.size || 64;
|
||||
var glyph = icons[props.icon] ? icons[props.icon]({ color: t.stroke, size: Math.round(sz * 0.47), sw: 1.7 }) : null;
|
||||
return h("div", { style: { width: sz + "px", height: sz + "px", borderRadius: "50%", background: t.tint,
|
||||
display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" } }, glyph);
|
||||
}
|
||||
|
||||
function Card(props) {
|
||||
return h("div", { style: Object.assign({
|
||||
background: C.surface, border: "1px solid " + C.cardBorder, borderRadius: "26px",
|
||||
padding: "24px", boxShadow: "0 20px 44px -28px rgba(33,28,22,.35)",
|
||||
}, props.style || {}) }, props.children);
|
||||
}
|
||||
|
||||
function Btn(props) {
|
||||
var ghost = props.variant === "ghost"; // secundario: contorno azul, sin relleno
|
||||
var success = props.variant === "success";
|
||||
var disabled = props.disabled;
|
||||
var style = {
|
||||
width: "100%", boxSizing: "border-box", padding: "15px", borderRadius: "16px",
|
||||
fontFamily: fonts.body, fontSize: "15px", fontWeight: 700,
|
||||
cursor: disabled ? "not-allowed" : (props.loading ? "progress" : "pointer"),
|
||||
display: "flex", alignItems: "center", justifyContent: "center", gap: "10px",
|
||||
};
|
||||
if (ghost) {
|
||||
style.background = "transparent";
|
||||
style.border = "1.5px solid " + (disabled ? "#C6CFD8" : C.primary);
|
||||
style.color = disabled ? "#B7C4D2" : C.primary;
|
||||
style.boxShadow = "none";
|
||||
} else {
|
||||
var bg = success ? C.green : C.primary;
|
||||
var shadow = success ? "0 12px 22px -10px rgba(47,138,99,.75)" : "0 12px 22px -10px rgba(46,119,184,.75)";
|
||||
style.border = "none";
|
||||
style.background = disabled ? "#C6CFD8" : bg;
|
||||
style.color = disabled ? "#F4F8FC" : "#fff";
|
||||
style.boxShadow = disabled ? "none" : shadow;
|
||||
}
|
||||
var kids = [];
|
||||
if (props.loading) kids.push(h("span", { key: "s", style: { display: "inline-flex" } },
|
||||
icons.spinner({ size: 18, color: ghost ? C.primary : "#fff", track: ghost ? C.line : undefined })));
|
||||
kids.push(h("span", { key: "t" }, props.children));
|
||||
return h("button", { type: props.type || "button", onClick: props.onClick, disabled: disabled, style: style }, kids);
|
||||
}
|
||||
|
||||
function Input(props) {
|
||||
var rest = Object.assign({}, props); delete rest.style;
|
||||
var style = Object.assign({
|
||||
width: "100%", boxSizing: "border-box", padding: "14px 15px",
|
||||
border: "1.5px solid " + C.inputBorder, borderRadius: "15px", background: C.inputBg,
|
||||
fontFamily: fonts.body, fontSize: "15px", color: C.ink, outline: "none",
|
||||
}, props.style || {});
|
||||
return h("input", Object.assign(rest, { style: style }));
|
||||
}
|
||||
|
||||
function Aviso(props) {
|
||||
var v = props.variant;
|
||||
var box = v === "warn" ? { bg: C.warnBg, bd: C.warnBorder, text: C.warnText, ink: C.amber }
|
||||
: v === "success" ? { bg: C.greenTint, bd: C.okBorder, text: C.okText, ink: C.green }
|
||||
: { bg: C.errBg, bd: C.errBorder, text: C.errText, ink: C.danger };
|
||||
var glyph = icons[props.icon] ? icons[props.icon]({ color: box.ink, size: 18, style: { flexShrink: 0 } }) : null;
|
||||
return h("div", { style: { display: "flex", gap: "10px", alignItems: "flex-start",
|
||||
background: box.bg, border: "1px solid " + box.bd, borderRadius: "14px", padding: "11px 13px", marginBottom: "14px" } },
|
||||
[ glyph ? h("span", { key: "i", style: { display: "inline-flex", flexShrink: 0, marginTop: "1px" } }, glyph) : null,
|
||||
h("span", { key: "t", style: { fontFamily: fonts.body, fontSize: "13px", fontWeight: 500, color: box.text, lineHeight: 1.45 } }, props.children) ]);
|
||||
}
|
||||
|
||||
// Patrón ícono-en-círculo + título + mensaje (+ progreso / acción opcionales).
|
||||
// props.tone: "green" | "blue" | "amber" | "danger"; props.icon: nombre en icons.
|
||||
function Estado(props) {
|
||||
var t = STATE[props.tone] || STATE.blue;
|
||||
var cardStyle = { textAlign: "center", padding: "28px 24px" };
|
||||
if (props.dashed) cardStyle.border = "1.5px dashed " + C.dashed;
|
||||
var kids = [
|
||||
h(IconBadge, { key: "i", icon: props.icon, tone: props.tone }),
|
||||
h("h2", { key: "t", style: { margin: "0 0 8px", fontFamily: fonts.title, fontWeight: 600,
|
||||
fontSize: "21px", color: t.title, letterSpacing: "-.01em", lineHeight: 1.2 } }, props.title),
|
||||
];
|
||||
if (props.sub) kids.push(h("p", { key: "s", style: { margin: 0, fontFamily: fonts.body,
|
||||
fontWeight: 400, fontSize: "14px", color: C.inkSoft, lineHeight: 1.55 } }, props.sub));
|
||||
if (typeof props.progress === "number") kids.push(
|
||||
h("div", { key: "pg", style: { height: "8px", borderRadius: "99px", background: C.track, marginTop: "16px", overflow: "hidden" } },
|
||||
h("div", { style: { height: "100%", width: Math.max(0, Math.min(100, props.progress)) + "%", borderRadius: "99px", background: C.green } })));
|
||||
if (props.action) kids.push(h("div", { key: "a", style: { marginTop: "18px" } }, props.action));
|
||||
return Card({ style: cardStyle, children: kids });
|
||||
}
|
||||
|
||||
// Píldora de estado. tone = string de estado real (activo/pendiente/cerrada/
|
||||
// abierta/revision/baja/autorizada/rechazada); mapea al color, no al revés.
|
||||
var BADGE = {
|
||||
activo: [C.greenTint, C.green], cerrada: [C.greenTint, C.green], autorizada: [C.greenTint, C.green],
|
||||
pendiente: [C.amberTint, C.amber], revision: [C.amberTint, C.amber],
|
||||
abierta: [C.neutralTint, C.inkSoft],
|
||||
baja: [C.dangerTint, C.danger], rechazada: [C.dangerTint, C.danger],
|
||||
};
|
||||
function StatusBadge(props) {
|
||||
var t = BADGE[props.tone] || [C.neutralTint, C.inkSoft];
|
||||
return h("span", { style: { display: "inline-block", padding: "3px 10px", borderRadius: "99px",
|
||||
fontFamily: fonts.body, fontSize: "11px", fontWeight: 600, background: t[0], color: t[1], whiteSpace: "nowrap" } }, props.children);
|
||||
}
|
||||
|
||||
// Tarjeta de horas con barra de avance. Al 100% muestra "¡Meta cumplida!".
|
||||
// Pinta valores del backend (total/meta/porcentaje/sub); no calcula nada.
|
||||
function HorasCard(props) {
|
||||
var pct = Math.max(0, Math.min(100, props.porcentaje || 0));
|
||||
var done = (props.porcentaje || 0) >= 100;
|
||||
var kids = [];
|
||||
if (done) {
|
||||
kids.push(h("div", { key: "stripe", style: { position: "absolute", top: 0, left: 0, right: 0, height: "4px",
|
||||
background: "linear-gradient(90deg," + C.green + "," + C.gold + ")" } }));
|
||||
kids.push(h("div", { key: "hdr", style: { display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" } },
|
||||
[ h("span", { key: "s", style: { display: "inline-flex" } }, icons.star({ size: 20 })),
|
||||
h("span", { key: "t", style: { fontFamily: fonts.title, fontWeight: 700, fontSize: "15px", color: C.green } }, "¡Meta cumplida!") ]));
|
||||
} else {
|
||||
kids.push(h("div", { key: "lbl", style: { fontFamily: fonts.body, fontWeight: 500, fontSize: "13px", color: C.inkSoft, marginBottom: "4px" } }, "Horas acumuladas"));
|
||||
}
|
||||
kids.push(h("div", { key: "num", style: { fontFamily: fonts.title, fontWeight: 700, fontSize: "30px", color: C.brand, letterSpacing: "-.01em", lineHeight: 1.1 } },
|
||||
[ props.total, " ", h("span", { key: "m", style: { fontFamily: fonts.body, fontWeight: 500, fontSize: "15px", color: C.inkSoft } }, "de " + props.meta) ]));
|
||||
kids.push(h("div", { key: "trk", style: { height: "9px", background: C.track, borderRadius: "99px", overflow: "hidden", margin: "13px 0 8px" } },
|
||||
h("div", { style: { height: "100%", width: pct + "%", background: done ? C.green : C.primary, borderRadius: "99px" } })));
|
||||
kids.push(h("div", { key: "sub", style: { fontFamily: fonts.body, fontWeight: 400, fontSize: "12px", color: done ? C.green : C.inkSoft } }, props.sub));
|
||||
return h("div", { style: { background: C.surface, border: "1px solid " + (done ? C.metaBorder : C.cardBorder),
|
||||
borderRadius: "20px", padding: "20px", boxShadow: "0 16px 34px -28px rgba(33,28,22,.3)", position: "relative", overflow: "hidden" } }, kids);
|
||||
}
|
||||
|
||||
return { Logo: Logo, IconBadge: IconBadge, Card: Card, Btn: Btn, Input: Input,
|
||||
Aviso: Aviso, Estado: Estado, StatusBadge: StatusBadge, HorasCard: HorasCard,
|
||||
palette: C, fonts: fonts, icons: icons };
|
||||
}
|
||||
|
||||
// ── Set cream de ESCRITORIO para el flavor 'panel' (rediseño visual) ──
|
||||
// Reusa paleta/fuentes/íconos cream a densidad de escritorio y añade lo propio
|
||||
// del panel: Nav, Table/Tr/Td, ProgressBar, Modal, EmptyState, Toggle, ErrorBar.
|
||||
// Independiente de makeCream (móvil): checada y becario no se ven afectados.
|
||||
function makePanel(React) {
|
||||
var h = React.createElement;
|
||||
var C = CREAM;
|
||||
var fonts = { title: FONT_TITLE, body: FONT_BODY };
|
||||
var icons = makeIcons(React);
|
||||
// tonos semánticos del panel (los helpers estadoXTone siguen en panel.html).
|
||||
var BADGE = {
|
||||
success: [C.greenTint, C.green], warn: [C.amberTint, C.amber],
|
||||
primary: [C.blueTint, C.primary], danger: [C.dangerTint, C.danger],
|
||||
chip: [C.neutralTint, C.inkSoft], neutral: [C.neutralTint, C.inkSoft],
|
||||
};
|
||||
|
||||
function Logo(props) {
|
||||
return h("img", { src: "logo-taboada.png", alt: "Fundación Taboada",
|
||||
style: Object.assign({ height: "40px", width: "auto", display: "block" }, (props && props.style) || {}) });
|
||||
}
|
||||
|
||||
function Card(props) {
|
||||
return h("div", { style: Object.assign({
|
||||
background: C.surface, border: "1px solid " + C.cardBorder, borderRadius: "18px",
|
||||
padding: "24px", boxShadow: "0 18px 40px -30px rgba(33,28,22,.3)",
|
||||
}, props.style || {}) }, props.children);
|
||||
}
|
||||
|
||||
function Btn(props) {
|
||||
var v = props.variant || "primary";
|
||||
var size = props.size === "sm" ? { pad: "7px 13px", font: "13px", radius: "10px" } : { pad: "11px 18px", font: "14px", radius: "13px" };
|
||||
var disabled = props.disabled;
|
||||
var VAR = {
|
||||
primary: { bg: C.primary, fg: "#fff", bd: "none", sh: "0 10px 20px -12px rgba(46,119,184,.7)" },
|
||||
success: { bg: C.green, fg: "#fff", bd: "none", sh: "0 10px 20px -12px rgba(47,138,99,.7)" },
|
||||
danger: { bg: C.danger, fg: "#fff", bd: "none", sh: "none" },
|
||||
subtle: { bg: C.softTint, fg: C.label, bd: "none", sh: "none" },
|
||||
ghost: { bg: "transparent", fg: C.primary, bd: "none", sh: "none" },
|
||||
link: { bg: "transparent", fg: C.inkSoft, bd: "none", sh: "none" },
|
||||
outline: { bg: "transparent", fg: C.label, bd: "1px solid " + C.line, sh: "none" },
|
||||
};
|
||||
var s = VAR[v] || VAR.primary;
|
||||
var solid = v === "primary" || v === "success" || v === "danger";
|
||||
var style = {
|
||||
display: props.block ? "flex" : "inline-flex", width: props.block ? "100%" : "auto", boxSizing: "border-box",
|
||||
alignItems: "center", justifyContent: "center", gap: "8px",
|
||||
padding: size.pad, borderRadius: size.radius, border: disabled ? "none" : s.bd,
|
||||
background: disabled ? "#C6CFD8" : s.bg, color: disabled ? "#F4F8FC" : s.fg,
|
||||
fontFamily: fonts.body, fontSize: size.font, fontWeight: 700,
|
||||
cursor: disabled ? "not-allowed" : (props.loading ? "progress" : "pointer"),
|
||||
boxShadow: disabled ? "none" : s.sh, whiteSpace: "nowrap",
|
||||
};
|
||||
var kids = [];
|
||||
if (props.loading) kids.push(h("span", { key: "s", style: { display: "inline-flex" } },
|
||||
icons.spinner({ size: 15, color: solid ? "#fff" : C.primary, track: C.line })));
|
||||
kids.push(h("span", { key: "t", style: { display: "inline-flex", alignItems: "center", gap: "7px" } }, props.children));
|
||||
return h("button", { type: props.type || "button", onClick: props.onClick, disabled: disabled, style: style }, kids);
|
||||
}
|
||||
|
||||
function Input(props) {
|
||||
var rest = Object.assign({}, props); delete rest.style;
|
||||
var style = Object.assign({
|
||||
width: "100%", boxSizing: "border-box", padding: "11px 14px",
|
||||
border: "1.5px solid " + C.inputBorder, borderRadius: "13px", background: C.inputBg,
|
||||
fontFamily: fonts.body, fontSize: "14px", color: C.ink, outline: "none",
|
||||
}, props.style || {});
|
||||
return h("input", Object.assign(rest, { style: style }));
|
||||
}
|
||||
|
||||
function Field(props) {
|
||||
return h("label", { style: { display: "block", marginBottom: "14px" } },
|
||||
h("span", { style: { display: "block", fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, color: C.label, marginBottom: "6px" } }, props.label),
|
||||
props.children);
|
||||
}
|
||||
|
||||
function Badge(props) {
|
||||
var t = BADGE[props.tone] || BADGE.chip;
|
||||
return h("span", { style: { display: "inline-block", padding: "4px 11px", borderRadius: "99px",
|
||||
fontFamily: fonts.body, fontSize: "12px", fontWeight: 600, background: t[0], color: t[1], whiteSpace: "nowrap" } }, props.children);
|
||||
}
|
||||
|
||||
function Aviso(props) {
|
||||
var v = props.variant;
|
||||
var box = v === "warn" ? { bg: C.warnBg, bd: C.warnBorder, text: C.warnText, ink: C.amber }
|
||||
: v === "success" ? { bg: C.greenTint, bd: C.okBorder, text: C.okText, ink: C.green }
|
||||
: { bg: C.errBg, bd: C.errBorder, text: C.errText, ink: C.danger };
|
||||
var glyph = icons[props.icon] ? icons[props.icon]({ color: box.ink, size: 18, style: { flexShrink: 0 } }) : null;
|
||||
return h("div", { style: { display: "flex", gap: "10px", alignItems: "flex-start",
|
||||
background: box.bg, border: "1px solid " + box.bd, borderRadius: "13px", padding: "11px 13px", marginBottom: "14px" } },
|
||||
[ glyph ? h("span", { key: "i", style: { display: "inline-flex", flexShrink: 0, marginTop: "1px" } }, glyph) : null,
|
||||
h("span", { key: "t", style: { fontFamily: fonts.body, fontSize: "13px", fontWeight: 500, color: box.text, lineHeight: 1.45 } }, props.children) ]);
|
||||
}
|
||||
|
||||
// Barra de error global, descartable (mapea err.message; el mapeo por code lo
|
||||
// hace quien la invoca).
|
||||
function ErrorBar(props) {
|
||||
if (!props.error) return null;
|
||||
return h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px",
|
||||
background: C.errBg, border: "1px solid " + C.errBorder, borderRadius: "14px", padding: "12px 16px", marginBottom: "16px" } },
|
||||
[ h("span", { key: "l", style: { display: "flex", alignItems: "center", gap: "10px" } },
|
||||
[ h("span", { key: "i", style: { display: "inline-flex", flexShrink: 0 } }, icons.alertTriangle({ size: 18, color: C.danger })),
|
||||
h("span", { key: "t", style: { fontFamily: fonts.body, fontSize: "14px", fontWeight: 500, color: C.errText } }, props.error) ]),
|
||||
h("span", { key: "x", onClick: props.onClose, style: { cursor: "pointer", display: "inline-flex", flexShrink: 0 } }, icons.x({ size: 16, color: C.errText, sw: 2.2 })) ]);
|
||||
}
|
||||
|
||||
function Toggle(props) {
|
||||
var on = !!props.checked;
|
||||
return h("label", { style: { display: "flex", alignItems: "center", gap: "11px", cursor: "pointer" } },
|
||||
[ h("span", { key: "sw", onClick: function () { props.onChange(!on); },
|
||||
style: { width: "42px", height: "24px", borderRadius: "99px", background: on ? C.primary : "#D6CDBB", position: "relative", flexShrink: 0, transition: "background .15s" } },
|
||||
h("span", { style: { position: "absolute", top: "3px", left: on ? "21px" : "3px", width: "18px", height: "18px", borderRadius: "50%", background: "#fff", transition: "left .15s" } })),
|
||||
props.label ? h("span", { key: "l", style: { fontFamily: fonts.body, fontSize: "14px", color: C.ink } }, props.label) : null ]);
|
||||
}
|
||||
|
||||
function ProgressBar(props) {
|
||||
var pct = Math.max(0, Math.min(100, props.value || 0));
|
||||
var done = (props.value || 0) >= 100;
|
||||
return h("div", { style: { height: (props.height || 7) + "px", background: C.track, borderRadius: "99px", overflow: "hidden" } },
|
||||
h("div", { style: { height: "100%", width: pct + "%", background: done ? C.green : C.primary, borderRadius: "99px" } }));
|
||||
}
|
||||
|
||||
// Navegación superior (logo + marca + pestañas + usuario + salir).
|
||||
function Nav(props) {
|
||||
var tab = function (t) {
|
||||
var active = props.active === t.key;
|
||||
return h("button", { key: t.key, onClick: function () { props.onTab(t.key); },
|
||||
style: { padding: "8px 15px", borderRadius: "11px", border: "none", cursor: "pointer",
|
||||
fontFamily: fonts.body, fontSize: "14px", fontWeight: 600,
|
||||
background: active ? C.blueTint : "transparent", color: active ? C.primaryDark : C.inkSoft } }, t.label);
|
||||
};
|
||||
return h("header", { style: { background: C.surface, borderBottom: "1px solid " + C.cardBorder,
|
||||
padding: "12px 24px", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "10px" } },
|
||||
[ h("div", { key: "l", style: { display: "flex", alignItems: "center", gap: "22px" } },
|
||||
[ h("div", { key: "b", style: { display: "flex", alignItems: "center", gap: "10px" } },
|
||||
[ h(Logo, { key: "lo", style: { height: "34px" } }),
|
||||
h("span", { key: "n", style: { fontFamily: fonts.title, fontWeight: 600, fontSize: "16px", color: C.brand } }, "Supervisión") ]),
|
||||
h("nav", { key: "t", style: { display: "flex", gap: "4px", flexWrap: "wrap" } }, props.tabs.map(tab)) ]),
|
||||
h("div", { key: "r", style: { display: "flex", alignItems: "center", gap: "14px" } },
|
||||
[ h("span", { key: "u", style: { fontFamily: fonts.body, fontSize: "13px", color: C.inkSoft } }, props.user),
|
||||
h(Btn, { key: "s", variant: "ghost", size: "sm", onClick: props.onLogout }, "Salir") ]) ]);
|
||||
}
|
||||
|
||||
// Tabla de escritorio: contenedor + thead temático. Filas con Tr/Td.
|
||||
function Table(props) {
|
||||
return h("div", { style: { background: C.surface, border: "1px solid " + C.cardBorder, borderRadius: "18px",
|
||||
overflow: "hidden", boxShadow: "0 18px 40px -30px rgba(33,28,22,.3)" } },
|
||||
h("div", { style: { overflowX: "auto" } },
|
||||
h("table", { style: { width: "100%", minWidth: (props.minWidth || 0) + "px", borderCollapse: "collapse", fontFamily: fonts.body, fontSize: "14px" } },
|
||||
[ h("thead", { key: "h" }, h("tr", { style: { background: "#F6F1E9", textAlign: "left" } },
|
||||
props.head.map(function (c, i) {
|
||||
return h("th", { key: i, style: { padding: "13px 16px", fontFamily: fonts.body, fontSize: "12px", fontWeight: 600,
|
||||
color: C.placeholder, textTransform: "uppercase", letterSpacing: ".06em", whiteSpace: "nowrap" } }, c);
|
||||
}))),
|
||||
h("tbody", { key: "b" }, props.children) ])));
|
||||
}
|
||||
function Tr(props) {
|
||||
return h("tr", { onClick: props.onClick, style: Object.assign({ borderTop: "1px solid " + C.cardBorder }, props.onClick ? { cursor: "pointer" } : {}) }, props.children);
|
||||
}
|
||||
function Td(props) {
|
||||
var style = {
|
||||
padding: "13px 16px", verticalAlign: "middle",
|
||||
fontFamily: props.mono ? "ui-monospace,SFMono-Regular,Menlo,monospace" : fonts.body,
|
||||
color: props.soft ? C.inkSoft : C.ink,
|
||||
};
|
||||
if (props.nowrap) style.whiteSpace = "nowrap";
|
||||
if (props.ellipsis) { style.maxWidth = "220px"; style.overflow = "hidden"; style.textOverflow = "ellipsis"; style.whiteSpace = "nowrap"; }
|
||||
Object.assign(style, props.style || {});
|
||||
return h("td", { style: style, title: props.title }, props.children);
|
||||
}
|
||||
|
||||
// Modal genérico (overlay + tarjeta). Mismo patrón para editar jornada,
|
||||
// alta/edición de becario y confirmaciones (autorizar/rechazar/baja/cerrar).
|
||||
function Modal(props) {
|
||||
return h("div", { style: { position: "fixed", inset: 0, background: "rgba(33,28,22,.4)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center", padding: "20px", zIndex: 50 } },
|
||||
h("div", { style: { width: "100%", maxWidth: (props.width || 400) + "px", background: C.surface, borderRadius: "22px",
|
||||
padding: "26px", boxShadow: "0 30px 60px -20px rgba(33,28,22,.5)", maxHeight: "90vh", overflowY: "auto" } },
|
||||
[ h("h3", { key: "t", style: { margin: "0 0 " + (props.sub ? "6px" : "18px"), fontFamily: fonts.title, fontWeight: 600, fontSize: "18px", color: C.brand } }, props.title),
|
||||
props.sub ? h("p", { key: "s", style: { margin: "0 0 18px", fontFamily: fonts.body, fontSize: "12px", color: C.inkSoft, lineHeight: 1.5 } }, props.sub) : null,
|
||||
h("div", { key: "c" }, props.children) ]));
|
||||
}
|
||||
|
||||
// Estado vacío: círculo con ícono + título + texto + acción opcional.
|
||||
function EmptyState(props) {
|
||||
var TONE = { blue: [C.blueTint, C.primary], green: [C.greenTint, C.green], neutral: [C.softTint, C.inkSoft] };
|
||||
var t = TONE[props.tone] || TONE.neutral;
|
||||
var glyph = icons[props.icon] ? icons[props.icon]({ color: t[1], size: 27, sw: 1.6 }) : null;
|
||||
var kids = [
|
||||
h("div", { key: "i", style: { width: "60px", height: "60px", borderRadius: "50%", background: t[0], display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" } }, glyph),
|
||||
h("h3", { key: "t", style: { margin: "0 0 6px", fontFamily: fonts.title, fontWeight: 600, fontSize: "17px", color: C.brand } }, props.title),
|
||||
];
|
||||
if (props.sub) kids.push(h("p", { key: "s", style: { margin: 0, fontFamily: fonts.body, fontSize: "13px", color: C.inkSoft, lineHeight: 1.5 } }, props.sub));
|
||||
if (props.action) kids.push(h("div", { key: "a", style: { marginTop: "18px" } }, props.action));
|
||||
return h("div", { style: { background: C.surface, border: "1px solid " + C.cardBorder, borderRadius: "20px",
|
||||
padding: "36px 26px", textAlign: "center", boxShadow: "0 20px 44px -32px rgba(33,28,22,.35)" } }, kids);
|
||||
}
|
||||
|
||||
return { palette: C, fonts: fonts, icons: icons, Logo: Logo, Card: Card, Btn: Btn, Input: Input, Field: Field,
|
||||
Badge: Badge, Aviso: Aviso, ErrorBar: ErrorBar, Toggle: Toggle, ProgressBar: ProgressBar,
|
||||
Nav: Nav, Table: Table, Tr: Tr, Td: Td, Modal: Modal, EmptyState: EmptyState };
|
||||
}
|
||||
|
||||
function makeUI(flavor) {
|
||||
var React = window.React;
|
||||
var h = React.createElement;
|
||||
if (flavor === "panel") return makePanel(React); // rediseño escritorio: set cream denso
|
||||
if (flavor === "checada" || flavor === "becario") return makeCream(React); // rediseño móvil: set cream
|
||||
var F = FLAVORS[flavor];
|
||||
if (!F) throw new Error("Theme.makeUI: flavor desconocido '" + flavor + "'");
|
||||
|
||||
function Card(props) {
|
||||
var base = {
|
||||
background: COLORS.surface, border: "1px solid " + COLORS.border,
|
||||
borderRadius: F.card.radius, padding: F.card.pad,
|
||||
boxShadow: F.card.shadow, marginBottom: F.card.mb,
|
||||
};
|
||||
return h("div", { style: Object.assign(base, props.style || {}) }, props.children);
|
||||
}
|
||||
|
||||
function Btn(props) {
|
||||
var v = btnVariant(props.variant);
|
||||
var size = F.btn.sizes[props.size || F.btn.defaultSize] || F.btn.sizes[F.btn.defaultSize];
|
||||
var disabled = props.disabled;
|
||||
var style = {
|
||||
padding: size.pad, borderRadius: F.btn.radius,
|
||||
background: disabled ? COLORS.border : v.bg,
|
||||
color: disabled && F.btn.disabledInk ? COLORS.inkSoft : v.color,
|
||||
border: v.border,
|
||||
fontFamily: FONT, fontSize: size.font, fontWeight: F.btn.weight,
|
||||
cursor: disabled ? "not-allowed" : "pointer",
|
||||
transition: F.btn.transition,
|
||||
};
|
||||
if (F.btn.block) style.width = "100%";
|
||||
return h("button", { type: props.type || "button", onClick: props.onClick, disabled: disabled, style: style }, props.children);
|
||||
}
|
||||
|
||||
function Input(props) {
|
||||
var rest = Object.assign({}, props);
|
||||
delete rest.style;
|
||||
var style = Object.assign({
|
||||
width: "100%", padding: F.input.pad, borderRadius: F.input.radius,
|
||||
border: "1px solid " + COLORS.border, fontSize: F.input.font,
|
||||
fontFamily: FONT, color: COLORS.ink, boxSizing: "border-box", outline: "none",
|
||||
}, props.style || {});
|
||||
return h("input", Object.assign(rest, { style: style }));
|
||||
}
|
||||
|
||||
function Badge(props) {
|
||||
var t = TONES[props.tone] || TONES.chip;
|
||||
var style = {
|
||||
background: t.bg, color: t.color, padding: F.badge.pad,
|
||||
borderRadius: RADIUS.pill, fontSize: "12px", fontWeight: 700,
|
||||
};
|
||||
if (F.badge.nowrap) style.whiteSpace = "nowrap";
|
||||
return h("span", { style: style }, props.children);
|
||||
}
|
||||
|
||||
function Field(props) {
|
||||
return h("label", { style: { display: "block", marginBottom: "12px" } },
|
||||
h("span", { style: { display: "block", fontSize: "13px", fontWeight: 600, color: COLORS.inkSoft, marginBottom: "5px" } }, props.label),
|
||||
props.children
|
||||
);
|
||||
}
|
||||
|
||||
// Patrón ícono + título + mensaje (+ botón opcional) de las pantallas de estado.
|
||||
// `tone` es un COLOR (no un tono de badge): tiñe el título.
|
||||
function Estado(props) {
|
||||
var kids = [
|
||||
h("div", { key: "e", style: { fontSize: "44px", marginBottom: "8px" } }, props.emoji),
|
||||
h("h2", { key: "t", style: { margin: "0 0 6px", color: props.tone || COLORS.ink, fontSize: "20px" } }, props.title),
|
||||
];
|
||||
if (props.sub) kids.push(h("p", { key: "s", style: { margin: 0, color: COLORS.inkSoft, fontSize: "14px", lineHeight: 1.5 } }, props.sub));
|
||||
if (props.action) kids.push(h("div", { key: "a", style: { marginTop: "16px" } }, props.action));
|
||||
return Card({ style: { textAlign: "center" }, children: kids });
|
||||
}
|
||||
|
||||
return { Btn: Btn, Card: Card, Input: Input, Badge: Badge, Field: Field, Estado: Estado };
|
||||
}
|
||||
|
||||
// ── Cliente HTTP compartido por checada/becario/panel ─────────────────────
|
||||
// Vive UNA sola vez aquí (antes estaba duplicado en las tres páginas). Mismo
|
||||
// origen detrás de nginx; credentials:'include' manda la cookie de sesión. El
|
||||
// Content-Type JSON se declara SOLO cuando de verdad hay body: anunciarlo en
|
||||
// un POST sin cuerpo hacía que Fastify respondiera 400. El error lleva
|
||||
// code/status/data para que cada página mapee por `code` igual que antes.
|
||||
async function apiFetch(path, options) {
|
||||
options = options || {};
|
||||
var headers = Object.assign({}, options.headers || {});
|
||||
if (options.body != null) headers["Content-Type"] = "application/json";
|
||||
var res = await window.fetch(
|
||||
window.location.origin + "/api" + path,
|
||||
Object.assign({ credentials: "include" }, options, { headers: headers })
|
||||
);
|
||||
var data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) {
|
||||
var err = new Error(data.error || "HTTP " + res.status);
|
||||
err.code = data.code;
|
||||
err.status = res.status;
|
||||
err.data = data;
|
||||
throw err;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
return { COLORS: COLORS, FONT: FONT, SPACE: SPACE, RADIUS: RADIUS, makeUI: makeUI, apiFetch: apiFetch };
|
||||
})();
|
||||
Reference in new issue
Block a user