feat(plataforma): consola con la vista de empresas, indicadores y ficha por empresa
Bloque 2 de la Pieza L. La consola ve empresas, no clientes: - Indicadores de plataforma: empresas activas y suspendidas, clientes totales, cargas del periodo, empresas con periodo de carga vencido y alertas abiertas. - Tabla de empresas (nombre, RFC, giro, plan, estado, alta, usuarios activos, clientes, última carga con su resultado y aviso de periodo vencido, alertas abiertas, metodología vigente) con búsqueda por nombre o RFC, filtros por giro, estado y periodo vencido y orden por columna. /plataforma/api/empresas da las mismas filas en JSON. - Ficha de empresa: datos, usuarios, historial de cargas solo con metadatos, metodología con su historial y su parte de la bitácora de plataforma. Todo sale de consultas de conteo agrupadas por tenant_id (services/plataforma.py); la prueba busca en el HTML y el JSON cada nombre, RFC, CURP e identificador de los clientes de la base de prueba y exige que no aparezca ninguno.
This commit is contained in:
1 parent
8a55270503
commit
1ef9fafc3e
8 files changed
+774
-15
No files matched your search
@@ -9,12 +9,12 @@ ni datos personales. Las consultas salen de `services/plataforma.py`.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
||||
from starlette.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
|
||||
from app.auth import (
|
||||
RUTA_ACCESO_PLATAFORMA,
|
||||
@@ -27,7 +27,7 @@ from app.auth import (
|
||||
sesion_plataforma_opcional,
|
||||
)
|
||||
from app.db import get_db
|
||||
from app.models import Tenant
|
||||
from app.importers.plantillas import GIROS
|
||||
from app.models.plataforma import UsuarioPlataforma
|
||||
from app.routers import render
|
||||
from app.services import plataforma as servicio
|
||||
@@ -162,11 +162,73 @@ def activar(
|
||||
# --- Consola (exige administrador) ------------------------------------------------------------
|
||||
|
||||
|
||||
Direccion = Literal["asc", "desc"]
|
||||
|
||||
|
||||
@protegido.get(RUTA_CONSOLA, include_in_schema=False)
|
||||
def consola(request: Request, db: Annotated[Session, Depends(get_db)]) -> HTMLResponse:
|
||||
# Solo conteos: la consola nunca lista clientes ni sus datos.
|
||||
empresas = db.scalar(select(func.count()).select_from(Tenant)) or 0
|
||||
return _pantalla(request, "plataforma/index.html", {"total_empresas": empresas})
|
||||
def consola(
|
||||
request: Request,
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
q: str | None = None,
|
||||
giro: str | None = None,
|
||||
estado: str | None = None,
|
||||
vencido: bool = False,
|
||||
orden: str = "nombre",
|
||||
dir: Direccion = "asc",
|
||||
) -> HTMLResponse:
|
||||
"""Vista de empresas: indicadores de plataforma y la tabla con búsqueda, filtros y orden.
|
||||
Solo conteos por empresa: la consola nunca lista clientes ni sus datos."""
|
||||
orden = orden if orden in servicio.ORDENES else "nombre"
|
||||
empresas = servicio.empresas(
|
||||
db, q=q, giro=giro, estado=estado, vencido=vencido, orden=orden, direccion=dir
|
||||
)
|
||||
filtros = {k: v for k, v in (("q", q), ("giro", giro), ("estado", estado)) if v}
|
||||
if vencido:
|
||||
filtros["vencido"] = "1"
|
||||
consulta = urlencode(filtros) + ("&" if filtros else "")
|
||||
return _pantalla(
|
||||
request,
|
||||
"plataforma/index.html",
|
||||
{
|
||||
"empresas": empresas,
|
||||
"indicadores": servicio.indicadores(db, servicio.empresas(db)),
|
||||
"giros": sorted(GIROS),
|
||||
"q": q,
|
||||
"giro": giro,
|
||||
"estado": estado,
|
||||
"vencido": vencido,
|
||||
"orden": orden,
|
||||
"direccion": dir,
|
||||
"consulta": consulta,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@protegido.get("/plataforma/api/empresas", include_in_schema=False)
|
||||
def api_empresas(
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
q: str | None = None,
|
||||
giro: str | None = None,
|
||||
estado: str | None = None,
|
||||
vencido: bool = False,
|
||||
orden: str = "nombre",
|
||||
dir: Direccion = "asc",
|
||||
) -> JSONResponse:
|
||||
"""Las mismas filas de la tabla, en JSON (solo agregados por empresa)."""
|
||||
filas = servicio.empresas(
|
||||
db, q=q, giro=giro, estado=estado, vencido=vencido, orden=orden, direccion=dir
|
||||
)
|
||||
return JSONResponse({"empresas": [f.como_dict() for f in filas]})
|
||||
|
||||
|
||||
@protegido.get("/plataforma/empresas/{tenant_id}", include_in_schema=False)
|
||||
def empresa(
|
||||
request: Request, tenant_id: int, db: Annotated[Session, Depends(get_db)]
|
||||
) -> HTMLResponse:
|
||||
ficha = servicio.ficha(db, tenant_id)
|
||||
if ficha is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Empresa no encontrada.")
|
||||
return _pantalla(request, "plataforma/empresa.html", {"ficha": ficha})
|
||||
|
||||
|
||||
router.include_router(protegido)
|
||||
+275
-3
@@ -13,6 +13,11 @@ la escribe en logs: la base conserva solo el SHA-256 del token. Al abrirla, el a
|
||||
define su contraseña (mínimo `LARGO_MINIMO_CONTRASENA` caracteres). Si el correo ya existe y no
|
||||
se activó, el comando emite una liga nueva y la anterior deja de servir; si ya está activo, no
|
||||
hace nada. Los siguientes administradores se dan de alta desde la consola.
|
||||
|
||||
La consola ve EMPRESAS, no CLIENTES: `empresas`, `indicadores` y `ficha` devuelven conteos,
|
||||
fechas y estados por empresa (consultas `count` agrupadas por `tenant_id`), nunca filas de
|
||||
clientes ni montos individuales. La única excepción son los usuarios de la empresa (nombre,
|
||||
correo, rol), que no son datos de clientes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,16 +28,18 @@ import logging
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import audit
|
||||
from app.auth import hashear_contrasena, verificar_contrasena
|
||||
from app.models import ahora_utc
|
||||
from app.models import Alerta, Cliente, LoteCarga, ModeloRiesgo, Tenant, Usuario, ahora_utc
|
||||
from app.models.plataforma import BitacoraPlataforma, UsuarioPlataforma
|
||||
from app.models.tenant import ESTADO_ACTIVA, ESTADO_SUSPENDIDA
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -229,6 +236,271 @@ def registrar_ingreso(session: Session, administrador: UsuarioPlataforma) -> Non
|
||||
)
|
||||
|
||||
|
||||
# --- Consola: empresas y cifras (solo agregados; nunca datos de clientes) ----------------------
|
||||
|
||||
ORDENES = (
|
||||
"nombre",
|
||||
"rfc",
|
||||
"giro",
|
||||
"plan",
|
||||
"estado",
|
||||
"fecha_alta",
|
||||
"usuarios_activos",
|
||||
"clientes",
|
||||
"ultima_carga",
|
||||
"alertas_abiertas",
|
||||
"metodologia",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UltimaCarga:
|
||||
"""Metadatos del último lote del módulo 1: fecha, quién, archivo, estado y conteos."""
|
||||
|
||||
fecha: datetime
|
||||
usuario: str
|
||||
archivo: str | None
|
||||
estado: str | None
|
||||
total: int | None
|
||||
aceptadas: int | None
|
||||
rechazadas: int | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilaEmpresa:
|
||||
id: int
|
||||
clave: str | None
|
||||
nombre: str
|
||||
rfc: str | None
|
||||
giro: str
|
||||
plan: str | None
|
||||
estado: str
|
||||
fecha_alta: datetime
|
||||
usuarios_activos: int
|
||||
clientes: int
|
||||
ultima_carga: UltimaCarga | None
|
||||
periodo_vencido: bool
|
||||
alertas_abiertas: int
|
||||
metodologia: str | None
|
||||
|
||||
def como_dict(self) -> dict[str, Any]:
|
||||
return audit.a_json(asdict(self))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Indicadores:
|
||||
empresas_activas: int
|
||||
empresas_suspendidas: int
|
||||
clientes: int
|
||||
cargas_del_periodo: int
|
||||
empresas_periodo_vencido: int
|
||||
alertas_abiertas: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FichaEmpresa:
|
||||
empresa: FilaEmpresa
|
||||
usuarios: list[dict[str, Any]]
|
||||
cargas: list[UltimaCarga]
|
||||
metodologias: list[dict[str, Any]]
|
||||
bitacora: list[BitacoraPlataforma]
|
||||
|
||||
|
||||
def _conteo_por_tenant(session: Session, columna_tenant, *condiciones) -> dict[int, int]:
|
||||
filas = session.execute(
|
||||
select(columna_tenant, func.count()).where(*condiciones).group_by(columna_tenant)
|
||||
)
|
||||
return {tenant_id: n for tenant_id, n in filas}
|
||||
|
||||
|
||||
def _lotes_del_modulo(session: Session, tenant_id: int | None = None):
|
||||
from app.services.operaciones import CARGADOS, TIPO_LOTE
|
||||
|
||||
consulta = select(LoteCarga).where(LoteCarga.tipo == TIPO_LOTE, LoteCarga.estado.in_(CARGADOS))
|
||||
if tenant_id is not None:
|
||||
consulta = consulta.where(LoteCarga.tenant_id == tenant_id)
|
||||
return session.scalars(consulta.order_by(LoteCarga.created_at.desc(), LoteCarga.id.desc()))
|
||||
|
||||
|
||||
def _metadatos(lote: LoteCarga) -> UltimaCarga:
|
||||
carga = (lote.filas or {}).get("carga") or {}
|
||||
return UltimaCarga(
|
||||
fecha=lote.created_at,
|
||||
usuario=lote.usuario,
|
||||
archivo=lote.nombre_archivo,
|
||||
estado=lote.estado,
|
||||
total=carga.get("total"),
|
||||
aceptadas=carga.get("aceptadas"),
|
||||
rechazadas=carga.get("rechazadas"),
|
||||
)
|
||||
|
||||
|
||||
def _metodologias_vigentes(session: Session) -> dict[int, str]:
|
||||
vigentes: dict[int, tuple[date, str]] = {}
|
||||
for modelo in session.scalars(
|
||||
select(ModeloRiesgo).where(
|
||||
ModeloRiesgo.valid_to.is_(None), ModeloRiesgo.validacion_omitida.is_(False)
|
||||
)
|
||||
):
|
||||
actual = vigentes.get(modelo.tenant_id)
|
||||
if actual is None or modelo.vigente_desde > actual[0]:
|
||||
vigentes[modelo.tenant_id] = (modelo.vigente_desde, modelo.version)
|
||||
return {tenant_id: version for tenant_id, (_, version) in vigentes.items()}
|
||||
|
||||
|
||||
def _vencida(ultima: UltimaCarga | None, periodo_meses: int | None, hoy: date) -> bool:
|
||||
"""Misma regla que `services.operaciones.carga_vencida`, sobre el lote ya leído."""
|
||||
from app import fechas
|
||||
from app.engine.aggregates import restar_meses
|
||||
|
||||
if ultima is None:
|
||||
return True
|
||||
return fechas.fecha_en_mexico(ultima.fecha) < restar_meses(hoy, periodo_meses or 1)
|
||||
|
||||
|
||||
def empresas(
|
||||
session: Session,
|
||||
*,
|
||||
q: str | None = None,
|
||||
giro: str | None = None,
|
||||
estado: str | None = None,
|
||||
vencido: bool = False,
|
||||
orden: str = "nombre",
|
||||
direccion: str = "asc",
|
||||
hoy: date | None = None,
|
||||
) -> list[FilaEmpresa]:
|
||||
"""Una fila por empresa con sus cifras agregadas. Consultas de conteo, nunca de clientes."""
|
||||
from app import fechas
|
||||
from app.services.alertas import ESTADOS_ABIERTOS
|
||||
|
||||
hoy = hoy or fechas.hoy()
|
||||
usuarios = _conteo_por_tenant(session, Usuario.tenant_id, Usuario.activo.is_(True))
|
||||
clientes = _conteo_por_tenant(session, Cliente.tenant_id)
|
||||
alertas = _conteo_por_tenant(session, Alerta.tenant_id, Alerta.estado.in_(ESTADOS_ABIERTOS))
|
||||
metodologias = _metodologias_vigentes(session)
|
||||
ultimas: dict[int, UltimaCarga] = {}
|
||||
for lote in _lotes_del_modulo(session):
|
||||
ultimas.setdefault(lote.tenant_id, _metadatos(lote))
|
||||
|
||||
filas = []
|
||||
for t in session.scalars(select(Tenant).order_by(Tenant.nombre)):
|
||||
ultima = ultimas.get(t.id)
|
||||
filas.append(
|
||||
FilaEmpresa(
|
||||
id=t.id,
|
||||
clave=t.clave,
|
||||
nombre=t.nombre,
|
||||
rfc=t.rfc,
|
||||
giro=t.giro,
|
||||
plan=t.plan,
|
||||
estado=t.estado,
|
||||
fecha_alta=t.created_at,
|
||||
usuarios_activos=usuarios.get(t.id, 0),
|
||||
clientes=clientes.get(t.id, 0),
|
||||
ultima_carga=ultima,
|
||||
periodo_vencido=_vencida(ultima, t.periodo_carga_meses, hoy),
|
||||
alertas_abiertas=alertas.get(t.id, 0),
|
||||
metodologia=metodologias.get(t.id),
|
||||
)
|
||||
)
|
||||
|
||||
if q:
|
||||
texto = q.strip().lower()
|
||||
filas = [f for f in filas if texto in f.nombre.lower() or texto in (f.rfc or "").lower()]
|
||||
if giro:
|
||||
filas = [f for f in filas if f.giro == giro]
|
||||
if estado:
|
||||
filas = [f for f in filas if f.estado == estado]
|
||||
if vencido:
|
||||
filas = [f for f in filas if f.periodo_vencido]
|
||||
if orden not in ORDENES:
|
||||
orden = "nombre"
|
||||
|
||||
def clave(f: FilaEmpresa):
|
||||
valor = (
|
||||
f.ultima_carga.fecha
|
||||
if orden == "ultima_carga" and f.ultima_carga
|
||||
else getattr(f, orden)
|
||||
)
|
||||
if orden == "ultima_carga" and f.ultima_carga is None:
|
||||
valor = None
|
||||
# Los nulos al final en cualquier dirección; el texto se compara sin mayúsculas.
|
||||
return (valor is None, valor.lower() if isinstance(valor, str) else valor or 0)
|
||||
|
||||
filas.sort(key=clave, reverse=(direccion == "desc"))
|
||||
return filas
|
||||
|
||||
|
||||
def indicadores(session: Session, filas: list[FilaEmpresa], hoy: date | None = None) -> Indicadores:
|
||||
from app import fechas
|
||||
from app.services.operaciones import CARGADOS, TIPO_LOTE
|
||||
|
||||
hoy = hoy or fechas.hoy()
|
||||
inicio_mes = fechas.inicio_del_dia_utc(date(hoy.year, hoy.month, 1))
|
||||
cargas_del_periodo = session.scalar(
|
||||
select(func.count(LoteCarga.id)).where(
|
||||
LoteCarga.tipo == TIPO_LOTE,
|
||||
LoteCarga.estado.in_(CARGADOS),
|
||||
LoteCarga.created_at >= inicio_mes,
|
||||
)
|
||||
)
|
||||
return Indicadores(
|
||||
empresas_activas=sum(1 for f in filas if f.estado == ESTADO_ACTIVA),
|
||||
empresas_suspendidas=sum(1 for f in filas if f.estado == ESTADO_SUSPENDIDA),
|
||||
clientes=sum(f.clientes for f in filas),
|
||||
cargas_del_periodo=cargas_del_periodo or 0,
|
||||
empresas_periodo_vencido=sum(1 for f in filas if f.periodo_vencido),
|
||||
alertas_abiertas=sum(f.alertas_abiertas for f in filas),
|
||||
)
|
||||
|
||||
|
||||
def ficha(session: Session, tenant_id: int, hoy: date | None = None) -> FichaEmpresa | None:
|
||||
"""La empresa con sus usuarios, el historial de cargas (solo metadatos), sus metodologías y
|
||||
su parte de la bitácora de plataforma. `None` si no existe."""
|
||||
empresa = next((f for f in empresas(session, hoy=hoy) if f.id == tenant_id), None)
|
||||
if empresa is None:
|
||||
return None
|
||||
usuarios = [
|
||||
{
|
||||
"id": u.id,
|
||||
"usuario": u.usuario,
|
||||
"nombre": u.nombre,
|
||||
"correo": u.correo,
|
||||
"rol": u.rol.value if hasattr(u.rol, "value") else u.rol,
|
||||
"ultimo_ingreso": u.ultimo_ingreso,
|
||||
"activo": u.activo,
|
||||
}
|
||||
for u in session.scalars(
|
||||
select(Usuario).where(Usuario.tenant_id == tenant_id).order_by(Usuario.usuario)
|
||||
)
|
||||
]
|
||||
cargas = [_metadatos(lote) for lote in _lotes_del_modulo(session, tenant_id)]
|
||||
metodologias = [
|
||||
{
|
||||
"version": m.version,
|
||||
"nombre": m.nombre,
|
||||
"vigente_desde": m.vigente_desde,
|
||||
"valid_to": m.valid_to,
|
||||
"aprobado_por": m.aprobado_por,
|
||||
"validacion_omitida": m.validacion_omitida,
|
||||
}
|
||||
for m in session.scalars(
|
||||
select(ModeloRiesgo)
|
||||
.where(ModeloRiesgo.tenant_id == tenant_id)
|
||||
.order_by(ModeloRiesgo.vigente_desde.desc(), ModeloRiesgo.id.desc())
|
||||
)
|
||||
]
|
||||
bitacora = list(
|
||||
session.scalars(
|
||||
select(BitacoraPlataforma)
|
||||
.where(BitacoraPlataforma.tenant_id == tenant_id)
|
||||
.order_by(BitacoraPlataforma.id.desc())
|
||||
.limit(200)
|
||||
)
|
||||
)
|
||||
return FichaEmpresa(empresa, usuarios, cargas, metodologias, bitacora)
|
||||
|
||||
|
||||
# --- Comando ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -1069,3 +1069,16 @@ textarea.campo__entrada--compacta { min-height: 84px; padding: 10px 12px; }
|
||||
.consola__cifras dt { font-size: 12px; color: var(--color-texto-suave); text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.consola__cifras dd { margin: 4px 0 0; font-family: var(--fuente-mono); font-size: 24px; font-weight: 600; }
|
||||
.acceso__texto { font-size: 14px; color: var(--color-texto-cuerpo); text-align: center; }
|
||||
.consola__filtros { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 14px 20px; border-bottom: 1px solid var(--color-borde-suave); }
|
||||
.consola__filtros .campo__entrada { height: 36px; width: auto; min-width: 180px; }
|
||||
.consola__casilla { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--color-texto-cuerpo); }
|
||||
.consola__orden { color: inherit; text-decoration: none; }
|
||||
.consola__orden.es-activo { color: var(--color-verde-texto); }
|
||||
.consola__total { font-size: 13px; color: var(--color-texto-suave); }
|
||||
.consola__migas { font-size: 13px; color: var(--color-texto-suave); }
|
||||
.consola__migas a { color: inherit; }
|
||||
.consola__datos { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px 20px; padding: 16px 20px; margin: 0; }
|
||||
.consola__datos dt { font-size: 12px; color: var(--color-texto-suave); text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.consola__datos dd { margin: 4px 0 0; font-size: 15px; }
|
||||
.consola__cifras dd.es-vencido { color: var(--tono-peligro); }
|
||||
tr.es-suspendida th, tr.es-suspendida td { color: var(--color-texto-suave); }
|
||||
@@ -0,0 +1,95 @@
|
||||
{% extends "plataforma/_base.html" %}
|
||||
{% from "_componentes/tarjeta.html" import tarjeta %}
|
||||
|
||||
{% block titulo %}{{ ficha.empresa.nombre }}{% endblock %}
|
||||
|
||||
{% block consola %}
|
||||
{% set e = ficha.empresa %}
|
||||
<p class="consola__migas"><a href="/plataforma">Empresas</a> › {{ e.nombre }}</p>
|
||||
<h1 class="consola__titulo">{{ e.nombre }}
|
||||
<span class="badge badge--{{ 'exito' if e.estado == 'activa' else 'neutro' }}">{{ e.estado | capitalize }}</span>
|
||||
</h1>
|
||||
|
||||
{% call tarjeta("Datos de la empresa", id="datos") %}
|
||||
<dl class="consola__datos" data-datos-empresa>
|
||||
<div><dt>RFC</dt><dd class="mono">{{ e.rfc or "—" }}</dd></div>
|
||||
<div><dt>Giro</dt><dd>{{ e.giro | capitalize }}</dd></div>
|
||||
<div><dt>Plan</dt><dd>{{ e.plan or "—" }}</dd></div>
|
||||
<div><dt>Alta</dt><dd>{{ e.fecha_alta | mx }}</dd></div>
|
||||
<div><dt>Clientes</dt><dd data-cifra="clientes">{{ e.clientes }}</dd></div>
|
||||
<div><dt>Alertas abiertas</dt><dd data-cifra="alertas_abiertas">{{ e.alertas_abiertas }}</dd></div>
|
||||
<div><dt>Metodología vigente</dt><dd>{{ e.metodologia or "Sin modelo" }}</dd></div>
|
||||
<div><dt>Periodo de carga</dt><dd>{% if e.periodo_vencido %}<span class="badge badge--peligro">Vencido</span>{% else %}Al corriente{% endif %}</dd></div>
|
||||
</dl>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Usuarios", plano=True, id="usuarios") %}
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla tabla--densa" data-tabla-usuarios>
|
||||
<thead><tr><th scope="col">Usuario</th><th scope="col">Nombre</th><th scope="col">Correo</th><th scope="col">Rol</th><th scope="col">Último ingreso</th><th scope="col">Estado</th></tr></thead>
|
||||
<tbody>
|
||||
{% for u in ficha.usuarios %}
|
||||
<tr data-usuario="{{ u.id }}">
|
||||
<th scope="row">{{ u.usuario }}</th>
|
||||
<td>{{ u.nombre or "—" }}</td>
|
||||
<td>{{ u.correo or "—" }}</td>
|
||||
<td>{{ u.rol }}</td>
|
||||
<td>{{ u.ultimo_ingreso | mx if u.ultimo_ingreso else "Nunca" }}</td>
|
||||
<td>{{ "Activo" if u.activo else "Desactivado" }}</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="6" class="tabla__vacio">Sin usuarios.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Historial de cargas", subtitulo="Solo metadatos: fecha, quién, archivo, conteos y resultado", plano=True, id="cargas") %}
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla tabla--densa" data-tabla-cargas>
|
||||
<thead><tr><th scope="col">Fecha</th><th scope="col">Quién</th><th scope="col">Archivo</th><th scope="col" class="es-der">Filas</th><th scope="col" class="es-der">Aceptadas</th><th scope="col" class="es-der">Rechazadas</th><th scope="col">Resultado</th></tr></thead>
|
||||
<tbody>
|
||||
{% for c in ficha.cargas %}
|
||||
<tr>
|
||||
<td>{{ c.fecha | mx }}</td><td>{{ c.usuario }}</td><td>{{ c.archivo or "—" }}</td>
|
||||
<td class="es-der">{{ c.total if c.total is not none else "—" }}</td>
|
||||
<td class="es-der">{{ c.aceptadas if c.aceptadas is not none else "—" }}</td>
|
||||
<td class="es-der">{{ c.rechazadas if c.rechazadas is not none else "—" }}</td>
|
||||
<td>{{ c.estado }}</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="7" class="tabla__vacio">Sin cargas por el módulo de carga de información.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Metodología", subtitulo="Versión vigente e historial", plano=True, id="metodologia") %}
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla tabla--densa" data-tabla-metodologias>
|
||||
<thead><tr><th scope="col">Versión</th><th scope="col">Nombre</th><th scope="col">Vigente desde</th><th scope="col">Hasta</th><th scope="col">Aprobó</th></tr></thead>
|
||||
<tbody>
|
||||
{% for m in ficha.metodologias %}
|
||||
<tr{% if not m.valid_to and not m.validacion_omitida %} class="es-vigente"{% endif %}>
|
||||
<th scope="row">{{ m.version }}</th><td>{{ m.nombre }}</td>
|
||||
<td>{{ m.vigente_desde | mx("%d/%m/%Y") }}</td>
|
||||
<td>{{ m.valid_to | mx if m.valid_to else "Vigente" }}</td>
|
||||
<td>{{ m.aprobado_por }}</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="5" class="tabla__vacio">Sin modelo de riesgo.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endcall %}
|
||||
|
||||
{% call tarjeta("Bitácora de plataforma", subtitulo="Acciones de la plataforma sobre esta empresa", plano=True, id="bitacora") %}
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla tabla--densa" data-tabla-bitacora>
|
||||
<thead><tr><th scope="col">Fecha</th><th scope="col">Quién</th><th scope="col">Acción</th><th scope="col">Motivo</th></tr></thead>
|
||||
<tbody>
|
||||
{% for b in ficha.bitacora %}
|
||||
<tr><td>{{ b.fecha | mx }}</td><td>{{ b.usuario }}</td><td class="mono">{{ b.accion }}</td><td>{{ b.motivo or "—" }}</td></tr>
|
||||
{% else %}<tr><td colspan="4" class="tabla__vacio">Sin acciones registradas.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endcall %}
|
||||
{% endblock %}
|
||||
@@ -3,11 +3,88 @@
|
||||
|
||||
{% block titulo %}Empresas{% endblock %}
|
||||
|
||||
{#- Enlace de orden de una columna: alterna asc/desc y conserva los filtros. -#}
|
||||
{%- macro orden_enlace(clave, titulo) -%}
|
||||
{%- set activa = orden == clave -%}
|
||||
{%- set dir = "desc" if activa and direccion == "asc" else "asc" -%}
|
||||
<a class="consola__orden{% if activa %} es-activo{% endif %}" data-orden="{{ clave }}"
|
||||
href="/plataforma?{{ consulta }}orden={{ clave }}&dir={{ dir }}">{{ titulo }}{% if activa %} {{ "▲" if direccion == "asc" else "▼" }}{% endif %}</a>
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block consola %}
|
||||
<h1 class="consola__titulo">Empresas</h1>
|
||||
{% call tarjeta("Plataforma", subtitulo="Cifras agregadas; la consola no muestra datos de clientes") %}
|
||||
<dl class="consola__cifras">
|
||||
<div><dt>Empresas</dt><dd data-cifra="empresas">{{ total_empresas }}</dd></div>
|
||||
|
||||
{% call tarjeta("Plataforma", subtitulo="Cifras agregadas de todas las empresas; la consola no muestra datos de clientes") %}
|
||||
<dl class="consola__cifras" data-indicadores>
|
||||
<div><dt>Empresas activas</dt><dd data-cifra="empresas_activas">{{ indicadores.empresas_activas }}</dd></div>
|
||||
<div><dt>Suspendidas</dt><dd data-cifra="empresas_suspendidas">{{ indicadores.empresas_suspendidas }}</dd></div>
|
||||
<div><dt>Clientes totales</dt><dd data-cifra="clientes">{{ indicadores.clientes }}</dd></div>
|
||||
<div><dt>Cargas del periodo</dt><dd data-cifra="cargas_del_periodo">{{ indicadores.cargas_del_periodo }}</dd></div>
|
||||
<div><dt>Con periodo de carga vencido</dt><dd data-cifra="empresas_periodo_vencido"{% if indicadores.empresas_periodo_vencido %} class="es-vencido"{% endif %}>{{ indicadores.empresas_periodo_vencido }}</dd></div>
|
||||
<div><dt>Alertas abiertas</dt><dd data-cifra="alertas_abiertas">{{ indicadores.alertas_abiertas }}</dd></div>
|
||||
</dl>
|
||||
{% endcall %}
|
||||
|
||||
{% set acciones %}<span class="consola__total" data-total-empresas="{{ empresas | length }}">{{ empresas | length }} empresa{{ "s" if empresas | length != 1 }}</span>{% endset %}
|
||||
{% call tarjeta("Empresas", acciones=acciones, plano=True) %}
|
||||
<form class="consola__filtros" method="get" action="/plataforma">
|
||||
<input class="campo__entrada" type="search" name="q" value="{{ q or '' }}" placeholder="Nombre o RFC" aria-label="Buscar por nombre o RFC">
|
||||
<select class="campo__entrada" name="giro" aria-label="Giro">
|
||||
<option value="">Todos los giros</option>
|
||||
{% for g in giros %}<option value="{{ g }}"{% if g == giro %} selected{% endif %}>{{ g | capitalize }}</option>{% endfor %}
|
||||
</select>
|
||||
<select class="campo__entrada" name="estado" aria-label="Estado">
|
||||
<option value="">Activas y suspendidas</option>
|
||||
<option value="activa"{% if estado == "activa" %} selected{% endif %}>Activas</option>
|
||||
<option value="suspendida"{% if estado == "suspendida" %} selected{% endif %}>Suspendidas</option>
|
||||
</select>
|
||||
<label class="consola__casilla"><input type="checkbox" name="vencido" value="1"{% if vencido %} checked{% endif %}> Solo con periodo vencido</label>
|
||||
<input type="hidden" name="orden" value="{{ orden }}"><input type="hidden" name="dir" value="{{ direccion }}">
|
||||
<button class="boton boton--mediano" type="submit">Filtrar</button>
|
||||
{% if q or giro or estado or vencido %}<a class="boton boton--mediano" href="/plataforma">Quitar filtros</a>{% endif %}
|
||||
</form>
|
||||
<div class="tabla-contenedor">
|
||||
<table class="tabla tabla--densa" data-tabla-empresas>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ orden_enlace("nombre", "Empresa") }}</th>
|
||||
<th scope="col">{{ orden_enlace("rfc", "RFC") }}</th>
|
||||
<th scope="col">{{ orden_enlace("giro", "Giro") }}</th>
|
||||
<th scope="col">{{ orden_enlace("plan", "Plan") }}</th>
|
||||
<th scope="col">{{ orden_enlace("estado", "Estado") }}</th>
|
||||
<th scope="col">{{ orden_enlace("fecha_alta", "Alta") }}</th>
|
||||
<th scope="col" class="es-der">{{ orden_enlace("usuarios_activos", "Usuarios") }}</th>
|
||||
<th scope="col" class="es-der">{{ orden_enlace("clientes", "Clientes") }}</th>
|
||||
<th scope="col">{{ orden_enlace("ultima_carga", "Última carga") }}</th>
|
||||
<th scope="col" class="es-der">{{ orden_enlace("alertas_abiertas", "Alertas abiertas") }}</th>
|
||||
<th scope="col">{{ orden_enlace("metodologia", "Metodología") }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for e in empresas %}
|
||||
<tr data-empresa="{{ e.id }}"{% if e.estado == "suspendida" %} class="es-suspendida"{% endif %}>
|
||||
<th scope="row"><a href="/plataforma/empresas/{{ e.id }}">{{ e.nombre }}</a></th>
|
||||
<td class="mono">{{ e.rfc or "—" }}</td>
|
||||
<td>{{ e.giro | capitalize }}</td>
|
||||
<td>{{ e.plan or "—" }}</td>
|
||||
<td><span class="badge badge--{{ 'exito' if e.estado == 'activa' else 'neutro' }}">{{ e.estado | capitalize }}</span></td>
|
||||
<td>{{ e.fecha_alta | mx("%d/%m/%Y") }}</td>
|
||||
<td class="es-der">{{ e.usuarios_activos }}</td>
|
||||
<td class="es-der" data-clientes>{{ e.clientes }}</td>
|
||||
<td>
|
||||
{% if e.ultima_carga %}
|
||||
{{ e.ultima_carga.fecha | mx }} · {{ e.ultima_carga.estado }}{% if e.ultima_carga.rechazadas %} · {{ e.ultima_carga.rechazadas }} rechazadas{% endif %}
|
||||
{% else %}Sin cargas{% endif %}
|
||||
{% if e.periodo_vencido %}<span class="badge badge--peligro" data-periodo-vencido>Periodo vencido</span>{% endif %}
|
||||
</td>
|
||||
<td class="es-der" data-alertas>{{ e.alertas_abiertas }}</td>
|
||||
<td>{{ e.metodologia or "Sin modelo" }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="11" class="tabla__vacio">Sin empresas con esos filtros.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endcall %}
|
||||
{% endblock %}
|
||||
@@ -173,7 +173,7 @@ def test_acceso_correcto_crea_su_propia_cookie_y_deja_bitacora(
|
||||
consola = cliente.get("/plataforma")
|
||||
assert consola.status_code == 200
|
||||
assert "data-consola" in consola.text and '<nav class="nav"' not in consola.text
|
||||
assert 'data-cifra="empresas">1<' in consola.text
|
||||
assert 'data-cifra="empresas_activas">1<' in consola.text
|
||||
with fabrica() as sesion:
|
||||
admin = sesion.scalar(sa.select(UsuarioPlataforma))
|
||||
assert admin.ultimo_ingreso is not None
|
||||
@@ -221,6 +221,8 @@ RUTAS_PLATAFORMA = (
|
||||
"/plataforma/acceso",
|
||||
"/plataforma/salir",
|
||||
"/plataforma/activar/{token}",
|
||||
"/plataforma/api/empresas",
|
||||
"/plataforma/empresas/{tenant_id}",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Consola de plataforma (Pieza L, bloque 2): con dos empresas, los conteos coinciden con los de
|
||||
cada empresa vista desde adentro, y la respuesta (HTML y JSON) no contiene datos de clientes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.auth import RUTA_ACCESO_PLATAFORMA, hashear_contrasena
|
||||
from app.config import get_settings
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.importers.chm_schema import importar_esquema
|
||||
from app.main import crear_app
|
||||
from app.models import Alerta, Base, Cliente, Identificacion, Tenant, Usuario
|
||||
from app.models.tenant import ESTADO_SUSPENDIDA, Regimen
|
||||
from app.models.usuario import Rol
|
||||
from app.services import alertas as servicio_alertas
|
||||
from app.services import plataforma as servicio
|
||||
from app.services.alertas import ESTADOS_ABIERTOS
|
||||
from seed import identidades_sinteticas
|
||||
from seed.usuarios_demo import sembrar
|
||||
from tests.test_plataforma import CONTRASENA, CONTRASENAS, CORREO
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "esquema_mini.xlsx"
|
||||
RFC_OTRA = "OTR200101AB1"
|
||||
NOMBRE_OTRA = "Otra Financiera de Prueba, S.A. de C.V."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fabrica(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> sessionmaker[Session]:
|
||||
"""Dos empresas: la demo con la cartera mini (alertas incluidas) y «otra» con tres clientes."""
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
fabrica = crear_session_factory(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
||||
monkeypatch.setattr(get_settings(), "data_dir", tmp_path)
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
sesion.commit()
|
||||
importar_esquema(sesion, FIXTURE, "pytest", sal="sal-consola")
|
||||
identidades_sinteticas.sembrar(sesion, usuario="pytest")
|
||||
servicio_alertas.ejecutar_reglas(sesion, usuario="pytest")
|
||||
otra = Tenant(
|
||||
clave="otra",
|
||||
nombre=NOMBRE_OTRA,
|
||||
rfc=RFC_OTRA,
|
||||
plan="basico",
|
||||
regimen=Regimen.LFPIORPI,
|
||||
actividad_vulnerable="Art. 17 fracción IV",
|
||||
uma_vigente=Decimal("117.31"),
|
||||
fecha_corte=date(2026, 8, 31),
|
||||
created_by="pytest",
|
||||
)
|
||||
sesion.add(otra)
|
||||
sesion.flush()
|
||||
for usuario, activo in (("oficial", True), ("analista", True), ("auditor", False)):
|
||||
sesion.add(
|
||||
Usuario(
|
||||
tenant_id=otra.id,
|
||||
usuario=f"{usuario}-otra",
|
||||
nombre=f"Persona {usuario} de otra",
|
||||
correo=f"{usuario}@otra.test",
|
||||
rol=Rol(usuario),
|
||||
hash=hashear_contrasena("clave-de-otra-empresa-1"),
|
||||
activo=activo,
|
||||
created_by="pytest",
|
||||
)
|
||||
)
|
||||
for n in range(3):
|
||||
sesion.add(
|
||||
Cliente(
|
||||
tenant_id=otra.id,
|
||||
id_externo=f"otra-cliente-{n:04d}",
|
||||
tipo_persona="fisica",
|
||||
created_by="pytest",
|
||||
)
|
||||
)
|
||||
_, token = servicio.crear_administrador(sesion, CORREO, "Admin de prueba")
|
||||
sesion.flush()
|
||||
servicio.activar(sesion, token, CONTRASENA, CONTRASENA)
|
||||
sesion.commit()
|
||||
return fabrica
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cliente(fabrica: sessionmaker[Session]) -> Iterator[TestClient]:
|
||||
with TestClient(crear_app(), follow_redirects=False) as c:
|
||||
r = c.post(RUTA_ACCESO_PLATAFORMA, data={"correo": CORREO, "contrasena": CONTRASENA})
|
||||
assert r.status_code == 303
|
||||
yield c
|
||||
|
||||
|
||||
def ids(fabrica: sessionmaker[Session]) -> dict[str, int]:
|
||||
with fabrica() as sesion:
|
||||
return {t.clave: t.id for t in sesion.scalars(sa.select(Tenant))}
|
||||
|
||||
|
||||
def conteos_desde_adentro(fabrica: sessionmaker[Session], tenant_id: int) -> dict[str, int]:
|
||||
"""Lo que la empresa ve en sus propias pantallas: la misma consulta que /cartera y /alertas."""
|
||||
with fabrica() as sesion:
|
||||
return {
|
||||
"clientes": sesion.scalar(
|
||||
sa.select(sa.func.count(Cliente.id)).where(Cliente.tenant_id == tenant_id)
|
||||
),
|
||||
"alertas_abiertas": sesion.scalar(
|
||||
sa.select(sa.func.count(Alerta.id)).where(
|
||||
Alerta.tenant_id == tenant_id, Alerta.estado.in_(ESTADOS_ABIERTOS)
|
||||
)
|
||||
),
|
||||
"usuarios_activos": sesion.scalar(
|
||||
sa.select(sa.func.count(Usuario.id)).where(
|
||||
Usuario.tenant_id == tenant_id, Usuario.activo.is_(True)
|
||||
)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def datos_de_clientes(fabrica: sessionmaker[Session]) -> set[str]:
|
||||
"""Nombres, RFC, CURP e identificadores de todos los clientes de la base de prueba."""
|
||||
valores: set[str] = set()
|
||||
with fabrica() as sesion:
|
||||
valores.update(sesion.scalars(sa.select(Cliente.id_externo)))
|
||||
for nombre, datos in sesion.execute(
|
||||
sa.select(Identificacion.nombre_busqueda, Identificacion.datos)
|
||||
):
|
||||
if nombre:
|
||||
valores.add(nombre)
|
||||
for clave in ("nombre", "apellido_paterno", "razon_social", "rfc", "curp"):
|
||||
if (datos or {}).get(clave):
|
||||
valores.add(str(datos[clave]))
|
||||
assert len(valores) > 20, "la base de prueba debería tener clientes con identificación"
|
||||
return {v for v in valores if len(v) >= 4}
|
||||
|
||||
|
||||
# --- Conteos ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_los_conteos_de_la_consola_coinciden_con_los_de_cada_empresa(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
html = cliente.get("/plataforma").text
|
||||
datos = cliente.get("/plataforma/api/empresas").json()["empresas"]
|
||||
assert {e["clave"] for e in datos} == {"demo", "otra"}
|
||||
total = {"clientes": 0, "alertas_abiertas": 0}
|
||||
for empresa in datos:
|
||||
adentro = conteos_desde_adentro(fabrica, empresa["id"])
|
||||
assert adentro["clientes"] > 0
|
||||
for clave, valor in adentro.items():
|
||||
assert empresa[clave] == valor, (empresa["clave"], clave)
|
||||
total["clientes"] += adentro["clientes"]
|
||||
total["alertas_abiertas"] += adentro["alertas_abiertas"]
|
||||
fila = re.search(rf'<tr data-empresa="{empresa["id"]}".*?</tr>', html, re.S).group(0)
|
||||
assert f'<td class="es-der" data-clientes>{adentro["clientes"]}</td>' in fila
|
||||
assert f'<td class="es-der" data-alertas>{adentro["alertas_abiertas"]}</td>' in fila
|
||||
demo = next(e for e in datos if e["clave"] == "demo")
|
||||
assert demo["alertas_abiertas"] > 0 and demo["metodologia"] == "v2"
|
||||
assert f'data-cifra="clientes">{total["clientes"]}<' in html
|
||||
assert f'data-cifra="alertas_abiertas">{total["alertas_abiertas"]}<' in html
|
||||
assert 'data-cifra="empresas_activas">2<' in html
|
||||
assert 'data-cifra="empresas_suspendidas">0<' in html
|
||||
# Ninguna de las dos ha cargado por el módulo 1: las dos tienen el periodo vencido.
|
||||
assert 'data-cifra="empresas_periodo_vencido"' in html
|
||||
assert html.count("data-periodo-vencido") == 2
|
||||
|
||||
|
||||
def test_la_ficha_muestra_usuarios_cargas_metodologia_y_bitacora(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
otra = ids(fabrica)["otra"]
|
||||
html = cliente.get(f"/plataforma/empresas/{otra}").text
|
||||
assert NOMBRE_OTRA in html and RFC_OTRA in html
|
||||
assert "oficial@otra.test" in html and "Persona auditor de otra" in html
|
||||
assert html.count('<tr data-usuario="') == 3 and "Desactivado" in html
|
||||
assert "Sin cargas por el módulo de carga de información." in html
|
||||
assert "Sin modelo de riesgo." in html
|
||||
assert "Sin acciones registradas." in html
|
||||
demo = ids(fabrica)["demo"]
|
||||
html_demo = cliente.get(f"/plataforma/empresas/{demo}").text
|
||||
assert '<th scope="row">v2</th>' in html_demo
|
||||
assert cliente.get("/plataforma/empresas/999").status_code == 404
|
||||
|
||||
|
||||
# --- Barrera: ningún dato de clientes ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_la_consola_no_contiene_ningun_dato_de_clientes(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
prohibidos = datos_de_clientes(fabrica)
|
||||
respuestas = [cliente.get("/plataforma").text, cliente.get("/plataforma/api/empresas").text]
|
||||
respuestas += [cliente.get(f"/plataforma/empresas/{i}").text for i in ids(fabrica).values()]
|
||||
for texto in respuestas:
|
||||
for valor in prohibidos:
|
||||
assert valor not in texto, valor
|
||||
filas = json.loads(respuestas[1])["empresas"]
|
||||
claves = set().union(*(f.keys() for f in filas))
|
||||
assert claves == set(servicio.FilaEmpresa.__dataclass_fields__)
|
||||
assert not claves & {"clientes_lista", "nombre_cliente", "curp", "montos"}
|
||||
|
||||
|
||||
# --- Búsqueda, filtros y orden ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_busqueda_filtros_y_orden(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
|
||||
def filas(**parametros) -> list[dict]:
|
||||
return cliente.get("/plataforma/api/empresas", params=parametros).json()["empresas"]
|
||||
|
||||
assert [f["clave"] for f in filas(q=RFC_OTRA.lower())] == ["otra"]
|
||||
assert [f["clave"] for f in filas(q="otra financiera")] == ["otra"]
|
||||
assert [f["clave"] for f in filas(giro="inmobiliario")] == []
|
||||
assert len(filas(giro="credito")) == 2
|
||||
assert [f["clave"] for f in filas(orden="clientes", dir="desc")][0] == "demo"
|
||||
assert [f["clave"] for f in filas(orden="clientes", dir="asc")][0] == "otra"
|
||||
assert [f["clave"] for f in filas(orden="inventado")] == ["demo", "otra"] # cae en nombre
|
||||
assert len(filas(vencido="1")) == 2
|
||||
|
||||
with fabrica() as sesion:
|
||||
otra = sesion.scalar(sa.select(Tenant).where(Tenant.clave == "otra"))
|
||||
otra.estado = ESTADO_SUSPENDIDA
|
||||
sesion.commit()
|
||||
assert [f["clave"] for f in filas(estado="suspendida")] == ["otra"]
|
||||
assert [f["clave"] for f in filas(estado="activa")] == ["demo"]
|
||||
html = cliente.get("/plataforma", params={"estado": "suspendida", "orden": "rfc"}).text
|
||||
assert 'data-total-empresas="1"' in html
|
||||
assert 'data-cifra="empresas_suspendidas">1<' in html # los indicadores no se filtran
|
||||
assert 'href="/plataforma?estado=suspendida&orden=rfc&dir=desc"' in html
|
||||
assert cliente.get("/plataforma", params={"dir": "lateral"}).status_code == 422
|
||||
@@ -168,6 +168,8 @@ def test_las_rutas_publicas_son_solo_las_esperadas() -> None:
|
||||
"/plataforma/acceso",
|
||||
"/plataforma/salir",
|
||||
"/plataforma/activar/{token}",
|
||||
"/plataforma/api/empresas",
|
||||
"/plataforma/empresas/{tenant_id}",
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user