feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.models.export_ import BonoResponse
|
||||
from app.services.calculators import BONOS
|
||||
|
||||
@@ -10,5 +10,5 @@ router = APIRouter(prefix="/bonos", tags=["Bonos"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[BonoResponse])
|
||||
async def get_bonos(_auth: dict = Depends(require_auth)):
|
||||
async def get_bonos(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [BonoResponse(**b) for b in BONOS]
|
||||
|
||||
@@ -5,7 +5,7 @@ import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.dependencies import get_db
|
||||
from app.models.catalogo import (
|
||||
ServicioCatalogoCreate,
|
||||
@@ -63,7 +63,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
||||
)
|
||||
async def list_catalogo(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
fase: int | None = Query(None, ge=0, le=3),
|
||||
tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"),
|
||||
categoriaId: str | None = Query(None),
|
||||
@@ -121,7 +121,7 @@ async def list_catalogo(
|
||||
async def create_catalogo(
|
||||
body: ServicioCatalogoCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
if body.categoriaId:
|
||||
cat = await db.fetchrow(
|
||||
@@ -168,7 +168,7 @@ async def create_catalogo(
|
||||
async def get_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
@@ -195,7 +195,7 @@ async def update_catalogo(
|
||||
servicio_id: str,
|
||||
body: ServicioCatalogoUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
@@ -265,7 +265,7 @@ async def update_catalogo(
|
||||
async def delete_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
|
||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
|
||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/categorias", tags=["Categorias"])
|
||||
|
||||
@router.get("", response_model=list[CategoriaResponse])
|
||||
async def list_categorias(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
@@ -33,7 +33,7 @@ async def list_categorias(
|
||||
)
|
||||
async def create_categoria(
|
||||
body: CategoriaCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -64,7 +64,7 @@ async def create_categoria(
|
||||
)
|
||||
async def get_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
@@ -93,7 +93,7 @@ async def get_categoria(
|
||||
async def update_categoria(
|
||||
categoria_id: str,
|
||||
body: CategoriaUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
@@ -166,7 +166,7 @@ async def update_categoria(
|
||||
)
|
||||
async def delete_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
|
||||
@@ -5,7 +5,7 @@ import math
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.dependencies import PaginationParams, get_db
|
||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
||||
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/clientes", tags=["Clientes"])
|
||||
)
|
||||
async def list_clientes(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:leer")),
|
||||
pagination: PaginationParams = Depends(PaginationParams),
|
||||
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
||||
):
|
||||
@@ -79,7 +79,7 @@ async def list_clientes(
|
||||
async def create_cliente(
|
||||
body: ClienteCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:escribir")),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'INSERT INTO "Cliente" (nombre, empresa, email, telefono) '
|
||||
@@ -109,7 +109,7 @@ async def create_cliente(
|
||||
async def get_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:leer")),
|
||||
):
|
||||
row = await db.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not row:
|
||||
@@ -146,7 +146,7 @@ async def update_cliente(
|
||||
cliente_id: str,
|
||||
body: ClienteUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:escribir")),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
@@ -192,7 +192,7 @@ async def update_cliente(
|
||||
async def delete_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_scope
|
||||
from app.dependencies import get_db, parse_date
|
||||
|
||||
router = APIRouter(prefix="/cobros", tags=["Cobros"])
|
||||
|
||||
|
||||
@router.get("/programas", summary="Listar programas de cobro recurrente")
|
||||
async def list_programas_cobro(
|
||||
activo: bool | None = Query(None),
|
||||
clienteId: str | None = Query(None),
|
||||
db: Connection = Depends(get_db),
|
||||
_auth: dict = Depends(require_scope("cobros:leer")),
|
||||
):
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if activo is not None:
|
||||
conditions.append(f"p.activo = ${idx}")
|
||||
params.append(activo)
|
||||
idx += 1
|
||||
if clienteId:
|
||||
conditions.append(f'p."clienteId" = ${idx}')
|
||||
params.append(clienteId)
|
||||
idx += 1
|
||||
|
||||
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
||||
rows = await db.fetch(
|
||||
f"""
|
||||
SELECT p.*,
|
||||
c.nombre AS cliente_nombre,
|
||||
c.empresa AS cliente_empresa,
|
||||
(SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p.id) AS pagos_count
|
||||
FROM "ProgramaPago" p
|
||||
JOIN "Cliente" c ON c.id = p."clienteId"
|
||||
{where}
|
||||
ORDER BY p.activo DESC, p."createdAt" DESC
|
||||
""",
|
||||
*params,
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"clienteId": r["clienteId"],
|
||||
"cotizacionId": r["cotizacionId"],
|
||||
"concepto": r["concepto"],
|
||||
"monto": float(r["monto"]),
|
||||
"moneda": r["moneda"],
|
||||
"frecuencia": r["frecuencia"],
|
||||
"diaSemana": r["diaSemana"],
|
||||
"diaMes": r["diaMes"],
|
||||
"fechaInicio": r["fechaInicio"].isoformat() if r["fechaInicio"] else None,
|
||||
"fechaFin": r["fechaFin"].isoformat() if r["fechaFin"] else None,
|
||||
"activo": r["activo"],
|
||||
"cliente": {
|
||||
"id": r["clienteId"],
|
||||
"nombre": r["cliente_nombre"],
|
||||
"empresa": r["cliente_empresa"],
|
||||
},
|
||||
"_count": {"pagos": int(r["pagos_count"])},
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.get("/pagos", summary="Listar cobros recurrentes con filtros")
|
||||
async def list_pagos_cobro(
|
||||
estado: str | None = Query(None, description="pendiente | en_revision | verificado | rechazado | anulado | por_pagar"),
|
||||
clienteId: str | None = Query(None),
|
||||
programaId: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
db: Connection = Depends(get_db),
|
||||
_auth: dict = Depends(require_scope("cobros:leer")),
|
||||
):
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if estado == "por_pagar":
|
||||
conditions.append("pr.estado IN ('pendiente', 'rechazado')")
|
||||
elif estado:
|
||||
conditions.append(f"pr.estado = ${idx}")
|
||||
params.append(estado)
|
||||
idx += 1
|
||||
|
||||
if clienteId:
|
||||
conditions.append(f'p."clienteId" = ${idx}')
|
||||
params.append(clienteId)
|
||||
idx += 1
|
||||
|
||||
if programaId:
|
||||
conditions.append(f'pr."programaId" = ${idx}')
|
||||
params.append(programaId)
|
||||
idx += 1
|
||||
|
||||
desde_dt = parse_date(desde)
|
||||
if desde_dt:
|
||||
conditions.append(f"pr.fecha >= ${idx}")
|
||||
params.append(desde_dt)
|
||||
idx += 1
|
||||
|
||||
hasta_dt = parse_date(hasta)
|
||||
if hasta_dt:
|
||||
conditions.append(f"pr.fecha <= ${idx}")
|
||||
params.append(hasta_dt)
|
||||
idx += 1
|
||||
|
||||
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
||||
rows = await db.fetch(
|
||||
f"""
|
||||
SELECT pr.*,
|
||||
p.concepto AS programa_concepto,
|
||||
p.moneda AS programa_moneda,
|
||||
p."clienteId" AS programa_cliente_id,
|
||||
c.nombre AS cliente_nombre,
|
||||
c.empresa AS cliente_empresa
|
||||
FROM "PagoRecurrente" pr
|
||||
JOIN "ProgramaPago" p ON p.id = pr."programaId"
|
||||
JOIN "Cliente" c ON c.id = p."clienteId"
|
||||
{where}
|
||||
ORDER BY pr.fecha DESC
|
||||
""",
|
||||
*params,
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"programaId": r["programaId"],
|
||||
"fecha": r["fecha"].isoformat() if r["fecha"] else None,
|
||||
"monto": float(r["monto"]),
|
||||
"estado": r["estado"],
|
||||
"verificadoAt": r["verificadoAt"].isoformat() if r["verificadoAt"] else None,
|
||||
"rechazadoAt": r["rechazadoAt"].isoformat() if r["rechazadoAt"] else None,
|
||||
"rechazoMotivo": r["rechazoMotivo"],
|
||||
"ultimoRecordatorioAt": r["ultimoRecordatorioAt"].isoformat() if r["ultimoRecordatorioAt"] else None,
|
||||
"recordatoriosEnviados": r["recordatoriosEnviados"],
|
||||
"nota": r["nota"],
|
||||
"programa": {
|
||||
"concepto": r["programa_concepto"],
|
||||
"moneda": r["programa_moneda"],
|
||||
"cliente": {
|
||||
"id": r["programa_cliente_id"],
|
||||
"nombre": r["cliente_nombre"],
|
||||
"empresa": r["cliente_empresa"],
|
||||
},
|
||||
},
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
@@ -6,14 +6,14 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/configuracion", tags=["Configuración"])
|
||||
|
||||
|
||||
@router.get("", response_model=ConfigResponse)
|
||||
async def get_configuracion(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch("SELECT clave, valor FROM Configuracion")
|
||||
@@ -24,7 +24,7 @@ async def get_configuracion(
|
||||
@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}})
|
||||
async def update_configuracion(
|
||||
body: ConfigUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
allowed = body.get_allowed()
|
||||
|
||||
+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)
|
||||
|
||||
+20
-14
@@ -15,7 +15,7 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.export_ import ExportDraft
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import es_agente_solo_aceptadas, require_scope
|
||||
from app.services.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename
|
||||
from app.services.pdf_generator import generate_cotizacion_pdf
|
||||
from app.services.excel_generator import generate_cotizacion_excel
|
||||
@@ -86,13 +86,12 @@ def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) ->
|
||||
"planBucefaloNivel": draft.planBucefaloNivel,
|
||||
"planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0,
|
||||
"incluirBonos": draft.incluirBonos,
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -188,13 +187,12 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
"planBucefaloNivel": plan_nivel,
|
||||
"planBucefaloPrecio": float(plan["precio"]) if plan else 0,
|
||||
"incluirBonos": cot["incluirBonos"],
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -203,7 +201,7 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
@router.post("/pdf")
|
||||
async def export_pdf_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -223,9 +221,13 @@ async def export_pdf_draft(
|
||||
@router.get("/pdf/{cotizacion_id}")
|
||||
async def export_pdf_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
pdf_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not pdf_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -247,7 +249,7 @@ async def export_pdf_saved(
|
||||
@router.post("/excel")
|
||||
async def export_excel_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -267,9 +269,13 @@ async def export_excel_draft(
|
||||
@router.get("/excel/{cotizacion_id}")
|
||||
async def export_excel_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
excel_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not excel_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -290,7 +296,7 @@ async def export_excel_saved(
|
||||
|
||||
@router.get("/catalogo", response_class=PlainTextResponse)
|
||||
async def export_catalogo_csv(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch(
|
||||
|
||||
@@ -11,7 +11,7 @@ from app.models.export_ import (
|
||||
PlanBucefaloResponse,
|
||||
)
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.services.calculators import (
|
||||
calcular_financiamiento,
|
||||
FINANCIAMIENTO_PLANES,
|
||||
@@ -28,7 +28,7 @@ class PlanResponse(FinanciamientoResponse):
|
||||
|
||||
|
||||
@router.get("/planes", response_model=list[PlanResponse])
|
||||
async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
async def get_planes(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [
|
||||
PlanResponse(
|
||||
meses=p["meses"],
|
||||
@@ -47,7 +47,7 @@ async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
)
|
||||
async def calcular(
|
||||
body: FinanciamientoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
):
|
||||
plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None)
|
||||
if not plan:
|
||||
@@ -77,7 +77,7 @@ async def calcular(
|
||||
)
|
||||
async def simulacion(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
cot = await db.fetchrow(
|
||||
|
||||
@@ -28,9 +28,9 @@ async def health_check():
|
||||
@router.get("/api-info", response_model=APIInfoResponse)
|
||||
async def api_info():
|
||||
return APIInfoResponse(
|
||||
name="Cotizador E3 API",
|
||||
name="Cotizador — Uriel Jareth Consulting API",
|
||||
version="1.0.0",
|
||||
description="API para el sistema de cotizaciones de Consultoría E3",
|
||||
description="API para el sistema de cotizaciones de Uriel Jareth Consulting",
|
||||
capabilities=[
|
||||
"Gestión de cotizaciones",
|
||||
"Catálogo de servicios",
|
||||
|
||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/import", tags=["Import"])
|
||||
|
||||
@@ -17,7 +17,7 @@ REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"}
|
||||
@router.post("/catalogo")
|
||||
async def import_catalogo_csv(
|
||||
file: UploadFile = File(...),
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
content = await file.read()
|
||||
|
||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.models.paquete import (
|
||||
PaqueteCreate,
|
||||
PaqueteUpdate,
|
||||
@@ -128,7 +128,7 @@ async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
||||
|
||||
@router.get("", response_model=list[PaqueteResponse])
|
||||
async def list_paquetes(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
@@ -145,7 +145,7 @@ async def list_paquetes(
|
||||
)
|
||||
async def create_paquete(
|
||||
body: PaqueteCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -179,7 +179,7 @@ async def create_paquete(
|
||||
)
|
||||
async def get_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
@@ -203,7 +203,7 @@ async def get_paquete(
|
||||
async def update_paquete(
|
||||
paquete_id: str,
|
||||
body: PaqueteUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
@@ -260,7 +260,7 @@ async def update_paquete(
|
||||
)
|
||||
async def delete_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
result = await conn.execute(
|
||||
@@ -281,7 +281,7 @@ async def delete_paquete(
|
||||
async def manage_paquete(
|
||||
paquete_id: str,
|
||||
body: ManageAction,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
paquete = await conn.fetchrow(
|
||||
|
||||
Reference in New Issue
Block a user