feat: restringe soloAdmin (Bucefalo CRM) a agentes, default WhatsApp+fallbackEmail y archivado reversible
This commit is contained in:
@@ -5,7 +5,7 @@ import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.auth import registrar_auditoria, require_scope, require_staff_human
|
||||
from app.dependencies import get_db
|
||||
from app.models.catalogo import (
|
||||
ServicioCatalogoCreate,
|
||||
@@ -49,6 +49,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
||||
variante=row["variante"],
|
||||
nivel=row["nivel"],
|
||||
activo=row["activo"],
|
||||
soloAdmin=bool(row.get("soloAdmin", False)),
|
||||
orden=row["orden"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
@@ -70,6 +71,8 @@ async def list_catalogo(
|
||||
q: str | None = Query(None, description="Search by nombre or descripcion"),
|
||||
):
|
||||
where_clauses: list[str] = ['activo = true']
|
||||
if auth.get("auth_type") == "agent":
|
||||
where_clauses.append('"soloAdmin" = false')
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
@@ -135,8 +138,8 @@ async def create_catalogo(
|
||||
row = await db.fetchrow(
|
||||
'INSERT INTO "ServicioCatalogo" '
|
||||
'(nombre, descripcion, fase, "tipoPago", "precioBase", "tiempoEntrega", '
|
||||
'"entregablesDefault", "categoriaId", variante, nivel, activo, orden) '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11) RETURNING *",
|
||||
'"entregablesDefault", "categoriaId", variante, nivel, activo, "soloAdmin", orden) '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11, $12) RETURNING *",
|
||||
body.nombre,
|
||||
body.descripcion,
|
||||
body.fase,
|
||||
@@ -147,6 +150,7 @@ async def create_catalogo(
|
||||
body.categoriaId,
|
||||
body.variante,
|
||||
body.nivel,
|
||||
body.soloAdmin,
|
||||
body.orden,
|
||||
)
|
||||
|
||||
@@ -176,6 +180,21 @@ async def get_catalogo(
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||
|
||||
if auth.get("auth_type") == "agent" and row.get("soloAdmin"):
|
||||
await registrar_auditoria(
|
||||
db,
|
||||
auth,
|
||||
"catalogo.solo_admin_bloqueado",
|
||||
"catalogo",
|
||||
recurso_id=servicio_id,
|
||||
exito=False,
|
||||
detalle={"nombre": row["nombre"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Este servicio esta restringido solo al administrador y no esta disponible para agentes",
|
||||
)
|
||||
|
||||
cat_row = None
|
||||
if row["categoriaId"]:
|
||||
cat_row = await db.fetchrow(
|
||||
@@ -222,6 +241,7 @@ async def update_catalogo(
|
||||
"variante": "variante",
|
||||
"nivel": "nivel",
|
||||
"activo": "activo",
|
||||
"soloAdmin": '"soloAdmin"',
|
||||
"orden": "orden",
|
||||
}
|
||||
|
||||
|
||||
@@ -23,8 +23,11 @@ async def list_clientes(
|
||||
auth: dict = Depends(require_scope("clientes:leer")),
|
||||
pagination: PaginationParams = Depends(PaginationParams),
|
||||
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
||||
incluirArchivados: bool = Query(False, description="Solo personal humano"),
|
||||
):
|
||||
where_clauses: list[str] = []
|
||||
if auth.get("auth_type") == "agent" or not incluirArchivados:
|
||||
where_clauses.append("archivado = false")
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
@@ -116,7 +119,7 @@ async def get_cliente(
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
cotizaciones = await db.fetch(
|
||||
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 '
|
||||
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 AND archivado = false '
|
||||
'ORDER BY "createdAt" DESC LIMIT 10',
|
||||
cliente_id,
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,7 +19,7 @@ from app.models.common import ErrorResponse, OkResponse
|
||||
router = APIRouter(prefix="/paquetes", tags=["Paquetes"])
|
||||
|
||||
|
||||
async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict]:
|
||||
async def _build_paquetes_responses(conn, paquete_rows: list[dict], excluir_solo_admin: bool = False) -> list[dict]:
|
||||
"""Build PaqueteResponse dicts for several paquetes with 2 queries in total
|
||||
(instead of 1 + N fases per paquete)."""
|
||||
if not paquete_rows:
|
||||
@@ -43,7 +43,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
' sc."precioBase" AS "sc_precioBase", sc."tiempoEntrega" AS "sc_tiempoEntrega",'
|
||||
' sc."entregablesDefault" AS "sc_entregablesDefault",'
|
||||
' sc."categoriaId" AS "sc_categoriaId", sc.variante AS "sc_variante",'
|
||||
' sc.activo AS "sc_activo", sc.orden AS "sc_orden",'
|
||||
' sc.activo AS "sc_activo", sc."soloAdmin" AS "sc_soloAdmin", sc.orden AS "sc_orden",'
|
||||
' sc."createdAt" AS "sc_createdAt", sc."updatedAt" AS "sc_updatedAt",'
|
||||
' cat.id AS "cat_id", cat.nombre AS "cat_nombre", cat.descripcion AS "cat_descripcion",'
|
||||
' cat.color AS "cat_color", cat.activo AS "cat_activo", cat.orden AS "cat_orden",'
|
||||
@@ -57,6 +57,8 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
|
||||
servicios_por_fase: dict[str, list[dict]] = {}
|
||||
for s in servicios_rows:
|
||||
if excluir_solo_admin and s.get("sc_soloAdmin"):
|
||||
continue
|
||||
cat = None
|
||||
if s["cat_id"]:
|
||||
cat = {
|
||||
@@ -87,6 +89,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
"categoriaId": s["sc_categoriaId"],
|
||||
"variante": s["sc_variante"],
|
||||
"activo": s["sc_activo"],
|
||||
"soloAdmin": bool(s.get("sc_soloAdmin", False)),
|
||||
"orden": s["sc_orden"],
|
||||
"createdAt": s["sc_createdAt"],
|
||||
"updatedAt": s["sc_updatedAt"],
|
||||
@@ -120,9 +123,9 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
]
|
||||
|
||||
|
||||
async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
||||
async def _build_paquete_response(conn, paquete_row: dict, excluir_solo_admin: bool = False) -> dict:
|
||||
"""Build a PaqueteResponse dict with nested fases and servicios."""
|
||||
results = await _build_paquetes_responses(conn, [paquete_row])
|
||||
results = await _build_paquetes_responses(conn, [paquete_row], excluir_solo_admin=excluir_solo_admin)
|
||||
return results[0]
|
||||
|
||||
|
||||
@@ -135,7 +138,8 @@ async def list_paquetes(
|
||||
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
||||
' FROM "Paquete" WHERE activo = true ORDER BY "createdAt" ASC'
|
||||
)
|
||||
return await _build_paquetes_responses(conn, [dict(row) for row in rows])
|
||||
excluir = _auth.get("auth_type") == "agent"
|
||||
return await _build_paquetes_responses(conn, [dict(row) for row in rows], excluir_solo_admin=excluir)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -192,7 +196,8 @@ async def get_paquete(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
return await _build_paquete_response(conn, dict(row))
|
||||
excluir = _auth.get("auth_type") == "agent"
|
||||
return await _build_paquete_response(conn, dict(row), excluir_solo_admin=excluir)
|
||||
|
||||
|
||||
@router.put(
|
||||
|
||||
Reference in New Issue
Block a user