feat: restringe soloAdmin (Bucefalo CRM) a agentes, default WhatsApp+fallbackEmail y archivado reversible

This commit is contained in:
urieljareth
2026-11-25 08:54:28 -06:00
parent 0d4f19f35d
commit 670265a390
31 changed files with 672 additions and 78 deletions
+74 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import re
import uuid
from datetime import datetime, timezone
@@ -32,6 +33,67 @@ def _cuid() -> str:
return uuid.uuid4().hex[:25]
_PATRON_BUCEFALO = re.compile(r"buc[eé]falo", re.IGNORECASE)
async def _validar_solo_admin_agente(
conn,
auth: dict,
servicios,
plan_bucefalo,
recurso_id: str | None = None,
) -> None:
"""Bloquea a agentes que intenten incluir servicios soloAdmin o planes de Bucéfalo CRM."""
if auth.get("auth_type") != "agent":
return
motivos: list[str] = []
if plan_bucefalo is not None:
motivos.append("planBucefalo")
servicios_lista = servicios or []
catalogo_ids = [
s.catalogoId
for s in servicios_lista
if getattr(s, "catalogoId", None)
and not s.catalogoId.startswith("custom-")
and not s.catalogoId.lower().startswith("bucefalo-")
]
solo_admin_ids: set[str] = set()
if catalogo_ids:
rows = await conn.fetch(
'SELECT id FROM "ServicioCatalogo" WHERE id = ANY($1::text[]) AND "soloAdmin" = true',
catalogo_ids,
)
solo_admin_ids = {r["id"] for r in rows}
for s in servicios_lista:
cid = (getattr(s, "catalogoId", "") or "").strip()
nombre = (getattr(s, "nombre", "") or "").strip()
if cid.lower().startswith("bucefalo-"):
motivos.append(f"catalogoId:{cid}")
elif cid in solo_admin_ids:
motivos.append(f"soloAdmin:{cid}")
elif _PATRON_BUCEFALO.search(nombre):
motivos.append(f"nombre:{nombre}")
if motivos:
await registrar_auditoria(
conn,
auth,
"cotizacion.servicio_solo_admin_bloqueado",
"cotizacion",
recurso_id=recurso_id,
exito=False,
detalle={"motivos": motivos},
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Los servicios restringidos al administrador (incluidos los planes de Bucefalo CRM) no pueden ser agregados por agentes",
)
async def _insert_servicio_cotizado(
conn,
cotizacion_id: str,
@@ -173,7 +235,7 @@ async def _resolve_bucefalo_servicio(conn) -> str | None:
async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, telefono: str) -> str:
row = await conn.fetchrow(
'SELECT id FROM "Cliente" WHERE nombre = $1 AND COALESCE(empresa, \'\') = $2',
'SELECT id FROM "Cliente" WHERE archivado = false AND nombre = $1 AND COALESCE(empresa, \'\') = $2',
nombre,
empresa or "",
)
@@ -211,6 +273,7 @@ async def list_cotizaciones(
q: str | None = Query(None),
desde: str | None = Query(None),
hasta: str | None = Query(None),
incluirArchivados: bool = Query(False),
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
):
pool = await get_pool()
@@ -232,6 +295,8 @@ async def list_cotizaciones(
estado_efectivo = "aceptada" if solo_aceptadas else estado
conditions: list[str] = []
if auth.get("auth_type") == "agent" or not incluirArchivados:
conditions.append("c.archivado = false")
params: list = []
idx = 1
@@ -304,6 +369,7 @@ async def create_cotizacion(
):
pool = await get_pool()
async with pool.acquire() as conn:
await _validar_solo_admin_agente(conn, auth, body.servicios, body.planBucefalo)
asesor_id = body.asesorId
if not asesor_id:
if auth.get("auth_type") == "jwt" and auth.get("userId"):
@@ -468,6 +534,13 @@ async def update_cotizacion(
status_code=status.HTTP_403_FORBIDDEN,
detail="Los agentes no pueden cambiar el estado de la cotización",
)
await _validar_solo_admin_agente(
conn,
auth,
body.servicios,
body.planBucefalo,
recurso_id=cotizacion_id,
)
if body.estado is not None and body.estado != existing["estado"]:
# Si un humano intenta cambiar estado en PUT, exige las mismas reglas que PATCH /estado