Merge feat/cumplimiento-ui-base: macros, app.js y alta.js del rediseño (Fase 1b)
This commit is contained in:
commit
6a101545cb
8 files changed
+757
-14
No files matched your search
@@ -0,0 +1,281 @@
|
||||
// collina-pld · alta de cliente y captura de identificación (expediente/nuevo.html y
|
||||
// expediente/identificacion.html). Mejora progresiva: sin JS el formulario se envía igual y
|
||||
// el servidor (Pydantic) es quien decide; sus errores llegan pintados en el mismo lugar.
|
||||
//
|
||||
// Solo valida lo que la plantilla declara en cada campo (required, type, maxlength,
|
||||
// minlength, pattern, min, max): ninguna regla propia, para no rechazar lo que el servidor
|
||||
// acepta.
|
||||
//
|
||||
// <form data-validar="al-salir"> activa todo lo de abajo
|
||||
// <section data-seccion data-corto="Domicilio"> sección numerada (anillo e índice)
|
||||
// <span class="anillo"><span data-numero>1</span>…</span>
|
||||
// <div class="campo" data-campo> … .campo__entrada … .campo__error … .campo__ayuda
|
||||
// [data-avance-hechos] [data-avance-total] [data-avance-mensaje] [data-avance-barra]
|
||||
// [data-indice] índice de secciones (lo arma este JS)
|
||||
// <input data-formato="mayusculas|digitos"> normaliza al escribir (RFC, CURP, CP)
|
||||
// <input data-msj-formato="…"> mensaje si no cumple su pattern
|
||||
//
|
||||
// Personas (administradores de la persona moral): filas de Nombre / Cargo / RFC que se
|
||||
// serializan, una por línea como "Nombre; cargo; RFC", al textarea que lee el servidor.
|
||||
// <div data-personas="#id-del-textarea" hidden> … <template data-persona-plantilla> …
|
||||
// fila: [data-persona] con [data-persona-campo="nombre|cargo|rfc"], [data-persona-n],
|
||||
// [data-persona-quitar]; botón [data-persona-agregar]; aviso [data-personas-error]
|
||||
// El contenedor del textarea lleva data-personas-respaldo: se oculta cuando hay JS.
|
||||
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
const $ = (selector, raiz = document) => raiz.querySelector(selector);
|
||||
const $$ = (selector, raiz = document) => [...raiz.querySelectorAll(selector)];
|
||||
|
||||
// --- Mensajes ----------------------------------------------------------------------------------
|
||||
|
||||
const mensajeDe = (campo) => {
|
||||
const v = campo.validity;
|
||||
if (v.valid) return "";
|
||||
if (v.valueMissing) return campo.tagName === "SELECT" ? "Elige una opción" : "Este campo es obligatorio";
|
||||
if (v.typeMismatch) return campo.type === "email" ? "Revisa el formato: nombre@dominio.mx" : "Revisa el formato";
|
||||
if (v.patternMismatch) return campo.dataset.msjFormato || "Revisa el formato";
|
||||
if (v.tooShort) return `Mínimo ${campo.minLength} caracteres`;
|
||||
if (v.tooLong) return `Máximo ${campo.maxLength} caracteres`;
|
||||
if (v.rangeOverflow) return campo.type === "date" ? "La fecha no puede ser posterior a hoy" : `Máximo ${campo.max}`;
|
||||
if (v.rangeUnderflow) return `Mínimo ${campo.min}`;
|
||||
return "Revisa el valor";
|
||||
};
|
||||
|
||||
const normalizar = (campo) => {
|
||||
const formato = campo.dataset.formato;
|
||||
if (!formato) return;
|
||||
let valor = campo.value;
|
||||
if (formato === "mayusculas") valor = valor.toUpperCase();
|
||||
if (formato === "digitos") valor = valor.replace(/\D/g, "");
|
||||
if (valor !== campo.value) campo.value = valor;
|
||||
};
|
||||
|
||||
// Pinta (o limpia) el error de un campo. El error del servidor se conserva hasta que el
|
||||
// usuario toca el campo.
|
||||
const pintar = (campo, mostrar) => {
|
||||
const contenedor = campo.closest("[data-campo]");
|
||||
const error = contenedor && $(".campo__error", contenedor);
|
||||
if (campo.dataset.errorServidor === "1") return mensajeDe(campo) || "servidor";
|
||||
const mensaje = mensajeDe(campo);
|
||||
const visible = mostrar && Boolean(mensaje);
|
||||
if (visible) campo.setAttribute("aria-invalid", "true");
|
||||
else campo.removeAttribute("aria-invalid");
|
||||
if (error) {
|
||||
error.textContent = visible ? mensaje : "";
|
||||
error.hidden = !visible;
|
||||
}
|
||||
const ayuda = contenedor && $(".campo__ayuda", contenedor);
|
||||
if (ayuda) ayuda.hidden = visible;
|
||||
const valido = contenedor && $(".campo__valido", contenedor);
|
||||
if (valido) valido.hidden = Boolean(mensaje) || !campo.value.trim();
|
||||
if (campo.tagName === "SELECT") campo.classList.toggle("es-vacio", !campo.value);
|
||||
return mensaje;
|
||||
};
|
||||
|
||||
// --- Personas (administradores) ---------------------------------------------------------------
|
||||
|
||||
const leerLineas = (texto) =>
|
||||
texto
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean)
|
||||
.map((l) => {
|
||||
const [nombre = "", cargo = "", rfc = ""] = l.split(";").map((p) => p.trim());
|
||||
return { nombre, cargo, rfc };
|
||||
});
|
||||
|
||||
const filaNueva = (caja, datos = {}) => {
|
||||
const plantilla = $("template[data-persona-plantilla]", caja);
|
||||
const fila = plantilla.content.firstElementChild.cloneNode(true);
|
||||
$$("[data-persona-campo]", fila).forEach((i) => {
|
||||
i.value = datos[i.dataset.personaCampo] || "";
|
||||
});
|
||||
return fila;
|
||||
};
|
||||
|
||||
const serializar = (caja) => {
|
||||
const destino = $(caja.dataset.personas);
|
||||
if (!destino) return;
|
||||
destino.value = $$("[data-persona]", caja)
|
||||
.map((fila) => {
|
||||
const v = Object.fromEntries($$("[data-persona-campo]", fila).map((i) => [i.dataset.personaCampo, i.value.trim()]));
|
||||
return v.nombre || v.cargo || v.rfc ? [v.nombre, v.cargo, v.rfc].join("; ").replace(/(; )+$/, "") : "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
const iniciarPersonas = (caja) => {
|
||||
const destino = $(caja.dataset.personas);
|
||||
if (!destino) return;
|
||||
const lista = $("[data-personas-filas]", caja) || caja;
|
||||
const filas = leerLineas(destino.value);
|
||||
(filas.length ? filas : [{}]).forEach((d) => lista.append(filaNueva(caja, d)));
|
||||
const respaldo = destino.closest("[data-personas-respaldo]");
|
||||
if (respaldo) respaldo.hidden = true;
|
||||
caja.hidden = false;
|
||||
};
|
||||
|
||||
const personasCompletas = (caja) =>
|
||||
$$("[data-persona]", caja).some((fila) =>
|
||||
["nombre", "cargo"].every((c) => {
|
||||
const i = $(`[data-persona-campo="${c}"]`, fila);
|
||||
return i && i.value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
// --- Avance por sección ------------------------------------------------------------------------
|
||||
|
||||
const actualizar = (form) => {
|
||||
const intento = form.dataset.intento === "1";
|
||||
const secciones = $$("[data-seccion]", form).filter((s) => !s.hidden);
|
||||
let hechos = 0;
|
||||
let total = 0;
|
||||
let invalidos = 0;
|
||||
secciones.forEach((seccion, n) => {
|
||||
const numero = $("[data-numero]", seccion);
|
||||
if (numero) numero.textContent = n + 1;
|
||||
let h = 0;
|
||||
let t = 0;
|
||||
let mal = 0;
|
||||
$$("[data-personas]", seccion).forEach((caja) => {
|
||||
if (caja.hidden) return;
|
||||
const ok = personasCompletas(caja);
|
||||
t += 1;
|
||||
h += ok ? 1 : 0;
|
||||
const aviso = $("[data-personas-error]", caja);
|
||||
if (aviso) aviso.hidden = !(intento && !ok);
|
||||
$$("[data-persona]", caja).forEach((fila, i) => {
|
||||
const indice = $("[data-persona-n]", fila);
|
||||
if (indice) indice.textContent = i + 1;
|
||||
const quitar = $("[data-persona-quitar]", fila);
|
||||
if (quitar) quitar.disabled = $$("[data-persona]", caja).length === 1;
|
||||
});
|
||||
});
|
||||
$$("[data-campo] .campo__entrada", seccion).forEach((campo) => {
|
||||
if (campo.disabled || campo.closest("[hidden]")) return;
|
||||
const mensaje = pintar(campo, intento || campo.dataset.tocado === "1");
|
||||
if (campo.required) {
|
||||
t += 1;
|
||||
if (!mensaje) h += 1;
|
||||
}
|
||||
if (mensaje && (campo.value.trim() || intento)) mal += 1;
|
||||
});
|
||||
seccion.dataset.estadoSeccion = t > 0 && h === t && mal === 0 ? "completa" : intento && (h < t || mal) ? "error" : "pendiente";
|
||||
seccion.dataset.hechos = h;
|
||||
seccion.dataset.total = t;
|
||||
hechos += h;
|
||||
total += t;
|
||||
invalidos += mal;
|
||||
});
|
||||
|
||||
const fijar = (selector, valor) => $$(selector).forEach((el) => (el.textContent = valor));
|
||||
fijar("[data-avance-hechos]", hechos);
|
||||
fijar("[data-avance-total]", total);
|
||||
$$("[data-avance-barra]").forEach((el) => el.style.setProperty("--valor", `${total ? Math.round((hechos / total) * 100) : 0}%`));
|
||||
const faltan = total - hechos;
|
||||
const listo = faltan === 0 && invalidos === 0;
|
||||
$$("[data-avance-mensaje]").forEach((el) => {
|
||||
el.textContent = listo
|
||||
? "Todo listo para guardar"
|
||||
: faltan > 0
|
||||
? `Faltan ${faltan} ${faltan === 1 ? "dato obligatorio" : "datos obligatorios"}`
|
||||
: `Corrige ${invalidos} ${invalidos === 1 ? "campo" : "campos"} con formato inválido`;
|
||||
el.classList.toggle("texto-exito", listo);
|
||||
el.classList.toggle("texto-peligro", !listo && intento);
|
||||
});
|
||||
|
||||
const indice = $("[data-indice]");
|
||||
if (indice) {
|
||||
indice.replaceChildren(
|
||||
...secciones.map((s, n) => {
|
||||
const a = document.createElement("a");
|
||||
a.href = `#${s.id}`;
|
||||
a.dataset.estadoSeccion = s.dataset.estadoSeccion;
|
||||
a.innerHTML =
|
||||
`<span class="anillo anillo--chico"><span>${n + 1}</span>` +
|
||||
'<svg class="icono" aria-hidden="true"><use href="#i-check"/></svg></span>' +
|
||||
'<span class="indice__titulo"></span><span class="indice__cuenta"></span>';
|
||||
$(".indice__titulo", a).textContent = s.dataset.corto || "";
|
||||
$(".indice__cuenta", a).textContent = `${s.dataset.hechos}/${s.dataset.total}`;
|
||||
return a;
|
||||
}),
|
||||
);
|
||||
}
|
||||
return { listo, primera: secciones.find((s) => s.dataset.estadoSeccion !== "completa") };
|
||||
};
|
||||
|
||||
// --- Eventos -------------------------------------------------------------------------------------
|
||||
|
||||
const formDe = (el) => el.closest && el.closest("form[data-validar]");
|
||||
|
||||
document.addEventListener("input", (evento) => {
|
||||
const form = formDe(evento.target);
|
||||
if (!form) return;
|
||||
const campo = evento.target;
|
||||
if (campo.matches(".campo__entrada")) {
|
||||
normalizar(campo);
|
||||
delete campo.dataset.errorServidor;
|
||||
}
|
||||
const caja = campo.closest("[data-personas]");
|
||||
if (caja) serializar(caja);
|
||||
actualizar(form);
|
||||
});
|
||||
|
||||
document.addEventListener("change", (evento) => {
|
||||
const form = formDe(evento.target);
|
||||
if (form) actualizar(form);
|
||||
});
|
||||
|
||||
document.addEventListener("focusout", (evento) => {
|
||||
const form = formDe(evento.target);
|
||||
if (!form || !evento.target.matches(".campo__entrada")) return;
|
||||
evento.target.dataset.tocado = "1";
|
||||
actualizar(form);
|
||||
});
|
||||
|
||||
document.addEventListener("click", (evento) => {
|
||||
const agregar = evento.target.closest("[data-persona-agregar]");
|
||||
const quitar = evento.target.closest("[data-persona-quitar]");
|
||||
if (!agregar && !quitar) return;
|
||||
const caja = evento.target.closest("[data-personas]");
|
||||
if (agregar) {
|
||||
const fila = filaNueva(caja);
|
||||
($("[data-personas-filas]", caja) || caja).append(fila);
|
||||
$("input", fila).focus();
|
||||
} else if ($$("[data-persona]", caja).length > 1) {
|
||||
quitar.closest("[data-persona]").remove();
|
||||
}
|
||||
serializar(caja);
|
||||
actualizar(formDe(caja));
|
||||
});
|
||||
|
||||
document.addEventListener("submit", (evento) => {
|
||||
const form = evento.target;
|
||||
if (!form.matches("form[data-validar]")) return;
|
||||
$$("[data-personas]", form).forEach(serializar);
|
||||
form.dataset.intento = "1";
|
||||
$$("[data-error-servidor]", form).forEach((c) => delete c.dataset.errorServidor);
|
||||
const resultado = actualizar(form);
|
||||
if (resultado.listo) return;
|
||||
evento.preventDefault();
|
||||
evento.stopImmediatePropagation(); // ni confirmaciones ni envío con datos incompletos
|
||||
const primera = resultado.primera;
|
||||
if (primera) {
|
||||
primera.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
const invalido = $("[aria-invalid='true'], [data-persona-campo]", primera);
|
||||
if (invalido) window.setTimeout(() => invalido.focus({ preventScroll: true }), 300);
|
||||
}
|
||||
}, true);
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
$$("form[data-validar]").forEach((form) => {
|
||||
form.noValidate = true; // la validación nativa queda para cuando no hay JS
|
||||
$$("[data-personas]", form).forEach(iniciarPersonas);
|
||||
$$(".campo__entrada[aria-invalid='true']", form).forEach((c) => (c.dataset.errorServidor = "1"));
|
||||
actualizar(form);
|
||||
});
|
||||
});
|
||||
})();
|
||||
+236
-8
@@ -1,17 +1,36 @@
|
||||
// collina-pld · utilidades transversales. Sin framework ni dependencias.
|
||||
// Solo lo que comparten todas las pantallas; el código de una pantalla va en su plantilla
|
||||
// (bloque `scripts`). Chart.js NO se carga aquí: lo trae el laboratorio.
|
||||
// (bloque `scripts`) o en su propio archivo (static/alta.js, static/laboratorio.js).
|
||||
// Chart.js NO se carga aquí: lo trae el laboratorio. Todo es mejora progresiva: sin JS, los
|
||||
// formularios se envían y los enlaces navegan igual.
|
||||
//
|
||||
// pld.toast("Guardado", "exito") tono: info | exito | aviso | peligro
|
||||
// <form data-confirmar="¿Cerrar el caso?"> pide confirmación antes de enviar
|
||||
// <button data-confirmar="…"> / <a data-confirmar="…"> igual, por botón o enlace
|
||||
// <button data-alternar="#id"> muestra u oculta el elemento (clase es-visible)
|
||||
// <button data-alternar="#id"> muestra u oculta el elemento (clase es-visible);
|
||||
// Esc cierra la barra lateral abierta
|
||||
// <div data-toast="Guardado" data-tono="exito" hidden></div> toast al cargar la página
|
||||
// <button data-requiere="#a,#b"> se habilita cuando #a tiene texto (≥ data-min o
|
||||
// minlength) y #b, si es casilla, está marcada
|
||||
// <span data-contador="#id" data-min="20"> "12 / 20 mín." → "34 caracteres"
|
||||
// <span data-pista-de="#boton" data-pistas="a|b" data-listo="…"> ayuda según lo que falta
|
||||
// <button data-distintos="#a,#b"> deshabilitado si los dos selects valen lo mismo
|
||||
// <button data-ver-contrasena> Ver / Ocultar la contraseña del mismo campo
|
||||
// <tr class="fila-enlace"> la fila navega al primer enlace que contiene
|
||||
// <tr data-cajon="#dialogo" data-plantilla="#tpl"> abre el cajón lateral con el <template>
|
||||
// <form data-autoenvio> envía los filtros al cambiar un select, fecha,
|
||||
// número o casilla
|
||||
// <label data-zona-archivo> … [data-zona-nombre] nombre del archivo elegido y arrastre
|
||||
// <input type="radio" data-descripcion="…"> pinta la descripción en [data-descripcion-regla]
|
||||
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
const pld = (window.pld = window.pld || {});
|
||||
const $ = (selector, raiz = document) => raiz.querySelector(selector);
|
||||
const $$ = (selector, raiz = document) => [...raiz.querySelectorAll(selector)];
|
||||
|
||||
// --- Toasts y confirmaciones ---------------------------------------------------------------
|
||||
|
||||
pld.toast = (mensaje, tono = "info", duracionMs = 4500) => {
|
||||
const contenedor = document.getElementById("toasts");
|
||||
@@ -19,7 +38,10 @@
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast toast--${tono}`;
|
||||
toast.setAttribute("role", tono === "peligro" ? "alert" : "status");
|
||||
toast.textContent = mensaje;
|
||||
if (tono !== "peligro" && document.getElementById("i-check")) {
|
||||
toast.innerHTML = '<svg class="icono icono--15" aria-hidden="true"><use href="#i-check"/></svg>';
|
||||
}
|
||||
toast.append(document.createTextNode(mensaje));
|
||||
contenedor.append(toast);
|
||||
window.setTimeout(() => toast.remove(), duracionMs);
|
||||
};
|
||||
@@ -32,25 +54,231 @@
|
||||
if (mensaje && !pld.confirmar(mensaje)) evento.preventDefault();
|
||||
});
|
||||
|
||||
// --- Requisitos, contadores, pistas y selects distintos ------------------------------------
|
||||
|
||||
const cumple = (el) => {
|
||||
if (!el) return false;
|
||||
if (el.type === "checkbox" || el.type === "radio") return el.checked;
|
||||
const minimo = Number(el.dataset.min || el.getAttribute("minlength") || 1);
|
||||
return el.value.trim().length >= minimo;
|
||||
};
|
||||
|
||||
pld.evaluar = (raiz = document) => {
|
||||
$$("[data-requiere]", raiz).forEach((boton) => {
|
||||
const falta = boton.dataset.requiere
|
||||
.split(",")
|
||||
.map((s) => cumple($(s.trim())))
|
||||
.indexOf(false);
|
||||
boton.disabled = falta !== -1 || boton.dataset.bloqueado === "1";
|
||||
if (boton.id) {
|
||||
const pista = $(`[data-pista-de="#${boton.id}"]`);
|
||||
if (pista) {
|
||||
pista.textContent =
|
||||
falta === -1 ? pista.dataset.listo || "" : (pista.dataset.pistas || "").split("|")[falta] || "";
|
||||
}
|
||||
}
|
||||
});
|
||||
$$("[data-contador]", raiz).forEach((contador) => {
|
||||
const campo = $(contador.dataset.contador);
|
||||
if (!campo) return;
|
||||
const n = campo.value.trim().length;
|
||||
const minimo = Number(contador.dataset.min || 0);
|
||||
contador.textContent = n < minimo ? `${n} / ${minimo} mín.` : `${n} caracteres`;
|
||||
contador.classList.toggle("es-suficiente", n >= minimo);
|
||||
});
|
||||
$$("[data-distintos]", raiz).forEach((boton) => {
|
||||
const [a, b] = boton.dataset.distintos.split(",").map((s) => $(s.trim()));
|
||||
boton.disabled = Boolean(a && b && a.value === b.value);
|
||||
});
|
||||
};
|
||||
|
||||
document.addEventListener("input", () => pld.evaluar());
|
||||
|
||||
// --- Filas enlace ----------------------------------------------------------------------------
|
||||
// La fila navega al primer enlace que contiene (sin data-href: tests/test_cartera.py cuenta los
|
||||
// href="/clientes/ de la página). No intercepta clics en controles de la fila ni cuando hay
|
||||
// texto seleccionado; Ctrl/Cmd/Mayús o el clic central abren en otra pestaña.
|
||||
|
||||
const INTERACTIVOS = "a, button, input, select, textarea, label, summary, details, [contenteditable]";
|
||||
|
||||
const hayTextoSeleccionado = () => {
|
||||
const seleccion = window.getSelection && window.getSelection();
|
||||
return Boolean(seleccion && seleccion.toString().trim());
|
||||
};
|
||||
|
||||
const destinoDeFila = (evento) => {
|
||||
const fila = evento.target.closest && evento.target.closest("tr.fila-enlace");
|
||||
if (!fila || fila.hasAttribute("data-cajon")) return null;
|
||||
if (evento.target.closest(INTERACTIVOS) || hayTextoSeleccionado()) return null;
|
||||
const enlace = $("a[href]", fila);
|
||||
return enlace ? enlace.href : null;
|
||||
};
|
||||
|
||||
// --- Cajón lateral (<dialog class="cajon">) ---------------------------------------------------
|
||||
|
||||
pld.abrirCajon = (selector, plantilla, origen) => {
|
||||
const dialogo = $(selector);
|
||||
const contenido = plantilla && $(plantilla);
|
||||
if (!dialogo || !contenido || typeof dialogo.showModal !== "function") return false;
|
||||
dialogo.replaceChildren(contenido.content.cloneNode(true));
|
||||
$$("tr.es-seleccionada").forEach((f) => f.classList.remove("es-seleccionada"));
|
||||
if (origen && origen.tagName === "TR") origen.classList.add("es-seleccionada");
|
||||
dialogo.addEventListener(
|
||||
"close",
|
||||
() => {
|
||||
if (origen) {
|
||||
origen.classList.remove("es-seleccionada");
|
||||
origen.focus({ preventScroll: true });
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
dialogo.showModal();
|
||||
pld.evaluar(dialogo);
|
||||
return true;
|
||||
};
|
||||
|
||||
const disparadorDeCajon = (evento) => {
|
||||
const disparador = evento.target.closest && evento.target.closest("[data-cajon]");
|
||||
if (!disparador) return null;
|
||||
const interactivo = evento.target.closest(INTERACTIVOS);
|
||||
if ((interactivo && interactivo !== disparador) || hayTextoSeleccionado()) return null;
|
||||
return disparador;
|
||||
};
|
||||
|
||||
// --- Clics y teclado ---------------------------------------------------------------------------
|
||||
|
||||
document.addEventListener("click", (evento) => {
|
||||
const enlace = evento.target.closest("a[data-confirmar]");
|
||||
const objetivo = evento.target;
|
||||
|
||||
const enlace = objetivo.closest("a[data-confirmar]");
|
||||
if (enlace && !pld.confirmar(enlace.dataset.confirmar)) {
|
||||
evento.preventDefault();
|
||||
return;
|
||||
}
|
||||
const alternador = evento.target.closest("[data-alternar]");
|
||||
|
||||
const alternador = objetivo.closest("[data-alternar]");
|
||||
if (alternador) {
|
||||
const objetivo = document.querySelector(alternador.dataset.alternar);
|
||||
if (objetivo) {
|
||||
const visible = objetivo.classList.toggle("es-visible");
|
||||
const elemento = $(alternador.dataset.alternar);
|
||||
if (elemento) {
|
||||
const visible = elemento.classList.toggle("es-visible");
|
||||
alternador.setAttribute("aria-expanded", String(visible));
|
||||
}
|
||||
}
|
||||
|
||||
const ver = objetivo.closest("[data-ver-contrasena]");
|
||||
if (ver) {
|
||||
const campo = ver.parentElement.querySelector("input");
|
||||
const mostrar = campo.type === "password";
|
||||
campo.type = mostrar ? "text" : "password";
|
||||
ver.textContent = mostrar ? "Ocultar" : "Ver";
|
||||
ver.setAttribute("aria-pressed", String(mostrar));
|
||||
ver.setAttribute("aria-label", mostrar ? "Ocultar contraseña" : "Mostrar contraseña");
|
||||
}
|
||||
|
||||
if (objetivo.closest("[data-cajon-cerrar]")) {
|
||||
objetivo.closest("dialog").close();
|
||||
return;
|
||||
}
|
||||
if (objetivo.matches("dialog.cajon")) {
|
||||
objetivo.close(); // clic en el fondo, fuera del panel
|
||||
return;
|
||||
}
|
||||
|
||||
const disparador = disparadorDeCajon(evento);
|
||||
if (disparador) {
|
||||
if (pld.abrirCajon(disparador.dataset.cajon, disparador.dataset.plantilla, disparador)) {
|
||||
evento.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const destino = destinoDeFila(evento);
|
||||
if (destino) {
|
||||
if (evento.ctrlKey || evento.metaKey || evento.shiftKey) window.open(destino, "_blank", "noopener");
|
||||
else window.location.href = destino;
|
||||
}
|
||||
});
|
||||
|
||||
// Clic central sobre una fila: otra pestaña, como en un enlace.
|
||||
document.addEventListener("auxclick", (evento) => {
|
||||
if (evento.button !== 1) return;
|
||||
const destino = destinoDeFila(evento);
|
||||
if (destino) {
|
||||
evento.preventDefault();
|
||||
window.open(destino, "_blank", "noopener");
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (evento) => {
|
||||
const disparador = evento.target.closest && evento.target.closest("[data-cajon]");
|
||||
if (disparador && evento.target === disparador && (evento.key === "Enter" || evento.key === " ")) {
|
||||
evento.preventDefault();
|
||||
pld.abrirCajon(disparador.dataset.cajon, disparador.dataset.plantilla, disparador);
|
||||
return;
|
||||
}
|
||||
if (evento.key === "Escape") {
|
||||
const lateral = $(".lateral.es-visible");
|
||||
if (lateral) {
|
||||
lateral.classList.remove("es-visible");
|
||||
const boton = $(`[data-alternar="#${lateral.id}"]`);
|
||||
if (boton) {
|
||||
boton.setAttribute("aria-expanded", "false");
|
||||
boton.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// --- Cambios: filtros, archivos, descripción de la regla ----------------------------------------
|
||||
|
||||
const pintarDescripcion = (opcion) => {
|
||||
const grupo = opcion.closest("fieldset") || opcion.form;
|
||||
const destino = grupo && $("[data-descripcion-regla]", grupo);
|
||||
if (destino) {
|
||||
destino.textContent = opcion.dataset.descripcion;
|
||||
destino.hidden = !opcion.dataset.descripcion;
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("change", (evento) => {
|
||||
const objetivo = evento.target;
|
||||
const filtros = objetivo.closest("form[data-autoenvio]");
|
||||
if (
|
||||
filtros &&
|
||||
objetivo.matches("select, input[type=checkbox], input[type=radio], input[type=date], input[type=number]")
|
||||
) {
|
||||
filtros.requestSubmit();
|
||||
return;
|
||||
}
|
||||
if (objetivo.matches("[data-zona-archivo] input[type=file]")) {
|
||||
const nombre = $("[data-zona-nombre]", objetivo.closest("[data-zona-archivo]"));
|
||||
if (nombre && objetivo.files[0]) nombre.textContent = objetivo.files[0].name;
|
||||
}
|
||||
if (objetivo.matches("input[data-descripcion]")) pintarDescripcion(objetivo);
|
||||
pld.evaluar();
|
||||
});
|
||||
|
||||
["dragenter", "dragover"].forEach((tipo) =>
|
||||
document.addEventListener(tipo, (evento) => {
|
||||
const zona = evento.target.closest && evento.target.closest("[data-zona-archivo]");
|
||||
if (zona) zona.classList.add("es-arrastrando");
|
||||
}),
|
||||
);
|
||||
["dragleave", "drop"].forEach((tipo) =>
|
||||
document.addEventListener(tipo, (evento) => {
|
||||
const zona = evento.target.closest && evento.target.closest("[data-zona-archivo]");
|
||||
if (zona) zona.classList.remove("es-arrastrando");
|
||||
}),
|
||||
);
|
||||
|
||||
// --- Al cargar ---------------------------------------------------------------------------------
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll("[data-toast]").forEach((el) => {
|
||||
pld.toast(el.dataset.toast, el.dataset.tono || "info");
|
||||
});
|
||||
$$("input[data-descripcion]:checked").forEach(pintarDescripcion);
|
||||
pld.evaluar();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,29 @@
|
||||
{#- Cifra de una franja de KPIs (.resumen). Con href es un enlace GET que filtra.
|
||||
|
||||
{% from "_componentes/cifra.html" import cifra %}
|
||||
|
||||
<div class="resumen">
|
||||
{{ cifra("Créditos", p.conteos.total, nota="en cartera", href="/creditos", seleccionada=not filtros.status) }}
|
||||
{{ cifra("Liquidados", p.conteos.liquidado, href="/creditos?status=liquidado") }}
|
||||
</div>
|
||||
|
||||
etiqueta rótulo en mono, arriba
|
||||
valor cifra grande (texto o Markup)
|
||||
nota texto chico junto a la cifra
|
||||
pie línea de ayuda debajo (.resumen__nota)
|
||||
seleccionada filtro activo: fondo verde y subrayado, aria-current="true"
|
||||
Ojo: los tests buscan algunas cifras junto con su texto ("124 abiertas de 124"); esas no se
|
||||
parten en etiqueta y valor.
|
||||
-#}
|
||||
|
||||
{%- macro cifra(etiqueta, valor, nota=None, href=None, seleccionada=False, pie=None, clase="") -%}
|
||||
{%- set elemento = "a" if href else "div" -%}
|
||||
<{{ elemento }} class="resumen__cifra{{ ' es-seleccionada' if seleccionada }}{{ ' ' ~ clase if clase }}"
|
||||
{%- if href %} href="{{ href }}"{% endif %}{% if seleccionada and href %} aria-current="true"{% endif %}>
|
||||
<span class="resumen__etiqueta">{{ etiqueta }}</span>
|
||||
<span class="resumen__valor"><strong>{{ valor }}</strong>{% if nota %}<small>{{ nota }}</small>{% endif %}</span>
|
||||
{%- if pie %}
|
||||
<span class="resumen__nota">{{ pie }}</span>
|
||||
{%- endif %}
|
||||
</{{ elemento }}>
|
||||
{%- endmacro -%}
|
||||
@@ -0,0 +1,46 @@
|
||||
{#- Paginación numerada con huecos ("1 2 3 … 21") y el texto "Página X de Y".
|
||||
|
||||
{% from "_componentes/paginacion.html" import paginacion %}
|
||||
|
||||
{{ paginacion(pagina, paginas, "/cartera?" ~ consulta ~ "&pagina=") }}
|
||||
{{ paginacion(pagina, paginas, url, total=total, por_pagina=50) }} agrega "1–50 de 1,023"
|
||||
{{ paginacion(pagina, paginas, url, simple=True) }} solo flechas
|
||||
|
||||
url_base termina en "pagina=" y conserva los demás filtros (los tests buscan, p. ej.,
|
||||
"pagina=3" junto a "titular=tercero"). Con una sola página no pinta nada, salvo siempre=True.
|
||||
-#}
|
||||
{%- from "_componentes/iconos.html" import icono -%}
|
||||
|
||||
{%- macro paginacion(pagina, paginas, url_base, total=None, por_pagina=None, simple=False, siempre=False) -%}
|
||||
{%- if paginas > 1 or siempre %}
|
||||
<nav class="paginacion{{ ' paginacion--simple' if simple }}" aria-label="Paginación">
|
||||
<span class="paginacion__rango">Página {{ pagina }} de {{ paginas }}
|
||||
{%- if total is not none and por_pagina %} · {{ "{:,}".format((pagina - 1) * por_pagina + 1 if total else 0) }}–{{ "{:,}".format([pagina * por_pagina, total] | min) }} de {{ "{:,}".format(total) }}{% endif -%}
|
||||
</span>
|
||||
<div class="paginacion__paginas">
|
||||
{%- if pagina > 1 %}
|
||||
<a class="paginacion__pagina" href="{{ url_base }}{{ pagina - 1 }}" aria-label="Página anterior">{{ icono("chevron-left") }}</a>
|
||||
{%- else %}
|
||||
<span class="paginacion__pagina" aria-disabled="true">{{ icono("chevron-left") }}</span>
|
||||
{%- endif %}
|
||||
{%- if not simple %}
|
||||
{%- set ns = namespace(previa=0) %}
|
||||
{%- for n in range(1, paginas + 1) %}
|
||||
{%- if n == 1 or n == paginas or (pagina - 2 <= n <= pagina + 2) or (pagina <= 3 and n <= 5) or (pagina >= paginas - 2 and n >= paginas - 4) %}
|
||||
{%- if ns.previa and n - ns.previa > 1 %}
|
||||
<span class="paginacion__hueco" aria-hidden="true">…</span>
|
||||
{%- endif %}
|
||||
<a class="paginacion__pagina" href="{{ url_base }}{{ n }}"{% if n == pagina %} aria-current="page"{% endif %}>{{ n }}</a>
|
||||
{%- set ns.previa = n %}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
{%- if pagina < paginas %}
|
||||
<a class="paginacion__pagina" href="{{ url_base }}{{ pagina + 1 }}" aria-label="Página siguiente">{{ icono("chevron") }}</a>
|
||||
{%- else %}
|
||||
<span class="paginacion__pagina" aria-disabled="true">{{ icono("chevron") }}</span>
|
||||
{%- endif %}
|
||||
</div>
|
||||
</nav>
|
||||
{%- endif %}
|
||||
{%- endmacro -%}
|
||||
@@ -0,0 +1,21 @@
|
||||
{#- Pestañas que son enlaces a rutas distintas (paso 5; Alertas | Casos).
|
||||
|
||||
{% from "_componentes/pestanas.html" import pestanas %}
|
||||
|
||||
{{ pestanas([("alertas", "Alertas", "/alertas"), ("casos", "Casos", "/casos")], "casos",
|
||||
etiqueta="Alertas y casos") }}
|
||||
|
||||
Cada elemento es (clave, título, href) o (clave, título, href, conteo); la activa lleva
|
||||
aria-current="page". El <nav> va dentro del contenido, siempre después de la barra lateral.
|
||||
-#}
|
||||
|
||||
{%- macro pestanas(items, activa, etiqueta="Secciones") -%}
|
||||
<nav aria-label="{{ etiqueta }}">
|
||||
<ul class="pestanas">
|
||||
{%- for item in items %}
|
||||
<li><a href="{{ item[2] }}"{% if item[0] == activa %} aria-current="page"{% endif %}><span>{{ item[1] }}</span>
|
||||
{%- if item | length > 3 and item[3] is not none %}<small>{{ item[3] }}</small>{% endif %}</a></li>
|
||||
{%- endfor %}
|
||||
</ul>
|
||||
</nav>
|
||||
{%- endmacro -%}
|
||||
@@ -12,9 +12,15 @@
|
||||
{% call(fila, col) tabla(columnas, clientes) %}
|
||||
{% if col.clave == "nivel" %}{{ badge_nivel(fila.nivel) }}{% else %}{{ fila[col.clave] }}{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
Opcionales (la salida sin ellos no cambia):
|
||||
clase clases extra de la tabla: tabla--blanca, tabla--densa, ancho-min-720…
|
||||
clase_contenedor clases extra del contenedor: tabla-contenedor--alto (encabezado fijo).
|
||||
Las tablas que necesitan atributos por fila (fila-enlace, es-posterior, data-cajon) o
|
||||
th scope="row" se escriben a mano con las mismas clases.
|
||||
-#}
|
||||
|
||||
{%- macro tabla(columnas, filas, vacio="Sin registros.") -%}
|
||||
{%- macro tabla(columnas, filas, vacio="Sin registros.", clase="", clase_contenedor="") -%}
|
||||
{%- set cols = [] -%}
|
||||
{%- for col in columnas -%}
|
||||
{%- if col is mapping -%}
|
||||
@@ -23,8 +29,8 @@
|
||||
{%- set _ = cols.append({"clave": col, "titulo": col | replace("_", " ") | capitalize, "alinear": "izq"}) -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla">
|
||||
<div class="tabla-contenedor{{ ' ' ~ clase_contenedor if clase_contenedor }}">
|
||||
<table class="tabla{{ ' ' ~ clase if clase }}">
|
||||
<thead>
|
||||
<tr>
|
||||
{%- for col in cols %}
|
||||
|
||||
@@ -5,17 +5,30 @@
|
||||
{% call tarjeta("Datos del cliente", subtitulo="Vigentes al corte") %}
|
||||
...contenido...
|
||||
{% endcall %}
|
||||
|
||||
Opcionales (la salida sin ellos no cambia):
|
||||
acciones HTML a la derecha del encabezado (botones, badges). Pásalo como bloque:
|
||||
{% set acciones %}<a class="boton boton--chico" href="…">Ver</a>{% endset %}
|
||||
{% call tarjeta("Créditos", acciones=acciones) %}…{% endcall %}
|
||||
Un {% set %} de bloque es Markup y no se escapa; una cadena normal sí.
|
||||
Igual con `subtitulo` si lleva marcado (cifras en mono, enlaces).
|
||||
plano True: el cuerpo sin relleno (tablas, listas y rejillas a sangre).
|
||||
id id de la sección (anclas del índice de la ficha).
|
||||
clase clases extra de la sección (tarjeta--vidrio, tarjeta--alerta, ancla…).
|
||||
-#}
|
||||
|
||||
{%- macro tarjeta(titulo, subtitulo=None) -%}
|
||||
<section class="tarjeta">
|
||||
{%- macro tarjeta(titulo, subtitulo=None, acciones=None, plano=False, id=None, clase="") -%}
|
||||
<section class="tarjeta{{ ' ' ~ clase if clase }}"{% if id %} id="{{ id }}"{% endif %}>
|
||||
<header class="tarjeta__encabezado">
|
||||
<h2 class="tarjeta__titulo">{{ titulo }}</h2>
|
||||
{%- if subtitulo %}
|
||||
<p class="tarjeta__subtitulo">{{ subtitulo }}</p>
|
||||
{%- endif %}
|
||||
{%- if acciones %}
|
||||
<div class="tarjeta__acciones">{{ acciones }}</div>
|
||||
{%- endif %}
|
||||
</header>
|
||||
<div class="tarjeta__cuerpo">
|
||||
<div class="tarjeta__cuerpo{{ ' tarjeta__cuerpo--plano' if plano }}">
|
||||
{{- caller() if caller else "" -}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Macros de `_componentes/` del rediseño: los parámetros nuevos de `tarjeta` y `tabla` no
|
||||
cambian su salida por omisión, y `paginacion`, `pestanas` y `cifra` pintan lo que prometen."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from app.routers import plantillas
|
||||
|
||||
|
||||
def renderizar(fuente: str, **contexto: object) -> str:
|
||||
return plantillas.env.from_string(fuente).render(**contexto)
|
||||
|
||||
|
||||
TARJETA = '{% from "_componentes/tarjeta.html" import tarjeta %}'
|
||||
TABLA = '{% from "_componentes/tabla.html" import tabla %}'
|
||||
PAGINACION = '{% from "_componentes/paginacion.html" import paginacion %}'
|
||||
|
||||
|
||||
def test_tarjeta_y_tabla_sin_opcionales_pintan_lo_mismo_que_antes() -> None:
|
||||
assert renderizar(TARJETA + '{% call tarjeta("A", "s") %}<p>cuerpo</p>{% endcall %}') == (
|
||||
'<section class="tarjeta">\n <header class="tarjeta__encabezado">\n'
|
||||
' <h2 class="tarjeta__titulo">A</h2>\n <p class="tarjeta__subtitulo">s</p>\n'
|
||||
' </header>\n <div class="tarjeta__cuerpo"><p>cuerpo</p></div>\n</section>'
|
||||
)
|
||||
assert renderizar(TABLA + '{{ tabla(["nombre"], []) }}') == (
|
||||
'<div class="tabla-contenedor">\n <table class="tabla">\n <thead>\n <tr>\n'
|
||||
' <th scope="col">Nombre</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n'
|
||||
' <td class="tabla__vacio" colspan="1">Sin registros.</td>\n </tr>\n'
|
||||
" </tbody>\n </table>\n</div>"
|
||||
)
|
||||
|
||||
|
||||
def test_tarjeta_con_acciones_plano_id_y_clase() -> None:
|
||||
html = renderizar(
|
||||
TARJETA
|
||||
+ '{% set acc %}<a href="/x">Ver</a>{% endset %}'
|
||||
+ '{{ tarjeta("T", subtitulo="<b>s</b>", acciones=acc, plano=True, id="c-x",'
|
||||
+ ' clase="ancla") }}'
|
||||
)
|
||||
assert '<section class="tarjeta ancla" id="c-x">' in html
|
||||
assert '<div class="tarjeta__acciones"><a href="/x">Ver</a></div>' in html
|
||||
assert '<div class="tarjeta__cuerpo tarjeta__cuerpo--plano">' in html
|
||||
assert "<b>s</b>" in html # una cadena normal se sigue escapando
|
||||
|
||||
|
||||
def test_tabla_con_clases() -> None:
|
||||
html = renderizar(
|
||||
TABLA
|
||||
+ '{{ tabla(["a"], [], clase="tabla--densa", clase_contenedor="tabla-contenedor--alto") }}'
|
||||
)
|
||||
assert '<div class="tabla-contenedor tabla-contenedor--alto">' in html
|
||||
assert '<table class="tabla tabla--densa">' in html
|
||||
|
||||
|
||||
def _paginas(html: str) -> list[str]:
|
||||
return re.findall(r'class="paginacion__(?:pagina|hueco)"[^>]*>([^<]*)<', html)
|
||||
|
||||
|
||||
def test_paginacion_numerada_con_huecos_y_filtros() -> None:
|
||||
base = "/operaciones?titular=tercero&pagina="
|
||||
primera = renderizar(PAGINACION + "{{ paginacion(1, 21, base) }}", base=base)
|
||||
assert "Página 1 de 21" in primera
|
||||
assert [p for p in _paginas(primera) if p.strip()] == ["1", "2", "3", "4", "5", "…", "21"]
|
||||
assert (
|
||||
'href="/operaciones?titular=tercero&pagina=2" aria-label="Página siguiente"' in primera
|
||||
)
|
||||
assert 'aria-current="page">1<' in primera
|
||||
|
||||
media = renderizar(
|
||||
PAGINACION + "{{ paginacion(10, 21, base, total=1023, por_pagina=50) }}", base=base
|
||||
)
|
||||
assert [p for p in _paginas(media) if p.strip()] == [
|
||||
"1",
|
||||
"…",
|
||||
"8",
|
||||
"9",
|
||||
"10",
|
||||
"11",
|
||||
"12",
|
||||
"…",
|
||||
"21",
|
||||
]
|
||||
assert "Página 10 de 21 · 451–500 de 1,023" in media
|
||||
assert "pagina=3" not in media # solo la ventana alrededor de la página actual
|
||||
|
||||
ultima = renderizar(
|
||||
PAGINACION + "{{ paginacion(21, 21, base, total=1023, por_pagina=50) }}", base=base
|
||||
)
|
||||
assert "1,001–1,023 de 1,023" in ultima and 'aria-label="Página siguiente"' not in ultima
|
||||
|
||||
|
||||
def test_paginacion_de_una_pagina_no_pinta_nada() -> None:
|
||||
assert renderizar(PAGINACION + '{{ paginacion(1, 1, "/x?pagina=") }}').strip() == ""
|
||||
assert "Página 1 de 1" in renderizar(
|
||||
PAGINACION + '{{ paginacion(1, 1, "/x?pagina=", siempre=True) }}'
|
||||
)
|
||||
|
||||
|
||||
def test_pestanas_y_cifra() -> None:
|
||||
pestanas = renderizar(
|
||||
'{% from "_componentes/pestanas.html" import pestanas %}'
|
||||
'{{ pestanas([("alertas", "Alertas", "/alertas"), ("casos", "Casos", "/casos", 3)],'
|
||||
' "casos") }}'
|
||||
)
|
||||
assert '<a href="/alertas"><span>Alertas</span></a>' in pestanas
|
||||
assert '<a href="/casos" aria-current="page"><span>Casos</span><small>3</small></a>' in pestanas
|
||||
|
||||
cifra = renderizar(
|
||||
'{% from "_componentes/cifra.html" import cifra %}'
|
||||
'{{ cifra("Activos", 12, nota="80%", href="/creditos?status=activo", seleccionada=True) }}'
|
||||
'{{ cifra("Total", 15) }}'
|
||||
)
|
||||
assert (
|
||||
'<a class="resumen__cifra es-seleccionada" href="/creditos?status=activo"'
|
||||
' aria-current="true">' in cifra
|
||||
)
|
||||
assert "<strong>12</strong><small>80%</small>" in cifra
|
||||
assert '<div class="resumen__cifra">' in cifra and "<strong>15</strong>" in cifra
|
||||
Reference in new issue
Block a user