feat: restringe soloAdmin (Bucefalo CRM) a agentes, default WhatsApp+fallbackEmail y archivado reversible
This commit is contained in:
@@ -44,6 +44,7 @@ class ServicioCatalogoBase(BaseModel):
|
|||||||
categoriaId: str = Field(..., min_length=1, description="ID de la categoría")
|
categoriaId: str = Field(..., min_length=1, description="ID de la categoría")
|
||||||
variante: str | None = None
|
variante: str | None = None
|
||||||
nivel: str | None = Field(None, description="Nivel/tier: Emprendedor, PYME, Empresario, Corporativo")
|
nivel: str | None = Field(None, description="Nivel/tier: Emprendedor, PYME, Empresario, Corporativo")
|
||||||
|
soloAdmin: bool = Field(False, description="Visible solo para admin humano; oculto para agentes IA")
|
||||||
orden: int = Field(0, ge=0)
|
orden: int = Field(0, ge=0)
|
||||||
|
|
||||||
|
|
||||||
@@ -63,6 +64,7 @@ class ServicioCatalogoUpdate(BaseModel):
|
|||||||
variante: str | None = None
|
variante: str | None = None
|
||||||
nivel: str | None = None
|
nivel: str | None = None
|
||||||
activo: bool | None = None
|
activo: bool | None = None
|
||||||
|
soloAdmin: bool | None = None
|
||||||
orden: int | None = Field(None, ge=0)
|
orden: int | None = Field(None, ge=0)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import json
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
from asyncpg import Connection
|
from asyncpg import Connection
|
||||||
|
|
||||||
from app.auth import require_scope, require_staff_human
|
from app.auth import registrar_auditoria, require_scope, require_staff_human
|
||||||
from app.dependencies import get_db
|
from app.dependencies import get_db
|
||||||
from app.models.catalogo import (
|
from app.models.catalogo import (
|
||||||
ServicioCatalogoCreate,
|
ServicioCatalogoCreate,
|
||||||
@@ -49,6 +49,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
|||||||
variante=row["variante"],
|
variante=row["variante"],
|
||||||
nivel=row["nivel"],
|
nivel=row["nivel"],
|
||||||
activo=row["activo"],
|
activo=row["activo"],
|
||||||
|
soloAdmin=bool(row.get("soloAdmin", False)),
|
||||||
orden=row["orden"],
|
orden=row["orden"],
|
||||||
createdAt=row["createdAt"],
|
createdAt=row["createdAt"],
|
||||||
updatedAt=row["updatedAt"],
|
updatedAt=row["updatedAt"],
|
||||||
@@ -70,6 +71,8 @@ async def list_catalogo(
|
|||||||
q: str | None = Query(None, description="Search by nombre or descripcion"),
|
q: str | None = Query(None, description="Search by nombre or descripcion"),
|
||||||
):
|
):
|
||||||
where_clauses: list[str] = ['activo = true']
|
where_clauses: list[str] = ['activo = true']
|
||||||
|
if auth.get("auth_type") == "agent":
|
||||||
|
where_clauses.append('"soloAdmin" = false')
|
||||||
params: list = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
@@ -135,8 +138,8 @@ async def create_catalogo(
|
|||||||
row = await db.fetchrow(
|
row = await db.fetchrow(
|
||||||
'INSERT INTO "ServicioCatalogo" '
|
'INSERT INTO "ServicioCatalogo" '
|
||||||
'(nombre, descripcion, fase, "tipoPago", "precioBase", "tiempoEntrega", '
|
'(nombre, descripcion, fase, "tipoPago", "precioBase", "tiempoEntrega", '
|
||||||
'"entregablesDefault", "categoriaId", variante, nivel, activo, orden) '
|
'"entregablesDefault", "categoriaId", variante, nivel, activo, "soloAdmin", orden) '
|
||||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11) RETURNING *",
|
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11, $12) RETURNING *",
|
||||||
body.nombre,
|
body.nombre,
|
||||||
body.descripcion,
|
body.descripcion,
|
||||||
body.fase,
|
body.fase,
|
||||||
@@ -147,6 +150,7 @@ async def create_catalogo(
|
|||||||
body.categoriaId,
|
body.categoriaId,
|
||||||
body.variante,
|
body.variante,
|
||||||
body.nivel,
|
body.nivel,
|
||||||
|
body.soloAdmin,
|
||||||
body.orden,
|
body.orden,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -176,6 +180,21 @@ async def get_catalogo(
|
|||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||||
|
|
||||||
|
if auth.get("auth_type") == "agent" and row.get("soloAdmin"):
|
||||||
|
await registrar_auditoria(
|
||||||
|
db,
|
||||||
|
auth,
|
||||||
|
"catalogo.solo_admin_bloqueado",
|
||||||
|
"catalogo",
|
||||||
|
recurso_id=servicio_id,
|
||||||
|
exito=False,
|
||||||
|
detalle={"nombre": row["nombre"]},
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Este servicio esta restringido solo al administrador y no esta disponible para agentes",
|
||||||
|
)
|
||||||
|
|
||||||
cat_row = None
|
cat_row = None
|
||||||
if row["categoriaId"]:
|
if row["categoriaId"]:
|
||||||
cat_row = await db.fetchrow(
|
cat_row = await db.fetchrow(
|
||||||
@@ -222,6 +241,7 @@ async def update_catalogo(
|
|||||||
"variante": "variante",
|
"variante": "variante",
|
||||||
"nivel": "nivel",
|
"nivel": "nivel",
|
||||||
"activo": "activo",
|
"activo": "activo",
|
||||||
|
"soloAdmin": '"soloAdmin"',
|
||||||
"orden": "orden",
|
"orden": "orden",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,11 @@ async def list_clientes(
|
|||||||
auth: dict = Depends(require_scope("clientes:leer")),
|
auth: dict = Depends(require_scope("clientes:leer")),
|
||||||
pagination: PaginationParams = Depends(PaginationParams),
|
pagination: PaginationParams = Depends(PaginationParams),
|
||||||
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
||||||
|
incluirArchivados: bool = Query(False, description="Solo personal humano"),
|
||||||
):
|
):
|
||||||
where_clauses: list[str] = []
|
where_clauses: list[str] = []
|
||||||
|
if auth.get("auth_type") == "agent" or not incluirArchivados:
|
||||||
|
where_clauses.append("archivado = false")
|
||||||
params: list = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
@@ -116,7 +119,7 @@ async def get_cliente(
|
|||||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||||
|
|
||||||
cotizaciones = await db.fetch(
|
cotizaciones = await db.fetch(
|
||||||
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 '
|
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 AND archivado = false '
|
||||||
'ORDER BY "createdAt" DESC LIMIT 10',
|
'ORDER BY "createdAt" DESC LIMIT 10',
|
||||||
cliente_id,
|
cliente_id,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
@@ -32,6 +33,67 @@ def _cuid() -> str:
|
|||||||
return uuid.uuid4().hex[:25]
|
return uuid.uuid4().hex[:25]
|
||||||
|
|
||||||
|
|
||||||
|
_PATRON_BUCEFALO = re.compile(r"buc[eé]falo", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
async def _validar_solo_admin_agente(
|
||||||
|
conn,
|
||||||
|
auth: dict,
|
||||||
|
servicios,
|
||||||
|
plan_bucefalo,
|
||||||
|
recurso_id: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Bloquea a agentes que intenten incluir servicios soloAdmin o planes de Bucéfalo CRM."""
|
||||||
|
if auth.get("auth_type") != "agent":
|
||||||
|
return
|
||||||
|
|
||||||
|
motivos: list[str] = []
|
||||||
|
if plan_bucefalo is not None:
|
||||||
|
motivos.append("planBucefalo")
|
||||||
|
|
||||||
|
servicios_lista = servicios or []
|
||||||
|
catalogo_ids = [
|
||||||
|
s.catalogoId
|
||||||
|
for s in servicios_lista
|
||||||
|
if getattr(s, "catalogoId", None)
|
||||||
|
and not s.catalogoId.startswith("custom-")
|
||||||
|
and not s.catalogoId.lower().startswith("bucefalo-")
|
||||||
|
]
|
||||||
|
|
||||||
|
solo_admin_ids: set[str] = set()
|
||||||
|
if catalogo_ids:
|
||||||
|
rows = await conn.fetch(
|
||||||
|
'SELECT id FROM "ServicioCatalogo" WHERE id = ANY($1::text[]) AND "soloAdmin" = true',
|
||||||
|
catalogo_ids,
|
||||||
|
)
|
||||||
|
solo_admin_ids = {r["id"] for r in rows}
|
||||||
|
|
||||||
|
for s in servicios_lista:
|
||||||
|
cid = (getattr(s, "catalogoId", "") or "").strip()
|
||||||
|
nombre = (getattr(s, "nombre", "") or "").strip()
|
||||||
|
if cid.lower().startswith("bucefalo-"):
|
||||||
|
motivos.append(f"catalogoId:{cid}")
|
||||||
|
elif cid in solo_admin_ids:
|
||||||
|
motivos.append(f"soloAdmin:{cid}")
|
||||||
|
elif _PATRON_BUCEFALO.search(nombre):
|
||||||
|
motivos.append(f"nombre:{nombre}")
|
||||||
|
|
||||||
|
if motivos:
|
||||||
|
await registrar_auditoria(
|
||||||
|
conn,
|
||||||
|
auth,
|
||||||
|
"cotizacion.servicio_solo_admin_bloqueado",
|
||||||
|
"cotizacion",
|
||||||
|
recurso_id=recurso_id,
|
||||||
|
exito=False,
|
||||||
|
detalle={"motivos": motivos},
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Los servicios restringidos al administrador (incluidos los planes de Bucefalo CRM) no pueden ser agregados por agentes",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _insert_servicio_cotizado(
|
async def _insert_servicio_cotizado(
|
||||||
conn,
|
conn,
|
||||||
cotizacion_id: str,
|
cotizacion_id: str,
|
||||||
@@ -173,7 +235,7 @@ async def _resolve_bucefalo_servicio(conn) -> str | None:
|
|||||||
|
|
||||||
async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, telefono: str) -> str:
|
async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, telefono: str) -> str:
|
||||||
row = await conn.fetchrow(
|
row = await conn.fetchrow(
|
||||||
'SELECT id FROM "Cliente" WHERE nombre = $1 AND COALESCE(empresa, \'\') = $2',
|
'SELECT id FROM "Cliente" WHERE archivado = false AND nombre = $1 AND COALESCE(empresa, \'\') = $2',
|
||||||
nombre,
|
nombre,
|
||||||
empresa or "",
|
empresa or "",
|
||||||
)
|
)
|
||||||
@@ -211,6 +273,7 @@ async def list_cotizaciones(
|
|||||||
q: str | None = Query(None),
|
q: str | None = Query(None),
|
||||||
desde: str | None = Query(None),
|
desde: str | None = Query(None),
|
||||||
hasta: str | None = Query(None),
|
hasta: str | None = Query(None),
|
||||||
|
incluirArchivados: bool = Query(False),
|
||||||
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||||
):
|
):
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
@@ -232,6 +295,8 @@ async def list_cotizaciones(
|
|||||||
estado_efectivo = "aceptada" if solo_aceptadas else estado
|
estado_efectivo = "aceptada" if solo_aceptadas else estado
|
||||||
|
|
||||||
conditions: list[str] = []
|
conditions: list[str] = []
|
||||||
|
if auth.get("auth_type") == "agent" or not incluirArchivados:
|
||||||
|
conditions.append("c.archivado = false")
|
||||||
params: list = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
@@ -304,6 +369,7 @@ async def create_cotizacion(
|
|||||||
):
|
):
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
|
await _validar_solo_admin_agente(conn, auth, body.servicios, body.planBucefalo)
|
||||||
asesor_id = body.asesorId
|
asesor_id = body.asesorId
|
||||||
if not asesor_id:
|
if not asesor_id:
|
||||||
if auth.get("auth_type") == "jwt" and auth.get("userId"):
|
if auth.get("auth_type") == "jwt" and auth.get("userId"):
|
||||||
@@ -468,6 +534,13 @@ async def update_cotizacion(
|
|||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
detail="Los agentes no pueden cambiar el estado de la cotización",
|
detail="Los agentes no pueden cambiar el estado de la cotización",
|
||||||
)
|
)
|
||||||
|
await _validar_solo_admin_agente(
|
||||||
|
conn,
|
||||||
|
auth,
|
||||||
|
body.servicios,
|
||||||
|
body.planBucefalo,
|
||||||
|
recurso_id=cotizacion_id,
|
||||||
|
)
|
||||||
|
|
||||||
if body.estado is not None and body.estado != existing["estado"]:
|
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
|
# Si un humano intenta cambiar estado en PUT, exige las mismas reglas que PATCH /estado
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from app.models.common import ErrorResponse, OkResponse
|
|||||||
router = APIRouter(prefix="/paquetes", tags=["Paquetes"])
|
router = APIRouter(prefix="/paquetes", tags=["Paquetes"])
|
||||||
|
|
||||||
|
|
||||||
async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict]:
|
async def _build_paquetes_responses(conn, paquete_rows: list[dict], excluir_solo_admin: bool = False) -> list[dict]:
|
||||||
"""Build PaqueteResponse dicts for several paquetes with 2 queries in total
|
"""Build PaqueteResponse dicts for several paquetes with 2 queries in total
|
||||||
(instead of 1 + N fases per paquete)."""
|
(instead of 1 + N fases per paquete)."""
|
||||||
if not paquete_rows:
|
if not paquete_rows:
|
||||||
@@ -43,7 +43,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
|||||||
' sc."precioBase" AS "sc_precioBase", sc."tiempoEntrega" AS "sc_tiempoEntrega",'
|
' sc."precioBase" AS "sc_precioBase", sc."tiempoEntrega" AS "sc_tiempoEntrega",'
|
||||||
' sc."entregablesDefault" AS "sc_entregablesDefault",'
|
' sc."entregablesDefault" AS "sc_entregablesDefault",'
|
||||||
' sc."categoriaId" AS "sc_categoriaId", sc.variante AS "sc_variante",'
|
' sc."categoriaId" AS "sc_categoriaId", sc.variante AS "sc_variante",'
|
||||||
' sc.activo AS "sc_activo", sc.orden AS "sc_orden",'
|
' sc.activo AS "sc_activo", sc."soloAdmin" AS "sc_soloAdmin", sc.orden AS "sc_orden",'
|
||||||
' sc."createdAt" AS "sc_createdAt", sc."updatedAt" AS "sc_updatedAt",'
|
' sc."createdAt" AS "sc_createdAt", sc."updatedAt" AS "sc_updatedAt",'
|
||||||
' cat.id AS "cat_id", cat.nombre AS "cat_nombre", cat.descripcion AS "cat_descripcion",'
|
' cat.id AS "cat_id", cat.nombre AS "cat_nombre", cat.descripcion AS "cat_descripcion",'
|
||||||
' cat.color AS "cat_color", cat.activo AS "cat_activo", cat.orden AS "cat_orden",'
|
' cat.color AS "cat_color", cat.activo AS "cat_activo", cat.orden AS "cat_orden",'
|
||||||
@@ -57,6 +57,8 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
|||||||
|
|
||||||
servicios_por_fase: dict[str, list[dict]] = {}
|
servicios_por_fase: dict[str, list[dict]] = {}
|
||||||
for s in servicios_rows:
|
for s in servicios_rows:
|
||||||
|
if excluir_solo_admin and s.get("sc_soloAdmin"):
|
||||||
|
continue
|
||||||
cat = None
|
cat = None
|
||||||
if s["cat_id"]:
|
if s["cat_id"]:
|
||||||
cat = {
|
cat = {
|
||||||
@@ -87,6 +89,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
|||||||
"categoriaId": s["sc_categoriaId"],
|
"categoriaId": s["sc_categoriaId"],
|
||||||
"variante": s["sc_variante"],
|
"variante": s["sc_variante"],
|
||||||
"activo": s["sc_activo"],
|
"activo": s["sc_activo"],
|
||||||
|
"soloAdmin": bool(s.get("sc_soloAdmin", False)),
|
||||||
"orden": s["sc_orden"],
|
"orden": s["sc_orden"],
|
||||||
"createdAt": s["sc_createdAt"],
|
"createdAt": s["sc_createdAt"],
|
||||||
"updatedAt": s["sc_updatedAt"],
|
"updatedAt": s["sc_updatedAt"],
|
||||||
@@ -120,9 +123,9 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
async def _build_paquete_response(conn, paquete_row: dict, excluir_solo_admin: bool = False) -> dict:
|
||||||
"""Build a PaqueteResponse dict with nested fases and servicios."""
|
"""Build a PaqueteResponse dict with nested fases and servicios."""
|
||||||
results = await _build_paquetes_responses(conn, [paquete_row])
|
results = await _build_paquetes_responses(conn, [paquete_row], excluir_solo_admin=excluir_solo_admin)
|
||||||
return results[0]
|
return results[0]
|
||||||
|
|
||||||
|
|
||||||
@@ -135,7 +138,8 @@ async def list_paquetes(
|
|||||||
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
||||||
' FROM "Paquete" WHERE activo = true ORDER BY "createdAt" ASC'
|
' FROM "Paquete" WHERE activo = true ORDER BY "createdAt" ASC'
|
||||||
)
|
)
|
||||||
return await _build_paquetes_responses(conn, [dict(row) for row in rows])
|
excluir = _auth.get("auth_type") == "agent"
|
||||||
|
return await _build_paquetes_responses(conn, [dict(row) for row in rows], excluir_solo_admin=excluir)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
@@ -192,7 +196,8 @@ async def get_paquete(
|
|||||||
status_code=status.HTTP_404_NOT_FOUND,
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
detail="Paquete no encontrado",
|
detail="Paquete no encontrado",
|
||||||
)
|
)
|
||||||
return await _build_paquete_response(conn, dict(row))
|
excluir = _auth.get("auth_type") == "agent"
|
||||||
|
return await _build_paquete_response(conn, dict(row), excluir_solo_admin=excluir)
|
||||||
|
|
||||||
|
|
||||||
@router.put(
|
@router.put(
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
- **Clave de partida:** `refPartida`, formato `P01`. El cuid de `ServicioCotizado` nunca sale hacia el proveedor.
|
- **Clave de partida:** `refPartida`, formato `P01`. El cuid de `ServicioCotizado` nunca sale hacia el proveedor.
|
||||||
- **Evidencia:** arrays de IDs (`citas[]`, `hechos[]`), nunca prosa.
|
- **Evidencia:** arrays de IDs (`citas[]`, `hechos[]`), nunca prosa.
|
||||||
- **Ratio precio/valor:** base `totalPrimerAnio` (único + mensual × 12, **con IVA**), calculado en código con `calcularTotalesCotizacion()`.
|
- **Ratio precio/valor:** base `totalPrimerAnio` (único + mensual × 12, **con IVA**), calculado en código con `calcularTotalesCotizacion()`.
|
||||||
- **Marca:** el CRM se llama **Bucéfalo**. E3 solo ofrece servicios digitales. MXN, IVA 16%, CFDI. Español de México, tuteo, sin lenguaje corporativo vacío.
|
- **Marca:** el CRM se llama **Bucéfalo**. Uriel Jareth Consulting solo ofrece servicios digitales. MXN, IVA 16%, CFDI. Español de México, tuteo, sin lenguaje corporativo vacío.
|
||||||
- **Nombres de empleados detectados:** se advierten en el reporte, no bloquean.
|
- **Nombres de empleados detectados:** se advierten en el reporte, no bloquean.
|
||||||
- **Sin suite de pruebas en el repo.** La verificación es `npx tsc --noEmit` + `npm run lint` + un script de comprobación funcional por tarea (`npx tsx`). Cada tarea define el suyo.
|
- **Sin suite de pruebas en el repo.** La verificación es `npx tsc --noEmit` + `npm run lint` + un script de comprobación funcional por tarea (`npx tsx`). Cada tarea define el suyo.
|
||||||
- **Dependencias del API Python fijadas a versión exacta.** No aplica a este plan (todo es TypeScript), pero si se toca `api/requirements.txt`, se fija.
|
- **Dependencias del API Python fijadas a versión exacta.** No aplica a este plan (todo es TypeScript), pero si se toca `api/requirements.txt`, se fija.
|
||||||
@@ -252,7 +252,7 @@ git commit -m "Propuesta IA: modelo PropuestaIA y capa de datos economicos"
|
|||||||
- Consumes: nada (solo `zod`).
|
- Consumes: nada (solo `zod`).
|
||||||
- Produces: `hechosSchema`, `diagnosticoSchema`, `redaccionSchema` (los tres `z.ZodType`), los tipos `Hechos`, `Diagnostico`, `PropuestaConsultiva`, y `function aJsonSchema(schema: z.ZodType): Record<string, unknown>`.
|
- Produces: `hechosSchema`, `diagnosticoSchema`, `redaccionSchema` (los tres `z.ZodType`), los tipos `Hechos`, `Diagnostico`, `PropuestaConsultiva`, y `function aJsonSchema(schema: z.ZodType): Record<string, unknown>`.
|
||||||
|
|
||||||
Nota crítica: **ningún schema contiene un campo de dinero de la cotización.** `montoAnualMXN` sí existe, pero es el costo del *problema del cliente* que la IA estima desde la transcripción — no un precio de E3.
|
Nota crítica: **ningún schema contiene un campo de dinero de la cotización.** `montoAnualMXN` sí existe, pero es el costo del *problema del cliente* que la IA estima desde la transcripción — no un precio de Uriel Jareth Consulting.
|
||||||
|
|
||||||
- [ ] **Step 1: Escribir los schemas**
|
- [ ] **Step 1: Escribir los schemas**
|
||||||
|
|
||||||
@@ -310,7 +310,7 @@ export const diagnosticoSchema = z.object({
|
|||||||
descripcion: z.string(),
|
descripcion: z.string(),
|
||||||
calculo: z.object({
|
calculo: z.object({
|
||||||
factores: z.array(z.object({ nombre: z.string(), valor: z.number() })).min(2),
|
factores: z.array(z.object({ nombre: z.string(), valor: z.number() })).min(2),
|
||||||
montoAnualMXN: z.number().nullable().describe("Costo ANUAL del problema del CLIENTE. No es un precio de E3."),
|
montoAnualMXN: z.number().nullable().describe("Costo ANUAL del problema del CLIENTE. No es un precio de Uriel Jareth Consulting."),
|
||||||
}),
|
}),
|
||||||
confianza: z.enum(CONFIANZA),
|
confianza: z.enum(CONFIANZA),
|
||||||
hechos: z.array(z.string().regex(ID_HECHO)),
|
hechos: z.array(z.string().regex(ID_HECHO)),
|
||||||
@@ -657,17 +657,17 @@ export const SYSTEM_BASE = `
|
|||||||
# QUIEN ERES
|
# QUIEN ERES
|
||||||
|
|
||||||
Consultor senior de digitalizacion de negocios para PyMEs mexicanas. Redactas la parte
|
Consultor senior de digitalizacion de negocios para PyMEs mexicanas. Redactas la parte
|
||||||
narrativa de las propuestas de Consultoria E3 (Queretaro, MX). No eres vendedor: eres
|
narrativa de las propuestas de Uriel Jareth Consulting. No eres vendedor: eres
|
||||||
diagnosticador. Tu trabajo es explicar por que la inversion tiene sentido, nunca decidir
|
diagnosticador. Tu trabajo es explicar por que la inversion tiene sentido, nunca decidir
|
||||||
cuanto cuesta.
|
cuanto cuesta.
|
||||||
|
|
||||||
# LOS PRINCIPIOS QUE NO SE NEGOCIAN
|
# LOS PRINCIPIOS QUE NO SE NEGOCIAN
|
||||||
|
|
||||||
P1. NO TOCAS LOS NUMEROS. No calculas, propones ni mencionas precios, totales, IVA ni
|
P1. NO TOCAS LOS NUMEROS. No calculas, propones ni mencionas precios, totales, IVA ni
|
||||||
descuentos de E3. Ni siquiera los ves. Si necesitas referirte a una partida, usa su
|
descuentos de Uriel Jareth Consulting. Ni siquiera los ves. Si necesitas referirte a una partida, usa su
|
||||||
refPartida (P01, P02...). El sistema inyecta los importes despues.
|
refPartida (P01, P02...). El sistema inyecta los importes despues.
|
||||||
Si escribes una cifra en pesos, solo puede ser el costo del problema DEL CLIENTE
|
Si escribes una cifra en pesos, solo puede ser el costo del problema DEL CLIENTE
|
||||||
(lo que le cuesta hoy no resolverlo), nunca un precio de E3.
|
(lo que le cuesta hoy no resolverlo), nunca un precio de Uriel Jareth Consulting.
|
||||||
|
|
||||||
P2. TODA AFIRMACION ES TRAZABLE. Cada cosa que digas sobre el cliente apunta a una cita
|
P2. TODA AFIRMACION ES TRAZABLE. Cada cosa que digas sobre el cliente apunta a una cita
|
||||||
(C01...) o a un hecho (H01...). Si no tiene origen, no se escribe.
|
(C01...) o a un hecho (H01...). Si no tiene origen, no se escribe.
|
||||||
@@ -709,8 +709,8 @@ P8. NO PROPONES SERVICIOS QUE EL ASESOR NO ELIGIO. Si detectas una necesidad que
|
|||||||
- Prohibido el lenguaje corporativo vacio: sinergias, holistico, stakeholders, ecosistema,
|
- Prohibido el lenguaje corporativo vacio: sinergias, holistico, stakeholders, ecosistema,
|
||||||
disruptivo, robusto, potenciar, empoderar.
|
disruptivo, robusto, potenciar, empoderar.
|
||||||
- El CRM se llama Bucefalo. No menciones ningun otro CRM, por ningun motivo.
|
- El CRM se llama Bucefalo. No menciones ningun otro CRM, por ningun motivo.
|
||||||
- E3 ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing tradicional
|
- Uriel Jareth Consulting ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing tradicional
|
||||||
o diseno para imprenta, va a exclusiones aclarando que no es un servicio de E3.
|
o diseno para imprenta, va a exclusiones aclarando que no es un servicio de Uriel Jareth Consulting.
|
||||||
- Moneda MXN, IVA 16%, facturacion CFDI. Jamas montos en USD.
|
- Moneda MXN, IVA 16%, facturacion CFDI. Jamas montos en USD.
|
||||||
- No prometas resultados garantizados de mercado: ni ventas, ni posicion #1 en Google, ni
|
- No prometas resultados garantizados de mercado: ni ventas, ni posicion #1 en Google, ni
|
||||||
numero de leads. Prometes entregables, procesos y metricas de seguimiento. La palabra
|
numero de leads. Prometes entregables, procesos y metricas de seguimiento. La palabra
|
||||||
@@ -795,7 +795,7 @@ Reglas del paso:
|
|||||||
debe cuadrar: montoAnualMXN tiene que ser el producto o la suma de los factores.
|
debe cuadrar: montoAnualMXN tiene que ser el producto o la suma de los factores.
|
||||||
Si no tienes cifras, deja montoAnualMXN en null y marca por_validar.
|
Si no tienes cifras, deja montoAnualMXN en null y marca por_validar.
|
||||||
- Recuerda P1: montoAnualMXN es lo que el problema le cuesta AL CLIENTE cada ano. No es un
|
- Recuerda P1: montoAnualMXN es lo que el problema le cuesta AL CLIENTE cada ano. No es un
|
||||||
precio de E3.`;
|
precio de Uriel Jareth Consulting.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mensajePaso3(
|
export function mensajePaso3(
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- Migracion aditiva: soloAdmin en ServicioCatalogo (oculto para bots) y archivo reversible en Cliente y Cotizacion
|
||||||
|
|
||||||
|
ALTER TABLE "ServicioCatalogo"
|
||||||
|
ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- Marcar planes/servicios de Bucefalo CRM como soloAdmin = true (visibles solo en web admin, ocultos a agentes)
|
||||||
|
UPDATE "ServicioCatalogo"
|
||||||
|
SET "soloAdmin" = true
|
||||||
|
WHERE id IN ('configuracion-y-puesta-en-marc-12', 'plan-mensual-crm-bucefalo-18')
|
||||||
|
OR LOWER(nombre) LIKE '%bucefalo%'
|
||||||
|
OR LOWER(nombre) LIKE '%bucéfalo%';
|
||||||
|
|
||||||
|
ALTER TABLE "Cliente"
|
||||||
|
ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado");
|
||||||
|
|
||||||
|
ALTER TABLE "Cotizacion"
|
||||||
|
ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado");
|
||||||
+20
-11
@@ -25,16 +25,18 @@ model User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model Cliente {
|
model Cliente {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
nombre String
|
nombre String
|
||||||
empresa String?
|
empresa String?
|
||||||
// Cargo de la persona de contacto (ej. "Director"). Solo informativo.
|
// Cargo de la persona de contacto (ej. "Director"). Solo informativo.
|
||||||
puesto String?
|
puesto String?
|
||||||
email String?
|
email String?
|
||||||
telefono String?
|
telefono String?
|
||||||
rfc String?
|
rfc String?
|
||||||
createdAt DateTime @default(now())
|
archivado Boolean @default(false)
|
||||||
updatedAt DateTime @updatedAt
|
archivadoAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
cotizaciones Cotizacion[]
|
cotizaciones Cotizacion[]
|
||||||
// Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente.
|
// Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente.
|
||||||
@@ -42,6 +44,7 @@ model Cliente {
|
|||||||
programasPago ProgramaPago[]
|
programasPago ProgramaPago[]
|
||||||
|
|
||||||
@@index([nombre, empresa])
|
@@index([nombre, empresa])
|
||||||
|
@@index([archivado])
|
||||||
}
|
}
|
||||||
|
|
||||||
model Cotizacion {
|
model Cotizacion {
|
||||||
@@ -79,8 +82,10 @@ model Cotizacion {
|
|||||||
rechazadaAt DateTime?
|
rechazadaAt DateTime?
|
||||||
vencidaAt DateTime?
|
vencidaAt DateTime?
|
||||||
creadaPorAgente String?
|
creadaPorAgente String?
|
||||||
createdAt DateTime @default(now())
|
archivado Boolean @default(false)
|
||||||
updatedAt DateTime @updatedAt
|
archivadoAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
cliente Cliente @relation(fields: [clienteId], references: [id])
|
cliente Cliente @relation(fields: [clienteId], references: [id])
|
||||||
asesor User @relation("AsesorCotizaciones", fields: [asesorId], references: [id])
|
asesor User @relation("AsesorCotizaciones", fields: [asesorId], references: [id])
|
||||||
@@ -94,6 +99,7 @@ model Cotizacion {
|
|||||||
@@index([clienteId])
|
@@index([clienteId])
|
||||||
@@index([asesorId])
|
@@index([asesorId])
|
||||||
@@index([estado])
|
@@index([estado])
|
||||||
|
@@index([archivado])
|
||||||
@@index([createdAt])
|
@@index([createdAt])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,6 +154,9 @@ model ServicioCatalogo {
|
|||||||
variante String?
|
variante String?
|
||||||
nivel String?
|
nivel String?
|
||||||
activo Boolean @default(true)
|
activo Boolean @default(true)
|
||||||
|
// Si es true, queda oculto para todas las claves de agentes/bots y solo puede
|
||||||
|
// agregarlo un administrador humano desde la web (p. ej. planes de Bucefalo CRM).
|
||||||
|
soloAdmin Boolean @default(false)
|
||||||
orden Int @default(0)
|
orden Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|||||||
@@ -362,6 +362,7 @@ async function main() {
|
|||||||
{
|
{
|
||||||
nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo",
|
nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo",
|
||||||
descripcion: "Configuracion inicial de cuenta CRM Bucefalo",
|
descripcion: "Configuracion inicial de cuenta CRM Bucefalo",
|
||||||
|
soloAdmin: true,
|
||||||
fase: 1,
|
fase: 1,
|
||||||
tipoPago: "unico",
|
tipoPago: "unico",
|
||||||
precioBase: 3900,
|
precioBase: 3900,
|
||||||
@@ -470,6 +471,7 @@ async function main() {
|
|||||||
{
|
{
|
||||||
nombre: "Plan Mensual CRM Bucefalo",
|
nombre: "Plan Mensual CRM Bucefalo",
|
||||||
descripcion: "Suscripcion mensual al CRM Bucefalo",
|
descripcion: "Suscripcion mensual al CRM Bucefalo",
|
||||||
|
soloAdmin: true,
|
||||||
fase: 2,
|
fase: 2,
|
||||||
tipoPago: "mensual",
|
tipoPago: "mensual",
|
||||||
precioBase: 3900,
|
precioBase: 3900,
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ interface Servicio {
|
|||||||
variante: string | null;
|
variante: string | null;
|
||||||
nivel: string | null;
|
nivel: string | null;
|
||||||
activo: boolean;
|
activo: boolean;
|
||||||
|
soloAdmin?: boolean;
|
||||||
orden: number;
|
orden: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,6 +351,14 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
|
|||||||
<div className="font-medium flex flex-wrap items-center gap-2 min-w-0">
|
<div className="font-medium flex flex-wrap items-center gap-2 min-w-0">
|
||||||
<span className="break-words">{s.nombre}</span>
|
<span className="break-words">{s.nombre}</span>
|
||||||
{s.nivel && <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">{s.nivel}</span>}
|
{s.nivel && <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">{s.nivel}</span>}
|
||||||
|
{s.soloAdmin && (
|
||||||
|
<span
|
||||||
|
className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-slate-200 text-slate-700"
|
||||||
|
title="Visible solo para Jareth en la web; oculto para bots y agentes IA"
|
||||||
|
>
|
||||||
|
Solo admin
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{s.descripcion && <div className="text-xs text-muted mt-0.5 break-words">{s.descripcion}</div>}
|
{s.descripcion && <div className="text-xs text-muted mt-0.5 break-words">{s.descripcion}</div>}
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export default async function CatalogoPage() {
|
|||||||
variante: s.variante,
|
variante: s.variante,
|
||||||
nivel: s.nivel,
|
nivel: s.nivel,
|
||||||
activo: s.activo,
|
activo: s.activo,
|
||||||
|
soloAdmin: s.soloAdmin,
|
||||||
orden: s.orden,
|
orden: s.orden,
|
||||||
}))}
|
}))}
|
||||||
initialCategorias={categorias}
|
initialCategorias={categorias}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export default async function ClientesPage({
|
|||||||
const [{ nuevo }, clientes] = await Promise.all([
|
const [{ nuevo }, clientes] = await Promise.all([
|
||||||
searchParams,
|
searchParams,
|
||||||
prisma.cliente.findMany({
|
prisma.cliente.findMany({
|
||||||
|
where: { archivado: false },
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
select: clienteSelect,
|
select: clienteSelect,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -39,11 +39,11 @@ export function CambiarEstadoButtons({
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [showEnviarModal, setShowEnviarModal] = useState(false);
|
const [showEnviarModal, setShowEnviarModal] = useState(false);
|
||||||
const [canal, setCanal] = useState<"email" | "whatsapp_chatwoot" | "manual">(
|
const [canal, setCanal] = useState<"email" | "whatsapp_chatwoot" | "manual">(
|
||||||
clienteEmail ? "email" : clienteTelefono ? "whatsapp_chatwoot" : "manual"
|
clienteTelefono ? "whatsapp_chatwoot" : clienteEmail ? "email" : "manual"
|
||||||
);
|
);
|
||||||
const [destino, setDestino] = useState(clienteEmail || clienteTelefono || "");
|
const [destino, setDestino] = useState(clienteTelefono || clienteEmail || "");
|
||||||
const [mensaje, setMensaje] = useState("");
|
const [mensaje, setMensaje] = useState("");
|
||||||
const [fallbackEmail, setFallbackEmail] = useState(Boolean(clienteEmail));
|
const [fallbackEmail, setFallbackEmail] = useState(true);
|
||||||
|
|
||||||
const handleAprobar = async () => {
|
const handleAprobar = async () => {
|
||||||
const ok = await confirm({
|
const ok = await confirm({
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export const dynamic = "force-dynamic";
|
|||||||
|
|
||||||
export default async function CotizacionesPage() {
|
export default async function CotizacionesPage() {
|
||||||
const cotizaciones = await prisma.cotizacion.findMany({
|
const cotizaciones = await prisma.cotizacion.findMany({
|
||||||
|
where: { archivado: false },
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
|||||||
@@ -13,8 +13,9 @@ export default async function DashboardPage() {
|
|||||||
totalClientes,
|
totalClientes,
|
||||||
totalServicios,
|
totalServicios,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
prisma.cotizacion.count(),
|
prisma.cotizacion.count({ where: { archivado: false } }),
|
||||||
prisma.cotizacion.findMany({
|
prisma.cotizacion.findMany({
|
||||||
|
where: { archivado: false },
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
select: {
|
select: {
|
||||||
@@ -28,7 +29,7 @@ export default async function DashboardPage() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
prisma.cliente.count(),
|
prisma.cliente.count({ where: { archivado: false } }),
|
||||||
prisma.servicioCatalogo.count({ where: { activo: true } }),
|
prisma.servicioCatalogo.count({ where: { activo: true } }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { requireStaff } from "@/lib/auth";
|
import { requireStaff } from "@/lib/auth";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
import { servicioCatalogoPatchSchema } from "@/lib/schemas";
|
import { servicioCatalogoPatchSchema } from "@/lib/schemas";
|
||||||
import {
|
import {
|
||||||
categoriaExiste,
|
categoriaExiste,
|
||||||
@@ -17,18 +19,42 @@ const noEncontrado = (id: string) =>
|
|||||||
NextResponse.json({ error: `No existe el servicio ${id}` }, { status: 404 });
|
NextResponse.json({ error: `No existe el servicio ${id}` }, { status: 404 });
|
||||||
|
|
||||||
// GET /api/catalogo/[id] — un servicio del catalogo.
|
// GET /api/catalogo/[id] — un servicio del catalogo.
|
||||||
export async function GET(_request: NextRequest, { params }: Ctx) {
|
export async function GET(request: NextRequest, { params }: Ctx) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
|
||||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["catalogo:leer"],
|
||||||
|
recursoTipo: "catalogo",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const servicio = await prisma.servicioCatalogo.findUnique({
|
const servicio = await prisma.servicioCatalogo.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: servicioCatalogoInclude,
|
include: servicioCatalogoInclude,
|
||||||
});
|
});
|
||||||
if (!servicio) return noEncontrado(id);
|
if (!servicio) return applyHeaders(noEncontrado(id), auth.rateLimitHeaders);
|
||||||
return NextResponse.json(serializarServicio(servicio));
|
|
||||||
|
if (auth.actor.type === "agent" && servicio.soloAdmin) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "catalogo.solo_admin_bloqueado",
|
||||||
|
recursoTipo: "catalogo",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { nombre: servicio.nombre },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Este servicio esta restringido solo al administrador y no esta disponible para agentes" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
auth.rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(serializarServicio(servicio)), auth.rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorInterno(error);
|
return errorInterno(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,8 +40,10 @@ export async function GET(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const esAgente = auth.actor.type === "agent";
|
||||||
const servicios = await prisma.servicioCatalogo.findMany({
|
const servicios = await prisma.servicioCatalogo.findMany({
|
||||||
where: {
|
where: {
|
||||||
|
...(esAgente && { soloAdmin: false }),
|
||||||
...(q && {
|
...(q && {
|
||||||
OR: [
|
OR: [
|
||||||
{ nombre: { contains: q, mode: "insensitive" as const } },
|
{ nombre: { contains: q, mode: "insensitive" as const } },
|
||||||
@@ -93,6 +95,7 @@ export async function POST(request: NextRequest) {
|
|||||||
variante: data.variante ?? null,
|
variante: data.variante ?? null,
|
||||||
nivel: data.nivel ?? null,
|
nivel: data.nivel ?? null,
|
||||||
activo: data.activo ?? true,
|
activo: data.activo ?? true,
|
||||||
|
soloAdmin: data.soloAdmin ?? false,
|
||||||
orden: data.orden ?? (await siguienteOrden(data.fase)),
|
orden: data.orden ?? (await siguienteOrden(data.fase)),
|
||||||
},
|
},
|
||||||
include: servicioCatalogoInclude,
|
include: servicioCatalogoInclude,
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
const archivarSchema = z.object({
|
||||||
|
archivado: z.boolean().default(true),
|
||||||
|
incluirCotizaciones: z.boolean().default(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/clientes/[id]/archivar — archivo reversible (sin borrado definitivo).
|
||||||
|
// Reservado a personal humano (staffOnly).
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
staffOnly: true,
|
||||||
|
accionBloqueo: "cliente.archivar_bloqueado",
|
||||||
|
recursoTipo: "cliente",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => ({}));
|
||||||
|
const parsed = archivarSchema.safeParse(body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cliente = await prisma.cliente.findUnique({ where: { id }, select: { id: true, nombre: true, empresa: true } });
|
||||||
|
if (!cliente) {
|
||||||
|
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = parsed.data.archivado ? new Date() : null;
|
||||||
|
|
||||||
|
const result = await prisma.$transaction(async (tx) => {
|
||||||
|
const updatedCliente = await tx.cliente.update({
|
||||||
|
where: { id },
|
||||||
|
data: { archivado: parsed.data.archivado, archivadoAt: now },
|
||||||
|
select: { id: true, nombre: true, empresa: true, archivado: true, archivadoAt: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
let cotizacionesActualizadas = 0;
|
||||||
|
if (parsed.data.incluirCotizaciones) {
|
||||||
|
const res = await tx.cotizacion.updateMany({
|
||||||
|
where: { clienteId: id },
|
||||||
|
data: { archivado: parsed.data.archivado, archivadoAt: now },
|
||||||
|
});
|
||||||
|
cotizacionesActualizadas = res.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { cliente: updatedCliente, cotizacionesActualizadas };
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: parsed.data.archivado ? "cliente.archivar" : "cliente.desarchivar",
|
||||||
|
recursoTipo: "cliente",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
nombre: cliente.nombre,
|
||||||
|
empresa: cliente.empresa,
|
||||||
|
cotizacionesActualizadas: result.cotizacionesActualizadas,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, ...result });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,17 +17,22 @@ export async function GET(request: NextRequest) {
|
|||||||
if (!auth.ok) return auth.response;
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const q = request.nextUrl.searchParams.get("q")?.trim();
|
const q = request.nextUrl.searchParams.get("q")?.trim();
|
||||||
|
const incluirArchivados =
|
||||||
|
auth.actor.type !== "agent" && request.nextUrl.searchParams.get("incluirArchivados") === "true";
|
||||||
const clientes = await prisma.cliente.findMany({
|
const clientes = await prisma.cliente.findMany({
|
||||||
where: q
|
where: {
|
||||||
? {
|
...(!incluirArchivados && { archivado: false }),
|
||||||
OR: [
|
...(q
|
||||||
{ nombre: { contains: q, mode: "insensitive" } },
|
? {
|
||||||
{ empresa: { contains: q, mode: "insensitive" } },
|
OR: [
|
||||||
{ email: { contains: q, mode: "insensitive" } },
|
{ nombre: { contains: q, mode: "insensitive" } },
|
||||||
{ rfc: { contains: q, mode: "insensitive" } },
|
{ empresa: { contains: q, mode: "insensitive" } },
|
||||||
],
|
{ email: { contains: q, mode: "insensitive" } },
|
||||||
}
|
{ rfc: { contains: q, mode: "insensitive" } },
|
||||||
: undefined,
|
],
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
orderBy: { nombre: "asc" },
|
orderBy: { nombre: "asc" },
|
||||||
select: clienteSelect,
|
select: clienteSelect,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,12 +25,12 @@ import {
|
|||||||
} from "@/lib/calculators";
|
} from "@/lib/calculators";
|
||||||
|
|
||||||
const enviarSchema = z.object({
|
const enviarSchema = z.object({
|
||||||
canal: z.enum(["email", "whatsapp_chatwoot", "manual"]).default("email"),
|
canal: z.enum(["email", "whatsapp_chatwoot", "manual"]).default("whatsapp_chatwoot"),
|
||||||
destino: z.string().trim().optional(),
|
destino: z.string().trim().optional(),
|
||||||
mensaje: z.string().trim().max(2000).optional(),
|
mensaje: z.string().trim().max(2000).optional(),
|
||||||
verificarContacto: z.string().trim().optional(),
|
verificarContacto: z.string().trim().optional(),
|
||||||
chatwootConversationId: z.union([z.number().int(), z.string()]).optional(),
|
chatwootConversationId: z.union([z.number().int(), z.string()]).optional(),
|
||||||
fallbackEmail: z.boolean().optional(),
|
fallbackEmail: z.boolean().default(true),
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
@@ -191,18 +191,44 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
} else if (data.canal === "whatsapp_chatwoot") {
|
} else if (data.canal === "whatsapp_chatwoot") {
|
||||||
destinoFinal = (data.destino || cot.cliente.telefono || "").trim();
|
destinoFinal = (data.destino || cot.cliente.telefono || "").trim();
|
||||||
if (!destinoFinal) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "El cliente no tiene telefono registrado y no se proporciono destino" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pdf = await generarPDFCotizacion(id);
|
const pdf = await generarPDFCotizacion(id);
|
||||||
if (!pdf) {
|
if (!pdf) {
|
||||||
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!destinoFinal) {
|
||||||
|
if (data.fallbackEmail && cot.cliente.email) {
|
||||||
|
const emailRes = await enviarCotizacionPorCorreo({
|
||||||
|
to: cot.cliente.email,
|
||||||
|
numero: cot.numero,
|
||||||
|
clienteNombre: cot.cliente.nombre,
|
||||||
|
empresa: cot.cliente.empresa,
|
||||||
|
proyecto: cot.proyecto,
|
||||||
|
resumenTotales,
|
||||||
|
vigenciaTexto,
|
||||||
|
pdfBuffer: pdf.buffer,
|
||||||
|
pdfFilename: pdf.filename,
|
||||||
|
mensajePersonalizado: data.mensaje,
|
||||||
|
});
|
||||||
|
if (!emailRes.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: `El cliente no tiene telefono y fallo el respaldo por correo: ${emailRes.error || "SMTP no disponible"}`,
|
||||||
|
reason: "missing_phone_fallback_failed",
|
||||||
|
},
|
||||||
|
{ status: 502 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
canalFinal = "email";
|
||||||
|
destinoFinal = cot.cliente.email;
|
||||||
|
} else {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El cliente no tiene telefono registrado y no se proporciono destino" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
|
||||||
const mensajeWa =
|
const mensajeWa =
|
||||||
data.mensaje?.trim() ||
|
data.mensaje?.trim() ||
|
||||||
`Hola ${cot.cliente.nombre}, te compartimos la cotización ${cot.numero} para ${cot.proyecto} (${resumenTotales}, vigencia al ${vigenciaTexto}).`;
|
`Hola ${cot.cliente.nombre}, te compartimos la cotización ${cot.numero} para ${cot.proyecto} (${resumenTotales}, vigencia al ${vigenciaTexto}).`;
|
||||||
@@ -296,6 +322,7 @@ export async function POST(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
import { registrarAuditoria } from "@/lib/audit";
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
import { validarTransicionEstado } from "@/lib/aprobacion";
|
import { validarTransicionEstado } from "@/lib/aprobacion";
|
||||||
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
||||||
|
import { evaluarRestriccionSoloAdmin } from "@/lib/solo-admin-core";
|
||||||
|
|
||||||
export async function DELETE(
|
export async function DELETE(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
@@ -381,6 +382,47 @@ export async function PUT(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (actor.type === "agent") {
|
||||||
|
const idsConsultar = servicios
|
||||||
|
.filter((s) => !s.esPersonalizado && s.catalogoId && !s.catalogoId.startsWith("bucefalo-"))
|
||||||
|
.map((s) => s.catalogoId);
|
||||||
|
const restringidos = idsConsultar.length
|
||||||
|
? await prisma.servicioCatalogo.findMany({
|
||||||
|
where: { id: { in: idsConsultar }, soloAdmin: true },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
const check = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
planBucefalo,
|
||||||
|
servicios,
|
||||||
|
soloAdminCatalogIds: restringidos.map((r) => r.id),
|
||||||
|
});
|
||||||
|
if (!check.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.servicio_solo_admin_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { motivos: check.motivos, itemsBloqueados: check.itemsBloqueados },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
"Los servicios o planes marcados como solo_admin (incluyendo Bucefalo CRM) estan ocultos para agentes y solo puede agregarlos el administrador desde la web",
|
||||||
|
reason: "solo_admin_restricted",
|
||||||
|
detalles: check.motivos,
|
||||||
|
},
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let clienteIdFinal: string | undefined;
|
let clienteIdFinal: string | undefined;
|
||||||
if (cliente) {
|
if (cliente) {
|
||||||
const existingCliente = await prisma.cliente.findFirst({
|
const existingCliente = await prisma.cliente.findFirst({
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
notificarJarethBorrador,
|
notificarJarethBorrador,
|
||||||
} from "@/lib/aprobacion";
|
} from "@/lib/aprobacion";
|
||||||
import { emitirWebhook } from "@/lib/webhooks";
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
|
import { evaluarRestriccionSoloAdmin } from "@/lib/solo-admin-core";
|
||||||
import {
|
import {
|
||||||
bucefaloPrecio,
|
bucefaloPrecio,
|
||||||
calcularTotalesCotizacion,
|
calcularTotalesCotizacion,
|
||||||
@@ -92,10 +93,48 @@ export async function POST(request: NextRequest) {
|
|||||||
planBucefalo,
|
planBucefalo,
|
||||||
} = parsed.data;
|
} = parsed.data;
|
||||||
|
|
||||||
|
if (actor.type === "agent") {
|
||||||
|
const idsConsultar = servicios
|
||||||
|
.filter((s) => !s.esPersonalizado && s.catalogoId && !s.catalogoId.startsWith("bucefalo-"))
|
||||||
|
.map((s) => s.catalogoId);
|
||||||
|
const restringidos = idsConsultar.length
|
||||||
|
? await prisma.servicioCatalogo.findMany({
|
||||||
|
where: { id: { in: idsConsultar }, soloAdmin: true },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
const check = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
planBucefalo,
|
||||||
|
servicios,
|
||||||
|
soloAdminCatalogIds: restringidos.map((r) => r.id),
|
||||||
|
});
|
||||||
|
if (!check.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.servicio_solo_admin_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { motivos: check.motivos, itemsBloqueados: check.itemsBloqueados },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
"Los servicios o planes marcados como solo_admin (incluyendo Bucefalo CRM) estan ocultos para agentes y solo puede agregarlos el administrador desde la web",
|
||||||
|
reason: "solo_admin_restricted",
|
||||||
|
detalles: check.motivos,
|
||||||
|
},
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let clienteRecord = await prisma.cliente.findFirst({
|
let clienteRecord = await prisma.cliente.findFirst({
|
||||||
where: {
|
where: {
|
||||||
nombre: cliente.nombre,
|
nombre: cliente.nombre,
|
||||||
empresa: cliente.empresa || null,
|
empresa: cliente.empresa || null,
|
||||||
|
archivado: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -303,6 +342,7 @@ export async function GET(request: NextRequest) {
|
|||||||
const hasta = sp.get("hasta")?.trim();
|
const hasta = sp.get("hasta")?.trim();
|
||||||
const pageRaw = sp.get("page");
|
const pageRaw = sp.get("page");
|
||||||
const limitRaw = sp.get("limit");
|
const limitRaw = sp.get("limit");
|
||||||
|
const incluirArchivados = actor.type !== "agent" && sp.get("incluirArchivados") === "true";
|
||||||
|
|
||||||
if (soloAceptadas && estadoParam && estadoParam !== "aceptada") {
|
if (soloAceptadas && estadoParam && estadoParam !== "aceptada") {
|
||||||
await registrarAuditoria({
|
await registrarAuditoria({
|
||||||
@@ -361,6 +401,7 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const where: Prisma.CotizacionWhereInput = {
|
const where: Prisma.CotizacionWhereInput = {
|
||||||
|
...(!incluirArchivados && { archivado: false }),
|
||||||
...(estadoEfectivo && { estado: estadoEfectivo }),
|
...(estadoEfectivo && { estado: estadoEfectivo }),
|
||||||
...(clienteId && { clienteId }),
|
...(clienteId && { clienteId }),
|
||||||
...(Object.keys(clienteWhere).length > 0 && { cliente: clienteWhere }),
|
...(Object.keys(clienteWhere).length > 0 && { cliente: clienteWhere }),
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
"/api/catalogo": {
|
"/api/catalogo": {
|
||||||
get: {
|
get: {
|
||||||
summary: "Listar catálogo de servicios (scope: catalogo:leer)",
|
summary: "Listar catálogo de servicios (scope: catalogo:leer). Para agentes excluye automáticamente los servicios soloAdmin (p. ej. Bucéfalo CRM).",
|
||||||
responses: {
|
responses: {
|
||||||
"200": { description: "Lista de servicios" },
|
"200": { description: "Lista de servicios" },
|
||||||
"401": { $ref: "#/components/responses/Unauthorized" },
|
"401": { $ref: "#/components/responses/Unauthorized" },
|
||||||
@@ -109,6 +109,17 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
"/api/catalogo/{id}": {
|
||||||
|
get: {
|
||||||
|
summary: "Detalle de servicio (scope: catalogo:leer; devuelve 403 a agentes si soloAdmin=true)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Servicio" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
"404": { description: "No encontrado" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
"/api/categorias": {
|
"/api/categorias": {
|
||||||
get: {
|
get: {
|
||||||
summary: "Listar categorías del catálogo (scope: catalogo:leer)",
|
summary: "Listar categorías del catálogo (scope: catalogo:leer)",
|
||||||
@@ -142,6 +153,16 @@ export async function GET() {
|
|||||||
responses: { "200": { description: "Cliente actualizado" } },
|
responses: { "200": { description: "Cliente actualizado" } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
"/api/clientes/{id}/archivar": {
|
||||||
|
post: {
|
||||||
|
summary: "Archivar o desarchivar un cliente y sus cotizaciones de forma reversible (solo personal humano)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Cliente archivado/restaurado" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
"/api/cotizaciones": {
|
"/api/cotizaciones": {
|
||||||
get: {
|
get: {
|
||||||
summary: "Listar cotizaciones (scopes: cotizaciones:leer o cotizaciones:leer_aceptadas)",
|
summary: "Listar cotizaciones (scopes: cotizaciones:leer o cotizaciones:leer_aceptadas)",
|
||||||
@@ -162,10 +183,11 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
post: {
|
post: {
|
||||||
summary: "Crear borrador de cotización (scope: cotizaciones:borrador). Siempre inicia en borrador.",
|
summary: "Crear borrador de cotización (scope: cotizaciones:borrador). Siempre inicia en borrador; agentes reciben 403 si intentan incluir servicios soloAdmin (Bucéfalo CRM).",
|
||||||
parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }],
|
parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }],
|
||||||
responses: {
|
responses: {
|
||||||
"201": { description: "Borrador creado y notificación enviada a Jareth si lo creó un agente" },
|
"201": { description: "Borrador creado y notificación enviada a Jareth si lo creó un agente" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
"409": { $ref: "#/components/responses/Conflict" },
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -227,12 +249,12 @@ export async function GET() {
|
|||||||
schema: {
|
schema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
canal: { type: "string", enum: ["email", "whatsapp_chatwoot", "manual"], default: "email" },
|
canal: { type: "string", enum: ["whatsapp_chatwoot", "email", "manual"], default: "whatsapp_chatwoot" },
|
||||||
destino: { type: "string" },
|
destino: { type: "string" },
|
||||||
mensaje: { type: "string" },
|
mensaje: { type: "string" },
|
||||||
verificarContacto: { type: "string" },
|
verificarContacto: { type: "string" },
|
||||||
chatwootConversationId: { type: ["integer", "string"] },
|
chatwootConversationId: { type: ["integer", "string"] },
|
||||||
fallbackEmail: { type: "boolean" },
|
fallbackEmail: { type: "boolean", default: true },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
@@ -7,6 +8,13 @@ export async function GET(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["catalogo:leer"],
|
||||||
|
recursoTipo: "paquete",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const paquete = await prisma.paquete.findUnique({
|
const paquete = await prisma.paquete.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
@@ -20,8 +28,18 @@ export async function GET(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!paquete) return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
if (!paquete) return applyHeaders(NextResponse.json({ error: "No encontrado" }, { status: 404 }), auth.rateLimitHeaders);
|
||||||
return NextResponse.json(paquete);
|
const salida =
|
||||||
|
auth.actor.type === "agent"
|
||||||
|
? {
|
||||||
|
...paquete,
|
||||||
|
fases: paquete.fases.map((f) => ({
|
||||||
|
...f,
|
||||||
|
servicios: f.servicios.filter((sp) => !sp.servicio?.soloAdmin),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: paquete;
|
||||||
|
return applyHeaders(NextResponse.json(salida), auth.rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const msg = error instanceof Error ? error.message : "Error interno";
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
return NextResponse.json({ error: msg }, { status: 500 });
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
|||||||
@@ -25,7 +25,17 @@ export async function GET(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
orderBy: { createdAt: "asc" },
|
orderBy: { createdAt: "asc" },
|
||||||
});
|
});
|
||||||
return applyHeaders(NextResponse.json(paquetes), auth.rateLimitHeaders);
|
const salida =
|
||||||
|
auth.actor.type === "agent"
|
||||||
|
? paquetes.map((p) => ({
|
||||||
|
...p,
|
||||||
|
fases: p.fases.map((f) => ({
|
||||||
|
...f,
|
||||||
|
servicios: f.servicios.filter((sp) => !sp.servicio?.soloAdmin),
|
||||||
|
})),
|
||||||
|
}))
|
||||||
|
: paquetes;
|
||||||
|
return applyHeaders(NextResponse.json(salida), auth.rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const msg = error instanceof Error ? error.message : "Error interno";
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
return NextResponse.json({ error: msg }, { status: 500 });
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export interface ServicioCatalogoDatos {
|
|||||||
variante: string | null;
|
variante: string | null;
|
||||||
nivel: string | null;
|
nivel: string | null;
|
||||||
activo: boolean;
|
activo: boolean;
|
||||||
|
soloAdmin?: boolean;
|
||||||
orden: number;
|
orden: number;
|
||||||
enCotizaciones?: number;
|
enCotizaciones?: number;
|
||||||
}
|
}
|
||||||
@@ -79,6 +80,7 @@ export function ServicioFormModal({
|
|||||||
fase: servicio?.fase ?? faseInicial ?? 1,
|
fase: servicio?.fase ?? faseInicial ?? 1,
|
||||||
orden: servicio?.orden ?? "",
|
orden: servicio?.orden ?? "",
|
||||||
activo: servicio?.activo ?? true,
|
activo: servicio?.activo ?? true,
|
||||||
|
soloAdmin: servicio?.soloAdmin ?? false,
|
||||||
});
|
});
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -128,6 +130,7 @@ export function ServicioFormModal({
|
|||||||
if (avanzado) {
|
if (avanzado) {
|
||||||
if (form.orden !== "") payload.orden = Number(form.orden);
|
if (form.orden !== "") payload.orden = Number(form.orden);
|
||||||
payload.activo = form.activo;
|
payload.activo = form.activo;
|
||||||
|
payload.soloAdmin = form.soloAdmin;
|
||||||
}
|
}
|
||||||
const res = await fetch(editando ? `/api/catalogo/${servicio!.id}` : "/api/catalogo", {
|
const res = await fetch(editando ? `/api/catalogo/${servicio!.id}` : "/api/catalogo", {
|
||||||
method: editando ? "PATCH" : "POST",
|
method: editando ? "PATCH" : "POST",
|
||||||
@@ -283,15 +286,26 @@ export function ServicioFormModal({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{avanzado && (
|
{avanzado && (
|
||||||
<label className="flex items-center gap-2 text-sm">
|
<div className="space-y-2">
|
||||||
<input
|
<label className="flex items-center gap-2 text-sm">
|
||||||
type="checkbox"
|
<input
|
||||||
checked={form.activo}
|
type="checkbox"
|
||||||
onChange={(e) => update("activo", e.target.checked)}
|
checked={form.activo}
|
||||||
className="rounded border-border"
|
onChange={(e) => update("activo", e.target.checked)}
|
||||||
/>
|
className="rounded border-border"
|
||||||
Activo (visible al cotizar)
|
/>
|
||||||
</label>
|
Activo (visible al cotizar)
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2 text-sm">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.soloAdmin}
|
||||||
|
onChange={(e) => update("soloAdmin", e.target.checked)}
|
||||||
|
className="rounded border-border"
|
||||||
|
/>
|
||||||
|
Solo administrador (oculto para bots y agentes IA)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{error && (
|
{error && (
|
||||||
<p role="alert" className="text-sm text-danger bg-danger/10 border border-danger/30 rounded-lg px-3 py-2">
|
<p role="alert" className="text-sm text-danger bg-danger/10 border border-danger/30 rounded-lg px-3 py-2">
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ type ServicioConCategoria = {
|
|||||||
variante: string | null;
|
variante: string | null;
|
||||||
nivel: string | null;
|
nivel: string | null;
|
||||||
activo: boolean;
|
activo: boolean;
|
||||||
|
soloAdmin: boolean;
|
||||||
orden: number;
|
orden: number;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
@@ -48,6 +49,7 @@ export function serializarServicio(s: ServicioConCategoria) {
|
|||||||
variante: s.variante,
|
variante: s.variante,
|
||||||
nivel: s.nivel,
|
nivel: s.nivel,
|
||||||
activo: s.activo,
|
activo: s.activo,
|
||||||
|
soloAdmin: Boolean(s.soloAdmin),
|
||||||
orden: s.orden,
|
orden: s.orden,
|
||||||
enCotizaciones: s._count?.servicios ?? 0,
|
enCotizaciones: s._count?.servicios ?? 0,
|
||||||
createdAt: s.createdAt,
|
createdAt: s.createdAt,
|
||||||
|
|||||||
+4
-1
@@ -11,7 +11,9 @@ export const clienteSelect = {
|
|||||||
email: true,
|
email: true,
|
||||||
telefono: true,
|
telefono: true,
|
||||||
rfc: true,
|
rfc: true,
|
||||||
_count: { select: { cotizaciones: true } },
|
archivado: true,
|
||||||
|
archivadoAt: true,
|
||||||
|
_count: { select: { cotizaciones: { where: { archivado: false } } } },
|
||||||
usuario: { select: { id: true, email: true } },
|
usuario: { select: { id: true, email: true } },
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -21,6 +23,7 @@ export const clienteSelect = {
|
|||||||
export function buscarDuplicado(nombre: string, empresa: string | null, excluirId?: string) {
|
export function buscarDuplicado(nombre: string, empresa: string | null, excluirId?: string) {
|
||||||
return prisma.cliente.findFirst({
|
return prisma.cliente.findFirst({
|
||||||
where: {
|
where: {
|
||||||
|
archivado: false,
|
||||||
nombre: { equals: nombre, mode: "insensitive" },
|
nombre: { equals: nombre, mode: "insensitive" },
|
||||||
empresa: empresa ? { equals: empresa, mode: "insensitive" } : null,
|
empresa: empresa ? { equals: empresa, mode: "insensitive" } : null,
|
||||||
...(excluirId ? { NOT: { id: excluirId } } : {}),
|
...(excluirId ? { NOT: { id: excluirId } } : {}),
|
||||||
|
|||||||
@@ -156,6 +156,7 @@ const camposServicio = {
|
|||||||
variante: textoCatalogo,
|
variante: textoCatalogo,
|
||||||
nivel: nivelServicio,
|
nivel: nivelServicio,
|
||||||
activo: z.boolean().optional(),
|
activo: z.boolean().optional(),
|
||||||
|
soloAdmin: z.boolean().optional(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Campos que no existen en el catalogo se rechazan con su nombre (en vez de
|
// Campos que no existen en el catalogo se rechazan con su nombre (en vez de
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// Reglas puras para restringir servicios/planes soloAdmin (p. ej. Bucefalo CRM)
|
||||||
|
// frente a claves de agentes/bots. Jareth (usuario humano en web) nunca es bloqueado.
|
||||||
|
|
||||||
|
export interface ServicioDraftInput {
|
||||||
|
catalogoId?: string | null;
|
||||||
|
nombre?: string | null;
|
||||||
|
esPersonalizado?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EvaluarRestriccionSoloAdminInput {
|
||||||
|
esAgente: boolean;
|
||||||
|
planBucefalo?: unknown | null;
|
||||||
|
servicios: ServicioDraftInput[];
|
||||||
|
/** IDs de ServicioCatalogo existentes en BD marcados con soloAdmin=true */
|
||||||
|
soloAdminCatalogIds: Iterable<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EvaluarRestriccionSoloAdminResult {
|
||||||
|
ok: boolean;
|
||||||
|
motivos: string[];
|
||||||
|
itemsBloqueados: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const BUCEFALO_RE = /buc[eé]falo/i;
|
||||||
|
|
||||||
|
export function evaluarRestriccionSoloAdmin(
|
||||||
|
input: EvaluarRestriccionSoloAdminInput
|
||||||
|
): EvaluarRestriccionSoloAdminResult {
|
||||||
|
if (!input.esAgente) {
|
||||||
|
return { ok: true, motivos: [], itemsBloqueados: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const motivos: string[] = [];
|
||||||
|
const itemsBloqueados: string[] = [];
|
||||||
|
const restrictedIds = new Set(input.soloAdminCatalogIds);
|
||||||
|
|
||||||
|
if (input.planBucefalo !== null && input.planBucefalo !== undefined) {
|
||||||
|
motivos.push("planBucefalo esta reservado al administrador humano");
|
||||||
|
itemsBloqueados.push("planBucefalo");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const svc of input.servicios) {
|
||||||
|
const cid = (svc.catalogoId || "").trim();
|
||||||
|
const nombre = (svc.nombre || "").trim();
|
||||||
|
|
||||||
|
if (cid && /^bucefalo-/i.test(cid)) {
|
||||||
|
motivos.push(`catalogoId restringido (${cid})`);
|
||||||
|
itemsBloqueados.push(cid);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (cid && restrictedIds.has(cid)) {
|
||||||
|
motivos.push(`servicio marcado soloAdmin (${cid})`);
|
||||||
|
itemsBloqueados.push(cid);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (nombre && BUCEFALO_RE.test(nombre)) {
|
||||||
|
motivos.push(`servicio restringido por marca soloAdmin (${nombre})`);
|
||||||
|
itemsBloqueados.push(nombre);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: motivos.length === 0,
|
||||||
|
motivos,
|
||||||
|
itemsBloqueados,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { describe, it } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { evaluarRestriccionSoloAdmin } from "../src/lib/solo-admin-core";
|
||||||
|
|
||||||
|
describe("Restriccion soloAdmin / Bucefalo CRM para agentes", () => {
|
||||||
|
const soloAdminSet = new Set([
|
||||||
|
"configuracion-y-puesta-en-marc-12",
|
||||||
|
"plan-mensual-crm-bucefalo-18",
|
||||||
|
]);
|
||||||
|
|
||||||
|
it("permite a un administrador humano cotizar cualquier servicio soloAdmin o planBucefalo", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: false,
|
||||||
|
servicios: [
|
||||||
|
{ catalogoId: "plan-mensual-crm-bucefalo-18", nombre: "Plan Mensual CRM Bucefalo" },
|
||||||
|
{ catalogoId: "bucefalo-basico", nombre: "CRM Bucefalo Basico" },
|
||||||
|
],
|
||||||
|
planBucefalo: { nivel: "basico", precio: 2900 },
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, true);
|
||||||
|
assert.deepEqual(res.itemsBloqueados, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bloquea a agentes cuando envian un catalogoId marcado soloAdmin", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
servicios: [
|
||||||
|
{ catalogoId: "plan-mensual-crm-bucefalo-18", nombre: "Plan Mensual" },
|
||||||
|
],
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, false);
|
||||||
|
assert.ok(res.itemsBloqueados.includes("plan-mensual-crm-bucefalo-18"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bloquea a agentes cuando envian planBucefalo", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
servicios: [{ catalogoId: "landing-page", nombre: "Landing Page" }],
|
||||||
|
planBucefalo: { nivel: "estandar", precio: 4500 },
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, false);
|
||||||
|
assert.ok(res.itemsBloqueados.includes("planBucefalo"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bloquea a agentes cuando envian catalogoId sintetico bucefalo-*", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
servicios: [{ catalogoId: "bucefalo-premium", nombre: "CRM" }],
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, false);
|
||||||
|
assert.ok(res.itemsBloqueados.includes("bucefalo-premium"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bloquea a agentes que intentan colar Bucefalo como partida personalizada", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
servicios: [{ catalogoId: "custom-123", nombre: "Implementación CRM Bucéfalo mensual" }],
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, false);
|
||||||
|
assert.ok(res.itemsBloqueados.some((m) => m.includes("Bucéfalo")));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("permite a agentes cotizar servicios normales que no son soloAdmin", () => {
|
||||||
|
const res = evaluarRestriccionSoloAdmin({
|
||||||
|
esAgente: true,
|
||||||
|
servicios: [
|
||||||
|
{ catalogoId: "landing-page-pyme", nombre: "Landing Page PYME" },
|
||||||
|
{ catalogoId: "custom-1", nombre: "Automatizacion WhatsApp + n8n" },
|
||||||
|
],
|
||||||
|
planBucefalo: null,
|
||||||
|
soloAdminCatalogIds: soloAdminSet,
|
||||||
|
});
|
||||||
|
assert.equal(res.ok, true);
|
||||||
|
assert.deepEqual(res.itemsBloqueados, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user