# AGENTS.md — Cotizador E3 ## Quick Reference | Command | Purpose | |---------|---------| | `npm run dev` | Start Next.js dev server on port 3000 | | `npm run build` | Production build (runs TypeScript check) | | `npm run lint` | ESLint (flat config, eslint-config-next) | | `npm run db:seed` | Run seed (upserts all data, idempotent) | | `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 -- ` | 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. **Windows environment.** Use `start.bat` / `stop.bat` to manage Docker PostgreSQL + Next.js together. PowerShell is the shell. Paths with brackets (e.g. `[id]`) require `-LiteralPath` in PowerShell, not `-Path`. **Two backends, one database.** The Next.js app (`src/`, port 3000) and a standalone Python FastAPI service (`api/`, port 8000) both talk to the same PostgreSQL DB. Prisma owns the schema/migrations; the Python API reads/writes the same tables independently. `docker-compose.yml` runs `postgres` + the `api` service; Next.js is run separately via `npm run dev` / `start.bat`. **Three compose files, and two of them are the same file.** `docker-compose.yaml` is a byte-identical copy of `docker-compose.coolify.yml` — it exists only so Coolify's default detection finds the production stack. Local dev is `docker-compose.yml` (postgres with port 5432 published + api). Because `.yml` and `.yaml` both exist, a bare `docker compose` warns about ambiguity before resolving to `docker-compose.yml`; pass `-f docker-compose.yml` explicitly, as `start.bat` does. **When you edit the Coolify stack, edit both `docker-compose.coolify.yml` and `docker-compose.yaml`** or Coolify deploys the stale copy. ## Prisma 7 — Critical Gotchas - **Prisma client is NOT at `@prisma/client`.** It's generated to `src/generated/prisma/` and imported as `@/generated/prisma/client`. - **Uses `PrismaPg` driver adapter** (from `@prisma/adapter-pg`) with individual connection params (host/port/user/password/database), NOT a connection string. The `connectionString` approach causes SCRAM auth errors with postgres:postgres. - **`prisma.config.ts`** has no `seed` property (unsupported by PrismaConfig type). Run seed manually with `npx tsx prisma/seed.ts`. - After changing `schema.prisma`: run `npx prisma migrate dev`, then `npx prisma generate`. - The `globalForPrisma` singleton pattern in `src/lib/db.ts` prevents hot-reload connection leaks in dev. ## PDFKit — Server-Side PDF - `pdfkit` is excluded from Next.js bundling via `serverExternalPackages` in `next.config.ts`. Without this, font metric files (`.afm`) can't be resolved at runtime. - **Footer auto-page-break bug:** `doc.text()` at `y > page.height - margins.bottom` triggers pdfkit's automatic page addition. To write footers in the bottom margin, temporarily set `doc.page.margins.bottom = 0`, write, then restore. Use `bufferPages: true` + `switchToPage()` to add footers after all content. - Returns `Promise` — convert to `Uint8Array` for `NextResponse` body. ## Next.js 16 Conventions - **Async params:** Dynamic route params are `Promise<{ id: string }>` — must `await params` before use. - **All pages are `force-dynamic`** — no static generation or ISR. - **Tailwind CSS v4** — no `tailwind.config.*` file. Config is in `postcss.config.mjs` (using `@tailwindcss/postcss`) and CSS custom properties via `@theme inline` in `src/app/globals.css`. ## Data Model Notes - **Configuracion** is a key-value store (`clave`/`valor`), not a traditional settings model. New config keys: `color_primario`, `color_secundario`, `logo_base64` (branding for PDF export). - **Cascading deletes:** Cotizacion → ServicioCotizado, PlanBucefaloCotizacion use `onDelete: Cascade`. - Cotización number format: `UJ{YY}{MM}{AsesorInitials}{seq}` (e.g. `UJ2605AG001`) — see `generarNumeroCotizacion` in `src/lib/calculators.ts`. Sequence is 3 digits, zero-padded. - Vigencia = 15 business days from fecha (excludes Sat/Sun) — `calcularVigencia`. - IVA_RATE = 0.16 (16%). - **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`. **`precio` is always the authoritative total.** For retainer and demanda lines, `horas × tarifaHora` is display/comparison metadata only — never re-derive a total from it. `calcularTotalesOpcion` and the PDF/Excel builders all sum `precio`. ### Doble propuesta (two-option quotes) `Cotizacion.esDoble` turns one quote into two comparable proposals. Each `ServicioCotizado.opcion` is `"1"`, `"2"`, or `"ambas"` (shared by both). `opcionesMetadata` (Json) holds per-option `titulo` / `descripcion` / `noIncluye` (`MetaOpcion`). `calcularTotalesOpcion(servicios, "1" | "2")` sums lines matching that option **plus** all `"ambas"` lines. Anything that renders or totals a quote must handle both the single and double shape. ### Registro de horas (hours log → payment notes) `RegistroHoras` tracks worked time against a quote so the client can be billed for it. Only offered when `esCotizacionPorTiempo(servicios)` is true (i.e. some line uses a time-based `modeloCobro`). - `estadoPago` is `"por_pagar"` (default) or `"pagada"`, with `fechaPago` stamped on transition. The two buckets must stay separated in totals — pending is what goes on the payment note, paid is history. `resumenPagoHoras` / `esPagada` in `calculators.ts` are the only place that logic should live. - Routes: `GET|POST /api/cotizaciones/[id]/horas` (GET takes `?from=&to=` day filters), `PATCH|DELETE .../horas/[registroId]`, and `POST .../nota-horas` which renders the PDF **server-side** via `src/lib/nota-horas-pdf.ts` (no browser URL). - Hours are entered as `horaInicio`/`horaFin` strings and converted by `calcularHorasRango`. Dates come in as `YYYY-MM-DD` and must go through `fechaRegistroDesdeISO` to avoid UTC off-by-one — don't `new Date(iso)` directly. - Grouping for display/PDF: `ModoAgrupacion` = `detalle | dia | semana | mes` via `periodoAgrupacion`. ## Auth - **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. - 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-e3/sesiones.json` y lo manda como cookie `cotizador-session`. Con `COTIZADOR_EMAIL`/`COTIZADOR_PASSWORD` renueva la sesión solo. No hay API key en Next: para eso está la API de Python. - 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`, 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: 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`. - Root `Dockerfile` builds Next.js with `JWT_SECRET=placeholder-build-only` (auth.ts throws at import without it; all pages are force-dynamic so nothing gets baked). - `*.xlsx` is gitignored (business files must never be committed). ## Architecture ``` src/ app/ (app)/ # Authed route group: dashboard, cotizaciones, clientes, catalogo, configuracion (has its own layout.tsx + Sidebar + DialogProvider) 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.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/ schema.prisma # 14 models (User, Cliente, Cotizacion, Categoria, Paquete, FasePaquete, # ServicioCatalogo, ServicioPaquete, ServicioCotizado, PlanBucefaloCotizacion, # 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 ``` - **Zustand store** (`src/lib/store.ts`) holds the cotización draft. Used by both the new (`cotizaciones/nueva`) and edit (`cotizaciones/[id]/editar`) pages, both of which render `CotizacionForm.tsx`. - **ExportButtons.tsx** has 4 variants: `ExportExcelButtonSaved` / `ExportPDFButtonSaved` (GET by ID) and `ExportExcelButtonDraft` / `ExportPDFButtonDraft` (POST with body). - **Business logic belongs in `calculators.ts`**, not in components or route handlers. It's the shared source of truth for totals, charge models, hours, phases, and formatting — and the file the Python `calculators.py` mirrors. ## UI Conventions - **Never use the browser's native `confirm()` / `alert()` / `prompt()`.** They render as "«domain» dice…" and break the brand. Use the platform's own dialogs: `useConfirm()`, `usePrompt()`, `useToast()` from `@/components/ui/DialogProvider`, mounted once in `src/app/(app)/layout.tsx`. `confirm` and `prompt` return promises (`boolean` / `string | null`); pass `danger: true` for destructive actions. - Everything user-facing is in **Spanish**. Code identifiers are Spanish too (`cotizacion`, `servicio`, `horas`) — match the surrounding naming rather than introducing English terms. - Icons come from `lucide-react`. Colors use the CSS custom properties from `globals.css` (`bg-card-bg`, `border-border`, `text-primary`, `text-muted`), not hardcoded Tailwind palette values. ## Python API (`api/`) — Optional Second Backend - **FastAPI app** (`api/main.py`) exposing the same domain as REST, for n8n and other integrations. - **The MCP server was removed on 2026-07-28.** It was unused, its transport had been broken for some time (it built a `StreamableHTTPServerTransport` per request with no session handling and returned 500 even with valid credentials), and its unpinned SDK took the whole API down in production when `mcp` jumped to 2.0.0. To revive it: `git show edb500f5:api/app/mcp/server.py`. - **`api/requirements.txt` pins exact versions on purpose.** That outage is why. Bump a dependency deliberately — never by accident on a redeploy. - Auth: **API key** (`X-API-Key` or `Authorization: Bearer`) for agents; JWT for human login. Routers in `api/app/routers/`, business logic in `api/app/services/` (its own `calculators.py`, `pdf_generator.py`, `excel_generator.py` — mirror the TS versions). - Run: `cd api && pip install -r requirements.txt && uvicorn main:app --reload --port 8000`. Swagger at `/docs`. Full endpoint reference in `api/COTIZADOR_API_SKILL.md`. - It reads `DB_*`, `API_KEY`, `JWT_SECRET` env vars (same DB as Prisma). ## 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.