From 0d4f19f35dbdd643b3ff480667f62dd535036ae5 Mon Sep 17 00:00:00 2001 From: urieljareth Date: Wed, 25 Nov 2026 00:55:18 -0600 Subject: [PATCH] feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC --- .claude/skills/cotizador-cli/SKILL.md | 4 +- .env.example | 52 +- AGENTS.md | 15 +- Dockerfile | 3 +- README.md | 20 +- api/.env.example | 2 + api/COTIZADOR_API_SKILL.md | 477 ++--------------- api/app/auth.py | 307 ++++++++++- api/app/config.py | 2 + api/app/models/common.py | 4 +- api/app/models/configuracion.py | 4 +- api/app/models/cotizacion.py | 68 +-- api/app/routers/bonos.py | 4 +- api/app/routers/catalogo.py | 12 +- api/app/routers/categorias.py | 12 +- api/app/routers/clientes.py | 12 +- api/app/routers/cobros.py | 157 ++++++ api/app/routers/configuracion.py | 6 +- api/app/routers/cotizaciones.py | 482 +++++++++++++---- api/app/routers/export_.py | 34 +- api/app/routers/financiamiento.py | 8 +- api/app/routers/health.py | 4 +- api/app/routers/import_.py | 4 +- api/app/routers/paquetes.py | 14 +- api/app/services/calculators.py | 83 ++- api/app/services/excel_generator.py | 18 +- api/app/services/pdf_generator.py | 6 +- api/main.py | 15 +- cli/cotizador.mjs | 23 +- docker-compose.coolify.yml | 14 +- docker-compose.yaml | 14 +- docker-compose.yml | 5 +- docs/CLI.md | 8 +- docs/paquetes-recomendados-pyme.md | 2 +- package-lock.json | 4 +- package.json | 5 +- prisma.config.ts | 1 + .../migration.sql | 139 +++++ prisma/schema.prisma | 110 ++++ prisma/seed.ts | 15 +- public/sw.js | 2 +- scripts/provision-agent-keys.ts | 248 +++++++++ scripts/verificar-propuesta-pdf.ts | 2 +- scripts/verificar-propuesta-schemas.ts | 2 +- .../configuracion/ConfiguracionClient.tsx | 9 +- .../[id]/CambiarEstadoButtons.tsx | 358 ++++++++++++- .../cotizaciones/[id]/RegistroHorasPanel.tsx | 4 +- src/app/(app)/cotizaciones/[id]/page.tsx | 36 +- src/app/(app)/page.tsx | 4 +- src/app/api/agent-keys/[id]/revoke/route.ts | 54 ++ src/app/api/agent-keys/[id]/rotate/route.ts | 60 +++ src/app/api/agent-keys/route.ts | 110 ++++ src/app/api/aprobar/[token]/route.ts | 120 +++++ src/app/api/audit-logs/route.ts | 46 ++ src/app/api/catalogo/route.ts | 31 +- src/app/api/categorias/route.ts | 14 +- src/app/api/clientes/[id]/route.ts | 54 +- src/app/api/clientes/route.ts | 79 ++- .../api/cobros/pagos/[id]/aprobar/route.ts | 47 +- .../api/cobros/pagos/[id]/registrar/route.ts | 133 +++-- src/app/api/cobros/pagos/route.ts | 16 +- src/app/api/cobros/programas/route.ts | 24 +- .../api/cotizaciones/[id]/aprobar/route.ts | 121 +++++ src/app/api/cotizaciones/[id]/enviar/route.ts | 374 +++++++++++++ src/app/api/cotizaciones/[id]/estado/route.ts | 154 ++++++ src/app/api/cotizaciones/[id]/precio/route.ts | 67 ++- src/app/api/cotizaciones/[id]/route.ts | 348 ++++++++++-- .../[id]/solicitar-aprobacion/route.ts | 76 +++ src/app/api/cotizaciones/route.ts | 497 ++++++++++++------ src/app/api/export/excel/[id]/route.ts | 7 +- src/app/api/export/excel/route.ts | 7 +- src/app/api/export/pdf/[id]/route.ts | 131 ++--- src/app/api/health/route.ts | 16 +- src/app/api/openapi.json/route.ts | 329 ++++++++++++ src/app/api/paquetes/route.ts | 14 +- src/app/api/webhooks/[id]/route.ts | 41 ++ src/app/api/webhooks/deliveries/route.ts | 29 + src/app/api/webhooks/route.ts | 103 ++++ src/app/aprobar/[token]/AprobarClient.tsx | 197 +++++++ src/app/aprobar/[token]/page.tsx | 85 +++ src/app/cliente/ClienteShell.tsx | 2 +- src/app/globals.css | 25 +- src/app/layout.tsx | 19 +- src/components/EstadoBadge.tsx | 21 +- src/lib/agent-auth-core.ts | 164 ++++++ src/lib/agent-auth.ts | 296 +++++++++++ src/lib/aprobacion-core.ts | 140 +++++ src/lib/aprobacion.ts | 291 ++++++++++ src/lib/audit.ts | 69 +++ src/lib/calculators.ts | 2 +- src/lib/config-helpers.ts | 24 +- src/lib/cotizacion-pdf.ts | 72 +++ src/lib/db.ts | 1 + src/lib/email.ts | 93 +++- src/lib/excel-builder.ts | 20 +- src/lib/idempotency.ts | 94 ++++ src/lib/nota-horas-pdf.ts | 4 +- src/lib/notificaciones.ts | 30 +- src/lib/pdf-generator.ts | 4 +- src/lib/propuesta/pdf.ts | 8 +- src/lib/propuesta/prompts.ts | 10 +- src/lib/propuesta/schemas.ts | 4 +- src/lib/webhooks-core.ts | 38 ++ src/lib/webhooks.ts | 250 +++++++++ src/middleware.ts | 28 + start.bat | 6 +- stop.bat | 4 +- tests/approval-guard.test.ts | 182 +++++++ tests/auth-scopes.test.ts | 147 ++++++ tests/calculators-parity.test.ts | 122 +++++ tests/webhooks-hmac.test.ts | 51 ++ 111 files changed, 7167 insertions(+), 1272 deletions(-) create mode 100644 api/app/routers/cobros.py create mode 100644 prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql create mode 100644 scripts/provision-agent-keys.ts create mode 100644 src/app/api/agent-keys/[id]/revoke/route.ts create mode 100644 src/app/api/agent-keys/[id]/rotate/route.ts create mode 100644 src/app/api/agent-keys/route.ts create mode 100644 src/app/api/aprobar/[token]/route.ts create mode 100644 src/app/api/audit-logs/route.ts create mode 100644 src/app/api/cotizaciones/[id]/aprobar/route.ts create mode 100644 src/app/api/cotizaciones/[id]/enviar/route.ts create mode 100644 src/app/api/cotizaciones/[id]/estado/route.ts create mode 100644 src/app/api/cotizaciones/[id]/solicitar-aprobacion/route.ts create mode 100644 src/app/api/openapi.json/route.ts create mode 100644 src/app/api/webhooks/[id]/route.ts create mode 100644 src/app/api/webhooks/deliveries/route.ts create mode 100644 src/app/api/webhooks/route.ts create mode 100644 src/app/aprobar/[token]/AprobarClient.tsx create mode 100644 src/app/aprobar/[token]/page.tsx create mode 100644 src/lib/agent-auth-core.ts create mode 100644 src/lib/agent-auth.ts create mode 100644 src/lib/aprobacion-core.ts create mode 100644 src/lib/aprobacion.ts create mode 100644 src/lib/audit.ts create mode 100644 src/lib/cotizacion-pdf.ts create mode 100644 src/lib/idempotency.ts create mode 100644 src/lib/webhooks-core.ts create mode 100644 src/lib/webhooks.ts create mode 100644 tests/approval-guard.test.ts create mode 100644 tests/auth-scopes.test.ts create mode 100644 tests/calculators-parity.test.ts create mode 100644 tests/webhooks-hmac.test.ts diff --git a/.claude/skills/cotizador-cli/SKILL.md b/.claude/skills/cotizador-cli/SKILL.md index 2441350..a4c3c36 100644 --- a/.claude/skills/cotizador-cli/SKILL.md +++ b/.claude/skills/cotizador-cli/SKILL.md @@ -1,9 +1,9 @@ --- 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 `. diff --git a/.env.example b/.env.example index 0e20c16..e956fc0 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,8 @@ -# Cotizador E3 — variables de entorno -# Copia este archivo a .env (local) o configúralas en Coolify (producción). +# Cotizador — Uriel Jareth Consulting — variables de entorno +# 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_PORT=5432 DB_USER=postgres @@ -9,19 +10,19 @@ DB_PASSWORD=postgres DB_NAME=cotizador_e3 # 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" -# ── Auth ── +# ── Auth ── # OBLIGATORIA. Genera una con: openssl rand -base64 32 JWT_SECRET= -# ── API Python (api/) — clave para agentes de IA / n8n ── +# ── API Python (api/) — clave para agentes de IA / n8n ── 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 -SEED_ADMIN_EMAIL=admin@e3.local +SEED_ADMIN_EMAIL=admin@urieljareth.com SEED_ADMIN_PASSWORD= SEED_ADMIN_NAME=Administrador # Asesor opcional: solo se crea si defines el email @@ -30,35 +31,46 @@ SEED_ASESOR_PASSWORD= SEED_ASESOR_NAME= # --- 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 -# mandaria la clave de MiniMax a api.anthropic.com. +# mandaría la clave de MiniMax a api.anthropic.com. MINIMAX_API_KEY= MINIMAX_BASE_URL=https://api.minimax.io/anthropic MINIMAX_MODEL=MiniMax-M3 # --- 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). VAPID_PUBLIC_KEY= VAPID_PRIVATE_KEY= -# URL publica (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. +# URL pública (links de correo y notificaciones). En Coolify: el dominio del servicio web. +# Variable de servidor: un NEXT_PUBLIC_* quedaría fijo en el bundle al compilar. 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_PORT=587 SMTP_USER= SMTP_PASS= 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 -# estado de cuenta mientras siga debiendo cobros (desde las 9:00 hora de Mexico). -# 0 apaga el automatico; el boton "Enviar recordatorio" de /cobros sigue sirviendo. +# 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 México). +# 0 apaga el automático; el botón "Enviar recordatorio" de /cobros sigue sirviendo. COBROS_RECORDATORIO_DIAS=3 -# Directorio de comprobantes. Local: vacio = /uploads. +# Directorio de comprobantes. Local: vacío = /uploads. # En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml). -UPLOAD_DIR= \ No newline at end of file +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 diff --git a/AGENTS.md b/AGENTS.md index f26169a..0908ebf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,4 @@ -# AGENTS.md — Cotizador E3 +# AGENTS.md — Cotizador — Uriel Jareth Consulting ## Quick Reference @@ -86,7 +86,7 @@ A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — se ## 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. - `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). @@ -160,5 +160,14 @@ docs/ # Business/product notes (Spanish), not code docs ## 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`. diff --git a/Dockerfile b/Dockerfile index 84a97f6..db4aa99 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 # `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/public ./public COPY --from=builder /app/prisma ./prisma +COPY --from=builder /app/scripts ./scripts COPY --from=builder /app/src/generated ./src/generated COPY --from=builder /app/prisma.config.ts ./prisma.config.ts COPY --from=builder /app/next.config.ts ./next.config.ts diff --git a/README.md b/README.md index d255697..31ba013 100644 --- a/README.md +++ b/README.md @@ -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 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 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/`) 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 +``` diff --git a/api/.env.example b/api/.env.example index 1864ac7..e94d4a1 100644 --- a/api/.env.example +++ b/api/.env.example @@ -3,6 +3,7 @@ DB_HOST=localhost DB_PORT=5432 DB_USER=postgres DB_PASSWORD=postgres +# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. DB_NAME=cotizador_e3 # Auth @@ -12,3 +13,4 @@ JWT_SECRET=change-me-to-a-secure-jwt-secret # Server API_HOST=0.0.0.0 API_PORT=8000 +ALLOW_LEGACY_API_KEY=false diff --git a/api/COTIZADOR_API_SKILL.md b/api/COTIZADOR_API_SKILL.md index f92fc0d..bc4fb5f 100644 --- a/api/COTIZADOR_API_SKILL.md +++ b/api/COTIZADOR_API_SKILL.md @@ -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` -**Auth:** API Key via `X-API-Key` header or `Authorization: Bearer ` -**Content-Type:** `application/json` -**OpenAPI Spec:** `GET /openapi.json` (no auth required) +## Autenticación y alcances (`AgentApiKey`) ---- +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 -- **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 +## Flujo de aprobación humana (regla de hierro) -Two payment types: -- **unico:** One-time payment -- **mensual:** Monthly recurring payment +Estados: `borrador` → `aprobada` → `enviada` → `aceptada` | `rechazada` | `vencida`. -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/` (`POST /api/aprobar/` 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) -``` -X-API-Key: your-api-key-here -``` -or -``` -Authorization: Bearer your-api-key-here -``` +Headers enviados: +- `X-Cotizador-Event` +- `X-Cotizador-Timestamp` +- `X-Cotizador-Delivery-Id` +- `X-Cotizador-Signature: sha256=` -### JWT (for human login) -``` -POST /auth/login -Body: { "email": "user@example.com", "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": "juan@acme.com", - "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": "juan@acme.com", - "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 +## Provisioning de claves (operador) ```bash -pip install -r requirements.txt -uvicorn main:app --reload --host 0.0.0.0 --port 8000 -# Swagger: http://localhost:8000/docs -# ReDoc: http://localhost:8000/redoc -# OpenAPI: http://localhost:8000/openapi.json +npx tsx scripts/provision-agent-keys.ts --preset +npx tsx scripts/provision-agent-keys.ts --list +npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate ``` diff --git a/api/app/auth.py b/api/app/auth.py index 48b107f..f377a98 100644 --- a/api/app/auth.py +++ b/api/app/auth.py @@ -1,18 +1,33 @@ from __future__ import annotations +import hashlib +import json +import math +import time +import uuid 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 passlib.context import CryptContext from app.config import settings +from app.database import get_pool pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") ALGORITHM = "HS256" 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: return pwd_context.verify(plain, hashed) @@ -36,30 +51,296 @@ def decode_token(token: str) -> dict | None: return None -async def get_api_key(x_api_key: str | None = Header(None)) -> str | None: - if x_api_key and x_api_key == settings.API_KEY: - return x_api_key - return None +def _client_ip(request: Request | None) -> str | None: + if request is 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( + request: Request, authorization: str | None = Header(None), x_api_key: str | None = Header(None), ) -> dict: - if x_api_key and x_api_key == settings.API_KEY: - return {"auth_type": "api_key"} + ip = _client_ip(request) + bearer_token: str | None = None if authorization: scheme, _, token = authorization.partition(" ") - if scheme.lower() == "bearer" and token: - payload = decode_token(token) + if scheme.lower() == "bearer" and token.strip(): + bearer_token = token.strip() + # 1. Intentar JWT humano primero + payload = decode_token(bearer_token) if payload: - return {"auth_type": "jwt", **payload} - if x_api_key == settings.API_KEY: - return {"auth_type": "api_key"} + if payload.get("role") == "cliente": + raise HTTPException( + 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( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid or missing authentication credentials", + detail="Credenciales de autenticacion invalidas o ausentes", 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 diff --git a/api/app/config.py b/api/app/config.py index eb08b1a..046a3f9 100644 --- a/api/app/config.py +++ b/api/app/config.py @@ -6,8 +6,10 @@ class Settings(BaseSettings): DB_PORT: int = 5432 DB_USER: 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" 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" API_HOST: str = "0.0.0.0" API_PORT: int = 8000 diff --git a/api/app/models/common.py b/api/app/models/common.py index 39b10cd..406360b 100644 --- a/api/app/models/common.py +++ b/api/app/models/common.py @@ -41,9 +41,9 @@ class HealthResponse(BaseModel): class APIInfoResponse(BaseModel): - name: str = "Cotizador E3 API" + name: str = "Cotizador — Uriel Jareth Consulting API" 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) diff --git a/api/app/models/configuracion.py b/api/app/models/configuracion.py index de24ea5..0fd4490 100644 --- a/api/app/models/configuracion.py +++ b/api/app/models/configuracion.py @@ -8,7 +8,7 @@ ALLOWED_CONFIG_KEYS: set[str] = { "logo_base64", "razon_social", "rfc", - "domicilio_fiscal", + "domicilio_fiscal", # Opcional interno; no se imprime en documentos generados "cuenta_nacional", "clabe_interbancaria", "cuenta_internacional", @@ -28,7 +28,7 @@ class ConfigUpdate(BaseModel): description="Key-value config pairs. Only whitelisted keys are processed.", json_schema_extra={ "examples": [ - {"color_primario": "#ff0000", "razon_social": "Nueva Empresa SA de CV"} + {"color_primario": "#0400C4", "razon_social": "Uriel Jareth Consulting"} ] }, ) diff --git a/api/app/models/cotizacion.py b/api/app/models/cotizacion.py index c0e45e5..75ab2d3 100644 --- a/api/app/models/cotizacion.py +++ b/api/app/models/cotizacion.py @@ -5,6 +5,8 @@ from typing import Any from pydantic import BaseModel, Field +ESTADOS_PATTERN = "^(borrador|aprobada|enviada|aceptada|rechazada|vencida)$" + class ServicioCotizadoInput(BaseModel): 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)") tiempoEntrega: str entregables: list[str] = Field(default_factory=list) - # Partidas por tiempo (sin catálogo). modeloCobro: "fijo" | "horas" | "retainer". esPersonalizado: bool = False horas: 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) 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)$") @@ -50,55 +50,18 @@ class CotizacionCreate(BaseModel): moneda: str = Field("MXN", pattern="^(MXN|USD)$") tipoCambio: str = "NA" 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 incluirFinanciamiento: bool = False + incluirIva: bool = True esDoble: bool = False opciones: dict[str, MetaOpcionInput] | None = None observaciones: str = "" - asesorId: str = Field(..., min_length=1) + asesorId: str | None = None cliente: ClienteInput servicios: list[ServicioCotizadoInput] = Field(..., min_length=1) 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": "juan@acme.com", - "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): fecha: datetime | None = None @@ -106,20 +69,21 @@ class CotizacionUpdate(BaseModel): moneda: str | None = Field(None, pattern="^(MXN|USD)$") tipoCambio: 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 incluirFinanciamiento: bool | None = None + incluirIva: bool | None = None esDoble: bool | None = None opciones: dict[str, MetaOpcionInput] | 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 servicios: list[ServicioCotizadoInput] | None = None planBucefalo: PlanBucefaloInput | None = None class CambiarEstadoRequest(BaseModel): - estado: str = Field(..., pattern="^(borrador|enviada|aprobada|rechazada)$") + estado: str = Field(..., pattern=ESTADOS_PATTERN) class ActualizarPrecioRequest(BaseModel): @@ -139,11 +103,23 @@ class CotizacionResponse(BaseModel): estado: str incluirBonos: bool incluirFinanciamiento: bool + incluirIva: bool = True esDoble: bool = False opcionesMetadata: dict[str, Any] | None = None observaciones: str | None clienteId: 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 updatedAt: datetime cliente: dict[str, Any] | None = None diff --git a/api/app/routers/bonos.py b/api/app/routers/bonos.py index 41a5c0f..c2f8670 100644 --- a/api/app/routers/bonos.py +++ b/api/app/routers/bonos.py @@ -2,7 +2,7 @@ from __future__ import annotations from fastapi import APIRouter, Depends -from app.auth import require_auth +from app.auth import require_scope from app.models.export_ import BonoResponse from app.services.calculators import BONOS @@ -10,5 +10,5 @@ router = APIRouter(prefix="/bonos", tags=["Bonos"]) @router.get("", response_model=list[BonoResponse]) -async def get_bonos(_auth: dict = Depends(require_auth)): +async def get_bonos(_auth: dict = Depends(require_scope("catalogo:leer"))): return [BonoResponse(**b) for b in BONOS] diff --git a/api/app/routers/catalogo.py b/api/app/routers/catalogo.py index e73932c..48da477 100644 --- a/api/app/routers/catalogo.py +++ b/api/app/routers/catalogo.py @@ -5,7 +5,7 @@ import json from fastapi import APIRouter, Depends, HTTPException, Query, status from asyncpg import Connection -from app.auth import require_auth +from app.auth import require_scope, require_staff_human from app.dependencies import get_db from app.models.catalogo import ( ServicioCatalogoCreate, @@ -63,7 +63,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse: ) async def list_catalogo( db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("catalogo:leer")), fase: int | None = Query(None, ge=0, le=3), tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"), categoriaId: str | None = Query(None), @@ -121,7 +121,7 @@ async def list_catalogo( async def create_catalogo( body: ServicioCatalogoCreate, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_staff_human), ): if body.categoriaId: cat = await db.fetchrow( @@ -168,7 +168,7 @@ async def create_catalogo( async def get_catalogo( servicio_id: str, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("catalogo:leer")), ): row = await db.fetchrow( 'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id @@ -195,7 +195,7 @@ async def update_catalogo( servicio_id: str, body: ServicioCatalogoUpdate, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_staff_human), ): existing = await db.fetchrow( 'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id @@ -265,7 +265,7 @@ async def update_catalogo( async def delete_catalogo( servicio_id: str, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_staff_human), ): existing = await db.fetchrow( 'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id diff --git a/api/app/routers/categorias.py b/api/app/routers/categorias.py index fa14b09..e54d49b 100644 --- a/api/app/routers/categorias.py +++ b/api/app/routers/categorias.py @@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from app.database import get_pool from app.dependencies import get_db -from app.auth import require_auth +from app.auth import require_scope, require_staff_human from app.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse from app.models.common import ErrorResponse, OkResponse @@ -15,7 +15,7 @@ router = APIRouter(prefix="/categorias", tags=["Categorias"]) @router.get("", response_model=list[CategoriaResponse]) async def list_categorias( - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), conn=Depends(get_db), ): rows = await conn.fetch( @@ -33,7 +33,7 @@ async def list_categorias( ) async def create_categoria( body: CategoriaCreate, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): now = datetime.now(timezone.utc) @@ -64,7 +64,7 @@ async def create_categoria( ) async def get_categoria( categoria_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), conn=Depends(get_db), ): row = await conn.fetchrow( @@ -93,7 +93,7 @@ async def get_categoria( async def update_categoria( categoria_id: str, body: CategoriaUpdate, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): existing = await conn.fetchrow( @@ -166,7 +166,7 @@ async def update_categoria( ) async def delete_categoria( categoria_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): existing = await conn.fetchrow( diff --git a/api/app/routers/clientes.py b/api/app/routers/clientes.py index fb26812..1e1c470 100644 --- a/api/app/routers/clientes.py +++ b/api/app/routers/clientes.py @@ -5,7 +5,7 @@ import math from fastapi import APIRouter, Depends, HTTPException, Query, status from asyncpg import Connection -from app.auth import require_auth +from app.auth import require_scope, require_staff_human from app.dependencies import PaginationParams, get_db from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse @@ -20,7 +20,7 @@ router = APIRouter(prefix="/clientes", tags=["Clientes"]) ) async def list_clientes( db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("clientes:leer")), pagination: PaginationParams = Depends(PaginationParams), q: str | None = Query(None, description="Search by nombre, empresa, or email"), ): @@ -79,7 +79,7 @@ async def list_clientes( async def create_cliente( body: ClienteCreate, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("clientes:escribir")), ): row = await db.fetchrow( 'INSERT INTO "Cliente" (nombre, empresa, email, telefono) ' @@ -109,7 +109,7 @@ async def create_cliente( async def get_cliente( cliente_id: str, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("clientes:leer")), ): row = await db.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cliente_id) if not row: @@ -146,7 +146,7 @@ async def update_cliente( cliente_id: str, body: ClienteUpdate, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("clientes:escribir")), ): existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id) if not existing: @@ -192,7 +192,7 @@ async def update_cliente( async def delete_cliente( cliente_id: str, db: Connection = Depends(get_db), - auth: dict = Depends(require_auth), + auth: dict = Depends(require_staff_human), ): existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id) if not existing: diff --git a/api/app/routers/cobros.py b/api/app/routers/cobros.py new file mode 100644 index 0000000..675bf21 --- /dev/null +++ b/api/app/routers/cobros.py @@ -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 + ] diff --git a/api/app/routers/configuracion.py b/api/app/routers/configuracion.py index 66d2cf1..1f57996 100644 --- a/api/app/routers/configuracion.py +++ b/api/app/routers/configuracion.py @@ -6,14 +6,14 @@ from asyncpg import Connection from app.dependencies import get_db from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS from app.models.common import ErrorResponse, OkResponse -from app.auth import require_auth +from app.auth import require_staff_human router = APIRouter(prefix="/configuracion", tags=["Configuración"]) @router.get("", response_model=ConfigResponse) async def get_configuracion( - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), db: Connection = Depends(get_db), ): rows = await db.fetch("SELECT clave, valor FROM Configuracion") @@ -24,7 +24,7 @@ async def get_configuracion( @router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}}) async def update_configuracion( body: ConfigUpdate, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), db: Connection = Depends(get_db), ): allowed = body.get_allowed() diff --git a/api/app/routers/cotizaciones.py b/api/app/routers/cotizaciones.py index 7f2794f..76a8fbe 100644 --- a/api/app/routers/cotizaciones.py +++ b/api/app/routers/cotizaciones.py @@ -6,7 +6,13 @@ from datetime import datetime, timezone from fastapi import APIRouter, Depends, HTTPException, Query, status -from app.auth import require_auth +from app.auth import ( + es_agente_solo_aceptadas, + registrar_auditoria, + require_auth, + require_scope, + require_staff_human, +) from app.database import get_pool from app.dependencies import PaginationParams, parse_date from app.models.common import Meta, OkResponse, PaginatedResponse @@ -26,9 +32,14 @@ def _cuid() -> str: return uuid.uuid4().hex[:25] -async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_servicio_id, now, es_doble: bool = False) -> None: - """Inserta un ServicioCotizado desde un ServicioCotizadoInput, manejando - partidas personalizadas (por horas / retainer) en paridad con el backend Next.js.""" +async def _insert_servicio_cotizado( + conn, + cotizacion_id: str, + svc, + bucefalo_servicio_id, + now, + es_doble: bool = False, +) -> None: es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-") if es_personalizado: @@ -39,8 +50,8 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv catalogo_id = svc.catalogoId modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo") - # Doble propuesta: por defecto "ambas"; None en cotizaciones normales. opcion = (svc.opcion or "ambas") if es_doble else None + precio_final = 0 if modelo_cobro == "demanda" else svc.precio await conn.execute( """ @@ -64,7 +75,7 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv opcion, svc.fase, svc.tipoPago, - svc.precio, + precio_final, svc.tiempoEntrega, json.dumps(svc.entregables), None, @@ -73,7 +84,6 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv def _parse_json(val): - """asyncpg devuelve columnas jsonb como str; las parsea a dict/list.""" if isinstance(val, str): try: return json.loads(val) @@ -86,6 +96,7 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan= d = dict(cot) if "opcionesMetadata" in d: d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"]) + d.pop("observacionesInternas", None) d["cliente"] = dict(cliente) if cliente else None d["asesor"] = dict(asesor) if asesor else None d["servicios"] = [dict(s) for s in servicios] if servicios else [] @@ -93,8 +104,6 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan= return d -# LEFT JOIN: los servicios personalizados no tienen servicioCatalogoId y un JOIN -# interno los dejaría fuera de la respuesta. COALESCE conserva el nombre custom. _SERVICIOS_SQL = """ SELECT sc.*, sc."servicioCatalogoId" as "catalogoId", COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId" @@ -119,8 +128,6 @@ async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None: async def _fetch_cotizaciones_full(conn, cot_rows) -> list[dict]: - """Versión batch de _fetch_cotizacion_full: 4 queries en total para toda la - página en lugar de 4 por cotización (evita N+1 en el listado).""" if not cot_rows: return [] @@ -193,7 +200,7 @@ async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, t # --------------------------------------------------------------------------- -# 1. GET /cotizaciones — List with filters + pagination +# 1. GET /cotizaciones # --------------------------------------------------------------------------- @router.get("", response_model=PaginatedResponse[CotizacionResponse]) async def list_cotizaciones( @@ -204,17 +211,33 @@ async def list_cotizaciones( q: str | None = Query(None), desde: str | None = Query(None), hasta: str | None = Query(None), - _auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")), ): pool = await get_pool() + solo_aceptadas = es_agente_solo_aceptadas(auth) + if solo_aceptadas and estado and estado != "aceptada": + await registrar_auditoria( + pool, + auth, + "cotizacion.leer_bloqueado", + "cotizacion", + exito=False, + detalle={"estadoSolicitado": estado}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Tu clave solo permite consultar cotizaciones aceptadas", + ) + + estado_efectivo = "aceptada" if solo_aceptadas else estado conditions: list[str] = [] params: list = [] idx = 1 - if estado: - conditions.append(f'c.estado = ${idx}') - params.append(estado) + if estado_efectivo: + conditions.append(f"c.estado = ${idx}") + params.append(estado_efectivo) idx += 1 if asesorId: conditions.append(f'c."asesorId" = ${idx}') @@ -226,18 +249,18 @@ async def list_cotizaciones( idx += 1 if q: conditions.append( - f'(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})' + f"(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})" ) params.append(f"%{q}%") idx += 1 desde_dt = parse_date(desde) if desde_dt: - conditions.append(f'c.fecha >= ${idx}') + conditions.append(f"c.fecha >= ${idx}") params.append(desde_dt) idx += 1 hasta_dt = parse_date(hasta) if hasta_dt: - conditions.append(f'c.fecha <= ${idx}') + conditions.append(f"c.fecha <= ${idx}") params.append(hasta_dt) idx += 1 @@ -263,7 +286,6 @@ async def list_cotizaciones( ) cotizaciones = await _fetch_cotizaciones_full(pool, rows) - pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0 return PaginatedResponse( @@ -273,12 +295,29 @@ async def list_cotizaciones( # --------------------------------------------------------------------------- -# 2. POST /cotizaciones — Create +# 2. POST /cotizaciones — Create (SIEMPRE borrador) # --------------------------------------------------------------------------- @router.post("", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED) -async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(require_auth)): +async def create_cotizacion( + body: CotizacionCreate, + auth: dict = Depends(require_scope("cotizaciones:borrador")), +): pool = await get_pool() async with pool.acquire() as conn: + asesor_id = body.asesorId + if not asesor_id: + if auth.get("auth_type") == "jwt" and auth.get("userId"): + asesor_id = auth["userId"] + else: + admin = await conn.fetchrow( + 'SELECT id FROM "User" WHERE role = \'admin\' ORDER BY "createdAt" ASC LIMIT 1' + ) + if not admin: + raise HTTPException(status_code=500, detail="No hay usuario administrador configurado") + asesor_id = admin["id"] + + creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None + async with conn.transaction(): cliente_id = await _find_or_create_cliente( conn, @@ -293,13 +332,15 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir opciones_json = None if body.esDoble and body.opciones: opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()}) + await conn.execute( """ INSERT INTO "Cotizacion" (id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago", - estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata", - observaciones, "clienteId", "asesorId", "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16) + estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble", + "opcionesMetadata", observaciones, "clienteId", "asesorId", + "creadaPorAgente", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18) """, cot_id, body.numero, @@ -311,16 +352,17 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir body.esquemaPago, body.incluirBonos, body.incluirFinanciamiento, + body.incluirIva, body.esDoble, opciones_json, body.observaciones or None, cliente_id, - body.asesorId, + asesor_id, + creada_por_agente, now, ) bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn) - for svc in body.servicios: await _insert_servicio_cotizado(conn, cot_id, svc, bucefalo_servicio_id, now, body.esDoble) @@ -338,32 +380,58 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir now, ) - row = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id) - result = dict(row) - result["opcionesMetadata"] = _parse_json(result.get("opcionesMetadata")) - return result + await registrar_auditoria( + conn, + auth, + "cotizacion.crear", + "cotizacion", + recurso_id=cot_id, + exito=True, + detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente}, + ) - -# --------------------------------------------------------------------------- -# 3. GET /cotizaciones/{id} — Get with relations -# --------------------------------------------------------------------------- -@router.get("/{cotizacion_id}", response_model=CotizacionResponse) -async def get_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)): - pool = await get_pool() - full = await _fetch_cotizacion_full(pool, cotizacion_id) - if not full: - raise HTTPException(status_code=404, detail="Cotización no encontrada") + full = await _fetch_cotizacion_full(pool, cot_id) return full # --------------------------------------------------------------------------- -# 4. PUT /cotizaciones/{id} — Update +# 3. GET /cotizaciones/{id} +# --------------------------------------------------------------------------- +@router.get("/{cotizacion_id}", response_model=CotizacionResponse) +async def get_cotizacion( + cotizacion_id: str, + auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")), +): + pool = await get_pool() + full = await _fetch_cotizacion_full(pool, cotizacion_id) + if not full: + raise HTTPException(status_code=404, detail="Cotización no encontrada") + + if es_agente_solo_aceptadas(auth) and full["estado"] != "aceptada": + await registrar_auditoria( + pool, + auth, + "cotizacion.leer_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"estadoActual": full["estado"]}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Tu clave solo permite consultar cotizaciones aceptadas", + ) + return full + + +# --------------------------------------------------------------------------- +# 4. PUT /cotizaciones/{id} # --------------------------------------------------------------------------- @router.put("/{cotizacion_id}", response_model=CotizacionResponse) async def update_cotizacion( cotizacion_id: str, body: CotizacionUpdate, - _auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("cotizaciones:borrador")), ): pool = await get_pool() async with pool.acquire() as conn: @@ -371,6 +439,58 @@ async def update_cotizacion( if not existing: raise HTTPException(status_code=404, detail="Cotización no encontrada") + if auth.get("auth_type") == "agent": + if existing["estado"] != "borrador": + await registrar_auditoria( + conn, + auth, + "cotizacion.editar_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"estadoActual": existing["estado"]}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Los agentes solo pueden editar cotizaciones en borrador", + ) + if body.estado is not None and body.estado != "borrador": + await registrar_auditoria( + conn, + auth, + "cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"actual": existing["estado"], "intento": body.estado}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Los agentes no pueden cambiar el estado de la cotización", + ) + + if body.estado is not None and body.estado != existing["estado"]: + # Si un humano intenta cambiar estado en PUT, exige las mismas reglas que PATCH /estado + if body.estado == "aprobada" and not (auth.get("auth_type") == "jwt" and auth.get("role") == "admin"): + await registrar_auditoria( + conn, + auth, + "cotizacion.aprobar_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"intento": "aprobada"}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Solo un administrador humano puede aprobar una cotización", + ) + if body.estado == "enviada" and (existing["estado"] != "aprobada" or existing["aprobadaAt"] is None): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="La cotización debe estar aprobada antes de marcarse como enviada", + ) + async with conn.transaction(): cliente_id = existing["clienteId"] if body.cliente: @@ -386,54 +506,55 @@ async def update_cotizacion( params: list = [] idx = 1 - def _add(field: str, col: str, val): + def _add(col: str, val): nonlocal idx - if val is not None: - updates.append(f'{col} = ${idx}') - params.append(val) - idx += 1 + updates.append(f'{col} = ${idx}') + params.append(val) + idx += 1 - _add("fecha", "fecha", body.fecha) - _add("vigencia", "vigencia", body.vigencia) - _add("moneda", "moneda", body.moneda) - _add("tipoCambio", '"tipoCambio"', body.tipoCambio) - _add("proyecto", "proyecto", body.proyecto) - _add("esquemaPago", '"esquemaPago"', body.esquemaPago) - _add("incluirBonos", '"incluirBonos"', body.incluirBonos) - _add("incluirFinanciamiento", '"incluirFinanciamiento"', body.incluirFinanciamiento) - _add("esDoble", '"esDoble"', body.esDoble) - _add("observaciones", "observaciones", body.observaciones) - _add("estado", "estado", body.estado) - - es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"] + if body.fecha is not None: + _add("fecha", body.fecha) + if body.vigencia is not None: + _add("vigencia", body.vigencia) + if body.moneda is not None: + _add("moneda", body.moneda) + if body.tipoCambio is not None: + _add('"tipoCambio"', body.tipoCambio) + if body.proyecto is not None: + _add("proyecto", body.proyecto) + if body.esquemaPago is not None: + _add('"esquemaPago"', body.esquemaPago) + if body.incluirBonos is not None: + _add('"incluirBonos"', body.incluirBonos) + if body.incluirFinanciamiento is not None: + _add('"incluirFinanciamiento"', body.incluirFinanciamiento) + if body.incluirIva is not None: + _add('"incluirIva"', body.incluirIva) if body.esDoble is not None: - # opcionesMetadata se sincroniza con esDoble: dict (json) si doble, NULL si no. - meta_json = None - if es_doble_final and body.opciones: - meta_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()}) - updates.append(f'"opcionesMetadata" = ${idx}') - params.append(meta_json) - idx += 1 - + _add('"esDoble"', body.esDoble) + if body.opciones is not None: + _add('"opcionesMetadata"', json.dumps({k: v.model_dump() for k, v in body.opciones.items()})) + if body.observaciones is not None: + _add("observaciones", body.observaciones) + if body.estado is not None and auth.get("auth_type") != "agent": + _add("estado", body.estado) if cliente_id != existing["clienteId"]: - updates.append(f'"clienteId" = ${idx}') - params.append(cliente_id) - idx += 1 + _add('"clienteId"', cliente_id) if updates: - updates.append(f'"updatedAt" = ${idx}') - params.append(datetime.now(timezone.utc)) - idx += 1 + updates.append('"updatedAt" = NOW()') params.append(cotizacion_id) await conn.execute( f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}', *params, ) + now = datetime.now(timezone.utc) + es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"] + if body.servicios is not None: await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id) bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn) - now = datetime.now(timezone.utc) for svc in body.servicios: await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final) @@ -442,7 +563,6 @@ async def update_cotizacion( 'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', cotizacion_id, ) - now = datetime.now(timezone.utc) if existing_plan: await conn.execute( 'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4', @@ -470,20 +590,40 @@ async def update_cotizacion( cotizacion_id, ) - full = await _fetch_cotizacion_full(pool, cotizacion_id) - return full + await registrar_auditoria( + conn, + auth, + "cotizacion.actualizar", + "cotizacion", + recurso_id=cotizacion_id, + exito=True, + ) + + return await _fetch_cotizacion_full(pool, cotizacion_id) # --------------------------------------------------------------------------- -# 5. DELETE /cotizaciones/{id} +# 5. DELETE /cotizaciones/{id} (solo personal humano) # --------------------------------------------------------------------------- @router.delete("/{cotizacion_id}", response_model=OkResponse) -async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)): +async def delete_cotizacion( + cotizacion_id: str, + auth: dict = Depends(require_staff_human), +): pool = await get_pool() - existing = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id) + existing = await pool.fetchrow('SELECT id, numero FROM "Cotizacion" WHERE id = $1', cotizacion_id) if not existing: raise HTTPException(status_code=404, detail="Cotización no encontrada") await pool.execute('DELETE FROM "Cotizacion" WHERE id = $1', cotizacion_id) + await registrar_auditoria( + pool, + auth, + "cotizacion.eliminar", + "cotizacion", + recurso_id=cotizacion_id, + exito=True, + detalle={"numero": existing["numero"]}, + ) return OkResponse(ok=True) @@ -494,13 +634,28 @@ async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_au async def update_precio_servicio( cotizacion_id: str, body: ActualizarPrecioRequest, - _auth: dict = Depends(require_auth), + auth: dict = Depends(require_scope("cotizaciones:borrador")), ): pool = await get_pool() - cot = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id) + cot = await pool.fetchrow('SELECT id, estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) if not cot: raise HTTPException(status_code=404, detail="Cotización no encontrada") + if auth.get("auth_type") == "agent" and cot["estado"] != "borrador": + await registrar_auditoria( + pool, + auth, + "cotizacion.editar_precio_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"estadoActual": cot["estado"]}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Los agentes solo pueden editar precios en cotizaciones en borrador", + ) + svc = await pool.fetchrow( 'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2', body.servicioId, @@ -518,13 +673,13 @@ async def update_precio_servicio( # --------------------------------------------------------------------------- -# 7. PATCH /cotizaciones/{id}/estado +# 7. PATCH /cotizaciones/{id}/estado (PARIDAD ESTRICTA DE APROBACIÓN) # --------------------------------------------------------------------------- @router.patch("/{cotizacion_id}/estado", response_model=OkResponse) async def cambiar_estado( cotizacion_id: str, body: CambiarEstadoRequest, - _auth: dict = Depends(require_auth), + auth: dict = Depends(require_auth), ): if body.estado not in ESTADOS_COTIZACION: raise HTTPException( @@ -533,13 +688,127 @@ async def cambiar_estado( ) pool = await get_pool() - result = await pool.execute( - 'UPDATE "Cotizacion" SET estado = $1, "updatedAt" = NOW() WHERE id = $2', - body.estado, - cotizacion_id, - ) - if result == "UPDATE 0": + existing = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id) + if not existing: raise HTTPException(status_code=404, detail="Cotización no encontrada") + + # REGLA DE HIERRO: Ningún agente puede cambiar estado (ni aprobar ni enviar por este endpoint). + if auth.get("auth_type") == "agent": + await registrar_auditoria( + pool, + auth, + "cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"actual": existing["estado"], "intento": body.estado}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Los agentes no pueden aprobar ni cambiar el estado directamente. Usa el flujo de aprobación humana y POST /api/cotizaciones/:id/enviar.", + ) + + es_admin = auth.get("auth_type") == "jwt" and auth.get("role") == "admin" + actual = existing["estado"] + nuevo = body.estado + + if nuevo == "aprobada": + if not es_admin: + await registrar_auditoria( + pool, + auth, + "cotizacion.aprobar_bloqueado", + "cotizacion", + recurso_id=cotizacion_id, + exito=False, + detalle={"actual": actual, "intento": nuevo}, + ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Solo un administrador humano puede aprobar una cotización", + ) + if actual != "borrador": + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"Solo se puede aprobar una cotización en borrador (estado actual: {actual})", + ) + await pool.execute( + """ + UPDATE "Cotizacion" + SET estado = 'aprobada', + "aprobadaPorId" = $1, + "aprobadaAt" = NOW(), + "aprobacionMetodo" = 'web_admin', + "updatedAt" = NOW() + WHERE id = $2 + """, + auth.get("userId"), + cotizacion_id, + ) + elif nuevo == "enviada": + if actual != "aprobada" or existing["aprobadaAt"] is None: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="La cotización debe estar aprobada antes de marcarse como enviada", + ) + await pool.execute( + """ + UPDATE "Cotizacion" + SET estado = 'enviada', + "enviadaAt" = NOW(), + "enviadaCanal" = 'manual', + "enviadaPor" = $1, + "updatedAt" = NOW() + WHERE id = $2 + """, + f"user:{auth.get('email') or auth.get('userId')}", + cotizacion_id, + ) + elif nuevo == "borrador": + if not es_admin: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Solo un administrador humano puede regresar a borrador", + ) + await pool.execute( + """ + UPDATE "Cotizacion" + SET estado = 'borrador', + "aprobadaPorId" = NULL, + "aprobadaAt" = NULL, + "aprobacionMetodo" = NULL, + "updatedAt" = NOW() + WHERE id = $1 + """, + cotizacion_id, + ) + elif nuevo in ("aceptada", "rechazada", "vencida"): + if actual != "enviada": + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"Solo se puede pasar a {nuevo} desde estado enviada (estado actual: {actual})", + ) + col_map = { + "aceptada": '"aceptadaAt"', + "rechazada": '"rechazadaAt"', + "vencida": '"vencidaAt"', + } + col = col_map[nuevo] + await pool.execute( + f'UPDATE "Cotizacion" SET estado = $1, {col} = NOW(), "updatedAt" = NOW() WHERE id = $2', + nuevo, + cotizacion_id, + ) + + await registrar_auditoria( + pool, + auth, + f"cotizacion.estado_{nuevo}", + "cotizacion", + recurso_id=cotizacion_id, + exito=True, + detalle={"anterior": actual, "nuevo": nuevo}, + ) return OkResponse(ok=True) @@ -547,7 +816,10 @@ async def cambiar_estado( # 8. POST /cotizaciones/{id}/duplicate # --------------------------------------------------------------------------- @router.post("/{cotizacion_id}/duplicate", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED) -async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)): +async def duplicate_cotizacion( + cotizacion_id: str, + auth: dict = Depends(require_scope("cotizaciones:borrador")), +): pool = await get_pool() async with pool.acquire() as conn: original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id) @@ -563,6 +835,8 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require cotizacion_id, ) + creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None + async with conn.transaction(): now = datetime.now(timezone.utc) new_id = _cuid() @@ -572,9 +846,10 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require """ INSERT INTO "Cotizacion" (id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago", - estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata", - observaciones, "clienteId", "asesorId", "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16) + estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble", + "opcionesMetadata", observaciones, "clienteId", "asesorId", + "creadaPorAgente", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18) """, new_id, new_numero, @@ -586,11 +861,13 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require original["esquemaPago"], original["incluirBonos"], original["incluirFinanciamiento"], + original["incluirIva"], original["esDoble"], original["opcionesMetadata"], original["observaciones"], original["clienteId"], original["asesorId"], + creada_por_agente, now, ) @@ -640,5 +917,14 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require now, ) - full = await _fetch_cotizacion_full(pool, new_id) - return full + await registrar_auditoria( + conn, + auth, + "cotizacion.duplicar", + "cotizacion", + recurso_id=new_id, + exito=True, + detalle={"origenId": cotizacion_id, "numero": new_numero}, + ) + + return await _fetch_cotizacion_full(pool, new_id) diff --git a/api/app/routers/export_.py b/api/app/routers/export_.py index 58a28f9..275c391 100644 --- a/api/app/routers/export_.py +++ b/api/app/routers/export_.py @@ -15,7 +15,7 @@ from asyncpg import Connection from app.dependencies import get_db from app.models.export_ import ExportDraft from app.models.common import ErrorResponse -from app.auth import require_auth +from app.auth import es_agente_solo_aceptadas, require_scope from app.services.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename from app.services.pdf_generator import generate_cotizacion_pdf from app.services.excel_generator import generate_cotizacion_excel @@ -86,13 +86,12 @@ def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) -> "planBucefaloNivel": draft.planBucefaloNivel, "planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0, "incluirBonos": draft.incluirBonos, - "colorPrimario": branding.get("color_primario", "#2563eb"), - "colorSecundario": branding.get("color_secundario", "#1e293b"), + "colorPrimario": branding.get("color_primario") or "#0400C4", + "colorSecundario": branding.get("color_secundario") or "#0F172A", "logoBase64": logo_b64, "logoMime": logo_mime, "configBancaria": branding, - "razonSocial": branding.get("razon_social", "Cotizador E3"), - "domicilioFiscal": branding.get("domicilio_fiscal"), + "razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting", } @@ -188,13 +187,12 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st "planBucefaloNivel": plan_nivel, "planBucefaloPrecio": float(plan["precio"]) if plan else 0, "incluirBonos": cot["incluirBonos"], - "colorPrimario": branding.get("color_primario", "#2563eb"), - "colorSecundario": branding.get("color_secundario", "#1e293b"), + "colorPrimario": branding.get("color_primario") or "#0400C4", + "colorSecundario": branding.get("color_secundario") or "#0F172A", "logoBase64": logo_b64, "logoMime": logo_mime, "configBancaria": branding, - "razonSocial": branding.get("razon_social", "Cotizador E3"), - "domicilioFiscal": branding.get("domicilio_fiscal"), + "razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting", } @@ -203,7 +201,7 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st @router.post("/pdf") async def export_pdf_draft( body: ExportDraft, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")), db: Connection = Depends(get_db), ): branding = await _load_branding(db) @@ -223,9 +221,13 @@ async def export_pdf_draft( @router.get("/pdf/{cotizacion_id}") async def export_pdf_saved( cotizacion_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")), db: Connection = Depends(get_db), ): + if es_agente_solo_aceptadas(_auth): + row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) + if row_est and row_est["estado"] != "aceptada": + raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas") pdf_data = await _build_pdf_data_from_db(db, cotizacion_id) if not pdf_data: raise HTTPException(status_code=404, detail="Cotización no encontrada") @@ -247,7 +249,7 @@ async def export_pdf_saved( @router.post("/excel") async def export_excel_draft( body: ExportDraft, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")), db: Connection = Depends(get_db), ): branding = await _load_branding(db) @@ -267,9 +269,13 @@ async def export_excel_draft( @router.get("/excel/{cotizacion_id}") async def export_excel_saved( cotizacion_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")), db: Connection = Depends(get_db), ): + if es_agente_solo_aceptadas(_auth): + row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) + if row_est and row_est["estado"] != "aceptada": + raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas") excel_data = await _build_pdf_data_from_db(db, cotizacion_id) if not excel_data: raise HTTPException(status_code=404, detail="Cotización no encontrada") @@ -290,7 +296,7 @@ async def export_excel_saved( @router.get("/catalogo", response_class=PlainTextResponse) async def export_catalogo_csv( - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), db: Connection = Depends(get_db), ): rows = await db.fetch( diff --git a/api/app/routers/financiamiento.py b/api/app/routers/financiamiento.py index c80c62f..c53e95b 100644 --- a/api/app/routers/financiamiento.py +++ b/api/app/routers/financiamiento.py @@ -11,7 +11,7 @@ from app.models.export_ import ( PlanBucefaloResponse, ) from app.models.common import ErrorResponse -from app.auth import require_auth +from app.auth import require_scope from app.services.calculators import ( calcular_financiamiento, FINANCIAMIENTO_PLANES, @@ -28,7 +28,7 @@ class PlanResponse(FinanciamientoResponse): @router.get("/planes", response_model=list[PlanResponse]) -async def get_planes(_auth: dict = Depends(require_auth)): +async def get_planes(_auth: dict = Depends(require_scope("catalogo:leer"))): return [ PlanResponse( meses=p["meses"], @@ -47,7 +47,7 @@ async def get_planes(_auth: dict = Depends(require_auth)): ) async def calcular( body: FinanciamientoRequest, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), ): plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None) if not plan: @@ -77,7 +77,7 @@ async def calcular( ) async def simulacion( cotizacion_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), db: Connection = Depends(get_db), ): cot = await db.fetchrow( diff --git a/api/app/routers/health.py b/api/app/routers/health.py index 9360392..b3a01c8 100644 --- a/api/app/routers/health.py +++ b/api/app/routers/health.py @@ -28,9 +28,9 @@ async def health_check(): @router.get("/api-info", response_model=APIInfoResponse) async def api_info(): return APIInfoResponse( - name="Cotizador E3 API", + name="Cotizador — Uriel Jareth Consulting API", version="1.0.0", - description="API para el sistema de cotizaciones de Consultoría E3", + description="API para el sistema de cotizaciones de Uriel Jareth Consulting", capabilities=[ "Gestión de cotizaciones", "Catálogo de servicios", diff --git a/api/app/routers/import_.py b/api/app/routers/import_.py index 1688399..fe2823e 100644 --- a/api/app/routers/import_.py +++ b/api/app/routers/import_.py @@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, File, UploadFile from asyncpg import Connection from app.dependencies import get_db -from app.auth import require_auth +from app.auth import require_staff_human router = APIRouter(prefix="/import", tags=["Import"]) @@ -17,7 +17,7 @@ REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"} @router.post("/catalogo") async def import_catalogo_csv( file: UploadFile = File(...), - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), db: Connection = Depends(get_db), ): content = await file.read() diff --git a/api/app/routers/paquetes.py b/api/app/routers/paquetes.py index 1948eea..57bd006 100644 --- a/api/app/routers/paquetes.py +++ b/api/app/routers/paquetes.py @@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from app.database import get_pool from app.dependencies import get_db -from app.auth import require_auth +from app.auth import require_scope, require_staff_human from app.models.paquete import ( PaqueteCreate, PaqueteUpdate, @@ -128,7 +128,7 @@ async def _build_paquete_response(conn, paquete_row: dict) -> dict: @router.get("", response_model=list[PaqueteResponse]) async def list_paquetes( - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), conn=Depends(get_db), ): rows = await conn.fetch( @@ -145,7 +145,7 @@ async def list_paquetes( ) async def create_paquete( body: PaqueteCreate, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): now = datetime.now(timezone.utc) @@ -179,7 +179,7 @@ async def create_paquete( ) async def get_paquete( paquete_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_scope("catalogo:leer")), conn=Depends(get_db), ): row = await conn.fetchrow( @@ -203,7 +203,7 @@ async def get_paquete( async def update_paquete( paquete_id: str, body: PaqueteUpdate, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): existing = await conn.fetchrow( @@ -260,7 +260,7 @@ async def update_paquete( ) async def delete_paquete( paquete_id: str, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): result = await conn.execute( @@ -281,7 +281,7 @@ async def delete_paquete( async def manage_paquete( paquete_id: str, body: ManageAction, - _auth: dict = Depends(require_auth), + _auth: dict = Depends(require_staff_human), conn=Depends(get_db), ): paquete = await conn.fetchrow( diff --git a/api/app/services/calculators.py b/api/app/services/calculators.py index 05a3880..e63b8d3 100644 --- a/api/app/services/calculators.py +++ b/api/app/services/calculators.py @@ -1,6 +1,7 @@ from __future__ import annotations -from datetime import date, datetime +import re +from datetime import date, datetime, timedelta IVA_RATE = 0.16 @@ -8,11 +9,12 @@ IVA_RATE = 0.16 # Tarifa por hora sugerida para partidas personalizadas (Hora Centinela). 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] = { "fijo": "Precio fijo", "horas": "Por horas", "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). @@ -39,7 +41,7 @@ PLANES_BUCEFALO = [ {"nivel": "empresarial", "label": "Empresarial", "precio": 7500}, ] -ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"] +ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"] FINANCIAMIENTO_PLANES = [ {"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: - 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: @@ -81,6 +87,8 @@ def detalle_modelo(serv: dict) -> str: serv.get("horasIncluidas") 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") tarifa = serv.get("tarifaHora") 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: """Totales de una opcion: suma sus partidas + las marcadas 'ambas'. - Espejo de calcularTotalesOpcion en TS. Respeta la regla de retainer: el total - usa `precio`, no `horas x tarifa`. Las horas son informativas. + Espejo exacto de calcularTotalesOpcion en TS. Respeta la regla de retainer: + 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] 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") horas = sum((s.get("horas") or 0) for s in rel) return { - "totalUnico": round(total_unico, 2), - "totalMensual": round(total_mensual, 2), - "horas": round(horas, 2), + "totalUnico": _r2(total_unico), + "totalMensual": _r2(total_mensual), + "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: for p in PLANES_BUCEFALO: if p["nivel"] == nivel: @@ -113,32 +152,37 @@ def bucefalo_precio(nivel: str) -> float: def calcular_vigencia(fecha: datetime | date) -> datetime: + """Suma exactamente 15 dias habiles (lunes a viernes), espejo de calculators.ts.""" if isinstance(fecha, datetime): vigencia = fecha.replace() else: vigencia = datetime.combine(fecha, datetime.min.time()) dias_habiles = 0 while dias_habiles < 15: - vigencia = vigencia.replace(day=vigencia.day + 1) if vigencia.day < 28 else vigencia + __import__("datetime").timedelta(days=1) - vigencia = vigencia + __import__("datetime").timedelta(days=1) - dia = vigencia.weekday() - if dia < 5: + vigencia = vigencia + timedelta(days=1) + if vigencia.weekday() < 5: dias_habiles += 1 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 monto_con_comision = monto + comision_total pago_mensual = monto_con_comision * (1 + tasa) / meses iva_mensual = pago_mensual * iva total_mensual = pago_mensual + iva_mensual return { - "pagoMensual": round(pago_mensual, 2), - "ivaMensual": round(iva_mensual, 2), - "totalMensual": round(total_mensual, 2), - "comisionTotal": round(comision_total, 2), - "granTotal": round(total_mensual * meses, 2), + "pagoMensual": _r2(pago_mensual), + "ivaMensual": _r2(iva_mensual), + "totalMensual": _r2(total_mensual), + "comisionTotal": _r2(comision_total), + "granTotal": _r2(total_mensual * meses), } @@ -151,7 +195,6 @@ def generar_numero_cotizacion(iniciales: str, secuencia: int) -> str: def sanitize_filename(name: str) -> str: - import re name = re.sub(r"[^\w\s.\-]", "", name) name = re.sub(r"\s+", " ", name) return name.strip() diff --git a/api/app/services/excel_generator.py b/api/app/services/excel_generator.py index 2ff5c93..b9aeebc 100644 --- a/api/app/services/excel_generator.py +++ b/api/app/services/excel_generator.py @@ -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, 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) 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_LIGHT = _argb(config_color, alpha="18") - SECONDARY = _argb(data.get("colorSecundario", "#1e293b")) + SECONDARY = _argb(data.get("colorSecundario") or "#0F172A") WHITE = "FFFFFFFF" LIGHT_BG = "FFF8FAFC" 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") white_fill = PatternFill(start_color=WHITE, end_color=WHITE, fill_type="solid") - razon_social = data.get("razonSocial", "Cotizador E3") - domicilio_fiscal = data.get("domicilioFiscal") + razon_social = data.get("razonSocial") or "Uriel Jareth Consulting" cliente_nombre = data.get("clienteNombre", "") cliente_empresa = data.get("clienteEmpresa", "") 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" wb = Workbook() - wb.properties.creator = "Cotizador E3" + wb.properties.creator = "Cotizador — Uriel Jareth Consulting" # ═══════════════════════════════════════════════════════════════════════════ # 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[f"B{r}"].value = razon_social dw[f"B{r}"].font = Font(bold=True, size=10, name="Calibri", color=PRIMARY) - if domicilio_fiscal: - 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) + # Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados. output = io.BytesIO() wb.save(output) diff --git a/api/app/services/pdf_generator.py b/api/app/services/pdf_generator.py index d0dacfc..7de69e6 100644 --- a/api/app/services/pdf_generator.py +++ b/api/app/services/pdf_generator.py @@ -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 @@ -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 -PRIMARY_DEFAULT = "#2563eb" -DARK_DEFAULT = "#1e293b" +PRIMARY_DEFAULT = "#0400C4" +DARK_DEFAULT = "#0F172A" MUTED = "#64748b" BORDER = "#cbd5e1" LIGHT_BG = "#f1f5f9" diff --git a/api/main.py b/api/main.py index e7dbec1..e6fee75 100644 --- a/api/main.py +++ b/api/main.py @@ -1,4 +1,4 @@ -"""Cotizador E3 — FastAPI Application +"""Cotizador — Uriel Jareth Consulting (FastAPI Application) REST API for digital marketing quotation management. Optimized for n8n workflows and other integrations. @@ -25,13 +25,13 @@ async def lifespan(app: FastAPI): app = FastAPI( - title="Cotizador E3 API", + title="Cotizador — Uriel Jareth Consulting API", 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. " "Autenticación por X-API-Key o Bearer JWT." ), - version="1.0.0", + version="2.0.0", lifespan=lifespan, docs_url="/docs", redoc_url="/redoc", @@ -42,7 +42,8 @@ app = FastAPI( {"name": "Clientes", "description": "Gestión de clientes"}, {"name": "Catálogo", "description": "Catálogo de servicios de marketing digital"}, {"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": "Configuración", "description": "Configuración de la empresa (key-value)"}, {"name": "Bonos", "description": "Bonos disponibles para cotizaciones"}, @@ -108,8 +109,8 @@ app.include_router(import_.router) @app.get("/", include_in_schema=False) async def root(): return { - "name": "Cotizador E3 API", - "version": "1.0.0", + "name": "Cotizador — Uriel Jareth Consulting API", + "version": "2.0.0", "docs": "/docs", "openapi": "/openapi.json", "health": "/health", diff --git a/cli/cotizador.mjs b/cli/cotizador.mjs index 68f1d5b..eb80069 100644 --- a/cli/cotizador.mjs +++ b/cli/cotizador.mjs @@ -1,5 +1,5 @@ #!/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 // de un usuario staff (login con correo y contrasena). @@ -227,13 +227,22 @@ async function leerDatos(valor) { // 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"); +// Fallback de solo lectura para sesiones previas antes del renombre. +const ARCHIVO_SESIONES_LEGACY = join(homedir(), ".cotizador-e3", "sesiones.json"); async function leerSesiones() { try { return JSON.parse(await readFile(ARCHIVO_SESIONES, "utf8")); } catch { + if (!process.env.COTIZADOR_HOME) { + try { + return JSON.parse(await readFile(ARCHIVO_SESIONES_LEGACY, "utf8")); + } catch { + return {}; + } + } return {}; } } @@ -646,14 +655,14 @@ const COMANDOS = [ // ----- sesion ----- { 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: [ { flag: "email", tipo: "texto", descripcion: "Correo (o $COTIZADOR_EMAIL)" }, { 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)" }, ], 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", ], endpoint: "POST /api/auth/login", @@ -1256,7 +1265,7 @@ function esquema() { nombre: "cotizador", version: VERSION, 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: { salida: "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)", 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_PASSWORD: "Contrasena para login automatico", 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, dominio: DOMINIO, @@ -1343,7 +1352,7 @@ function ayudaGeneral() { grupos.get(g).push(c); } const ancho = Math.max(...COMANDOS.map((c) => c.comando.length)) + 2; - let txt = `cotizador ${VERSION} — CLI del Cotizador E3\n\nUso: cotizador [argumentos] [flags]\n`; + let txt = `cotizador ${VERSION} — CLI del Cotizador — Uriel Jareth Consulting\n\nUso: cotizador [argumentos] [flags]\n`; for (const [g, cmds] of grupos) { txt += `\n${g.toUpperCase()}\n`; for (const c of cmds) txt += ` ${c.comando.padEnd(ancho)}${c.descripcion.split(/\.\s+(?=[A-Z(])/)[0]}\n`; diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.yml index f3dd7f4..28e8736 100644 --- a/docker-compose.coolify.yml +++ b/docker-compose.coolify.yml @@ -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 # "Docker Compose Location" = /docker-compose.coolify.yml @@ -16,6 +16,7 @@ services: environment: POSTGRES_USER: ${DB_USER:-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} volumes: - postgres_data:/var/lib/postgresql/data @@ -49,7 +50,7 @@ services: - MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3} # Seed inicial: pon RUN_SEED=true solo en el primer despliegue - 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_NAME=${SEED_ADMIN_NAME:-Administrador} - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} @@ -68,11 +69,16 @@ services: - SMTP_USER=${SMTP_USER} - SMTP_PASS=${SMTP_PASS} - 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). - COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3} # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. - 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: - uploads_data:/app/uploads depends_on: @@ -99,6 +105,8 @@ services: - DB_NAME=${DB_NAME:-cotizador_e3} - API_KEY=${API_KEY} - 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: postgres: condition: service_healthy diff --git a/docker-compose.yaml b/docker-compose.yaml index f3dd7f4..28e8736 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -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 # "Docker Compose Location" = /docker-compose.coolify.yml @@ -16,6 +16,7 @@ services: environment: POSTGRES_USER: ${DB_USER:-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} volumes: - postgres_data:/var/lib/postgresql/data @@ -49,7 +50,7 @@ services: - MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3} # Seed inicial: pon RUN_SEED=true solo en el primer despliegue - 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_NAME=${SEED_ADMIN_NAME:-Administrador} - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} @@ -68,11 +69,16 @@ services: - SMTP_USER=${SMTP_USER} - SMTP_PASS=${SMTP_PASS} - 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). - COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3} # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. - 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: - uploads_data:/app/uploads depends_on: @@ -99,6 +105,8 @@ services: - DB_NAME=${DB_NAME:-cotizador_e3} - API_KEY=${API_KEY} - 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: postgres: condition: service_healthy diff --git a/docker-compose.yml b/docker-compose.yml index f223d2d..e6a71dd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,11 +1,12 @@ services: postgres: image: postgres:16-alpine - container_name: cotizador-e3-db + container_name: cotizador-uj-db restart: unless-stopped environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres + # Se conserva el nombre fisico de BD para no romper el volumen postgres_data. POSTGRES_DB: cotizador_e3 ports: - "5432:5432" @@ -14,7 +15,7 @@ services: api: build: ./api - container_name: cotizador-e3-api + container_name: cotizador-uj-api restart: unless-stopped ports: - "8000:8000" diff --git a/docs/CLI.md b/docs/CLI.md index 803ae4c..2958d05 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1,6 +1,6 @@ # 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). - 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 # instala el comando "cotizador" globalm | `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_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 -cotizador login --email asesor@consultoriae3.com --password-stdin < pass.txt +cotizador login --email admin@urieljareth.com --password-stdin < pass.txt cotizador whoami ``` diff --git a/docs/paquetes-recomendados-pyme.md b/docs/paquetes-recomendados-pyme.md index c92691c..778dbca 100644 --- a/docs/paquetes-recomendados-pyme.md +++ b/docs/paquetes-recomendados-pyme.md @@ -1,6 +1,6 @@ # 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. diff --git a/package-lock.json b/package-lock.json index 4b410bf..a2f835d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "cotizador-e3", + "name": "cotizador-uj", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "cotizador-e3", + "name": "cotizador-uj", "version": "0.1.0", "dependencies": { "@anthropic-ai/sdk": "^0.115.0", diff --git a/package.json b/package.json index ad14a7b..8118f06 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "cotizador-e3", + "name": "cotizador-uj", "version": "0.1.0", "private": true, "bin": { @@ -14,7 +14,8 @@ "db:seed": "npx tsx prisma/seed.ts", "db:studio": "npx prisma studio", "db:generate": "npx prisma generate", - "cli": "node cli/cotizador.mjs" + "cli": "node cli/cotizador.mjs", + "test": "node --import tsx --test tests/*.test.ts" }, "prisma": { "seed": "npx tsx prisma/seed.ts" diff --git a/prisma.config.ts b/prisma.config.ts index a66e3df..8359142 100644 --- a/prisma.config.ts +++ b/prisma.config.ts @@ -10,6 +10,7 @@ function databaseUrl(): string { const port = process.env["DB_PORT"] || "5432"; const user = encodeURIComponent(process.env["DB_USER"] || "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"; return `postgresql://${user}:${password}@${host}:${port}/${name}`; } diff --git a/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql b/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql new file mode 100644 index 0000000..4d77830 --- /dev/null +++ b/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql @@ -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 $$; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8b1a2a4..1168184 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -68,6 +68,17 @@ model Cotizacion { observacionesInternas String? clienteId 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()) updatedAt DateTime @updatedAt @@ -78,6 +89,7 @@ model Cotizacion { registrosHoras RegistroHoras[] propuestasIA PropuestaIA[] programasPago ProgramaPago[] + approvalTokens ApprovalToken[] @@index([clienteId]) @@index([asesorId]) @@ -380,3 +392,101 @@ model SuscripcionPush { @@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]) +} diff --git a/prisma/seed.ts b/prisma/seed.ts index 7fb4b91..4da06ea 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -7,6 +7,7 @@ const adapter = new PrismaPg({ port: parseInt(process.env.DB_PORT || "5432"), user: process.env.DB_USER || "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", }); const prisma = new PrismaClient({ adapter }); @@ -16,7 +17,7 @@ async function main() { // Credentials come from env. Without SEED_*_PASSWORD the user is created // 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; if (!adminPassword) { console.warn( @@ -567,7 +568,7 @@ async function main() { }, { 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, tipoPago: "mensual", 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 // Niveles: Emprendedor / PYME / Empresario / Corporativo // ────────────────────────────────────────────────────────────── @@ -1966,7 +1967,7 @@ async function main() { }, { clave: "domicilio_fiscal", - valor: "EMILIANO ZAPATA S/N, CUAMIO, CUITZEO, MICHOACAN DE OCAMPO CP 58855", + valor: "", }, { clave: "cuenta_nacional", @@ -2002,7 +2003,7 @@ async function main() { }, { 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", @@ -2010,11 +2011,11 @@ async function main() { }, { clave: "color_primario", - valor: "#2563eb", + valor: "#0400C4", }, { clave: "color_secundario", - valor: "#1e293b", + valor: "#0F172A", }, { clave: "logo_base64", diff --git a/public/sw.js b/public/sw.js index e585f3a..80c8c2c 100644 --- a/public/sw.js +++ b/public/sw.js @@ -8,7 +8,7 @@ self.addEventListener("push", (event) => { } catch { data = {}; } - const titulo = (data && data.titulo) || "Cotizador E3"; + const titulo = (data && data.titulo) || "Cotizador — Uriel Jareth Consulting"; const cuerpo = (data && data.cuerpo) || ""; const url = (data && data.url) || "/cliente/pagos"; event.waitUntil( diff --git a/scripts/provision-agent-keys.ts b/scripts/provision-agent-keys.ts new file mode 100644 index 0000000..d8ee85d --- /dev/null +++ b/scripts/provision-agent-keys.ts @@ -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 = {}; + 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 --scopes [--rate-limit 60] [--rotate]" + ); + process.exit(2); + } + + const rotate = Boolean(args.rotate); + const results: Array> = []; + + 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); +}); diff --git a/scripts/verificar-propuesta-pdf.ts b/scripts/verificar-propuesta-pdf.ts index c4ce942..1cd2a85 100644 --- a/scripts/verificar-propuesta-pdf.ts +++ b/scripts/verificar-propuesta-pdf.ts @@ -102,7 +102,7 @@ const datos: DatosPropuestaPDF = { fecha: new Date("2026-07-29"), vigencia: new Date("2026-08-19"), proyecto: "MKT Digital", - branding: { colorPrimario: "#2563eb" }, + branding: { colorPrimario: "#0400C4" }, }; async function main() { diff --git a/scripts/verificar-propuesta-schemas.ts b/scripts/verificar-propuesta-schemas.ts index 5322c83..a5b5ae4 100644 --- a/scripts/verificar-propuesta-schemas.ts +++ b/scripts/verificar-propuesta-schemas.ts @@ -6,7 +6,7 @@ function check(n: string, ok: boolean, d = "") { 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([ aJsonSchema(hechosSchema), aJsonSchema(diagnosticoSchema), diff --git a/src/app/(app)/configuracion/ConfiguracionClient.tsx b/src/app/(app)/configuracion/ConfiguracionClient.tsx index 5d73dbe..dd1b659 100644 --- a/src/app/(app)/configuracion/ConfiguracionClient.tsx +++ b/src/app/(app)/configuracion/ConfiguracionClient.tsx @@ -20,7 +20,7 @@ const SECTIONS = [ fields: [ { key: "razon_social", label: "Razon Social", 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 handleChange(field.key, e.target.value)} 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
) : field.type === "textarea" ? ( @@ -222,6 +222,9 @@ export function ConfiguracionClient({ initial }: { initial: Record )} + {"hint" in field && field.hint && ( +

{field.hint}

+ )} ))} diff --git a/src/app/(app)/cotizaciones/[id]/CambiarEstadoButtons.tsx b/src/app/(app)/cotizaciones/[id]/CambiarEstadoButtons.tsx index a924147..8791327 100644 --- a/src/app/(app)/cotizaciones/[id]/CambiarEstadoButtons.tsx +++ b/src/app/(app)/cotizaciones/[id]/CambiarEstadoButtons.tsx @@ -2,46 +2,350 @@ import { useState } from "react"; 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 = [ - { value: "borrador", label: "Borrador" }, - { value: "enviada", label: "Enviada" }, - { value: "aprobada", label: "Aprobada" }, - { value: "rechazada", label: "Rechazada" }, -]; +interface Props { + cotizacionId: string; + numero: string; + estado: string; + 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 [loading, setLoading] = useState(false); + const confirm = useConfirm(); 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); try { - const res = await fetch(`/api/cotizaciones/${cotizacionId}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ estado: nuevoEstado }), + const res = await fetch(`/api/cotizaciones/${cotizacionId}/aprobar`, { + method: "POST", }); - if (res.ok) router.refresh(); - else showToast("Error al cambiar estado", "error"); + const data = await res.json().catch(() => ({})); + if (res.ok) { + showToast("Cotización aprobada correctamente", "success"); + router.refresh(); + } else { + showToast(data.error || "No se pudo aprobar la cotización", "error"); + } } finally { 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 ( - +
+ + + {estado === "borrador" && esAdmin && ( + + )} + + {estado === "aprobada" && ( + <> + + {esAdmin && ( + + )} + + )} + + {estado === "enviada" && ( + <> + + + + + )} + + {(estado === "rechazada" || estado === "vencida") && esAdmin && ( + + )} + + {showEnviarModal && ( +
!loading && setShowEnviarModal(false)} + > +
e.stopPropagation()} + className="bg-white rounded-xl border border-border shadow-xl max-w-md w-full p-5 space-y-4" + > +
+

Enviar cotización {numero}

+

+ El PDF oficial se genera automáticamente al confirmar el envío. +

+
+ +
+ + + {esAdmin && ( + + )} +
+ +
+ + setDestino(e.target.value)} + required={canal !== "manual"} + placeholder={canal === "email" ? "cliente@empresa.com" : "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" + /> +
+ + {canal !== "manual" && ( +
+ +