142 lines
5.1 KiB
Python
142 lines
5.1 KiB
Python
"""Router `reglas`: las reglas de alerta de la empresa y su edición desde la pantalla.
|
|
|
|
- `GET /reglas`: las 21 reglas vigentes con su nivel, plazo, parámetros y versión (los tres roles).
|
|
- `GET /reglas/{clave}`: la regla vigente, el formulario de cambio (solo el oficial) y el historial
|
|
de versiones con la justificación de cada una.
|
|
- `POST /reglas/{clave}`: solo el oficial, con justificación. Nunca edita la versión vigente:
|
|
`services.alertas.editar_regla` la cierra y abre una nueva, y el cambio queda en el audit trail.
|
|
Las alertas ya creadas conservan la versión que las produjo.
|
|
|
|
Desde aquí se cambian el nivel, el plazo y los parámetros numéricos. Las listas (catálogos, tipos) y
|
|
los textos se cambian con el archivo de reglas (`--sincronizar-reglas`).
|
|
"""
|
|
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
|
|
from app.auth import requiere_rol
|
|
from app.db import get_db
|
|
from app.models import ReglaAlerta, Usuario
|
|
from app.models.usuario import Rol
|
|
from app.routers import render
|
|
from app.routers.expediente import leer_formulario
|
|
from app.services import alertas as servicio
|
|
from app.services.agregados import tenant_de_sesion
|
|
|
|
router = APIRouter(tags=["reglas"])
|
|
ROL_EDITA = Rol.OFICIAL
|
|
PREFIJO_PARAMETRO = "parametro_"
|
|
|
|
|
|
def _fila(regla: ReglaAlerta) -> dict[str, Any]:
|
|
parametros = servicio.parametros_de_regla(regla.parametros)
|
|
internos = dict(regla.parametros or {})
|
|
return {
|
|
"id": regla.id,
|
|
"clave": regla.clave,
|
|
"familia": regla.familia,
|
|
"nombre": regla.nombre,
|
|
"criterio_texto": regla.criterio_texto,
|
|
"nivel": regla.nivel,
|
|
"plazo_aviso": regla.plazo_aviso,
|
|
"tipo_evaluacion": regla.tipo_evaluacion,
|
|
"version": regla.version,
|
|
"vigente_desde": regla.vigente_desde,
|
|
"valid_to": regla.valid_to,
|
|
"aprobado_por": regla.aprobado_por,
|
|
"justificacion": internos.get("_justificacion"),
|
|
"sustituye_a": internos.get("_sustituye_a"),
|
|
"parametros": [
|
|
{"clave": k, "valor": v, "editable": servicio.es_parametro_editable(v)}
|
|
for k, v in parametros.items()
|
|
],
|
|
}
|
|
|
|
|
|
@router.get("/reglas", include_in_schema=False)
|
|
def lista(request: Request, db: Annotated[Session, Depends(get_db)]) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
vigentes = [
|
|
_fila(regla)
|
|
for v in servicio.reglas_vigentes(db, tenant)
|
|
if (regla := db.get(ReglaAlerta, v.id)) is not None
|
|
]
|
|
return render(
|
|
request,
|
|
"reglas/lista.html",
|
|
{"reglas": vigentes, "puede_editar": request.state.usuario.rol == ROL_EDITA},
|
|
)
|
|
|
|
|
|
def _detalle(
|
|
request: Request,
|
|
db: Session,
|
|
clave: str,
|
|
*,
|
|
error: str | None = None,
|
|
enviado: dict[str, str] | None = None,
|
|
status_code: int = 200,
|
|
) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
vigente = servicio.regla_vigente_de(db, tenant, clave)
|
|
if vigente is None:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "No existe esa regla.")
|
|
return render(
|
|
request,
|
|
"reglas/detalle.html",
|
|
{
|
|
"regla": _fila(vigente),
|
|
"historial": [_fila(r) for r in servicio.historial_de_regla(db, tenant, clave)],
|
|
"niveles": servicio.NIVELES_ALERTA,
|
|
"plazos": servicio.PLAZOS_REGLA,
|
|
"puede_editar": request.state.usuario.rol == ROL_EDITA,
|
|
"error": error,
|
|
"enviado": enviado or {},
|
|
"guardada": request.query_params.get("guardada"),
|
|
"largo_minimo": servicio.LARGO_MINIMO_MOTIVO_REGLAS,
|
|
},
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
@router.get("/reglas/{clave}", include_in_schema=False)
|
|
def detalle(request: Request, clave: str, db: Annotated[Session, Depends(get_db)]) -> HTMLResponse:
|
|
return _detalle(request, db, clave)
|
|
|
|
|
|
@router.post("/reglas/{clave}", include_in_schema=False)
|
|
def guardar(
|
|
request: Request,
|
|
clave: str,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(ROL_EDITA))],
|
|
form: Annotated[dict[str, Any], Depends(leer_formulario)],
|
|
) -> Response:
|
|
parametros = {
|
|
nombre.removeprefix(PREFIJO_PARAMETRO): valor
|
|
for nombre, valor in form.items()
|
|
if nombre.startswith(PREFIJO_PARAMETRO)
|
|
}
|
|
try:
|
|
with db.begin_nested():
|
|
nueva = servicio.editar_regla(
|
|
db,
|
|
clave,
|
|
nivel=form.get("nivel", ""),
|
|
plazo_aviso=form.get("plazo_aviso", ""),
|
|
parametros=parametros,
|
|
justificacion=form.get("justificacion", ""),
|
|
usuario=usuario.usuario,
|
|
)
|
|
except servicio.ReglaNoEncontradaError:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "No existe esa regla.") from None
|
|
except servicio.EdicionDeReglaError as exc:
|
|
return _detalle(request, db, clave, error=str(exc), enviado=form, status_code=400)
|
|
db.commit()
|
|
return RedirectResponse(
|
|
f"/reglas/{nueva.clave}?guardada={nueva.version}", status_code=status.HTTP_303_SEE_OTHER
|
|
)
|