feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
+384
-98
@@ -6,7 +6,13 @@ from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import (
|
||||
es_agente_solo_aceptadas,
|
||||
registrar_auditoria,
|
||||
require_auth,
|
||||
require_scope,
|
||||
require_staff_human,
|
||||
)
|
||||
from app.database import get_pool
|
||||
from app.dependencies import PaginationParams, parse_date
|
||||
from app.models.common import Meta, OkResponse, PaginatedResponse
|
||||
@@ -26,9 +32,14 @@ def _cuid() -> str:
|
||||
return uuid.uuid4().hex[:25]
|
||||
|
||||
|
||||
async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_servicio_id, now, es_doble: bool = False) -> None:
|
||||
"""Inserta un ServicioCotizado desde un ServicioCotizadoInput, manejando
|
||||
partidas personalizadas (por horas / retainer) en paridad con el backend Next.js."""
|
||||
async def _insert_servicio_cotizado(
|
||||
conn,
|
||||
cotizacion_id: str,
|
||||
svc,
|
||||
bucefalo_servicio_id,
|
||||
now,
|
||||
es_doble: bool = False,
|
||||
) -> None:
|
||||
es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-")
|
||||
|
||||
if es_personalizado:
|
||||
@@ -39,8 +50,8 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
catalogo_id = svc.catalogoId
|
||||
|
||||
modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo")
|
||||
# Doble propuesta: por defecto "ambas"; None en cotizaciones normales.
|
||||
opcion = (svc.opcion or "ambas") if es_doble else None
|
||||
precio_final = 0 if modelo_cobro == "demanda" else svc.precio
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -64,7 +75,7 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
opcion,
|
||||
svc.fase,
|
||||
svc.tipoPago,
|
||||
svc.precio,
|
||||
precio_final,
|
||||
svc.tiempoEntrega,
|
||||
json.dumps(svc.entregables),
|
||||
None,
|
||||
@@ -73,7 +84,6 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
|
||||
|
||||
def _parse_json(val):
|
||||
"""asyncpg devuelve columnas jsonb como str; las parsea a dict/list."""
|
||||
if isinstance(val, str):
|
||||
try:
|
||||
return json.loads(val)
|
||||
@@ -86,6 +96,7 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=
|
||||
d = dict(cot)
|
||||
if "opcionesMetadata" in d:
|
||||
d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"])
|
||||
d.pop("observacionesInternas", None)
|
||||
d["cliente"] = dict(cliente) if cliente else None
|
||||
d["asesor"] = dict(asesor) if asesor else None
|
||||
d["servicios"] = [dict(s) for s in servicios] if servicios else []
|
||||
@@ -93,8 +104,6 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=
|
||||
return d
|
||||
|
||||
|
||||
# LEFT JOIN: los servicios personalizados no tienen servicioCatalogoId y un JOIN
|
||||
# interno los dejaría fuera de la respuesta. COALESCE conserva el nombre custom.
|
||||
_SERVICIOS_SQL = """
|
||||
SELECT sc.*, sc."servicioCatalogoId" as "catalogoId",
|
||||
COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId"
|
||||
@@ -119,8 +128,6 @@ async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None:
|
||||
|
||||
|
||||
async def _fetch_cotizaciones_full(conn, cot_rows) -> list[dict]:
|
||||
"""Versión batch de _fetch_cotizacion_full: 4 queries en total para toda la
|
||||
página en lugar de 4 por cotización (evita N+1 en el listado)."""
|
||||
if not cot_rows:
|
||||
return []
|
||||
|
||||
@@ -193,7 +200,7 @@ async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. GET /cotizaciones — List with filters + pagination
|
||||
# 1. GET /cotizaciones
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("", response_model=PaginatedResponse[CotizacionResponse])
|
||||
async def list_cotizaciones(
|
||||
@@ -204,17 +211,33 @@ async def list_cotizaciones(
|
||||
q: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
solo_aceptadas = es_agente_solo_aceptadas(auth)
|
||||
if solo_aceptadas and estado and estado != "aceptada":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.leer_bloqueado",
|
||||
"cotizacion",
|
||||
exito=False,
|
||||
detalle={"estadoSolicitado": estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Tu clave solo permite consultar cotizaciones aceptadas",
|
||||
)
|
||||
|
||||
estado_efectivo = "aceptada" if solo_aceptadas else estado
|
||||
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if estado:
|
||||
conditions.append(f'c.estado = ${idx}')
|
||||
params.append(estado)
|
||||
if estado_efectivo:
|
||||
conditions.append(f"c.estado = ${idx}")
|
||||
params.append(estado_efectivo)
|
||||
idx += 1
|
||||
if asesorId:
|
||||
conditions.append(f'c."asesorId" = ${idx}')
|
||||
@@ -226,18 +249,18 @@ async def list_cotizaciones(
|
||||
idx += 1
|
||||
if q:
|
||||
conditions.append(
|
||||
f'(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})'
|
||||
f"(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})"
|
||||
)
|
||||
params.append(f"%{q}%")
|
||||
idx += 1
|
||||
desde_dt = parse_date(desde)
|
||||
if desde_dt:
|
||||
conditions.append(f'c.fecha >= ${idx}')
|
||||
conditions.append(f"c.fecha >= ${idx}")
|
||||
params.append(desde_dt)
|
||||
idx += 1
|
||||
hasta_dt = parse_date(hasta)
|
||||
if hasta_dt:
|
||||
conditions.append(f'c.fecha <= ${idx}')
|
||||
conditions.append(f"c.fecha <= ${idx}")
|
||||
params.append(hasta_dt)
|
||||
idx += 1
|
||||
|
||||
@@ -263,7 +286,6 @@ async def list_cotizaciones(
|
||||
)
|
||||
|
||||
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
||||
|
||||
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
||||
|
||||
return PaginatedResponse(
|
||||
@@ -273,12 +295,29 @@ async def list_cotizaciones(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. POST /cotizaciones — Create
|
||||
# 2. POST /cotizaciones — Create (SIEMPRE borrador)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.post("", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(require_auth)):
|
||||
async def create_cotizacion(
|
||||
body: CotizacionCreate,
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
asesor_id = body.asesorId
|
||||
if not asesor_id:
|
||||
if auth.get("auth_type") == "jwt" and auth.get("userId"):
|
||||
asesor_id = auth["userId"]
|
||||
else:
|
||||
admin = await conn.fetchrow(
|
||||
'SELECT id FROM "User" WHERE role = \'admin\' ORDER BY "createdAt" ASC LIMIT 1'
|
||||
)
|
||||
if not admin:
|
||||
raise HTTPException(status_code=500, detail="No hay usuario administrador configurado")
|
||||
asesor_id = admin["id"]
|
||||
|
||||
creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None
|
||||
|
||||
async with conn.transaction():
|
||||
cliente_id = await _find_or_create_cliente(
|
||||
conn,
|
||||
@@ -293,13 +332,15 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
opciones_json = None
|
||||
if body.esDoble and body.opciones:
|
||||
opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "Cotizacion"
|
||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||
"creadaPorAgente", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18)
|
||||
""",
|
||||
cot_id,
|
||||
body.numero,
|
||||
@@ -311,16 +352,17 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
body.esquemaPago,
|
||||
body.incluirBonos,
|
||||
body.incluirFinanciamiento,
|
||||
body.incluirIva,
|
||||
body.esDoble,
|
||||
opciones_json,
|
||||
body.observaciones or None,
|
||||
cliente_id,
|
||||
body.asesorId,
|
||||
asesor_id,
|
||||
creada_por_agente,
|
||||
now,
|
||||
)
|
||||
|
||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||
|
||||
for svc in body.servicios:
|
||||
await _insert_servicio_cotizado(conn, cot_id, svc, bucefalo_servicio_id, now, body.esDoble)
|
||||
|
||||
@@ -338,32 +380,58 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
now,
|
||||
)
|
||||
|
||||
row = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id)
|
||||
result = dict(row)
|
||||
result["opcionesMetadata"] = _parse_json(result.get("opcionesMetadata"))
|
||||
return result
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.crear",
|
||||
"cotizacion",
|
||||
recurso_id=cot_id,
|
||||
exito=True,
|
||||
detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. GET /cotizaciones/{id} — Get with relations
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def get_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
pool = await get_pool()
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
if not full:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
full = await _fetch_cotizacion_full(pool, cot_id)
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. PUT /cotizaciones/{id} — Update
|
||||
# 3. GET /cotizaciones/{id}
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def get_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
if not full:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if es_agente_solo_aceptadas(auth) and full["estado"] != "aceptada":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.leer_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": full["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Tu clave solo permite consultar cotizaciones aceptadas",
|
||||
)
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. PUT /cotizaciones/{id}
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.put("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def update_cotizacion(
|
||||
cotizacion_id: str,
|
||||
body: CotizacionUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
@@ -371,6 +439,58 @@ async def update_cotizacion(
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if auth.get("auth_type") == "agent":
|
||||
if existing["estado"] != "borrador":
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.editar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": existing["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes solo pueden editar cotizaciones en borrador",
|
||||
)
|
||||
if body.estado is not None and body.estado != "borrador":
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": existing["estado"], "intento": body.estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes no pueden cambiar el estado de la cotización",
|
||||
)
|
||||
|
||||
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
|
||||
if body.estado == "aprobada" and not (auth.get("auth_type") == "jwt" and auth.get("role") == "admin"):
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"intento": "aprobada"},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede aprobar una cotización",
|
||||
)
|
||||
if body.estado == "enviada" and (existing["estado"] != "aprobada" or existing["aprobadaAt"] is None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="La cotización debe estar aprobada antes de marcarse como enviada",
|
||||
)
|
||||
|
||||
async with conn.transaction():
|
||||
cliente_id = existing["clienteId"]
|
||||
if body.cliente:
|
||||
@@ -386,54 +506,55 @@ async def update_cotizacion(
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
def _add(field: str, col: str, val):
|
||||
def _add(col: str, val):
|
||||
nonlocal idx
|
||||
if val is not None:
|
||||
updates.append(f'{col} = ${idx}')
|
||||
params.append(val)
|
||||
idx += 1
|
||||
updates.append(f'{col} = ${idx}')
|
||||
params.append(val)
|
||||
idx += 1
|
||||
|
||||
_add("fecha", "fecha", body.fecha)
|
||||
_add("vigencia", "vigencia", body.vigencia)
|
||||
_add("moneda", "moneda", body.moneda)
|
||||
_add("tipoCambio", '"tipoCambio"', body.tipoCambio)
|
||||
_add("proyecto", "proyecto", body.proyecto)
|
||||
_add("esquemaPago", '"esquemaPago"', body.esquemaPago)
|
||||
_add("incluirBonos", '"incluirBonos"', body.incluirBonos)
|
||||
_add("incluirFinanciamiento", '"incluirFinanciamiento"', body.incluirFinanciamiento)
|
||||
_add("esDoble", '"esDoble"', body.esDoble)
|
||||
_add("observaciones", "observaciones", body.observaciones)
|
||||
_add("estado", "estado", body.estado)
|
||||
|
||||
es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"]
|
||||
if body.fecha is not None:
|
||||
_add("fecha", body.fecha)
|
||||
if body.vigencia is not None:
|
||||
_add("vigencia", body.vigencia)
|
||||
if body.moneda is not None:
|
||||
_add("moneda", body.moneda)
|
||||
if body.tipoCambio is not None:
|
||||
_add('"tipoCambio"', body.tipoCambio)
|
||||
if body.proyecto is not None:
|
||||
_add("proyecto", body.proyecto)
|
||||
if body.esquemaPago is not None:
|
||||
_add('"esquemaPago"', body.esquemaPago)
|
||||
if body.incluirBonos is not None:
|
||||
_add('"incluirBonos"', body.incluirBonos)
|
||||
if body.incluirFinanciamiento is not None:
|
||||
_add('"incluirFinanciamiento"', body.incluirFinanciamiento)
|
||||
if body.incluirIva is not None:
|
||||
_add('"incluirIva"', body.incluirIva)
|
||||
if body.esDoble is not None:
|
||||
# opcionesMetadata se sincroniza con esDoble: dict (json) si doble, NULL si no.
|
||||
meta_json = None
|
||||
if es_doble_final and body.opciones:
|
||||
meta_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
||||
updates.append(f'"opcionesMetadata" = ${idx}')
|
||||
params.append(meta_json)
|
||||
idx += 1
|
||||
|
||||
_add('"esDoble"', body.esDoble)
|
||||
if body.opciones is not None:
|
||||
_add('"opcionesMetadata"', json.dumps({k: v.model_dump() for k, v in body.opciones.items()}))
|
||||
if body.observaciones is not None:
|
||||
_add("observaciones", body.observaciones)
|
||||
if body.estado is not None and auth.get("auth_type") != "agent":
|
||||
_add("estado", body.estado)
|
||||
if cliente_id != existing["clienteId"]:
|
||||
updates.append(f'"clienteId" = ${idx}')
|
||||
params.append(cliente_id)
|
||||
idx += 1
|
||||
_add('"clienteId"', cliente_id)
|
||||
|
||||
if updates:
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(datetime.now(timezone.utc))
|
||||
idx += 1
|
||||
updates.append('"updatedAt" = NOW()')
|
||||
params.append(cotizacion_id)
|
||||
await conn.execute(
|
||||
f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}',
|
||||
*params,
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"]
|
||||
|
||||
if body.servicios is not None:
|
||||
await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id)
|
||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||
now = datetime.now(timezone.utc)
|
||||
for svc in body.servicios:
|
||||
await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final)
|
||||
|
||||
@@ -442,7 +563,6 @@ async def update_cotizacion(
|
||||
'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
if existing_plan:
|
||||
await conn.execute(
|
||||
'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4',
|
||||
@@ -470,20 +590,40 @@ async def update_cotizacion(
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
return full
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.actualizar",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
)
|
||||
|
||||
return await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. DELETE /cotizaciones/{id}
|
||||
# 5. DELETE /cotizaciones/{id} (solo personal humano)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.delete("/{cotizacion_id}", response_model=OkResponse)
|
||||
async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
async def delete_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
pool = await get_pool()
|
||||
existing = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
existing = await pool.fetchrow('SELECT id, numero FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
await pool.execute('DELETE FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.eliminar",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
detalle={"numero": existing["numero"]},
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@@ -494,13 +634,28 @@ async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_au
|
||||
async def update_precio_servicio(
|
||||
cotizacion_id: str,
|
||||
body: ActualizarPrecioRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
cot = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
cot = await pool.fetchrow('SELECT id, estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not cot:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if auth.get("auth_type") == "agent" and cot["estado"] != "borrador":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.editar_precio_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": cot["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes solo pueden editar precios en cotizaciones en borrador",
|
||||
)
|
||||
|
||||
svc = await pool.fetchrow(
|
||||
'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2',
|
||||
body.servicioId,
|
||||
@@ -518,13 +673,13 @@ async def update_precio_servicio(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. PATCH /cotizaciones/{id}/estado
|
||||
# 7. PATCH /cotizaciones/{id}/estado (PARIDAD ESTRICTA DE APROBACIÓN)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.patch("/{cotizacion_id}/estado", response_model=OkResponse)
|
||||
async def cambiar_estado(
|
||||
cotizacion_id: str,
|
||||
body: CambiarEstadoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
if body.estado not in ESTADOS_COTIZACION:
|
||||
raise HTTPException(
|
||||
@@ -533,13 +688,127 @@ async def cambiar_estado(
|
||||
)
|
||||
|
||||
pool = await get_pool()
|
||||
result = await pool.execute(
|
||||
'UPDATE "Cotizacion" SET estado = $1, "updatedAt" = NOW() WHERE id = $2',
|
||||
body.estado,
|
||||
cotizacion_id,
|
||||
)
|
||||
if result == "UPDATE 0":
|
||||
existing = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
# REGLA DE HIERRO: Ningún agente puede cambiar estado (ni aprobar ni enviar por este endpoint).
|
||||
if auth.get("auth_type") == "agent":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": existing["estado"], "intento": body.estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes no pueden aprobar ni cambiar el estado directamente. Usa el flujo de aprobación humana y POST /api/cotizaciones/:id/enviar.",
|
||||
)
|
||||
|
||||
es_admin = auth.get("auth_type") == "jwt" and auth.get("role") == "admin"
|
||||
actual = existing["estado"]
|
||||
nuevo = body.estado
|
||||
|
||||
if nuevo == "aprobada":
|
||||
if not es_admin:
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": actual, "intento": nuevo},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede aprobar una cotización",
|
||||
)
|
||||
if actual != "borrador":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Solo se puede aprobar una cotización en borrador (estado actual: {actual})",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'aprobada',
|
||||
"aprobadaPorId" = $1,
|
||||
"aprobadaAt" = NOW(),
|
||||
"aprobacionMetodo" = 'web_admin',
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $2
|
||||
""",
|
||||
auth.get("userId"),
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo == "enviada":
|
||||
if actual != "aprobada" or existing["aprobadaAt"] is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="La cotización debe estar aprobada antes de marcarse como enviada",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'enviada',
|
||||
"enviadaAt" = NOW(),
|
||||
"enviadaCanal" = 'manual',
|
||||
"enviadaPor" = $1,
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $2
|
||||
""",
|
||||
f"user:{auth.get('email') or auth.get('userId')}",
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo == "borrador":
|
||||
if not es_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede regresar a borrador",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'borrador',
|
||||
"aprobadaPorId" = NULL,
|
||||
"aprobadaAt" = NULL,
|
||||
"aprobacionMetodo" = NULL,
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $1
|
||||
""",
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo in ("aceptada", "rechazada", "vencida"):
|
||||
if actual != "enviada":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Solo se puede pasar a {nuevo} desde estado enviada (estado actual: {actual})",
|
||||
)
|
||||
col_map = {
|
||||
"aceptada": '"aceptadaAt"',
|
||||
"rechazada": '"rechazadaAt"',
|
||||
"vencida": '"vencidaAt"',
|
||||
}
|
||||
col = col_map[nuevo]
|
||||
await pool.execute(
|
||||
f'UPDATE "Cotizacion" SET estado = $1, {col} = NOW(), "updatedAt" = NOW() WHERE id = $2',
|
||||
nuevo,
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
f"cotizacion.estado_{nuevo}",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
detalle={"anterior": actual, "nuevo": nuevo},
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@@ -547,7 +816,10 @@ async def cambiar_estado(
|
||||
# 8. POST /cotizaciones/{id}/duplicate
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.post("/{cotizacion_id}/duplicate", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
async def duplicate_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
@@ -563,6 +835,8 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None
|
||||
|
||||
async with conn.transaction():
|
||||
now = datetime.now(timezone.utc)
|
||||
new_id = _cuid()
|
||||
@@ -572,9 +846,10 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
"""
|
||||
INSERT INTO "Cotizacion"
|
||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||
"creadaPorAgente", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18)
|
||||
""",
|
||||
new_id,
|
||||
new_numero,
|
||||
@@ -586,11 +861,13 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
original["esquemaPago"],
|
||||
original["incluirBonos"],
|
||||
original["incluirFinanciamiento"],
|
||||
original["incluirIva"],
|
||||
original["esDoble"],
|
||||
original["opcionesMetadata"],
|
||||
original["observaciones"],
|
||||
original["clienteId"],
|
||||
original["asesorId"],
|
||||
creada_por_agente,
|
||||
now,
|
||||
)
|
||||
|
||||
@@ -640,5 +917,14 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
now,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, new_id)
|
||||
return full
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.duplicar",
|
||||
"cotizacion",
|
||||
recurso_id=new_id,
|
||||
exito=True,
|
||||
detalle={"origenId": cotizacion_id, "numero": new_numero},
|
||||
)
|
||||
|
||||
return await _fetch_cotizacion_full(pool, new_id)
|
||||
|
||||
Reference in New Issue
Block a user