931 lines
34 KiB
Python
931 lines
34 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
|
|
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
|
|
from app.models.cotizacion import (
|
|
ActualizarPrecioRequest,
|
|
CambiarEstadoRequest,
|
|
CotizacionCreate,
|
|
CotizacionResponse,
|
|
CotizacionUpdate,
|
|
)
|
|
from app.services.calculators import ESTADOS_COTIZACION
|
|
|
|
router = APIRouter(prefix="/cotizaciones", tags=["Cotizaciones"])
|
|
|
|
|
|
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:
|
|
es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-")
|
|
|
|
if es_personalizado:
|
|
catalogo_id = None
|
|
elif svc.catalogoId.startswith("bucefalo-") and bucefalo_servicio_id:
|
|
catalogo_id = bucefalo_servicio_id
|
|
else:
|
|
catalogo_id = svc.catalogoId
|
|
|
|
modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo")
|
|
opcion = (svc.opcion or "ambas") if es_doble else None
|
|
precio_final = 0 if modelo_cobro == "demanda" else svc.precio
|
|
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "ServicioCotizado"
|
|
(id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado",
|
|
horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
|
opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas,
|
|
seleccionado, "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,true,$18,$18)
|
|
""",
|
|
_cuid(),
|
|
cotizacion_id,
|
|
catalogo_id,
|
|
svc.nombre if es_personalizado else None,
|
|
es_personalizado,
|
|
svc.horas if es_personalizado else None,
|
|
svc.tarifaHora if es_personalizado else None,
|
|
modelo_cobro,
|
|
svc.montoMinimo if es_personalizado else None,
|
|
svc.horasIncluidas if es_personalizado else None,
|
|
opcion,
|
|
svc.fase,
|
|
svc.tipoPago,
|
|
precio_final,
|
|
svc.tiempoEntrega,
|
|
json.dumps(svc.entregables),
|
|
None,
|
|
now,
|
|
)
|
|
|
|
|
|
def _parse_json(val):
|
|
if isinstance(val, str):
|
|
try:
|
|
return json.loads(val)
|
|
except (ValueError, TypeError):
|
|
return None
|
|
return val
|
|
|
|
|
|
def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=None) -> dict:
|
|
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 []
|
|
d["planBucefalo"] = dict(plan) if plan else None
|
|
return d
|
|
|
|
|
|
_SERVICIOS_SQL = """
|
|
SELECT sc.*, sc."servicioCatalogoId" as "catalogoId",
|
|
COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId"
|
|
FROM "ServicioCotizado" sc
|
|
LEFT JOIN "ServicioCatalogo" s ON s.id = sc."servicioCatalogoId"
|
|
WHERE sc."cotizacionId" = {}
|
|
ORDER BY sc.fase, sc.opcion, sc.id
|
|
"""
|
|
|
|
|
|
async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None:
|
|
cot = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id)
|
|
if not cot:
|
|
return None
|
|
|
|
cliente = await conn.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cot["clienteId"])
|
|
asesor = await conn.fetchrow('SELECT id, email, name, role FROM "User" WHERE id = $1', cot["asesorId"])
|
|
servicios = await conn.fetch(_SERVICIOS_SQL.format("$1"), cot_id)
|
|
plan = await conn.fetchrow('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', cot_id)
|
|
|
|
return _build_cotizacion_dict(cot, cliente, asesor, servicios, plan)
|
|
|
|
|
|
async def _fetch_cotizaciones_full(conn, cot_rows) -> list[dict]:
|
|
if not cot_rows:
|
|
return []
|
|
|
|
cot_ids = [r["id"] for r in cot_rows]
|
|
cliente_ids = list({r["clienteId"] for r in cot_rows})
|
|
asesor_ids = list({r["asesorId"] for r in cot_rows})
|
|
|
|
clientes = await conn.fetch('SELECT * FROM "Cliente" WHERE id = ANY($1::text[])', cliente_ids)
|
|
asesores = await conn.fetch('SELECT id, email, name, role FROM "User" WHERE id = ANY($1::text[])', asesor_ids)
|
|
servicios = await conn.fetch(_SERVICIOS_SQL.format("ANY($1::text[])"), cot_ids)
|
|
planes = await conn.fetch('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = ANY($1::text[])', cot_ids)
|
|
|
|
clientes_map = {c["id"]: c for c in clientes}
|
|
asesores_map = {a["id"]: a for a in asesores}
|
|
planes_map = {p["cotizacionId"]: p for p in planes}
|
|
servicios_map: dict[str, list] = {}
|
|
for s in servicios:
|
|
servicios_map.setdefault(s["cotizacionId"], []).append(s)
|
|
|
|
return [
|
|
_build_cotizacion_dict(
|
|
cot,
|
|
clientes_map.get(cot["clienteId"]),
|
|
asesores_map.get(cot["asesorId"]),
|
|
servicios_map.get(cot["id"], []),
|
|
planes_map.get(cot["id"]),
|
|
)
|
|
for cot in cot_rows
|
|
]
|
|
|
|
|
|
async def _resolve_bucefalo_servicio(conn) -> str | None:
|
|
row = await conn.fetchrow(
|
|
"""
|
|
SELECT s.id FROM "ServicioCatalogo" s
|
|
JOIN "Categoria" c ON c.id = s."categoriaId"
|
|
WHERE c.nombre = 'CRM' AND s."tipoPago" = 'mensual' AND s.activo = true
|
|
ORDER BY s.orden LIMIT 1
|
|
"""
|
|
)
|
|
return row["id"] if row else 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',
|
|
nombre,
|
|
empresa or "",
|
|
)
|
|
if row:
|
|
if email or telefono:
|
|
await conn.execute(
|
|
'UPDATE "Cliente" SET email = COALESCE($1, email), telefono = COALESCE($2, telefono), "updatedAt" = NOW() WHERE id = $3',
|
|
email or None,
|
|
telefono or None,
|
|
row["id"],
|
|
)
|
|
return row["id"]
|
|
|
|
new_id = _cuid()
|
|
await conn.execute(
|
|
'INSERT INTO "Cliente" (id, nombre, empresa, email, telefono, "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, NOW(), NOW())',
|
|
new_id,
|
|
nombre,
|
|
empresa or None,
|
|
email or None,
|
|
telefono or None,
|
|
)
|
|
return new_id
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 1. GET /cotizaciones
|
|
# ---------------------------------------------------------------------------
|
|
@router.get("", response_model=PaginatedResponse[CotizacionResponse])
|
|
async def list_cotizaciones(
|
|
pagination: PaginationParams = Depends(),
|
|
estado: str | None = Query(None),
|
|
asesorId: str | None = Query(None),
|
|
clienteId: str | None = Query(None),
|
|
q: str | None = Query(None),
|
|
desde: str | None = Query(None),
|
|
hasta: str | None = Query(None),
|
|
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_efectivo:
|
|
conditions.append(f"c.estado = ${idx}")
|
|
params.append(estado_efectivo)
|
|
idx += 1
|
|
if asesorId:
|
|
conditions.append(f'c."asesorId" = ${idx}')
|
|
params.append(asesorId)
|
|
idx += 1
|
|
if clienteId:
|
|
conditions.append(f'c."clienteId" = ${idx}')
|
|
params.append(clienteId)
|
|
idx += 1
|
|
if q:
|
|
conditions.append(
|
|
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}")
|
|
params.append(desde_dt)
|
|
idx += 1
|
|
hasta_dt = parse_date(hasta)
|
|
if hasta_dt:
|
|
conditions.append(f"c.fecha <= ${idx}")
|
|
params.append(hasta_dt)
|
|
idx += 1
|
|
|
|
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
|
|
|
count_row = await pool.fetchrow(
|
|
f'SELECT COUNT(*) FROM "Cotizacion" c LEFT JOIN "Cliente" cl ON cl.id = c."clienteId" {where}',
|
|
*params,
|
|
)
|
|
total = count_row["count"]
|
|
|
|
rows = await pool.fetch(
|
|
f"""
|
|
SELECT c.* FROM "Cotizacion" c
|
|
LEFT JOIN "Cliente" cl ON cl.id = c."clienteId"
|
|
{where}
|
|
ORDER BY c."createdAt" DESC
|
|
LIMIT ${idx} OFFSET ${idx + 1}
|
|
""",
|
|
*params,
|
|
pagination.limit,
|
|
pagination.offset,
|
|
)
|
|
|
|
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
|
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
|
|
|
return PaginatedResponse(
|
|
data=cotizaciones,
|
|
meta=Meta(total=total, page=pagination.page, limit=pagination.limit, pages=pages),
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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_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,
|
|
body.cliente.nombre,
|
|
body.cliente.empresa,
|
|
body.cliente.email,
|
|
body.cliente.telefono,
|
|
)
|
|
|
|
cot_id = _cuid()
|
|
now = datetime.now(timezone.utc)
|
|
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", "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,
|
|
body.fecha,
|
|
body.vigencia,
|
|
body.moneda,
|
|
body.tipoCambio,
|
|
body.proyecto,
|
|
body.esquemaPago,
|
|
body.incluirBonos,
|
|
body.incluirFinanciamiento,
|
|
body.incluirIva,
|
|
body.esDoble,
|
|
opciones_json,
|
|
body.observaciones or None,
|
|
cliente_id,
|
|
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)
|
|
|
|
if body.planBucefalo:
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "PlanBucefaloCotizacion"
|
|
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,true,$5,$5)
|
|
""",
|
|
_cuid(),
|
|
cot_id,
|
|
body.planBucefalo.nivel,
|
|
body.planBucefalo.precio,
|
|
now,
|
|
)
|
|
|
|
await registrar_auditoria(
|
|
conn,
|
|
auth,
|
|
"cotizacion.crear",
|
|
"cotizacion",
|
|
recurso_id=cot_id,
|
|
exito=True,
|
|
detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente},
|
|
)
|
|
|
|
full = await _fetch_cotizacion_full(pool, cot_id)
|
|
return full
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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_scope("cotizaciones:borrador")),
|
|
):
|
|
pool = await get_pool()
|
|
async with pool.acquire() as conn:
|
|
existing = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
|
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:
|
|
cliente_id = await _find_or_create_cliente(
|
|
conn,
|
|
body.cliente.nombre,
|
|
body.cliente.empresa,
|
|
body.cliente.email,
|
|
body.cliente.telefono,
|
|
)
|
|
|
|
updates: list[str] = []
|
|
params: list = []
|
|
idx = 1
|
|
|
|
def _add(col: str, val):
|
|
nonlocal idx
|
|
updates.append(f'{col} = ${idx}')
|
|
params.append(val)
|
|
idx += 1
|
|
|
|
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:
|
|
_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"]:
|
|
_add('"clienteId"', cliente_id)
|
|
|
|
if updates:
|
|
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)
|
|
for svc in body.servicios:
|
|
await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final)
|
|
|
|
if body.planBucefalo is not None:
|
|
existing_plan = await conn.fetchrow(
|
|
'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
|
cotizacion_id,
|
|
)
|
|
if existing_plan:
|
|
await conn.execute(
|
|
'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4',
|
|
body.planBucefalo.nivel,
|
|
body.planBucefalo.precio,
|
|
now,
|
|
existing_plan["id"],
|
|
)
|
|
else:
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "PlanBucefaloCotizacion"
|
|
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,true,$5,$5)
|
|
""",
|
|
_cuid(),
|
|
cotizacion_id,
|
|
body.planBucefalo.nivel,
|
|
body.planBucefalo.precio,
|
|
now,
|
|
)
|
|
elif body.planBucefalo is None and "planBucefalo" in body.model_fields_set:
|
|
await conn.execute(
|
|
'DELETE FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
|
cotizacion_id,
|
|
)
|
|
|
|
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} (solo personal humano)
|
|
# ---------------------------------------------------------------------------
|
|
@router.delete("/{cotizacion_id}", response_model=OkResponse)
|
|
async def delete_cotizacion(
|
|
cotizacion_id: str,
|
|
auth: dict = Depends(require_staff_human),
|
|
):
|
|
pool = await get_pool()
|
|
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)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 6. PATCH /cotizaciones/{id}/precio
|
|
# ---------------------------------------------------------------------------
|
|
@router.patch("/{cotizacion_id}/precio", response_model=OkResponse)
|
|
async def update_precio_servicio(
|
|
cotizacion_id: str,
|
|
body: ActualizarPrecioRequest,
|
|
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
|
):
|
|
pool = await get_pool()
|
|
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,
|
|
cotizacion_id,
|
|
)
|
|
if not svc:
|
|
raise HTTPException(status_code=404, detail="Servicio no pertenece a esta cotización")
|
|
|
|
await pool.execute(
|
|
'UPDATE "ServicioCotizado" SET precio = $1, "updatedAt" = NOW() WHERE id = $2',
|
|
body.precio,
|
|
body.servicioId,
|
|
)
|
|
return OkResponse(ok=True)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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),
|
|
):
|
|
if body.estado not in ESTADOS_COTIZACION:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail=f"Estado inválido. Permitidos: {', '.join(ESTADOS_COTIZACION)}",
|
|
)
|
|
|
|
pool = await get_pool()
|
|
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)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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_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)
|
|
if not original:
|
|
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
|
|
|
servicios = await conn.fetch(
|
|
'SELECT * FROM "ServicioCotizado" WHERE "cotizacionId" = $1',
|
|
cotizacion_id,
|
|
)
|
|
plan = await conn.fetchrow(
|
|
'SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
|
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()
|
|
new_numero = original["numero"] + "-COPY"
|
|
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "Cotizacion"
|
|
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
|
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,
|
|
original["fecha"],
|
|
original["vigencia"],
|
|
original["moneda"],
|
|
original["tipoCambio"],
|
|
original["proyecto"],
|
|
original["esquemaPago"],
|
|
original["incluirBonos"],
|
|
original["incluirFinanciamiento"],
|
|
original["incluirIva"],
|
|
original["esDoble"],
|
|
original["opcionesMetadata"],
|
|
original["observaciones"],
|
|
original["clienteId"],
|
|
original["asesorId"],
|
|
creada_por_agente,
|
|
now,
|
|
)
|
|
|
|
for svc in servicios:
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "ServicioCotizado"
|
|
(id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado",
|
|
horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
|
opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas,
|
|
seleccionado, "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$19)
|
|
""",
|
|
_cuid(),
|
|
new_id,
|
|
svc["servicioCatalogoId"],
|
|
svc["nombre"],
|
|
svc["esPersonalizado"],
|
|
svc["horas"],
|
|
svc["tarifaHora"],
|
|
svc["modeloCobro"],
|
|
svc["montoMinimo"],
|
|
svc["horasIncluidas"],
|
|
svc["opcion"],
|
|
svc["fase"],
|
|
svc["tipoPago"],
|
|
svc["precio"],
|
|
svc["tiempoEntrega"],
|
|
svc["entregables"],
|
|
svc["notas"],
|
|
svc["seleccionado"],
|
|
now,
|
|
)
|
|
|
|
if plan:
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO "PlanBucefaloCotizacion"
|
|
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
|
VALUES ($1,$2,$3,$4,$5,$6,$6)
|
|
""",
|
|
_cuid(),
|
|
new_id,
|
|
plan["nivel"],
|
|
plan["precio"],
|
|
plan["seleccionado"],
|
|
now,
|
|
)
|
|
|
|
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)
|