11 KiB
11 KiB
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:distininternal/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/v5pool (internal/db/db.go) using individualDB_HOST,DB_PORT,DB_USER,DB_PASSWORD,DB_NAMEparams (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 databasecotizador_e3. - Migrations: Idempotent SQL files in
internal/db/migrations/*.sql, tracked in"_go_migrations", executed automatically oncotizador servestartup (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.gois the single source of truth for totals, charge models, phases, financing, Bucéfalo CRM prices, hours ranges, and formatting (mirrored for UI previews inweb/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 (
FinanciamientoPlan3/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.preciois always the authoritative total — never re-derive totals fromhoras × tarifaHorafor retainer/demanda lines. - Doble propuesta (
Cotizacion.esDoble):ServicioCotizado.opcionis"1","2", or"ambas".CalcularTotalesOpcionsums lines matching the option plus"ambas". - Registro de horas (
RegistroHoras):estadoPagois"por_pagar"or"pagada"(fechaPagostamped on transition). Pending and paid totals stay separated (ResumenPagoHoras). Dates useFechaRegistroDesdeISOto 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:
observacionesInternasmust NEVER leak into PDFs, Excel exports, client portal responses, orsoloAceptadasagent responses.
Auth, Panel Isolation & Iron-Clad Rules (internal/auth/)
- JWT sessions signed with HS256 (
golang-jwt/jwt/v5, 7-day expiry) in httpOnly cookiecotizador-session.JWT_SECRETis required at server startup. Passwords hashed withbcrypt(cost 10). - Roles:
admin,asesor(staff) andcliente(client portal).- Staff routes call
Auth.RequireActor(...)inside every handler; client portal routes (/api/cliente/*) callAuth.RequireCliente(...). - Shared routes (
/api/comprobantes/{pagoId},/api/export/pdf/{id}) explicitly validate ownership whenrole == "cliente".
- Staff routes call
- Agent API Keys (
AgentApiKey): Prefixedujc_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 humanrole="admin"(POST /api/cotizaciones/{id}/aprobar) or one-time signed link (/aprobar/{token}+POST { confirmar: true }). Sending (POST /api/cotizaciones/{id}/enviar) requiresestado == "aprobada" && aprobadaAt != nil. soloAdminitems: Catalog services markedsoloAdmin = 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/guardsPOST /api/cotizaciones,POST /api/cotizaciones/{id}/enviar,POST /api/clientes, andPOST /api/cobros/pagos/{id}/registrar. Security-relevant events and blocked attempts are written toAuditLog(internal/audit/). - Webhooks (
internal/webhooks/): HMAC-SHA256 (X-Cotizador-Signature: sha256=...), 3 retries, 8s timeout,WebhookDeliverylog, automaticWEBHOOK_N8N_URL/WEBHOOK_N8N_SECRETfan-out.
Cobros recurrentes, Notificaciones & Subidas
- Dates (
internal/domain/cobros_fechas.go): Calendar dates inAmerica/Mexico_Citypersisted as UTC midnight (ParseFechaCalendario,FormatFechaCobro,InstanteDePago). Never parseYYYY-MM-DDwith local timezone blindly. - Anular vs delete: Cancelling a charge marks
estado = "anulado"(never deletes the row, otherwiseGenerarCobrosrecreates it aspendiente). - Scheduler (
internal/scheduler/): Runs 20s after boot and every 60 min — runs overdue reminders first (from 9:00 MX whenCOBROS_RECORDATORIO_DIAS > 0), thenGenerarCobros+NotificarCobrosNuevos, plus idempotentpago.vencidowebhook emission. - Uploads (
internal/uploads/): Stored inUPLOAD_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/v2for quote workbooks (HOJA RESUMEN+ per-service tabs, never leakingobservacionesInternasordomicilioFiscal) 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.jsandindex.htmlare servedno-cache; all non-API paths fall back toindex.html. - Never use native browser
confirm()/alert()/prompt(). UseuseConfirm(),usePrompt(),useToast()fromweb/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, uuide6vie34d83iv5vw3eyzinl3s) uses Docker Compose Location/docker-compose.yaml— keepdocker-compose.coolify.ymlanddocker-compose.yamlbyte-identical. - Deploys come from GitHub
main(origin), not Gitea. Auto-deploy is on: pushing toorigin maintriggers deployment; pushing togiteamirrors the repo. APP_URLmust be set tohttps://cotizador.urieljareth.orgin Coolify.postgres_data(cotizador_e3) anduploads_data(/app/uploads) volumes are preserved across deploys.- Healthcheck:
GET /api/health(pings PostgreSQL and returns{"status":"ok","runtime":"go",...}). *.xlsxis 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