Compare commits
10
Commits
ab6080ebe7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f64487b88 | ||
|
|
670265a390 | ||
|
|
0d4f19f35d | ||
|
|
75180b0fe4 | ||
|
|
78385a8ac8 | ||
|
|
4b1408052a | ||
|
|
14526f92f2 | ||
|
|
5e2b784c24 | ||
|
|
6402128dfc | ||
|
|
76e93e6615 |
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: cotizador-cli
|
||||
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 — Uriel Jareth Consulting por CLI
|
||||
|
||||
El CLI vive en `cli/cotizador.mjs` (Node 18+, sin dependencias). Ejecútalo desde la raíz del repo con `node cli/cotizador.mjs <comando>`.
|
||||
|
||||
## Antes de nada
|
||||
|
||||
1. Descubre los comandos con `node cli/cotizador.mjs esquema`. Devuelve en JSON cada comando con sus flags, tipos, valores válidos, ejemplos y endpoint, más el dominio (fases, tipos de pago, estados). No adivines flags.
|
||||
2. Sesión: `node cli/cotizador.mjs whoami`. Si sale código 3, pide al usuario sus credenciales o que defina `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD`. Nunca escribas una contraseña en un archivo del repo ni la repitas en el chat.
|
||||
3. Destino: `COTIZADOR_URL` (default `http://localhost:3000`). Producción es `https://cotizador.urieljareth.org`. **Confirma con el usuario antes de escribir en producción.**
|
||||
|
||||
## Reglas
|
||||
|
||||
- Salida JSON en stdout; errores JSON en stderr con `codigo` y a veces `sugerencia`: léela y síguela.
|
||||
- Usa `--campos` para traer solo lo que necesitas (`--campos id,nombre,precioBase`).
|
||||
- Antes de crear, editar o borrar algo que el usuario no haya pedido literalmente, corre el comando con `--dry-run` y muéstrale la petición.
|
||||
- `eliminar` exige `--confirmar`. No lo agregues por tu cuenta: es una acción irreversible y la decide el usuario.
|
||||
- Editar un servicio es parcial. `--entregable` reemplaza la lista; para sumar uno usa `--agregar-entregable`.
|
||||
- Para referirte a un servicio puedes usar su nombre exacto; si sale "ambiguo", usa el id de la sugerencia.
|
||||
|
||||
## Recetas
|
||||
|
||||
```bash
|
||||
node cli/cotizador.mjs servicios listar --q "seo" --campos id,nombre,precioBase,fase
|
||||
node cli/cotizador.mjs servicios crear --nombre "..." --fase 1 --tipo-pago unico --precio 5000 --categoria "Desarrollo Web"
|
||||
node cli/cotizador.mjs servicios editar "<nombre o id>" --precio 5500
|
||||
node cli/cotizador.mjs cotizaciones crear --cliente "..." --empresa "..." --servicio "<nombre o id>" --servicio "<id>=4500"
|
||||
node cli/cotizador.mjs cotizaciones estado UJ2611AD001 enviada
|
||||
node cli/cotizador.mjs cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf
|
||||
```
|
||||
|
||||
Guía completa: `docs/CLI.md`.
|
||||
+35
-17
@@ -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,29 +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.
|
||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
# 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
|
||||
|
||||
# Directorio de comprobantes. Local: vacio = <repo>/uploads.
|
||||
# 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: vacío = <repo>/uploads.
|
||||
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
||||
UPLOAD_DIR=
|
||||
UPLOAD_DIR=
|
||||
|
||||
# --- API de agentes, aprobación humana y webhooks HMAC-SHA256 ---
|
||||
# Correo al que llegan las solicitudes de aprobación de borradores (fallback: primer usuario admin)
|
||||
ADMIN_NOTIFY_EMAIL=
|
||||
# Webhook saliente por defecto hacia n8n (firmado con X-Cotizador-Signature: sha256=...)
|
||||
WEBHOOK_N8N_URL=
|
||||
WEBHOOK_N8N_SECRET=
|
||||
# Webhook de n8n para envío de cotizaciones aprobadas por WhatsApp/Chatwoot
|
||||
WEBHOOK_WHATSAPP_SEND_URL=
|
||||
# Backend Python (api/): solo aceptar la vieja API_KEY sin alcances si se habilita explícitamente
|
||||
ALLOW_LEGACY_API_KEY=false
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# AGENTS.md — Cotizador E3
|
||||
# AGENTS.md — Cotizador — Uriel Jareth Consulting
|
||||
|
||||
## Quick Reference
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
| `npm run db:migrate` | Create/apply migration (`prisma migrate dev`) |
|
||||
| `npm run db:generate` | Regenerate Prisma client |
|
||||
| `npm run db:studio` | Prisma Studio GUI |
|
||||
| `npm run cli -- <comando>` | CLI `cotizador` (servicios, clientes, cotizaciones, horas). `node cli/cotizador.mjs esquema` lo describe en JSON. See `docs/CLI.md` |
|
||||
|
||||
**There is no test suite** — no runner, no test files, in either backend. Verification is `npm run build` (typechecks) + `npm run lint`. Don't claim a change is verified on the strength of a build alone; exercise the affected route or page.
|
||||
|
||||
@@ -50,6 +51,14 @@
|
||||
- **Bucéfalo CRM plan prices** (in `calculators.ts`, NOT the DB): basico=$1,000, estandar=$3,500, premium=$4,500, empresarial=$7,500 (monthly).
|
||||
- **Financing** lives in the `FinanciamientoPlan` table (3/6/9/12 months). Formula: `comisionTotal = monto × comision%`, `pagoMensual = (monto + comisionTotal) × (1 + tasa) / meses`, then add 16% IVA. Both backends must keep this formula identical.
|
||||
|
||||
### Catálogo de servicios (alta y edición)
|
||||
|
||||
- API: `GET|POST /api/catalogo` (GET filtra `?q=&fase=&tipoPago=&categoriaId=&activo=true|false`; sin `activo` devuelve activos y archivados) y `GET|PATCH|PUT|DELETE /api/catalogo/[id]`. **PATCH y PUT son parciales**: solo tocan los campos enviados (`servicioCatalogoPatchSchema`). DELETE archiva (`activo=false`) si alguna cotización usa el servicio; si no, lo borra.
|
||||
- Las respuestas salen de `serializarServicio` (`src/lib/catalogo.ts`): forma plana con `categoriaNombre`, `categoriaColor` y `enCotizaciones`. Los 400 de estas rutas usan `errorValidacion` (`{ error, detalles: [{ campo, mensaje }] }`).
|
||||
- En `servicioCatalogoSchema` solo `nombre`, `fase`, `tipoPago` y `precioBase` son obligatorios; `categoriaId` es opcional y, sin `orden`, el servicio queda al final de su fase (`siguienteOrden`). En esos esquemas el `.optional()` va **por fuera** del transform de texto: si va por dentro, una clave ausente se vuelve `null` y un PATCH borra el dato.
|
||||
- UI: `src/components/ServicioFormModal.tsx` hace el POST/PATCH y muestra el error de la API sin cerrarse. Lo usan `/catalogo` y `CotizacionForm`: en el cotizador, "Nuevo servicio" (general o por fase) lo crea y lo deja seleccionado, y el lápiz de cada servicio lo edita. Si la cotización usa ese servicio, su partida toma el nombre, fase, tipo de pago, tiempo y entregables nuevos; el precio solo si la partida tenía el precio base anterior.
|
||||
- Los ids de los servicios del seed son slugs (`auditoria-en-sitio-web-2`), no cuids: no valides ids por formato.
|
||||
|
||||
### Charge models (`ServicioCotizado.modeloCobro`)
|
||||
|
||||
A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — see `MODELOS_COBRO` in `calculators.ts`. The time-based three are `MODELOS_COBRO_TIEMPO`. Supporting fields: `esPersonalizado`, `horas`, `tarifaHora`, `montoMinimo`, `horasIncluidas`. `TARIFA_HORA_DEFAULT = 700`.
|
||||
@@ -73,21 +82,33 @@ A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — se
|
||||
|
||||
- **JWT sessions** (`src/lib/auth.ts`) signed with `jose` (HS256, 7-day expiry), stored in the `cotizador-session` httpOnly cookie. `JWT_SECRET` env var is **required** (throws at startup if missing).
|
||||
- **`src/middleware.ts`** gates everything except `PUBLIC_PATHS` (`/login`, `/api/auth/login`, `/api/auth/logout`, `/api/health`, `/sw.js`). Unauthenticated API calls → 401 JSON; pages → redirect to `/login` (`/login?panel=cliente` para rutas de cliente). On success it injects `x-user-id` / `x-user-role` / `x-cliente-id` request headers for downstream handlers.
|
||||
- Passwords hashed with `bcryptjs`. Roles: `admin`, `asesor` (default) y **`cliente`**. El middleware separa paneles: `role=cliente` solo entra a `/cliente*` y `/api/cliente*`; el staff no entra a esas rutas; `/api/comprobantes` y `/api/export/pdf` son **compartidas** (el handler valida pertenencia). Además de middleware, las rutas nuevas usan `requireStaff()` / `requireRole("cliente")` de `src/lib/auth.ts` dentro del handler (defensa en profundidad). El login redirige por rol (`/` vs `/cliente`); la sesión de cliente lleva el claim `clienteId`.
|
||||
- Clientes se dan de alta y se editan en `/clientes` (`POST /api/clientes`, `PATCH /api/clientes/[id]`, helpers en `src/lib/clientes.ts`) sin pasar por una cotización; como las cotizaciones reconocen al cliente por `nombre + empresa`, la API rechaza esa pareja duplicada (sin distinguir mayúsculas) con 409. `/clientes?nuevo=1` abre el alta. `Cliente.puesto` es solo informativo. Passwords hashed with `bcryptjs`. Roles: `admin`, `asesor` (default) y **`cliente`**. El middleware separa paneles: `role=cliente` solo entra a `/cliente*` y `/api/cliente*`; el staff no entra a esas rutas; `/api/comprobantes` y `/api/export/pdf` son **compartidas** (el handler valida pertenencia). Además de middleware, las rutas nuevas usan `requireStaff()` / `requireRole("cliente")` de `src/lib/auth.ts` dentro del handler (defensa en profundidad). El login redirige por rol (`/` vs `/cliente`); la sesión de cliente lleva el claim `clienteId`.
|
||||
|
||||
## 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-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).
|
||||
- Skill para agentes: `.claude/skills/cotizador-cli/SKILL.md`. Guía: `docs/CLI.md`.
|
||||
|
||||
## Cobros recurrentes y panel de cliente
|
||||
|
||||
- **Modelos**: `ProgramaPago` (cadencia semanal/quincenal/mensual, ej. `$750 cada sábado`), `PagoRecurrente` (único por `programaId+fecha`; estados `pendiente → en_revision → verificado | rechazado`), `ComprobantePago` (archivo en `UPLOAD_DIR/comprobantes/…`, fuera de `/public`), `SuscripcionPush`. `User.clienteId` vincula la cuenta `role=cliente` con un `Cliente` (1:1).
|
||||
- **Modelos**: `ProgramaPago` (cadencia semanal/quincenal/mensual, ej. `$750 cada sábado`), `PagoRecurrente` (único por `programaId+fecha`; estados `pendiente → en_revision → verificado | rechazado`, más `anulado` = sin cargo; `nota` es interna del admin y el cliente no la ve), `ComprobantePago` (archivo en `UPLOAD_DIR/comprobantes/…`, fuera de `/public`), `SuscripcionPush`. `User.clienteId` vincula la cuenta `role=cliente` con un `Cliente` (1:1).
|
||||
- **`src/lib/cobros-fechas.ts` vs `src/lib/cobros.ts`**: las utilidades puras (estados, fechas de calendario MX, formatos, `fechasPeriodo`) viven en `cobros-fechas.ts`. **Los componentes `"use client"` importan de `@/lib/cobros-fechas`, NUNCA de `@/lib/cobros`** — ese arrastra Prisma/pg y rompe el build de Next. `cobros.ts` (lado servidor) re-exporta todo y agrega `generarCobros()` idempotente.
|
||||
- **Fechas**: una fecha de cobro es fecha de calendario en `America/Mexico_City` persistida como medianoche UTC (`parseFechaCalendario` / `formatFechaCobro` / `formatFechaCorta`). No usar `new Date(iso)` directo.
|
||||
- **Scheduler**: `src/instrumentation.ts` importa `src/lib/scheduler.ts` **dentro del guard `NEXT_RUNTIME === "nodejs"`** (si lo mueves fuera, pg entra al bundle Edge y el build falla). Corre a los 20 s del arranque y cada 60 min: `generarCobros()` + `notificarCobrosNuevos()`.
|
||||
- **Notificaciones** (`src/lib/notificaciones.ts`): llamar **después** de persistir el cambio — `notificarCobrosNuevos(pagos)`, `notificarVerificacion(pagoId)`, `notificarRechazo(pagoId, motivo)`. Son best-effort; SMTP/VAPID sin configurar solo avisan en log (`email.ts` / `push.ts`), jamás tumbaron el flujo.
|
||||
- **Recordatorios de pagos pendientes** (`enviarRecordatoriosPendientes` en `notificaciones.ts`): "por pagar" = `pendiente | rechazado` con `fecha <= hoy` (`ESTADOS_POR_PAGAR`, `pagosPorCobrar()` en `cobros.ts`, que incluye programas inactivos). Manda **un estado de cuenta por cliente** (lista, total por moneda, datos bancarios de Configuración) por correo + push y sella `ultimoRecordatorioAt` / `recordatoriosEnviados` **solo si algún canal lo entregó**. El scheduler lo corre desde las 9:00 MX cuando algún cobro lleva `COBROS_RECORDATORIO_DIAS` (default 3; 0 = apagado) sin aviso, y lo hace **antes** de `notificarCobrosNuevos` para no mandar dos correos al mismo cliente en una corrida. Envío manual: `POST /api/cobros/recordatorios` (`{ clienteId? }`, ignora la espera) desde la sección "Pagos por cobrar" de `/cobros`.
|
||||
- **Pagos fuera del panel** (clientes sin cuenta o que avisan por otro medio): `POST /api/cobros/pagos/[id]/registrar` (`{ fecha, nota? }`, `pendiente|rechazado → verificado` sin comprobante; `verificadoAt = instanteDePago(fecha)`, mediodía MX, para que `calendarioDe()` no lo corra al día anterior), `.../anular` (`{ motivo }` → `anulado`) y `.../reabrir` (manual o anulado → `pendiente`). **Anular no borra el registro**: si se borrara, `generarCobros()` lo volvería a crear como pendiente, porque rellena todos los periodos desde `fechaInicio`. Por eso un programa con historial se carga completo (un registro por periodo) y no solo con los pagos. `GET /api/cobros/pagos` acepta `clienteId` y `estado=por_pagar`.
|
||||
- **Subidas**: `src/lib/uploads.ts` (`guardarComprobante`/`eliminarComprobante`) convierte imágenes a WebP con sharp (máx 1920 px, q80), PDFs tal cual, 10 MB. Las rutas se guardan con separadores `/` aunque el dev corra en Windows. El rechazo borra el archivo del servidor y el cliente puede volver a subir.
|
||||
- **UI**: admin en `/cobros` (nav del Sidebar), panel cliente en `/cliente` (shell propio, sin el Sidebar de staff) con `public/sw.js` para Web Push.
|
||||
|
||||
## Deployment (Coolify)
|
||||
|
||||
- Production stack: `docker-compose.coolify.yml` (postgres + web + api). In Coolify set **Docker Compose Location** to `/docker-compose.coolify.yml`. Local dev keeps using `docker-compose.yml` + `start.bat`.
|
||||
- Production stack: postgres + web + api. The live Coolify app (`cotizador`, uuid `e6vie34d83iv5vw3eyzinl3s`, https://cotizador.urieljareth.org) has **Docker Compose Location `/docker-compose.yaml`** — the byte-identical copy — so both files must stay in sync. Local dev keeps using `docker-compose.yml` + `start.bat`.
|
||||
- **Deploys come from GitHub `main` (`origin`), not Gitea.** Auto-deploy is on: a push to GitHub `main` *is* the deploy (~15 min full build). Pushing to `gitea` only mirrors the code. Don't also trigger the deploy API after a push, or two deploys race.
|
||||
- `APP_URL` must be set in Coolify (`https://cotizador.urieljareth.org`): email links fall back to `http://localhost:3000` without it. **Never read a runtime value through a `NEXT_PUBLIC_*` name on the server** — Next inlines those at build time (even via a computed key), and the production image is built without them.
|
||||
- The `web` container runs `prisma migrate deploy` on every start, and the seed only when `RUN_SEED=true`. Seed users/passwords come from `SEED_*` env vars (see `.env.example`) — `prisma/seed.ts` never overwrites an existing password unless the env var is set.
|
||||
- `DATABASE_URL` is only used by the Prisma CLI (migrations); the apps use individual `DB_*` vars. Both must point to the same DB.
|
||||
- Healthchecks: web `GET /api/health` (public in middleware, pings DB), api `GET /health`.
|
||||
@@ -103,8 +124,8 @@ src/
|
||||
api/ # Next.js route handlers (REST): auth, catalogo, categorias, cotizaciones (+ horas, nota-horas, precio),
|
||||
# configuracion, paquetes, export, import, health
|
||||
login/ # Public login page
|
||||
components/ # CotizacionForm (~1.4k lines), ExportButtons, EstadoBadge, layout/Sidebar, ui/DialogProvider
|
||||
lib/ # auth, db, store, calculators, schemas, config-helpers,
|
||||
components/ # CotizacionForm (~1.5k lines), ServicioFormModal, ExportButtons, EstadoBadge, layout/Sidebar, ui/DialogProvider
|
||||
lib/ # auth, db, store, calculators, schemas, config-helpers, catalogo, cotizaciones,
|
||||
# pdf-generator (quote PDF), nota-horas-pdf (hours-note PDF), excel-builder
|
||||
generated/prisma/ # Prisma client output (gitignored)
|
||||
prisma/
|
||||
@@ -113,6 +134,7 @@ prisma/
|
||||
# RegistroHoras, Configuracion, Bono, FinanciamientoPlan)
|
||||
seed.ts # All catalog data (services, categorias, bonos, planes, config) — idempotent upserts
|
||||
migrations/ # 10 migrations
|
||||
cli/ # cotizador.mjs — CLI para humanos y LLMs (see docs/CLI.md)
|
||||
api/ # Standalone Python FastAPI service (see below)
|
||||
docs/ # Business/product notes (Spanish), not code docs
|
||||
```
|
||||
@@ -138,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`.
|
||||
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
# Cotizador E3 — Next.js (web)
|
||||
# Cotizador — Uriel Jareth Consulting — Next.js (web)
|
||||
# Multi-stage build. El runner conserva node_modules completo para que
|
||||
# `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
|
||||
|
||||
@@ -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/<token>`) y no puede enviarse (`POST /api/cotizaciones/:id/enviar`) hasta quedar `aprobada` por un administrador humano.
|
||||
- **Webhooks salientes HMAC-SHA256:** firmados con `X-Cotizador-Signature: sha256=...`, reintentos automáticos y registro en `WebhookDelivery`.
|
||||
- **Paridad en `api/` (FastAPI):** valida las mismas `AgentApiKey`, scopes, rate limit y reglas de aprobación; `ALLOW_LEGACY_API_KEY=false` por defecto; agrega `GET /cobros/programas` y `GET /cobros/pagos`.
|
||||
|
||||
## Pruebas automáticas
|
||||
|
||||
```bash
|
||||
npm test # Pruebas unitarias y paridad TS/Python (node --test + tsx)
|
||||
npm run lint # ESLint
|
||||
npm run build # Build de producción Next.js
|
||||
```
|
||||
|
||||
@@ -3,6 +3,7 @@ DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_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
|
||||
|
||||
+36
-441
@@ -1,457 +1,52 @@
|
||||
# Cotizador E3 — API Documentation for AI Skills
|
||||
# Cotizador — Uriel Jareth Consulting — Guía de API para Agentes
|
||||
|
||||
## Overview
|
||||
## Arquitectura unificada
|
||||
|
||||
REST API for Consultoría E3's digital marketing quotation system. Allows AI agents to manage clients, browse service catalogs, create quotations, calculate financing, generate PDF/Excel documents, and manage the full sales pipeline.
|
||||
- **API principal (Next.js `/api/**`):** `https://cotizador.urieljareth.org/api` — OpenAPI 3.1 en `GET /api/openapi.json`.
|
||||
- Incluye catálogo, clientes, cotizaciones, flujo de aprobación humana, envío por correo/WhatsApp, PDF/Excel, cobros recurrentes, claves de agentes, auditoría y webhooks HMAC-SHA256.
|
||||
- **API Python en paridad (FastAPI):** `https://cotizador-api.urieljareth.org` — Swagger en `/docs`.
|
||||
- Valida las mismas claves `AgentApiKey` (SHA-256) contra la misma PostgreSQL, aplica scopes, rate limit, auditoría (`AuditLog`), paridad de cálculo (`calculators.py`) y lectura de `/cobros/programas` y `/cobros/pagos`.
|
||||
- La vieja `API_KEY` ilimitada está desactivada por defecto (`ALLOW_LEGACY_API_KEY=false`).
|
||||
|
||||
**Base URL:** `http://localhost:8000`
|
||||
**Auth:** API Key via `X-API-Key` header or `Authorization: Bearer <key>`
|
||||
**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/<token>` (`POST /api/aprobar/<token>` con `{ "confirmar": true }`). Ningún agente ni asesor puede aprobar (`403` + `AuditLog`).
|
||||
4. Una vez en `aprobada` (con `aprobadaAt`), el agente con `cotizaciones:enviar` puede ejecutar `POST /api/cotizaciones/:id/enviar` con `canal: "email" | "whatsapp_chatwoot"` y opcionalmente `verificarContacto` (email o teléfono del prospecto; si no coincide → `403`). Sin aprobación previa devuelve `409`.
|
||||
|
||||
---
|
||||
## Webhooks salientes (HMAC-SHA256)
|
||||
|
||||
## Authentication
|
||||
Eventos: `cotizacion.creada`, `cotizacion.aprobada`, `cotizacion.enviada`, `cotizacion.aceptada`, `cotizacion.rechazada`, `cotizacion.vencida`, `pago.registrado`, `pago.vencido`.
|
||||
|
||||
### API Key (for agents)
|
||||
```
|
||||
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=<hmac_sha256_hex>`
|
||||
|
||||
### JWT (for human login)
|
||||
```
|
||||
POST /auth/login
|
||||
Body: { "email": "[email protected]", "password": "secret" }
|
||||
Response: { "user": { "id", "name", "email", "role" } }
|
||||
Sets cookie: cotizador-session (httpOnly, 7 days)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Endpoints Reference
|
||||
|
||||
### Health & Info
|
||||
|
||||
#### GET /health
|
||||
Health check endpoint. No auth required.
|
||||
- **Response:** `{ "status": "ok", "timestamp": "2026-05-03T..." }`
|
||||
|
||||
#### GET /api-info
|
||||
API capabilities and version info.
|
||||
- **Response:** `{ "name": "Cotizador E3 API", "version": "1.0.0", "capabilities": [...] }`
|
||||
|
||||
---
|
||||
|
||||
### Clients (Clientes)
|
||||
|
||||
#### GET /clientes
|
||||
List clients with optional search and pagination.
|
||||
- **Query params:** `?q=texto&page=1&limit=50`
|
||||
- **Response:** `{ "data": [Cliente], "meta": { "total", "page", "limit", "pages" } }`
|
||||
|
||||
#### POST /clientes
|
||||
Create a new client.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Juan Pérez",
|
||||
"empresa": "ACME Corp",
|
||||
"email": "[email protected]",
|
||||
"telefono": "4421234567"
|
||||
}
|
||||
```
|
||||
- **Response (201):** Full Cliente object with `id`
|
||||
|
||||
#### GET /clientes/{id}
|
||||
Get client details including recent quotations.
|
||||
- **Response:** Cliente object + `cotizaciones` array
|
||||
|
||||
#### PUT /clientes/{id}
|
||||
Update client information.
|
||||
- **Body:** Same as POST (all fields optional for update)
|
||||
|
||||
#### DELETE /clientes/{id}
|
||||
Delete client. Returns 409 if client has quotations.
|
||||
- **Response (200):** `{ "ok": true }`
|
||||
- **Error (409):** `{ "error": "Cliente tiene N cotizaciones asociadas" }`
|
||||
|
||||
---
|
||||
|
||||
### Service Catalog (Catálogo)
|
||||
|
||||
#### GET /catalogo
|
||||
List all active services with optional filters.
|
||||
- **Query params:** `?fase=0&tipoPago=mensual&categoriaId=xxx&q=seo`
|
||||
- **Response:** Array of ServicioCatalogo objects
|
||||
|
||||
Each service:
|
||||
```json
|
||||
{
|
||||
"id": "cuid",
|
||||
"nombre": "Posicionamiento SEO",
|
||||
"descripcion": "...",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precioBase": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregablesDefault": ["Keyword research", "On-page optimization"],
|
||||
"categoriaId": "cuid",
|
||||
"variante": null,
|
||||
"activo": true,
|
||||
"orden": 0
|
||||
}
|
||||
```
|
||||
|
||||
#### POST /catalogo
|
||||
Create a new service.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Nuevo Servicio",
|
||||
"descripcion": "Descripción del servicio",
|
||||
"fase": 1,
|
||||
"tipoPago": "unico",
|
||||
"precioBase": 5000,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregablesDefault": ["Entregable 1", "Entregable 2"],
|
||||
"categoriaId": "cuid",
|
||||
"variante": null,
|
||||
"orden": 0
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /catalogo/{id}
|
||||
Get service details with category info.
|
||||
|
||||
#### PUT /catalogo/{id}
|
||||
Update service. Same body as POST.
|
||||
|
||||
#### DELETE /catalogo/{id}
|
||||
Soft-delete if used in quotations, hard-delete otherwise.
|
||||
- **Response:** `{ "ok": true, "archived": true|false }`
|
||||
|
||||
---
|
||||
|
||||
### Categories (Categorías)
|
||||
|
||||
Available: SEO (#10b981), Marketing (#6366f1), Paid Media (#f59e0b), Desarrollo Web (#3b82f6), Automatizaciones (#8b5cf6), CRM (#ec4899), Desarrollo Personalizado (#14b8a6)
|
||||
|
||||
#### GET /categorias
|
||||
List all categories ordered by `orden`.
|
||||
|
||||
#### POST /categorias
|
||||
- **Body:** `{ "nombre": "Nueva Cat", "descripcion": "...", "color": "#6b7280", "orden": 0 }`
|
||||
|
||||
#### GET /categorias/{id}
|
||||
Get category with its services.
|
||||
|
||||
#### PUT /categorias/{id}
|
||||
- **Body:** `{ "nombre", "descripcion", "color", "orden", "activo" }`
|
||||
|
||||
#### DELETE /categorias/{id}
|
||||
Returns 409 if category has associated services.
|
||||
|
||||
---
|
||||
|
||||
### Quotations (Cotizaciones)
|
||||
|
||||
#### GET /cotizaciones
|
||||
List quotations with filters.
|
||||
- **Query params:** `?estado=borrador&asesorId=xxx&clienteId=xxx&q=texto&desde=2026-01-01&hasta=2026-12-31&page=1&limit=50`
|
||||
- **Response:** Array with full relations (cliente, asesor, servicios+catalogo, planBucefalo)
|
||||
|
||||
#### POST /cotizaciones
|
||||
Create a complete quotation. Auto-creates client if not found.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"numero": "UJ2605AG001",
|
||||
"fecha": "2026-05-03",
|
||||
"vigencia": "2026-05-24",
|
||||
"moneda": "MXN",
|
||||
"tipoCambio": "NA",
|
||||
"proyecto": "MKT Digital",
|
||||
"esquemaPago": "Pago Unico/Mensual",
|
||||
"incluirBonos": false,
|
||||
"incluirFinanciamiento": false,
|
||||
"observaciones": "",
|
||||
"asesorId": "cuid",
|
||||
"cliente": {
|
||||
"nombre": "Juan Pérez",
|
||||
"empresa": "ACME Corp",
|
||||
"email": "[email protected]",
|
||||
"telefono": "4421234567"
|
||||
},
|
||||
"servicios": [
|
||||
{
|
||||
"catalogoId": "cuid",
|
||||
"nombre": "SEO On-Page",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precio": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregables": ["Keyword research", "On-page SEO"]
|
||||
}
|
||||
],
|
||||
"planBucefalo": {
|
||||
"nivel": "basico",
|
||||
"precio": 1000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /cotizaciones/{id}
|
||||
Get quotation with all relations.
|
||||
|
||||
#### PUT /cotizaciones/{id}
|
||||
Update quotation. Replaces all services in a transaction.
|
||||
- **Body:** Same as POST without `numero` and `asesorId`. Optional `estado`.
|
||||
|
||||
#### DELETE /cotizaciones/{id}
|
||||
Hard-delete with cascade.
|
||||
|
||||
#### PATCH /cotizaciones/{id}/precio
|
||||
Update price of a single service.
|
||||
- **Body:** `{ "servicioId": "cuid", "precio": 7500 }`
|
||||
|
||||
#### PATCH /cotizaciones/{id}/estado
|
||||
Change quotation status.
|
||||
- **Body:** `{ "estado": "enviada" }` — `borrador`, `enviada`, `aprobada`, `rechazada`
|
||||
|
||||
#### POST /cotizaciones/{id}/duplicate
|
||||
Duplicate quotation as new copy in `borrador` state.
|
||||
|
||||
---
|
||||
|
||||
### Packages (Paquetes)
|
||||
|
||||
#### GET /paquetes
|
||||
List active packages with nested phases and services.
|
||||
|
||||
#### POST /paquetes
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Paquete Básico",
|
||||
"descripcion": "...",
|
||||
"fases": [
|
||||
{ "nombre": "Auditoría", "orden": 0 },
|
||||
{ "nombre": "Setup", "orden": 1 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /paquetes/{id}
|
||||
Get package with full nested structure.
|
||||
|
||||
#### PUT /paquetes/{id}
|
||||
- **Body:** `{ "nombre", "descripcion", "activo" }`
|
||||
|
||||
#### DELETE /paquetes/{id}
|
||||
Hard-delete with cascade.
|
||||
|
||||
#### POST /paquetes/{id}/manage
|
||||
Multi-action endpoint:
|
||||
- `{ "action": "addFase", "nombre": "Fase 3", "orden": 2 }`
|
||||
- `{ "action": "updateFase", "faseId": "cuid", "nombre": "New Name", "orden": 1 }`
|
||||
- `{ "action": "deleteFase", "faseId": "cuid" }`
|
||||
- `{ "action": "addServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
||||
- `{ "action": "removeServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
||||
|
||||
---
|
||||
|
||||
### Configuration (Configuración)
|
||||
|
||||
Allowed keys: `color_primario`, `color_secundario`, `logo_base64`, `razon_social`, `rfc`, `domicilio_fiscal`, `cuenta_nacional`, `clabe_interbancaria`, `cuenta_internacional`, `cuenta_internacional_swift`, `hora_centinela`, `anualidad_hosting`, `iva`, `terminos_condiciones`, `no_incluye`, `notas_adicionales`
|
||||
|
||||
#### GET /configuracion
|
||||
- **Response:** `{ "color_primario": "#2563eb", "razon_social": "...", ... }`
|
||||
|
||||
#### PUT /configuracion
|
||||
Bulk upsert. Only whitelisted keys processed.
|
||||
- **Body:** `{ "color_primario": "#ff0000", "razon_social": "Nuevo Nombre" }`
|
||||
|
||||
---
|
||||
|
||||
### Bonuses (Bonos)
|
||||
|
||||
Available: Centinela Web, Workshop Buyer Persona, Workshop Propuesta de Valor, Membresía Premium, Mes Gratis CRM, Script de Ventas
|
||||
|
||||
#### GET /bonos
|
||||
|
||||
---
|
||||
|
||||
### Financing (Financiamiento)
|
||||
|
||||
| Months | Rate | Commission | Min Amount |
|
||||
|--------|------|------------|------------|
|
||||
| 3 | 7.7% | 2.5% | $300 |
|
||||
| 6 | 10.7% | 2.5% | $600 |
|
||||
| 9 | 13.7% | 2.5% | $900 |
|
||||
| 12 | 16.7% | 2.5% | $1,200 |
|
||||
|
||||
#### GET /financiamiento/planes
|
||||
|
||||
#### POST /financiamiento/calcular
|
||||
- **Body:** `{ "monto": 50000, "meses": 6 }`
|
||||
- **Response:** `{ "pagoMensual", "ivaMensual", "totalMensual", "comisionTotal", "granTotal" }`
|
||||
|
||||
#### GET /financiamiento/simulacion/{cotizacion_id}
|
||||
Auto-calculate financing for existing quotation.
|
||||
|
||||
---
|
||||
|
||||
### Export
|
||||
|
||||
#### POST /export/pdf — PDF from draft data
|
||||
#### GET /export/pdf/{id} — PDF from saved quotation
|
||||
#### POST /export/excel — Excel from draft data
|
||||
#### GET /export/excel/{id} — Excel from saved quotation
|
||||
#### GET /export/catalogo — CSV of active services
|
||||
#### GET /export/catalogo/plantilla — CSV import template
|
||||
|
||||
---
|
||||
|
||||
### Import
|
||||
|
||||
#### POST /import/catalogo
|
||||
Bulk import services from CSV. `multipart/form-data` with `file` field.
|
||||
- **Response:** `{ "creados": 5, "omitidos": 2, "errores": [...] }`
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
### Quotation Number
|
||||
Format: `UJ{YY}{MM}{AsesorInitials}{sequence}` — e.g., `UJ2605AG001`
|
||||
|
||||
### Quotation Validity
|
||||
15 business days from issue (excludes Sat/Sun).
|
||||
|
||||
### CRM Bucefalo Plans
|
||||
basico=$1,000/mes, estandar=$3,500/mes, premium=$4,500/mes, empresarial=$7,500/mes
|
||||
|
||||
### Client Deduplication
|
||||
Matched by `(nombre, empresa)` pair.
|
||||
|
||||
### Service Soft-Delete
|
||||
If referenced by quotations → `activo=false`. Otherwise hard-delete.
|
||||
|
||||
### Financing Formula
|
||||
```
|
||||
comisionTotal = monto × comision%
|
||||
montoConComision = monto + comisionTotal
|
||||
pagoMensual = montoConComision × (1 + tasa) / meses
|
||||
ivaMensual = pagoMensual × 0.16
|
||||
totalMensual = pagoMensual + ivaMensual
|
||||
granTotal = totalMensual × meses
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Responses
|
||||
|
||||
### Success (paginated)
|
||||
```json
|
||||
{
|
||||
"data": [...],
|
||||
"meta": { "total": 45, "page": 1, "limit": 50, "pages": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
### Error
|
||||
```json
|
||||
{ "error": "Message", "detail": "Details", "code": "ERROR_CODE" }
|
||||
```
|
||||
|
||||
### HTTP Codes
|
||||
200=OK, 201=Created, 204=No Content, 400=Bad Request, 401=Unauthorized, 404=Not Found, 409=Conflict, 500=Server Error
|
||||
|
||||
---
|
||||
|
||||
## Agent Workflows
|
||||
|
||||
### Create quotation
|
||||
```
|
||||
1. GET /catalogo?fase=0 → audit services
|
||||
2. GET /catalogo?fase=1 → setup services
|
||||
3. GET /catalogo?fase=2&tipoPago=mensual → ongoing services
|
||||
4. POST /financiamiento/calcular → simulate payments
|
||||
5. POST /cotizaciones → create quotation
|
||||
6. GET /export/pdf/{id} → generate PDF
|
||||
```
|
||||
|
||||
### Review pipeline
|
||||
```
|
||||
1. GET /cotizaciones?estado=borrador → pending
|
||||
2. GET /cotizaciones?estado=enviada → awaiting
|
||||
3. GET /cotizaciones?estado=aprobada → won
|
||||
```
|
||||
|
||||
### Negotiate price
|
||||
```
|
||||
1. GET /cotizaciones/{id} → current state
|
||||
2. PATCH /cotizaciones/{id}/precio → adjust price
|
||||
3. GET /export/pdf/{id} → regenerate PDF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Integration — removed (2026-07-28)
|
||||
|
||||
The `/mcp` endpoint and the `api/app/mcp/` package no longer exist. Agents should use
|
||||
the REST endpoints documented above, authenticating with `X-API-Key` or a Bearer JWT.
|
||||
|
||||
It was removed for three reasons: nobody was using it; its transport had been broken
|
||||
for some time (it constructed a `StreamableHTTPServerTransport` per request with no
|
||||
session handling, returning 500 even with valid credentials); and its unpinned SDK
|
||||
took the entire API down in production when `mcp` released 2.0.0 and dropped
|
||||
`Server.list_tools()`.
|
||||
|
||||
To bring it back: `git show edb500f5:api/app/mcp/server.py`. Pin the SDK to the 1.x
|
||||
series and fix the transport before mounting it again.
|
||||
|
||||
---
|
||||
|
||||
## Environment
|
||||
|
||||
```
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_NAME=cotizador_e3
|
||||
API_KEY=your-secret-api-key
|
||||
JWT_SECRET=your-jwt-secret
|
||||
```
|
||||
|
||||
## Run
|
||||
## 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
|
||||
```
|
||||
|
||||
+294
-13
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -44,6 +44,7 @@ class ServicioCatalogoBase(BaseModel):
|
||||
categoriaId: str = Field(..., min_length=1, description="ID de la categoría")
|
||||
variante: str | None = None
|
||||
nivel: str | None = Field(None, description="Nivel/tier: Emprendedor, PYME, Empresario, Corporativo")
|
||||
soloAdmin: bool = Field(False, description="Visible solo para admin humano; oculto para agentes IA")
|
||||
orden: int = Field(0, ge=0)
|
||||
|
||||
|
||||
@@ -63,6 +64,7 @@ class ServicioCatalogoUpdate(BaseModel):
|
||||
variante: str | None = None
|
||||
nivel: str | None = None
|
||||
activo: bool | None = None
|
||||
soloAdmin: bool | None = None
|
||||
orden: int | None = Field(None, ge=0)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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"}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
@@ -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": "[email protected]",
|
||||
"telefono": "4421234567",
|
||||
},
|
||||
"servicios": [
|
||||
{
|
||||
"catalogoId": "cuid-servicio",
|
||||
"nombre": "SEO On-Page",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precio": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregables": ["Keyword research"],
|
||||
}
|
||||
],
|
||||
"planBucefalo": {"nivel": "basico", "precio": 1000},
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CotizacionUpdate(BaseModel):
|
||||
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
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.models.export_ import BonoResponse
|
||||
from app.services.calculators import BONOS
|
||||
|
||||
@@ -10,5 +10,5 @@ router = APIRouter(prefix="/bonos", tags=["Bonos"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[BonoResponse])
|
||||
async def get_bonos(_auth: dict = Depends(require_auth)):
|
||||
async def get_bonos(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [BonoResponse(**b) for b in BONOS]
|
||||
|
||||
@@ -5,7 +5,7 @@ import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import registrar_auditoria, require_scope, require_staff_human
|
||||
from app.dependencies import get_db
|
||||
from app.models.catalogo import (
|
||||
ServicioCatalogoCreate,
|
||||
@@ -49,6 +49,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
||||
variante=row["variante"],
|
||||
nivel=row["nivel"],
|
||||
activo=row["activo"],
|
||||
soloAdmin=bool(row.get("soloAdmin", False)),
|
||||
orden=row["orden"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
@@ -63,13 +64,15 @@ 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),
|
||||
q: str | None = Query(None, description="Search by nombre or descripcion"),
|
||||
):
|
||||
where_clauses: list[str] = ['activo = true']
|
||||
if auth.get("auth_type") == "agent":
|
||||
where_clauses.append('"soloAdmin" = false')
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
@@ -121,7 +124,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(
|
||||
@@ -135,8 +138,8 @@ async def create_catalogo(
|
||||
row = await db.fetchrow(
|
||||
'INSERT INTO "ServicioCatalogo" '
|
||||
'(nombre, descripcion, fase, "tipoPago", "precioBase", "tiempoEntrega", '
|
||||
'"entregablesDefault", "categoriaId", variante, nivel, activo, orden) '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11) RETURNING *",
|
||||
'"entregablesDefault", "categoriaId", variante, nivel, activo, "soloAdmin", orden) '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11, $12) RETURNING *",
|
||||
body.nombre,
|
||||
body.descripcion,
|
||||
body.fase,
|
||||
@@ -147,6 +150,7 @@ async def create_catalogo(
|
||||
body.categoriaId,
|
||||
body.variante,
|
||||
body.nivel,
|
||||
body.soloAdmin,
|
||||
body.orden,
|
||||
)
|
||||
|
||||
@@ -168,7 +172,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
|
||||
@@ -176,6 +180,21 @@ async def get_catalogo(
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||
|
||||
if auth.get("auth_type") == "agent" and row.get("soloAdmin"):
|
||||
await registrar_auditoria(
|
||||
db,
|
||||
auth,
|
||||
"catalogo.solo_admin_bloqueado",
|
||||
"catalogo",
|
||||
recurso_id=servicio_id,
|
||||
exito=False,
|
||||
detalle={"nombre": row["nombre"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Este servicio esta restringido solo al administrador y no esta disponible para agentes",
|
||||
)
|
||||
|
||||
cat_row = None
|
||||
if row["categoriaId"]:
|
||||
cat_row = await db.fetchrow(
|
||||
@@ -195,7 +214,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
|
||||
@@ -222,6 +241,7 @@ async def update_catalogo(
|
||||
"variante": "variante",
|
||||
"nivel": "nivel",
|
||||
"activo": "activo",
|
||||
"soloAdmin": '"soloAdmin"',
|
||||
"orden": "orden",
|
||||
}
|
||||
|
||||
@@ -265,7 +285,7 @@ async def update_catalogo(
|
||||
async def delete_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
|
||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
|
||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/categorias", tags=["Categorias"])
|
||||
|
||||
@router.get("", response_model=list[CategoriaResponse])
|
||||
async def list_categorias(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
@@ -33,7 +33,7 @@ async def list_categorias(
|
||||
)
|
||||
async def create_categoria(
|
||||
body: CategoriaCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -64,7 +64,7 @@ async def create_categoria(
|
||||
)
|
||||
async def get_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
@@ -93,7 +93,7 @@ async def get_categoria(
|
||||
async def update_categoria(
|
||||
categoria_id: str,
|
||||
body: CategoriaUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
@@ -166,7 +166,7 @@ async def update_categoria(
|
||||
)
|
||||
async def delete_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
|
||||
@@ -5,7 +5,7 @@ import math
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.dependencies import PaginationParams, get_db
|
||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
||||
@@ -20,11 +20,14 @@ 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"),
|
||||
incluirArchivados: bool = Query(False, description="Solo personal humano"),
|
||||
):
|
||||
where_clauses: list[str] = []
|
||||
if auth.get("auth_type") == "agent" or not incluirArchivados:
|
||||
where_clauses.append("archivado = false")
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
@@ -79,7 +82,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,14 +112,14 @@ 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:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
cotizaciones = await db.fetch(
|
||||
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 '
|
||||
'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 AND archivado = false '
|
||||
'ORDER BY "createdAt" DESC LIMIT 10',
|
||||
cliente_id,
|
||||
)
|
||||
@@ -146,7 +149,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 +195,7 @@ async def update_cliente(
|
||||
async def delete_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
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"],
|
||||
"vencidoNotificadoAt": r["vencidoNotificadoAt"].isoformat() if ("vencidoNotificadoAt" in r and r["vencidoNotificadoAt"]) else None,
|
||||
"nota": r["nota"],
|
||||
"programa": {
|
||||
"concepto": r["programa_concepto"],
|
||||
"moneda": r["programa_moneda"],
|
||||
"cliente": {
|
||||
"id": r["programa_cliente_id"],
|
||||
"nombre": r["cliente_nombre"],
|
||||
"empresa": r["cliente_empresa"],
|
||||
},
|
||||
},
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
@@ -6,14 +6,14 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/configuracion", tags=["Configuración"])
|
||||
|
||||
|
||||
@router.get("", response_model=ConfigResponse)
|
||||
async def get_configuracion(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch("SELECT clave, valor FROM Configuracion")
|
||||
@@ -24,7 +24,7 @@ async def get_configuracion(
|
||||
@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}})
|
||||
async def update_configuracion(
|
||||
body: ConfigUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
allowed = body.get_allowed()
|
||||
|
||||
+458
-99
@@ -1,12 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
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 +33,75 @@ 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."""
|
||||
_PATRON_BUCEFALO = re.compile(r"buc[eé]falo", re.IGNORECASE)
|
||||
|
||||
|
||||
async def _validar_solo_admin_agente(
|
||||
conn,
|
||||
auth: dict,
|
||||
servicios,
|
||||
plan_bucefalo,
|
||||
recurso_id: str | None = None,
|
||||
) -> None:
|
||||
"""Bloquea a agentes que intenten incluir servicios soloAdmin o planes de Bucéfalo CRM."""
|
||||
if auth.get("auth_type") != "agent":
|
||||
return
|
||||
|
||||
motivos: list[str] = []
|
||||
if plan_bucefalo is not None:
|
||||
motivos.append("planBucefalo")
|
||||
|
||||
servicios_lista = servicios or []
|
||||
catalogo_ids = [
|
||||
s.catalogoId
|
||||
for s in servicios_lista
|
||||
if getattr(s, "catalogoId", None)
|
||||
and not s.catalogoId.startswith("custom-")
|
||||
and not s.catalogoId.lower().startswith("bucefalo-")
|
||||
]
|
||||
|
||||
solo_admin_ids: set[str] = set()
|
||||
if catalogo_ids:
|
||||
rows = await conn.fetch(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = ANY($1::text[]) AND "soloAdmin" = true',
|
||||
catalogo_ids,
|
||||
)
|
||||
solo_admin_ids = {r["id"] for r in rows}
|
||||
|
||||
for s in servicios_lista:
|
||||
cid = (getattr(s, "catalogoId", "") or "").strip()
|
||||
nombre = (getattr(s, "nombre", "") or "").strip()
|
||||
if cid.lower().startswith("bucefalo-"):
|
||||
motivos.append(f"catalogoId:{cid}")
|
||||
elif cid in solo_admin_ids:
|
||||
motivos.append(f"soloAdmin:{cid}")
|
||||
elif _PATRON_BUCEFALO.search(nombre):
|
||||
motivos.append(f"nombre:{nombre}")
|
||||
|
||||
if motivos:
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.servicio_solo_admin_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=recurso_id,
|
||||
exito=False,
|
||||
detalle={"motivos": motivos},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los servicios restringidos al administrador (incluidos los planes de Bucefalo CRM) no pueden ser agregados por agentes",
|
||||
)
|
||||
|
||||
|
||||
async def _insert_servicio_cotizado(
|
||||
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 +112,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 +137,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 +146,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 +158,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 +166,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 +190,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 []
|
||||
|
||||
@@ -166,7 +235,7 @@ async def _resolve_bucefalo_servicio(conn) -> str | None:
|
||||
|
||||
async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, telefono: str) -> str:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id FROM "Cliente" WHERE nombre = $1 AND COALESCE(empresa, \'\') = $2',
|
||||
'SELECT id FROM "Cliente" WHERE archivado = false AND nombre = $1 AND COALESCE(empresa, \'\') = $2',
|
||||
nombre,
|
||||
empresa or "",
|
||||
)
|
||||
@@ -193,7 +262,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 +273,36 @@ async def list_cotizaciones(
|
||||
q: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
_auth: dict = Depends(require_auth),
|
||||
incluirArchivados: bool = Query(False),
|
||||
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] = []
|
||||
if auth.get("auth_type") == "agent" or not incluirArchivados:
|
||||
conditions.append("c.archivado = false")
|
||||
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 +314,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 +351,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 +360,30 @@ 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:
|
||||
await _validar_solo_admin_agente(conn, auth, body.servicios, body.planBucefalo)
|
||||
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 +398,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 +418,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 +446,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 +505,65 @@ 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",
|
||||
)
|
||||
await _validar_solo_admin_agente(
|
||||
conn,
|
||||
auth,
|
||||
body.servicios,
|
||||
body.planBucefalo,
|
||||
recurso_id=cotizacion_id,
|
||||
)
|
||||
|
||||
if body.estado is not None and body.estado != existing["estado"]:
|
||||
# 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 +579,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 +636,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 +663,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 +707,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 +746,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 +761,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 +889,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 +908,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 +919,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 +934,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 +990,14 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
now,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, new_id)
|
||||
return full
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.duplicar",
|
||||
"cotizacion",
|
||||
recurso_id=new_id,
|
||||
exito=True,
|
||||
detalle={"origenId": cotizacion_id, "numero": new_numero},
|
||||
)
|
||||
|
||||
return await _fetch_cotizacion_full(pool, new_id)
|
||||
|
||||
+20
-14
@@ -15,7 +15,7 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.export_ import ExportDraft
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import es_agente_solo_aceptadas, require_scope
|
||||
from app.services.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename
|
||||
from app.services.pdf_generator import generate_cotizacion_pdf
|
||||
from app.services.excel_generator import generate_cotizacion_excel
|
||||
@@ -86,13 +86,12 @@ def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) ->
|
||||
"planBucefaloNivel": draft.planBucefaloNivel,
|
||||
"planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0,
|
||||
"incluirBonos": draft.incluirBonos,
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -188,13 +187,12 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
"planBucefaloNivel": plan_nivel,
|
||||
"planBucefaloPrecio": float(plan["precio"]) if plan else 0,
|
||||
"incluirBonos": cot["incluirBonos"],
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -203,7 +201,7 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
@router.post("/pdf")
|
||||
async def export_pdf_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -223,9 +221,13 @@ async def export_pdf_draft(
|
||||
@router.get("/pdf/{cotizacion_id}")
|
||||
async def export_pdf_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
pdf_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not pdf_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -247,7 +249,7 @@ async def export_pdf_saved(
|
||||
@router.post("/excel")
|
||||
async def export_excel_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -267,9 +269,13 @@ async def export_excel_draft(
|
||||
@router.get("/excel/{cotizacion_id}")
|
||||
async def export_excel_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
excel_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not excel_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -290,7 +296,7 @@ async def export_excel_saved(
|
||||
|
||||
@router.get("/catalogo", response_class=PlainTextResponse)
|
||||
async def export_catalogo_csv(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch(
|
||||
|
||||
@@ -11,7 +11,7 @@ from app.models.export_ import (
|
||||
PlanBucefaloResponse,
|
||||
)
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.services.calculators import (
|
||||
calcular_financiamiento,
|
||||
FINANCIAMIENTO_PLANES,
|
||||
@@ -28,7 +28,7 @@ class PlanResponse(FinanciamientoResponse):
|
||||
|
||||
|
||||
@router.get("/planes", response_model=list[PlanResponse])
|
||||
async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
async def get_planes(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [
|
||||
PlanResponse(
|
||||
meses=p["meses"],
|
||||
@@ -47,7 +47,7 @@ async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
)
|
||||
async def calcular(
|
||||
body: FinanciamientoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
):
|
||||
plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None)
|
||||
if not plan:
|
||||
@@ -77,7 +77,7 @@ async def calcular(
|
||||
)
|
||||
async def simulacion(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
cot = await db.fetchrow(
|
||||
|
||||
@@ -28,9 +28,9 @@ async def health_check():
|
||||
@router.get("/api-info", response_model=APIInfoResponse)
|
||||
async def api_info():
|
||||
return APIInfoResponse(
|
||||
name="Cotizador E3 API",
|
||||
name="Cotizador — Uriel Jareth Consulting API",
|
||||
version="1.0.0",
|
||||
description="API para el sistema de cotizaciones de Consultoría E3",
|
||||
description="API para el sistema de cotizaciones de Uriel Jareth Consulting",
|
||||
capabilities=[
|
||||
"Gestión de cotizaciones",
|
||||
"Catálogo de servicios",
|
||||
|
||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/import", tags=["Import"])
|
||||
|
||||
@@ -17,7 +17,7 @@ REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"}
|
||||
@router.post("/catalogo")
|
||||
async def import_catalogo_csv(
|
||||
file: UploadFile = File(...),
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
content = await file.read()
|
||||
|
||||
+18
-13
@@ -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,
|
||||
@@ -19,7 +19,7 @@ from app.models.common import ErrorResponse, OkResponse
|
||||
router = APIRouter(prefix="/paquetes", tags=["Paquetes"])
|
||||
|
||||
|
||||
async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict]:
|
||||
async def _build_paquetes_responses(conn, paquete_rows: list[dict], excluir_solo_admin: bool = False) -> list[dict]:
|
||||
"""Build PaqueteResponse dicts for several paquetes with 2 queries in total
|
||||
(instead of 1 + N fases per paquete)."""
|
||||
if not paquete_rows:
|
||||
@@ -43,7 +43,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
' sc."precioBase" AS "sc_precioBase", sc."tiempoEntrega" AS "sc_tiempoEntrega",'
|
||||
' sc."entregablesDefault" AS "sc_entregablesDefault",'
|
||||
' sc."categoriaId" AS "sc_categoriaId", sc.variante AS "sc_variante",'
|
||||
' sc.activo AS "sc_activo", sc.orden AS "sc_orden",'
|
||||
' sc.activo AS "sc_activo", sc."soloAdmin" AS "sc_soloAdmin", sc.orden AS "sc_orden",'
|
||||
' sc."createdAt" AS "sc_createdAt", sc."updatedAt" AS "sc_updatedAt",'
|
||||
' cat.id AS "cat_id", cat.nombre AS "cat_nombre", cat.descripcion AS "cat_descripcion",'
|
||||
' cat.color AS "cat_color", cat.activo AS "cat_activo", cat.orden AS "cat_orden",'
|
||||
@@ -57,6 +57,8 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
|
||||
servicios_por_fase: dict[str, list[dict]] = {}
|
||||
for s in servicios_rows:
|
||||
if excluir_solo_admin and s.get("sc_soloAdmin"):
|
||||
continue
|
||||
cat = None
|
||||
if s["cat_id"]:
|
||||
cat = {
|
||||
@@ -87,6 +89,7 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
"categoriaId": s["sc_categoriaId"],
|
||||
"variante": s["sc_variante"],
|
||||
"activo": s["sc_activo"],
|
||||
"soloAdmin": bool(s.get("sc_soloAdmin", False)),
|
||||
"orden": s["sc_orden"],
|
||||
"createdAt": s["sc_createdAt"],
|
||||
"updatedAt": s["sc_updatedAt"],
|
||||
@@ -120,22 +123,23 @@ async def _build_paquetes_responses(conn, paquete_rows: list[dict]) -> list[dict
|
||||
]
|
||||
|
||||
|
||||
async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
||||
async def _build_paquete_response(conn, paquete_row: dict, excluir_solo_admin: bool = False) -> dict:
|
||||
"""Build a PaqueteResponse dict with nested fases and servicios."""
|
||||
results = await _build_paquetes_responses(conn, [paquete_row])
|
||||
results = await _build_paquetes_responses(conn, [paquete_row], excluir_solo_admin=excluir_solo_admin)
|
||||
return results[0]
|
||||
|
||||
|
||||
@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(
|
||||
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
||||
' FROM "Paquete" WHERE activo = true ORDER BY "createdAt" ASC'
|
||||
)
|
||||
return await _build_paquetes_responses(conn, [dict(row) for row in rows])
|
||||
excluir = _auth.get("auth_type") == "agent"
|
||||
return await _build_paquetes_responses(conn, [dict(row) for row in rows], excluir_solo_admin=excluir)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -145,7 +149,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 +183,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(
|
||||
@@ -192,7 +196,8 @@ async def get_paquete(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
return await _build_paquete_response(conn, dict(row))
|
||||
excluir = _auth.get("auth_type") == "agent"
|
||||
return await _build_paquete_response(conn, dict(row), excluir_solo_admin=excluir)
|
||||
|
||||
|
||||
@router.put(
|
||||
@@ -203,7 +208,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 +265,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 +286,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(
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
+8
-7
@@ -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",
|
||||
|
||||
+1450
File diff suppressed because it is too large
Load Diff
@@ -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,14 +50,15 @@ 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}
|
||||
- SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD}
|
||||
- SEED_ASESOR_NAME=${SEED_ASESOR_NAME}
|
||||
# URL publica: la usan los links de correo y de las notificaciones push.
|
||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
||||
# Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar).
|
||||
- APP_URL=${APP_URL}
|
||||
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
|
||||
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
|
||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||
@@ -67,9 +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:
|
||||
@@ -96,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
|
||||
|
||||
+15
-4
@@ -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,14 +50,15 @@ 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}
|
||||
- SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD}
|
||||
- SEED_ASESOR_NAME=${SEED_ASESOR_NAME}
|
||||
# URL publica: la usan los links de correo y de las notificaciones push.
|
||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
||||
# Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar).
|
||||
- APP_URL=${APP_URL}
|
||||
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
|
||||
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
|
||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||
@@ -67,9 +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:
|
||||
@@ -96,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
|
||||
|
||||
+3
-2
@@ -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"
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# CLI `cotizador`
|
||||
|
||||
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.
|
||||
|
||||
## Cómo ejecutarlo
|
||||
|
||||
```bash
|
||||
node cli/cotizador.mjs <comando> # desde la raíz del repo
|
||||
npm run cli -- <comando> # equivalente
|
||||
npm link && cotizador <comando> # instala el comando "cotizador" globalmente
|
||||
```
|
||||
|
||||
## Configuración
|
||||
|
||||
| Variable | Uso |
|
||||
|---|---|
|
||||
| `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-uj` |
|
||||
|
||||
`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 admin@urieljareth.com --password-stdin < pass.txt
|
||||
cotizador whoami
|
||||
```
|
||||
|
||||
## Convenciones (lo que una LLM necesita saber)
|
||||
|
||||
- **Salida**: JSON en stdout. `--campos id,nombre,precioBase` recorta campos (acepta rutas con punto: `planBucefalo.nivel`). `--formato tabla` es para humanos. `--compacto` deja el JSON en una línea.
|
||||
- **Errores**: JSON en stderr `{ ok:false, error, codigo, status?, detalles?, sugerencia? }`. `detalles` lista cada campo rechazado por el servidor. `sugerencia` dice qué ejecutar a continuación.
|
||||
- **Códigos de salida**: 0 ok · 1 error del servidor · 2 uso incorrecto · 3 sin sesión o sin permiso · 4 no encontrado · 5 validación · 6 duplicado · 7 sin conexión.
|
||||
- **Entrada**: flags `--kebab-case`. Para cuerpos completos, `--datos` acepta JSON en línea, `@archivo.json` o `-` (stdin). Las flags pisan lo que venga en `--datos`.
|
||||
- **Referencias**: donde se pide el id de un servicio también vale su nombre exacto. Las cotizaciones aceptan el número (`UJ2611AD001`). Las categorías, el id o el nombre.
|
||||
- **Escrituras seguras**: `--dry-run` muestra la petición sin enviarla. Borrar exige `--confirmar`. Una flag desconocida es error, no se ignora.
|
||||
- **Montos**: MXN sin IVA. El IVA (16 %) se calcula al cotizar.
|
||||
|
||||
## Servicios del catálogo
|
||||
|
||||
```bash
|
||||
cotizador servicios listar --fase 1 --campos id,nombre,precioBase # solo activos
|
||||
cotizador servicios listar --q "seo" --todos # incluye archivados
|
||||
cotizador servicios ver "Auditoria en Sitio Web"
|
||||
|
||||
cotizador servicios crear --nombre "Auditoria SEO tecnica" --fase 0 --tipo-pago unico \
|
||||
--precio 6500 --categoria SEO --entregable "Reporte PDF" --entregable "Sesion de 1 h"
|
||||
|
||||
cotizador servicios editar "Auditoria SEO tecnica" --precio 7200 # solo cambia el precio
|
||||
cotizador servicios editar <id> --agregar-entregable "Checklist" # agrega sin reemplazar
|
||||
cotizador servicios editar <id> --entregable "A" --entregable "B" # reemplaza la lista
|
||||
|
||||
cotizador servicios archivar <id> # lo oculta al cotizar; reversible con "servicios activar"
|
||||
cotizador servicios eliminar <id> --confirmar
|
||||
```
|
||||
|
||||
Obligatorios al crear: `--nombre`, `--fase` (0-3), `--tipo-pago` (`unico`|`mensual`), `--precio`. Sin `--orden`, el servicio queda al final de su fase.
|
||||
|
||||
**Editar** es parcial: solo cambia lo que pasas. Las cotizaciones ya guardadas conservan su precio, entregables y tiempo de entrega; el **nombre** sí cambia en ellas, porque se lee del catálogo.
|
||||
|
||||
**Eliminar** borra el servicio solo si ninguna cotización lo usa. Si alguna lo usa, el servidor lo archiva (`archived: true`) para no romperla.
|
||||
|
||||
## Cotizaciones
|
||||
|
||||
```bash
|
||||
cotizador cotizaciones crear --cliente "Ana Ruiz" --empresa "Panaderia Sol" \
|
||||
--servicio "Auditoria en Sitio Web" --servicio <id>=4500 \
|
||||
--partida-horas "Soporte tecnico|10|700" --bucefalo estandar
|
||||
|
||||
cotizador cotizaciones listar --estado enviada --formato tabla
|
||||
cotizador cotizaciones ver UJ2611AD001
|
||||
cotizador cotizaciones estado UJ2611AD001 enviada
|
||||
cotizador cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf
|
||||
cotizador cotizaciones excel UJ2611AD001
|
||||
```
|
||||
|
||||
Al crear, el servidor asigna el número (`UJ{AA}{MM}{iniciales}{consecutivo}`), el asesor (el usuario de la sesión), la fecha (hoy) y la vigencia (15 días hábiles). Si el cliente (nombre + empresa) no existe, se da de alta. `--servicio id=precio` ajusta el precio de esa partida sin tocar el catálogo. El precio del plan de Bucéfalo CRM sale de la lista de precios del servidor.
|
||||
|
||||
Para cotizaciones de doble propuesta, retainer o demanda, manda el cuerpo completo con `--datos` (el formato de cada partida está en `cotizador esquema` → `formatos.partidaCotizacion`). Las ediciones completas de una cotización existente se hacen en la web o con `cotizador api PUT /api/cotizaciones/<id> --datos @cuerpo.json`.
|
||||
|
||||
## Clientes, categorías, paquetes y horas
|
||||
|
||||
```bash
|
||||
cotizador clientes listar --q sol
|
||||
cotizador clientes crear --nombre "Ana Ruiz" --empresa "Panaderia Sol" --email ana@sol.mx
|
||||
cotizador clientes editar <id> --telefono "442 000 0000"
|
||||
|
||||
cotizador categorias listar
|
||||
cotizador categorias crear --nombre "Automatizacion" --color "#0ea5e9"
|
||||
cotizador paquetes listar
|
||||
|
||||
cotizador horas registrar UJ2611AD001 --fecha 2026-11-20 --inicio 09:00 --fin 11:30 --descripcion "Ajustes de campanas"
|
||||
cotizador horas listar UJ2611AD001 --desde 2026-11-01
|
||||
```
|
||||
|
||||
## Lo que no cubre un comando
|
||||
|
||||
`cotizador api <METODO> <ruta> [--datos ...]` llama cualquier endpoint de `src/app/api` con la sesión del CLI:
|
||||
|
||||
```bash
|
||||
cotizador api GET /api/configuracion
|
||||
cotizador api POST /api/cobros/recordatorios --datos '{}'
|
||||
```
|
||||
|
||||
En Git Bash, MSYS convierte `/api/...` en una ruta de Windows; el CLI lo corrige solo. También acepta `api/...` sin la barra.
|
||||
|
||||
## Agregar un comando
|
||||
|
||||
Cada comando es una entrada del arreglo `COMANDOS` en `cli/cotizador.mjs`, con `comando`, `descripcion`, `flags`, `ejemplos`, `endpoint` y `run`. La ayuda, la validación de flags y `cotizador esquema` salen de esa misma definición, así que no hay que documentarlo en otro lado. La lógica de negocio sigue en el servidor (`calculators.ts`, rutas de la API): el CLI solo arma peticiones.
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
- **Clave de partida:** `refPartida`, formato `P01`. El cuid de `ServicioCotizado` nunca sale hacia el proveedor.
|
||||
- **Evidencia:** arrays de IDs (`citas[]`, `hechos[]`), nunca prosa.
|
||||
- **Ratio precio/valor:** base `totalPrimerAnio` (único + mensual × 12, **con IVA**), calculado en código con `calcularTotalesCotizacion()`.
|
||||
- **Marca:** el CRM se llama **Bucéfalo**. E3 solo ofrece servicios digitales. MXN, IVA 16%, CFDI. Español de México, tuteo, sin lenguaje corporativo vacío.
|
||||
- **Marca:** el CRM se llama **Bucéfalo**. Uriel Jareth Consulting solo ofrece servicios digitales. MXN, IVA 16%, CFDI. Español de México, tuteo, sin lenguaje corporativo vacío.
|
||||
- **Nombres de empleados detectados:** se advierten en el reporte, no bloquean.
|
||||
- **Sin suite de pruebas en el repo.** La verificación es `npx tsc --noEmit` + `npm run lint` + un script de comprobación funcional por tarea (`npx tsx`). Cada tarea define el suyo.
|
||||
- **Dependencias del API Python fijadas a versión exacta.** No aplica a este plan (todo es TypeScript), pero si se toca `api/requirements.txt`, se fija.
|
||||
@@ -252,7 +252,7 @@ git commit -m "Propuesta IA: modelo PropuestaIA y capa de datos economicos"
|
||||
- Consumes: nada (solo `zod`).
|
||||
- Produces: `hechosSchema`, `diagnosticoSchema`, `redaccionSchema` (los tres `z.ZodType`), los tipos `Hechos`, `Diagnostico`, `PropuestaConsultiva`, y `function aJsonSchema(schema: z.ZodType): Record<string, unknown>`.
|
||||
|
||||
Nota crítica: **ningún schema contiene un campo de dinero de la cotización.** `montoAnualMXN` sí existe, pero es el costo del *problema del cliente* que la IA estima desde la transcripción — no un precio de E3.
|
||||
Nota crítica: **ningún schema contiene un campo de dinero de la cotización.** `montoAnualMXN` sí existe, pero es el costo del *problema del cliente* que la IA estima desde la transcripción — no un precio de Uriel Jareth Consulting.
|
||||
|
||||
- [ ] **Step 1: Escribir los schemas**
|
||||
|
||||
@@ -310,7 +310,7 @@ export const diagnosticoSchema = z.object({
|
||||
descripcion: z.string(),
|
||||
calculo: z.object({
|
||||
factores: z.array(z.object({ nombre: z.string(), valor: z.number() })).min(2),
|
||||
montoAnualMXN: z.number().nullable().describe("Costo ANUAL del problema del CLIENTE. No es un precio de E3."),
|
||||
montoAnualMXN: z.number().nullable().describe("Costo ANUAL del problema del CLIENTE. No es un precio de Uriel Jareth Consulting."),
|
||||
}),
|
||||
confianza: z.enum(CONFIANZA),
|
||||
hechos: z.array(z.string().regex(ID_HECHO)),
|
||||
@@ -657,17 +657,17 @@ export const SYSTEM_BASE = `
|
||||
# QUIEN ERES
|
||||
|
||||
Consultor senior de digitalizacion de negocios para PyMEs mexicanas. Redactas la parte
|
||||
narrativa de las propuestas de Consultoria E3 (Queretaro, MX). No eres vendedor: eres
|
||||
narrativa de las propuestas de Uriel Jareth Consulting. No eres vendedor: eres
|
||||
diagnosticador. Tu trabajo es explicar por que la inversion tiene sentido, nunca decidir
|
||||
cuanto cuesta.
|
||||
|
||||
# LOS PRINCIPIOS QUE NO SE NEGOCIAN
|
||||
|
||||
P1. NO TOCAS LOS NUMEROS. No calculas, propones ni mencionas precios, totales, IVA ni
|
||||
descuentos de E3. Ni siquiera los ves. Si necesitas referirte a una partida, usa su
|
||||
descuentos de Uriel Jareth Consulting. Ni siquiera los ves. Si necesitas referirte a una partida, usa su
|
||||
refPartida (P01, P02...). El sistema inyecta los importes despues.
|
||||
Si escribes una cifra en pesos, solo puede ser el costo del problema DEL CLIENTE
|
||||
(lo que le cuesta hoy no resolverlo), nunca un precio de E3.
|
||||
(lo que le cuesta hoy no resolverlo), nunca un precio de Uriel Jareth Consulting.
|
||||
|
||||
P2. TODA AFIRMACION ES TRAZABLE. Cada cosa que digas sobre el cliente apunta a una cita
|
||||
(C01...) o a un hecho (H01...). Si no tiene origen, no se escribe.
|
||||
@@ -709,8 +709,8 @@ P8. NO PROPONES SERVICIOS QUE EL ASESOR NO ELIGIO. Si detectas una necesidad que
|
||||
- Prohibido el lenguaje corporativo vacio: sinergias, holistico, stakeholders, ecosistema,
|
||||
disruptivo, robusto, potenciar, empoderar.
|
||||
- El CRM se llama Bucefalo. No menciones ningun otro CRM, por ningun motivo.
|
||||
- E3 ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing tradicional
|
||||
o diseno para imprenta, va a exclusiones aclarando que no es un servicio de E3.
|
||||
- Uriel Jareth Consulting ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing tradicional
|
||||
o diseno para imprenta, va a exclusiones aclarando que no es un servicio de Uriel Jareth Consulting.
|
||||
- Moneda MXN, IVA 16%, facturacion CFDI. Jamas montos en USD.
|
||||
- No prometas resultados garantizados de mercado: ni ventas, ni posicion #1 en Google, ni
|
||||
numero de leads. Prometes entregables, procesos y metricas de seguimiento. La palabra
|
||||
@@ -795,7 +795,7 @@ Reglas del paso:
|
||||
debe cuadrar: montoAnualMXN tiene que ser el producto o la suma de los factores.
|
||||
Si no tienes cifras, deja montoAnualMXN en null y marca por_validar.
|
||||
- Recuerda P1: montoAnualMXN es lo que el problema le cuesta AL CLIENTE cada ano. No es un
|
||||
precio de E3.`;
|
||||
precio de Uriel Jareth Consulting.`;
|
||||
}
|
||||
|
||||
export function mensajePaso3(
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
+7
-2
@@ -1,7 +1,10 @@
|
||||
{
|
||||
"name": "cotizador-e3",
|
||||
"name": "cotizador-uj",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"cotizador": "cli/cotizador.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
@@ -10,7 +13,9 @@
|
||||
"db:migrate": "npx prisma migrate dev",
|
||||
"db:seed": "npx tsx prisma/seed.ts",
|
||||
"db:studio": "npx prisma studio",
|
||||
"db:generate": "npx prisma generate"
|
||||
"db:generate": "npx prisma generate",
|
||||
"cli": "node cli/cotizador.mjs",
|
||||
"test": "node --import tsx --test tests/*.test.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "npx tsx prisma/seed.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}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "ultimoRecordatorioAt" TIMESTAMP(3);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Cliente" ADD COLUMN "puesto" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN "nota" TEXT;
|
||||
@@ -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 $$;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Migracion aditiva: soloAdmin en ServicioCatalogo (oculto para bots) y archivo reversible en Cliente y Cotizacion
|
||||
|
||||
ALTER TABLE "ServicioCatalogo"
|
||||
ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- Marcar planes/servicios de Bucefalo CRM como soloAdmin = true (visibles solo en web admin, ocultos a agentes)
|
||||
UPDATE "ServicioCatalogo"
|
||||
SET "soloAdmin" = true
|
||||
WHERE id IN ('configuracion-y-puesta-en-marc-12', 'plan-mensual-crm-bucefalo-18')
|
||||
OR LOWER(nombre) LIKE '%bucefalo%'
|
||||
OR LOWER(nombre) LIKE '%bucéfalo%';
|
||||
|
||||
ALTER TABLE "Cliente"
|
||||
ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado");
|
||||
|
||||
ALTER TABLE "Cotizacion"
|
||||
ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado");
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Additive idempotency stamp for pago.vencido webhook emission
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3);
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt");
|
||||
+146
-12
@@ -25,14 +25,18 @@ model User {
|
||||
}
|
||||
|
||||
model Cliente {
|
||||
id String @id @default(cuid())
|
||||
nombre String
|
||||
empresa String?
|
||||
email String?
|
||||
telefono String?
|
||||
rfc String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
id String @id @default(cuid())
|
||||
nombre String
|
||||
empresa String?
|
||||
// Cargo de la persona de contacto (ej. "Director"). Solo informativo.
|
||||
puesto String?
|
||||
email String?
|
||||
telefono String?
|
||||
rfc String?
|
||||
archivado Boolean @default(false)
|
||||
archivadoAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
cotizaciones Cotizacion[]
|
||||
// Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente.
|
||||
@@ -40,6 +44,7 @@ model Cliente {
|
||||
programasPago ProgramaPago[]
|
||||
|
||||
@@index([nombre, empresa])
|
||||
@@index([archivado])
|
||||
}
|
||||
|
||||
model Cotizacion {
|
||||
@@ -66,8 +71,21 @@ model Cotizacion {
|
||||
observacionesInternas String?
|
||||
clienteId String
|
||||
asesorId String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
aprobadaPorId String?
|
||||
aprobadaAt DateTime?
|
||||
aprobacionMetodo String?
|
||||
enviadaAt DateTime?
|
||||
enviadaPor String?
|
||||
enviadaCanal String?
|
||||
enviadaDestino String?
|
||||
aceptadaAt DateTime?
|
||||
rechazadaAt DateTime?
|
||||
vencidaAt DateTime?
|
||||
creadaPorAgente String?
|
||||
archivado Boolean @default(false)
|
||||
archivadoAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
cliente Cliente @relation(fields: [clienteId], references: [id])
|
||||
asesor User @relation("AsesorCotizaciones", fields: [asesorId], references: [id])
|
||||
@@ -76,10 +94,12 @@ model Cotizacion {
|
||||
registrosHoras RegistroHoras[]
|
||||
propuestasIA PropuestaIA[]
|
||||
programasPago ProgramaPago[]
|
||||
approvalTokens ApprovalToken[]
|
||||
|
||||
@@index([clienteId])
|
||||
@@index([asesorId])
|
||||
@@index([estado])
|
||||
@@index([archivado])
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
@@ -134,6 +154,9 @@ model ServicioCatalogo {
|
||||
variante String?
|
||||
nivel String?
|
||||
activo Boolean @default(true)
|
||||
// Si es true, queda oculto para todas las claves de agentes/bots y solo puede
|
||||
// agregarlo un administrador humano desde la web (p. ej. planes de Bucefalo CRM).
|
||||
soloAdmin Boolean @default(false)
|
||||
orden Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -315,8 +338,9 @@ model ProgramaPago {
|
||||
|
||||
// Un cobro generado para un periodo concreto (ej. sabado 2026-07-04).
|
||||
// estados: pendiente (sin comprobante) | en_revision (comprobante subido,
|
||||
// esperando admin) | verificado (admin aprobo) | rechazado (admin rechazo y
|
||||
// borro el archivo; el cliente puede volver a subir).
|
||||
// esperando admin) | verificado (admin aprobo, o registro el pago a mano) |
|
||||
// rechazado (admin rechazo y borro el archivo; el cliente puede volver a subir) |
|
||||
// anulado (el admin lo dejo sin cargo; no cuenta como adeudo).
|
||||
model PagoRecurrente {
|
||||
id String @id @default(cuid())
|
||||
programaId String
|
||||
@@ -328,6 +352,17 @@ model PagoRecurrente {
|
||||
verificadoAt DateTime?
|
||||
rechazadoAt DateTime?
|
||||
rechazoMotivo String?
|
||||
// Ultimo recordatorio de pago enviado al cliente mientras el cobro sigue
|
||||
// por pagar (pendiente/rechazado). El scheduler lo usa para no repetir el
|
||||
// aviso antes de COBROS_RECORDATORIO_DIAS; el envio manual lo ignora.
|
||||
ultimoRecordatorioAt DateTime?
|
||||
recordatoriosEnviados Int @default(0)
|
||||
// Sello idempotente para el webhook pago.vencido: se escribe atomicamente la
|
||||
// primera vez que el cobro se notifica como vencido (1 evento por cobro).
|
||||
vencidoNotificadoAt DateTime?
|
||||
// Nota interna del admin (no la ve el cliente): forma de pago o abonos al
|
||||
// registrar un pago manual, o el motivo al anular un cobro.
|
||||
nota String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -337,6 +372,7 @@ model PagoRecurrente {
|
||||
@@unique([programaId, fecha])
|
||||
@@index([estado])
|
||||
@@index([fecha])
|
||||
@@index([vencidoNotificadoAt])
|
||||
}
|
||||
|
||||
// Comprobante de pago subido por el cliente (imagen o PDF). El archivo vive en
|
||||
@@ -369,3 +405,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])
|
||||
}
|
||||
|
||||
+10
-7
@@ -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(
|
||||
@@ -361,6 +362,7 @@ async function main() {
|
||||
{
|
||||
nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo",
|
||||
descripcion: "Configuracion inicial de cuenta CRM Bucefalo",
|
||||
soloAdmin: true,
|
||||
fase: 1,
|
||||
tipoPago: "unico",
|
||||
precioBase: 3900,
|
||||
@@ -469,6 +471,7 @@ async function main() {
|
||||
{
|
||||
nombre: "Plan Mensual CRM Bucefalo",
|
||||
descripcion: "Suscripcion mensual al CRM Bucefalo",
|
||||
soloAdmin: true,
|
||||
fase: 2,
|
||||
tipoPago: "mensual",
|
||||
precioBase: 3900,
|
||||
@@ -567,7 +570,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 +588,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 +1969,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 +2005,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 +2013,11 @@ async function main() {
|
||||
},
|
||||
{
|
||||
clave: "color_primario",
|
||||
valor: "#2563eb",
|
||||
valor: "#0400C4",
|
||||
},
|
||||
{
|
||||
clave: "color_secundario",
|
||||
valor: "#1e293b",
|
||||
valor: "#0F172A",
|
||||
},
|
||||
{
|
||||
clave: "logo_base64",
|
||||
|
||||
+1
-1
@@ -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(
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* Provisioning CLI de claves de agente (AgentApiKey) para Uriel Jareth Consulting.
|
||||
*
|
||||
* Uso dentro del contenedor web o en local con variables DB_* cargadas:
|
||||
* npx tsx scripts/provision-agent-keys.ts --list
|
||||
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --scopes catalogo:leer,clientes:leer,clientes:escribir,cotizaciones:leer,cotizaciones:borrador,cotizaciones:enviar --rate-limit 60
|
||||
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate
|
||||
* npx tsx scripts/provision-agent-keys.ts --preset [--rotate]
|
||||
*
|
||||
* Imprime JSON limpio en stdout para que un operador/orquestador guarde las
|
||||
* claves directamente en accesos/cotizador.env sin exponerlas en logs.
|
||||
*/
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { PrismaClient } from "../src/generated/prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
|
||||
const VALID_SCOPES = new Set([
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
"cobros:registrar",
|
||||
]);
|
||||
|
||||
const PRESETS: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [
|
||||
{
|
||||
nombre: "sales-agent",
|
||||
scopes: [
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
],
|
||||
rateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
nombre: "jefe-operaciones",
|
||||
scopes: [
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cobros:leer",
|
||||
],
|
||||
rateLimitPerMin: 120,
|
||||
},
|
||||
{
|
||||
nombre: "cobranza",
|
||||
scopes: [
|
||||
"clientes:leer",
|
||||
"cobros:leer",
|
||||
],
|
||||
rateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
nombre: "entrega",
|
||||
scopes: [
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
],
|
||||
rateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
nombre: "n8n-ecosystem",
|
||||
scopes: [
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
],
|
||||
rateLimitPerMin: 180,
|
||||
},
|
||||
];
|
||||
|
||||
function generateKey() {
|
||||
const rawKey = `ujc_live_${randomBytes(32).toString("hex")}`;
|
||||
const prefijo = rawKey.slice(0, 14);
|
||||
const keyHash = createHash("sha256").update(rawKey, "utf8").digest("hex");
|
||||
return { rawKey, prefijo, keyHash };
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]) {
|
||||
const args: Record<string, string | boolean> = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const token = argv[i];
|
||||
if (!token.startsWith("--")) continue;
|
||||
const key = token.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (!next || next.startsWith("--")) {
|
||||
args[key] = true;
|
||||
} else {
|
||||
args[key] = next;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
|
||||
const adapter = new PrismaPg({
|
||||
host: process.env.DB_HOST || "localhost",
|
||||
port: parseInt(process.env.DB_PORT || "5432", 10),
|
||||
user: process.env.DB_USER || "postgres",
|
||||
password: process.env.DB_PASSWORD || "postgres",
|
||||
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
||||
});
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
try {
|
||||
if (args.list) {
|
||||
const keys = await prisma.agentApiKey.findMany({
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
prefijo: true,
|
||||
scopes: true,
|
||||
rateLimitPerMin: true,
|
||||
activo: true,
|
||||
revokedAt: true,
|
||||
lastUsedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, keys }, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
const targets: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [];
|
||||
|
||||
if (args.preset) {
|
||||
targets.push(...PRESETS);
|
||||
} else if (typeof args.nombre === "string" && args.nombre.trim()) {
|
||||
const nombre = args.nombre.trim();
|
||||
const rawScopes =
|
||||
typeof args.scopes === "string"
|
||||
? args.scopes
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const rateLimitPerMin =
|
||||
typeof args["rate-limit"] === "string" ? parseInt(args["rate-limit"], 10) || 60 : 60;
|
||||
|
||||
for (const sc of rawScopes) {
|
||||
if (!VALID_SCOPES.has(sc)) {
|
||||
throw new Error(`Scope invalido: "${sc}". Validos: ${Array.from(VALID_SCOPES).join(", ")}`);
|
||||
}
|
||||
}
|
||||
targets.push({ nombre, scopes: rawScopes, rateLimitPerMin });
|
||||
} else {
|
||||
console.error(
|
||||
"Uso: npx tsx scripts/provision-agent-keys.ts --list | --preset [--rotate] | --nombre <nombre> --scopes <a,b> [--rate-limit 60] [--rotate]"
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const rotate = Boolean(args.rotate);
|
||||
const results: Array<Record<string, unknown>> = [];
|
||||
|
||||
for (const target of targets) {
|
||||
const existing = await prisma.agentApiKey.findUnique({
|
||||
where: { nombre: target.nombre },
|
||||
});
|
||||
|
||||
if (existing && !rotate) {
|
||||
results.push({
|
||||
nombre: existing.nombre,
|
||||
action: "exists",
|
||||
id: existing.id,
|
||||
prefijo: existing.prefijo,
|
||||
scopes: existing.scopes,
|
||||
rateLimitPerMin: existing.rateLimitPerMin,
|
||||
activo: existing.activo,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const scopesFinal =
|
||||
target.scopes.length > 0 ? Array.from(new Set(target.scopes)) : existing?.scopes ?? [];
|
||||
if (scopesFinal.length === 0) {
|
||||
throw new Error(`Debes indicar --scopes al crear la clave "${target.nombre}"`);
|
||||
}
|
||||
|
||||
const { rawKey, prefijo, keyHash } = generateKey();
|
||||
|
||||
if (existing) {
|
||||
const updated = await prisma.agentApiKey.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
prefijo,
|
||||
keyHash,
|
||||
scopes: scopesFinal,
|
||||
rateLimitPerMin: target.rateLimitPerMin || existing.rateLimitPerMin,
|
||||
activo: true,
|
||||
revokedAt: null,
|
||||
},
|
||||
});
|
||||
results.push({
|
||||
nombre: updated.nombre,
|
||||
action: "rotated",
|
||||
id: updated.id,
|
||||
prefijo: updated.prefijo,
|
||||
scopes: updated.scopes,
|
||||
rateLimitPerMin: updated.rateLimitPerMin,
|
||||
rawKey,
|
||||
});
|
||||
} else {
|
||||
const created = await prisma.agentApiKey.create({
|
||||
data: {
|
||||
nombre: target.nombre,
|
||||
prefijo,
|
||||
keyHash,
|
||||
scopes: scopesFinal,
|
||||
rateLimitPerMin: target.rateLimitPerMin,
|
||||
activo: true,
|
||||
},
|
||||
});
|
||||
results.push({
|
||||
nombre: created.nombre,
|
||||
action: "created",
|
||||
id: created.id,
|
||||
prefijo: created.prefijo,
|
||||
scopes: created.scopes,
|
||||
rateLimitPerMin: created.rateLimitPerMin,
|
||||
rawKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ ok: true, results }, null, 2));
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) }));
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -102,7 +102,7 @@ const datos: DatosPropuestaPDF = {
|
||||
fecha: new Date("2026-07-29"),
|
||||
vigencia: new Date("2026-08-19"),
|
||||
proyecto: "MKT Digital",
|
||||
branding: { colorPrimario: "#2563eb" },
|
||||
branding: { colorPrimario: "#0400C4" },
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -12,12 +12,12 @@ import {
|
||||
Package,
|
||||
LayoutGrid,
|
||||
Settings,
|
||||
Save,
|
||||
FileDown,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { formatCurrency, FASES as FASES_LABELS } from "@/lib/calculators";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { ServicioFormModal } from "@/components/ServicioFormModal";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Servicio {
|
||||
@@ -35,6 +35,7 @@ interface Servicio {
|
||||
variante: string | null;
|
||||
nivel: string | null;
|
||||
activo: boolean;
|
||||
soloAdmin?: boolean;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
@@ -69,8 +70,6 @@ interface Props {
|
||||
|
||||
type Tab = "categorias" | "paquetes" | "servicios";
|
||||
|
||||
const FASES = FASES_LABELS;
|
||||
|
||||
export function CatalogoClient({ initialServicios, initialCategorias, initialPaquetes }: Props) {
|
||||
const showConfirm = useConfirm();
|
||||
const showPrompt = usePrompt();
|
||||
@@ -352,6 +351,14 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
|
||||
<div className="font-medium flex flex-wrap items-center gap-2 min-w-0">
|
||||
<span className="break-words">{s.nombre}</span>
|
||||
{s.nivel && <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">{s.nivel}</span>}
|
||||
{s.soloAdmin && (
|
||||
<span
|
||||
className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-slate-200 text-slate-700"
|
||||
title="Visible solo para Jareth en la web; oculto para bots y agentes IA"
|
||||
>
|
||||
Solo admin
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{s.descripcion && <div className="text-xs text-muted mt-0.5 break-words">{s.descripcion}</div>}
|
||||
</td>
|
||||
@@ -519,28 +526,13 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
|
||||
<ServicioFormModal
|
||||
servicio={servicioModal}
|
||||
categorias={categorias}
|
||||
onSave={async (data) => {
|
||||
onSaved={(guardado) => {
|
||||
if (servicioModal) {
|
||||
const res = await fetch(`/api/catalogo/${servicioModal.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
setServicios((p) => p.map((s) => (s.id === servicioModal.id ? { ...s, ...updated, categoriaNombre: categorias.find((c) => c.id === data.categoriaId)?.nombre || s.categoriaNombre, categoriaColor: categorias.find((c) => c.id === data.categoriaId)?.color || s.categoriaColor } : s)));
|
||||
}
|
||||
setServicios((p) => p.map((s) => (s.id === guardado.id ? { ...s, ...guardado } : s)));
|
||||
showToast("Servicio actualizado", "success");
|
||||
} else {
|
||||
const res = await fetch("/api/catalogo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const created = await res.json();
|
||||
const cat = categorias.find((c) => c.id === data.categoriaId);
|
||||
setServicios((p) => [...p, { ...created, categoriaNombre: cat?.nombre || "Sin categoria", categoriaColor: cat?.color || "#6b7280" }]);
|
||||
}
|
||||
setServicios((p) => [...p, guardado]);
|
||||
showToast("Servicio creado", "success");
|
||||
}
|
||||
setServicioModal(null);
|
||||
setShowNewServicio(false);
|
||||
@@ -645,148 +637,3 @@ function AddServicioModal({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ServicioFormModal({
|
||||
servicio,
|
||||
categorias,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
servicio: Servicio | null;
|
||||
categorias: Categoria[];
|
||||
onSave: (data: Record<string, unknown>) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [form, setForm] = useState({
|
||||
nombre: servicio?.nombre || "",
|
||||
descripcion: servicio?.descripcion || "",
|
||||
categoriaId: servicio?.categoriaId || "",
|
||||
tipoPago: servicio?.tipoPago || "unico",
|
||||
precioBase: servicio?.precioBase ?? 0,
|
||||
tiempoEntrega: servicio?.tiempoEntrega || "4 - 10 dias",
|
||||
entregablesDefault: servicio?.entregablesDefault?.join("\n") || "",
|
||||
variante: servicio?.variante || "",
|
||||
nivel: servicio?.nivel || "",
|
||||
fase: servicio?.fase ?? 1,
|
||||
orden: servicio?.orden ?? 0,
|
||||
activo: servicio?.activo ?? true,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.nombre.trim()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const entregables = form.entregablesDefault
|
||||
.split("\n")
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
await onSave({
|
||||
nombre: form.nombre.trim(),
|
||||
descripcion: form.descripcion.trim() || null,
|
||||
categoriaId: form.categoriaId || null,
|
||||
tipoPago: form.tipoPago,
|
||||
precioBase: Number(form.precioBase),
|
||||
tiempoEntrega: form.tiempoEntrega,
|
||||
entregablesDefault: entregables,
|
||||
variante: form.variante.trim() || null,
|
||||
nivel: form.nivel.trim() || null,
|
||||
fase: form.fase,
|
||||
orden: form.orden,
|
||||
activo: form.activo,
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const update = (key: string, value: unknown) => setForm((p) => ({ ...p, [key]: value }));
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h3 className="font-semibold">{servicio ? "Editar Servicio" : "Nuevo Servicio"}</h3>
|
||||
<button onClick={onClose}><X className="w-5 h-5 text-muted" /></button>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1 p-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nombre *</label>
|
||||
<input type="text" value={form.nombre} onChange={(e) => update("nombre", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Descripcion</label>
|
||||
<textarea value={form.descripcion} onChange={(e) => update("descripcion", e.target.value)} rows={2} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Categoria</label>
|
||||
<select value={form.categoriaId} onChange={(e) => update("categoriaId", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
<option value="">Sin categoria</option>
|
||||
{categorias.map((c) => <option key={c.id} value={c.id}>{c.nombre}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tipo de Pago</label>
|
||||
<select value={form.tipoPago} onChange={(e) => update("tipoPago", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
<option value="unico">Unico</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Precio Base</label>
|
||||
<input type="number" value={form.precioBase} onChange={(e) => update("precioBase", Number(e.target.value))} min={0} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Fase</label>
|
||||
<select value={form.fase} onChange={(e) => update("fase", Number(e.target.value))} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
{Object.entries(FASES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tiempo Entrega</label>
|
||||
<input type="text" value={form.tiempoEntrega} onChange={(e) => update("tiempoEntrega", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Entregables (uno por linea)</label>
|
||||
<textarea value={form.entregablesDefault} onChange={(e) => update("entregablesDefault", e.target.value)} rows={4} placeholder="Entregable 1 Entregable 2 ..." className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none font-mono text-xs" />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nivel</label>
|
||||
<select value={form.nivel} onChange={(e) => update("nivel", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
<option value="">Sin nivel</option>
|
||||
<option value="Emprendedor">Emprendedor</option>
|
||||
<option value="PYME">PYME</option>
|
||||
<option value="Empresario">Empresario</option>
|
||||
<option value="Corporativo">Corporativo</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Variante</label>
|
||||
<input type="text" value={form.variante} onChange={(e) => update("variante", e.target.value)} placeholder="Ej: WooCommerce, Shopify..." className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Orden</label>
|
||||
<input type="number" value={form.orden} onChange={(e) => update("orden", Number(e.target.value))} min={0} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={form.activo} onChange={(e) => update("activo", e.target.checked)} className="rounded border-border" />
|
||||
Activo
|
||||
</label>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-3">
|
||||
<button onClick={onClose} className="px-4 py-2 border border-border rounded-lg text-sm hover:bg-gray-50">Cancelar</button>
|
||||
<button onClick={handleSave} disabled={saving || !form.nombre.trim()} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium disabled:opacity-50 hover:bg-primary-dark">
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{servicio ? "Guardar Cambios" : "Crear Servicio"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ export default async function CatalogoPage() {
|
||||
variante: s.variante,
|
||||
nivel: s.nivel,
|
||||
activo: s.activo,
|
||||
soloAdmin: s.soloAdmin,
|
||||
orden: s.orden,
|
||||
}))}
|
||||
initialCategorias={categorias}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
|
||||
export type ClienteEditable = {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
puesto: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
rfc: string | null;
|
||||
};
|
||||
|
||||
type Form = Record<"nombre" | "empresa" | "puesto" | "email" | "telefono" | "rfc", string>;
|
||||
|
||||
const CAMPOS: {
|
||||
clave: keyof Form;
|
||||
etiqueta: string;
|
||||
tipo?: string;
|
||||
placeholder?: string;
|
||||
autoComplete?: string;
|
||||
ancho?: boolean;
|
||||
}[] = [
|
||||
{ clave: "nombre", etiqueta: "Nombre del contacto *", placeholder: "Nombre y apellidos", autoComplete: "off", ancho: true },
|
||||
{ clave: "puesto", etiqueta: "Puesto", placeholder: "Ej. Director", autoComplete: "off" },
|
||||
{ clave: "empresa", etiqueta: "Empresa", placeholder: "Razón o nombre comercial", autoComplete: "off" },
|
||||
{ clave: "email", etiqueta: "Correo", tipo: "email", placeholder: "[email protected]", autoComplete: "off" },
|
||||
{ clave: "telefono", etiqueta: "Teléfono", tipo: "tel", placeholder: "+52 442 123 4567", autoComplete: "off" },
|
||||
{ clave: "rfc", etiqueta: "RFC", placeholder: "Opcional", autoComplete: "off" },
|
||||
];
|
||||
|
||||
// Alta o edicion de un cliente sin pasar por una cotizacion. Las cotizaciones
|
||||
// reconocen al cliente por nombre + empresa, asi que la API rechaza duplicados.
|
||||
export function ClienteDialog({
|
||||
cliente,
|
||||
onClose,
|
||||
onGuardado,
|
||||
}: {
|
||||
// null = alta de un cliente nuevo.
|
||||
cliente: ClienteEditable | null;
|
||||
onClose: () => void;
|
||||
onGuardado: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const [form, setForm] = useState<Form>({
|
||||
nombre: cliente?.nombre ?? "",
|
||||
empresa: cliente?.empresa ?? "",
|
||||
puesto: cliente?.puesto ?? "",
|
||||
email: cliente?.email ?? "",
|
||||
telefono: cliente?.telefono ?? "",
|
||||
rfc: cliente?.rfc ?? "",
|
||||
});
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const guardar = async () => {
|
||||
if (!form.nombre.trim()) {
|
||||
toast("El nombre es requerido", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
try {
|
||||
const res = await fetch(cliente ? `/api/clientes/${cliente.id}` : "/api/clientes", {
|
||||
method: cliente ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al guardar el cliente", "error");
|
||||
return;
|
||||
}
|
||||
toast(cliente ? "Cliente actualizado" : `${data.nombre} quedó registrado`, "success");
|
||||
onGuardado();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
titulo={cliente ? `Editar a ${cliente.nombre}` : "Nuevo cliente"}
|
||||
descripcion={
|
||||
cliente
|
||||
? undefined
|
||||
: "Regístralo para programarle cobros o tenerlo listo para su próxima cotización."
|
||||
}
|
||||
onClose={onClose}
|
||||
onSubmit={guardar}
|
||||
ancho="max-w-lg"
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={onClose} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : cliente ? "Guardar cambios" : "Agregar cliente"}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{CAMPOS.map((c) => (
|
||||
<div key={c.clave} className={c.ancho ? "sm:col-span-2" : undefined}>
|
||||
<label htmlFor={`cliente-${c.clave}`} className={claseEtiqueta}>
|
||||
{c.etiqueta}
|
||||
</label>
|
||||
<input
|
||||
id={`cliente-${c.clave}`}
|
||||
type={c.tipo ?? "text"}
|
||||
value={form[c.clave]}
|
||||
required={c.clave === "nombre"}
|
||||
autoComplete={c.autoComplete}
|
||||
placeholder={c.placeholder}
|
||||
onChange={(e) => setForm((f) => ({ ...f, [c.clave]: e.target.value }))}
|
||||
className={`${claseCampo}${c.clave === "rfc" ? " uppercase placeholder:normal-case" : ""}`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,19 @@
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { KeyRound, Search, Trash2 } from "lucide-react";
|
||||
import { KeyRound, Pencil, Search, Trash2, UserPlus, Users } from "lucide-react";
|
||||
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton";
|
||||
import { ClienteDialog, type ClienteEditable } from "./ClienteDialog";
|
||||
|
||||
interface Cliente {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
export interface Cliente extends ClienteEditable {
|
||||
_count: { cotizaciones: number };
|
||||
usuario: { id: string; email: string } | null;
|
||||
}
|
||||
@@ -23,9 +26,20 @@ type DialogoAcceso = {
|
||||
password: string;
|
||||
} | null;
|
||||
|
||||
export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
// undefined = cerrado; null = alta; Cliente = edicion.
|
||||
type DialogoCliente = Cliente | null | undefined;
|
||||
|
||||
export function ClientesList({
|
||||
clientes,
|
||||
abrirNuevo = false,
|
||||
}: {
|
||||
clientes: Cliente[];
|
||||
// /clientes?nuevo=1 (enlace desde "Nuevo programa" de /cobros).
|
||||
abrirNuevo?: boolean;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [dialogo, setDialogo] = useState<DialogoAcceso>(null);
|
||||
const [editando, setEditando] = useState<DialogoCliente>(abrirNuevo ? null : undefined);
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
const router = useRouter();
|
||||
const showConfirm = useConfirm();
|
||||
@@ -34,19 +48,28 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
const filtered = useMemo(() => {
|
||||
if (!search) return clientes;
|
||||
const q = search.toLowerCase();
|
||||
return clientes.filter(
|
||||
(c) =>
|
||||
c.nombre.toLowerCase().includes(q) ||
|
||||
(c.empresa || "").toLowerCase().includes(q) ||
|
||||
(c.email || "").toLowerCase().includes(q)
|
||||
return clientes.filter((c) =>
|
||||
[c.nombre, c.empresa, c.email, c.telefono, c.puesto].some((v) =>
|
||||
(v || "").toLowerCase().includes(q)
|
||||
)
|
||||
);
|
||||
}, [clientes, search]);
|
||||
|
||||
const cerrarCliente = () => {
|
||||
setEditando(undefined);
|
||||
if (abrirNuevo) router.replace("/clientes");
|
||||
};
|
||||
|
||||
const clienteGuardado = () => {
|
||||
cerrarCliente();
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
const abrirDialogo = (cliente: Cliente, modo: "crear" | "rotar") => {
|
||||
setDialogo({
|
||||
cliente,
|
||||
modo,
|
||||
email: modo === "rotar" ? cliente.usuario?.email || "" : "",
|
||||
email: modo === "rotar" ? cliente.usuario?.email || "" : cliente.email || "",
|
||||
password: "",
|
||||
});
|
||||
};
|
||||
@@ -56,11 +79,11 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
const email = dialogo.email.trim();
|
||||
const password = dialogo.password;
|
||||
if (!email) {
|
||||
toast("El email es requerido", "error");
|
||||
toast("El correo es requerido", "error");
|
||||
return;
|
||||
}
|
||||
if (password.length < 6) {
|
||||
toast("La contrasena debe tener al menos 6 caracteres", "error");
|
||||
toast("La contraseña debe tener al menos 6 caracteres", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
@@ -79,7 +102,7 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
setDialogo(null);
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
@@ -88,7 +111,7 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
const revocarAcceso = async (cliente: Cliente) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Revocar acceso",
|
||||
message: `Eliminar la cuenta de panel de ${cliente.nombre}? El cliente dejara de poder iniciar sesion.`,
|
||||
message: `¿Eliminar la cuenta de panel de ${cliente.nombre}? El cliente dejará de poder iniciar sesión.`,
|
||||
confirmText: "Revocar",
|
||||
danger: true,
|
||||
});
|
||||
@@ -105,67 +128,75 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
toast("Acceso revocado", "success");
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<div className="relative max-w-sm">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="relative w-full max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
||||
<input
|
||||
type="text"
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Buscar por nombre, empresa, email..."
|
||||
className="w-full pl-10 pr-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
placeholder="Buscar por nombre, empresa, correo o teléfono..."
|
||||
aria-label="Buscar clientes"
|
||||
className="w-full pl-10 pr-3 py-2 border border-border rounded-lg text-sm bg-card-bg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setEditando(null)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-primary hover:opacity-90"
|
||||
>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
Nuevo cliente
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<p className="text-center text-muted py-8">
|
||||
{search ? "Sin resultados para esa busqueda" : "No hay clientes"}
|
||||
</p>
|
||||
{clientes.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<Users className="w-10 h-10 text-muted mx-auto mb-3" />
|
||||
<h2 className="text-lg font-semibold mb-2">Aún no hay clientes</h2>
|
||||
<p className="text-muted max-w-sm mx-auto">
|
||||
Agrégalos con «Nuevo cliente» o se registrarán solos al guardar su primera cotización.
|
||||
</p>
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<p className="text-center text-muted py-8">Sin resultados para esa búsqueda</p>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
// relative: el sr-only (absolute) del encabezado debe quedar dentro del
|
||||
// scroll horizontal; si no, ensancha toda la pagina en movil.
|
||||
<div className="relative bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[60rem] text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Nombre
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Nombre</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Empresa</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Correo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Teléfono</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Cotizaciones</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acceso panel</th>
|
||||
<th className="px-5 py-3">
|
||||
<span className="sr-only">Acciones</span>
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Empresa
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Email
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Telefono
|
||||
</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">
|
||||
Cotizaciones
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Acceso panel
|
||||
</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted w-16" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((c) => (
|
||||
<tr
|
||||
key={c.id}
|
||||
className="border-b border-border hover:bg-gray-50"
|
||||
>
|
||||
<td className="px-5 py-3 font-medium">{c.nombre}</td>
|
||||
<td className="px-5 py-3">{c.empresa || "-"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.email || "-"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.telefono || "-"}</td>
|
||||
<tr key={c.id} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3 min-w-[12rem]">
|
||||
<div className="font-medium">{c.nombre}</div>
|
||||
{c.puesto && <div className="text-xs text-muted">{c.puesto}</div>}
|
||||
</td>
|
||||
<td className="px-5 py-3 min-w-[10rem]">{c.empresa || "—"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.email || "—"}</td>
|
||||
<td className="px-5 py-3 text-muted whitespace-nowrap tabular-nums">
|
||||
{c.telefono || "—"}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<span className="inline-block px-2 py-0.5 bg-primary-light text-primary rounded text-xs font-medium">
|
||||
<span className="inline-block px-2 py-0.5 bg-primary-light text-primary rounded text-xs font-medium tabular-nums">
|
||||
{c._count.cotizaciones}
|
||||
</span>
|
||||
</td>
|
||||
@@ -191,19 +222,29 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
) : (
|
||||
<button
|
||||
onClick={() => abrirDialogo(c, "crear")}
|
||||
className="px-3 py-1 rounded-lg text-xs text-white bg-primary hover:opacity-90"
|
||||
className="px-3 py-1 rounded-lg text-xs font-medium text-primary-dark bg-primary-light/70 hover:bg-primary hover:text-white transition-colors"
|
||||
>
|
||||
Crear acceso
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<NuevaCotizacionClienteButton
|
||||
clienteNombre={c.nombre}
|
||||
clienteEmpresa={c.empresa || ""}
|
||||
clienteEmail={c.email || ""}
|
||||
clienteTelefono={c.telefono || ""}
|
||||
/>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<button
|
||||
onClick={() => setEditando(c)}
|
||||
className="p-1.5 text-muted hover:text-primary hover:bg-primary/5 rounded transition-colors"
|
||||
title="Editar cliente"
|
||||
aria-label={`Editar a ${c.nombre}`}
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</button>
|
||||
<NuevaCotizacionClienteButton
|
||||
clienteNombre={c.nombre}
|
||||
clienteEmpresa={c.empresa || ""}
|
||||
clienteEmail={c.email || ""}
|
||||
clienteTelefono={c.telefono || ""}
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -212,63 +253,60 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editando !== undefined && (
|
||||
<ClienteDialog cliente={editando} onClose={cerrarCliente} onGuardado={clienteGuardado} />
|
||||
)}
|
||||
|
||||
{dialogo && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={() => setDialogo(null)}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-xl bg-card-bg border border-border shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="px-5 py-4 border-b border-border font-semibold">
|
||||
{dialogo.modo === "crear"
|
||||
? `Crear acceso para ${dialogo.cliente.nombre}`
|
||||
: `Rotar acceso de ${dialogo.cliente.nombre}`}
|
||||
</div>
|
||||
<div className="p-5 space-y-3">
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
value={dialogo.email}
|
||||
onChange={(e) =>
|
||||
setDialogo((d) => (d ? { ...d, email: e.target.value } : d))
|
||||
}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Contrasena</label>
|
||||
<input
|
||||
type="password"
|
||||
value={dialogo.password}
|
||||
onChange={(e) =>
|
||||
setDialogo((d) => (d ? { ...d, password: e.target.value } : d))
|
||||
}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
placeholder="Minimo 6 caracteres"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-2">
|
||||
<button
|
||||
onClick={() => setDialogo(null)}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
<Modal
|
||||
titulo={
|
||||
dialogo.modo === "crear"
|
||||
? `Crear acceso para ${dialogo.cliente.nombre}`
|
||||
: `Rotar acceso de ${dialogo.cliente.nombre}`
|
||||
}
|
||||
descripcion="Con este correo y contraseña entrará al portal de clientes para ver sus cotizaciones y pagos."
|
||||
onClose={() => setDialogo(null)}
|
||||
onSubmit={guardarAcceso}
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={() => setDialogo(null)} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={guardarAcceso}
|
||||
disabled={guardando}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : "Guardar"}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="acceso-email" className={claseEtiqueta}>
|
||||
Correo
|
||||
</label>
|
||||
<input
|
||||
id="acceso-email"
|
||||
type="email"
|
||||
value={dialogo.email}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setDialogo((d) => (d ? { ...d, email: e.target.value } : d))}
|
||||
className={claseCampo}
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="acceso-password" className={claseEtiqueta}>
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
id="acceso-password"
|
||||
type="password"
|
||||
value={dialogo.password}
|
||||
autoComplete="new-password"
|
||||
onChange={(e) => setDialogo((d) => (d ? { ...d, password: e.target.value } : d))}
|
||||
className={claseCampo}
|
||||
placeholder="Mínimo 6 caracteres"
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -31,7 +31,8 @@ export function NuevaCotizacionClienteButton({
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="p-1.5 text-muted hover:text-primary hover:bg-primary/5 rounded transition-colors"
|
||||
title="Nueva cotizacion"
|
||||
title="Nueva cotización"
|
||||
aria-label={`Nueva cotización para ${clienteNombre}`}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
@@ -1,60 +1,33 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { clienteSelect } from "@/lib/clientes";
|
||||
import { ClientesList } from "./ClientesList";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ClientesPage() {
|
||||
const clientes = await prisma.cliente.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
empresa: true,
|
||||
email: true,
|
||||
telefono: true,
|
||||
_count: { select: { cotizaciones: true } },
|
||||
usuario: { select: { id: true, email: true } },
|
||||
},
|
||||
});
|
||||
export default async function ClientesPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ nuevo?: string }>;
|
||||
}) {
|
||||
const [{ nuevo }, clientes] = await Promise.all([
|
||||
searchParams,
|
||||
prisma.cliente.findMany({
|
||||
where: { archivado: false },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: clienteSelect,
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Clientes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{clientes.length} clientes registrados
|
||||
</p>
|
||||
</div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Clientes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{clientes.length === 1 ? "1 cliente registrado" : `${clientes.length} clientes registrados`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{clientes.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h2 className="text-lg font-semibold mb-2">No hay clientes</h2>
|
||||
<p className="text-muted mb-4">
|
||||
Los clientes se crean automaticamente al generar cotizaciones
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ClientesListWrapper clientes={clientes} />
|
||||
)}
|
||||
<ClientesList clientes={clientes} abrirNuevo={nuevo === "1"} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
import { ClientesList } from "./ClientesList";
|
||||
|
||||
function ClientesListWrapper({
|
||||
clientes,
|
||||
}: {
|
||||
clientes: {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
_count: { cotizaciones: number };
|
||||
usuario: { id: string; email: string } | null;
|
||||
}[];
|
||||
}) {
|
||||
return <ClientesList clientes={clientes} />;
|
||||
}
|
||||
|
||||
@@ -2,11 +2,20 @@
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||
import { ProgramasTabla } from "./ProgramasTabla";
|
||||
import { PagosTabla } from "./PagosTabla";
|
||||
import type { ProgramaRow, ClienteOpt, PagoRow } from "./types";
|
||||
import { PorCobrarTabla } from "./PorCobrarTabla";
|
||||
import { RegistrarPagoDialog } from "./RegistrarPagoDialog";
|
||||
import type {
|
||||
ProgramaRow,
|
||||
ClienteOpt,
|
||||
PagoRow,
|
||||
SaldoClienteRow,
|
||||
ResultadoRecordatorioRow,
|
||||
} from "./types";
|
||||
|
||||
// Frecuencia legible en la tabla de programas.
|
||||
export function frecuenciaLegible(p: {
|
||||
@@ -18,27 +27,52 @@ export function frecuenciaLegible(p: {
|
||||
"domingo",
|
||||
"lunes",
|
||||
"martes",
|
||||
"miercoles",
|
||||
"miércoles",
|
||||
"jueves",
|
||||
"viernes",
|
||||
"sabado",
|
||||
"sábado",
|
||||
];
|
||||
if (p.frecuencia === "semanal") {
|
||||
const d = p.diaSemana ?? 0;
|
||||
return `Cada ${dias[d]}`;
|
||||
}
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada dia ${p.diaMes ?? 1}`;
|
||||
return `Cada día ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
// Por que un recordatorio no llego a nadie, en palabras del admin.
|
||||
function motivoNoEntregado(
|
||||
r: ResultadoRecordatorioRow,
|
||||
canales: { correo: boolean; push: boolean }
|
||||
): string {
|
||||
if (!canales.correo && !canales.push) {
|
||||
return "No hay SMTP (correo) ni VAPID (push) configurados en el servidor";
|
||||
}
|
||||
if (r.correo === "error") return "Falló el envío del correo; revisa el log del servidor";
|
||||
if (r.correo === "sin_email") {
|
||||
return "El cliente no tiene correo y no activó los avisos push";
|
||||
}
|
||||
if (r.correo === "omitido") {
|
||||
return "SMTP no configurado y el cliente no activó los avisos push";
|
||||
}
|
||||
return "No se pudo entregar por ningún canal";
|
||||
}
|
||||
|
||||
export function CobrosClient({
|
||||
programas,
|
||||
clientes,
|
||||
pagosIniciales,
|
||||
saldos,
|
||||
diasRecordatorio,
|
||||
enRevision,
|
||||
}: {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
pagosIniciales: PagoRow[];
|
||||
saldos: SaldoClienteRow[];
|
||||
diasRecordatorio: number;
|
||||
// Comprobantes esperando aprobacion (para la franja de resumen).
|
||||
enRevision: number;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const showConfirm = useConfirm();
|
||||
@@ -54,6 +88,8 @@ export function CobrosClient({
|
||||
const [clienteFiltro, setClienteFiltro] = useState("");
|
||||
const [desdeFiltro, setDesdeFiltro] = useState("");
|
||||
const [hastaFiltro, setHastaFiltro] = useState("");
|
||||
const [enviandoRecordatorio, setEnviandoRecordatorio] = useState<string | null>(null);
|
||||
const [registrando, setRegistrando] = useState<PagoRow | null>(null);
|
||||
|
||||
const cargarPagos = useCallback(async () => {
|
||||
setCargandoPagos(true);
|
||||
@@ -89,7 +125,7 @@ export function CobrosClient({
|
||||
const ok = await showConfirm({
|
||||
title: "Generar cobros",
|
||||
message:
|
||||
"Se generaran los cobros pendientes de todos los programas activos hasta hoy. Continuar?",
|
||||
"Se generarán los cobros pendientes de todos los programas activos hasta hoy. ¿Continuar?",
|
||||
confirmText: "Generar",
|
||||
});
|
||||
if (!ok) return;
|
||||
@@ -106,13 +142,69 @@ export function CobrosClient({
|
||||
}
|
||||
const n = data.generados ?? 0;
|
||||
toast(
|
||||
n > 0 ? `Se generaron ${n} cobros` : "No habia cobros pendientes",
|
||||
n > 0 ? `Se generaron ${n} cobros` : "No había cobros pendientes",
|
||||
"success"
|
||||
);
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
// saldo = null -> a todos los clientes con pagos vencidos.
|
||||
const recordar = async (saldo: SaldoClienteRow | null) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Enviar recordatorio de pago",
|
||||
message: saldo
|
||||
? `Se enviará a ${saldo.nombre} su estado de cuenta: ${saldo.pagos} ${saldo.pagos === 1 ? "cobro pendiente" : "cobros pendientes"} por ${formatTotales(saldo.totales)}, por correo y aviso push.`
|
||||
: `Se enviará el estado de cuenta a ${saldos.length} ${saldos.length === 1 ? "cliente" : "clientes"} con pagos vencidos, por correo y aviso push.`,
|
||||
confirmText: "Enviar",
|
||||
});
|
||||
if (!ok) return;
|
||||
setEnviandoRecordatorio(saldo?.clienteId ?? "*");
|
||||
try {
|
||||
const res = await fetch("/api/cobros/recordatorios", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(saldo ? { clienteId: saldo.clienteId } : {}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al enviar el recordatorio", "error");
|
||||
return;
|
||||
}
|
||||
const resultados: ResultadoRecordatorioRow[] = data.resultados ?? [];
|
||||
const canales = data.canales ?? { correo: false, push: false };
|
||||
const entregados = resultados.filter((r) => r.entregado);
|
||||
if (resultados.length === 0) {
|
||||
toast("No hay pagos vencidos por recordar", "info");
|
||||
} else if (entregados.length === resultados.length) {
|
||||
toast(
|
||||
entregados.length === 1
|
||||
? `Recordatorio enviado a ${entregados[0].cliente}`
|
||||
: `Recordatorio enviado a ${entregados.length} clientes`,
|
||||
"success"
|
||||
);
|
||||
} else if (entregados.length > 0) {
|
||||
const fallidos = resultados.filter((r) => !r.entregado).map((r) => r.cliente);
|
||||
toast(
|
||||
`Enviado a ${entregados.length} de ${resultados.length}. Sin entregar: ${fallidos.join(", ")}`,
|
||||
"info"
|
||||
);
|
||||
} else {
|
||||
toast(
|
||||
resultados.length === 1
|
||||
? `No se envió: ${motivoNoEntregado(resultados[0], canales)}`
|
||||
: `No se envió a ningún cliente: ${motivoNoEntregado(resultados[0], canales)}`,
|
||||
"error"
|
||||
);
|
||||
}
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setEnviandoRecordatorio(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -121,8 +213,8 @@ export function CobrosClient({
|
||||
const ok = await showConfirm({
|
||||
title: activar ? "Activar programa" : "Desactivar programa",
|
||||
message: activar
|
||||
? `Activar el programa "${p.concepto}"? Se generaran cobros en sus proximos periodos.`
|
||||
: `Desactivar el programa "${p.concepto}"? No se generaran mas cobros, pero los existentes se conservan.`,
|
||||
? `¿Activar el programa "${p.concepto}"? Se generarán cobros en sus próximos periodos.`
|
||||
: `¿Desactivar el programa "${p.concepto}"? No se generarán más cobros, pero los existentes se conservan.`,
|
||||
confirmText: activar ? "Activar" : "Desactivar",
|
||||
danger: !activar,
|
||||
});
|
||||
@@ -141,7 +233,7 @@ export function CobrosClient({
|
||||
toast(activar ? "Programa activado" : "Programa desactivado", "success");
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -163,8 +255,9 @@ export function CobrosClient({
|
||||
}
|
||||
toast("Cobro verificado", "success");
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -189,28 +282,157 @@ export function CobrosClient({
|
||||
}
|
||||
toast("Comprobante rechazado", "success");
|
||||
cargarPagos();
|
||||
// El cobro vuelve a estar por pagar: refresca el saldo por cliente.
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
// Desde "Pagos por cobrar": filtra la tabla a lo que debe ese cliente para
|
||||
// registrarle los pagos que hizo por fuera del panel.
|
||||
const verPorPagar = (saldo: SaldoClienteRow) => {
|
||||
setClienteFiltro(saldo.clienteId);
|
||||
setEstadoFiltro("por_pagar");
|
||||
setDesdeFiltro("");
|
||||
setHastaFiltro("");
|
||||
document.getElementById("comprobantes")?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
};
|
||||
|
||||
const alRegistrar = () => {
|
||||
setRegistrando(null);
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
const anular = async (pago: PagoRow) => {
|
||||
const motivo = await showPrompt({
|
||||
title: "Anular cobro",
|
||||
message: `El cobro del ${formatFechaCorta(new Date(pago.fecha))} de ${pago.programa.cliente.nombre} quedará sin cargo y dejará de contar como adeudo. Puedes reabrirlo después.`,
|
||||
label: "Motivo",
|
||||
placeholder: "Ej. semana sin servicio, cortesía...",
|
||||
confirmText: "Anular cobro",
|
||||
});
|
||||
if (motivo === null) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/anular`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ motivo: motivo.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al anular", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro anulado", "success");
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const reabrir = async (pago: PagoRow) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Reabrir cobro",
|
||||
message:
|
||||
pago.estado === "anulado"
|
||||
? `El cobro del ${formatFechaCorta(new Date(pago.fecha))} volverá a pendiente y contará otra vez como adeudo.`
|
||||
: `Se quitará el pago registrado del ${formatFechaCorta(new Date(pago.fecha))} y el cobro volverá a pendiente.`,
|
||||
confirmText: "Reabrir",
|
||||
danger: pago.estado !== "anulado",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/reabrir`, { method: "POST" });
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al reabrir", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro reabierto", "success");
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const totalPorCobrar: Record<string, number> = {};
|
||||
for (const s of saldos) {
|
||||
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||
totalPorCobrar[moneda] = (totalPorCobrar[moneda] ?? 0) + total;
|
||||
}
|
||||
}
|
||||
const programasActivos = programas.filter((p) => p.activo).length;
|
||||
const resumen = [
|
||||
{
|
||||
href: "#por-cobrar",
|
||||
label: "Por cobrar",
|
||||
valor: saldos.length ? formatTotales(totalPorCobrar) : "$0",
|
||||
detalle: saldos.length
|
||||
? `${saldos.length} ${saldos.length === 1 ? "cliente con adeudo" : "clientes con adeudo"}`
|
||||
: "Nadie tiene pagos vencidos",
|
||||
alerta: saldos.length > 0,
|
||||
},
|
||||
{
|
||||
href: "#comprobantes",
|
||||
label: "Comprobantes por revisar",
|
||||
valor: String(enRevision),
|
||||
detalle: enRevision ? "Esperan tu aprobación" : "Todo revisado",
|
||||
alerta: enRevision > 0,
|
||||
},
|
||||
{
|
||||
href: "#programas",
|
||||
label: "Programas activos",
|
||||
valor: String(programasActivos),
|
||||
detalle: `${programas.length - programasActivos} inactivos`,
|
||||
alerta: false,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-10">
|
||||
<section>
|
||||
<ProgramasTabla
|
||||
programas={programas}
|
||||
clientes={clientes}
|
||||
onToggleActivo={toggleActivo}
|
||||
<nav
|
||||
aria-label="Resumen de cobros"
|
||||
className="grid grid-cols-1 sm:grid-cols-3 bg-card-bg rounded-xl border border-border divide-y sm:divide-y-0 sm:divide-x divide-border overflow-hidden"
|
||||
>
|
||||
{resumen.map((r) => (
|
||||
<a key={r.href} href={r.href} className="block px-5 py-4 hover:bg-gray-50 transition-colors">
|
||||
<p className="text-xs font-medium text-muted">{r.label}</p>
|
||||
<p className={`text-xl font-semibold tracking-tight tabular-nums mt-1 ${r.alerta ? "text-foreground" : "text-muted"}`}>
|
||||
{r.valor}
|
||||
</p>
|
||||
<p className={`text-xs mt-0.5 ${r.alerta ? "text-amber-700" : "text-muted"}`}>{r.detalle}</p>
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<section id="por-cobrar" className="scroll-mt-20">
|
||||
<PorCobrarTabla
|
||||
saldos={saldos}
|
||||
diasRecordatorio={diasRecordatorio}
|
||||
enviando={enviandoRecordatorio}
|
||||
onRecordar={recordar}
|
||||
onVerPorPagar={verPorPagar}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<section id="comprobantes" className="scroll-mt-20">
|
||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||
<h2 className="text-lg font-semibold">Cobros generados</h2>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Comprobantes y cobros</h2>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Aprueba los comprobantes que suben tus clientes, registra los pagos que recibes por
|
||||
fuera del panel y consulta cualquier cobro.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={generarAhora}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90"
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Generar cobros ahora
|
||||
</button>
|
||||
</div>
|
||||
@@ -224,10 +446,12 @@ export function CobrosClient({
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="por_pagar">Por pagar (pendiente o rechazado)</option>
|
||||
<option value="pendiente">Pendiente</option>
|
||||
<option value="en_revision">En revision</option>
|
||||
<option value="en_revision">En revisión</option>
|
||||
<option value="verificado">Verificado</option>
|
||||
<option value="rechazado">Rechazado</option>
|
||||
<option value="anulado">Anulado</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
@@ -240,7 +464,7 @@ export function CobrosClient({
|
||||
<option value="">Todos</option>
|
||||
{clientes.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
{c.empresa ? `${c.nombre} — ${c.empresa}` : c.nombre}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -270,8 +494,27 @@ export function CobrosClient({
|
||||
cargando={cargandoPagos}
|
||||
onAprobar={aprobar}
|
||||
onRechazar={rechazar}
|
||||
onRegistrar={setRegistrando}
|
||||
onAnular={anular}
|
||||
onReabrir={reabrir}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section id="programas" className="scroll-mt-20">
|
||||
<ProgramasTabla
|
||||
programas={programas}
|
||||
clientes={clientes}
|
||||
onToggleActivo={toggleActivo}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{registrando && (
|
||||
<RegistrarPagoDialog
|
||||
pago={registrando}
|
||||
onClose={() => setRegistrando(null)}
|
||||
onRegistrado={alRegistrar}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ESTADOS_PAGO } from "@/lib/cobros-fechas";
|
||||
|
||||
// Badges de estado de cobro (colores locales, no reutiliza EstadoBadge que es
|
||||
// para cotizaciones). pendiente=amber, en_revision=azul, verificado=verde,
|
||||
// rechazado=rojizo.
|
||||
// rechazado=rojizo, anulado=gris.
|
||||
const ESTILOS: Record<string, { cls: string; label: string }> = {
|
||||
[ESTADOS_PAGO.PENDIENTE]: {
|
||||
cls: "bg-amber-100 text-amber-800",
|
||||
@@ -12,7 +12,7 @@ const ESTILOS: Record<string, { cls: string; label: string }> = {
|
||||
},
|
||||
[ESTADOS_PAGO.EN_REVISION]: {
|
||||
cls: "bg-blue-100 text-blue-800",
|
||||
label: "En revision",
|
||||
label: "En revisión",
|
||||
},
|
||||
[ESTADOS_PAGO.VERIFICADO]: {
|
||||
cls: "bg-green-100 text-green-800",
|
||||
@@ -22,6 +22,10 @@ const ESTILOS: Record<string, { cls: string; label: string }> = {
|
||||
cls: "bg-red-100 text-red-800",
|
||||
label: "Rechazado",
|
||||
},
|
||||
[ESTADOS_PAGO.ANULADO]: {
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
label: "Anulado",
|
||||
},
|
||||
};
|
||||
|
||||
export function EstadoPagoBadge({ estado }: { estado: string }) {
|
||||
|
||||
@@ -1,21 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { Check, X, FileText } from "lucide-react";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import { Ban, Check, FileText, HandCoins, RotateCcw, X } from "lucide-react";
|
||||
import { calendarioDe, esPorPagar, formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||
import { EstadoPagoBadge } from "./EstadoPagoBadge";
|
||||
import type { PagoRow } from "./types";
|
||||
|
||||
const claseAccion = "text-xs hover:underline flex items-center gap-1 whitespace-nowrap";
|
||||
|
||||
// Detalle bajo el estado: motivo de rechazo, dia del pago y nota interna.
|
||||
function DetalleEstado({ p }: { p: PagoRow }) {
|
||||
const lineas: string[] = [];
|
||||
if (p.estado === "rechazado" && p.rechazoMotivo) lineas.push(p.rechazoMotivo);
|
||||
if (p.estado === "verificado" && p.verificadoAt) {
|
||||
const dia = formatFechaCorta(calendarioDe(new Date(p.verificadoAt)));
|
||||
lineas.push(p.comprobante ? `Aprobado el ${dia}` : `Pagado el ${dia}`);
|
||||
}
|
||||
if (p.nota) lineas.push(p.nota);
|
||||
if (lineas.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-1 max-w-[16rem] space-y-0.5 text-xs text-muted">
|
||||
{lineas.map((l, i) => (
|
||||
<p key={i} className="line-clamp-2" title={l}>
|
||||
{l}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PagosTabla({
|
||||
pagos,
|
||||
cargando,
|
||||
onAprobar,
|
||||
onRechazar,
|
||||
onRegistrar,
|
||||
onAnular,
|
||||
onReabrir,
|
||||
}: {
|
||||
pagos: PagoRow[];
|
||||
cargando: boolean;
|
||||
onAprobar: (p: PagoRow) => void;
|
||||
onRechazar: (p: PagoRow) => void;
|
||||
onRegistrar: (p: PagoRow) => void;
|
||||
onAnular: (p: PagoRow) => void;
|
||||
onReabrir: (p: PagoRow) => void;
|
||||
}) {
|
||||
if (cargando) {
|
||||
return (
|
||||
@@ -29,79 +57,99 @@ export function PagosTabla({
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">No hay cobros</h3>
|
||||
<p className="text-muted">
|
||||
Genera cobros con el boton o ajusta los filtros
|
||||
</p>
|
||||
<p className="text-muted">Ajusta los filtros para ver otros cobros.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[56rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Fecha</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Comprobante</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pagos.map((p) => (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3">{formatFechaCorta(new Date(p.fecha))}</td>
|
||||
<td className="px-5 py-3">{p.programa.concepto}</td>
|
||||
<td className="px-5 py-3">{p.programa.cliente.nombre}</td>
|
||||
<td className="px-5 py-3 text-right">{formatCurrency(p.monto)}</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<EstadoPagoBadge estado={p.estado} />
|
||||
{p.estado === "rechazado" && p.rechazoMotivo && (
|
||||
<div className="text-xs text-muted mt-1">{p.rechazoMotivo}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
{p.comprobante ? (
|
||||
<a
|
||||
href={`/api/comprobantes/${p.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
>
|
||||
<FileText className="w-3 h-3" />
|
||||
Ver
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.estado === "en_revision" ? (
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => onAprobar(p)}
|
||||
className="text-xs text-success hover:underline flex items-center gap-1"
|
||||
{pagos.map((p) => {
|
||||
const manual = p.estado === "verificado" && !p.comprobante;
|
||||
return (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50 align-top">
|
||||
<td className="px-5 py-3 whitespace-nowrap">{formatFechaCorta(new Date(p.fecha))}</td>
|
||||
<td className="px-5 py-3">{p.programa.concepto}</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{p.programa.cliente.nombre}</div>
|
||||
{p.programa.cliente.empresa && (
|
||||
<div className="text-xs text-muted">{p.programa.cliente.empresa}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right whitespace-nowrap">
|
||||
{formatMonto(p.monto, p.programa.moneda)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<EstadoPagoBadge estado={p.estado} />
|
||||
<DetalleEstado p={p} />
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
{p.comprobante ? (
|
||||
<a
|
||||
href={`/api/comprobantes/${p.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
>
|
||||
<Check className="w-3 h-3" />
|
||||
Aprobar
|
||||
</button>
|
||||
<FileText className="w-3 h-3" />
|
||||
Ver
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted text-xs">{manual ? "Registro manual" : "—"}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.estado === "en_revision" ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={() => onAprobar(p)} className={`${claseAccion} text-success`}>
|
||||
<Check className="w-3 h-3" />
|
||||
Aprobar
|
||||
</button>
|
||||
<button onClick={() => onRechazar(p)} className={`${claseAccion} text-danger`}>
|
||||
<X className="w-3 h-3" />
|
||||
Rechazar
|
||||
</button>
|
||||
</div>
|
||||
) : esPorPagar(p.estado) ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={() => onRegistrar(p)} className={`${claseAccion} text-primary`}>
|
||||
<HandCoins className="w-3 h-3" />
|
||||
Registrar pago
|
||||
</button>
|
||||
<button onClick={() => onAnular(p)} className={`${claseAccion} text-muted`}>
|
||||
<Ban className="w-3 h-3" />
|
||||
Anular
|
||||
</button>
|
||||
</div>
|
||||
) : manual || p.estado === "anulado" ? (
|
||||
<button
|
||||
onClick={() => onRechazar(p)}
|
||||
className="text-xs text-danger hover:underline flex items-center gap-1"
|
||||
onClick={() => onReabrir(p)}
|
||||
className={`${claseAccion} text-muted`}
|
||||
title="Devolver el cobro a pendiente"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
Rechazar
|
||||
<RotateCcw className="w-3 h-3" />
|
||||
Reabrir
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { BellRing, HandCoins, Send } from "lucide-react";
|
||||
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||
import type { SaldoClienteRow } from "./types";
|
||||
|
||||
// Saldo vencido por cliente y envio del recordatorio de pago (estado de cuenta
|
||||
// por correo + push). El scheduler lo reenvia solo cada `diasRecordatorio`
|
||||
// dias; estos botones lo mandan en el momento.
|
||||
export function PorCobrarTabla({
|
||||
saldos,
|
||||
diasRecordatorio,
|
||||
enviando,
|
||||
onRecordar,
|
||||
onVerPorPagar,
|
||||
}: {
|
||||
saldos: SaldoClienteRow[];
|
||||
diasRecordatorio: number;
|
||||
// clienteId en envio, "*" para todos, null si no hay envio en curso.
|
||||
enviando: string | null;
|
||||
onRecordar: (saldo: SaldoClienteRow | null) => void;
|
||||
// Filtra la tabla de cobros a lo que debe el cliente (para registrar pagos).
|
||||
onVerPorPagar: (saldo: SaldoClienteRow) => void;
|
||||
}) {
|
||||
const totalGeneral: Record<string, number> = {};
|
||||
for (const s of saldos) {
|
||||
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||
totalGeneral[moneda] = (totalGeneral[moneda] ?? 0) + total;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Pagos por cobrar</h2>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{diasRecordatorio > 0
|
||||
? `Cobros vencidos sin pago o con comprobante rechazado. El recordatorio se reenvía solo cada ${diasRecordatorio} ${diasRecordatorio === 1 ? "día" : "días"} a partir de las 9:00.`
|
||||
: "Cobros vencidos sin pago o con comprobante rechazado. El recordatorio automático está desactivado (COBROS_RECORDATORIO_DIAS=0)."}
|
||||
</p>
|
||||
</div>
|
||||
{saldos.length > 0 && (
|
||||
<button
|
||||
onClick={() => onRecordar(null)}
|
||||
disabled={enviando !== null}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<BellRing className="w-4 h-4" />
|
||||
{enviando === "*" ? "Enviando..." : "Recordar a todos"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{saldos.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">Sin pagos vencidos</h3>
|
||||
<p className="text-muted">Ningún cliente tiene cobros pendientes de pago.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[54rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Cobros</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Adeudo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Más antiguo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Último recordatorio</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{saldos.map((s) => (
|
||||
<tr key={s.clienteId} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3">
|
||||
<div className="font-medium">{s.nombre}</div>
|
||||
{s.empresa && <div className="text-xs text-muted">{s.empresa}</div>}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">{s.pagos}</td>
|
||||
<td className="px-5 py-3 text-right font-medium whitespace-nowrap">
|
||||
{formatTotales(s.totales)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{formatFechaCorta(new Date(s.masAntigua))}</div>
|
||||
<div className={`text-xs ${s.diasAtraso > 0 ? "text-danger" : "text-muted"}`}>
|
||||
{s.diasAtraso === 0
|
||||
? "vence hoy"
|
||||
: `${s.diasAtraso} ${s.diasAtraso === 1 ? "día" : "días"} de atraso`}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-muted">
|
||||
{s.ultimoRecordatorio
|
||||
? formatFechaCorta(new Date(s.ultimoRecordatorio))
|
||||
: "Nunca"}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<button
|
||||
onClick={() => onVerPorPagar(s)}
|
||||
title="Ver sus cobros por pagar para registrar los pagos recibidos"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline whitespace-nowrap"
|
||||
>
|
||||
<HandCoins className="w-3 h-3" />
|
||||
Registrar pagos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onRecordar(s)}
|
||||
disabled={enviando !== null || !s.contactable}
|
||||
title={
|
||||
s.contactable
|
||||
? "Enviar estado de cuenta por correo y push"
|
||||
: "El cliente no tiene correo ni cuenta de panel"
|
||||
}
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline whitespace-nowrap disabled:opacity-40 disabled:no-underline disabled:cursor-not-allowed"
|
||||
>
|
||||
<Send className="w-3 h-3" />
|
||||
{enviando === s.clienteId ? "Enviando..." : "Enviar recordatorio"}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="bg-gray-50">
|
||||
<td className="px-5 py-3 font-medium" colSpan={2}>
|
||||
Total por cobrar
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-semibold whitespace-nowrap">
|
||||
{formatTotales(totalGeneral)}
|
||||
</td>
|
||||
<td colSpan={3} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Pencil, Power, Plus } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import { formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||
import type { ProgramaRow, ClienteOpt } from "./types";
|
||||
|
||||
const DIAS = [
|
||||
"Domingo",
|
||||
"Lunes",
|
||||
"Martes",
|
||||
"Miercoles",
|
||||
"Miércoles",
|
||||
"Jueves",
|
||||
"Viernes",
|
||||
"Sabado",
|
||||
"Sábado",
|
||||
];
|
||||
|
||||
function frecuenciaTexto(p: {
|
||||
@@ -25,7 +25,7 @@ function frecuenciaTexto(p: {
|
||||
}): string {
|
||||
if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`;
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada dia ${p.diaMes ?? 1}`;
|
||||
return `Cada día ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
function EstadoProgramaBadge({ activo }: { activo: boolean }) {
|
||||
@@ -154,7 +154,7 @@ export function ProgramasTabla({
|
||||
setDialogo(null);
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
@@ -162,7 +162,7 @@ export function ProgramasTabla({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<h2 className="text-lg font-semibold">Programas de pago</h2>
|
||||
<button
|
||||
onClick={abrirNuevo}
|
||||
@@ -181,15 +181,15 @@ export function ProgramasTabla({
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[56rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Frecuencia</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Proximo cobro</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Próximo cobro</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
@@ -204,7 +204,7 @@ export function ProgramasTabla({
|
||||
<div className="text-xs text-muted">{p.cliente.empresa}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right">{formatCurrency(p.monto)}</td>
|
||||
<td className="px-5 py-3 text-right">{formatMonto(p.monto, p.moneda)}</td>
|
||||
<td className="px-5 py-3">{frecuenciaTexto(p)}</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.proximaFecha
|
||||
@@ -269,6 +269,13 @@ export function ProgramasTabla({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-muted mt-1">
|
||||
¿No aparece?{" "}
|
||||
<Link href="/clientes?nuevo=1" className="text-primary hover:underline">
|
||||
Da de alta al cliente
|
||||
</Link>{" "}
|
||||
sin hacerle una cotización.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
@@ -341,6 +348,9 @@ export function ProgramasTabla({
|
||||
onChange={(e) => set("fechaInicio", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted mt-1">
|
||||
Si es una fecha pasada, se generan como pendientes todos los cobros desde ese día.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
import { formatFechaCorta, formatMonto, hoyCalendario } from "@/lib/cobros-fechas";
|
||||
import type { PagoRow } from "./types";
|
||||
|
||||
// Registrar a mano un pago recibido fuera del panel (transferencia avisada por
|
||||
// WhatsApp, efectivo...). El cobro queda verificado sin comprobante.
|
||||
export function RegistrarPagoDialog({
|
||||
pago,
|
||||
onClose,
|
||||
onRegistrado,
|
||||
}: {
|
||||
pago: PagoRow;
|
||||
onClose: () => void;
|
||||
onRegistrado: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const hoy = hoyCalendario().toISOString().slice(0, 10);
|
||||
const [fecha, setFecha] = useState(hoy);
|
||||
const [nota, setNota] = useState("");
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const guardar = async () => {
|
||||
if (!fecha) {
|
||||
toast("Indica la fecha del pago", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/registrar`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ fecha, nota: nota.trim() || undefined }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al registrar el pago", "error");
|
||||
return;
|
||||
}
|
||||
toast("Pago registrado", "success");
|
||||
onRegistrado();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
titulo="Registrar pago"
|
||||
descripcion={
|
||||
<>
|
||||
{pago.programa.cliente.nombre} · cobro del {formatFechaCorta(new Date(pago.fecha))} por{" "}
|
||||
<span className="font-medium text-foreground tabular-nums">
|
||||
{formatMonto(pago.monto, pago.programa.moneda)}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
onSubmit={guardar}
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={onClose} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : "Registrar pago"}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="registrar-fecha" className={claseEtiqueta}>
|
||||
Fecha en que pagó
|
||||
</label>
|
||||
<input
|
||||
id="registrar-fecha"
|
||||
type="date"
|
||||
value={fecha}
|
||||
max={hoy}
|
||||
required
|
||||
onChange={(e) => setFecha(e.target.value)}
|
||||
className={claseCampo}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="registrar-nota" className={claseEtiqueta}>
|
||||
Nota interna (opcional)
|
||||
</label>
|
||||
<input
|
||||
id="registrar-nota"
|
||||
type="text"
|
||||
value={nota}
|
||||
maxLength={500}
|
||||
onChange={(e) => setNota(e.target.value)}
|
||||
placeholder="Ej. transferencia, efectivo, pagó en dos partes..."
|
||||
className={claseCampo}
|
||||
/>
|
||||
<p className="text-xs text-muted mt-1">Solo la ves tú; el cliente no la ve.</p>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { proximaFecha } from "@/lib/cobros";
|
||||
import {
|
||||
agruparPorCliente,
|
||||
calendarioDe,
|
||||
diasDeAtraso,
|
||||
diasRecordatorio,
|
||||
pagosPorCobrar,
|
||||
proximaFecha,
|
||||
totalesPorMoneda,
|
||||
} from "@/lib/cobros";
|
||||
import { CobrosClient } from "./CobrosClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -22,7 +30,7 @@ type ProgramaConCliente = {
|
||||
};
|
||||
|
||||
export default async function CobrosPage() {
|
||||
const [programas, clientes, pagosIniciales] = await Promise.all([
|
||||
const [programas, clientes, pagosIniciales, porCobrar] = await Promise.all([
|
||||
prisma.programaPago.findMany({
|
||||
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
||||
include: {
|
||||
@@ -49,6 +57,7 @@ export default async function CobrosPage() {
|
||||
comprobante: true,
|
||||
},
|
||||
}),
|
||||
pagosPorCobrar(),
|
||||
]);
|
||||
|
||||
const programasData = (programas as ProgramaConCliente[]).map((p) => {
|
||||
@@ -82,6 +91,8 @@ export default async function CobrosPage() {
|
||||
monto: p.monto,
|
||||
estado: p.estado,
|
||||
rechazoMotivo: p.rechazoMotivo,
|
||||
verificadoAt: p.verificadoAt ? p.verificadoAt.toISOString() : null,
|
||||
nota: p.nota,
|
||||
programa: {
|
||||
concepto: p.programa.concepto,
|
||||
moneda: p.programa.moneda,
|
||||
@@ -98,12 +109,35 @@ export default async function CobrosPage() {
|
||||
: null,
|
||||
}));
|
||||
|
||||
// Saldo vencido por cliente, del mas atrasado al mas reciente (pagosPorCobrar
|
||||
// ya viene ordenado por fecha y el Map conserva el orden de aparicion).
|
||||
const saldosData = [...agruparPorCliente(porCobrar)].map(([clienteId, lista]) => {
|
||||
const cliente = lista[0].programa.cliente;
|
||||
let ultimo: Date | null = null;
|
||||
for (const p of lista) {
|
||||
if (p.ultimoRecordatorioAt && (!ultimo || p.ultimoRecordatorioAt > ultimo)) {
|
||||
ultimo = p.ultimoRecordatorioAt;
|
||||
}
|
||||
}
|
||||
return {
|
||||
clienteId,
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa,
|
||||
pagos: lista.length,
|
||||
totales: totalesPorMoneda(lista),
|
||||
masAntigua: lista[0].fecha.toISOString(),
|
||||
diasAtraso: diasDeAtraso(lista[0].fecha),
|
||||
ultimoRecordatorio: ultimo ? calendarioDe(ultimo).toISOString() : null,
|
||||
contactable: Boolean(cliente.email || cliente.usuario),
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold">Cobros recurrentes</h1>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Cobros recurrentes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Programa cobros periodicos y revisa los comprobantes de tus clientes
|
||||
Cobra a tiempo, revisa comprobantes y programa cobros periódicos
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -111,6 +145,9 @@ export default async function CobrosPage() {
|
||||
programas={programasData}
|
||||
clientes={clientesData}
|
||||
pagosIniciales={pagosData}
|
||||
saldos={saldosData}
|
||||
diasRecordatorio={diasRecordatorio()}
|
||||
enRevision={pagosData.length}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -36,6 +36,10 @@ export type PagoRow = {
|
||||
monto: number;
|
||||
estado: string;
|
||||
rechazoMotivo: string | null;
|
||||
// Dia del pago (manual) o de la aprobacion del comprobante; null si no se pago.
|
||||
verificadoAt: string | null;
|
||||
// Nota interna del admin: abonos/forma de pago, o motivo de anulacion.
|
||||
nota: string | null;
|
||||
programa: {
|
||||
concepto: string;
|
||||
moneda: string;
|
||||
@@ -43,3 +47,32 @@ export type PagoRow = {
|
||||
};
|
||||
comprobante: ComprobanteMeta | null;
|
||||
};
|
||||
|
||||
// Saldo vencido de un cliente (cobros pendientes o rechazados con fecha <= hoy).
|
||||
export type SaldoClienteRow = {
|
||||
clienteId: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
pagos: number;
|
||||
// Total por moneda: un cliente puede tener programas en MXN y USD.
|
||||
totales: Record<string, number>;
|
||||
masAntigua: string;
|
||||
diasAtraso: number;
|
||||
// Fecha de calendario MX del ultimo recordatorio entregado, o null.
|
||||
ultimoRecordatorio: string | null;
|
||||
// Hay a donde mandar el aviso: email del cliente o cuenta de panel.
|
||||
contactable: boolean;
|
||||
};
|
||||
|
||||
// Respuesta de POST /api/cobros/recordatorios (espejo de ResultadoRecordatorio
|
||||
// en src/lib/notificaciones.ts, que no se importa desde el navegador).
|
||||
export type ResultadoRecordatorioRow = {
|
||||
clienteId: string;
|
||||
cliente: string;
|
||||
pagos: number;
|
||||
totales: Record<string, number>;
|
||||
correo: "enviado" | "omitido" | "sin_email" | "error";
|
||||
push: number;
|
||||
entregado: boolean;
|
||||
pagoIds: string[];
|
||||
};
|
||||
|
||||
@@ -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<string, strin
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
value={config[field.key] || "#2563eb"}
|
||||
value={config[field.key] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4")}
|
||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||
className="w-10 h-10 rounded-lg border border-border cursor-pointer p-0.5"
|
||||
/>
|
||||
@@ -204,7 +204,7 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
|
||||
/>
|
||||
<div
|
||||
className="w-8 h-8 rounded-full border border-border"
|
||||
style={{ backgroundColor: config[field.key] || "#2563eb" }}
|
||||
style={{ backgroundColor: config[field.key] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4") }}
|
||||
/>
|
||||
</div>
|
||||
) : field.type === "textarea" ? (
|
||||
@@ -222,6 +222,9 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
)}
|
||||
{"hint" in field && field.hint && (
|
||||
<p className="text-xs text-muted mt-1">{field.hint}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -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">(
|
||||
clienteTelefono ? "whatsapp_chatwoot" : clienteEmail ? "email" : "manual"
|
||||
);
|
||||
const [destino, setDestino] = useState(clienteTelefono || clienteEmail || "");
|
||||
const [mensaje, setMensaje] = useState("");
|
||||
const [fallbackEmail, setFallbackEmail] = useState(true);
|
||||
|
||||
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 (
|
||||
<select
|
||||
value={estado}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
disabled={loading}
|
||||
className="text-xs font-medium px-2 py-1 rounded-full border border-border bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
|
||||
>
|
||||
{OPCIONES.map((o) => (
|
||||
<option key={o.value} value={o.value}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EstadoBadge estado={estado} />
|
||||
|
||||
{estado === "borrador" && esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAprobar}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle2 className="w-3.5 h-3.5" />}
|
||||
Aprobar cotización
|
||||
</button>
|
||||
)}
|
||||
|
||||
{estado === "aprobada" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEnviarModal(true)}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
Enviar cotización
|
||||
</button>
|
||||
{esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Reabrir
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{estado === "enviada" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("aceptada", "Aceptada")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-green-300 text-green-700 hover:bg-green-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
Aceptada
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("rechazada", "Rechazada", true)}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-red-300 text-red-700 hover:bg-red-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<XCircle className="w-3.5 h-3.5" />
|
||||
Rechazada
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("vencida", "Vencida")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-amber-300 text-amber-800 hover:bg-amber-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
Vencida
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{(estado === "rechazada" || estado === "vencida") && esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Reabrir borrador
|
||||
</button>
|
||||
)}
|
||||
|
||||
{showEnviarModal && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4"
|
||||
onClick={() => !loading && setShowEnviarModal(false)}
|
||||
>
|
||||
<form
|
||||
onSubmit={handleEnviar}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-white rounded-xl border border-border shadow-xl max-w-md w-full p-5 space-y-4"
|
||||
>
|
||||
<div>
|
||||
<h3 className="font-semibold text-base">Enviar cotización {numero}</h3>
|
||||
<p className="text-xs text-muted mt-0.5">
|
||||
El PDF oficial se genera automáticamente al confirmar el envío.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("email")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "email"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
Correo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("whatsapp_chatwoot")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "whatsapp_chatwoot"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4" />
|
||||
WhatsApp
|
||||
</button>
|
||||
{esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("manual")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "manual"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
Manual
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-muted mb-1">
|
||||
{canal === "email"
|
||||
? "Correo destino"
|
||||
: canal === "whatsapp_chatwoot"
|
||||
? "Teléfono WhatsApp"
|
||||
: "Destino / referencia"}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={destino}
|
||||
onChange={(e) => setDestino(e.target.value)}
|
||||
required={canal !== "manual"}
|
||||
placeholder={canal === "email" ? "[email protected]" : "4421234567"}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{canal !== "manual" && (
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-muted mb-1">
|
||||
Mensaje adicional (opcional)
|
||||
</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
value={mensaje}
|
||||
onChange={(e) => setMensaje(e.target.value)}
|
||||
placeholder="Nota breve para acompañar la propuesta..."
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canal === "whatsapp_chatwoot" && clienteEmail && (
|
||||
<label className="flex items-center gap-2 text-xs text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={fallbackEmail}
|
||||
onChange={(e) => setFallbackEmail(e.target.checked)}
|
||||
/>
|
||||
Si WhatsApp está fuera de la ventana de 24h, enviar por correo ({clienteEmail})
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-border">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEnviarModal(false)}
|
||||
disabled={loading}
|
||||
className="px-3 py-2 rounded-lg border border-border text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
Confirmar envío
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -331,8 +331,8 @@ export function RegistroHorasPanel({
|
||||
|
||||
// ---- HTML autocontenido de la nota de pago (para imprimir / guardar como PDF) ----
|
||||
const construirHTMLNota = () => {
|
||||
const PRIMARY = branding.colorPrimario || "#2563eb";
|
||||
const DARK = branding.colorSecundario || "#111827";
|
||||
const PRIMARY = branding.colorPrimario || "#0400C4";
|
||||
const DARK = branding.colorSecundario || "#0F172A";
|
||||
const logoSrc = branding.logoBase64
|
||||
? `data:${branding.logoMime || "image/png"};base64,${branding.logoBase64}`
|
||||
: "";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { getConfigBranding } from "@/lib/config-helpers";
|
||||
import {
|
||||
formatDate,
|
||||
@@ -42,7 +43,9 @@ export default async function CotizacionDetailPage({
|
||||
|
||||
// El registro de horas (notas de pago) solo aplica a cotizaciones aprobadas que se
|
||||
// cobran por tiempo (horas/retainer/demanda).
|
||||
const mostrarHoras = cot.estado === "aprobada" && esCotizacionPorTiempo(cot.servicios);
|
||||
const session = await getSession();
|
||||
const esAdmin = session?.role === "admin";
|
||||
const mostrarHoras = ["aprobada", "enviada", "aceptada"].includes(cot.estado) && esCotizacionPorTiempo(cot.servicios);
|
||||
const branding = mostrarHoras ? await getConfigBranding() : null;
|
||||
|
||||
const serviciosUnicos = cot.servicios
|
||||
@@ -107,6 +110,28 @@ export default async function CotizacionDetailPage({
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Información de la Cotización</h2>
|
||||
{(cot.creadaPorAgente || cot.aprobadaAt || cot.enviadaAt) && (
|
||||
<div className="flex flex-wrap gap-2 mb-4 text-xs">
|
||||
{cot.creadaPorAgente && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-purple-100 text-purple-800 font-medium">
|
||||
Creada por agente: {cot.creadaPorAgente}
|
||||
</span>
|
||||
)}
|
||||
{cot.aprobadaAt && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-indigo-50 text-indigo-800 border border-indigo-200">
|
||||
Aprobada el {formatDate(cot.aprobadaAt)}
|
||||
{cot.aprobacionMetodo ? ` (${cot.aprobacionMetodo === "enlace_firmado" ? "enlace firmado" : "panel admin"})` : ""}
|
||||
</span>
|
||||
)}
|
||||
{cot.enviadaAt && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-blue-50 text-blue-800 border border-blue-200">
|
||||
Enviada el {formatDate(cot.enviadaAt)}
|
||||
{cot.enviadaCanal ? ` vía ${cot.enviadaCanal}` : ""}
|
||||
{cot.enviadaDestino ? ` a ${cot.enviadaDestino}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted">Cliente</span>
|
||||
@@ -139,7 +164,14 @@ export default async function CotizacionDetailPage({
|
||||
<div>
|
||||
<span className="text-muted">Estado</span>
|
||||
<div className="mt-0.5">
|
||||
<CambiarEstadoButtons cotizacionId={cot.id} estado={cot.estado} />
|
||||
<CambiarEstadoButtons
|
||||
cotizacionId={cot.id}
|
||||
numero={cot.numero}
|
||||
estado={cot.estado}
|
||||
esAdmin={esAdmin}
|
||||
clienteEmail={cot.cliente.email}
|
||||
clienteTelefono={cot.cliente.telefono}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function CotizacionesPage() {
|
||||
const cotizaciones = await prisma.cotizacion.findMany({
|
||||
where: { archivado: false },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
|
||||
@@ -13,8 +13,9 @@ export default async function DashboardPage() {
|
||||
totalClientes,
|
||||
totalServicios,
|
||||
] = await Promise.all([
|
||||
prisma.cotizacion.count(),
|
||||
prisma.cotizacion.count({ where: { archivado: false } }),
|
||||
prisma.cotizacion.findMany({
|
||||
where: { archivado: false },
|
||||
take: 10,
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
@@ -28,7 +29,7 @@ export default async function DashboardPage() {
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.cliente.count(),
|
||||
prisma.cliente.count({ where: { archivado: false } }),
|
||||
prisma.servicioCatalogo.count({ where: { activo: true } }),
|
||||
]);
|
||||
|
||||
@@ -45,7 +46,7 @@ export default async function DashboardPage() {
|
||||
value: totalClientes,
|
||||
icon: Users,
|
||||
color: "text-secondary",
|
||||
bg: "bg-purple-100",
|
||||
bg: "bg-slate-100",
|
||||
},
|
||||
{
|
||||
label: "Servicios Activos",
|
||||
@@ -62,7 +63,7 @@ export default async function DashboardPage() {
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Dashboard</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Bienvenido al Cotizador E3
|
||||
Bienvenido al Cotizador — Uriel Jareth Consulting
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
adminOnly: true,
|
||||
recursoTipo: "agent_key",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const existing = await prisma.agentApiKey.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "Clave no encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
const updated = await prisma.agentApiKey.update({
|
||||
where: { id },
|
||||
data: {
|
||||
activo: false,
|
||||
revokedAt: new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
prefijo: true,
|
||||
activo: true,
|
||||
revokedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "agent_key.revocar",
|
||||
recursoTipo: "agent_key",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { nombre: updated.nombre, prefijo: updated.prefijo },
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generateApiKey, requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
adminOnly: true,
|
||||
recursoTipo: "agent_key",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const existing = await prisma.agentApiKey.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "Clave no encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
const { rawKey, prefijo, keyHash } = generateApiKey();
|
||||
|
||||
const updated = await prisma.agentApiKey.update({
|
||||
where: { id },
|
||||
data: {
|
||||
prefijo,
|
||||
keyHash,
|
||||
activo: true,
|
||||
revokedAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
prefijo: true,
|
||||
scopes: true,
|
||||
rateLimitPerMin: true,
|
||||
activo: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "agent_key.rotar",
|
||||
recursoTipo: "agent_key",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { nombre: updated.nombre, prefijoNuevo: prefijo },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ...updated, rawKey });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
AGENT_SCOPES,
|
||||
generateApiKey,
|
||||
requireActor,
|
||||
} from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
const createKeySchema = z.object({
|
||||
nombre: z.string().trim().min(2, "Nombre requerido (min. 2 caracteres)").max(100),
|
||||
scopes: z
|
||||
.array(z.enum(AGENT_SCOPES))
|
||||
.min(1, "Debes asignar al menos un alcance"),
|
||||
rateLimitPerMin: z.number().int().min(1).max(1000).default(60),
|
||||
});
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "agent_key" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const keys = await prisma.agentApiKey.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
prefijo: true,
|
||||
scopes: true,
|
||||
rateLimitPerMin: true,
|
||||
activo: true,
|
||||
revokedAt: true,
|
||||
lastUsedAt: true,
|
||||
createdById: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(keys);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "agent_key" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = createKeySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { nombre, scopes, rateLimitPerMin } = parsed.data;
|
||||
const existe = await prisma.agentApiKey.findUnique({ where: { nombre } });
|
||||
if (existe) {
|
||||
return NextResponse.json(
|
||||
{ error: `Ya existe una clave con el nombre "${nombre}"` },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const { rawKey, prefijo, keyHash } = generateApiKey();
|
||||
const createdById = auth.actor.type === "user" ? auth.actor.userId : null;
|
||||
|
||||
const created = await prisma.agentApiKey.create({
|
||||
data: {
|
||||
nombre,
|
||||
prefijo,
|
||||
keyHash,
|
||||
scopes: Array.from(new Set(scopes)),
|
||||
rateLimitPerMin,
|
||||
activo: true,
|
||||
createdById,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
nombre: true,
|
||||
prefijo: true,
|
||||
scopes: true,
|
||||
rateLimitPerMin: true,
|
||||
activo: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "agent_key.crear",
|
||||
recursoTipo: "agent_key",
|
||||
recursoId: created.id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { nombre: created.nombre, prefijo: created.prefijo, scopes: created.scopes },
|
||||
});
|
||||
|
||||
// rawKey se devuelve UNA SOLA VEZ al momento de crear la clave.
|
||||
return NextResponse.json({ ...created, rawKey }, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { hashSecret } from "@/lib/agent-auth-core";
|
||||
import { obtenerIp } from "@/lib/audit";
|
||||
import { aprobarCotizacionConToken } from "@/lib/aprobacion";
|
||||
import { calcularTotalesCotizacion } from "@/lib/calculators";
|
||||
|
||||
// GET /api/aprobar/[token] — consulta segura SIN mutar nada (proteccion anti-prefetch).
|
||||
export async function GET(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ token: string }> }
|
||||
) {
|
||||
try {
|
||||
const { token } = await params;
|
||||
const tokenHash = hashSecret(token);
|
||||
const now = new Date();
|
||||
|
||||
const record = await prisma.approvalToken.findUnique({
|
||||
where: { tokenHash },
|
||||
include: {
|
||||
cotizacion: {
|
||||
include: {
|
||||
cliente: { select: { nombre: true, empresa: true } },
|
||||
servicios: {
|
||||
where: { seleccionado: true },
|
||||
include: { servicioCatalogo: { select: { nombre: true } } },
|
||||
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
planBucefalo: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
return NextResponse.json({ error: "Enlace de aprobacion invalido" }, { status: 404 });
|
||||
}
|
||||
if (record.usadoAt) {
|
||||
return NextResponse.json(
|
||||
{ error: "Este enlace de aprobacion ya fue utilizado", usadoAt: record.usadoAt },
|
||||
{ status: 410 }
|
||||
);
|
||||
}
|
||||
if (record.expiraAt <= now) {
|
||||
return NextResponse.json(
|
||||
{ error: "Este enlace de aprobacion ha expirado", expiraAt: record.expiraAt },
|
||||
{ status: 410 }
|
||||
);
|
||||
}
|
||||
|
||||
const cot = record.cotizacion;
|
||||
const totales = calcularTotalesCotizacion(cot.servicios, {
|
||||
incluirIva: cot.incluirIva,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
cotizacion: {
|
||||
id: cot.id,
|
||||
numero: cot.numero,
|
||||
proyecto: cot.proyecto,
|
||||
moneda: cot.moneda,
|
||||
estado: cot.estado,
|
||||
fecha: cot.fecha,
|
||||
vigencia: cot.vigencia,
|
||||
incluirIva: cot.incluirIva,
|
||||
creadaPorAgente: cot.creadaPorAgente,
|
||||
cliente: cot.cliente,
|
||||
totales,
|
||||
partidas: cot.servicios.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precio,
|
||||
modeloCobro: s.modeloCobro,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
})),
|
||||
},
|
||||
expiraAt: record.expiraAt,
|
||||
puedeAprobar: cot.estado === "borrador",
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/aprobar/[token] — exige { confirmar: true } y aprueba en transaccion atomica.
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ token: string }> }
|
||||
) {
|
||||
try {
|
||||
const { token } = await params;
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body || body.confirmar !== true) {
|
||||
return NextResponse.json(
|
||||
{ error: "Se requiere { confirmar: true } para aprobar la cotizacion" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const res = await aprobarCotizacionConToken(token, obtenerIp(request));
|
||||
if (!res.ok) {
|
||||
return NextResponse.json({ error: res.error }, { status: res.status });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
cotizacionId: res.cotizacionId,
|
||||
numero: res.numero,
|
||||
estado: "aprobada",
|
||||
aprobadaAt: res.aprobadaAt,
|
||||
aprobacionMetodo: "enlace_firmado",
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireActor } from "@/lib/agent-auth";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, { adminOnly: true, recursoTipo: "audit_log" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const sp = request.nextUrl.searchParams;
|
||||
const accion = sp.get("accion")?.trim();
|
||||
const actorNombre = sp.get("actorNombre")?.trim();
|
||||
const recursoId = sp.get("recursoId")?.trim();
|
||||
const page = Math.max(1, parseInt(sp.get("page") || "1", 10) || 1);
|
||||
const limit = Math.min(200, Math.max(1, parseInt(sp.get("limit") || "50", 10) || 50));
|
||||
|
||||
const where = {
|
||||
...(accion && { accion: { contains: accion, mode: "insensitive" as const } }),
|
||||
...(actorNombre && { actorNombre: { contains: actorNombre, mode: "insensitive" as const } }),
|
||||
...(recursoId && { recursoId }),
|
||||
};
|
||||
|
||||
const [total, data] = await Promise.all([
|
||||
prisma.auditLog.count({ where }),
|
||||
prisma.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
pages: Math.ceil(total / limit),
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,43 +1,116 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { servicioCatalogoPatchSchema } from "@/lib/schemas";
|
||||
import {
|
||||
categoriaExiste,
|
||||
errorInterno,
|
||||
errorValidacion,
|
||||
sinCamposDeSoloLectura,
|
||||
serializarServicio,
|
||||
servicioCatalogoInclude,
|
||||
} from "@/lib/catalogo";
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
const noEncontrado = (id: string) =>
|
||||
NextResponse.json({ error: `No existe el servicio ${id}` }, { status: 404 });
|
||||
|
||||
// GET /api/catalogo/[id] — un servicio del catalogo.
|
||||
export async function GET(request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const servicio = await prisma.servicioCatalogo.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
fase: body.fase,
|
||||
tipoPago: body.tipoPago,
|
||||
precioBase: body.precioBase,
|
||||
tiempoEntrega: body.tiempoEntrega,
|
||||
entregablesDefault: body.entregablesDefault || [],
|
||||
variante: body.variante || null,
|
||||
nivel: body.nivel || null,
|
||||
activo: body.activo !== false,
|
||||
orden: body.orden,
|
||||
categoriaId: body.categoriaId || null,
|
||||
},
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["catalogo:leer"],
|
||||
recursoTipo: "catalogo",
|
||||
recursoId: id,
|
||||
});
|
||||
return NextResponse.json(servicio);
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const servicio = await prisma.servicioCatalogo.findUnique({
|
||||
where: { id },
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
if (!servicio) return applyHeaders(noEncontrado(id), auth.rateLimitHeaders);
|
||||
|
||||
if (auth.actor.type === "agent" && servicio.soloAdmin) {
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "catalogo.solo_admin_bloqueado",
|
||||
recursoTipo: "catalogo",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { nombre: servicio.nombre },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Este servicio esta restringido solo al administrador y no esta disponible para agentes" },
|
||||
{ status: 403 }
|
||||
),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
return applyHeaders(NextResponse.json(serializarServicio(servicio)), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
// PATCH (y PUT, por compatibilidad) /api/catalogo/[id] — edicion PARCIAL: solo
|
||||
// cambian los campos enviados. Mandar `{ "precioBase": 4500 }` no toca nada mas.
|
||||
// Las cotizaciones ya guardadas conservan su precio, entregables y tiempo de
|
||||
// entrega; el nombre del servicio si se actualiza en ellas (se lee del catalogo).
|
||||
async function actualizar(request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = servicioCatalogoPatchSchema.safeParse(sinCamposDeSoloLectura(body));
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
const data = parsed.data;
|
||||
|
||||
const existe = await prisma.servicioCatalogo.findUnique({ where: { id }, select: { id: true } });
|
||||
if (!existe) return noEncontrado(id);
|
||||
|
||||
if (data.categoriaId && !(await categoriaExiste(data.categoriaId))) {
|
||||
return NextResponse.json(
|
||||
{ error: `categoriaId: no existe la categoria ${data.categoriaId}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const servicio = await prisma.servicioCatalogo.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(serializarServicio(servicio));
|
||||
} catch (error: unknown) {
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const PATCH = actualizar;
|
||||
export const PUT = actualizar;
|
||||
|
||||
// DELETE /api/catalogo/[id] — si alguna cotizacion usa el servicio se ARCHIVA
|
||||
// (activo=false) para no romper esas cotizaciones; si no, se borra.
|
||||
// Respuesta: { ok: true, archived: boolean }.
|
||||
export async function DELETE(_request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const { id } = await params;
|
||||
const existe = await prisma.servicioCatalogo.findUnique({ where: { id }, select: { id: true } });
|
||||
if (!existe) return noEncontrado(id);
|
||||
|
||||
const inUse = await prisma.servicioCotizado.count({
|
||||
where: { servicioCatalogoId: id },
|
||||
});
|
||||
@@ -48,10 +121,10 @@ export async function DELETE(
|
||||
});
|
||||
return NextResponse.json({ ok: true, archived: true });
|
||||
}
|
||||
// ServicioPaquete cae en cascada: el servicio sale de los paquetes.
|
||||
await prisma.servicioCatalogo.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true, archived: false });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,107 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { servicioCatalogoSchema } from "@/lib/schemas";
|
||||
import {
|
||||
categoriaExiste,
|
||||
errorInterno,
|
||||
errorValidacion,
|
||||
sinCamposDeSoloLectura,
|
||||
serializarServicio,
|
||||
servicioCatalogoInclude,
|
||||
siguienteOrden,
|
||||
} from "@/lib/catalogo";
|
||||
|
||||
export async function GET() {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const servicios = await prisma.servicioCatalogo.findMany({
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["catalogo:leer"],
|
||||
recursoTipo: "catalogo",
|
||||
});
|
||||
return NextResponse.json(servicios);
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const sp = request.nextUrl.searchParams;
|
||||
const q = sp.get("q")?.trim();
|
||||
const fase = sp.get("fase");
|
||||
const tipoPago = sp.get("tipoPago");
|
||||
const categoriaId = sp.get("categoriaId");
|
||||
const activo = sp.get("activo");
|
||||
|
||||
if (fase !== null && !/^[0-3]$/.test(fase)) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "fase debe ser 0, 1, 2 o 3" }, { status: 400 }),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
if (tipoPago !== null && tipoPago !== "unico" && tipoPago !== "mensual") {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "tipoPago debe ser 'unico' o 'mensual'" }, { status: 400 }),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const esAgente = auth.actor.type === "agent";
|
||||
const servicios = await prisma.servicioCatalogo.findMany({
|
||||
where: {
|
||||
...(esAgente && { soloAdmin: false }),
|
||||
...(q && {
|
||||
OR: [
|
||||
{ nombre: { contains: q, mode: "insensitive" as const } },
|
||||
{ descripcion: { contains: q, mode: "insensitive" as const } },
|
||||
],
|
||||
}),
|
||||
...(fase !== null && { fase: Number(fase) }),
|
||||
...(tipoPago && { tipoPago }),
|
||||
...(categoriaId && { categoriaId }),
|
||||
...(activo === "true" && { activo: true }),
|
||||
...(activo === "false" && { activo: false }),
|
||||
},
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return applyHeaders(NextResponse.json(servicios.map(serializarServicio)), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = servicioCatalogoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "catalogo" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = servicioCatalogoSchema.safeParse(sinCamposDeSoloLectura(body));
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
const data = parsed.data;
|
||||
|
||||
if (data.categoriaId && !(await categoriaExiste(data.categoriaId))) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ error: `categoriaId: no existe la categoria ${data.categoriaId}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const servicio = await prisma.servicioCatalogo.create({
|
||||
data: {
|
||||
nombre: parsed.data.nombre,
|
||||
descripcion: parsed.data.descripcion,
|
||||
fase: parsed.data.fase,
|
||||
tipoPago: parsed.data.tipoPago,
|
||||
precioBase: parsed.data.precioBase,
|
||||
tiempoEntrega: parsed.data.tiempoEntrega,
|
||||
entregablesDefault: parsed.data.entregablesDefault,
|
||||
categoriaId: parsed.data.categoriaId,
|
||||
variante: parsed.data.variante,
|
||||
nivel: parsed.data.nivel ?? null,
|
||||
activo: true,
|
||||
orden: parsed.data.orden,
|
||||
nombre: data.nombre,
|
||||
descripcion: data.descripcion ?? null,
|
||||
fase: data.fase,
|
||||
tipoPago: data.tipoPago,
|
||||
precioBase: data.precioBase,
|
||||
tiempoEntrega: data.tiempoEntrega,
|
||||
entregablesDefault: data.entregablesDefault,
|
||||
categoriaId: data.categoriaId ?? null,
|
||||
variante: data.variante ?? null,
|
||||
nivel: data.nivel ?? null,
|
||||
activo: data.activo ?? true,
|
||||
soloAdmin: data.soloAdmin ?? false,
|
||||
orden: data.orden ?? (await siguienteOrden(data.fase)),
|
||||
},
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(servicio, { status: 201 });
|
||||
return NextResponse.json(serializarServicio(servicio), { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
|
||||
export async function GET() {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["catalogo:leer"],
|
||||
recursoTipo: "categoria",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const cats = await prisma.categoria.findMany({ orderBy: { orden: "asc" } });
|
||||
return NextResponse.json(cats);
|
||||
return applyHeaders(NextResponse.json(cats), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
@@ -13,6 +20,9 @@ export async function GET() {
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "categoria" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await request.json();
|
||||
const cat = await prisma.categoria.create({
|
||||
data: {
|
||||
|
||||
@@ -49,6 +49,12 @@ export async function POST(
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
if (pago.estado === ESTADOS_PAGO.ANULADO) {
|
||||
return NextResponse.json(
|
||||
{ error: "Este cobro quedó sin cargo; no necesitas pagarlo." },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
const file = formData.get("file");
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
const archivarSchema = z.object({
|
||||
archivado: z.boolean().default(true),
|
||||
incluirCotizaciones: z.boolean().default(true),
|
||||
});
|
||||
|
||||
// POST /api/clientes/[id]/archivar — archivo reversible (sin borrado definitivo).
|
||||
// Reservado a personal humano (staffOnly).
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
staffOnly: true,
|
||||
accionBloqueo: "cliente.archivar_bloqueado",
|
||||
recursoTipo: "cliente",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const parsed = archivarSchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const cliente = await prisma.cliente.findUnique({ where: { id }, select: { id: true, nombre: true, empresa: true } });
|
||||
if (!cliente) {
|
||||
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
|
||||
}
|
||||
|
||||
const now = parsed.data.archivado ? new Date() : null;
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const updatedCliente = await tx.cliente.update({
|
||||
where: { id },
|
||||
data: { archivado: parsed.data.archivado, archivadoAt: now },
|
||||
select: { id: true, nombre: true, empresa: true, archivado: true, archivadoAt: true },
|
||||
});
|
||||
|
||||
let cotizacionesActualizadas = 0;
|
||||
if (parsed.data.incluirCotizaciones) {
|
||||
const res = await tx.cotizacion.updateMany({
|
||||
where: { clienteId: id },
|
||||
data: { archivado: parsed.data.archivado, archivadoAt: now },
|
||||
});
|
||||
cotizacionesActualizadas = res.count;
|
||||
}
|
||||
|
||||
return { cliente: updatedCliente, cotizacionesActualizadas };
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: parsed.data.archivado ? "cliente.archivar" : "cliente.desarchivar",
|
||||
recursoTipo: "cliente",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa,
|
||||
cotizacionesActualizadas: result.cotizacionesActualizadas,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true, ...result });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { clienteSchema } from "@/lib/schemas";
|
||||
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
||||
|
||||
// PATCH /api/clientes/[id] — edita los datos del cliente.
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["clientes:escribir"],
|
||||
recursoTipo: "cliente",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const previo = await prisma.cliente.findUnique({ where: { id }, select: { id: true } });
|
||||
if (!previo) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = clienteSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
if (await buscarDuplicado(data.nombre, data.empresa, id)) {
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: mensajeDuplicado(data.nombre, data.empresa) },
|
||||
{ status: 409 }
|
||||
),
|
||||
auth.rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const cliente = await prisma.cliente.update({
|
||||
where: { id },
|
||||
data,
|
||||
select: clienteSelect,
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "cliente.actualizar",
|
||||
recursoTipo: "cliente",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { nombre: cliente.nombre, empresa: cliente.empresa },
|
||||
});
|
||||
|
||||
return applyHeaders(NextResponse.json(cliente), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { clienteSchema } from "@/lib/schemas";
|
||||
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
||||
|
||||
// GET /api/clientes — lista de clientes. ?q=texto busca en nombre, empresa,
|
||||
// email y RFC.
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["clientes:leer"],
|
||||
recursoTipo: "cliente",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const q = request.nextUrl.searchParams.get("q")?.trim();
|
||||
const incluirArchivados =
|
||||
auth.actor.type !== "agent" && request.nextUrl.searchParams.get("incluirArchivados") === "true";
|
||||
const clientes = await prisma.cliente.findMany({
|
||||
where: {
|
||||
...(!incluirArchivados && { archivado: false }),
|
||||
...(q
|
||||
? {
|
||||
OR: [
|
||||
{ nombre: { contains: q, mode: "insensitive" } },
|
||||
{ empresa: { contains: q, mode: "insensitive" } },
|
||||
{ email: { contains: q, mode: "insensitive" } },
|
||||
{ rfc: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: { nombre: "asc" },
|
||||
select: clienteSelect,
|
||||
});
|
||||
return applyHeaders(NextResponse.json(clientes), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/clientes — alta directa de un cliente (staff o agente con clientes:escribir).
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["clientes:escribir"],
|
||||
recursoTipo: "cliente",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||
|
||||
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||
const parsed = clienteSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
if (await buscarDuplicado(data.nombre, data.empresa)) {
|
||||
return NextResponse.json(
|
||||
{ error: mensajeDuplicado(data.nombre, data.empresa) },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const cliente = await prisma.cliente.create({ data, select: clienteSelect });
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cliente.crear",
|
||||
recursoTipo: "cliente",
|
||||
recursoId: cliente.id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { nombre: cliente.nombre, empresa: cliente.empresa },
|
||||
});
|
||||
|
||||
return NextResponse.json(cliente, { status: 201 });
|
||||
});
|
||||
|
||||
return applyHeaders(res, rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { ESTADOS_PAGO, esPorPagar } from "@/lib/cobros";
|
||||
import { anularPagoSchema } from "@/lib/schemas";
|
||||
|
||||
// POST /api/cobros/pagos/[id]/anular — deja un cobro sin cargo (semana sin
|
||||
// servicio, cortesia). No se borra: el registro (programaId, fecha) impide que
|
||||
// generarCobros() lo vuelva a crear. Se deshace con /reabrir.
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const parsed = anularPagoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const pago = await prisma.pagoRecurrente.findUnique({ where: { id } });
|
||||
if (!pago) {
|
||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
}
|
||||
if (!esPorPagar(pago.estado)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Solo se pueden anular cobros pendientes o rechazados" },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const actualizado = await prisma.pagoRecurrente.update({
|
||||
where: { id },
|
||||
data: {
|
||||
estado: ESTADOS_PAGO.ANULADO,
|
||||
rechazadoAt: null,
|
||||
rechazoMotivo: null,
|
||||
nota: parsed.data.motivo,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(actualizado);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
import { ESTADOS_PAGO } from "@/lib/cobros";
|
||||
import { notificarVerificacion } from "@/lib/notificaciones";
|
||||
|
||||
// POST /api/cobros/pagos/[id]/aprobar — valida un comprobante en revision.
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
staffOnly: true,
|
||||
recursoTipo: "pago_recurrente",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const pago = await prisma.pagoRecurrente.findUnique({ where: { id } });
|
||||
const pago = await prisma.pagoRecurrente.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
programa: {
|
||||
include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true, telefono: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!pago) {
|
||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
}
|
||||
@@ -40,6 +49,28 @@ export async function POST(
|
||||
|
||||
await notificarVerificacion(id);
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "pago.aprobar_comprobante",
|
||||
recursoTipo: "pago_recurrente",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { programaId: pago.programaId, monto: pago.monto },
|
||||
});
|
||||
|
||||
void emitirWebhook("pago.registrado", {
|
||||
pagoId: actualizado.id,
|
||||
programaId: pago.programaId,
|
||||
concepto: pago.programa.concepto,
|
||||
monto: actualizado.monto,
|
||||
moneda: pago.programa.moneda,
|
||||
fechaCobro: actualizado.fecha.toISOString().slice(0, 10),
|
||||
verificadoAt: actualizado.verificadoAt?.toISOString() ?? null,
|
||||
metodo: "comprobante_verificado",
|
||||
cliente: pago.programa.cliente,
|
||||
});
|
||||
|
||||
return NextResponse.json(actualizado);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { ESTADOS_PAGO } from "@/lib/cobros";
|
||||
|
||||
// POST /api/cobros/pagos/[id]/reabrir — deshace un pago registrado a mano o una
|
||||
// anulacion: el cobro vuelve a pendiente. Un pago verificado CON comprobante no
|
||||
// se reabre aqui (el comprobante es la prueba del cliente; se rechaza antes de
|
||||
// aprobar, no despues).
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const pago = await prisma.pagoRecurrente.findUnique({
|
||||
where: { id },
|
||||
include: { comprobante: { select: { id: true } } },
|
||||
});
|
||||
if (!pago) {
|
||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
}
|
||||
const manual = pago.estado === ESTADOS_PAGO.VERIFICADO && !pago.comprobante;
|
||||
if (!manual && pago.estado !== ESTADOS_PAGO.ANULADO) {
|
||||
return NextResponse.json(
|
||||
{ error: "Solo se reabren pagos registrados a mano o cobros anulados" },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const actualizado = await prisma.pagoRecurrente.update({
|
||||
where: { id },
|
||||
data: { estado: ESTADOS_PAGO.PENDIENTE, verificadoAt: null, nota: null },
|
||||
});
|
||||
|
||||
return NextResponse.json(actualizado);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
import {
|
||||
ESTADOS_PAGO,
|
||||
esPorPagar,
|
||||
hoyCalendario,
|
||||
instanteDePago,
|
||||
parseFechaCalendario,
|
||||
} from "@/lib/cobros";
|
||||
import { registrarPagoSchema } from "@/lib/schemas";
|
||||
import { notificarVerificacion } from "@/lib/notificaciones";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cobros:registrar"],
|
||||
recursoTipo: "pago_recurrente",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||
|
||||
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||
const parsed = registrarPagoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const fechaPago = parseFechaCalendario(parsed.data.fecha);
|
||||
if (fechaPago > hoyCalendario()) {
|
||||
return NextResponse.json(
|
||||
{ error: "La fecha de pago no puede ser futura" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const pago = await prisma.pagoRecurrente.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
programa: {
|
||||
include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true, telefono: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!pago) {
|
||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
}
|
||||
if (!esPorPagar(pago.estado)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Solo se pueden registrar cobros pendientes o rechazados" },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const actualizado = await prisma.pagoRecurrente.update({
|
||||
where: { id },
|
||||
data: {
|
||||
estado: ESTADOS_PAGO.VERIFICADO,
|
||||
verificadoAt: instanteDePago(fechaPago),
|
||||
rechazadoAt: null,
|
||||
rechazoMotivo: null,
|
||||
nota: parsed.data.nota || null,
|
||||
},
|
||||
});
|
||||
|
||||
await notificarVerificacion(id);
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "pago.registrar",
|
||||
recursoTipo: "pago_recurrente",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
programaId: pago.programaId,
|
||||
monto: pago.monto,
|
||||
fechaPago: parsed.data.fecha,
|
||||
},
|
||||
});
|
||||
|
||||
void emitirWebhook("pago.registrado", {
|
||||
pagoId: actualizado.id,
|
||||
programaId: pago.programaId,
|
||||
concepto: pago.programa.concepto,
|
||||
monto: actualizado.monto,
|
||||
moneda: pago.programa.moneda,
|
||||
fechaCobro: actualizado.fecha.toISOString().slice(0, 10),
|
||||
verificadoAt: actualizado.verificadoAt?.toISOString() ?? null,
|
||||
metodo: "registro_manual",
|
||||
cliente: pago.programa.cliente,
|
||||
});
|
||||
|
||||
return NextResponse.json(actualizado);
|
||||
});
|
||||
|
||||
return applyHeaders(res, rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { parseFechaCalendario } from "@/lib/cobros";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { ESTADOS_POR_PAGAR, parseFechaCalendario } from "@/lib/cobros";
|
||||
|
||||
// GET /api/cobros/pagos?estado=&programaId=&desde=&hasta=
|
||||
// Pagos ordenados por fecha desc con programa+cliente y comprobante.
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cobros:leer"],
|
||||
recursoTipo: "pago_recurrente",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const estado = searchParams.get("estado");
|
||||
const clienteId = searchParams.get("clienteId");
|
||||
const programaId = searchParams.get("programaId");
|
||||
const desde = searchParams.get("desde");
|
||||
const hasta = searchParams.get("hasta");
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
if (estado) where.estado = estado;
|
||||
if (estado === "por_pagar") where.estado = { in: ESTADOS_POR_PAGAR };
|
||||
else if (estado) where.estado = estado;
|
||||
if (clienteId) where.programa = { clienteId };
|
||||
if (programaId) where.programaId = programaId;
|
||||
if (desde || hasta) {
|
||||
where.fecha = {
|
||||
@@ -43,7 +45,7 @@ export async function GET(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(pagos);
|
||||
return applyHeaders(NextResponse.json(pagos), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { programaPagoSchema } from "@/lib/schemas";
|
||||
import { parseFechaCalendario, proximaFecha } from "@/lib/cobros";
|
||||
|
||||
// GET /api/cobros/programas — lista programas con cliente, conteo de pagos y
|
||||
// proxima fecha calculada. Solo staff.
|
||||
export async function GET() {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cobros:leer"],
|
||||
recursoTipo: "programa_pago",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const programas = await prisma.programaPago.findMany({
|
||||
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
||||
@@ -29,20 +28,17 @@ export async function GET() {
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json(salida);
|
||||
return applyHeaders(NextResponse.json(salida), auth.rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/cobros/programas — crea un programa de pago recurrente.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
const auth = await requireActor(request, { staffOnly: true, recursoTipo: "programa_pago" });
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = programaPagoSchema.safeParse(body);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { smtpConfigurado } from "@/lib/email";
|
||||
import { pushConfigurado } from "@/lib/push";
|
||||
import { enviarRecordatoriosPendientes } from "@/lib/notificaciones";
|
||||
|
||||
const recordatoriosSchema = z.object({
|
||||
clienteId: z.string().min(1, "Cliente invalido").optional(),
|
||||
});
|
||||
|
||||
// POST /api/cobros/recordatorios — envia YA el recordatorio de pagos pendientes
|
||||
// (estado de cuenta por correo+push) a un cliente o a todos los que deben.
|
||||
// Es el envio manual: ignora la espera de COBROS_RECORDATORIO_DIAS que respeta
|
||||
// el scheduler.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const raw = await request.json().catch(() => ({}));
|
||||
const parsed = recordatoriosSchema.safeParse(raw ?? {});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const resultados = await enviarRecordatoriosPendientes({
|
||||
clienteId: parsed.data.clienteId,
|
||||
forzar: true,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
resultados,
|
||||
// Para que la UI explique por que no salio nada en lugar de fingir exito.
|
||||
canales: { correo: smtpConfigurado(), push: pushConfigurado() },
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
import { calcularTotalesCotizacion } from "@/lib/calculators";
|
||||
import { appBaseUrl } from "@/lib/aprobacion";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
adminOnly: true,
|
||||
accionBloqueo: "cotizacion.aprobar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
if (actor.type !== "user" || actor.role !== "admin") {
|
||||
return NextResponse.json({ error: "Solo un administrador humano puede aprobar" }, { status: 403 });
|
||||
}
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, servicios: true },
|
||||
});
|
||||
if (!cot) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
if (cot.estado !== "borrador") {
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: `Solo se pueden aprobar cotizaciones en borrador (estado actual: ${cot.estado})` },
|
||||
{ status: 409 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
await tx.approvalToken.updateMany({
|
||||
where: { cotizacionId: id, usadoAt: null },
|
||||
data: { expiraAt: now },
|
||||
});
|
||||
|
||||
return tx.cotizacion.update({
|
||||
where: { id },
|
||||
data: {
|
||||
estado: "aprobada",
|
||||
aprobadaPorId: actor.userId,
|
||||
aprobadaAt: now,
|
||||
aprobacionMetodo: "web_admin",
|
||||
},
|
||||
include: { cliente: true },
|
||||
});
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.aprobar",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
numero: updated.numero,
|
||||
metodo: "web_admin",
|
||||
},
|
||||
});
|
||||
|
||||
const tot = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
|
||||
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||
|
||||
void emitirWebhook("cotizacion.aprobada", {
|
||||
cotizacionId: updated.id,
|
||||
numero: updated.numero,
|
||||
folio: updated.numero,
|
||||
titulo: updated.proyecto,
|
||||
proyecto: updated.proyecto,
|
||||
moneda: updated.moneda,
|
||||
total: totalWebhook,
|
||||
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||
estado: "aprobada",
|
||||
aprobadaAt: now.toISOString(),
|
||||
aprobadaPorId: actor.userId,
|
||||
aprobacionMetodo: "web_admin",
|
||||
cliente: {
|
||||
id: updated.cliente.id,
|
||||
nombre: updated.cliente.nombre,
|
||||
empresa: updated.cliente.empresa,
|
||||
email: updated.cliente.email,
|
||||
telefono: updated.cliente.telefono,
|
||||
},
|
||||
});
|
||||
|
||||
return applyHeaders(
|
||||
NextResponse.json({
|
||||
ok: true,
|
||||
id: updated.id,
|
||||
numero: updated.numero,
|
||||
estado: updated.estado,
|
||||
aprobadaAt: updated.aprobadaAt,
|
||||
aprobacionMetodo: updated.aprobacionMetodo,
|
||||
}),
|
||||
rateLimitHeaders
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
applyHeaders,
|
||||
coincideContacto,
|
||||
requireActor,
|
||||
} from "@/lib/agent-auth";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { generarPDFCotizacion } from "@/lib/cotizacion-pdf";
|
||||
import { enviarCotizacionPorCorreo } from "@/lib/email";
|
||||
import {
|
||||
appBaseUrl,
|
||||
notificarJarethWhatsAppFueraVentana,
|
||||
} from "@/lib/aprobacion";
|
||||
import {
|
||||
emitirWebhook,
|
||||
invocarEnvioWhatsAppN8n,
|
||||
} from "@/lib/webhooks";
|
||||
import {
|
||||
calcularTotalesCotizacion,
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
} from "@/lib/calculators";
|
||||
|
||||
const enviarSchema = z.object({
|
||||
canal: z.enum(["email", "whatsapp_chatwoot", "manual"]).default("whatsapp_chatwoot"),
|
||||
destino: z.string().trim().optional(),
|
||||
mensaje: z.string().trim().max(2000).optional(),
|
||||
verificarContacto: z.string().trim().optional(),
|
||||
chatwootConversationId: z.union([z.number().int(), z.string()]).optional(),
|
||||
fallbackEmail: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:enviar"],
|
||||
accionBloqueo: "cotizacion.enviar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||
|
||||
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||
const parsed = enviarSchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
servicios: true,
|
||||
},
|
||||
});
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
// GUARDIA DURA: ninguna cotizacion sale sin aprobacion humana previa
|
||||
if (cot.estado !== "aprobada" || !cot.aprobadaAt) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: {
|
||||
estadoActual: cot.estado,
|
||||
aprobadaAt: cot.aprobadaAt,
|
||||
motivo: "no_aprobada",
|
||||
},
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||
estadoActual: cot.estado,
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Verificacion de identidad del contacto (anti-fuga entre prospectos)
|
||||
if (data.verificarContacto && !coincideContacto(data.verificarContacto, cot.cliente)) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_contacto_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { motivo: "verificarContacto_no_coincide" },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "El contacto proporcionado no coincide con el cliente de esta cotizacion" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
let canalFinal: "email" | "whatsapp_chatwoot" | "manual" = data.canal;
|
||||
let destinoFinal = "";
|
||||
|
||||
const totales = calcularTotalesCotizacion(cot.servicios, {
|
||||
incluirIva: cot.incluirIva,
|
||||
});
|
||||
const partesResumen: string[] = [];
|
||||
if (totales.totalUnico > 0) partesResumen.push(`Único: ${formatCurrency(totales.totalUnico)}`);
|
||||
if (totales.totalMensual > 0) partesResumen.push(`Mensual: ${formatCurrency(totales.totalMensual)}/mes`);
|
||||
const resumenTotales = partesResumen.length ? partesResumen.join(" · ") : "$0";
|
||||
const vigenciaTexto = formatDate(cot.vigencia);
|
||||
|
||||
if (data.canal === "manual") {
|
||||
if (actor.type !== "user" || actor.role !== "admin") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { motivo: "manual_solo_admin" },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "El registro de envio manual esta reservado al administrador humano" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
destinoFinal = data.destino || cot.cliente.email || cot.cliente.telefono || "manual";
|
||||
} else if (data.canal === "email") {
|
||||
destinoFinal = (data.destino || cot.cliente.email || "").trim();
|
||||
if (!destinoFinal) {
|
||||
return NextResponse.json(
|
||||
{ error: "El cliente no tiene correo electronico registrado y no se proporciono destino" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const pdf = await generarPDFCotizacion(id);
|
||||
if (!pdf) {
|
||||
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
||||
}
|
||||
|
||||
const envio = await enviarCotizacionPorCorreo({
|
||||
to: destinoFinal,
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
empresa: cot.cliente.empresa,
|
||||
proyecto: cot.proyecto,
|
||||
resumenTotales,
|
||||
vigenciaTexto,
|
||||
pdfBuffer: pdf.buffer,
|
||||
pdfFilename: pdf.filename,
|
||||
mensajePersonalizado: data.mensaje,
|
||||
});
|
||||
|
||||
if (!envio.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_error",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { canal: "email", destino: destinoFinal, omitido: envio.omitido, error: envio.error },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: envio.omitido
|
||||
? "SMTP no esta configurado en el servidor"
|
||||
: `Fallo el envio por correo: ${envio.error || "error desconocido"}`,
|
||||
omitido: envio.omitido ?? false,
|
||||
},
|
||||
{ status: envio.omitido ? 503 : 502 }
|
||||
);
|
||||
}
|
||||
} else if (data.canal === "whatsapp_chatwoot") {
|
||||
destinoFinal = (data.destino || cot.cliente.telefono || "").trim();
|
||||
const pdf = await generarPDFCotizacion(id);
|
||||
if (!pdf) {
|
||||
return NextResponse.json({ error: "No se pudo generar el PDF" }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!destinoFinal) {
|
||||
if (data.fallbackEmail && cot.cliente.email) {
|
||||
const emailRes = await enviarCotizacionPorCorreo({
|
||||
to: cot.cliente.email,
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
empresa: cot.cliente.empresa,
|
||||
proyecto: cot.proyecto,
|
||||
resumenTotales,
|
||||
vigenciaTexto,
|
||||
pdfBuffer: pdf.buffer,
|
||||
pdfFilename: pdf.filename,
|
||||
mensajePersonalizado: data.mensaje,
|
||||
});
|
||||
if (!emailRes.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `El cliente no tiene telefono y fallo el respaldo por correo: ${emailRes.error || "SMTP no disponible"}`,
|
||||
reason: "missing_phone_fallback_failed",
|
||||
},
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
canalFinal = "email";
|
||||
destinoFinal = cot.cliente.email;
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: "El cliente no tiene telefono registrado y no se proporciono destino" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
} else {
|
||||
|
||||
const mensajeWa =
|
||||
data.mensaje?.trim() ||
|
||||
`Hola ${cot.cliente.nombre}, te compartimos la cotización ${cot.numero} para ${cot.proyecto} (${resumenTotales}, vigencia al ${vigenciaTexto}).`;
|
||||
|
||||
const waRes = await invocarEnvioWhatsAppN8n({
|
||||
cotizacionId: cot.id,
|
||||
numero: cot.numero,
|
||||
folio: cot.numero,
|
||||
estado: cot.estado,
|
||||
aprobadaAt: cot.aprobadaAt ? cot.aprobadaAt.toISOString() : null,
|
||||
cliente: {
|
||||
nombre: cot.cliente.nombre,
|
||||
empresa: cot.cliente.empresa,
|
||||
telefono: cot.cliente.telefono,
|
||||
email: cot.cliente.email,
|
||||
},
|
||||
destino: destinoFinal,
|
||||
chatwootConversationId: data.chatwootConversationId ?? null,
|
||||
mensaje: mensajeWa,
|
||||
pdfFilename: pdf.filename,
|
||||
pdfBase64: pdf.buffer.toString("base64"),
|
||||
pdfUrl: `${appBaseUrl()}/api/export/pdf/${cot.id}`,
|
||||
});
|
||||
|
||||
if (!waRes.delivered) {
|
||||
if (waRes.reason === "outside_24h_window") {
|
||||
if (data.fallbackEmail && cot.cliente.email) {
|
||||
const emailRes = await enviarCotizacionPorCorreo({
|
||||
to: cot.cliente.email,
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
empresa: cot.cliente.empresa,
|
||||
proyecto: cot.proyecto,
|
||||
resumenTotales,
|
||||
vigenciaTexto,
|
||||
pdfBuffer: pdf.buffer,
|
||||
pdfFilename: pdf.filename,
|
||||
mensajePersonalizado: data.mensaje,
|
||||
});
|
||||
if (!emailRes.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `WhatsApp fuera de ventana de 24h y fallo el respaldo por correo: ${emailRes.error || "SMTP no disponible"}`,
|
||||
reason: "outside_24h_window",
|
||||
},
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
canalFinal = "email";
|
||||
destinoFinal = cot.cliente.email;
|
||||
} else {
|
||||
const notificadoJareth = await notificarJarethWhatsAppFueraVentana(
|
||||
cot,
|
||||
destinoFinal,
|
||||
waRes.error
|
||||
);
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_fuera_ventana",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { canal: "whatsapp_chatwoot", destino: destinoFinal, notificadoJareth },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Fuera de ventana de 24h en WhatsApp",
|
||||
reason: "outside_24h_window",
|
||||
notificadoJareth,
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
} else {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar_error",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { canal: "whatsapp_chatwoot", destino: destinoFinal, reason: waRes.reason, error: waRes.error },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: waRes.error || "Fallo el envio por WhatsApp",
|
||||
reason: waRes.reason || "whatsapp_error",
|
||||
},
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const enviadaPor =
|
||||
actor.type === "agent" ? `agent:${actor.nombre}` : `user:${actor.email || actor.userId}`;
|
||||
|
||||
const updated = await prisma.cotizacion.update({
|
||||
where: { id },
|
||||
data: {
|
||||
estado: "enviada",
|
||||
enviadaAt: now,
|
||||
enviadaPor,
|
||||
enviadaCanal: canalFinal,
|
||||
enviadaDestino: destinoFinal,
|
||||
},
|
||||
include: { cliente: true },
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.enviar",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
numero: updated.numero,
|
||||
canal: canalFinal,
|
||||
destino: destinoFinal,
|
||||
fallbackUsado: data.canal === "whatsapp_chatwoot" && canalFinal === "email",
|
||||
},
|
||||
});
|
||||
|
||||
const totalWebhook = Number((totales.totalUnico + totales.totalMensual).toFixed(2));
|
||||
|
||||
void emitirWebhook("cotizacion.enviada", {
|
||||
cotizacionId: updated.id,
|
||||
numero: updated.numero,
|
||||
folio: updated.numero,
|
||||
titulo: updated.proyecto,
|
||||
proyecto: updated.proyecto,
|
||||
moneda: updated.moneda,
|
||||
total: totalWebhook,
|
||||
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||
estado: "enviada",
|
||||
enviadaAt: now.toISOString(),
|
||||
enviadaPor,
|
||||
enviadaCanal: canalFinal,
|
||||
enviadaDestino: destinoFinal,
|
||||
cliente: {
|
||||
id: updated.cliente.id,
|
||||
nombre: updated.cliente.nombre,
|
||||
empresa: updated.cliente.empresa,
|
||||
email: updated.cliente.email,
|
||||
telefono: updated.cliente.telefono,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
id: updated.id,
|
||||
numero: updated.numero,
|
||||
estado: updated.estado,
|
||||
enviadaAt: updated.enviadaAt,
|
||||
enviadaCanal: updated.enviadaCanal,
|
||||
enviadaDestino: updated.enviadaDestino,
|
||||
enviadaPor: updated.enviadaPor,
|
||||
});
|
||||
});
|
||||
|
||||
return applyHeaders(res, rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { calcularTotalesCotizacion, ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { appBaseUrl, validarTransicionEstado } from "@/lib/aprobacion";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
||||
|
||||
const estadoSchema = z.object({
|
||||
estado: z.enum(ESTADOS_COTIZACION),
|
||||
});
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
staffOnly: true,
|
||||
accionBloqueo: "cotizacion.estado_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = estadoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: `Estado invalido. Permitidos: ${ESTADOS_COTIZACION.join(", ")}` },
|
||||
{ status: 400 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const nuevoEstado = parsed.data.estado;
|
||||
|
||||
const existing = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, servicios: true },
|
||||
});
|
||||
if (!existing) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const validacion = validarTransicionEstado({
|
||||
actual: existing.estado,
|
||||
nuevo: nuevoEstado,
|
||||
actor,
|
||||
viaEndpoint: "estado",
|
||||
aprobadaAt: existing.aprobadaAt,
|
||||
});
|
||||
if (!validacion.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion:
|
||||
nuevoEstado === "aprobada"
|
||||
? "cotizacion.aprobar_bloqueado"
|
||||
: "cotizacion.estado_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { actual: existing.estado, intento: nuevoEstado, error: validacion.error },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updateData: Record<string, unknown> = { estado: nuevoEstado };
|
||||
if (nuevoEstado === "aprobada") {
|
||||
updateData.aprobadaAt = now;
|
||||
updateData.aprobadaPorId = actor.type === "user" ? actor.userId : null;
|
||||
updateData.aprobacionMetodo = "web_admin";
|
||||
} else if (nuevoEstado === "borrador") {
|
||||
updateData.aprobadaAt = null;
|
||||
updateData.aprobadaPorId = null;
|
||||
updateData.aprobacionMetodo = null;
|
||||
} else if (nuevoEstado === "aceptada") {
|
||||
updateData.aceptadaAt = now;
|
||||
} else if (nuevoEstado === "rechazada") {
|
||||
updateData.rechazadaAt = now;
|
||||
} else if (nuevoEstado === "vencida") {
|
||||
updateData.vencidaAt = now;
|
||||
} else if (nuevoEstado === "enviada") {
|
||||
updateData.enviadaAt = now;
|
||||
updateData.enviadaCanal = "manual";
|
||||
updateData.enviadaPor = actor.type === "user" ? `user:${actor.email || actor.userId}` : null;
|
||||
}
|
||||
|
||||
const updated = await prisma.cotizacion.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: `cotizacion.estado_${nuevoEstado}`,
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { anterior: existing.estado, nuevo: nuevoEstado },
|
||||
});
|
||||
|
||||
const mapEvento: Partial<Record<string, EventoWebhook>> = {
|
||||
aprobada: "cotizacion.aprobada",
|
||||
enviada: "cotizacion.enviada",
|
||||
aceptada: "cotizacion.aceptada",
|
||||
rechazada: "cotizacion.rechazada",
|
||||
vencida: "cotizacion.vencida",
|
||||
};
|
||||
const ev = mapEvento[nuevoEstado];
|
||||
if (ev && nuevoEstado !== existing.estado) {
|
||||
const tot = calcularTotalesCotizacion(existing.servicios, { incluirIva: existing.incluirIva });
|
||||
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||
void emitirWebhook(ev, {
|
||||
cotizacionId: updated.id,
|
||||
numero: updated.numero,
|
||||
folio: updated.numero,
|
||||
titulo: updated.proyecto,
|
||||
proyecto: updated.proyecto,
|
||||
moneda: updated.moneda,
|
||||
total: totalWebhook,
|
||||
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||
estado: updated.estado,
|
||||
timestamp: now.toISOString(),
|
||||
cliente: {
|
||||
id: existing.cliente.id,
|
||||
nombre: existing.cliente.nombre,
|
||||
empresa: existing.cliente.empresa,
|
||||
email: existing.cliente.email,
|
||||
telefono: existing.cliente.telefono,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { z } from "zod";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
const schema = z.object({
|
||||
servicioId: z.string().min(1),
|
||||
@@ -13,12 +15,54 @@ export async function PATCH(
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:borrador"],
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, estado: true },
|
||||
});
|
||||
if (!cot) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
if (actor.type === "agent" && cot.estado !== "borrador") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.editar_precio_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { estadoActual: cot.estado },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Los agentes solo pueden modificar precios en cotizaciones en borrador" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,7 +73,10 @@ export async function PATCH(
|
||||
});
|
||||
|
||||
if (!serv) {
|
||||
return NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 });
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.servicioCotizado.update({
|
||||
@@ -37,7 +84,17 @@ export async function PATCH(
|
||||
data: { precio },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.actualizar_precio",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { servicioId, precioAnterior: serv.precio, precioNuevo: precio },
|
||||
});
|
||||
|
||||
return applyHeaders(NextResponse.json({ ok: true }), rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
|
||||
@@ -2,6 +2,17 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||
import { cotizacionPutSchema } from "@/lib/schemas";
|
||||
import { asesorPublicoSelect } from "@/lib/cotizaciones";
|
||||
import {
|
||||
applyHeaders,
|
||||
coincideContacto,
|
||||
esAgenteSoloAceptadas,
|
||||
requireActor,
|
||||
} from "@/lib/agent-auth";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { appBaseUrl, validarTransicionEstado } from "@/lib/aprobacion";
|
||||
import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks";
|
||||
import { evaluarRestriccionSoloAdmin } from "@/lib/solo-admin-core";
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
@@ -9,15 +20,30 @@ export async function DELETE(
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
staffOnly: true,
|
||||
accionBloqueo: "cotizacion.eliminar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({ where: { id } });
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.cotizacion.delete({ where: { id } }),
|
||||
]);
|
||||
await prisma.$transaction([prisma.cotizacion.delete({ where: { id } })]);
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: auth.actor,
|
||||
accion: "cotizacion.eliminar",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { numero: cot.numero },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
@@ -32,61 +58,283 @@ export async function GET(
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:leer", "cotizaciones:leer_aceptadas"],
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const soloAceptadas = esAgenteSoloAceptadas(actor);
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
asesor: { select: asesorPublicoSelect },
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
return NextResponse.json(cot);
|
||||
|
||||
if (soloAceptadas && cot.estado !== "aceptada") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.leer_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { estadoActual: cot.estado },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Tu clave solo permite consultar cotizaciones aceptadas" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const verificarContacto = request.nextUrl.searchParams.get("verificarContacto")?.trim();
|
||||
if (verificarContacto && !coincideContacto(verificarContacto, cot.cliente)) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.verificar_contacto_fallo",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { motivo: "contacto_no_coincide" },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "El contacto verificado no coincide con el cliente de esta cotizacion" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const salida = soloAceptadas ? { ...cot, observacionesInternas: null } : cot;
|
||||
return applyHeaders(NextResponse.json(salida), rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function datosPorTransicion(nuevoEstado: string, actorUserId?: string) {
|
||||
const now = new Date();
|
||||
if (nuevoEstado === "aprobada") {
|
||||
return {
|
||||
estado: "aprobada",
|
||||
aprobadaAt: now,
|
||||
aprobadaPorId: actorUserId ?? null,
|
||||
aprobacionMetodo: "web_admin",
|
||||
};
|
||||
}
|
||||
if (nuevoEstado === "borrador") {
|
||||
return {
|
||||
estado: "borrador",
|
||||
aprobadaAt: null,
|
||||
aprobadaPorId: null,
|
||||
aprobacionMetodo: null,
|
||||
};
|
||||
}
|
||||
if (nuevoEstado === "enviada") {
|
||||
return { estado: "enviada", enviadaAt: now, enviadaCanal: "manual" };
|
||||
}
|
||||
if (nuevoEstado === "aceptada") {
|
||||
return { estado: "aceptada", aceptadaAt: now };
|
||||
}
|
||||
if (nuevoEstado === "rechazada") {
|
||||
return { estado: "rechazada", rechazadaAt: now };
|
||||
}
|
||||
if (nuevoEstado === "vencida") {
|
||||
return { estado: "vencida", vencidaAt: now };
|
||||
}
|
||||
return { estado: nuevoEstado };
|
||||
}
|
||||
|
||||
function eventoPorEstado(estado: string): EventoWebhook | null {
|
||||
if (estado === "aprobada") return "cotizacion.aprobada";
|
||||
if (estado === "enviada") return "cotizacion.enviada";
|
||||
if (estado === "aceptada") return "cotizacion.aceptada";
|
||||
if (estado === "rechazada") return "cotizacion.rechazada";
|
||||
if (estado === "vencida") return "cotizacion.vencida";
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:borrador"],
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const body = await request.json();
|
||||
|
||||
// Camino rápido: cambio de estado puntual (CambiarEstadoButtons envía solo
|
||||
// { estado }). El schema completo exige todos los campos de la cotización,
|
||||
// así que un PUT con solo el estado fallaría la validación; lo tratamos
|
||||
// como un patch parcial.
|
||||
const bodyKeys = Object.keys(body);
|
||||
const existing = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true },
|
||||
});
|
||||
if (!existing) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
// Camino rapido: cambio de estado puntual ({ estado })
|
||||
const bodyKeys = Object.keys(body || {});
|
||||
if (bodyKeys.length === 1 && bodyKeys[0] === "estado") {
|
||||
const nuevoEstado = body.estado;
|
||||
if (!ESTADOS_COTIZACION.includes(nuevoEstado as typeof ESTADOS_COTIZACION[number])) {
|
||||
return NextResponse.json({ error: "Estado invalido" }, { status: 400 });
|
||||
}
|
||||
const existing = await prisma.cotizacion.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
const nuevoEstado = String(body.estado || "");
|
||||
const validacion = validarTransicionEstado({
|
||||
actual: existing.estado,
|
||||
nuevo: nuevoEstado,
|
||||
actor,
|
||||
viaEndpoint: "put",
|
||||
aprobadaAt: existing.aprobadaAt,
|
||||
});
|
||||
|
||||
if (!validacion.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion:
|
||||
nuevoEstado === "aprobada"
|
||||
? "cotizacion.aprobar_bloqueado"
|
||||
: "cotizacion.estado_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { actual: existing.estado, intento: nuevoEstado, error: validacion.error },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const dataEstado = datosPorTransicion(
|
||||
nuevoEstado,
|
||||
actor.type === "user" ? actor.userId : undefined
|
||||
);
|
||||
const updated = await prisma.cotizacion.update({
|
||||
where: { id },
|
||||
data: { estado: nuevoEstado },
|
||||
data: dataEstado,
|
||||
});
|
||||
return NextResponse.json(updated);
|
||||
|
||||
if (nuevoEstado === "aprobada") {
|
||||
await prisma.approvalToken.updateMany({
|
||||
where: { cotizacionId: id, usadoAt: null },
|
||||
data: { expiraAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: `cotizacion.estado_${nuevoEstado}`,
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { anterior: existing.estado, nuevo: nuevoEstado },
|
||||
});
|
||||
|
||||
const ev = eventoPorEstado(nuevoEstado);
|
||||
if (ev && nuevoEstado !== existing.estado) {
|
||||
void emitirWebhook(ev, {
|
||||
cotizacionId: updated.id,
|
||||
numero: updated.numero,
|
||||
folio: updated.numero,
|
||||
titulo: updated.proyecto,
|
||||
proyecto: updated.proyecto,
|
||||
moneda: updated.moneda,
|
||||
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
||||
estado: updated.estado,
|
||||
cliente: {
|
||||
id: existing.cliente.id,
|
||||
nombre: existing.cliente.nombre,
|
||||
empresa: existing.cliente.empresa,
|
||||
email: existing.cliente.email,
|
||||
telefono: existing.cliente.telefono,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||
}
|
||||
|
||||
// Si es agente, SOLO puede editar cotizaciones en borrador y NUNCA cambiar estado
|
||||
if (actor.type === "agent") {
|
||||
if (existing.estado !== "borrador") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.editar_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { estadoActual: existing.estado },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Los agentes solo pueden editar cotizaciones en estado borrador" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
if (body.estado && body.estado !== "borrador") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion:
|
||||
body.estado === "aprobada"
|
||||
? "cotizacion.aprobar_bloqueado"
|
||||
: "cotizacion.estado_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { actual: existing.estado, intento: body.estado },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Los agentes no pueden cambiar el estado de la cotizacion al editarla" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = cotizacionPutSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
fecha,
|
||||
vigencia,
|
||||
@@ -105,11 +353,80 @@ export async function PUT(
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
const estado = body.estado;
|
||||
const estadoSolicitado = body.estado as string | undefined;
|
||||
|
||||
const existing = await prisma.cotizacion.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
let extraEstadoData: Record<string, unknown> = {};
|
||||
if (estadoSolicitado && estadoSolicitado !== existing.estado) {
|
||||
const validacion = validarTransicionEstado({
|
||||
actual: existing.estado,
|
||||
nuevo: estadoSolicitado,
|
||||
actor,
|
||||
viaEndpoint: "put",
|
||||
aprobadaAt: existing.aprobadaAt,
|
||||
});
|
||||
if (!validacion.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion:
|
||||
estadoSolicitado === "aprobada"
|
||||
? "cotizacion.aprobar_bloqueado"
|
||||
: "cotizacion.estado_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { actual: existing.estado, intento: estadoSolicitado, error: validacion.error },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: validacion.error }, { status: validacion.status ?? 403 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
extraEstadoData = datosPorTransicion(
|
||||
estadoSolicitado,
|
||||
actor.type === "user" ? actor.userId : undefined
|
||||
);
|
||||
}
|
||||
|
||||
if (actor.type === "agent") {
|
||||
const idsConsultar = servicios
|
||||
.filter((s) => !s.esPersonalizado && s.catalogoId && !s.catalogoId.startsWith("bucefalo-"))
|
||||
.map((s) => s.catalogoId);
|
||||
const restringidos = idsConsultar.length
|
||||
? await prisma.servicioCatalogo.findMany({
|
||||
where: { id: { in: idsConsultar }, soloAdmin: true },
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
const check = evaluarRestriccionSoloAdmin({
|
||||
esAgente: true,
|
||||
planBucefalo,
|
||||
servicios,
|
||||
soloAdminCatalogIds: restringidos.map((r) => r.id),
|
||||
});
|
||||
if (!check.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.servicio_solo_admin_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { motivos: check.motivos, itemsBloqueados: check.itemsBloqueados },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Los servicios o planes marcados como solo_admin (incluyendo Bucefalo CRM) estan ocultos para agentes y solo puede agregarlos el administrador desde la web",
|
||||
reason: "solo_admin_restricted",
|
||||
detalles: check.motivos,
|
||||
},
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let clienteIdFinal: string | undefined;
|
||||
@@ -160,20 +477,23 @@ export async function PUT(
|
||||
...(esDoble !== undefined && { opcionesMetadata: esDoble ? opciones ?? {} : undefined }),
|
||||
...(observaciones !== undefined && { observaciones }),
|
||||
...(observacionesInternas !== undefined && { observacionesInternas }),
|
||||
...(estado && ESTADOS_COTIZACION.includes(estado as typeof ESTADOS_COTIZACION[number]) && { estado }),
|
||||
...(estadoSolicitado &&
|
||||
ESTADOS_COTIZACION.includes(estadoSolicitado as (typeof ESTADOS_COTIZACION)[number]) &&
|
||||
extraEstadoData),
|
||||
},
|
||||
});
|
||||
|
||||
if (servicios && Array.isArray(servicios)) {
|
||||
// El servicio Bucéfalo del catálogo se resuelve una sola vez, no por partida.
|
||||
const necesitaBucefalo = servicios.some(
|
||||
(s) => !s.esPersonalizado && s.catalogoId?.startsWith("bucefalo-")
|
||||
);
|
||||
const bucefaloCatalogoId = necesitaBucefalo
|
||||
? (await prisma.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
select: { id: true },
|
||||
}))?.id ?? null
|
||||
? (
|
||||
await prisma.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
select: { id: true },
|
||||
})
|
||||
)?.id ?? null
|
||||
: null;
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
@@ -202,7 +522,6 @@ export async function PUT(
|
||||
opcion: esDobleFinal ? serv.opcion ?? "ambas" : null,
|
||||
fase: serv.fase,
|
||||
tipoPago: serv.tipoPago,
|
||||
// "demanda": tarifa por hora sin compromiso; nunca suma al total.
|
||||
precio: serv.modeloCobro === "demanda" ? 0 : serv.precio,
|
||||
tiempoEntrega: serv.tiempoEntrega,
|
||||
entregables: serv.entregables,
|
||||
@@ -230,10 +549,20 @@ export async function PUT(
|
||||
|
||||
const updated = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, asesor: true, servicios: true },
|
||||
include: { cliente: true, asesor: { select: asesorPublicoSelect }, servicios: true },
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.actualizar",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: { numero: existing.numero },
|
||||
});
|
||||
|
||||
return applyHeaders(NextResponse.json(updated), rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error updating cotizacion:", error);
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
||||
import { crearEnlaceAprobacion, notificarJarethBorrador } from "@/lib/aprobacion";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:borrador"],
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, servicios: true },
|
||||
});
|
||||
if (!cot) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
if (cot.estado !== "borrador") {
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: `Solo se puede solicitar aprobacion en estado borrador (actual: ${cot.estado})` },
|
||||
{ status: 409 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const enlace = await crearEnlaceAprobacion(id);
|
||||
const actorEtiqueta = actor.type === "agent" ? `Agente: ${actor.nombre}` : actor.name;
|
||||
const aviso = await notificarJarethBorrador(cot, enlace, actorEtiqueta);
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.solicitar_aprobacion",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
numero: cot.numero,
|
||||
correoEnviado: aviso.ok,
|
||||
omitido: aviso.omitido ?? false,
|
||||
},
|
||||
});
|
||||
|
||||
// Nunca exponer el enlace/token raw en la respuesta para que un agente no pueda auto-aprobarse.
|
||||
return applyHeaders(
|
||||
NextResponse.json({
|
||||
ok: true,
|
||||
cotizacionId: id,
|
||||
numero: cot.numero,
|
||||
expiraAt: enlace.expiraAt.toISOString(),
|
||||
correoEnviado: aviso.ok,
|
||||
correoOmitido: aviso.omitido ?? false,
|
||||
}),
|
||||
rateLimitHeaders
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+400
-122
@@ -1,142 +1,316 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { cotizacionPostSchema } from "@/lib/schemas";
|
||||
import {
|
||||
applyHeaders,
|
||||
esAgenteSoloAceptadas,
|
||||
requireActor,
|
||||
} from "@/lib/agent-auth";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import {
|
||||
appBaseUrl,
|
||||
crearEnlaceAprobacion,
|
||||
notificarJarethBorrador,
|
||||
} from "@/lib/aprobacion";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
import { evaluarRestriccionSoloAdmin } from "@/lib/solo-admin-core";
|
||||
import {
|
||||
bucefaloPrecio,
|
||||
calcularTotalesCotizacion,
|
||||
calcularVigencia,
|
||||
} from "@/lib/calculators";
|
||||
import { errorValidacion } from "@/lib/catalogo";
|
||||
import { asesorPublicoSelect, siguienteNumeroCotizacion } from "@/lib/cotizaciones";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = cotizacionPostSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const {
|
||||
numero,
|
||||
fecha,
|
||||
vigencia,
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
incluirIva,
|
||||
esDoble,
|
||||
opciones,
|
||||
observaciones,
|
||||
observacionesInternas,
|
||||
cliente,
|
||||
asesorId,
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
|
||||
let clienteRecord = await prisma.cliente.findFirst({
|
||||
where: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
},
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:borrador"],
|
||||
recursoTipo: "cotizacion",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
if (!clienteRecord) {
|
||||
clienteRecord = await prisma.cliente.create({
|
||||
data: {
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const actorKey = actor.type === "agent" ? `agent:${actor.keyId}` : `user:${actor.userId}`;
|
||||
|
||||
const res = await withIdempotency(request, actorKey, async ({ body }) => {
|
||||
const parsed = cotizacionPostSchema.safeParse(body);
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
|
||||
// Resolver asesorId: para usuario humano usa su propia sesion; para agente
|
||||
// usa el primer usuario admin si no se indico asesorId.
|
||||
let asesorId = parsed.data.asesorId;
|
||||
if (!asesorId) {
|
||||
if (actor.type === "user") {
|
||||
asesorId = actor.userId;
|
||||
} else {
|
||||
const admin = await prisma.user.findFirst({
|
||||
where: { role: "admin" },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!admin) {
|
||||
return NextResponse.json(
|
||||
{ error: "No existe un usuario administrador para asignar como asesor" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
asesorId = admin.id;
|
||||
}
|
||||
}
|
||||
|
||||
const asesor = await prisma.user.findUnique({
|
||||
where: { id: asesorId },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!asesor) {
|
||||
return NextResponse.json(
|
||||
{ error: `asesorId: no existe el usuario ${asesorId}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const fecha = parsed.data.fecha ?? new Date();
|
||||
const vigencia = parsed.data.vigencia ?? calcularVigencia(fecha);
|
||||
const numero = parsed.data.numero ?? (await siguienteNumeroCotizacion(asesor.name));
|
||||
|
||||
const {
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
incluirIva,
|
||||
esDoble,
|
||||
opciones,
|
||||
observaciones,
|
||||
observacionesInternas,
|
||||
cliente,
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
|
||||
if (actor.type === "agent") {
|
||||
const idsConsultar = servicios
|
||||
.filter((s) => !s.esPersonalizado && s.catalogoId && !s.catalogoId.startsWith("bucefalo-"))
|
||||
.map((s) => s.catalogoId);
|
||||
const restringidos = idsConsultar.length
|
||||
? await prisma.servicioCatalogo.findMany({
|
||||
where: { id: { in: idsConsultar }, soloAdmin: true },
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
const check = evaluarRestriccionSoloAdmin({
|
||||
esAgente: true,
|
||||
planBucefalo,
|
||||
servicios,
|
||||
soloAdminCatalogIds: restringidos.map((r) => r.id),
|
||||
});
|
||||
if (!check.ok) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.servicio_solo_admin_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { motivos: check.motivos, itemsBloqueados: check.itemsBloqueados },
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Los servicios o planes marcados como solo_admin (incluyendo Bucefalo CRM) estan ocultos para agentes y solo puede agregarlos el administrador desde la web",
|
||||
reason: "solo_admin_restricted",
|
||||
detalles: check.motivos,
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let clienteRecord = await prisma.cliente.findFirst({
|
||||
where: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
email: cliente.email || null,
|
||||
telefono: cliente.telefono || null,
|
||||
rfc: cliente.rfc || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const clienteIdFinal = clienteRecord.id;
|
||||
|
||||
// El servicio Bucéfalo del catálogo es el mismo para todas las partidas:
|
||||
// se resuelve una sola vez fuera del loop de inserción.
|
||||
const necesitaBucefalo = servicios.some(
|
||||
(s) => !s.esPersonalizado && s.catalogoId.startsWith("bucefalo-")
|
||||
);
|
||||
const bucefaloCatalogoId = necesitaBucefalo
|
||||
? (await prisma.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
select: { id: true },
|
||||
}))?.id ?? null
|
||||
: null;
|
||||
|
||||
const cotizacion = await prisma.$transaction(async (tx) => {
|
||||
const cot = await tx.cotizacion.create({
|
||||
data: {
|
||||
numero,
|
||||
fecha: new Date(fecha),
|
||||
vigencia: new Date(vigencia),
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
incluirIva: incluirIva ?? true,
|
||||
esDoble: esDoble ?? false,
|
||||
opcionesMetadata: esDoble ? opciones ?? {} : undefined,
|
||||
observaciones: observaciones || null,
|
||||
observacionesInternas: observacionesInternas || null,
|
||||
clienteId: clienteIdFinal,
|
||||
asesorId,
|
||||
estado: "borrador",
|
||||
archivado: false,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.servicioCotizado.createMany({
|
||||
data: servicios.map((servicio) => {
|
||||
let catalogoId: string | null;
|
||||
if (servicio.esPersonalizado) {
|
||||
catalogoId = null;
|
||||
} else if (servicio.catalogoId.startsWith("bucefalo-")) {
|
||||
catalogoId = bucefaloCatalogoId;
|
||||
} else {
|
||||
catalogoId = servicio.catalogoId;
|
||||
}
|
||||
return {
|
||||
cotizacionId: cot.id,
|
||||
servicioCatalogoId: catalogoId,
|
||||
nombre: servicio.esPersonalizado ? servicio.nombre : null,
|
||||
esPersonalizado: servicio.esPersonalizado ?? false,
|
||||
horas: servicio.esPersonalizado ? servicio.horas ?? null : null,
|
||||
tarifaHora: servicio.esPersonalizado ? servicio.tarifaHora ?? null : null,
|
||||
modeloCobro: servicio.modeloCobro ?? (servicio.esPersonalizado ? "horas" : "fijo"),
|
||||
montoMinimo: servicio.esPersonalizado ? servicio.montoMinimo ?? null : null,
|
||||
horasIncluidas: servicio.esPersonalizado ? servicio.horasIncluidas ?? null : null,
|
||||
opcion: esDoble ? servicio.opcion ?? "ambas" : null,
|
||||
fase: servicio.fase,
|
||||
tipoPago: servicio.tipoPago,
|
||||
// "demanda": tarifa por hora sin compromiso; nunca suma al total.
|
||||
precio: servicio.modeloCobro === "demanda" ? 0 : servicio.precio,
|
||||
tiempoEntrega: servicio.tiempoEntrega,
|
||||
entregables: servicio.entregables,
|
||||
beneficios: servicio.beneficios ?? [],
|
||||
seleccionado: true,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (planBucefalo) {
|
||||
await tx.planBucefaloCotizacion.create({
|
||||
if (!clienteRecord) {
|
||||
clienteRecord = await prisma.cliente.create({
|
||||
data: {
|
||||
cotizacionId: cot.id,
|
||||
nivel: planBucefalo.nivel,
|
||||
precio: planBucefalo.precio,
|
||||
seleccionado: true,
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
email: cliente.email || null,
|
||||
telefono: cliente.telefono || null,
|
||||
rfc: cliente.rfc || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return cot;
|
||||
const clienteIdFinal = clienteRecord.id;
|
||||
|
||||
const necesitaBucefalo = servicios.some(
|
||||
(s) => !s.esPersonalizado && s.catalogoId.startsWith("bucefalo-")
|
||||
);
|
||||
const bucefaloCatalogoId = necesitaBucefalo
|
||||
? (
|
||||
await prisma.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
select: { id: true },
|
||||
})
|
||||
)?.id ?? null
|
||||
: null;
|
||||
|
||||
const cotizacion = await prisma.$transaction(async (tx) => {
|
||||
const cot = await tx.cotizacion.create({
|
||||
data: {
|
||||
numero,
|
||||
fecha: new Date(fecha),
|
||||
vigencia: new Date(vigencia),
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
incluirIva: incluirIva ?? true,
|
||||
esDoble: esDoble ?? false,
|
||||
opcionesMetadata: esDoble ? opciones ?? {} : undefined,
|
||||
observaciones: observaciones || null,
|
||||
observacionesInternas: observacionesInternas || null,
|
||||
clienteId: clienteIdFinal,
|
||||
asesorId,
|
||||
// SIEMPRE nace en borrador, aunque el body intente enviar otro estado.
|
||||
estado: "borrador",
|
||||
creadaPorAgente: actor.type === "agent" ? actor.nombre : null,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.servicioCotizado.createMany({
|
||||
data: servicios.map((servicio) => {
|
||||
let catalogoId: string | null;
|
||||
if (servicio.esPersonalizado) {
|
||||
catalogoId = null;
|
||||
} else if (servicio.catalogoId.startsWith("bucefalo-")) {
|
||||
catalogoId = bucefaloCatalogoId;
|
||||
} else {
|
||||
catalogoId = servicio.catalogoId;
|
||||
}
|
||||
return {
|
||||
cotizacionId: cot.id,
|
||||
servicioCatalogoId: catalogoId,
|
||||
nombre: servicio.esPersonalizado ? servicio.nombre : null,
|
||||
esPersonalizado: servicio.esPersonalizado ?? false,
|
||||
horas: servicio.esPersonalizado ? servicio.horas ?? null : null,
|
||||
tarifaHora: servicio.esPersonalizado ? servicio.tarifaHora ?? null : null,
|
||||
modeloCobro: servicio.modeloCobro ?? (servicio.esPersonalizado ? "horas" : "fijo"),
|
||||
montoMinimo: servicio.esPersonalizado ? servicio.montoMinimo ?? null : null,
|
||||
horasIncluidas: servicio.esPersonalizado ? servicio.horasIncluidas ?? null : null,
|
||||
opcion: esDoble ? servicio.opcion ?? "ambas" : null,
|
||||
fase: servicio.fase,
|
||||
tipoPago: servicio.tipoPago,
|
||||
// "demanda": tarifa por hora sin compromiso; nunca suma al total.
|
||||
precio: servicio.modeloCobro === "demanda" ? 0 : servicio.precio,
|
||||
tiempoEntrega: servicio.tiempoEntrega,
|
||||
entregables: servicio.entregables,
|
||||
beneficios: servicio.beneficios ?? [],
|
||||
seleccionado: true,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (planBucefalo) {
|
||||
await tx.planBucefaloCotizacion.create({
|
||||
data: {
|
||||
cotizacionId: cot.id,
|
||||
nivel: planBucefalo.nivel,
|
||||
precio: planBucefalo.precio ?? bucefaloPrecio(planBucefalo.nivel),
|
||||
seleccionado: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return cot;
|
||||
});
|
||||
|
||||
const totales = calcularTotalesCotizacion(
|
||||
servicios.map((s) => ({
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.modeloCobro === "demanda" ? 0 : s.precio,
|
||||
seleccionado: true,
|
||||
})),
|
||||
{ incluirIva: cotizacion.incluirIva }
|
||||
);
|
||||
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.crear",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: cotizacion.id,
|
||||
request,
|
||||
exito: true,
|
||||
detalle: {
|
||||
numero: cotizacion.numero,
|
||||
clienteId: clienteIdFinal,
|
||||
creadaPorAgente: cotizacion.creadaPorAgente,
|
||||
totalUnico: totales.totalUnico,
|
||||
totalMensual: totales.totalMensual,
|
||||
},
|
||||
});
|
||||
|
||||
// Flujo de aprobacion cuando la crea un agente (el enlace firmado solo va por correo a Jareth)
|
||||
if (actor.type === "agent") {
|
||||
const enlace = await crearEnlaceAprobacion(cotizacion.id);
|
||||
void notificarJarethBorrador(
|
||||
{
|
||||
id: cotizacion.id,
|
||||
numero: cotizacion.numero,
|
||||
proyecto: cotizacion.proyecto,
|
||||
moneda: cotizacion.moneda,
|
||||
vigencia: cotizacion.vigencia,
|
||||
incluirIva: cotizacion.incluirIva,
|
||||
cliente: { nombre: clienteRecord.nombre, empresa: clienteRecord.empresa },
|
||||
servicios: servicios.map((s) => ({
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.modeloCobro === "demanda" ? 0 : s.precio,
|
||||
seleccionado: true,
|
||||
})),
|
||||
},
|
||||
enlace,
|
||||
`Agente: ${actor.nombre}`
|
||||
);
|
||||
}
|
||||
|
||||
// Webhook cotizacion.creada (sin exponer el token raw de un solo uso)
|
||||
void emitirWebhook("cotizacion.creada", {
|
||||
cotizacionId: cotizacion.id,
|
||||
numero: cotizacion.numero,
|
||||
folio: cotizacion.numero,
|
||||
titulo: cotizacion.proyecto,
|
||||
estado: "borrador",
|
||||
proyecto: cotizacion.proyecto,
|
||||
moneda: cotizacion.moneda,
|
||||
total: Number((totales.totalUnico + totales.totalMensual).toFixed(2)),
|
||||
url: `${appBaseUrl()}/cotizaciones/${cotizacion.id}`,
|
||||
creadaPorAgente: cotizacion.creadaPorAgente,
|
||||
totales,
|
||||
adminReviewUrl: `${appBaseUrl()}/cotizaciones/${cotizacion.id}`,
|
||||
cliente: {
|
||||
id: clienteRecord.id,
|
||||
nombre: clienteRecord.nombre,
|
||||
empresa: clienteRecord.empresa,
|
||||
email: clienteRecord.email,
|
||||
telefono: clienteRecord.telefono,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(cotizacion, { status: 201 });
|
||||
});
|
||||
|
||||
return NextResponse.json(cotizacion, { status: 201 });
|
||||
return applyHeaders(res, rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error creating cotizacion:", error);
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
@@ -144,18 +318,122 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
// GET /api/cotizaciones — lista, de la mas reciente a la mas antigua.
|
||||
// Filtros opcionales: ?estado=, ?clienteId=, ?q=, ?clienteEmail=,
|
||||
// ?clienteTelefono=, ?desde=, ?hasta=, ?page=, ?limit=.
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const auth = await requireActor(request, {
|
||||
scopes: ["cotizaciones:leer", "cotizaciones:leer_aceptadas"],
|
||||
recursoTipo: "cotizacion",
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
const soloAceptadas = esAgenteSoloAceptadas(actor);
|
||||
|
||||
const sp = request.nextUrl.searchParams;
|
||||
const estadoParam = sp.get("estado");
|
||||
const clienteId = sp.get("clienteId");
|
||||
const q = sp.get("q")?.trim();
|
||||
const clienteEmail = sp.get("clienteEmail")?.trim();
|
||||
const clienteTelefono = sp.get("clienteTelefono")?.trim();
|
||||
const desde = sp.get("desde")?.trim();
|
||||
const hasta = sp.get("hasta")?.trim();
|
||||
const pageRaw = sp.get("page");
|
||||
const limitRaw = sp.get("limit");
|
||||
const incluirArchivados = actor.type !== "agent" && sp.get("incluirArchivados") === "true";
|
||||
|
||||
if (soloAceptadas && estadoParam && estadoParam !== "aceptada") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.leer_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { estadoSolicitado: estadoParam },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Tu clave solo tiene permiso para consultar cotizaciones aceptadas" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const limit = limitRaw ? Number(limitRaw) : undefined;
|
||||
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "limit debe ser un entero entre 1 y 200" }, { status: 400 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const page = pageRaw ? Number(pageRaw) : undefined;
|
||||
if (page !== undefined && (!Number.isInteger(page) || page < 1)) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "page debe ser un entero mayor a 0" }, { status: 400 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
const estadoEfectivo = soloAceptadas ? "aceptada" : estadoParam || undefined;
|
||||
|
||||
const clienteWhere: Prisma.ClienteWhereInput = {};
|
||||
if (clienteEmail) {
|
||||
clienteWhere.email = { equals: clienteEmail, mode: "insensitive" };
|
||||
}
|
||||
if (clienteTelefono) {
|
||||
const digits = clienteTelefono.replace(/\D/g, "");
|
||||
const ultimos = digits.length >= 10 ? digits.slice(-10) : clienteTelefono;
|
||||
clienteWhere.telefono = { contains: ultimos };
|
||||
}
|
||||
|
||||
const fechaWhere: Prisma.DateTimeFilter = {};
|
||||
if (desde) {
|
||||
const d = new Date(desde);
|
||||
if (!Number.isNaN(d.getTime())) fechaWhere.gte = d;
|
||||
}
|
||||
if (hasta) {
|
||||
const h = new Date(hasta);
|
||||
if (!Number.isNaN(h.getTime())) fechaWhere.lte = h;
|
||||
}
|
||||
|
||||
const where: Prisma.CotizacionWhereInput = {
|
||||
...(!incluirArchivados && { archivado: false }),
|
||||
...(estadoEfectivo && { estado: estadoEfectivo }),
|
||||
...(clienteId && { clienteId }),
|
||||
...(Object.keys(clienteWhere).length > 0 && { cliente: clienteWhere }),
|
||||
...(Object.keys(fechaWhere).length > 0 && { fecha: fechaWhere }),
|
||||
...(q && {
|
||||
OR: [
|
||||
{ numero: { contains: q, mode: "insensitive" as const } },
|
||||
{ proyecto: { contains: q, mode: "insensitive" as const } },
|
||||
{ cliente: { nombre: { contains: q, mode: "insensitive" as const } } },
|
||||
{ cliente: { empresa: { contains: q, mode: "insensitive" as const } } },
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
const cotizaciones = await prisma.cotizacion.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
skip: page && limit ? (page - 1) * limit : undefined,
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
asesor: { select: asesorPublicoSelect },
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(cotizaciones);
|
||||
|
||||
const salida = soloAceptadas
|
||||
? cotizaciones.map((c) => ({ ...c, observacionesInternas: null }))
|
||||
: cotizaciones;
|
||||
|
||||
return applyHeaders(NextResponse.json(salida), rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
|
||||
@@ -37,8 +37,7 @@ export async function GET(
|
||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||
|
||||
const data: ExcelData = {
|
||||
razonSocial: bancaria.razon_social || "Cotizador E3",
|
||||
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
|
||||
razonSocial: bancaria.razon_social || "Uriel Jareth Consulting",
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
clienteEmpresa: cot.cliente.empresa || "",
|
||||
@@ -70,8 +69,8 @@ export async function GET(
|
||||
opcionesMetadata: cot.opcionesMetadata as never,
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel ?? null,
|
||||
planBucefaloPrecio: cot.planBucefalo?.precio ?? null,
|
||||
colorPrimario: branding.colorPrimario || "#2563eb",
|
||||
colorSecundario: branding.colorSecundario || "#1e293b",
|
||||
colorPrimario: branding.colorPrimario || "#0400C4",
|
||||
colorSecundario: branding.colorSecundario || "#0F172A",
|
||||
incluirIva: cot.incluirIva,
|
||||
// El Excel es un documento del cliente: solo el texto del cliente.
|
||||
observaciones: cot.observaciones,
|
||||
|
||||
@@ -48,8 +48,7 @@ export async function POST(request: NextRequest) {
|
||||
]);
|
||||
|
||||
const data: ExcelData = {
|
||||
razonSocial: bancaria.razon_social || "Cotizador E3",
|
||||
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
|
||||
razonSocial: bancaria.razon_social || "Uriel Jareth Consulting",
|
||||
numero: "BORRADOR",
|
||||
clienteNombre: draft.clienteNombre,
|
||||
clienteEmpresa: draft.clienteEmpresa,
|
||||
@@ -78,8 +77,8 @@ export async function POST(request: NextRequest) {
|
||||
esDoble: draft.esDoble,
|
||||
opcionesMetadata: draft.esDoble ? draft.opciones ?? null : null,
|
||||
planBucefaloNivel: draft.planBucefaloNivel,
|
||||
colorPrimario: branding.colorPrimario || "#2563eb",
|
||||
colorSecundario: branding.colorSecundario || "#1e293b",
|
||||
colorPrimario: branding.colorPrimario || "#0400C4",
|
||||
colorSecundario: branding.colorSecundario || "#0F172A",
|
||||
observaciones: draft.observaciones,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||
import { sanitizeFilename } from "@/lib/calculators";
|
||||
import {
|
||||
applyHeaders,
|
||||
esAgenteSoloAceptadas,
|
||||
requireActor,
|
||||
} from "@/lib/agent-auth";
|
||||
import { generarPDFCotizacion } from "@/lib/cotizacion-pdf";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -11,90 +14,72 @@ export async function GET(
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
// Ruta compartida (staff + cliente): el cliente solo puede descargar sus
|
||||
// propias cotizaciones; para staff no se toca nada mas del handler.
|
||||
const session = await getSession();
|
||||
if (session?.role === "cliente") {
|
||||
const auth = await requireActor(request, {
|
||||
allowCliente: true,
|
||||
scopes: ["cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas"],
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
});
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { actor, rateLimitHeaders } = auth;
|
||||
|
||||
if (actor.type === "user" && actor.role === "cliente") {
|
||||
const propia = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
select: { clienteId: true },
|
||||
});
|
||||
if (!propia || propia.clienteId !== session.clienteId) {
|
||||
if (!propia || propia.clienteId !== actor.clienteId) {
|
||||
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
}
|
||||
}
|
||||
const [cot, config, branding, bonos] = await Promise.all([
|
||||
prisma.cotizacion.findUnique({
|
||||
|
||||
if (esAgenteSoloAceptadas(actor)) {
|
||||
const estadoRow = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
// orderBy explicito: drawSection abre un encabezado de fase nuevo cada vez
|
||||
// que cambia serv.fase, o sea que asume el array agrupado. Sin esto el orden
|
||||
// lo decide Postgres y el PDF puede salir distinto del Excel del mismo envio.
|
||||
servicios: {
|
||||
include: { servicioCatalogo: true },
|
||||
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
planBucefalo: true,
|
||||
},
|
||||
}),
|
||||
getConfigBancaria(),
|
||||
getConfigBranding(),
|
||||
prisma.bono.findMany({ where: { activo: true }, orderBy: { numero: "asc" } }),
|
||||
]);
|
||||
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
select: { estado: true },
|
||||
});
|
||||
if (!estadoRow) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
if (estadoRow.estado !== "aceptada") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: "cotizacion.export_pdf_bloqueado",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: id,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { estadoActual: estadoRow.estado },
|
||||
});
|
||||
return applyHeaders(
|
||||
NextResponse.json(
|
||||
{ error: "Tu clave solo permite descargar PDF de cotizaciones aceptadas" },
|
||||
{ status: 403 }
|
||||
),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
}
|
||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||
const nombre = `${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}`;
|
||||
|
||||
const buffer = await generateCotizacionPDF({
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
clienteEmpresa: cot.cliente.empresa || "",
|
||||
asesorNombre: cot.asesor.name,
|
||||
fecha: cot.fecha,
|
||||
vigencia: cot.vigencia,
|
||||
moneda: cot.moneda,
|
||||
tipoCambio: cot.tipoCambio,
|
||||
proyecto: cot.proyecto,
|
||||
esquemaPago: cot.esquemaPago,
|
||||
servicios: cot.servicios.filter((s) => s.seleccionado).map((s) => ({
|
||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precio,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
||||
esPersonalizado: s.esPersonalizado,
|
||||
horas: s.horas ?? undefined,
|
||||
tarifaHora: s.tarifaHora ?? undefined,
|
||||
modeloCobro: s.modeloCobro ?? undefined,
|
||||
montoMinimo: s.montoMinimo ?? undefined,
|
||||
horasIncluidas: s.horasIncluidas ?? undefined,
|
||||
opcion: s.opcion ?? undefined,
|
||||
})),
|
||||
esDoble: cot.esDoble,
|
||||
opcionesMetadata: cot.opcionesMetadata as never,
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
|
||||
incluirBonos: cot.incluirBonos,
|
||||
bonos,
|
||||
incluirIva: cot.incluirIva,
|
||||
// Solo el texto del cliente. observacionesInternas no se pasa nunca.
|
||||
observaciones: cot.observaciones,
|
||||
configBancaria: config,
|
||||
...branding,
|
||||
});
|
||||
const pdf = await generarPDFCotizacion(id);
|
||||
if (!pdf) {
|
||||
return applyHeaders(
|
||||
NextResponse.json({ error: "No encontrada" }, { status: 404 }),
|
||||
rateLimitHeaders
|
||||
);
|
||||
}
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
const response = new NextResponse(new Uint8Array(pdf.buffer), {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="${nombre}.pdf"`,
|
||||
"Content-Disposition": `attachment; filename="${pdf.filename}"`,
|
||||
},
|
||||
});
|
||||
return applyHeaders(response, rateLimitHeaders);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
|
||||
@@ -3,13 +3,25 @@ import { prisma } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const APP_VERSION = "2.0.0";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
return NextResponse.json({ status: "ok", database: "ok" });
|
||||
return NextResponse.json({
|
||||
status: "ok",
|
||||
database: "ok",
|
||||
version: APP_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ status: "error", database: "unreachable" },
|
||||
{
|
||||
status: "error",
|
||||
database: "unreachable",
|
||||
version: APP_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user