Files
cotizador/AGENTS.md
T

118 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AGENTS.md — Cotizador — Uriel Jareth Consulting (Go + Vite SPA)
## Quick Reference
| Command | Purpose |
|---------|---------|
| `go run ./cmd/cotizador serve` | Start unified Go server (API + embedded SPA) on port 3000 (runs auto-migrations on boot) |
| `go test -count=1 ./...` | Run all Go unit & HTTP API security tests |
| `go vet ./...` | Static analysis across all Go packages |
| `go build -o cotizador ./cmd/cotizador` | Compile unified static binary (`serve`, `migrate`, `seed`, `provision-keys`, `cli`) |
| `go run ./cmd/cotizador migrate` | Apply idempotent SQL migrations (`_go_migrations`) |
| `go run ./cmd/cotizador seed` | Run idempotent catalog/config/user seed |
| `go run ./cmd/cotizador provision-keys --preset` | Provision scoped `AgentApiKey` credentials in PostgreSQL |
| `go run ./cmd/cotizador cli <comando>` | CLI `cotizador` (servicios, clientes, cotizaciones, horas). `cotizador cli esquema` lo describe en JSON |
| `cd web && npm run dev` | Start Vite dev server (proxies `/api` to `http://localhost:3000`) |
| `cd web && npm run build` | Build production React 19 + Tailwind CSS v4 SPA into `web/dist/` |
**Windows environment.** Use `start.bat` / `stop.bat` to manage Docker PostgreSQL + SPA build + Go server together. PowerShell is the shell.
**Single Go backend + embedded SPA.** A single Go 1.27 binary (`cmd/cotizador`) serves:
- All REST API routes under `/api/*` (OpenAPI 3.1 at `/api/openapi.json`)
- The compiled Vite React 19 + Tailwind CSS v4 SPA (`web/` → embedded via `//go:embed all:dist` in `internal/spa/`)
- Background recurring payment & reminder scheduler (`internal/scheduler`)
- Server-side PDF (`fpdf`) and Excel/CSV (`excelize`) generation
- Consultative AI proposal pipeline via MiniMax (`internal/propuesta`)
- Built-in CLI (`cotizador cli ...`) and key provisioning (`cotizador provision-keys`)
**Compose files:** `docker-compose.yaml` is a byte-identical copy of `docker-compose.coolify.yml` — Coolify reads `/docker-compose.yaml`. **Whenever you edit the Coolify stack, update both `docker-compose.coolify.yml` and `docker-compose.yaml` identically.** Local dev uses `docker-compose.yml` (PostgreSQL 16 on port 5432). Pass `-f docker-compose.yml` explicitly in local dev.
## PostgreSQL & Migrations
- **Direct `pgx/v5` pool** (`internal/db/db.go`) using individual `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` params (never a raw connection string, avoiding SCRAM encoding issues).
- **Schema compatibility:** All 25 tables preserve exact quoted PascalCase table names (`"Cotizacion"`, `"PagoRecurrente"`, etc.) and quoted camelCase columns (`"tipoPago"`, `"vencidoNotificadoAt"`, etc.) from the live production database `cotizador_e3`.
- **Migrations:** Idempotent SQL files in `internal/db/migrations/*.sql`, tracked in `"_go_migrations"`, executed automatically on `cotizador serve` startup (safe on both empty DBs and live production DBs).
- **IDs:** `db.NewID()` generates CUID-like URL-safe IDs. Seed service IDs are slugs (e.g. `auditoria-en-sitio-web-2`); never validate IDs by format.
## Domain & Business Rules (`internal/domain/`)
- **`internal/domain/calculators.go`** is the single source of truth for totals, charge models, phases, financing, Bucéfalo CRM prices, hours ranges, and formatting (mirrored for UI previews in `web/src/lib/calculators.ts`).
- Cotización number format: `UJ{YY}{MM}{AsesorInitials}{seq}` (3-digit zero-padded sequence).
- Vigencia = 15 business days from `fecha` (excludes Sat/Sun). `IVA_RATE = 0.16` (16%).
- **Bucéfalo CRM plan prices:** basico=\$1,000, estandar=\$3,500, premium=\$4,500, empresarial=\$7,500 (monthly).
- **Financing (`FinanciamientoPlan` 3/6/9/12 months):** `comisionTotal = monto × comision%`, `pagoMensual = (monto + comisionTotal) × (1 + tasa) / meses`, then +16% IVA.
- **Charge models (`ServicioCotizado.modeloCobro`):** `fijo` (default), `horas`, `retainer`, `demanda`. `TARIFA_HORA_DEFAULT = 700`. **`precio` is always the authoritative total** — never re-derive totals from `horas × tarifaHora` for retainer/demanda lines.
- **Doble propuesta (`Cotizacion.esDoble`):** `ServicioCotizado.opcion` is `"1"`, `"2"`, or `"ambas"`. `CalcularTotalesOpcion` sums lines matching the option **plus** `"ambas"`.
- **Registro de horas (`RegistroHoras`):** `estadoPago` is `"por_pagar"` or `"pagada"` (`fechaPago` stamped on transition). Pending and paid totals stay separated (`ResumenPagoHoras`). Dates use `FechaRegistroDesdeISO` to avoid UTC off-by-one. Grouping modes: `detalle | dia | semana | mes`.
- **`Configuracion`:** Key-value store (`clave`/`valor`), including branding (`color_primario`, `color_secundario`, `logo_base64`) and bank transfer info.
- **Internal notes:** `observacionesInternas` must NEVER leak into PDFs, Excel exports, client portal responses, or `soloAceptadas` agent responses.
## Auth, Panel Isolation & Iron-Clad Rules (`internal/auth/`)
- **JWT sessions** signed with HS256 (`golang-jwt/jwt/v5`, 7-day expiry) in httpOnly cookie `cotizador-session`. `JWT_SECRET` is required at server startup. Passwords hashed with `bcrypt` (cost 10).
- **Roles:** `admin`, `asesor` (staff) and `cliente` (client portal).
- Staff routes call `Auth.RequireActor(...)` inside every handler; client portal routes (`/api/cliente/*`) call `Auth.RequireCliente(...)`.
- Shared routes (`/api/comprobantes/{pagoId}`, `/api/export/pdf/{id}`) explicitly validate ownership when `role == "cliente"`.
- **Agent API Keys (`AgentApiKey`):** Prefixed `ujc_live_*`, SHA-256 hashed in PostgreSQL, 60s sliding-window in-memory rate limit, exact **9 scopes** (`catalogo:leer`, `clientes:leer`, `clientes:escribir`, `cotizaciones:leer`, `cotizaciones:leer_aceptadas`, `cotizaciones:borrador`, `cotizaciones:enviar`, `cobros:leer`, `cobros:registrar`).
- **Iron-clad approval rule:** No agent can ever approve quotes (never add an approval scope). States: `borrador → aprobada → enviada → aceptada | rechazada | vencida`. Approval requires human `role="admin"` (`POST /api/cotizaciones/{id}/aprobar`) or one-time signed link (`/aprobar/{token}` + `POST { confirmar: true }`). Sending (`POST /api/cotizaciones/{id}/enviar`) requires `estado == "aprobada" && aprobadaAt != nil`.
- **`soloAdmin` items:** Catalog services marked `soloAdmin = true` (e.g. Bucéfalo CRM items) and quotes containing them are hidden/blocked from agents (`internal/domain/solo_admin_core.go`).
- **Idempotency & Audit:** `internal/idempotency/` guards `POST /api/cotizaciones`, `POST /api/cotizaciones/{id}/enviar`, `POST /api/clientes`, and `POST /api/cobros/pagos/{id}/registrar`. Security-relevant events and blocked attempts are written to `AuditLog` (`internal/audit/`).
- **Webhooks (`internal/webhooks/`):** HMAC-SHA256 (`X-Cotizador-Signature: sha256=...`), 3 retries, 8s timeout, `WebhookDelivery` log, automatic `WEBHOOK_N8N_URL`/`WEBHOOK_N8N_SECRET` fan-out.
## Cobros recurrentes, Notificaciones & Subidas
- **Dates (`internal/domain/cobros_fechas.go`):** Calendar dates in `America/Mexico_City` persisted as UTC midnight (`ParseFechaCalendario`, `FormatFechaCobro`, `InstanteDePago`). Never parse `YYYY-MM-DD` with local timezone blindly.
- **Anular vs delete:** Cancelling a charge marks `estado = "anulado"` (never deletes the row, otherwise `GenerarCobros` recreates it as `pendiente`).
- **Scheduler (`internal/scheduler/`):** Runs 20s after boot and every 60 min — runs overdue reminders first (from 9:00 MX when `COBROS_RECORDATORIO_DIAS > 0`), then `GenerarCobros` + `NotificarCobrosNuevos`, plus idempotent `pago.vencido` webhook emission.
- **Uploads (`internal/uploads/`):** Stored in `UPLOAD_DIR/comprobantes/<pagoId>/<uuid>.<ext>` (max 10 MB, path-traversal guarded). Pure-Go image resize (max 1920 px) + WebP encoding (`nativewebp`); PDFs saved as-is.
- **Notifications (`internal/notify/`):** Best-effort SMTP MIME (HTML + text + PDF attachments) and Web Push VAPID (`webpush-go`). Missing SMTP/VAPID config logs a warning and never breaks the flow.
## PDF, Excel & Propuesta IA
- **PDFs (`internal/pdf/`):** Pure Go (`codeberg.org/go-pdf/fpdf`) with embedded UTF-8 Go fonts and PNG/JPEG/WebP logo support: quote PDF, hours payment note PDF, consultative proposal PDF, and separate red-banner internal annex PDF.
- **Excel & CSV (`internal/excel/`):** `excelize/v2` for quote workbooks (`HOJA RESUMEN` + per-service tabs, never leaking `observacionesInternas` or `domicilioFiscal`) and catalog CSV export/template/import.
- **Propuesta IA (`internal/propuesta/`):** MiniMax Anthropic-compatible API (`MINIMAX_API_KEY`, `MINIMAX_BASE_URL`, `MINIMAX_MODEL`) with deterministic economic ratio calculation, validation, and auto-reparation.
## Frontend SPA (`web/`) & UI Conventions
- React 19 + TypeScript + Vite 6 + Tailwind CSS v4 + React Router v7 + Zustand + `lucide-react`.
- Compiled to `web/dist/` and embedded in the Go binary (`internal/spa/dist/`). Static assets under `/assets/*` are served immutable; `/sw.js` and `index.html` are served `no-cache`; all non-API paths fall back to `index.html`.
- **Never use native browser `confirm()` / `alert()` / `prompt()`.** Use `useConfirm()`, `usePrompt()`, `useToast()` from `web/src/components/ui/DialogProvider.tsx`.
- Everything user-facing is in **Spanish**, using CSS custom properties from `web/src/index.css`.
## Deployment (Coolify)
- Production stack: `postgres` + `web` (single Go container, port 3000, `https://cotizador.urieljareth.org`).
- Coolify app (`cotizador`, uuid `e6vie34d83iv5vw3eyzinl3s`) uses **Docker Compose Location `/docker-compose.yaml`** — keep `docker-compose.coolify.yml` and `docker-compose.yaml` byte-identical.
- **Deploys come from GitHub `main` (`origin`), not Gitea.** Auto-deploy is on: pushing to `origin main` triggers deployment; pushing to `gitea` mirrors the repo.
- `APP_URL` must be set to `https://cotizador.urieljareth.org` in Coolify.
- `postgres_data` (`cotizador_e3`) and `uploads_data` (`/app/uploads`) volumes are preserved across deploys.
- Healthcheck: `GET /api/health` (pings PostgreSQL and returns `{"status":"ok","runtime":"go",...}`).
- `*.xlsx` is gitignored (business files must never be committed).
## Architecture
```
cmd/cotizador/ # Unified binary entrypoint (serve, migrate, seed, provision-keys, cli)
internal/
config/ # Env var loading
db/ # pgxpool connector, CUID generator, embedded SQL migrations
domain/ # Business logic: calculators, cobros dates, approval & soloAdmin rules
auth/ # JWT sessions, bcrypt, AgentApiKey SHA-256, 9 scopes, rate limiter
audit/ # AuditLog writer
idempotency/ # 24h Idempotency-Key store
webhooks/ # HMAC-SHA256 dispatcher, n8n WhatsApp invoker, delivery log
uploads/ # Pure-Go WebP converter & receipt file storage
notify/ # SMTP MIME + Web Push VAPID + domain email/push notifications
scheduler/ # Recurring charge generation & overdue reminders
pdf/ # Quote, hours-note, consultative proposal & internal annex PDFs
excel/ # Quote Excel workbook & catalog CSV export/import
propuesta/ # MiniMax AI consultative proposal pipeline
seed/ # Idempotent catalog/config/user seed & agent key provisioning
cli/ # Self-describing LLM-friendly CLI (30 commands, JSON stdout/stderr)
spa/ # //go:embed Vite SPA handler
httpapi/ # chi/v5 router & all REST handlers + OpenAPI 3.1
web/ # Vite + React 19 + Tailwind v4 SPA (staff app + client portal + /aprobar/:token)
docs/ # Product & migration docs
```