feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
@@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
name: cotizador-cli
|
name: cotizador-cli
|
||||||
description: Usa el CLI `cotizador` para operar el Cotizador E3 desde la terminal — crear y editar servicios del catálogo, dar de alta clientes, armar cotizaciones, cambiar su estado, descargar PDF/Excel y registrar horas. Úsalo cuando pidan "crea un servicio", "sube el precio de X", "cotiza a este cliente", "lista las cotizaciones enviadas", "descarga el PDF de UJ..." o cualquier operación sobre la plataforma sin abrir el navegador.
|
description: Usa el CLI `cotizador` para operar el Cotizador — Uriel Jareth Consulting desde la terminal — crear y editar servicios del catálogo, dar de alta clientes, armar cotizaciones, cambiar su estado, descargar PDF/Excel y registrar horas. Úsalo cuando pidan "crea un servicio", "sube el precio de X", "cotiza a este cliente", "lista las cotizaciones enviadas", "descarga el PDF de UJ..." o cualquier operación sobre la plataforma sin abrir el navegador.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Operar el Cotizador E3 por CLI
|
# Operar el Cotizador — Uriel Jareth Consulting por CLI
|
||||||
|
|
||||||
El CLI vive en `cli/cotizador.mjs` (Node 18+, sin dependencias). Ejecútalo desde la raíz del repo con `node cli/cotizador.mjs <comando>`.
|
El CLI vive en `cli/cotizador.mjs` (Node 18+, sin dependencias). Ejecútalo desde la raíz del repo con `node cli/cotizador.mjs <comando>`.
|
||||||
|
|
||||||
|
|||||||
+31
-19
@@ -1,7 +1,8 @@
|
|||||||
# Cotizador E3 — variables de entorno
|
# Cotizador — Uriel Jareth Consulting — variables de entorno
|
||||||
# Copia este archivo a .env (local) o configúralas en Coolify (producción).
|
# Copia este archivo a .env (local) o configúralas en Coolify (producción).
|
||||||
|
|
||||||
# ── Base de datos (compartida por Next.js y el API Python) ──
|
# ── Base de datos (compartida por Next.js y el API Python) ──
|
||||||
|
# Se conserva el nombre físico de BD (cotizador_e3) en producción para no romper el volumen postgres_data.
|
||||||
DB_HOST=localhost
|
DB_HOST=localhost
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
DB_USER=postgres
|
DB_USER=postgres
|
||||||
@@ -9,19 +10,19 @@ DB_PASSWORD=postgres
|
|||||||
DB_NAME=cotizador_e3
|
DB_NAME=cotizador_e3
|
||||||
|
|
||||||
# Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines,
|
# Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines,
|
||||||
# se construye automáticamente desde las DB_* (ver prisma.config.ts).
|
# se construye automáticamente desde las DB_* (ver prisma.config.ts).
|
||||||
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3"
|
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3"
|
||||||
|
|
||||||
# ── Auth ──
|
# ── Auth ──
|
||||||
# OBLIGATORIA. Genera una con: openssl rand -base64 32
|
# OBLIGATORIA. Genera una con: openssl rand -base64 32
|
||||||
JWT_SECRET=
|
JWT_SECRET=
|
||||||
|
|
||||||
# ── API Python (api/) — clave para agentes de IA / n8n ──
|
# ── API Python (api/) — clave para agentes de IA / n8n ──
|
||||||
API_KEY=
|
API_KEY=
|
||||||
|
|
||||||
# ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ──
|
# ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ──
|
||||||
RUN_SEED=false
|
RUN_SEED=false
|
||||||
SEED_ADMIN_EMAIL=admin@e3.local
|
SEED_ADMIN_EMAIL=admin@urieljareth.com
|
||||||
SEED_ADMIN_PASSWORD=
|
SEED_ADMIN_PASSWORD=
|
||||||
SEED_ADMIN_NAME=Administrador
|
SEED_ADMIN_NAME=Administrador
|
||||||
# Asesor opcional: solo se crea si defines el email
|
# Asesor opcional: solo se crea si defines el email
|
||||||
@@ -30,35 +31,46 @@ SEED_ASESOR_PASSWORD=
|
|||||||
SEED_ASESOR_NAME=
|
SEED_ASESOR_NAME=
|
||||||
|
|
||||||
# --- Propuesta consultiva con IA (MiniMax) ---
|
# --- Propuesta consultiva con IA (MiniMax) ---
|
||||||
# Clave del panel de MiniMax. NUNCA se commitea: .env esta en .gitignore.
|
# Clave del panel de MiniMax. NUNCA se commitea: .env está en .gitignore.
|
||||||
# Ojo con el prefijo: NO uses ANTHROPIC_API_KEY. El SDK la lee por su cuenta y
|
# Ojo con el prefijo: NO uses ANTHROPIC_API_KEY. El SDK la lee por su cuenta y
|
||||||
# mandaria la clave de MiniMax a api.anthropic.com.
|
# mandaría la clave de MiniMax a api.anthropic.com.
|
||||||
MINIMAX_API_KEY=
|
MINIMAX_API_KEY=
|
||||||
MINIMAX_BASE_URL=https://api.minimax.io/anthropic
|
MINIMAX_BASE_URL=https://api.minimax.io/anthropic
|
||||||
MINIMAX_MODEL=MiniMax-M3
|
MINIMAX_MODEL=MiniMax-M3
|
||||||
|
|
||||||
# --- Notificaciones (panel de cliente) ---
|
# --- Notificaciones (panel de cliente) ---
|
||||||
# Web Push. Genera el par con: node -e "require('web-push').generateVAPIDKeys()|console.log"
|
# Web Push. Genera el par con: node -e "console.log(require('web-push').generateVAPIDKeys())"
|
||||||
# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log).
|
# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log).
|
||||||
VAPID_PUBLIC_KEY=
|
VAPID_PUBLIC_KEY=
|
||||||
VAPID_PRIVATE_KEY=
|
VAPID_PRIVATE_KEY=
|
||||||
# URL publica (links de correo y notificaciones). En Coolify: el dominio del servicio web.
|
# URL pública (links de correo y notificaciones). En Coolify: el dominio del servicio web.
|
||||||
# Variable de servidor: un NEXT_PUBLIC_* quedaria fijo en el bundle al compilar.
|
# Variable de servidor: un NEXT_PUBLIC_* quedaría fijo en el bundle al compilar.
|
||||||
APP_URL=http://localhost:3000
|
APP_URL=http://localhost:3000
|
||||||
|
|
||||||
# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log)
|
# SMTP de correos (opcionales: sin SMTP_HOST no se envía correo, solo avisa en log)
|
||||||
SMTP_HOST=
|
SMTP_HOST=
|
||||||
SMTP_PORT=587
|
SMTP_PORT=587
|
||||||
SMTP_USER=
|
SMTP_USER=
|
||||||
SMTP_PASS=
|
SMTP_PASS=
|
||||||
SMTP_FROM=
|
SMTP_FROM=
|
||||||
SMTP_FROM_NAME=Cotizador E3
|
SMTP_FROM_NAME=Uriel Jareth Consulting
|
||||||
|
|
||||||
# Recordatorio de pagos pendientes: cada cuantos dias se reenvia al cliente su
|
# Recordatorio de pagos pendientes: cada cuántos días se reenvía al cliente su
|
||||||
# estado de cuenta mientras siga debiendo cobros (desde las 9:00 hora de Mexico).
|
# estado de cuenta mientras siga debiendo cobros (desde las 9:00 hora de México).
|
||||||
# 0 apaga el automatico; el boton "Enviar recordatorio" de /cobros sigue sirviendo.
|
# 0 apaga el automático; el botón "Enviar recordatorio" de /cobros sigue sirviendo.
|
||||||
COBROS_RECORDATORIO_DIAS=3
|
COBROS_RECORDATORIO_DIAS=3
|
||||||
|
|
||||||
# Directorio de comprobantes. Local: vacio = <repo>/uploads.
|
# Directorio de comprobantes. Local: vacío = <repo>/uploads.
|
||||||
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
||||||
UPLOAD_DIR=
|
UPLOAD_DIR=
|
||||||
|
|
||||||
|
# --- API de agentes, aprobación humana y webhooks HMAC-SHA256 ---
|
||||||
|
# Correo al que llegan las solicitudes de aprobación de borradores (fallback: primer usuario admin)
|
||||||
|
ADMIN_NOTIFY_EMAIL=
|
||||||
|
# Webhook saliente por defecto hacia n8n (firmado con X-Cotizador-Signature: sha256=...)
|
||||||
|
WEBHOOK_N8N_URL=
|
||||||
|
WEBHOOK_N8N_SECRET=
|
||||||
|
# Webhook de n8n para envío de cotizaciones aprobadas por WhatsApp/Chatwoot
|
||||||
|
WEBHOOK_WHATSAPP_SEND_URL=
|
||||||
|
# Backend Python (api/): solo aceptar la vieja API_KEY sin alcances si se habilita explícitamente
|
||||||
|
ALLOW_LEGACY_API_KEY=false
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# AGENTS.md — Cotizador E3
|
# AGENTS.md — Cotizador — Uriel Jareth Consulting
|
||||||
|
|
||||||
## Quick Reference
|
## Quick Reference
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — se
|
|||||||
|
|
||||||
## CLI (`cli/cotizador.mjs`)
|
## CLI (`cli/cotizador.mjs`)
|
||||||
|
|
||||||
- Node puro (18+), sin dependencias, habla con la API de Next con la sesión de un usuario staff: `login` guarda el JWT en `~/.cotizador-e3/sesiones.json` y lo manda como cookie `cotizador-session`. Con `COTIZADOR_EMAIL`/`COTIZADOR_PASSWORD` renueva la sesión solo. No hay API key en Next: para eso está la API de Python.
|
- Node puro (18+), sin dependencias, habla con la API de Next con la sesión de un usuario staff: `login` guarda el JWT en `~/.cotizador-uj/sesiones.json` y lo manda como cookie `cotizador-session`. Con `COTIZADOR_EMAIL`/`COTIZADOR_PASSWORD` renueva la sesión solo. No hay API key en Next: para eso está la API de Python.
|
||||||
- Pensado para LLMs: JSON en stdout, errores JSON en stderr con códigos de salida fijos (2 uso, 3 auth, 4 no encontrado, 5 validación, 6 duplicado, 7 red), `--campos`, `--dry-run`, `--confirmar` obligatorio para borrar y error ante flags desconocidas. `cotizador esquema` vuelca el registro de comandos; ayuda, validación y esquema salen del mismo arreglo `COMANDOS`, así que un comando nuevo se documenta solo.
|
- Pensado para LLMs: JSON en stdout, errores JSON en stderr con códigos de salida fijos (2 uso, 3 auth, 4 no encontrado, 5 validación, 6 duplicado, 7 red), `--campos`, `--dry-run`, `--confirmar` obligatorio para borrar y error ante flags desconocidas. `cotizador esquema` vuelca el registro de comandos; ayuda, validación y esquema salen del mismo arreglo `COMANDOS`, así que un comando nuevo se documenta solo.
|
||||||
- `POST /api/cotizaciones` acepta un cuerpo mínimo para el CLI: sin `numero` lo genera el servidor (`siguienteNumeroCotizacion` en `src/lib/cotizaciones.ts`, misma regla que el formulario), sin `asesorId` usa el usuario de la sesión, sin `fecha`/`vigencia` usa hoy + 15 días hábiles, y `planBucefalo.precio` cae al precio de lista.
|
- `POST /api/cotizaciones` acepta un cuerpo mínimo para el CLI: sin `numero` lo genera el servidor (`siguienteNumeroCotizacion` en `src/lib/cotizaciones.ts`, misma regla que el formulario), sin `asesorId` usa el usuario de la sesión, sin `fecha`/`vigencia` usa hoy + 15 días hábiles, y `planBucefalo.precio` cae al precio de lista.
|
||||||
- Respuestas JSON de cotizaciones: el asesor sale con `asesorPublicoSelect`, **nunca** `asesor: true` (incluye el hash de la contraseña).
|
- Respuestas JSON de cotizaciones: el asesor sale con `asesorPublicoSelect`, **nunca** `asesor: true` (incluye el hash de la contraseña).
|
||||||
@@ -160,5 +160,14 @@ docs/ # Business/product notes (Spanish), not code docs
|
|||||||
|
|
||||||
## Domain
|
## Domain
|
||||||
|
|
||||||
Quotation system for Consultoría E3 (digital marketing agency in Querétaro, MX). Services organized in 4 phases: Fase 0 (Auditorías), Fase 1 (Setup/Infra), Fase 2 (Publicidad/Manejo), Fase 3 (Contenido/SEO). Two payment types: `unico` (one-time) and `mensual` (recurring). Optional Bucéfalo CRM plans and Openpay financing.
|
Quotation system for Uriel Jareth Consulting. Services organized in 4 phases: Fase 0 (Auditorías), Fase 1 (Setup/Infra), Fase 2 (Publicidad/Manejo), Fase 3 (Contenido/SEO). Two payment types: `unico` (one-time) and `mensual` (recurring). Optional Bucéfalo CRM plans and Openpay financing.
|
||||||
|
|
||||||
|
## API para Agentes, Aprobación y Webhooks
|
||||||
|
|
||||||
|
- **API unificada:** Next.js (`/api/**`) es la API principal (OpenAPI 3.1 en `/api/openapi.json`). FastAPI (`api/`) se mantiene en **paridad de seguridad** contra la misma PostgreSQL (`AgentApiKey` SHA-256, scopes, rate limit, `AuditLog`, bloqueo de aprobación/envío, `ALLOW_LEGACY_API_KEY=false` por defecto y lectura `/cobros/programas` + `/cobros/pagos`).
|
||||||
|
- **Edge vs Node:** `src/middleware.ts` corre en Edge y NO importa Prisma ni `pg`. Si llega `X-API-Key` o `Authorization: Bearer` sin cookie de sesión, limpia headers `x-user-*`/`x-cliente-id` y delega la validación al Route Handler vía `requireActor()` en `src/lib/agent-auth.ts`.
|
||||||
|
- **Regla de hierro de aprobación:** ningún agente puede aprobar cotizaciones (jamás agregar un scope de aprobación). Estados: `borrador → aprobada → enviada → aceptada | rechazada | vencida`. Aprobar exige usuario humano `role="admin"` (`POST /api/cotizaciones/[id]/aprobar`) o enlace firmado de un solo uso (`/aprobar/[token]` con `POST { confirmar: true }`). Enviar (`POST /api/cotizaciones/[id]/enviar`) exige `estado === "aprobada" && aprobadaAt !== null`.
|
||||||
|
- **Idempotencia y auditoría:** `withIdempotency()` (`src/lib/idempotency.ts`) en `POST /api/cotizaciones`, `POST /api/cotizaciones/[id]/enviar`, `POST /api/clientes` y `POST /api/cobros/pagos/[id]/registrar`. Toda acción relevante o intento bloqueado se registra en `AuditLog` (`src/lib/audit.ts`).
|
||||||
|
- **Webhooks HMAC-SHA256:** `src/lib/webhooks.ts` firma con `X-Cotizador-Signature: sha256=...`, incluye automáticamente `WEBHOOK_N8N_URL`/`WEBHOOK_N8N_SECRET` y guarda historial en `WebhookDelivery`. `enviarRecordatoriosPendientes` emite `pago.vencido` de forma best-effort sin alterar los correos/push ni `ultimoRecordatorioAt`.
|
||||||
|
- **Provisioning CLI:** `npx tsx scripts/provision-agent-keys.ts --preset` (incluido en el `Dockerfile` runner).
|
||||||
|
- **Pruebas automáticas:** `npm test` (`node --import tsx --test tests/*.test.ts`) valida scopes, rate limit, guardia de aprobación, firmas HMAC y paridad numérica exacta entre `src/lib/calculators.ts` y `api/app/services/calculators.py`.
|
||||||
|
|||||||
+2
-1
@@ -1,4 +1,4 @@
|
|||||||
# Cotizador E3 — Next.js (web)
|
# Cotizador — Uriel Jareth Consulting — Next.js (web)
|
||||||
# Multi-stage build. El runner conserva node_modules completo para que
|
# Multi-stage build. El runner conserva node_modules completo para que
|
||||||
# `prisma migrate deploy` y el seed (tsx) funcionen dentro del contenedor.
|
# `prisma migrate deploy` y el seed (tsx) funcionen dentro del contenedor.
|
||||||
|
|
||||||
@@ -33,6 +33,7 @@ COPY --from=builder /app/node_modules ./node_modules
|
|||||||
COPY --from=builder /app/.next ./.next
|
COPY --from=builder /app/.next ./.next
|
||||||
COPY --from=builder /app/public ./public
|
COPY --from=builder /app/public ./public
|
||||||
COPY --from=builder /app/prisma ./prisma
|
COPY --from=builder /app/prisma ./prisma
|
||||||
|
COPY --from=builder /app/scripts ./scripts
|
||||||
COPY --from=builder /app/src/generated ./src/generated
|
COPY --from=builder /app/src/generated ./src/generated
|
||||||
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
|
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
|
||||||
COPY --from=builder /app/next.config.ts ./next.config.ts
|
COPY --from=builder /app/next.config.ts ./next.config.ts
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Cotizador E3
|
# Cotizador — Uriel Jareth Consulting
|
||||||
|
|
||||||
Sistema de generación de cotizaciones para Consultoría E3 (marketing digital, Querétaro MX).
|
Sistema de generación de cotizaciones para Uriel Jareth Consulting.
|
||||||
Servicios organizados en 4 fases, dos tipos de pago (único / mensual), planes CRM Bucéfalo
|
Servicios organizados en 4 fases, dos tipos de pago (único / mensual), planes CRM Bucéfalo
|
||||||
y financiamiento opcional. Exporta a PDF y Excel.
|
y financiamiento opcional. Exporta a PDF y Excel.
|
||||||
|
|
||||||
@@ -97,3 +97,19 @@ El stack de producción está en [docker-compose.coolify.yml](docker-compose.coo
|
|||||||
|
|
||||||
Las convenciones del proyecto, gotchas de Prisma 7 / PDFKit / Next.js 16 y el modelo de datos
|
Las convenciones del proyecto, gotchas de Prisma 7 / PDFKit / Next.js 16 y el modelo de datos
|
||||||
están en [`AGENTS.md`](AGENTS.md) (importado por `CLAUDE.md`).
|
están en [`AGENTS.md`](AGENTS.md) (importado por `CLAUDE.md`).
|
||||||
|
|
||||||
|
## API para agentes, aprobación y webhooks
|
||||||
|
|
||||||
|
- **Especificación OpenAPI 3.1:** `GET /api/openapi.json`
|
||||||
|
- **Claves granulares (`AgentApiKey`):** prefijo `ujc_live_*`, hash SHA-256 en PostgreSQL, rate limit por minuto y bitácora `AuditLog`. Provisioning por CLI: `npx tsx scripts/provision-agent-keys.ts --preset`.
|
||||||
|
- **Aprobación humana obligatoria:** toda cotización creada por agente nace en `borrador`, notifica a `ADMIN_NOTIFY_EMAIL` con un enlace firmado de un solo uso (`/aprobar/<token>`) y no puede enviarse (`POST /api/cotizaciones/:id/enviar`) hasta quedar `aprobada` por un administrador humano.
|
||||||
|
- **Webhooks salientes HMAC-SHA256:** firmados con `X-Cotizador-Signature: sha256=...`, reintentos automáticos y registro en `WebhookDelivery`.
|
||||||
|
- **Paridad en `api/` (FastAPI):** valida las mismas `AgentApiKey`, scopes, rate limit y reglas de aprobación; `ALLOW_LEGACY_API_KEY=false` por defecto; agrega `GET /cobros/programas` y `GET /cobros/pagos`.
|
||||||
|
|
||||||
|
## Pruebas automáticas
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test # Pruebas unitarias y paridad TS/Python (node --test + tsx)
|
||||||
|
npm run lint # ESLint
|
||||||
|
npm run build # Build de producción Next.js
|
||||||
|
```
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ DB_HOST=localhost
|
|||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
DB_USER=postgres
|
DB_USER=postgres
|
||||||
DB_PASSWORD=postgres
|
DB_PASSWORD=postgres
|
||||||
|
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
DB_NAME=cotizador_e3
|
DB_NAME=cotizador_e3
|
||||||
|
|
||||||
# Auth
|
# Auth
|
||||||
@@ -12,3 +13,4 @@ JWT_SECRET=change-me-to-a-secure-jwt-secret
|
|||||||
# Server
|
# Server
|
||||||
API_HOST=0.0.0.0
|
API_HOST=0.0.0.0
|
||||||
API_PORT=8000
|
API_PORT=8000
|
||||||
|
ALLOW_LEGACY_API_KEY=false
|
||||||
|
|||||||
+36
-441
@@ -1,457 +1,52 @@
|
|||||||
# Cotizador E3 — API Documentation for AI Skills
|
# Cotizador — Uriel Jareth Consulting — Guía de API para Agentes
|
||||||
|
|
||||||
## Overview
|
## Arquitectura unificada
|
||||||
|
|
||||||
REST API for Consultoría E3's digital marketing quotation system. Allows AI agents to manage clients, browse service catalogs, create quotations, calculate financing, generate PDF/Excel documents, and manage the full sales pipeline.
|
- **API principal (Next.js `/api/**`):** `https://cotizador.urieljareth.org/api` — OpenAPI 3.1 en `GET /api/openapi.json`.
|
||||||
|
- Incluye catálogo, clientes, cotizaciones, flujo de aprobación humana, envío por correo/WhatsApp, PDF/Excel, cobros recurrentes, claves de agentes, auditoría y webhooks HMAC-SHA256.
|
||||||
|
- **API Python en paridad (FastAPI):** `https://cotizador-api.urieljareth.org` — Swagger en `/docs`.
|
||||||
|
- Valida las mismas claves `AgentApiKey` (SHA-256) contra la misma PostgreSQL, aplica scopes, rate limit, auditoría (`AuditLog`), paridad de cálculo (`calculators.py`) y lectura de `/cobros/programas` y `/cobros/pagos`.
|
||||||
|
- La vieja `API_KEY` ilimitada está desactivada por defecto (`ALLOW_LEGACY_API_KEY=false`).
|
||||||
|
|
||||||
**Base URL:** `http://localhost:8000`
|
## Autenticación y alcances (`AgentApiKey`)
|
||||||
**Auth:** API Key via `X-API-Key` header or `Authorization: Bearer <key>`
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
**OpenAPI Spec:** `GET /openapi.json` (no auth required)
|
|
||||||
|
|
||||||
---
|
Envía la clave con prefijo `ujc_live_*` en `X-API-Key: ujc_live_...` o `Authorization: Bearer ujc_live_...`.
|
||||||
|
|
||||||
## Domain Context
|
Alcances válidos (jamás existe un scope de aprobación):
|
||||||
|
- `catalogo:leer` — catálogo, categorías, paquetes, bonos, financiamiento
|
||||||
|
- `clientes:leer` / `clientes:escribir` — consultar, crear y editar clientes
|
||||||
|
- `cotizaciones:leer` — listar y leer cotizaciones
|
||||||
|
- `cotizaciones:leer_aceptadas` — solo cotizaciones en estado `aceptada` (y sus PDFs)
|
||||||
|
- `cotizaciones:borrador` — crear y editar borradores (nunca aprobar ni cambiar estado)
|
||||||
|
- `cotizaciones:enviar` — enviar cotizaciones **ya aprobadas** vía `POST /api/cotizaciones/:id/enviar`
|
||||||
|
- `cobros:leer` / `cobros:registrar` — consultar programas/cobros y registrar pagos fuera del panel
|
||||||
|
|
||||||
Consultoría E3 is a digital marketing agency in Querétaro, México. Services are organized in 4 project phases:
|
Headers de rate limit en respuestas de agente: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (y `Retry-After` en `429`).
|
||||||
|
Para `POST` mutantes se soporta `Idempotency-Key` (TTL 24h; replay devuelve `X-Idempotency-Replayed: true`, cuerpo distinto devuelve `409`).
|
||||||
|
|
||||||
- **Fase 0 — Auditoría / Acompañamiento:** Initial assessments and ongoing consulting
|
## Flujo de aprobación humana (regla de hierro)
|
||||||
- **Fase 1 — Setup e Infraestructura:** One-time setup (websites, branding, CRM config)
|
|
||||||
- **Fase 2 — Publicidad y Manejo:** Ongoing advertising and social media management
|
|
||||||
- **Fase 3 — Contenido y SEO:** Content creation and search engine optimization
|
|
||||||
|
|
||||||
Two payment types:
|
Estados: `borrador` → `aprobada` → `enviada` → `aceptada` | `rechazada` | `vencida`.
|
||||||
- **unico:** One-time payment
|
|
||||||
- **mensual:** Monthly recurring payment
|
|
||||||
|
|
||||||
Currency: MXN (Mexican Pesos) or USD. IVA (tax) rate: 16%.
|
1. Un agente con `cotizaciones:borrador` crea la cotización con `POST /api/cotizaciones`. **Siempre** nace en `borrador`.
|
||||||
|
2. El servidor genera un enlace firmado de un solo uso (expira en 72h) y lo envía por correo exclusivamente a Jareth (`ADMIN_NOTIFY_EMAIL`), además de emitir el webhook `cotizacion.creada` (sin exponer el token raw).
|
||||||
|
3. Jareth aprueba desde el panel (`POST /api/cotizaciones/:id/aprobar`) o desde `/aprobar/<token>` (`POST /api/aprobar/<token>` con `{ "confirmar": true }`). Ningún agente ni asesor puede aprobar (`403` + `AuditLog`).
|
||||||
|
4. Una vez en `aprobada` (con `aprobadaAt`), el agente con `cotizaciones:enviar` puede ejecutar `POST /api/cotizaciones/:id/enviar` con `canal: "email" | "whatsapp_chatwoot"` y opcionalmente `verificarContacto` (email o teléfono del prospecto; si no coincide → `403`). Sin aprobación previa devuelve `409`.
|
||||||
|
|
||||||
---
|
## Webhooks salientes (HMAC-SHA256)
|
||||||
|
|
||||||
## Authentication
|
Eventos: `cotizacion.creada`, `cotizacion.aprobada`, `cotizacion.enviada`, `cotizacion.aceptada`, `cotizacion.rechazada`, `cotizacion.vencida`, `pago.registrado`, `pago.vencido`.
|
||||||
|
|
||||||
### API Key (for agents)
|
Headers enviados:
|
||||||
```
|
- `X-Cotizador-Event`
|
||||||
X-API-Key: your-api-key-here
|
- `X-Cotizador-Timestamp`
|
||||||
```
|
- `X-Cotizador-Delivery-Id`
|
||||||
or
|
- `X-Cotizador-Signature: sha256=<hmac_sha256_hex>`
|
||||||
```
|
|
||||||
Authorization: Bearer your-api-key-here
|
|
||||||
```
|
|
||||||
|
|
||||||
### JWT (for human login)
|
## Provisioning de claves (operador)
|
||||||
```
|
|
||||||
POST /auth/login
|
|
||||||
Body: { "email": "[email protected]", "password": "secret" }
|
|
||||||
Response: { "user": { "id", "name", "email", "role" } }
|
|
||||||
Sets cookie: cotizador-session (httpOnly, 7 days)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Endpoints Reference
|
|
||||||
|
|
||||||
### Health & Info
|
|
||||||
|
|
||||||
#### GET /health
|
|
||||||
Health check endpoint. No auth required.
|
|
||||||
- **Response:** `{ "status": "ok", "timestamp": "2026-05-03T..." }`
|
|
||||||
|
|
||||||
#### GET /api-info
|
|
||||||
API capabilities and version info.
|
|
||||||
- **Response:** `{ "name": "Cotizador E3 API", "version": "1.0.0", "capabilities": [...] }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Clients (Clientes)
|
|
||||||
|
|
||||||
#### GET /clientes
|
|
||||||
List clients with optional search and pagination.
|
|
||||||
- **Query params:** `?q=texto&page=1&limit=50`
|
|
||||||
- **Response:** `{ "data": [Cliente], "meta": { "total", "page", "limit", "pages" } }`
|
|
||||||
|
|
||||||
#### POST /clientes
|
|
||||||
Create a new client.
|
|
||||||
- **Body:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"nombre": "Juan Pérez",
|
|
||||||
"empresa": "ACME Corp",
|
|
||||||
"email": "[email protected]",
|
|
||||||
"telefono": "4421234567"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- **Response (201):** Full Cliente object with `id`
|
|
||||||
|
|
||||||
#### GET /clientes/{id}
|
|
||||||
Get client details including recent quotations.
|
|
||||||
- **Response:** Cliente object + `cotizaciones` array
|
|
||||||
|
|
||||||
#### PUT /clientes/{id}
|
|
||||||
Update client information.
|
|
||||||
- **Body:** Same as POST (all fields optional for update)
|
|
||||||
|
|
||||||
#### DELETE /clientes/{id}
|
|
||||||
Delete client. Returns 409 if client has quotations.
|
|
||||||
- **Response (200):** `{ "ok": true }`
|
|
||||||
- **Error (409):** `{ "error": "Cliente tiene N cotizaciones asociadas" }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Service Catalog (Catálogo)
|
|
||||||
|
|
||||||
#### GET /catalogo
|
|
||||||
List all active services with optional filters.
|
|
||||||
- **Query params:** `?fase=0&tipoPago=mensual&categoriaId=xxx&q=seo`
|
|
||||||
- **Response:** Array of ServicioCatalogo objects
|
|
||||||
|
|
||||||
Each service:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"id": "cuid",
|
|
||||||
"nombre": "Posicionamiento SEO",
|
|
||||||
"descripcion": "...",
|
|
||||||
"fase": 3,
|
|
||||||
"tipoPago": "mensual",
|
|
||||||
"precioBase": 2900,
|
|
||||||
"tiempoEntrega": "7 - 14 dias",
|
|
||||||
"entregablesDefault": ["Keyword research", "On-page optimization"],
|
|
||||||
"categoriaId": "cuid",
|
|
||||||
"variante": null,
|
|
||||||
"activo": true,
|
|
||||||
"orden": 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### POST /catalogo
|
|
||||||
Create a new service.
|
|
||||||
- **Body:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"nombre": "Nuevo Servicio",
|
|
||||||
"descripcion": "Descripción del servicio",
|
|
||||||
"fase": 1,
|
|
||||||
"tipoPago": "unico",
|
|
||||||
"precioBase": 5000,
|
|
||||||
"tiempoEntrega": "7 - 14 dias",
|
|
||||||
"entregablesDefault": ["Entregable 1", "Entregable 2"],
|
|
||||||
"categoriaId": "cuid",
|
|
||||||
"variante": null,
|
|
||||||
"orden": 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### GET /catalogo/{id}
|
|
||||||
Get service details with category info.
|
|
||||||
|
|
||||||
#### PUT /catalogo/{id}
|
|
||||||
Update service. Same body as POST.
|
|
||||||
|
|
||||||
#### DELETE /catalogo/{id}
|
|
||||||
Soft-delete if used in quotations, hard-delete otherwise.
|
|
||||||
- **Response:** `{ "ok": true, "archived": true|false }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Categories (Categorías)
|
|
||||||
|
|
||||||
Available: SEO (#10b981), Marketing (#6366f1), Paid Media (#f59e0b), Desarrollo Web (#3b82f6), Automatizaciones (#8b5cf6), CRM (#ec4899), Desarrollo Personalizado (#14b8a6)
|
|
||||||
|
|
||||||
#### GET /categorias
|
|
||||||
List all categories ordered by `orden`.
|
|
||||||
|
|
||||||
#### POST /categorias
|
|
||||||
- **Body:** `{ "nombre": "Nueva Cat", "descripcion": "...", "color": "#6b7280", "orden": 0 }`
|
|
||||||
|
|
||||||
#### GET /categorias/{id}
|
|
||||||
Get category with its services.
|
|
||||||
|
|
||||||
#### PUT /categorias/{id}
|
|
||||||
- **Body:** `{ "nombre", "descripcion", "color", "orden", "activo" }`
|
|
||||||
|
|
||||||
#### DELETE /categorias/{id}
|
|
||||||
Returns 409 if category has associated services.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Quotations (Cotizaciones)
|
|
||||||
|
|
||||||
#### GET /cotizaciones
|
|
||||||
List quotations with filters.
|
|
||||||
- **Query params:** `?estado=borrador&asesorId=xxx&clienteId=xxx&q=texto&desde=2026-01-01&hasta=2026-12-31&page=1&limit=50`
|
|
||||||
- **Response:** Array with full relations (cliente, asesor, servicios+catalogo, planBucefalo)
|
|
||||||
|
|
||||||
#### POST /cotizaciones
|
|
||||||
Create a complete quotation. Auto-creates client if not found.
|
|
||||||
- **Body:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"numero": "UJ2605AG001",
|
|
||||||
"fecha": "2026-05-03",
|
|
||||||
"vigencia": "2026-05-24",
|
|
||||||
"moneda": "MXN",
|
|
||||||
"tipoCambio": "NA",
|
|
||||||
"proyecto": "MKT Digital",
|
|
||||||
"esquemaPago": "Pago Unico/Mensual",
|
|
||||||
"incluirBonos": false,
|
|
||||||
"incluirFinanciamiento": false,
|
|
||||||
"observaciones": "",
|
|
||||||
"asesorId": "cuid",
|
|
||||||
"cliente": {
|
|
||||||
"nombre": "Juan Pérez",
|
|
||||||
"empresa": "ACME Corp",
|
|
||||||
"email": "[email protected]",
|
|
||||||
"telefono": "4421234567"
|
|
||||||
},
|
|
||||||
"servicios": [
|
|
||||||
{
|
|
||||||
"catalogoId": "cuid",
|
|
||||||
"nombre": "SEO On-Page",
|
|
||||||
"fase": 3,
|
|
||||||
"tipoPago": "mensual",
|
|
||||||
"precio": 2900,
|
|
||||||
"tiempoEntrega": "7 - 14 dias",
|
|
||||||
"entregables": ["Keyword research", "On-page SEO"]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"planBucefalo": {
|
|
||||||
"nivel": "basico",
|
|
||||||
"precio": 1000
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### GET /cotizaciones/{id}
|
|
||||||
Get quotation with all relations.
|
|
||||||
|
|
||||||
#### PUT /cotizaciones/{id}
|
|
||||||
Update quotation. Replaces all services in a transaction.
|
|
||||||
- **Body:** Same as POST without `numero` and `asesorId`. Optional `estado`.
|
|
||||||
|
|
||||||
#### DELETE /cotizaciones/{id}
|
|
||||||
Hard-delete with cascade.
|
|
||||||
|
|
||||||
#### PATCH /cotizaciones/{id}/precio
|
|
||||||
Update price of a single service.
|
|
||||||
- **Body:** `{ "servicioId": "cuid", "precio": 7500 }`
|
|
||||||
|
|
||||||
#### PATCH /cotizaciones/{id}/estado
|
|
||||||
Change quotation status.
|
|
||||||
- **Body:** `{ "estado": "enviada" }` — `borrador`, `enviada`, `aprobada`, `rechazada`
|
|
||||||
|
|
||||||
#### POST /cotizaciones/{id}/duplicate
|
|
||||||
Duplicate quotation as new copy in `borrador` state.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Packages (Paquetes)
|
|
||||||
|
|
||||||
#### GET /paquetes
|
|
||||||
List active packages with nested phases and services.
|
|
||||||
|
|
||||||
#### POST /paquetes
|
|
||||||
- **Body:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"nombre": "Paquete Básico",
|
|
||||||
"descripcion": "...",
|
|
||||||
"fases": [
|
|
||||||
{ "nombre": "Auditoría", "orden": 0 },
|
|
||||||
{ "nombre": "Setup", "orden": 1 }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### GET /paquetes/{id}
|
|
||||||
Get package with full nested structure.
|
|
||||||
|
|
||||||
#### PUT /paquetes/{id}
|
|
||||||
- **Body:** `{ "nombre", "descripcion", "activo" }`
|
|
||||||
|
|
||||||
#### DELETE /paquetes/{id}
|
|
||||||
Hard-delete with cascade.
|
|
||||||
|
|
||||||
#### POST /paquetes/{id}/manage
|
|
||||||
Multi-action endpoint:
|
|
||||||
- `{ "action": "addFase", "nombre": "Fase 3", "orden": 2 }`
|
|
||||||
- `{ "action": "updateFase", "faseId": "cuid", "nombre": "New Name", "orden": 1 }`
|
|
||||||
- `{ "action": "deleteFase", "faseId": "cuid" }`
|
|
||||||
- `{ "action": "addServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
|
||||||
- `{ "action": "removeServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Configuration (Configuración)
|
|
||||||
|
|
||||||
Allowed keys: `color_primario`, `color_secundario`, `logo_base64`, `razon_social`, `rfc`, `domicilio_fiscal`, `cuenta_nacional`, `clabe_interbancaria`, `cuenta_internacional`, `cuenta_internacional_swift`, `hora_centinela`, `anualidad_hosting`, `iva`, `terminos_condiciones`, `no_incluye`, `notas_adicionales`
|
|
||||||
|
|
||||||
#### GET /configuracion
|
|
||||||
- **Response:** `{ "color_primario": "#2563eb", "razon_social": "...", ... }`
|
|
||||||
|
|
||||||
#### PUT /configuracion
|
|
||||||
Bulk upsert. Only whitelisted keys processed.
|
|
||||||
- **Body:** `{ "color_primario": "#ff0000", "razon_social": "Nuevo Nombre" }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Bonuses (Bonos)
|
|
||||||
|
|
||||||
Available: Centinela Web, Workshop Buyer Persona, Workshop Propuesta de Valor, Membresía Premium, Mes Gratis CRM, Script de Ventas
|
|
||||||
|
|
||||||
#### GET /bonos
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Financing (Financiamiento)
|
|
||||||
|
|
||||||
| Months | Rate | Commission | Min Amount |
|
|
||||||
|--------|------|------------|------------|
|
|
||||||
| 3 | 7.7% | 2.5% | $300 |
|
|
||||||
| 6 | 10.7% | 2.5% | $600 |
|
|
||||||
| 9 | 13.7% | 2.5% | $900 |
|
|
||||||
| 12 | 16.7% | 2.5% | $1,200 |
|
|
||||||
|
|
||||||
#### GET /financiamiento/planes
|
|
||||||
|
|
||||||
#### POST /financiamiento/calcular
|
|
||||||
- **Body:** `{ "monto": 50000, "meses": 6 }`
|
|
||||||
- **Response:** `{ "pagoMensual", "ivaMensual", "totalMensual", "comisionTotal", "granTotal" }`
|
|
||||||
|
|
||||||
#### GET /financiamiento/simulacion/{cotizacion_id}
|
|
||||||
Auto-calculate financing for existing quotation.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Export
|
|
||||||
|
|
||||||
#### POST /export/pdf — PDF from draft data
|
|
||||||
#### GET /export/pdf/{id} — PDF from saved quotation
|
|
||||||
#### POST /export/excel — Excel from draft data
|
|
||||||
#### GET /export/excel/{id} — Excel from saved quotation
|
|
||||||
#### GET /export/catalogo — CSV of active services
|
|
||||||
#### GET /export/catalogo/plantilla — CSV import template
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Import
|
|
||||||
|
|
||||||
#### POST /import/catalogo
|
|
||||||
Bulk import services from CSV. `multipart/form-data` with `file` field.
|
|
||||||
- **Response:** `{ "creados": 5, "omitidos": 2, "errores": [...] }`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Business Rules
|
|
||||||
|
|
||||||
### Quotation Number
|
|
||||||
Format: `UJ{YY}{MM}{AsesorInitials}{sequence}` — e.g., `UJ2605AG001`
|
|
||||||
|
|
||||||
### Quotation Validity
|
|
||||||
15 business days from issue (excludes Sat/Sun).
|
|
||||||
|
|
||||||
### CRM Bucefalo Plans
|
|
||||||
basico=$1,000/mes, estandar=$3,500/mes, premium=$4,500/mes, empresarial=$7,500/mes
|
|
||||||
|
|
||||||
### Client Deduplication
|
|
||||||
Matched by `(nombre, empresa)` pair.
|
|
||||||
|
|
||||||
### Service Soft-Delete
|
|
||||||
If referenced by quotations → `activo=false`. Otherwise hard-delete.
|
|
||||||
|
|
||||||
### Financing Formula
|
|
||||||
```
|
|
||||||
comisionTotal = monto × comision%
|
|
||||||
montoConComision = monto + comisionTotal
|
|
||||||
pagoMensual = montoConComision × (1 + tasa) / meses
|
|
||||||
ivaMensual = pagoMensual × 0.16
|
|
||||||
totalMensual = pagoMensual + ivaMensual
|
|
||||||
granTotal = totalMensual × meses
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Common Responses
|
|
||||||
|
|
||||||
### Success (paginated)
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"data": [...],
|
|
||||||
"meta": { "total": 45, "page": 1, "limit": 50, "pages": 1 }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error
|
|
||||||
```json
|
|
||||||
{ "error": "Message", "detail": "Details", "code": "ERROR_CODE" }
|
|
||||||
```
|
|
||||||
|
|
||||||
### HTTP Codes
|
|
||||||
200=OK, 201=Created, 204=No Content, 400=Bad Request, 401=Unauthorized, 404=Not Found, 409=Conflict, 500=Server Error
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Agent Workflows
|
|
||||||
|
|
||||||
### Create quotation
|
|
||||||
```
|
|
||||||
1. GET /catalogo?fase=0 → audit services
|
|
||||||
2. GET /catalogo?fase=1 → setup services
|
|
||||||
3. GET /catalogo?fase=2&tipoPago=mensual → ongoing services
|
|
||||||
4. POST /financiamiento/calcular → simulate payments
|
|
||||||
5. POST /cotizaciones → create quotation
|
|
||||||
6. GET /export/pdf/{id} → generate PDF
|
|
||||||
```
|
|
||||||
|
|
||||||
### Review pipeline
|
|
||||||
```
|
|
||||||
1. GET /cotizaciones?estado=borrador → pending
|
|
||||||
2. GET /cotizaciones?estado=enviada → awaiting
|
|
||||||
3. GET /cotizaciones?estado=aprobada → won
|
|
||||||
```
|
|
||||||
|
|
||||||
### Negotiate price
|
|
||||||
```
|
|
||||||
1. GET /cotizaciones/{id} → current state
|
|
||||||
2. PATCH /cotizaciones/{id}/precio → adjust price
|
|
||||||
3. GET /export/pdf/{id} → regenerate PDF
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## MCP Integration — removed (2026-07-28)
|
|
||||||
|
|
||||||
The `/mcp` endpoint and the `api/app/mcp/` package no longer exist. Agents should use
|
|
||||||
the REST endpoints documented above, authenticating with `X-API-Key` or a Bearer JWT.
|
|
||||||
|
|
||||||
It was removed for three reasons: nobody was using it; its transport had been broken
|
|
||||||
for some time (it constructed a `StreamableHTTPServerTransport` per request with no
|
|
||||||
session handling, returning 500 even with valid credentials); and its unpinned SDK
|
|
||||||
took the entire API down in production when `mcp` released 2.0.0 and dropped
|
|
||||||
`Server.list_tools()`.
|
|
||||||
|
|
||||||
To bring it back: `git show edb500f5:api/app/mcp/server.py`. Pin the SDK to the 1.x
|
|
||||||
series and fix the transport before mounting it again.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Environment
|
|
||||||
|
|
||||||
```
|
|
||||||
DB_HOST=localhost
|
|
||||||
DB_PORT=5432
|
|
||||||
DB_USER=postgres
|
|
||||||
DB_PASSWORD=postgres
|
|
||||||
DB_NAME=cotizador_e3
|
|
||||||
API_KEY=your-secret-api-key
|
|
||||||
JWT_SECRET=your-jwt-secret
|
|
||||||
```
|
|
||||||
|
|
||||||
## Run
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt
|
npx tsx scripts/provision-agent-keys.ts --preset
|
||||||
uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
npx tsx scripts/provision-agent-keys.ts --list
|
||||||
# Swagger: http://localhost:8000/docs
|
npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate
|
||||||
# ReDoc: http://localhost:8000/redoc
|
|
||||||
# OpenAPI: http://localhost:8000/openapi.json
|
|
||||||
```
|
```
|
||||||
|
|||||||
+293
-12
@@ -1,18 +1,33 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import Header, HTTPException, status
|
from fastapi import Depends, Header, HTTPException, Request, status
|
||||||
from jose import JWTError, jwt
|
from jose import JWTError, jwt
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
|
from app.database import get_pool
|
||||||
|
|
||||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
ALGORITHM = "HS256"
|
ALGORITHM = "HS256"
|
||||||
ACCESS_TOKEN_EXPIRE_DAYS = 7
|
ACCESS_TOKEN_EXPIRE_DAYS = 7
|
||||||
|
|
||||||
|
# Rate limiter en memoria con ventana deslizante de 60 segundos por key_id.
|
||||||
|
_WINDOW_SECS = 60.0
|
||||||
|
_rate_buckets: dict[str, list[float]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def hash_secret(raw: str) -> str:
|
||||||
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def verify_password(plain: str, hashed: str) -> bool:
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
return pwd_context.verify(plain, hashed)
|
return pwd_context.verify(plain, hashed)
|
||||||
@@ -36,30 +51,296 @@ def decode_token(token: str) -> dict | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def get_api_key(x_api_key: str | None = Header(None)) -> str | None:
|
def _client_ip(request: Request | None) -> str | None:
|
||||||
if x_api_key and x_api_key == settings.API_KEY:
|
if request is None:
|
||||||
return x_api_key
|
|
||||||
return None
|
return None
|
||||||
|
xff = request.headers.get("x-forwarded-for")
|
||||||
|
if xff:
|
||||||
|
first = xff.split(",")[0].strip()
|
||||||
|
if first:
|
||||||
|
return first
|
||||||
|
xri = request.headers.get("x-real-ip")
|
||||||
|
if xri:
|
||||||
|
return xri.strip()
|
||||||
|
return request.client.host if request.client else None
|
||||||
|
|
||||||
|
|
||||||
|
def check_rate_limit(key_id: str, limit_per_min: int, now: float | None = None) -> dict[str, Any]:
|
||||||
|
now_ts = now if now is not None else time.time()
|
||||||
|
limit = max(1, limit_per_min or 60)
|
||||||
|
cutoff = now_ts - _WINDOW_SECS
|
||||||
|
stamps = [ts for ts in _rate_buckets.get(key_id, []) if ts > cutoff]
|
||||||
|
|
||||||
|
if len(stamps) >= limit:
|
||||||
|
oldest = stamps[0] if stamps else now_ts
|
||||||
|
reset_ts = oldest + _WINDOW_SECS
|
||||||
|
retry_after = max(1, math.ceil(reset_ts - now_ts))
|
||||||
|
_rate_buckets[key_id] = stamps
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"limit": limit,
|
||||||
|
"remaining": 0,
|
||||||
|
"reset_at": math.ceil(reset_ts),
|
||||||
|
"retry_after": retry_after,
|
||||||
|
}
|
||||||
|
|
||||||
|
stamps.append(now_ts)
|
||||||
|
_rate_buckets[key_id] = stamps
|
||||||
|
oldest = stamps[0] if stamps else now_ts
|
||||||
|
reset_ts = oldest + _WINDOW_SECS
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"limit": limit,
|
||||||
|
"remaining": max(0, limit - len(stamps)),
|
||||||
|
"reset_at": math.ceil(reset_ts),
|
||||||
|
"retry_after": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def registrar_auditoria(
|
||||||
|
conn,
|
||||||
|
auth: dict | None,
|
||||||
|
accion: str,
|
||||||
|
recurso_tipo: str,
|
||||||
|
recurso_id: str | None = None,
|
||||||
|
exito: bool = True,
|
||||||
|
detalle: dict[str, Any] | None = None,
|
||||||
|
ip: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Registra una entrada en AuditLog (best-effort; nunca tumba el request)."""
|
||||||
|
try:
|
||||||
|
actor_tipo = "system"
|
||||||
|
actor_id: str | None = None
|
||||||
|
actor_nombre = "system"
|
||||||
|
|
||||||
|
if auth:
|
||||||
|
atype = auth.get("auth_type")
|
||||||
|
if atype == "jwt":
|
||||||
|
actor_tipo = "user"
|
||||||
|
actor_id = auth.get("userId")
|
||||||
|
actor_nombre = auth.get("email") or auth.get("name") or str(actor_id or "user")
|
||||||
|
elif atype == "agent":
|
||||||
|
actor_tipo = "agent"
|
||||||
|
actor_id = auth.get("key_id")
|
||||||
|
actor_nombre = auth.get("nombre") or "agent"
|
||||||
|
elif atype == "legacy_api_key":
|
||||||
|
actor_tipo = "system"
|
||||||
|
actor_nombre = "legacy_api_key"
|
||||||
|
|
||||||
|
ip_final = ip or (auth.get("ip") if auth else None)
|
||||||
|
await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO "AuditLog"
|
||||||
|
(id, "actorTipo", "actorId", "actorNombre", accion, "recursoTipo",
|
||||||
|
"recursoId", ip, exito, detalle, "createdAt")
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW())
|
||||||
|
""",
|
||||||
|
uuid.uuid4().hex[:25],
|
||||||
|
actor_tipo,
|
||||||
|
actor_id,
|
||||||
|
actor_nombre,
|
||||||
|
accion,
|
||||||
|
recurso_tipo,
|
||||||
|
recurso_id,
|
||||||
|
ip_final,
|
||||||
|
exito,
|
||||||
|
json.dumps(detalle) if detalle is not None else None,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def _validate_agent_key(raw_key: str, ip: str | None) -> dict | None:
|
||||||
|
pool = await get_pool()
|
||||||
|
key_hash = hash_secret(raw_key)
|
||||||
|
row = await pool.fetchrow(
|
||||||
|
"""
|
||||||
|
SELECT id, nombre, prefijo, scopes, "rateLimitPerMin", "lastUsedAt"
|
||||||
|
FROM "AgentApiKey"
|
||||||
|
WHERE "keyHash" = $1 AND activo = true AND "revokedAt" IS NULL
|
||||||
|
""",
|
||||||
|
key_hash,
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
|
||||||
|
rl = check_rate_limit(row["id"], row["rateLimitPerMin"])
|
||||||
|
actor = {
|
||||||
|
"auth_type": "agent",
|
||||||
|
"key_id": row["id"],
|
||||||
|
"nombre": row["nombre"],
|
||||||
|
"prefijo": row["prefijo"],
|
||||||
|
"scopes": list(row["scopes"] or []),
|
||||||
|
"rate_limit": row["rateLimitPerMin"],
|
||||||
|
"ip": ip,
|
||||||
|
}
|
||||||
|
if not rl["ok"]:
|
||||||
|
await registrar_auditoria(
|
||||||
|
pool,
|
||||||
|
actor,
|
||||||
|
"auth.rate_limit",
|
||||||
|
"api",
|
||||||
|
exito=False,
|
||||||
|
detalle={"limit": rl["limit"]},
|
||||||
|
ip=ip,
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||||
|
detail="Limite de peticiones por minuto excedido",
|
||||||
|
headers={
|
||||||
|
"X-RateLimit-Limit": str(rl["limit"]),
|
||||||
|
"X-RateLimit-Remaining": "0",
|
||||||
|
"X-RateLimit-Reset": str(rl["reset_at"]),
|
||||||
|
"Retry-After": str(rl["retry_after"]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
last_used = row["lastUsedAt"]
|
||||||
|
now_dt = datetime.now(timezone.utc)
|
||||||
|
if last_used is None or (
|
||||||
|
now_dt - (last_used.replace(tzinfo=timezone.utc) if last_used.tzinfo is None else last_used)
|
||||||
|
).total_seconds() > 60:
|
||||||
|
try:
|
||||||
|
await pool.execute(
|
||||||
|
'UPDATE "AgentApiKey" SET "lastUsedAt" = NOW() WHERE id = $1',
|
||||||
|
row["id"],
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return actor
|
||||||
|
|
||||||
|
|
||||||
async def require_auth(
|
async def require_auth(
|
||||||
|
request: Request,
|
||||||
authorization: str | None = Header(None),
|
authorization: str | None = Header(None),
|
||||||
x_api_key: str | None = Header(None),
|
x_api_key: str | None = Header(None),
|
||||||
) -> dict:
|
) -> dict:
|
||||||
if x_api_key and x_api_key == settings.API_KEY:
|
ip = _client_ip(request)
|
||||||
return {"auth_type": "api_key"}
|
bearer_token: str | None = None
|
||||||
|
|
||||||
if authorization:
|
if authorization:
|
||||||
scheme, _, token = authorization.partition(" ")
|
scheme, _, token = authorization.partition(" ")
|
||||||
if scheme.lower() == "bearer" and token:
|
if scheme.lower() == "bearer" and token.strip():
|
||||||
payload = decode_token(token)
|
bearer_token = token.strip()
|
||||||
|
# 1. Intentar JWT humano primero
|
||||||
|
payload = decode_token(bearer_token)
|
||||||
if payload:
|
if payload:
|
||||||
return {"auth_type": "jwt", **payload}
|
if payload.get("role") == "cliente":
|
||||||
if x_api_key == settings.API_KEY:
|
raise HTTPException(
|
||||||
return {"auth_type": "api_key"}
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Acceso restringido al panel de cliente",
|
||||||
|
)
|
||||||
|
return {"auth_type": "jwt", "ip": ip, **payload}
|
||||||
|
|
||||||
|
raw_key = (x_api_key or "").strip() or bearer_token
|
||||||
|
if raw_key:
|
||||||
|
# 2. Validar contra AgentApiKey en PostgreSQL (SHA-256)
|
||||||
|
agent_actor = await _validate_agent_key(raw_key, ip)
|
||||||
|
if agent_actor:
|
||||||
|
return agent_actor
|
||||||
|
|
||||||
|
# 3. Compatibilidad legacy SOLO si ALLOW_LEGACY_API_KEY=true explicitamente
|
||||||
|
if settings.ALLOW_LEGACY_API_KEY and raw_key == settings.API_KEY:
|
||||||
|
return {"auth_type": "legacy_api_key", "scopes": [], "ip": ip}
|
||||||
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Invalid or missing authentication credentials",
|
detail="Credenciales de autenticacion invalidas o ausentes",
|
||||||
headers={"WWW-Authenticate": "Bearer"},
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def require_scope(*required_scopes: str, mode: str = "any"):
|
||||||
|
async def _checker(
|
||||||
|
request: Request,
|
||||||
|
auth: dict = Depends(require_auth),
|
||||||
|
) -> dict:
|
||||||
|
atype = auth.get("auth_type")
|
||||||
|
if atype in ("jwt", "legacy_api_key"):
|
||||||
|
return auth
|
||||||
|
|
||||||
|
scopes = set(auth.get("scopes") or [])
|
||||||
|
ok = (
|
||||||
|
all(s in scopes for s in required_scopes)
|
||||||
|
if mode == "all"
|
||||||
|
else any(s in scopes for s in required_scopes)
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
pool = await get_pool()
|
||||||
|
await registrar_auditoria(
|
||||||
|
pool,
|
||||||
|
auth,
|
||||||
|
"auth.scope_insuficiente",
|
||||||
|
"api",
|
||||||
|
exito=False,
|
||||||
|
detalle={
|
||||||
|
"path": request.url.path,
|
||||||
|
"requiredScopes": list(required_scopes),
|
||||||
|
"actorScopes": list(scopes),
|
||||||
|
},
|
||||||
|
ip=auth.get("ip"),
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Alcance insuficiente. Requerido: {', '.join(required_scopes)}",
|
||||||
|
)
|
||||||
|
return auth
|
||||||
|
|
||||||
|
return _checker
|
||||||
|
|
||||||
|
|
||||||
|
async def require_staff_human(
|
||||||
|
request: Request,
|
||||||
|
auth: dict = Depends(require_auth),
|
||||||
|
) -> dict:
|
||||||
|
atype = auth.get("auth_type")
|
||||||
|
if atype == "jwt" and auth.get("role") != "cliente":
|
||||||
|
return auth
|
||||||
|
if atype == "legacy_api_key":
|
||||||
|
return auth
|
||||||
|
|
||||||
|
pool = await get_pool()
|
||||||
|
await registrar_auditoria(
|
||||||
|
pool,
|
||||||
|
auth,
|
||||||
|
"auth.staff_requerido",
|
||||||
|
"api",
|
||||||
|
exito=False,
|
||||||
|
detalle={"path": request.url.path, "auth_type": atype},
|
||||||
|
ip=auth.get("ip"),
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Accion restringida a personal humano",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def require_admin_human(
|
||||||
|
request: Request,
|
||||||
|
auth: dict = Depends(require_auth),
|
||||||
|
) -> dict:
|
||||||
|
if auth.get("auth_type") == "jwt" and auth.get("role") == "admin":
|
||||||
|
return auth
|
||||||
|
|
||||||
|
pool = await get_pool()
|
||||||
|
await registrar_auditoria(
|
||||||
|
pool,
|
||||||
|
auth,
|
||||||
|
"auth.admin_requerido",
|
||||||
|
"api",
|
||||||
|
exito=False,
|
||||||
|
detalle={"path": request.url.path, "auth_type": auth.get("auth_type")},
|
||||||
|
ip=auth.get("ip"),
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Accion restringida exclusivamente a un administrador humano",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def es_agente_solo_aceptadas(auth: dict) -> bool:
|
||||||
|
if auth.get("auth_type") != "agent":
|
||||||
|
return False
|
||||||
|
scopes = set(auth.get("scopes") or [])
|
||||||
|
return "cotizaciones:leer_aceptadas" in scopes and "cotizaciones:leer" not in scopes
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ class Settings(BaseSettings):
|
|||||||
DB_PORT: int = 5432
|
DB_PORT: int = 5432
|
||||||
DB_USER: str = "postgres"
|
DB_USER: str = "postgres"
|
||||||
DB_PASSWORD: str = "postgres"
|
DB_PASSWORD: str = "postgres"
|
||||||
|
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
DB_NAME: str = "cotizador_e3"
|
DB_NAME: str = "cotizador_e3"
|
||||||
API_KEY: str = "change-me-to-a-secure-random-key"
|
API_KEY: str = "change-me-to-a-secure-random-key"
|
||||||
|
ALLOW_LEGACY_API_KEY: bool = False
|
||||||
JWT_SECRET: str = "change-me-to-a-secure-jwt-secret"
|
JWT_SECRET: str = "change-me-to-a-secure-jwt-secret"
|
||||||
API_HOST: str = "0.0.0.0"
|
API_HOST: str = "0.0.0.0"
|
||||||
API_PORT: int = 8000
|
API_PORT: int = 8000
|
||||||
|
|||||||
@@ -41,9 +41,9 @@ class HealthResponse(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class APIInfoResponse(BaseModel):
|
class APIInfoResponse(BaseModel):
|
||||||
name: str = "Cotizador E3 API"
|
name: str = "Cotizador — Uriel Jareth Consulting API"
|
||||||
version: str = "1.0.0"
|
version: str = "1.0.0"
|
||||||
description: str = "API para sistema de cotizaciones de marketing digital"
|
description: str = "API para el sistema de cotizaciones de Uriel Jareth Consulting"
|
||||||
capabilities: list[str] = Field(default_factory=list)
|
capabilities: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ ALLOWED_CONFIG_KEYS: set[str] = {
|
|||||||
"logo_base64",
|
"logo_base64",
|
||||||
"razon_social",
|
"razon_social",
|
||||||
"rfc",
|
"rfc",
|
||||||
"domicilio_fiscal",
|
"domicilio_fiscal", # Opcional interno; no se imprime en documentos generados
|
||||||
"cuenta_nacional",
|
"cuenta_nacional",
|
||||||
"clabe_interbancaria",
|
"clabe_interbancaria",
|
||||||
"cuenta_internacional",
|
"cuenta_internacional",
|
||||||
@@ -28,7 +28,7 @@ class ConfigUpdate(BaseModel):
|
|||||||
description="Key-value config pairs. Only whitelisted keys are processed.",
|
description="Key-value config pairs. Only whitelisted keys are processed.",
|
||||||
json_schema_extra={
|
json_schema_extra={
|
||||||
"examples": [
|
"examples": [
|
||||||
{"color_primario": "#ff0000", "razon_social": "Nueva Empresa SA de CV"}
|
{"color_primario": "#0400C4", "razon_social": "Uriel Jareth Consulting"}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ from typing import Any
|
|||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
ESTADOS_PATTERN = "^(borrador|aprobada|enviada|aceptada|rechazada|vencida)$"
|
||||||
|
|
||||||
|
|
||||||
class ServicioCotizadoInput(BaseModel):
|
class ServicioCotizadoInput(BaseModel):
|
||||||
catalogoId: str = Field(..., min_length=1, description="ID del servicio del catálogo o 'custom-...' para partidas personalizadas")
|
catalogoId: str = Field(..., min_length=1, description="ID del servicio del catálogo o 'custom-...' para partidas personalizadas")
|
||||||
@@ -14,14 +16,12 @@ class ServicioCotizadoInput(BaseModel):
|
|||||||
precio: float = Field(..., ge=0, description="Precio (puede diferir del precioBase)")
|
precio: float = Field(..., ge=0, description="Precio (puede diferir del precioBase)")
|
||||||
tiempoEntrega: str
|
tiempoEntrega: str
|
||||||
entregables: list[str] = Field(default_factory=list)
|
entregables: list[str] = Field(default_factory=list)
|
||||||
# Partidas por tiempo (sin catálogo). modeloCobro: "fijo" | "horas" | "retainer".
|
|
||||||
esPersonalizado: bool = False
|
esPersonalizado: bool = False
|
||||||
horas: float | None = Field(None, ge=0)
|
horas: float | None = Field(None, ge=0)
|
||||||
tarifaHora: float | None = Field(None, ge=0)
|
tarifaHora: float | None = Field(None, ge=0)
|
||||||
modeloCobro: str | None = Field(None, pattern="^(fijo|horas|retainer)$")
|
modeloCobro: str | None = Field(None, pattern="^(fijo|horas|retainer|demanda)$")
|
||||||
montoMinimo: float | None = Field(None, ge=0)
|
montoMinimo: float | None = Field(None, ge=0)
|
||||||
horasIncluidas: float | None = Field(None, ge=0)
|
horasIncluidas: float | None = Field(None, ge=0)
|
||||||
# Doble propuesta: "1" | "2" | "ambas". None en cotizaciones normales.
|
|
||||||
opcion: str | None = Field(None, pattern="^(1|2|ambas)$")
|
opcion: str | None = Field(None, pattern="^(1|2|ambas)$")
|
||||||
|
|
||||||
|
|
||||||
@@ -50,55 +50,18 @@ class CotizacionCreate(BaseModel):
|
|||||||
moneda: str = Field("MXN", pattern="^(MXN|USD)$")
|
moneda: str = Field("MXN", pattern="^(MXN|USD)$")
|
||||||
tipoCambio: str = "NA"
|
tipoCambio: str = "NA"
|
||||||
proyecto: str = "MKT Digital"
|
proyecto: str = "MKT Digital"
|
||||||
esquemaPago: str = Field("Pago Unico/Mensual", pattern="^(Pago Unico|Mensual|Pago Unico/Mensual)$")
|
esquemaPago: str = Field("Pago Unico/Mensual", pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$")
|
||||||
incluirBonos: bool = False
|
incluirBonos: bool = False
|
||||||
incluirFinanciamiento: bool = False
|
incluirFinanciamiento: bool = False
|
||||||
|
incluirIva: bool = True
|
||||||
esDoble: bool = False
|
esDoble: bool = False
|
||||||
opciones: dict[str, MetaOpcionInput] | None = None
|
opciones: dict[str, MetaOpcionInput] | None = None
|
||||||
observaciones: str = ""
|
observaciones: str = ""
|
||||||
asesorId: str = Field(..., min_length=1)
|
asesorId: str | None = None
|
||||||
cliente: ClienteInput
|
cliente: ClienteInput
|
||||||
servicios: list[ServicioCotizadoInput] = Field(..., min_length=1)
|
servicios: list[ServicioCotizadoInput] = Field(..., min_length=1)
|
||||||
planBucefalo: PlanBucefaloInput | None = None
|
planBucefalo: PlanBucefaloInput | None = None
|
||||||
|
|
||||||
model_config = {
|
|
||||||
"json_schema_extra": {
|
|
||||||
"examples": [
|
|
||||||
{
|
|
||||||
"numero": "UJ2605AG001",
|
|
||||||
"fecha": "2026-05-03",
|
|
||||||
"vigencia": "2026-05-24",
|
|
||||||
"moneda": "MXN",
|
|
||||||
"tipoCambio": "NA",
|
|
||||||
"proyecto": "MKT Digital",
|
|
||||||
"esquemaPago": "Pago Unico/Mensual",
|
|
||||||
"incluirBonos": False,
|
|
||||||
"incluirFinanciamiento": False,
|
|
||||||
"observaciones": "",
|
|
||||||
"asesorId": "cuid-asesor",
|
|
||||||
"cliente": {
|
|
||||||
"nombre": "Juan Pérez",
|
|
||||||
"empresa": "ACME Corp",
|
|
||||||
"email": "[email protected]",
|
|
||||||
"telefono": "4421234567",
|
|
||||||
},
|
|
||||||
"servicios": [
|
|
||||||
{
|
|
||||||
"catalogoId": "cuid-servicio",
|
|
||||||
"nombre": "SEO On-Page",
|
|
||||||
"fase": 3,
|
|
||||||
"tipoPago": "mensual",
|
|
||||||
"precio": 2900,
|
|
||||||
"tiempoEntrega": "7 - 14 dias",
|
|
||||||
"entregables": ["Keyword research"],
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"planBucefalo": {"nivel": "basico", "precio": 1000},
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class CotizacionUpdate(BaseModel):
|
class CotizacionUpdate(BaseModel):
|
||||||
fecha: datetime | None = None
|
fecha: datetime | None = None
|
||||||
@@ -106,20 +69,21 @@ class CotizacionUpdate(BaseModel):
|
|||||||
moneda: str | None = Field(None, pattern="^(MXN|USD)$")
|
moneda: str | None = Field(None, pattern="^(MXN|USD)$")
|
||||||
tipoCambio: str | None = None
|
tipoCambio: str | None = None
|
||||||
proyecto: str | None = None
|
proyecto: str | None = None
|
||||||
esquemaPago: str | None = Field(None, pattern="^(Pago Unico|Mensual|Pago Unico/Mensual)$")
|
esquemaPago: str | None = Field(None, pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$")
|
||||||
incluirBonos: bool | None = None
|
incluirBonos: bool | None = None
|
||||||
incluirFinanciamiento: bool | None = None
|
incluirFinanciamiento: bool | None = None
|
||||||
|
incluirIva: bool | None = None
|
||||||
esDoble: bool | None = None
|
esDoble: bool | None = None
|
||||||
opciones: dict[str, MetaOpcionInput] | None = None
|
opciones: dict[str, MetaOpcionInput] | None = None
|
||||||
observaciones: str | None = None
|
observaciones: str | None = None
|
||||||
estado: str | None = Field(None, pattern="^(borrador|enviada|aprobada|rechazada)$")
|
estado: str | None = Field(None, pattern=ESTADOS_PATTERN)
|
||||||
cliente: ClienteInput | None = None
|
cliente: ClienteInput | None = None
|
||||||
servicios: list[ServicioCotizadoInput] | None = None
|
servicios: list[ServicioCotizadoInput] | None = None
|
||||||
planBucefalo: PlanBucefaloInput | None = None
|
planBucefalo: PlanBucefaloInput | None = None
|
||||||
|
|
||||||
|
|
||||||
class CambiarEstadoRequest(BaseModel):
|
class CambiarEstadoRequest(BaseModel):
|
||||||
estado: str = Field(..., pattern="^(borrador|enviada|aprobada|rechazada)$")
|
estado: str = Field(..., pattern=ESTADOS_PATTERN)
|
||||||
|
|
||||||
|
|
||||||
class ActualizarPrecioRequest(BaseModel):
|
class ActualizarPrecioRequest(BaseModel):
|
||||||
@@ -139,11 +103,23 @@ class CotizacionResponse(BaseModel):
|
|||||||
estado: str
|
estado: str
|
||||||
incluirBonos: bool
|
incluirBonos: bool
|
||||||
incluirFinanciamiento: bool
|
incluirFinanciamiento: bool
|
||||||
|
incluirIva: bool = True
|
||||||
esDoble: bool = False
|
esDoble: bool = False
|
||||||
opcionesMetadata: dict[str, Any] | None = None
|
opcionesMetadata: dict[str, Any] | None = None
|
||||||
observaciones: str | None
|
observaciones: str | None
|
||||||
clienteId: str
|
clienteId: str
|
||||||
asesorId: str
|
asesorId: str
|
||||||
|
aprobadaPorId: str | None = None
|
||||||
|
aprobadaAt: datetime | None = None
|
||||||
|
aprobacionMetodo: str | None = None
|
||||||
|
enviadaAt: datetime | None = None
|
||||||
|
enviadaPor: str | None = None
|
||||||
|
enviadaCanal: str | None = None
|
||||||
|
enviadaDestino: str | None = None
|
||||||
|
aceptadaAt: datetime | None = None
|
||||||
|
rechazadaAt: datetime | None = None
|
||||||
|
vencidaAt: datetime | None = None
|
||||||
|
creadaPorAgente: str | None = None
|
||||||
createdAt: datetime
|
createdAt: datetime
|
||||||
updatedAt: datetime
|
updatedAt: datetime
|
||||||
cliente: dict[str, Any] | None = None
|
cliente: dict[str, Any] | None = None
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
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.models.export_ import BonoResponse
|
||||||
from app.services.calculators import BONOS
|
from app.services.calculators import BONOS
|
||||||
|
|
||||||
@@ -10,5 +10,5 @@ router = APIRouter(prefix="/bonos", tags=["Bonos"])
|
|||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=list[BonoResponse])
|
@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]
|
return [BonoResponse(**b) for b in BONOS]
|
||||||
|
|||||||
@@ -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_auth
|
from app.auth import 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,
|
||||||
@@ -63,7 +63,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
|||||||
)
|
)
|
||||||
async def list_catalogo(
|
async def list_catalogo(
|
||||||
db: Connection = Depends(get_db),
|
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),
|
fase: int | None = Query(None, ge=0, le=3),
|
||||||
tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"),
|
tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"),
|
||||||
categoriaId: str | None = Query(None),
|
categoriaId: str | None = Query(None),
|
||||||
@@ -121,7 +121,7 @@ async def list_catalogo(
|
|||||||
async def create_catalogo(
|
async def create_catalogo(
|
||||||
body: ServicioCatalogoCreate,
|
body: ServicioCatalogoCreate,
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_staff_human),
|
||||||
):
|
):
|
||||||
if body.categoriaId:
|
if body.categoriaId:
|
||||||
cat = await db.fetchrow(
|
cat = await db.fetchrow(
|
||||||
@@ -168,7 +168,7 @@ async def create_catalogo(
|
|||||||
async def get_catalogo(
|
async def get_catalogo(
|
||||||
servicio_id: str,
|
servicio_id: str,
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
):
|
):
|
||||||
row = await db.fetchrow(
|
row = await db.fetchrow(
|
||||||
'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||||
@@ -195,7 +195,7 @@ async def update_catalogo(
|
|||||||
servicio_id: str,
|
servicio_id: str,
|
||||||
body: ServicioCatalogoUpdate,
|
body: ServicioCatalogoUpdate,
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_staff_human),
|
||||||
):
|
):
|
||||||
existing = await db.fetchrow(
|
existing = await db.fetchrow(
|
||||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||||
@@ -265,7 +265,7 @@ async def update_catalogo(
|
|||||||
async def delete_catalogo(
|
async def delete_catalogo(
|
||||||
servicio_id: str,
|
servicio_id: str,
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_staff_human),
|
||||||
):
|
):
|
||||||
existing = await db.fetchrow(
|
existing = await db.fetchrow(
|
||||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
'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.database import get_pool
|
||||||
from app.dependencies import get_db
|
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.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse
|
||||||
from app.models.common import ErrorResponse, OkResponse
|
from app.models.common import ErrorResponse, OkResponse
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/categorias", tags=["Categorias"])
|
|||||||
|
|
||||||
@router.get("", response_model=list[CategoriaResponse])
|
@router.get("", response_model=list[CategoriaResponse])
|
||||||
async def list_categorias(
|
async def list_categorias(
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
rows = await conn.fetch(
|
rows = await conn.fetch(
|
||||||
@@ -33,7 +33,7 @@ async def list_categorias(
|
|||||||
)
|
)
|
||||||
async def create_categoria(
|
async def create_categoria(
|
||||||
body: CategoriaCreate,
|
body: CategoriaCreate,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
@@ -64,7 +64,7 @@ async def create_categoria(
|
|||||||
)
|
)
|
||||||
async def get_categoria(
|
async def get_categoria(
|
||||||
categoria_id: str,
|
categoria_id: str,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
row = await conn.fetchrow(
|
row = await conn.fetchrow(
|
||||||
@@ -93,7 +93,7 @@ async def get_categoria(
|
|||||||
async def update_categoria(
|
async def update_categoria(
|
||||||
categoria_id: str,
|
categoria_id: str,
|
||||||
body: CategoriaUpdate,
|
body: CategoriaUpdate,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
existing = await conn.fetchrow(
|
existing = await conn.fetchrow(
|
||||||
@@ -166,7 +166,7 @@ async def update_categoria(
|
|||||||
)
|
)
|
||||||
async def delete_categoria(
|
async def delete_categoria(
|
||||||
categoria_id: str,
|
categoria_id: str,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
existing = await conn.fetchrow(
|
existing = await conn.fetchrow(
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import math
|
|||||||
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_auth
|
from app.auth import require_scope, require_staff_human
|
||||||
from app.dependencies import PaginationParams, get_db
|
from app.dependencies import PaginationParams, get_db
|
||||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||||
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
||||||
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/clientes", tags=["Clientes"])
|
|||||||
)
|
)
|
||||||
async def list_clientes(
|
async def list_clientes(
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
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"),
|
||||||
):
|
):
|
||||||
@@ -79,7 +79,7 @@ async def list_clientes(
|
|||||||
async def create_cliente(
|
async def create_cliente(
|
||||||
body: ClienteCreate,
|
body: ClienteCreate,
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_scope("clientes:escribir")),
|
||||||
):
|
):
|
||||||
row = await db.fetchrow(
|
row = await db.fetchrow(
|
||||||
'INSERT INTO "Cliente" (nombre, empresa, email, telefono) '
|
'INSERT INTO "Cliente" (nombre, empresa, email, telefono) '
|
||||||
@@ -109,7 +109,7 @@ async def create_cliente(
|
|||||||
async def get_cliente(
|
async def get_cliente(
|
||||||
cliente_id: str,
|
cliente_id: str,
|
||||||
db: Connection = Depends(get_db),
|
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)
|
row = await db.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cliente_id)
|
||||||
if not row:
|
if not row:
|
||||||
@@ -146,7 +146,7 @@ async def update_cliente(
|
|||||||
cliente_id: str,
|
cliente_id: str,
|
||||||
body: ClienteUpdate,
|
body: ClienteUpdate,
|
||||||
db: Connection = Depends(get_db),
|
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)
|
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||||
if not existing:
|
if not existing:
|
||||||
@@ -192,7 +192,7 @@ async def update_cliente(
|
|||||||
async def delete_cliente(
|
async def delete_cliente(
|
||||||
cliente_id: str,
|
cliente_id: str,
|
||||||
db: Connection = Depends(get_db),
|
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)
|
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||||
if not existing:
|
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.dependencies import get_db
|
||||||
from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS
|
from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS
|
||||||
from app.models.common import ErrorResponse, OkResponse
|
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 = APIRouter(prefix="/configuracion", tags=["Configuración"])
|
||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=ConfigResponse)
|
@router.get("", response_model=ConfigResponse)
|
||||||
async def get_configuracion(
|
async def get_configuracion(
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
rows = await db.fetch("SELECT clave, valor FROM Configuracion")
|
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}})
|
@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}})
|
||||||
async def update_configuracion(
|
async def update_configuracion(
|
||||||
body: ConfigUpdate,
|
body: ConfigUpdate,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
allowed = body.get_allowed()
|
allowed = body.get_allowed()
|
||||||
|
|||||||
+380
-94
@@ -6,7 +6,13 @@ from datetime import datetime, timezone
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
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.database import get_pool
|
||||||
from app.dependencies import PaginationParams, parse_date
|
from app.dependencies import PaginationParams, parse_date
|
||||||
from app.models.common import Meta, OkResponse, PaginatedResponse
|
from app.models.common import Meta, OkResponse, PaginatedResponse
|
||||||
@@ -26,9 +32,14 @@ def _cuid() -> str:
|
|||||||
return uuid.uuid4().hex[:25]
|
return uuid.uuid4().hex[:25]
|
||||||
|
|
||||||
|
|
||||||
async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_servicio_id, now, es_doble: bool = False) -> None:
|
async def _insert_servicio_cotizado(
|
||||||
"""Inserta un ServicioCotizado desde un ServicioCotizadoInput, manejando
|
conn,
|
||||||
partidas personalizadas (por horas / retainer) en paridad con el backend Next.js."""
|
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-")
|
es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-")
|
||||||
|
|
||||||
if es_personalizado:
|
if es_personalizado:
|
||||||
@@ -39,8 +50,8 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
|||||||
catalogo_id = svc.catalogoId
|
catalogo_id = svc.catalogoId
|
||||||
|
|
||||||
modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo")
|
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
|
opcion = (svc.opcion or "ambas") if es_doble else None
|
||||||
|
precio_final = 0 if modelo_cobro == "demanda" else svc.precio
|
||||||
|
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
"""
|
"""
|
||||||
@@ -64,7 +75,7 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
|||||||
opcion,
|
opcion,
|
||||||
svc.fase,
|
svc.fase,
|
||||||
svc.tipoPago,
|
svc.tipoPago,
|
||||||
svc.precio,
|
precio_final,
|
||||||
svc.tiempoEntrega,
|
svc.tiempoEntrega,
|
||||||
json.dumps(svc.entregables),
|
json.dumps(svc.entregables),
|
||||||
None,
|
None,
|
||||||
@@ -73,7 +84,6 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
|||||||
|
|
||||||
|
|
||||||
def _parse_json(val):
|
def _parse_json(val):
|
||||||
"""asyncpg devuelve columnas jsonb como str; las parsea a dict/list."""
|
|
||||||
if isinstance(val, str):
|
if isinstance(val, str):
|
||||||
try:
|
try:
|
||||||
return json.loads(val)
|
return json.loads(val)
|
||||||
@@ -86,6 +96,7 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=
|
|||||||
d = dict(cot)
|
d = dict(cot)
|
||||||
if "opcionesMetadata" in d:
|
if "opcionesMetadata" in d:
|
||||||
d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"])
|
d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"])
|
||||||
|
d.pop("observacionesInternas", None)
|
||||||
d["cliente"] = dict(cliente) if cliente else None
|
d["cliente"] = dict(cliente) if cliente else None
|
||||||
d["asesor"] = dict(asesor) if asesor else None
|
d["asesor"] = dict(asesor) if asesor else None
|
||||||
d["servicios"] = [dict(s) for s in servicios] if servicios else []
|
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
|
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 = """
|
_SERVICIOS_SQL = """
|
||||||
SELECT sc.*, sc."servicioCatalogoId" as "catalogoId",
|
SELECT sc.*, sc."servicioCatalogoId" as "catalogoId",
|
||||||
COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId"
|
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]:
|
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:
|
if not cot_rows:
|
||||||
return []
|
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])
|
@router.get("", response_model=PaginatedResponse[CotizacionResponse])
|
||||||
async def list_cotizaciones(
|
async def list_cotizaciones(
|
||||||
@@ -204,17 +211,33 @@ 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),
|
||||||
_auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||||
):
|
):
|
||||||
pool = await get_pool()
|
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] = []
|
conditions: list[str] = []
|
||||||
params: list = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
if estado:
|
if estado_efectivo:
|
||||||
conditions.append(f'c.estado = ${idx}')
|
conditions.append(f"c.estado = ${idx}")
|
||||||
params.append(estado)
|
params.append(estado_efectivo)
|
||||||
idx += 1
|
idx += 1
|
||||||
if asesorId:
|
if asesorId:
|
||||||
conditions.append(f'c."asesorId" = ${idx}')
|
conditions.append(f'c."asesorId" = ${idx}')
|
||||||
@@ -226,18 +249,18 @@ async def list_cotizaciones(
|
|||||||
idx += 1
|
idx += 1
|
||||||
if q:
|
if q:
|
||||||
conditions.append(
|
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}%")
|
params.append(f"%{q}%")
|
||||||
idx += 1
|
idx += 1
|
||||||
desde_dt = parse_date(desde)
|
desde_dt = parse_date(desde)
|
||||||
if desde_dt:
|
if desde_dt:
|
||||||
conditions.append(f'c.fecha >= ${idx}')
|
conditions.append(f"c.fecha >= ${idx}")
|
||||||
params.append(desde_dt)
|
params.append(desde_dt)
|
||||||
idx += 1
|
idx += 1
|
||||||
hasta_dt = parse_date(hasta)
|
hasta_dt = parse_date(hasta)
|
||||||
if hasta_dt:
|
if hasta_dt:
|
||||||
conditions.append(f'c.fecha <= ${idx}')
|
conditions.append(f"c.fecha <= ${idx}")
|
||||||
params.append(hasta_dt)
|
params.append(hasta_dt)
|
||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
@@ -263,7 +286,6 @@ async def list_cotizaciones(
|
|||||||
)
|
)
|
||||||
|
|
||||||
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
||||||
|
|
||||||
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
||||||
|
|
||||||
return PaginatedResponse(
|
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)
|
@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()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
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():
|
async with conn.transaction():
|
||||||
cliente_id = await _find_or_create_cliente(
|
cliente_id = await _find_or_create_cliente(
|
||||||
conn,
|
conn,
|
||||||
@@ -293,13 +332,15 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
|||||||
opciones_json = None
|
opciones_json = None
|
||||||
if body.esDoble and body.opciones:
|
if body.esDoble and body.opciones:
|
||||||
opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
||||||
|
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO "Cotizacion"
|
INSERT INTO "Cotizacion"
|
||||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
"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,
|
cot_id,
|
||||||
body.numero,
|
body.numero,
|
||||||
@@ -311,16 +352,17 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
|||||||
body.esquemaPago,
|
body.esquemaPago,
|
||||||
body.incluirBonos,
|
body.incluirBonos,
|
||||||
body.incluirFinanciamiento,
|
body.incluirFinanciamiento,
|
||||||
|
body.incluirIva,
|
||||||
body.esDoble,
|
body.esDoble,
|
||||||
opciones_json,
|
opciones_json,
|
||||||
body.observaciones or None,
|
body.observaciones or None,
|
||||||
cliente_id,
|
cliente_id,
|
||||||
body.asesorId,
|
asesor_id,
|
||||||
|
creada_por_agente,
|
||||||
now,
|
now,
|
||||||
)
|
)
|
||||||
|
|
||||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||||
|
|
||||||
for svc in body.servicios:
|
for svc in body.servicios:
|
||||||
await _insert_servicio_cotizado(conn, cot_id, svc, bucefalo_servicio_id, now, body.esDoble)
|
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,
|
now,
|
||||||
)
|
)
|
||||||
|
|
||||||
row = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id)
|
await registrar_auditoria(
|
||||||
result = dict(row)
|
conn,
|
||||||
result["opcionesMetadata"] = _parse_json(result.get("opcionesMetadata"))
|
auth,
|
||||||
return result
|
"cotizacion.crear",
|
||||||
|
"cotizacion",
|
||||||
|
recurso_id=cot_id,
|
||||||
|
exito=True,
|
||||||
|
detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente},
|
||||||
|
)
|
||||||
|
|
||||||
|
full = await _fetch_cotizacion_full(pool, cot_id)
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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")
|
|
||||||
return full
|
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)
|
@router.put("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||||
async def update_cotizacion(
|
async def update_cotizacion(
|
||||||
cotizacion_id: str,
|
cotizacion_id: str,
|
||||||
body: CotizacionUpdate,
|
body: CotizacionUpdate,
|
||||||
_auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||||
):
|
):
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
@@ -371,6 +439,58 @@ async def update_cotizacion(
|
|||||||
if not existing:
|
if not existing:
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
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():
|
async with conn.transaction():
|
||||||
cliente_id = existing["clienteId"]
|
cliente_id = existing["clienteId"]
|
||||||
if body.cliente:
|
if body.cliente:
|
||||||
@@ -386,54 +506,55 @@ async def update_cotizacion(
|
|||||||
params: list = []
|
params: list = []
|
||||||
idx = 1
|
idx = 1
|
||||||
|
|
||||||
def _add(field: str, col: str, val):
|
def _add(col: str, val):
|
||||||
nonlocal idx
|
nonlocal idx
|
||||||
if val is not None:
|
|
||||||
updates.append(f'{col} = ${idx}')
|
updates.append(f'{col} = ${idx}')
|
||||||
params.append(val)
|
params.append(val)
|
||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
_add("fecha", "fecha", body.fecha)
|
if body.fecha is not None:
|
||||||
_add("vigencia", "vigencia", body.vigencia)
|
_add("fecha", body.fecha)
|
||||||
_add("moneda", "moneda", body.moneda)
|
if body.vigencia is not None:
|
||||||
_add("tipoCambio", '"tipoCambio"', body.tipoCambio)
|
_add("vigencia", body.vigencia)
|
||||||
_add("proyecto", "proyecto", body.proyecto)
|
if body.moneda is not None:
|
||||||
_add("esquemaPago", '"esquemaPago"', body.esquemaPago)
|
_add("moneda", body.moneda)
|
||||||
_add("incluirBonos", '"incluirBonos"', body.incluirBonos)
|
if body.tipoCambio is not None:
|
||||||
_add("incluirFinanciamiento", '"incluirFinanciamiento"', body.incluirFinanciamiento)
|
_add('"tipoCambio"', body.tipoCambio)
|
||||||
_add("esDoble", '"esDoble"', body.esDoble)
|
if body.proyecto is not None:
|
||||||
_add("observaciones", "observaciones", body.observaciones)
|
_add("proyecto", body.proyecto)
|
||||||
_add("estado", "estado", body.estado)
|
if body.esquemaPago is not None:
|
||||||
|
_add('"esquemaPago"', body.esquemaPago)
|
||||||
es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"]
|
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:
|
if body.esDoble is not None:
|
||||||
# opcionesMetadata se sincroniza con esDoble: dict (json) si doble, NULL si no.
|
_add('"esDoble"', body.esDoble)
|
||||||
meta_json = None
|
if body.opciones is not None:
|
||||||
if es_doble_final and body.opciones:
|
_add('"opcionesMetadata"', json.dumps({k: v.model_dump() for k, v in body.opciones.items()}))
|
||||||
meta_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
if body.observaciones is not None:
|
||||||
updates.append(f'"opcionesMetadata" = ${idx}')
|
_add("observaciones", body.observaciones)
|
||||||
params.append(meta_json)
|
if body.estado is not None and auth.get("auth_type") != "agent":
|
||||||
idx += 1
|
_add("estado", body.estado)
|
||||||
|
|
||||||
if cliente_id != existing["clienteId"]:
|
if cliente_id != existing["clienteId"]:
|
||||||
updates.append(f'"clienteId" = ${idx}')
|
_add('"clienteId"', cliente_id)
|
||||||
params.append(cliente_id)
|
|
||||||
idx += 1
|
|
||||||
|
|
||||||
if updates:
|
if updates:
|
||||||
updates.append(f'"updatedAt" = ${idx}')
|
updates.append('"updatedAt" = NOW()')
|
||||||
params.append(datetime.now(timezone.utc))
|
|
||||||
idx += 1
|
|
||||||
params.append(cotizacion_id)
|
params.append(cotizacion_id)
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}',
|
f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}',
|
||||||
*params,
|
*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:
|
if body.servicios is not None:
|
||||||
await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id)
|
await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id)
|
||||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
for svc in body.servicios:
|
for svc in body.servicios:
|
||||||
await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final)
|
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',
|
'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||||
cotizacion_id,
|
cotizacion_id,
|
||||||
)
|
)
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
if existing_plan:
|
if existing_plan:
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4',
|
'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4',
|
||||||
@@ -470,20 +590,40 @@ async def update_cotizacion(
|
|||||||
cotizacion_id,
|
cotizacion_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
await registrar_auditoria(
|
||||||
return full
|
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)
|
@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()
|
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:
|
if not existing:
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||||
await pool.execute('DELETE FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
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)
|
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(
|
async def update_precio_servicio(
|
||||||
cotizacion_id: str,
|
cotizacion_id: str,
|
||||||
body: ActualizarPrecioRequest,
|
body: ActualizarPrecioRequest,
|
||||||
_auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||||
):
|
):
|
||||||
pool = await get_pool()
|
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:
|
if not cot:
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
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(
|
svc = await pool.fetchrow(
|
||||||
'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2',
|
'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2',
|
||||||
body.servicioId,
|
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)
|
@router.patch("/{cotizacion_id}/estado", response_model=OkResponse)
|
||||||
async def cambiar_estado(
|
async def cambiar_estado(
|
||||||
cotizacion_id: str,
|
cotizacion_id: str,
|
||||||
body: CambiarEstadoRequest,
|
body: CambiarEstadoRequest,
|
||||||
_auth: dict = Depends(require_auth),
|
auth: dict = Depends(require_auth),
|
||||||
):
|
):
|
||||||
if body.estado not in ESTADOS_COTIZACION:
|
if body.estado not in ESTADOS_COTIZACION:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -533,13 +688,127 @@ async def cambiar_estado(
|
|||||||
)
|
)
|
||||||
|
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
result = await pool.execute(
|
existing = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||||
'UPDATE "Cotizacion" SET estado = $1, "updatedAt" = NOW() WHERE id = $2',
|
if not existing:
|
||||||
body.estado,
|
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,
|
cotizacion_id,
|
||||||
)
|
)
|
||||||
if result == "UPDATE 0":
|
elif nuevo == "enviada":
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
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)
|
return OkResponse(ok=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -547,7 +816,10 @@ async def cambiar_estado(
|
|||||||
# 8. POST /cotizaciones/{id}/duplicate
|
# 8. POST /cotizaciones/{id}/duplicate
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@router.post("/{cotizacion_id}/duplicate", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
@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()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
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,
|
cotizacion_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None
|
||||||
|
|
||||||
async with conn.transaction():
|
async with conn.transaction():
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
new_id = _cuid()
|
new_id = _cuid()
|
||||||
@@ -572,9 +846,10 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
|||||||
"""
|
"""
|
||||||
INSERT INTO "Cotizacion"
|
INSERT INTO "Cotizacion"
|
||||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
"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_id,
|
||||||
new_numero,
|
new_numero,
|
||||||
@@ -586,11 +861,13 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
|||||||
original["esquemaPago"],
|
original["esquemaPago"],
|
||||||
original["incluirBonos"],
|
original["incluirBonos"],
|
||||||
original["incluirFinanciamiento"],
|
original["incluirFinanciamiento"],
|
||||||
|
original["incluirIva"],
|
||||||
original["esDoble"],
|
original["esDoble"],
|
||||||
original["opcionesMetadata"],
|
original["opcionesMetadata"],
|
||||||
original["observaciones"],
|
original["observaciones"],
|
||||||
original["clienteId"],
|
original["clienteId"],
|
||||||
original["asesorId"],
|
original["asesorId"],
|
||||||
|
creada_por_agente,
|
||||||
now,
|
now,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -640,5 +917,14 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
|||||||
now,
|
now,
|
||||||
)
|
)
|
||||||
|
|
||||||
full = await _fetch_cotizacion_full(pool, new_id)
|
await registrar_auditoria(
|
||||||
return full
|
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.dependencies import get_db
|
||||||
from app.models.export_ import ExportDraft
|
from app.models.export_ import ExportDraft
|
||||||
from app.models.common import ErrorResponse
|
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.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename
|
||||||
from app.services.pdf_generator import generate_cotizacion_pdf
|
from app.services.pdf_generator import generate_cotizacion_pdf
|
||||||
from app.services.excel_generator import generate_cotizacion_excel
|
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,
|
"planBucefaloNivel": draft.planBucefaloNivel,
|
||||||
"planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0,
|
"planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0,
|
||||||
"incluirBonos": draft.incluirBonos,
|
"incluirBonos": draft.incluirBonos,
|
||||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||||
"logoBase64": logo_b64,
|
"logoBase64": logo_b64,
|
||||||
"logoMime": logo_mime,
|
"logoMime": logo_mime,
|
||||||
"configBancaria": branding,
|
"configBancaria": branding,
|
||||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -188,13 +187,12 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
|||||||
"planBucefaloNivel": plan_nivel,
|
"planBucefaloNivel": plan_nivel,
|
||||||
"planBucefaloPrecio": float(plan["precio"]) if plan else 0,
|
"planBucefaloPrecio": float(plan["precio"]) if plan else 0,
|
||||||
"incluirBonos": cot["incluirBonos"],
|
"incluirBonos": cot["incluirBonos"],
|
||||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||||
"logoBase64": logo_b64,
|
"logoBase64": logo_b64,
|
||||||
"logoMime": logo_mime,
|
"logoMime": logo_mime,
|
||||||
"configBancaria": branding,
|
"configBancaria": branding,
|
||||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -203,7 +201,7 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
|||||||
@router.post("/pdf")
|
@router.post("/pdf")
|
||||||
async def export_pdf_draft(
|
async def export_pdf_draft(
|
||||||
body: ExportDraft,
|
body: ExportDraft,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
branding = await _load_branding(db)
|
branding = await _load_branding(db)
|
||||||
@@ -223,9 +221,13 @@ async def export_pdf_draft(
|
|||||||
@router.get("/pdf/{cotizacion_id}")
|
@router.get("/pdf/{cotizacion_id}")
|
||||||
async def export_pdf_saved(
|
async def export_pdf_saved(
|
||||||
cotizacion_id: str,
|
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),
|
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)
|
pdf_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||||
if not pdf_data:
|
if not pdf_data:
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||||
@@ -247,7 +249,7 @@ async def export_pdf_saved(
|
|||||||
@router.post("/excel")
|
@router.post("/excel")
|
||||||
async def export_excel_draft(
|
async def export_excel_draft(
|
||||||
body: ExportDraft,
|
body: ExportDraft,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
branding = await _load_branding(db)
|
branding = await _load_branding(db)
|
||||||
@@ -267,9 +269,13 @@ async def export_excel_draft(
|
|||||||
@router.get("/excel/{cotizacion_id}")
|
@router.get("/excel/{cotizacion_id}")
|
||||||
async def export_excel_saved(
|
async def export_excel_saved(
|
||||||
cotizacion_id: str,
|
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),
|
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)
|
excel_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||||
if not excel_data:
|
if not excel_data:
|
||||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
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)
|
@router.get("/catalogo", response_class=PlainTextResponse)
|
||||||
async def export_catalogo_csv(
|
async def export_catalogo_csv(
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
rows = await db.fetch(
|
rows = await db.fetch(
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from app.models.export_ import (
|
|||||||
PlanBucefaloResponse,
|
PlanBucefaloResponse,
|
||||||
)
|
)
|
||||||
from app.models.common import ErrorResponse
|
from app.models.common import ErrorResponse
|
||||||
from app.auth import require_auth
|
from app.auth import require_scope
|
||||||
from app.services.calculators import (
|
from app.services.calculators import (
|
||||||
calcular_financiamiento,
|
calcular_financiamiento,
|
||||||
FINANCIAMIENTO_PLANES,
|
FINANCIAMIENTO_PLANES,
|
||||||
@@ -28,7 +28,7 @@ class PlanResponse(FinanciamientoResponse):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/planes", response_model=list[PlanResponse])
|
@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 [
|
return [
|
||||||
PlanResponse(
|
PlanResponse(
|
||||||
meses=p["meses"],
|
meses=p["meses"],
|
||||||
@@ -47,7 +47,7 @@ async def get_planes(_auth: dict = Depends(require_auth)):
|
|||||||
)
|
)
|
||||||
async def calcular(
|
async def calcular(
|
||||||
body: FinanciamientoRequest,
|
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)
|
plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None)
|
||||||
if not plan:
|
if not plan:
|
||||||
@@ -77,7 +77,7 @@ async def calcular(
|
|||||||
)
|
)
|
||||||
async def simulacion(
|
async def simulacion(
|
||||||
cotizacion_id: str,
|
cotizacion_id: str,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
cot = await db.fetchrow(
|
cot = await db.fetchrow(
|
||||||
|
|||||||
@@ -28,9 +28,9 @@ async def health_check():
|
|||||||
@router.get("/api-info", response_model=APIInfoResponse)
|
@router.get("/api-info", response_model=APIInfoResponse)
|
||||||
async def api_info():
|
async def api_info():
|
||||||
return APIInfoResponse(
|
return APIInfoResponse(
|
||||||
name="Cotizador E3 API",
|
name="Cotizador — Uriel Jareth Consulting API",
|
||||||
version="1.0.0",
|
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=[
|
capabilities=[
|
||||||
"Gestión de cotizaciones",
|
"Gestión de cotizaciones",
|
||||||
"Catálogo de servicios",
|
"Catálogo de servicios",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, File, UploadFile
|
|||||||
from asyncpg import Connection
|
from asyncpg import Connection
|
||||||
|
|
||||||
from app.dependencies import get_db
|
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"])
|
router = APIRouter(prefix="/import", tags=["Import"])
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"}
|
|||||||
@router.post("/catalogo")
|
@router.post("/catalogo")
|
||||||
async def import_catalogo_csv(
|
async def import_catalogo_csv(
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
db: Connection = Depends(get_db),
|
db: Connection = Depends(get_db),
|
||||||
):
|
):
|
||||||
content = await file.read()
|
content = await file.read()
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
|||||||
|
|
||||||
from app.database import get_pool
|
from app.database import get_pool
|
||||||
from app.dependencies import get_db
|
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 (
|
from app.models.paquete import (
|
||||||
PaqueteCreate,
|
PaqueteCreate,
|
||||||
PaqueteUpdate,
|
PaqueteUpdate,
|
||||||
@@ -128,7 +128,7 @@ async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
|||||||
|
|
||||||
@router.get("", response_model=list[PaqueteResponse])
|
@router.get("", response_model=list[PaqueteResponse])
|
||||||
async def list_paquetes(
|
async def list_paquetes(
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
rows = await conn.fetch(
|
rows = await conn.fetch(
|
||||||
@@ -145,7 +145,7 @@ async def list_paquetes(
|
|||||||
)
|
)
|
||||||
async def create_paquete(
|
async def create_paquete(
|
||||||
body: PaqueteCreate,
|
body: PaqueteCreate,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
@@ -179,7 +179,7 @@ async def create_paquete(
|
|||||||
)
|
)
|
||||||
async def get_paquete(
|
async def get_paquete(
|
||||||
paquete_id: str,
|
paquete_id: str,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
row = await conn.fetchrow(
|
row = await conn.fetchrow(
|
||||||
@@ -203,7 +203,7 @@ async def get_paquete(
|
|||||||
async def update_paquete(
|
async def update_paquete(
|
||||||
paquete_id: str,
|
paquete_id: str,
|
||||||
body: PaqueteUpdate,
|
body: PaqueteUpdate,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
existing = await conn.fetchrow(
|
existing = await conn.fetchrow(
|
||||||
@@ -260,7 +260,7 @@ async def update_paquete(
|
|||||||
)
|
)
|
||||||
async def delete_paquete(
|
async def delete_paquete(
|
||||||
paquete_id: str,
|
paquete_id: str,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
result = await conn.execute(
|
result = await conn.execute(
|
||||||
@@ -281,7 +281,7 @@ async def delete_paquete(
|
|||||||
async def manage_paquete(
|
async def manage_paquete(
|
||||||
paquete_id: str,
|
paquete_id: str,
|
||||||
body: ManageAction,
|
body: ManageAction,
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_staff_human),
|
||||||
conn=Depends(get_db),
|
conn=Depends(get_db),
|
||||||
):
|
):
|
||||||
paquete = await conn.fetchrow(
|
paquete = await conn.fetchrow(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, datetime
|
import re
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
|
||||||
|
|
||||||
IVA_RATE = 0.16
|
IVA_RATE = 0.16
|
||||||
@@ -8,11 +9,12 @@ IVA_RATE = 0.16
|
|||||||
# Tarifa por hora sugerida para partidas personalizadas (Hora Centinela).
|
# Tarifa por hora sugerida para partidas personalizadas (Hora Centinela).
|
||||||
TARIFA_HORA_DEFAULT = 700
|
TARIFA_HORA_DEFAULT = 700
|
||||||
|
|
||||||
# Modelos de cobro de una partida (espejo del frontend TS).
|
# Modelos de cobro de una partida (espejo exacto de src/lib/calculators.ts).
|
||||||
MODELOS_COBRO: dict[str, str] = {
|
MODELOS_COBRO: dict[str, str] = {
|
||||||
"fijo": "Precio fijo",
|
"fijo": "Precio fijo",
|
||||||
"horas": "Por horas",
|
"horas": "Por horas",
|
||||||
"retainer": "Retainer (minimo + adicionales)",
|
"retainer": "Retainer (minimo + adicionales)",
|
||||||
|
"demanda": "Bajo demanda / por hora",
|
||||||
}
|
}
|
||||||
|
|
||||||
# Doble propuesta: cada partida va en la Opcion 1, la 2 o en ambas (espejo del TS).
|
# Doble propuesta: cada partida va en la Opcion 1, la 2 o en ambas (espejo del TS).
|
||||||
@@ -39,7 +41,7 @@ PLANES_BUCEFALO = [
|
|||||||
{"nivel": "empresarial", "label": "Empresarial", "precio": 7500},
|
{"nivel": "empresarial", "label": "Empresarial", "precio": 7500},
|
||||||
]
|
]
|
||||||
|
|
||||||
ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"]
|
ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"]
|
||||||
|
|
||||||
FINANCIAMIENTO_PLANES = [
|
FINANCIAMIENTO_PLANES = [
|
||||||
{"meses": 3, "tasa": 0.077, "comision": 2.5, "montoMinimo": 300},
|
{"meses": 3, "tasa": 0.077, "comision": 2.5, "montoMinimo": 300},
|
||||||
@@ -58,8 +60,12 @@ BONOS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _r2(n: float) -> float:
|
||||||
|
return round(n + 1e-12, 2) if n >= 0 else -round(-n + 1e-12, 2)
|
||||||
|
|
||||||
|
|
||||||
def calcular_precio_horas(horas: float, tarifa_hora: float) -> float:
|
def calcular_precio_horas(horas: float, tarifa_hora: float) -> float:
|
||||||
return round((horas or 0) * (tarifa_hora or 0), 2)
|
return _r2((horas or 0) * (tarifa_hora or 0))
|
||||||
|
|
||||||
|
|
||||||
def describir_retainer(monto_minimo: float, horas_incluidas: float, tarifa_hora: float) -> str:
|
def describir_retainer(monto_minimo: float, horas_incluidas: float, tarifa_hora: float) -> str:
|
||||||
@@ -81,6 +87,8 @@ def detalle_modelo(serv: dict) -> str:
|
|||||||
serv.get("horasIncluidas") or 0,
|
serv.get("horasIncluidas") or 0,
|
||||||
serv.get("tarifaHora") or 0,
|
serv.get("tarifaHora") or 0,
|
||||||
)
|
)
|
||||||
|
if modelo == "demanda":
|
||||||
|
return f"{format_currency(serv.get('tarifaHora') or 0)}/hr · segun consumo"
|
||||||
horas = serv.get("horas")
|
horas = serv.get("horas")
|
||||||
tarifa = serv.get("tarifaHora")
|
tarifa = serv.get("tarifaHora")
|
||||||
if (modelo == "horas" or serv.get("esPersonalizado")) and horas and tarifa:
|
if (modelo == "horas" or serv.get("esPersonalizado")) and horas and tarifa:
|
||||||
@@ -91,20 +99,51 @@ def detalle_modelo(serv: dict) -> str:
|
|||||||
def calcular_totales_opcion(servicios: list[dict], opcion: str) -> dict:
|
def calcular_totales_opcion(servicios: list[dict], opcion: str) -> dict:
|
||||||
"""Totales de una opcion: suma sus partidas + las marcadas 'ambas'.
|
"""Totales de una opcion: suma sus partidas + las marcadas 'ambas'.
|
||||||
|
|
||||||
Espejo de calcularTotalesOpcion en TS. Respeta la regla de retainer: el total
|
Espejo exacto de calcularTotalesOpcion en TS. Respeta la regla de retainer:
|
||||||
usa `precio`, no `horas x tarifa`. Las horas son informativas.
|
el total usa precio, no horas x tarifa. Las horas son informativas.
|
||||||
"""
|
"""
|
||||||
rel = [s for s in servicios if s.get("opcion") == "ambas" or s.get("opcion") == opcion]
|
rel = [s for s in servicios if s.get("opcion") == "ambas" or s.get("opcion") == opcion]
|
||||||
total_unico = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "unico")
|
total_unico = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "unico")
|
||||||
total_mensual = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "mensual")
|
total_mensual = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "mensual")
|
||||||
horas = sum((s.get("horas") or 0) for s in rel)
|
horas = sum((s.get("horas") or 0) for s in rel)
|
||||||
return {
|
return {
|
||||||
"totalUnico": round(total_unico, 2),
|
"totalUnico": _r2(total_unico),
|
||||||
"totalMensual": round(total_mensual, 2),
|
"totalMensual": _r2(total_mensual),
|
||||||
"horas": round(horas, 2),
|
"horas": _r2(horas),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def calcular_totales_cotizacion(
|
||||||
|
servicios: list[dict],
|
||||||
|
incluir_iva: bool = True,
|
||||||
|
) -> dict:
|
||||||
|
"""Espejo exacto de calcularTotalesCotizacion en src/lib/calculators.ts."""
|
||||||
|
activos = [s for s in servicios if s.get("seleccionado", True) is not False]
|
||||||
|
subtotal_unico = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "unico"))
|
||||||
|
subtotal_mensual = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "mensual"))
|
||||||
|
|
||||||
|
iva_unico = _r2(subtotal_unico * IVA_RATE) if incluir_iva else 0.0
|
||||||
|
iva_mensual = _r2(subtotal_mensual * IVA_RATE) if incluir_iva else 0.0
|
||||||
|
|
||||||
|
total_unico = _r2(subtotal_unico + iva_unico)
|
||||||
|
total_mensual = _r2(subtotal_mensual + iva_mensual)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"subtotalUnico": subtotal_unico,
|
||||||
|
"subtotalMensual": subtotal_mensual,
|
||||||
|
"ivaUnico": iva_unico,
|
||||||
|
"ivaMensual": iva_mensual,
|
||||||
|
"totalUnico": total_unico,
|
||||||
|
"totalMensual": total_mensual,
|
||||||
|
"totalPrimerAnio": _r2(total_unico + total_mensual * 12),
|
||||||
|
"incluyeIva": incluir_iva,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def con_iva(monto: float, incluir_iva: bool = True) -> float:
|
||||||
|
return _r2((monto or 0) * (1 + IVA_RATE if incluir_iva else 1))
|
||||||
|
|
||||||
|
|
||||||
def bucefalo_precio(nivel: str) -> float:
|
def bucefalo_precio(nivel: str) -> float:
|
||||||
for p in PLANES_BUCEFALO:
|
for p in PLANES_BUCEFALO:
|
||||||
if p["nivel"] == nivel:
|
if p["nivel"] == nivel:
|
||||||
@@ -113,32 +152,37 @@ def bucefalo_precio(nivel: str) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def calcular_vigencia(fecha: datetime | date) -> datetime:
|
def calcular_vigencia(fecha: datetime | date) -> datetime:
|
||||||
|
"""Suma exactamente 15 dias habiles (lunes a viernes), espejo de calculators.ts."""
|
||||||
if isinstance(fecha, datetime):
|
if isinstance(fecha, datetime):
|
||||||
vigencia = fecha.replace()
|
vigencia = fecha.replace()
|
||||||
else:
|
else:
|
||||||
vigencia = datetime.combine(fecha, datetime.min.time())
|
vigencia = datetime.combine(fecha, datetime.min.time())
|
||||||
dias_habiles = 0
|
dias_habiles = 0
|
||||||
while dias_habiles < 15:
|
while dias_habiles < 15:
|
||||||
vigencia = vigencia.replace(day=vigencia.day + 1) if vigencia.day < 28 else vigencia + __import__("datetime").timedelta(days=1)
|
vigencia = vigencia + timedelta(days=1)
|
||||||
vigencia = vigencia + __import__("datetime").timedelta(days=1)
|
if vigencia.weekday() < 5:
|
||||||
dia = vigencia.weekday()
|
|
||||||
if dia < 5:
|
|
||||||
dias_habiles += 1
|
dias_habiles += 1
|
||||||
return vigencia
|
return vigencia
|
||||||
|
|
||||||
|
|
||||||
def calcular_financiamiento(monto: float, meses: int, tasa: float, comision: float, iva: float = IVA_RATE) -> dict:
|
def calcular_financiamiento(
|
||||||
|
monto: float,
|
||||||
|
meses: int,
|
||||||
|
tasa: float,
|
||||||
|
comision: float,
|
||||||
|
iva: float = IVA_RATE,
|
||||||
|
) -> dict:
|
||||||
comision_total = (monto * comision) / 100
|
comision_total = (monto * comision) / 100
|
||||||
monto_con_comision = monto + comision_total
|
monto_con_comision = monto + comision_total
|
||||||
pago_mensual = monto_con_comision * (1 + tasa) / meses
|
pago_mensual = monto_con_comision * (1 + tasa) / meses
|
||||||
iva_mensual = pago_mensual * iva
|
iva_mensual = pago_mensual * iva
|
||||||
total_mensual = pago_mensual + iva_mensual
|
total_mensual = pago_mensual + iva_mensual
|
||||||
return {
|
return {
|
||||||
"pagoMensual": round(pago_mensual, 2),
|
"pagoMensual": _r2(pago_mensual),
|
||||||
"ivaMensual": round(iva_mensual, 2),
|
"ivaMensual": _r2(iva_mensual),
|
||||||
"totalMensual": round(total_mensual, 2),
|
"totalMensual": _r2(total_mensual),
|
||||||
"comisionTotal": round(comision_total, 2),
|
"comisionTotal": _r2(comision_total),
|
||||||
"granTotal": round(total_mensual * meses, 2),
|
"granTotal": _r2(total_mensual * meses),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -151,7 +195,6 @@ def generar_numero_cotizacion(iniciales: str, secuencia: int) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def sanitize_filename(name: str) -> str:
|
def sanitize_filename(name: str) -> str:
|
||||||
import re
|
|
||||||
name = re.sub(r"[^\w\s.\-]", "", name)
|
name = re.sub(r"[^\w\s.\-]", "", name)
|
||||||
name = re.sub(r"\s+", " ", name)
|
name = re.sub(r"\s+", " ", name)
|
||||||
return name.strip()
|
return name.strip()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Excel Generator for Cotizador E3 — port of src/lib/excel-builder.ts using openpyxl.
|
"""Excel Generator for Cotizador — Uriel Jareth Consulting — port of src/lib/excel-builder.ts using openpyxl.
|
||||||
|
|
||||||
Mantiene paridad de layout con el builder de TypeScript: mismas columnas, merges,
|
Mantiene paridad de layout con el builder de TypeScript: mismas columnas, merges,
|
||||||
celdas dinámicas (wrapText + altura calculada) para que el texto nunca se salga.
|
celdas dinámicas (wrapText + altura calculada) para que el texto nunca se salga.
|
||||||
@@ -94,10 +94,10 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
|||||||
data: dict with quotation data (same as PDF generator)
|
data: dict with quotation data (same as PDF generator)
|
||||||
saved: if True, uses real quotation number instead of "BORRADOR"
|
saved: if True, uses real quotation number instead of "BORRADOR"
|
||||||
"""
|
"""
|
||||||
config_color = data.get("colorPrimario", "#2563eb")
|
config_color = data.get("colorPrimario") or "#0400C4"
|
||||||
PRIMARY = _argb(config_color)
|
PRIMARY = _argb(config_color)
|
||||||
PRIMARY_LIGHT = _argb(config_color, alpha="18")
|
PRIMARY_LIGHT = _argb(config_color, alpha="18")
|
||||||
SECONDARY = _argb(data.get("colorSecundario", "#1e293b"))
|
SECONDARY = _argb(data.get("colorSecundario") or "#0F172A")
|
||||||
WHITE = "FFFFFFFF"
|
WHITE = "FFFFFFFF"
|
||||||
LIGHT_BG = "FFF8FAFC"
|
LIGHT_BG = "FFF8FAFC"
|
||||||
MUTED = "FF64748B"
|
MUTED = "FF64748B"
|
||||||
@@ -118,8 +118,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
|||||||
light_fill = PatternFill(start_color=LIGHT_BG, end_color=LIGHT_BG, fill_type="solid")
|
light_fill = PatternFill(start_color=LIGHT_BG, end_color=LIGHT_BG, fill_type="solid")
|
||||||
white_fill = PatternFill(start_color=WHITE, end_color=WHITE, fill_type="solid")
|
white_fill = PatternFill(start_color=WHITE, end_color=WHITE, fill_type="solid")
|
||||||
|
|
||||||
razon_social = data.get("razonSocial", "Cotizador E3")
|
razon_social = data.get("razonSocial") or "Uriel Jareth Consulting"
|
||||||
domicilio_fiscal = data.get("domicilioFiscal")
|
|
||||||
cliente_nombre = data.get("clienteNombre", "")
|
cliente_nombre = data.get("clienteNombre", "")
|
||||||
cliente_empresa = data.get("clienteEmpresa", "")
|
cliente_empresa = data.get("clienteEmpresa", "")
|
||||||
asesor_nombre = data.get("asesorNombre", "")
|
asesor_nombre = data.get("asesorNombre", "")
|
||||||
@@ -135,7 +134,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
|||||||
numero_label = data.get("numero", "BORRADOR") if saved else "BORRADOR"
|
numero_label = data.get("numero", "BORRADOR") if saved else "BORRADOR"
|
||||||
|
|
||||||
wb = Workbook()
|
wb = Workbook()
|
||||||
wb.properties.creator = "Cotizador E3"
|
wb.properties.creator = "Cotizador — Uriel Jareth Consulting"
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# HOJA RESUMEN
|
# HOJA RESUMEN
|
||||||
@@ -525,12 +524,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
|||||||
dw.merge_cells(f"B{r}:J{r}")
|
dw.merge_cells(f"B{r}:J{r}")
|
||||||
dw[f"B{r}"].value = razon_social
|
dw[f"B{r}"].value = razon_social
|
||||||
dw[f"B{r}"].font = Font(bold=True, size=10, name="Calibri", color=PRIMARY)
|
dw[f"B{r}"].font = Font(bold=True, size=10, name="Calibri", color=PRIMARY)
|
||||||
if domicilio_fiscal:
|
# Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados.
|
||||||
r += 1
|
|
||||||
dw.merge_cells(f"B{r}:J{r}")
|
|
||||||
dw[f"B{r}"].value = domicilio_fiscal
|
|
||||||
dw[f"B{r}"].font = iva_font
|
|
||||||
_set_wrapped(dw, r, "B", domicilio_fiscal, ent_width, font_size=9)
|
|
||||||
|
|
||||||
output = io.BytesIO()
|
output = io.BytesIO()
|
||||||
wb.save(output)
|
wb.save(output)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""PDF Generator for Cotizador E3 — port of pdf-generator.ts using ReportLab."""
|
"""PDF Generator for Cotizador — Uriel Jareth Consulting — port of pdf-generator.ts using ReportLab."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -15,8 +15,8 @@ from reportlab.lib.utils import ImageReader
|
|||||||
|
|
||||||
from app.services.calculators import FASES_SHORT, PLANES_BUCEFALO, bucefalo_precio, detalle_modelo, calcular_totales_opcion
|
from app.services.calculators import FASES_SHORT, PLANES_BUCEFALO, bucefalo_precio, detalle_modelo, calcular_totales_opcion
|
||||||
|
|
||||||
PRIMARY_DEFAULT = "#2563eb"
|
PRIMARY_DEFAULT = "#0400C4"
|
||||||
DARK_DEFAULT = "#1e293b"
|
DARK_DEFAULT = "#0F172A"
|
||||||
MUTED = "#64748b"
|
MUTED = "#64748b"
|
||||||
BORDER = "#cbd5e1"
|
BORDER = "#cbd5e1"
|
||||||
LIGHT_BG = "#f1f5f9"
|
LIGHT_BG = "#f1f5f9"
|
||||||
|
|||||||
+8
-7
@@ -1,4 +1,4 @@
|
|||||||
"""Cotizador E3 — FastAPI Application
|
"""Cotizador — Uriel Jareth Consulting (FastAPI Application)
|
||||||
|
|
||||||
REST API for digital marketing quotation management.
|
REST API for digital marketing quotation management.
|
||||||
Optimized for n8n workflows and other integrations.
|
Optimized for n8n workflows and other integrations.
|
||||||
@@ -25,13 +25,13 @@ async def lifespan(app: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Cotizador E3 API",
|
title="Cotizador — Uriel Jareth Consulting API",
|
||||||
description=(
|
description=(
|
||||||
"API REST para el sistema de cotizaciones de marketing digital de Consultoría E3. "
|
"API REST para el sistema de cotizaciones de Uriel Jareth Consulting. "
|
||||||
"Optimizada para integración con n8n y otros consumidores. "
|
"Optimizada para integración con n8n y otros consumidores. "
|
||||||
"Autenticación por X-API-Key o Bearer JWT."
|
"Autenticación por X-API-Key o Bearer JWT."
|
||||||
),
|
),
|
||||||
version="1.0.0",
|
version="2.0.0",
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
docs_url="/docs",
|
docs_url="/docs",
|
||||||
redoc_url="/redoc",
|
redoc_url="/redoc",
|
||||||
@@ -42,7 +42,8 @@ app = FastAPI(
|
|||||||
{"name": "Clientes", "description": "Gestión de clientes"},
|
{"name": "Clientes", "description": "Gestión de clientes"},
|
||||||
{"name": "Catálogo", "description": "Catálogo de servicios de marketing digital"},
|
{"name": "Catálogo", "description": "Catálogo de servicios de marketing digital"},
|
||||||
{"name": "Categorías", "description": "Categorías de servicios"},
|
{"name": "Categorías", "description": "Categorías de servicios"},
|
||||||
{"name": "Cotizaciones", "description": "Cotizaciones — CRUD completo con servicios y plan CRM"},
|
{"name": "Cotizaciones", "description": "Cotizaciones — CRUD con paridad de aprobación humana"},
|
||||||
|
{"name": "Cobros", "description": "Consulta de programas y pagos recurrentes (scope cobros:leer)"},
|
||||||
{"name": "Paquetes", "description": "Paquetes de servicios con fases"},
|
{"name": "Paquetes", "description": "Paquetes de servicios con fases"},
|
||||||
{"name": "Configuración", "description": "Configuración de la empresa (key-value)"},
|
{"name": "Configuración", "description": "Configuración de la empresa (key-value)"},
|
||||||
{"name": "Bonos", "description": "Bonos disponibles para cotizaciones"},
|
{"name": "Bonos", "description": "Bonos disponibles para cotizaciones"},
|
||||||
@@ -108,8 +109,8 @@ app.include_router(import_.router)
|
|||||||
@app.get("/", include_in_schema=False)
|
@app.get("/", include_in_schema=False)
|
||||||
async def root():
|
async def root():
|
||||||
return {
|
return {
|
||||||
"name": "Cotizador E3 API",
|
"name": "Cotizador — Uriel Jareth Consulting API",
|
||||||
"version": "1.0.0",
|
"version": "2.0.0",
|
||||||
"docs": "/docs",
|
"docs": "/docs",
|
||||||
"openapi": "/openapi.json",
|
"openapi": "/openapi.json",
|
||||||
"health": "/health",
|
"health": "/health",
|
||||||
|
|||||||
+16
-7
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// cotizador — CLI del Cotizador E3, pensado para humanos y para LLMs.
|
// cotizador — CLI del Cotizador — Uriel Jareth Consulting, pensado para humanos y para LLMs.
|
||||||
//
|
//
|
||||||
// - Habla con la API REST de Next.js (la misma que usa la web), con la sesion
|
// - Habla con la API REST de Next.js (la misma que usa la web), con la sesion
|
||||||
// de un usuario staff (login con correo y contrasena).
|
// de un usuario staff (login con correo y contrasena).
|
||||||
@@ -227,13 +227,22 @@ async function leerDatos(valor) {
|
|||||||
// Sesion y HTTP
|
// Sesion y HTTP
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const DIR_CONFIG = process.env.COTIZADOR_HOME || join(homedir(), ".cotizador-e3");
|
const DIR_CONFIG = process.env.COTIZADOR_HOME || join(homedir(), ".cotizador-uj");
|
||||||
const ARCHIVO_SESIONES = join(DIR_CONFIG, "sesiones.json");
|
const ARCHIVO_SESIONES = join(DIR_CONFIG, "sesiones.json");
|
||||||
|
// Fallback de solo lectura para sesiones previas antes del renombre.
|
||||||
|
const ARCHIVO_SESIONES_LEGACY = join(homedir(), ".cotizador-e3", "sesiones.json");
|
||||||
|
|
||||||
async function leerSesiones() {
|
async function leerSesiones() {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(await readFile(ARCHIVO_SESIONES, "utf8"));
|
return JSON.parse(await readFile(ARCHIVO_SESIONES, "utf8"));
|
||||||
} catch {
|
} catch {
|
||||||
|
if (!process.env.COTIZADOR_HOME) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(await readFile(ARCHIVO_SESIONES_LEGACY, "utf8"));
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -646,14 +655,14 @@ const COMANDOS = [
|
|||||||
// ----- sesion -----
|
// ----- sesion -----
|
||||||
{
|
{
|
||||||
comando: "login",
|
comando: "login",
|
||||||
descripcion: "Inicia sesion con una cuenta staff y guarda el token en ~/.cotizador-e3/sesiones.json (7 dias).",
|
descripcion: "Inicia sesion con una cuenta staff y guarda el token en ~/.cotizador-uj/sesiones.json (7 dias).",
|
||||||
flags: [
|
flags: [
|
||||||
{ flag: "email", tipo: "texto", descripcion: "Correo (o $COTIZADOR_EMAIL)" },
|
{ flag: "email", tipo: "texto", descripcion: "Correo (o $COTIZADOR_EMAIL)" },
|
||||||
{ flag: "password", tipo: "texto", descripcion: "Contrasena (o $COTIZADOR_PASSWORD)" },
|
{ flag: "password", tipo: "texto", descripcion: "Contrasena (o $COTIZADOR_PASSWORD)" },
|
||||||
{ flag: "password-stdin", tipo: "booleano", descripcion: "Lee la contrasena de stdin (no queda en el historial)" },
|
{ flag: "password-stdin", tipo: "booleano", descripcion: "Lee la contrasena de stdin (no queda en el historial)" },
|
||||||
],
|
],
|
||||||
ejemplos: [
|
ejemplos: [
|
||||||
"cotizador login --email asesor@consultoriae3.com --password-stdin < pass.txt",
|
"cotizador login --email admin@urieljareth.com --password-stdin < pass.txt",
|
||||||
"COTIZADOR_EMAIL=... COTIZADOR_PASSWORD=... cotizador login",
|
"COTIZADOR_EMAIL=... COTIZADOR_PASSWORD=... cotizador login",
|
||||||
],
|
],
|
||||||
endpoint: "POST /api/auth/login",
|
endpoint: "POST /api/auth/login",
|
||||||
@@ -1256,7 +1265,7 @@ function esquema() {
|
|||||||
nombre: "cotizador",
|
nombre: "cotizador",
|
||||||
version: VERSION,
|
version: VERSION,
|
||||||
descripcion:
|
descripcion:
|
||||||
"CLI del Cotizador E3 (Consultoria E3). Gestiona el catalogo de servicios, clientes, cotizaciones y horas a traves de la API REST de la plataforma.",
|
"CLI del Cotizador — Uriel Jareth Consulting. Gestiona el catalogo de servicios, clientes, cotizaciones y horas a traves de la API REST de la plataforma.",
|
||||||
convenciones: {
|
convenciones: {
|
||||||
salida: "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)",
|
salida: "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)",
|
||||||
errores: "JSON en stderr: { ok:false, error, codigo, status?, detalles?, sugerencia? }",
|
errores: "JSON en stderr: { ok:false, error, codigo, status?, detalles?, sugerencia? }",
|
||||||
@@ -1270,7 +1279,7 @@ function esquema() {
|
|||||||
COTIZADOR_EMAIL: "Correo para login automatico cuando no hay sesion o vencio",
|
COTIZADOR_EMAIL: "Correo para login automatico cuando no hay sesion o vencio",
|
||||||
COTIZADOR_PASSWORD: "Contrasena para login automatico",
|
COTIZADOR_PASSWORD: "Contrasena para login automatico",
|
||||||
COTIZADOR_TOKEN: "Token de sesion explicito (omite el archivo de sesiones)",
|
COTIZADOR_TOKEN: "Token de sesion explicito (omite el archivo de sesiones)",
|
||||||
COTIZADOR_HOME: "Carpeta de la sesion guardada (default ~/.cotizador-e3)",
|
COTIZADOR_HOME: "Carpeta de la sesion guardada (default ~/.cotizador-uj)",
|
||||||
},
|
},
|
||||||
codigosSalida: DESCRIPCION_CODIGOS,
|
codigosSalida: DESCRIPCION_CODIGOS,
|
||||||
dominio: DOMINIO,
|
dominio: DOMINIO,
|
||||||
@@ -1343,7 +1352,7 @@ function ayudaGeneral() {
|
|||||||
grupos.get(g).push(c);
|
grupos.get(g).push(c);
|
||||||
}
|
}
|
||||||
const ancho = Math.max(...COMANDOS.map((c) => c.comando.length)) + 2;
|
const ancho = Math.max(...COMANDOS.map((c) => c.comando.length)) + 2;
|
||||||
let txt = `cotizador ${VERSION} — CLI del Cotizador E3\n\nUso: cotizador <comando> [argumentos] [flags]\n`;
|
let txt = `cotizador ${VERSION} — CLI del Cotizador — Uriel Jareth Consulting\n\nUso: cotizador <comando> [argumentos] [flags]\n`;
|
||||||
for (const [g, cmds] of grupos) {
|
for (const [g, cmds] of grupos) {
|
||||||
txt += `\n${g.toUpperCase()}\n`;
|
txt += `\n${g.toUpperCase()}\n`;
|
||||||
for (const c of cmds) txt += ` ${c.comando.padEnd(ancho)}${c.descripcion.split(/\.\s+(?=[A-Z(])/)[0]}\n`;
|
for (const c of cmds) txt += ` ${c.comando.padEnd(ancho)}${c.descripcion.split(/\.\s+(?=[A-Z(])/)[0]}\n`;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Cotizador E3 — stack de producción para Coolify
|
# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify
|
||||||
#
|
#
|
||||||
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
||||||
# "Docker Compose Location" = /docker-compose.coolify.yml
|
# "Docker Compose Location" = /docker-compose.coolify.yml
|
||||||
@@ -16,6 +16,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${DB_USER:-postgres}
|
POSTGRES_USER: ${DB_USER:-postgres}
|
||||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
||||||
|
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
@@ -49,7 +50,7 @@ services:
|
|||||||
- MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3}
|
- MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3}
|
||||||
# Seed inicial: pon RUN_SEED=true solo en el primer despliegue
|
# Seed inicial: pon RUN_SEED=true solo en el primer despliegue
|
||||||
- RUN_SEED=${RUN_SEED:-false}
|
- RUN_SEED=${RUN_SEED:-false}
|
||||||
- SEED_ADMIN_EMAIL=${SEED_ADMIN_EMAIL:-admin@e3.local}
|
- SEED_ADMIN_EMAIL=${SEED_ADMIN_EMAIL:-admin@urieljareth.com}
|
||||||
- SEED_ADMIN_PASSWORD=${SEED_ADMIN_PASSWORD}
|
- SEED_ADMIN_PASSWORD=${SEED_ADMIN_PASSWORD}
|
||||||
- SEED_ADMIN_NAME=${SEED_ADMIN_NAME:-Administrador}
|
- SEED_ADMIN_NAME=${SEED_ADMIN_NAME:-Administrador}
|
||||||
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
|
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
|
||||||
@@ -68,11 +69,16 @@ services:
|
|||||||
- SMTP_USER=${SMTP_USER}
|
- SMTP_USER=${SMTP_USER}
|
||||||
- SMTP_PASS=${SMTP_PASS}
|
- SMTP_PASS=${SMTP_PASS}
|
||||||
- SMTP_FROM=${SMTP_FROM}
|
- SMTP_FROM=${SMTP_FROM}
|
||||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting}
|
||||||
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
||||||
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||||
- UPLOAD_DIR=/app/uploads
|
- UPLOAD_DIR=/app/uploads
|
||||||
|
# Notificaciones de aprobacion humana y webhooks HMAC-SHA256 hacia n8n
|
||||||
|
- ADMIN_NOTIFY_EMAIL=${ADMIN_NOTIFY_EMAIL}
|
||||||
|
- WEBHOOK_N8N_URL=${WEBHOOK_N8N_URL}
|
||||||
|
- WEBHOOK_N8N_SECRET=${WEBHOOK_N8N_SECRET}
|
||||||
|
- WEBHOOK_WHATSAPP_SEND_URL=${WEBHOOK_WHATSAPP_SEND_URL}
|
||||||
volumes:
|
volumes:
|
||||||
- uploads_data:/app/uploads
|
- uploads_data:/app/uploads
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -99,6 +105,8 @@ services:
|
|||||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||||
- API_KEY=${API_KEY}
|
- API_KEY=${API_KEY}
|
||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
|
# La vieja API_KEY sin alcances queda desactivada por defecto; usar AgentApiKey
|
||||||
|
- ALLOW_LEGACY_API_KEY=${ALLOW_LEGACY_API_KEY:-false}
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
+11
-3
@@ -1,4 +1,4 @@
|
|||||||
# Cotizador E3 — stack de producción para Coolify
|
# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify
|
||||||
#
|
#
|
||||||
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
||||||
# "Docker Compose Location" = /docker-compose.coolify.yml
|
# "Docker Compose Location" = /docker-compose.coolify.yml
|
||||||
@@ -16,6 +16,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${DB_USER:-postgres}
|
POSTGRES_USER: ${DB_USER:-postgres}
|
||||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
||||||
|
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
@@ -49,7 +50,7 @@ services:
|
|||||||
- MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3}
|
- MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3}
|
||||||
# Seed inicial: pon RUN_SEED=true solo en el primer despliegue
|
# Seed inicial: pon RUN_SEED=true solo en el primer despliegue
|
||||||
- RUN_SEED=${RUN_SEED:-false}
|
- RUN_SEED=${RUN_SEED:-false}
|
||||||
- SEED_ADMIN_EMAIL=${SEED_ADMIN_EMAIL:-admin@e3.local}
|
- SEED_ADMIN_EMAIL=${SEED_ADMIN_EMAIL:-admin@urieljareth.com}
|
||||||
- SEED_ADMIN_PASSWORD=${SEED_ADMIN_PASSWORD}
|
- SEED_ADMIN_PASSWORD=${SEED_ADMIN_PASSWORD}
|
||||||
- SEED_ADMIN_NAME=${SEED_ADMIN_NAME:-Administrador}
|
- SEED_ADMIN_NAME=${SEED_ADMIN_NAME:-Administrador}
|
||||||
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
|
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
|
||||||
@@ -68,11 +69,16 @@ services:
|
|||||||
- SMTP_USER=${SMTP_USER}
|
- SMTP_USER=${SMTP_USER}
|
||||||
- SMTP_PASS=${SMTP_PASS}
|
- SMTP_PASS=${SMTP_PASS}
|
||||||
- SMTP_FROM=${SMTP_FROM}
|
- SMTP_FROM=${SMTP_FROM}
|
||||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting}
|
||||||
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
||||||
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||||
- UPLOAD_DIR=/app/uploads
|
- UPLOAD_DIR=/app/uploads
|
||||||
|
# Notificaciones de aprobacion humana y webhooks HMAC-SHA256 hacia n8n
|
||||||
|
- ADMIN_NOTIFY_EMAIL=${ADMIN_NOTIFY_EMAIL}
|
||||||
|
- WEBHOOK_N8N_URL=${WEBHOOK_N8N_URL}
|
||||||
|
- WEBHOOK_N8N_SECRET=${WEBHOOK_N8N_SECRET}
|
||||||
|
- WEBHOOK_WHATSAPP_SEND_URL=${WEBHOOK_WHATSAPP_SEND_URL}
|
||||||
volumes:
|
volumes:
|
||||||
- uploads_data:/app/uploads
|
- uploads_data:/app/uploads
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -99,6 +105,8 @@ services:
|
|||||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||||
- API_KEY=${API_KEY}
|
- API_KEY=${API_KEY}
|
||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
|
# La vieja API_KEY sin alcances queda desactivada por defecto; usar AgentApiKey
|
||||||
|
- ALLOW_LEGACY_API_KEY=${ALLOW_LEGACY_API_KEY:-false}
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
+3
-2
@@ -1,11 +1,12 @@
|
|||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
container_name: cotizador-e3-db
|
container_name: cotizador-uj-db
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: postgres
|
POSTGRES_USER: postgres
|
||||||
POSTGRES_PASSWORD: postgres
|
POSTGRES_PASSWORD: postgres
|
||||||
|
# Se conserva el nombre fisico de BD para no romper el volumen postgres_data.
|
||||||
POSTGRES_DB: cotizador_e3
|
POSTGRES_DB: cotizador_e3
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
@@ -14,7 +15,7 @@ services:
|
|||||||
|
|
||||||
api:
|
api:
|
||||||
build: ./api
|
build: ./api
|
||||||
container_name: cotizador-e3-api
|
container_name: cotizador-uj-api
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
|
|||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
# CLI `cotizador`
|
# CLI `cotizador`
|
||||||
|
|
||||||
Opera el Cotizador E3 desde la terminal: catálogo de servicios, categorías, paquetes, clientes, cotizaciones y horas. Está hecho para que lo use una persona o una LLM: la salida es JSON, los errores son JSON con código de salida, y `cotizador esquema` describe todos los comandos en JSON.
|
Opera el Cotizador — Uriel Jareth Consulting desde la terminal: catálogo de servicios, categorías, paquetes, clientes, cotizaciones y horas. Está hecho para que lo use una persona o una LLM: la salida es JSON, los errores son JSON con código de salida, y `cotizador esquema` describe todos los comandos en JSON.
|
||||||
|
|
||||||
- Código: `cli/cotizador.mjs` (Node 18+, sin dependencias).
|
- Código: `cli/cotizador.mjs` (Node 18+, sin dependencias).
|
||||||
- Habla con la API de Next.js (`src/app/api`), la misma que usa la web, con la sesión de un usuario **staff** (admin o asesor). Las cuentas de rol `cliente` no sirven.
|
- Habla con la API de Next.js (`src/app/api`), la misma que usa la web, con la sesión de un usuario **staff** (admin o asesor). Las cuentas de rol `cliente` no sirven.
|
||||||
@@ -20,12 +20,12 @@ npm link && cotizador <comando> # instala el comando "cotizador" globalm
|
|||||||
| `COTIZADOR_URL` | URL base. Default `http://localhost:3000`. Producción: `https://cotizador.urieljareth.org` |
|
| `COTIZADOR_URL` | URL base. Default `http://localhost:3000`. Producción: `https://cotizador.urieljareth.org` |
|
||||||
| `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD` | Login automático cuando no hay sesión o venció (útil para agentes) |
|
| `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD` | Login automático cuando no hay sesión o venció (útil para agentes) |
|
||||||
| `COTIZADOR_TOKEN` | Token de sesión explícito (omite el archivo de sesiones) |
|
| `COTIZADOR_TOKEN` | Token de sesión explícito (omite el archivo de sesiones) |
|
||||||
| `COTIZADOR_HOME` | Carpeta de la sesión guardada. Default `~/.cotizador-e3` |
|
| `COTIZADOR_HOME` | Carpeta de la sesión guardada. Default `~/.cotizador-uj` |
|
||||||
|
|
||||||
`cotizador login` guarda el token (dura 7 días) en `~/.cotizador-e3/sesiones.json`, una sesión por URL. La contraseña nunca se guarda.
|
`cotizador login` guarda el token (dura 7 días) en `~/.cotizador-uj/sesiones.json`, una sesión por URL. La contraseña nunca se guarda.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cotizador login --email asesor@consultoriae3.com --password-stdin < pass.txt
|
cotizador login --email admin@urieljareth.com --password-stdin < pass.txt
|
||||||
cotizador whoami
|
cotizador whoami
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Paquetes recomendados PyME — Guía de venta
|
# Paquetes recomendados PyME — Guía de venta
|
||||||
|
|
||||||
Esta guía describe los **6 paquetes recomendados** que vienen pre-armados en el cotizador. Cada uno agrupa servicios del catálogo por las 4 fases de E3 (Auditoría → Setup → Publicidad/Manejo → Contenido/SEO) y está pensado para un **tipo de cliente PyME** según su **etapa de madurez** y su **giro de negocio**.
|
Esta guía describe los **6 paquetes recomendados** que vienen pre-armados en el cotizador. Cada uno agrupa servicios del catálogo por las 4 fases de Uriel Jareth Consulting (Auditoría → Setup → Publicidad/Manejo → Contenido/SEO) y está pensado para un **tipo de cliente PyME** según su **etapa de madurez** y su **giro de negocio**.
|
||||||
|
|
||||||
> **Cómo usarlos:** en *Cotizaciones → Nueva*, usa el selector **"Iniciar desde Paquete"**, elige el paquete que mejor describe al cliente y pulsa **"Cargar servicios"**. Se precargan todos los servicios con su precio base; a partir de ahí ajustas, quitas o agregas lo que haga falta. Son un punto de partida, no una camisa de fuerza.
|
> **Cómo usarlos:** en *Cotizaciones → Nueva*, usa el selector **"Iniciar desde Paquete"**, elige el paquete que mejor describe al cliente y pulsa **"Cargar servicios"**. Se precargan todos los servicios con su precio base; a partir de ahí ajustas, quitas o agregas lo que haga falta. Son un punto de partida, no una camisa de fuerza.
|
||||||
|
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "cotizador-e3",
|
"name": "cotizador-uj",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "cotizador-e3",
|
"name": "cotizador-uj",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sdk": "^0.115.0",
|
"@anthropic-ai/sdk": "^0.115.0",
|
||||||
|
|||||||
+3
-2
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "cotizador-e3",
|
"name": "cotizador-uj",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -14,7 +14,8 @@
|
|||||||
"db:seed": "npx tsx prisma/seed.ts",
|
"db:seed": "npx tsx prisma/seed.ts",
|
||||||
"db:studio": "npx prisma studio",
|
"db:studio": "npx prisma studio",
|
||||||
"db:generate": "npx prisma generate",
|
"db:generate": "npx prisma generate",
|
||||||
"cli": "node cli/cotizador.mjs"
|
"cli": "node cli/cotizador.mjs",
|
||||||
|
"test": "node --import tsx --test tests/*.test.ts"
|
||||||
},
|
},
|
||||||
"prisma": {
|
"prisma": {
|
||||||
"seed": "npx tsx prisma/seed.ts"
|
"seed": "npx tsx prisma/seed.ts"
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ function databaseUrl(): string {
|
|||||||
const port = process.env["DB_PORT"] || "5432";
|
const port = process.env["DB_PORT"] || "5432";
|
||||||
const user = encodeURIComponent(process.env["DB_USER"] || "postgres");
|
const user = encodeURIComponent(process.env["DB_USER"] || "postgres");
|
||||||
const password = encodeURIComponent(process.env["DB_PASSWORD"] || "postgres");
|
const password = encodeURIComponent(process.env["DB_PASSWORD"] || "postgres");
|
||||||
|
// Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
const name = process.env["DB_DATABASE"] || process.env["DB_NAME"] || "cotizador_e3";
|
const name = process.env["DB_DATABASE"] || process.env["DB_NAME"] || "cotizador_e3";
|
||||||
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
|
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
-- AlterTable: campos opcionales de aprobacion, envio, cierre y autoria de agente en Cotizacion
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaPorId" TEXT;
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobacionMetodo" TEXT;
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaPor" TEXT;
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaCanal" TEXT;
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaDestino" TEXT;
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aceptadaAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "rechazadaAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "vencidaAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "creadaPorAgente" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable: AgentApiKey
|
||||||
|
CREATE TABLE IF NOT EXISTS "AgentApiKey" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"prefijo" TEXT NOT NULL,
|
||||||
|
"keyHash" TEXT NOT NULL,
|
||||||
|
"scopes" TEXT[],
|
||||||
|
"rateLimitPerMin" INTEGER NOT NULL DEFAULT 60,
|
||||||
|
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"revokedAt" TIMESTAMP(3),
|
||||||
|
"lastUsedAt" TIMESTAMP(3),
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable: AuditLog
|
||||||
|
CREATE TABLE IF NOT EXISTS "AuditLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"actorTipo" TEXT NOT NULL,
|
||||||
|
"actorId" TEXT,
|
||||||
|
"actorNombre" TEXT NOT NULL,
|
||||||
|
"accion" TEXT NOT NULL,
|
||||||
|
"recursoTipo" TEXT NOT NULL,
|
||||||
|
"recursoId" TEXT,
|
||||||
|
"ip" TEXT,
|
||||||
|
"requestId" TEXT,
|
||||||
|
"exito" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"detalle" JSONB,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable: ApprovalToken
|
||||||
|
CREATE TABLE IF NOT EXISTS "ApprovalToken" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"cotizacionId" TEXT NOT NULL,
|
||||||
|
"tokenHash" TEXT NOT NULL,
|
||||||
|
"expiraAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"usadoAt" TIMESTAMP(3),
|
||||||
|
"usadoIp" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ApprovalToken_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable: IdempotencyKey
|
||||||
|
CREATE TABLE IF NOT EXISTS "IdempotencyKey" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"method" TEXT NOT NULL,
|
||||||
|
"path" TEXT NOT NULL,
|
||||||
|
"requestHash" TEXT NOT NULL,
|
||||||
|
"statusCode" INTEGER NOT NULL,
|
||||||
|
"responseBody" JSONB NOT NULL,
|
||||||
|
"expiraAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable: WebhookEndpoint
|
||||||
|
CREATE TABLE IF NOT EXISTS "WebhookEndpoint" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"secret" TEXT NOT NULL,
|
||||||
|
"eventos" TEXT[],
|
||||||
|
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable: WebhookDelivery
|
||||||
|
CREATE TABLE IF NOT EXISTS "WebhookDelivery" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"endpointId" TEXT,
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"evento" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"statusCode" INTEGER,
|
||||||
|
"exito" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"intentos" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"error" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_nombre_key" ON "AgentApiKey"("nombre");
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_keyHash_key" ON "AgentApiKey"("keyHash");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_accion_idx" ON "AuditLog"("accion");
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_recursoTipo_recursoId_idx" ON "AuditLog"("recursoTipo", "recursoId");
|
||||||
|
CREATE INDEX IF NOT EXISTS "AuditLog_actorNombre_idx" ON "AuditLog"("actorNombre");
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "ApprovalToken_tokenHash_key" ON "ApprovalToken"("tokenHash");
|
||||||
|
CREATE INDEX IF NOT EXISTS "ApprovalToken_cotizacionId_idx" ON "ApprovalToken"("cotizacionId");
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "IdempotencyKey_key_key" ON "IdempotencyKey"("key");
|
||||||
|
CREATE INDEX IF NOT EXISTS "IdempotencyKey_expiraAt_idx" ON "IdempotencyKey"("expiraAt");
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "WebhookEndpoint_nombre_key" ON "WebhookEndpoint"("nombre");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "WebhookDelivery_evento_idx" ON "WebhookDelivery"("evento");
|
||||||
|
CREATE INDEX IF NOT EXISTS "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt");
|
||||||
|
|
||||||
|
-- AddForeignKey (idempotent)
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "ApprovalToken" ADD CONSTRAINT "ApprovalToken_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN null;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN null;
|
||||||
|
END $$;
|
||||||
@@ -68,6 +68,17 @@ model Cotizacion {
|
|||||||
observacionesInternas String?
|
observacionesInternas String?
|
||||||
clienteId String
|
clienteId String
|
||||||
asesorId String
|
asesorId String
|
||||||
|
aprobadaPorId String?
|
||||||
|
aprobadaAt DateTime?
|
||||||
|
aprobacionMetodo String?
|
||||||
|
enviadaAt DateTime?
|
||||||
|
enviadaPor String?
|
||||||
|
enviadaCanal String?
|
||||||
|
enviadaDestino String?
|
||||||
|
aceptadaAt DateTime?
|
||||||
|
rechazadaAt DateTime?
|
||||||
|
vencidaAt DateTime?
|
||||||
|
creadaPorAgente String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@ -78,6 +89,7 @@ model Cotizacion {
|
|||||||
registrosHoras RegistroHoras[]
|
registrosHoras RegistroHoras[]
|
||||||
propuestasIA PropuestaIA[]
|
propuestasIA PropuestaIA[]
|
||||||
programasPago ProgramaPago[]
|
programasPago ProgramaPago[]
|
||||||
|
approvalTokens ApprovalToken[]
|
||||||
|
|
||||||
@@index([clienteId])
|
@@index([clienteId])
|
||||||
@@index([asesorId])
|
@@index([asesorId])
|
||||||
@@ -380,3 +392,101 @@ model SuscripcionPush {
|
|||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// API para Agentes, Auditoria, Aprobacion, Idempotencia y Webhooks
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
model AgentApiKey {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
nombre String @unique
|
||||||
|
prefijo String
|
||||||
|
keyHash String @unique
|
||||||
|
scopes String[]
|
||||||
|
rateLimitPerMin Int @default(60)
|
||||||
|
activo Boolean @default(true)
|
||||||
|
revokedAt DateTime?
|
||||||
|
lastUsedAt DateTime?
|
||||||
|
createdById String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
model AuditLog {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
actorTipo String
|
||||||
|
actorId String?
|
||||||
|
actorNombre String
|
||||||
|
accion String
|
||||||
|
recursoTipo String
|
||||||
|
recursoId String?
|
||||||
|
ip String?
|
||||||
|
requestId String?
|
||||||
|
exito Boolean @default(true)
|
||||||
|
detalle Json?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([createdAt])
|
||||||
|
@@index([accion])
|
||||||
|
@@index([recursoTipo, recursoId])
|
||||||
|
@@index([actorNombre])
|
||||||
|
}
|
||||||
|
|
||||||
|
model ApprovalToken {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
cotizacionId String
|
||||||
|
tokenHash String @unique
|
||||||
|
expiraAt DateTime
|
||||||
|
usadoAt DateTime?
|
||||||
|
usadoIp String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([cotizacionId])
|
||||||
|
}
|
||||||
|
|
||||||
|
model IdempotencyKey {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
key String @unique
|
||||||
|
method String
|
||||||
|
path String
|
||||||
|
requestHash String
|
||||||
|
statusCode Int
|
||||||
|
responseBody Json
|
||||||
|
expiraAt DateTime
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([expiraAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
model WebhookEndpoint {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
nombre String @unique
|
||||||
|
url String
|
||||||
|
secret String
|
||||||
|
eventos String[]
|
||||||
|
activo Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
entregas WebhookDelivery[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model WebhookDelivery {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
endpointId String?
|
||||||
|
url String
|
||||||
|
evento String
|
||||||
|
payload Json
|
||||||
|
statusCode Int?
|
||||||
|
exito Boolean @default(false)
|
||||||
|
intentos Int @default(1)
|
||||||
|
error String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
endpoint WebhookEndpoint? @relation(fields: [endpointId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([evento])
|
||||||
|
@@index([createdAt])
|
||||||
|
}
|
||||||
|
|||||||
+8
-7
@@ -7,6 +7,7 @@ const adapter = new PrismaPg({
|
|||||||
port: parseInt(process.env.DB_PORT || "5432"),
|
port: parseInt(process.env.DB_PORT || "5432"),
|
||||||
user: process.env.DB_USER || "postgres",
|
user: process.env.DB_USER || "postgres",
|
||||||
password: process.env.DB_PASSWORD || "postgres",
|
password: process.env.DB_PASSWORD || "postgres",
|
||||||
|
// Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
||||||
});
|
});
|
||||||
const prisma = new PrismaClient({ adapter });
|
const prisma = new PrismaClient({ adapter });
|
||||||
@@ -16,7 +17,7 @@ async function main() {
|
|||||||
|
|
||||||
// Credentials come from env. Without SEED_*_PASSWORD the user is created
|
// Credentials come from env. Without SEED_*_PASSWORD the user is created
|
||||||
// with a default password only if it doesn't exist yet (never overwritten).
|
// with a default password only if it doesn't exist yet (never overwritten).
|
||||||
const adminEmail = process.env.SEED_ADMIN_EMAIL || "admin@e3.local";
|
const adminEmail = process.env.SEED_ADMIN_EMAIL || "admin@urieljareth.com";
|
||||||
const adminPassword = process.env.SEED_ADMIN_PASSWORD;
|
const adminPassword = process.env.SEED_ADMIN_PASSWORD;
|
||||||
if (!adminPassword) {
|
if (!adminPassword) {
|
||||||
console.warn(
|
console.warn(
|
||||||
@@ -567,7 +568,7 @@ async function main() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
nombre: "Plan de Acompanamiento Integral",
|
nombre: "Plan de Acompanamiento Integral",
|
||||||
descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando E3, 3 operando en conjunto y 3 meses operando en acompanamiento)",
|
descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando Uriel Jareth Consulting, 3 operando en conjunto y 3 meses operando en acompanamiento)",
|
||||||
fase: 0,
|
fase: 0,
|
||||||
tipoPago: "mensual",
|
tipoPago: "mensual",
|
||||||
precioBase: 9000,
|
precioBase: 9000,
|
||||||
@@ -585,7 +586,7 @@ async function main() {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// ──────────────────────────────────────────────────────────────
|
// ──────────────────────────────────────────────────────────────
|
||||||
// SERVICIOS NIVELADOS (Catalogo E3 - Cotizacion Final)
|
// SERVICIOS NIVELADOS (Catalogo Uriel Jareth Consulting - Cotizacion Final)
|
||||||
// Precios convertidos de USD a MXN al tipo de cambio 17.30
|
// Precios convertidos de USD a MXN al tipo de cambio 17.30
|
||||||
// Niveles: Emprendedor / PYME / Empresario / Corporativo
|
// Niveles: Emprendedor / PYME / Empresario / Corporativo
|
||||||
// ──────────────────────────────────────────────────────────────
|
// ──────────────────────────────────────────────────────────────
|
||||||
@@ -1966,7 +1967,7 @@ async function main() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "domicilio_fiscal",
|
clave: "domicilio_fiscal",
|
||||||
valor: "EMILIANO ZAPATA S/N, CUAMIO, CUITZEO, MICHOACAN DE OCAMPO CP 58855",
|
valor: "",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "cuenta_nacional",
|
clave: "cuenta_nacional",
|
||||||
@@ -2002,7 +2003,7 @@ async function main() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "no_incluye",
|
clave: "no_incluye",
|
||||||
valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por E3 y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional).",
|
valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por Uriel Jareth Consulting y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "notas_adicionales",
|
clave: "notas_adicionales",
|
||||||
@@ -2010,11 +2011,11 @@ async function main() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "color_primario",
|
clave: "color_primario",
|
||||||
valor: "#2563eb",
|
valor: "#0400C4",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "color_secundario",
|
clave: "color_secundario",
|
||||||
valor: "#1e293b",
|
valor: "#0F172A",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
clave: "logo_base64",
|
clave: "logo_base64",
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ self.addEventListener("push", (event) => {
|
|||||||
} catch {
|
} catch {
|
||||||
data = {};
|
data = {};
|
||||||
}
|
}
|
||||||
const titulo = (data && data.titulo) || "Cotizador E3";
|
const titulo = (data && data.titulo) || "Cotizador — Uriel Jareth Consulting";
|
||||||
const cuerpo = (data && data.cuerpo) || "";
|
const cuerpo = (data && data.cuerpo) || "";
|
||||||
const url = (data && data.url) || "/cliente/pagos";
|
const url = (data && data.url) || "/cliente/pagos";
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
/**
|
||||||
|
* Provisioning CLI de claves de agente (AgentApiKey) para Uriel Jareth Consulting.
|
||||||
|
*
|
||||||
|
* Uso dentro del contenedor web o en local con variables DB_* cargadas:
|
||||||
|
* npx tsx scripts/provision-agent-keys.ts --list
|
||||||
|
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --scopes catalogo:leer,clientes:leer,clientes:escribir,cotizaciones:leer,cotizaciones:borrador,cotizaciones:enviar --rate-limit 60
|
||||||
|
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate
|
||||||
|
* npx tsx scripts/provision-agent-keys.ts --preset [--rotate]
|
||||||
|
*
|
||||||
|
* Imprime JSON limpio en stdout para que un operador/orquestador guarde las
|
||||||
|
* claves directamente en accesos/cotizador.env sin exponerlas en logs.
|
||||||
|
*/
|
||||||
|
import { createHash, randomBytes } from "node:crypto";
|
||||||
|
import { PrismaClient } from "../src/generated/prisma/client";
|
||||||
|
import { PrismaPg } from "@prisma/adapter-pg";
|
||||||
|
|
||||||
|
const VALID_SCOPES = new Set([
|
||||||
|
"catalogo:leer",
|
||||||
|
"clientes:leer",
|
||||||
|
"clientes:escribir",
|
||||||
|
"cotizaciones:leer",
|
||||||
|
"cotizaciones:leer_aceptadas",
|
||||||
|
"cotizaciones:borrador",
|
||||||
|
"cotizaciones:enviar",
|
||||||
|
"cobros:leer",
|
||||||
|
"cobros:registrar",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const PRESETS: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [
|
||||||
|
{
|
||||||
|
nombre: "sales-agent",
|
||||||
|
scopes: [
|
||||||
|
"catalogo:leer",
|
||||||
|
"clientes:leer",
|
||||||
|
"clientes:escribir",
|
||||||
|
"cotizaciones:leer",
|
||||||
|
"cotizaciones:borrador",
|
||||||
|
"cotizaciones:enviar",
|
||||||
|
],
|
||||||
|
rateLimitPerMin: 60,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
nombre: "jefe-operaciones",
|
||||||
|
scopes: [
|
||||||
|
"catalogo:leer",
|
||||||
|
"clientes:leer",
|
||||||
|
"cotizaciones:leer",
|
||||||
|
"cobros:leer",
|
||||||
|
],
|
||||||
|
rateLimitPerMin: 120,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
nombre: "cobranza",
|
||||||
|
scopes: [
|
||||||
|
"clientes:leer",
|
||||||
|
"cobros:leer",
|
||||||
|
],
|
||||||
|
rateLimitPerMin: 60,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
nombre: "entrega",
|
||||||
|
scopes: [
|
||||||
|
"clientes:leer",
|
||||||
|
"cotizaciones:leer_aceptadas",
|
||||||
|
],
|
||||||
|
rateLimitPerMin: 60,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
nombre: "n8n-ecosystem",
|
||||||
|
scopes: [
|
||||||
|
"catalogo:leer",
|
||||||
|
"clientes:leer",
|
||||||
|
"cotizaciones:leer",
|
||||||
|
"cotizaciones:enviar",
|
||||||
|
"cobros:leer",
|
||||||
|
],
|
||||||
|
rateLimitPerMin: 180,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function generateKey() {
|
||||||
|
const rawKey = `ujc_live_${randomBytes(32).toString("hex")}`;
|
||||||
|
const prefijo = rawKey.slice(0, 14);
|
||||||
|
const keyHash = createHash("sha256").update(rawKey, "utf8").digest("hex");
|
||||||
|
return { rawKey, prefijo, keyHash };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv: string[]) {
|
||||||
|
const args: Record<string, string | boolean> = {};
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const token = argv[i];
|
||||||
|
if (!token.startsWith("--")) continue;
|
||||||
|
const key = token.slice(2);
|
||||||
|
const next = argv[i + 1];
|
||||||
|
if (!next || next.startsWith("--")) {
|
||||||
|
args[key] = true;
|
||||||
|
} else {
|
||||||
|
args[key] = next;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = parseArgs(process.argv.slice(2));
|
||||||
|
|
||||||
|
const adapter = new PrismaPg({
|
||||||
|
host: process.env.DB_HOST || "localhost",
|
||||||
|
port: parseInt(process.env.DB_PORT || "5432", 10),
|
||||||
|
user: process.env.DB_USER || "postgres",
|
||||||
|
password: process.env.DB_PASSWORD || "postgres",
|
||||||
|
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
||||||
|
});
|
||||||
|
const prisma = new PrismaClient({ adapter });
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (args.list) {
|
||||||
|
const keys = await prisma.agentApiKey.findMany({
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
prefijo: true,
|
||||||
|
scopes: true,
|
||||||
|
rateLimitPerMin: true,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: true,
|
||||||
|
lastUsedAt: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log(JSON.stringify({ ok: true, keys }, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [];
|
||||||
|
|
||||||
|
if (args.preset) {
|
||||||
|
targets.push(...PRESETS);
|
||||||
|
} else if (typeof args.nombre === "string" && args.nombre.trim()) {
|
||||||
|
const nombre = args.nombre.trim();
|
||||||
|
const rawScopes =
|
||||||
|
typeof args.scopes === "string"
|
||||||
|
? args.scopes
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
: [];
|
||||||
|
const rateLimitPerMin =
|
||||||
|
typeof args["rate-limit"] === "string" ? parseInt(args["rate-limit"], 10) || 60 : 60;
|
||||||
|
|
||||||
|
for (const sc of rawScopes) {
|
||||||
|
if (!VALID_SCOPES.has(sc)) {
|
||||||
|
throw new Error(`Scope invalido: "${sc}". Validos: ${Array.from(VALID_SCOPES).join(", ")}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targets.push({ nombre, scopes: rawScopes, rateLimitPerMin });
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
"Uso: npx tsx scripts/provision-agent-keys.ts --list | --preset [--rotate] | --nombre <nombre> --scopes <a,b> [--rate-limit 60] [--rotate]"
|
||||||
|
);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rotate = Boolean(args.rotate);
|
||||||
|
const results: Array<Record<string, unknown>> = [];
|
||||||
|
|
||||||
|
for (const target of targets) {
|
||||||
|
const existing = await prisma.agentApiKey.findUnique({
|
||||||
|
where: { nombre: target.nombre },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing && !rotate) {
|
||||||
|
results.push({
|
||||||
|
nombre: existing.nombre,
|
||||||
|
action: "exists",
|
||||||
|
id: existing.id,
|
||||||
|
prefijo: existing.prefijo,
|
||||||
|
scopes: existing.scopes,
|
||||||
|
rateLimitPerMin: existing.rateLimitPerMin,
|
||||||
|
activo: existing.activo,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const scopesFinal =
|
||||||
|
target.scopes.length > 0 ? Array.from(new Set(target.scopes)) : existing?.scopes ?? [];
|
||||||
|
if (scopesFinal.length === 0) {
|
||||||
|
throw new Error(`Debes indicar --scopes al crear la clave "${target.nombre}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rawKey, prefijo, keyHash } = generateKey();
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
const updated = await prisma.agentApiKey.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: {
|
||||||
|
prefijo,
|
||||||
|
keyHash,
|
||||||
|
scopes: scopesFinal,
|
||||||
|
rateLimitPerMin: target.rateLimitPerMin || existing.rateLimitPerMin,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
results.push({
|
||||||
|
nombre: updated.nombre,
|
||||||
|
action: "rotated",
|
||||||
|
id: updated.id,
|
||||||
|
prefijo: updated.prefijo,
|
||||||
|
scopes: updated.scopes,
|
||||||
|
rateLimitPerMin: updated.rateLimitPerMin,
|
||||||
|
rawKey,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const created = await prisma.agentApiKey.create({
|
||||||
|
data: {
|
||||||
|
nombre: target.nombre,
|
||||||
|
prefijo,
|
||||||
|
keyHash,
|
||||||
|
scopes: scopesFinal,
|
||||||
|
rateLimitPerMin: target.rateLimitPerMin,
|
||||||
|
activo: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
results.push({
|
||||||
|
nombre: created.nombre,
|
||||||
|
action: "created",
|
||||||
|
id: created.id,
|
||||||
|
prefijo: created.prefijo,
|
||||||
|
scopes: created.scopes,
|
||||||
|
rateLimitPerMin: created.rateLimitPerMin,
|
||||||
|
rawKey,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(JSON.stringify({ ok: true, results }, null, 2));
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) }));
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -102,7 +102,7 @@ const datos: DatosPropuestaPDF = {
|
|||||||
fecha: new Date("2026-07-29"),
|
fecha: new Date("2026-07-29"),
|
||||||
vigencia: new Date("2026-08-19"),
|
vigencia: new Date("2026-08-19"),
|
||||||
proyecto: "MKT Digital",
|
proyecto: "MKT Digital",
|
||||||
branding: { colorPrimario: "#2563eb" },
|
branding: { colorPrimario: "#0400C4" },
|
||||||
};
|
};
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ function check(n: string, ok: boolean, d = "") {
|
|||||||
if (!ok) fallas++;
|
if (!ok) fallas++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── P1 por construccion: ningun schema declara un campo de dinero de E3 ──
|
// ── P1 por construccion: ningun schema declara un campo de dinero de Uriel Jareth Consulting ──
|
||||||
const todos = JSON.stringify([
|
const todos = JSON.stringify([
|
||||||
aJsonSchema(hechosSchema),
|
aJsonSchema(hechosSchema),
|
||||||
aJsonSchema(diagnosticoSchema),
|
aJsonSchema(diagnosticoSchema),
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const SECTIONS = [
|
|||||||
fields: [
|
fields: [
|
||||||
{ key: "razon_social", label: "Razon Social", type: "text" },
|
{ key: "razon_social", label: "Razon Social", type: "text" },
|
||||||
{ key: "rfc", label: "RFC", type: "text" },
|
{ key: "rfc", label: "RFC", type: "text" },
|
||||||
{ key: "domicilio_fiscal", label: "Domicilio Fiscal", type: "text" },
|
{ key: "domicilio_fiscal", label: "Domicilio Fiscal (opcional, uso interno)", type: "text", hint: "Solo referencia interna. No se imprime en cotizaciones, PDF ni Excel." },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -192,7 +192,7 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
|
|||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<input
|
<input
|
||||||
type="color"
|
type="color"
|
||||||
value={config[field.key] || "#2563eb"}
|
value={config[field.key] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4")}
|
||||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||||
className="w-10 h-10 rounded-lg border border-border cursor-pointer p-0.5"
|
className="w-10 h-10 rounded-lg border border-border cursor-pointer p-0.5"
|
||||||
/>
|
/>
|
||||||
@@ -204,7 +204,7 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
|
|||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
className="w-8 h-8 rounded-full border border-border"
|
className="w-8 h-8 rounded-full border border-border"
|
||||||
style={{ backgroundColor: config[field.key] || "#2563eb" }}
|
style={{ backgroundColor: config[field.key] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4") }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : field.type === "textarea" ? (
|
) : field.type === "textarea" ? (
|
||||||
@@ -222,6 +222,9 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
|
|||||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{"hint" in field && field.hint && (
|
||||||
|
<p className="text-xs text-muted mt-1">{field.hint}</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,46 +2,350 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useToast } from "@/components/ui/DialogProvider";
|
import {
|
||||||
|
CheckCircle2,
|
||||||
|
Send,
|
||||||
|
Mail,
|
||||||
|
MessageSquare,
|
||||||
|
Check,
|
||||||
|
XCircle,
|
||||||
|
Clock,
|
||||||
|
RotateCcw,
|
||||||
|
Loader2,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||||
|
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||||
|
|
||||||
const OPCIONES = [
|
interface Props {
|
||||||
{ value: "borrador", label: "Borrador" },
|
cotizacionId: string;
|
||||||
{ value: "enviada", label: "Enviada" },
|
numero: string;
|
||||||
{ value: "aprobada", label: "Aprobada" },
|
estado: string;
|
||||||
{ value: "rechazada", label: "Rechazada" },
|
esAdmin: boolean;
|
||||||
];
|
clienteEmail: string | null;
|
||||||
|
clienteTelefono: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export function CambiarEstadoButtons({ cotizacionId, estado }: { cotizacionId: string; estado: string }) {
|
export function CambiarEstadoButtons({
|
||||||
|
cotizacionId,
|
||||||
|
numero,
|
||||||
|
estado,
|
||||||
|
esAdmin,
|
||||||
|
clienteEmail,
|
||||||
|
clienteTelefono,
|
||||||
|
}: Props) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [loading, setLoading] = useState(false);
|
const confirm = useConfirm();
|
||||||
const showToast = useToast();
|
const showToast = useToast();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [showEnviarModal, setShowEnviarModal] = useState(false);
|
||||||
|
const [canal, setCanal] = useState<"email" | "whatsapp_chatwoot" | "manual">(
|
||||||
|
clienteEmail ? "email" : clienteTelefono ? "whatsapp_chatwoot" : "manual"
|
||||||
|
);
|
||||||
|
const [destino, setDestino] = useState(clienteEmail || clienteTelefono || "");
|
||||||
|
const [mensaje, setMensaje] = useState("");
|
||||||
|
const [fallbackEmail, setFallbackEmail] = useState(Boolean(clienteEmail));
|
||||||
|
|
||||||
|
const handleAprobar = async () => {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "Aprobar cotización",
|
||||||
|
message: `¿Confirmas aprobar la cotización ${numero}? Una vez aprobada podrá enviarse al cliente por correo o WhatsApp.`,
|
||||||
|
confirmText: "Aprobar cotización",
|
||||||
|
cancelText: "Cancelar",
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
const handleChange = async (nuevoEstado: string) => {
|
|
||||||
if (nuevoEstado === estado) return;
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}`, {
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/aprobar`, {
|
||||||
method: "PUT",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ estado: nuevoEstado }),
|
|
||||||
});
|
});
|
||||||
if (res.ok) router.refresh();
|
const data = await res.json().catch(() => ({}));
|
||||||
else showToast("Error al cambiar estado", "error");
|
if (res.ok) {
|
||||||
|
showToast("Cotización aprobada correctamente", "success");
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
showToast(data.error || "No se pudo aprobar la cotización", "error");
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleEnviar = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/enviar`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
canal,
|
||||||
|
destino: destino.trim() || undefined,
|
||||||
|
mensaje: mensaje.trim() || undefined,
|
||||||
|
fallbackEmail: canal === "whatsapp_chatwoot" ? fallbackEmail : undefined,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (res.ok) {
|
||||||
|
showToast(`Cotización enviada (${data.enviadaCanal || canal})`, "success");
|
||||||
|
setShowEnviarModal(false);
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
showToast(data.error || "Error al enviar la cotización", "error");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTransicion = async (
|
||||||
|
nuevoEstado: "aceptada" | "rechazada" | "vencida" | "borrador",
|
||||||
|
etiqueta: string,
|
||||||
|
danger = false
|
||||||
|
) => {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: `Cambiar estado a ${etiqueta}`,
|
||||||
|
message: `¿Confirmas marcar la cotización ${numero} como "${etiqueta}"?`,
|
||||||
|
confirmText: `Marcar ${etiqueta}`,
|
||||||
|
cancelText: "Cancelar",
|
||||||
|
danger,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/estado`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ estado: nuevoEstado }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (res.ok) {
|
||||||
|
showToast(`Cotización marcada como ${etiqueta}`, "success");
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
showToast(data.error || "Error al cambiar estado", "error");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cambiarCanal = (nuevo: "email" | "whatsapp_chatwoot" | "manual") => {
|
||||||
|
setCanal(nuevo);
|
||||||
|
if (nuevo === "email") setDestino(clienteEmail || "");
|
||||||
|
else if (nuevo === "whatsapp_chatwoot") setDestino(clienteTelefono || "");
|
||||||
|
else setDestino(clienteEmail || clienteTelefono || "");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<select
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
value={estado}
|
<EstadoBadge estado={estado} />
|
||||||
onChange={(e) => handleChange(e.target.value)}
|
|
||||||
|
{estado === "borrador" && esAdmin && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleAprobar}
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
className="text-xs font-medium px-2 py-1 rounded-full border border-border bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
|
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{OPCIONES.map((o) => (
|
{loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle2 className="w-3.5 h-3.5" />}
|
||||||
<option key={o.value} value={o.value}>{o.label}</option>
|
Aprobar cotización
|
||||||
))}
|
</button>
|
||||||
</select>
|
)}
|
||||||
|
|
||||||
|
{estado === "aprobada" && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowEnviarModal(true)}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Send className="w-3.5 h-3.5" />
|
||||||
|
Enviar cotización
|
||||||
|
</button>
|
||||||
|
{esAdmin && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<RotateCcw className="w-3.5 h-3.5" />
|
||||||
|
Reabrir
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{estado === "enviada" && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTransicion("aceptada", "Aceptada")}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-green-300 text-green-700 hover:bg-green-50 text-xs font-medium disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Check className="w-3.5 h-3.5" />
|
||||||
|
Aceptada
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTransicion("rechazada", "Rechazada", true)}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-red-300 text-red-700 hover:bg-red-50 text-xs font-medium disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<XCircle className="w-3.5 h-3.5" />
|
||||||
|
Rechazada
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTransicion("vencida", "Vencida")}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-amber-300 text-amber-800 hover:bg-amber-50 text-xs font-medium disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Clock className="w-3.5 h-3.5" />
|
||||||
|
Vencida
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(estado === "rechazada" || estado === "vencida") && esAdmin && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<RotateCcw className="w-3.5 h-3.5" />
|
||||||
|
Reabrir borrador
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showEnviarModal && (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4"
|
||||||
|
onClick={() => !loading && setShowEnviarModal(false)}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
onSubmit={handleEnviar}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
className="bg-white rounded-xl border border-border shadow-xl max-w-md w-full p-5 space-y-4"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-base">Enviar cotización {numero}</h3>
|
||||||
|
<p className="text-xs text-muted mt-0.5">
|
||||||
|
El PDF oficial se genera automáticamente al confirmar el envío.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => cambiarCanal("email")}
|
||||||
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||||
|
canal === "email"
|
||||||
|
? "border-primary bg-primary-light/20 text-primary"
|
||||||
|
: "border-border text-muted hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Mail className="w-4 h-4" />
|
||||||
|
Correo
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => cambiarCanal("whatsapp_chatwoot")}
|
||||||
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||||
|
canal === "whatsapp_chatwoot"
|
||||||
|
? "border-primary bg-primary-light/20 text-primary"
|
||||||
|
: "border-border text-muted hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-4 h-4" />
|
||||||
|
WhatsApp
|
||||||
|
</button>
|
||||||
|
{esAdmin && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => cambiarCanal("manual")}
|
||||||
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||||
|
canal === "manual"
|
||||||
|
? "border-primary bg-primary-light/20 text-primary"
|
||||||
|
: "border-border text-muted hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="w-4 h-4" />
|
||||||
|
Manual
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-muted mb-1">
|
||||||
|
{canal === "email"
|
||||||
|
? "Correo destino"
|
||||||
|
: canal === "whatsapp_chatwoot"
|
||||||
|
? "Teléfono WhatsApp"
|
||||||
|
: "Destino / referencia"}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={destino}
|
||||||
|
onChange={(e) => setDestino(e.target.value)}
|
||||||
|
required={canal !== "manual"}
|
||||||
|
placeholder={canal === "email" ? "[email protected]" : "4421234567"}
|
||||||
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canal !== "manual" && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-muted mb-1">
|
||||||
|
Mensaje adicional (opcional)
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
rows={3}
|
||||||
|
value={mensaje}
|
||||||
|
onChange={(e) => setMensaje(e.target.value)}
|
||||||
|
placeholder="Nota breve para acompañar la propuesta..."
|
||||||
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{canal === "whatsapp_chatwoot" && clienteEmail && (
|
||||||
|
<label className="flex items-center gap-2 text-xs text-muted">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={fallbackEmail}
|
||||||
|
onChange={(e) => setFallbackEmail(e.target.checked)}
|
||||||
|
/>
|
||||||
|
Si WhatsApp está fuera de la ventana de 24h, enviar por correo ({clienteEmail})
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2 border-t border-border">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowEnviarModal(false)}
|
||||||
|
disabled={loading}
|
||||||
|
className="px-3 py-2 rounded-lg border border-border text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||||
|
Confirmar envío
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -331,8 +331,8 @@ export function RegistroHorasPanel({
|
|||||||
|
|
||||||
// ---- HTML autocontenido de la nota de pago (para imprimir / guardar como PDF) ----
|
// ---- HTML autocontenido de la nota de pago (para imprimir / guardar como PDF) ----
|
||||||
const construirHTMLNota = () => {
|
const construirHTMLNota = () => {
|
||||||
const PRIMARY = branding.colorPrimario || "#2563eb";
|
const PRIMARY = branding.colorPrimario || "#0400C4";
|
||||||
const DARK = branding.colorSecundario || "#111827";
|
const DARK = branding.colorSecundario || "#0F172A";
|
||||||
const logoSrc = branding.logoBase64
|
const logoSrc = branding.logoBase64
|
||||||
? `data:${branding.logoMime || "image/png"};base64,${branding.logoBase64}`
|
? `data:${branding.logoMime || "image/png"};base64,${branding.logoBase64}`
|
||||||
: "";
|
: "";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
|
import { getSession } from "@/lib/auth";
|
||||||
import { getConfigBranding } from "@/lib/config-helpers";
|
import { getConfigBranding } from "@/lib/config-helpers";
|
||||||
import {
|
import {
|
||||||
formatDate,
|
formatDate,
|
||||||
@@ -42,7 +43,9 @@ export default async function CotizacionDetailPage({
|
|||||||
|
|
||||||
// El registro de horas (notas de pago) solo aplica a cotizaciones aprobadas que se
|
// El registro de horas (notas de pago) solo aplica a cotizaciones aprobadas que se
|
||||||
// cobran por tiempo (horas/retainer/demanda).
|
// cobran por tiempo (horas/retainer/demanda).
|
||||||
const mostrarHoras = cot.estado === "aprobada" && esCotizacionPorTiempo(cot.servicios);
|
const session = await getSession();
|
||||||
|
const esAdmin = session?.role === "admin";
|
||||||
|
const mostrarHoras = ["aprobada", "enviada", "aceptada"].includes(cot.estado) && esCotizacionPorTiempo(cot.servicios);
|
||||||
const branding = mostrarHoras ? await getConfigBranding() : null;
|
const branding = mostrarHoras ? await getConfigBranding() : null;
|
||||||
|
|
||||||
const serviciosUnicos = cot.servicios
|
const serviciosUnicos = cot.servicios
|
||||||
@@ -107,6 +110,28 @@ export default async function CotizacionDetailPage({
|
|||||||
|
|
||||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||||
<h2 className="font-semibold text-lg mb-4">Información de la Cotización</h2>
|
<h2 className="font-semibold text-lg mb-4">Información de la Cotización</h2>
|
||||||
|
{(cot.creadaPorAgente || cot.aprobadaAt || cot.enviadaAt) && (
|
||||||
|
<div className="flex flex-wrap gap-2 mb-4 text-xs">
|
||||||
|
{cot.creadaPorAgente && (
|
||||||
|
<span className="px-2.5 py-1 rounded-full bg-purple-100 text-purple-800 font-medium">
|
||||||
|
Creada por agente: {cot.creadaPorAgente}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{cot.aprobadaAt && (
|
||||||
|
<span className="px-2.5 py-1 rounded-full bg-indigo-50 text-indigo-800 border border-indigo-200">
|
||||||
|
Aprobada el {formatDate(cot.aprobadaAt)}
|
||||||
|
{cot.aprobacionMetodo ? ` (${cot.aprobacionMetodo === "enlace_firmado" ? "enlace firmado" : "panel admin"})` : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{cot.enviadaAt && (
|
||||||
|
<span className="px-2.5 py-1 rounded-full bg-blue-50 text-blue-800 border border-blue-200">
|
||||||
|
Enviada el {formatDate(cot.enviadaAt)}
|
||||||
|
{cot.enviadaCanal ? ` vía ${cot.enviadaCanal}` : ""}
|
||||||
|
{cot.enviadaDestino ? ` a ${cot.enviadaDestino}` : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-muted">Cliente</span>
|
<span className="text-muted">Cliente</span>
|
||||||
@@ -139,7 +164,14 @@ export default async function CotizacionDetailPage({
|
|||||||
<div>
|
<div>
|
||||||
<span className="text-muted">Estado</span>
|
<span className="text-muted">Estado</span>
|
||||||
<div className="mt-0.5">
|
<div className="mt-0.5">
|
||||||
<CambiarEstadoButtons cotizacionId={cot.id} estado={cot.estado} />
|
<CambiarEstadoButtons
|
||||||
|
cotizacionId={cot.id}
|
||||||
|
numero={cot.numero}
|
||||||
|
estado={cot.estado}
|
||||||
|
esAdmin={esAdmin}
|
||||||
|
clienteEmail={cot.cliente.email}
|
||||||
|
clienteTelefono={cot.cliente.telefono}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export default async function DashboardPage() {
|
|||||||
value: totalClientes,
|
value: totalClientes,
|
||||||
icon: Users,
|
icon: Users,
|
||||||
color: "text-secondary",
|
color: "text-secondary",
|
||||||
bg: "bg-purple-100",
|
bg: "bg-slate-100",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Servicios Activos",
|
label: "Servicios Activos",
|
||||||
@@ -62,7 +62,7 @@ export default async function DashboardPage() {
|
|||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-foreground">Dashboard</h1>
|
<h1 className="text-2xl font-bold text-foreground">Dashboard</h1>
|
||||||
<p className="text-muted text-sm mt-1">
|
<p className="text-muted text-sm mt-1">
|
||||||
Bienvenido al Cotizador E3
|
Bienvenido al Cotizador — Uriel Jareth Consulting
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
adminOnly: true,
|
||||||
|
recursoTipo: "agent_key",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const existing = await prisma.agentApiKey.findUnique({ where: { id } });
|
||||||
|
if (!existing) {
|
||||||
|
return NextResponse.json({ error: "Clave no encontrada" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await prisma.agentApiKey.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
activo: false,
|
||||||
|
revokedAt: new Date(),
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
prefijo: true,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "agent_key.revocar",
|
||||||
|
recursoTipo: "agent_key",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: updated.nombre, prefijo: updated.prefijo },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(updated);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { generateApiKey, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
adminOnly: true,
|
||||||
|
recursoTipo: "agent_key",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const existing = await prisma.agentApiKey.findUnique({ where: { id } });
|
||||||
|
if (!existing) {
|
||||||
|
return NextResponse.json({ error: "Clave no encontrada" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rawKey, prefijo, keyHash } = generateApiKey();
|
||||||
|
|
||||||
|
const updated = await prisma.agentApiKey.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
prefijo,
|
||||||
|
keyHash,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: null,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
prefijo: true,
|
||||||
|
scopes: true,
|
||||||
|
rateLimitPerMin: true,
|
||||||
|
activo: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "agent_key.rotar",
|
||||||
|
recursoTipo: "agent_key",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: updated.nombre, prefijoNuevo: prefijo },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ...updated, rawKey });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import {
|
||||||
|
AGENT_SCOPES,
|
||||||
|
generateApiKey,
|
||||||
|
requireActor,
|
||||||
|
} from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
const createKeySchema = z.object({
|
||||||
|
nombre: z.string().trim().min(2, "Nombre requerido (min. 2 caracteres)").max(100),
|
||||||
|
scopes: z
|
||||||
|
.array(z.enum(AGENT_SCOPES))
|
||||||
|
.min(1, "Debes asignar al menos un alcance"),
|
||||||
|
rateLimitPerMin: z.number().int().min(1).max(1000).default(60),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "agent_key" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const keys = await prisma.agentApiKey.findMany({
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
prefijo: true,
|
||||||
|
scopes: true,
|
||||||
|
rateLimitPerMin: true,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: true,
|
||||||
|
lastUsedAt: true,
|
||||||
|
createdById: true,
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return NextResponse.json(keys);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "agent_key" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
const parsed = createKeySchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { nombre, scopes, rateLimitPerMin } = parsed.data;
|
||||||
|
const existe = await prisma.agentApiKey.findUnique({ where: { nombre } });
|
||||||
|
if (existe) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Ya existe una clave con el nombre "${nombre}"` },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rawKey, prefijo, keyHash } = generateApiKey();
|
||||||
|
const createdById = auth.actor.type === "user" ? auth.actor.userId : null;
|
||||||
|
|
||||||
|
const created = await prisma.agentApiKey.create({
|
||||||
|
data: {
|
||||||
|
nombre,
|
||||||
|
prefijo,
|
||||||
|
keyHash,
|
||||||
|
scopes: Array.from(new Set(scopes)),
|
||||||
|
rateLimitPerMin,
|
||||||
|
activo: true,
|
||||||
|
createdById,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
prefijo: true,
|
||||||
|
scopes: true,
|
||||||
|
rateLimitPerMin: true,
|
||||||
|
activo: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "agent_key.crear",
|
||||||
|
recursoTipo: "agent_key",
|
||||||
|
recursoId: created.id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: created.nombre, prefijo: created.prefijo, scopes: created.scopes },
|
||||||
|
});
|
||||||
|
|
||||||
|
// rawKey se devuelve UNA SOLA VEZ al momento de crear la clave.
|
||||||
|
return NextResponse.json({ ...created, rawKey }, { status: 201 });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { hashSecret } from "@/lib/agent-auth-core";
|
||||||
|
import { obtenerIp } from "@/lib/audit";
|
||||||
|
import { aprobarCotizacionConToken } from "@/lib/aprobacion";
|
||||||
|
import { calcularTotalesCotizacion } from "@/lib/calculators";
|
||||||
|
|
||||||
|
// GET /api/aprobar/[token] — consulta segura SIN mutar nada (proteccion anti-prefetch).
|
||||||
|
export async function GET(
|
||||||
|
_request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ token: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { token } = await params;
|
||||||
|
const tokenHash = hashSecret(token);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const record = await prisma.approvalToken.findUnique({
|
||||||
|
where: { tokenHash },
|
||||||
|
include: {
|
||||||
|
cotizacion: {
|
||||||
|
include: {
|
||||||
|
cliente: { select: { nombre: true, empresa: true } },
|
||||||
|
servicios: {
|
||||||
|
where: { seleccionado: true },
|
||||||
|
include: { servicioCatalogo: { select: { nombre: true } } },
|
||||||
|
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||||
|
},
|
||||||
|
planBucefalo: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!record) {
|
||||||
|
return NextResponse.json({ error: "Enlace de aprobacion invalido" }, { status: 404 });
|
||||||
|
}
|
||||||
|
if (record.usadoAt) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Este enlace de aprobacion ya fue utilizado", usadoAt: record.usadoAt },
|
||||||
|
{ status: 410 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (record.expiraAt <= now) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Este enlace de aprobacion ha expirado", expiraAt: record.expiraAt },
|
||||||
|
{ status: 410 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cot = record.cotizacion;
|
||||||
|
const totales = calcularTotalesCotizacion(cot.servicios, {
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
cotizacion: {
|
||||||
|
id: cot.id,
|
||||||
|
numero: cot.numero,
|
||||||
|
proyecto: cot.proyecto,
|
||||||
|
moneda: cot.moneda,
|
||||||
|
estado: cot.estado,
|
||||||
|
fecha: cot.fecha,
|
||||||
|
vigencia: cot.vigencia,
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
creadaPorAgente: cot.creadaPorAgente,
|
||||||
|
cliente: cot.cliente,
|
||||||
|
totales,
|
||||||
|
partidas: cot.servicios.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||||
|
fase: s.fase,
|
||||||
|
tipoPago: s.tipoPago,
|
||||||
|
precio: s.precio,
|
||||||
|
modeloCobro: s.modeloCobro,
|
||||||
|
tiempoEntrega: s.tiempoEntrega,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
expiraAt: record.expiraAt,
|
||||||
|
puedeAprobar: cot.estado === "borrador",
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/aprobar/[token] — exige { confirmar: true } y aprueba en transaccion atomica.
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ token: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { token } = await params;
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
if (!body || body.confirmar !== true) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Se requiere { confirmar: true } para aprobar la cotizacion" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await aprobarCotizacionConToken(token, obtenerIp(request));
|
||||||
|
if (!res.ok) {
|
||||||
|
return NextResponse.json({ error: res.error }, { status: res.status });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
cotizacionId: res.cotizacionId,
|
||||||
|
numero: res.numero,
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaAt: res.aprobadaAt,
|
||||||
|
aprobacionMetodo: "enlace_firmado",
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "audit_log" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const sp = request.nextUrl.searchParams;
|
||||||
|
const accion = sp.get("accion")?.trim();
|
||||||
|
const actorNombre = sp.get("actorNombre")?.trim();
|
||||||
|
const recursoId = sp.get("recursoId")?.trim();
|
||||||
|
const page = Math.max(1, parseInt(sp.get("page") || "1", 10) || 1);
|
||||||
|
const limit = Math.min(200, Math.max(1, parseInt(sp.get("limit") || "50", 10) || 50));
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
...(accion && { accion: { contains: accion, mode: "insensitive" as const } }),
|
||||||
|
...(actorNombre && { actorNombre: { contains: actorNombre, mode: "insensitive" as const } }),
|
||||||
|
...(recursoId && { recursoId }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const [total, data] = await Promise.all([
|
||||||
|
prisma.auditLog.count({ where }),
|
||||||
|
prisma.auditLog.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data,
|
||||||
|
meta: {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
pages: Math.ceil(total / limit),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +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 { requireStaff } from "@/lib/auth";
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
import { servicioCatalogoSchema } from "@/lib/schemas";
|
import { servicioCatalogoSchema } from "@/lib/schemas";
|
||||||
import {
|
import {
|
||||||
categoriaExiste,
|
categoriaExiste,
|
||||||
@@ -12,14 +12,13 @@ import {
|
|||||||
siguienteOrden,
|
siguienteOrden,
|
||||||
} from "@/lib/catalogo";
|
} from "@/lib/catalogo";
|
||||||
|
|
||||||
// GET /api/catalogo — lista de servicios del catalogo.
|
|
||||||
// Filtros opcionales: ?q=texto (nombre/descripcion), ?fase=0-3,
|
|
||||||
// ?tipoPago=unico|mensual, ?categoriaId=..., ?activo=true|false.
|
|
||||||
// Sin `activo` devuelve activos y archivados (la pagina /catalogo los muestra todos).
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
scopes: ["catalogo:leer"],
|
||||||
|
recursoTipo: "catalogo",
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const sp = request.nextUrl.searchParams;
|
const sp = request.nextUrl.searchParams;
|
||||||
const q = sp.get("q")?.trim();
|
const q = sp.get("q")?.trim();
|
||||||
@@ -29,10 +28,16 @@ export async function GET(request: NextRequest) {
|
|||||||
const activo = sp.get("activo");
|
const activo = sp.get("activo");
|
||||||
|
|
||||||
if (fase !== null && !/^[0-3]$/.test(fase)) {
|
if (fase !== null && !/^[0-3]$/.test(fase)) {
|
||||||
return NextResponse.json({ error: "fase debe ser 0, 1, 2 o 3" }, { status: 400 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "fase debe ser 0, 1, 2 o 3" }, { status: 400 }),
|
||||||
|
auth.rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (tipoPago !== null && tipoPago !== "unico" && tipoPago !== "mensual") {
|
if (tipoPago !== null && tipoPago !== "unico" && tipoPago !== "mensual") {
|
||||||
return NextResponse.json({ error: "tipoPago debe ser 'unico' o 'mensual'" }, { status: 400 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "tipoPago debe ser 'unico' o 'mensual'" }, { status: 400 }),
|
||||||
|
auth.rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const servicios = await prisma.servicioCatalogo.findMany({
|
const servicios = await prisma.servicioCatalogo.findMany({
|
||||||
@@ -52,18 +57,16 @@ export async function GET(request: NextRequest) {
|
|||||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||||
include: servicioCatalogoInclude,
|
include: servicioCatalogoInclude,
|
||||||
});
|
});
|
||||||
return NextResponse.json(servicios.map(serializarServicio));
|
return applyHeaders(NextResponse.json(servicios.map(serializarServicio)), auth.rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorInterno(error);
|
return errorInterno(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /api/catalogo — alta de un servicio. Obligatorios: nombre, fase,
|
|
||||||
// tipoPago, precioBase. Sin `orden` se coloca al final de su fase.
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "catalogo" });
|
||||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const body = await request.json().catch(() => null);
|
const body = await request.json().catch(() => null);
|
||||||
const parsed = servicioCatalogoSchema.safeParse(sinCamposDeSoloLectura(body));
|
const parsed = servicioCatalogoSchema.safeParse(sinCamposDeSoloLectura(body));
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
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) {
|
||||||
try {
|
try {
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["catalogo:leer"],
|
||||||
|
recursoTipo: "categoria",
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const cats = await prisma.categoria.findMany({ orderBy: { orden: "asc" } });
|
const cats = await prisma.categoria.findMany({ orderBy: { orden: "asc" } });
|
||||||
return NextResponse.json(cats);
|
return applyHeaders(NextResponse.json(cats), 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 });
|
||||||
@@ -13,6 +20,9 @@ export async function GET() {
|
|||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "categoria" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const cat = await prisma.categoria.create({
|
const cat = await prisma.categoria.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -1,41 +1,52 @@
|
|||||||
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 { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
import { clienteSchema } from "@/lib/schemas";
|
import { clienteSchema } from "@/lib/schemas";
|
||||||
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
||||||
|
|
||||||
// PATCH /api/clientes/[id] — edita los datos del cliente. No toca la cuenta de
|
// PATCH /api/clientes/[id] — edita los datos del cliente.
|
||||||
// panel: el correo de acceso se cambia con "Rotar" (/api/clientes/[id]/acceso).
|
|
||||||
export async function PATCH(
|
export async function PATCH(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
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: ["clientes:escribir"],
|
||||||
|
recursoTipo: "cliente",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const previo = await prisma.cliente.findUnique({ where: { id }, select: { id: true } });
|
const previo = await prisma.cliente.findUnique({ where: { id }, select: { id: true } });
|
||||||
if (!previo) {
|
if (!previo) {
|
||||||
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }),
|
||||||
|
auth.rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const parsed = clienteSchema.safeParse(body);
|
const parsed = clienteSchema.safeParse(body);
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
|
),
|
||||||
|
auth.rateLimitHeaders
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const data = parsed.data;
|
const data = parsed.data;
|
||||||
|
|
||||||
if (await buscarDuplicado(data.nombre, data.empresa, id)) {
|
if (await buscarDuplicado(data.nombre, data.empresa, id)) {
|
||||||
return NextResponse.json(
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
{ error: mensajeDuplicado(data.nombre, data.empresa) },
|
{ error: mensajeDuplicado(data.nombre, data.empresa) },
|
||||||
{ status: 409 }
|
{ status: 409 }
|
||||||
|
),
|
||||||
|
auth.rateLimitHeaders
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +55,18 @@ export async function PATCH(
|
|||||||
data,
|
data,
|
||||||
select: clienteSelect,
|
select: clienteSelect,
|
||||||
});
|
});
|
||||||
return NextResponse.json(cliente);
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "cliente.actualizar",
|
||||||
|
recursoTipo: "cliente",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: cliente.nombre, empresa: cliente.empresa },
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(cliente), 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 });
|
||||||
|
|||||||
@@ -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 { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { withIdempotency } from "@/lib/idempotency";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
import { clienteSchema } from "@/lib/schemas";
|
import { clienteSchema } from "@/lib/schemas";
|
||||||
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
||||||
|
|
||||||
@@ -8,10 +10,12 @@ import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes
|
|||||||
// email y RFC.
|
// email y RFC.
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["clientes:leer"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "cliente",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const q = request.nextUrl.searchParams.get("q")?.trim();
|
const q = request.nextUrl.searchParams.get("q")?.trim();
|
||||||
const clientes = await prisma.cliente.findMany({
|
const clientes = await prisma.cliente.findMany({
|
||||||
where: q
|
where: q
|
||||||
@@ -27,23 +31,26 @@ export async function GET(request: NextRequest) {
|
|||||||
orderBy: { nombre: "asc" },
|
orderBy: { nombre: "asc" },
|
||||||
select: clienteSelect,
|
select: clienteSelect,
|
||||||
});
|
});
|
||||||
return NextResponse.json(clientes);
|
return applyHeaders(NextResponse.json(clientes), 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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /api/clientes — alta directa de un cliente, sin pasar por una cotizacion
|
// POST /api/clientes — alta directa de un cliente (staff o agente con clientes:escribir).
|
||||||
// (ej. para programarle cobros recurrentes). Solo staff.
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["clientes:escribir"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "cliente",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const body = await request.json();
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||||
|
|
||||||
|
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||||
const parsed = clienteSchema.safeParse(body);
|
const parsed = clienteSchema.safeParse(body);
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -61,7 +68,21 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cliente = await prisma.cliente.create({ data, select: clienteSelect });
|
const cliente = await prisma.cliente.create({ data, select: clienteSelect });
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cliente.crear",
|
||||||
|
recursoTipo: "cliente",
|
||||||
|
recursoId: cliente.id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: cliente.nombre, empresa: cliente.empresa },
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json(cliente, { status: 201 });
|
return NextResponse.json(cliente, { status: 201 });
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(res, 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 });
|
||||||
|
|||||||
@@ -1,23 +1,32 @@
|
|||||||
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 { requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
import { ESTADOS_PAGO } from "@/lib/cobros";
|
import { ESTADOS_PAGO } from "@/lib/cobros";
|
||||||
import { notificarVerificacion } from "@/lib/notificaciones";
|
import { notificarVerificacion } from "@/lib/notificaciones";
|
||||||
|
|
||||||
// POST /api/cobros/pagos/[id]/aprobar — valida un comprobante en revision.
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
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, {
|
||||||
|
staffOnly: true,
|
||||||
|
recursoTipo: "pago_recurrente",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const pago = await prisma.pagoRecurrente.findUnique({ where: { id } });
|
const pago = await prisma.pagoRecurrente.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
programa: {
|
||||||
|
include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
if (!pago) {
|
if (!pago) {
|
||||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||||
}
|
}
|
||||||
@@ -40,6 +49,28 @@ export async function POST(
|
|||||||
|
|
||||||
await notificarVerificacion(id);
|
await notificarVerificacion(id);
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "pago.aprobar_comprobante",
|
||||||
|
recursoTipo: "pago_recurrente",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { programaId: pago.programaId, monto: pago.monto },
|
||||||
|
});
|
||||||
|
|
||||||
|
void emitirWebhook("pago.registrado", {
|
||||||
|
pagoId: actualizado.id,
|
||||||
|
programaId: pago.programaId,
|
||||||
|
concepto: pago.programa.concepto,
|
||||||
|
monto: actualizado.monto,
|
||||||
|
moneda: pago.programa.moneda,
|
||||||
|
fechaCobro: actualizado.fecha.toISOString().slice(0, 10),
|
||||||
|
verificadoAt: actualizado.verificadoAt?.toISOString() ?? null,
|
||||||
|
metodo: "comprobante_verificado",
|
||||||
|
cliente: pago.programa.cliente,
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json(actualizado);
|
return NextResponse.json(actualizado);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const msg = error instanceof Error ? error.message : "Error interno";
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
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 { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { withIdempotency } from "@/lib/idempotency";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
import {
|
import {
|
||||||
ESTADOS_PAGO,
|
ESTADOS_PAGO,
|
||||||
esPorPagar,
|
esPorPagar,
|
||||||
@@ -11,21 +14,23 @@ import {
|
|||||||
import { registrarPagoSchema } from "@/lib/schemas";
|
import { registrarPagoSchema } from "@/lib/schemas";
|
||||||
import { notificarVerificacion } from "@/lib/notificaciones";
|
import { notificarVerificacion } from "@/lib/notificaciones";
|
||||||
|
|
||||||
// POST /api/cobros/pagos/[id]/registrar — el admin marca como pagado un cobro
|
|
||||||
// que el cliente pago fuera del panel (transferencia avisada por otro medio,
|
|
||||||
// efectivo). Queda verificado sin comprobante; `fecha` es el dia del pago.
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
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 body = await request.json();
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cobros:registrar"],
|
||||||
|
recursoTipo: "pago_recurrente",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||||
|
|
||||||
|
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||||
const parsed = registrarPagoSchema.safeParse(body);
|
const parsed = registrarPagoSchema.safeParse(body);
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -42,7 +47,14 @@ export async function POST(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pago = await prisma.pagoRecurrente.findUnique({ where: { id } });
|
const pago = await prisma.pagoRecurrente.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
programa: {
|
||||||
|
include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
if (!pago) {
|
if (!pago) {
|
||||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||||
}
|
}
|
||||||
@@ -66,7 +78,36 @@ export async function POST(
|
|||||||
|
|
||||||
await notificarVerificacion(id);
|
await notificarVerificacion(id);
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "pago.registrar",
|
||||||
|
recursoTipo: "pago_recurrente",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
programaId: pago.programaId,
|
||||||
|
monto: pago.monto,
|
||||||
|
fechaPago: parsed.data.fecha,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
void emitirWebhook("pago.registrado", {
|
||||||
|
pagoId: actualizado.id,
|
||||||
|
programaId: pago.programaId,
|
||||||
|
concepto: pago.programa.concepto,
|
||||||
|
monto: actualizado.monto,
|
||||||
|
moneda: pago.programa.moneda,
|
||||||
|
fechaCobro: actualizado.fecha.toISOString().slice(0, 10),
|
||||||
|
verificadoAt: actualizado.verificadoAt?.toISOString() ?? null,
|
||||||
|
metodo: "registro_manual",
|
||||||
|
cliente: pago.programa.cliente,
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json(actualizado);
|
return NextResponse.json(actualizado);
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(res, 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 });
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
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 { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
import { ESTADOS_POR_PAGAR, parseFechaCalendario } from "@/lib/cobros";
|
import { ESTADOS_POR_PAGAR, parseFechaCalendario } from "@/lib/cobros";
|
||||||
|
|
||||||
// GET /api/cobros/pagos?estado=&clienteId=&programaId=&desde=&hasta=
|
|
||||||
// Pagos ordenados por fecha desc con programa+cliente y comprobante.
|
|
||||||
// estado=por_pagar agrupa pendiente + rechazado (lo que el cliente debe).
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["cobros:leer"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "pago_recurrente",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const estado = searchParams.get("estado");
|
const estado = searchParams.get("estado");
|
||||||
@@ -47,7 +45,7 @@ export async function GET(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(pagos);
|
return applyHeaders(NextResponse.json(pagos), 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 });
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
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 { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
import { programaPagoSchema } from "@/lib/schemas";
|
import { programaPagoSchema } from "@/lib/schemas";
|
||||||
import { parseFechaCalendario, proximaFecha } from "@/lib/cobros";
|
import { parseFechaCalendario, proximaFecha } from "@/lib/cobros";
|
||||||
|
|
||||||
// GET /api/cobros/programas — lista programas con cliente, conteo de pagos y
|
export async function GET(request: NextRequest) {
|
||||||
// proxima fecha calculada. Solo staff.
|
|
||||||
export async function GET() {
|
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["cobros:leer"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "programa_pago",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const programas = await prisma.programaPago.findMany({
|
const programas = await prisma.programaPago.findMany({
|
||||||
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
||||||
@@ -29,20 +28,17 @@ export async function GET() {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(salida);
|
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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /api/cobros/programas — crea un programa de pago recurrente.
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "programa_pago" });
|
||||||
if (!session) {
|
if (!auth.ok) return auth.response;
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const parsed = programaPagoSchema.safeParse(body);
|
const parsed = programaPagoSchema.safeParse(body);
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
|
import { calcularTotalesCotizacion } from "@/lib/calculators";
|
||||||
|
import { appBaseUrl } from "@/lib/aprobacion";
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
adminOnly: true,
|
||||||
|
accionBloqueo: "cotizacion.aprobar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
if (actor.type !== "user" || actor.role !== "admin") {
|
||||||
|
return NextResponse.json({ error: "Solo un administrador humano puede aprobar" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cot = await prisma.cotizacion.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { cliente: true, servicios: true },
|
||||||
|
});
|
||||||
|
if (!cot) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cot.estado !== "borrador") {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: `Solo se pueden aprobar cotizaciones en borrador (estado actual: ${cot.estado})` },
|
||||||
|
{ status: 409 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const updated = await prisma.$transaction(async (tx) => {
|
||||||
|
await tx.approvalToken.updateMany({
|
||||||
|
where: { cotizacionId: id, usadoAt: null },
|
||||||
|
data: { expiraAt: now },
|
||||||
|
});
|
||||||
|
|
||||||
|
return tx.cotizacion.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaPorId: actor.userId,
|
||||||
|
aprobadaAt: now,
|
||||||
|
aprobacionMetodo: "web_admin",
|
||||||
|
},
|
||||||
|
include: { cliente: true },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.aprobar",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
numero: updated.numero,
|
||||||
|
metodo: "web_admin",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const tot = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
|
||||||
|
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||||
|
|
||||||
|
void emitirWebhook("cotizacion.aprobada", {
|
||||||
|
cotizacionId: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
folio: updated.numero,
|
||||||
|
titulo: updated.proyecto,
|
||||||
|
proyecto: updated.proyecto,
|
||||||
|
moneda: updated.moneda,
|
||||||
|
total: totalWebhook,
|
||||||
|
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaAt: now.toISOString(),
|
||||||
|
aprobadaPorId: actor.userId,
|
||||||
|
aprobacionMetodo: "web_admin",
|
||||||
|
cliente: {
|
||||||
|
id: updated.cliente.id,
|
||||||
|
nombre: updated.cliente.nombre,
|
||||||
|
empresa: updated.cliente.empresa,
|
||||||
|
email: updated.cliente.email,
|
||||||
|
telefono: updated.cliente.telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
id: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
estado: updated.estado,
|
||||||
|
aprobadaAt: updated.aprobadaAt,
|
||||||
|
aprobacionMetodo: updated.aprobacionMetodo,
|
||||||
|
}),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import {
|
||||||
|
applyHeaders,
|
||||||
|
coincideContacto,
|
||||||
|
requireActor,
|
||||||
|
} from "@/lib/agent-auth";
|
||||||
|
import { withIdempotency } from "@/lib/idempotency";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { generarPDFCotizacion } from "@/lib/cotizacion-pdf";
|
||||||
|
import { enviarCotizacionPorCorreo } from "@/lib/email";
|
||||||
|
import {
|
||||||
|
appBaseUrl,
|
||||||
|
notificarJarethWhatsAppFueraVentana,
|
||||||
|
} from "@/lib/aprobacion";
|
||||||
|
import {
|
||||||
|
emitirWebhook,
|
||||||
|
invocarEnvioWhatsAppN8n,
|
||||||
|
} from "@/lib/webhooks";
|
||||||
|
import {
|
||||||
|
calcularTotalesCotizacion,
|
||||||
|
formatCurrency,
|
||||||
|
formatDate,
|
||||||
|
} from "@/lib/calculators";
|
||||||
|
|
||||||
|
const enviarSchema = z.object({
|
||||||
|
canal: z.enum(["email", "whatsapp_chatwoot", "manual"]).default("email"),
|
||||||
|
destino: z.string().trim().optional(),
|
||||||
|
mensaje: z.string().trim().max(2000).optional(),
|
||||||
|
verificarContacto: z.string().trim().optional(),
|
||||||
|
chatwootConversationId: z.union([z.number().int(), z.string()]).optional(),
|
||||||
|
fallbackEmail: z.boolean().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cotizaciones:enviar"],
|
||||||
|
accionBloqueo: "cotizacion.enviar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||||
|
|
||||||
|
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||||
|
const parsed = enviarSchema.safeParse(body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = parsed.data;
|
||||||
|
|
||||||
|
const cot = await prisma.cotizacion.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
cliente: true,
|
||||||
|
servicios: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!cot) {
|
||||||
|
return NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// GUARDIA DURA: ninguna cotizacion sale sin aprobacion humana previa
|
||||||
|
if (cot.estado !== "aprobada" || !cot.aprobadaAt) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: {
|
||||||
|
estadoActual: cot.estado,
|
||||||
|
aprobadaAt: cot.aprobadaAt,
|
||||||
|
motivo: "no_aprobada",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||||
|
estadoActual: cot.estado,
|
||||||
|
},
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificacion de identidad del contacto (anti-fuga entre prospectos)
|
||||||
|
if (data.verificarContacto && !coincideContacto(data.verificarContacto, cot.cliente)) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_contacto_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { motivo: "verificarContacto_no_coincide" },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El contacto proporcionado no coincide con el cliente de esta cotizacion" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let canalFinal: "email" | "whatsapp_chatwoot" | "manual" = data.canal;
|
||||||
|
let destinoFinal = "";
|
||||||
|
|
||||||
|
const totales = calcularTotalesCotizacion(cot.servicios, {
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
});
|
||||||
|
const partesResumen: string[] = [];
|
||||||
|
if (totales.totalUnico > 0) partesResumen.push(`Único: ${formatCurrency(totales.totalUnico)}`);
|
||||||
|
if (totales.totalMensual > 0) partesResumen.push(`Mensual: ${formatCurrency(totales.totalMensual)}/mes`);
|
||||||
|
const resumenTotales = partesResumen.length ? partesResumen.join(" · ") : "$0";
|
||||||
|
const vigenciaTexto = formatDate(cot.vigencia);
|
||||||
|
|
||||||
|
if (data.canal === "manual") {
|
||||||
|
if (actor.type !== "user" || actor.role !== "admin") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { motivo: "manual_solo_admin" },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El registro de envio manual esta reservado al administrador humano" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
destinoFinal = data.destino || cot.cliente.email || cot.cliente.telefono || "manual";
|
||||||
|
} else if (data.canal === "email") {
|
||||||
|
destinoFinal = (data.destino || cot.cliente.email || "").trim();
|
||||||
|
if (!destinoFinal) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El cliente no tiene correo electronico registrado y no se proporciono destino" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pdf = await generarPDFCotizacion(id);
|
||||||
|
if (!pdf) {
|
||||||
|
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const envio = await enviarCotizacionPorCorreo({
|
||||||
|
to: destinoFinal,
|
||||||
|
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 (!envio.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_error",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { canal: "email", destino: destinoFinal, omitido: envio.omitido, error: envio.error },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: envio.omitido
|
||||||
|
? "SMTP no esta configurado en el servidor"
|
||||||
|
: `Fallo el envio por correo: ${envio.error || "error desconocido"}`,
|
||||||
|
omitido: envio.omitido ?? false,
|
||||||
|
},
|
||||||
|
{ status: envio.omitido ? 503 : 502 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (data.canal === "whatsapp_chatwoot") {
|
||||||
|
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);
|
||||||
|
if (!pdf) {
|
||||||
|
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const mensajeWa =
|
||||||
|
data.mensaje?.trim() ||
|
||||||
|
`Hola ${cot.cliente.nombre}, te compartimos la cotización ${cot.numero} para ${cot.proyecto} (${resumenTotales}, vigencia al ${vigenciaTexto}).`;
|
||||||
|
|
||||||
|
const waRes = await invocarEnvioWhatsAppN8n({
|
||||||
|
cotizacionId: cot.id,
|
||||||
|
numero: cot.numero,
|
||||||
|
folio: cot.numero,
|
||||||
|
estado: cot.estado,
|
||||||
|
aprobadaAt: cot.aprobadaAt ? cot.aprobadaAt.toISOString() : null,
|
||||||
|
cliente: {
|
||||||
|
nombre: cot.cliente.nombre,
|
||||||
|
empresa: cot.cliente.empresa,
|
||||||
|
telefono: cot.cliente.telefono,
|
||||||
|
email: cot.cliente.email,
|
||||||
|
},
|
||||||
|
destino: destinoFinal,
|
||||||
|
chatwootConversationId: data.chatwootConversationId ?? null,
|
||||||
|
mensaje: mensajeWa,
|
||||||
|
pdfFilename: pdf.filename,
|
||||||
|
pdfBase64: pdf.buffer.toString("base64"),
|
||||||
|
pdfUrl: `${appBaseUrl()}/api/export/pdf/${cot.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!waRes.delivered) {
|
||||||
|
if (waRes.reason === "outside_24h_window") {
|
||||||
|
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: `WhatsApp fuera de ventana de 24h y fallo el respaldo por correo: ${emailRes.error || "SMTP no disponible"}`,
|
||||||
|
reason: "outside_24h_window",
|
||||||
|
},
|
||||||
|
{ status: 502 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
canalFinal = "email";
|
||||||
|
destinoFinal = cot.cliente.email;
|
||||||
|
} else {
|
||||||
|
const notificadoJareth = await notificarJarethWhatsAppFueraVentana(
|
||||||
|
cot,
|
||||||
|
destinoFinal,
|
||||||
|
waRes.error
|
||||||
|
);
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_fuera_ventana",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { canal: "whatsapp_chatwoot", destino: destinoFinal, notificadoJareth },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: "Fuera de ventana de 24h en WhatsApp",
|
||||||
|
reason: "outside_24h_window",
|
||||||
|
notificadoJareth,
|
||||||
|
},
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar_error",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { canal: "whatsapp_chatwoot", destino: destinoFinal, reason: waRes.reason, error: waRes.error },
|
||||||
|
});
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: waRes.error || "Fallo el envio por WhatsApp",
|
||||||
|
reason: waRes.reason || "whatsapp_error",
|
||||||
|
},
|
||||||
|
{ status: 502 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const enviadaPor =
|
||||||
|
actor.type === "agent" ? `agent:${actor.nombre}` : `user:${actor.email || actor.userId}`;
|
||||||
|
|
||||||
|
const updated = await prisma.cotizacion.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
estado: "enviada",
|
||||||
|
enviadaAt: now,
|
||||||
|
enviadaPor,
|
||||||
|
enviadaCanal: canalFinal,
|
||||||
|
enviadaDestino: destinoFinal,
|
||||||
|
},
|
||||||
|
include: { cliente: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.enviar",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
numero: updated.numero,
|
||||||
|
canal: canalFinal,
|
||||||
|
destino: destinoFinal,
|
||||||
|
fallbackUsado: data.canal === "whatsapp_chatwoot" && canalFinal === "email",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalWebhook = Number((totales.totalUnico + totales.totalMensual).toFixed(2));
|
||||||
|
|
||||||
|
void emitirWebhook("cotizacion.enviada", {
|
||||||
|
cotizacionId: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
folio: updated.numero,
|
||||||
|
titulo: updated.proyecto,
|
||||||
|
proyecto: updated.proyecto,
|
||||||
|
moneda: updated.moneda,
|
||||||
|
total: totalWebhook,
|
||||||
|
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||||
|
estado: "enviada",
|
||||||
|
enviadaAt: now.toISOString(),
|
||||||
|
enviadaPor,
|
||||||
|
enviadaCanal: canalFinal,
|
||||||
|
enviadaDestino: destinoFinal,
|
||||||
|
cliente: {
|
||||||
|
id: updated.cliente.id,
|
||||||
|
nombre: updated.cliente.nombre,
|
||||||
|
empresa: updated.cliente.empresa,
|
||||||
|
email: updated.cliente.email,
|
||||||
|
telefono: updated.cliente.telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
id: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
estado: updated.estado,
|
||||||
|
enviadaAt: updated.enviadaAt,
|
||||||
|
enviadaCanal: updated.enviadaCanal,
|
||||||
|
enviadaDestino: updated.enviadaDestino,
|
||||||
|
enviadaPor: updated.enviadaPor,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(res, rateLimitHeaders);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { calcularTotalesCotizacion, ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { appBaseUrl, validarTransicionEstado } from "@/lib/aprobacion";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
||||||
|
|
||||||
|
const estadoSchema = z.object({
|
||||||
|
estado: z.enum(ESTADOS_COTIZACION),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function PATCH(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
staffOnly: true,
|
||||||
|
accionBloqueo: "cotizacion.estado_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
const parsed = estadoSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: `Estado invalido. Permitidos: ${ESTADOS_COTIZACION.join(", ")}` },
|
||||||
|
{ status: 400 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nuevoEstado = parsed.data.estado;
|
||||||
|
|
||||||
|
const existing = await prisma.cotizacion.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { cliente: true, servicios: true },
|
||||||
|
});
|
||||||
|
if (!existing) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const validacion = validarTransicionEstado({
|
||||||
|
actual: existing.estado,
|
||||||
|
nuevo: nuevoEstado,
|
||||||
|
actor,
|
||||||
|
viaEndpoint: "estado",
|
||||||
|
aprobadaAt: existing.aprobadaAt,
|
||||||
|
});
|
||||||
|
if (!validacion.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion:
|
||||||
|
nuevoEstado === "aprobada"
|
||||||
|
? "cotizacion.aprobar_bloqueado"
|
||||||
|
: "cotizacion.estado_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { actual: existing.estado, intento: nuevoEstado, error: validacion.error },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const updateData: Record<string, unknown> = { estado: nuevoEstado };
|
||||||
|
if (nuevoEstado === "aprobada") {
|
||||||
|
updateData.aprobadaAt = now;
|
||||||
|
updateData.aprobadaPorId = actor.type === "user" ? actor.userId : null;
|
||||||
|
updateData.aprobacionMetodo = "web_admin";
|
||||||
|
} else if (nuevoEstado === "borrador") {
|
||||||
|
updateData.aprobadaAt = null;
|
||||||
|
updateData.aprobadaPorId = null;
|
||||||
|
updateData.aprobacionMetodo = null;
|
||||||
|
} else if (nuevoEstado === "aceptada") {
|
||||||
|
updateData.aceptadaAt = now;
|
||||||
|
} else if (nuevoEstado === "rechazada") {
|
||||||
|
updateData.rechazadaAt = now;
|
||||||
|
} else if (nuevoEstado === "vencida") {
|
||||||
|
updateData.vencidaAt = now;
|
||||||
|
} else if (nuevoEstado === "enviada") {
|
||||||
|
updateData.enviadaAt = now;
|
||||||
|
updateData.enviadaCanal = "manual";
|
||||||
|
updateData.enviadaPor = actor.type === "user" ? `user:${actor.email || actor.userId}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await prisma.cotizacion.update({
|
||||||
|
where: { id },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: `cotizacion.estado_${nuevoEstado}`,
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { anterior: existing.estado, nuevo: nuevoEstado },
|
||||||
|
});
|
||||||
|
|
||||||
|
const mapEvento: Partial<Record<string, EventoWebhook>> = {
|
||||||
|
aprobada: "cotizacion.aprobada",
|
||||||
|
enviada: "cotizacion.enviada",
|
||||||
|
aceptada: "cotizacion.aceptada",
|
||||||
|
rechazada: "cotizacion.rechazada",
|
||||||
|
vencida: "cotizacion.vencida",
|
||||||
|
};
|
||||||
|
const ev = mapEvento[nuevoEstado];
|
||||||
|
if (ev && nuevoEstado !== existing.estado) {
|
||||||
|
const tot = calcularTotalesCotizacion(existing.servicios, { incluirIva: existing.incluirIva });
|
||||||
|
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||||
|
void emitirWebhook(ev, {
|
||||||
|
cotizacionId: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
folio: updated.numero,
|
||||||
|
titulo: updated.proyecto,
|
||||||
|
proyecto: updated.proyecto,
|
||||||
|
moneda: updated.moneda,
|
||||||
|
total: totalWebhook,
|
||||||
|
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||||
|
estado: updated.estado,
|
||||||
|
timestamp: now.toISOString(),
|
||||||
|
cliente: {
|
||||||
|
id: existing.cliente.id,
|
||||||
|
nombre: existing.cliente.nombre,
|
||||||
|
empresa: existing.cliente.empresa,
|
||||||
|
email: existing.cliente.email,
|
||||||
|
telefono: existing.cliente.telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
const schema = z.object({
|
const schema = z.object({
|
||||||
servicioId: z.string().min(1),
|
servicioId: z.string().min(1),
|
||||||
@@ -13,12 +15,54 @@ export async function PATCH(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cotizaciones:borrador"],
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
|
||||||
|
const cot = await prisma.cotizacion.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { id: true, estado: true },
|
||||||
|
});
|
||||||
|
if (!cot) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actor.type === "agent" && cot.estado !== "borrador") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.editar_precio_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { estadoActual: cot.estado },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Los agentes solo pueden modificar precios en cotizaciones en borrador" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const parsed = schema.safeParse(body);
|
const parsed = schema.safeParse(body);
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,7 +73,10 @@ export async function PATCH(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!serv) {
|
if (!serv) {
|
||||||
return NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await prisma.servicioCotizado.update({
|
await prisma.servicioCotizado.update({
|
||||||
@@ -37,7 +84,17 @@ export async function PATCH(
|
|||||||
data: { precio },
|
data: { precio },
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.actualizar_precio",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { servicioId, precioAnterior: serv.precio, precioNuevo: precio },
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json({ ok: true }), 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 });
|
||||||
|
|||||||
@@ -3,6 +3,15 @@ import { prisma } from "@/lib/db";
|
|||||||
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||||
import { cotizacionPutSchema } from "@/lib/schemas";
|
import { cotizacionPutSchema } from "@/lib/schemas";
|
||||||
import { asesorPublicoSelect } from "@/lib/cotizaciones";
|
import { asesorPublicoSelect } from "@/lib/cotizaciones";
|
||||||
|
import {
|
||||||
|
applyHeaders,
|
||||||
|
coincideContacto,
|
||||||
|
esAgenteSoloAceptadas,
|
||||||
|
requireActor,
|
||||||
|
} from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { validarTransicionEstado } from "@/lib/aprobacion";
|
||||||
|
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
||||||
|
|
||||||
export async function DELETE(
|
export async function DELETE(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
@@ -10,15 +19,30 @@ export async function DELETE(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
staffOnly: true,
|
||||||
|
accionBloqueo: "cotizacion.eliminar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const cot = await prisma.cotizacion.findUnique({ where: { id } });
|
const cot = await prisma.cotizacion.findUnique({ where: { id } });
|
||||||
if (!cot) {
|
if (!cot) {
|
||||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
await prisma.$transaction([
|
await prisma.$transaction([prisma.cotizacion.delete({ where: { id } })]);
|
||||||
prisma.cotizacion.delete({ where: { id } }),
|
|
||||||
]);
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "cotizacion.eliminar",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { numero: cot.numero },
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
@@ -33,6 +57,16 @@ export async function GET(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cotizaciones:leer", "cotizaciones:leer_aceptadas"],
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const soloAceptadas = esAgenteSoloAceptadas(actor);
|
||||||
|
|
||||||
const cot = await prisma.cotizacion.findUnique({
|
const cot = await prisma.cotizacion.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
@@ -43,51 +77,257 @@ export async function GET(
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!cot) {
|
if (!cot) {
|
||||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return NextResponse.json(cot);
|
|
||||||
|
if (soloAceptadas && cot.estado !== "aceptada") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.leer_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { estadoActual: cot.estado },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Tu clave solo permite consultar cotizaciones aceptadas" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const verificarContacto = request.nextUrl.searchParams.get("verificarContacto")?.trim();
|
||||||
|
if (verificarContacto && !coincideContacto(verificarContacto, cot.cliente)) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.verificar_contacto_fallo",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { motivo: "contacto_no_coincide" },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "El contacto verificado no coincide con el cliente de esta cotizacion" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const salida = soloAceptadas ? { ...cot, observacionesInternas: null } : cot;
|
||||||
|
return applyHeaders(NextResponse.json(salida), 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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function datosPorTransicion(nuevoEstado: string, actorUserId?: string) {
|
||||||
|
const now = new Date();
|
||||||
|
if (nuevoEstado === "aprobada") {
|
||||||
|
return {
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaAt: now,
|
||||||
|
aprobadaPorId: actorUserId ?? null,
|
||||||
|
aprobacionMetodo: "web_admin",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (nuevoEstado === "borrador") {
|
||||||
|
return {
|
||||||
|
estado: "borrador",
|
||||||
|
aprobadaAt: null,
|
||||||
|
aprobadaPorId: null,
|
||||||
|
aprobacionMetodo: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (nuevoEstado === "enviada") {
|
||||||
|
return { estado: "enviada", enviadaAt: now, enviadaCanal: "manual" };
|
||||||
|
}
|
||||||
|
if (nuevoEstado === "aceptada") {
|
||||||
|
return { estado: "aceptada", aceptadaAt: now };
|
||||||
|
}
|
||||||
|
if (nuevoEstado === "rechazada") {
|
||||||
|
return { estado: "rechazada", rechazadaAt: now };
|
||||||
|
}
|
||||||
|
if (nuevoEstado === "vencida") {
|
||||||
|
return { estado: "vencida", vencidaAt: now };
|
||||||
|
}
|
||||||
|
return { estado: nuevoEstado };
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventoPorEstado(estado: string): EventoWebhook | null {
|
||||||
|
if (estado === "aprobada") return "cotizacion.aprobada";
|
||||||
|
if (estado === "enviada") return "cotizacion.enviada";
|
||||||
|
if (estado === "aceptada") return "cotizacion.aceptada";
|
||||||
|
if (estado === "rechazada") return "cotizacion.rechazada";
|
||||||
|
if (estado === "vencida") return "cotizacion.vencida";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cotizaciones:borrador"],
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
|
||||||
// Camino rápido: cambio de estado puntual (CambiarEstadoButtons envía solo
|
const existing = await prisma.cotizacion.findUnique({
|
||||||
// { estado }). El schema completo exige todos los campos de la cotización,
|
where: { id },
|
||||||
// así que un PUT con solo el estado fallaría la validación; lo tratamos
|
include: { cliente: true },
|
||||||
// como un patch parcial.
|
});
|
||||||
const bodyKeys = Object.keys(body);
|
|
||||||
if (bodyKeys.length === 1 && bodyKeys[0] === "estado") {
|
|
||||||
const nuevoEstado = body.estado;
|
|
||||||
if (!ESTADOS_COTIZACION.includes(nuevoEstado as typeof ESTADOS_COTIZACION[number])) {
|
|
||||||
return NextResponse.json({ error: "Estado invalido" }, { status: 400 });
|
|
||||||
}
|
|
||||||
const existing = await prisma.cotizacion.findUnique({ where: { id } });
|
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Camino rapido: cambio de estado puntual ({ estado })
|
||||||
|
const bodyKeys = Object.keys(body || {});
|
||||||
|
if (bodyKeys.length === 1 && bodyKeys[0] === "estado") {
|
||||||
|
const nuevoEstado = String(body.estado || "");
|
||||||
|
const validacion = validarTransicionEstado({
|
||||||
|
actual: existing.estado,
|
||||||
|
nuevo: nuevoEstado,
|
||||||
|
actor,
|
||||||
|
viaEndpoint: "put",
|
||||||
|
aprobadaAt: existing.aprobadaAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!validacion.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion:
|
||||||
|
nuevoEstado === "aprobada"
|
||||||
|
? "cotizacion.aprobar_bloqueado"
|
||||||
|
: "cotizacion.estado_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { actual: existing.estado, intento: nuevoEstado, error: validacion.error },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dataEstado = datosPorTransicion(
|
||||||
|
nuevoEstado,
|
||||||
|
actor.type === "user" ? actor.userId : undefined
|
||||||
|
);
|
||||||
const updated = await prisma.cotizacion.update({
|
const updated = await prisma.cotizacion.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { estado: nuevoEstado },
|
data: dataEstado,
|
||||||
});
|
});
|
||||||
return NextResponse.json(updated);
|
|
||||||
|
if (nuevoEstado === "aprobada") {
|
||||||
|
await prisma.approvalToken.updateMany({
|
||||||
|
where: { cotizacionId: id, usadoAt: null },
|
||||||
|
data: { expiraAt: new Date() },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: `cotizacion.estado_${nuevoEstado}`,
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { anterior: existing.estado, nuevo: nuevoEstado },
|
||||||
|
});
|
||||||
|
|
||||||
|
const ev = eventoPorEstado(nuevoEstado);
|
||||||
|
if (ev && nuevoEstado !== existing.estado) {
|
||||||
|
void emitirWebhook(ev, {
|
||||||
|
cotizacionId: updated.id,
|
||||||
|
numero: updated.numero,
|
||||||
|
estado: updated.estado,
|
||||||
|
cliente: {
|
||||||
|
id: existing.cliente.id,
|
||||||
|
nombre: existing.cliente.nombre,
|
||||||
|
empresa: existing.cliente.empresa,
|
||||||
|
email: existing.cliente.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si es agente, SOLO puede editar cotizaciones en borrador y NUNCA cambiar estado
|
||||||
|
if (actor.type === "agent") {
|
||||||
|
if (existing.estado !== "borrador") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.editar_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { estadoActual: existing.estado },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Los agentes solo pueden editar cotizaciones en estado borrador" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (body.estado && body.estado !== "borrador") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion:
|
||||||
|
body.estado === "aprobada"
|
||||||
|
? "cotizacion.aprobar_bloqueado"
|
||||||
|
: "cotizacion.estado_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { actual: existing.estado, intento: body.estado },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Los agentes no pueden cambiar el estado de la cotizacion al editarla" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsed = cotizacionPutSchema.safeParse(body);
|
const parsed = cotizacionPutSchema.safeParse(body);
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
fecha,
|
fecha,
|
||||||
vigencia,
|
vigencia,
|
||||||
@@ -106,11 +346,39 @@ export async function PUT(
|
|||||||
servicios,
|
servicios,
|
||||||
planBucefalo,
|
planBucefalo,
|
||||||
} = parsed.data;
|
} = parsed.data;
|
||||||
const estado = body.estado;
|
const estadoSolicitado = body.estado as string | undefined;
|
||||||
|
|
||||||
const existing = await prisma.cotizacion.findUnique({ where: { id } });
|
let extraEstadoData: Record<string, unknown> = {};
|
||||||
if (!existing) {
|
if (estadoSolicitado && estadoSolicitado !== existing.estado) {
|
||||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
const validacion = validarTransicionEstado({
|
||||||
|
actual: existing.estado,
|
||||||
|
nuevo: estadoSolicitado,
|
||||||
|
actor,
|
||||||
|
viaEndpoint: "put",
|
||||||
|
aprobadaAt: existing.aprobadaAt,
|
||||||
|
});
|
||||||
|
if (!validacion.ok) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion:
|
||||||
|
estadoSolicitado === "aprobada"
|
||||||
|
? "cotizacion.aprobar_bloqueado"
|
||||||
|
: "cotizacion.estado_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { actual: existing.estado, intento: estadoSolicitado, error: validacion.error },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
extraEstadoData = datosPorTransicion(
|
||||||
|
estadoSolicitado,
|
||||||
|
actor.type === "user" ? actor.userId : undefined
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let clienteIdFinal: string | undefined;
|
let clienteIdFinal: string | undefined;
|
||||||
@@ -161,20 +429,23 @@ export async function PUT(
|
|||||||
...(esDoble !== undefined && { opcionesMetadata: esDoble ? opciones ?? {} : undefined }),
|
...(esDoble !== undefined && { opcionesMetadata: esDoble ? opciones ?? {} : undefined }),
|
||||||
...(observaciones !== undefined && { observaciones }),
|
...(observaciones !== undefined && { observaciones }),
|
||||||
...(observacionesInternas !== undefined && { observacionesInternas }),
|
...(observacionesInternas !== undefined && { observacionesInternas }),
|
||||||
...(estado && ESTADOS_COTIZACION.includes(estado as typeof ESTADOS_COTIZACION[number]) && { estado }),
|
...(estadoSolicitado &&
|
||||||
|
ESTADOS_COTIZACION.includes(estadoSolicitado as (typeof ESTADOS_COTIZACION)[number]) &&
|
||||||
|
extraEstadoData),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (servicios && Array.isArray(servicios)) {
|
if (servicios && Array.isArray(servicios)) {
|
||||||
// El servicio Bucéfalo del catálogo se resuelve una sola vez, no por partida.
|
|
||||||
const necesitaBucefalo = servicios.some(
|
const necesitaBucefalo = servicios.some(
|
||||||
(s) => !s.esPersonalizado && s.catalogoId?.startsWith("bucefalo-")
|
(s) => !s.esPersonalizado && s.catalogoId?.startsWith("bucefalo-")
|
||||||
);
|
);
|
||||||
const bucefaloCatalogoId = necesitaBucefalo
|
const bucefaloCatalogoId = necesitaBucefalo
|
||||||
? (await prisma.servicioCatalogo.findFirst({
|
? (
|
||||||
|
await prisma.servicioCatalogo.findFirst({
|
||||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
}))?.id ?? null
|
})
|
||||||
|
)?.id ?? null
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
await prisma.$transaction(async (tx) => {
|
await prisma.$transaction(async (tx) => {
|
||||||
@@ -203,7 +474,6 @@ export async function PUT(
|
|||||||
opcion: esDobleFinal ? serv.opcion ?? "ambas" : null,
|
opcion: esDobleFinal ? serv.opcion ?? "ambas" : null,
|
||||||
fase: serv.fase,
|
fase: serv.fase,
|
||||||
tipoPago: serv.tipoPago,
|
tipoPago: serv.tipoPago,
|
||||||
// "demanda": tarifa por hora sin compromiso; nunca suma al total.
|
|
||||||
precio: serv.modeloCobro === "demanda" ? 0 : serv.precio,
|
precio: serv.modeloCobro === "demanda" ? 0 : serv.precio,
|
||||||
tiempoEntrega: serv.tiempoEntrega,
|
tiempoEntrega: serv.tiempoEntrega,
|
||||||
entregables: serv.entregables,
|
entregables: serv.entregables,
|
||||||
@@ -234,7 +504,17 @@ export async function PUT(
|
|||||||
include: { cliente: true, asesor: { select: asesorPublicoSelect }, servicios: true },
|
include: { cliente: true, asesor: { select: asesorPublicoSelect }, servicios: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(updated);
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.actualizar",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { numero: existing.numero },
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
console.error("Error updating cotizacion:", error);
|
console.error("Error updating cotizacion:", error);
|
||||||
const msg = error instanceof Error ? error.message : "Error interno";
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||||
|
import { crearEnlaceAprobacion, notificarJarethBorrador } from "@/lib/aprobacion";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["cotizaciones:borrador"],
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
|
||||||
|
const cot = await prisma.cotizacion.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { cliente: true, servicios: true },
|
||||||
|
});
|
||||||
|
if (!cot) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (cot.estado !== "borrador") {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: `Solo se puede solicitar aprobacion en estado borrador (actual: ${cot.estado})` },
|
||||||
|
{ status: 409 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const enlace = await crearEnlaceAprobacion(id);
|
||||||
|
const actorEtiqueta = actor.type === "agent" ? `Agente: ${actor.nombre}` : actor.name;
|
||||||
|
const aviso = await notificarJarethBorrador(cot, enlace, actorEtiqueta);
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.solicitar_aprobacion",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
numero: cot.numero,
|
||||||
|
correoEnviado: aviso.ok,
|
||||||
|
omitido: aviso.omitido ?? false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Nunca exponer el enlace/token raw en la respuesta para que un agente no pueda auto-aprobarse.
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({
|
||||||
|
ok: true,
|
||||||
|
cotizacionId: id,
|
||||||
|
numero: cot.numero,
|
||||||
|
expiraAt: enlace.expiraAt.toISOString(),
|
||||||
|
correoEnviado: aviso.ok,
|
||||||
|
correoOmitido: aviso.omitido ?? false,
|
||||||
|
}),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,32 +1,76 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import type { Prisma } from "@/generated/prisma/client";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { cotizacionPostSchema } from "@/lib/schemas";
|
import { cotizacionPostSchema } from "@/lib/schemas";
|
||||||
import { requireStaff } from "@/lib/auth";
|
import {
|
||||||
import { bucefaloPrecio, calcularVigencia } from "@/lib/calculators";
|
applyHeaders,
|
||||||
|
esAgenteSoloAceptadas,
|
||||||
|
requireActor,
|
||||||
|
} from "@/lib/agent-auth";
|
||||||
|
import { withIdempotency } from "@/lib/idempotency";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import {
|
||||||
|
appBaseUrl,
|
||||||
|
crearEnlaceAprobacion,
|
||||||
|
notificarJarethBorrador,
|
||||||
|
} from "@/lib/aprobacion";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
|
import {
|
||||||
|
bucefaloPrecio,
|
||||||
|
calcularTotalesCotizacion,
|
||||||
|
calcularVigencia,
|
||||||
|
} from "@/lib/calculators";
|
||||||
import { errorValidacion } from "@/lib/catalogo";
|
import { errorValidacion } from "@/lib/catalogo";
|
||||||
import { asesorPublicoSelect, siguienteNumeroCotizacion } from "@/lib/cotizaciones";
|
import { asesorPublicoSelect, siguienteNumeroCotizacion } from "@/lib/cotizaciones";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["cotizaciones:borrador"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "cotizacion",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const body = await request.json().catch(() => null);
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||||
|
|
||||||
|
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||||
const parsed = cotizacionPostSchema.safeParse(body);
|
const parsed = cotizacionPostSchema.safeParse(body);
|
||||||
if (!parsed.success) return errorValidacion(parsed.error);
|
if (!parsed.success) return errorValidacion(parsed.error);
|
||||||
|
|
||||||
// Defaults del servidor para altas por API/CLI: asesor = usuario de la
|
// Resolver asesorId: para usuario humano usa su propia sesion; para agente
|
||||||
// sesion, fecha = hoy, vigencia = 15 dias habiles, numero = consecutivo.
|
// usa el primer usuario admin si no se indico asesorId.
|
||||||
const asesorId = parsed.data.asesorId ?? session.userId;
|
let asesorId = parsed.data.asesorId;
|
||||||
|
if (!asesorId) {
|
||||||
|
if (actor.type === "user") {
|
||||||
|
asesorId = actor.userId;
|
||||||
|
} else {
|
||||||
|
const admin = await prisma.user.findFirst({
|
||||||
|
where: { role: "admin" },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!admin) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "No existe un usuario administrador para asignar como asesor" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
asesorId = admin.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const asesor = await prisma.user.findUnique({
|
const asesor = await prisma.user.findUnique({
|
||||||
where: { id: asesorId },
|
where: { id: asesorId },
|
||||||
select: { id: true, name: true },
|
select: { id: true, name: true },
|
||||||
});
|
});
|
||||||
if (!asesor) {
|
if (!asesor) {
|
||||||
return NextResponse.json({ error: `asesorId: no existe el usuario ${asesorId}` }, { status: 400 });
|
return NextResponse.json(
|
||||||
|
{ error: `asesorId: no existe el usuario ${asesorId}` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fecha = parsed.data.fecha ?? new Date();
|
const fecha = parsed.data.fecha ?? new Date();
|
||||||
const vigencia = parsed.data.vigencia ?? calcularVigencia(fecha);
|
const vigencia = parsed.data.vigencia ?? calcularVigencia(fecha);
|
||||||
const numero = parsed.data.numero ?? (await siguienteNumeroCotizacion(asesor.name));
|
const numero = parsed.data.numero ?? (await siguienteNumeroCotizacion(asesor.name));
|
||||||
@@ -69,16 +113,16 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const clienteIdFinal = clienteRecord.id;
|
const clienteIdFinal = clienteRecord.id;
|
||||||
|
|
||||||
// El servicio Bucéfalo del catálogo es el mismo para todas las partidas:
|
|
||||||
// se resuelve una sola vez fuera del loop de inserción.
|
|
||||||
const necesitaBucefalo = servicios.some(
|
const necesitaBucefalo = servicios.some(
|
||||||
(s) => !s.esPersonalizado && s.catalogoId.startsWith("bucefalo-")
|
(s) => !s.esPersonalizado && s.catalogoId.startsWith("bucefalo-")
|
||||||
);
|
);
|
||||||
const bucefaloCatalogoId = necesitaBucefalo
|
const bucefaloCatalogoId = necesitaBucefalo
|
||||||
? (await prisma.servicioCatalogo.findFirst({
|
? (
|
||||||
|
await prisma.servicioCatalogo.findFirst({
|
||||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
}))?.id ?? null
|
})
|
||||||
|
)?.id ?? null
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const cotizacion = await prisma.$transaction(async (tx) => {
|
const cotizacion = await prisma.$transaction(async (tx) => {
|
||||||
@@ -100,7 +144,9 @@ export async function POST(request: NextRequest) {
|
|||||||
observacionesInternas: observacionesInternas || null,
|
observacionesInternas: observacionesInternas || null,
|
||||||
clienteId: clienteIdFinal,
|
clienteId: clienteIdFinal,
|
||||||
asesorId,
|
asesorId,
|
||||||
|
// SIEMPRE nace en borrador, aunque el body intente enviar otro estado.
|
||||||
estado: "borrador",
|
estado: "borrador",
|
||||||
|
creadaPorAgente: actor.type === "agent" ? actor.nombre : null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -151,7 +197,81 @@ export async function POST(request: NextRequest) {
|
|||||||
return cot;
|
return cot;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const totales = calcularTotalesCotizacion(
|
||||||
|
servicios.map((s) => ({
|
||||||
|
tipoPago: s.tipoPago,
|
||||||
|
precio: s.modeloCobro === "demanda" ? 0 : s.precio,
|
||||||
|
seleccionado: true,
|
||||||
|
})),
|
||||||
|
{ incluirIva: cotizacion.incluirIva }
|
||||||
|
);
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.crear",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: cotizacion.id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: {
|
||||||
|
numero: cotizacion.numero,
|
||||||
|
clienteId: clienteIdFinal,
|
||||||
|
creadaPorAgente: cotizacion.creadaPorAgente,
|
||||||
|
totalUnico: totales.totalUnico,
|
||||||
|
totalMensual: totales.totalMensual,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Flujo de aprobacion cuando la crea un agente (el enlace firmado solo va por correo a Jareth)
|
||||||
|
if (actor.type === "agent") {
|
||||||
|
const enlace = await crearEnlaceAprobacion(cotizacion.id);
|
||||||
|
void notificarJarethBorrador(
|
||||||
|
{
|
||||||
|
id: cotizacion.id,
|
||||||
|
numero: cotizacion.numero,
|
||||||
|
proyecto: cotizacion.proyecto,
|
||||||
|
moneda: cotizacion.moneda,
|
||||||
|
vigencia: cotizacion.vigencia,
|
||||||
|
incluirIva: cotizacion.incluirIva,
|
||||||
|
cliente: { nombre: clienteRecord.nombre, empresa: clienteRecord.empresa },
|
||||||
|
servicios: servicios.map((s) => ({
|
||||||
|
tipoPago: s.tipoPago,
|
||||||
|
precio: s.modeloCobro === "demanda" ? 0 : s.precio,
|
||||||
|
seleccionado: true,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
enlace,
|
||||||
|
`Agente: ${actor.nombre}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Webhook cotizacion.creada (sin exponer el token raw de un solo uso)
|
||||||
|
void emitirWebhook("cotizacion.creada", {
|
||||||
|
cotizacionId: cotizacion.id,
|
||||||
|
numero: cotizacion.numero,
|
||||||
|
folio: cotizacion.numero,
|
||||||
|
titulo: cotizacion.proyecto,
|
||||||
|
estado: "borrador",
|
||||||
|
proyecto: cotizacion.proyecto,
|
||||||
|
moneda: cotizacion.moneda,
|
||||||
|
total: Number((totales.totalUnico + totales.totalMensual).toFixed(2)),
|
||||||
|
url: `${appBaseUrl()}/cotizaciones/${cotizacion.id}`,
|
||||||
|
creadaPorAgente: cotizacion.creadaPorAgente,
|
||||||
|
totales,
|
||||||
|
adminReviewUrl: `${appBaseUrl()}/cotizaciones/${cotizacion.id}`,
|
||||||
|
cliente: {
|
||||||
|
id: clienteRecord.id,
|
||||||
|
nombre: clienteRecord.nombre,
|
||||||
|
empresa: clienteRecord.empresa,
|
||||||
|
email: clienteRecord.email,
|
||||||
|
telefono: clienteRecord.telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json(cotizacion, { status: 201 });
|
return NextResponse.json(cotizacion, { status: 201 });
|
||||||
|
});
|
||||||
|
|
||||||
|
return applyHeaders(res, rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
console.error("Error creating cotizacion:", error);
|
console.error("Error creating cotizacion:", error);
|
||||||
const message = error instanceof Error ? error.message : "Error interno";
|
const message = error instanceof Error ? error.message : "Error interno";
|
||||||
@@ -160,29 +280,91 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GET /api/cotizaciones — lista, de la mas reciente a la mas antigua.
|
// GET /api/cotizaciones — lista, de la mas reciente a la mas antigua.
|
||||||
// Filtros opcionales: ?estado=borrador|enviada|aprobada|rechazada,
|
// Filtros opcionales: ?estado=, ?clienteId=, ?q=, ?clienteEmail=,
|
||||||
// ?clienteId=..., ?q=texto (numero, cliente o empresa), ?limit=N.
|
// ?clienteTelefono=, ?desde=, ?hasta=, ?page=, ?limit=.
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await requireStaff();
|
const auth = await requireActor(request, {
|
||||||
if (!session) {
|
scopes: ["cotizaciones:leer", "cotizaciones:leer_aceptadas"],
|
||||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
recursoTipo: "cotizacion",
|
||||||
}
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
const soloAceptadas = esAgenteSoloAceptadas(actor);
|
||||||
|
|
||||||
const sp = request.nextUrl.searchParams;
|
const sp = request.nextUrl.searchParams;
|
||||||
const estado = sp.get("estado");
|
const estadoParam = sp.get("estado");
|
||||||
const clienteId = sp.get("clienteId");
|
const clienteId = sp.get("clienteId");
|
||||||
const q = sp.get("q")?.trim();
|
const q = sp.get("q")?.trim();
|
||||||
|
const clienteEmail = sp.get("clienteEmail")?.trim();
|
||||||
|
const clienteTelefono = sp.get("clienteTelefono")?.trim();
|
||||||
|
const desde = sp.get("desde")?.trim();
|
||||||
|
const hasta = sp.get("hasta")?.trim();
|
||||||
|
const pageRaw = sp.get("page");
|
||||||
const limitRaw = sp.get("limit");
|
const limitRaw = sp.get("limit");
|
||||||
const limit = limitRaw ? Number(limitRaw) : undefined;
|
|
||||||
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
|
if (soloAceptadas && estadoParam && estadoParam !== "aceptada") {
|
||||||
return NextResponse.json({ error: "limit debe ser un entero mayor a 0" }, { status: 400 });
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.leer_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { estadoSolicitado: estadoParam },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Tu clave solo tiene permiso para consultar cotizaciones aceptadas" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cotizaciones = await prisma.cotizacion.findMany({
|
const limit = limitRaw ? Number(limitRaw) : undefined;
|
||||||
where: {
|
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
|
||||||
...(estado && { estado }),
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "limit debe ser un entero entre 1 y 200" }, { status: 400 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = pageRaw ? Number(pageRaw) : undefined;
|
||||||
|
if (page !== undefined && (!Number.isInteger(page) || page < 1)) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "page debe ser un entero mayor a 0" }, { status: 400 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const estadoEfectivo = soloAceptadas ? "aceptada" : estadoParam || undefined;
|
||||||
|
|
||||||
|
const clienteWhere: Prisma.ClienteWhereInput = {};
|
||||||
|
if (clienteEmail) {
|
||||||
|
clienteWhere.email = { equals: clienteEmail, mode: "insensitive" };
|
||||||
|
}
|
||||||
|
if (clienteTelefono) {
|
||||||
|
const digits = clienteTelefono.replace(/\D/g, "");
|
||||||
|
const ultimos = digits.length >= 10 ? digits.slice(-10) : clienteTelefono;
|
||||||
|
clienteWhere.telefono = { contains: ultimos };
|
||||||
|
}
|
||||||
|
|
||||||
|
const fechaWhere: Prisma.DateTimeFilter = {};
|
||||||
|
if (desde) {
|
||||||
|
const d = new Date(desde);
|
||||||
|
if (!Number.isNaN(d.getTime())) fechaWhere.gte = d;
|
||||||
|
}
|
||||||
|
if (hasta) {
|
||||||
|
const h = new Date(hasta);
|
||||||
|
if (!Number.isNaN(h.getTime())) fechaWhere.lte = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
const where: Prisma.CotizacionWhereInput = {
|
||||||
|
...(estadoEfectivo && { estado: estadoEfectivo }),
|
||||||
...(clienteId && { clienteId }),
|
...(clienteId && { clienteId }),
|
||||||
|
...(Object.keys(clienteWhere).length > 0 && { cliente: clienteWhere }),
|
||||||
|
...(Object.keys(fechaWhere).length > 0 && { fecha: fechaWhere }),
|
||||||
...(q && {
|
...(q && {
|
||||||
OR: [
|
OR: [
|
||||||
{ numero: { contains: q, mode: "insensitive" as const } },
|
{ numero: { contains: q, mode: "insensitive" as const } },
|
||||||
@@ -191,9 +373,13 @@ export async function GET(request: NextRequest) {
|
|||||||
{ cliente: { empresa: { contains: q, mode: "insensitive" as const } } },
|
{ cliente: { empresa: { contains: q, mode: "insensitive" as const } } },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
},
|
};
|
||||||
|
|
||||||
|
const cotizaciones = await prisma.cotizacion.findMany({
|
||||||
|
where,
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
take: limit,
|
take: limit,
|
||||||
|
skip: page && limit ? (page - 1) * limit : undefined,
|
||||||
include: {
|
include: {
|
||||||
cliente: true,
|
cliente: true,
|
||||||
asesor: { select: asesorPublicoSelect },
|
asesor: { select: asesorPublicoSelect },
|
||||||
@@ -201,7 +387,12 @@ export async function GET(request: NextRequest) {
|
|||||||
planBucefalo: true,
|
planBucefalo: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return NextResponse.json(cotizaciones);
|
|
||||||
|
const salida = soloAceptadas
|
||||||
|
? cotizaciones.map((c) => ({ ...c, observacionesInternas: null }))
|
||||||
|
: cotizaciones;
|
||||||
|
|
||||||
|
return applyHeaders(NextResponse.json(salida), rateLimitHeaders);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = error instanceof Error ? error.message : "Error interno";
|
const message = error instanceof Error ? error.message : "Error interno";
|
||||||
return NextResponse.json({ error: message }, { status: 500 });
|
return NextResponse.json({ error: message }, { status: 500 });
|
||||||
|
|||||||
@@ -37,8 +37,7 @@ export async function GET(
|
|||||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||||
|
|
||||||
const data: ExcelData = {
|
const data: ExcelData = {
|
||||||
razonSocial: bancaria.razon_social || "Cotizador E3",
|
razonSocial: bancaria.razon_social || "Uriel Jareth Consulting",
|
||||||
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
|
|
||||||
numero: cot.numero,
|
numero: cot.numero,
|
||||||
clienteNombre: cot.cliente.nombre,
|
clienteNombre: cot.cliente.nombre,
|
||||||
clienteEmpresa: cot.cliente.empresa || "",
|
clienteEmpresa: cot.cliente.empresa || "",
|
||||||
@@ -70,8 +69,8 @@ export async function GET(
|
|||||||
opcionesMetadata: cot.opcionesMetadata as never,
|
opcionesMetadata: cot.opcionesMetadata as never,
|
||||||
planBucefaloNivel: cot.planBucefalo?.nivel ?? null,
|
planBucefaloNivel: cot.planBucefalo?.nivel ?? null,
|
||||||
planBucefaloPrecio: cot.planBucefalo?.precio ?? null,
|
planBucefaloPrecio: cot.planBucefalo?.precio ?? null,
|
||||||
colorPrimario: branding.colorPrimario || "#2563eb",
|
colorPrimario: branding.colorPrimario || "#0400C4",
|
||||||
colorSecundario: branding.colorSecundario || "#1e293b",
|
colorSecundario: branding.colorSecundario || "#0F172A",
|
||||||
incluirIva: cot.incluirIva,
|
incluirIva: cot.incluirIva,
|
||||||
// El Excel es un documento del cliente: solo el texto del cliente.
|
// El Excel es un documento del cliente: solo el texto del cliente.
|
||||||
observaciones: cot.observaciones,
|
observaciones: cot.observaciones,
|
||||||
|
|||||||
@@ -48,8 +48,7 @@ export async function POST(request: NextRequest) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const data: ExcelData = {
|
const data: ExcelData = {
|
||||||
razonSocial: bancaria.razon_social || "Cotizador E3",
|
razonSocial: bancaria.razon_social || "Uriel Jareth Consulting",
|
||||||
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
|
|
||||||
numero: "BORRADOR",
|
numero: "BORRADOR",
|
||||||
clienteNombre: draft.clienteNombre,
|
clienteNombre: draft.clienteNombre,
|
||||||
clienteEmpresa: draft.clienteEmpresa,
|
clienteEmpresa: draft.clienteEmpresa,
|
||||||
@@ -78,8 +77,8 @@ export async function POST(request: NextRequest) {
|
|||||||
esDoble: draft.esDoble,
|
esDoble: draft.esDoble,
|
||||||
opcionesMetadata: draft.esDoble ? draft.opciones ?? null : null,
|
opcionesMetadata: draft.esDoble ? draft.opciones ?? null : null,
|
||||||
planBucefaloNivel: draft.planBucefaloNivel,
|
planBucefaloNivel: draft.planBucefaloNivel,
|
||||||
colorPrimario: branding.colorPrimario || "#2563eb",
|
colorPrimario: branding.colorPrimario || "#0400C4",
|
||||||
colorSecundario: branding.colorSecundario || "#1e293b",
|
colorSecundario: branding.colorSecundario || "#0F172A",
|
||||||
observaciones: draft.observaciones,
|
observaciones: draft.observaciones,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { getSession } from "@/lib/auth";
|
import {
|
||||||
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
applyHeaders,
|
||||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
esAgenteSoloAceptadas,
|
||||||
import { sanitizeFilename } from "@/lib/calculators";
|
requireActor,
|
||||||
|
} from "@/lib/agent-auth";
|
||||||
|
import { generarPDFCotizacion } from "@/lib/cotizacion-pdf";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
@@ -11,90 +14,72 @@ export async function GET(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
// Ruta compartida (staff + cliente): el cliente solo puede descargar sus
|
const auth = await requireActor(request, {
|
||||||
// propias cotizaciones; para staff no se toca nada mas del handler.
|
allowCliente: true,
|
||||||
const session = await getSession();
|
scopes: ["cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas"],
|
||||||
if (session?.role === "cliente") {
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { actor, rateLimitHeaders } = auth;
|
||||||
|
|
||||||
|
if (actor.type === "user" && actor.role === "cliente") {
|
||||||
const propia = await prisma.cotizacion.findUnique({
|
const propia = await prisma.cotizacion.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
select: { clienteId: true },
|
select: { clienteId: true },
|
||||||
});
|
});
|
||||||
if (!propia || propia.clienteId !== session.clienteId) {
|
if (!propia || propia.clienteId !== actor.clienteId) {
|
||||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const [cot, config, branding, bonos] = await Promise.all([
|
|
||||||
prisma.cotizacion.findUnique({
|
if (esAgenteSoloAceptadas(actor)) {
|
||||||
|
const estadoRow = await prisma.cotizacion.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: {
|
select: { estado: true },
|
||||||
cliente: true,
|
|
||||||
asesor: true,
|
|
||||||
// orderBy explicito: drawSection abre un encabezado de fase nuevo cada vez
|
|
||||||
// que cambia serv.fase, o sea que asume el array agrupado. Sin esto el orden
|
|
||||||
// lo decide Postgres y el PDF puede salir distinto del Excel del mismo envio.
|
|
||||||
servicios: {
|
|
||||||
include: { servicioCatalogo: true },
|
|
||||||
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
|
||||||
},
|
|
||||||
planBucefalo: true,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
getConfigBancaria(),
|
|
||||||
getConfigBranding(),
|
|
||||||
prisma.bono.findMany({ where: { activo: true }, orderBy: { numero: "asc" } }),
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (!cot) {
|
|
||||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
|
||||||
}
|
|
||||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
|
||||||
const nombre = `${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}`;
|
|
||||||
|
|
||||||
const buffer = await generateCotizacionPDF({
|
|
||||||
numero: cot.numero,
|
|
||||||
clienteNombre: cot.cliente.nombre,
|
|
||||||
clienteEmpresa: cot.cliente.empresa || "",
|
|
||||||
asesorNombre: cot.asesor.name,
|
|
||||||
fecha: cot.fecha,
|
|
||||||
vigencia: cot.vigencia,
|
|
||||||
moneda: cot.moneda,
|
|
||||||
tipoCambio: cot.tipoCambio,
|
|
||||||
proyecto: cot.proyecto,
|
|
||||||
esquemaPago: cot.esquemaPago,
|
|
||||||
servicios: cot.servicios.filter((s) => s.seleccionado).map((s) => ({
|
|
||||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
|
||||||
fase: s.fase,
|
|
||||||
tipoPago: s.tipoPago,
|
|
||||||
precio: s.precio,
|
|
||||||
tiempoEntrega: s.tiempoEntrega,
|
|
||||||
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
|
||||||
esPersonalizado: s.esPersonalizado,
|
|
||||||
horas: s.horas ?? undefined,
|
|
||||||
tarifaHora: s.tarifaHora ?? undefined,
|
|
||||||
modeloCobro: s.modeloCobro ?? undefined,
|
|
||||||
montoMinimo: s.montoMinimo ?? undefined,
|
|
||||||
horasIncluidas: s.horasIncluidas ?? undefined,
|
|
||||||
opcion: s.opcion ?? undefined,
|
|
||||||
})),
|
|
||||||
esDoble: cot.esDoble,
|
|
||||||
opcionesMetadata: cot.opcionesMetadata as never,
|
|
||||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
|
||||||
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
|
|
||||||
incluirBonos: cot.incluirBonos,
|
|
||||||
bonos,
|
|
||||||
incluirIva: cot.incluirIva,
|
|
||||||
// Solo el texto del cliente. observacionesInternas no se pasa nunca.
|
|
||||||
observaciones: cot.observaciones,
|
|
||||||
configBancaria: config,
|
|
||||||
...branding,
|
|
||||||
});
|
});
|
||||||
|
if (!estadoRow) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (estadoRow.estado !== "aceptada") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: "cotizacion.export_pdf_bloqueado",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { estadoActual: estadoRow.estado },
|
||||||
|
});
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json(
|
||||||
|
{ error: "Tu clave solo permite descargar PDF de cotizaciones aceptadas" },
|
||||||
|
{ status: 403 }
|
||||||
|
),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new NextResponse(new Uint8Array(buffer), {
|
const pdf = await generarPDFCotizacion(id);
|
||||||
|
if (!pdf) {
|
||||||
|
return applyHeaders(
|
||||||
|
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||||
|
rateLimitHeaders
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = new NextResponse(new Uint8Array(pdf.buffer), {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/pdf",
|
"Content-Type": "application/pdf",
|
||||||
"Content-Disposition": `attachment; filename="${nombre}.pdf"`,
|
"Content-Disposition": `attachment; filename="${pdf.filename}"`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
return applyHeaders(response, 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 });
|
||||||
|
|||||||
@@ -3,13 +3,25 @@ import { prisma } from "@/lib/db";
|
|||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const APP_VERSION = "2.0.0";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
await prisma.$queryRaw`SELECT 1`;
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
return NextResponse.json({ status: "ok", database: "ok" });
|
return NextResponse.json({
|
||||||
|
status: "ok",
|
||||||
|
database: "ok",
|
||||||
|
version: APP_VERSION,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ status: "error", database: "unreachable" },
|
{
|
||||||
|
status: "error",
|
||||||
|
database: "unreachable",
|
||||||
|
version: APP_VERSION,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
{ status: 503 }
|
{ status: 503 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { AGENT_SCOPES } from "@/lib/agent-auth-core";
|
||||||
|
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||||
|
import { EVENTOS_WEBHOOK } from "@/lib/webhooks-core";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const serverUrl = (process.env.APP_URL || "https://cotizador.urieljareth.org").replace(/\/+$/, "");
|
||||||
|
|
||||||
|
const spec = {
|
||||||
|
openapi: "3.1.0",
|
||||||
|
info: {
|
||||||
|
title: "Cotizador — Uriel Jareth Consulting API",
|
||||||
|
version: "2.0.0",
|
||||||
|
description:
|
||||||
|
"API unificada para agentes de IA y operación comercial de Uriel Jareth Consulting. " +
|
||||||
|
"Autenticación por cookie JWT (usuarios humanos) o X-API-Key / Bearer ujc_live_* (agentes con alcances granulares). " +
|
||||||
|
"Ningún agente puede aprobar cotizaciones: la aprobación es exclusivamente humana (panel admin o enlace firmado de un solo uso).",
|
||||||
|
},
|
||||||
|
servers: [{ url: serverUrl }],
|
||||||
|
components: {
|
||||||
|
securitySchemes: {
|
||||||
|
ApiKeyAuth: {
|
||||||
|
type: "apiKey",
|
||||||
|
in: "header",
|
||||||
|
name: "X-API-Key",
|
||||||
|
description: "Clave de agente con prefijo ujc_live_* y alcances específicos.",
|
||||||
|
},
|
||||||
|
BearerAuth: {
|
||||||
|
type: "http",
|
||||||
|
scheme: "bearer",
|
||||||
|
description: "Misma clave ujc_live_* en Authorization: Bearer <key>.",
|
||||||
|
},
|
||||||
|
CookieAuth: {
|
||||||
|
type: "apiKey",
|
||||||
|
in: "cookie",
|
||||||
|
name: "cotizador-session",
|
||||||
|
description: "Sesión JWT humana (admin / asesor).",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
parameters: {
|
||||||
|
IdempotencyKey: {
|
||||||
|
name: "Idempotency-Key",
|
||||||
|
in: "header",
|
||||||
|
required: false,
|
||||||
|
schema: { type: "string", maxLength: 128 },
|
||||||
|
description: "Clave opcional para reintentos seguros (TTL 24h; 409 si cambia el cuerpo).",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
schemas: {
|
||||||
|
ErrorResponse: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
error: { type: "string" },
|
||||||
|
reason: { type: "string" },
|
||||||
|
},
|
||||||
|
required: ["error"],
|
||||||
|
},
|
||||||
|
AgentScope: {
|
||||||
|
type: "string",
|
||||||
|
enum: [...AGENT_SCOPES],
|
||||||
|
},
|
||||||
|
EstadoCotizacion: {
|
||||||
|
type: "string",
|
||||||
|
enum: [...ESTADOS_COTIZACION],
|
||||||
|
},
|
||||||
|
WebhookEvent: {
|
||||||
|
type: "string",
|
||||||
|
enum: [...EVENTOS_WEBHOOK],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
Unauthorized: {
|
||||||
|
description: "No autenticado o clave inválida/revocada",
|
||||||
|
content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } } },
|
||||||
|
},
|
||||||
|
Forbidden: {
|
||||||
|
description: "Alcance insuficiente, acción exclusiva de humano o contacto no verificado",
|
||||||
|
content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } } },
|
||||||
|
},
|
||||||
|
Conflict: {
|
||||||
|
description: "Transición inválida, falta aprobación previa, fuera de ventana 24h o conflicto de idempotencia",
|
||||||
|
content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } } },
|
||||||
|
},
|
||||||
|
TooManyRequests: {
|
||||||
|
description: "Límite de peticiones por minuto excedido (incluye headers X-RateLimit-* y Retry-After)",
|
||||||
|
content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
security: [{ ApiKeyAuth: [] }, { BearerAuth: [] }, { CookieAuth: [] }],
|
||||||
|
paths: {
|
||||||
|
"/api/health": {
|
||||||
|
get: {
|
||||||
|
summary: "Estado de salud del servicio y BD",
|
||||||
|
security: [],
|
||||||
|
responses: { "200": { description: "OK" }, "503": { description: "BD no disponible" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/catalogo": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar catálogo de servicios (scope: catalogo:leer)",
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Lista de servicios" },
|
||||||
|
"401": { $ref: "#/components/responses/Unauthorized" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
"429": { $ref: "#/components/responses/TooManyRequests" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/categorias": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar categorías del catálogo (scope: catalogo:leer)",
|
||||||
|
responses: { "200": { description: "Lista de categorías" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/paquetes": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar paquetes activos con fases y servicios (scope: catalogo:leer)",
|
||||||
|
responses: { "200": { description: "Lista de paquetes" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/clientes": {
|
||||||
|
get: {
|
||||||
|
summary: "Buscar y listar clientes (scope: clientes:leer)",
|
||||||
|
responses: { "200": { description: "Lista de clientes" } },
|
||||||
|
},
|
||||||
|
post: {
|
||||||
|
summary: "Crear cliente (scope: clientes:escribir)",
|
||||||
|
parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }],
|
||||||
|
responses: {
|
||||||
|
"201": { description: "Cliente creado" },
|
||||||
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/clientes/{id}": {
|
||||||
|
patch: {
|
||||||
|
summary: "Actualizar datos de un cliente (scope: clientes:escribir)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "Cliente actualizado" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar cotizaciones (scopes: cotizaciones:leer o cotizaciones:leer_aceptadas)",
|
||||||
|
parameters: [
|
||||||
|
{ name: "estado", in: "query", schema: { $ref: "#/components/schemas/EstadoCotizacion" } },
|
||||||
|
{ name: "clienteId", in: "query", schema: { type: "string" } },
|
||||||
|
{ name: "q", in: "query", schema: { type: "string" } },
|
||||||
|
{ name: "clienteEmail", in: "query", schema: { type: "string" } },
|
||||||
|
{ name: "clienteTelefono", in: "query", schema: { type: "string" } },
|
||||||
|
{ name: "desde", in: "query", schema: { type: "string", format: "date" } },
|
||||||
|
{ name: "hasta", in: "query", schema: { type: "string", format: "date" } },
|
||||||
|
{ name: "page", in: "query", schema: { type: "integer" } },
|
||||||
|
{ name: "limit", in: "query", schema: { type: "integer" } },
|
||||||
|
],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Lista de cotizaciones" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
post: {
|
||||||
|
summary: "Crear borrador de cotización (scope: cotizaciones:borrador). Siempre inicia en borrador.",
|
||||||
|
parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }],
|
||||||
|
responses: {
|
||||||
|
"201": { description: "Borrador creado y notificación enviada a Jareth si lo creó un agente" },
|
||||||
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones/{id}": {
|
||||||
|
get: {
|
||||||
|
summary: "Obtener detalle de cotización (soporta ?verificarContacto=email|telefono)",
|
||||||
|
parameters: [
|
||||||
|
{ name: "id", in: "path", required: true, schema: { type: "string" } },
|
||||||
|
{ name: "verificarContacto", in: "query", schema: { type: "string" } },
|
||||||
|
],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Detalle de cotización" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
put: {
|
||||||
|
summary: "Editar borrador (scope: cotizaciones:borrador; agentes no pueden cambiar estado)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Cotización actualizada" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
delete: {
|
||||||
|
summary: "Eliminar cotización (solo personal humano)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "Eliminada" }, "403": { $ref: "#/components/responses/Forbidden" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones/{id}/solicitar-aprobacion": {
|
||||||
|
post: {
|
||||||
|
summary: "Reenviar solicitud de aprobación humana por correo a Jareth (scope: cotizaciones:borrador)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "Solicitud generada" }, "409": { $ref: "#/components/responses/Conflict" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones/{id}/aprobar": {
|
||||||
|
post: {
|
||||||
|
summary: "Aprobar cotización (EXCLUSIVO administrador humano; agentes siempre reciben 403)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Cotización aprobada" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones/{id}/enviar": {
|
||||||
|
post: {
|
||||||
|
summary: "Enviar cotización YA aprobada por email, whatsapp_chatwoot o manual (scope: cotizaciones:enviar)",
|
||||||
|
parameters: [
|
||||||
|
{ name: "id", in: "path", required: true, schema: { type: "string" } },
|
||||||
|
{ $ref: "#/components/parameters/IdempotencyKey" },
|
||||||
|
],
|
||||||
|
requestBody: {
|
||||||
|
content: {
|
||||||
|
"application/json": {
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
canal: { type: "string", enum: ["email", "whatsapp_chatwoot", "manual"], default: "email" },
|
||||||
|
destino: { type: "string" },
|
||||||
|
mensaje: { type: "string" },
|
||||||
|
verificarContacto: { type: "string" },
|
||||||
|
chatwootConversationId: { type: ["integer", "string"] },
|
||||||
|
fallbackEmail: { type: "boolean" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Cotización enviada y marcada como enviada" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cotizaciones/{id}/estado": {
|
||||||
|
patch: {
|
||||||
|
summary: "Cambiar estado post-envío (aceptada, rechazada, vencida) — solo personal humano",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: {
|
||||||
|
"200": { description: "Estado actualizado" },
|
||||||
|
"403": { $ref: "#/components/responses/Forbidden" },
|
||||||
|
"409": { $ref: "#/components/responses/Conflict" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/export/pdf/{id}": {
|
||||||
|
get: {
|
||||||
|
summary: "Descargar PDF de cotización (staff, cliente dueño o agente con scope de lectura/envío)",
|
||||||
|
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "PDF binario" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cobros/programas": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar programas de cobro recurrente (scope: cobros:leer)",
|
||||||
|
responses: { "200": { description: "Lista de programas" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cobros/pagos": {
|
||||||
|
get: {
|
||||||
|
summary: "Listar cobros recurrentes con filtros (scope: cobros:leer)",
|
||||||
|
responses: { "200": { description: "Lista de cobros" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/cobros/pagos/{id}/registrar": {
|
||||||
|
post: {
|
||||||
|
summary: "Registrar pago recibido fuera del panel (scope: cobros:registrar; emite webhook pago.registrado)",
|
||||||
|
parameters: [
|
||||||
|
{ name: "id", in: "path", required: true, schema: { type: "string" } },
|
||||||
|
{ $ref: "#/components/parameters/IdempotencyKey" },
|
||||||
|
],
|
||||||
|
responses: { "200": { description: "Pago verificado" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/aprobar/{token}": {
|
||||||
|
get: {
|
||||||
|
summary: "Consultar resumen de cotización de un enlace firmado sin mutar estado",
|
||||||
|
security: [],
|
||||||
|
parameters: [{ name: "token", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "Resumen seguro" }, "404": { description: "Inválido" }, "410": { description: "Usado o expirado" } },
|
||||||
|
},
|
||||||
|
post: {
|
||||||
|
summary: "Confirmar aprobación de un solo uso con { confirmar: true }",
|
||||||
|
security: [],
|
||||||
|
parameters: [{ name: "token", in: "path", required: true, schema: { type: "string" } }],
|
||||||
|
responses: { "200": { description: "Aprobada" }, "410": { description: "Usado o expirado" } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/agent-keys": {
|
||||||
|
get: { summary: "Listar claves de agentes (solo admin humano)", responses: { "200": { description: "Lista de claves (sin hash)" } } },
|
||||||
|
post: { summary: "Crear clave de agente (solo admin humano; devuelve rawKey una vez)", responses: { "201": { description: "Clave creada" } } },
|
||||||
|
},
|
||||||
|
"/api/agent-keys/{id}/rotate": {
|
||||||
|
post: { summary: "Rotar secreto de una clave (solo admin humano)", responses: { "200": { description: "Clave rotada" } } },
|
||||||
|
},
|
||||||
|
"/api/agent-keys/{id}/revoke": {
|
||||||
|
post: { summary: "Revocar clave de agente (solo admin humano)", responses: { "200": { description: "Clave revocada" } } },
|
||||||
|
},
|
||||||
|
"/api/audit-logs": {
|
||||||
|
get: { summary: "Consultar bitácora de auditoría (solo admin humano)", responses: { "200": { description: "Bitácora paginada" } } },
|
||||||
|
},
|
||||||
|
"/api/webhooks": {
|
||||||
|
get: { summary: "Listar endpoints webhook (solo admin humano)", responses: { "200": { description: "Lista" } } },
|
||||||
|
post: { summary: "Registrar endpoint webhook HMAC-SHA256 (solo admin humano)", responses: { "201": { description: "Creado" } } },
|
||||||
|
},
|
||||||
|
"/api/webhooks/{id}": {
|
||||||
|
delete: { summary: "Eliminar endpoint webhook (solo admin humano)", responses: { "200": { description: "Eliminado" } } },
|
||||||
|
},
|
||||||
|
"/api/webhooks/deliveries": {
|
||||||
|
get: { summary: "Historial de entregas webhook (solo admin humano)", responses: { "200": { description: "Entregas" } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return NextResponse.json(spec);
|
||||||
|
}
|
||||||
@@ -1,8 +1,15 @@
|
|||||||
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) {
|
||||||
try {
|
try {
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
scopes: ["catalogo:leer"],
|
||||||
|
recursoTipo: "paquete",
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const paquetes = await prisma.paquete.findMany({
|
const paquetes = await prisma.paquete.findMany({
|
||||||
where: { activo: true },
|
where: { activo: true },
|
||||||
include: {
|
include: {
|
||||||
@@ -18,7 +25,7 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
orderBy: { createdAt: "asc" },
|
orderBy: { createdAt: "asc" },
|
||||||
});
|
});
|
||||||
return NextResponse.json(paquetes);
|
return applyHeaders(NextResponse.json(paquetes), 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 });
|
||||||
@@ -27,6 +34,9 @@ export async function GET() {
|
|||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "paquete" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const paquete = await prisma.paquete.create({
|
const paquete = await prisma.paquete.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
export async function DELETE(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const auth = await requireActor(request, {
|
||||||
|
adminOnly: true,
|
||||||
|
recursoTipo: "webhook",
|
||||||
|
recursoId: id,
|
||||||
|
});
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const existing = await prisma.webhookEndpoint.findUnique({ where: { id } });
|
||||||
|
if (!existing) {
|
||||||
|
return NextResponse.json({ error: "Webhook no encontrado" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.webhookEndpoint.delete({ where: { id } });
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "webhook.eliminar",
|
||||||
|
recursoTipo: "webhook",
|
||||||
|
recursoId: id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: existing.nombre, url: existing.url },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "webhook_delivery" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const sp = request.nextUrl.searchParams;
|
||||||
|
const evento = sp.get("evento")?.trim();
|
||||||
|
const endpointId = sp.get("endpointId")?.trim();
|
||||||
|
const limit = Math.min(200, Math.max(1, parseInt(sp.get("limit") || "50", 10) || 50));
|
||||||
|
|
||||||
|
const deliveries = await prisma.webhookDelivery.findMany({
|
||||||
|
where: {
|
||||||
|
...(evento && { evento }),
|
||||||
|
...(endpointId && { endpointId }),
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
take: limit,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(deliveries);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireActor } from "@/lib/agent-auth";
|
||||||
|
import { EVENTOS_WEBHOOK } from "@/lib/webhooks";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
|
||||||
|
const createWebhookSchema = z.object({
|
||||||
|
nombre: z.string().trim().min(2).max(100),
|
||||||
|
url: z.string().url("URL de webhook invalida"),
|
||||||
|
secret: z.string().trim().min(16, "El secreto debe tener al menos 16 caracteres").optional(),
|
||||||
|
eventos: z
|
||||||
|
.array(z.enum(["*", ...EVENTOS_WEBHOOK]))
|
||||||
|
.min(1, "Debes suscribir al menos un evento"),
|
||||||
|
activo: z.boolean().default(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "webhook" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const endpoints = await prisma.webhookEndpoint.findMany({
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
url: true,
|
||||||
|
eventos: true,
|
||||||
|
activo: true,
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
_count: { select: { entregas: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return NextResponse.json(endpoints);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "webhook" });
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
const parsed = createWebhookSchema.safeParse(body);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existe = await prisma.webhookEndpoint.findUnique({
|
||||||
|
where: { nombre: parsed.data.nombre },
|
||||||
|
});
|
||||||
|
if (existe) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Ya existe un webhook con el nombre "${parsed.data.nombre}"` },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const secret = parsed.data.secret || `whsec_${randomBytes(24).toString("hex")}`;
|
||||||
|
|
||||||
|
const created = await prisma.webhookEndpoint.create({
|
||||||
|
data: {
|
||||||
|
nombre: parsed.data.nombre,
|
||||||
|
url: parsed.data.url,
|
||||||
|
secret,
|
||||||
|
eventos: Array.from(new Set(parsed.data.eventos)),
|
||||||
|
activo: parsed.data.activo,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
nombre: true,
|
||||||
|
url: true,
|
||||||
|
eventos: true,
|
||||||
|
activo: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: auth.actor,
|
||||||
|
accion: "webhook.crear",
|
||||||
|
recursoTipo: "webhook",
|
||||||
|
recursoId: created.id,
|
||||||
|
request,
|
||||||
|
exito: true,
|
||||||
|
detalle: { nombre: created.nombre, url: created.url, eventos: created.eventos },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ...created, secret }, { status: 201 });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { CheckCircle2, AlertTriangle, Loader2, ShieldCheck } from "lucide-react";
|
||||||
|
import { formatCurrency } from "@/lib/calculators";
|
||||||
|
|
||||||
|
interface PartidaResumen {
|
||||||
|
id: string;
|
||||||
|
nombre: string;
|
||||||
|
fase: number;
|
||||||
|
tipoPago: string;
|
||||||
|
precio: number;
|
||||||
|
tiempoEntrega: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResumenProps {
|
||||||
|
token: string;
|
||||||
|
cotizacion: {
|
||||||
|
id: string;
|
||||||
|
numero: string;
|
||||||
|
proyecto: string;
|
||||||
|
moneda: string;
|
||||||
|
estado: string;
|
||||||
|
vigenciaTexto: string;
|
||||||
|
creadaPorAgente: string | null;
|
||||||
|
cliente: { nombre: string; empresa: string | null };
|
||||||
|
totalUnico: number;
|
||||||
|
totalMensual: number;
|
||||||
|
incluirIva: boolean;
|
||||||
|
partidas: PartidaResumen[];
|
||||||
|
};
|
||||||
|
puedeAprobar: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AprobarClient({ token, cotizacion, puedeAprobar }: ResumenProps) {
|
||||||
|
const [estado, setEstado] = useState(cotizacion.estado);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [aprobadaOk, setAprobadaOk] = useState(false);
|
||||||
|
|
||||||
|
const handleAprobar = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/aprobar/${encodeURIComponent(token)}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ confirmar: true }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
setError(data.error || "No se pudo aprobar la cotización");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEstado("aprobada");
|
||||||
|
setAprobadaOk(true);
|
||||||
|
} catch {
|
||||||
|
setError("Error de red al confirmar la aprobación");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#f8fafc] py-10 px-4">
|
||||||
|
<div className="max-w-2xl mx-auto">
|
||||||
|
<div className="bg-white rounded-2xl border border-[#e2e8f0] shadow-sm overflow-hidden">
|
||||||
|
<div className="bg-[#0F172A] text-white px-6 py-5 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs tracking-[0.12em] uppercase text-blue-300 font-semibold">
|
||||||
|
Uriel Jareth Consulting
|
||||||
|
</p>
|
||||||
|
<h1 className="text-xl font-bold mt-1">Revisión y aprobación de cotización</h1>
|
||||||
|
</div>
|
||||||
|
<ShieldCheck className="w-8 h-8 text-blue-300 shrink-0" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-6 space-y-6">
|
||||||
|
{aprobadaOk && (
|
||||||
|
<div className="rounded-xl bg-green-50 border border-green-200 p-4 flex items-start gap-3">
|
||||||
|
<CheckCircle2 className="w-5 h-5 text-green-600 shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-green-900">Cotización aprobada correctamente</p>
|
||||||
|
<p className="text-sm text-green-800 mt-0.5">
|
||||||
|
La cotización <strong>{cotizacion.numero}</strong> quedó autorizada y lista para enviarse al cliente.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-xl bg-red-50 border border-red-200 p-4 flex items-start gap-3">
|
||||||
|
<AlertTriangle className="w-5 h-5 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
<p className="text-sm text-red-800">{error}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm bg-[#f8fafc] rounded-xl border border-[#e2e8f0] p-4">
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Folio</span>
|
||||||
|
<span className="font-semibold text-[#0F172A]">{cotizacion.numero}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Estado actual</span>
|
||||||
|
<span className="font-semibold text-[#0F172A] capitalize">{estado}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Cliente</span>
|
||||||
|
<span className="font-medium text-[#0F172A]">
|
||||||
|
{cotizacion.cliente.nombre}
|
||||||
|
{cotizacion.cliente.empresa ? ` · ${cotizacion.cliente.empresa}` : ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Proyecto</span>
|
||||||
|
<span className="font-medium text-[#0F172A]">{cotizacion.proyecto}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Vigencia</span>
|
||||||
|
<span className="font-medium text-[#0F172A]">{cotizacion.vigenciaTexto}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b] block text-xs">Origen</span>
|
||||||
|
<span className="font-medium text-[#0F172A]">
|
||||||
|
{cotizacion.creadaPorAgente ? `Agente: ${cotizacion.creadaPorAgente}` : "Equipo interno"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold text-[#0F172A] mb-2">Partidas incluidas</h2>
|
||||||
|
<div className="border border-[#e2e8f0] rounded-xl overflow-hidden">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-[#f8fafc] text-[#64748b] text-xs">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left py-2.5 px-3 font-medium">Concepto</th>
|
||||||
|
<th className="text-left py-2.5 px-3 font-medium">Tipo</th>
|
||||||
|
<th className="text-right py-2.5 px-3 font-medium">Subtotal</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{cotizacion.partidas.map((p) => (
|
||||||
|
<tr key={p.id} className="border-t border-[#e2e8f0]">
|
||||||
|
<td className="py-2.5 px-3 text-[#0F172A]">{p.nombre}</td>
|
||||||
|
<td className="py-2.5 px-3 text-[#64748b] capitalize">{p.tipoPago}</td>
|
||||||
|
<td className="py-2.5 px-3 text-right font-medium text-[#0F172A]">
|
||||||
|
{formatCurrency(p.precio)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 pt-2 border-t border-[#e2e8f0]">
|
||||||
|
<div className="text-sm text-[#0F172A] space-y-0.5">
|
||||||
|
{cotizacion.totalUnico > 0 && (
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b]">Total único ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): </span>
|
||||||
|
<strong>{formatCurrency(cotizacion.totalUnico)} {cotizacion.moneda}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{cotizacion.totalMensual > 0 && (
|
||||||
|
<div>
|
||||||
|
<span className="text-[#64748b]">Total mensual ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): </span>
|
||||||
|
<strong>{formatCurrency(cotizacion.totalMensual)} {cotizacion.moneda}/mes</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{puedeAprobar && !aprobadaOk && (
|
||||||
|
<button
|
||||||
|
onClick={handleAprobar}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-lg bg-[#0400C4] hover:bg-[#03009e] text-white font-semibold text-sm transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
|
Aprobando…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<CheckCircle2 className="w-4 h-4" />
|
||||||
|
Aprobar cotización
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { hashSecret } from "@/lib/agent-auth-core";
|
||||||
|
import { calcularTotalesCotizacion, formatDate } from "@/lib/calculators";
|
||||||
|
import { AprobarClient } from "./AprobarClient";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AprobarTokenPage({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ token: string }>;
|
||||||
|
}) {
|
||||||
|
const { token } = await params;
|
||||||
|
const tokenHash = hashSecret(token);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const record = await prisma.approvalToken.findUnique({
|
||||||
|
where: { tokenHash },
|
||||||
|
include: {
|
||||||
|
cotizacion: {
|
||||||
|
include: {
|
||||||
|
cliente: { select: { nombre: true, empresa: true } },
|
||||||
|
servicios: {
|
||||||
|
where: { seleccionado: true },
|
||||||
|
include: { servicioCatalogo: { select: { nombre: true } } },
|
||||||
|
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!record || record.usadoAt || record.expiraAt <= now) {
|
||||||
|
const motivo = !record
|
||||||
|
? "Este enlace de aprobación no es válido."
|
||||||
|
: record.usadoAt
|
||||||
|
? "Este enlace de aprobación ya fue utilizado anteriormente."
|
||||||
|
: "Este enlace de aprobación ha expirado.";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-2xl border border-[#e2e8f0] shadow-sm p-6 text-center">
|
||||||
|
<p className="text-xs tracking-[0.12em] uppercase text-[#0400C4] font-semibold">
|
||||||
|
Uriel Jareth Consulting
|
||||||
|
</p>
|
||||||
|
<h1 className="text-lg font-bold text-[#0F172A] mt-2">Enlace no disponible</h1>
|
||||||
|
<p className="text-sm text-[#64748b] mt-2">{motivo}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cot = record.cotizacion;
|
||||||
|
const totales = calcularTotalesCotizacion(cot.servicios, {
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AprobarClient
|
||||||
|
token={token}
|
||||||
|
puedeAprobar={cot.estado === "borrador"}
|
||||||
|
cotizacion={{
|
||||||
|
id: cot.id,
|
||||||
|
numero: cot.numero,
|
||||||
|
proyecto: cot.proyecto,
|
||||||
|
moneda: cot.moneda,
|
||||||
|
estado: cot.estado,
|
||||||
|
vigenciaTexto: formatDate(cot.vigencia),
|
||||||
|
creadaPorAgente: cot.creadaPorAgente,
|
||||||
|
cliente: cot.cliente,
|
||||||
|
totalUnico: totales.totalUnico,
|
||||||
|
totalMensual: totales.totalMensual,
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
partidas: cot.servicios.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||||
|
fase: s.fase,
|
||||||
|
tipoPago: s.tipoPago,
|
||||||
|
precio: s.precio,
|
||||||
|
tiempoEntrega: s.tiempoEntrega,
|
||||||
|
})),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -162,7 +162,7 @@ export function ClienteShell({ nombre }: { nombre: string }) {
|
|||||||
<Sparkles className="w-4 h-4" />
|
<Sparkles className="w-4 h-4" />
|
||||||
</span>
|
</span>
|
||||||
<span className="min-w-0">
|
<span className="min-w-0">
|
||||||
<span className="block font-bold leading-tight">Cotizador E3</span>
|
<span className="block font-bold leading-tight truncate">Cotizador — Uriel Jareth Consulting</span>
|
||||||
<span className="block text-xs text-muted truncate">{nombre}</span>
|
<span className="block text-xs text-muted truncate">{nombre}</span>
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
+17
-8
@@ -2,18 +2,18 @@
|
|||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: #f8fafc;
|
--background: #f8fafc;
|
||||||
--foreground: #1e293b;
|
--foreground: #0f172a;
|
||||||
--primary: #2563eb;
|
--primary: #0400c4;
|
||||||
--primary-dark: #1d4ed8;
|
--primary-dark: #03009a;
|
||||||
--primary-light: #dbeafe;
|
--primary-light: #e8e8ff;
|
||||||
--secondary: #7c3aed;
|
--secondary: #0f172a;
|
||||||
--accent: #06b6d4;
|
--accent: #06b6d4;
|
||||||
--success: #10b981;
|
--success: #10b981;
|
||||||
--warning: #f59e0b;
|
--warning: #f59e0b;
|
||||||
--danger: #ef4444;
|
--danger: #ef4444;
|
||||||
--sidebar-bg: #1e293b;
|
--sidebar-bg: #0f172a;
|
||||||
--sidebar-text: #cbd5e1;
|
--sidebar-text: #cbd5e1;
|
||||||
--sidebar-active: #2563eb;
|
--sidebar-active: #0400c4;
|
||||||
--card-bg: #ffffff;
|
--card-bg: #ffffff;
|
||||||
--border: #e2e8f0;
|
--border: #e2e8f0;
|
||||||
/* Texto secundario: slate-500 da 4.8:1 sobre blanco (slate-400 se quedaba en
|
/* Texto secundario: slate-500 da 4.8:1 sobre blanco (slate-400 se quedaba en
|
||||||
@@ -37,7 +37,8 @@
|
|||||||
--color-card-bg: var(--card-bg);
|
--color-card-bg: var(--card-bg);
|
||||||
--color-border: var(--border);
|
--color-border: var(--border);
|
||||||
--color-muted: var(--muted);
|
--color-muted: var(--muted);
|
||||||
--font-sans: var(--font-geist-sans);
|
--font-sans: var(--font-figtree);
|
||||||
|
--font-heading: var(--font-archivo);
|
||||||
--font-mono: var(--font-geist-mono);
|
--font-mono: var(--font-geist-mono);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,6 +48,14 @@ body {
|
|||||||
font-family: var(--font-sans), Arial, Helvetica, sans-serif;
|
font-family: var(--font-sans), Arial, Helvetica, sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
.font-display {
|
||||||
|
font-family: var(--font-heading), var(--font-sans), Arial, Helvetica, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: #cbd5e1 transparent;
|
scrollbar-color: #cbd5e1 transparent;
|
||||||
|
|||||||
+13
-6
@@ -1,10 +1,17 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { Archivo, Figtree, Geist_Mono } from "next/font/google";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
const geistSans = Geist({
|
const figtree = Figtree({
|
||||||
variable: "--font-geist-sans",
|
variable: "--font-figtree",
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
|
weight: ["400", "500", "600", "700"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const archivo = Archivo({
|
||||||
|
variable: "--font-archivo",
|
||||||
|
subsets: ["latin"],
|
||||||
|
weight: ["600", "700", "800"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const geistMono = Geist_Mono({
|
const geistMono = Geist_Mono({
|
||||||
@@ -13,9 +20,9 @@ const geistMono = Geist_Mono({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Cotizador - Uriel Jareth Consulting",
|
title: "Cotizador — Uriel Jareth Consulting",
|
||||||
description:
|
description:
|
||||||
"Sistema de generacion de cotizaciones para Uriel Jareth Consulting",
|
"Sistema de generación de cotizaciones para Uriel Jareth Consulting",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
@@ -27,7 +34,7 @@ export default function RootLayout({
|
|||||||
<html
|
<html
|
||||||
lang="es"
|
lang="es"
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
className={`${figtree.variable} ${archivo.variable} ${geistMono.variable} h-full antialiased`}
|
||||||
>
|
>
|
||||||
<body className="min-h-full flex flex-col">{children}</body>
|
<body className="min-h-full flex flex-col">{children}</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,14 +1,29 @@
|
|||||||
const COLORS: Record<string, string> = {
|
const COLORS: Record<string, string> = {
|
||||||
borrador: "bg-gray-100 text-gray-700",
|
borrador: "bg-gray-100 text-gray-700",
|
||||||
|
aprobada: "bg-indigo-100 text-indigo-800",
|
||||||
enviada: "bg-blue-100 text-blue-700",
|
enviada: "bg-blue-100 text-blue-700",
|
||||||
aprobada: "bg-green-100 text-green-700",
|
aceptada: "bg-green-100 text-green-700",
|
||||||
rechazada: "bg-red-100 text-red-700",
|
rechazada: "bg-red-100 text-red-700",
|
||||||
|
vencida: "bg-amber-100 text-amber-800",
|
||||||
|
};
|
||||||
|
|
||||||
|
const LABELS: Record<string, string> = {
|
||||||
|
borrador: "Borrador",
|
||||||
|
aprobada: "Aprobada",
|
||||||
|
enviada: "Enviada",
|
||||||
|
aceptada: "Aceptada",
|
||||||
|
rechazada: "Rechazada",
|
||||||
|
vencida: "Vencida",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function EstadoBadge({ estado }: { estado: string }) {
|
export function EstadoBadge({ estado }: { estado: string }) {
|
||||||
return (
|
return (
|
||||||
<span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${COLORS[estado] || COLORS.borrador}`}>
|
<span
|
||||||
{estado.charAt(0).toUpperCase() + estado.slice(1)}
|
className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||||
|
COLORS[estado] || COLORS.borrador
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{LABELS[estado] || estado.charAt(0).toUpperCase() + estado.slice(1)}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { createHash, randomBytes } from "node:crypto";
|
||||||
|
|
||||||
|
// Alcances validos para claves de agentes. JAMAS incluir un scope de aprobacion:
|
||||||
|
// aprobar una cotizacion es exclusivamente accion humana de Jareth.
|
||||||
|
export const AGENT_SCOPES = [
|
||||||
|
"catalogo:leer",
|
||||||
|
"clientes:leer",
|
||||||
|
"clientes:escribir",
|
||||||
|
"cotizaciones:leer",
|
||||||
|
"cotizaciones:leer_aceptadas",
|
||||||
|
"cotizaciones:borrador",
|
||||||
|
"cotizaciones:enviar",
|
||||||
|
"cobros:leer",
|
||||||
|
"cobros:registrar",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type AgentScope = (typeof AGENT_SCOPES)[number];
|
||||||
|
|
||||||
|
export const API_KEY_PREFIX = "ujc_live_";
|
||||||
|
|
||||||
|
export type ActorContext =
|
||||||
|
| {
|
||||||
|
type: "user";
|
||||||
|
userId: string;
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
role: string;
|
||||||
|
clienteId?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "agent";
|
||||||
|
keyId: string;
|
||||||
|
nombre: string;
|
||||||
|
prefijo: string;
|
||||||
|
scopes: string[];
|
||||||
|
rateLimitPerMin: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function esScopeValido(scope: string): scope is AgentScope {
|
||||||
|
return (AGENT_SCOPES as readonly string[]).includes(scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hashSecret(raw: string): string {
|
||||||
|
return createHash("sha256").update(raw, "utf8").digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateApiKey(): { rawKey: string; prefijo: string; keyHash: string } {
|
||||||
|
const token = randomBytes(32).toString("hex");
|
||||||
|
const rawKey = `${API_KEY_PREFIX}${token}`;
|
||||||
|
const prefijo = rawKey.slice(0, 14);
|
||||||
|
const keyHash = hashSecret(rawKey);
|
||||||
|
return { rawKey, prefijo, keyHash };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tienePrefijoApiKey(raw: string): boolean {
|
||||||
|
return raw.startsWith(API_KEY_PREFIX) && raw.length >= API_KEY_PREFIX.length + 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function actorTieneScope(
|
||||||
|
actor: ActorContext,
|
||||||
|
requiredScopes: AgentScope[],
|
||||||
|
mode: "any" | "all" = "any"
|
||||||
|
): boolean {
|
||||||
|
if (actor.type === "user") {
|
||||||
|
return actor.role !== "cliente";
|
||||||
|
}
|
||||||
|
if (requiredScopes.length === 0) return true;
|
||||||
|
if (mode === "all") {
|
||||||
|
return requiredScopes.every((s) => actor.scopes.includes(s));
|
||||||
|
}
|
||||||
|
return requiredScopes.some((s) => actor.scopes.includes(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function esAgenteSoloAceptadas(actor: ActorContext): boolean {
|
||||||
|
return (
|
||||||
|
actor.type === "agent" &&
|
||||||
|
actor.scopes.includes("cotizaciones:leer_aceptadas") &&
|
||||||
|
!actor.scopes.includes("cotizaciones:leer")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verifica si `verificarContacto` (email o telefono) coincide con el cliente de la cotizacion.
|
||||||
|
// Para email: exacto case-insensitive. Para telefono: coincidencia en los ultimos 10 digitos MX.
|
||||||
|
export function coincideContacto(
|
||||||
|
verificarContacto: string,
|
||||||
|
cliente: { email?: string | null; telefono?: string | null }
|
||||||
|
): boolean {
|
||||||
|
const valor = (verificarContacto || "").trim();
|
||||||
|
if (!valor) return false;
|
||||||
|
|
||||||
|
if (valor.includes("@")) {
|
||||||
|
const emailCliente = (cliente.email || "").trim().toLowerCase();
|
||||||
|
return Boolean(emailCliente) && emailCliente === valor.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
const digitosEntrada = valor.replace(/\D/g, "");
|
||||||
|
const digitosCliente = (cliente.telefono || "").replace(/\D/g, "");
|
||||||
|
if (digitosEntrada.length < 10 || digitosCliente.length < 10) return false;
|
||||||
|
return digitosEntrada.slice(-10) === digitosCliente.slice(-10);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limiter en memoria con ventana deslizante de 60 segundos por keyId.
|
||||||
|
const WINDOW_MS = 60_000;
|
||||||
|
const buckets = new Map<string, number[]>();
|
||||||
|
|
||||||
|
export interface RateLimitResult {
|
||||||
|
ok: boolean;
|
||||||
|
limit: number;
|
||||||
|
remaining: number;
|
||||||
|
resetAt: number; // epoch seconds
|
||||||
|
retryAfterSeconds: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkRateLimit(
|
||||||
|
keyId: string,
|
||||||
|
limitPerMin: number,
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
): RateLimitResult {
|
||||||
|
const limit = Math.max(1, limitPerMin || 60);
|
||||||
|
const cutoff = nowMs - WINDOW_MS;
|
||||||
|
const timestamps = (buckets.get(keyId) ?? []).filter((ts) => ts > cutoff);
|
||||||
|
|
||||||
|
if (timestamps.length >= limit) {
|
||||||
|
const oldest = timestamps[0] ?? nowMs;
|
||||||
|
const resetMs = oldest + WINDOW_MS;
|
||||||
|
const retryAfterSeconds = Math.max(1, Math.ceil((resetMs - nowMs) / 1000));
|
||||||
|
buckets.set(keyId, timestamps);
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
limit,
|
||||||
|
remaining: 0,
|
||||||
|
resetAt: Math.ceil(resetMs / 1000),
|
||||||
|
retryAfterSeconds,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
timestamps.push(nowMs);
|
||||||
|
buckets.set(keyId, timestamps);
|
||||||
|
const oldest = timestamps[0] ?? nowMs;
|
||||||
|
const resetMs = oldest + WINDOW_MS;
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
limit,
|
||||||
|
remaining: Math.max(0, limit - timestamps.length),
|
||||||
|
resetAt: Math.ceil(resetMs / 1000),
|
||||||
|
retryAfterSeconds: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildRateLimitHeaders(rl: RateLimitResult): Record<string, string> {
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
"X-RateLimit-Limit": String(rl.limit),
|
||||||
|
"X-RateLimit-Remaining": String(rl.remaining),
|
||||||
|
"X-RateLimit-Reset": String(rl.resetAt),
|
||||||
|
};
|
||||||
|
if (!rl.ok) {
|
||||||
|
headers["Retry-After"] = String(rl.retryAfterSeconds);
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetRateLimiterForTests(): void {
|
||||||
|
buckets.clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { getSession } from "@/lib/auth";
|
||||||
|
import { registrarAuditoria, obtenerIp } from "@/lib/audit";
|
||||||
|
import {
|
||||||
|
AGENT_SCOPES,
|
||||||
|
API_KEY_PREFIX,
|
||||||
|
actorTieneScope,
|
||||||
|
buildRateLimitHeaders,
|
||||||
|
checkRateLimit,
|
||||||
|
coincideContacto,
|
||||||
|
esAgenteSoloAceptadas,
|
||||||
|
esScopeValido,
|
||||||
|
generateApiKey,
|
||||||
|
hashSecret,
|
||||||
|
resetRateLimiterForTests,
|
||||||
|
tienePrefijoApiKey,
|
||||||
|
type ActorContext,
|
||||||
|
type AgentScope,
|
||||||
|
type RateLimitResult,
|
||||||
|
} from "@/lib/agent-auth-core";
|
||||||
|
|
||||||
|
export {
|
||||||
|
AGENT_SCOPES,
|
||||||
|
API_KEY_PREFIX,
|
||||||
|
actorTieneScope,
|
||||||
|
buildRateLimitHeaders,
|
||||||
|
checkRateLimit,
|
||||||
|
coincideContacto,
|
||||||
|
esAgenteSoloAceptadas,
|
||||||
|
esScopeValido,
|
||||||
|
generateApiKey,
|
||||||
|
hashSecret,
|
||||||
|
obtenerIp,
|
||||||
|
resetRateLimiterForTests,
|
||||||
|
tienePrefijoApiKey,
|
||||||
|
type ActorContext,
|
||||||
|
type AgentScope,
|
||||||
|
type RateLimitResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
function extraerApiKey(request: NextRequest): string | null {
|
||||||
|
const direct = request.headers.get("x-api-key")?.trim();
|
||||||
|
if (direct) return direct;
|
||||||
|
const auth = request.headers.get("authorization")?.trim();
|
||||||
|
if (auth && auth.toLowerCase().startsWith("bearer ")) {
|
||||||
|
const token = auth.slice(7).trim();
|
||||||
|
if (token) return token;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthAttemptResult {
|
||||||
|
actor: ActorContext | null;
|
||||||
|
rateLimited?: boolean;
|
||||||
|
rateLimit?: RateLimitResult;
|
||||||
|
invalidKey?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticateActor(request: NextRequest): Promise<AuthAttemptResult> {
|
||||||
|
// 1. Sesion humana por cookie JWT (siempre tiene prioridad en el navegador)
|
||||||
|
const session = await getSession();
|
||||||
|
if (session) {
|
||||||
|
return {
|
||||||
|
actor: {
|
||||||
|
type: "user",
|
||||||
|
userId: session.userId,
|
||||||
|
email: session.email,
|
||||||
|
name: session.name,
|
||||||
|
role: session.role || "asesor",
|
||||||
|
clienteId: session.clienteId,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. API Key para agentes (X-API-Key o Authorization: Bearer)
|
||||||
|
const rawKey = extraerApiKey(request);
|
||||||
|
if (!rawKey) return { actor: null };
|
||||||
|
|
||||||
|
const keyHash = hashSecret(rawKey);
|
||||||
|
const record = await prisma.agentApiKey.findFirst({
|
||||||
|
where: {
|
||||||
|
keyHash,
|
||||||
|
activo: true,
|
||||||
|
revokedAt: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!record) {
|
||||||
|
return { actor: null, invalidKey: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const rl = checkRateLimit(record.id, record.rateLimitPerMin);
|
||||||
|
if (!rl.ok) {
|
||||||
|
return {
|
||||||
|
actor: {
|
||||||
|
type: "agent",
|
||||||
|
keyId: record.id,
|
||||||
|
nombre: record.nombre,
|
||||||
|
prefijo: record.prefijo,
|
||||||
|
scopes: record.scopes,
|
||||||
|
rateLimitPerMin: record.rateLimitPerMin,
|
||||||
|
},
|
||||||
|
rateLimited: true,
|
||||||
|
rateLimit: rl,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Actualizar lastUsedAt en background si pasaron >60s
|
||||||
|
const ahora = Date.now();
|
||||||
|
if (!record.lastUsedAt || ahora - record.lastUsedAt.getTime() > 60_000) {
|
||||||
|
void prisma.agentApiKey
|
||||||
|
.update({
|
||||||
|
where: { id: record.id },
|
||||||
|
data: { lastUsedAt: new Date(ahora) },
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
actor: {
|
||||||
|
type: "agent",
|
||||||
|
keyId: record.id,
|
||||||
|
nombre: record.nombre,
|
||||||
|
prefijo: record.prefijo,
|
||||||
|
scopes: record.scopes,
|
||||||
|
rateLimitPerMin: record.rateLimitPerMin,
|
||||||
|
},
|
||||||
|
rateLimit: rl,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RequireActorOptions {
|
||||||
|
scopes?: AgentScope[];
|
||||||
|
scopeMode?: "any" | "all";
|
||||||
|
adminOnly?: boolean;
|
||||||
|
staffOnly?: boolean;
|
||||||
|
allowCliente?: boolean;
|
||||||
|
accionBloqueo?: string;
|
||||||
|
recursoTipo?: string;
|
||||||
|
recursoId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RequireActorResult =
|
||||||
|
| { ok: true; actor: ActorContext; rateLimitHeaders: Record<string, string> }
|
||||||
|
| { ok: false; response: NextResponse };
|
||||||
|
|
||||||
|
export async function requireActor(
|
||||||
|
request: NextRequest,
|
||||||
|
opts: RequireActorOptions = {}
|
||||||
|
): Promise<RequireActorResult> {
|
||||||
|
const attempt = await authenticateActor(request);
|
||||||
|
const rlHeaders = attempt.rateLimit ? buildRateLimitHeaders(attempt.rateLimit) : {};
|
||||||
|
|
||||||
|
if (attempt.rateLimited && attempt.actor) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: attempt.actor,
|
||||||
|
accion: "auth.rate_limit",
|
||||||
|
recursoTipo: opts.recursoTipo || "api",
|
||||||
|
recursoId: opts.recursoId,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: {
|
||||||
|
path: request.nextUrl.pathname,
|
||||||
|
limit: attempt.rateLimit?.limit,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{ error: "Limite de peticiones por minuto excedido. Intenta de nuevo mas tarde." },
|
||||||
|
{ status: 429, headers: rlHeaders }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!attempt.actor) {
|
||||||
|
if (attempt.invalidKey) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: { type: "system", nombre: "api-key-invalida" },
|
||||||
|
accion: "auth.api_key_invalida",
|
||||||
|
recursoTipo: opts.recursoTipo || "api",
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { path: request.nextUrl.pathname },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json({ error: "No autenticado" }, { status: 401 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const actor = attempt.actor;
|
||||||
|
|
||||||
|
// adminOnly: exclusivamente usuario humano con role === "admin"
|
||||||
|
if (opts.adminOnly) {
|
||||||
|
if (actor.type !== "user" || actor.role !== "admin") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: opts.accionBloqueo || "auth.admin_requerido",
|
||||||
|
recursoTipo: opts.recursoTipo || "api",
|
||||||
|
recursoId: opts.recursoId,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { path: request.nextUrl.pathname, actorType: actor.type },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{ error: "Accion restringida exclusivamente a un administrador humano" },
|
||||||
|
{ status: 403, headers: rlHeaders }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// staffOnly: exclusivamente usuario humano staff (admin o asesor)
|
||||||
|
if (opts.staffOnly) {
|
||||||
|
if (actor.type !== "user" || actor.role === "cliente") {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: opts.accionBloqueo || "auth.staff_requerido",
|
||||||
|
recursoTipo: opts.recursoTipo || "api",
|
||||||
|
recursoId: opts.recursoId,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: { path: request.nextUrl.pathname, actorType: actor.type },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{ error: "Accion restringida a personal humano" },
|
||||||
|
{ status: 403, headers: rlHeaders }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usuarios cliente: bloqueados salvo allowCliente
|
||||||
|
if (actor.type === "user" && actor.role === "cliente") {
|
||||||
|
if (!opts.allowCliente) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json({ error: "No autorizado" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usuarios staff (admin/asesor) pasan scopes de agente
|
||||||
|
if (actor.type === "user") {
|
||||||
|
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agente: validar scopes
|
||||||
|
if (opts.scopes && opts.scopes.length > 0) {
|
||||||
|
const okScope = actorTieneScope(actor, opts.scopes, opts.scopeMode ?? "any");
|
||||||
|
if (!okScope) {
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor,
|
||||||
|
accion: opts.accionBloqueo || "auth.scope_insuficiente",
|
||||||
|
recursoTipo: opts.recursoTipo || "api",
|
||||||
|
recursoId: opts.recursoId,
|
||||||
|
request,
|
||||||
|
exito: false,
|
||||||
|
detalle: {
|
||||||
|
path: request.nextUrl.pathname,
|
||||||
|
requiredScopes: opts.scopes,
|
||||||
|
actorScopes: actor.scopes,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json(
|
||||||
|
{
|
||||||
|
error: "Alcance insuficiente para esta operacion",
|
||||||
|
requiredScopes: opts.scopes,
|
||||||
|
},
|
||||||
|
{ status: 403, headers: rlHeaders }
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyHeaders(response: NextResponse, headers: Record<string, string>): NextResponse {
|
||||||
|
for (const [k, v] of Object.entries(headers)) {
|
||||||
|
response.headers.set(k, v);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { ESTADOS_COTIZACION, type EstadoCotizacion } from "@/lib/calculators";
|
||||||
|
import type { ActorContext } from "@/lib/agent-auth-core";
|
||||||
|
|
||||||
|
export { ESTADOS_COTIZACION, type EstadoCotizacion };
|
||||||
|
|
||||||
|
export type ViaTransicion = "aprobar" | "enlace_firmado" | "enviar" | "estado" | "put";
|
||||||
|
|
||||||
|
export interface ValidarTransicionInput {
|
||||||
|
actual: string;
|
||||||
|
nuevo: string;
|
||||||
|
actor: ActorContext | { type: "enlace_firmado" };
|
||||||
|
viaEndpoint: ViaTransicion;
|
||||||
|
aprobadaAt?: Date | string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ValidarTransicionResult {
|
||||||
|
ok: boolean;
|
||||||
|
status?: 400 | 403 | 409;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function esEstadoValido(estado: string): estado is EstadoCotizacion {
|
||||||
|
return (ESTADOS_COTIZACION as readonly string[]).includes(estado);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validarTransicionEstado(input: ValidarTransicionInput): ValidarTransicionResult {
|
||||||
|
const { actual, nuevo, actor, viaEndpoint, aprobadaAt } = input;
|
||||||
|
|
||||||
|
if (!esEstadoValido(nuevo)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 400,
|
||||||
|
error: `Estado invalido. Permitidos: ${ESTADOS_COTIZACION.join(", ")}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actual === nuevo) {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const esAdminHumano = actor.type === "user" && actor.role === "admin";
|
||||||
|
const esStaffHumano = actor.type === "user" && actor.role !== "cliente";
|
||||||
|
const esEnlaceFirmado = actor.type === "enlace_firmado" && viaEndpoint === "enlace_firmado";
|
||||||
|
const esAgente = actor.type === "agent";
|
||||||
|
|
||||||
|
// REGLA DE HIERRO 1: Nadie salvo admin humano o enlace firmado de un solo uso puede aprobar.
|
||||||
|
if (nuevo === "aprobada") {
|
||||||
|
if (!esAdminHumano && !esEnlaceFirmado) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
error: "Solo un administrador humano o el enlace firmado puede aprobar una cotizacion",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (actual !== "borrador") {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: `Solo se puede aprobar una cotizacion en borrador (estado actual: ${actual})`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// REGLA DE HIERRO 2: Nadie puede pasar a "enviada" sin estar previamente aprobada (con aprobadaAt).
|
||||||
|
if (nuevo === "enviada") {
|
||||||
|
if (esAgente && viaEndpoint !== "enviar") {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
error: "Los agentes solo pueden enviar cotizaciones mediante POST /api/cotizaciones/:id/enviar",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (actual !== "aprobada" || !aprobadaAt) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (esAgente) {
|
||||||
|
if (!actor.scopes.includes("cotizaciones:enviar")) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
error: "El agente no tiene el alcance cotizaciones:enviar",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
if (!esStaffHumano) {
|
||||||
|
return { ok: false, status: 403, error: "No autorizado para enviar cotizaciones" };
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reabrir a borrador: solo admin humano desde aprobada, rechazada o vencida.
|
||||||
|
if (nuevo === "borrador") {
|
||||||
|
if (!esAdminHumano) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
error: "Solo un administrador humano puede regresar una cotizacion a borrador",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!["aprobada", "rechazada", "vencida"].includes(actual)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: `No se puede regresar a borrador desde el estado ${actual}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Estados de cierre post-envio: aceptada | rechazada | vencida
|
||||||
|
if (["aceptada", "rechazada", "vencida"].includes(nuevo)) {
|
||||||
|
if (!esStaffHumano) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
error: "Solo el equipo humano puede marcar una cotizacion como aceptada, rechazada o vencida",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (actual !== "enviada") {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: `Solo se puede pasar a ${nuevo} desde el estado enviada (estado actual: ${actual})`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: `Transicion no permitida de ${actual} a ${nuevo}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { hashSecret } from "@/lib/agent-auth-core";
|
||||||
|
import { enviarCorreo } from "@/lib/email";
|
||||||
|
import { calcularTotalesCotizacion, formatCurrency, formatDate } from "@/lib/calculators";
|
||||||
|
import { registrarAuditoria } from "@/lib/audit";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
|
import {
|
||||||
|
ESTADOS_COTIZACION,
|
||||||
|
validarTransicionEstado,
|
||||||
|
type EstadoCotizacion,
|
||||||
|
type ValidarTransicionInput,
|
||||||
|
type ValidarTransicionResult,
|
||||||
|
type ViaTransicion,
|
||||||
|
} from "@/lib/aprobacion-core";
|
||||||
|
|
||||||
|
export {
|
||||||
|
ESTADOS_COTIZACION,
|
||||||
|
validarTransicionEstado,
|
||||||
|
type EstadoCotizacion,
|
||||||
|
type ValidarTransicionInput,
|
||||||
|
type ValidarTransicionResult,
|
||||||
|
type ViaTransicion,
|
||||||
|
};
|
||||||
|
|
||||||
|
const APPROVAL_TTL_MS = 72 * 60 * 60 * 1000; // 72 horas
|
||||||
|
|
||||||
|
export function appBaseUrl(): string {
|
||||||
|
return (process.env.APP_URL || "http://localhost:3000").replace(/\/+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function escHtml(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolverAdminNotifyEmail(): Promise<string | null> {
|
||||||
|
const fromEnv = process.env.ADMIN_NOTIFY_EMAIL?.trim();
|
||||||
|
if (fromEnv) return fromEnv;
|
||||||
|
const admin = await prisma.user.findFirst({
|
||||||
|
where: { role: "admin" },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
select: { email: true },
|
||||||
|
});
|
||||||
|
return admin?.email ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function crearEnlaceAprobacion(
|
||||||
|
cotizacionId: string
|
||||||
|
): Promise<{ url: string; expiraAt: Date }> {
|
||||||
|
const now = new Date();
|
||||||
|
const expiraAt = new Date(now.getTime() + APPROVAL_TTL_MS);
|
||||||
|
const rawToken = randomBytes(32).toString("hex");
|
||||||
|
const tokenHash = hashSecret(rawToken);
|
||||||
|
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
// Invalida tokens previos sin usar de esta cotizacion
|
||||||
|
await tx.approvalToken.updateMany({
|
||||||
|
where: { cotizacionId, usadoAt: null },
|
||||||
|
data: { expiraAt: now },
|
||||||
|
});
|
||||||
|
await tx.approvalToken.create({
|
||||||
|
data: {
|
||||||
|
cotizacionId,
|
||||||
|
tokenHash,
|
||||||
|
expiraAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
url: `${appBaseUrl()}/aprobar/${rawToken}`,
|
||||||
|
expiraAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function notificarJarethBorrador(
|
||||||
|
cotizacion: {
|
||||||
|
id: string;
|
||||||
|
numero: string;
|
||||||
|
proyecto: string;
|
||||||
|
moneda: string;
|
||||||
|
vigencia: Date;
|
||||||
|
incluirIva: boolean;
|
||||||
|
cliente: { nombre: string; empresa?: string | null };
|
||||||
|
servicios: Array<{ tipoPago: string; precio: number; seleccionado?: boolean }>;
|
||||||
|
},
|
||||||
|
enlaceAprobacion: { url: string; expiraAt: Date },
|
||||||
|
creadoPor: string
|
||||||
|
): Promise<{ ok: boolean; omitido?: boolean; destino?: string; error?: string }> {
|
||||||
|
try {
|
||||||
|
const destino = await resolverAdminNotifyEmail();
|
||||||
|
if (!destino) {
|
||||||
|
console.warn("[aprobacion] no hay ADMIN_NOTIFY_EMAIL ni usuario admin para notificar");
|
||||||
|
return { ok: false, omitido: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const totales = calcularTotalesCotizacion(cotizacion.servicios, {
|
||||||
|
incluirIva: cotizacion.incluirIva,
|
||||||
|
});
|
||||||
|
const partesMonto: string[] = [];
|
||||||
|
if (totales.totalUnico > 0) partesMonto.push(`Único: ${formatCurrency(totales.totalUnico)}`);
|
||||||
|
if (totales.totalMensual > 0) partesMonto.push(`Mensual: ${formatCurrency(totales.totalMensual)}/mes`);
|
||||||
|
const montoTexto = partesMonto.length ? partesMonto.join(" · ") : "$0";
|
||||||
|
const panelUrl = `${appBaseUrl()}/cotizaciones/${cotizacion.id}`;
|
||||||
|
|
||||||
|
const subject = `[Aprobación requerida] Borrador ${cotizacion.numero} — ${cotizacion.cliente.empresa || cotizacion.cliente.nombre}`;
|
||||||
|
const html = `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||||
|
<div style="max-width:580px;margin:0 auto;padding:32px 16px">
|
||||||
|
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||||
|
<p style="font-size:12px;letter-spacing:0.06em;color:#0400c4;font-weight:700;margin:0 0 6px">URIEL JARETH CONSULTING · APROBACIÓN</p>
|
||||||
|
<h1 style="font-size:20px;color:#0f172a;margin:0 0 12px">Nuevo borrador listo para revisión</h1>
|
||||||
|
<p style="font-size:14px;color:#334155;line-height:1.6;margin:0 0 16px">
|
||||||
|
Se generó un borrador de cotización y requiere tu aprobación humana antes de poder enviarse al cliente.
|
||||||
|
</p>
|
||||||
|
<div style="padding:14px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;color:#0f172a;line-height:1.7">
|
||||||
|
<div><strong>Folio:</strong> ${escHtml(cotizacion.numero)}</div>
|
||||||
|
<div><strong>Cliente:</strong> ${escHtml(cotizacion.cliente.nombre)}${cotizacion.cliente.empresa ? ` (${escHtml(cotizacion.cliente.empresa)})` : ""}</div>
|
||||||
|
<div><strong>Proyecto:</strong> ${escHtml(cotizacion.proyecto)}</div>
|
||||||
|
<div><strong>Total (${escHtml(cotizacion.moneda)}):</strong> ${escHtml(montoTexto)}</div>
|
||||||
|
<div><strong>Vigencia:</strong> ${escHtml(formatDate(cotizacion.vigencia))}</div>
|
||||||
|
<div><strong>Creada por:</strong> ${escHtml(creadoPor)}</div>
|
||||||
|
</div>
|
||||||
|
<p style="margin:24px 0 12px">
|
||||||
|
<a href="${enlaceAprobacion.url}" style="display:inline-block;background:#0400c4;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">
|
||||||
|
Revisar y aprobar cotización
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p style="font-size:13px;color:#475569;margin:0 0 12px">
|
||||||
|
O ábrela en el panel: <a href="${panelUrl}" style="color:#0400c4">${panelUrl}</a>
|
||||||
|
</p>
|
||||||
|
<p style="font-size:12px;color:#94a3b8;margin:16px 0 0">
|
||||||
|
Este enlace de aprobación es de un solo uso y expira el ${escHtml(enlaceAprobacion.expiraAt.toISOString())}. No lo compartas con terceros.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div></body></html>`;
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Nuevo borrador de cotización ${cotizacion.numero}`,
|
||||||
|
`Cliente: ${cotizacion.cliente.nombre}${cotizacion.cliente.empresa ? ` (${cotizacion.cliente.empresa})` : ""}`,
|
||||||
|
`Proyecto: ${cotizacion.proyecto}`,
|
||||||
|
`Total (${cotizacion.moneda}): ${montoTexto}`,
|
||||||
|
`Creada por: ${creadoPor}`,
|
||||||
|
`Enlace de aprobación (un solo uso): ${enlaceAprobacion.url}`,
|
||||||
|
`Panel: ${panelUrl}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const res = await enviarCorreo({ to: destino, subject, html, text });
|
||||||
|
return { ...res, destino };
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[aprobacion] fallo al notificar a Jareth:", err);
|
||||||
|
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function notificarJarethWhatsAppFueraVentana(
|
||||||
|
cotizacion: { id: string; numero: string; cliente: { nombre: string; empresa?: string | null } },
|
||||||
|
destino: string,
|
||||||
|
detalle?: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const adminEmail = await resolverAdminNotifyEmail();
|
||||||
|
if (!adminEmail) return false;
|
||||||
|
const panelUrl = `${appBaseUrl()}/cotizaciones/${cotizacion.id}`;
|
||||||
|
const res = await enviarCorreo({
|
||||||
|
to: adminEmail,
|
||||||
|
subject: `[WhatsApp 24h] No se pudo enviar cotización ${cotizacion.numero}`,
|
||||||
|
html: `<p>La cotización <strong>${escHtml(cotizacion.numero)}</strong> para <strong>${escHtml(cotizacion.cliente.nombre)}</strong> no pudo enviarse por WhatsApp a <code>${escHtml(destino)}</code> porque la conversación está fuera de la ventana de 24 horas.</p><p>${detalle ? escHtml(detalle) : ""}</p><p>Revisa o reenvía por correo desde: <a href="${panelUrl}">${panelUrl}</a></p>`,
|
||||||
|
text: `La cotización ${cotizacion.numero} para ${cotizacion.cliente.nombre} no pudo enviarse por WhatsApp (${destino}): fuera de ventana de 24h. Panel: ${panelUrl}`,
|
||||||
|
});
|
||||||
|
return res.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function aprobarCotizacionConToken(
|
||||||
|
rawToken: string,
|
||||||
|
ip: string | null
|
||||||
|
): Promise<
|
||||||
|
| { ok: true; cotizacionId: string; numero: string; aprobadaAt: Date }
|
||||||
|
| { ok: false; status: 404 | 409 | 410; error: string }
|
||||||
|
> {
|
||||||
|
const tokenHash = hashSecret(rawToken);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const resultado = await prisma.$transaction(async (tx) => {
|
||||||
|
const token = await tx.approvalToken.findUnique({
|
||||||
|
where: { tokenHash },
|
||||||
|
include: { cotizacion: { include: { cliente: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return { ok: false as const, status: 404 as const, error: "Enlace de aprobacion invalido" };
|
||||||
|
}
|
||||||
|
if (token.usadoAt) {
|
||||||
|
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ya fue utilizado" };
|
||||||
|
}
|
||||||
|
if (token.expiraAt <= now) {
|
||||||
|
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ha expirado" };
|
||||||
|
}
|
||||||
|
if (token.cotizacion.estado !== "borrador") {
|
||||||
|
return {
|
||||||
|
ok: false as const,
|
||||||
|
status: 409 as const,
|
||||||
|
error: `La cotizacion ya no esta en borrador (estado actual: ${token.cotizacion.estado})`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consumo atomico condicional para evitar doble aprobacion concurrente
|
||||||
|
const claimed = await tx.approvalToken.updateMany({
|
||||||
|
where: { id: token.id, usadoAt: null, expiraAt: { gt: now } },
|
||||||
|
data: { usadoAt: now, usadoIp: ip },
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) {
|
||||||
|
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ya fue utilizado" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalida cualquier otro token pendiente de la misma cotizacion
|
||||||
|
await tx.approvalToken.updateMany({
|
||||||
|
where: { cotizacionId: token.cotizacionId, usadoAt: null, id: { not: token.id } },
|
||||||
|
data: { expiraAt: now },
|
||||||
|
});
|
||||||
|
|
||||||
|
const cot = await tx.cotizacion.update({
|
||||||
|
where: { id: token.cotizacionId },
|
||||||
|
data: {
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaAt: now,
|
||||||
|
aprobacionMetodo: "enlace_firmado",
|
||||||
|
},
|
||||||
|
include: { cliente: true, servicios: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const tot = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
|
||||||
|
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
cotizacionId: cot.id,
|
||||||
|
numero: cot.numero,
|
||||||
|
proyecto: cot.proyecto,
|
||||||
|
moneda: cot.moneda,
|
||||||
|
total: totalWebhook,
|
||||||
|
aprobadaAt: now,
|
||||||
|
cliente: cot.cliente,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!resultado.ok) return resultado;
|
||||||
|
|
||||||
|
await registrarAuditoria({
|
||||||
|
actor: { type: "system", nombre: "enlace_firmado" },
|
||||||
|
accion: "cotizacion.aprobar",
|
||||||
|
recursoTipo: "cotizacion",
|
||||||
|
recursoId: resultado.cotizacionId,
|
||||||
|
exito: true,
|
||||||
|
detalle: { metodo: "enlace_firmado", ip },
|
||||||
|
});
|
||||||
|
|
||||||
|
void emitirWebhook("cotizacion.aprobada", {
|
||||||
|
cotizacionId: resultado.cotizacionId,
|
||||||
|
numero: resultado.numero,
|
||||||
|
folio: resultado.numero,
|
||||||
|
titulo: resultado.proyecto,
|
||||||
|
proyecto: resultado.proyecto,
|
||||||
|
moneda: resultado.moneda,
|
||||||
|
total: resultado.total,
|
||||||
|
url: `${appBaseUrl()}/cotizaciones/${resultado.cotizacionId}`,
|
||||||
|
estado: "aprobada",
|
||||||
|
aprobadaAt: resultado.aprobadaAt.toISOString(),
|
||||||
|
aprobacionMetodo: "enlace_firmado",
|
||||||
|
cliente: {
|
||||||
|
id: resultado.cliente.id,
|
||||||
|
nombre: resultado.cliente.nombre,
|
||||||
|
empresa: resultado.cliente.empresa,
|
||||||
|
email: resultado.cliente.email,
|
||||||
|
telefono: resultado.cliente.telefono,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
cotizacionId: resultado.cotizacionId,
|
||||||
|
numero: resultado.numero,
|
||||||
|
aprobadaAt: resultado.aprobadaAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
import type { Prisma } from "@/generated/prisma/client";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import type { ActorContext } from "@/lib/agent-auth-core";
|
||||||
|
|
||||||
|
export type AuditActor =
|
||||||
|
| ActorContext
|
||||||
|
| { type: "system"; nombre?: string; id?: string };
|
||||||
|
|
||||||
|
export function obtenerIp(request?: NextRequest | Request | null): string | null {
|
||||||
|
if (!request) return null;
|
||||||
|
const xff = request.headers.get("x-forwarded-for");
|
||||||
|
if (xff) {
|
||||||
|
const first = xff.split(",")[0]?.trim();
|
||||||
|
if (first) return first;
|
||||||
|
}
|
||||||
|
return request.headers.get("x-real-ip")?.trim() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registrarAuditoria(params: {
|
||||||
|
actor?: AuditActor | null;
|
||||||
|
accion: string;
|
||||||
|
recursoTipo: string;
|
||||||
|
recursoId?: string | null;
|
||||||
|
request?: NextRequest | Request | null;
|
||||||
|
exito?: boolean;
|
||||||
|
detalle?: Record<string, unknown> | null;
|
||||||
|
}): Promise<void> {
|
||||||
|
try {
|
||||||
|
let actorTipo = "system";
|
||||||
|
let actorId: string | null = null;
|
||||||
|
let actorNombre = "system";
|
||||||
|
|
||||||
|
if (params.actor) {
|
||||||
|
if (params.actor.type === "user") {
|
||||||
|
actorTipo = "user";
|
||||||
|
actorId = params.actor.userId;
|
||||||
|
actorNombre = params.actor.email || params.actor.name || params.actor.userId;
|
||||||
|
} else if (params.actor.type === "agent") {
|
||||||
|
actorTipo = "agent";
|
||||||
|
actorId = params.actor.keyId;
|
||||||
|
actorNombre = params.actor.nombre;
|
||||||
|
} else {
|
||||||
|
actorTipo = "system";
|
||||||
|
actorId = params.actor.id ?? null;
|
||||||
|
actorNombre = params.actor.nombre ?? "system";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestId = params.request?.headers.get("x-request-id") ?? null;
|
||||||
|
|
||||||
|
await prisma.auditLog.create({
|
||||||
|
data: {
|
||||||
|
actorTipo,
|
||||||
|
actorId,
|
||||||
|
actorNombre,
|
||||||
|
accion: params.accion,
|
||||||
|
recursoTipo: params.recursoTipo,
|
||||||
|
recursoId: params.recursoId ?? null,
|
||||||
|
ip: obtenerIp(params.request),
|
||||||
|
requestId,
|
||||||
|
exito: params.exito ?? true,
|
||||||
|
detalle: (params.detalle ?? undefined) as Prisma.InputJsonValue | undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[audit] fallo al registrar AuditLog:", params.accion, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -196,7 +196,7 @@ export const PLANES_BUCEFALO = [
|
|||||||
{ nivel: "empresarial", label: "Empresarial", precio: 7500 },
|
{ nivel: "empresarial", label: "Empresarial", precio: 7500 },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"] as const;
|
export const ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"] as const;
|
||||||
export type EstadoCotizacion = (typeof ESTADOS_COTIZACION)[number];
|
export type EstadoCotizacion = (typeof ESTADOS_COTIZACION)[number];
|
||||||
|
|
||||||
// ----- Registro de horas (notas de pago) -----
|
// ----- Registro de horas (notas de pago) -----
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
|
|
||||||
|
export const DEFAULT_COLOR_PRIMARIO = "#0400C4";
|
||||||
|
export const DEFAULT_COLOR_SECUNDARIO = "#0F172A";
|
||||||
|
|
||||||
export async function getConfigBranding() {
|
export async function getConfigBranding() {
|
||||||
try {
|
try {
|
||||||
const configs = await prisma.configuracion.findMany({
|
const configs = await prisma.configuracion.findMany({
|
||||||
@@ -8,13 +11,24 @@ export async function getConfigBranding() {
|
|||||||
const map: Record<string, string> = {};
|
const map: Record<string, string> = {};
|
||||||
for (const c of configs) map[c.clave] = c.valor;
|
for (const c of configs) map[c.clave] = c.valor;
|
||||||
return {
|
return {
|
||||||
colorPrimario: map.color_primario || undefined,
|
colorPrimario: map.color_primario || DEFAULT_COLOR_PRIMARIO,
|
||||||
colorSecundario: map.color_secundario || undefined,
|
colorSecundario: map.color_secundario || DEFAULT_COLOR_SECUNDARIO,
|
||||||
logoBase64: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":").slice(1).join(":") : map.logo_base64) : undefined,
|
logoBase64: map.logo_base64
|
||||||
logoMime: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":")[0] : "image/png") : undefined,
|
? map.logo_base64.includes(":")
|
||||||
|
? map.logo_base64.split(":").slice(1).join(":")
|
||||||
|
: map.logo_base64
|
||||||
|
: undefined,
|
||||||
|
logoMime: map.logo_base64
|
||||||
|
? map.logo_base64.includes(":")
|
||||||
|
? map.logo_base64.split(":")[0]
|
||||||
|
: "image/png"
|
||||||
|
: undefined,
|
||||||
};
|
};
|
||||||
} catch {
|
} catch {
|
||||||
return {};
|
return {
|
||||||
|
colorPrimario: DEFAULT_COLOR_PRIMARIO,
|
||||||
|
colorSecundario: DEFAULT_COLOR_SECUNDARIO,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
||||||
|
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||||
|
import { sanitizeFilename } from "@/lib/calculators";
|
||||||
|
|
||||||
|
export async function generarPDFCotizacion(cotizacionId: string) {
|
||||||
|
const [cot, config, branding, bonos] = await Promise.all([
|
||||||
|
prisma.cotizacion.findUnique({
|
||||||
|
where: { id: cotizacionId },
|
||||||
|
include: {
|
||||||
|
cliente: true,
|
||||||
|
asesor: { select: { id: true, name: true, email: true, role: true } },
|
||||||
|
servicios: {
|
||||||
|
include: { servicioCatalogo: true },
|
||||||
|
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||||
|
},
|
||||||
|
planBucefalo: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
getConfigBancaria(),
|
||||||
|
getConfigBranding(),
|
||||||
|
prisma.bono.findMany({ where: { activo: true }, orderBy: { numero: "asc" } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!cot) return null;
|
||||||
|
|
||||||
|
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||||
|
const filename = `${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}.pdf`;
|
||||||
|
|
||||||
|
const buffer = await generateCotizacionPDF({
|
||||||
|
numero: cot.numero,
|
||||||
|
clienteNombre: cot.cliente.nombre,
|
||||||
|
clienteEmpresa: cot.cliente.empresa || "",
|
||||||
|
asesorNombre: cot.asesor.name,
|
||||||
|
fecha: cot.fecha,
|
||||||
|
vigencia: cot.vigencia,
|
||||||
|
moneda: cot.moneda,
|
||||||
|
tipoCambio: cot.tipoCambio,
|
||||||
|
proyecto: cot.proyecto,
|
||||||
|
esquemaPago: cot.esquemaPago,
|
||||||
|
servicios: cot.servicios
|
||||||
|
.filter((s) => s.seleccionado)
|
||||||
|
.map((s) => ({
|
||||||
|
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||||
|
fase: s.fase,
|
||||||
|
tipoPago: s.tipoPago,
|
||||||
|
precio: s.precio,
|
||||||
|
tiempoEntrega: s.tiempoEntrega,
|
||||||
|
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
||||||
|
esPersonalizado: s.esPersonalizado,
|
||||||
|
horas: s.horas ?? undefined,
|
||||||
|
tarifaHora: s.tarifaHora ?? undefined,
|
||||||
|
modeloCobro: s.modeloCobro ?? undefined,
|
||||||
|
montoMinimo: s.montoMinimo ?? undefined,
|
||||||
|
horasIncluidas: s.horasIncluidas ?? undefined,
|
||||||
|
opcion: s.opcion ?? undefined,
|
||||||
|
})),
|
||||||
|
esDoble: cot.esDoble,
|
||||||
|
opcionesMetadata: cot.opcionesMetadata as never,
|
||||||
|
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||||
|
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
|
||||||
|
incluirBonos: cot.incluirBonos,
|
||||||
|
bonos,
|
||||||
|
incluirIva: cot.incluirIva,
|
||||||
|
// Solo el texto del cliente. observacionesInternas no se pasa nunca.
|
||||||
|
observaciones: cot.observaciones,
|
||||||
|
configBancaria: config,
|
||||||
|
...branding,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { buffer, filename, cot };
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ function createPrismaClient() {
|
|||||||
port: parseInt(process.env.DB_PORT || "5432"),
|
port: parseInt(process.env.DB_PORT || "5432"),
|
||||||
user: process.env.DB_USER || "postgres",
|
user: process.env.DB_USER || "postgres",
|
||||||
password: process.env.DB_PASSWORD || "postgres",
|
password: process.env.DB_PASSWORD || "postgres",
|
||||||
|
// Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||||
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
||||||
});
|
});
|
||||||
return new PrismaClient({ adapter });
|
return new PrismaClient({ adapter });
|
||||||
|
|||||||
+90
-3
@@ -9,8 +9,14 @@ import type { Transporter } from "nodemailer";
|
|||||||
// SMTP_PORT=587 (587=starttls, 465=ssl, 25=negociacion)
|
// SMTP_PORT=587 (587=starttls, 465=ssl, 25=negociacion)
|
||||||
// SMTP_USER=usuario
|
// SMTP_USER=usuario
|
||||||
// SMTP_PASS=contrasena
|
// SMTP_PASS=contrasena
|
||||||
// SMTP_FROM=co[email protected] (opcional, por defecto SMTP_USER)
|
// SMTP_FROM=co[email protected] (opcional, por defecto SMTP_USER)
|
||||||
// SMTP_FROM_NAME=Cotizador E3 (opcional)
|
// SMTP_FROM_NAME=Uriel Jareth Consulting (opcional)
|
||||||
|
|
||||||
|
export interface AdjuntoCorreo {
|
||||||
|
filename: string;
|
||||||
|
content: Buffer;
|
||||||
|
contentType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ResultadoEnvio {
|
export interface ResultadoEnvio {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
@@ -49,11 +55,20 @@ export function reiniciarTransport() {
|
|||||||
transport = undefined;
|
transport = undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escHtml(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """);
|
||||||
|
}
|
||||||
|
|
||||||
export async function enviarCorreo(opciones: {
|
export async function enviarCorreo(opciones: {
|
||||||
to: string;
|
to: string;
|
||||||
subject: string;
|
subject: string;
|
||||||
html: string;
|
html: string;
|
||||||
text?: string;
|
text?: string;
|
||||||
|
attachments?: AdjuntoCorreo[];
|
||||||
}): Promise<ResultadoEnvio> {
|
}): Promise<ResultadoEnvio> {
|
||||||
const t = obtenerTransport();
|
const t = obtenerTransport();
|
||||||
if (!t) {
|
if (!t) {
|
||||||
@@ -62,11 +77,16 @@ export async function enviarCorreo(opciones: {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await t.sendMail({
|
await t.sendMail({
|
||||||
from: `"${process.env.SMTP_FROM_NAME || "Cotizador E3"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
|
from: `"${process.env.SMTP_FROM_NAME || "Uriel Jareth Consulting"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
|
||||||
to: opciones.to,
|
to: opciones.to,
|
||||||
subject: opciones.subject,
|
subject: opciones.subject,
|
||||||
html: opciones.html,
|
html: opciones.html,
|
||||||
text: opciones.text,
|
text: opciones.text,
|
||||||
|
attachments: opciones.attachments?.map((a) => ({
|
||||||
|
filename: a.filename,
|
||||||
|
content: a.content,
|
||||||
|
contentType: a.contentType || "application/pdf",
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -75,3 +95,70 @@ export async function enviarCorreo(opciones: {
|
|||||||
return { ok: false, error: msg };
|
return { ok: false, error: msg };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function enviarCotizacionPorCorreo(opts: {
|
||||||
|
to: string;
|
||||||
|
numero: string;
|
||||||
|
clienteNombre: string;
|
||||||
|
empresa?: string | null;
|
||||||
|
proyecto: string;
|
||||||
|
resumenTotales: string;
|
||||||
|
vigenciaTexto: string;
|
||||||
|
pdfBuffer: Buffer;
|
||||||
|
pdfFilename: string;
|
||||||
|
mensajePersonalizado?: string;
|
||||||
|
}): Promise<ResultadoEnvio> {
|
||||||
|
const asunto = `Cotización ${opts.numero} — ${opts.proyecto} | Uriel Jareth Consulting`;
|
||||||
|
const mensajeExtra = opts.mensajePersonalizado?.trim()
|
||||||
|
? `<p style="margin:12px 0;white-space:pre-line">${escHtml(opts.mensajePersonalizado.trim())}</p>`
|
||||||
|
: "";
|
||||||
|
const empresaTexto = opts.empresa ? ` (${escHtml(opts.empresa)})` : "";
|
||||||
|
const html = `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||||
|
<div style="max-width:580px;margin:0 auto;padding:32px 16px">
|
||||||
|
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||||
|
<p style="font-size:12px;letter-spacing:0.06em;color:#0400c4;font-weight:700;margin:0 0 6px">URIEL JARETH CONSULTING</p>
|
||||||
|
<h1 style="font-size:20px;color:#0f172a;margin:0 0 16px">Cotización ${escHtml(opts.numero)}</h1>
|
||||||
|
<p style="font-size:15px;color:#334155;line-height:1.6;margin:0 0 12px">
|
||||||
|
Hola <strong>${escHtml(opts.clienteNombre)}</strong>${empresaTexto},
|
||||||
|
</p>
|
||||||
|
<p style="font-size:15px;color:#334155;line-height:1.6;margin:0 0 16px">
|
||||||
|
Adjuntamos en formato PDF la propuesta para <strong>${escHtml(opts.proyecto)}</strong>.
|
||||||
|
</p>
|
||||||
|
${mensajeExtra}
|
||||||
|
<div style="margin:18px 0;padding:14px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;color:#0f172a">
|
||||||
|
<div><strong>Folio:</strong> ${escHtml(opts.numero)}</div>
|
||||||
|
<div><strong>Resumen:</strong> ${escHtml(opts.resumenTotales)}</div>
|
||||||
|
<div><strong>Vigencia:</strong> ${escHtml(opts.vigenciaTexto)}</div>
|
||||||
|
</div>
|
||||||
|
<p style="font-size:14px;color:#475569;line-height:1.6;margin:16px 0 0">
|
||||||
|
Quedamos atentos a cualquier duda o ajuste que necesites revisar.
|
||||||
|
</p>
|
||||||
|
<p style="font-size:12px;color:#94a3b8;margin:24px 0 0">Uriel Jareth Consulting · urieljareth.com</p>
|
||||||
|
</div>
|
||||||
|
</div></body></html>`;
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Hola ${opts.clienteNombre},`,
|
||||||
|
`Adjuntamos en PDF la cotización ${opts.numero} para ${opts.proyecto}.`,
|
||||||
|
opts.mensajePersonalizado?.trim() || "",
|
||||||
|
`Resumen: ${opts.resumenTotales}`,
|
||||||
|
`Vigencia: ${opts.vigenciaTexto}`,
|
||||||
|
"Uriel Jareth Consulting · urieljareth.com",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("\n\n");
|
||||||
|
|
||||||
|
return enviarCorreo({
|
||||||
|
to: opts.to,
|
||||||
|
subject: asunto,
|
||||||
|
html,
|
||||||
|
text,
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
filename: opts.pdfFilename.endsWith(".pdf") ? opts.pdfFilename : `${opts.pdfFilename}.pdf`,
|
||||||
|
content: opts.pdfBuffer,
|
||||||
|
contentType: "application/pdf",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ export interface ExcelData {
|
|||||||
colorSecundario: string;
|
colorSecundario: string;
|
||||||
incluirIva?: boolean;
|
incluirIva?: boolean;
|
||||||
/** Texto que SI ve el cliente. El Excel es un documento del cliente (lleva razon
|
/** Texto que SI ve el cliente. El Excel es un documento del cliente (lleva razon
|
||||||
* social, "En atencion a:", domicilio fiscal y nota legal), no una herramienta
|
* social, "En atencion a:" y nota legal), no una herramienta
|
||||||
* interna: por eso `observacionesInternas` NO se declara aqui. */
|
* interna: por eso `observacionesInternas` NO se declara aqui. */
|
||||||
observaciones?: string | null;
|
observaciones?: string | null;
|
||||||
}
|
}
|
||||||
@@ -119,16 +119,16 @@ function setWrapped(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
||||||
const PRIMARY = argb(data.colorPrimario || "#2563eb");
|
const PRIMARY = argb(data.colorPrimario || "#0400C4");
|
||||||
const PRIMARY_LIGHT = argb(data.colorPrimario || "#2563eb", "18");
|
const PRIMARY_LIGHT = argb(data.colorPrimario || "#0400C4", "18");
|
||||||
const SECONDARY = argb(data.colorSecundario || "#1e293b");
|
const SECONDARY = argb(data.colorSecundario || "#0F172A");
|
||||||
const WHITE = "FFFFFFFF";
|
const WHITE = "FFFFFFFF";
|
||||||
const LIGHT_BG = "FFF8FAFC";
|
const LIGHT_BG = "FFF8FAFC";
|
||||||
const MUTED = "FF64748B";
|
const MUTED = "FF64748B";
|
||||||
const BORDER_COLOR = "FFE2E8F0";
|
const BORDER_COLOR = "FFE2E8F0";
|
||||||
|
|
||||||
const workbook = new ExcelJS.Workbook();
|
const workbook = new ExcelJS.Workbook();
|
||||||
workbook.creator = "Cotizador E3";
|
workbook.creator = "Cotizador — Uriel Jareth Consulting";
|
||||||
workbook.created = new Date();
|
workbook.created = new Date();
|
||||||
|
|
||||||
const headerFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: WHITE } };
|
const headerFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: WHITE } };
|
||||||
@@ -405,7 +405,7 @@ export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
|||||||
setWrapped(ws, row, "B", notaResumen, mergedWidth(ws, "B", "K"), { fontSize: 9 });
|
setWrapped(ws, row, "B", notaResumen, mergedWidth(ws, "B", "K"), { fontSize: 9 });
|
||||||
|
|
||||||
// Observaciones del cliente. Solo este campo: el Excel lleva razon social,
|
// Observaciones del cliente. Solo este campo: el Excel lleva razon social,
|
||||||
// "En atencion a:" y domicilio fiscal, o sea que es un documento que el cliente
|
// "En atencion a:" y nota legal, o sea que es un documento que el cliente
|
||||||
// recibe. observacionesInternas no existe en ExcelData a proposito.
|
// recibe. observacionesInternas no existe en ExcelData a proposito.
|
||||||
if (data.observaciones && data.observaciones.trim()) {
|
if (data.observaciones && data.observaciones.trim()) {
|
||||||
row += 2;
|
row += 2;
|
||||||
@@ -556,13 +556,7 @@ export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
|||||||
dw.mergeCells(`B${r}:J${r}`);
|
dw.mergeCells(`B${r}:J${r}`);
|
||||||
dw.getCell(`B${r}`).value = data.razonSocial;
|
dw.getCell(`B${r}`).value = data.razonSocial;
|
||||||
dw.getCell(`B${r}`).font = { ...boldFont, color: { argb: PRIMARY } };
|
dw.getCell(`B${r}`).font = { ...boldFont, color: { argb: PRIMARY } };
|
||||||
if (data.domicilioFiscal) {
|
// Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados.
|
||||||
r++;
|
|
||||||
dw.mergeCells(`B${r}:J${r}`);
|
|
||||||
dw.getCell(`B${r}`).value = data.domicilioFiscal;
|
|
||||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
|
||||||
setWrapped(dw, r, "B", data.domicilioFiscal, mergedWidth(dw, "B", "J"), { fontSize: 9 });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const buffer = await workbook.xlsx.writeBuffer();
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import type { Prisma } from "@/generated/prisma/client";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { hashSecret } from "@/lib/agent-auth-core";
|
||||||
|
|
||||||
|
const TTL_MS = 24 * 60 * 60 * 1000; // 24 horas
|
||||||
|
|
||||||
|
export interface IdempotentContext {
|
||||||
|
rawBody: string;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function withIdempotency(
|
||||||
|
request: NextRequest,
|
||||||
|
actorKey: string,
|
||||||
|
handler: (ctx: IdempotentContext) => Promise<NextResponse>
|
||||||
|
): Promise<NextResponse> {
|
||||||
|
const rawBody = await request.text();
|
||||||
|
let parsedBody: unknown = null;
|
||||||
|
if (rawBody.trim()) {
|
||||||
|
try {
|
||||||
|
parsedBody = JSON.parse(rawBody);
|
||||||
|
} catch {
|
||||||
|
parsedBody = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const idemHeader = request.headers.get("idempotency-key")?.trim();
|
||||||
|
if (!idemHeader) {
|
||||||
|
return handler({ rawBody, body: parsedBody });
|
||||||
|
}
|
||||||
|
|
||||||
|
const method = request.method.toUpperCase();
|
||||||
|
const pathname = request.nextUrl.pathname;
|
||||||
|
const composedKey = `${actorKey}:${method}:${pathname}:${idemHeader}`;
|
||||||
|
const requestHash = hashSecret(rawBody);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const existing = await prisma.idempotencyKey.findUnique({
|
||||||
|
where: { key: composedKey },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing && existing.expiraAt > now) {
|
||||||
|
if (existing.requestHash !== requestHash) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
"Conflicto de idempotencia: Idempotency-Key ya fue usada con un cuerpo distinto",
|
||||||
|
},
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const replayed = NextResponse.json(existing.responseBody, {
|
||||||
|
status: existing.statusCode,
|
||||||
|
});
|
||||||
|
replayed.headers.set("X-Idempotency-Replayed", "true");
|
||||||
|
return replayed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing && existing.expiraAt <= now) {
|
||||||
|
await prisma.idempotencyKey.delete({ where: { key: composedKey } }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await handler({ rawBody, body: parsedBody });
|
||||||
|
|
||||||
|
if (response.status < 500) {
|
||||||
|
try {
|
||||||
|
const cloned = response.clone();
|
||||||
|
const responseJson = await cloned.json().catch(() => ({ ok: response.ok }));
|
||||||
|
await prisma.idempotencyKey.upsert({
|
||||||
|
where: { key: composedKey },
|
||||||
|
create: {
|
||||||
|
key: composedKey,
|
||||||
|
method,
|
||||||
|
path: pathname,
|
||||||
|
requestHash,
|
||||||
|
statusCode: response.status,
|
||||||
|
responseBody: responseJson as Prisma.InputJsonValue,
|
||||||
|
expiraAt: new Date(Date.now() + TTL_MS),
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
requestHash,
|
||||||
|
statusCode: response.status,
|
||||||
|
responseBody: responseJson as Prisma.InputJsonValue,
|
||||||
|
expiraAt: new Date(Date.now() + TTL_MS),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[idempotency] fallo al guardar clave:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
@@ -70,8 +70,8 @@ export async function generateNotaHorasPDF(data: NotaHorasPDFData): Promise<Buff
|
|||||||
const logoBuffer = data.logoBase64 ? await toPngBuffer(data.logoBase64, data.logoMime) : undefined;
|
const logoBuffer = data.logoBase64 ? await toPngBuffer(data.logoBase64, data.logoMime) : undefined;
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const PRIMARY = data.colorPrimario || "#2563eb";
|
const PRIMARY = data.colorPrimario || "#0400C4";
|
||||||
const DARK = data.colorSecundario || "#111827";
|
const DARK = data.colorSecundario || "#0F172A";
|
||||||
const MUTED = "#6b7280";
|
const MUTED = "#6b7280";
|
||||||
const BORDER = "#d1d5db";
|
const BORDER = "#d1d5db";
|
||||||
const HEAD_BG = "#f3f4f6";
|
const HEAD_BG = "#f3f4f6";
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
type PagoPorCobrar,
|
type PagoPorCobrar,
|
||||||
} from "@/lib/cobros";
|
} from "@/lib/cobros";
|
||||||
import type { PagoRecurrente } from "@/generated/prisma/client";
|
import type { PagoRecurrente } from "@/generated/prisma/client";
|
||||||
|
import { emitirWebhook } from "@/lib/webhooks";
|
||||||
|
|
||||||
// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es
|
// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es
|
||||||
// best-effort: un fallo de correo/push jamas revienta el flujo que lo llamo
|
// best-effort: un fallo de correo/push jamas revienta el flujo que lo llamo
|
||||||
@@ -53,16 +54,16 @@ function formatoMoneda(monto: number, moneda: string): string {
|
|||||||
|
|
||||||
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
|
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
|
||||||
const botonHtml = boton
|
const botonHtml = boton
|
||||||
? `<p style="margin:24px 0"><a href="${boton.url}" style="background:#0f172a;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">${boton.texto}</a></p>`
|
? `<p style="margin:24px 0"><a href="${boton.url}" style="background:#0400c4;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">${boton.texto}</a></p>`
|
||||||
: "";
|
: "";
|
||||||
return `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
return `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||||
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
|
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
|
||||||
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||||
<p style="font-size:13px;color:#71717a;margin:0 0 4px">COTIZADOR E3</p>
|
<p style="font-size:13px;color:#64748b;margin:0 0 4px">URIEL JARETH CONSULTING</p>
|
||||||
<h1 style="font-size:20px;color:#18181b;margin:0 0 16px">${esc(titulo)}</h1>
|
<h1 style="font-size:20px;color:#18181b;margin:0 0 16px">${esc(titulo)}</h1>
|
||||||
<div style="font-size:15px;color:#3f3f46;line-height:1.6">${cuerpo}</div>
|
<div style="font-size:15px;color:#3f3f46;line-height:1.6">${cuerpo}</div>
|
||||||
${botonHtml}
|
${botonHtml}
|
||||||
<p style="font-size:12px;color:#a1a1aa;margin:24px 0 0">Consultoría E3 · Querétaro, México</p>
|
<p style="font-size:12px;color:#a1a1aa;margin:24px 0 0">Uriel Jareth Consulting · urieljareth.com</p>
|
||||||
</div>
|
</div>
|
||||||
</div></body></html>`;
|
</div></body></html>`;
|
||||||
}
|
}
|
||||||
@@ -422,6 +423,29 @@ export async function enviarRecordatoriosPendientes(
|
|||||||
console.error("[notificaciones] fallo el recordatorio del cliente", clienteId, e);
|
console.error("[notificaciones] fallo el recordatorio del cliente", clienteId, e);
|
||||||
resultado.correo = "error";
|
resultado.correo = "error";
|
||||||
}
|
}
|
||||||
|
// Emision best-effort del webhook pago.vencido sin alterar ni duplicar correos/push.
|
||||||
|
void emitirWebhook("pago.vencido", {
|
||||||
|
clienteId,
|
||||||
|
cliente: {
|
||||||
|
id: clienteId,
|
||||||
|
nombre: cliente.nombre,
|
||||||
|
empresa: cliente.empresa ?? null,
|
||||||
|
email: cliente.usuario?.email || cliente.email || null,
|
||||||
|
},
|
||||||
|
totales: resultado.totales,
|
||||||
|
pagos: lista.map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
programaId: p.programaId,
|
||||||
|
concepto: p.programa.concepto,
|
||||||
|
fecha: p.fecha.toISOString().slice(0, 10),
|
||||||
|
monto: p.monto,
|
||||||
|
moneda: p.programa.moneda,
|
||||||
|
estado: p.estado,
|
||||||
|
diasAtraso: diasDeAtraso(p.fecha, hoy),
|
||||||
|
})),
|
||||||
|
recordatorioEntregado: resultado.entregado,
|
||||||
|
});
|
||||||
|
|
||||||
resultados.push(resultado);
|
resultados.push(resultado);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,8 +90,8 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
|
|||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const PRIMARY = data.colorPrimario || "#2563eb";
|
const PRIMARY = data.colorPrimario || "#0400C4";
|
||||||
const DARK = data.colorSecundario || "#1e293b";
|
const DARK = data.colorSecundario || "#0F172A";
|
||||||
const MUTED = "#64748b";
|
const MUTED = "#64748b";
|
||||||
const BORDER = "#cbd5e1";
|
const BORDER = "#cbd5e1";
|
||||||
const LIGHT_BG = "#f1f5f9";
|
const LIGHT_BG = "#f1f5f9";
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export interface DatosPropuestaPDF {
|
|||||||
const COLOR_SEMAFORO: Record<string, string> = {
|
const COLOR_SEMAFORO: Record<string, string> = {
|
||||||
rojo: "#dc2626",
|
rojo: "#dc2626",
|
||||||
ambar: "#d97706",
|
ambar: "#d97706",
|
||||||
azul: "#2563eb",
|
azul: "#0400C4",
|
||||||
verde: "#16a34a",
|
verde: "#16a34a",
|
||||||
};
|
};
|
||||||
const ETIQUETA_SEMAFORO: Record<string, string> = {
|
const ETIQUETA_SEMAFORO: Record<string, string> = {
|
||||||
@@ -102,8 +102,8 @@ function crearLienzo(): { lienzo: Lienzo; listo: Promise<Buffer> } {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function generarPropuestaPDF(d: DatosPropuestaPDF): Promise<Buffer> {
|
export async function generarPropuestaPDF(d: DatosPropuestaPDF): Promise<Buffer> {
|
||||||
const PRIMARY = hexSeguro(d.branding.colorPrimario, "#2563eb");
|
const PRIMARY = hexSeguro(d.branding.colorPrimario, "#0400C4");
|
||||||
const DARK = hexSeguro(d.branding.colorSecundario, "#1e293b");
|
const DARK = hexSeguro(d.branding.colorSecundario, "#0F172A");
|
||||||
const MUTED = "#64748b";
|
const MUTED = "#64748b";
|
||||||
const BORDER = "#e2e8f0";
|
const BORDER = "#e2e8f0";
|
||||||
|
|
||||||
@@ -420,7 +420,7 @@ export async function generarAnexoInternoPDF(d: DatosPropuestaPDF): Promise<Buff
|
|||||||
const { lienzo, listo } = crearLienzo();
|
const { lienzo, listo } = crearLienzo();
|
||||||
const { doc, W, L, maxY, mTop } = lienzo;
|
const { doc, W, L, maxY, mTop } = lienzo;
|
||||||
let y = mTop;
|
let y = mTop;
|
||||||
const DARK = "#1e293b";
|
const DARK = "#0F172A";
|
||||||
const MUTED = "#64748b";
|
const MUTED = "#64748b";
|
||||||
const need = (h: number, yy: number) => (yy + h > maxY ? (doc.addPage(), mTop) : yy);
|
const need = (h: number, yy: number) => (yy + h > maxY ? (doc.addPage(), mTop) : yy);
|
||||||
const txtH = (s: string, w: number, size: number) =>
|
const txtH = (s: string, w: number, size: number) =>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user