Compare commits
12
Commits
ab6080ebe7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fae832b22 | ||
|
|
b5ebcd0b86 | ||
|
|
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 integrado en el binario Go (`cmd/cotizador`). Ejecútalo desde la raíz del repo con `go run ./cmd/cotizador cli <comando>` (o `./cotizador cli <comando>`).
|
||||
|
||||
## Antes de nada
|
||||
|
||||
1. Descubre los comandos con `go run ./cmd/cotizador cli 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: `go run ./cmd/cotizador cli 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
|
||||
go run ./cmd/cotizador cli servicios listar --q "seo" --campos id,nombre,precioBase,fase
|
||||
go run ./cmd/cotizador cli servicios crear --nombre "..." --fase 1 --tipo-pago unico --precio 5000 --categoria "Desarrollo Web"
|
||||
go run ./cmd/cotizador cli servicios editar "<nombre o id>" --precio 5500
|
||||
go run ./cmd/cotizador cli cotizaciones crear --cliente "..." --empresa "..." --servicio "<nombre o id>" --servicio "<id>=4500"
|
||||
go run ./cmd/cotizador cli cotizaciones estado UJ2611AD001 enviada
|
||||
go run ./cmd/cotizador cli cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf
|
||||
```
|
||||
|
||||
Guía completa: `docs/CLI.md`.
|
||||
+6
-5
@@ -1,19 +1,20 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.claude
|
||||
api
|
||||
.opencode
|
||||
docs
|
||||
uploads
|
||||
web/node_modules
|
||||
web/dist
|
||||
cotizador
|
||||
cotizador.exe
|
||||
*.xlsx
|
||||
*.bat
|
||||
.env*
|
||||
!.env.example
|
||||
*.tsbuildinfo
|
||||
*.tmp.*
|
||||
Dockerfile
|
||||
docker-compose*.yml
|
||||
docker-compose*.yaml
|
||||
README.md
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
src/generated
|
||||
|
||||
+31
-26
@@ -1,27 +1,24 @@
|
||||
# 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 (Go + SPA)
|
||||
# Copia este archivo a .env (local) o configúralas en Coolify (producción).
|
||||
|
||||
# ── Base de datos (compartida por Next.js y el API Python) ──
|
||||
# ── Servidor ──
|
||||
PORT=3000
|
||||
|
||||
# ── Base de datos PostgreSQL ──
|
||||
# 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
|
||||
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).
|
||||
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_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
|
||||
@@ -29,30 +26,38 @@ SEED_ASESOR_EMAIL=
|
||||
SEED_ASESOR_PASSWORD=
|
||||
SEED_ASESOR_NAME=
|
||||
|
||||
# --- Propuesta consultiva con IA (MiniMax) ---
|
||||
# Clave del panel de MiniMax. NUNCA se commitea: .env esta 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.
|
||||
# ── Propuesta consultiva con IA (MiniMax) ──
|
||||
# Sin MINIMAX_API_KEY el botón de generar devuelve un error claro; el resto funciona igual.
|
||||
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"
|
||||
# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log).
|
||||
# ── Notificaciones (panel de cliente y aprobación) ──
|
||||
# Web Push (VAPID). Sin claves se omiten las notificaciones push con 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 para links de correo, aprobación y notificaciones push.
|
||||
APP_URL=http://localhost:3000
|
||||
|
||||
# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log)
|
||||
# SMTP de correos (opcional: sin SMTP_HOST se omite el envío con aviso 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.
|
||||
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
||||
# Recordatorio automático de pagos pendientes (días desde las 9:00 hora de México; 0 = apagado)
|
||||
COBROS_RECORDATORIO_DIAS=3
|
||||
|
||||
# Directorio de comprobantes. Local: vacío = <repo>/uploads. En Coolify: /app/uploads.
|
||||
UPLOAD_DIR=
|
||||
|
||||
# ── API de agentes, aprobación humana y webhooks HMAC-SHA256 ──
|
||||
# Correo para 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=
|
||||
|
||||
+23
-55
@@ -1,65 +1,33 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
# Frontend dependencies & build output
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
# Embedded SPA build output (keep placeholder index.html so `go test` / `go build` works from fresh clone)
|
||||
internal/spa/dist/*
|
||||
!internal/spa/dist/index.html
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
# Compiled Go binaries
|
||||
/cotizador
|
||||
/cotizador.exe
|
||||
*.exe
|
||||
*.test
|
||||
*.out
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
# Environment files
|
||||
.env*
|
||||
!.env.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# python api (api/)
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
/src/generated/prisma
|
||||
|
||||
# business files (never commit quotation spreadsheets)
|
||||
# Business files (never commit quotation spreadsheets)
|
||||
*.xlsx
|
||||
|
||||
# editor temp files
|
||||
# Uploaded payment receipts (root only; do not ignore internal/uploads Go package)
|
||||
/uploads/
|
||||
|
||||
# OS / editor / local agent artifacts
|
||||
.DS_Store
|
||||
*.pem
|
||||
*.tmp.*
|
||||
|
||||
# claude local settings
|
||||
npm-debug.log*
|
||||
.claude/settings.local.json
|
||||
|
||||
# Comprobantes de pago subidos por los clientes (nunca se commitean)
|
||||
uploads/
|
||||
.opencode/
|
||||
.mimocode/
|
||||
|
||||
@@ -1,142 +1,117 @@
|
||||
# AGENTS.md — Cotizador E3
|
||||
# AGENTS.md — Cotizador — Uriel Jareth Consulting (Go + Vite SPA)
|
||||
|
||||
## 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 |
|
||||
| `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/` |
|
||||
|
||||
**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 + SPA build + Go server together. PowerShell is the shell.
|
||||
|
||||
**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`.
|
||||
**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`)
|
||||
|
||||
**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`.
|
||||
**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.
|
||||
|
||||
**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.
|
||||
## PostgreSQL & Migrations
|
||||
|
||||
## Prisma 7 — Critical Gotchas
|
||||
- **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.
|
||||
|
||||
- **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.
|
||||
## Domain & Business Rules (`internal/domain/`)
|
||||
|
||||
## PDFKit — Server-Side PDF
|
||||
- **`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.
|
||||
|
||||
- `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<Buffer>` — convert to `Uint8Array` for `NextResponse` body.
|
||||
## Auth, Panel Isolation & Iron-Clad Rules (`internal/auth/`)
|
||||
|
||||
## Next.js 16 Conventions
|
||||
- **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.
|
||||
|
||||
- **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`.
|
||||
## Cobros recurrentes, Notificaciones & Subidas
|
||||
|
||||
## Data Model Notes
|
||||
- **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.
|
||||
|
||||
- **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.
|
||||
## PDF, Excel & Propuesta IA
|
||||
|
||||
### Charge models (`ServicioCotizado.modeloCobro`)
|
||||
- **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.
|
||||
|
||||
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`.
|
||||
## Frontend SPA (`web/`) & UI Conventions
|
||||
|
||||
**`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.
|
||||
- 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`.
|
||||
|
||||
## 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).
|
||||
- **`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.
|
||||
- **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.
|
||||
- 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: `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`.
|
||||
- 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).
|
||||
- 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
|
||||
|
||||
```
|
||||
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.4k lines), ExportButtons, EstadoBadge, layout/Sidebar, ui/DialogProvider
|
||||
lib/ # auth, db, store, calculators, schemas, config-helpers,
|
||||
# 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
|
||||
api/ # Standalone Python FastAPI service (see below)
|
||||
docs/ # Business/product notes (Spanish), not code docs
|
||||
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
|
||||
```
|
||||
|
||||
- **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.
|
||||
|
||||
|
||||
+33
-40
@@ -1,48 +1,41 @@
|
||||
# Cotizador E3 — 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.
|
||||
# Cotizador — Uriel Jareth Consulting — Binario unificado Go + SPA Vite embebido
|
||||
# Multi-stage build:
|
||||
# 1. node:22-alpine compila el SPA React 19 + Tailwind CSS v4 (web/dist)
|
||||
# 2. golang:1.27-alpine embebe web/dist via //go:embed y compila binario estatico (CGO_ENABLED=0)
|
||||
# 3. alpine:3.21 ejecuta el binario unico (~25 MB) con ca-certificates y tzdata
|
||||
|
||||
FROM node:22-slim AS base
|
||||
# ── Stage 1: Frontend SPA (Vite + React 19 + Tailwind v4) ──
|
||||
FROM node:22-alpine AS web-builder
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json* ./
|
||||
RUN if [ -f package-lock.json ]; then npm ci; else npm install; fi
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
# ── Stage 2: Backend Go + SPA embebido ──
|
||||
FROM golang:1.27-alpine AS go-builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd/ ./cmd/
|
||||
COPY internal/ ./internal/
|
||||
RUN rm -rf internal/spa/dist/*
|
||||
COPY --from=web-builder /web/dist/ ./internal/spa/dist/
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/cotizador ./cmd/cotizador
|
||||
|
||||
# ── Stage 3: Runtime minimo ──
|
||||
FROM alpine:3.21 AS runner
|
||||
RUN apk add --no-cache ca-certificates tzdata wget
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
COPY --from=go-builder /out/cotizador /app/cotizador
|
||||
|
||||
# ── Dependencias ──
|
||||
FROM base AS deps
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
# ── Build ──
|
||||
FROM base AS builder
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
# Placeholder solo para el build: src/lib/auth.ts lanza error al importarse
|
||||
# sin JWT_SECRET. Todas las páginas son force-dynamic, nada queda horneado.
|
||||
ENV JWT_SECRET=placeholder-build-only
|
||||
RUN npx prisma generate && npm run build
|
||||
|
||||
# ── Runtime ──
|
||||
FROM base AS runner
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
# openssl: el CLI de Prisma lo necesita para detectar la versión de libssl
|
||||
RUN apt-get update -y && apt-get install -y --no-install-recommends openssl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
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/src/generated ./src/generated
|
||||
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
|
||||
COPY --from=builder /app/next.config.ts ./next.config.ts
|
||||
COPY --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
COPY --from=builder /app/package.json ./package.json
|
||||
ENV UPLOAD_DIR=/app/uploads
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=5 \
|
||||
CMD node -e "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=5 \
|
||||
CMD wget -qO- http://localhost:3000/api/health >/dev/null || exit 1
|
||||
|
||||
# Migraciones primero, seed opcional (RUN_SEED=true), luego el servidor.
|
||||
CMD ["sh", "-c", "npx prisma migrate deploy && if [ \"$RUN_SEED\" = \"true\" ]; then npx tsx prisma/seed.ts; fi && exec node_modules/.bin/next start -p ${PORT:-3000}"]
|
||||
ENTRYPOINT ["/app/cotizador"]
|
||||
CMD ["serve"]
|
||||
|
||||
@@ -1,99 +1,59 @@
|
||||
# Cotizador E3
|
||||
# Cotizador — Uriel Jareth Consulting
|
||||
|
||||
Sistema de generación de cotizaciones para Consultoría E3 (marketing digital, Querétaro MX).
|
||||
Servicios organizados en 4 fases, dos tipos de pago (único / mensual), planes CRM Bucéfalo
|
||||
y financiamiento opcional. Exporta a PDF y Excel.
|
||||
Sistema de generación de cotizaciones, registro de horas, cobros recurrentes, propuestas consultivas con IA y portal de clientes para Uriel Jareth Consulting.
|
||||
Servicios organizados en 4 fases, dos tipos de pago (único / mensual), propuestas simples o dobles, planes CRM Bucéfalo y financiamiento opcional. Exporta a PDF y Excel.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Frontend / app web:** Next.js 16 (App Router) + React 19 + Tailwind CSS v4 + Zustand
|
||||
- **ORM:** Prisma 7 (cliente generado en `src/generated/prisma`, driver adapter `PrismaPg`)
|
||||
- **Base de datos:** PostgreSQL 16 (vía Docker)
|
||||
- **Auth:** JWT (`jose`) en cookie httpOnly, contraseñas con `bcryptjs`
|
||||
- **API alterna:** servicio Python FastAPI en [`api/`](api/) (para n8n / integraciones)
|
||||
- **Backend unificado:** Go 1.27 (`chi/v5`, `pgx/v5`, `fpdf`, `excelize/v2`, `webpush-go`, `nativewebp`, `CGO_ENABLED=0`)
|
||||
- **Frontend SPA:** React 19 + TypeScript + Vite + Tailwind CSS v4 + Zustand (compilado y embebido en el binario Go vía `//go:embed`)
|
||||
- **Base de datos:** PostgreSQL 16 (migraciones SQL idempotentes embebidas en el binario)
|
||||
- **Auth:** JWT HS256 en cookie httpOnly (`cotizador-session`) + contraseñas `bcrypt` + `AgentApiKey` SHA-256 con 9 alcances granulares y rate limit
|
||||
|
||||
## Requisitos
|
||||
## Requisitos (desarrollo local)
|
||||
|
||||
- Node.js 20+
|
||||
- Go 1.27+
|
||||
- Node.js 22+ (solo para compilar el frontend en `web/`)
|
||||
- Docker (para PostgreSQL)
|
||||
- Un archivo `.env` en la raíz — copia [.env.example](.env.example) y define al menos `JWT_SECRET`
|
||||
|
||||
## Arranque rápido (Windows)
|
||||
|
||||
```bat
|
||||
start.bat :: levanta PostgreSQL en Docker, aplica migraciones y arranca Next.js
|
||||
stop.bat :: detiene todo
|
||||
```
|
||||
|
||||
## Arranque manual
|
||||
|
||||
```bash
|
||||
docker compose up -d postgres # base de datos
|
||||
npx prisma migrate deploy # aplica migraciones
|
||||
npx tsx prisma/seed.ts # carga catálogo (idempotente)
|
||||
npm run dev # http://localhost:3000
|
||||
start.bat :: levanta PostgreSQL, compila el SPA Vite y arranca el servidor Go en :3000
|
||||
stop.bat :: detiene el servidor y PostgreSQL
|
||||
```
|
||||
|
||||
## Comandos
|
||||
|
||||
| Comando | Propósito |
|
||||
|---------|-----------|
|
||||
| `npm run dev` | Servidor de desarrollo (puerto 3000) |
|
||||
| `npm run build` | Build de producción (incluye chequeo de tipos) |
|
||||
| `npm run lint` | ESLint |
|
||||
| `npm run db:migrate` | `prisma migrate dev` |
|
||||
| `npm run db:seed` | Carga de datos semilla |
|
||||
| `npm run db:studio` | Prisma Studio |
|
||||
| `npm run db:generate` | Regenera el cliente Prisma |
|
||||
| `go run ./cmd/cotizador serve` | Inicia el servidor (aplica migraciones automáticamente) en `http://localhost:3000` |
|
||||
| `go run ./cmd/cotizador migrate` | Aplica migraciones SQL idempotentes |
|
||||
| `go run ./cmd/cotizador seed` | Carga catálogo, planes y usuarios iniciales (idempotente) |
|
||||
| `go run ./cmd/cotizador provision-keys --preset` | Provisiona llaves `AgentApiKey` en PostgreSQL |
|
||||
| `go run ./cmd/cotizador cli esquema` | Describe los 30 comandos del CLI en JSON |
|
||||
| `go test -count=1 ./...` | Ejecuta todas las pruebas unitarias y de seguridad HTTP |
|
||||
| `go vet ./...` | Análisis estático de Go |
|
||||
| `cd web && npm run dev` | Dev server de Vite con proxy `/api` → `:3000` |
|
||||
| `cd web && npm run build` | Compila el SPA en `web/dist/` |
|
||||
|
||||
## API Python (opcional)
|
||||
## API para agentes, aprobación humana y webhooks
|
||||
|
||||
```bash
|
||||
cd api
|
||||
pip install -r requirements.txt
|
||||
uvicorn main:app --reload --port 8000 # Swagger en /docs
|
||||
```
|
||||
|
||||
Referencia completa de endpoints en [`api/COTIZADOR_API_SKILL.md`](api/COTIZADOR_API_SKILL.md).
|
||||
- **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`.
|
||||
- **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`.
|
||||
|
||||
## Despliegue en Coolify
|
||||
|
||||
El stack de producción está en [docker-compose.coolify.yml](docker-compose.coolify.yml): `postgres` + `web` (Next.js) + `api` (FastAPI). El contenedor `web` aplica las migraciones de Prisma automáticamente en cada arranque.
|
||||
El stack de producción está en [docker-compose.coolify.yml](docker-compose.coolify.yml) (y su copia byte-idéntica [docker-compose.yaml](docker-compose.yaml)): `postgres` + `web` (binario Go + SPA embebido en imagen Alpine minimalista).
|
||||
|
||||
### Pasos
|
||||
1. `web` ejecuta las migraciones SQL automáticamente en cada arranque y el seed solo cuando `RUN_SEED=true`.
|
||||
2. Los volúmenes `postgres_data` (`cotizador_e3`) y `uploads_data` (`/app/uploads`) persisten entre despliegues.
|
||||
3. Healthcheck: `GET /api/health` (verifica conexión a PostgreSQL).
|
||||
4. Los despliegues automáticos se disparan al hacer push a `main` en GitHub (`origin`).
|
||||
|
||||
1. **Sube el repo a GitHub** (privado recomendado).
|
||||
2. En Coolify: **+ New Resource → Docker Compose**, conecta el repo y la rama.
|
||||
3. En la configuración del recurso, define **Docker Compose Location** = `/docker-compose.coolify.yml`.
|
||||
4. Coolify detecta los servicios y asigna dominio a `web` (puerto 3000) y `api` (puerto 8000) vía las variables `SERVICE_FQDN_*` — configura los dominios deseados en la UI.
|
||||
5. Define las variables de entorno en Coolify:
|
||||
## Documentación técnica
|
||||
|
||||
| Variable | Obligatoria | Notas |
|
||||
|----------|-------------|-------|
|
||||
| `JWT_SECRET` | Sí | `openssl rand -base64 32` |
|
||||
| `API_KEY` | Sí (para el API) | Clave para agentes/n8n |
|
||||
| `DB_PASSWORD` | Recomendada | Password de PostgreSQL (default `postgres`) |
|
||||
| `RUN_SEED` | Primer deploy | `true` solo la primera vez; luego `false` |
|
||||
| `SEED_ADMIN_EMAIL` / `SEED_ADMIN_PASSWORD` / `SEED_ADMIN_NAME` | Primer deploy | Usuario admin inicial |
|
||||
| `SEED_ASESOR_EMAIL` / `SEED_ASESOR_PASSWORD` / `SEED_ASESOR_NAME` | No | Asesor opcional |
|
||||
|
||||
6. **Deploy.** Orden de arranque: `postgres` (healthy) → `web` (migra + seed + sirve) → `api`.
|
||||
7. Después del primer despliegue exitoso, cambia `RUN_SEED` a `false` y redeploya (el seed es idempotente, pero no hace falta correrlo cada vez).
|
||||
|
||||
### Healthchecks
|
||||
|
||||
- Web: `GET /api/health` (verifica también la conexión a la BD)
|
||||
- API: `GET /health`
|
||||
|
||||
### Notas
|
||||
|
||||
- No expongas el puerto 5432: los servicios se comunican por la red interna del compose.
|
||||
- El volumen `postgres_data` persiste la base de datos entre deploys. No lo borres.
|
||||
- El API expone REST en `https://<dominio-api>` con auth por `X-API-Key` o JWT. El servidor MCP se retiro el 2026-07-28 (ver `AGENTS.md`).
|
||||
- Las versiones de `api/requirements.txt` estan fijas a proposito: un rango abierto dejo entrar `mcp` 2.0.0 y tumbo el API en produccion. Sube dependencias a proposito, no al redesplegar.
|
||||
- La fórmula de financiamiento y los cálculos viven duplicados en `src/lib/calculators.ts` y `api/app/services/calculators.py` — mantenlos en paridad.
|
||||
|
||||
## Documentación para agentes
|
||||
|
||||
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`).
|
||||
Ver [`AGENTS.md`](AGENTS.md) para convenciones, modelo de datos, reglas de negocio y guía de arquitectura.
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
.venv
|
||||
venv
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
.env*
|
||||
Dockerfile
|
||||
@@ -1,14 +0,0 @@
|
||||
# Database
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_NAME=cotizador_e3
|
||||
|
||||
# Auth
|
||||
API_KEY=change-me-to-a-secure-random-key
|
||||
JWT_SECRET=change-me-to-a-secure-jwt-secret
|
||||
|
||||
# Server
|
||||
API_HOST=0.0.0.0
|
||||
API_PORT=8000
|
||||
@@ -1,457 +0,0 @@
|
||||
# Cotizador E3 — API Documentation for AI Skills
|
||||
|
||||
## Overview
|
||||
|
||||
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.
|
||||
|
||||
**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)
|
||||
|
||||
---
|
||||
|
||||
## Domain Context
|
||||
|
||||
Consultoría E3 is a digital marketing agency in Querétaro, México. Services are organized in 4 project phases:
|
||||
|
||||
- **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
|
||||
|
||||
Two payment types:
|
||||
- **unico:** One-time payment
|
||||
- **mensual:** Monthly recurring payment
|
||||
|
||||
Currency: MXN (Mexican Pesos) or USD. IVA (tax) rate: 16%.
|
||||
|
||||
---
|
||||
|
||||
## Authentication
|
||||
|
||||
### API Key (for agents)
|
||||
```
|
||||
X-API-Key: your-api-key-here
|
||||
```
|
||||
or
|
||||
```
|
||||
Authorization: Bearer your-api-key-here
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
```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
|
||||
```
|
||||
@@ -1,19 +0,0 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=5 \
|
||||
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"
|
||||
|
||||
# --proxy-headers: necesario detrás del reverse proxy (Traefik/Coolify)
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips=*"]
|
||||
@@ -1,65 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import Header, HTTPException, status
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_DAYS = 7
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def create_access_token(data: dict) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
|
||||
to_encode.update({"exp": expire, "iat": datetime.now(timezone.utc)})
|
||||
return jwt.encode(to_encode, settings.JWT_SECRET, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict | None:
|
||||
try:
|
||||
return jwt.decode(token, settings.JWT_SECRET, algorithms=[ALGORITHM])
|
||||
except JWTError:
|
||||
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
|
||||
|
||||
|
||||
async def require_auth(
|
||||
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"}
|
||||
|
||||
if authorization:
|
||||
scheme, _, token = authorization.partition(" ")
|
||||
if scheme.lower() == "bearer" and token:
|
||||
payload = decode_token(token)
|
||||
if payload:
|
||||
return {"auth_type": "jwt", **payload}
|
||||
if x_api_key == settings.API_KEY:
|
||||
return {"auth_type": "api_key"}
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or missing authentication credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
@@ -1,18 +0,0 @@
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
DB_HOST: str = "localhost"
|
||||
DB_PORT: int = 5432
|
||||
DB_USER: str = "postgres"
|
||||
DB_PASSWORD: str = "postgres"
|
||||
DB_NAME: str = "cotizador_e3"
|
||||
API_KEY: str = "change-me-to-a-secure-random-key"
|
||||
JWT_SECRET: str = "change-me-to-a-secure-jwt-secret"
|
||||
API_HOST: str = "0.0.0.0"
|
||||
API_PORT: int = 8000
|
||||
|
||||
model_config = {"env_file": ".env", "env_file_encoding": "utf-8", "extra": "ignore"}
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -1,33 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.config import settings
|
||||
|
||||
pool: asyncpg.Pool | None = None
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
global pool
|
||||
pool = await asyncpg.create_pool(
|
||||
host=settings.DB_HOST,
|
||||
port=settings.DB_PORT,
|
||||
user=settings.DB_USER,
|
||||
password=settings.DB_PASSWORD,
|
||||
database=settings.DB_NAME,
|
||||
min_size=5,
|
||||
max_size=20,
|
||||
)
|
||||
|
||||
|
||||
async def close_db() -> None:
|
||||
global pool
|
||||
if pool:
|
||||
await pool.close()
|
||||
pool = None
|
||||
|
||||
|
||||
async def get_pool() -> asyncpg.Pool:
|
||||
if pool is None:
|
||||
raise RuntimeError("Database pool not initialized. Call init_db() first.")
|
||||
return pool
|
||||
@@ -1,37 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Query
|
||||
|
||||
from app.database import get_pool
|
||||
|
||||
|
||||
async def get_db():
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
class PaginationParams:
|
||||
def __init__(
|
||||
self,
|
||||
page: Annotated[int, Query(ge=1)] = 1,
|
||||
limit: Annotated[int, Query(ge=1, le=200)] = 50,
|
||||
):
|
||||
self.page = page
|
||||
self.limit = limit
|
||||
self.offset = (page - 1) * limit
|
||||
|
||||
|
||||
def parse_date(date_str: str | None):
|
||||
if not date_str:
|
||||
return None
|
||||
from datetime import datetime
|
||||
try:
|
||||
return datetime.fromisoformat(date_str.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -1,79 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class CategoriaBase(BaseModel):
|
||||
nombre: str = Field(..., min_length=1, description="Nombre de la categoría")
|
||||
descripcion: str | None = None
|
||||
color: str = Field("#6b7280", description="Color hex para UI")
|
||||
orden: int = Field(0, ge=0)
|
||||
|
||||
|
||||
class CategoriaCreate(CategoriaBase):
|
||||
pass
|
||||
|
||||
|
||||
class CategoriaUpdate(BaseModel):
|
||||
nombre: str | None = Field(None, min_length=1)
|
||||
descripcion: str | None = None
|
||||
color: str | None = None
|
||||
orden: int | None = Field(None, ge=0)
|
||||
activo: bool | None = None
|
||||
|
||||
|
||||
class CategoriaResponse(CategoriaBase):
|
||||
id: str
|
||||
activo: bool
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class ServicioCatalogoBase(BaseModel):
|
||||
nombre: str = Field(..., min_length=1, description="Nombre del servicio")
|
||||
descripcion: str | None = None
|
||||
fase: int = Field(..., ge=0, le=3, description="Fase: 0=Auditoría, 1=Setup, 2=Publicidad, 3=Contenido/SEO")
|
||||
tipoPago: str = Field(..., pattern="^(unico|mensual)$", description="Tipo de pago")
|
||||
precioBase: float = Field(..., ge=0, description="Precio base en la moneda local")
|
||||
tiempoEntrega: str = Field("7 - 14 dias", description="Tiempo de entrega estimado")
|
||||
entregablesDefault: list[str] = Field(default_factory=list, description="Lista de entregables")
|
||||
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")
|
||||
orden: int = Field(0, ge=0)
|
||||
|
||||
|
||||
class ServicioCatalogoCreate(ServicioCatalogoBase):
|
||||
pass
|
||||
|
||||
|
||||
class ServicioCatalogoUpdate(BaseModel):
|
||||
nombre: str | None = Field(None, min_length=1)
|
||||
descripcion: str | None = None
|
||||
fase: int | None = Field(None, ge=0, le=3)
|
||||
tipoPago: str | None = Field(None, pattern="^(unico|mensual)$")
|
||||
precioBase: float | None = Field(None, ge=0)
|
||||
tiempoEntrega: str | None = None
|
||||
entregablesDefault: list[str] | None = None
|
||||
categoriaId: str | None = None
|
||||
variante: str | None = None
|
||||
nivel: str | None = None
|
||||
activo: bool | None = None
|
||||
orden: int | None = Field(None, ge=0)
|
||||
|
||||
|
||||
class ServicioCatalogoResponse(ServicioCatalogoBase):
|
||||
id: str
|
||||
activo: bool
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
categoriaRel: CategoriaResponse | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
from app.models.cliente import ClienteResponse
|
||||
@@ -1,35 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ClienteBase(BaseModel):
|
||||
nombre: str = Field(..., min_length=1, description="Nombre completo del contacto")
|
||||
empresa: str | None = Field(None, description="Nombre de la empresa")
|
||||
email: str | None = Field(None, description="Email de contacto")
|
||||
telefono: str | None = Field(None, description="Teléfono de contacto")
|
||||
|
||||
|
||||
class ClienteCreate(ClienteBase):
|
||||
pass
|
||||
|
||||
|
||||
class ClienteUpdate(BaseModel):
|
||||
nombre: str | None = Field(None, min_length=1)
|
||||
empresa: str | None = None
|
||||
email: str | None = None
|
||||
telefono: str | None = None
|
||||
|
||||
|
||||
class ClienteResponse(ClienteBase):
|
||||
id: str
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class ClienteWithCotizaciones(ClienteResponse):
|
||||
cotizaciones: list[dict] | None = None
|
||||
@@ -1,57 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class Meta(BaseModel):
|
||||
total: int = 0
|
||||
page: int = 1
|
||||
limit: int = 50
|
||||
pages: int = 0
|
||||
|
||||
|
||||
class PaginatedResponse(BaseModel, Generic[T]):
|
||||
data: list[T]
|
||||
meta: Meta
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: str
|
||||
detail: str | None = None
|
||||
code: str | None = None
|
||||
|
||||
|
||||
class OkResponse(BaseModel):
|
||||
ok: bool = True
|
||||
|
||||
|
||||
class ArchivedResponse(BaseModel):
|
||||
ok: bool = True
|
||||
archived: bool
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str = "ok"
|
||||
timestamp: str
|
||||
database: str = "connected"
|
||||
|
||||
|
||||
class APIInfoResponse(BaseModel):
|
||||
name: str = "Cotizador E3 API"
|
||||
version: str = "1.0.0"
|
||||
description: str = "API para sistema de cotizaciones de marketing digital"
|
||||
capabilities: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
user: dict[str, Any]
|
||||
token: str | None = None
|
||||
@@ -1,41 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
ALLOWED_CONFIG_KEYS: set[str] = {
|
||||
"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",
|
||||
}
|
||||
|
||||
|
||||
class ConfigUpdate(BaseModel):
|
||||
config: dict[str, str] = Field(
|
||||
...,
|
||||
description="Key-value config pairs. Only whitelisted keys are processed.",
|
||||
json_schema_extra={
|
||||
"examples": [
|
||||
{"color_primario": "#ff0000", "razon_social": "Nueva Empresa SA de CV"}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
def get_allowed(self) -> dict[str, str]:
|
||||
return {k: v for k, v in self.config.items() if k in ALLOWED_CONFIG_KEYS}
|
||||
|
||||
|
||||
class ConfigResponse(BaseModel):
|
||||
config: dict[str, str]
|
||||
@@ -1,154 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ServicioCotizadoInput(BaseModel):
|
||||
catalogoId: str = Field(..., min_length=1, description="ID del servicio del catálogo o 'custom-...' para partidas personalizadas")
|
||||
nombre: str = Field(..., min_length=1, description="Nombre del servicio")
|
||||
fase: int = Field(..., ge=0, le=3)
|
||||
tipoPago: str = Field(..., pattern="^(unico|mensual)$")
|
||||
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)$")
|
||||
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)$")
|
||||
|
||||
|
||||
class MetaOpcionInput(BaseModel):
|
||||
titulo: str | None = None
|
||||
descripcion: str | None = None
|
||||
noIncluye: str | None = None
|
||||
|
||||
|
||||
class PlanBucefaloInput(BaseModel):
|
||||
nivel: str = Field(..., description="Nivel: basico, estandar, premium, empresarial")
|
||||
precio: float = Field(..., ge=0)
|
||||
|
||||
|
||||
class ClienteInput(BaseModel):
|
||||
nombre: str = Field(..., min_length=1)
|
||||
empresa: str = ""
|
||||
email: str = ""
|
||||
telefono: str = ""
|
||||
|
||||
|
||||
class CotizacionCreate(BaseModel):
|
||||
numero: str = Field(..., min_length=1, description="Número de cotización (formato UJ{YY}{MM}{init}{seq})")
|
||||
fecha: datetime
|
||||
vigencia: datetime
|
||||
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)$")
|
||||
incluirBonos: bool = False
|
||||
incluirFinanciamiento: bool = False
|
||||
esDoble: bool = False
|
||||
opciones: dict[str, MetaOpcionInput] | None = None
|
||||
observaciones: str = ""
|
||||
asesorId: str = Field(..., min_length=1)
|
||||
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
|
||||
vigencia: datetime | None = None
|
||||
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)$")
|
||||
incluirBonos: bool | None = None
|
||||
incluirFinanciamiento: 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)$")
|
||||
cliente: ClienteInput | None = None
|
||||
servicios: list[ServicioCotizadoInput] | None = None
|
||||
planBucefalo: PlanBucefaloInput | None = None
|
||||
|
||||
|
||||
class CambiarEstadoRequest(BaseModel):
|
||||
estado: str = Field(..., pattern="^(borrador|enviada|aprobada|rechazada)$")
|
||||
|
||||
|
||||
class ActualizarPrecioRequest(BaseModel):
|
||||
servicioId: str = Field(..., min_length=1)
|
||||
precio: float = Field(..., ge=0)
|
||||
|
||||
|
||||
class CotizacionResponse(BaseModel):
|
||||
id: str
|
||||
numero: str
|
||||
fecha: datetime
|
||||
vigencia: datetime
|
||||
moneda: str
|
||||
tipoCambio: str
|
||||
proyecto: str
|
||||
esquemaPago: str
|
||||
estado: str
|
||||
incluirBonos: bool
|
||||
incluirFinanciamiento: bool
|
||||
esDoble: bool = False
|
||||
opcionesMetadata: dict[str, Any] | None = None
|
||||
observaciones: str | None
|
||||
clienteId: str
|
||||
asesorId: str
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
cliente: dict[str, Any] | None = None
|
||||
asesor: dict[str, Any] | None = None
|
||||
servicios: list[dict[str, Any]] | None = None
|
||||
planBucefalo: dict[str, Any] | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -1,73 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ServicioDraft(BaseModel):
|
||||
nombre: str
|
||||
fase: int
|
||||
tipoPago: str
|
||||
precio: float
|
||||
tiempoEntrega: str
|
||||
entregables: list[str] = Field(default_factory=list)
|
||||
esPersonalizado: bool = False
|
||||
horas: float | None = None
|
||||
tarifaHora: float | None = None
|
||||
modeloCobro: str | None = None
|
||||
montoMinimo: float | None = None
|
||||
horasIncluidas: float | None = None
|
||||
# Doble propuesta: "1" | "2" | "ambas".
|
||||
opcion: str | None = None
|
||||
|
||||
|
||||
class MetaOpcionDraft(BaseModel):
|
||||
titulo: str | None = None
|
||||
descripcion: str | None = None
|
||||
noIncluye: str | None = None
|
||||
|
||||
|
||||
class ExportDraft(BaseModel):
|
||||
clienteNombre: str = ""
|
||||
clienteEmpresa: str = ""
|
||||
asesorNombre: str = ""
|
||||
fecha: str = ""
|
||||
moneda: str = "MXN"
|
||||
tipoCambio: str = "NA"
|
||||
proyecto: str = "MKT Digital"
|
||||
esquemaPago: str = "Pago Unico/Mensual"
|
||||
incluirBonos: bool = False
|
||||
servicios: list[ServicioDraft] = Field(default_factory=list)
|
||||
planBucefaloNivel: str | None = None
|
||||
observaciones: str = ""
|
||||
esDoble: bool = False
|
||||
opciones: dict[str, MetaOpcionDraft] | None = None
|
||||
|
||||
|
||||
class FinanciamientoRequest(BaseModel):
|
||||
monto: float = Field(..., ge=0, description="Monto total a financiar en MXN")
|
||||
meses: int = Field(..., ge=3, le=12, description="Plazo en meses: 3, 6, 9, o 12")
|
||||
|
||||
|
||||
class FinanciamientoResponse(BaseModel):
|
||||
pagoMensual: float
|
||||
ivaMensual: float
|
||||
totalMensual: float
|
||||
comisionTotal: float
|
||||
granTotal: float
|
||||
meses: int
|
||||
tasa: float
|
||||
comision: float
|
||||
|
||||
|
||||
class BonoResponse(BaseModel):
|
||||
id: str
|
||||
numero: int
|
||||
titulo: str
|
||||
descripcion: str
|
||||
activo: bool
|
||||
|
||||
|
||||
class PlanBucefaloResponse(BaseModel):
|
||||
nivel: str
|
||||
label: str
|
||||
precio: float
|
||||
@@ -1,55 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class FasePaqueteInput(BaseModel):
|
||||
nombre: str = Field(..., min_length=1)
|
||||
orden: int = Field(0, ge=0)
|
||||
|
||||
|
||||
class PaqueteCreate(BaseModel):
|
||||
nombre: str = Field(..., min_length=1, description="Nombre del paquete")
|
||||
descripcion: str | None = None
|
||||
fases: list[FasePaqueteInput] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PaqueteUpdate(BaseModel):
|
||||
nombre: str | None = Field(None, min_length=1)
|
||||
descripcion: str | None = None
|
||||
activo: bool | None = None
|
||||
|
||||
|
||||
class ManageAction(BaseModel):
|
||||
action: str = Field(..., description="Acción: addFase, updateFase, deleteFase, addServicio, removeServicio")
|
||||
faseId: str | None = None
|
||||
nombre: str | None = None
|
||||
orden: int | None = None
|
||||
servicioCatalogoId: str | None = None
|
||||
fasePaqueteId: str | None = None
|
||||
|
||||
|
||||
class FasePaqueteResponse(BaseModel):
|
||||
id: str
|
||||
paqueteId: str
|
||||
nombre: str
|
||||
orden: int
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
servicios: list[dict] | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class PaqueteResponse(BaseModel):
|
||||
id: str
|
||||
nombre: str
|
||||
descripcion: str | None
|
||||
activo: bool
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
fases: list[FasePaqueteResponse] | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -1,71 +0,0 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.auth import verify_password, create_access_token, require_auth, get_password_hash
|
||||
from app.models.common import LoginRequest, LoginResponse, OkResponse, ErrorResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
async def login(body: LoginRequest):
|
||||
pool = get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, email, password, name, role FROM "User" WHERE email = $1',
|
||||
body.email,
|
||||
)
|
||||
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas",
|
||||
)
|
||||
|
||||
if not verify_password(body.password, row["password"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas",
|
||||
)
|
||||
|
||||
token = create_access_token({"sub": str(row["id"]), "email": row["email"], "role": row["role"]})
|
||||
|
||||
return LoginResponse(
|
||||
access_token=token,
|
||||
user={
|
||||
"id": row["id"],
|
||||
"email": row["email"],
|
||||
"name": row["name"],
|
||||
"role": row["role"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/logout", response_model=OkResponse)
|
||||
async def logout():
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(current_user: dict = Depends(require_auth)):
|
||||
pool = get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, email, name, role, "createdAt", "updatedAt" FROM "User" WHERE id = $1',
|
||||
current_user["sub"],
|
||||
)
|
||||
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Usuario no encontrado",
|
||||
)
|
||||
|
||||
return {
|
||||
"id": row["id"],
|
||||
"email": row["email"],
|
||||
"name": row["name"],
|
||||
"role": row["role"],
|
||||
"createdAt": row["createdAt"].isoformat() if row["createdAt"] else None,
|
||||
"updatedAt": row["updatedAt"].isoformat() if row["updatedAt"] else None,
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.models.export_ import BonoResponse
|
||||
from app.services.calculators import BONOS
|
||||
|
||||
router = APIRouter(prefix="/bonos", tags=["Bonos"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[BonoResponse])
|
||||
async def get_bonos(_auth: dict = Depends(require_auth)):
|
||||
return [BonoResponse(**b) for b in BONOS]
|
||||
@@ -1,288 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.dependencies import get_db
|
||||
from app.models.catalogo import (
|
||||
ServicioCatalogoCreate,
|
||||
ServicioCatalogoUpdate,
|
||||
ServicioCatalogoResponse,
|
||||
CategoriaResponse,
|
||||
)
|
||||
from app.models.common import ArchivedResponse, ErrorResponse, OkResponse
|
||||
|
||||
router = APIRouter(prefix="/catalogo", tags=["Catalogo"])
|
||||
|
||||
|
||||
def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
||||
entregables = row["entregablesDefault"]
|
||||
if isinstance(entregables, str):
|
||||
entregables = json.loads(entregables)
|
||||
|
||||
categoria = None
|
||||
if categoria_row:
|
||||
categoria = CategoriaResponse(
|
||||
id=categoria_row["id"],
|
||||
nombre=categoria_row["nombre"],
|
||||
descripcion=categoria_row["descripcion"],
|
||||
color=categoria_row["color"],
|
||||
orden=categoria_row["orden"],
|
||||
activo=categoria_row["activo"],
|
||||
createdAt=categoria_row["createdAt"],
|
||||
updatedAt=categoria_row["updatedAt"],
|
||||
)
|
||||
|
||||
return ServicioCatalogoResponse(
|
||||
id=row["id"],
|
||||
nombre=row["nombre"],
|
||||
descripcion=row["descripcion"],
|
||||
fase=row["fase"],
|
||||
tipoPago=row["tipoPago"],
|
||||
precioBase=float(row["precioBase"]),
|
||||
tiempoEntrega=row["tiempoEntrega"],
|
||||
entregablesDefault=entregables,
|
||||
categoriaId=row["categoriaId"],
|
||||
variante=row["variante"],
|
||||
nivel=row["nivel"],
|
||||
activo=row["activo"],
|
||||
orden=row["orden"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
categoriaRel=categoria,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=list[ServicioCatalogoResponse],
|
||||
summary="List active catalog services with filters",
|
||||
)
|
||||
async def list_catalogo(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
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']
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if fase is not None:
|
||||
where_clauses.append(f"fase = ${idx}")
|
||||
params.append(fase)
|
||||
idx += 1
|
||||
|
||||
if tipoPago:
|
||||
where_clauses.append(f'"tipoPago" = ${idx}')
|
||||
params.append(tipoPago)
|
||||
idx += 1
|
||||
|
||||
if categoriaId:
|
||||
where_clauses.append(f'"categoriaId" = ${idx}')
|
||||
params.append(categoriaId)
|
||||
idx += 1
|
||||
|
||||
if q:
|
||||
where_clauses.append(f"(nombre ILIKE ${idx} OR descripcion ILIKE ${idx})")
|
||||
params.append(f"%{q}%")
|
||||
idx += 1
|
||||
|
||||
where_sql = f"WHERE {' AND '.join(where_clauses)}"
|
||||
|
||||
rows = await db.fetch(
|
||||
f'SELECT * FROM "ServicioCatalogo" {where_sql} ORDER BY fase ASC, orden ASC',
|
||||
*params,
|
||||
)
|
||||
|
||||
# Una sola query para todas las categorías referenciadas (evita N+1).
|
||||
cat_ids = list({r["categoriaId"] for r in rows if r["categoriaId"]})
|
||||
cat_map: dict = {}
|
||||
if cat_ids:
|
||||
cat_rows = await db.fetch(
|
||||
'SELECT * FROM "Categoria" WHERE id = ANY($1::text[])', cat_ids
|
||||
)
|
||||
cat_map = {c["id"]: c for c in cat_rows}
|
||||
|
||||
return [_row_to_response(r, cat_map.get(r["categoriaId"])) for r in rows]
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=ServicioCatalogoResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a new catalog service",
|
||||
)
|
||||
async def create_catalogo(
|
||||
body: ServicioCatalogoCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
if body.categoriaId:
|
||||
cat = await db.fetchrow(
|
||||
'SELECT id FROM "Categoria" WHERE id = $1', body.categoriaId
|
||||
)
|
||||
if not cat:
|
||||
raise HTTPException(status_code=400, detail="Categoria no encontrada")
|
||||
|
||||
entregables_json = json.dumps(body.entregablesDefault)
|
||||
|
||||
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 *",
|
||||
body.nombre,
|
||||
body.descripcion,
|
||||
body.fase,
|
||||
body.tipoPago,
|
||||
body.precioBase,
|
||||
body.tiempoEntrega,
|
||||
entregables_json,
|
||||
body.categoriaId,
|
||||
body.variante,
|
||||
body.nivel,
|
||||
body.orden,
|
||||
)
|
||||
|
||||
cat_row = None
|
||||
if row["categoriaId"]:
|
||||
cat_row = await db.fetchrow(
|
||||
'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"]
|
||||
)
|
||||
|
||||
return _row_to_response(row, cat_row)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{servicio_id}",
|
||||
response_model=ServicioCatalogoResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
summary="Get catalog service by ID with categoria join",
|
||||
)
|
||||
async def get_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||
|
||||
cat_row = None
|
||||
if row["categoriaId"]:
|
||||
cat_row = await db.fetchrow(
|
||||
'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"]
|
||||
)
|
||||
|
||||
return _row_to_response(row, cat_row)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{servicio_id}",
|
||||
response_model=ServicioCatalogoResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
summary="Update a catalog service",
|
||||
)
|
||||
async def update_catalogo(
|
||||
servicio_id: str,
|
||||
body: ServicioCatalogoUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||
|
||||
if body.categoriaId:
|
||||
cat = await db.fetchrow(
|
||||
'SELECT id FROM "Categoria" WHERE id = $1', body.categoriaId
|
||||
)
|
||||
if not cat:
|
||||
raise HTTPException(status_code=400, detail="Categoria no encontrada")
|
||||
|
||||
field_map = {
|
||||
"nombre": "nombre",
|
||||
"descripcion": "descripcion",
|
||||
"fase": "fase",
|
||||
"tipoPago": '"tipoPago"',
|
||||
"precioBase": '"precioBase"',
|
||||
"tiempoEntrega": '"tiempoEntrega"',
|
||||
"entregablesDefault": '"entregablesDefault"',
|
||||
"categoriaId": '"categoriaId"',
|
||||
"variante": "variante",
|
||||
"nivel": "nivel",
|
||||
"activo": "activo",
|
||||
"orden": "orden",
|
||||
}
|
||||
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
for field, col in field_map.items():
|
||||
value = getattr(body, field, None)
|
||||
if value is not None:
|
||||
if field == "entregablesDefault":
|
||||
value = json.dumps(value)
|
||||
updates.append(f"{col} = ${idx}")
|
||||
params.append(value)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(status_code=400, detail="No fields to update")
|
||||
|
||||
params.append(servicio_id)
|
||||
row = await db.fetchrow(
|
||||
f'UPDATE "ServicioCatalogo" SET {", ".join(updates)} WHERE id = ${idx} RETURNING *',
|
||||
*params,
|
||||
)
|
||||
|
||||
cat_row = None
|
||||
if row["categoriaId"]:
|
||||
cat_row = await db.fetchrow(
|
||||
'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"]
|
||||
)
|
||||
|
||||
return _row_to_response(row, cat_row)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{servicio_id}",
|
||||
response_model=ArchivedResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
summary="Delete or soft-delete a catalog service",
|
||||
)
|
||||
async def delete_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Servicio no encontrado")
|
||||
|
||||
ref_count = await db.fetchval(
|
||||
'SELECT COUNT(*) FROM "ServicioCotizado" WHERE "servicioCatalogoId" = $1',
|
||||
servicio_id,
|
||||
)
|
||||
|
||||
if ref_count > 0:
|
||||
await db.execute(
|
||||
'UPDATE "ServicioCatalogo" SET activo = false WHERE id = $1', servicio_id
|
||||
)
|
||||
return ArchivedResponse(ok=True, archived=True)
|
||||
|
||||
await db.execute('DELETE FROM "ServicioCatalogo" WHERE id = $1', servicio_id)
|
||||
return ArchivedResponse(ok=True, archived=False)
|
||||
@@ -1,192 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
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.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
|
||||
router = APIRouter(prefix="/categorias", tags=["Categorias"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[CategoriaResponse])
|
||||
async def list_categorias(
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
'SELECT id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"'
|
||||
' FROM "Categoria" ORDER BY orden ASC'
|
||||
)
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=CategoriaResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
responses={409: {"model": ErrorResponse}},
|
||||
)
|
||||
async def create_categoria(
|
||||
body: CategoriaCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO "Categoria" (id, nombre, descripcion, color, orden, "createdAt", "updatedAt")'
|
||||
" VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $5)"
|
||||
' RETURNING id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"',
|
||||
body.nombre,
|
||||
body.descripcion,
|
||||
body.color,
|
||||
body.orden,
|
||||
now,
|
||||
)
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower() or "duplicate" in str(e).lower():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Ya existe una categoría con el nombre '{body.nombre}'",
|
||||
)
|
||||
raise
|
||||
return dict(row)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{categoria_id}",
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def get_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
'SELECT c.id, c.nombre, c.descripcion, c.color, c.activo, c.orden,'
|
||||
' c."createdAt", c."updatedAt",'
|
||||
' COUNT(s.id)::int AS "serviciosCount"'
|
||||
' FROM "Categoria" c'
|
||||
' LEFT JOIN "ServicioCatalogo" s ON s."categoriaId" = c.id'
|
||||
" WHERE c.id = $1"
|
||||
" GROUP BY c.id",
|
||||
categoria_id,
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Categoría no encontrada",
|
||||
)
|
||||
return dict(row)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{categoria_id}",
|
||||
response_model=CategoriaResponse,
|
||||
responses={404: {"model": ErrorResponse}, 409: {"model": ErrorResponse}},
|
||||
)
|
||||
async def update_categoria(
|
||||
categoria_id: str,
|
||||
body: CategoriaUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
'SELECT id FROM "Categoria" WHERE id = $1', categoria_id
|
||||
)
|
||||
if not existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Categoría no encontrada",
|
||||
)
|
||||
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if body.nombre is not None:
|
||||
updates.append(f"nombre = ${idx}")
|
||||
params.append(body.nombre)
|
||||
idx += 1
|
||||
if body.descripcion is not None:
|
||||
updates.append(f"descripcion = ${idx}")
|
||||
params.append(body.descripcion)
|
||||
idx += 1
|
||||
if body.color is not None:
|
||||
updates.append(f"color = ${idx}")
|
||||
params.append(body.color)
|
||||
idx += 1
|
||||
if body.orden is not None:
|
||||
updates.append(f"orden = ${idx}")
|
||||
params.append(body.orden)
|
||||
idx += 1
|
||||
if body.activo is not None:
|
||||
updates.append(f"activo = ${idx}")
|
||||
params.append(body.activo)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"'
|
||||
' FROM "Categoria" WHERE id = $1',
|
||||
categoria_id,
|
||||
)
|
||||
return dict(row)
|
||||
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(datetime.now(timezone.utc))
|
||||
idx += 1
|
||||
|
||||
params.append(categoria_id)
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
f'UPDATE "Categoria" SET {", ".join(updates)} WHERE id = ${idx}'
|
||||
' RETURNING id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"',
|
||||
*params,
|
||||
)
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower() or "duplicate" in str(e).lower():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Ya existe una categoría con el nombre '{body.nombre}'",
|
||||
)
|
||||
raise
|
||||
return dict(row)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{categoria_id}",
|
||||
response_model=OkResponse,
|
||||
responses={404: {"model": ErrorResponse}, 409: {"model": ErrorResponse}},
|
||||
)
|
||||
async def delete_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
'SELECT id FROM "Categoria" WHERE id = $1', categoria_id
|
||||
)
|
||||
if not existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Categoría no encontrada",
|
||||
)
|
||||
|
||||
count = await conn.fetchval(
|
||||
'SELECT COUNT(*)::int FROM "ServicioCatalogo" WHERE "categoriaId" = $1',
|
||||
categoria_id,
|
||||
)
|
||||
if count > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Tiene {count} servicios asociados",
|
||||
)
|
||||
|
||||
await conn.execute('DELETE FROM "Categoria" WHERE id = $1', categoria_id)
|
||||
return OkResponse(ok=True)
|
||||
@@ -1,211 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.dependencies import PaginationParams, get_db
|
||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
||||
|
||||
router = APIRouter(prefix="/clientes", tags=["Clientes"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PaginatedResponse[ClienteResponse],
|
||||
summary="List clients with pagination and search",
|
||||
)
|
||||
async def list_clientes(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
pagination: PaginationParams = Depends(PaginationParams),
|
||||
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
||||
):
|
||||
where_clauses: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if q:
|
||||
where_clauses.append(
|
||||
f"(nombre ILIKE ${idx} OR empresa ILIKE ${idx} OR email ILIKE ${idx})"
|
||||
)
|
||||
params.append(f"%{q}%")
|
||||
idx += 1
|
||||
|
||||
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
|
||||
|
||||
count_row = await db.fetchrow(
|
||||
f"SELECT COUNT(*) AS total FROM \"Cliente\" {where_sql}", *params
|
||||
)
|
||||
total = count_row["total"]
|
||||
pages = math.ceil(total / pagination.limit) if total > 0 else 0
|
||||
|
||||
rows = await db.fetch(
|
||||
f'SELECT * FROM "Cliente" {where_sql} ORDER BY "createdAt" DESC '
|
||||
f"LIMIT ${idx} OFFSET ${idx + 1}",
|
||||
*params,
|
||||
pagination.limit,
|
||||
pagination.offset,
|
||||
)
|
||||
|
||||
data = [
|
||||
ClienteResponse(
|
||||
id=r["id"],
|
||||
nombre=r["nombre"],
|
||||
empresa=r["empresa"],
|
||||
email=r["email"],
|
||||
telefono=r["telefono"],
|
||||
createdAt=r["createdAt"],
|
||||
updatedAt=r["updatedAt"],
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
return PaginatedResponse(
|
||||
data=data,
|
||||
meta=Meta(total=total, page=pagination.page, limit=pagination.limit, pages=pages),
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=ClienteResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a new client",
|
||||
)
|
||||
async def create_cliente(
|
||||
body: ClienteCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'INSERT INTO "Cliente" (nombre, empresa, email, telefono) '
|
||||
"VALUES ($1, $2, $3, $4) RETURNING *",
|
||||
body.nombre,
|
||||
body.empresa,
|
||||
body.email,
|
||||
body.telefono,
|
||||
)
|
||||
return ClienteResponse(
|
||||
id=row["id"],
|
||||
nombre=row["nombre"],
|
||||
empresa=row["empresa"],
|
||||
email=row["email"],
|
||||
telefono=row["telefono"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{cliente_id}",
|
||||
response_model=ClienteResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
summary="Get client by ID with recent cotizaciones",
|
||||
)
|
||||
async def get_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
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 '
|
||||
'ORDER BY "createdAt" DESC LIMIT 10',
|
||||
cliente_id,
|
||||
)
|
||||
|
||||
cliente = ClienteResponse(
|
||||
id=row["id"],
|
||||
nombre=row["nombre"],
|
||||
empresa=row["empresa"],
|
||||
email=row["email"],
|
||||
telefono=row["telefono"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
)
|
||||
|
||||
return cliente.model_copy(
|
||||
update={"cotizaciones": [dict(c) for c in cotizaciones]}
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{cliente_id}",
|
||||
response_model=ClienteResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
summary="Update a client",
|
||||
)
|
||||
async def update_cliente(
|
||||
cliente_id: str,
|
||||
body: ClienteUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
for field in ("nombre", "empresa", "email", "telefono"):
|
||||
value = getattr(body, field, None)
|
||||
if value is not None:
|
||||
updates.append(f"{field} = ${idx}")
|
||||
params.append(value)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(status_code=400, detail="No fields to update")
|
||||
|
||||
params.append(cliente_id)
|
||||
row = await db.fetchrow(
|
||||
f'UPDATE "Cliente" SET {", ".join(updates)} WHERE id = ${idx} RETURNING *',
|
||||
*params,
|
||||
)
|
||||
|
||||
return ClienteResponse(
|
||||
id=row["id"],
|
||||
nombre=row["nombre"],
|
||||
empresa=row["empresa"],
|
||||
email=row["email"],
|
||||
telefono=row["telefono"],
|
||||
createdAt=row["createdAt"],
|
||||
updatedAt=row["updatedAt"],
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{cliente_id}",
|
||||
response_model=OkResponse,
|
||||
responses={409: {"model": ErrorResponse}, 404: {"model": ErrorResponse}},
|
||||
summary="Delete a client (fails if cotizaciones exist)",
|
||||
)
|
||||
async def delete_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
cot_count = await db.fetchval(
|
||||
'SELECT COUNT(*) FROM "Cotizacion" WHERE "clienteId" = $1', cliente_id
|
||||
)
|
||||
if cot_count > 0:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="No se puede eliminar: el cliente tiene cotizaciones asociadas",
|
||||
)
|
||||
|
||||
await db.execute('DELETE FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
return OkResponse()
|
||||
@@ -1,49 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
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
|
||||
|
||||
router = APIRouter(prefix="/configuracion", tags=["Configuración"])
|
||||
|
||||
|
||||
@router.get("", response_model=ConfigResponse)
|
||||
async def get_configuracion(
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch("SELECT clave, valor FROM Configuracion")
|
||||
config = {row["clave"]: row["valor"] for row in rows}
|
||||
return ConfigResponse(config=config)
|
||||
|
||||
|
||||
@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}})
|
||||
async def update_configuracion(
|
||||
body: ConfigUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
allowed = body.get_allowed()
|
||||
if not allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No valid config keys provided",
|
||||
)
|
||||
|
||||
async with db.transaction():
|
||||
for clave, valor in allowed.items():
|
||||
await db.execute(
|
||||
"""
|
||||
INSERT INTO "Configuracion" (id, clave, valor, "updatedAt")
|
||||
VALUES (gen_random_uuid(), $1, $2, now())
|
||||
ON CONFLICT (clave) DO UPDATE SET valor = $2, "updatedAt" = now()
|
||||
""",
|
||||
clave,
|
||||
valor,
|
||||
)
|
||||
|
||||
return OkResponse()
|
||||
@@ -1,644 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.database import get_pool
|
||||
from app.dependencies import PaginationParams, parse_date
|
||||
from app.models.common import Meta, OkResponse, PaginatedResponse
|
||||
from app.models.cotizacion import (
|
||||
ActualizarPrecioRequest,
|
||||
CambiarEstadoRequest,
|
||||
CotizacionCreate,
|
||||
CotizacionResponse,
|
||||
CotizacionUpdate,
|
||||
)
|
||||
from app.services.calculators import ESTADOS_COTIZACION
|
||||
|
||||
router = APIRouter(prefix="/cotizaciones", tags=["Cotizaciones"])
|
||||
|
||||
|
||||
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."""
|
||||
es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-")
|
||||
|
||||
if es_personalizado:
|
||||
catalogo_id = None
|
||||
elif svc.catalogoId.startswith("bucefalo-") and bucefalo_servicio_id:
|
||||
catalogo_id = bucefalo_servicio_id
|
||||
else:
|
||||
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
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "ServicioCotizado"
|
||||
(id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado",
|
||||
horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
||||
opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas,
|
||||
seleccionado, "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,true,$18,$18)
|
||||
""",
|
||||
_cuid(),
|
||||
cotizacion_id,
|
||||
catalogo_id,
|
||||
svc.nombre if es_personalizado else None,
|
||||
es_personalizado,
|
||||
svc.horas if es_personalizado else None,
|
||||
svc.tarifaHora if es_personalizado else None,
|
||||
modelo_cobro,
|
||||
svc.montoMinimo if es_personalizado else None,
|
||||
svc.horasIncluidas if es_personalizado else None,
|
||||
opcion,
|
||||
svc.fase,
|
||||
svc.tipoPago,
|
||||
svc.precio,
|
||||
svc.tiempoEntrega,
|
||||
json.dumps(svc.entregables),
|
||||
None,
|
||||
now,
|
||||
)
|
||||
|
||||
|
||||
def _parse_json(val):
|
||||
"""asyncpg devuelve columnas jsonb como str; las parsea a dict/list."""
|
||||
if isinstance(val, str):
|
||||
try:
|
||||
return json.loads(val)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return val
|
||||
|
||||
|
||||
def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=None) -> dict:
|
||||
d = dict(cot)
|
||||
if "opcionesMetadata" in d:
|
||||
d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"])
|
||||
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 []
|
||||
d["planBucefalo"] = dict(plan) if plan else None
|
||||
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"
|
||||
FROM "ServicioCotizado" sc
|
||||
LEFT JOIN "ServicioCatalogo" s ON s.id = sc."servicioCatalogoId"
|
||||
WHERE sc."cotizacionId" = {}
|
||||
ORDER BY sc.fase, sc.opcion, sc.id
|
||||
"""
|
||||
|
||||
|
||||
async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None:
|
||||
cot = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id)
|
||||
if not cot:
|
||||
return None
|
||||
|
||||
cliente = await conn.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cot["clienteId"])
|
||||
asesor = await conn.fetchrow('SELECT id, email, name, role FROM "User" WHERE id = $1', cot["asesorId"])
|
||||
servicios = await conn.fetch(_SERVICIOS_SQL.format("$1"), cot_id)
|
||||
plan = await conn.fetchrow('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', cot_id)
|
||||
|
||||
return _build_cotizacion_dict(cot, cliente, asesor, servicios, plan)
|
||||
|
||||
|
||||
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 []
|
||||
|
||||
cot_ids = [r["id"] for r in cot_rows]
|
||||
cliente_ids = list({r["clienteId"] for r in cot_rows})
|
||||
asesor_ids = list({r["asesorId"] for r in cot_rows})
|
||||
|
||||
clientes = await conn.fetch('SELECT * FROM "Cliente" WHERE id = ANY($1::text[])', cliente_ids)
|
||||
asesores = await conn.fetch('SELECT id, email, name, role FROM "User" WHERE id = ANY($1::text[])', asesor_ids)
|
||||
servicios = await conn.fetch(_SERVICIOS_SQL.format("ANY($1::text[])"), cot_ids)
|
||||
planes = await conn.fetch('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = ANY($1::text[])', cot_ids)
|
||||
|
||||
clientes_map = {c["id"]: c for c in clientes}
|
||||
asesores_map = {a["id"]: a for a in asesores}
|
||||
planes_map = {p["cotizacionId"]: p for p in planes}
|
||||
servicios_map: dict[str, list] = {}
|
||||
for s in servicios:
|
||||
servicios_map.setdefault(s["cotizacionId"], []).append(s)
|
||||
|
||||
return [
|
||||
_build_cotizacion_dict(
|
||||
cot,
|
||||
clientes_map.get(cot["clienteId"]),
|
||||
asesores_map.get(cot["asesorId"]),
|
||||
servicios_map.get(cot["id"], []),
|
||||
planes_map.get(cot["id"]),
|
||||
)
|
||||
for cot in cot_rows
|
||||
]
|
||||
|
||||
|
||||
async def _resolve_bucefalo_servicio(conn) -> str | None:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT s.id FROM "ServicioCatalogo" s
|
||||
JOIN "Categoria" c ON c.id = s."categoriaId"
|
||||
WHERE c.nombre = 'CRM' AND s."tipoPago" = 'mensual' AND s.activo = true
|
||||
ORDER BY s.orden LIMIT 1
|
||||
"""
|
||||
)
|
||||
return row["id"] if row else 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',
|
||||
nombre,
|
||||
empresa or "",
|
||||
)
|
||||
if row:
|
||||
if email or telefono:
|
||||
await conn.execute(
|
||||
'UPDATE "Cliente" SET email = COALESCE($1, email), telefono = COALESCE($2, telefono), "updatedAt" = NOW() WHERE id = $3',
|
||||
email or None,
|
||||
telefono or None,
|
||||
row["id"],
|
||||
)
|
||||
return row["id"]
|
||||
|
||||
new_id = _cuid()
|
||||
await conn.execute(
|
||||
'INSERT INTO "Cliente" (id, nombre, empresa, email, telefono, "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, NOW(), NOW())',
|
||||
new_id,
|
||||
nombre,
|
||||
empresa or None,
|
||||
email or None,
|
||||
telefono or None,
|
||||
)
|
||||
return new_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. GET /cotizaciones — List with filters + pagination
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("", response_model=PaginatedResponse[CotizacionResponse])
|
||||
async def list_cotizaciones(
|
||||
pagination: PaginationParams = Depends(),
|
||||
estado: str | None = Query(None),
|
||||
asesorId: str | None = Query(None),
|
||||
clienteId: str | None = Query(None),
|
||||
q: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
_auth: dict = Depends(require_auth),
|
||||
):
|
||||
pool = await get_pool()
|
||||
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if estado:
|
||||
conditions.append(f'c.estado = ${idx}')
|
||||
params.append(estado)
|
||||
idx += 1
|
||||
if asesorId:
|
||||
conditions.append(f'c."asesorId" = ${idx}')
|
||||
params.append(asesorId)
|
||||
idx += 1
|
||||
if clienteId:
|
||||
conditions.append(f'c."clienteId" = ${idx}')
|
||||
params.append(clienteId)
|
||||
idx += 1
|
||||
if q:
|
||||
conditions.append(
|
||||
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}')
|
||||
params.append(desde_dt)
|
||||
idx += 1
|
||||
hasta_dt = parse_date(hasta)
|
||||
if hasta_dt:
|
||||
conditions.append(f'c.fecha <= ${idx}')
|
||||
params.append(hasta_dt)
|
||||
idx += 1
|
||||
|
||||
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
||||
|
||||
count_row = await pool.fetchrow(
|
||||
f'SELECT COUNT(*) FROM "Cotizacion" c LEFT JOIN "Cliente" cl ON cl.id = c."clienteId" {where}',
|
||||
*params,
|
||||
)
|
||||
total = count_row["count"]
|
||||
|
||||
rows = await pool.fetch(
|
||||
f"""
|
||||
SELECT c.* FROM "Cotizacion" c
|
||||
LEFT JOIN "Cliente" cl ON cl.id = c."clienteId"
|
||||
{where}
|
||||
ORDER BY c."createdAt" DESC
|
||||
LIMIT ${idx} OFFSET ${idx + 1}
|
||||
""",
|
||||
*params,
|
||||
pagination.limit,
|
||||
pagination.offset,
|
||||
)
|
||||
|
||||
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
||||
|
||||
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
||||
|
||||
return PaginatedResponse(
|
||||
data=cotizaciones,
|
||||
meta=Meta(total=total, page=pagination.page, limit=pagination.limit, pages=pages),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. POST /cotizaciones — Create
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.post("", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(require_auth)):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
cliente_id = await _find_or_create_cliente(
|
||||
conn,
|
||||
body.cliente.nombre,
|
||||
body.cliente.empresa,
|
||||
body.cliente.email,
|
||||
body.cliente.telefono,
|
||||
)
|
||||
|
||||
cot_id = _cuid()
|
||||
now = datetime.now(timezone.utc)
|
||||
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)
|
||||
""",
|
||||
cot_id,
|
||||
body.numero,
|
||||
body.fecha,
|
||||
body.vigencia,
|
||||
body.moneda,
|
||||
body.tipoCambio,
|
||||
body.proyecto,
|
||||
body.esquemaPago,
|
||||
body.incluirBonos,
|
||||
body.incluirFinanciamiento,
|
||||
body.esDoble,
|
||||
opciones_json,
|
||||
body.observaciones or None,
|
||||
cliente_id,
|
||||
body.asesorId,
|
||||
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)
|
||||
|
||||
if body.planBucefalo:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "PlanBucefaloCotizacion"
|
||||
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,true,$5,$5)
|
||||
""",
|
||||
_cuid(),
|
||||
cot_id,
|
||||
body.planBucefalo.nivel,
|
||||
body.planBucefalo.precio,
|
||||
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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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")
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. PUT /cotizaciones/{id} — Update
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.put("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def update_cotizacion(
|
||||
cotizacion_id: str,
|
||||
body: CotizacionUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
existing = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
async with conn.transaction():
|
||||
cliente_id = existing["clienteId"]
|
||||
if body.cliente:
|
||||
cliente_id = await _find_or_create_cliente(
|
||||
conn,
|
||||
body.cliente.nombre,
|
||||
body.cliente.empresa,
|
||||
body.cliente.email,
|
||||
body.cliente.telefono,
|
||||
)
|
||||
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
def _add(field: str, col: str, val):
|
||||
nonlocal idx
|
||||
if val is not None:
|
||||
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.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
|
||||
|
||||
if cliente_id != existing["clienteId"]:
|
||||
updates.append(f'"clienteId" = ${idx}')
|
||||
params.append(cliente_id)
|
||||
idx += 1
|
||||
|
||||
if updates:
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(datetime.now(timezone.utc))
|
||||
idx += 1
|
||||
params.append(cotizacion_id)
|
||||
await conn.execute(
|
||||
f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}',
|
||||
*params,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
if body.planBucefalo is not None:
|
||||
existing_plan = await conn.fetchrow(
|
||||
'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',
|
||||
body.planBucefalo.nivel,
|
||||
body.planBucefalo.precio,
|
||||
now,
|
||||
existing_plan["id"],
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "PlanBucefaloCotizacion"
|
||||
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,true,$5,$5)
|
||||
""",
|
||||
_cuid(),
|
||||
cotizacion_id,
|
||||
body.planBucefalo.nivel,
|
||||
body.planBucefalo.precio,
|
||||
now,
|
||||
)
|
||||
elif body.planBucefalo is None and "planBucefalo" in body.model_fields_set:
|
||||
await conn.execute(
|
||||
'DELETE FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. DELETE /cotizaciones/{id}
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.delete("/{cotizacion_id}", response_model=OkResponse)
|
||||
async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
pool = await get_pool()
|
||||
existing = await pool.fetchrow('SELECT id 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)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. PATCH /cotizaciones/{id}/precio
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.patch("/{cotizacion_id}/precio", response_model=OkResponse)
|
||||
async def update_precio_servicio(
|
||||
cotizacion_id: str,
|
||||
body: ActualizarPrecioRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
):
|
||||
pool = await get_pool()
|
||||
cot = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not cot:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
svc = await pool.fetchrow(
|
||||
'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2',
|
||||
body.servicioId,
|
||||
cotizacion_id,
|
||||
)
|
||||
if not svc:
|
||||
raise HTTPException(status_code=404, detail="Servicio no pertenece a esta cotización")
|
||||
|
||||
await pool.execute(
|
||||
'UPDATE "ServicioCotizado" SET precio = $1, "updatedAt" = NOW() WHERE id = $2',
|
||||
body.precio,
|
||||
body.servicioId,
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. PATCH /cotizaciones/{id}/estado
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.patch("/{cotizacion_id}/estado", response_model=OkResponse)
|
||||
async def cambiar_estado(
|
||||
cotizacion_id: str,
|
||||
body: CambiarEstadoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
):
|
||||
if body.estado not in ESTADOS_COTIZACION:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"Estado inválido. Permitidos: {', '.join(ESTADOS_COTIZACION)}",
|
||||
)
|
||||
|
||||
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":
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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)):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not original:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
servicios = await conn.fetch(
|
||||
'SELECT * FROM "ServicioCotizado" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
plan = await conn.fetchrow(
|
||||
'SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
async with conn.transaction():
|
||||
now = datetime.now(timezone.utc)
|
||||
new_id = _cuid()
|
||||
new_numero = original["numero"] + "-COPY"
|
||||
|
||||
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)
|
||||
""",
|
||||
new_id,
|
||||
new_numero,
|
||||
original["fecha"],
|
||||
original["vigencia"],
|
||||
original["moneda"],
|
||||
original["tipoCambio"],
|
||||
original["proyecto"],
|
||||
original["esquemaPago"],
|
||||
original["incluirBonos"],
|
||||
original["incluirFinanciamiento"],
|
||||
original["esDoble"],
|
||||
original["opcionesMetadata"],
|
||||
original["observaciones"],
|
||||
original["clienteId"],
|
||||
original["asesorId"],
|
||||
now,
|
||||
)
|
||||
|
||||
for svc in servicios:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "ServicioCotizado"
|
||||
(id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado",
|
||||
horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas",
|
||||
opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas,
|
||||
seleccionado, "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$19)
|
||||
""",
|
||||
_cuid(),
|
||||
new_id,
|
||||
svc["servicioCatalogoId"],
|
||||
svc["nombre"],
|
||||
svc["esPersonalizado"],
|
||||
svc["horas"],
|
||||
svc["tarifaHora"],
|
||||
svc["modeloCobro"],
|
||||
svc["montoMinimo"],
|
||||
svc["horasIncluidas"],
|
||||
svc["opcion"],
|
||||
svc["fase"],
|
||||
svc["tipoPago"],
|
||||
svc["precio"],
|
||||
svc["tiempoEntrega"],
|
||||
svc["entregables"],
|
||||
svc["notas"],
|
||||
svc["seleccionado"],
|
||||
now,
|
||||
)
|
||||
|
||||
if plan:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "PlanBucefaloCotizacion"
|
||||
(id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$6)
|
||||
""",
|
||||
_cuid(),
|
||||
new_id,
|
||||
plan["nivel"],
|
||||
plan["precio"],
|
||||
plan["seleccionado"],
|
||||
now,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, new_id)
|
||||
return full
|
||||
@@ -1,362 +0,0 @@
|
||||
"""Export endpoints — PDF, Excel, CSV generation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import PlainTextResponse, Response
|
||||
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.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
|
||||
|
||||
router = APIRouter(prefix="/export", tags=["Export"])
|
||||
|
||||
|
||||
async def _load_branding(db: Connection) -> dict[str, str]:
|
||||
rows = await db.fetch('SELECT clave, valor FROM "Configuracion"')
|
||||
return {r["clave"]: r["valor"] for r in rows}
|
||||
|
||||
|
||||
def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) -> dict[str, Any]:
|
||||
fecha = datetime.now()
|
||||
if draft.fecha:
|
||||
try:
|
||||
fecha = datetime.fromisoformat(draft.fecha.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
try:
|
||||
fecha = datetime.strptime(draft.fecha, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
vigencia = calcular_vigencia(fecha)
|
||||
logo_raw = branding.get("logo_base64", "")
|
||||
logo_mime = None
|
||||
logo_b64 = None
|
||||
if logo_raw and ":" in logo_raw:
|
||||
parts = logo_raw.split(":", 1)
|
||||
logo_mime = parts[0]
|
||||
logo_b64 = parts[1]
|
||||
elif logo_raw:
|
||||
logo_b64 = logo_raw
|
||||
|
||||
return {
|
||||
"numero": "BORRADOR",
|
||||
"clienteNombre": draft.clienteNombre,
|
||||
"clienteEmpresa": draft.clienteEmpresa,
|
||||
"asesorNombre": draft.asesorNombre,
|
||||
"fecha": fecha,
|
||||
"vigencia": vigencia,
|
||||
"moneda": draft.moneda,
|
||||
"tipoCambio": draft.tipoCambio,
|
||||
"proyecto": draft.proyecto,
|
||||
"esquemaPago": draft.esquemaPago,
|
||||
"servicios": [
|
||||
{
|
||||
"nombre": s.nombre,
|
||||
"fase": s.fase,
|
||||
"tipoPago": s.tipoPago,
|
||||
"precio": s.precio,
|
||||
"tiempoEntrega": s.tiempoEntrega,
|
||||
"entregables": s.entregables,
|
||||
"esPersonalizado": s.esPersonalizado,
|
||||
"horas": s.horas,
|
||||
"tarifaHora": s.tarifaHora,
|
||||
"modeloCobro": s.modeloCobro,
|
||||
"montoMinimo": s.montoMinimo,
|
||||
"horasIncluidas": s.horasIncluidas,
|
||||
"opcion": s.opcion,
|
||||
}
|
||||
for s in draft.servicios
|
||||
],
|
||||
"esDoble": draft.esDoble,
|
||||
"opcionesMetadata": (
|
||||
{k: v.model_dump() for k, v in draft.opciones.items()} if draft.esDoble and draft.opciones else None
|
||||
),
|
||||
"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"),
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
}
|
||||
|
||||
|
||||
async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[str, Any] | None:
|
||||
cot = await db.fetchrow(
|
||||
"""SELECT c.*, cl.nombre as cliente_nombre, cl.empresa as cliente_empresa,
|
||||
u.name as asesor_nombre
|
||||
FROM "Cotizacion" c
|
||||
LEFT JOIN "Cliente" cl ON cl.id = c."clienteId"
|
||||
LEFT JOIN "User" u ON u.id = c."asesorId"
|
||||
WHERE c.id = $1""",
|
||||
cotizacion_id,
|
||||
)
|
||||
if not cot:
|
||||
return None
|
||||
|
||||
servicios = await db.fetch(
|
||||
"""SELECT sc.fase, sc."tipoPago", sc.precio, sc."tiempoEntrega", sc.entregables,
|
||||
sc."esPersonalizado", sc.horas, sc."tarifaHora", sc."modeloCobro",
|
||||
sc."montoMinimo", sc."horasIncluidas", sc.opcion,
|
||||
COALESCE(s.nombre, sc.nombre) AS nombre
|
||||
FROM "ServicioCotizado" sc
|
||||
LEFT JOIN "ServicioCatalogo" s ON s.id = sc."servicioCatalogoId"
|
||||
WHERE sc."cotizacionId" = $1 AND sc.seleccionado = true
|
||||
ORDER BY sc.fase, sc.opcion, sc.id""",
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
plan = await db.fetchrow(
|
||||
'SELECT nivel, precio FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
branding = await _load_branding(db)
|
||||
|
||||
logo_raw = branding.get("logo_base64", "")
|
||||
logo_mime = None
|
||||
logo_b64 = None
|
||||
if logo_raw and ":" in logo_raw:
|
||||
parts = logo_raw.split(":", 1)
|
||||
logo_mime = parts[0]
|
||||
logo_b64 = parts[1]
|
||||
elif logo_raw:
|
||||
logo_b64 = logo_raw
|
||||
|
||||
servicios_list = []
|
||||
for s in servicios:
|
||||
ent = s["entregables"]
|
||||
if isinstance(ent, str):
|
||||
try:
|
||||
ent = json.loads(ent)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
ent = []
|
||||
servicios_list.append({
|
||||
"nombre": s["nombre"] or "Servicio",
|
||||
"fase": s["fase"],
|
||||
"tipoPago": s["tipoPago"],
|
||||
"precio": float(s["precio"]),
|
||||
"tiempoEntrega": s["tiempoEntrega"],
|
||||
"entregables": ent or [],
|
||||
"esPersonalizado": s["esPersonalizado"],
|
||||
"horas": float(s["horas"]) if s["horas"] is not None else None,
|
||||
"tarifaHora": float(s["tarifaHora"]) if s["tarifaHora"] is not None else None,
|
||||
"modeloCobro": s["modeloCobro"],
|
||||
"montoMinimo": float(s["montoMinimo"]) if s["montoMinimo"] is not None else None,
|
||||
"horasIncluidas": float(s["horasIncluidas"]) if s["horasIncluidas"] is not None else None,
|
||||
"opcion": s["opcion"],
|
||||
})
|
||||
|
||||
opciones_meta = cot["opcionesMetadata"]
|
||||
if isinstance(opciones_meta, str):
|
||||
try:
|
||||
opciones_meta = json.loads(opciones_meta)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
opciones_meta = None
|
||||
|
||||
plan_nivel = plan["nivel"] if plan else None
|
||||
|
||||
return {
|
||||
"numero": cot["numero"],
|
||||
"clienteNombre": cot["cliente_nombre"] or "",
|
||||
"clienteEmpresa": cot["cliente_empresa"] or "",
|
||||
"asesorNombre": cot["asesor_nombre"] or "",
|
||||
"fecha": cot["fecha"],
|
||||
"vigencia": cot["vigencia"],
|
||||
"moneda": cot["moneda"],
|
||||
"tipoCambio": cot["tipoCambio"],
|
||||
"proyecto": cot["proyecto"],
|
||||
"esquemaPago": cot["esquemaPago"],
|
||||
"servicios": servicios_list,
|
||||
"esDoble": cot["esDoble"],
|
||||
"opcionesMetadata": opciones_meta,
|
||||
"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"),
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
}
|
||||
|
||||
|
||||
# ── PDF ENDPOINTS ──────────────────────────────────
|
||||
|
||||
@router.post("/pdf")
|
||||
async def export_pdf_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
pdf_data = _build_pdf_data_from_draft(body, branding)
|
||||
pdf_bytes = generate_cotizacion_pdf(pdf_data)
|
||||
|
||||
empresa = body.clienteEmpresa or body.clienteNombre or "Cotizacion"
|
||||
filename = f"{sanitize_filename(empresa)} - BORRADOR.pdf"
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/pdf/{cotizacion_id}")
|
||||
async def export_pdf_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
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")
|
||||
|
||||
pdf_bytes = generate_cotizacion_pdf(pdf_data)
|
||||
|
||||
empresa = pdf_data["clienteEmpresa"] or pdf_data["clienteNombre"]
|
||||
filename = f"{sanitize_filename(empresa)} - {sanitize_filename(pdf_data['numero'])}.pdf"
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
# ── EXCEL ENDPOINTS ────────────────────────────────
|
||||
|
||||
@router.post("/excel")
|
||||
async def export_excel_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
excel_data = _build_pdf_data_from_draft(body, branding)
|
||||
excel_bytes = generate_cotizacion_excel(excel_data, saved=False)
|
||||
|
||||
empresa = body.clienteEmpresa or body.clienteNombre or "Cotizacion"
|
||||
filename = f"{sanitize_filename(empresa)} - {sanitize_filename(body.clienteNombre)} - BORRADOR.xlsx"
|
||||
|
||||
return Response(
|
||||
content=excel_bytes,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/excel/{cotizacion_id}")
|
||||
async def export_excel_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
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")
|
||||
|
||||
excel_bytes = generate_cotizacion_excel(excel_data, saved=True)
|
||||
|
||||
empresa = excel_data["clienteEmpresa"] or excel_data["clienteNombre"]
|
||||
filename = f"{sanitize_filename(empresa)} - {sanitize_filename(excel_data['numero'])}.xlsx"
|
||||
|
||||
return Response(
|
||||
content=excel_bytes,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
# ── CSV ENDPOINTS ──────────────────────────────────
|
||||
|
||||
@router.get("/catalogo", response_class=PlainTextResponse)
|
||||
async def export_catalogo_csv(
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch(
|
||||
"""SELECT s.id, s.nombre, s.descripcion, s.fase, s."tipoPago",
|
||||
s."precioBase", s."tiempoEntrega", s."entregablesDefault",
|
||||
s.variante, s.orden, c.nombre AS categoria
|
||||
FROM "ServicioCatalogo" s
|
||||
LEFT JOIN "Categoria" c ON c.id = s."categoriaId"
|
||||
WHERE s.activo = true
|
||||
ORDER BY s.fase, s.orden"""
|
||||
)
|
||||
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
writer.writerow([
|
||||
"Nombre", "Categoria", "Fase", "Tipo de Pago", "Precio Base",
|
||||
"Tiempo de Entrega", "Entregables", "Variante",
|
||||
])
|
||||
for r in rows:
|
||||
entregables = r["entregablesDefault"] or []
|
||||
if isinstance(entregables, list):
|
||||
entregables = " | ".join(entregables)
|
||||
elif isinstance(entregables, str):
|
||||
try:
|
||||
ent_list = json.loads(entregables)
|
||||
entregables = " | ".join(ent_list) if isinstance(ent_list, list) else entregables
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
writer.writerow([
|
||||
r["nombre"], r["categoria"], r["fase"], r["tipoPago"],
|
||||
r["precioBase"], r["tiempoEntrega"], entregables, r["variante"],
|
||||
])
|
||||
|
||||
return PlainTextResponse(
|
||||
content=buf.getvalue(),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": "attachment; filename=catalogo-servicios.csv"},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/catalogo/plantilla", response_class=PlainTextResponse)
|
||||
async def export_catalogo_template(db: Connection = Depends(get_db)):
|
||||
cats = await db.fetch(
|
||||
'SELECT nombre FROM "Categoria" WHERE activo = true ORDER BY orden'
|
||||
)
|
||||
cat_names = [r["nombre"] for r in cats]
|
||||
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
writer.writerow([
|
||||
"nombre", "descripcion", "fase", "tipoPago",
|
||||
"precioBase", "tiempoEntrega", "entregablesDefault", "variante", "categoria",
|
||||
])
|
||||
writer.writerow([
|
||||
"SEO On-Page", "Optimización on-page para buscadores", "Contenido y SEO", "mensual",
|
||||
"2900", "7 - 14 dias", "Keyword research | On-page optimization", "", "SEO",
|
||||
])
|
||||
writer.writerow([
|
||||
"", "", "", "", "", "", "", "", "",
|
||||
])
|
||||
writer.writerow([f"CATEGORIAS: {', '.join(cat_names)}"])
|
||||
writer.writerow(["FASES: Auditoria, Setup e Infraestructura, Publicidad y Manejo, Contenido y SEO"])
|
||||
writer.writerow(["TIPOS DE PAGO: unico, mensual"])
|
||||
|
||||
return PlainTextResponse(
|
||||
content=buf.getvalue(),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": "attachment; filename=plantilla-catalogo.csv"},
|
||||
)
|
||||
@@ -1,122 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.dependencies import get_db
|
||||
from app.models.export_ import (
|
||||
FinanciamientoRequest,
|
||||
FinanciamientoResponse,
|
||||
BonoResponse,
|
||||
PlanBucefaloResponse,
|
||||
)
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.services.calculators import (
|
||||
calcular_financiamiento,
|
||||
FINANCIAMIENTO_PLANES,
|
||||
PLANES_BUCEFALO,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/financiamiento", tags=["Financiamiento"])
|
||||
|
||||
|
||||
class PlanResponse(FinanciamientoResponse):
|
||||
meses: int
|
||||
tasa: float
|
||||
comision: float
|
||||
|
||||
|
||||
@router.get("/planes", response_model=list[PlanResponse])
|
||||
async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
return [
|
||||
PlanResponse(
|
||||
meses=p["meses"],
|
||||
tasa=p["tasa"],
|
||||
comision=p["comision"],
|
||||
**calcular_financiamiento(1000, p["meses"], p["tasa"], p["comision"]),
|
||||
)
|
||||
for p in sorted(FINANCIAMIENTO_PLANES, key=lambda x: x["meses"])
|
||||
]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/calcular",
|
||||
response_model=FinanciamientoResponse,
|
||||
responses={400: {"model": ErrorResponse}},
|
||||
)
|
||||
async def calcular(
|
||||
body: FinanciamientoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
):
|
||||
plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None)
|
||||
if not plan:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"No financing plan available for {body.meses} months",
|
||||
)
|
||||
if body.monto < plan["montoMinimo"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Minimum amount for {body.meses} months is ${plan['montoMinimo']}",
|
||||
)
|
||||
|
||||
result = calcular_financiamiento(body.monto, body.meses, plan["tasa"], plan["comision"])
|
||||
return FinanciamientoResponse(
|
||||
**result,
|
||||
meses=body.meses,
|
||||
tasa=plan["tasa"],
|
||||
comision=plan["comision"],
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/simulacion/{cotizacion_id}",
|
||||
response_model=list[FinanciamientoResponse],
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def simulacion(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
cot = await db.fetchrow(
|
||||
'SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id
|
||||
)
|
||||
if not cot:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Cotización not found",
|
||||
)
|
||||
|
||||
rows = await db.fetch(
|
||||
'SELECT precio FROM "ServicioCotizado" WHERE "cotizacionId" = $1 AND seleccionado = true',
|
||||
cotizacion_id,
|
||||
)
|
||||
total = sum(float(r["precio"]) for r in rows)
|
||||
|
||||
plan_buc = await db.fetchrow(
|
||||
'SELECT precio FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
if plan_buc:
|
||||
total += float(plan_buc["precio"])
|
||||
|
||||
if total <= 0:
|
||||
return []
|
||||
|
||||
results = []
|
||||
for plan in FINANCIAMIENTO_PLANES:
|
||||
if total < plan["montoMinimo"]:
|
||||
continue
|
||||
result = calcular_financiamiento(total, plan["meses"], plan["tasa"], plan["comision"])
|
||||
results.append(
|
||||
FinanciamientoResponse(
|
||||
**result,
|
||||
meses=plan["meses"],
|
||||
tasa=plan["tasa"],
|
||||
comision=plan["comision"],
|
||||
)
|
||||
)
|
||||
|
||||
return results
|
||||
@@ -1,42 +0,0 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.database import get_pool
|
||||
from app.models.common import ErrorResponse, HealthResponse, APIInfoResponse
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
async def health_check():
|
||||
pool = await get_pool()
|
||||
try:
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
db_status = "connected"
|
||||
except Exception:
|
||||
db_status = "disconnected"
|
||||
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
timestamp=datetime.now(timezone.utc).isoformat(),
|
||||
database=db_status,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api-info", response_model=APIInfoResponse)
|
||||
async def api_info():
|
||||
return APIInfoResponse(
|
||||
name="Cotizador E3 API",
|
||||
version="1.0.0",
|
||||
description="API para el sistema de cotizaciones de Consultoría E3",
|
||||
capabilities=[
|
||||
"Gestión de cotizaciones",
|
||||
"Catálogo de servicios",
|
||||
"Planes Bucéfalo CRM",
|
||||
"Exportación PDF/Excel",
|
||||
"Autenticación JWT",
|
||||
"Financiamiento Openpay",
|
||||
],
|
||||
)
|
||||
@@ -1,113 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
|
||||
from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
|
||||
router = APIRouter(prefix="/import", tags=["Import"])
|
||||
|
||||
REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"}
|
||||
|
||||
|
||||
@router.post("/catalogo")
|
||||
async def import_catalogo_csv(
|
||||
file: UploadFile = File(...),
|
||||
_auth: dict = Depends(require_auth),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
content = await file.read()
|
||||
text = content.decode("utf-8-sig")
|
||||
reader = csv.DictReader(io.StringIO(text))
|
||||
|
||||
if not reader.fieldnames or not REQUIRED_COLUMNS.issubset(set(reader.fieldnames)):
|
||||
missing = REQUIRED_COLUMNS - set(reader.fieldnames or [])
|
||||
return {
|
||||
"creados": 0,
|
||||
"omitidos": 0,
|
||||
"errores": [f"Missing required columns: {', '.join(missing)}"],
|
||||
}
|
||||
|
||||
categorias = await db.fetch('SELECT id, nombre FROM "Categoria" WHERE activo = true')
|
||||
cat_map = {r["nombre"]: r["id"] for r in categorias}
|
||||
|
||||
existing = await db.fetch('SELECT nombre FROM "ServicioCatalogo" WHERE activo = true')
|
||||
existing_names = {r["nombre"] for r in existing}
|
||||
|
||||
creados = 0
|
||||
omitidos = 0
|
||||
errores: list[str] = []
|
||||
|
||||
async with db.transaction():
|
||||
for i, row in enumerate(reader, start=2):
|
||||
nombre = (row.get("nombre") or "").strip()
|
||||
if not nombre:
|
||||
omitidos += 1
|
||||
continue
|
||||
|
||||
if nombre in existing_names:
|
||||
omitidos += 1
|
||||
continue
|
||||
|
||||
cat_nombre = (row.get("categoria") or "").strip()
|
||||
cat_id = cat_map.get(cat_nombre)
|
||||
if not cat_id:
|
||||
errores.append(f"Row {i}: category '{cat_nombre}' not found")
|
||||
continue
|
||||
|
||||
try:
|
||||
fase = int(row.get("fase", "0"))
|
||||
if fase not in (0, 1, 2, 3):
|
||||
raise ValueError
|
||||
except (ValueError, TypeError):
|
||||
errores.append(f"Row {i}: invalid fase '{row.get('fase')}'")
|
||||
continue
|
||||
|
||||
tipo_pago = (row.get("tipoPago") or "").strip()
|
||||
if tipo_pago not in ("unico", "mensual"):
|
||||
errores.append(f"Row {i}: invalid tipoPago '{tipo_pago}'")
|
||||
continue
|
||||
|
||||
try:
|
||||
precio = float(row.get("precioBase", "0"))
|
||||
except (ValueError, TypeError):
|
||||
errores.append(f"Row {i}: invalid precioBase '{row.get('precioBase')}'")
|
||||
continue
|
||||
|
||||
tiempo = (row.get("tiempoEntrega") or "7 - 14 dias").strip()
|
||||
variante = (row.get("variante") or "").strip() or None
|
||||
try:
|
||||
orden = int(row.get("orden", "0"))
|
||||
except (ValueError, TypeError):
|
||||
orden = 0
|
||||
|
||||
entregables_raw = (row.get("entregablesDefault") or "").strip()
|
||||
entregables = [e.strip() for e in entregables_raw.split(";") if e.strip()] if entregables_raw else []
|
||||
|
||||
await db.execute(
|
||||
"""
|
||||
INSERT INTO "ServicioCatalogo"
|
||||
(id, nombre, descripcion, fase, "tipoPago", "precioBase",
|
||||
"tiempoEntrega", "entregablesDefault", "categoriaId",
|
||||
variante, orden, activo, "createdAt", "updatedAt")
|
||||
VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, now(), now())
|
||||
""",
|
||||
nombre,
|
||||
(row.get("descripcion") or "").strip() or None,
|
||||
fase,
|
||||
tipo_pago,
|
||||
precio,
|
||||
tiempo,
|
||||
entregables if entregables else None,
|
||||
cat_id,
|
||||
variante,
|
||||
orden,
|
||||
)
|
||||
existing_names.add(nombre)
|
||||
creados += 1
|
||||
|
||||
return {"creados": creados, "omitidos": omitidos, "errores": errores}
|
||||
@@ -1,437 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
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.models.paquete import (
|
||||
PaqueteCreate,
|
||||
PaqueteUpdate,
|
||||
PaqueteResponse,
|
||||
FasePaqueteResponse,
|
||||
ManageAction,
|
||||
)
|
||||
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]:
|
||||
"""Build PaqueteResponse dicts for several paquetes with 2 queries in total
|
||||
(instead of 1 + N fases per paquete)."""
|
||||
if not paquete_rows:
|
||||
return []
|
||||
|
||||
paquete_ids = [p["id"] for p in paquete_rows]
|
||||
fases_rows = await conn.fetch(
|
||||
'SELECT id, "paqueteId", nombre, orden, "createdAt", "updatedAt"'
|
||||
' FROM "FasePaquete" WHERE "paqueteId" = ANY($1::text[]) ORDER BY orden ASC',
|
||||
paquete_ids,
|
||||
)
|
||||
|
||||
fase_ids = [f["id"] for f in fases_rows]
|
||||
servicios_rows = []
|
||||
if fase_ids:
|
||||
servicios_rows = await conn.fetch(
|
||||
'SELECT sp.id, sp."servicioCatalogoId", sp."fasePaqueteId",'
|
||||
' sp."createdAt", sp."updatedAt",'
|
||||
' sc.id AS "sc_id", sc.nombre AS "sc_nombre", sc.descripcion AS "sc_descripcion",'
|
||||
' sc.fase AS "sc_fase", sc."tipoPago" AS "sc_tipoPago",'
|
||||
' 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."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",'
|
||||
' cat."createdAt" AS "cat_createdAt", cat."updatedAt" AS "cat_updatedAt"'
|
||||
' FROM "ServicioPaquete" sp'
|
||||
' JOIN "ServicioCatalogo" sc ON sc.id = sp."servicioCatalogoId"'
|
||||
' LEFT JOIN "Categoria" cat ON cat.id = sc."categoriaId"'
|
||||
' WHERE sp."fasePaqueteId" = ANY($1::text[])',
|
||||
fase_ids,
|
||||
)
|
||||
|
||||
servicios_por_fase: dict[str, list[dict]] = {}
|
||||
for s in servicios_rows:
|
||||
cat = None
|
||||
if s["cat_id"]:
|
||||
cat = {
|
||||
"id": s["cat_id"],
|
||||
"nombre": s["cat_nombre"],
|
||||
"descripcion": s["cat_descripcion"],
|
||||
"color": s["cat_color"],
|
||||
"activo": s["cat_activo"],
|
||||
"orden": s["cat_orden"],
|
||||
"createdAt": s["cat_createdAt"],
|
||||
"updatedAt": s["cat_updatedAt"],
|
||||
}
|
||||
servicios_por_fase.setdefault(s["fasePaqueteId"], []).append({
|
||||
"id": s["id"],
|
||||
"servicioCatalogoId": s["servicioCatalogoId"],
|
||||
"fasePaqueteId": s["fasePaqueteId"],
|
||||
"createdAt": s["createdAt"],
|
||||
"updatedAt": s["updatedAt"],
|
||||
"servicio": {
|
||||
"id": s["sc_id"],
|
||||
"nombre": s["sc_nombre"],
|
||||
"descripcion": s["sc_descripcion"],
|
||||
"fase": s["sc_fase"],
|
||||
"tipoPago": s["sc_tipoPago"],
|
||||
"precioBase": s["sc_precioBase"],
|
||||
"tiempoEntrega": s["sc_tiempoEntrega"],
|
||||
"entregablesDefault": s["sc_entregablesDefault"],
|
||||
"categoriaId": s["sc_categoriaId"],
|
||||
"variante": s["sc_variante"],
|
||||
"activo": s["sc_activo"],
|
||||
"orden": s["sc_orden"],
|
||||
"createdAt": s["sc_createdAt"],
|
||||
"updatedAt": s["sc_updatedAt"],
|
||||
"categoriaRel": cat,
|
||||
},
|
||||
})
|
||||
|
||||
fases_por_paquete: dict[str, list[dict]] = {}
|
||||
for fase in fases_rows:
|
||||
fases_por_paquete.setdefault(fase["paqueteId"], []).append({
|
||||
"id": fase["id"],
|
||||
"paqueteId": fase["paqueteId"],
|
||||
"nombre": fase["nombre"],
|
||||
"orden": fase["orden"],
|
||||
"createdAt": fase["createdAt"],
|
||||
"updatedAt": fase["updatedAt"],
|
||||
"servicios": servicios_por_fase.get(fase["id"], []),
|
||||
})
|
||||
|
||||
return [
|
||||
{
|
||||
"id": p["id"],
|
||||
"nombre": p["nombre"],
|
||||
"descripcion": p["descripcion"],
|
||||
"activo": p["activo"],
|
||||
"createdAt": p["createdAt"],
|
||||
"updatedAt": p["updatedAt"],
|
||||
"fases": fases_por_paquete.get(p["id"], []),
|
||||
}
|
||||
for p in paquete_rows
|
||||
]
|
||||
|
||||
|
||||
async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
||||
"""Build a PaqueteResponse dict with nested fases and servicios."""
|
||||
results = await _build_paquetes_responses(conn, [paquete_row])
|
||||
return results[0]
|
||||
|
||||
|
||||
@router.get("", response_model=list[PaqueteResponse])
|
||||
async def list_paquetes(
|
||||
_auth: dict = Depends(require_auth),
|
||||
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])
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=PaqueteResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_paquete(
|
||||
body: PaqueteCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
paquete_row = await conn.fetchrow(
|
||||
'INSERT INTO "Paquete" (id, nombre, descripcion, "createdAt", "updatedAt")'
|
||||
" VALUES (gen_random_uuid(), $1, $2, $3, $3)"
|
||||
' RETURNING id, nombre, descripcion, activo, "createdAt", "updatedAt"',
|
||||
body.nombre,
|
||||
body.descripcion,
|
||||
now,
|
||||
)
|
||||
|
||||
paquete_id = paquete_row["id"]
|
||||
for fase in body.fases:
|
||||
await conn.execute(
|
||||
'INSERT INTO "FasePaquete" (id, "paqueteId", nombre, orden, "createdAt", "updatedAt")'
|
||||
" VALUES (gen_random_uuid(), $1, $2, $3, $4, $4)",
|
||||
paquete_id,
|
||||
fase.nombre,
|
||||
fase.orden,
|
||||
now,
|
||||
)
|
||||
|
||||
return await _build_paquete_response(conn, dict(paquete_row))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{paquete_id}",
|
||||
response_model=PaqueteResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def get_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
||||
' FROM "Paquete" WHERE id = $1',
|
||||
paquete_id,
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
return await _build_paquete_response(conn, dict(row))
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{paquete_id}",
|
||||
response_model=PaqueteResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def update_paquete(
|
||||
paquete_id: str,
|
||||
body: PaqueteUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
'SELECT id FROM "Paquete" WHERE id = $1', paquete_id
|
||||
)
|
||||
if not existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if body.nombre is not None:
|
||||
updates.append(f"nombre = ${idx}")
|
||||
params.append(body.nombre)
|
||||
idx += 1
|
||||
if body.descripcion is not None:
|
||||
updates.append(f"descripcion = ${idx}")
|
||||
params.append(body.descripcion)
|
||||
idx += 1
|
||||
if body.activo is not None:
|
||||
updates.append(f"activo = ${idx}")
|
||||
params.append(body.activo)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"'
|
||||
' FROM "Paquete" WHERE id = $1',
|
||||
paquete_id,
|
||||
)
|
||||
return await _build_paquete_response(conn, dict(row))
|
||||
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(datetime.now(timezone.utc))
|
||||
idx += 1
|
||||
|
||||
params.append(paquete_id)
|
||||
row = await conn.fetchrow(
|
||||
f'UPDATE "Paquete" SET {", ".join(updates)} WHERE id = ${idx}'
|
||||
' RETURNING id, nombre, descripcion, activo, "createdAt", "updatedAt"',
|
||||
*params,
|
||||
)
|
||||
return await _build_paquete_response(conn, dict(row))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{paquete_id}",
|
||||
response_model=OkResponse,
|
||||
responses={404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def delete_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
result = await conn.execute(
|
||||
'DELETE FROM "Paquete" WHERE id = $1', paquete_id
|
||||
)
|
||||
if result == "DELETE 0":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{paquete_id}/manage",
|
||||
responses={400: {"model": ErrorResponse}, 404: {"model": ErrorResponse}},
|
||||
)
|
||||
async def manage_paquete(
|
||||
paquete_id: str,
|
||||
body: ManageAction,
|
||||
_auth: dict = Depends(require_auth),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
paquete = await conn.fetchrow(
|
||||
'SELECT id FROM "Paquete" WHERE id = $1', paquete_id
|
||||
)
|
||||
if not paquete:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Paquete no encontrado",
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
action = body.action
|
||||
|
||||
if action == "addFase":
|
||||
if not body.nombre:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="El campo 'nombre' es requerido para addFase",
|
||||
)
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO "FasePaquete" (id, "paqueteId", nombre, orden, "createdAt", "updatedAt")'
|
||||
" VALUES (gen_random_uuid(), $1, $2, $3, $4, $4)"
|
||||
' RETURNING id, "paqueteId", nombre, orden, "createdAt", "updatedAt"',
|
||||
paquete_id,
|
||||
body.nombre,
|
||||
body.orden or 0,
|
||||
now,
|
||||
)
|
||||
return dict(row), status.HTTP_201_CREATED
|
||||
|
||||
if action == "updateFase":
|
||||
if not body.faseId:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="El campo 'faseId' es requerido para updateFase",
|
||||
)
|
||||
updates: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
if body.nombre is not None:
|
||||
updates.append(f"nombre = ${idx}")
|
||||
params.append(body.nombre)
|
||||
idx += 1
|
||||
if body.orden is not None:
|
||||
updates.append(f"orden = ${idx}")
|
||||
params.append(body.orden)
|
||||
idx += 1
|
||||
if not updates:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT id, "paqueteId", nombre, orden, "createdAt", "updatedAt"'
|
||||
' FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2',
|
||||
body.faseId,
|
||||
paquete_id,
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Fase no encontrada",
|
||||
)
|
||||
return dict(row)
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(now)
|
||||
idx += 1
|
||||
params.extend([body.faseId, paquete_id])
|
||||
row = await conn.fetchrow(
|
||||
f'UPDATE "FasePaquete" SET {", ".join(updates)}'
|
||||
f" WHERE id = ${idx} AND \"paqueteId\" = ${idx + 1}"
|
||||
' RETURNING id, "paqueteId", nombre, orden, "createdAt", "updatedAt"',
|
||||
*params,
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Fase no encontrada",
|
||||
)
|
||||
return dict(row)
|
||||
|
||||
if action == "deleteFase":
|
||||
if not body.faseId:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="El campo 'faseId' es requerido para deleteFase",
|
||||
)
|
||||
result = await conn.execute(
|
||||
'DELETE FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2',
|
||||
body.faseId,
|
||||
paquete_id,
|
||||
)
|
||||
if result == "DELETE 0":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Fase no encontrada",
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
if action == "addServicio":
|
||||
if not body.servicioCatalogoId or not body.fasePaqueteId:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Los campos 'servicioCatalogoId' y 'fasePaqueteId' son requeridos para addServicio",
|
||||
)
|
||||
fase = await conn.fetchrow(
|
||||
'SELECT id FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2',
|
||||
body.fasePaqueteId,
|
||||
paquete_id,
|
||||
)
|
||||
if not fase:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Fase no encontrada en este paquete",
|
||||
)
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO "ServicioPaquete" (id, "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")'
|
||||
" VALUES (gen_random_uuid(), $1, $2, $3, $3)"
|
||||
' RETURNING id, "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt"',
|
||||
body.servicioCatalogoId,
|
||||
body.fasePaqueteId,
|
||||
now,
|
||||
)
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower() or "duplicate" in str(e).lower():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Este servicio ya está asignado a esta fase",
|
||||
)
|
||||
raise
|
||||
return dict(row), status.HTTP_201_CREATED
|
||||
|
||||
if action == "removeServicio":
|
||||
if not body.servicioCatalogoId or not body.fasePaqueteId:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Los campos 'servicioCatalogoId' y 'fasePaqueteId' son requeridos para removeServicio",
|
||||
)
|
||||
result = await conn.execute(
|
||||
'DELETE FROM "ServicioPaquete"'
|
||||
' WHERE "servicioCatalogoId" = $1 AND "fasePaqueteId" = $2',
|
||||
body.servicioCatalogoId,
|
||||
body.fasePaqueteId,
|
||||
)
|
||||
if result == "DELETE 0":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Servicio no encontrado en esta fase",
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Acción desconocida: '{action}'. Acciones válidas: addFase, updateFase, deleteFase, addServicio, removeServicio",
|
||||
)
|
||||
@@ -1,165 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
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_COBRO: dict[str, str] = {
|
||||
"fijo": "Precio fijo",
|
||||
"horas": "Por horas",
|
||||
"retainer": "Retainer (minimo + adicionales)",
|
||||
}
|
||||
|
||||
# Doble propuesta: cada partida va en la Opcion 1, la 2 o en ambas (espejo del TS).
|
||||
OPCIONES = ("1", "2", "ambas")
|
||||
|
||||
FASES: dict[int, str] = {
|
||||
0: "FASE 0 - Auditoria / Acompanamiento",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
FASES_SHORT: dict[int, str] = {
|
||||
0: "FASE 0 - Auditoria",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
PLANES_BUCEFALO = [
|
||||
{"nivel": "basico", "label": "Basico", "precio": 1000},
|
||||
{"nivel": "estandar", "label": "Estandar", "precio": 3500},
|
||||
{"nivel": "premium", "label": "Premium", "precio": 4500},
|
||||
{"nivel": "empresarial", "label": "Empresarial", "precio": 7500},
|
||||
]
|
||||
|
||||
ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"]
|
||||
|
||||
FINANCIAMIENTO_PLANES = [
|
||||
{"meses": 3, "tasa": 0.077, "comision": 2.5, "montoMinimo": 300},
|
||||
{"meses": 6, "tasa": 0.107, "comision": 2.5, "montoMinimo": 600},
|
||||
{"meses": 9, "tasa": 0.137, "comision": 2.5, "montoMinimo": 900},
|
||||
{"meses": 12, "tasa": 0.167, "comision": 2.5, "montoMinimo": 1200},
|
||||
]
|
||||
|
||||
BONOS = [
|
||||
{"id": "bono-1", "numero": 1, "titulo": "Servicio Centinela Web", "descripcion": "Monitoreo web 30 min/mes", "activo": True},
|
||||
{"id": "bono-2", "numero": 2, "titulo": "Workshop Buyer Persona", "descripcion": "Taller de definición de buyer persona", "activo": True},
|
||||
{"id": "bono-3", "numero": 3, "titulo": "Workshop Propuesta de Valor", "descripcion": "Taller de propuesta de valor", "activo": True},
|
||||
{"id": "bono-4", "numero": 4, "titulo": "Membresia Premium", "descripcion": "Membresía premium por 1 año", "activo": True},
|
||||
{"id": "bono-5", "numero": 5, "titulo": "Mes Gratis Bucefalo CRM", "descripcion": "Un mes gratis del CRM Bucefalo", "activo": True},
|
||||
{"id": "bono-6", "numero": 6, "titulo": "Script de Ventas", "descripcion": "Script de ventas con 100+ complementos", "activo": True},
|
||||
]
|
||||
|
||||
|
||||
def calcular_precio_horas(horas: float, tarifa_hora: float) -> float:
|
||||
return round((horas or 0) * (tarifa_hora or 0), 2)
|
||||
|
||||
|
||||
def describir_retainer(monto_minimo: float, horas_incluidas: float, tarifa_hora: float) -> str:
|
||||
"""Texto descriptivo de un retainer (espejo de describirRetainer en TS)."""
|
||||
partes = [f"{format_currency(monto_minimo or 0)}/mes"]
|
||||
if horas_incluidas:
|
||||
partes.append(f"incluye {horas_incluidas:g} hr")
|
||||
if tarifa_hora:
|
||||
partes.append(f"adicional {format_currency(tarifa_hora)}/hr (se factura aparte)")
|
||||
return " · ".join(partes)
|
||||
|
||||
|
||||
def detalle_modelo(serv: dict) -> str:
|
||||
"""Sub-linea de desglose por modelo de cobro para PDF/Excel."""
|
||||
modelo = serv.get("modeloCobro")
|
||||
if modelo == "retainer":
|
||||
return describir_retainer(
|
||||
serv.get("montoMinimo") or 0,
|
||||
serv.get("horasIncluidas") or 0,
|
||||
serv.get("tarifaHora") or 0,
|
||||
)
|
||||
horas = serv.get("horas")
|
||||
tarifa = serv.get("tarifaHora")
|
||||
if (modelo == "horas" or serv.get("esPersonalizado")) and horas and tarifa:
|
||||
return f"{horas:g} h x {format_currency(tarifa)}/hr"
|
||||
return ""
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
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),
|
||||
}
|
||||
|
||||
|
||||
def bucefalo_precio(nivel: str) -> float:
|
||||
for p in PLANES_BUCEFALO:
|
||||
if p["nivel"] == nivel:
|
||||
return float(p["precio"])
|
||||
return 0.0
|
||||
|
||||
|
||||
def calcular_vigencia(fecha: datetime | date) -> datetime:
|
||||
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:
|
||||
dias_habiles += 1
|
||||
return vigencia
|
||||
|
||||
|
||||
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),
|
||||
}
|
||||
|
||||
|
||||
def generar_numero_cotizacion(iniciales: str, secuencia: int) -> str:
|
||||
now = datetime.now()
|
||||
yy = str(now.year)[-2:]
|
||||
mm = f"{now.month:02d}"
|
||||
seq = f"{secuencia:03d}"
|
||||
return f"UJ{yy}{mm}{iniciales}{seq}"
|
||||
|
||||
|
||||
def sanitize_filename(name: str) -> str:
|
||||
import re
|
||||
name = re.sub(r"[^\w\s.\-]", "", name)
|
||||
name = re.sub(r"\s+", " ", name)
|
||||
return name.strip()
|
||||
|
||||
|
||||
def format_currency(amount: float) -> str:
|
||||
return f"${amount:,.2f}"
|
||||
|
||||
|
||||
def format_date(d: datetime | date) -> str:
|
||||
return f"{d.day:02d}/{d.month:02d}/{d.year}"
|
||||
@@ -1,537 +0,0 @@
|
||||
"""Excel Generator for Cotizador E3 — 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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import column_index_from_string, get_column_letter
|
||||
from openpyxl.worksheet.worksheet import Worksheet
|
||||
|
||||
from app.services.calculators import bucefalo_precio, detalle_modelo, calcular_totales_opcion, format_currency
|
||||
|
||||
FASES_MAP = {0: "FASE 0", 1: "FASE 1", 2: "FASE 2", 3: "FASE 3"}
|
||||
|
||||
|
||||
def _argb(hex_color: str, alpha: str = "FF") -> str:
|
||||
h = hex_color.lstrip("#")
|
||||
if len(h) > 6:
|
||||
h = h[:6]
|
||||
return f"{alpha}{h.upper()}"
|
||||
|
||||
|
||||
def _thin_border(color: str = "FFD1D5DB") -> Border:
|
||||
side = Side(style="thin", color=color)
|
||||
return Border(top=side, left=side, bottom=side, right=side)
|
||||
|
||||
|
||||
def _sanitize_sheet_name(name: str) -> str:
|
||||
name = (name or "Servicio")[:31]
|
||||
return re.sub(r"[/\\*?\[\]:]", "", name) or "Servicio"
|
||||
|
||||
|
||||
def _set_col_widths(ws: Worksheet, widths: list[tuple[str, float]]):
|
||||
for col_letter, width in widths:
|
||||
ws.column_dimensions[col_letter].width = width
|
||||
|
||||
|
||||
def _merged_width(widths: dict[str, float], start_col: str, end_col: str) -> float:
|
||||
"""Suma de anchos (unidades de carácter de Excel) entre dos columnas, inclusive."""
|
||||
start = column_index_from_string(start_col)
|
||||
end = column_index_from_string(end_col)
|
||||
return sum(widths.get(get_column_letter(c), 8) for c in range(start, end + 1))
|
||||
|
||||
|
||||
def _estimate_row_height(text: str, width_chars: float, font_size: int = 10) -> float:
|
||||
"""Altura (pt) que necesita una fila para mostrar `text` envuelto en `width_chars`."""
|
||||
cpl = max(8, int(width_chars))
|
||||
if font_size <= 10:
|
||||
line_h = 14.0
|
||||
elif font_size <= 11:
|
||||
line_h = 15.5
|
||||
elif font_size <= 12:
|
||||
line_h = 17.0
|
||||
else:
|
||||
line_h = 20.0
|
||||
lines = 0
|
||||
for seg in str(text or "").split("\n"):
|
||||
lines += max(1, math.ceil(len(seg) / cpl))
|
||||
return max(16.0, round(lines * line_h + 4))
|
||||
|
||||
|
||||
def _set_wrapped(
|
||||
ws: Worksheet,
|
||||
row: int,
|
||||
col: str,
|
||||
text: str,
|
||||
width_chars: float,
|
||||
font_size: int = 10,
|
||||
horizontal: str = "left",
|
||||
vertical: str = "top",
|
||||
):
|
||||
"""Marca la celda como envolvente y agranda la fila si el texto lo requiere."""
|
||||
cell = ws[f"{col}{row}"]
|
||||
cell.alignment = Alignment(wrap_text=True, vertical=vertical, horizontal=horizontal)
|
||||
needed = _estimate_row_height(text, width_chars, font_size)
|
||||
current = ws.row_dimensions[row].height or 0
|
||||
if needed > current:
|
||||
ws.row_dimensions[row].height = needed
|
||||
|
||||
|
||||
def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> bytes:
|
||||
"""Generate a multi-sheet Excel workbook for a quotation.
|
||||
|
||||
Args:
|
||||
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")
|
||||
PRIMARY = _argb(config_color)
|
||||
PRIMARY_LIGHT = _argb(config_color, alpha="18")
|
||||
SECONDARY = _argb(data.get("colorSecundario", "#1e293b"))
|
||||
WHITE = "FFFFFFFF"
|
||||
LIGHT_BG = "FFF8FAFC"
|
||||
MUTED = "FF64748B"
|
||||
BORDER_COLOR = "FFE2E8F0"
|
||||
|
||||
header_font = Font(bold=True, size=10, name="Calibri", color=WHITE)
|
||||
label_font = Font(bold=True, size=10, name="Calibri", color=MUTED)
|
||||
value_font = Font(size=10, name="Calibri")
|
||||
bold_font = Font(bold=True, size=10, name="Calibri")
|
||||
total_font = Font(bold=True, size=11, name="Calibri")
|
||||
small_font = Font(italic=True, size=9, name="Calibri", color=MUTED)
|
||||
fase_font = Font(bold=True, size=11, name="Calibri", color=PRIMARY)
|
||||
iva_font = Font(italic=False, size=9, name="Calibri", color=MUTED)
|
||||
|
||||
primary_fill = PatternFill(start_color=PRIMARY, end_color=PRIMARY, fill_type="solid")
|
||||
primary_light_fill = PatternFill(start_color=PRIMARY_LIGHT, end_color=PRIMARY_LIGHT, fill_type="solid")
|
||||
secondary_fill = PatternFill(start_color=SECONDARY, end_color=SECONDARY, fill_type="solid")
|
||||
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")
|
||||
cliente_nombre = data.get("clienteNombre", "")
|
||||
cliente_empresa = data.get("clienteEmpresa", "")
|
||||
asesor_nombre = data.get("asesorNombre", "")
|
||||
fecha = data.get("fecha", datetime.now())
|
||||
vigencia = data.get("vigencia", datetime.now())
|
||||
moneda = data.get("moneda", "MXN")
|
||||
tipo_cambio = data.get("tipoCambio", "NA")
|
||||
proyecto = data.get("proyecto", "MKT Digital")
|
||||
esquema = data.get("esquemaPago", "Pago Unico/Mensual")
|
||||
servicios = data.get("servicios", [])
|
||||
plan_nivel = data.get("planBucefaloNivel")
|
||||
plan_precio = data.get("planBucefaloPrecio")
|
||||
numero_label = data.get("numero", "BORRADOR") if saved else "BORRADOR"
|
||||
|
||||
wb = Workbook()
|
||||
wb.properties.creator = "Cotizador E3"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# HOJA RESUMEN
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
ws = wb.active
|
||||
ws.title = "HOJA RESUMEN"
|
||||
ws.sheet_view.showGridLines = False
|
||||
|
||||
resumen_widths = {
|
||||
"A": 3, "B": 18, "C": 26, "D": 13, "E": 16,
|
||||
"F": 22, "G": 6, "H": 6, "I": 6, "J": 6, "K": 16,
|
||||
}
|
||||
_set_col_widths(ws, list(resumen_widths.items()))
|
||||
|
||||
# Banner
|
||||
ws.merge_cells("B2:K2")
|
||||
cell = ws["B2"]
|
||||
cell.value = razon_social
|
||||
cell.font = Font(bold=True, size=16, name="Calibri", color=WHITE)
|
||||
cell.alignment = Alignment(vertical="center")
|
||||
for col in range(1, 12):
|
||||
ws.cell(row=2, column=col).fill = primary_fill
|
||||
ws.row_dimensions[2].height = 28
|
||||
|
||||
ws.merge_cells("B3:K3")
|
||||
cell = ws["B3"]
|
||||
cell.value = numero_label
|
||||
cell.font = Font(bold=True, size=11, name="Calibri", color=WHITE)
|
||||
cell.alignment = Alignment(vertical="center")
|
||||
for col in range(1, 12):
|
||||
ws.cell(row=3, column=col).fill = secondary_fill
|
||||
|
||||
# Info section
|
||||
info_start = 5
|
||||
info_rows = [
|
||||
[("B", "En atencion a:"), ("C", cliente_nombre), ("E", "Empresa:"), ("F", cliente_empresa or "—")],
|
||||
[("B", "Proyecto:"), ("C", proyecto), ("E", "Moneda:"), ("F", moneda)],
|
||||
[("B", "Asesor:"), ("C", asesor_nombre), ("E", "Tipo de Cambio:"), ("F", tipo_cambio)],
|
||||
[("B", "Fecha:"), ("C", ""), ("E", "Esquema de Pago:"), ("F", esquema)],
|
||||
]
|
||||
c_val_w = _merged_width(resumen_widths, "C", "C")
|
||||
f_val_w = _merged_width(resumen_widths, "F", "F")
|
||||
|
||||
for i, row_data in enumerate(info_rows):
|
||||
r = info_start + i
|
||||
(lc1, lv1), (vc1, vv1), (lc2, lv2), (vc2, vv2) = row_data
|
||||
ws[f"{lc1}{r}"].value = lv1
|
||||
ws[f"{lc1}{r}"].font = label_font
|
||||
ws[f"{vc1}{r}"].value = vv1
|
||||
ws[f"{vc1}{r}"].font = value_font
|
||||
if vv1:
|
||||
_set_wrapped(ws, r, vc1, vv1, c_val_w)
|
||||
ws[f"{lc2}{r}"].value = lv2
|
||||
ws[f"{lc2}{r}"].font = label_font
|
||||
ws[f"{vc2}{r}"].value = vv2
|
||||
ws[f"{vc2}{r}"].font = value_font
|
||||
if vv2:
|
||||
_set_wrapped(ws, r, vc2, vv2, f_val_w)
|
||||
|
||||
# Fecha (en la fila "Fecha:")
|
||||
fecha_cell = ws[f"C{info_start + 3}"]
|
||||
fecha_cell.value = fecha
|
||||
fecha_cell.number_format = "DD/MM/YYYY"
|
||||
fecha_cell.font = value_font
|
||||
|
||||
vig_row = info_start + 4
|
||||
ws[f"B{vig_row}"].value = "Vigencia:"
|
||||
ws[f"B{vig_row}"].font = label_font
|
||||
ws[f"C{vig_row}"].value = vigencia
|
||||
ws[f"C{vig_row}"].number_format = "DD/MM/YYYY"
|
||||
ws[f"C{vig_row}"].font = value_font
|
||||
|
||||
# Services table
|
||||
table_start = info_start + 6
|
||||
col_b = column_index_from_string("B")
|
||||
col_k = column_index_from_string("K")
|
||||
|
||||
def style_table_row(row_num: int, fill: PatternFill, border_color: str):
|
||||
"""Estiliza (relleno + borde) todo el ancho de la fila, de B a K."""
|
||||
border = _thin_border(border_color)
|
||||
for c in range(col_b, col_k + 1):
|
||||
cell = ws.cell(row=row_num, column=c)
|
||||
cell.fill = fill
|
||||
cell.border = border
|
||||
|
||||
ws.merge_cells(f"D{table_start}:J{table_start}")
|
||||
style_table_row(table_start, primary_fill, PRIMARY)
|
||||
for col_letter, txt, align in [
|
||||
("B", "Fase", "left"),
|
||||
("C", "Tipo de Pago", "left"),
|
||||
("D", "Servicio", "left"),
|
||||
("K", "Precio", "right"),
|
||||
]:
|
||||
cell = ws[f"{col_letter}{table_start}"]
|
||||
cell.value = txt
|
||||
cell.font = header_font
|
||||
cell.alignment = Alignment(horizontal=align, vertical="center")
|
||||
ws.row_dimensions[table_start].height = 24
|
||||
|
||||
servicios_unicos = [s for s in servicios if s.get("tipoPago") == "unico"]
|
||||
servicios_mensuales = [s for s in servicios if s.get("tipoPago") == "mensual"]
|
||||
serv_width = _merged_width(resumen_widths, "D", "J")
|
||||
es_doble = bool(data.get("esDoble"))
|
||||
opciones_meta = data.get("opcionesMetadata") or {}
|
||||
|
||||
row = table_start + 1
|
||||
|
||||
# Totales (helpers reutilizados por modo normal y doble propuesta)
|
||||
def write_total_row(label: str, amount: float, font: Font):
|
||||
nonlocal row
|
||||
ws.merge_cells(f"B{row}:J{row}")
|
||||
ws[f"B{row}"].value = label
|
||||
ws[f"B{row}"].font = font
|
||||
ws[f"B{row}"].alignment = Alignment(vertical="center")
|
||||
ws[f"K{row}"].value = amount
|
||||
ws[f"K{row}"].number_format = "$#,##0.00"
|
||||
ws[f"K{row}"].font = font
|
||||
ws[f"K{row}"].alignment = Alignment(horizontal="right", vertical="center")
|
||||
style_table_row(row, primary_light_fill, PRIMARY)
|
||||
row += 1
|
||||
|
||||
def write_iva_note():
|
||||
nonlocal row
|
||||
ws.merge_cells(f"B{row}:J{row}")
|
||||
ws[f"B{row}"].value = "(+ IVA)"
|
||||
ws[f"B{row}"].font = iva_font
|
||||
row += 1
|
||||
|
||||
def draw_service_rows(servs):
|
||||
nonlocal row
|
||||
current_fase = -1
|
||||
for serv in servs:
|
||||
fase = serv.get("fase", 0)
|
||||
if fase != current_fase:
|
||||
current_fase = fase
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
ws[f"B{row}"].value = FASES_MAP.get(fase, f"FASE {fase}")
|
||||
ws[f"B{row}"].font = fase_font
|
||||
ws[f"B{row}"].alignment = Alignment(vertical="center")
|
||||
for col in range(2, 12):
|
||||
ws.cell(row=row, column=col).fill = primary_light_fill
|
||||
ws.row_dimensions[row].height = 20
|
||||
row += 1
|
||||
|
||||
row_bg = light_fill if row % 2 == 0 else white_fill
|
||||
ws.merge_cells(f"D{row}:J{row}")
|
||||
style_table_row(row, row_bg, BORDER_COLOR)
|
||||
ws[f"C{row}"].value = "Unico" if serv.get("tipoPago") == "unico" else "Mensual"
|
||||
ws[f"C{row}"].font = value_font
|
||||
ws[f"C{row}"].alignment = Alignment(vertical="top")
|
||||
_detalle = detalle_modelo(serv)
|
||||
serv_text = f"{serv.get('nombre', '')} — {_detalle}" if _detalle else serv.get("nombre", "")
|
||||
ws[f"D{row}"].value = serv_text
|
||||
ws[f"D{row}"].font = value_font
|
||||
_set_wrapped(ws, row, "D", serv_text, serv_width)
|
||||
ws[f"K{row}"].value = serv.get("precio", 0)
|
||||
ws[f"K{row}"].number_format = "$#,##0.00"
|
||||
ws[f"K{row}"].font = value_font
|
||||
ws[f"K{row}"].alignment = Alignment(horizontal="right", vertical="top")
|
||||
row += 1
|
||||
|
||||
def write_opcion_banner(op: str):
|
||||
nonlocal row
|
||||
meta = opciones_meta.get(op) or {}
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
titulo = meta.get("titulo")
|
||||
ws[f"B{row}"].value = f"OPCION {op}" + (f": {titulo}" if titulo else "")
|
||||
ws[f"B{row}"].font = Font(bold=True, size=12, name="Calibri", color=WHITE)
|
||||
ws[f"B{row}"].alignment = Alignment(vertical="center")
|
||||
for col in range(2, 12):
|
||||
ws.cell(row=row, column=col).fill = secondary_fill
|
||||
ws.row_dimensions[row].height = 22
|
||||
row += 1
|
||||
desc = meta.get("descripcion")
|
||||
if desc:
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
ws[f"B{row}"].value = desc
|
||||
ws[f"B{row}"].font = value_font
|
||||
_set_wrapped(ws, row, "B", desc, _merged_width(resumen_widths, "B", "K"))
|
||||
row += 1
|
||||
no_incluye = meta.get("noIncluye")
|
||||
if no_incluye:
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
ws[f"B{row}"].value = f"No incluye: {no_incluye}"
|
||||
ws[f"B{row}"].font = small_font
|
||||
_set_wrapped(ws, row, "B", f"No incluye: {no_incluye}", _merged_width(resumen_widths, "B", "K"), font_size=9)
|
||||
row += 1
|
||||
|
||||
if es_doble:
|
||||
for op in ("1", "2"):
|
||||
u = [s for s in servicios_unicos if s.get("opcion") in (op, "ambas")]
|
||||
me = [s for s in servicios_mensuales if s.get("opcion") in (op, "ambas")]
|
||||
write_opcion_banner(op)
|
||||
draw_service_rows(u + me)
|
||||
row += 1
|
||||
write_total_row(f"Total Pago Unico - Opcion {op}", sum(s.get("precio", 0) for s in u), total_font)
|
||||
write_iva_note()
|
||||
write_total_row(f"Total Pago Mensual - Opcion {op}", sum(s.get("precio", 0) for s in me), total_font)
|
||||
write_iva_note()
|
||||
row += 1
|
||||
|
||||
# Comparativa de opciones (totales con IVA + horas)
|
||||
t1 = calcular_totales_opcion(servicios, "1")
|
||||
t2 = calcular_totales_opcion(servicios, "2")
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
ws[f"B{row}"].value = "COMPARATIVA DE OPCIONES"
|
||||
ws[f"B{row}"].font = Font(bold=True, size=12, name="Calibri", color=WHITE)
|
||||
ws[f"B{row}"].alignment = Alignment(vertical="center")
|
||||
for col in range(2, 12):
|
||||
ws.cell(row=row, column=col).fill = primary_fill
|
||||
ws.row_dimensions[row].height = 22
|
||||
row += 1
|
||||
t1_tit = (opciones_meta.get("1") or {}).get("titulo")
|
||||
t2_tit = (opciones_meta.get("2") or {}).get("titulo")
|
||||
|
||||
def comp_row(lab: str, v1: str, v2: str, font: Font):
|
||||
nonlocal row
|
||||
ws.merge_cells(f"B{row}:F{row}")
|
||||
ws[f"B{row}"].value = lab
|
||||
ws[f"B{row}"].font = font
|
||||
ws.merge_cells(f"G{row}:H{row}")
|
||||
ws[f"G{row}"].value = v1
|
||||
ws[f"G{row}"].font = font
|
||||
ws[f"G{row}"].alignment = Alignment(horizontal="right")
|
||||
ws.merge_cells(f"I{row}:K{row}")
|
||||
ws[f"I{row}"].value = v2
|
||||
ws[f"I{row}"].font = font
|
||||
ws[f"I{row}"].alignment = Alignment(horizontal="right")
|
||||
border = _thin_border(BORDER_COLOR)
|
||||
for col in range(col_b, col_k + 1):
|
||||
ws.cell(row=row, column=col).border = border
|
||||
row += 1
|
||||
|
||||
comp_row("Concepto", "Opcion 1" + (f" - {t1_tit}" if t1_tit else ""), "Opcion 2" + (f" - {t2_tit}" if t2_tit else ""), bold_font)
|
||||
comp_row("Total unico (c/IVA)", format_currency(t1["totalUnico"] * 1.16), format_currency(t2["totalUnico"] * 1.16), value_font)
|
||||
comp_row("Total mensual (c/IVA)", format_currency(t1["totalMensual"] * 1.16), format_currency(t2["totalMensual"] * 1.16), value_font)
|
||||
comp_row("Horas estimadas", f"{t1['horas']:g} h", f"{t2['horas']:g} h", value_font)
|
||||
row += 1
|
||||
else:
|
||||
draw_service_rows(servicios_unicos + servicios_mensuales)
|
||||
row += 1
|
||||
write_total_row("Total Pago Unico", sum(s.get("precio", 0) for s in servicios_unicos), total_font)
|
||||
write_iva_note()
|
||||
write_total_row("Total Pago Mensual", sum(s.get("precio", 0) for s in servicios_mensuales), total_font)
|
||||
write_iva_note()
|
||||
row += 1
|
||||
|
||||
if plan_nivel:
|
||||
precio = plan_precio if plan_precio is not None else bucefalo_precio(plan_nivel)
|
||||
write_total_row(f"CRM Bucefalo - {plan_nivel.capitalize()}", precio, bold_font)
|
||||
row += 1
|
||||
|
||||
ws.merge_cells(f"B{row}:K{row}")
|
||||
nota_resumen = "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 dias habiles."
|
||||
ws[f"B{row}"].value = nota_resumen
|
||||
ws[f"B{row}"].font = small_font
|
||||
_set_wrapped(ws, row, "B", nota_resumen, _merged_width(resumen_widths, "B", "K"), font_size=9)
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# HOJAS DETALLADAS POR SERVICIO
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
detail_widths = {
|
||||
"A": 3, "B": 16, "C": 30, "D": 8, "E": 4,
|
||||
"F": 18, "G": 22, "H": 6, "I": 6, "J": 16,
|
||||
}
|
||||
used_names: set[str] = set()
|
||||
for serv in servicios:
|
||||
base = _sanitize_sheet_name(serv.get("nombre", "Servicio"))
|
||||
safe_name = base
|
||||
n = 2
|
||||
while safe_name.lower() in used_names:
|
||||
suffix = f" ({n})"
|
||||
safe_name = base[: 31 - len(suffix)] + suffix
|
||||
n += 1
|
||||
used_names.add(safe_name.lower())
|
||||
|
||||
dw = wb.create_sheet(title=safe_name)
|
||||
dw.sheet_view.showGridLines = False
|
||||
_set_col_widths(dw, list(detail_widths.items()))
|
||||
|
||||
fase = serv.get("fase", 0)
|
||||
dw.merge_cells("B1:J1")
|
||||
banner_text = f"{FASES_MAP.get(fase, f'FASE {fase}')} — {serv.get('nombre', '')}"
|
||||
dw["B1"].value = banner_text
|
||||
dw["B1"].font = Font(bold=True, size=14, name="Calibri", color=WHITE)
|
||||
dw["B1"].alignment = Alignment(vertical="center", wrap_text=True)
|
||||
for col in range(1, 11):
|
||||
dw.cell(row=1, column=col).fill = primary_fill
|
||||
dw.row_dimensions[1].height = max(
|
||||
30, _estimate_row_height(banner_text, _merged_width(detail_widths, "B", "J"), 14)
|
||||
)
|
||||
|
||||
c_val = _merged_width(detail_widths, "C", "D")
|
||||
g_val = _merged_width(detail_widths, "G", "H")
|
||||
|
||||
r = 3
|
||||
dw[f"B{r}"].value = "Cliente:"
|
||||
dw[f"B{r}"].font = label_font
|
||||
dw.merge_cells(f"C{r}:D{r}")
|
||||
dw[f"C{r}"].value = cliente_empresa or cliente_nombre
|
||||
dw[f"C{r}"].font = bold_font
|
||||
_set_wrapped(dw, r, "C", cliente_empresa or cliente_nombre, c_val)
|
||||
dw[f"F{r}"].value = "No. Cotizacion:"
|
||||
dw[f"F{r}"].font = label_font
|
||||
dw.merge_cells(f"G{r}:H{r}")
|
||||
dw[f"G{r}"].value = numero_label
|
||||
dw[f"G{r}"].font = bold_font
|
||||
r += 2
|
||||
|
||||
dw[f"B{r}"].value = "Servicio:"
|
||||
dw[f"B{r}"].font = label_font
|
||||
dw.merge_cells(f"C{r}:D{r}")
|
||||
dw[f"C{r}"].value = serv.get("nombre", "")
|
||||
dw[f"C{r}"].font = Font(bold=True, size=12, name="Calibri", color=PRIMARY)
|
||||
_set_wrapped(dw, r, "C", serv.get("nombre", ""), c_val, font_size=12)
|
||||
dw[f"F{r}"].value = "Tiempo de Entrega:"
|
||||
dw[f"F{r}"].font = label_font
|
||||
dw.merge_cells(f"G{r}:H{r}")
|
||||
dw[f"G{r}"].value = serv.get("tiempoEntrega", "")
|
||||
dw[f"G{r}"].font = value_font
|
||||
_set_wrapped(dw, r, "G", serv.get("tiempoEntrega", ""), g_val)
|
||||
r += 2
|
||||
|
||||
_detalle_serv = detalle_modelo(serv)
|
||||
if _detalle_serv:
|
||||
dw[f"B{r}"].value = "Detalle:"
|
||||
dw[f"B{r}"].font = label_font
|
||||
dw.merge_cells(f"C{r}:J{r}")
|
||||
dw[f"C{r}"].value = _detalle_serv
|
||||
dw[f"C{r}"].font = value_font
|
||||
_set_wrapped(dw, r, "C", _detalle_serv, _merged_width(detail_widths, "C", "J"))
|
||||
r += 2
|
||||
|
||||
# Encabezado de entregables — barra completa B:J
|
||||
dw.merge_cells(f"B{r}:J{r}")
|
||||
dw[f"B{r}"].value = "Entregables"
|
||||
dw[f"B{r}"].font = header_font
|
||||
dw[f"B{r}"].alignment = Alignment(vertical="center")
|
||||
for col in range(column_index_from_string("B"), column_index_from_string("J") + 1):
|
||||
dw.cell(row=r, column=col).fill = primary_fill
|
||||
dw.row_dimensions[r].height = 22
|
||||
r += 1
|
||||
|
||||
ent_width = _merged_width(detail_widths, "B", "J")
|
||||
entregables = serv.get("entregables", [])
|
||||
b_idx = column_index_from_string("B")
|
||||
j_idx = column_index_from_string("J")
|
||||
for i, ent in enumerate(entregables):
|
||||
er = r + i
|
||||
dw.merge_cells(f"B{er}:J{er}")
|
||||
txt = f"{i + 1}. {ent}"
|
||||
dw[f"B{er}"].value = txt
|
||||
dw[f"B{er}"].font = value_font
|
||||
_set_wrapped(dw, er, "B", txt, ent_width)
|
||||
bg = light_fill if i % 2 == 1 else white_fill
|
||||
for col in range(b_idx, j_idx + 1):
|
||||
dw.cell(row=er, column=col).fill = bg
|
||||
dw.cell(row=er, column=col).border = _thin_border(BORDER_COLOR)
|
||||
r += len(entregables) + 1
|
||||
|
||||
# Total: etiqueta B:H + precio I:J
|
||||
dw.merge_cells(f"B{r}:H{r}")
|
||||
tipo_label = "Unico" if serv.get("tipoPago") == "unico" else "Mensual"
|
||||
dw[f"B{r}"].value = f"Total Pago {tipo_label}"
|
||||
dw[f"B{r}"].font = total_font
|
||||
dw[f"B{r}"].alignment = Alignment(vertical="center")
|
||||
dw.merge_cells(f"I{r}:J{r}")
|
||||
dw[f"I{r}"].value = serv.get("precio", 0)
|
||||
dw[f"I{r}"].number_format = "$#,##0.00"
|
||||
dw[f"I{r}"].font = total_font
|
||||
dw[f"I{r}"].alignment = Alignment(horizontal="right", vertical="center")
|
||||
for col in range(b_idx, j_idx + 1):
|
||||
dw.cell(row=r, column=col).fill = primary_light_fill
|
||||
dw.cell(row=r, column=col).border = _thin_border(PRIMARY)
|
||||
r += 1
|
||||
dw[f"B{r}"].value = "(+ IVA)"
|
||||
dw[f"B{r}"].font = iva_font
|
||||
r += 2
|
||||
|
||||
dw.merge_cells(f"B{r}:J{r}")
|
||||
nota_detalle = "Esta cotizacion tiene una vigencia de 15 dias habiles. Todos los precios en MXN, precios + IVA."
|
||||
dw[f"B{r}"].value = nota_detalle
|
||||
dw[f"B{r}"].font = small_font
|
||||
_set_wrapped(dw, r, "B", nota_detalle, ent_width, font_size=9)
|
||||
r += 2
|
||||
|
||||
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)
|
||||
|
||||
output = io.BytesIO()
|
||||
wb.save(output)
|
||||
return output.getvalue()
|
||||
@@ -1,552 +0,0 @@
|
||||
"""PDF Generator for Cotizador E3 — port of pdf-generator.ts using ReportLab."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import LETTER
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.pdfgen import canvas
|
||||
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"
|
||||
MUTED = "#64748b"
|
||||
BORDER = "#cbd5e1"
|
||||
LIGHT_BG = "#f1f5f9"
|
||||
WHITE = "#ffffff"
|
||||
|
||||
PAGE_W, PAGE_H = LETTER
|
||||
MARGIN_TOP = 45
|
||||
MARGIN_BOTTOM = 55
|
||||
MARGIN_LEFT = 50
|
||||
MARGIN_RIGHT = 50
|
||||
CONTENT_W = PAGE_W - MARGIN_LEFT - MARGIN_RIGHT
|
||||
|
||||
|
||||
def _hex_to_rgb(hex_color: str) -> colors.Color:
|
||||
h = hex_color.lstrip("#")
|
||||
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
||||
return colors.Color(r / 255, g / 255, b / 255)
|
||||
|
||||
|
||||
def _fmt_currency(n: float) -> str:
|
||||
return f"${n:,.2f}"
|
||||
|
||||
|
||||
def _wrap_text(c, text: str, font: str, size: float, max_width: float) -> list[str]:
|
||||
"""Envuelve texto en lineas que caben en max_width (respeta saltos de linea)."""
|
||||
lines: list[str] = []
|
||||
for paragraph in str(text or "").split("\n"):
|
||||
words = paragraph.split()
|
||||
line = ""
|
||||
for word in words:
|
||||
test = f"{line} {word}".strip()
|
||||
if c.stringWidth(test, font, size) > max_width and line:
|
||||
lines.append(line)
|
||||
line = word
|
||||
else:
|
||||
line = test
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _fmt_date(d: datetime) -> str:
|
||||
months = [
|
||||
"enero", "febrero", "marzo", "abril", "mayo", "junio",
|
||||
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
|
||||
]
|
||||
return f"{d.day} de {months[d.month - 1]} de {d.year}"
|
||||
|
||||
|
||||
def _load_logo(logo_base64: str | None, logo_mime: str | None) -> ImageReader | None:
|
||||
if not logo_base64:
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(logo_base64)
|
||||
return io.BytesIO(raw)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def generate_cotizacion_pdf(data: dict[str, Any]) -> bytes:
|
||||
"""Generate a professional quotation PDF.
|
||||
|
||||
Args:
|
||||
data: dict with keys matching CotizacionPDFData interface:
|
||||
numero, clienteNombre, clienteEmpresa, asesorNombre, fecha, vigencia,
|
||||
moneda, tipoCambio, proyecto, esquemaPago, servicios[],
|
||||
planBucefaloNivel, planBucefaloPrecio, incluirBonos,
|
||||
configBancaria{}, colorPrimario, colorSecundario, logoBase64, logoMime
|
||||
"""
|
||||
PRIMARY = data.get("colorPrimario") or PRIMARY_DEFAULT
|
||||
DARK = data.get("colorSecundario") or DARK_DEFAULT
|
||||
primary_rgb = _hex_to_rgb(PRIMARY)
|
||||
dark_rgb = _hex_to_rgb(DARK)
|
||||
muted_rgb = _hex_to_rgb(MUTED)
|
||||
border_rgb = _hex_to_rgb(BORDER)
|
||||
light_rgb = _hex_to_rgb(LIGHT_BG)
|
||||
white_rgb = _hex_to_rgb(WHITE)
|
||||
|
||||
buf = io.BytesIO()
|
||||
c = canvas.Canvas(buf, pagesize=LETTER)
|
||||
c.setTitle(f"Cotizacion {data.get('numero', '')}")
|
||||
|
||||
logo = _load_logo(data.get("logoBase64"), data.get("logoMime"))
|
||||
|
||||
servicios = data.get("servicios", [])
|
||||
plan_nivel = data.get("planBucefaloNivel")
|
||||
plan_precio = data.get("planBucefaloPrecio", 0)
|
||||
incluir_bonos = data.get("incluirBonos", False)
|
||||
cfg_bancaria = data.get("configBancaria") or {}
|
||||
|
||||
# ── PAGE 1: COVER ──────────────────────────────
|
||||
c.setFillColor(white_rgb)
|
||||
c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
|
||||
|
||||
y = PAGE_H - 80
|
||||
if logo:
|
||||
try:
|
||||
c.drawImage(logo, MARGIN_LEFT, y - 20, width=65, height=65, preserveAspectRatio=True, mask="auto")
|
||||
y -= 85
|
||||
except Exception:
|
||||
logo = None
|
||||
|
||||
if not logo:
|
||||
c.setFont("Helvetica-Bold", 28)
|
||||
c.setFillColor(primary_rgb)
|
||||
c.drawString(MARGIN_LEFT, y, "UJ")
|
||||
c.setFont("Helvetica", 9)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(MARGIN_LEFT + 48, y - 15, "Uriel Jareth Consulting")
|
||||
y -= 40
|
||||
|
||||
bar_y = y
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, bar_y, CONTENT_W, 4, fill=1, stroke=0)
|
||||
|
||||
c.setFont("Helvetica-Bold", 36)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT, bar_y - 40, "Cotizacion")
|
||||
c.setFont("Helvetica", 18)
|
||||
c.setFillColor(primary_rgb)
|
||||
c.drawString(MARGIN_LEFT, bar_y - 65, data.get("numero", ""))
|
||||
|
||||
iy = bar_y - 100
|
||||
cL = MARGIN_LEFT
|
||||
cR = MARGIN_LEFT + CONTENT_W * 0.52
|
||||
|
||||
info_l = [
|
||||
("Cliente", data.get("clienteNombre", "")),
|
||||
("Empresa", data.get("clienteEmpresa", "")),
|
||||
("Proyecto", data.get("proyecto", "")),
|
||||
("Asesor", data.get("asesorNombre", "")),
|
||||
]
|
||||
info_r = [
|
||||
("Fecha", _fmt_date(data.get("fecha", datetime.now()))),
|
||||
("Vigencia", _fmt_date(data.get("vigencia", datetime.now()))),
|
||||
("Moneda", data.get("moneda", "MXN")),
|
||||
("Esquema", data.get("esquemaPago", "")),
|
||||
]
|
||||
|
||||
for i in range(max(len(info_l), len(info_r))):
|
||||
if i < len(info_l) and info_l[i][1]:
|
||||
c.setFont("Helvetica", 9)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(cL, iy, info_l[i][0])
|
||||
c.setFont("Helvetica", 11)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(cL, iy - 14, info_l[i][1])
|
||||
if i < len(info_r) and info_r[i][1]:
|
||||
c.setFont("Helvetica", 9)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(cR, iy, info_r[i][0])
|
||||
c.setFont("Helvetica", 11)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(cR, iy - 14, str(info_r[i][1]))
|
||||
iy -= 32
|
||||
|
||||
# ── PAGE 2+: RESUMEN ──────────────────────────
|
||||
c.showPage()
|
||||
y = PAGE_H - MARGIN_TOP
|
||||
|
||||
if logo:
|
||||
try:
|
||||
c.drawImage(logo, MARGIN_LEFT + CONTENT_W - 70, y - 5, width=22, height=22, preserveAspectRatio=True, mask="auto")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y - 16, 4, 16, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 15)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 12, y - 15, "Hoja Resumen")
|
||||
y -= 28
|
||||
|
||||
cliente_ref = data.get("clienteEmpresa") or data.get("clienteNombre", "")
|
||||
c.setFont("Helvetica", 8)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(MARGIN_LEFT, y, f"En atencion a: {cliente_ref}")
|
||||
c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y, f"No. Cotizacion: {data.get('numero', '')}")
|
||||
y -= 11
|
||||
c.drawString(MARGIN_LEFT, y, f"Asesor: {data.get('asesorNombre', '')}")
|
||||
c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y, f"Fecha: {_fmt_date(data.get('fecha', datetime.now()))} | Moneda: {data.get('moneda', 'MXN')}")
|
||||
y -= 18
|
||||
|
||||
col_nombre = MARGIN_LEFT
|
||||
col_tipo = MARGIN_LEFT + CONTENT_W - 200
|
||||
col_tiempo = MARGIN_LEFT + CONTENT_W - 120
|
||||
col_precio = MARGIN_LEFT + CONTENT_W - 60
|
||||
|
||||
es_doble = bool(data.get("esDoble"))
|
||||
opciones_meta = data.get("opcionesMetadata") or {}
|
||||
|
||||
def _draw_table_header(y_pos):
|
||||
c.setFillColor(light_rgb)
|
||||
c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 16, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 7)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(col_nombre + 6, y_pos + 3, "Servicio")
|
||||
c.drawString(col_tipo + 4, y_pos + 3, "Tipo")
|
||||
c.drawString(col_tiempo + 4, y_pos + 3, "Entrega")
|
||||
c.drawRightString(col_precio + 60, y_pos + 3, "Precio")
|
||||
y_pos -= 4
|
||||
c.setStrokeColor(border_rgb)
|
||||
c.setLineWidth(0.3)
|
||||
c.line(MARGIN_LEFT, y_pos, MARGIN_LEFT + CONTENT_W, y_pos)
|
||||
return y_pos - 14
|
||||
|
||||
unicos = [s for s in servicios if s.get("tipoPago") == "unico"]
|
||||
mensuales = [s for s in servicios if s.get("tipoPago") == "mensual"]
|
||||
|
||||
def _draw_section(srv_list, tipo_label, titulo_total, y_pos):
|
||||
if not srv_list:
|
||||
return y_pos
|
||||
current_fase = -1
|
||||
max_y = PAGE_H - MARGIN_BOTTOM - 5
|
||||
|
||||
for serv in srv_list:
|
||||
fase = serv.get("fase", 0)
|
||||
if fase != current_fase:
|
||||
current_fase = fase
|
||||
if y_pos - 20 < max_y - PAGE_H:
|
||||
c.showPage()
|
||||
y_pos = PAGE_H - MARGIN_TOP
|
||||
c.setFillColor(light_rgb)
|
||||
c.rect(MARGIN_LEFT, y_pos - 14, CONTENT_W, 14, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 7)
|
||||
c.setFillColor(primary_rgb)
|
||||
c.drawString(MARGIN_LEFT + 6, y_pos - 11, FASES_SHORT.get(fase, f"FASE {fase}"))
|
||||
y_pos -= 18
|
||||
|
||||
c.setFont("Helvetica", 8)
|
||||
c.setFillColor(dark_rgb)
|
||||
nombre = serv.get("nombre", "")
|
||||
c.drawString(col_nombre + 6, y_pos - 10, nombre[:60])
|
||||
c.setFont("Helvetica", 7)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(col_tipo + 4, y_pos - 10, tipo_label)
|
||||
c.drawString(col_tiempo + 4, y_pos - 10, serv.get("tiempoEntrega", "")[:15])
|
||||
c.setFont("Helvetica-Bold", 8)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawRightString(col_precio + 60, y_pos - 10, _fmt_currency(serv.get("precio", 0)))
|
||||
y_pos -= 14
|
||||
|
||||
detalle = detalle_modelo(serv)
|
||||
if detalle:
|
||||
c.setFont("Helvetica-Oblique", 6.5)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(col_nombre + 10, y_pos - 7, detalle[:90])
|
||||
y_pos -= 9
|
||||
|
||||
entregables = serv.get("entregables", [])
|
||||
if entregables:
|
||||
half = (len(entregables) + 1) // 2
|
||||
for idx in range(half):
|
||||
e1 = entregables[idx]
|
||||
e2 = entregables[idx + half] if idx + half < len(entregables) else None
|
||||
c.setFont("Helvetica", 6)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(col_nombre + 10, y_pos - 8, f"\u2022 {e1[:50]}")
|
||||
if e2:
|
||||
c.drawString(col_nombre + CONTENT_W * 0.48, y_pos - 8, f"\u2022 {e2[:50]}")
|
||||
y_pos -= 9
|
||||
|
||||
c.setStrokeColor(_hex_to_rgb("#e5e7eb"))
|
||||
c.setLineWidth(0.2)
|
||||
c.line(col_nombre + 6, y_pos, MARGIN_LEFT + CONTENT_W, y_pos)
|
||||
y_pos -= 6
|
||||
|
||||
total = sum(s.get("precio", 0) for s in srv_list)
|
||||
y_pos -= 4
|
||||
c.setFillColor(_hex_to_rgb("#f8fafc"))
|
||||
c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 18, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 8.5)
|
||||
c.setFillColor(primary_rgb)
|
||||
c.drawString(col_nombre + 6, y_pos + 3, titulo_total)
|
||||
c.drawRightString(col_precio + 60, y_pos + 3, _fmt_currency(total))
|
||||
y_pos -= 18
|
||||
c.setFont("Helvetica", 6)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.drawString(col_nombre + 6, y_pos, "(Precios en Moneda Nacional, no incluyen IVA)")
|
||||
y_pos -= 14
|
||||
return y_pos
|
||||
|
||||
def _draw_opcion_header(op, y_pos):
|
||||
meta = opciones_meta.get(op) or {}
|
||||
max_y = PAGE_H - MARGIN_BOTTOM - 5
|
||||
if y_pos - 30 < max_y:
|
||||
c.showPage()
|
||||
y_pos = PAGE_H - MARGIN_TOP
|
||||
titulo = meta.get("titulo")
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y_pos - 18, CONTENT_W, 18, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 10)
|
||||
c.setFillColor(white_rgb)
|
||||
c.drawString(MARGIN_LEFT + 8, y_pos - 13, f"OPCION {op}" + (f": {titulo}" if titulo else ""))
|
||||
y_pos -= 24
|
||||
desc = meta.get("descripcion")
|
||||
if desc:
|
||||
c.setFont("Helvetica", 7.5)
|
||||
c.setFillColor(dark_rgb)
|
||||
for line in _wrap_text(c, desc, "Helvetica", 7.5, CONTENT_W - 12):
|
||||
c.drawString(MARGIN_LEFT + 6, y_pos - 8, line)
|
||||
y_pos -= 10
|
||||
y_pos -= 2
|
||||
no_incluye = meta.get("noIncluye")
|
||||
if no_incluye:
|
||||
c.setFont("Helvetica-Oblique", 7)
|
||||
c.setFillColor(muted_rgb)
|
||||
for line in _wrap_text(c, f"No incluye: {no_incluye}", "Helvetica-Oblique", 7, CONTENT_W - 12):
|
||||
c.drawString(MARGIN_LEFT + 6, y_pos - 8, line)
|
||||
y_pos -= 10
|
||||
y_pos -= 4
|
||||
return y_pos
|
||||
|
||||
def _draw_comparativa(y_pos):
|
||||
t1 = calcular_totales_opcion(servicios, "1")
|
||||
t2 = calcular_totales_opcion(servicios, "2")
|
||||
max_y = PAGE_H - MARGIN_BOTTOM - 5
|
||||
if y_pos - 90 < max_y:
|
||||
c.showPage()
|
||||
y_pos = PAGE_H - MARGIN_TOP
|
||||
y_pos -= 6
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y_pos - 10, 3, 10, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 10)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 10, y_pos - 8, "Comparativa de opciones")
|
||||
y_pos -= 22
|
||||
c_label = MARGIN_LEFT
|
||||
c_op1 = MARGIN_LEFT + CONTENT_W * 0.45
|
||||
c_op2 = MARGIN_LEFT + CONTENT_W * 0.72
|
||||
t1_tit = (opciones_meta.get("1") or {}).get("titulo")
|
||||
t2_tit = (opciones_meta.get("2") or {}).get("titulo")
|
||||
c.setFillColor(light_rgb)
|
||||
c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 16, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 7.5)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(c_label + 6, y_pos + 3, "Concepto")
|
||||
c.drawString(c_op1, y_pos + 3, f"Opcion 1" + (f" - {t1_tit}" if t1_tit else ""))
|
||||
c.drawString(c_op2, y_pos + 3, f"Opcion 2" + (f" - {t2_tit}" if t2_tit else ""))
|
||||
y_pos -= 18
|
||||
filas = [
|
||||
("Total unico (c/IVA)", _fmt_currency(t1["totalUnico"] * 1.16), _fmt_currency(t2["totalUnico"] * 1.16)),
|
||||
("Total mensual (c/IVA)", _fmt_currency(t1["totalMensual"] * 1.16), _fmt_currency(t2["totalMensual"] * 1.16)),
|
||||
("Horas estimadas", f"{t1['horas']:g} h", f"{t2['horas']:g} h"),
|
||||
]
|
||||
for lab, v1, v2 in filas:
|
||||
c.setFont("Helvetica", 8)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(c_label + 6, y_pos - 8, lab)
|
||||
c.setFont("Helvetica-Bold", 8)
|
||||
c.drawString(c_op1, y_pos - 8, v1)
|
||||
c.drawString(c_op2, y_pos - 8, v2)
|
||||
c.setStrokeColor(_hex_to_rgb("#e5e7eb"))
|
||||
c.setLineWidth(0.2)
|
||||
c.line(c_label + 6, y_pos - 12, MARGIN_LEFT + CONTENT_W, y_pos - 12)
|
||||
y_pos -= 14
|
||||
return y_pos - 8
|
||||
|
||||
if es_doble:
|
||||
for op in ("1", "2"):
|
||||
y = _draw_opcion_header(op, y)
|
||||
y = _draw_table_header(y)
|
||||
u = [s for s in unicos if s.get("opcion") in (op, "ambas")]
|
||||
me = [s for s in mensuales if s.get("opcion") in (op, "ambas")]
|
||||
if u:
|
||||
y = _draw_section(u, "Unico", f"Total Pago Unico - Opcion {op}", y)
|
||||
if me:
|
||||
y = _draw_section(me, "Mensual", f"Total Pago Mensual - Opcion {op}", y)
|
||||
y = _draw_comparativa(y)
|
||||
else:
|
||||
y = _draw_table_header(y)
|
||||
if unicos:
|
||||
y = _draw_section(unicos, "Unico", "Total Pago Unico", y)
|
||||
if mensuales:
|
||||
y = _draw_section(mensuales, "Mensual", "Total Pago Mensual", y)
|
||||
|
||||
if plan_nivel:
|
||||
label = plan_nivel.capitalize()
|
||||
c.setFillColor(light_rgb)
|
||||
c.rect(MARGIN_LEFT, y - 2, CONTENT_W, 14, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 7.5)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(col_nombre + 6, y + 3, f"Plan Bucefalo CRM - {label}")
|
||||
c.drawRightString(col_precio + 60, y + 3, _fmt_currency(plan_precio))
|
||||
y -= 20
|
||||
|
||||
if incluir_bonos:
|
||||
y -= 6
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y - 10, 3, 10, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 9)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 10, y - 8, "Bonos (Pago en una exhibicion)")
|
||||
y -= 20
|
||||
bonos = [
|
||||
"Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)",
|
||||
"Bono 2: Workshop Estrategico de Buyer Persona",
|
||||
"Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible",
|
||||
"Bono 4: 1 ano de Membresia Premium",
|
||||
"Bono 5: Un mes gratis de Bucefalo CRM",
|
||||
"Bono 6: Script de Ventas con mas de 100 complementos",
|
||||
]
|
||||
for b in bonos:
|
||||
c.setFont("Helvetica", 7)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 8, y - 8, f"\u2713 {b}")
|
||||
y -= 12
|
||||
|
||||
# ── T&C PAGE ──────────────────────────────────
|
||||
c.showPage()
|
||||
y = PAGE_H - MARGIN_TOP
|
||||
|
||||
if logo:
|
||||
try:
|
||||
c.drawImage(logo, MARGIN_LEFT + CONTENT_W - 70, y - 5, width=22, height=22, preserveAspectRatio=True, mask="auto")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y - 16, 4, 16, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 15)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 12, y - 15, "Terminos y Condiciones")
|
||||
y -= 30
|
||||
|
||||
def _section_title(title, yy):
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, yy - 9, 3, 9, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 9)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 10, yy - 8, title)
|
||||
return yy - 20
|
||||
|
||||
def _draw_bullets(title, items, yy):
|
||||
yy = _section_title(title, yy)
|
||||
for t in items:
|
||||
c.setFont("Helvetica", 7.5)
|
||||
c.setFillColor(dark_rgb)
|
||||
# Simple text wrapping
|
||||
words = t.split()
|
||||
line = ""
|
||||
for word in words:
|
||||
test = f"{line} {word}".strip()
|
||||
if c.stringWidth(test, "Helvetica", 7.5) > CONTENT_W - 10:
|
||||
c.drawString(MARGIN_LEFT + 2, yy - 8, f"\u2022 {line}")
|
||||
yy -= 11
|
||||
line = word
|
||||
else:
|
||||
line = test
|
||||
if line:
|
||||
c.drawString(MARGIN_LEFT + 2, yy - 8, f"\u2022 {line}")
|
||||
yy -= 11
|
||||
return yy - 8
|
||||
|
||||
y = _draw_bullets("Condiciones", [
|
||||
"Esta cotizacion tiene una vigencia de 15 dias habiles.",
|
||||
"Cualquier ajuste al proyecto despues de la aprobacion del contenido afectara la fecha de entrega y por consiguiente el costo.",
|
||||
"El cliente debera proporcionar la informacion solicitada por Uriel Jareth Consulting en tiempo y forma.",
|
||||
"Si la falta de informacion provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizaran por separado.",
|
||||
"Los pagos correspondientes a los servicios mensuales deberan realizarse en los primeros 5 dias del mes.",
|
||||
"Todo el material e informacion necesarios para la realizacion del sitio web deberan ser entregados en un plazo maximo de 40 dias naturales a partir del arranque del proyecto.",
|
||||
], y)
|
||||
|
||||
y = _draw_bullets("Que no incluye el proyecto?", [
|
||||
"Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.",
|
||||
"Redaccion de entradas de Blog.",
|
||||
"Integracion de Servicios de terceros ajenos a los cotizados.",
|
||||
"Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.",
|
||||
"Creacion de Redes Sociales (En caso de requerir el servicio incluira un costo adicional).",
|
||||
], y)
|
||||
|
||||
y = _draw_bullets("Notas", [
|
||||
"El presente proyecto debera tener un responsable oficial.",
|
||||
"La Hora Centinela tiene un precio de $700.00 MXN.",
|
||||
"Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberacion (buy-out fee).",
|
||||
"Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generara costo extra del 15% al 30% para retomar el proyecto.",
|
||||
], y)
|
||||
|
||||
y -= 8
|
||||
c.setFillColor(primary_rgb)
|
||||
c.rect(MARGIN_LEFT, y - 9, 3, 9, fill=1, stroke=0)
|
||||
c.setFont("Helvetica-Bold", 9)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 10, y - 8, "Datos Bancarios")
|
||||
y -= 20
|
||||
|
||||
razon_social = cfg_bancaria.get("razon_social", "URIEL JARETH ALVARADO ORTIZ")
|
||||
rfc = cfg_bancaria.get("rfc", "AAOU970201SU7")
|
||||
clabe_nac = cfg_bancaria.get("clabe_interbancaria", cfg_bancaria.get("cuenta_nacional", ""))
|
||||
cuenta_nac = cfg_bancaria.get("cuenta_nacional", "")
|
||||
banco_nac = "BBVA" if cuenta_nac else ""
|
||||
|
||||
box_h = 48
|
||||
c.setFillColor(light_rgb)
|
||||
c.setStrokeColor(border_rgb)
|
||||
c.rect(MARGIN_LEFT, y - box_h, CONTENT_W, box_h, fill=1, stroke=1)
|
||||
c.setFont("Helvetica-Bold", 7)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 8, y - 12, "Transferencia Nacional")
|
||||
c.setFont("Helvetica", 6.5)
|
||||
if cuenta_nac:
|
||||
c.drawString(MARGIN_LEFT + 8, y - 24, f"Cuenta: {cuenta_nac}")
|
||||
if clabe_nac:
|
||||
c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 24, f"CLABE: {clabe_nac}")
|
||||
c.drawString(MARGIN_LEFT + 8, y - 35, f"Razon Social: {razon_social}")
|
||||
c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 35, f"RFC: {rfc}")
|
||||
if banco_nac:
|
||||
c.drawString(MARGIN_LEFT + 8, y - 46, f"Banco: {banco_nac}")
|
||||
y -= box_h + 8
|
||||
|
||||
c.setFillColor(light_rgb)
|
||||
c.rect(MARGIN_LEFT, y - box_h, CONTENT_W, box_h, fill=1, stroke=1)
|
||||
c.setFont("Helvetica-Bold", 7)
|
||||
c.setFillColor(dark_rgb)
|
||||
c.drawString(MARGIN_LEFT + 8, y - 12, "Transferencia Internacional")
|
||||
c.setFont("Helvetica", 6.5)
|
||||
c.drawString(MARGIN_LEFT + 8, y - 24, f"Beneficiario: {razon_social}")
|
||||
c.drawString(MARGIN_LEFT + 8, y - 35, "Banco: BBVA Mexico")
|
||||
c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 35, "SWIFT: BCMRMXMMPYM")
|
||||
|
||||
# ── FOOTER ON ALL PAGES ──────────────────────
|
||||
page_count = c.getPageNumber()
|
||||
for i in range(1, page_count + 1):
|
||||
c.setPageSize(LETTER)
|
||||
c.setFont("Helvetica", 6)
|
||||
c.setFillColor(muted_rgb)
|
||||
c.setStrokeColor(border_rgb)
|
||||
c.setLineWidth(0.5)
|
||||
c.line(MARGIN_LEFT, MARGIN_BOTTOM - 10, MARGIN_LEFT + CONTENT_W, MARGIN_BOTTOM - 10)
|
||||
c.drawCentredString(PAGE_W / 2, MARGIN_BOTTOM - 22, "Uriel Jareth Consulting")
|
||||
c.drawCentredString(PAGE_W / 2, MARGIN_BOTTOM - 32, "urieljareth.com | [email protected] | (445) 182 9943")
|
||||
|
||||
c.save()
|
||||
return buf.getvalue()
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
"""Cotizador E3 — FastAPI Application
|
||||
|
||||
REST API for digital marketing quotation management.
|
||||
Optimized for n8n workflows and other integrations.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.config import settings
|
||||
from app.database import close_db, init_db
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await init_db()
|
||||
yield
|
||||
await close_db()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Cotizador E3 API",
|
||||
description=(
|
||||
"API REST para el sistema de cotizaciones de marketing digital de Consultoría E3. "
|
||||
"Optimizada para integración con n8n y otros consumidores. "
|
||||
"Autenticación por X-API-Key o Bearer JWT."
|
||||
),
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
openapi_tags=[
|
||||
{"name": "Health", "description": "Health check y información de la API"},
|
||||
{"name": "Auth", "description": "Autenticación (API Key + JWT)"},
|
||||
{"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": "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"},
|
||||
{"name": "Financiamiento", "description": "Planes y cálculo de financiamiento"},
|
||||
{"name": "Export", "description": "Exportación de PDF, Excel y CSV"},
|
||||
{"name": "Import", "description": "Importación masiva de servicios"},
|
||||
],
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"error": "Error interno del servidor", "detail": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
# Register routers
|
||||
from app.routers import (
|
||||
auth,
|
||||
bonos,
|
||||
catalogo,
|
||||
categorias,
|
||||
clientes,
|
||||
configuracion,
|
||||
cotizaciones,
|
||||
export_,
|
||||
financiamiento,
|
||||
health,
|
||||
import_,
|
||||
paquetes,
|
||||
)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(clientes.router)
|
||||
app.include_router(catalogo.router)
|
||||
app.include_router(categorias.router)
|
||||
app.include_router(cotizaciones.router)
|
||||
app.include_router(paquetes.router)
|
||||
app.include_router(configuracion.router)
|
||||
app.include_router(bonos.router)
|
||||
app.include_router(financiamiento.router)
|
||||
app.include_router(export_.router)
|
||||
app.include_router(import_.router)
|
||||
|
||||
# El servidor MCP se retiro (2026-07-28). No se estaba usando, su transporte
|
||||
# llevaba tiempo roto (instanciaba un StreamableHTTPServerTransport por peticion,
|
||||
# sin manejo de sesion, y devolvia 500 con credencial valida) y su SDK sin fijar
|
||||
# tumbo el API entero en produccion al saltar a 2.0.0. Si algun dia se retoma,
|
||||
# el codigo esta en el historial: `git show edb500f5:api/app/mcp/server.py`.
|
||||
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return {
|
||||
"name": "Cotizador E3 API",
|
||||
"version": "1.0.0",
|
||||
"docs": "/docs",
|
||||
"openapi": "/openapi.json",
|
||||
"health": "/health",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("main:app", host=settings.API_HOST, port=settings.API_PORT, reload=True)
|
||||
@@ -1,30 +0,0 @@
|
||||
# Versiones FIJAS a proposito.
|
||||
#
|
||||
# Por que: el 2026-07-28 una reconstruccion del API tomo mcp 2.0.0 (el rango era
|
||||
# `mcp>=1.0.0`), que elimino Server.list_tools(). El import lanzo AttributeError
|
||||
# al arrancar y dejo el contenedor en crash-loop ~50 minutos. Once de las doce
|
||||
# dependencias eran rangos `>=` sin techo, o sea que cada build era una tirada de
|
||||
# dados contra PyPI: `pydantic>=2.0` habria aceptado pydantic 3 igual de alegre.
|
||||
#
|
||||
# Estas versiones son exactamente las que corrian sanas en produccion cuando se
|
||||
# fijaron (capturadas con `pip freeze` del contenedor healthy).
|
||||
#
|
||||
# Para subir una dependencia: cambiala aqui a proposito, reconstruye y prueba.
|
||||
# Nunca por accidente al redesplegar.
|
||||
#
|
||||
# Limitacion conocida: esto fija las dependencias DIRECTAS. Las transitivas
|
||||
# (starlette, cryptography, anyio...) las sigue resolviendo pip. Es un riesgo
|
||||
# mucho menor, pero si algun dia muerde, el siguiente paso es un lock completo
|
||||
# con pip-tools o uv.
|
||||
|
||||
fastapi==0.140.13
|
||||
uvicorn[standard]==0.51.0
|
||||
asyncpg==0.31.0
|
||||
pydantic==2.13.4
|
||||
pydantic-settings==2.14.2
|
||||
python-jose[cryptography]==3.5.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
python-multipart==0.0.32
|
||||
reportlab==5.0.0
|
||||
openpyxl==3.1.5
|
||||
httpx==0.28.1
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
/**
|
||||
* Caza del error intermitente: corre el pipeline real contra UJ2606UR001 hasta que
|
||||
* falle, e imprime TODO lo que sepamos de la peticion que lo provoco.
|
||||
*/
|
||||
import { cargarEconomia } from "@/lib/propuesta/economia";
|
||||
import { crearCliente, modelo } from "@/lib/propuesta/cliente-ia";
|
||||
import { hechosSchema, diagnosticoSchema, redaccionSchema, aJsonSchema, type Hechos, type Diagnostico } from "@/lib/propuesta/schemas";
|
||||
import { SYSTEM_BASE, mensajePaso1, mensajePaso2, mensajePaso3, type ContextoEntrada } from "@/lib/propuesta/prompts";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type Anthropic from "@anthropic-ai/sdk";
|
||||
import type { z } from "zod";
|
||||
import fs from "node:fs";
|
||||
|
||||
const LOG = process.argv[2];
|
||||
// Escritura directa: el buffer de stdout se pierde si el proceso muere.
|
||||
function log(...a: unknown[]) {
|
||||
const linea = a.map((x) => (typeof x === "string" ? x : JSON.stringify(x))).join(" ");
|
||||
fs.appendFileSync(LOG, linea + "\n");
|
||||
}
|
||||
const console = { log } as unknown as Console;
|
||||
|
||||
const NUMERO = "UJ2606UR001";
|
||||
const TRANSCRIPCION = "Una propuesta de zero to hero para un negocio inicial";
|
||||
|
||||
/** Igual que llamarConHerramienta pero registra cada peticion y explota con detalle. */
|
||||
async function correrPaso(nombre: string, msg: string, schema: z.ZodType, maxTokens: number, maxIntentos: number) {
|
||||
const cliente = crearCliente();
|
||||
const tools = [{ name: nombre, description: "Registra el resultado.", input_schema: aJsonSchema(schema) as never }];
|
||||
const mensajes: Anthropic.MessageParam[] = [{ role: "user", content: msg }];
|
||||
|
||||
for (let intento = 1; intento <= maxIntentos; intento++) {
|
||||
let res: Anthropic.Message;
|
||||
try {
|
||||
res = await cliente.messages.create({
|
||||
model: modelo(), max_tokens: maxTokens,
|
||||
system: [{ type: "text", text: SYSTEM_BASE, cache_control: { type: "ephemeral" } }],
|
||||
tools, messages: mensajes,
|
||||
});
|
||||
} catch (e) {
|
||||
const err = e as { status?: number; message?: string; error?: unknown };
|
||||
console.log(`\n*** ERROR EN ${nombre} intento ${intento} ***`);
|
||||
console.log(" status:", err.status);
|
||||
console.log(" message:", String(err.message).slice(0, 600));
|
||||
if (err.error) console.log(" error:", JSON.stringify(err.error).slice(0, 800));
|
||||
console.log("\n --- FORMA DE LOS MENSAJES ENVIADOS ---");
|
||||
mensajes.forEach((m, i) => {
|
||||
const c = m.content;
|
||||
const tipos = typeof c === "string" ? "string" : (c as { type: string }[]).map((b) => b.type).join(",");
|
||||
console.log(` [${i}] role=${m.role} bloques=${tipos}`);
|
||||
});
|
||||
throw new Error("REPRODUCIDO");
|
||||
}
|
||||
|
||||
const bloques = res.content.map((b) => b.type).join(",");
|
||||
console.log(` ${nombre} intento ${intento}: stop=${res.stop_reason} bloques=[${bloques}] out=${res.usage.output_tokens}`);
|
||||
|
||||
const tus = res.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
|
||||
const ok = tus.find((b) => b.name === nombre);
|
||||
if (ok) {
|
||||
const parsed = schema.safeParse(ok.input);
|
||||
if (parsed.success) return parsed.data;
|
||||
const errTxt = (await import("zod")).z.prettifyError(parsed.error);
|
||||
console.log(` zod rechazo: ${errTxt.split("\n")[0]}`);
|
||||
mensajes.push(
|
||||
{ role: "assistant", content: res.content },
|
||||
{ role: "user", content: [
|
||||
...tus.map((b) => ({ type: "tool_result" as const, tool_use_id: b.id, is_error: true, content: errTxt })),
|
||||
{ type: "text" as const, text: "Corrige y reintenta." },
|
||||
] },
|
||||
);
|
||||
continue;
|
||||
}
|
||||
mensajes.push(
|
||||
{ role: "assistant", content: res.content },
|
||||
{ role: "user", content: `Debes llamar a ${nombre}.` },
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function unaVuelta(entrada: ContextoEntrada, econ: Awaited<ReturnType<typeof cargarEconomia>>, n: number) {
|
||||
console.log(`\n===== VUELTA ${n} =====`);
|
||||
const h = (await correrPaso("registrar_hechos", mensajePaso1(entrada), hechosSchema, 8000, 5)) as Hechos | null;
|
||||
if (!h) { console.log(" extraccion agoto intentos"); return; }
|
||||
const d = (await correrPaso("registrar_diagnostico", mensajePaso2(entrada, h, econ), diagnosticoSchema, 8000, 4)) as Diagnostico | null;
|
||||
if (!d) { console.log(" diagnostico agoto intentos"); return; }
|
||||
const r = await correrPaso("registrar_propuesta", mensajePaso3(entrada, h, d, econ), redaccionSchema, 12000, 4);
|
||||
console.log(r ? " vuelta completa OK" : " redaccion agoto intentos");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const cot = await prisma.cotizacion.findFirst({ where: { numero: NUMERO }, include: { cliente: true, servicios: true } });
|
||||
if (!cot) throw new Error("no encontrada");
|
||||
const econ = await cargarEconomia(cot.id);
|
||||
const entrada: ContextoEntrada = {
|
||||
transcripcion: TRANSCRIPCION,
|
||||
notas: cot.servicios.map((s) => s.notas).filter(Boolean).join("\n"),
|
||||
observaciones: cot.observaciones || "",
|
||||
cliente: cot.cliente.nombre, empresa: cot.cliente.empresa || "", proyecto: cot.proyecto,
|
||||
};
|
||||
console.log(`${econ.partidas.length} partidas`);
|
||||
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
try { await unaVuelta(entrada, econ, i); }
|
||||
catch (e) {
|
||||
if (e instanceof Error && e.message === "REPRODUCIDO") { console.log("\n>>> error reproducido, deteniendo"); break; }
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch((e) => { console.error("fallo:", e); process.exit(1); });
|
||||
@@ -0,0 +1,171 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/cli"
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/httpapi"
|
||||
"cotizador/internal/notify"
|
||||
"cotizador/internal/scheduler"
|
||||
"cotizador/internal/seed"
|
||||
"cotizador/internal/webhooks"
|
||||
)
|
||||
|
||||
func main() {
|
||||
subcmd := "serve"
|
||||
var subArgs []string
|
||||
if len(os.Args) > 1 {
|
||||
subcmd = os.Args[1]
|
||||
subArgs = os.Args[2:]
|
||||
}
|
||||
|
||||
switch subcmd {
|
||||
case "cli":
|
||||
os.Exit(cli.Run(subArgs))
|
||||
case "migrate":
|
||||
if err := runMigrate(); err != nil {
|
||||
log.Fatalf("[migrate] %v", err)
|
||||
}
|
||||
log.Println("[migrate] migraciones aplicadas correctamente")
|
||||
case "seed":
|
||||
if err := runSeed(); err != nil {
|
||||
log.Fatalf("[seed] %v", err)
|
||||
}
|
||||
log.Println("[seed] catalogo y configuracion inicial aplicados correctamente")
|
||||
case "provision-keys":
|
||||
if err := runProvisionKeys(subArgs); err != nil {
|
||||
log.Fatalf("[provision-keys] %v", err)
|
||||
}
|
||||
case "serve":
|
||||
if err := runServer(); err != nil {
|
||||
log.Fatalf("[serve] %v", err)
|
||||
}
|
||||
default:
|
||||
// Allow direct CLI commands like `cotizador esquema` or `cotizador servicios listar`
|
||||
os.Exit(cli.Run(os.Args[1:]))
|
||||
}
|
||||
}
|
||||
|
||||
func runMigrate() error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
pool, err := db.Connect(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
return db.Migrate(ctx, pool)
|
||||
}
|
||||
|
||||
func runSeed() error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
pool, err := db.Connect(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := db.Migrate(ctx, pool); err != nil {
|
||||
return err
|
||||
}
|
||||
return seed.Run(ctx, pool, cfg)
|
||||
}
|
||||
|
||||
func runProvisionKeys(args []string) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
pool, err := db.Connect(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
return seed.RunProvisionKeys(ctx, pool, args)
|
||||
}
|
||||
|
||||
func runServer() error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cfg.RequireJWTSecret(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
pool, err := db.Connect(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Always ensure schema migrations are applied on boot (safe & idempotent on live DBs)
|
||||
if err := db.Migrate(ctx, pool); err != nil {
|
||||
return fmt.Errorf("error en migracion automatica: %w", err)
|
||||
}
|
||||
if cfg.RunSeed {
|
||||
if err := seed.Run(ctx, pool, cfg); err != nil {
|
||||
return fmt.Errorf("error en seed automatico: %w", err)
|
||||
}
|
||||
log.Println("[boot] RUN_SEED=true aplicado correctamente")
|
||||
}
|
||||
|
||||
authSvc := auth.NewService(cfg.JWTSecret, cfg.IsProduction(), pool)
|
||||
whDispatcher := webhooks.NewDispatcher(pool, cfg)
|
||||
notifSvc := notify.NewService(cfg, pool, whDispatcher)
|
||||
|
||||
// Start recurring payment & reminder scheduler
|
||||
scheduler.Start(ctx, pool, notifSvc)
|
||||
|
||||
srv := httpapi.NewServer(cfg, pool, authSvc, whDispatcher, notifSvc)
|
||||
httpSrv := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
Handler: srv.Router(),
|
||||
ReadHeaderTimeout: 15 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 300 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("[cotizador] servidor Go escuchando en :%s (APP_URL=%s)", cfg.Port, cfg.AppURL)
|
||||
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[cotizador] cerrando servidor ordenadamente...")
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return httpSrv.Shutdown(shutCtx)
|
||||
case err := <-errCh:
|
||||
return err
|
||||
}
|
||||
}
|
||||
+23
-50
@@ -1,13 +1,10 @@
|
||||
# Cotizador E3 — stack de producción para Coolify
|
||||
# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify (Go + SPA embebido)
|
||||
#
|
||||
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
||||
# "Docker Compose Location" = /docker-compose.coolify.yml
|
||||
# En Coolify: Docker Compose Location = /docker-compose.yaml (copia byte-identica de este archivo).
|
||||
# Las variables SERVICE_FQDN_WEB_3000 las resuelve Coolify automáticamente.
|
||||
# Define JWT_SECRET, DB_PASSWORD y las variables opcionales en Coolify.
|
||||
#
|
||||
# Las variables SERVICE_FQDN_* las resuelve Coolify automáticamente (asignan
|
||||
# dominio a cada servicio). Define JWT_SECRET, API_KEY, DB_PASSWORD y las
|
||||
# SEED_* en el panel de variables de entorno de Coolify.
|
||||
#
|
||||
# Para desarrollo local sigue usándose docker-compose.yml + start.bat.
|
||||
# Para desarrollo local usa docker-compose.yml + start.bat.
|
||||
|
||||
services:
|
||||
postgres:
|
||||
@@ -16,6 +13,7 @@ services:
|
||||
environment:
|
||||
POSTGRES_USER: ${DB_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
||||
# Se conserva el nombre físico de BD en producción para no romper el volumen postgres_data.
|
||||
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
@@ -32,78 +30,53 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- SERVICE_FQDN_WEB_3000
|
||||
- PORT=3000
|
||||
- DB_HOST=postgres
|
||||
- DB_PORT=5432
|
||||
- DB_USER=${DB_USER:-postgres}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-postgres}
|
||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||
# Solo la usa el CLI de Prisma (migrate deploy); debe coincidir con DB_*
|
||||
- DATABASE_URL=postgresql://${DB_USER:-postgres}:${DB_PASSWORD:-postgres}@postgres:5432/${DB_NAME:-cotizador_e3}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
# Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el boton de
|
||||
# generar devuelve un error claro; el resto de la app funciona igual.
|
||||
# OJO: el prefijo NO puede ser ANTHROPIC_*, el SDK lo lee por su cuenta y
|
||||
# mandaria la clave de MiniMax a api.anthropic.com.
|
||||
# Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el botón devuelve error claro.
|
||||
- MINIMAX_API_KEY=${MINIMAX_API_KEY}
|
||||
- MINIMAX_BASE_URL=${MINIMAX_BASE_URL:-https://api.minimax.io/anthropic}
|
||||
- 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}
|
||||
# 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.
|
||||
# URL pública para links de correo, aprobación y notificaciones push
|
||||
- APP_URL=${APP_URL}
|
||||
# Web Push (VAPID)
|
||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
|
||||
# SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log.
|
||||
# SMTP de correos (opcional: sin SMTP_HOST se omite el envío y avisa en log)
|
||||
- SMTP_HOST=${SMTP_HOST}
|
||||
- SMTP_PORT=${SMTP_PORT:-587}
|
||||
- SMTP_USER=${SMTP_USER}
|
||||
- SMTP_PASS=${SMTP_PASS}
|
||||
- SMTP_FROM=${SMTP_FROM}
|
||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting}
|
||||
# Recordatorios de pagos pendientes (días; 0 = apagado)
|
||||
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||
# Comprobantes de pago en volumen persistente
|
||||
- UPLOAD_DIR=/app/uploads
|
||||
# Notificaciones de aprobación 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:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
start_period: 60s
|
||||
retries: 5
|
||||
|
||||
api:
|
||||
build:
|
||||
context: ./api
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- SERVICE_FQDN_API_8000
|
||||
- DB_HOST=postgres
|
||||
- DB_PORT=5432
|
||||
- DB_USER=${DB_USER:-postgres}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-postgres}
|
||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||
- API_KEY=${API_KEY}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
# web aplica las migraciones de Prisma; el api usa las mismas tablas
|
||||
web:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"]
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:3000/api/health >/dev/null || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
start_period: 30s
|
||||
|
||||
+23
-50
@@ -1,13 +1,10 @@
|
||||
# Cotizador E3 — stack de producción para Coolify
|
||||
# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify (Go + SPA embebido)
|
||||
#
|
||||
# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar
|
||||
# "Docker Compose Location" = /docker-compose.coolify.yml
|
||||
# En Coolify: Docker Compose Location = /docker-compose.yaml (copia byte-identica de este archivo).
|
||||
# Las variables SERVICE_FQDN_WEB_3000 las resuelve Coolify automáticamente.
|
||||
# Define JWT_SECRET, DB_PASSWORD y las variables opcionales en Coolify.
|
||||
#
|
||||
# Las variables SERVICE_FQDN_* las resuelve Coolify automáticamente (asignan
|
||||
# dominio a cada servicio). Define JWT_SECRET, API_KEY, DB_PASSWORD y las
|
||||
# SEED_* en el panel de variables de entorno de Coolify.
|
||||
#
|
||||
# Para desarrollo local sigue usándose docker-compose.yml + start.bat.
|
||||
# Para desarrollo local usa docker-compose.yml + start.bat.
|
||||
|
||||
services:
|
||||
postgres:
|
||||
@@ -16,6 +13,7 @@ services:
|
||||
environment:
|
||||
POSTGRES_USER: ${DB_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres}
|
||||
# Se conserva el nombre físico de BD en producción para no romper el volumen postgres_data.
|
||||
POSTGRES_DB: ${DB_NAME:-cotizador_e3}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
@@ -32,78 +30,53 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- SERVICE_FQDN_WEB_3000
|
||||
- PORT=3000
|
||||
- DB_HOST=postgres
|
||||
- DB_PORT=5432
|
||||
- DB_USER=${DB_USER:-postgres}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-postgres}
|
||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||
# Solo la usa el CLI de Prisma (migrate deploy); debe coincidir con DB_*
|
||||
- DATABASE_URL=postgresql://${DB_USER:-postgres}:${DB_PASSWORD:-postgres}@postgres:5432/${DB_NAME:-cotizador_e3}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
# Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el boton de
|
||||
# generar devuelve un error claro; el resto de la app funciona igual.
|
||||
# OJO: el prefijo NO puede ser ANTHROPIC_*, el SDK lo lee por su cuenta y
|
||||
# mandaria la clave de MiniMax a api.anthropic.com.
|
||||
# Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el botón devuelve error claro.
|
||||
- MINIMAX_API_KEY=${MINIMAX_API_KEY}
|
||||
- MINIMAX_BASE_URL=${MINIMAX_BASE_URL:-https://api.minimax.io/anthropic}
|
||||
- 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}
|
||||
# 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.
|
||||
# URL pública para links de correo, aprobación y notificaciones push
|
||||
- APP_URL=${APP_URL}
|
||||
# Web Push (VAPID)
|
||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
|
||||
# SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log.
|
||||
# SMTP de correos (opcional: sin SMTP_HOST se omite el envío y avisa en log)
|
||||
- SMTP_HOST=${SMTP_HOST}
|
||||
- SMTP_PORT=${SMTP_PORT:-587}
|
||||
- SMTP_USER=${SMTP_USER}
|
||||
- SMTP_PASS=${SMTP_PASS}
|
||||
- SMTP_FROM=${SMTP_FROM}
|
||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting}
|
||||
# Recordatorios de pagos pendientes (días; 0 = apagado)
|
||||
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||
# Comprobantes de pago en volumen persistente
|
||||
- UPLOAD_DIR=/app/uploads
|
||||
# Notificaciones de aprobación 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:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
start_period: 60s
|
||||
retries: 5
|
||||
|
||||
api:
|
||||
build:
|
||||
context: ./api
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- SERVICE_FQDN_API_8000
|
||||
- DB_HOST=postgres
|
||||
- DB_PORT=5432
|
||||
- DB_USER=${DB_USER:-postgres}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-postgres}
|
||||
- DB_NAME=${DB_NAME:-cotizador_e3}
|
||||
- API_KEY=${API_KEY}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
# web aplica las migraciones de Prisma; el api usa las mismas tablas
|
||||
web:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"]
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:3000/api/health >/dev/null || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
start_period: 30s
|
||||
|
||||
+7
-18
@@ -1,33 +1,22 @@
|
||||
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 físico de BD para no romper el volumen postgres_data.
|
||||
POSTGRES_DB: cotizador_e3
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
api:
|
||||
build: ./api
|
||||
container_name: cotizador-e3-api
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
- DB_HOST=postgres
|
||||
- DB_PORT=5432
|
||||
- DB_USER=postgres
|
||||
- DB_PASSWORD=postgres
|
||||
- DB_NAME=cotizador_e3
|
||||
- API_KEY=${API_KEY:-change-me}
|
||||
- JWT_SECRET=${JWT_SECRET:-change-me}
|
||||
depends_on:
|
||||
- postgres
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d cotizador_e3"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
+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 [email protected] --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 [email protected]
|
||||
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(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Migración Completa a Go — Cotizador Uriel Jareth Consulting
|
||||
|
||||
Fecha: 2026-11-28
|
||||
Estado: Aprobado (Opción A — ejecución autónoma hasta producción)
|
||||
|
||||
## 1. Objetivo y Alcance
|
||||
|
||||
Unificar todo el sistema Cotizador en **un único binario en Go** (`cotizador`) acompañado del frontend React actual compilado como SPA estática (Vite) y embebido vía `//go:embed`, eliminando Node.js y Python FastAPI de producción.
|
||||
|
||||
- **Producción (Coolify)**: `postgres` (`postgres:16-alpine`, volumen `postgres_data` intacto) + `web` (binario Go en puerto `3000`, volumen `uploads_data:/app/uploads`). El servicio `api` (puerto `8000`, FastAPI) se elimina; todo el tráfico humano, de cliente y de agentes/n8n usa `/api/**` en `https://cotizador.urieljareth.org`.
|
||||
- **Compatibilidad de datos**: Conexión directa a las 25 tablas PostgreSQL existentes (nombres PascalCase/camelCase creados por Prisma) sin pérdidas ni cambios destructivos. Sesiones JWT (`cotizador-session`, HS256 con `JWT_SECRET`) y contraseñas `bcrypt` mantienen compatibilidad al 100%.
|
||||
|
||||
## 2. Arquitectura del Proyecto
|
||||
|
||||
```text
|
||||
cmd/
|
||||
cotizador/ # Binario único: serve (default), migrate, seed, provision-keys, cli
|
||||
internal/
|
||||
config/ # Variables de entorno (DB_*, JWT_SECRET, APP_URL, SMTP_*, VAPID_*, MINIMAX_*, WEBHOOK_*, etc.)
|
||||
db/ # pgxpool, migraciones SQL idempotentes embebidas, generador CUID
|
||||
seed/ # Seed idempotente (usuarios, 7 categorías, 59 servicios, 7 paquetes, 6 bonos, 4 financiamiento, 16 config)
|
||||
domain/ # calculators.go, cobros_fechas.go, aprobacion_core.go, solo_admin_core.go, models.go
|
||||
auth/ # JWT HS256, bcrypt, AgentApiKey SHA-256, 9 scopes, rate limiter 60s, RequireActor
|
||||
audit/ # Escritura best-effort a AuditLog
|
||||
idempotency/ # Idempotency-Key (TTL 24h, SHA-256 body, 409 mismatch, X-Idempotency-Replayed)
|
||||
webhooks/ # HMAC-SHA256, 8 eventos, fan-out WebhookEndpoint + WEBHOOK_N8N_URL, reintentos, WhatsApp n8n, pago.vencido idempotente
|
||||
notify/ # SMTP HTML/PDF, Web Push (VAPID), recordatorios pendientes, alertas de aprobación a Jareth
|
||||
uploads/ # Comprobantes en UPLOAD_DIR/comprobantes/<pagoId>/<uuid>.<ext> (<=10MB, WebP/JPEG/PDF, anti path-traversal)
|
||||
pdf/ # 4 generadores PDF con fuente TrueType UTF-8 embebida (cotización, nota de horas, propuesta IA cliente, anexo interno)
|
||||
excel/ # excelize/v2 (HOJA RESUMEN + hoja por servicio, simple y doble) + CSV catálogo export/plantilla/import
|
||||
propuesta/ # Cliente MiniMax (Anthropic Messages + tool-calling + cache), economía, prompts, pipeline 3 pasos, validación R0..R6/filtros
|
||||
scheduler/ # Goroutine (20s arranque, cada 60 min): generarCobros -> (>=9h MX) enviarRecordatoriosPendientes -> notificarCobrosNuevos
|
||||
httpapi/ # chi/v5 router, middlewares de seguridad y separación de paneles, 62+ endpoints + 4 endpoints SPA + OpenAPI 3.1 + SPA embebida
|
||||
cli/ # CLI en Go (29 comandos, esquema JSON, códigos de salida 0..7, ~/.cotizador-uj/sesiones.json)
|
||||
spa/ # //go:embed dist/* (build estático de web/)
|
||||
web/ # Vite + React 19 + React Router + Tailwind v4 + Zustand (15 vistas migradas de Next.js)
|
||||
```
|
||||
|
||||
## 3. Reglas de Seguridad e Invariantes
|
||||
|
||||
1. **Sin bypass de API key**: toda ruta protegida valida JWT o `AgentApiKey` directamente contra PostgreSQL (cierra el hueco de ~15 rutas que en Next.js dependían del middleware Edge).
|
||||
2. **Separación estricta de paneles**: `role=cliente` solo accede a `/cliente*`, `/api/cliente*`, `/api/comprobantes/{pagoId}` (propios) y `GET /api/export/pdf/{id}` (propios). Staff no accede a `/cliente*` ni `/api/cliente*`. API keys jamás acceden a `/api/cliente*`.
|
||||
3. **Regla de hierro de aprobación**: ningún agente puede aprobar cotizaciones (9 scopes permitidos, cero scope de aprobación). Transición `borrador -> aprobada` exige usuario humano `role="admin"` (`POST /api/cotizaciones/{id}/aprobar`) o enlace firmado de un solo uso (`/aprobar/{token}` con `POST { confirmar: true }`). Enviar exige `estado == "aprobada" && aprobadaAt != nil`.
|
||||
4. **Restricción `soloAdmin` (Bucéfalo CRM)**: oculto en catálogo/paquetes y bloqueado en creación/edición de cotizaciones para cualquier agente.
|
||||
5. **Privacidad estructural**: `observacionesInternas` nunca se expone en PDF/Excel ni a agentes con solo `cotizaciones:leer_aceptadas`.
|
||||
6. **Idempotencia**: `Idempotency-Key` en `POST /api/clientes`, `POST /api/cotizaciones`, `POST /api/cotizaciones/{id}/enviar` y `POST /api/cobros/pagos/{id}/registrar`.
|
||||
|
||||
## 4. Endpoints Adicionales para la SPA (reemplazo de Server Components)
|
||||
|
||||
- `GET /api/dashboard`: conteos de cotizaciones/clientes/servicios activos + 10 cotizaciones recientes.
|
||||
- `GET /api/asesores`: lista segura (`id`, `name`, `email`, `role`) de asesores/admins + siguiente secuencia de folio (`nextSeq`).
|
||||
- `GET /api/cobros/resumen`: datos consolidados de `/cobros` (programas con `proximaFecha`, clientes, pagos `en_revision`, saldos `pagosPorCobrar` agrupados por cliente y `diasRecordatorio`).
|
||||
- `GET /api/cliente/pagos`: incluye tanto `pagos` (compatibilidad) como `programas` agrupados y `bancaria` (`getConfigBancaria`).
|
||||
|
||||
## 5. Estrategia de Base de Datos y Despliegue
|
||||
|
||||
- `cotizador migrate` ejecuta `001_initial_schema.sql` completamente idempotente (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`) compatible al 100% con bases creadas por Prisma y bases nuevas vacías.
|
||||
- `Dockerfile` multi-stage:
|
||||
1. `node:22-alpine`: compila `web/` → `dist/`.
|
||||
2. `golang:1.25-alpine`: incrusta `web/dist` en `internal/spa/dist`, compila binario estático (`CGO_ENABLED=0`).
|
||||
3. `alpine:3.21`: `ca-certificates` + `tzdata` (para `America/Mexico_City`) + binario `cotizador`. Al arrancar corre `cotizador migrate`, condicionalmente `cotizador seed` (`RUN_SEED=true`), y luego `cotizador serve`.
|
||||
- `docker-compose.coolify.yml` y `docker-compose.yaml` (copia idéntica) mantienen `postgres` y `web` (puerto 3000) con los volúmenes `postgres_data` y `uploads_data`.
|
||||
- Despliegue: push a `origin` (GitHub `main`, auto-deploy Coolify) y espejo a `gitea`, seguido de verificación en vivo contra `https://cotizador.urieljareth.org`.
|
||||
@@ -1,18 +0,0 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,31 @@
|
||||
module cotizador
|
||||
|
||||
go 1.27.4
|
||||
|
||||
require (
|
||||
codeberg.org/go-pdf/fpdf v0.12.0
|
||||
github.com/HugoSmits86/nativewebp v1.3.0
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.13.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/xuri/excelize/v2 v2.11.1
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/image v0.48.0
|
||||
golang.org/x/text v0.44.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/richardlehane/mscfb v1.0.9 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.6 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.7.2 // indirect
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec // indirect
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
codeberg.org/go-pdf/fpdf v0.12.0 h1:g8E/1VqGqB2lZUUaqQrrTnA0IEJLPTTX1DZ0qS/ZmhU=
|
||||
codeberg.org/go-pdf/fpdf v0.12.0/go.mod h1:WJNJ2bvCj81rZBdhOf7lKOGoSl+OKMXcIcXqDcP8r5Y=
|
||||
github.com/HugoSmits86/nativewebp v1.3.0 h1:n1egtEzSV4KwFtealr7dzdYq1wI/uj/bOQ/QcTcIyVE=
|
||||
github.com/HugoSmits86/nativewebp v1.3.0/go.mod h1:YNQuWenlVmSUUASVNhTDwf4d7FwYQGbGhklC8p72Vr8=
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s=
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/richardlehane/mscfb v1.0.9 h1:8xdd9auUvXbFoCw3L9h1spnQHZgjNsSX+ek46J6A9tE=
|
||||
github.com/richardlehane/mscfb v1.0.9/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
|
||||
github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
|
||||
github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
|
||||
github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec h1:sZZokRLgr8nyrzkDDCQcvEYBsTrZr6eqXa/R9qALoQA=
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.11.1 h1:tm/FVufArvfUiJXJtGv8jna/zZS1t9Uji2ImsnS9iBo=
|
||||
github.com/xuri/excelize/v2 v2.11.1/go.mod h1:NQLBThVu4BB7tYM8wJIBj2dZsptXbDW4WyrFlL8YLZQ=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
|
||||
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,87 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
ActorTipo string
|
||||
ActorID string
|
||||
ActorNombre string
|
||||
Accion string
|
||||
RecursoTipo string
|
||||
RecursoID string
|
||||
IP string
|
||||
RequestID string
|
||||
Exito bool
|
||||
Detalle any
|
||||
}
|
||||
|
||||
func ClientIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if len(parts) > 0 && strings.TrimSpace(parts[0]) != "" {
|
||||
return strings.TrimSpace(parts[0])
|
||||
}
|
||||
}
|
||||
if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" {
|
||||
return xri
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
func RequestID(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
}
|
||||
|
||||
// Registrar writes an AuditLog row best-effort (never fails caller flow).
|
||||
func Registrar(ctx context.Context, pool *pgxpool.Pool, e Entry) {
|
||||
if pool == nil {
|
||||
return
|
||||
}
|
||||
var detalleBytes []byte
|
||||
if e.Detalle != nil {
|
||||
if b, err := json.Marshal(e.Detalle); err == nil {
|
||||
detalleBytes = b
|
||||
}
|
||||
}
|
||||
var actorID, recursoID, ip, reqID *string
|
||||
if e.ActorID != "" {
|
||||
v := e.ActorID
|
||||
actorID = &v
|
||||
}
|
||||
if e.RecursoID != "" {
|
||||
v := e.RecursoID
|
||||
recursoID = &v
|
||||
}
|
||||
if e.IP != "" {
|
||||
v := e.IP
|
||||
ip = &v
|
||||
}
|
||||
if e.RequestID != "" {
|
||||
v := e.RequestID
|
||||
reqID = &v
|
||||
}
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "AuditLog" ("id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`, db.NewID(), e.ActorTipo, actorID, e.ActorNombre, e.Accion, e.RecursoTipo, recursoID, ip, reqID, e.Exito, detalleBytes)
|
||||
if err != nil {
|
||||
log.Printf("[audit] error escribiendo AuditLog (%s): %v", e.Accion, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/domain"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionCookieName = "cotizador-session"
|
||||
SessionTTL = 7 * 24 * time.Hour
|
||||
APIKeyPrefix = "ujc_live_"
|
||||
)
|
||||
|
||||
// Exact 9 allowed agent scopes. NEVER add an approval scope.
|
||||
var AgentScopes = []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
"cobros:registrar",
|
||||
}
|
||||
|
||||
func IsValidScope(s string) bool {
|
||||
return slices.Contains(AgentScopes, s)
|
||||
}
|
||||
|
||||
type SessionPayload struct {
|
||||
UserID string `json:"userId"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ClienteID string `json:"clienteId,omitempty"`
|
||||
}
|
||||
|
||||
type jwtClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ClienteID string `json:"clienteId,omitempty"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type Actor struct {
|
||||
Type string // "user" | "agent"
|
||||
UserID string
|
||||
Email string
|
||||
Name string
|
||||
Role string // "admin" | "asesor" | "cliente"
|
||||
ClienteID string
|
||||
KeyID string
|
||||
KeyNombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
RateHeaders map[string]string
|
||||
}
|
||||
|
||||
func (a *Actor) ToDomainActor() domain.ActorInfo {
|
||||
return domain.ActorInfo{
|
||||
Type: a.Type,
|
||||
Role: a.Role,
|
||||
Scopes: a.Scopes,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Actor) AuditActor() (tipo, id, nombre string) {
|
||||
if a.Type == "agent" {
|
||||
return "agent", a.KeyID, a.KeyNombre
|
||||
}
|
||||
return "user", a.UserID, a.Email
|
||||
}
|
||||
|
||||
func (a *Actor) IsAdmin() bool {
|
||||
return a.Type == "user" && a.Role == "admin"
|
||||
}
|
||||
|
||||
func (a *Actor) IsStaff() bool {
|
||||
return a.Type == "user" && a.Role != "cliente"
|
||||
}
|
||||
|
||||
func (a *Actor) IsCliente() bool {
|
||||
return a.Type == "user" && a.Role == "cliente"
|
||||
}
|
||||
|
||||
func (a *Actor) IsAgent() bool {
|
||||
return a.Type == "agent"
|
||||
}
|
||||
|
||||
func (a *Actor) HasScopes(required []string, mode string) bool {
|
||||
if a.IsStaff() {
|
||||
return true
|
||||
}
|
||||
if !a.IsAgent() {
|
||||
return false
|
||||
}
|
||||
if len(required) == 0 {
|
||||
return true
|
||||
}
|
||||
if mode == "all" {
|
||||
for _, req := range required {
|
||||
if !slices.Contains(a.Scopes, req) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
for _, req := range required {
|
||||
if slices.Contains(a.Scopes, req) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EsAgenteSoloAceptadas returns true when agent has cotizaciones:leer_aceptadas and NOT cotizaciones:leer.
|
||||
func (a *Actor) EsAgenteSoloAceptadas() bool {
|
||||
return a.IsAgent() &&
|
||||
slices.Contains(a.Scopes, "cotizaciones:leer_aceptadas") &&
|
||||
!slices.Contains(a.Scopes, "cotizaciones:leer")
|
||||
}
|
||||
|
||||
func (a *Actor) ApplyHeaders(w http.ResponseWriter) {
|
||||
for k, v := range a.RateHeaders {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
func HashPassword(plain string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(plain), 10)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func ComparePassword(hash, plain string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
|
||||
}
|
||||
|
||||
func HashSecret(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func GenerateAPIKey() (rawKey, prefijo, keyHash string) {
|
||||
var b [32]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
rawKey = APIKeyPrefix + hex.EncodeToString(b[:])
|
||||
prefijo = rawKey[:14]
|
||||
keyHash = HashSecret(rawKey)
|
||||
return
|
||||
}
|
||||
|
||||
func GenerateRandomToken(numBytes int) (raw, hash string) {
|
||||
b := make([]byte, numBytes)
|
||||
_, _ = rand.Read(b)
|
||||
raw = hex.EncodeToString(b)
|
||||
hash = HashSecret(raw)
|
||||
return
|
||||
}
|
||||
|
||||
var nonDigitsRe = regexp.MustCompile(`\D+`)
|
||||
|
||||
// CoincideContacto matches exact email (case-insensitive) or last 10 digits of phone.
|
||||
func CoincideContacto(verificar string, clienteEmail, clienteTelefono string) bool {
|
||||
v := strings.TrimSpace(verificar)
|
||||
if v == "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(v, "@") {
|
||||
return clienteEmail != "" && strings.EqualFold(v, strings.TrimSpace(clienteEmail))
|
||||
}
|
||||
digitsV := nonDigitsRe.ReplaceAllString(v, "")
|
||||
digitsC := nonDigitsRe.ReplaceAllString(clienteTelefono, "")
|
||||
if len(digitsV) < 7 || len(digitsC) < 7 {
|
||||
return false
|
||||
}
|
||||
if len(digitsV) > 10 {
|
||||
digitsV = digitsV[len(digitsV)-10:]
|
||||
}
|
||||
if len(digitsC) > 10 {
|
||||
digitsC = digitsC[len(digitsC)-10:]
|
||||
}
|
||||
return digitsV == digitsC
|
||||
}
|
||||
|
||||
// RateLimiter implements an in-memory 60-second sliding window per API key.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string][]time.Time
|
||||
}
|
||||
|
||||
func NewRateLimiter() *RateLimiter {
|
||||
return &RateLimiter{buckets: make(map[string][]time.Time)}
|
||||
}
|
||||
|
||||
type RateLimitResult struct {
|
||||
Allowed bool
|
||||
Limit int
|
||||
Remaining int
|
||||
ResetUnix int64
|
||||
RetryAfter int
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) Check(keyID string, limit int, now time.Time) RateLimitResult {
|
||||
if limit < 1 {
|
||||
limit = 60
|
||||
}
|
||||
windowStart := now.Add(-60 * time.Second)
|
||||
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
existing := rl.buckets[keyID]
|
||||
kept := existing[:0]
|
||||
for _, ts := range existing {
|
||||
if ts.After(windowStart) {
|
||||
kept = append(kept, ts)
|
||||
}
|
||||
}
|
||||
|
||||
if len(kept) >= limit {
|
||||
rl.buckets[keyID] = kept
|
||||
oldest := kept[0]
|
||||
resetAt := oldest.Add(60 * time.Second)
|
||||
retrySec := int(time.Until(resetAt).Seconds())
|
||||
if now != (time.Time{}) {
|
||||
retrySec = int(resetAt.Sub(now).Seconds())
|
||||
}
|
||||
if retrySec < 1 {
|
||||
retrySec = 1
|
||||
}
|
||||
return RateLimitResult{
|
||||
Allowed: false,
|
||||
Limit: limit,
|
||||
Remaining: 0,
|
||||
ResetUnix: resetAt.Unix(),
|
||||
RetryAfter: retrySec,
|
||||
}
|
||||
}
|
||||
|
||||
kept = append(kept, now)
|
||||
rl.buckets[keyID] = kept
|
||||
resetAt := kept[0].Add(60 * time.Second)
|
||||
return RateLimitResult{
|
||||
Allowed: true,
|
||||
Limit: limit,
|
||||
Remaining: limit - len(kept),
|
||||
ResetUnix: resetAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func BuildRateLimitHeaders(res RateLimitResult) map[string]string {
|
||||
h := map[string]string{
|
||||
"X-RateLimit-Limit": strconv.Itoa(res.Limit),
|
||||
"X-RateLimit-Remaining": strconv.Itoa(res.Remaining),
|
||||
"X-RateLimit-Reset": strconv.FormatInt(res.ResetUnix, 10),
|
||||
}
|
||||
if !res.Allowed {
|
||||
retry := res.RetryAfter
|
||||
if retry < 1 {
|
||||
retry = 1
|
||||
}
|
||||
h["Retry-After"] = strconv.Itoa(retry)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
jwtSecret []byte
|
||||
isProduction bool
|
||||
pool *pgxpool.Pool
|
||||
limiter *RateLimiter
|
||||
}
|
||||
|
||||
func NewService(jwtSecret string, isProduction bool, pool *pgxpool.Pool) *Service {
|
||||
return &Service{
|
||||
jwtSecret: []byte(jwtSecret),
|
||||
isProduction: isProduction,
|
||||
pool: pool,
|
||||
limiter: NewRateLimiter(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) SignSession(p SessionPayload) (string, error) {
|
||||
now := time.Now()
|
||||
claims := jwtClaims{
|
||||
UserID: p.UserID,
|
||||
Email: p.Email,
|
||||
Name: p.Name,
|
||||
Role: p.Role,
|
||||
ClienteID: p.ClienteID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(SessionTTL)),
|
||||
},
|
||||
}
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return tok.SignedString(s.jwtSecret)
|
||||
}
|
||||
|
||||
func (s *Service) VerifySession(tokenStr string) (*SessionPayload, error) {
|
||||
if tokenStr == "" {
|
||||
return nil, errors.New("empty token")
|
||||
}
|
||||
tok, err := jwt.ParseWithClaims(tokenStr, &jwtClaims{}, func(t *jwt.Token) (any, error) {
|
||||
if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return s.jwtSecret, nil
|
||||
})
|
||||
if err != nil || !tok.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
c, ok := tok.Claims.(*jwtClaims)
|
||||
if !ok || c.UserID == "" {
|
||||
return nil, errors.New("invalid claims")
|
||||
}
|
||||
role := c.Role
|
||||
if role == "" {
|
||||
role = "asesor"
|
||||
}
|
||||
return &SessionPayload{
|
||||
UserID: c.UserID,
|
||||
Email: c.Email,
|
||||
Name: c.Name,
|
||||
Role: role,
|
||||
ClienteID: c.ClienteID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) SetSessionCookie(w http.ResponseWriter, token string) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
MaxAge: int(SessionTTL.Seconds()),
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: s.isProduction,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Secure: s.isProduction,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) SessionFromRequest(r *http.Request) (*SessionPayload, bool) {
|
||||
c, err := r.Cookie(SessionCookieName)
|
||||
if err != nil || c.Value == "" {
|
||||
return nil, false
|
||||
}
|
||||
p, err := s.VerifySession(c.Value)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func ExtractAPIKey(r *http.Request) string {
|
||||
if k := strings.TrimSpace(r.Header.Get("X-API-Key")); k != "" {
|
||||
return k
|
||||
}
|
||||
authz := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
if len(authz) > 7 && strings.EqualFold(authz[:7], "bearer ") {
|
||||
return strings.TrimSpace(authz[7:])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type RequireOptions struct {
|
||||
AdminOnly bool
|
||||
StaffOnly bool
|
||||
AllowCliente bool
|
||||
Scopes []string
|
||||
ScopeMode string // "any" (default) | "all"
|
||||
AccionBloqueo string
|
||||
RecursoTipo string
|
||||
RecursoID string
|
||||
}
|
||||
|
||||
// RequireActor authenticates either cookie session (priority) or AgentApiKey,
|
||||
// enforces role/scope/rate-limit rules, logs failures to AuditLog, and writes the HTTP error response if denied.
|
||||
func (s *Service) RequireActor(w http.ResponseWriter, r *http.Request, opts RequireOptions) (*Actor, bool) {
|
||||
var actor *Actor
|
||||
|
||||
// 1. Cookie JWT takes priority
|
||||
if sess, ok := s.SessionFromRequest(r); ok {
|
||||
actor = &Actor{
|
||||
Type: "user",
|
||||
UserID: sess.UserID,
|
||||
Email: sess.Email,
|
||||
Name: sess.Name,
|
||||
Role: sess.Role,
|
||||
ClienteID: sess.ClienteID,
|
||||
}
|
||||
} else if rawKey := ExtractAPIKey(r); rawKey != "" {
|
||||
// 2. Agent API Key lookup via SHA-256
|
||||
keyHash := HashSecret(rawKey)
|
||||
var id, nombre string
|
||||
var scopes []string
|
||||
var rateLimit int
|
||||
var lastUsedAt *time.Time
|
||||
err := s.pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "nombre", "scopes", "rateLimitPerMin", "lastUsedAt"
|
||||
FROM "AgentApiKey"
|
||||
WHERE "keyHash" = $1 AND "activo" = true AND "revokedAt" IS NULL
|
||||
`, keyHash).Scan(&id, &nombre, &scopes, &rateLimit, &lastUsedAt)
|
||||
if err != nil {
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
writeAuthJSON(w, http.StatusInternalServerError, map[string]any{"error": "Error validando credenciales"})
|
||||
return nil, false
|
||||
}
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: "agent",
|
||||
ActorNombre: "clave_invalida",
|
||||
Accion: "auth.api_key_invalida",
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "API key invalida o revocada"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Rate limit check
|
||||
rlRes := s.limiter.Check(id, rateLimit, time.Now())
|
||||
headers := BuildRateLimitHeaders(rlRes)
|
||||
if !rlRes.Allowed {
|
||||
for k, v := range headers {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: "agent",
|
||||
ActorID: id,
|
||||
ActorNombre: nombre,
|
||||
Accion: "auth.rate_limit",
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"limit": rateLimit, "path": r.URL.Path},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusTooManyRequests, map[string]any{"error": "Limite de peticiones por minuto excedido"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Throttled async lastUsedAt update (>60s)
|
||||
if lastUsedAt == nil || time.Since(*lastUsedAt) > 60*time.Second {
|
||||
go func(keyID string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE "AgentApiKey" SET "lastUsedAt" = NOW(), "updatedAt" = NOW() WHERE "id" = $1`, keyID)
|
||||
}(id)
|
||||
}
|
||||
|
||||
actor = &Actor{
|
||||
Type: "agent",
|
||||
KeyID: id,
|
||||
KeyNombre: nombre,
|
||||
Scopes: scopes,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RateHeaders: headers,
|
||||
}
|
||||
} else {
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Role / Scope enforcement
|
||||
if opts.AdminOnly && !actor.IsAdmin() {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.admin_requerido"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Solo un administrador humano puede realizar esta accion"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if opts.StaffOnly && !actor.IsStaff() {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.staff_requerido"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"path": r.URL.Path, "method": r.Method},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para equipo interno"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if actor.IsCliente() && !opts.AllowCliente {
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso no permitido para cuentas de cliente"})
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if len(opts.Scopes) > 0 && !actor.IsCliente() {
|
||||
mode := opts.ScopeMode
|
||||
if mode == "" {
|
||||
mode = "any"
|
||||
}
|
||||
if !actor.HasScopes(opts.Scopes, mode) {
|
||||
tipo, aid, anombre := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.pool, audit.Entry{
|
||||
ActorTipo: tipo,
|
||||
ActorID: aid,
|
||||
ActorNombre: anombre,
|
||||
Accion: firstOr(opts.AccionBloqueo, "auth.scope_insuficiente"),
|
||||
RecursoTipo: firstOr(opts.RecursoTipo, "auth"),
|
||||
RecursoID: opts.RecursoID,
|
||||
IP: audit.ClientIP(r),
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: false,
|
||||
Detalle: map[string]any{"requiredScopes": opts.Scopes, "path": r.URL.Path},
|
||||
})
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{
|
||||
"error": "Alcance insuficiente para esta operacion",
|
||||
"requiredScopes": opts.Scopes,
|
||||
})
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
actor.ApplyHeaders(w)
|
||||
return actor, true
|
||||
}
|
||||
|
||||
// RequireCliente enforces a valid cookie session with role == "cliente" and non-empty clienteId.
|
||||
func (s *Service) RequireCliente(w http.ResponseWriter, r *http.Request) (*SessionPayload, bool) {
|
||||
sess, ok := s.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"})
|
||||
return nil, false
|
||||
}
|
||||
if sess.Role != "cliente" || sess.ClienteID == "" {
|
||||
writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para clientes"})
|
||||
return nil, false
|
||||
}
|
||||
return sess, true
|
||||
}
|
||||
|
||||
func firstOr(v, fallback string) string {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func writeAuthJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAPIKeyAndScopes(t *testing.T) {
|
||||
raw, pref, hash := GenerateAPIKey()
|
||||
if !strings.HasPrefix(raw, APIKeyPrefix) || len(raw) != 73 {
|
||||
t.Fatalf("unexpected raw key format: len=%d", len(raw))
|
||||
}
|
||||
if pref != raw[:14] || len(hash) != 64 || hash != HashSecret(raw) {
|
||||
t.Fatalf("hash/prefix mismatch")
|
||||
}
|
||||
if len(AgentScopes) != 9 {
|
||||
t.Fatalf("expected 9 scopes, got %d", len(AgentScopes))
|
||||
}
|
||||
for _, s := range AgentScopes {
|
||||
if strings.Contains(s, "aprobar") {
|
||||
t.Fatalf("approval scope must never exist: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
entrega := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer_aceptadas"}}
|
||||
if !entrega.EsAgenteSoloAceptadas() {
|
||||
t.Fatalf("expected EsAgenteSoloAceptadas=true")
|
||||
}
|
||||
ops := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}}
|
||||
if ops.EsAgenteSoloAceptadas() {
|
||||
t.Fatalf("expected EsAgenteSoloAceptadas=false when cotizaciones:leer present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimiter(t *testing.T) {
|
||||
rl := NewRateLimiter()
|
||||
now := time.Now()
|
||||
for i := 0; i < 3; i++ {
|
||||
res := rl.Check("k1", 3, now.Add(time.Duration(i)*time.Second))
|
||||
if !res.Allowed {
|
||||
t.Fatalf("request %d should be allowed", i)
|
||||
}
|
||||
}
|
||||
blocked := rl.Check("k1", 3, now.Add(4*time.Second))
|
||||
if blocked.Allowed || blocked.Remaining != 0 {
|
||||
t.Fatalf("4th request should be blocked: %+v", blocked)
|
||||
}
|
||||
afterWindow := rl.Check("k1", 3, now.Add(65*time.Second))
|
||||
if !afterWindow.Allowed {
|
||||
t.Fatalf("request after 60s window should be allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoincideContacto(t *testing.T) {
|
||||
if !CoincideContacto("[email protected]", "[email protected]", "") {
|
||||
t.Fatal("case-insensitive email should match")
|
||||
}
|
||||
if !CoincideContacto("+52 1 55 1234-5678", "", "5512345678") {
|
||||
t.Fatal("last 10 phone digits should match")
|
||||
}
|
||||
if CoincideContacto("[email protected]", "[email protected]", "5512345678") {
|
||||
t.Fatal("mismatched contact should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJWTSignAndVerify(t *testing.T) {
|
||||
svc := NewService("super-secret-test-key", false, nil)
|
||||
tok, err := svc.SignSession(SessionPayload{
|
||||
UserID: "u1", Email: "[email protected]", Name: "Admin", Role: "admin",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sign failed: %v", err)
|
||||
}
|
||||
got, err := svc.VerifySession(tok)
|
||||
if err != nil || got.UserID != "u1" || got.Role != "admin" {
|
||||
t.Fatalf("verify failed: %+v, err=%v", got, err)
|
||||
}
|
||||
}
|
||||
+1131
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,399 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func runCLI(t *testing.T, args []string, stdin string) (int, string, string) {
|
||||
t.Helper()
|
||||
var stdout, stderr bytes.Buffer
|
||||
code := runWithIO(args, strings.NewReader(stdin), &stdout, &stderr)
|
||||
return code, stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
func TestEsquemaAndSchemaAlias(t *testing.T) {
|
||||
for _, cmd := range []string{"esquema", "schema"} {
|
||||
code, stdout, stderr := runCLI(t, []string{cmd}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("%s: expected exit 0, got %d (stderr=%s)", cmd, code, stderr)
|
||||
}
|
||||
if stderr != "" {
|
||||
t.Fatalf("%s: expected empty stderr, got %s", cmd, stderr)
|
||||
}
|
||||
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &doc); err != nil {
|
||||
t.Fatalf("%s: invalid JSON output: %v", cmd, err)
|
||||
}
|
||||
if doc["nombre"] != "cotizador" || doc["version"] != Version {
|
||||
t.Errorf("%s: unexpected nombre/version: %v / %v", cmd, doc["nombre"], doc["version"])
|
||||
}
|
||||
|
||||
cmds, ok := doc["comandos"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: comandos missing or not array", cmd)
|
||||
}
|
||||
if len(cmds) != 30 {
|
||||
t.Fatalf("%s: expected 30 commands in esquema, got %d", cmd, len(cmds))
|
||||
}
|
||||
|
||||
// Verify all expected command names exist
|
||||
names := make(map[string]bool)
|
||||
for _, item := range cmds {
|
||||
m := item.(map[string]any)
|
||||
names[m["comando"].(string)] = true
|
||||
}
|
||||
required := []string{
|
||||
"login", "logout", "whoami",
|
||||
"servicios listar", "servicios ver", "servicios crear", "servicios editar",
|
||||
"servicios archivar", "servicios activar", "servicios eliminar",
|
||||
"categorias listar", "categorias crear",
|
||||
"paquetes listar", "paquetes ver",
|
||||
"clientes listar", "clientes crear", "clientes editar",
|
||||
"cotizaciones listar", "cotizaciones ver", "cotizaciones crear",
|
||||
"cotizaciones estado", "cotizaciones pdf", "cotizaciones excel", "cotizaciones eliminar",
|
||||
"horas listar", "horas registrar",
|
||||
"api", "esquema", "ayuda", "version",
|
||||
}
|
||||
for _, r := range required {
|
||||
if !names[r] {
|
||||
t.Errorf("%s: missing command %q in esquema", cmd, r)
|
||||
}
|
||||
}
|
||||
|
||||
codigos, ok := doc["codigosSalida"].(map[string]any)
|
||||
if !ok || len(codigos) != 8 {
|
||||
t.Errorf("%s: expected 8 codigosSalida (0..7), got %v", cmd, codigos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionAndHelp(t *testing.T) {
|
||||
code, stdout, _ := runCLI(t, []string{"--version", "--compacto"}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("expected 0, got %d", code)
|
||||
}
|
||||
if strings.TrimSpace(stdout) != `{"version":"1.0.0"}` {
|
||||
t.Fatalf("unexpected compact version output: %q", stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "FLAGS GLOBALES") {
|
||||
t.Fatalf("empty args should print general help, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{"servicios", "crear", "-h"}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "POST /api/catalogo") {
|
||||
t.Fatalf("-h should print command help, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
|
||||
code, stdout, _ = runCLI(t, []string{"ayuda", "cotizaciones", "crear"}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "POST /api/cotizaciones") {
|
||||
t.Fatalf("ayuda <cmd> failed, got code=%d stdout=%q", code, stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagParsingAndUnknownFlags(t *testing.T) {
|
||||
// Unknown flag on valid command -> ExitUso (2) + JSON stderr
|
||||
code, stdout, stderr := runCLI(t, []string{"servicios", "listar", "--bandera-invalida", "123"}, "")
|
||||
if code != ExitUso {
|
||||
t.Fatalf("expected ExitUso (2), got %d", code)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Fatalf("expected empty stdout on error, got %q", stdout)
|
||||
}
|
||||
var errDoc map[string]any
|
||||
if err := json.Unmarshal([]byte(stderr), &errDoc); err != nil {
|
||||
t.Fatalf("expected JSON stderr, got %q: %v", stderr, err)
|
||||
}
|
||||
if errDoc["ok"] != false || int(errDoc["codigo"].(float64)) != ExitUso {
|
||||
t.Fatalf("unexpected error JSON: %+v", errDoc)
|
||||
}
|
||||
|
||||
// Flag belonging to another command -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"categorias", "listar", "--precio", "100"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "--precio") {
|
||||
t.Fatalf("expected ExitUso mentioning --precio, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// Unknown command -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"noexiste"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "Comando desconocido") {
|
||||
t.Fatalf("expected ExitUso for unknown command, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// Invalid --formato -> ExitUso (2)
|
||||
code, _, _ = runCLI(t, []string{"version", "--formato", "xml"}, "")
|
||||
if code != ExitUso {
|
||||
t.Fatalf("expected ExitUso for invalid --formato, got %d", code)
|
||||
}
|
||||
|
||||
// Destructive delete without --confirmar -> ExitUso (2)
|
||||
code, _, stderr = runCLI(t, []string{"servicios", "eliminar", "abc123"}, "")
|
||||
if code != ExitUso || !strings.Contains(stderr, "--confirmar") {
|
||||
t.Fatalf("expected ExitUso requiring --confirmar, got code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
|
||||
// --no-compacto boolean negation
|
||||
pos, flags, err := parsearArgs([]string{"version", "--no-compacto", "--entregable=Uno", "--entregable", "Dos"}, append(flagsGlobales, flagsServicio...))
|
||||
if err != nil {
|
||||
t.Fatalf("parsearArgs failed: %v", err)
|
||||
}
|
||||
if len(pos) != 1 || pos[0] != "version" {
|
||||
t.Fatalf("unexpected positionals: %v", pos)
|
||||
}
|
||||
if !flags.Has("compacto") || flags.Bool("compacto") {
|
||||
t.Fatalf("expected compacto=false")
|
||||
}
|
||||
if got := flags.List("entregable"); len(got) != 2 || got[0] != "Uno" || got[1] != "Dos" {
|
||||
t.Fatalf("expected 2 repeatable entregables, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunWriteCommands(t *testing.T) {
|
||||
// 1. servicios crear --dry-run (with repeatable --entregable and formatted price)
|
||||
code, stdout, stderr := runCLI(t, []string{
|
||||
"servicios", "crear",
|
||||
"--url", "http://example.test",
|
||||
"--nombre", "Auditoria SEO",
|
||||
"--fase", "0",
|
||||
"--tipo-pago", "unico",
|
||||
"--precio", "$6,500",
|
||||
"--entregable", "Reporte PDF",
|
||||
"--entregable", "Sesion 1h",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios crear --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
var dr map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &dr); err != nil {
|
||||
t.Fatalf("invalid dry-run JSON: %v", err)
|
||||
}
|
||||
if dr["dryRun"] != true || dr["metodo"] != "POST" || dr["url"] != "http://example.test/api/catalogo" {
|
||||
t.Fatalf("unexpected dry-run payload: %+v", dr)
|
||||
}
|
||||
cuerpo := dr["cuerpo"].(map[string]any)
|
||||
if cuerpo["nombre"] != "Auditoria SEO" || cuerpo["precioBase"].(float64) != 6500 {
|
||||
t.Fatalf("unexpected dry-run cuerpo: %+v", cuerpo)
|
||||
}
|
||||
|
||||
// 2. cotizaciones crear with --partida-horas and --dry-run
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"cotizaciones", "crear",
|
||||
"--url", "http://example.test",
|
||||
"--cliente", "Ana Ruiz",
|
||||
"--empresa", "Panaderia Sol",
|
||||
"--partida-horas", "Soporte tecnico|10|700",
|
||||
"--sin-iva",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("cotizaciones crear --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &dr); err != nil {
|
||||
t.Fatalf("invalid dry-run JSON: %v", err)
|
||||
}
|
||||
cuerpo = dr["cuerpo"].(map[string]any)
|
||||
if cuerpo["incluirIva"] != false {
|
||||
t.Errorf("expected incluirIva=false, got %v", cuerpo["incluirIva"])
|
||||
}
|
||||
partidas := cuerpo["servicios"].([]any)
|
||||
if len(partidas) != 1 {
|
||||
t.Fatalf("expected 1 partida, got %d", len(partidas))
|
||||
}
|
||||
p0 := partidas[0].(map[string]any)
|
||||
if p0["precio"].(float64) != 7000 || p0["modeloCobro"] != "horas" {
|
||||
t.Errorf("unexpected partida por horas: %+v", p0)
|
||||
}
|
||||
|
||||
// 3. servicios eliminar --dry-run works without --confirmar
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"servicios", "eliminar", "srv-123",
|
||||
"--url", "http://example.test",
|
||||
"--dry-run",
|
||||
}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios eliminar --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"metodo": "DELETE"`) {
|
||||
t.Errorf("expected DELETE in dry-run output: %s", stdout)
|
||||
}
|
||||
|
||||
// 4. api POST with --datos from stdin and --dry-run
|
||||
code, stdout, stderr = runCLI(t, []string{
|
||||
"api", "POST", "api/cobros/recordatorios",
|
||||
"--url", "http://example.test",
|
||||
"--datos", "-",
|
||||
"--dry-run",
|
||||
}, `{"clienteId":"cli-1"}`)
|
||||
if code != ExitOK {
|
||||
t.Fatalf("api POST --datos - --dry-run failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"clienteId": "cli-1"`) || !strings.Contains(stdout, "http://example.test/api/cobros/recordatorios") {
|
||||
t.Errorf("unexpected api dry-run output: %s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLoginAutoReauthAndExitCodes(t *testing.T) {
|
||||
tmpHome := t.TempDir()
|
||||
t.Setenv("COTIZADOR_HOME", tmpHome)
|
||||
t.Setenv("COTIZADOR_TOKEN", "")
|
||||
t.Setenv("COTIZADOR_EMAIL", "")
|
||||
t.Setenv("COTIZADOR_PASSWORD", "")
|
||||
|
||||
var loginCalls atomic.Int32
|
||||
var meCalls atomic.Int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/auth/login":
|
||||
loginCalls.Add(1)
|
||||
var body map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["email"] == "[email protected]" {
|
||||
http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "tok-cli"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "[email protected]", "role": "cliente"}})
|
||||
return
|
||||
}
|
||||
if body["password"] != "secret" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "Credenciales invalidas"})
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "jwt-staff-token"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": body["email"], "name": "Admin", "role": "admin"}})
|
||||
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/auth/me":
|
||||
n := meCalls.Add(1)
|
||||
c, err := r.Cookie("cotizador-session")
|
||||
if err != nil || c.Value != "jwt-staff-token" || n == 2 {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "No autenticado"})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "[email protected]", "role": "admin"}})
|
||||
|
||||
case r.URL.Path == "/api/catalogo" && r.Method == http.MethodGet:
|
||||
_ = json.NewEncoder(w).Encode([]map[string]any{
|
||||
{"id": "s1", "nombre": "SEO Basico", "precioBase": 2900, "extra": map[string]any{"nested": "val"}},
|
||||
{"id": "s2", "nombre": "Google Ads", "precioBase": 4900, "extra": map[string]any{"nested": "val2"}},
|
||||
})
|
||||
|
||||
case r.URL.Path == "/api/test/400":
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "invalido", "detalles": []string{"campo"}})
|
||||
case r.URL.Path == "/api/test/404":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "no existe"})
|
||||
case r.URL.Path == "/api/test/409":
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "duplicado"})
|
||||
case r.URL.Path == "/api/test/500":
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": "boom"})
|
||||
case r.URL.Path == "/api/cotizaciones/cot-1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": "cot-1", "numero": "UJ2605AG001"})
|
||||
case r.URL.Path == "/api/export/pdf/cot-1":
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="UJ2605AG001.pdf"`)
|
||||
_, _ = w.Write([]byte("%PDF-1.4 mock"))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Cliente role rejected on login -> ExitAuth (3)
|
||||
code, _, _ := runCLI(t, []string{"login", "--url", srv.URL, "--email", "[email protected]", "--password", "x"}, "")
|
||||
if code != ExitAuth {
|
||||
t.Fatalf("expected ExitAuth for cliente role, got %d", code)
|
||||
}
|
||||
|
||||
// Staff login via --password-stdin persists sesiones.json
|
||||
code, stdout, stderr := runCLI(t, []string{"login", "--url", srv.URL, "--email", "[email protected]", "--password-stdin"}, "secret\n")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("login failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `"ok": true`) {
|
||||
t.Fatalf("unexpected login stdout: %s", stdout)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmpHome, "sesiones.json")); err != nil {
|
||||
t.Fatalf("expected sesiones.json to be written: %v", err)
|
||||
}
|
||||
|
||||
// whoami uses saved cookie (meCalls == 1)
|
||||
code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, "[email protected]") {
|
||||
t.Fatalf("whoami failed: code=%d stdout=%s stderr=%s", code, stdout, stderr)
|
||||
}
|
||||
|
||||
// Auto-reauth on 401 when COTIZADOR_EMAIL/PASSWORD are set (meCalls == 2 returns 401, triggers login, retry meCalls == 3 succeeds)
|
||||
t.Setenv("COTIZADOR_EMAIL", "[email protected]")
|
||||
t.Setenv("COTIZADOR_PASSWORD", "secret")
|
||||
beforeLogins := loginCalls.Load()
|
||||
code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("auto-reauth whoami failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if loginCalls.Load() != beforeLogins+1 {
|
||||
t.Fatalf("expected 1 auto-reauth login call, got delta %d", loginCalls.Load()-beforeLogins)
|
||||
}
|
||||
|
||||
// --campos + --formato tabla
|
||||
code, stdout, stderr = runCLI(t, []string{"servicios", "listar", "--url", srv.URL, "--campos", "id,nombre,extra.nested", "--formato", "tabla"}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("servicios listar tabla failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, "SEO Basico") || !strings.Contains(stdout, "extra.nested") || !strings.Contains(stdout, "val2") {
|
||||
t.Fatalf("unexpected table output:\n%s", stdout)
|
||||
}
|
||||
|
||||
// Status-to-exit-code mapping
|
||||
cases := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"/api/test/400", ExitValidacion},
|
||||
{"/api/test/404", ExitNoEncontrado},
|
||||
{"/api/test/409", ExitConflicto},
|
||||
{"/api/test/500", ExitError},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
code, _, _ = runCLI(t, []string{"api", "GET", tc.path, "--url", srv.URL}, "")
|
||||
if code != tc.want {
|
||||
t.Errorf("%s: expected exit %d, got %d", tc.path, tc.want, code)
|
||||
}
|
||||
}
|
||||
|
||||
// Binary PDF download
|
||||
outPDF := filepath.Join(tmpHome, "out.pdf")
|
||||
code, stdout, stderr = runCLI(t, []string{"cotizaciones", "pdf", "cot-1", "--url", srv.URL, "--salida", outPDF}, "")
|
||||
if code != ExitOK {
|
||||
t.Fatalf("cotizaciones pdf failed: code=%d stderr=%s", code, stderr)
|
||||
}
|
||||
b, err := os.ReadFile(outPDF)
|
||||
if err != nil || string(b) != "%PDF-1.4 mock" {
|
||||
t.Fatalf("downloaded PDF mismatch: err=%v content=%q", err, string(b))
|
||||
}
|
||||
|
||||
// Logout removes saved session
|
||||
code, stdout, _ = runCLI(t, []string{"logout", "--url", srv.URL}, "")
|
||||
if code != ExitOK || !strings.Contains(stdout, `"sesionBorrada": true`) {
|
||||
t.Fatalf("logout failed: code=%d stdout=%s", code, stdout)
|
||||
}
|
||||
|
||||
// Network error -> ExitRed (7)
|
||||
code, _, stderr = runCLI(t, []string{"whoami", "--url", "http://127.0.0.1:1"}, "")
|
||||
if code != ExitRed {
|
||||
t.Fatalf("expected ExitRed (7) on unreachable port, got %d (stderr=%s)", code, stderr)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,145 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string
|
||||
Env string
|
||||
|
||||
// PostgreSQL (individual params matching docker-compose & existing .env)
|
||||
DBHost string
|
||||
DBPort int
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBName string
|
||||
|
||||
// Auth
|
||||
JWTSecret string
|
||||
|
||||
// Public URL (used in emails & push links; runtime env)
|
||||
AppURL string
|
||||
|
||||
// Seed
|
||||
RunSeed bool
|
||||
SeedAdminEmail string
|
||||
SeedAdminPassword string
|
||||
SeedAdminName string
|
||||
SeedAsesorEmail string
|
||||
SeedAsesorPass string
|
||||
SeedAsesorName string
|
||||
|
||||
// MiniMax AI (Anthropic-compatible endpoint)
|
||||
MinimaxAPIKey string
|
||||
MinimaxBaseURL string
|
||||
MinimaxModel string
|
||||
|
||||
// Web Push (VAPID)
|
||||
VAPIDPublicKey string
|
||||
VAPIDPrivateKey string
|
||||
VAPIDSubject string
|
||||
|
||||
// SMTP
|
||||
SMTPHost string
|
||||
SMTPPort int
|
||||
SMTPUser string
|
||||
SMTPPass string
|
||||
SMTPFrom string
|
||||
SMTPFromName string
|
||||
|
||||
// Cobros & Uploads
|
||||
CobrosRecordatorioDias int
|
||||
UploadDir string
|
||||
|
||||
// Notifications & Webhooks
|
||||
AdminNotifyEmail string
|
||||
WebhookN8NURL string
|
||||
WebhookN8NSecret string
|
||||
WebhookWhatsAppSendURL string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
_ = godotenv.Load()
|
||||
|
||||
dbName := firstNonEmpty(os.Getenv("DB_DATABASE"), os.Getenv("DB_NAME"), "cotizador_e3")
|
||||
dbPort := parseIntDefault(os.Getenv("DB_PORT"), 5432)
|
||||
smtpPort := parseIntDefault(os.Getenv("SMTP_PORT"), 587)
|
||||
recDias := parseIntDefault(os.Getenv("COBROS_RECORDATORIO_DIAS"), 3)
|
||||
|
||||
cfg := &Config{
|
||||
Port: firstNonEmpty(os.Getenv("PORT"), "3000"),
|
||||
Env: firstNonEmpty(os.Getenv("NODE_ENV"), os.Getenv("APP_ENV"), "production"),
|
||||
DBHost: firstNonEmpty(os.Getenv("DB_HOST"), "localhost"),
|
||||
DBPort: dbPort,
|
||||
DBUser: firstNonEmpty(os.Getenv("DB_USER"), "postgres"),
|
||||
DBPassword: firstNonEmpty(os.Getenv("DB_PASSWORD"), "postgres"),
|
||||
DBName: dbName,
|
||||
JWTSecret: strings.TrimSpace(os.Getenv("JWT_SECRET")),
|
||||
AppURL: strings.TrimRight(firstNonEmpty(os.Getenv("APP_URL"), "http://localhost:3000"), "/"),
|
||||
RunSeed: strings.EqualFold(strings.TrimSpace(os.Getenv("RUN_SEED")), "true"),
|
||||
SeedAdminEmail: firstNonEmpty(os.Getenv("SEED_ADMIN_EMAIL"), "[email protected]"),
|
||||
SeedAdminPassword: os.Getenv("SEED_ADMIN_PASSWORD"),
|
||||
SeedAdminName: firstNonEmpty(os.Getenv("SEED_ADMIN_NAME"), "Administrador"),
|
||||
SeedAsesorEmail: strings.TrimSpace(os.Getenv("SEED_ASESOR_EMAIL")),
|
||||
SeedAsesorPass: os.Getenv("SEED_ASESOR_PASSWORD"),
|
||||
SeedAsesorName: firstNonEmpty(os.Getenv("SEED_ASESOR_NAME"), "Asesor"),
|
||||
MinimaxAPIKey: strings.TrimSpace(os.Getenv("MINIMAX_API_KEY")),
|
||||
MinimaxBaseURL: strings.TrimRight(firstNonEmpty(os.Getenv("MINIMAX_BASE_URL"), "https://api.minimax.io/anthropic"), "/"),
|
||||
MinimaxModel: firstNonEmpty(os.Getenv("MINIMAX_MODEL"), "MiniMax-M3"),
|
||||
VAPIDPublicKey: strings.TrimSpace(os.Getenv("VAPID_PUBLIC_KEY")),
|
||||
VAPIDPrivateKey: strings.TrimSpace(os.Getenv("VAPID_PRIVATE_KEY")),
|
||||
VAPIDSubject: firstNonEmpty(os.Getenv("VAPID_SUBJECT"), "mailto:[email protected]"),
|
||||
SMTPHost: strings.TrimSpace(os.Getenv("SMTP_HOST")),
|
||||
SMTPPort: smtpPort,
|
||||
SMTPUser: strings.TrimSpace(os.Getenv("SMTP_USER")),
|
||||
SMTPPass: os.Getenv("SMTP_PASS"),
|
||||
SMTPFrom: firstNonEmpty(os.Getenv("SMTP_FROM"), os.Getenv("SMTP_USER")),
|
||||
SMTPFromName: firstNonEmpty(os.Getenv("SMTP_FROM_NAME"), "Uriel Jareth Consulting"),
|
||||
CobrosRecordatorioDias: recDias,
|
||||
UploadDir: firstNonEmpty(os.Getenv("UPLOAD_DIR"), "./uploads"),
|
||||
AdminNotifyEmail: strings.TrimSpace(os.Getenv("ADMIN_NOTIFY_EMAIL")),
|
||||
WebhookN8NURL: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_URL")),
|
||||
WebhookN8NSecret: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_SECRET")),
|
||||
WebhookWhatsAppSendURL: strings.TrimSpace(os.Getenv("WEBHOOK_WHATSAPP_SEND_URL")),
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) RequireJWTSecret() error {
|
||||
if c.JWTSecret == "" {
|
||||
return fmt.Errorf("JWT_SECRET es obligatorio y no esta configurado")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) IsProduction() bool {
|
||||
return strings.EqualFold(c.Env, "production")
|
||||
}
|
||||
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseIntDefault(s string, def int) int {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
var idCounter uint64
|
||||
|
||||
// NewID generates a URL-safe, sortable, collision-resistant CUID-like identifier
|
||||
// (e.g. "c" + base36 timestamp + counter + random hex, 25 chars).
|
||||
func NewID() string {
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 36)
|
||||
cnt := strconv.FormatUint(atomic.AddUint64(&idCounter, 1)%1679616, 36)
|
||||
var b [8]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return "c" + ts + cnt + hex.EncodeToString(b[:])[:12]
|
||||
}
|
||||
|
||||
// Connect opens a pgxpool using individual connection parameters (matching the
|
||||
// existing Docker/Coolify environment without SCRAM URL-encoding issues).
|
||||
func Connect(ctx context.Context, cfg *config.Config) (*pgxpool.Pool, error) {
|
||||
poolCfg, err := pgxpool.ParseConfig("")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg.ConnConfig.Host = cfg.DBHost
|
||||
poolCfg.ConnConfig.Port = uint16(cfg.DBPort)
|
||||
poolCfg.ConnConfig.User = cfg.DBUser
|
||||
poolCfg.ConnConfig.Password = cfg.DBPassword
|
||||
poolCfg.ConnConfig.Database = cfg.DBName
|
||||
poolCfg.MaxConns = 20
|
||||
poolCfg.MinConns = 2
|
||||
poolCfg.MaxConnLifetime = 30 * time.Minute
|
||||
poolCfg.MaxConnIdleTime = 5 * time.Minute
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error conectando a PostgreSQL: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("error haciendo ping a PostgreSQL (%s:%d/%s): %w", cfg.DBHost, cfg.DBPort, cfg.DBName, err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Migrate runs embedded idempotent SQL migrations and tracks applied files in `_go_migrations`.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
_, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS "_go_migrations" (
|
||||
"name" TEXT PRIMARY KEY,
|
||||
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creando tabla _go_migrations: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error leyendo migraciones embebidas: %w", err)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
var exists bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "_go_migrations" WHERE "name" = $1)`, name).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("error verificando migracion %s: %w", name, err)
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
|
||||
sqlBytes, err := migrationsFS.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error leyendo %s: %w", name, err)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("error ejecutando migracion %s: %w", name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO "_go_migrations" ("name") VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("error registrando migracion %s: %w", name, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
-- Cotizador — Uriel Jareth Consulting
|
||||
-- Consolidated idempotent PostgreSQL schema matching Prisma's exact 25-table schema.
|
||||
-- Safe to run on both an empty database and an existing production database with live data.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Cliente" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"empresa" TEXT,
|
||||
"puesto" TEXT,
|
||||
"email" TEXT,
|
||||
"telefono" TEXT,
|
||||
"rfc" TEXT,
|
||||
"archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"archivadoAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Cliente_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"password" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'asesor',
|
||||
"clienteId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Cotizacion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"numero" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"vigencia" TIMESTAMP(3) NOT NULL,
|
||||
"moneda" TEXT NOT NULL DEFAULT 'MXN',
|
||||
"tipoCambio" TEXT NOT NULL DEFAULT 'NA',
|
||||
"proyecto" TEXT NOT NULL DEFAULT 'MKT Digital',
|
||||
"esquemaPago" TEXT NOT NULL DEFAULT 'Pago Unico/Mensual',
|
||||
"estado" TEXT NOT NULL DEFAULT 'borrador',
|
||||
"incluirBonos" BOOLEAN NOT NULL DEFAULT false,
|
||||
"incluirFinanciamiento" BOOLEAN NOT NULL DEFAULT false,
|
||||
"incluirIva" BOOLEAN NOT NULL DEFAULT true,
|
||||
"esDoble" BOOLEAN NOT NULL DEFAULT false,
|
||||
"opcionesMetadata" JSONB,
|
||||
"observaciones" TEXT,
|
||||
"observacionesInternas" TEXT,
|
||||
"clienteId" TEXT NOT NULL,
|
||||
"asesorId" TEXT NOT NULL,
|
||||
"aprobadaPorId" TEXT,
|
||||
"aprobadaAt" TIMESTAMP(3),
|
||||
"aprobacionMetodo" TEXT,
|
||||
"enviadaAt" TIMESTAMP(3),
|
||||
"enviadaPor" TEXT,
|
||||
"enviadaCanal" TEXT,
|
||||
"enviadaDestino" TEXT,
|
||||
"aceptadaAt" TIMESTAMP(3),
|
||||
"rechazadaAt" TIMESTAMP(3),
|
||||
"vencidaAt" TIMESTAMP(3),
|
||||
"creadaPorAgente" TEXT,
|
||||
"archivado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"archivadoAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Cotizacion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Categoria" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"color" TEXT NOT NULL DEFAULT '#6b7280',
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Categoria_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Paquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Paquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "FasePaquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"paqueteId" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "FasePaquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioCatalogo" (
|
||||
"id" TEXT NOT NULL,
|
||||
"nombre" TEXT NOT NULL,
|
||||
"descripcion" TEXT,
|
||||
"fase" INTEGER NOT NULL DEFAULT 1,
|
||||
"tipoPago" TEXT NOT NULL DEFAULT 'unico',
|
||||
"precioBase" DOUBLE PRECISION NOT NULL,
|
||||
"tiempoEntrega" TEXT NOT NULL DEFAULT '4 - 10 dias',
|
||||
"entregablesDefault" JSONB NOT NULL DEFAULT '[]',
|
||||
"categoriaId" TEXT,
|
||||
"variante" TEXT,
|
||||
"nivel" TEXT,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"soloAdmin" BOOLEAN NOT NULL DEFAULT false,
|
||||
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioCatalogo_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioPaquete" (
|
||||
"id" TEXT NOT NULL,
|
||||
"servicioCatalogoId" TEXT NOT NULL,
|
||||
"fasePaqueteId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioPaquete_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ServicioCotizado" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"servicioCatalogoId" TEXT,
|
||||
"nombre" TEXT,
|
||||
"esPersonalizado" BOOLEAN NOT NULL DEFAULT false,
|
||||
"horas" DOUBLE PRECISION,
|
||||
"tarifaHora" DOUBLE PRECISION,
|
||||
"modeloCobro" TEXT NOT NULL DEFAULT 'fijo',
|
||||
"montoMinimo" DOUBLE PRECISION,
|
||||
"horasIncluidas" DOUBLE PRECISION,
|
||||
"opcion" TEXT,
|
||||
"fase" INTEGER NOT NULL,
|
||||
"tipoPago" TEXT NOT NULL,
|
||||
"precio" DOUBLE PRECISION NOT NULL,
|
||||
"tiempoEntrega" TEXT NOT NULL,
|
||||
"entregables" JSONB NOT NULL DEFAULT '[]',
|
||||
"beneficios" JSONB NOT NULL DEFAULT '[]',
|
||||
"notas" TEXT,
|
||||
"seleccionado" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ServicioCotizado_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PlanBucefaloCotizacion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"nivel" TEXT NOT NULL DEFAULT 'basico',
|
||||
"precio" DOUBLE PRECISION NOT NULL,
|
||||
"seleccionado" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PlanBucefaloCotizacion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "RegistroHoras" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL,
|
||||
"horaInicio" TEXT NOT NULL,
|
||||
"horaFin" TEXT NOT NULL,
|
||||
"horas" DOUBLE PRECISION NOT NULL,
|
||||
"tarifaHora" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"descripcion" TEXT NOT NULL,
|
||||
"estadoPago" TEXT NOT NULL DEFAULT 'por_pagar',
|
||||
"fechaPago" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "RegistroHoras_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PropuestaIA" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT NOT NULL,
|
||||
"estado" TEXT NOT NULL DEFAULT 'borrador',
|
||||
"contenidoIA" JSONB NOT NULL,
|
||||
"contenidoEditado" JSONB,
|
||||
"transcripcion" TEXT,
|
||||
"traza" JSONB,
|
||||
"avisos" JSONB NOT NULL DEFAULT '[]',
|
||||
"modelo" TEXT NOT NULL,
|
||||
"aprobadaPor" TEXT,
|
||||
"aprobadaAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PropuestaIA_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Configuracion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"clave" TEXT NOT NULL,
|
||||
"valor" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Configuracion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "Bono" (
|
||||
"id" TEXT NOT NULL,
|
||||
"numero" INTEGER NOT NULL,
|
||||
"titulo" TEXT NOT NULL,
|
||||
"descripcion" TEXT NOT NULL,
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
CONSTRAINT "Bono_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "FinanciamientoPlan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"meses" INTEGER NOT NULL,
|
||||
"tasa" DOUBLE PRECISION NOT NULL,
|
||||
"comision" DOUBLE PRECISION NOT NULL,
|
||||
"montoMinimo" DOUBLE PRECISION NOT NULL,
|
||||
"iva" DOUBLE PRECISION NOT NULL DEFAULT 0.16,
|
||||
CONSTRAINT "FinanciamientoPlan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ProgramaPago" (
|
||||
"id" TEXT NOT NULL,
|
||||
"clienteId" TEXT NOT NULL,
|
||||
"cotizacionId" TEXT,
|
||||
"concepto" TEXT NOT NULL,
|
||||
"monto" DOUBLE PRECISION NOT NULL,
|
||||
"moneda" TEXT NOT NULL DEFAULT 'MXN',
|
||||
"frecuencia" TEXT NOT NULL DEFAULT 'semanal',
|
||||
"diaSemana" INTEGER,
|
||||
"diaMes" INTEGER,
|
||||
"fechaInicio" TIMESTAMP(3) NOT NULL,
|
||||
"fechaFin" TIMESTAMP(3),
|
||||
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PagoRecurrente" (
|
||||
"id" TEXT NOT NULL,
|
||||
"programaId" TEXT NOT NULL,
|
||||
"fecha" TIMESTAMP(3) NOT NULL,
|
||||
"monto" DOUBLE PRECISION NOT NULL,
|
||||
"estado" TEXT NOT NULL DEFAULT 'pendiente',
|
||||
"verificadoAt" TIMESTAMP(3),
|
||||
"rechazadoAt" TIMESTAMP(3),
|
||||
"rechazoMotivo" TEXT,
|
||||
"ultimoRecordatorioAt" TIMESTAMP(3),
|
||||
"recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0,
|
||||
"vencidoNotificadoAt" TIMESTAMP(3),
|
||||
"nota" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "ComprobantePago" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pagoId" TEXT NOT NULL,
|
||||
"archivoRuta" TEXT NOT NULL,
|
||||
"archivoNombre" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"tamano" INTEGER NOT NULL,
|
||||
"subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "SuscripcionPush" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"endpoint" TEXT NOT NULL,
|
||||
"p256dh" TEXT NOT NULL,
|
||||
"auth" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
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 DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
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 DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
-- Ensure additive columns exist on older production DBs
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "puesto" TEXT;
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "observacionesInternas" TEXT;
|
||||
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;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3);
|
||||
|
||||
ALTER TABLE "ServicioCatalogo" ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "ultimoRecordatorioAt" TIMESTAMP(3);
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3);
|
||||
ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "nota" TEXT;
|
||||
|
||||
-- Unique & regular indexes
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "User_email_key" ON "User"("email");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "User_clienteId_key" ON "User"("clienteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "Cliente_nombre_empresa_idx" ON "Cliente"("nombre", "empresa");
|
||||
CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Cotizacion_numero_key" ON "Cotizacion"("numero");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_clienteId_idx" ON "Cotizacion"("clienteId");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_asesorId_idx" ON "Cotizacion"("asesorId");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_estado_idx" ON "Cotizacion"("estado");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado");
|
||||
CREATE INDEX IF NOT EXISTS "Cotizacion_createdAt_idx" ON "Cotizacion"("createdAt");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Categoria_nombre_key" ON "Categoria"("nombre");
|
||||
CREATE INDEX IF NOT EXISTS "FasePaquete_paqueteId_idx" ON "FasePaquete"("paqueteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCatalogo_categoriaId_idx" ON "ServicioCatalogo"("categoriaId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCatalogo_activo_fase_orden_idx" ON "ServicioCatalogo"("activo", "fase", "orden");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ServicioPaquete_servicioCatalogoId_fasePaqueteId_key" ON "ServicioPaquete"("servicioCatalogoId", "fasePaqueteId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioPaquete_fasePaqueteId_idx" ON "ServicioPaquete"("fasePaqueteId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCotizado_cotizacionId_idx" ON "ServicioCotizado"("cotizacionId");
|
||||
CREATE INDEX IF NOT EXISTS "ServicioCotizado_servicioCatalogoId_idx" ON "ServicioCotizado"("servicioCatalogoId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "PlanBucefaloCotizacion_cotizacionId_key" ON "PlanBucefaloCotizacion"("cotizacionId");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_cotizacionId_idx" ON "RegistroHoras"("cotizacionId");
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_fecha_idx" ON "RegistroHoras"("fecha");
|
||||
CREATE INDEX IF NOT EXISTS "RegistroHoras_estadoPago_idx" ON "RegistroHoras"("estadoPago");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "PropuestaIA_cotizacionId_idx" ON "PropuestaIA"("cotizacionId");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "Configuracion_clave_key" ON "Configuracion"("clave");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "FinanciamientoPlan_meses_key" ON "FinanciamientoPlan"("meses");
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId");
|
||||
CREATE INDEX IF NOT EXISTS "ProgramaPago_activo_idx" ON "ProgramaPago"("activo");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha");
|
||||
CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt");
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint");
|
||||
CREATE INDEX IF NOT EXISTS "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId");
|
||||
|
||||
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");
|
||||
|
||||
-- Foreign keys (idempotent)
|
||||
DO $$ BEGIN ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_asesorId_fkey" FOREIGN KEY ("asesorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "FasePaquete" ADD CONSTRAINT "FasePaquete_paqueteId_fkey" FOREIGN KEY ("paqueteId") REFERENCES "Paquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioCatalogo" ADD CONSTRAINT "ServicioCatalogo_categoriaId_fkey" FOREIGN KEY ("categoriaId") REFERENCES "Categoria"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_fasePaqueteId_fkey" FOREIGN KEY ("fasePaqueteId") REFERENCES "FasePaquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_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 "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "PlanBucefaloCotizacion" ADD CONSTRAINT "PlanBucefaloCotizacion_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 "RegistroHoras" ADD CONSTRAINT "RegistroHoras_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 "PropuestaIA" ADD CONSTRAINT "PropuestaIA_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 "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
DO $$ BEGIN ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
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,146 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ActorInfo struct {
|
||||
Type string // "user" | "agent" | "enlace_firmado"
|
||||
Role string // "admin" | "asesor" | "cliente"
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
type ValidarTransicionInput struct {
|
||||
Actual string
|
||||
Nuevo string
|
||||
Actor ActorInfo
|
||||
ViaEndpoint string // "aprobar" | "enlace_firmado" | "enviar" | "estado" | "put"
|
||||
AprobadaAt *time.Time
|
||||
}
|
||||
|
||||
type ValidarTransicionResult struct {
|
||||
OK bool
|
||||
Status int
|
||||
Error string
|
||||
}
|
||||
|
||||
func ValidarTransicionEstado(in ValidarTransicionInput) ValidarTransicionResult {
|
||||
if !EsEstadoCotizacionValido(in.Nuevo) {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 400,
|
||||
Error: fmt.Sprintf("Estado invalido. Permitidos: %s", strings.Join(EstadosCotizacion, ", ")),
|
||||
}
|
||||
}
|
||||
|
||||
if in.Actual == in.Nuevo {
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
esAdminHumano := in.Actor.Type == "user" && in.Actor.Role == "admin"
|
||||
esStaffHumano := in.Actor.Type == "user" && in.Actor.Role != "cliente"
|
||||
esEnlaceFirmado := in.Actor.Type == "enlace_firmado" && in.ViaEndpoint == "enlace_firmado"
|
||||
esAgente := in.Actor.Type == "agent"
|
||||
|
||||
// REGLA DE HIERRO 1: Nadie salvo admin humano o enlace firmado de un solo uso puede aprobar.
|
||||
if in.Nuevo == "aprobada" {
|
||||
if !esAdminHumano && !esEnlaceFirmado {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo un administrador humano o el enlace firmado puede aprobar una cotizacion",
|
||||
}
|
||||
}
|
||||
if in.Actual != "borrador" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Solo se puede aprobar una cotizacion en borrador (estado actual: %s)", in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// REGLA DE HIERRO 2: Nadie puede pasar a "enviada" sin estar previamente aprobada (con aprobadaAt).
|
||||
if in.Nuevo == "enviada" {
|
||||
if esAgente && in.ViaEndpoint != "enviar" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Los agentes solo pueden enviar cotizaciones mediante POST /api/cotizaciones/:id/enviar",
|
||||
}
|
||||
}
|
||||
if in.Actual != "aprobada" || in.AprobadaAt == nil {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||
}
|
||||
}
|
||||
if esAgente {
|
||||
if !slices.Contains(in.Actor.Scopes, "cotizaciones:enviar") {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "El agente no tiene el alcance cotizaciones:enviar",
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
if !esStaffHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "No autorizado para enviar cotizaciones",
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// Reabrir a borrador: solo admin humano desde aprobada, rechazada o vencida.
|
||||
if in.Nuevo == "borrador" {
|
||||
if !esAdminHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo un administrador humano puede regresar una cotizacion a borrador",
|
||||
}
|
||||
}
|
||||
if in.Actual != "aprobada" && in.Actual != "rechazada" && in.Actual != "vencida" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("No se puede regresar a borrador desde el estado %s", in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
// Estados de cierre post-envio: aceptada | rechazada | vencida
|
||||
if in.Nuevo == "aceptada" || in.Nuevo == "rechazada" || in.Nuevo == "vencida" {
|
||||
if !esStaffHumano {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 403,
|
||||
Error: "Solo el equipo humano puede marcar una cotizacion como aceptada, rechazada o vencida",
|
||||
}
|
||||
}
|
||||
if in.Actual != "enviada" {
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Solo se puede pasar a %s desde el estado enviada (estado actual: %s)", in.Nuevo, in.Actual),
|
||||
}
|
||||
}
|
||||
return ValidarTransicionResult{OK: true}
|
||||
}
|
||||
|
||||
return ValidarTransicionResult{
|
||||
OK: false,
|
||||
Status: 409,
|
||||
Error: fmt.Sprintf("Transicion no permitida de %s a %s", in.Actual, in.Nuevo),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
IVARate = 0.16
|
||||
TarifaHoraDefault = 700.0
|
||||
)
|
||||
|
||||
var ModelosCobro = map[string]string{
|
||||
"fijo": "Precio fijo",
|
||||
"horas": "Por horas",
|
||||
"retainer": "Retainer (minimo + adicionales)",
|
||||
"demanda": "Bajo demanda / por hora",
|
||||
}
|
||||
|
||||
var ModelosCobroTiempo = []string{"horas", "retainer", "demanda"}
|
||||
|
||||
var Fases = map[int]string{
|
||||
0: "FASE 0 - Auditoria / Acompanamiento",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
var FasesShort = map[int]string{
|
||||
0: "FASE 0 - Auditoria",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
}
|
||||
|
||||
type PlanBucefaloDef struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Label string `json:"label"`
|
||||
Precio float64 `json:"precio"`
|
||||
}
|
||||
|
||||
var PlanesBucefalo = []PlanBucefaloDef{
|
||||
{Nivel: "basico", Label: "Basico", Precio: 1000},
|
||||
{Nivel: "estandar", Label: "Estandar", Precio: 3500},
|
||||
{Nivel: "premium", Label: "Premium", Precio: 4500},
|
||||
{Nivel: "empresarial", Label: "Empresarial", Precio: 7500},
|
||||
}
|
||||
|
||||
var EstadosCotizacion = []string{"borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"}
|
||||
|
||||
var EstadosPagoHoras = []string{"por_pagar", "pagada"}
|
||||
|
||||
var NivelesServicio = []string{"Emprendedor", "PYME", "Empresario", "Corporativo"}
|
||||
|
||||
type MetaOpcion struct {
|
||||
Titulo string `json:"titulo,omitempty"`
|
||||
Descripcion string `json:"descripcion,omitempty"`
|
||||
NoIncluye string `json:"noIncluye,omitempty"`
|
||||
}
|
||||
|
||||
type ServicioCalc struct {
|
||||
Nombre string
|
||||
ModeloCobro string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
TipoPago string
|
||||
Precio float64
|
||||
Seleccionado bool
|
||||
}
|
||||
|
||||
type TotalesOpcion struct {
|
||||
TotalUnico float64 `json:"totalUnico"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
Horas float64 `json:"horas"`
|
||||
}
|
||||
|
||||
type TotalesCotizacion struct {
|
||||
SubtotalUnico float64 `json:"subtotalUnico"`
|
||||
SubtotalMensual float64 `json:"subtotalMensual"`
|
||||
IVAUnico float64 `json:"ivaUnico"`
|
||||
IVAMensual float64 `json:"ivaMensual"`
|
||||
TotalUnico float64 `json:"totalUnico"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
TotalPrimerAnio float64 `json:"totalPrimerAnio"`
|
||||
IncluyeIVA bool `json:"incluyeIva"`
|
||||
}
|
||||
|
||||
type FinanciamientoInput struct {
|
||||
Monto float64
|
||||
Meses int
|
||||
Tasa float64
|
||||
Comision float64
|
||||
IVA float64
|
||||
}
|
||||
|
||||
type FinanciamientoResult struct {
|
||||
PagoMensual float64 `json:"pagoMensual"`
|
||||
IVAMensual float64 `json:"ivaMensual"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
ComisionTotal float64 `json:"comisionTotal"`
|
||||
GranTotal float64 `json:"granTotal"`
|
||||
}
|
||||
|
||||
type BucketHoras struct {
|
||||
Horas float64 `json:"horas"`
|
||||
Importe float64 `json:"importe"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type ResumenPagoHoras struct {
|
||||
PorPagar BucketHoras `json:"porPagar"`
|
||||
Pagada BucketHoras `json:"pagada"`
|
||||
Total BucketHoras `json:"total"`
|
||||
}
|
||||
|
||||
type RegistroHorasCalc struct {
|
||||
Horas float64
|
||||
TarifaHora float64
|
||||
EstadoPago string
|
||||
}
|
||||
|
||||
type PeriodoAgrupacion struct {
|
||||
Clave string `json:"clave"`
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
}
|
||||
|
||||
func Round2(n float64) float64 {
|
||||
return math.Round(n*100) / 100
|
||||
}
|
||||
|
||||
func CalcularPrecioHoras(horas, tarifaHora float64) float64 {
|
||||
return Round2(horas * tarifaHora)
|
||||
}
|
||||
|
||||
func ConIVA(monto float64, incluirIVA bool) float64 {
|
||||
if incluirIVA {
|
||||
return Round2(monto * (1 + IVARate))
|
||||
}
|
||||
return Round2(monto)
|
||||
}
|
||||
|
||||
func BucefaloPrecio(nivel string) float64 {
|
||||
for _, p := range PlanesBucefalo {
|
||||
if p.Nivel == nivel {
|
||||
return p.Precio
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func EsEstadoCotizacionValido(estado string) bool {
|
||||
for _, e := range EstadosCotizacion {
|
||||
if e == estado {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EsModeloTiempo(modelo string) bool {
|
||||
for _, m := range ModelosCobroTiempo {
|
||||
if m == modelo {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EsCotizacionPorTiempo(servicios []ServicioCalc) bool {
|
||||
for _, s := range servicios {
|
||||
if EsModeloTiempo(s.ModeloCobro) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TarifaHoraSugerida(servicios []ServicioCalc) float64 {
|
||||
for _, s := range servicios {
|
||||
if EsModeloTiempo(s.ModeloCobro) && s.TarifaHora != nil && *s.TarifaHora > 0 {
|
||||
return *s.TarifaHora
|
||||
}
|
||||
}
|
||||
return TarifaHoraDefault
|
||||
}
|
||||
|
||||
func DescribirRetainer(montoMinimo, horasIncluidas, tarifaHora float64) string {
|
||||
partes := []string{fmt.Sprintf("%s/mes", FormatCurrency(montoMinimo))}
|
||||
if horasIncluidas != 0 {
|
||||
partes = append(partes, fmt.Sprintf("incluye %s hr", formatTrimFloat(horasIncluidas)))
|
||||
}
|
||||
if tarifaHora != 0 {
|
||||
partes = append(partes, fmt.Sprintf("adicional %s/hr (se factura aparte)", FormatCurrency(tarifaHora)))
|
||||
}
|
||||
return strings.Join(partes, " · ")
|
||||
}
|
||||
|
||||
func DetalleModelo(s ServicioCalc) string {
|
||||
switch s.ModeloCobro {
|
||||
case "retainer":
|
||||
var mm, hi, th float64
|
||||
if s.MontoMinimo != nil {
|
||||
mm = *s.MontoMinimo
|
||||
}
|
||||
if s.HorasIncluidas != nil {
|
||||
hi = *s.HorasIncluidas
|
||||
}
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return DescribirRetainer(mm, hi, th)
|
||||
case "demanda":
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return fmt.Sprintf("%s/hr · segun consumo", FormatCurrency(th))
|
||||
default:
|
||||
if (s.ModeloCobro == "horas" || s.EsPersonalizado) && s.Horas != nil && *s.Horas != 0 && s.TarifaHora != nil && *s.TarifaHora != 0 {
|
||||
return fmt.Sprintf("%s h x %s/hr", formatTrimFloat(*s.Horas), FormatCurrency(*s.TarifaHora))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func PrecioDisplay(s ServicioCalc) string {
|
||||
if s.ModeloCobro == "demanda" {
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
return fmt.Sprintf("%s/hr", FormatCurrency(th))
|
||||
}
|
||||
return FormatCurrency(s.Precio)
|
||||
}
|
||||
|
||||
func NotaDemanda(servicios []ServicioCalc) string {
|
||||
var partes []string
|
||||
for _, s := range servicios {
|
||||
if s.ModeloCobro == "demanda" {
|
||||
nombre := strings.TrimSpace(s.Nombre)
|
||||
if nombre == "" {
|
||||
nombre = "Servicio"
|
||||
}
|
||||
var th float64
|
||||
if s.TarifaHora != nil {
|
||||
th = *s.TarifaHora
|
||||
}
|
||||
partes = append(partes, fmt.Sprintf("%s a %s/hr", nombre, FormatCurrency(th)))
|
||||
}
|
||||
}
|
||||
if len(partes) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("+ Horas facturadas a fin de mes segun consumo (no incluidas en el total): %s.", strings.Join(partes, ", "))
|
||||
}
|
||||
|
||||
func CalcularTotalesOpcion(servicios []ServicioCalc, opcion string) TotalesOpcion {
|
||||
var totalUnico, totalMensual, horas float64
|
||||
for _, s := range servicios {
|
||||
op := ""
|
||||
if s.Opcion != nil {
|
||||
op = *s.Opcion
|
||||
}
|
||||
if op != "ambas" && op != opcion {
|
||||
continue
|
||||
}
|
||||
switch s.TipoPago {
|
||||
case "unico":
|
||||
totalUnico += s.Precio
|
||||
case "mensual":
|
||||
totalMensual += s.Precio
|
||||
}
|
||||
if s.Horas != nil {
|
||||
horas += *s.Horas
|
||||
}
|
||||
}
|
||||
return TotalesOpcion{
|
||||
TotalUnico: Round2(totalUnico),
|
||||
TotalMensual: Round2(totalMensual),
|
||||
Horas: Round2(horas),
|
||||
}
|
||||
}
|
||||
|
||||
func CalcularTotalesCotizacion(servicios []ServicioCalc, incluirIVA bool) TotalesCotizacion {
|
||||
var sumUnico, sumMensual float64
|
||||
for _, s := range servicios {
|
||||
if !s.Seleccionado {
|
||||
continue
|
||||
}
|
||||
switch s.TipoPago {
|
||||
case "unico":
|
||||
sumUnico += s.Precio
|
||||
case "mensual":
|
||||
sumMensual += s.Precio
|
||||
}
|
||||
}
|
||||
subtotalUnico := Round2(sumUnico)
|
||||
subtotalMensual := Round2(sumMensual)
|
||||
|
||||
var ivaUnico, ivaMensual float64
|
||||
if incluirIVA {
|
||||
ivaUnico = Round2(subtotalUnico * IVARate)
|
||||
ivaMensual = Round2(subtotalMensual * IVARate)
|
||||
}
|
||||
totalUnico := Round2(subtotalUnico + ivaUnico)
|
||||
totalMensual := Round2(subtotalMensual + ivaMensual)
|
||||
|
||||
return TotalesCotizacion{
|
||||
SubtotalUnico: subtotalUnico,
|
||||
SubtotalMensual: subtotalMensual,
|
||||
IVAUnico: ivaUnico,
|
||||
IVAMensual: ivaMensual,
|
||||
TotalUnico: totalUnico,
|
||||
TotalMensual: totalMensual,
|
||||
TotalPrimerAnio: Round2(totalUnico + totalMensual*12),
|
||||
IncluyeIVA: incluirIVA,
|
||||
}
|
||||
}
|
||||
|
||||
func CalcularVigencia(fecha time.Time) time.Time {
|
||||
vigencia := fecha
|
||||
diasHabiles := 0
|
||||
for diasHabiles < 15 {
|
||||
vigencia = vigencia.AddDate(0, 0, 1)
|
||||
wd := vigencia.Weekday()
|
||||
if wd != time.Sunday && wd != time.Saturday {
|
||||
diasHabiles++
|
||||
}
|
||||
}
|
||||
return vigencia
|
||||
}
|
||||
|
||||
func CalcularFinanciamiento(input FinanciamientoInput) FinanciamientoResult {
|
||||
comisionTotal := (input.Monto * input.Comision) / 100.0
|
||||
montoConComision := input.Monto + comisionTotal
|
||||
pagoMensual := montoConComision * (1.0 + input.Tasa) / float64(input.Meses)
|
||||
ivaMensual := pagoMensual * input.IVA
|
||||
totalMensual := pagoMensual + ivaMensual
|
||||
return FinanciamientoResult{
|
||||
PagoMensual: Round2(pagoMensual),
|
||||
IVAMensual: Round2(ivaMensual),
|
||||
TotalMensual: Round2(totalMensual),
|
||||
ComisionTotal: Round2(comisionTotal),
|
||||
GranTotal: Round2(totalMensual * float64(input.Meses)),
|
||||
}
|
||||
}
|
||||
|
||||
func GenerarNumeroCotizacion(asesorIniciales string, secuencia int, now time.Time) string {
|
||||
yy := fmt.Sprintf("%02d", now.Year()%100)
|
||||
mm := fmt.Sprintf("%02d", int(now.Month()))
|
||||
seq := fmt.Sprintf("%03d", secuencia)
|
||||
return fmt.Sprintf("UJ%s%s%s%s", yy, mm, asesorIniciales, seq)
|
||||
}
|
||||
|
||||
var horaRe = regexp.MustCompile(`^(\d{1,2}):(\d{2})$`)
|
||||
|
||||
func CalcularHorasRango(horaInicio, horaFin string) float64 {
|
||||
a := horaRe.FindStringSubmatch(horaInicio)
|
||||
b := horaRe.FindStringSubmatch(horaFin)
|
||||
if a == nil || b == nil {
|
||||
return 0
|
||||
}
|
||||
ah, _ := strconv.Atoi(a[1])
|
||||
am, _ := strconv.Atoi(a[2])
|
||||
bh, _ := strconv.Atoi(b[1])
|
||||
bm, _ := strconv.Atoi(b[2])
|
||||
ini := ah*60 + am
|
||||
fin := bh*60 + bm
|
||||
if fin <= ini {
|
||||
return 0
|
||||
}
|
||||
return Round2(float64(fin-ini) / 60.0)
|
||||
}
|
||||
|
||||
func FechaRegistroDesdeISO(fechaISO string) (time.Time, error) {
|
||||
t, err := time.Parse("2006-01-02", strings.TrimSpace(fechaISO))
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, time.UTC), nil
|
||||
}
|
||||
|
||||
func FormatFechaRegistro(date time.Time) string {
|
||||
u := date.UTC()
|
||||
return fmt.Sprintf("%02d/%02d/%04d", u.Day(), int(u.Month()), u.Year())
|
||||
}
|
||||
|
||||
var mesesLargo = []string{
|
||||
"enero", "febrero", "marzo", "abril", "mayo", "junio",
|
||||
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
|
||||
}
|
||||
|
||||
func lunesDeSemanaUTC(d time.Time) time.Time {
|
||||
u := d.UTC()
|
||||
r := time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC)
|
||||
wd := int(r.Weekday()) // 0 = Sunday
|
||||
offset := 1 - wd
|
||||
if wd == 0 {
|
||||
offset = -6
|
||||
}
|
||||
return r.AddDate(0, 0, offset)
|
||||
}
|
||||
|
||||
func PeriodoAgrupacionDe(fecha time.Time, modo string) PeriodoAgrupacion {
|
||||
u := fecha.UTC()
|
||||
y, m, d := u.Year(), int(u.Month()), u.Day()
|
||||
switch modo {
|
||||
case "mes":
|
||||
return PeriodoAgrupacion{
|
||||
Clave: fmt.Sprintf("%04d-%02d", y, m),
|
||||
Etiqueta: fmt.Sprintf("%s %d", mesesLargo[m-1], y),
|
||||
}
|
||||
case "semana":
|
||||
lunes := lunesDeSemanaUTC(u)
|
||||
domingo := lunes.AddDate(0, 0, 6)
|
||||
clave := fmt.Sprintf("%04d-%02d-%02d", lunes.Year(), int(lunes.Month()), lunes.Day())
|
||||
etiqueta := fmt.Sprintf("Semana %02d/%02d - %02d/%02d", lunes.Day(), int(lunes.Month()), domingo.Day(), int(domingo.Month()))
|
||||
return PeriodoAgrupacion{Clave: clave, Etiqueta: etiqueta}
|
||||
default:
|
||||
return PeriodoAgrupacion{
|
||||
Clave: fmt.Sprintf("%04d-%02d-%02d", y, m, d),
|
||||
Etiqueta: FormatFechaRegistro(u),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func EsPagada(estadoPago string) bool {
|
||||
return estadoPago == "pagada"
|
||||
}
|
||||
|
||||
func CalcularResumenPagoHoras(registros []RegistroHorasCalc) ResumenPagoHoras {
|
||||
var r ResumenPagoHoras
|
||||
for _, x := range registros {
|
||||
importe := x.Horas * x.TarifaHora
|
||||
if EsPagada(x.EstadoPago) {
|
||||
r.Pagada.Horas += x.Horas
|
||||
r.Pagada.Importe += importe
|
||||
r.Pagada.Count++
|
||||
} else {
|
||||
r.PorPagar.Horas += x.Horas
|
||||
r.PorPagar.Importe += importe
|
||||
r.PorPagar.Count++
|
||||
}
|
||||
r.Total.Horas += x.Horas
|
||||
r.Total.Importe += importe
|
||||
r.Total.Count++
|
||||
}
|
||||
r.PorPagar.Horas = Round2(r.PorPagar.Horas)
|
||||
r.PorPagar.Importe = Round2(r.PorPagar.Importe)
|
||||
r.Pagada.Horas = Round2(r.Pagada.Horas)
|
||||
r.Pagada.Importe = Round2(r.Pagada.Importe)
|
||||
r.Total.Horas = Round2(r.Total.Horas)
|
||||
r.Total.Importe = Round2(r.Total.Importe)
|
||||
return r
|
||||
}
|
||||
|
||||
var sanitizeFileRe = regexp.MustCompile(`[^\w\s.\-]`)
|
||||
var multiSpaceRe = regexp.MustCompile(`\s+`)
|
||||
|
||||
func SanitizeFilename(name string) string {
|
||||
s := sanitizeFileRe.ReplaceAllString(name, "")
|
||||
s = multiSpaceRe.ReplaceAllString(s, " ")
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// FormatCurrency formats MXN like Intl.NumberFormat("es-MX", {style:"currency", currency:"MXN", minFrac:0, maxFrac:2}).
|
||||
func FormatCurrency(amount float64) string {
|
||||
return FormatMonto(amount, "MXN")
|
||||
}
|
||||
|
||||
// FormatMonto formats currency matching es-MX formatting: "$4,500", "$4,500.50", "US$25" / "USD 25".
|
||||
func FormatMonto(amount float64, moneda string) string {
|
||||
neg := amount < 0
|
||||
abs := math.Abs(amount)
|
||||
rounded := Round2(abs)
|
||||
intPart := int64(rounded)
|
||||
fracPart := int(math.Round((rounded - float64(intPart)) * 100))
|
||||
if fracPart == 100 {
|
||||
intPart++
|
||||
fracPart = 0
|
||||
}
|
||||
|
||||
intStr := addCommas(intPart)
|
||||
numStr := intStr
|
||||
if fracPart > 0 {
|
||||
numStr = fmt.Sprintf("%s.%02d", intStr, fracPart)
|
||||
}
|
||||
|
||||
prefix := "$"
|
||||
if moneda != "" && !strings.EqualFold(moneda, "MXN") {
|
||||
prefix = strings.ToUpper(moneda) + " "
|
||||
}
|
||||
if neg {
|
||||
return "-" + prefix + numStr
|
||||
}
|
||||
return prefix + numStr
|
||||
}
|
||||
|
||||
func FormatDateLongMX(d time.Time) string {
|
||||
return fmt.Sprintf("%02d de %s de %d", d.Day(), mesesLargo[int(d.Month())-1], d.Year())
|
||||
}
|
||||
|
||||
func FormatDateShort(d time.Time) string {
|
||||
return fmt.Sprintf("%02d/%02d/%04d", d.Day(), int(d.Month()), d.Year())
|
||||
}
|
||||
|
||||
func addCommas(n int64) string {
|
||||
s := strconv.FormatInt(n, 10)
|
||||
if len(s) <= 3 {
|
||||
return s
|
||||
}
|
||||
var out strings.Builder
|
||||
rem := len(s) % 3
|
||||
if rem > 0 {
|
||||
out.WriteString(s[:rem])
|
||||
if len(s) > rem {
|
||||
out.WriteByte(',')
|
||||
}
|
||||
}
|
||||
for i := rem; i < len(s); i += 3 {
|
||||
if i > rem {
|
||||
out.WriteByte(',')
|
||||
}
|
||||
out.WriteString(s[i : i+3])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func formatTrimFloat(f float64) string {
|
||||
return strconv.FormatFloat(Round2(f), 'f', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
ZonaHoraria = "America/Mexico_City"
|
||||
RecordatorioDiasDef = 3
|
||||
HoraRecordatorios = 9
|
||||
EstadoPagoPendiente = "pendiente"
|
||||
EstadoPagoEnRevision = "en_revision"
|
||||
EstadoPagoVerificado = "verificado"
|
||||
EstadoPagoRechazado = "rechazado"
|
||||
EstadoPagoAnulado = "anulado"
|
||||
)
|
||||
|
||||
var EstadosPorPagar = []string{EstadoPagoPendiente, EstadoPagoRechazado}
|
||||
|
||||
func EsPorPagar(estado string) bool {
|
||||
return estado == EstadoPagoPendiente || estado == EstadoPagoRechazado
|
||||
}
|
||||
|
||||
func mexicoLocation() *time.Location {
|
||||
loc, err := time.LoadLocation(ZonaHoraria)
|
||||
if err != nil {
|
||||
// Mexico City has been permanently UTC-6 since 2022 (no DST).
|
||||
return time.FixedZone("America/Mexico_City", -6*3600)
|
||||
}
|
||||
return loc
|
||||
}
|
||||
|
||||
var fechaISORe = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`)
|
||||
|
||||
// ParseFechaCalendario parses "YYYY-MM-DD" into UTC midnight calendar date.
|
||||
func ParseFechaCalendario(iso string) (time.Time, error) {
|
||||
m := fechaISORe.FindStringSubmatch(strings.TrimSpace(iso))
|
||||
if m == nil {
|
||||
return time.Time{}, fmt.Errorf("Fecha invalida: %s (se espera YYYY-MM-DD)", iso)
|
||||
}
|
||||
y, _ := strconv.Atoi(m[1])
|
||||
mo, _ := strconv.Atoi(m[2])
|
||||
d, _ := strconv.Atoi(m[3])
|
||||
return time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC), nil
|
||||
}
|
||||
|
||||
// ACalendario extracts calendar (year, month, day) from UTC parts.
|
||||
func ACalendario(t time.Time) (int, time.Month, int) {
|
||||
u := t.UTC()
|
||||
return u.Year(), u.Month(), u.Day()
|
||||
}
|
||||
|
||||
// CalendarioDe converts a real timestamp to its America/Mexico_City calendar date (UTC midnight).
|
||||
func CalendarioDe(instante time.Time) time.Time {
|
||||
mx := instante.In(mexicoLocation())
|
||||
return time.Date(mx.Year(), mx.Month(), mx.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func HoyCalendario() time.Time {
|
||||
return CalendarioDe(time.Now())
|
||||
}
|
||||
|
||||
func HoraMexico(instante time.Time) int {
|
||||
return instante.In(mexicoLocation()).Hour()
|
||||
}
|
||||
|
||||
// InstanteDePago returns noon in Mexico City (18:00 UTC) so CalendarioDe() maps back to the same day.
|
||||
func InstanteDePago(fecha time.Time) time.Time {
|
||||
y, m, d := ACalendario(fecha)
|
||||
return time.Date(y, m, d, 18, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func SumarDias(d time.Time, dias int) time.Time {
|
||||
return d.UTC().AddDate(0, 0, dias)
|
||||
}
|
||||
|
||||
func DiasDeAtraso(fecha, hoy time.Time) int {
|
||||
diff := math.Round(hoy.UTC().Sub(fecha.UTC()).Hours() / 24.0)
|
||||
if diff < 0 {
|
||||
return 0
|
||||
}
|
||||
return int(diff)
|
||||
}
|
||||
|
||||
func DiasHasta(fecha, hoy time.Time) int {
|
||||
return int(math.Round(fecha.UTC().Sub(hoy.UTC()).Hours() / 24.0))
|
||||
}
|
||||
|
||||
func DescribirVencimiento(fecha, hoy time.Time) string {
|
||||
d := DiasHasta(fecha, hoy)
|
||||
switch {
|
||||
case d == 0:
|
||||
return "vence hoy"
|
||||
case d == 1:
|
||||
return "mañana"
|
||||
case d > 1:
|
||||
return fmt.Sprintf("en %d días", d)
|
||||
case d == -1:
|
||||
return "hace 1 día"
|
||||
default:
|
||||
return fmt.Sprintf("hace %d días", -d)
|
||||
}
|
||||
}
|
||||
|
||||
var diasSemanaLargo = []string{
|
||||
"Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado",
|
||||
}
|
||||
|
||||
var diasSemanaCorto = []string{
|
||||
"dom", "lun", "mar", "mié", "jue", "vie", "sáb",
|
||||
}
|
||||
|
||||
var mesesCorto = []string{
|
||||
"ene", "feb", "mar", "abr", "may", "jun",
|
||||
"jul", "ago", "sep", "oct", "nov", "dic",
|
||||
}
|
||||
|
||||
func FormatFechaCobro(date time.Time) string {
|
||||
u := date.UTC()
|
||||
return fmt.Sprintf("%s, %02d de %s de %d", diasSemanaLargo[int(u.Weekday())], u.Day(), mesesLargo[int(u.Month())-1], u.Year())
|
||||
}
|
||||
|
||||
func FormatFechaBreve(date, hoy time.Time) string {
|
||||
u := date.UTC()
|
||||
anio := ""
|
||||
if u.Year() != hoy.UTC().Year() {
|
||||
anio = fmt.Sprintf(" %d", u.Year())
|
||||
}
|
||||
return fmt.Sprintf("%s %d %s%s", diasSemanaCorto[int(u.Weekday())], u.Day(), mesesCorto[int(u.Month())-1], anio)
|
||||
}
|
||||
|
||||
func FormatFechaCorta(date time.Time) string {
|
||||
y, m, d := ACalendario(date)
|
||||
return fmt.Sprintf("%02d/%02d/%04d", d, int(m), y)
|
||||
}
|
||||
|
||||
func FormatTotales(totales map[string]float64) string {
|
||||
if len(totales) == 0 {
|
||||
return "$0"
|
||||
}
|
||||
keys := make([]string, 0, len(totales))
|
||||
for k := range totales {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
partes := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
partes = append(partes, FormatMonto(totales[k], k))
|
||||
}
|
||||
return strings.Join(partes, " + ")
|
||||
}
|
||||
|
||||
type ProgramaCalendario struct {
|
||||
Frecuencia string
|
||||
DiaSemana *int
|
||||
DiaMes *int
|
||||
FechaInicio time.Time
|
||||
FechaFin *time.Time
|
||||
}
|
||||
|
||||
func FechasPeriodo(p ProgramaCalendario, hasta time.Time) []time.Time {
|
||||
iy, im, id := ACalendario(p.FechaInicio)
|
||||
inicioD := time.Date(iy, im, id, 0, 0, 0, 0, time.UTC)
|
||||
limite := hasta.UTC()
|
||||
if p.FechaFin != nil {
|
||||
fy, fm, fd := ACalendario(*p.FechaFin)
|
||||
finD := time.Date(fy, fm, fd, 0, 0, 0, 0, time.UTC)
|
||||
if finD.Before(limite) {
|
||||
limite = finD
|
||||
}
|
||||
}
|
||||
if inicioD.After(limite) {
|
||||
return nil
|
||||
}
|
||||
|
||||
var out []time.Time
|
||||
switch p.Frecuencia {
|
||||
case "semanal":
|
||||
dia := int(inicioD.Weekday())
|
||||
if p.DiaSemana != nil {
|
||||
dia = *p.DiaSemana
|
||||
}
|
||||
d := inicioD
|
||||
for guard := 0; int(d.Weekday()) != dia && guard < 7; guard++ {
|
||||
d = SumarDias(d, 1)
|
||||
}
|
||||
for !d.After(limite) {
|
||||
out = append(out, d)
|
||||
d = SumarDias(d, 7)
|
||||
}
|
||||
case "quincenal":
|
||||
mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
for !mes.After(limite) {
|
||||
for _, dia := range []int{1, 15} {
|
||||
d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC)
|
||||
if !d.Before(inicioD) && !d.After(limite) {
|
||||
out = append(out, d)
|
||||
}
|
||||
}
|
||||
mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
default: // mensual
|
||||
diaMes := 1
|
||||
if p.DiaMes != nil {
|
||||
diaMes = *p.DiaMes
|
||||
}
|
||||
mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
for !mes.After(limite) {
|
||||
ultimoDia := time.Date(mes.Year(), mes.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
|
||||
dia := diaMes
|
||||
if dia > ultimoDia {
|
||||
dia = ultimoDia
|
||||
}
|
||||
d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC)
|
||||
if !d.Before(inicioD) && !d.After(limite) {
|
||||
out = append(out, d)
|
||||
}
|
||||
mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ProximaFecha(p ProgramaCalendario, desde time.Time) *time.Time {
|
||||
ventana := FechasPeriodo(p, SumarDias(desde, 366))
|
||||
for _, f := range ventana {
|
||||
if !f.Before(desde) {
|
||||
v := f
|
||||
return &v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func floatPtr(v float64) *float64 { return &v }
|
||||
func strPtr(v string) *string { return &v }
|
||||
|
||||
func TestCalculatorsParity(t *testing.T) {
|
||||
if IVARate != 0.16 {
|
||||
t.Fatalf("expected IVARate 0.16, got %v", IVARate)
|
||||
}
|
||||
if len(EstadosCotizacion) != 6 {
|
||||
t.Fatalf("expected 6 estados, got %d", len(EstadosCotizacion))
|
||||
}
|
||||
|
||||
// Financing plans (3, 6, 9, 12 months)
|
||||
cases := []struct {
|
||||
meses int
|
||||
tasa float64
|
||||
monto float64
|
||||
wantComision float64
|
||||
wantPagoMes float64
|
||||
wantTotalMes float64
|
||||
}{
|
||||
{3, 0.077, 10000, 250, 3679.75, 4268.51},
|
||||
{6, 0.107, 10000, 250, 1891.13, 2193.71},
|
||||
{9, 0.137, 10000, 250, 1294.92, 1502.1},
|
||||
{12, 0.167, 10000, 250, 996.81, 1156.3},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := CalcularFinanciamiento(FinanciamientoInput{
|
||||
Monto: tc.monto, Meses: tc.meses, Tasa: tc.tasa, Comision: 2.5, IVA: 0.16,
|
||||
})
|
||||
if res.ComisionTotal != tc.wantComision {
|
||||
t.Errorf("%dm comisionTotal=%v want %v", tc.meses, res.ComisionTotal, tc.wantComision)
|
||||
}
|
||||
if res.PagoMensual != tc.wantPagoMes {
|
||||
t.Errorf("%dm pagoMensual=%v want %v", tc.meses, res.PagoMensual, tc.wantPagoMes)
|
||||
}
|
||||
if res.TotalMensual != tc.wantTotalMes {
|
||||
t.Errorf("%dm totalMensual=%v want %v", tc.meses, res.TotalMensual, tc.wantTotalMes)
|
||||
}
|
||||
}
|
||||
|
||||
// Totales cotizacion with mixed models & unselected item
|
||||
svcs := []ServicioCalc{
|
||||
{TipoPago: "unico", Precio: 15000, Seleccionado: true, ModeloCobro: "fijo"},
|
||||
{TipoPago: "mensual", Precio: 5000, Seleccionado: true, ModeloCobro: "retainer"},
|
||||
{TipoPago: "mensual", Precio: 0, Seleccionado: true, ModeloCobro: "demanda", TarifaHora: floatPtr(700)},
|
||||
{TipoPago: "unico", Precio: 99999, Seleccionado: false},
|
||||
}
|
||||
totCon := CalcularTotalesCotizacion(svcs, true)
|
||||
if totCon.SubtotalUnico != 15000 || totCon.SubtotalMensual != 5000 || totCon.TotalUnico != 17400 || totCon.TotalMensual != 5800 || totCon.TotalPrimerAnio != 87000 {
|
||||
t.Fatalf("unexpected totCon: %+v", totCon)
|
||||
}
|
||||
totSin := CalcularTotalesCotizacion(svcs, false)
|
||||
if totSin.IVAUnico != 0 || totSin.TotalUnico != 15000 || totSin.TotalPrimerAnio != 75000 {
|
||||
t.Fatalf("unexpected totSin: %+v", totSin)
|
||||
}
|
||||
|
||||
// Doble propuesta option totals
|
||||
doble := []ServicioCalc{
|
||||
{Opcion: strPtr("1"), TipoPago: "unico", Precio: 10000, Horas: floatPtr(10)},
|
||||
{Opcion: strPtr("2"), TipoPago: "unico", Precio: 20000, Horas: floatPtr(20)},
|
||||
{Opcion: strPtr("ambas"), TipoPago: "mensual", Precio: 3000, Horas: floatPtr(5)},
|
||||
}
|
||||
op1 := CalcularTotalesOpcion(doble, "1")
|
||||
op2 := CalcularTotalesOpcion(doble, "2")
|
||||
if op1.TotalUnico != 10000 || op1.TotalMensual != 3000 || op1.Horas != 15 {
|
||||
t.Fatalf("unexpected op1: %+v", op1)
|
||||
}
|
||||
if op2.TotalUnico != 20000 || op2.TotalMensual != 3000 || op2.Horas != 25 {
|
||||
t.Fatalf("unexpected op2: %+v", op2)
|
||||
}
|
||||
|
||||
// 15 business days vigencia: Mon 2026-06-01 -> Mon 2026-06-22
|
||||
start := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
vig := CalcularVigencia(start)
|
||||
if vig.Format("2006-01-02") != "2026-06-22" {
|
||||
t.Fatalf("expected vigencia 2026-06-22, got %s", vig.Format("2006-01-02"))
|
||||
}
|
||||
|
||||
// Hours range & summary
|
||||
if h := CalcularHorasRango("09:00", "13:30"); h != 4.5 {
|
||||
t.Fatalf("expected 4.5 hours, got %v", h)
|
||||
}
|
||||
resH := CalcularResumenPagoHoras([]RegistroHorasCalc{
|
||||
{Horas: 2, TarifaHora: 700, EstadoPago: "por_pagar"},
|
||||
{Horas: 3, TarifaHora: 700, EstadoPago: "pagada"},
|
||||
})
|
||||
if resH.PorPagar.Importe != 1400 || resH.Pagada.Importe != 2100 || resH.Total.Importe != 3500 {
|
||||
t.Fatalf("unexpected resumen horas: %+v", resH)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApprovalGuard(t *testing.T) {
|
||||
now := time.Now()
|
||||
agent := ActorInfo{Type: "agent", Scopes: []string{"cotizaciones:borrador", "cotizaciones:enviar"}}
|
||||
asesor := ActorInfo{Type: "user", Role: "asesor"}
|
||||
admin := ActorInfo{Type: "user", Role: "admin"}
|
||||
enlace := ActorInfo{Type: "enlace_firmado"}
|
||||
|
||||
// Agent cannot approve
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: agent, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent approval should be 403, got %+v", r)
|
||||
}
|
||||
// Asesor cannot approve
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: asesor, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("asesor approval should be 403, got %+v", r)
|
||||
}
|
||||
// Admin can approve borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: admin, ViaEndpoint: "aprobar"}); !r.OK {
|
||||
t.Fatalf("admin approval should succeed, got %+v", r)
|
||||
}
|
||||
// Signed link can approve borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: enlace, ViaEndpoint: "enlace_firmado"}); !r.OK {
|
||||
t.Fatalf("signed link approval should succeed, got %+v", r)
|
||||
}
|
||||
// Cannot send borrador
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar"}); r.OK || r.Status != 409 {
|
||||
t.Fatalf("sending draft should be 409, got %+v", r)
|
||||
}
|
||||
// Agent cannot set enviada via PUT
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "put", AprobadaAt: &now}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent PUT enviada should be 403, got %+v", r)
|
||||
}
|
||||
// Agent can send approved quote via enviar
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar", AprobadaAt: &now}); !r.OK {
|
||||
t.Fatalf("agent enviar approved should succeed, got %+v", r)
|
||||
}
|
||||
// Agent cannot mark aceptada
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: agent, ViaEndpoint: "estado"}); r.OK || r.Status != 403 {
|
||||
t.Fatalf("agent aceptada should be 403, got %+v", r)
|
||||
}
|
||||
// Staff can mark aceptada
|
||||
if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: asesor, ViaEndpoint: "estado"}); !r.OK {
|
||||
t.Fatalf("asesor aceptada should succeed, got %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoloAdminRestriction(t *testing.T) {
|
||||
soloIDs := map[string]struct{}{"plan-mensual-crm-bucefalo-18": {}}
|
||||
|
||||
// Human admin allowed everything
|
||||
r1 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{
|
||||
EsAgente: false,
|
||||
HasPlanBucefalo: true,
|
||||
Servicios: []ServicioDraftInput{{CatalogoID: "plan-mensual-crm-bucefalo-18", Nombre: "CRM Bucéfalo"}},
|
||||
SoloAdminCatalogIDs: soloIDs,
|
||||
})
|
||||
if !r1.OK {
|
||||
t.Fatalf("human admin should not be blocked: %+v", r1)
|
||||
}
|
||||
|
||||
// Agent blocked on planBucefalo, soloAdmin ID, bucefalo-* prefix, and custom name
|
||||
r2 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{
|
||||
EsAgente: true,
|
||||
HasPlanBucefalo: true,
|
||||
Servicios: []ServicioDraftInput{
|
||||
{CatalogoID: "plan-mensual-crm-bucefalo-18"},
|
||||
{CatalogoID: "bucefalo-pro"},
|
||||
{Nombre: "Implementacion Bucéfalo Custom"},
|
||||
},
|
||||
SoloAdminCatalogIDs: soloIDs,
|
||||
})
|
||||
if r2.OK || len(r2.ItemsBloqueados) != 4 {
|
||||
t.Fatalf("expected 4 blocked items, got %+v", r2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFechasPeriodo(t *testing.T) {
|
||||
ini, _ := ParseFechaCalendario("2026-07-01")
|
||||
fin, _ := ParseFechaCalendario("2026-07-31")
|
||||
sab := 6
|
||||
fechas := FechasPeriodo(ProgramaCalendario{
|
||||
Frecuencia: "semanal",
|
||||
DiaSemana: &sab,
|
||||
FechaInicio: ini,
|
||||
FechaFin: &fin,
|
||||
}, fin)
|
||||
if len(fechas) != 4 || FormatFechaCorta(fechas[0]) != "04/07/2026" {
|
||||
t.Fatalf("expected 4 saturdays starting 04/07/2026, got %d (%v)", len(fechas), fechas)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ServicioDraftInput struct {
|
||||
CatalogoID string
|
||||
Nombre string
|
||||
EsPersonalizado bool
|
||||
}
|
||||
|
||||
type EvaluarSoloAdminInput struct {
|
||||
EsAgente bool
|
||||
HasPlanBucefalo bool
|
||||
Servicios []ServicioDraftInput
|
||||
SoloAdminCatalogIDs map[string]struct{}
|
||||
}
|
||||
|
||||
type EvaluarSoloAdminResult struct {
|
||||
OK bool
|
||||
Motivos []string
|
||||
ItemsBloqueados []string
|
||||
}
|
||||
|
||||
var bucefaloRe = regexp.MustCompile(`(?i)buc[eé]falo`)
|
||||
var bucefaloPrefixRe = regexp.MustCompile(`(?i)^bucefalo-`)
|
||||
|
||||
func EvaluarRestriccionSoloAdmin(in EvaluarSoloAdminInput) EvaluarSoloAdminResult {
|
||||
if !in.EsAgente {
|
||||
return EvaluarSoloAdminResult{OK: true}
|
||||
}
|
||||
|
||||
var motivos []string
|
||||
var bloqueados []string
|
||||
|
||||
if in.HasPlanBucefalo {
|
||||
motivos = append(motivos, "planBucefalo esta reservado al administrador humano")
|
||||
bloqueados = append(bloqueados, "planBucefalo")
|
||||
}
|
||||
|
||||
for _, svc := range in.Servicios {
|
||||
cid := strings.TrimSpace(svc.CatalogoID)
|
||||
nombre := strings.TrimSpace(svc.Nombre)
|
||||
|
||||
if cid != "" && bucefaloPrefixRe.MatchString(cid) {
|
||||
motivos = append(motivos, fmt.Sprintf("catalogoId restringido (%s)", cid))
|
||||
bloqueados = append(bloqueados, cid)
|
||||
continue
|
||||
}
|
||||
if cid != "" {
|
||||
if _, ok := in.SoloAdminCatalogIDs[cid]; ok {
|
||||
motivos = append(motivos, fmt.Sprintf("servicio marcado soloAdmin (%s)", cid))
|
||||
bloqueados = append(bloqueados, cid)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if nombre != "" && bucefaloRe.MatchString(nombre) {
|
||||
motivos = append(motivos, fmt.Sprintf("servicio restringido por marca soloAdmin (%s)", nombre))
|
||||
bloqueados = append(bloqueados, nombre)
|
||||
}
|
||||
}
|
||||
|
||||
return EvaluarSoloAdminResult{
|
||||
OK: len(motivos) == 0,
|
||||
Motivos: motivos,
|
||||
ItemsBloqueados: bloqueados,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CatalogoCSVRow struct {
|
||||
Nombre string
|
||||
Categoria string
|
||||
Fase int
|
||||
TipoPago string
|
||||
PrecioBase float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
Variante string
|
||||
}
|
||||
|
||||
var fasesExportCSV = map[int]string{
|
||||
0: "Auditoria",
|
||||
1: "Setup e Infraestructura",
|
||||
2: "Publicidad y Manejo",
|
||||
3: "Contenido y SEO",
|
||||
}
|
||||
|
||||
var fasesImportCSV = map[string]int{
|
||||
"0": 0,
|
||||
"fase 0": 0,
|
||||
"auditoria": 0,
|
||||
"auditoría": 0,
|
||||
"1": 1,
|
||||
"fase 1": 1,
|
||||
"setup e infraestructura": 1,
|
||||
"setup": 1,
|
||||
"infraestructura": 1,
|
||||
"2": 2,
|
||||
"fase 2": 2,
|
||||
"publicidad y manejo": 2,
|
||||
"publicidad": 2,
|
||||
"manejo": 2,
|
||||
"3": 3,
|
||||
"fase 3": 3,
|
||||
"contenido y seo": 3,
|
||||
"contenido": 3,
|
||||
"seo": 3,
|
||||
}
|
||||
|
||||
func ExportCatalogoCSV(rows []CatalogoCSVRow) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
w := csv.NewWriter(&buf)
|
||||
|
||||
if err := w.Write([]string{
|
||||
"Nombre",
|
||||
"Categoria",
|
||||
"Fase",
|
||||
"Tipo de Pago",
|
||||
"Precio Base",
|
||||
"Tiempo de Entrega",
|
||||
"Entregables",
|
||||
"Variante",
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, r := range rows {
|
||||
faseLabel, ok := fasesExportCSV[r.Fase]
|
||||
if !ok {
|
||||
faseLabel = fmt.Sprintf("Fase %d", r.Fase)
|
||||
}
|
||||
tipoLabel := "Mensual"
|
||||
if strings.EqualFold(strings.TrimSpace(r.TipoPago), "unico") {
|
||||
tipoLabel = "Pago Unico"
|
||||
}
|
||||
rec := []string{
|
||||
r.Nombre,
|
||||
r.Categoria,
|
||||
faseLabel,
|
||||
tipoLabel,
|
||||
strconv.FormatFloat(r.PrecioBase, 'f', -1, 64),
|
||||
r.TiempoEntrega,
|
||||
strings.Join(r.Entregables, " | "),
|
||||
r.Variante,
|
||||
}
|
||||
if err := w.Write(rec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
if err := w.Error(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func PlantillaCatalogoCSV() []byte {
|
||||
const tpl = `Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante
|
||||
"SEO On-Page Basico","SEO","Setup e Infraestructura","unico",5000,"7 - 14 dias","Auditoria SEO | Optimizacion de meta tags | Mapa del sitio",
|
||||
"Manejo de Redes Sociales","Marketing","Publicidad y Manejo","mensual",8000,"Mensual","Publicaciones semanales | Reporte mensual | Gestion de comunidad","Basico"
|
||||
"Gestion de Google Ads","Paid Media","Publicidad y Manejo","mensual",5000,"Mensual","Configuracion de campanas | Reporte semanal",
|
||||
"Sitio Web Informativo","Desarrollo Web","Setup e Infraestructura","unico",15000,"15 - 30 dias","Diseno responsivo | Hasta 5 secciones | Formulario de contacto",
|
||||
"Automatizacion Email Marketing","Automatizaciones","Publicidad y Manejo","unico",8000,"10 - 15 dias","Configuracion de flujos | Plantillas de correo | Integracion CRM",
|
||||
"CRM Basico","CRM","Publicidad y Manejo","mensual",1000,"Mensual","CRM completo segun plan contratado","basico"
|
||||
|
||||
,,,,
|
||||
"CATEGORIAS DISPONIBLES: SEO / Marketing / Paid Media / Desarrollo Web / Automatizaciones / CRM",,,,,
|
||||
"FASES: Auditoria / Setup e Infraestructura / Publicidad y Manejo / Contenido y SEO",,,,,
|
||||
"TIPOS DE PAGO: unico / mensual",,,,,
|
||||
"ENTREGABLES: separar con | (pipe)",,,,,
|
||||
"VARIANTE: opcional (ej: Basico, Estandar, Premium)",,,,,
|
||||
`
|
||||
return []byte(tpl)
|
||||
}
|
||||
|
||||
func isInstructionLine(line string) bool {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" {
|
||||
return true
|
||||
}
|
||||
unquoted := strings.ToUpper(strings.TrimPrefix(trimmed, `"`))
|
||||
for _, prefix := range []string{
|
||||
"CATEGORIAS",
|
||||
"CATEGORÍAS",
|
||||
"FASES:",
|
||||
"TIPOS DE PAGO",
|
||||
"TIPOS",
|
||||
"ENTREGABLES:",
|
||||
"VARIANTE:",
|
||||
} {
|
||||
if strings.HasPrefix(unquoted, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ParseCatalogoCSV(raw []byte) ([]CatalogoCSVRow, error) {
|
||||
// Strip UTF-8 BOM if present.
|
||||
raw = bytes.TrimPrefix(raw, []byte{0xEF, 0xBB, 0xBF})
|
||||
|
||||
text := strings.ReplaceAll(string(raw), "\r\n", "\n")
|
||||
rawLines := strings.Split(text, "\n")
|
||||
var kept []string
|
||||
for _, l := range rawLines {
|
||||
if isInstructionLine(l) {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, l)
|
||||
}
|
||||
if len(kept) < 2 {
|
||||
return nil, errors.New("el CSV esta vacio o no tiene datos")
|
||||
}
|
||||
|
||||
r := csv.NewReader(strings.NewReader(strings.Join(kept, "\n")))
|
||||
r.FieldsPerRecord = -1
|
||||
r.LazyQuotes = true
|
||||
r.TrimLeadingSpace = true
|
||||
|
||||
// Skip header row.
|
||||
if _, err := r.Read(); err != nil {
|
||||
return nil, fmt.Errorf("error leyendo encabezado CSV: %w", err)
|
||||
}
|
||||
|
||||
var rows []CatalogoCSVRow
|
||||
for {
|
||||
rec, err := r.Read()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error leyendo CSV: %w", err)
|
||||
}
|
||||
if len(rec) < 5 {
|
||||
continue
|
||||
}
|
||||
|
||||
get := func(i int) string {
|
||||
if i >= len(rec) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(rec[i])
|
||||
}
|
||||
|
||||
nombre := get(0)
|
||||
categoria := get(1)
|
||||
faseStr := strings.ToLower(get(2))
|
||||
tipoStr := strings.ToLower(get(3))
|
||||
precioStr := get(4)
|
||||
tiempoEntrega := get(5)
|
||||
entregablesStr := get(6)
|
||||
variante := get(7)
|
||||
|
||||
if nombre == "" || categoria == "" || tipoStr == "" || precioStr == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
fase, ok := fasesImportCSV[faseStr]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
var tipoPago string
|
||||
switch tipoStr {
|
||||
case "unico", "único", "pago unico", "pago único":
|
||||
tipoPago = "unico"
|
||||
case "mensual":
|
||||
tipoPago = "mensual"
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
cleanedPrecio := strings.NewReplacer("$", "", ",", "", " ", "").Replace(precioStr)
|
||||
precioBase, err := strconv.ParseFloat(cleanedPrecio, 64)
|
||||
if err != nil || math.IsNaN(precioBase) || math.IsInf(precioBase, 0) || precioBase < 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if tiempoEntrega == "" {
|
||||
tiempoEntrega = "7 - 14 dias"
|
||||
}
|
||||
|
||||
var entregables []string
|
||||
if entregablesStr != "" {
|
||||
for _, part := range strings.Split(entregablesStr, "|") {
|
||||
if p := strings.TrimSpace(part); p != "" {
|
||||
entregables = append(entregables, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rows = append(rows, CatalogoCSVRow{
|
||||
Nombre: nombre,
|
||||
Categoria: categoria,
|
||||
Fase: fase,
|
||||
TipoPago: tipoPago,
|
||||
PrecioBase: precioBase,
|
||||
TiempoEntrega: tiempoEntrega,
|
||||
Entregables: entregables,
|
||||
Variante: variante,
|
||||
})
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
return nil, errors.New("no se encontraron filas validas. Verifica el formato del CSV")
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type ServicioExcel struct {
|
||||
Nombre string
|
||||
Fase int
|
||||
TipoPago string
|
||||
Precio float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
ModeloCobro string
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
}
|
||||
|
||||
// CotizacionExcelData holds client-facing quotation data for Excel export.
|
||||
// ObservacionesInternas is intentionally NOT declared here so internal notes
|
||||
// can never leak into a client workbook.
|
||||
type CotizacionExcelData struct {
|
||||
RazonSocial string
|
||||
DomicilioFiscal string
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
AsesorNombre string
|
||||
Fecha time.Time
|
||||
Vigencia time.Time
|
||||
Moneda string
|
||||
TipoCambio string
|
||||
Proyecto string
|
||||
EsquemaPago string
|
||||
Servicios []ServicioExcel
|
||||
EsDoble bool
|
||||
OpcionesMetadata map[string]domain.MetaOpcion
|
||||
PlanBucefaloNivel *string
|
||||
PlanBucefaloPrecio *float64
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
IncluirIVA bool
|
||||
Observaciones *string
|
||||
}
|
||||
|
||||
var (
|
||||
hexRe = regexp.MustCompile(`^#?[0-9a-fA-F]{6}$`)
|
||||
invalidTabRe = regexp.MustCompile(`[/\\*?\[\]:]`)
|
||||
fasesExcelMap = map[int]string{
|
||||
0: "FASE 0",
|
||||
1: "FASE 1",
|
||||
2: "FASE 2",
|
||||
3: "FASE 3",
|
||||
}
|
||||
)
|
||||
|
||||
func cleanHex(v, fallback string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if !hexRe.MatchString(v) {
|
||||
v = fallback
|
||||
}
|
||||
return strings.ToUpper(strings.TrimPrefix(v, "#"))
|
||||
}
|
||||
|
||||
// tintLight blends ~10% of hex color onto white (#FFFFFF) for crisp light fills in Excel.
|
||||
func tintLight(hex6 string) string {
|
||||
r, _ := strconv.ParseInt(hex6[0:2], 16, 64)
|
||||
g, _ := strconv.ParseInt(hex6[2:4], 16, 64)
|
||||
b, _ := strconv.ParseInt(hex6[4:6], 16, 64)
|
||||
blend := func(c int64) int64 {
|
||||
return int64(math.Round(float64(c)*0.10 + 255.0*0.90))
|
||||
}
|
||||
return fmt.Sprintf("%02X%02X%02X", blend(r), blend(g), blend(b))
|
||||
}
|
||||
|
||||
func capitalize(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
r := []rune(s)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func servicioExcelToCalc(s ServicioExcel) domain.ServicioCalc {
|
||||
return domain.ServicioCalc{
|
||||
Nombre: s.Nombre,
|
||||
ModeloCobro: s.ModeloCobro,
|
||||
EsPersonalizado: s.EsPersonalizado,
|
||||
Horas: s.Horas,
|
||||
TarifaHora: s.TarifaHora,
|
||||
MontoMinimo: s.MontoMinimo,
|
||||
HorasIncluidas: s.HorasIncluidas,
|
||||
Opcion: s.Opcion,
|
||||
TipoPago: s.TipoPago,
|
||||
Precio: s.Precio,
|
||||
Seleccionado: true,
|
||||
}
|
||||
}
|
||||
|
||||
func serviciosExcelToCalc(list []ServicioExcel) []domain.ServicioCalc {
|
||||
out := make([]domain.ServicioCalc, len(list))
|
||||
for i, s := range list {
|
||||
out[i] = servicioExcelToCalc(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func estimateRowHeight(text string, widthChars float64, fontSize float64) float64 {
|
||||
cpl := int(math.Floor(widthChars))
|
||||
if cpl < 8 {
|
||||
cpl = 8
|
||||
}
|
||||
lineH := 14.0
|
||||
switch {
|
||||
case fontSize <= 10:
|
||||
lineH = 14
|
||||
case fontSize <= 11:
|
||||
lineH = 15.5
|
||||
case fontSize <= 12:
|
||||
lineH = 17
|
||||
default:
|
||||
lineH = 20
|
||||
}
|
||||
lines := 0
|
||||
for _, seg := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") {
|
||||
n := utf8.RuneCountInString(seg)
|
||||
l := int(math.Ceil(float64(n) / float64(cpl)))
|
||||
if l < 1 {
|
||||
l = 1
|
||||
}
|
||||
lines += l
|
||||
}
|
||||
h := math.Round(float64(lines)*lineH + 4)
|
||||
if h < 16 {
|
||||
return 16
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func sanitizeSheetName(name string, used map[string]bool) string {
|
||||
cleaned := strings.TrimSpace(invalidTabRe.ReplaceAllString(name, ""))
|
||||
cleaned = strings.Trim(cleaned, "'")
|
||||
if cleaned == "" {
|
||||
cleaned = "Servicio"
|
||||
}
|
||||
runes := []rune(cleaned)
|
||||
if len(runes) > 31 {
|
||||
runes = runes[:31]
|
||||
}
|
||||
base := string(runes)
|
||||
candidate := base
|
||||
n := 2
|
||||
for used[strings.ToLower(candidate)] {
|
||||
suffix := fmt.Sprintf(" (%d)", n)
|
||||
maxBase := 31 - utf8.RuneCountInString(suffix)
|
||||
br := []rune(base)
|
||||
if len(br) > maxBase {
|
||||
br = br[:maxBase]
|
||||
}
|
||||
candidate = string(br) + suffix
|
||||
n++
|
||||
}
|
||||
used[strings.ToLower(candidate)] = true
|
||||
return candidate
|
||||
}
|
||||
|
||||
type styleSpec struct {
|
||||
bold bool
|
||||
italic bool
|
||||
size float64
|
||||
fontColor string
|
||||
fillColor string
|
||||
borderClr string
|
||||
horiz string
|
||||
vert string
|
||||
wrap bool
|
||||
numFmt string
|
||||
}
|
||||
|
||||
type wbHelper struct {
|
||||
f *excelize.File
|
||||
styles map[styleSpec]int
|
||||
}
|
||||
|
||||
func newWBHelper() *wbHelper {
|
||||
return &wbHelper{
|
||||
f: excelize.NewFile(),
|
||||
styles: make(map[styleSpec]int),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wbHelper) styleID(s styleSpec) int {
|
||||
if id, ok := h.styles[s]; ok {
|
||||
return id
|
||||
}
|
||||
size := s.size
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
st := &excelize.Style{
|
||||
Font: &excelize.Font{
|
||||
Family: "Calibri",
|
||||
Size: size,
|
||||
Bold: s.bold,
|
||||
Italic: s.italic,
|
||||
Color: s.fontColor,
|
||||
},
|
||||
Alignment: &excelize.Alignment{
|
||||
Horizontal: s.horiz,
|
||||
Vertical: s.vert,
|
||||
WrapText: s.wrap,
|
||||
},
|
||||
}
|
||||
if s.fillColor != "" {
|
||||
st.Fill = excelize.Fill{
|
||||
Type: "pattern",
|
||||
Pattern: 1,
|
||||
Color: []string{s.fillColor},
|
||||
}
|
||||
}
|
||||
if s.borderClr != "" {
|
||||
st.Border = []excelize.Border{
|
||||
{Type: "top", Color: s.borderClr, Style: 1},
|
||||
{Type: "bottom", Color: s.borderClr, Style: 1},
|
||||
{Type: "left", Color: s.borderClr, Style: 1},
|
||||
{Type: "right", Color: s.borderClr, Style: 1},
|
||||
}
|
||||
}
|
||||
if s.numFmt != "" {
|
||||
nf := s.numFmt
|
||||
st.CustomNumFmt = &nf
|
||||
}
|
||||
id, err := h.f.NewStyle(st)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
h.styles[s] = id
|
||||
return id
|
||||
}
|
||||
|
||||
func (h *wbHelper) hideGrid(sheet string) {
|
||||
show := false
|
||||
_ = h.f.SetSheetView(sheet, 0, &excelize.ViewOptions{ShowGridLines: &show})
|
||||
}
|
||||
|
||||
func (h *wbHelper) setColWidths(sheet string, widths map[string]float64) {
|
||||
for col, w := range widths {
|
||||
_ = h.f.SetColWidth(sheet, col, col, w)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *wbHelper) ensureRowHeight(sheet string, row int, minH float64) {
|
||||
cur, _ := h.f.GetRowHeight(sheet, row)
|
||||
if cur < minH {
|
||||
_ = h.f.SetRowHeight(sheet, row, minH)
|
||||
}
|
||||
}
|
||||
|
||||
func sumWidths(widths map[string]float64, cols ...string) float64 {
|
||||
total := 0.0
|
||||
for _, c := range cols {
|
||||
if w, ok := widths[c]; ok {
|
||||
total += w
|
||||
} else {
|
||||
total += 8
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func BuildCotizacionExcel(data CotizacionExcelData) ([]byte, error) {
|
||||
primary := cleanHex(data.ColorPrimario, "0400C4")
|
||||
primaryLight := tintLight(primary)
|
||||
secondary := cleanHex(data.ColorSecundario, "0F172A")
|
||||
white := "FFFFFF"
|
||||
lightBG := "F8FAFC"
|
||||
muted := "64748B"
|
||||
borderColor := "E2E8F0"
|
||||
|
||||
wb := newWBHelper()
|
||||
defer wb.f.Close()
|
||||
|
||||
_ = wb.f.SetDocProps(&excelize.DocProperties{
|
||||
Creator: "Cotizador — Uriel Jareth Consulting",
|
||||
Created: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
|
||||
const resumenSheet = "HOJA RESUMEN"
|
||||
_ = wb.f.SetSheetName("Sheet1", resumenSheet)
|
||||
resumenWidths := map[string]float64{
|
||||
"A": 3, "B": 18, "C": 26, "D": 13, "E": 16, "F": 22,
|
||||
"G": 6, "H": 6, "I": 6, "J": 6, "K": 16,
|
||||
}
|
||||
wb.setColWidths(resumenSheet, resumenWidths)
|
||||
wb.hideGrid(resumenSheet)
|
||||
|
||||
// Common styles.
|
||||
stBanner1 := wb.styleID(styleSpec{bold: true, size: 16, fontColor: white, fillColor: primary, vert: "center"})
|
||||
stBanner2 := wb.styleID(styleSpec{bold: true, size: 11, fontColor: white, fillColor: secondary, vert: "center"})
|
||||
stLabel := wb.styleID(styleSpec{bold: true, size: 10, fontColor: muted, vert: "top"})
|
||||
stValueWrap := wb.styleID(styleSpec{size: 10, vert: "top", wrap: true})
|
||||
stDate := wb.styleID(styleSpec{size: 10, vert: "top", numFmt: "DD/MM/YYYY"})
|
||||
stHeaderL := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stHeaderR := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "right", vert: "center"})
|
||||
stFase := wb.styleID(styleSpec{bold: true, size: 11, fontColor: primary, fillColor: primaryLight, vert: "center"})
|
||||
stSmall := wb.styleID(styleSpec{italic: true, size: 9, fontColor: muted, vert: "top", wrap: true})
|
||||
stIvaNote := wb.styleID(styleSpec{size: 9, fontColor: muted})
|
||||
stObsTitle := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary})
|
||||
stOpBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: secondary, vert: "center"})
|
||||
stCompBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: primary, vert: "center"})
|
||||
|
||||
// ── Banner ──
|
||||
_ = wb.f.MergeCell(resumenSheet, "B2", "K2")
|
||||
_ = wb.f.SetCellValue(resumenSheet, "B2", data.RazonSocial)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, "A2", "K2", stBanner1)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, 2, 28)
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, "B3", "K3")
|
||||
_ = wb.f.SetCellValue(resumenSheet, "B3", data.Numero)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, "A3", "K3", stBanner2)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, 3, 20)
|
||||
|
||||
// ── Info cliente / proyecto ──
|
||||
infoStart := 5
|
||||
empresa := data.ClienteEmpresa
|
||||
if strings.TrimSpace(empresa) == "" {
|
||||
empresa = "—"
|
||||
}
|
||||
type infoPair struct{ l1, v1, l2, v2 string }
|
||||
infoRows := []infoPair{
|
||||
{"En atención a:", data.ClienteNombre, "Empresa:", empresa},
|
||||
{"Proyecto:", data.Proyecto, "Moneda:", data.Moneda},
|
||||
{"Asesor:", data.AsesorNombre, "Tipo de Cambio:", data.TipoCambio},
|
||||
{"Fecha:", "", "Esquema de Pago:", data.EsquemaPago},
|
||||
}
|
||||
for i, ip := range infoRows {
|
||||
r := infoStart + i
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", r), ip.l1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
if ip.v1 != "" {
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", r), ip.v1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", r), fmt.Sprintf("C%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v1, resumenWidths["C"], 10))
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("E%d", r), ip.l2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("E%d", r), fmt.Sprintf("E%d", r), stLabel)
|
||||
if ip.v2 != "" {
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("F%d", r), ip.v2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v2, resumenWidths["F"], 10))
|
||||
}
|
||||
}
|
||||
|
||||
if !data.Fecha.IsZero() {
|
||||
fUTC := time.Date(data.Fecha.Year(), data.Fecha.Month(), data.Fecha.Day(), 0, 0, 0, 0, time.UTC)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fUTC)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fmt.Sprintf("C%d", infoStart+3), stDate)
|
||||
}
|
||||
|
||||
vigRow := infoStart + 4
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", vigRow), "Vigencia:")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", vigRow), fmt.Sprintf("B%d", vigRow), stLabel)
|
||||
if !data.Vigencia.IsZero() {
|
||||
vUTC := time.Date(data.Vigencia.Year(), data.Vigencia.Month(), data.Vigencia.Day(), 0, 0, 0, 0, time.UTC)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", vigRow), vUTC)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", vigRow), fmt.Sprintf("C%d", vigRow), stDate)
|
||||
}
|
||||
|
||||
// ── Tabla de servicios ──
|
||||
tableStart := infoStart + 6
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", tableStart), fmt.Sprintf("J%d", tableStart))
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", tableStart), fmt.Sprintf("J%d", tableStart), stHeaderL)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", tableStart), fmt.Sprintf("K%d", tableStart), stHeaderR)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", tableStart), "Fase")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", tableStart), "Tipo de Pago")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", tableStart), "Servicio")
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", tableStart), "Precio")
|
||||
_ = wb.f.SetRowHeight(resumenSheet, tableStart, 24)
|
||||
|
||||
var unicos, mensuales []ServicioExcel
|
||||
for _, s := range data.Servicios {
|
||||
if s.TipoPago == "mensual" {
|
||||
mensuales = append(mensuales, s)
|
||||
} else {
|
||||
unicos = append(unicos, s)
|
||||
}
|
||||
}
|
||||
|
||||
servWidth := sumWidths(resumenWidths, "D", "E", "F", "G", "H", "I", "J")
|
||||
fullWidth := sumWidths(resumenWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J", "K")
|
||||
row := tableStart + 1
|
||||
|
||||
writeTotalRow := func(label string, amount float64, fontSize float64) {
|
||||
stLbl := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stAmt := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"})
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), label)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stLbl)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), amount)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stAmt)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 20)
|
||||
row++
|
||||
}
|
||||
|
||||
writeIvaNote := func() {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "(+ IVA)")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stIvaNote)
|
||||
row++
|
||||
}
|
||||
|
||||
drawServiceRows := func(servs []ServicioExcel) {
|
||||
currentFase := -1
|
||||
for _, serv := range servs {
|
||||
if serv.Fase != currentFase {
|
||||
currentFase = serv.Fase
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
fLbl := fasesExcelMap[serv.Fase]
|
||||
if fLbl == "" {
|
||||
fLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), fLbl)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stFase)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 20)
|
||||
row++
|
||||
}
|
||||
bg := white
|
||||
if row%2 == 0 {
|
||||
bg = lightBG
|
||||
}
|
||||
stCell := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top"})
|
||||
stCellWrap := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true})
|
||||
stPrice := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "right", vert: "top", numFmt: "$#,##0.00"})
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row))
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("C%d", row), stCell)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row), stCellWrap)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stPrice)
|
||||
|
||||
tipo := "Único"
|
||||
if serv.TipoPago == "mensual" {
|
||||
tipo = "Mensual"
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", row), tipo)
|
||||
|
||||
detalle := domain.DetalleModelo(servicioExcelToCalc(serv))
|
||||
servText := serv.Nombre
|
||||
if detalle != "" {
|
||||
servText = fmt.Sprintf("%s — %s", serv.Nombre, detalle)
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", row), servText)
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), serv.Precio)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(servText, servWidth, 10))
|
||||
row++
|
||||
}
|
||||
}
|
||||
|
||||
writeOpcionBanner := func(op string) {
|
||||
meta := data.OpcionesMetadata[op]
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
tit := "OPCIÓN " + op
|
||||
if strings.TrimSpace(meta.Titulo) != "" {
|
||||
tit += ": " + meta.Titulo
|
||||
}
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), tit)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stOpBanner)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 22)
|
||||
row++
|
||||
if strings.TrimSpace(meta.Descripcion) != "" {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), meta.Descripcion)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stValueWrap)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(meta.Descripcion, fullWidth, 10))
|
||||
row++
|
||||
}
|
||||
if strings.TrimSpace(meta.NoIncluye) != "" {
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
txt := "No incluye: " + meta.NoIncluye
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), txt)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(txt, fullWidth, 9))
|
||||
row++
|
||||
}
|
||||
}
|
||||
|
||||
sumPrices := func(list []ServicioExcel) float64 {
|
||||
tot := 0.0
|
||||
for _, s := range list {
|
||||
tot += s.Precio
|
||||
}
|
||||
return domain.Round2(tot)
|
||||
}
|
||||
|
||||
if data.EsDoble {
|
||||
filterOp := func(list []ServicioExcel, op string) []ServicioExcel {
|
||||
var out []ServicioExcel
|
||||
for _, s := range list {
|
||||
if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
for _, op := range []string{"1", "2"} {
|
||||
u := filterOp(unicos, op)
|
||||
me := filterOp(mensuales, op)
|
||||
writeOpcionBanner(op)
|
||||
combined := make([]ServicioExcel, 0, len(u)+len(me))
|
||||
combined = append(combined, u...)
|
||||
combined = append(combined, me...)
|
||||
drawServiceRows(combined)
|
||||
row++
|
||||
writeTotalRow(fmt.Sprintf("Total Pago Único - Opción %s", op), sumPrices(u), 11)
|
||||
writeIvaNote()
|
||||
writeTotalRow(fmt.Sprintf("Total Pago Mensual - Opción %s", op), sumPrices(me), 11)
|
||||
writeIvaNote()
|
||||
row++
|
||||
}
|
||||
|
||||
calcs := serviciosExcelToCalc(data.Servicios)
|
||||
t1 := domain.CalcularTotalesOpcion(calcs, "1")
|
||||
t2 := domain.CalcularTotalesOpcion(calcs, "2")
|
||||
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "COMPARATIVA DE OPCIONES")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stCompBanner)
|
||||
_ = wb.f.SetRowHeight(resumenSheet, row, 22)
|
||||
row++
|
||||
|
||||
compRow := func(lab, v1, v2 string, bold bool) {
|
||||
stL := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "left", vert: "center"})
|
||||
stR := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "right", vert: "center"})
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), lab)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row), stL)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("G%d", row), v1)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row), stR)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("I%d", row), v2)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row), stR)
|
||||
row++
|
||||
}
|
||||
|
||||
t1Tit := data.OpcionesMetadata["1"].Titulo
|
||||
t2Tit := data.OpcionesMetadata["2"].Titulo
|
||||
op1Lbl := "Opción 1"
|
||||
if t1Tit != "" {
|
||||
op1Lbl += " - " + t1Tit
|
||||
}
|
||||
op2Lbl := "Opción 2"
|
||||
if t2Tit != "" {
|
||||
op2Lbl += " - " + t2Tit
|
||||
}
|
||||
compRow("Concepto", op1Lbl, op2Lbl, true)
|
||||
ivaLbl := ""
|
||||
if data.IncluirIVA {
|
||||
ivaLbl = " (c/IVA)"
|
||||
}
|
||||
compRow("Total único"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalUnico, data.IncluirIVA)), false)
|
||||
compRow("Total mensual"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalMensual, data.IncluirIVA)), false)
|
||||
compRow("Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas), false)
|
||||
row++
|
||||
} else {
|
||||
combined := make([]ServicioExcel, 0, len(unicos)+len(mensuales))
|
||||
combined = append(combined, unicos...)
|
||||
combined = append(combined, mensuales...)
|
||||
drawServiceRows(combined)
|
||||
row++
|
||||
writeTotalRow("Total Pago Único", sumPrices(unicos), 11)
|
||||
writeIvaNote()
|
||||
writeTotalRow("Total Pago Mensual", sumPrices(mensuales), 11)
|
||||
writeIvaNote()
|
||||
row++
|
||||
}
|
||||
|
||||
if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" {
|
||||
nivel := strings.TrimSpace(*data.PlanBucefaloNivel)
|
||||
precio := domain.BucefaloPrecio(strings.ToLower(nivel))
|
||||
if data.PlanBucefaloPrecio != nil {
|
||||
precio = *data.PlanBucefaloPrecio
|
||||
}
|
||||
writeTotalRow("CRM Bucéfalo - "+capitalize(nivel), precio, 10)
|
||||
row++
|
||||
}
|
||||
|
||||
notaResumen := "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 días hábiles."
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), notaResumen)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(notaResumen, fullWidth, 9))
|
||||
|
||||
// Observaciones del cliente (solo cliente, nunca observaciones internas).
|
||||
if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" {
|
||||
row += 2
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "OBSERVACIONES")
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stObsTitle)
|
||||
row++
|
||||
texto := strings.TrimSpace(*data.Observaciones)
|
||||
_ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row))
|
||||
_ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), texto)
|
||||
_ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall)
|
||||
wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(texto, fullWidth, 9))
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// HOJAS DETALLADAS POR SERVICIO
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
usedNames := map[string]bool{
|
||||
strings.ToLower(resumenSheet): true,
|
||||
}
|
||||
detailWidths := map[string]float64{
|
||||
"A": 3, "B": 16, "C": 30, "D": 8, "E": 4,
|
||||
"F": 18, "G": 22, "H": 6, "I": 6, "J": 16,
|
||||
}
|
||||
stDetBanner := wb.styleID(styleSpec{bold: true, size: 14, fontColor: white, fillColor: primary, vert: "center", wrap: true})
|
||||
stBoldWrap := wb.styleID(styleSpec{bold: true, size: 10, vert: "top", wrap: true})
|
||||
stServTit := wb.styleID(styleSpec{bold: true, size: 12, fontColor: primary, vert: "top", wrap: true})
|
||||
stEntHead := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, vert: "center"})
|
||||
stTotLbl := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"})
|
||||
stTotVal := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"})
|
||||
stRazon := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary})
|
||||
|
||||
for _, serv := range data.Servicios {
|
||||
tabName := sanitizeSheetName(serv.Nombre, usedNames)
|
||||
_, _ = wb.f.NewSheet(tabName)
|
||||
wb.setColWidths(tabName, detailWidths)
|
||||
wb.hideGrid(tabName)
|
||||
|
||||
fLbl := fasesExcelMap[serv.Fase]
|
||||
if fLbl == "" {
|
||||
fLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
bannerText := fmt.Sprintf("%s — %s", fLbl, serv.Nombre)
|
||||
_ = wb.f.MergeCell(tabName, "B1", "J1")
|
||||
_ = wb.f.SetCellValue(tabName, "B1", bannerText)
|
||||
_ = wb.f.SetCellStyle(tabName, "A1", "J1", stDetBanner)
|
||||
bh := estimateRowHeight(bannerText, sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J"), 14)
|
||||
if bh < 30 {
|
||||
bh = 30
|
||||
}
|
||||
_ = wb.f.SetRowHeight(tabName, 1, bh)
|
||||
|
||||
cValW := sumWidths(detailWidths, "C", "D")
|
||||
gValW := sumWidths(detailWidths, "G", "H")
|
||||
entW := sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J")
|
||||
|
||||
r := 3
|
||||
clienteDisp := data.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisp) == "" {
|
||||
clienteDisp = data.ClienteNombre
|
||||
}
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Cliente:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), clienteDisp)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stBoldWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(clienteDisp, cValW, 10))
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "No. Cotización:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), data.Numero)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stBoldWrap)
|
||||
r += 2
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Servicio:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), serv.Nombre)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stServTit)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.Nombre, cValW, 12))
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "Tiempo de Entrega:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), serv.TiempoEntrega)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.TiempoEntrega, gValW, 10))
|
||||
r += 2
|
||||
|
||||
detalleServ := domain.DetalleModelo(servicioExcelToCalc(serv))
|
||||
if detalleServ != "" {
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Detalle:")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), detalleServ)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r), stValueWrap)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(detalleServ, sumWidths(detailWidths, "C", "D", "E", "F", "G", "H", "I", "J"), 10))
|
||||
r += 2
|
||||
}
|
||||
|
||||
// Entregables header
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Entregables")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stEntHead)
|
||||
_ = wb.f.SetRowHeight(tabName, r, 22)
|
||||
r++
|
||||
|
||||
for i, ent := range serv.Entregables {
|
||||
er := r + i
|
||||
bg := white
|
||||
if i%2 == 1 {
|
||||
bg = lightBG
|
||||
}
|
||||
stEnt := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true})
|
||||
txt := fmt.Sprintf("%d. %s", i+1, ent)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", er), txt)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er), stEnt)
|
||||
wb.ensureRowHeight(tabName, er, estimateRowHeight(txt, entW, 10))
|
||||
}
|
||||
r += len(serv.Entregables) + 1
|
||||
|
||||
tipoTot := "Único"
|
||||
if serv.TipoPago == "mensual" {
|
||||
tipoTot = "Mensual"
|
||||
}
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Total Pago "+tipoTot)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r), stTotLbl)
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("I%d", r), serv.Precio)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r), stTotVal)
|
||||
_ = wb.f.SetRowHeight(tabName, r, 20)
|
||||
r++
|
||||
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "(+ IVA)")
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stIvaNote)
|
||||
r += 2
|
||||
|
||||
notaDetalle := "Esta cotización tiene una vigencia de 15 días hábiles. Todos los precios en MXN, precios + IVA."
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), notaDetalle)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stSmall)
|
||||
wb.ensureRowHeight(tabName, r, estimateRowHeight(notaDetalle, entW, 9))
|
||||
r += 2
|
||||
|
||||
// Brand decision: never print domicilio fiscal in generated documents.
|
||||
_ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r))
|
||||
_ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), data.RazonSocial)
|
||||
_ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stRazon)
|
||||
}
|
||||
|
||||
buf, err := wb.f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
func f64(v float64) *float64 { return &v }
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func TestCotizacionExcelDataHasNoObservacionesInternas(t *testing.T) {
|
||||
rt := reflect.TypeOf(CotizacionExcelData{})
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
name := strings.ToLower(rt.Field(i).Name)
|
||||
if strings.Contains(name, "interna") {
|
||||
t.Fatalf("CotizacionExcelData must never declare internal observations field, found %q", rt.Field(i).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sheetContains(t *testing.T, f *excelize.File, sheet, substr string) bool {
|
||||
t.Helper()
|
||||
rows, err := f.GetRows(sheet)
|
||||
if err != nil {
|
||||
t.Fatalf("GetRows(%s): %v", sheet, err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
for _, cell := range row {
|
||||
if strings.Contains(cell, substr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestBuildCotizacionExcelSingle(t *testing.T) {
|
||||
fecha := time.Date(2026, 5, 10, 0, 0, 0, 0, time.UTC)
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
obs := "Nota visible para el cliente con acentos: diseño y año."
|
||||
|
||||
raw, err := BuildCotizacionExcel(CotizacionExcelData{
|
||||
RazonSocial: "URIEL JARETH CONSULTING",
|
||||
DomicilioFiscal: "DOMICILIO_SECRETO_NO_IMPRIMIR 123",
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "Sofía Ramírez",
|
||||
ClienteEmpresa: "Ramírez Diseño S.A.",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: "MXN",
|
||||
TipoCambio: "N/A",
|
||||
Proyecto: "Sitio Web y Campañas",
|
||||
EsquemaPago: "50/50",
|
||||
Servicios: []ServicioExcel{
|
||||
{
|
||||
Nombre: "Auditoría SEO / Técnica: [2026]*?",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
Precio: 6000,
|
||||
TiempoEntrega: "7 días",
|
||||
Entregables: []string{"Diagnóstico técnico", "Roadmap SEO"},
|
||||
ModeloCobro: "fijo",
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo Custom",
|
||||
Fase: 1,
|
||||
TipoPago: "unico",
|
||||
Precio: 14000,
|
||||
TiempoEntrega: "15 días",
|
||||
Entregables: []string{"Frontend", "Backend"},
|
||||
ModeloCobro: "horas",
|
||||
EsPersonalizado: true,
|
||||
Horas: f64(20),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Retainer Mensual",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
Precio: 7500,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Soporte", "Reportes"},
|
||||
ModeloCobro: "retainer",
|
||||
MontoMinimo: f64(7500),
|
||||
HorasIncluidas: f64(10),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo Custom", // duplicate tab name test
|
||||
Fase: 3,
|
||||
TipoPago: "mensual",
|
||||
Precio: 0,
|
||||
TiempoEntrega: "Bajo demanda",
|
||||
ModeloCobro: "demanda",
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
},
|
||||
PlanBucefaloNivel: str("premium"), // nil price -> falls back to domain.BucefaloPrecio (4500)
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
IncluirIVA: true,
|
||||
Observaciones: &obs,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildCotizacionExcel error: %v", err)
|
||||
}
|
||||
|
||||
f, err := excelize.OpenReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("excelize.OpenReader error: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
sheets := f.GetSheetList()
|
||||
if len(sheets) != 5 {
|
||||
t.Fatalf("expected 5 sheets (1 resumen + 4 services), got %d: %v", len(sheets), sheets)
|
||||
}
|
||||
if sheets[0] != "HOJA RESUMEN" {
|
||||
t.Fatalf("expected first sheet HOJA RESUMEN, got %q", sheets[0])
|
||||
}
|
||||
|
||||
// Verify key values in HOJA RESUMEN
|
||||
if v, _ := f.GetCellValue("HOJA RESUMEN", "B2"); v != "URIEL JARETH CONSULTING" {
|
||||
t.Errorf("B2 = %q, want URIEL JARETH CONSULTING", v)
|
||||
}
|
||||
if v, _ := f.GetCellValue("HOJA RESUMEN", "B3"); v != "UJ2605UR001" {
|
||||
t.Errorf("B3 = %q, want UJ2605UR001", v)
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "20 h x $700/hr") {
|
||||
t.Errorf("HOJA RESUMEN missing horas DetalleModelo")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "segun consumo") {
|
||||
t.Errorf("HOJA RESUMEN missing demanda DetalleModelo")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "CRM Bucéfalo - Premium") {
|
||||
t.Errorf("HOJA RESUMEN missing Plan Bucéfalo row")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", obs) {
|
||||
t.Errorf("HOJA RESUMEN missing Observaciones")
|
||||
}
|
||||
|
||||
// Verify DomicilioFiscal is NEVER printed on any sheet.
|
||||
for _, s := range sheets {
|
||||
if sheetContains(t, f, s, "DOMICILIO_SECRETO_NO_IMPRIMIR") {
|
||||
t.Fatalf("sheet %q leaked DomicilioFiscal", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCotizacionExcelDoblePropuesta(t *testing.T) {
|
||||
fecha := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
raw, err := BuildCotizacionExcel(CotizacionExcelData{
|
||||
RazonSocial: "URIEL JARETH CONSULTING",
|
||||
Numero: "UJ2606UR002",
|
||||
ClienteNombre: "Luis Torres",
|
||||
ClienteEmpresa: "Torres Corp",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: domain.CalcularVigencia(fecha),
|
||||
Moneda: "MXN",
|
||||
Proyecto: "Escalamiento",
|
||||
EsquemaPago: "Mensual",
|
||||
EsDoble: true,
|
||||
IncluirIVA: true,
|
||||
OpcionesMetadata: map[string]domain.MetaOpcion{
|
||||
"1": {Titulo: "Básico", Descripcion: "Plan inicial", NoIncluye: "Video"},
|
||||
"2": {Titulo: "Pro", Descripcion: "Plan avanzado", NoIncluye: "Pauta"},
|
||||
},
|
||||
Servicios: []ServicioExcel{
|
||||
{Nombre: "HOJA RESUMEN", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(5)},
|
||||
{Nombre: "Landing", Fase: 1, TipoPago: "unico", Precio: 10000, TiempoEntrega: "10 días", Opcion: str("1"), Horas: f64(10)},
|
||||
{Nombre: "Web Pro", Fase: 1, TipoPago: "unico", Precio: 20000, TiempoEntrega: "20 días", Opcion: str("2"), Horas: f64(25)},
|
||||
{Nombre: "Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
|
||||
},
|
||||
PlanBucefaloNivel: str("basico"),
|
||||
PlanBucefaloPrecio: f64(1200),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildCotizacionExcel doble error: %v", err)
|
||||
}
|
||||
|
||||
f, err := excelize.OpenReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("OpenReader error: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 1: Básico") {
|
||||
t.Errorf("missing OPCIÓN 1 banner")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 2: Pro") {
|
||||
t.Errorf("missing OPCIÓN 2 banner")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "COMPARATIVA DE OPCIONES") {
|
||||
t.Errorf("missing COMPARATIVA DE OPCIONES")
|
||||
}
|
||||
// Opción 1 único = (5000+10000)*1.16 = $17,400; Opción 2 único = (5000+20000)*1.16 = $29,000
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "$17,400") || !sheetContains(t, f, "HOJA RESUMEN", "$29,000") {
|
||||
t.Errorf("expected IVA-adjusted comparative totals $17,400 and $29,000")
|
||||
}
|
||||
if !sheetContains(t, f, "HOJA RESUMEN", "15 h") || !sheetContains(t, f, "HOJA RESUMEN", "30 h") {
|
||||
t.Errorf("expected comparative hours 15 h and 30 h")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogoCSVExportPlantillaAndParse(t *testing.T) {
|
||||
// 1. Plantilla parses cleanly into 6 rows.
|
||||
tpl := PlantillaCatalogoCSV()
|
||||
parsedTpl, err := ParseCatalogoCSV(tpl)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCatalogoCSV(PlantillaCatalogoCSV()) error: %v", err)
|
||||
}
|
||||
if len(parsedTpl) != 6 {
|
||||
t.Fatalf("expected 6 rows from plantilla, got %d", len(parsedTpl))
|
||||
}
|
||||
if parsedTpl[0].Nombre != "SEO On-Page Basico" || parsedTpl[0].Fase != 1 || parsedTpl[0].TipoPago != "unico" || parsedTpl[0].PrecioBase != 5000 {
|
||||
t.Errorf("unexpected first plantilla row: %+v", parsedTpl[0])
|
||||
}
|
||||
if len(parsedTpl[0].Entregables) != 3 {
|
||||
t.Errorf("expected 3 entregables in first row, got %v", parsedTpl[0].Entregables)
|
||||
}
|
||||
|
||||
// 2. Round-trip ExportCatalogoCSV -> ParseCatalogoCSV (including commas, quotes, BOM).
|
||||
orig := []CatalogoCSVRow{
|
||||
{
|
||||
Nombre: `Auditoría "Pro", Web & SEO`,
|
||||
Categoria: "SEO",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
PrecioBase: 4500.5,
|
||||
TiempoEntrega: "5 - 7 días",
|
||||
Entregables: []string{"Informe técnico", "Sesión de entrega"},
|
||||
Variante: "Premium",
|
||||
},
|
||||
{
|
||||
Nombre: "Gestión de Redes",
|
||||
Categoria: "Marketing",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
PrecioBase: 8000,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Calendario editorial", "Reporte mensual"},
|
||||
Variante: "",
|
||||
},
|
||||
}
|
||||
exported, err := ExportCatalogoCSV(orig)
|
||||
if err != nil {
|
||||
t.Fatalf("ExportCatalogoCSV error: %v", err)
|
||||
}
|
||||
|
||||
// Prepend UTF-8 BOM to verify BOM stripping too.
|
||||
withBOM := append([]byte{0xEF, 0xBB, 0xBF}, exported...)
|
||||
roundTrip, err := ParseCatalogoCSV(withBOM)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCatalogoCSV round-trip error: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(roundTrip, orig) {
|
||||
t.Fatalf("round-trip mismatch:\ngot: %+v\nwant: %+v", roundTrip, orig)
|
||||
}
|
||||
|
||||
// 3. Error cases.
|
||||
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\n")); err == nil {
|
||||
t.Errorf("expected error for header-only CSV")
|
||||
}
|
||||
if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\nFoo,Bar,Invalida,unico,-5\n")); err == nil {
|
||||
t.Errorf("expected error when no valid rows exist")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleAgentKeysList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdById", "createdAt", "updatedAt"
|
||||
FROM "AgentApiKey"
|
||||
ORDER BY "createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando claves de agente")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, prefijo string
|
||||
var scopes []string
|
||||
var rateLimit int
|
||||
var activo bool
|
||||
var revokedAt, lastUsedAt *time.Time
|
||||
var createdByID *string
|
||||
var createdAt, updatedAt time.Time
|
||||
if rows.Scan(&id, &nombre, &prefijo, &scopes, &rateLimit, &activo, &revokedAt, &lastUsedAt, &createdByID, &createdAt, &updatedAt) == nil {
|
||||
keys = append(keys, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"scopes": scopes,
|
||||
"rateLimitPerMin": rateLimit,
|
||||
"activo": activo,
|
||||
"revokedAt": revokedAt,
|
||||
"lastUsedAt": lastUsedAt,
|
||||
"createdById": createdByID,
|
||||
"createdAt": createdAt,
|
||||
"updatedAt": updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": keys, "scopesDisponibles": auth.AgentScopes})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin *int `json:"rateLimitPerMin"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
if nombre == "" || len(body.Scopes) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "nombre y scopes son requeridos")
|
||||
return
|
||||
}
|
||||
for _, sc := range body.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
writeError(w, http.StatusBadRequest, fmt.Sprintf("Scope invalido o no permitido: %s", sc))
|
||||
return
|
||||
}
|
||||
}
|
||||
rl := 60
|
||||
if body.RateLimitPerMin != nil {
|
||||
rl = *body.RateLimitPerMin
|
||||
if rl < 1 || rl > 1000 {
|
||||
writeError(w, http.StatusBadRequest, "rateLimitPerMin debe estar entre 1 y 1000")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdById", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, true, $7, NOW(), NOW())
|
||||
`, id, nombre, prefijo, keyHash, body.Scopes, rl, actor.UserID)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "duplicate") || strings.Contains(err.Error(), "23505") {
|
||||
writeError(w, http.StatusConflict, "Ya existe una clave con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando clave de agente")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.crear", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "scopes": body.Scopes, "rateLimitPerMin": rl},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"rawKey": rawKey,
|
||||
"scopes": body.Scopes,
|
||||
"rateLimitPerMin": rl,
|
||||
"activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysRotate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
|
||||
var nombre string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "prefijo" = $1, "keyHash" = $2, "activo" = true, "revokedAt" = NULL, "updatedAt" = NOW()
|
||||
WHERE "id" = $3
|
||||
RETURNING "nombre"
|
||||
`, prefijo, keyHash, id).Scan(&nombre)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Clave no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error rotando clave")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.rotar", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "prefijo": prefijo},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"prefijo": prefijo,
|
||||
"rawKey": rawKey,
|
||||
"activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentKeysRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var nombre string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "activo" = false, "revokedAt" = NOW(), "updatedAt" = NOW()
|
||||
WHERE "id" = $1
|
||||
RETURNING "nombre"
|
||||
`, id).Scan(&nombre)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Clave no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error revocando clave")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "agent_key.revocar", RecursoTipo: "agent_key", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "activo": false})
|
||||
}
|
||||
|
||||
func (s *Server) handleAuditLogs(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "audit_log"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := parseIntQuery(r, "page", 1, 1, 10000)
|
||||
limit := parseIntQuery(r, "limit", 50, 1, 200)
|
||||
offset := (page - 1) * limit
|
||||
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
addArg := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("accion")); v != "" {
|
||||
conds = append(conds, `"accion" = `+addArg(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("actorNombre")); v != "" {
|
||||
conds = append(conds, `"actorNombre" ILIKE `+addArg("%"+v+"%"))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("recursoId")); v != "" {
|
||||
conds = append(conds, `"recursoId" = `+addArg(v))
|
||||
}
|
||||
whereSQL := strings.Join(conds, " AND ")
|
||||
|
||||
var total int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "AuditLog" WHERE `+whereSQL, args...).Scan(&total)
|
||||
|
||||
limArg := addArg(limit)
|
||||
offArg := addArg(offset)
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle", "createdAt"
|
||||
FROM "AuditLog"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT `+limArg+` OFFSET `+offArg, args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando auditoria")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
data := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, actorTipo, actorNombre, accion, recursoTipo string
|
||||
var actorID, recursoID, ip, reqID *string
|
||||
var exito bool
|
||||
var detalle []byte
|
||||
var createdAt time.Time
|
||||
if rows.Scan(&id, &actorTipo, &actorID, &actorNombre, &accion, &recursoTipo, &recursoID, &ip, &reqID, &exito, &detalle, &createdAt) == nil {
|
||||
var det any
|
||||
if len(detalle) > 0 {
|
||||
_ = json.Unmarshal(detalle, &det)
|
||||
}
|
||||
data = append(data, map[string]any{
|
||||
"id": id, "actorTipo": actorTipo, "actorId": actorID, "actorNombre": actorNombre,
|
||||
"accion": accion, "recursoTipo": recursoTipo, "recursoId": recursoID,
|
||||
"ip": ip, "requestId": reqID, "exito": exito, "detalle": det, "createdAt": createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"data": data,
|
||||
"meta": map[string]any{"total": total, "page": page, "limit": limit},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "nombre", "url", "eventos", "activo", "createdAt", "updatedAt"
|
||||
FROM "WebhookEndpoint"
|
||||
ORDER BY "createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando webhooks")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, urlStr string
|
||||
var eventos []string
|
||||
var activo bool
|
||||
var createdAt, updatedAt time.Time
|
||||
if rows.Scan(&id, &nombre, &urlStr, &eventos, &activo, &createdAt, &updatedAt) == nil {
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "nombre": nombre, "url": urlStr, "eventos": eventos,
|
||||
"activo": activo, "createdAt": createdAt, "updatedAt": updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": list, "eventosDisponibles": webhooks.EventosOficiales})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"secret"`
|
||||
Eventos []string `json:"eventos"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
urlStr := strings.TrimSpace(body.URL)
|
||||
if nombre == "" || urlStr == "" || len(body.Eventos) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "nombre, url y eventos son requeridos")
|
||||
return
|
||||
}
|
||||
for _, ev := range body.Eventos {
|
||||
if !webhooks.EsEventoValido(ev) {
|
||||
writeError(w, http.StatusBadRequest, fmt.Sprintf("Evento invalido: %s", ev))
|
||||
return
|
||||
}
|
||||
}
|
||||
secret := strings.TrimSpace(body.Secret)
|
||||
if secret == "" {
|
||||
var b [24]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
secret = "whsec_" + hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "WebhookEndpoint" ("id", "nombre", "url", "secret", "eventos", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, true, NOW(), NOW())
|
||||
`, id, nombre, urlStr, secret, body.Eventos)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "23505") || strings.Contains(err.Error(), "duplicate") {
|
||||
writeError(w, http.StatusConflict, "Ya existe un webhook con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando webhook")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "webhook.crear", RecursoTipo: "webhook", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "url": urlStr, "eventos": body.Eventos},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id, "nombre": nombre, "url": urlStr, "secret": secret, "eventos": body.Eventos, "activo": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksDelete(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "WebhookEndpoint" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Webhook no encontrado")
|
||||
return
|
||||
}
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "webhook.eliminar", RecursoTipo: "webhook", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebhooksDeliveries(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
limit := parseIntQuery(r, "limit", 50, 1, 200)
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
if ev := strings.TrimSpace(q.Get("evento")); ev != "" {
|
||||
args = append(args, ev)
|
||||
conds = append(conds, fmt.Sprintf(`"evento" = $%d`, len(args)))
|
||||
}
|
||||
if eid := strings.TrimSpace(q.Get("endpointId")); eid != "" {
|
||||
args = append(args, eid)
|
||||
conds = append(conds, fmt.Sprintf(`"endpointId" = $%d`, len(args)))
|
||||
}
|
||||
args = append(args, limit)
|
||||
rows, err := s.Pool.Query(r.Context(), fmt.Sprintf(`
|
||||
SELECT "id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error", "createdAt"
|
||||
FROM "WebhookDelivery"
|
||||
WHERE %s
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT $%d
|
||||
`, strings.Join(conds, " AND "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando entregas de webhooks")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, urlStr, evento string
|
||||
var endpointID, errStr *string
|
||||
var payload []byte
|
||||
var statusCode *int
|
||||
var exito bool
|
||||
var intentos int
|
||||
var createdAt time.Time
|
||||
if rows.Scan(&id, &endpointID, &urlStr, &evento, &payload, &statusCode, &exito, &intentos, &errStr, &createdAt) == nil {
|
||||
var p any
|
||||
_ = json.Unmarshal(payload, &p)
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "endpointId": endpointID, "url": urlStr, "evento": evento,
|
||||
"payload": p, "statusCode": statusCode, "exito": exito, "intentos": intentos,
|
||||
"error": errStr, "createdAt": createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": list})
|
||||
}
|
||||
|
||||
var configAllowedKeys = map[string]bool{
|
||||
"razon_social": true,
|
||||
"rfc": true,
|
||||
"domicilio_fiscal": true,
|
||||
"banco_nacional": true,
|
||||
"cuenta_nacional": true,
|
||||
"clabe_interbancaria": true,
|
||||
"clabe_nacional": true,
|
||||
"banco_internacional": true,
|
||||
"cuenta_internacional": true,
|
||||
"cuenta_internacional_swift": true,
|
||||
"swift": true,
|
||||
"routing_number": true,
|
||||
"hora_centinela": true,
|
||||
"anualidad_hosting": true,
|
||||
"iva": true,
|
||||
"terminos_condiciones": true,
|
||||
"no_incluye": true,
|
||||
"notas_adicionales": true,
|
||||
"nota_legal": true,
|
||||
"color_primario": true,
|
||||
"color_secundario": true,
|
||||
"logo_base64": true,
|
||||
"email_facturacion": true,
|
||||
"telefono_contacto": true,
|
||||
}
|
||||
|
||||
func (s *Server) handleConfiguracionGet(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context()))
|
||||
}
|
||||
|
||||
func (s *Server) handleConfiguracionPut(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok {
|
||||
return
|
||||
}
|
||||
var body map[string]string
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
for k, v := range body {
|
||||
if !configAllowedKeys[k] {
|
||||
continue
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT ("clave") DO UPDATE SET "valor" = EXCLUDED."valor", "updatedAt" = NOW()
|
||||
`, db.NewID(), k, v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando configuracion")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context()))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
var one int
|
||||
if err := s.Pool.QueryRow(ctx, "SELECT 1").Scan(&one); err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"status": "error",
|
||||
"db": "disconnected",
|
||||
"version": "3.0.0-go",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"db": "connected",
|
||||
"runtime": "go",
|
||||
"version": "3.0.0-go",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleOpenAPI(w http.ResponseWriter, r *http.Request) {
|
||||
serverURL := s.Cfg.AppURL
|
||||
if serverURL == "" {
|
||||
serverURL = "https://cotizador.urieljareth.org"
|
||||
}
|
||||
spec := map[string]any{
|
||||
"openapi": "3.1.0",
|
||||
"info": map[string]any{
|
||||
"title": "Cotizador — Uriel Jareth Consulting API",
|
||||
"version": "3.0.0",
|
||||
"description": "API unificada en Go para agentes de IA y operacion comercial de Uriel Jareth Consulting. " +
|
||||
"Autenticacion por cookie JWT (usuarios humanos) o X-API-Key / Bearer ujc_live_* (agentes con alcances granulares). " +
|
||||
"Ningun agente puede aprobar cotizaciones: la aprobacion es exclusivamente humana (panel admin o enlace firmado de un solo uso).",
|
||||
},
|
||||
"servers": []map[string]any{{"url": serverURL}},
|
||||
"components": map[string]any{
|
||||
"securitySchemes": map[string]any{
|
||||
"ApiKeyAuth": map[string]any{"type": "apiKey", "in": "header", "name": "X-API-Key"},
|
||||
"BearerAuth": map[string]any{"type": "http", "scheme": "bearer"},
|
||||
"CookieAuth": map[string]any{"type": "apiKey", "in": "cookie", "name": auth.SessionCookieName},
|
||||
},
|
||||
"schemas": map[string]any{
|
||||
"AgentScope": map[string]any{"type": "string", "enum": auth.AgentScopes},
|
||||
"EstadoCotizacion": map[string]any{"type": "string", "enum": domain.EstadosCotizacion},
|
||||
"WebhookEvent": map[string]any{"type": "string", "enum": webhooks.EventosOficiales},
|
||||
},
|
||||
},
|
||||
"security": []map[string]any{{"ApiKeyAuth": []any{}}, {"BearerAuth": []any{}}, {"CookieAuth": []any{}}},
|
||||
"paths": map[string]any{
|
||||
"/api/health": map[string]any{"get": map[string]any{"summary": "Estado de salud del servicio y BD", "security": []any{}}},
|
||||
"/api/catalogo": map[string]any{"get": map[string]any{"summary": "Listar catalogo de servicios (scope: catalogo:leer)"}, "post": map[string]any{"summary": "Crear servicio (staff)"}},
|
||||
"/api/catalogo/{id}": map[string]any{"get": map[string]any{"summary": "Detalle de servicio (scope: catalogo:leer; 403 si soloAdmin para agentes)"}},
|
||||
"/api/categorias": map[string]any{"get": map[string]any{"summary": "Listar categorias (scope: catalogo:leer)"}},
|
||||
"/api/paquetes": map[string]any{"get": map[string]any{"summary": "Listar paquetes activos (scope: catalogo:leer)"}},
|
||||
"/api/clientes": map[string]any{"get": map[string]any{"summary": "Listar clientes (scope: clientes:leer)"}, "post": map[string]any{"summary": "Crear cliente (scope: clientes:escribir, idempotente)"}},
|
||||
"/api/clientes/{id}": map[string]any{"patch": map[string]any{"summary": "Actualizar cliente (scope: clientes:escribir)"}},
|
||||
"/api/clientes/{id}/archivar": map[string]any{"post": map[string]any{"summary": "Archivar/desarchivar cliente (staff)"}},
|
||||
"/api/cotizaciones": map[string]any{"get": map[string]any{"summary": "Listar cotizaciones (cotizaciones:leer | cotizaciones:leer_aceptadas)"}, "post": map[string]any{"summary": "Crear borrador (cotizaciones:borrador, idempotente)"}},
|
||||
"/api/cotizaciones/{id}": map[string]any{"get": map[string]any{"summary": "Detalle cotizacion (?verificarContacto=...)"}, "put": map[string]any{"summary": "Editar borrador"}, "delete": map[string]any{"summary": "Eliminar cotizacion (staff)"}},
|
||||
"/api/cotizaciones/{id}/solicitar-aprobacion": map[string]any{"post": map[string]any{"summary": "Reenviar enlace de aprobacion a Jareth"}},
|
||||
"/api/cotizaciones/{id}/aprobar": map[string]any{"post": map[string]any{"summary": "Aprobar cotizacion (EXCLUSIVO admin humano)"}},
|
||||
"/api/cotizaciones/{id}/enviar": map[string]any{"post": map[string]any{"summary": "Enviar cotizacion aprobada (cotizaciones:enviar, idempotente)"}},
|
||||
"/api/cotizaciones/{id}/estado": map[string]any{"patch": map[string]any{"summary": "Cambiar estado (staff)"}},
|
||||
"/api/cotizaciones/{id}/precio": map[string]any{"patch": map[string]any{"summary": "Actualizar precio de partida"}},
|
||||
"/api/aprobar/{token}": map[string]any{"get": map[string]any{"summary": "Resumen de aprobacion firmado", "security": []any{}}, "post": map[string]any{"summary": "Confirmar aprobacion de un solo uso", "security": []any{}}},
|
||||
"/api/cobros/programas": map[string]any{"get": map[string]any{"summary": "Listar programas recurrentes (cobros:leer)"}},
|
||||
"/api/cobros/pagos": map[string]any{"get": map[string]any{"summary": "Listar cobros recurrentes (cobros:leer)"}},
|
||||
"/api/cobros/pagos/{id}/registrar": map[string]any{"post": map[string]any{"summary": "Registrar pago manual (cobros:registrar, idempotente)"}},
|
||||
"/api/export/pdf/{id}": map[string]any{"get": map[string]any{"summary": "Exportar PDF de cotizacion"}},
|
||||
"/api/agent-keys": map[string]any{"get": map[string]any{"summary": "Listar claves de agente (admin)"}, "post": map[string]any{"summary": "Crear clave de agente (admin)"}},
|
||||
"/api/audit-logs": map[string]any{"get": map[string]any{"summary": "Consultar auditoria (admin)"}},
|
||||
"/api/webhooks": map[string]any{"get": map[string]any{"summary": "Listar webhooks (admin)"}, "post": map[string]any{"summary": "Registrar webhook (admin)"}},
|
||||
},
|
||||
}
|
||||
writeJSON(w, http.StatusOK, spec)
|
||||
}
|
||||
|
||||
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Datos de acceso invalidos")
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(body.Email))
|
||||
if email == "" || body.Password == "" {
|
||||
writeError(w, http.StatusBadRequest, "Email y contrasena requeridos")
|
||||
return
|
||||
}
|
||||
|
||||
var id, dbEmail, passHash, name, role string
|
||||
var clienteID *string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "email", "password", "name", "role", "clienteId"
|
||||
FROM "User"
|
||||
WHERE LOWER("email") = $1
|
||||
LIMIT 1
|
||||
`, email).Scan(&id, &dbEmail, &passHash, &name, &role, &clienteID)
|
||||
if err != nil || !auth.ComparePassword(passHash, body.Password) {
|
||||
writeError(w, http.StatusUnauthorized, "Credenciales invalidas")
|
||||
return
|
||||
}
|
||||
if role == "" {
|
||||
role = "asesor"
|
||||
}
|
||||
cid := ""
|
||||
if clienteID != nil {
|
||||
cid = *clienteID
|
||||
}
|
||||
|
||||
payload := auth.SessionPayload{
|
||||
UserID: id,
|
||||
Email: dbEmail,
|
||||
Name: name,
|
||||
Role: role,
|
||||
ClienteID: cid,
|
||||
}
|
||||
tok, err := s.Auth.SignSession(payload)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando sesion")
|
||||
return
|
||||
}
|
||||
s.Auth.SetSessionCookie(w, tok)
|
||||
|
||||
respUser := map[string]any{
|
||||
"id": id,
|
||||
"userId": id,
|
||||
"email": dbEmail,
|
||||
"name": name,
|
||||
"role": role,
|
||||
}
|
||||
if cid != "" {
|
||||
respUser["clienteId"] = cid
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": respUser})
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// handleMe returns the authenticated cookie session user (for both staff and cliente).
|
||||
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "No autenticado")
|
||||
return
|
||||
}
|
||||
user := map[string]any{
|
||||
"userId": sess.UserID,
|
||||
"email": sess.Email,
|
||||
"name": sess.Name,
|
||||
"role": sess.Role,
|
||||
}
|
||||
if sess.ClienteID != "" {
|
||||
user["clienteId"] = sess.ClienteID
|
||||
if s.Pool != nil {
|
||||
var clienteNombre string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, sess.ClienteID).Scan(&clienteNombre); err == nil {
|
||||
user["clienteNombre"] = clienteNombre
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
// handleAsesores returns safe staff user list + next quote sequence for CotizacionForm.
|
||||
func (s *Server) handleAsesores(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "asesor"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "name", "email", "role"
|
||||
FROM "User"
|
||||
WHERE "role" <> 'cliente'
|
||||
ORDER BY "name" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando asesores")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
asesores := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, name, email, role string
|
||||
if rows.Scan(&id, &name, &email, &role) == nil {
|
||||
asesores = append(asesores, map[string]any{
|
||||
"id": id,
|
||||
"name": name,
|
||||
"email": email,
|
||||
"role": role,
|
||||
"iniciales": asesorInitials(name),
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"asesores": asesores,
|
||||
"nextSeq": s.nextCotizacionSeq(r.Context()),
|
||||
})
|
||||
}
|
||||
|
||||
// handleDashboard provides summary counts + 10 recent quotes for the SPA dashboard.
|
||||
func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "dashboard"}); !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
var totalCot, totalCli, totalSvc int
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "archivado" = false`).Scan(&totalCot)
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cliente" WHERE "archivado" = false`).Scan(&totalCli)
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "activo" = true`).Scan(&totalSvc)
|
||||
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT q."id", q."numero", q."fecha", q."vigencia", q."proyecto", q."estado",
|
||||
q."moneda", q."esDoble", q."incluirIva",
|
||||
c."id", c."nombre", COALESCE(c."empresa", '')
|
||||
FROM "Cotizacion" q
|
||||
JOIN "Cliente" c ON c."id" = q."clienteId"
|
||||
WHERE q."archivado" = false
|
||||
ORDER BY q."createdAt" DESC
|
||||
LIMIT 10
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando dashboard")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
recientes := []map[string]any{}
|
||||
var cotIDs []string
|
||||
for rows.Next() {
|
||||
var id, numero, proyecto, estado, moneda, cid, cnombre, cempresa string
|
||||
var fecha, vigencia time.Time
|
||||
var esDoble, incluirIva bool
|
||||
if rows.Scan(&id, &numero, &fecha, &vigencia, &proyecto, &estado, &moneda, &esDoble, &incluirIva, &cid, &cnombre, &cempresa) == nil {
|
||||
cotIDs = append(cotIDs, id)
|
||||
recientes = append(recientes, map[string]any{
|
||||
"id": id,
|
||||
"numero": numero,
|
||||
"fecha": fecha,
|
||||
"vigencia": vigencia,
|
||||
"proyecto": proyecto,
|
||||
"estado": estado,
|
||||
"moneda": moneda,
|
||||
"esDoble": esDoble,
|
||||
"incluirIva": incluirIva,
|
||||
"cliente": map[string]any{
|
||||
"id": cid,
|
||||
"nombre": cnombre,
|
||||
"empresa": nullableStr(cempresa),
|
||||
},
|
||||
"servicios": []any{},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(cotIDs) > 0 {
|
||||
svcRows, err := s.Pool.Query(ctx, `
|
||||
SELECT "cotizacionId", "tipoPago", "precio", "seleccionado", "opcion"
|
||||
FROM "ServicioCotizado"
|
||||
WHERE "cotizacionId" = ANY($1)
|
||||
`, cotIDs)
|
||||
if err == nil {
|
||||
defer svcRows.Close()
|
||||
byCot := map[string][]map[string]any{}
|
||||
for svcRows.Next() {
|
||||
var qid, tipoPago string
|
||||
var precio float64
|
||||
var sel bool
|
||||
var opcion *string
|
||||
if svcRows.Scan(&qid, &tipoPago, &precio, &sel, &opcion) == nil {
|
||||
byCot[qid] = append(byCot[qid], map[string]any{
|
||||
"tipoPago": tipoPago,
|
||||
"precio": precio,
|
||||
"seleccionado": sel,
|
||||
"opcion": opcion,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, item := range recientes {
|
||||
if svcs, ok := byCot[item["id"].(string)]; ok {
|
||||
item["servicios"] = svcs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"totalCotizaciones": totalCot,
|
||||
"totalClientes": totalCli,
|
||||
"totalServicios": totalSvc,
|
||||
"cotizacionesRecientes": recientes,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAprobarTokenGet(w http.ResponseWriter, r *http.Request) {
|
||||
rawToken := strings.TrimSpace(chi.URLParam(r, "token"))
|
||||
if rawToken == "" {
|
||||
writeError(w, http.StatusNotFound, "Enlace invalido")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashSecret(rawToken)
|
||||
|
||||
var tokID, cotID, numero, proyecto, estado, moneda, cNombre string
|
||||
var cEmpresa, cEmail, creadaPorAgente *string
|
||||
var expiraAt time.Time
|
||||
var usadoAt *time.Time
|
||||
var incluirIva, esDoble bool
|
||||
var fecha, vigencia time.Time
|
||||
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt",
|
||||
q."numero", q."proyecto", q."estado", q."moneda", q."incluirIva", q."esDoble", q."fecha", q."vigencia", q."creadaPorAgente",
|
||||
c."nombre", c."empresa", c."email"
|
||||
FROM "ApprovalToken" t
|
||||
JOIN "Cotizacion" q ON q."id" = t."cotizacionId"
|
||||
JOIN "Cliente" c ON c."id" = q."clienteId"
|
||||
WHERE t."tokenHash" = $1
|
||||
`, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &numero, &proyecto, &estado, &moneda, &incluirIva, &esDoble, &fecha, &vigencia, &creadaPorAgente, &cNombre, &cEmpresa, &cEmail)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando enlace")
|
||||
return
|
||||
}
|
||||
|
||||
if usadoAt != nil {
|
||||
writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ya fue utilizado", "usado": true})
|
||||
return
|
||||
}
|
||||
if time.Now().After(expiraAt) {
|
||||
writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ha expirado", "expirado": true})
|
||||
return
|
||||
}
|
||||
|
||||
svcRows, _ := s.Pool.Query(r.Context(), `
|
||||
SELECT s."id", COALESCE(s."nombre", sc."nombre", 'Servicio'), s."fase", s."tipoPago", s."precio", s."tiempoEntrega", s."seleccionado", s."modeloCobro", s."opcion"
|
||||
FROM "ServicioCotizado" s
|
||||
LEFT JOIN "ServicioCatalogo" sc ON sc."id" = s."servicioCatalogoId"
|
||||
WHERE s."cotizacionId" = $1
|
||||
ORDER BY s."fase" ASC, s."createdAt" ASC
|
||||
`, cotID)
|
||||
partidas := []map[string]any{}
|
||||
var calcSvcs []domain.ServicioCalc
|
||||
if svcRows != nil {
|
||||
defer svcRows.Close()
|
||||
for svcRows.Next() {
|
||||
var sid, nom, tp, te, mc string
|
||||
var fase int
|
||||
var precio float64
|
||||
var sel bool
|
||||
var op *string
|
||||
if svcRows.Scan(&sid, &nom, &fase, &tp, &precio, &te, &sel, &mc, &op) == nil {
|
||||
partidas = append(partidas, map[string]any{
|
||||
"id": sid, "nombre": nom, "fase": fase, "tipoPago": tp, "precio": precio,
|
||||
"tiempoEntrega": te, "seleccionado": sel, "modeloCobro": mc, "opcion": op,
|
||||
})
|
||||
calcSvcs = append(calcSvcs, domain.ServicioCalc{
|
||||
Nombre: nom, TipoPago: tp, Precio: precio, Seleccionado: sel, ModeloCobro: mc, Opcion: op,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
totales := domain.CalcularTotalesCotizacion(calcSvcs, incluirIva)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"cotizacion": map[string]any{
|
||||
"id": cotID,
|
||||
"numero": numero,
|
||||
"proyecto": proyecto,
|
||||
"estado": estado,
|
||||
"moneda": moneda,
|
||||
"incluirIva": incluirIva,
|
||||
"esDoble": esDoble,
|
||||
"fecha": fecha,
|
||||
"vigencia": vigencia,
|
||||
"creadaPorAgente": creadaPorAgente,
|
||||
"cliente": map[string]any{
|
||||
"nombre": cNombre,
|
||||
"empresa": cEmpresa,
|
||||
"email": cEmail,
|
||||
},
|
||||
"totales": totales,
|
||||
"partidas": partidas,
|
||||
"servicios": partidas,
|
||||
},
|
||||
"puedeAprobar": estado == "borrador",
|
||||
"totales": totales,
|
||||
"expiraAt": expiraAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAprobarTokenPost(w http.ResponseWriter, r *http.Request) {
|
||||
rawToken := strings.TrimSpace(chi.URLParam(r, "token"))
|
||||
var body struct {
|
||||
Confirmar bool `json:"confirmar"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || !body.Confirmar {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere confirmar: true para aprobar la cotizacion")
|
||||
return
|
||||
}
|
||||
tokenHash := auth.HashSecret(rawToken)
|
||||
ip := audit.ClientIP(r)
|
||||
|
||||
tx, err := s.Pool.Begin(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error iniciando transaccion")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
|
||||
var tokID, cotID, estado, numero string
|
||||
var expiraAt time.Time
|
||||
var usadoAt *time.Time
|
||||
err = tx.QueryRow(r.Context(), `
|
||||
SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt", q."estado", q."numero"
|
||||
FROM "ApprovalToken" t
|
||||
JOIN "Cotizacion" q ON q."id" = t."cotizacionId"
|
||||
WHERE t."tokenHash" = $1
|
||||
FOR UPDATE OF t, q
|
||||
`, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &estado, &numero)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error validando enlace")
|
||||
return
|
||||
}
|
||||
if usadoAt != nil || time.Now().After(expiraAt) {
|
||||
writeError(w, http.StatusGone, "El enlace de aprobacion ya fue usado o expiro")
|
||||
return
|
||||
}
|
||||
|
||||
tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{
|
||||
Actual: estado,
|
||||
Nuevo: "aprobada",
|
||||
Actor: domain.ActorInfo{Type: "enlace_firmado"},
|
||||
ViaEndpoint: "enlace_firmado",
|
||||
})
|
||||
if !tr.OK {
|
||||
writeError(w, tr.Status, tr.Error)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
UPDATE "ApprovalToken" SET "usadoAt" = $1, "usadoIp" = $2 WHERE "id" = $3
|
||||
`, now, ip, tokID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error consumiendo enlace")
|
||||
return
|
||||
}
|
||||
// Invalidate sibling open tokens
|
||||
_, _ = tx.Exec(r.Context(), `
|
||||
UPDATE "ApprovalToken" SET "usadoAt" = $1 WHERE "cotizacionId" = $2 AND "usadoAt" IS NULL
|
||||
`, now, cotID)
|
||||
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
UPDATE "Cotizacion"
|
||||
SET "estado" = 'aprobada', "aprobadaAt" = $1, "aprobacionMetodo" = 'enlace_firmado', "updatedAt" = NOW()
|
||||
WHERE "id" = $2
|
||||
`, now, cotID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error aprobando cotizacion")
|
||||
return
|
||||
}
|
||||
if err := tx.Commit(r.Context()); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error confirmando aprobacion")
|
||||
return
|
||||
}
|
||||
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: "system",
|
||||
ActorNombre: "enlace_firmado",
|
||||
Accion: "cotizacion.aprobar",
|
||||
RecursoTipo: "cotizacion",
|
||||
RecursoID: cotID,
|
||||
IP: ip,
|
||||
RequestID: audit.RequestID(r),
|
||||
Exito: true,
|
||||
Detalle: map[string]any{"numero": numero, "metodo": "enlace_firmado"},
|
||||
})
|
||||
|
||||
go s.Webhooks.Emitir(context.Background(), "cotizacion.aprobada", map[string]any{
|
||||
"cotizacionId": cotID,
|
||||
"numero": numero,
|
||||
"estado": "aprobada",
|
||||
"aprobacionMetodo": "enlace_firmado",
|
||||
"aprobadaAt": now.UTC().Format(time.RFC3339),
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"cotizacionId": cotID,
|
||||
"numero": numero,
|
||||
"estado": "aprobada",
|
||||
"aprobadaAt": now,
|
||||
})
|
||||
}
|
||||
|
||||
func nullableStr(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func parseJSONRawOrEmptyArray(raw []byte) any {
|
||||
if len(raw) == 0 {
|
||||
return []any{}
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return []any{}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/excel"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryServicioCatalogo(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT sc."id", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago", sc."precioBase",
|
||||
sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel",
|
||||
sc."activo", sc."soloAdmin", sc."orden",
|
||||
c."nombre", c."color",
|
||||
(SELECT COUNT(*) FROM "ServicioCotizado" cot WHERE cot."servicioCatalogoId" = sc."id") AS en_cotizaciones
|
||||
FROM "ServicioCatalogo" sc
|
||||
LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY sc."fase" ASC, sc."orden" ASC, sc."nombre" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, tipoPago, tiempoEntrega string
|
||||
var descripcion, categoriaID, variante, nivel, catNombre, catColor *string
|
||||
var fase, orden, enCot int
|
||||
var precioBase float64
|
||||
var entregablesRaw []byte
|
||||
var activo, soloAdmin bool
|
||||
if err := rows.Scan(
|
||||
&id, &nombre, &descripcion, &fase, &tipoPago, &precioBase,
|
||||
&tiempoEntrega, &entregablesRaw, &categoriaID, &variante, &nivel,
|
||||
&activo, &soloAdmin, &orden,
|
||||
&catNombre, &catColor, &enCot,
|
||||
); err != nil {
|
||||
continue
|
||||
}
|
||||
var entregables []string
|
||||
_ = json.Unmarshal(entregablesRaw, &entregables)
|
||||
if entregables == nil {
|
||||
entregables = []string{}
|
||||
}
|
||||
var catRel any
|
||||
if categoriaID != nil && catNombre != nil {
|
||||
catRel = map[string]any{"id": *categoriaID, "nombre": *catNombre, "color": catColor}
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"descripcion": descripcion,
|
||||
"fase": fase,
|
||||
"tipoPago": tipoPago,
|
||||
"precioBase": precioBase,
|
||||
"tiempoEntrega": tiempoEntrega,
|
||||
"entregablesDefault": entregables,
|
||||
"categoriaId": categoriaID,
|
||||
"categoriaNombre": catNombre,
|
||||
"categoriaColor": catColor,
|
||||
"categoriaRel": catRel,
|
||||
"variante": variante,
|
||||
"nivel": nivel,
|
||||
"activo": activo,
|
||||
"soloAdmin": soloAdmin,
|
||||
"orden": orden,
|
||||
"enCotizaciones": enCot,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
|
||||
if actor.IsAgent() {
|
||||
conds = append(conds, `sc."soloAdmin" = false`)
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("q")); v != "" {
|
||||
p := add("%" + v + "%")
|
||||
conds = append(conds, fmt.Sprintf(`(sc."nombre" ILIKE %s OR COALESCE(sc."descripcion", '') ILIKE %s OR COALESCE(sc."variante", '') ILIKE %s)`, p, p, p))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("fase")); v != "" {
|
||||
if f, err := strconv.Atoi(v); err == nil {
|
||||
conds = append(conds, `sc."fase" = `+add(f))
|
||||
}
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("tipoPago")); v != "" {
|
||||
conds = append(conds, `sc."tipoPago" = `+add(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("categoriaId")); v != "" {
|
||||
conds = append(conds, `sc."categoriaId" = `+add(v))
|
||||
}
|
||||
if v := strings.TrimSpace(q.Get("activo")); v == "true" || v == "false" {
|
||||
conds = append(conds, `sc."activo" = `+add(v == "true"))
|
||||
}
|
||||
|
||||
list, err := s.queryServicioCatalogo(r.Context(), strings.Join(conds, " AND "), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando catalogo")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoGet(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
list, err := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if err != nil || len(list) == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
svc := list[0]
|
||||
if actor.IsAgent() && svc["soloAdmin"] == true {
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "catalogo.solo_admin_bloqueado", RecursoTipo: "catalogo", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
||||
})
|
||||
writeError(w, http.StatusForbidden, "Servicio restringido para administradores")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, svc)
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
var detalles []ValidationDetail
|
||||
nombre := strings.TrimSpace(asString(raw["nombre"]))
|
||||
if nombre == "" {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "nombre", Mensaje: "El nombre es obligatorio"})
|
||||
}
|
||||
fase, faseOK := asInt(raw["fase"])
|
||||
if !faseOK || fase < 0 || fase > 3 {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "fase", Mensaje: "La fase debe ser 0, 1, 2 o 3"})
|
||||
}
|
||||
tipoPago := strings.TrimSpace(asString(raw["tipoPago"]))
|
||||
if tipoPago != "unico" && tipoPago != "mensual" {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "tipoPago", Mensaje: "tipoPago debe ser unico o mensual"})
|
||||
}
|
||||
precioBase, precioOK := asFloat(raw["precioBase"])
|
||||
if !precioOK || precioBase < 0 {
|
||||
detalles = append(detalles, ValidationDetail{Campo: "precioBase", Mensaje: "precioBase debe ser >= 0"})
|
||||
}
|
||||
if len(detalles) > 0 {
|
||||
writeValidationError(w, detalles)
|
||||
return
|
||||
}
|
||||
|
||||
var categoriaID *string
|
||||
if cid := strings.TrimSpace(asString(raw["categoriaId"])); cid != "" {
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&exists)
|
||||
if !exists {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}})
|
||||
return
|
||||
}
|
||||
categoriaID = &cid
|
||||
}
|
||||
|
||||
orden, hasOrden := asInt(raw["orden"])
|
||||
if !hasOrden {
|
||||
var maxOrden int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) FROM "ServicioCatalogo" WHERE "fase" = $1`, fase).Scan(&maxOrden)
|
||||
orden = maxOrden + 1
|
||||
}
|
||||
|
||||
tiempoEntrega := firstNonEmptyStr(asString(raw["tiempoEntrega"]), "4 - 10 dias")
|
||||
entregables := asStringSlice(raw["entregablesDefault"])
|
||||
entJSON, _ := json.Marshal(entregables)
|
||||
|
||||
activo := true
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
activo = v
|
||||
}
|
||||
soloAdmin := false
|
||||
if v, ok := raw["soloAdmin"].(bool); ok {
|
||||
soloAdmin = v
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "descripcion", "fase", "tipoPago", "precioBase",
|
||||
"tiempoEntrega", "entregablesDefault", "categoriaId", "variante", "nivel",
|
||||
"activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,NOW(),NOW())
|
||||
`, id, nombre, nullableTrim(asString(raw["descripcion"])), fase, tipoPago, precioBase,
|
||||
tiempoEntrega, entJSON, categoriaID, nullableTrim(asString(raw["variante"])), nullableTrim(asString(raw["nivel"])),
|
||||
activo, soloAdmin, orden)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando servicio")
|
||||
return
|
||||
}
|
||||
|
||||
list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusCreated, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoPatch(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "ServicioCatalogo" WHERE "id" = $1)`, id).Scan(&exists)
|
||||
if !exists {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
|
||||
if v, ok := raw["nombre"]; ok {
|
||||
nom := strings.TrimSpace(asString(v))
|
||||
if nom == "" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}})
|
||||
return
|
||||
}
|
||||
add("nombre", nom)
|
||||
}
|
||||
if v, ok := raw["descripcion"]; ok {
|
||||
add("descripcion", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["fase"]; ok {
|
||||
f, okInt := asInt(v)
|
||||
if !okInt || f < 0 || f > 3 {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "fase", Mensaje: "Fase invalida"}})
|
||||
return
|
||||
}
|
||||
add("fase", f)
|
||||
}
|
||||
if v, ok := raw["tipoPago"]; ok {
|
||||
tp := strings.TrimSpace(asString(v))
|
||||
if tp != "unico" && tp != "mensual" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "tipoPago", Mensaje: "tipoPago invalido"}})
|
||||
return
|
||||
}
|
||||
add("tipoPago", tp)
|
||||
}
|
||||
if v, ok := raw["precioBase"]; ok {
|
||||
pb, okF := asFloat(v)
|
||||
if !okF || pb < 0 {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "precioBase", Mensaje: "precioBase invalido"}})
|
||||
return
|
||||
}
|
||||
add("precioBase", pb)
|
||||
}
|
||||
if v, ok := raw["tiempoEntrega"]; ok {
|
||||
add("tiempoEntrega", firstNonEmptyStr(asString(v), "4 - 10 dias"))
|
||||
}
|
||||
if v, ok := raw["entregablesDefault"]; ok {
|
||||
entJSON, _ := json.Marshal(asStringSlice(v))
|
||||
add("entregablesDefault", entJSON)
|
||||
}
|
||||
if v, ok := raw["categoriaId"]; ok {
|
||||
cid := strings.TrimSpace(asString(v))
|
||||
if cid == "" {
|
||||
add("categoriaId", nil)
|
||||
} else {
|
||||
var catOK bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&catOK)
|
||||
if !catOK {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}})
|
||||
return
|
||||
}
|
||||
add("categoriaId", cid)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["variante"]; ok {
|
||||
add("variante", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["nivel"]; ok {
|
||||
add("nivel", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
add("activo", v)
|
||||
}
|
||||
if v, ok := raw["soloAdmin"].(bool); ok {
|
||||
add("soloAdmin", v)
|
||||
}
|
||||
if v, ok := raw["orden"]; ok {
|
||||
if ord, okInt := asInt(v); okInt {
|
||||
add("orden", ord)
|
||||
}
|
||||
}
|
||||
|
||||
args = append(args, id)
|
||||
_, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ServicioCatalogo" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando servicio")
|
||||
return
|
||||
}
|
||||
|
||||
list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusOK, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCatalogoDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var enCot int
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCotizado" WHERE "servicioCatalogoId" = $1`, id).Scan(&enCot); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error verificando uso del servicio")
|
||||
return
|
||||
}
|
||||
if enCot > 0 {
|
||||
tag, err := s.Pool.Exec(r.Context(), `UPDATE "ServicioCatalogo" SET "activo" = false, "updatedAt" = NOW() WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "archivado": true, "enCotizaciones": enCot})
|
||||
return
|
||||
}
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "ServicioCatalogo" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Servicio no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "eliminado": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT c."id", c."nombre", c."descripcion", c."color", c."activo", c."orden",
|
||||
(SELECT COUNT(*) FROM "ServicioCatalogo" sc WHERE sc."categoriaId" = c."id") AS servicios_count
|
||||
FROM "Categoria" c
|
||||
ORDER BY c."orden" ASC, c."nombre" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando categorias")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre, color string
|
||||
var desc *string
|
||||
var activo bool
|
||||
var orden, cnt int
|
||||
if rows.Scan(&id, &nombre, &desc, &color, &activo, &orden, &cnt) == nil {
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden,
|
||||
"_count": map[string]any{"servicios": cnt},
|
||||
})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Color string `json:"color"`
|
||||
Orden *int `json:"orden"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" {
|
||||
writeError(w, http.StatusBadRequest, "El nombre es obligatorio")
|
||||
return
|
||||
}
|
||||
color := firstNonEmptyStr(body.Color, "#6b7280")
|
||||
orden := 0
|
||||
if body.Orden != nil {
|
||||
orden = *body.Orden
|
||||
} else {
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) + 1 FROM "Categoria"`).Scan(&orden)
|
||||
}
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW())
|
||||
`, id, strings.TrimSpace(body.Nombre), body.Descripcion, color, orden)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "23505") {
|
||||
writeError(w, http.StatusConflict, "Ya existe una categoria con ese nombre")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error creando categoria")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": id, "nombre": strings.TrimSpace(body.Nombre), "descripcion": body.Descripcion, "color": color, "activo": true, "orden": orden,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Nombre *string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Color *string `json:"color"`
|
||||
Activo *bool `json:"activo"`
|
||||
Orden *int `json:"orden"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if body.Nombre != nil {
|
||||
add("nombre", strings.TrimSpace(*body.Nombre))
|
||||
}
|
||||
if body.Descripcion != nil {
|
||||
add("descripcion", *body.Descripcion)
|
||||
}
|
||||
if body.Color != nil {
|
||||
add("color", *body.Color)
|
||||
}
|
||||
if body.Activo != nil {
|
||||
add("activo", *body.Activo)
|
||||
}
|
||||
if body.Orden != nil {
|
||||
add("orden", *body.Orden)
|
||||
}
|
||||
args = append(args, id)
|
||||
var nombre, color string
|
||||
var desc *string
|
||||
var activo bool
|
||||
var orden int
|
||||
err := s.Pool.QueryRow(r.Context(), fmt.Sprintf(`
|
||||
UPDATE "Categoria" SET %s WHERE "id" = $%d
|
||||
RETURNING "nombre", "descripcion", "color", "activo", "orden"
|
||||
`, strings.Join(sets, ", "), len(args)), args...).Scan(&nombre, &desc, &color, &activo, &orden)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Categoria no encontrada")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando categoria")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden})
|
||||
}
|
||||
|
||||
func (s *Server) handleCategoriasDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var cnt int
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "categoriaId" = $1`, id).Scan(&cnt)
|
||||
if cnt > 0 {
|
||||
writeError(w, http.StatusConflict, "No se puede eliminar una categoria con servicios asociados")
|
||||
return
|
||||
}
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Categoria" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Categoria no encontrada")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) loadPaqueteFull(ctx context.Context, paqueteID string, hideSoloAdmin bool) (map[string]any, error) {
|
||||
var id, nombre string
|
||||
var desc *string
|
||||
var activo bool
|
||||
err := s.Pool.QueryRow(ctx, `SELECT "id", "nombre", "descripcion", "activo" FROM "Paquete" WHERE "id" = $1`, paqueteID).Scan(&id, &nombre, &desc, &activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
faseRows, err := s.Pool.Query(ctx, `SELECT "id", "nombre", "orden" FROM "FasePaquete" WHERE "paqueteId" = $1 ORDER BY "orden" ASC`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer faseRows.Close()
|
||||
|
||||
fases := []map[string]any{}
|
||||
for faseRows.Next() {
|
||||
var fid, fnom string
|
||||
var forden int
|
||||
if faseRows.Scan(&fid, &fnom, &forden) != nil {
|
||||
continue
|
||||
}
|
||||
filterAdmin := ""
|
||||
if hideSoloAdmin {
|
||||
filterAdmin = ` AND sc."soloAdmin" = false`
|
||||
}
|
||||
sRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT sp."id", sp."servicioCatalogoId", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago",
|
||||
sc."precioBase", sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel", sc."soloAdmin",
|
||||
c."nombre", c."color"
|
||||
FROM "ServicioPaquete" sp
|
||||
JOIN "ServicioCatalogo" sc ON sc."id" = sp."servicioCatalogoId"
|
||||
LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId"
|
||||
WHERE sp."fasePaqueteId" = $1 AND sc."activo" = true`+filterAdmin+`
|
||||
ORDER BY sc."orden" ASC, sc."nombre" ASC
|
||||
`, fid)
|
||||
svcs := []map[string]any{}
|
||||
if sRows != nil {
|
||||
for sRows.Next() {
|
||||
var spid, scid, snom, tp, te string
|
||||
var sdesc, cid, vari, niv, cnom, ccol *string
|
||||
var sfase int
|
||||
var pb float64
|
||||
var entRaw []byte
|
||||
var sadmin bool
|
||||
if sRows.Scan(&spid, &scid, &snom, &sdesc, &sfase, &tp, &pb, &te, &entRaw, &cid, &vari, &niv, &sadmin, &cnom, &ccol) == nil {
|
||||
var ent []string
|
||||
_ = json.Unmarshal(entRaw, &ent)
|
||||
if ent == nil {
|
||||
ent = []string{}
|
||||
}
|
||||
svcs = append(svcs, map[string]any{
|
||||
"id": spid,
|
||||
"servicioCatalogoId": scid,
|
||||
"fasePaqueteId": fid,
|
||||
"servicio": map[string]any{
|
||||
"id": scid, "nombre": snom, "descripcion": sdesc, "fase": sfase,
|
||||
"tipoPago": tp, "precioBase": pb, "tiempoEntrega": te,
|
||||
"entregablesDefault": ent, "categoriaId": cid, "variante": vari, "nivel": niv,
|
||||
"soloAdmin": sadmin, "categoriaNombre": cnom, "categoriaColor": ccol,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
sRows.Close()
|
||||
}
|
||||
fases = append(fases, map[string]any{
|
||||
"id": fid, "paqueteId": id, "nombre": fnom, "orden": forden, "servicios": svcs,
|
||||
})
|
||||
}
|
||||
return map[string]any{
|
||||
"id": id, "nombre": nombre, "descripcion": desc, "activo": activo, "fases": fases,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `SELECT "id" FROM "Paquete" WHERE "activo" = true ORDER BY "createdAt" ASC`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando paquetes")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if rows.Scan(&id) == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
list := []map[string]any{}
|
||||
for _, id := range ids {
|
||||
if p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent()); err == nil {
|
||||
list = append(list, p)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesGet(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Fases []struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Orden int `json:"orden"`
|
||||
} `json:"fases"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" {
|
||||
writeError(w, http.StatusBadRequest, "El nombre del paquete es obligatorio")
|
||||
return
|
||||
}
|
||||
id := db.NewID()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, true, NOW(), NOW())
|
||||
`, id, strings.TrimSpace(body.Nombre), body.Descripcion)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando paquete")
|
||||
return
|
||||
}
|
||||
for i, f := range body.Fases {
|
||||
ord := f.Orden
|
||||
if ord == 0 {
|
||||
ord = i
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
`, db.NewID(), id, strings.TrimSpace(f.Nombre), ord)
|
||||
}
|
||||
p, _ := s.loadPaqueteFull(r.Context(), id, false)
|
||||
writeJSON(w, http.StatusCreated, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Nombre *string `json:"nombre"`
|
||||
Descripcion *string `json:"descripcion"`
|
||||
Activo *bool `json:"activo"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if body.Nombre != nil {
|
||||
add("nombre", strings.TrimSpace(*body.Nombre))
|
||||
}
|
||||
if body.Descripcion != nil {
|
||||
add("descripcion", *body.Descripcion)
|
||||
}
|
||||
if body.Activo != nil {
|
||||
add("activo", *body.Activo)
|
||||
}
|
||||
args = append(args, id)
|
||||
tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Paquete" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
p, _ := s.loadPaqueteFull(r.Context(), id, false)
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Paquete" WHERE "id" = $1`, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handlePaquetesManage(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok {
|
||||
return
|
||||
}
|
||||
paqueteID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Action string `json:"action"`
|
||||
FaseID string `json:"faseId"`
|
||||
FasePaqueteID string `json:"fasePaqueteId"`
|
||||
Nombre string `json:"nombre"`
|
||||
Orden *int `json:"orden"`
|
||||
ServicioCatalogoID string `json:"servicioCatalogoId"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
fid := firstNonEmptyStr(body.FasePaqueteID, body.FaseID)
|
||||
|
||||
switch body.Action {
|
||||
case "addFase":
|
||||
ord := 0
|
||||
if body.Orden != nil {
|
||||
ord = *body.Orden
|
||||
} else {
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), -1) + 1 FROM "FasePaquete" WHERE "paqueteId" = $1`, paqueteID).Scan(&ord)
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
`, db.NewID(), paqueteID, strings.TrimSpace(body.Nombre), ord)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error agregando fase")
|
||||
return
|
||||
}
|
||||
case "updateFase":
|
||||
if body.Nombre != "" {
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "nombre" = $1, "updatedAt" = NOW() WHERE "id" = $2`, strings.TrimSpace(body.Nombre), fid)
|
||||
}
|
||||
if body.Orden != nil {
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "orden" = $1, "updatedAt" = NOW() WHERE "id" = $2`, *body.Orden, fid)
|
||||
}
|
||||
case "deleteFase":
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "FasePaquete" WHERE "id" = $1`, fid)
|
||||
case "addServicio":
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), body.ServicioCatalogoID, fid)
|
||||
case "removeServicio":
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
DELETE FROM "ServicioPaquete" WHERE "servicioCatalogoId" = $1 AND "fasePaqueteId" = $2
|
||||
`, body.ServicioCatalogoID, fid)
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "Accion invalida")
|
||||
return
|
||||
}
|
||||
|
||||
p, err := s.loadPaqueteFull(r.Context(), paqueteID, false)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Paquete no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportCatalogoCSV(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
list, err := s.queryServicioCatalogo(r.Context(), `sc."activo" = true`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error exportando catalogo")
|
||||
return
|
||||
}
|
||||
rows := make([]excel.CatalogoCSVRow, 0, len(list))
|
||||
for _, it := range list {
|
||||
cat := ""
|
||||
if c, ok := it["categoriaNombre"].(*string); ok && c != nil {
|
||||
cat = *c
|
||||
}
|
||||
vari := ""
|
||||
if v, ok := it["variante"].(*string); ok && v != nil {
|
||||
vari = *v
|
||||
}
|
||||
ent, _ := it["entregablesDefault"].([]string)
|
||||
rows = append(rows, excel.CatalogoCSVRow{
|
||||
Nombre: asString(it["nombre"]),
|
||||
Categoria: cat,
|
||||
Fase: it["fase"].(int),
|
||||
TipoPago: asString(it["tipoPago"]),
|
||||
PrecioBase: it["precioBase"].(float64),
|
||||
TiempoEntrega: asString(it["tiempoEntrega"]),
|
||||
Entregables: ent,
|
||||
Variante: vari,
|
||||
})
|
||||
}
|
||||
csvBytes, err := excel.ExportCatalogoCSV(rows)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando CSV")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="catalogo-servicios.csv"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(csvBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportCatalogoPlantilla(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="plantilla-catalogo.csv"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(excel.PlantillaCatalogoCSV())
|
||||
}
|
||||
|
||||
func (s *Server) handleImportCatalogoCSV(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok {
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(10 << 20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo archivo multipart")
|
||||
return
|
||||
}
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, 10<<20))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "No se pudo leer el archivo")
|
||||
return
|
||||
}
|
||||
rows, err := excel.ParseCatalogoCSV(raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
catMap := map[string]string{}
|
||||
cRows, _ := s.Pool.Query(r.Context(), `SELECT "id", LOWER("nombre") FROM "Categoria" WHERE "activo" = true`)
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var cid, cnom string
|
||||
if cRows.Scan(&cid, &cnom) == nil {
|
||||
catMap[cnom] = cid
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
imported := 0
|
||||
for i, row := range rows {
|
||||
var catID *string
|
||||
if id, ok := catMap[strings.ToLower(strings.TrimSpace(row.Categoria))]; ok {
|
||||
cid := id
|
||||
catID = &cid
|
||||
}
|
||||
entJSON, _ := json.Marshal(row.Entregables)
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "fase", "tipoPago", "precioBase", "tiempoEntrega",
|
||||
"entregablesDefault", "categoriaId", "variante", "activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,true,false,$10,NOW(),NOW())
|
||||
`, db.NewID(), row.Nombre, row.Fase, row.TipoPago, row.PrecioBase, firstNonEmptyStr(row.TiempoEntrega, "4 - 10 dias"),
|
||||
entJSON, catID, nullableTrim(row.Variante), i+1)
|
||||
if err == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "importados": imported})
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
s, ok := v.(string)
|
||||
if ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
|
||||
func nullableTrim(s string) *string {
|
||||
t := strings.TrimSpace(s)
|
||||
if t == "" {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
|
||||
func asInt(v any) (int, bool) {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return int(x), true
|
||||
case int:
|
||||
return x, true
|
||||
case string:
|
||||
n, err := strconv.Atoi(strings.TrimSpace(x))
|
||||
return n, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func asFloat(v any) (float64, bool) {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return x, true
|
||||
case int:
|
||||
return float64(x), true
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
|
||||
return f, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func asStringSlice(v any) []string {
|
||||
if v == nil {
|
||||
return []string{}
|
||||
}
|
||||
switch arr := v.(type) {
|
||||
case []string:
|
||||
return arr
|
||||
case []any:
|
||||
out := make([]string, 0, len(arr))
|
||||
for _, item := range arr {
|
||||
if s := strings.TrimSpace(asString(item)); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return []string{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/uploads"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) handleClienteResumen(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
cid := sess.ClienteID
|
||||
hoy := domain.HoyCalendario()
|
||||
inicioMes := time.Date(hoy.Year(), hoy.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
var nombre string
|
||||
var empresa, email *string
|
||||
if err := s.Pool.QueryRow(ctx, `SELECT "nombre", "empresa", "email" FROM "Cliente" WHERE "id" = $1`, cid).Scan(&nombre, &empresa, &email); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando perfil")
|
||||
return
|
||||
}
|
||||
|
||||
var totalCot, pagosPendientes, pagosEnRevision, pagosVerificadosMes int
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "clienteId" = $1 AND "archivado" = false`, cid).Scan(&totalCot)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado')
|
||||
`, cid).Scan(&pagosPendientes)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" = 'en_revision'
|
||||
`, cid).Scan(&pagosEnRevision)
|
||||
_ = s.Pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" = 'verificado' AND COALESCE(p."verificadoAt", p."fecha") >= $2
|
||||
`, cid, inicioMes).Scan(&pagosVerificadosMes)
|
||||
|
||||
// Pending balance + oldest unpaid date
|
||||
saldoPendiente := map[string]float64{}
|
||||
var masAntiguo *time.Time
|
||||
pendRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."fecha", p."monto", pr."moneda"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado')
|
||||
ORDER BY p."fecha" ASC
|
||||
`, cid)
|
||||
if pendRows != nil {
|
||||
for pendRows.Next() {
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var mon string
|
||||
if pendRows.Scan(&fecha, &monto, &mon) == nil {
|
||||
saldoPendiente[mon] = domain.Round2(saldoPendiente[mon] + monto)
|
||||
if masAntiguo == nil || fecha.Before(*masAntiguo) {
|
||||
t := fecha
|
||||
masAntiguo = &t
|
||||
}
|
||||
}
|
||||
}
|
||||
pendRows.Close()
|
||||
}
|
||||
|
||||
// Upcoming scheduled charges from active programs
|
||||
proximos := []map[string]any{}
|
||||
progRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin"
|
||||
FROM "ProgramaPago"
|
||||
WHERE "clienteId" = $1 AND "activo" = true
|
||||
ORDER BY "createdAt" DESC
|
||||
`, cid)
|
||||
if progRows != nil {
|
||||
for progRows.Next() {
|
||||
var conc, mon, frec string
|
||||
var monto float64
|
||||
var ds, dm *int
|
||||
var fIni time.Time
|
||||
var fFin *time.Time
|
||||
if progRows.Scan(&conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin) == nil {
|
||||
if prox := domain.ProximaFecha(domain.ProgramaCalendario{
|
||||
Frecuencia: frec, DiaSemana: ds, DiaMes: dm, FechaInicio: fIni, FechaFin: fFin,
|
||||
}, hoy); prox != nil {
|
||||
proximos = append(proximos, map[string]any{
|
||||
"fecha": *prox,
|
||||
"monto": monto,
|
||||
"moneda": mon,
|
||||
"concepto": conc,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
progRows.Close()
|
||||
}
|
||||
|
||||
// Recent cotizaciones
|
||||
cRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "clienteId" = $1 AND "archivado" = false
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT 5
|
||||
`, cid)
|
||||
cotRecientes := []map[string]any{}
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var qid, num, proy, est, mon string
|
||||
var fecha, vig time.Time
|
||||
var esDoble, incIva bool
|
||||
if cRows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil {
|
||||
cotRecientes = append(cotRecientes, s.enrichClienteCotSummary(ctx, qid, num, proy, est, mon, fecha, vig, esDoble, incIva))
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"cliente": map[string]any{"id": cid, "nombre": nombre, "empresa": empresa, "email": email},
|
||||
"cotizacionesActivas": totalCot,
|
||||
"cotizaciones": cotRecientes,
|
||||
"pagos": map[string]any{
|
||||
"pendientes": pagosPendientes,
|
||||
"saldoPendiente": saldoPendiente,
|
||||
"masAntiguo": masAntiguo,
|
||||
"enRevision": pagosEnRevision,
|
||||
"verificadosMes": pagosVerificadosMes,
|
||||
"proximos": proximos,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) enrichClienteCotSummary(ctx context.Context, qid, num, proy, est, mon string, fecha, vig time.Time, esDoble, incIva bool) map[string]any {
|
||||
full, _, err := s.loadCotizacionFull(ctx, qid, true)
|
||||
var tot domain.TotalesCotizacion
|
||||
var totalesOpciones map[string]any
|
||||
if err == nil {
|
||||
tot = domain.CalcularTotalesCotizacion(full.ServiciosCalc, incIva)
|
||||
if esDoble {
|
||||
o1 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "1")
|
||||
o2 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "2")
|
||||
totalesOpciones = map[string]any{"1": o1, "2": o2}
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"id": qid, "numero": num, "proyecto": proy, "estado": est, "moneda": mon,
|
||||
"fecha": fecha, "vigencia": vig, "esDoble": esDoble, "incluirIva": incIva,
|
||||
"totales": tot, "totalesOpciones": totalesOpciones,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteCotizacionesList(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := s.Pool.Query(r.Context(), `
|
||||
SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "clienteId" = $1 AND "archivado" = false
|
||||
ORDER BY "createdAt" DESC
|
||||
`, sess.ClienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando cotizaciones")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var qid, num, proy, est, mon string
|
||||
var fecha, vig time.Time
|
||||
var esDoble, incIva bool
|
||||
if rows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil {
|
||||
list = append(list, s.enrichClienteCotSummary(r.Context(), qid, num, proy, est, mon, fecha, vig, esDoble, incIva))
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteCotizacionGet(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, jsonMap, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil || full.ClienteID != sess.ClienteID {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
// Never expose internal notes or registrosHoras to client view
|
||||
jsonMap["observacionesInternas"] = nil
|
||||
writeJSON(w, http.StatusOK, jsonMap)
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePagosList(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
|
||||
// Load programs belonging to client
|
||||
progRows, err := s.Pool.Query(ctx, `
|
||||
SELECT "id", "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo"
|
||||
FROM "ProgramaPago"
|
||||
WHERE "clienteId" = $1
|
||||
ORDER BY "activo" DESC, "createdAt" DESC
|
||||
`, sess.ClienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando pagos")
|
||||
return
|
||||
}
|
||||
defer progRows.Close()
|
||||
|
||||
programas := []map[string]any{}
|
||||
progByID := map[string]map[string]any{}
|
||||
for progRows.Next() {
|
||||
var pid, conc, mon, frec string
|
||||
var monto float64
|
||||
var ds, dm *int
|
||||
var fIni time.Time
|
||||
var fFin *time.Time
|
||||
var activo bool
|
||||
if progRows.Scan(&pid, &conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin, &activo) == nil {
|
||||
pm := map[string]any{
|
||||
"id": pid, "concepto": conc, "monto": monto, "moneda": mon,
|
||||
"frecuencia": frec, "diaSemana": ds, "diaMes": dm,
|
||||
"fechaInicio": fIni, "fechaFin": fFin, "activo": activo,
|
||||
"pagos": []map[string]any{},
|
||||
}
|
||||
programas = append(programas, pm)
|
||||
progByID[pid] = pm
|
||||
}
|
||||
}
|
||||
|
||||
// Load payments (omitting internal `nota` for clients!)
|
||||
pRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado",
|
||||
p."verificadoAt", p."rechazadoAt", p."rechazoMotivo",
|
||||
pr."concepto", pr."moneda", pr."frecuencia",
|
||||
c."id", c."archivoNombre", c."mime", c."tamano", c."subidoAt"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
LEFT JOIN "ComprobantePago" c ON c."pagoId" = p."id"
|
||||
WHERE pr."clienteId" = $1
|
||||
ORDER BY p."fecha" DESC
|
||||
`, sess.ClienteID)
|
||||
pagos := []map[string]any{}
|
||||
if pRows != nil {
|
||||
defer pRows.Close()
|
||||
for pRows.Next() {
|
||||
var id, progID, est, conc, mon, frec string
|
||||
var rmot, compID, compNom, compMime *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var verifAt, rechAt, compSub *time.Time
|
||||
var compTam *int
|
||||
if pRows.Scan(&id, &progID, &fecha, &monto, &est, &verifAt, &rechAt, &rmot,
|
||||
&conc, &mon, &frec, &compID, &compNom, &compMime, &compTam, &compSub) == nil {
|
||||
var comp any
|
||||
if compID != nil {
|
||||
comp = map[string]any{
|
||||
"id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub,
|
||||
}
|
||||
}
|
||||
row := map[string]any{
|
||||
"id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": est,
|
||||
"verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rmot,
|
||||
"programa": map[string]any{"id": progID, "concepto": conc, "moneda": mon, "frecuencia": frec},
|
||||
"comprobante": comp,
|
||||
}
|
||||
pagos = append(pagos, row)
|
||||
if pm, ok := progByID[progID]; ok {
|
||||
pm["pagos"] = append(pm["pagos"].([]map[string]any), row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"pagos": pagos,
|
||||
"programas": programas,
|
||||
"bancaria": s.getConfigBancaria(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteComprobanteUpload(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pagoID := chi.URLParam(r, "id")
|
||||
|
||||
var estado, ownerClienteID string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT p."estado", pr."clienteId"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&estado, &ownerClienteID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error verificando cobro")
|
||||
return
|
||||
}
|
||||
if ownerClienteID != sess.ClienteID {
|
||||
writeError(w, http.StatusForbidden, "No tienes acceso a este cobro")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
writeError(w, http.StatusConflict, "Solo puedes subir comprobante para cobros pendientes o rechazados")
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ParseMultipartForm(uploads.MaxFileSizeBytes + (1 << 20)); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo formulario de archivo")
|
||||
return
|
||||
}
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(file, uploads.MaxFileSizeBytes+1))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Error leyendo archivo")
|
||||
return
|
||||
}
|
||||
saved, err := uploads.GuardarComprobante(s.Cfg.UploadDir, pagoID, header.Filename, header.Header.Get("Content-Type"), raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Remove previous comprobante if any
|
||||
var oldRuta string
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID).Scan(&oldRuta)
|
||||
if oldRuta != "" {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, oldRuta)
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID)
|
||||
}
|
||||
|
||||
compID := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ComprobantePago" ("id", "pagoId", "archivoRuta", "archivoNombre", "mime", "tamano", "subidoAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
||||
`, compID, pagoID, saved.ArchivoRuta, saved.ArchivoNombre, saved.Mime, saved.Tamano)
|
||||
if err != nil {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, saved.ArchivoRuta)
|
||||
writeError(w, http.StatusInternalServerError, "Error registrando comprobante")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='en_revision', "rechazoMotivo"=NULL, "updatedAt"=NOW() WHERE "id" = $1
|
||||
`, pagoID)
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"ok": true, "id": compID, "pagoId": pagoID, "estado": "en_revision",
|
||||
"archivoNombre": saved.ArchivoNombre, "mime": saved.Mime, "tamano": saved.Tamano,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireCliente(w, r); !ok {
|
||||
return
|
||||
}
|
||||
if !s.Notify.VAPIDConfigured() {
|
||||
writeError(w, http.StatusNotImplemented, "Notificaciones push no configuradas")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"publicKey": s.Cfg.VAPIDPublicKey})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushSubscribe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Keys struct {
|
||||
P256dh string `json:"p256dh"`
|
||||
Auth string `json:"auth"`
|
||||
} `json:"keys"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Endpoint) == "" || body.Keys.P256dh == "" || body.Keys.Auth == "" {
|
||||
writeError(w, http.StatusBadRequest, "Suscripcion push invalida")
|
||||
return
|
||||
}
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "SuscripcionPush" ("id", "userId", "endpoint", "p256dh", "auth", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
|
||||
ON CONFLICT ("endpoint") DO UPDATE SET "userId" = EXCLUDED."userId", "p256dh" = EXCLUDED."p256dh", "auth" = EXCLUDED."auth", "updatedAt" = NOW()
|
||||
`, db.NewID(), sess.UserID, strings.TrimSpace(body.Endpoint), body.Keys.P256dh, body.Keys.Auth)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando suscripcion push")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.RequireCliente(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
if strings.TrimSpace(body.Endpoint) != "" {
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1 AND "endpoint" = $2`, sess.UserID, strings.TrimSpace(body.Endpoint))
|
||||
} else {
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1`, sess.UserID)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/idempotency"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryClientes(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT c."id", c."nombre", c."empresa", c."puesto", c."email", c."telefono", c."rfc",
|
||||
c."archivado", c."archivadoAt", c."createdAt", c."updatedAt",
|
||||
u."id", u."email",
|
||||
(SELECT COUNT(*) FROM "Cotizacion" q WHERE q."clienteId" = c."id" AND q."archivado" = false) AS cot_count,
|
||||
(SELECT COUNT(*) FROM "ProgramaPago" p WHERE p."clienteId" = c."id" AND p."activo" = true) AS prog_count
|
||||
FROM "Cliente" c
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY c."nombre" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, nombre string
|
||||
var empresa, puesto, email, telefono, rfc, uid, uemail *string
|
||||
var archivado bool
|
||||
var archivadoAt *time.Time
|
||||
var createdAt, updatedAt time.Time
|
||||
var cotCount, progCount int
|
||||
if rows.Scan(&id, &nombre, &empresa, &puesto, &email, &telefono, &rfc, &archivado, &archivadoAt, &createdAt, &updatedAt, &uid, &uemail, &cotCount, &progCount) == nil {
|
||||
var usuario any
|
||||
if uid != nil {
|
||||
usuario = map[string]any{"id": *uid, "email": uemail}
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id,
|
||||
"nombre": nombre,
|
||||
"empresa": empresa,
|
||||
"puesto": puesto,
|
||||
"email": email,
|
||||
"telefono": telefono,
|
||||
"rfc": rfc,
|
||||
"archivado": archivado,
|
||||
"archivadoAt": archivadoAt,
|
||||
"createdAt": createdAt,
|
||||
"updatedAt": updatedAt,
|
||||
"usuario": usuario,
|
||||
"_count": map[string]any{
|
||||
"cotizaciones": cotCount,
|
||||
"programasPago": progCount,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) clienteDuplicadoExiste(ctx context.Context, nombre, empresa, excludeID string) (bool, error) {
|
||||
empNorm := strings.ToLower(strings.TrimSpace(empresa))
|
||||
var exists bool
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM "Cliente"
|
||||
WHERE "archivado" = false
|
||||
AND LOWER(TRIM("nombre")) = LOWER(TRIM($1))
|
||||
AND LOWER(TRIM(COALESCE("empresa", ''))) = $2
|
||||
AND ($3 = '' OR "id" <> $3)
|
||||
)
|
||||
`, nombre, empNorm, excludeID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesList(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:leer"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
|
||||
incluirArchivados := !actor.IsAgent() && q.Get("incluirArchivados") == "true"
|
||||
if !incluirArchivados {
|
||||
conds = append(conds, `c."archivado" = false`)
|
||||
}
|
||||
if search := strings.TrimSpace(q.Get("q")); search != "" {
|
||||
p := add("%" + search + "%")
|
||||
conds = append(conds, fmt.Sprintf(`(c."nombre" ILIKE %s OR COALESCE(c."empresa", '') ILIKE %s OR COALESCE(c."email", '') ILIKE %s OR COALESCE(c."rfc", '') ILIKE %s)`, p, p, p, p))
|
||||
}
|
||||
|
||||
list, err := s.queryClientes(r.Context(), strings.Join(conds, " AND "), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando clientes")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesCreate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
||||
var body struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Empresa *string `json:"empresa"`
|
||||
Puesto *string `json:"puesto"`
|
||||
Email *string `json:"email"`
|
||||
Telefono *string `json:"telefono"`
|
||||
RFC *string `json:"rfc"`
|
||||
}
|
||||
if err := json.Unmarshal(rawBody, &body); err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
||||
}
|
||||
nombre := strings.TrimSpace(body.Nombre)
|
||||
if nombre == "" {
|
||||
return http.StatusBadRequest, map[string]any{
|
||||
"error": "Datos invalidos",
|
||||
"detalles": []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre del cliente es obligatorio"}},
|
||||
}
|
||||
}
|
||||
empStr := ""
|
||||
if body.Empresa != nil {
|
||||
empStr = strings.TrimSpace(*body.Empresa)
|
||||
}
|
||||
dup, err := s.clienteDuplicadoExiste(r.Context(), nombre, empStr, "")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error validando duplicado"}
|
||||
}
|
||||
if dup {
|
||||
return http.StatusConflict, map[string]any{"error": "Ya existe un cliente con el mismo nombre y empresa"}
|
||||
}
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "Cliente" ("id", "nombre", "empresa", "puesto", "email", "telefono", "rfc", "archivado", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, false, NOW(), NOW())
|
||||
`, id, nombre, nullableTrim(empStr), trimPtr(body.Puesto), trimPtr(body.Email), trimPtr(body.Telefono), trimPtr(body.RFC))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"}
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cliente.crear", RecursoTipo: "cliente", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"nombre": nombre, "empresa": empStr},
|
||||
})
|
||||
|
||||
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
return http.StatusCreated, list[0]
|
||||
}
|
||||
return http.StatusCreated, map[string]any{"id": id, "nombre": nombre}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleClientesUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var curNombre string
|
||||
var curEmpresa *string
|
||||
err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", "empresa" FROM "Cliente" WHERE "id" = $1`, id).Scan(&curNombre, &curEmpresa)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando cliente")
|
||||
return
|
||||
}
|
||||
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
newNombre := curNombre
|
||||
if v, ok := raw["nombre"]; ok {
|
||||
newNombre = strings.TrimSpace(asString(v))
|
||||
if newNombre == "" {
|
||||
writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}})
|
||||
return
|
||||
}
|
||||
}
|
||||
newEmpresa := ""
|
||||
if curEmpresa != nil {
|
||||
newEmpresa = *curEmpresa
|
||||
}
|
||||
if v, ok := raw["empresa"]; ok {
|
||||
newEmpresa = strings.TrimSpace(asString(v))
|
||||
}
|
||||
|
||||
if dup, _ := s.clienteDuplicadoExiste(r.Context(), newNombre, newEmpresa, id); dup {
|
||||
writeError(w, http.StatusConflict, "Ya existe otro cliente con el mismo nombre y empresa")
|
||||
return
|
||||
}
|
||||
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if _, ok := raw["nombre"]; ok {
|
||||
add("nombre", newNombre)
|
||||
}
|
||||
if _, ok := raw["empresa"]; ok {
|
||||
add("empresa", nullableTrim(newEmpresa))
|
||||
}
|
||||
if v, ok := raw["puesto"]; ok {
|
||||
add("puesto", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["email"]; ok {
|
||||
add("email", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["telefono"]; ok {
|
||||
add("telefono", nullableTrim(asString(v)))
|
||||
}
|
||||
if v, ok := raw["rfc"]; ok {
|
||||
add("rfc", nullableTrim(asString(v)))
|
||||
}
|
||||
args = append(args, id)
|
||||
_, err = s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cliente" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando cliente")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cliente.actualizar", RecursoTipo: "cliente", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
|
||||
list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id)
|
||||
if len(list) == 1 {
|
||||
writeJSON(w, http.StatusOK, list[0])
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteAccesoCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
var cliNombre string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&cliNombre); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(body.Email))
|
||||
if email == "" || len(body.Password) < 6 {
|
||||
writeError(w, http.StatusBadRequest, "Email y contrasena (minimo 6 caracteres) requeridos")
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := auth.HashPassword(body.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error encriptando contrasena")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if another user owns this email
|
||||
var conflict bool
|
||||
_ = s.Pool.QueryRow(r.Context(), `
|
||||
SELECT EXISTS(SELECT 1 FROM "User" WHERE LOWER("email") = $1 AND ("clienteId" IS NULL OR "clienteId" <> $2))
|
||||
`, email, clienteID).Scan(&conflict)
|
||||
if conflict {
|
||||
writeError(w, http.StatusConflict, "Ese correo ya esta en uso por otra cuenta")
|
||||
return
|
||||
}
|
||||
|
||||
var existingID string
|
||||
err = s.Pool.QueryRow(r.Context(), `SELECT "id" FROM "User" WHERE "clienteId" = $1`, clienteID).Scan(&existingID)
|
||||
if err == nil && existingID != "" {
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "User" SET "email" = $1, "password" = $2, "name" = $3, "role" = 'cliente', "updatedAt" = NOW()
|
||||
WHERE "id" = $4
|
||||
`, email, hash, cliNombre, existingID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando acceso")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": existingID, "email": email, "actualizado": true})
|
||||
return
|
||||
}
|
||||
|
||||
uid := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "clienteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'cliente', $5, NOW(), NOW())
|
||||
`, uid, email, hash, cliNombre, clienteID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando cuenta de cliente")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": uid, "email": email})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteAccesoDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "User" WHERE "clienteId" = $1 AND "role" = 'cliente'`, clienteID)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleClienteArchivar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
||||
StaffOnly: true,
|
||||
AccionBloqueo: "cliente.archivar_bloqueado",
|
||||
RecursoTipo: "cliente",
|
||||
})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
clienteID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Archivado *bool `json:"archivado"`
|
||||
IncluirCotizaciones *bool `json:"incluirCotizaciones"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
archivado := true
|
||||
if body.Archivado != nil {
|
||||
archivado = *body.Archivado
|
||||
}
|
||||
incluirCot := true
|
||||
if body.IncluirCotizaciones != nil {
|
||||
incluirCot = *body.IncluirCotizaciones
|
||||
}
|
||||
|
||||
var archAt *time.Time
|
||||
if archivado {
|
||||
now := time.Now()
|
||||
archAt = &now
|
||||
}
|
||||
|
||||
tag, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "Cliente" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "id" = $3
|
||||
`, archivado, archAt, clienteID)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Cliente no encontrado")
|
||||
return
|
||||
}
|
||||
var cotAfectadas int64
|
||||
if incluirCot {
|
||||
ctag, _ := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "Cotizacion" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "clienteId" = $3
|
||||
`, archivado, archAt, clienteID)
|
||||
cotAfectadas = ctag.RowsAffected()
|
||||
}
|
||||
|
||||
accion := "cliente.archivar"
|
||||
if !archivado {
|
||||
accion = "cliente.desarchivar"
|
||||
}
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: accion, RecursoTipo: "cliente", RecursoID: clienteID,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"archivado": archivado, "cotizacionesAfectadas": cotAfectadas},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"id": clienteID,
|
||||
"archivado": archivado,
|
||||
"cotizacionesAfectadas": cotAfectadas,
|
||||
})
|
||||
}
|
||||
|
||||
func trimPtr(p *string) *string {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
return nullableTrim(*p)
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/idempotency"
|
||||
"cotizador/internal/scheduler"
|
||||
"cotizador/internal/uploads"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) queryProgramas(ctx context.Context) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."clienteId", p."cotizacionId", p."concepto", p."monto", p."moneda",
|
||||
p."frecuencia", p."diaSemana", p."diaMes", p."fechaInicio", p."fechaFin", p."activo",
|
||||
p."createdAt", p."updatedAt",
|
||||
c."nombre", c."empresa", c."email",
|
||||
(SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p."id") AS pagos_count
|
||||
FROM "ProgramaPago" p
|
||||
JOIN "Cliente" c ON c."id" = p."clienteId"
|
||||
ORDER BY p."activo" DESC, p."createdAt" DESC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
hoy := domain.HoyCalendario()
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, clienteID, concepto, moneda, frecuencia, cNombre string
|
||||
var cotID, cEmpresa, cEmail *string
|
||||
var monto float64
|
||||
var diaSemana, diaMes *int
|
||||
var fechaInicio, createdAt, updatedAt time.Time
|
||||
var fechaFin *time.Time
|
||||
var activo bool
|
||||
var pagosCount int
|
||||
if rows.Scan(&id, &clienteID, &cotID, &concepto, &monto, &moneda, &frecuencia, &diaSemana, &diaMes,
|
||||
&fechaInicio, &fechaFin, &activo, &createdAt, &updatedAt, &cNombre, &cEmpresa, &cEmail, &pagosCount) == nil {
|
||||
var prox *time.Time
|
||||
if activo {
|
||||
prox = domain.ProximaFecha(domain.ProgramaCalendario{
|
||||
Frecuencia: frecuencia, DiaSemana: diaSemana, DiaMes: diaMes,
|
||||
FechaInicio: fechaInicio, FechaFin: fechaFin,
|
||||
}, hoy)
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "clienteId": clienteID, "cotizacionId": cotID,
|
||||
"concepto": concepto, "monto": monto, "moneda": moneda,
|
||||
"frecuencia": frecuencia, "diaSemana": diaSemana, "diaMes": diaMes,
|
||||
"fechaInicio": fechaInicio, "fechaFin": fechaFin, "activo": activo,
|
||||
"proximaFecha": prox, "createdAt": createdAt, "updatedAt": updatedAt,
|
||||
"cliente": map[string]any{"id": clienteID, "nombre": cNombre, "empresa": cEmpresa, "email": cEmail},
|
||||
"pagosCount": pagosCount,
|
||||
"_count": map[string]any{"pagos": pagosCount},
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosResumen(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
hoy := domain.HoyCalendario()
|
||||
|
||||
programas, err := s.queryProgramas(ctx)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando programas")
|
||||
return
|
||||
}
|
||||
|
||||
// Clientes for dropdown
|
||||
cRows, _ := s.Pool.Query(ctx, `SELECT "id", "nombre", "empresa" FROM "Cliente" WHERE "archivado" = false ORDER BY "nombre" ASC`)
|
||||
clientes := []map[string]any{}
|
||||
if cRows != nil {
|
||||
for cRows.Next() {
|
||||
var cid, cnom string
|
||||
var cemp *string
|
||||
if cRows.Scan(&cid, &cnom, &cemp) == nil {
|
||||
clientes = append(clientes, map[string]any{"id": cid, "nombre": cnom, "empresa": cemp})
|
||||
}
|
||||
}
|
||||
cRows.Close()
|
||||
}
|
||||
|
||||
// Pagos en revision
|
||||
revPagos, _ := s.queryPagos(ctx, `p."estado" = 'en_revision'`, nil)
|
||||
|
||||
// Pagos por cobrar (pendiente | rechazado, fecha <= hoy, including inactive programs)
|
||||
porCobrarRows, _ := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt", p."recordatoriosEnviados",
|
||||
pr."concepto", pr."moneda",
|
||||
c."id", c."nombre", c."empresa", c."email",
|
||||
(SELECT COUNT(*) FROM "SuscripcionPush" sp JOIN "User" u ON u."id" = sp."userId" WHERE u."clienteId" = c."id") AS push_count
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
WHERE p."estado" IN ('pendiente', 'rechazado') AND p."fecha" <= $1
|
||||
ORDER BY c."nombre" ASC, p."fecha" ASC
|
||||
`, hoy)
|
||||
|
||||
type saldoClient struct {
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa *string
|
||||
ClienteEmail *string
|
||||
Contactable bool
|
||||
Totales map[string]float64
|
||||
MasAntigua time.Time
|
||||
UltimoRecordatorio *time.Time
|
||||
PagosCount int
|
||||
}
|
||||
saldoMap := map[string]*saldoClient{}
|
||||
var saldoOrder []string
|
||||
if porCobrarRows != nil {
|
||||
for porCobrarRows.Next() {
|
||||
var pid, prid, estado, concepto, moneda, cid, cnom string
|
||||
var cemp, cemail *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var ultRec *time.Time
|
||||
var recCnt, pushCnt int
|
||||
if porCobrarRows.Scan(&pid, &prid, &fecha, &monto, &estado, &ultRec, &recCnt, &concepto, &moneda, &cid, &cnom, &cemp, &cemail, &pushCnt) == nil {
|
||||
sc, ok := saldoMap[cid]
|
||||
if !ok {
|
||||
sc = &saldoClient{
|
||||
ClienteID: cid, ClienteNombre: cnom, ClienteEmpresa: cemp, ClienteEmail: cemail,
|
||||
Contactable: (cemail != nil && strings.TrimSpace(*cemail) != "") || pushCnt > 0,
|
||||
Totales: map[string]float64{},
|
||||
MasAntigua: fecha,
|
||||
}
|
||||
saldoMap[cid] = sc
|
||||
saldoOrder = append(saldoOrder, cid)
|
||||
}
|
||||
if fecha.Before(sc.MasAntigua) {
|
||||
sc.MasAntigua = fecha
|
||||
}
|
||||
sc.Totales[moneda] = domain.Round2(sc.Totales[moneda] + monto)
|
||||
if ultRec != nil && (sc.UltimoRecordatorio == nil || ultRec.After(*sc.UltimoRecordatorio)) {
|
||||
t := *ultRec
|
||||
sc.UltimoRecordatorio = &t
|
||||
}
|
||||
sc.PagosCount++
|
||||
}
|
||||
}
|
||||
porCobrarRows.Close()
|
||||
}
|
||||
|
||||
saldos := make([]map[string]any, 0, len(saldoOrder))
|
||||
for _, cid := range saldoOrder {
|
||||
sc := saldoMap[cid]
|
||||
saldos = append(saldos, map[string]any{
|
||||
"clienteId": sc.ClienteID,
|
||||
"nombre": sc.ClienteNombre,
|
||||
"empresa": sc.ClienteEmpresa,
|
||||
"pagos": sc.PagosCount,
|
||||
"totales": sc.Totales,
|
||||
"masAntigua": sc.MasAntigua,
|
||||
"diasAtraso": domain.DiasDeAtraso(sc.MasAntigua, hoy),
|
||||
"ultimoRecordatorio": sc.UltimoRecordatorio,
|
||||
"contactable": sc.Contactable,
|
||||
})
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"programas": programas,
|
||||
"clientes": clientes,
|
||||
"pagosEnRevision": revPagos,
|
||||
"saldos": saldos,
|
||||
"diasRecordatorio": s.Cfg.CobrosRecordatorioDias,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
list, err := s.queryProgramas(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando programas")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ClienteID string `json:"clienteId"`
|
||||
CotizacionID *string `json:"cotizacionId"`
|
||||
Concepto string `json:"concepto"`
|
||||
Monto float64 `json:"monto"`
|
||||
Moneda string `json:"moneda"`
|
||||
Frecuencia string `json:"frecuencia"`
|
||||
DiaSemana *int `json:"diaSemana"`
|
||||
DiaMes *int `json:"diaMes"`
|
||||
FechaInicio string `json:"fechaInicio"`
|
||||
FechaFin *string `json:"fechaFin"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
if body.ClienteID == "" || strings.TrimSpace(body.Concepto) == "" || body.Monto <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "clienteId, concepto y monto > 0 son obligatorios")
|
||||
return
|
||||
}
|
||||
fIni, err := domain.ParseFechaCalendario(body.FechaInicio)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
var fFin *time.Time
|
||||
if body.FechaFin != nil && strings.TrimSpace(*body.FechaFin) != "" {
|
||||
t, err := domain.ParseFechaCalendario(*body.FechaFin)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
fFin = &t
|
||||
}
|
||||
frec := firstNonEmptyStr(body.Frecuencia, "semanal")
|
||||
mon := firstNonEmptyStr(body.Moneda, "MXN")
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "ProgramaPago" (
|
||||
"id", "clienteId", "cotizacionId", "concepto", "monto", "moneda",
|
||||
"frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo", "createdAt", "updatedAt"
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,NOW(),NOW())
|
||||
`, id, body.ClienteID, trimPtr(body.CotizacionID), strings.TrimSpace(body.Concepto), body.Monto, mon,
|
||||
frec, body.DiaSemana, body.DiaMes, fIni, fFin)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error creando programa de pago")
|
||||
return
|
||||
}
|
||||
|
||||
// Generate initial due charges right away
|
||||
if nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, id, nil); err == nil && len(nuevos) > 0 {
|
||||
go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"id": id, "ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleProgramasUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var raw map[string]any
|
||||
if err := decodeJSON(r, &raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
sets := []string{`"updatedAt" = NOW()`}
|
||||
args := []any{}
|
||||
add := func(col string, val any) {
|
||||
args = append(args, val)
|
||||
sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args)))
|
||||
}
|
||||
if v, ok := raw["concepto"]; ok {
|
||||
add("concepto", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["monto"]; ok {
|
||||
if m, okF := asFloat(v); okF && m > 0 {
|
||||
add("monto", m)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["moneda"]; ok {
|
||||
add("moneda", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["frecuencia"]; ok {
|
||||
add("frecuencia", strings.TrimSpace(asString(v)))
|
||||
}
|
||||
if v, ok := raw["diaSemana"]; ok {
|
||||
if n, okI := asInt(v); okI {
|
||||
add("diaSemana", n)
|
||||
} else {
|
||||
add("diaSemana", nil)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["diaMes"]; ok {
|
||||
if n, okI := asInt(v); okI {
|
||||
add("diaMes", n)
|
||||
} else {
|
||||
add("diaMes", nil)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["fechaFin"]; ok {
|
||||
sVal := strings.TrimSpace(asString(v))
|
||||
if sVal == "" {
|
||||
add("fechaFin", nil)
|
||||
} else if t, err := domain.ParseFechaCalendario(sVal); err == nil {
|
||||
add("fechaFin", t)
|
||||
}
|
||||
}
|
||||
if v, ok := raw["activo"].(bool); ok {
|
||||
add("activo", v)
|
||||
}
|
||||
args = append(args, id)
|
||||
tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ProgramaPago" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Programa no encontrado")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id})
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosGenerar(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ProgramaID string `json:"programaId"`
|
||||
Hasta string `json:"hasta"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
var hasta *time.Time
|
||||
if strings.TrimSpace(body.Hasta) != "" {
|
||||
t, err := domain.ParseFechaCalendario(body.Hasta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hasta = &t
|
||||
}
|
||||
nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, body.ProgramaID, hasta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando cobros")
|
||||
return
|
||||
}
|
||||
if len(nuevos) > 0 {
|
||||
go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "generados": len(nuevos), "ids": nuevos})
|
||||
}
|
||||
|
||||
func (s *Server) queryPagos(ctx context.Context, whereSQL string, args []any) ([]map[string]any, error) {
|
||||
rows, err := s.Pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado",
|
||||
p."verificadoAt", p."rechazadoAt", p."rechazoMotivo",
|
||||
p."ultimoRecordatorioAt", p."recordatoriosEnviados", p."nota",
|
||||
pr."concepto", pr."moneda", pr."frecuencia", pr."clienteId",
|
||||
c."nombre", c."empresa", c."email",
|
||||
comp."id", comp."archivoNombre", comp."mime", comp."tamano", comp."subidoAt"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "ComprobantePago" comp ON comp."pagoId" = p."id"
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY p."fecha" DESC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, progID, estado, concepto, moneda, frec, cid, cnom string
|
||||
var rechazoMotivo, nota, cemp, cemail, compID, compNom, compMime *string
|
||||
var fecha time.Time
|
||||
var monto float64
|
||||
var verifAt, rechAt, ultRec, compSub *time.Time
|
||||
var recCnt int
|
||||
var compTam *int
|
||||
if rows.Scan(&id, &progID, &fecha, &monto, &estado, &verifAt, &rechAt, &rechazoMotivo,
|
||||
&ultRec, &recCnt, ¬a, &concepto, &moneda, &frec, &cid, &cnom, &cemp, &cemail,
|
||||
&compID, &compNom, &compMime, &compTam, &compSub) == nil {
|
||||
var comp any
|
||||
if compID != nil {
|
||||
comp = map[string]any{
|
||||
"id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub,
|
||||
}
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": estado,
|
||||
"verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rechazoMotivo,
|
||||
"ultimoRecordatorioAt": ultRec, "recordatoriosEnviados": recCnt, "nota": nota,
|
||||
"programa": map[string]any{
|
||||
"id": progID, "concepto": concepto, "moneda": moneda, "frecuencia": frec, "clienteId": cid,
|
||||
"cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail},
|
||||
},
|
||||
"comprobante": comp,
|
||||
})
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func (s *Server) handlePagosList(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
conds := []string{"1=1"}
|
||||
args := []any{}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
if est := strings.TrimSpace(q.Get("estado")); est != "" {
|
||||
if est == "por_pagar" {
|
||||
conds = append(conds, `p."estado" IN ('pendiente', 'rechazado')`)
|
||||
} else {
|
||||
conds = append(conds, `p."estado" = `+add(est))
|
||||
}
|
||||
}
|
||||
if cid := strings.TrimSpace(q.Get("clienteId")); cid != "" {
|
||||
conds = append(conds, `pr."clienteId" = `+add(cid))
|
||||
}
|
||||
if pid := strings.TrimSpace(q.Get("programaId")); pid != "" {
|
||||
conds = append(conds, `p."programaId" = `+add(pid))
|
||||
}
|
||||
if d := strings.TrimSpace(q.Get("desde")); d != "" {
|
||||
if t, err := domain.ParseFechaCalendario(d); err == nil {
|
||||
conds = append(conds, `p."fecha" >= `+add(t))
|
||||
}
|
||||
}
|
||||
if h := strings.TrimSpace(q.Get("hasta")); h != "" {
|
||||
if t, err := domain.ParseFechaCalendario(h); err == nil {
|
||||
conds = append(conds, `p."fecha" <= `+add(t))
|
||||
}
|
||||
}
|
||||
list, err := s.queryPagos(r.Context(), strings.Join(conds, " AND "), args)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error listando pagos")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoAprobar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var estado string
|
||||
var monto float64
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoEnRevision {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden aprobar cobros en revision")
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='verificado', "verificadoAt"=$1, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW()
|
||||
WHERE "id" = $2
|
||||
`, now, id)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error aprobando comprobante")
|
||||
return
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "pago.aprobar_comprobante", RecursoTipo: "pago", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
})
|
||||
go s.Notify.NotificarVerificacion(context.Background(), id)
|
||||
go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{
|
||||
"pagoId": id, "monto": monto, "metodo": "comprobante_verificado", "verificadoAt": now.UTC().Format(time.RFC3339),
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": now})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoRechazar(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Motivo string `json:"motivo"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
motivo := strings.TrimSpace(body.Motivo)
|
||||
if motivo == "" {
|
||||
writeError(w, http.StatusBadRequest, "El motivo del rechazo es obligatorio")
|
||||
return
|
||||
}
|
||||
|
||||
var ruta string
|
||||
_ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, id).Scan(&ruta)
|
||||
if ruta != "" {
|
||||
_ = uploads.EliminarComprobante(s.Cfg.UploadDir, ruta)
|
||||
_, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, id)
|
||||
}
|
||||
|
||||
tag, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='rechazado', "rechazadoAt"=NOW(), "rechazoMotivo"=$1, "updatedAt"=NOW()
|
||||
WHERE "id" = $2
|
||||
`, motivo, id)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
go s.Notify.NotificarRechazo(context.Background(), id, motivo)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "rechazado"})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoRegistrar(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:registrar"}, RecursoTipo: "pago"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) {
|
||||
var body struct {
|
||||
Fecha string `json:"fecha"`
|
||||
Nota *string `json:"nota"`
|
||||
}
|
||||
if err := json.Unmarshal(rawBody, &body); err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": "JSON invalido"}
|
||||
}
|
||||
hoy := domain.HoyCalendario()
|
||||
fPago := hoy
|
||||
if strings.TrimSpace(body.Fecha) != "" {
|
||||
t, err := domain.ParseFechaCalendario(body.Fecha)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, map[string]any{"error": err.Error()}
|
||||
}
|
||||
if t.After(hoy) {
|
||||
return http.StatusBadRequest, map[string]any{"error": "La fecha de pago no puede ser futura"}
|
||||
}
|
||||
fPago = t
|
||||
}
|
||||
|
||||
var estado string
|
||||
var monto float64
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil {
|
||||
return http.StatusNotFound, map[string]any{"error": "Cobro no encontrado"}
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
return http.StatusConflict, map[string]any{"error": "Solo se pueden registrar cobros pendientes o rechazados"}
|
||||
}
|
||||
|
||||
verifAt := domain.InstanteDePago(fPago)
|
||||
_, err := s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "estado"='verificado', "verificadoAt"=$1, "nota"=$2, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW()
|
||||
WHERE "id" = $3
|
||||
`, verifAt, trimPtr(body.Nota), id)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, map[string]any{"error": "Error registrando pago"}
|
||||
}
|
||||
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "pago.registrar", RecursoTipo: "pago", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true,
|
||||
Detalle: map[string]any{"fecha": fPago.Format("2006-01-02"), "nota": body.Nota},
|
||||
})
|
||||
go s.Notify.NotificarVerificacion(context.Background(), id)
|
||||
go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{
|
||||
"pagoId": id, "monto": monto, "metodo": "registro_manual", "verificadoAt": verifAt.UTC().Format(time.RFC3339),
|
||||
})
|
||||
return http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": verifAt}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoAnular(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Motivo string `json:"motivo"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
motivo := strings.TrimSpace(body.Motivo)
|
||||
if motivo == "" {
|
||||
writeError(w, http.StatusBadRequest, "El motivo es obligatorio")
|
||||
return
|
||||
}
|
||||
var estado string
|
||||
if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado); err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden anular cobros pendientes o rechazados")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `UPDATE "PagoRecurrente" SET "estado"='anulado', "nota"=$1, "updatedAt"=NOW() WHERE "id" = $2`, motivo, id)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "anulado"})
|
||||
}
|
||||
|
||||
func (s *Server) handlePagoReabrir(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
var estado string
|
||||
var hasComp bool
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT p."estado", EXISTS(SELECT 1 FROM "ComprobantePago" c WHERE c."pagoId" = p."id")
|
||||
FROM "PagoRecurrente" p WHERE p."id" = $1
|
||||
`, id).Scan(&estado, &hasComp)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cobro no encontrado")
|
||||
return
|
||||
}
|
||||
if estado == domain.EstadoPagoVerificado && hasComp {
|
||||
writeError(w, http.StatusConflict, "No se puede reabrir un cobro verificado con comprobante")
|
||||
return
|
||||
}
|
||||
if estado != domain.EstadoPagoVerificado && estado != domain.EstadoPagoAnulado {
|
||||
writeError(w, http.StatusConflict, "Solo se pueden reabrir cobros anulados o registrados manualmente")
|
||||
return
|
||||
}
|
||||
_, _ = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PagoRecurrente" SET "estado"='pendiente', "verificadoAt"=NULL, "nota"=NULL, "updatedAt"=NOW() WHERE "id" = $1
|
||||
`, id)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "pendiente"})
|
||||
}
|
||||
|
||||
func (s *Server) handleCobrosRecordatorios(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ClienteID string `json:"clienteId"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
res, err := s.Notify.EnviarRecordatoriosPendientes(r.Context(), strings.TrimSpace(body.ClienteID), true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error enviando recordatorios")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func (s *Server) handleComprobanteGet(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.Auth.SessionFromRequest(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "No autenticado")
|
||||
return
|
||||
}
|
||||
pagoID := chi.URLParam(r, "pagoId")
|
||||
var ruta, nombre, mime, ownerClienteID string
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT c."archivoRuta", c."archivoNombre", c."mime", pr."clienteId"
|
||||
FROM "ComprobantePago" c
|
||||
JOIN "PagoRecurrente" p ON p."id" = c."pagoId"
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
WHERE c."pagoId" = $1
|
||||
`, pagoID).Scan(&ruta, &nombre, &mime, &ownerClienteID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "Comprobante no encontrado")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error consultando comprobante")
|
||||
return
|
||||
}
|
||||
if sess.Role == "cliente" && sess.ClienteID != ownerClienteID {
|
||||
writeError(w, http.StatusForbidden, "No tienes acceso a este comprobante")
|
||||
return
|
||||
}
|
||||
absPath, err := uploads.RutaAbsoluta(s.Cfg.UploadDir, ruta)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusForbidden, "Ruta invalida")
|
||||
return
|
||||
}
|
||||
data, err := os.ReadFile(absPath)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Archivo no encontrado en disco")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", mime)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, domain.SanitizeFilename(nombre)))
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,649 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/audit"
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/excel"
|
||||
"cotizador/internal/pdf"
|
||||
"cotizador/internal/propuesta"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Server) loadBonosPDF(ctx context.Context) []pdf.BonoPDF {
|
||||
rows, err := s.Pool.Query(ctx, `SELECT "numero", "descripcion" FROM "Bono" WHERE "activo" = true ORDER BY "numero" ASC`)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []pdf.BonoPDF
|
||||
for rows.Next() {
|
||||
var b pdf.BonoPDF
|
||||
if rows.Scan(&b.Numero, &b.Descripcion) == nil {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) buildQuotePDFBytes(ctx context.Context, full *cotizacionFull) ([]byte, error) {
|
||||
branding := s.getConfigBranding(ctx)
|
||||
var bonos []pdf.BonoPDF
|
||||
if full.IncluirBonos {
|
||||
bonos = s.loadBonosPDF(ctx)
|
||||
}
|
||||
return pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{
|
||||
Numero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
AsesorNombre: full.AsesorName,
|
||||
Fecha: full.Fecha,
|
||||
Vigencia: full.Vigencia,
|
||||
Moneda: full.Moneda,
|
||||
TipoCambio: full.TipoCambio,
|
||||
Proyecto: full.Proyecto,
|
||||
EsquemaPago: full.EsquemaPago,
|
||||
Servicios: full.ServiciosPDF,
|
||||
EsDoble: full.EsDoble,
|
||||
OpcionesMetadata: full.OpcionesMetadata,
|
||||
PlanBucefaloNivel: full.PlanBucefaloNv,
|
||||
PlanBucefaloPrecio: full.PlanBucefaloPr,
|
||||
IncluirBonos: full.IncluirBonos,
|
||||
Bonos: bonos,
|
||||
IncluirIVA: full.IncluirIVA,
|
||||
Observaciones: full.Observaciones,
|
||||
ConfigBancaria: s.getConfigBancaria(ctx),
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleExportPDFByID(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{
|
||||
AllowCliente: true,
|
||||
Scopes: []string{"cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas"},
|
||||
RecursoTipo: "cotizacion_pdf",
|
||||
})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
if actor.IsCliente() && full.ClienteID != actor.ClienteID {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
if actor.EsAgenteSoloAceptadas() && full.Estado != "aceptada" {
|
||||
tipo, aid, anom := actor.AuditActor()
|
||||
audit.Registrar(r.Context(), s.Pool, audit.Entry{
|
||||
ActorTipo: tipo, ActorID: aid, ActorNombre: anom,
|
||||
Accion: "cotizacion.export_pdf_bloqueado", RecursoTipo: "cotizacion", RecursoID: id,
|
||||
IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false,
|
||||
})
|
||||
writeError(w, http.StatusForbidden, "Solo puedes exportar PDF de cotizaciones aceptadas")
|
||||
return
|
||||
}
|
||||
|
||||
pdfBytes, err := s.buildQuotePDFBytes(r.Context(), full)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(full.Numero)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
|
||||
type draftExportBody struct {
|
||||
Draft *draftExportPayload `json:"draft"`
|
||||
draftExportPayload
|
||||
}
|
||||
|
||||
type draftExportPayload struct {
|
||||
Numero string `json:"numero"`
|
||||
ClienteNombre string `json:"clienteNombre"`
|
||||
ClienteEmpresa string `json:"clienteEmpresa"`
|
||||
AsesorNombre string `json:"asesorNombre"`
|
||||
Fecha string `json:"fecha"`
|
||||
Vigencia string `json:"vigencia"`
|
||||
Moneda string `json:"moneda"`
|
||||
TipoCambio string `json:"tipoCambio"`
|
||||
Proyecto string `json:"proyecto"`
|
||||
EsquemaPago string `json:"esquemaPago"`
|
||||
IncluirBonos bool `json:"incluirBonos"`
|
||||
IncluirIVA *bool `json:"incluirIva"`
|
||||
EsDoble bool `json:"esDoble"`
|
||||
OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"`
|
||||
Observaciones *string `json:"observaciones"`
|
||||
PlanBucefaloNivel *string `json:"planBucefaloNivel"`
|
||||
PlanBucefaloPrecio *float64 `json:"planBucefaloPrecio"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio *float64 `json:"precio"`
|
||||
Seleccionado *bool `json:"seleccionado"`
|
||||
} `json:"planBucefalo"`
|
||||
Servicios []servicioInputDTO `json:"servicios"`
|
||||
}
|
||||
|
||||
func (s *Server) handleExportPDFDraft(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_pdf"}); !ok {
|
||||
return
|
||||
}
|
||||
var wrap draftExportBody
|
||||
if err := decodeJSON(r, &wrap); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Borrador invalido")
|
||||
return
|
||||
}
|
||||
d := wrap.draftExportPayload
|
||||
if wrap.Draft != nil {
|
||||
d = *wrap.Draft
|
||||
}
|
||||
fecha := time.Now()
|
||||
if t, err := parseFlexibleDate(d.Fecha); err == nil {
|
||||
fecha = t
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
if t, err := parseFlexibleDate(d.Vigencia); err == nil {
|
||||
vigencia = t
|
||||
}
|
||||
incluirIVA := true
|
||||
if d.IncluirIVA != nil {
|
||||
incluirIVA = *d.IncluirIVA
|
||||
}
|
||||
svcs := make([]pdf.ServicioPDF, 0, len(d.Servicios))
|
||||
for _, sv := range d.Servicios {
|
||||
if sv.Seleccionado != nil && !*sv.Seleccionado {
|
||||
continue
|
||||
}
|
||||
svcs = append(svcs, pdf.ServicioPDF{
|
||||
Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase,
|
||||
TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio,
|
||||
TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"),
|
||||
Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado,
|
||||
Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"),
|
||||
MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
pbNivel, pbPrecio := resolveDraftBucefalo(d)
|
||||
branding := s.getConfigBranding(r.Context())
|
||||
var bonos []pdf.BonoPDF
|
||||
if d.IncluirBonos {
|
||||
bonos = s.loadBonosPDF(r.Context())
|
||||
}
|
||||
pdfBytes, err := pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{
|
||||
Numero: firstNonEmptyStr(d.Numero, "BORRADOR"),
|
||||
ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"),
|
||||
ClienteEmpresa: d.ClienteEmpresa,
|
||||
AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"),
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: firstNonEmptyStr(d.Moneda, "MXN"),
|
||||
TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"),
|
||||
Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"),
|
||||
EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"),
|
||||
Servicios: svcs,
|
||||
EsDoble: d.EsDoble,
|
||||
OpcionesMetadata: d.OpcionesMetadata,
|
||||
PlanBucefaloNivel: pbNivel,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
IncluirBonos: d.IncluirBonos,
|
||||
Bonos: bonos,
|
||||
IncluirIVA: incluirIVA,
|
||||
Observaciones: d.Observaciones,
|
||||
ConfigBancaria: s.getConfigBancaria(r.Context()),
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF de borrador")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR"))))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportExcelByID(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok {
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), id, true)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
cfgMap := s.getAllConfigMap(r.Context())
|
||||
svcs := make([]excel.ServicioExcel, 0, len(full.ServiciosPDF))
|
||||
for _, sv := range full.ServiciosPDF {
|
||||
svcs = append(svcs, excel.ServicioExcel{
|
||||
Nombre: sv.Nombre, Fase: sv.Fase, TipoPago: sv.TipoPago, Precio: sv.Precio,
|
||||
TiempoEntrega: sv.TiempoEntrega, Entregables: sv.Entregables,
|
||||
EsPersonalizado: sv.EsPersonalizado, Horas: sv.Horas, TarifaHora: sv.TarifaHora,
|
||||
ModeloCobro: sv.ModeloCobro, MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
var pbPrecio *float64
|
||||
if full.PlanBucefaloNv != nil {
|
||||
p := full.PlanBucefaloPr
|
||||
pbPrecio = &p
|
||||
}
|
||||
xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{
|
||||
RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"),
|
||||
DomicilioFiscal: cfgMap["domicilio_fiscal"],
|
||||
Numero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
AsesorNombre: full.AsesorName,
|
||||
Fecha: full.Fecha,
|
||||
Vigencia: full.Vigencia,
|
||||
Moneda: full.Moneda,
|
||||
TipoCambio: full.TipoCambio,
|
||||
Proyecto: full.Proyecto,
|
||||
EsquemaPago: full.EsquemaPago,
|
||||
Servicios: svcs,
|
||||
EsDoble: full.EsDoble,
|
||||
OpcionesMetadata: full.OpcionesMetadata,
|
||||
PlanBucefaloNivel: full.PlanBucefaloNv,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"),
|
||||
IncluirIVA: full.IncluirIVA,
|
||||
Observaciones: full.Observaciones,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando Excel")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(full.Numero)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(xlsxBytes)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportExcelDraft(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok {
|
||||
return
|
||||
}
|
||||
var wrap draftExportBody
|
||||
if err := decodeJSON(r, &wrap); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Borrador invalido")
|
||||
return
|
||||
}
|
||||
d := wrap.draftExportPayload
|
||||
if wrap.Draft != nil {
|
||||
d = *wrap.Draft
|
||||
}
|
||||
fecha := time.Now()
|
||||
if t, err := parseFlexibleDate(d.Fecha); err == nil {
|
||||
fecha = t
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
if t, err := parseFlexibleDate(d.Vigencia); err == nil {
|
||||
vigencia = t
|
||||
}
|
||||
incluirIVA := true
|
||||
if d.IncluirIVA != nil {
|
||||
incluirIVA = *d.IncluirIVA
|
||||
}
|
||||
svcs := make([]excel.ServicioExcel, 0, len(d.Servicios))
|
||||
for _, sv := range d.Servicios {
|
||||
if sv.Seleccionado != nil && !*sv.Seleccionado {
|
||||
continue
|
||||
}
|
||||
svcs = append(svcs, excel.ServicioExcel{
|
||||
Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase,
|
||||
TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio,
|
||||
TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"),
|
||||
Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado,
|
||||
Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"),
|
||||
MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion,
|
||||
})
|
||||
}
|
||||
pbNivel, pbPrecioVal := resolveDraftBucefalo(d)
|
||||
var pbPrecio *float64
|
||||
if pbNivel != nil {
|
||||
pbPrecio = &pbPrecioVal
|
||||
}
|
||||
cfgMap := s.getAllConfigMap(r.Context())
|
||||
xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{
|
||||
RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"),
|
||||
DomicilioFiscal: cfgMap["domicilio_fiscal"],
|
||||
Numero: firstNonEmptyStr(d.Numero, "BORRADOR"),
|
||||
ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"),
|
||||
ClienteEmpresa: d.ClienteEmpresa,
|
||||
AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"),
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: firstNonEmptyStr(d.Moneda, "MXN"),
|
||||
TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"),
|
||||
Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"),
|
||||
EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"),
|
||||
Servicios: svcs,
|
||||
EsDoble: d.EsDoble,
|
||||
OpcionesMetadata: d.OpcionesMetadata,
|
||||
PlanBucefaloNivel: pbNivel,
|
||||
PlanBucefaloPrecio: pbPrecio,
|
||||
ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"),
|
||||
IncluirIVA: incluirIVA,
|
||||
Observaciones: d.Observaciones,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando Excel de borrador")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR"))))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(xlsxBytes)
|
||||
}
|
||||
|
||||
func resolveDraftBucefalo(d draftExportPayload) (*string, float64) {
|
||||
if d.PlanBucefalo != nil {
|
||||
if d.PlanBucefalo.Seleccionado != nil && !*d.PlanBucefalo.Seleccionado {
|
||||
return nil, 0
|
||||
}
|
||||
nv := d.PlanBucefalo.Nivel
|
||||
pr := domain.BucefaloPrecio(nv)
|
||||
if d.PlanBucefalo.Precio != nil {
|
||||
pr = *d.PlanBucefalo.Precio
|
||||
}
|
||||
return &nv, pr
|
||||
}
|
||||
if d.PlanBucefaloNivel != nil && *d.PlanBucefaloNivel != "" {
|
||||
pr := domain.BucefaloPrecio(*d.PlanBucefaloNivel)
|
||||
if d.PlanBucefaloPrecio != nil {
|
||||
pr = *d.PlanBucefaloPrecio
|
||||
}
|
||||
return d.PlanBucefaloNivel, pr
|
||||
}
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// ── Propuesta Consultiva IA ──────────────────────────────────────────────────
|
||||
|
||||
func (s *Server) handlePropuestaIAGet(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var id, estado, modelo string
|
||||
var contenidoIA, contenidoEditado, traza, avisos []byte
|
||||
var transcripcion, aprobadaPor *string
|
||||
var aprobadaAt *time.Time
|
||||
var createdAt, updatedAt time.Time
|
||||
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "estado", "contenidoIA", "contenidoEditado", "transcripcion", "traza", "avisos",
|
||||
"modelo", "aprobadaPor", "aprobadaAt", "createdAt", "updatedAt"
|
||||
FROM "PropuestaIA"
|
||||
WHERE "cotizacionId" = $1
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT 1
|
||||
`, cotID).Scan(&id, &estado, &contenidoIA, &contenidoEditado, &transcripcion, &traza, &avisos,
|
||||
&modelo, &aprobadaPor, &aprobadaAt, &createdAt, &updatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"propuesta": nil})
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando propuesta IA")
|
||||
return
|
||||
}
|
||||
|
||||
var cIA, cEd, tr, av any
|
||||
_ = json.Unmarshal(contenidoIA, &cIA)
|
||||
if len(contenidoEditado) > 0 {
|
||||
_ = json.Unmarshal(contenidoEditado, &cEd)
|
||||
}
|
||||
if len(traza) > 0 {
|
||||
_ = json.Unmarshal(traza, &tr)
|
||||
}
|
||||
_ = json.Unmarshal(avisos, &av)
|
||||
if av == nil {
|
||||
av = []any{}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"propuesta": map[string]any{
|
||||
"id": id, "cotizacionId": cotID, "estado": estado,
|
||||
"contenidoIA": cIA, "contenidoEditado": cEd, "transcripcion": transcripcion,
|
||||
"traza": tr, "avisos": av, "modelo": modelo,
|
||||
"aprobadaPor": aprobadaPor, "aprobadaAt": aprobadaAt,
|
||||
"createdAt": createdAt, "updatedAt": updatedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIACreate(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Transcripcion string `json:"transcripcion"`
|
||||
NotasAdicionales string `json:"notasAdicionales"`
|
||||
}
|
||||
_ = decodeJSON(r, &body)
|
||||
|
||||
res, err := propuesta.GenerarPropuesta(r.Context(), s.Cfg, s.Pool, propuesta.GenerarInput{
|
||||
CotizacionID: cotID,
|
||||
Transcripcion: body.Transcripcion,
|
||||
NotasAdicionales: body.NotasAdicionales,
|
||||
})
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "doble") || strings.Contains(err.Error(), "partidas") || strings.Contains(err.Error(), "MINIMAX_API_KEY") {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
cJSON, _ := json.Marshal(res.Contenido)
|
||||
tJSON, _ := json.Marshal(res.Traza)
|
||||
aJSON, _ := json.Marshal(res.Avisos)
|
||||
|
||||
id := db.NewID()
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
INSERT INTO "PropuestaIA" ("id", "cotizacionId", "estado", "contenidoIA", "transcripcion", "traza", "avisos", "modelo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, 'borrador', $3, $4, $5, $6, $7, NOW(), NOW())
|
||||
`, id, cotID, cJSON, nullableTrim(body.Transcripcion), tJSON, aJSON, res.Modelo)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error guardando propuesta IA")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"propuesta": map[string]any{
|
||||
"id": id, "cotizacionId": cotID, "estado": "borrador",
|
||||
"contenidoIA": res.Contenido, "contenidoEditado": nil,
|
||||
"transcripcion": nullableTrim(body.Transcripcion),
|
||||
"traza": res.Traza, "avisos": res.Avisos, "modelo": res.Modelo,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIAPatch(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
ContenidoEditado map[string]any `json:"contenidoEditado"`
|
||||
Estado string `json:"estado"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "JSON invalido")
|
||||
return
|
||||
}
|
||||
|
||||
var propID string
|
||||
var transcripcion *string
|
||||
var contenidoIA []byte
|
||||
err := s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "id", "transcripcion", "contenidoIA" FROM "PropuestaIA"
|
||||
WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1
|
||||
`, cotID).Scan(&propID, &transcripcion, &contenidoIA)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Propuesta IA no encontrada")
|
||||
return
|
||||
}
|
||||
|
||||
contenido := body.ContenidoEditado
|
||||
if contenido == nil {
|
||||
_ = json.Unmarshal(contenidoIA, &contenido)
|
||||
}
|
||||
|
||||
full, _, _ := s.loadCotizacionFull(r.Context(), cotID, false)
|
||||
econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando economia de cotizacion")
|
||||
return
|
||||
}
|
||||
fuentesCliente := derefStr(transcripcion)
|
||||
if full != nil && full.Observaciones != nil {
|
||||
fuentesCliente += "\n" + *full.Observaciones
|
||||
}
|
||||
notasInternas := ""
|
||||
if full != nil && full.ObservacionesInternas != nil {
|
||||
notasInternas = *full.ObservacionesInternas
|
||||
}
|
||||
avisos := propuesta.ValidarPropuesta(contenido, econ, fuentesCliente, notasInternas)
|
||||
|
||||
cEdJSON, _ := json.Marshal(contenido)
|
||||
avJSON, _ := json.Marshal(avisos)
|
||||
estado := "borrador"
|
||||
var aprobadaPor *string
|
||||
var aprobadaAt *time.Time
|
||||
if body.Estado == "aprobada" {
|
||||
if propuesta.HayBloqueantes(avisos) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "Hay avisos bloqueantes pendientes por resolver", "avisos": avisos})
|
||||
return
|
||||
}
|
||||
estado = "aprobada"
|
||||
ap := actor.Email
|
||||
aprobadaPor = &ap
|
||||
now := time.Now()
|
||||
aprobadaAt = &now
|
||||
}
|
||||
|
||||
_, err = s.Pool.Exec(r.Context(), `
|
||||
UPDATE "PropuestaIA"
|
||||
SET "contenidoEditado" = $1, "avisos" = $2, "estado" = $3, "aprobadaPor" = COALESCE($4, "aprobadaPor"), "aprobadaAt" = COALESCE($5, "aprobadaAt"), "updatedAt" = NOW()
|
||||
WHERE "id" = $6
|
||||
`, cEdJSON, avJSON, estado, aprobadaPor, aprobadaAt, propID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error actualizando propuesta IA")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true, "id": propID, "estado": estado, "contenidoEditado": contenido, "avisos": avisos,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePropuestaIAPDF(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok {
|
||||
return
|
||||
}
|
||||
cotID := chi.URLParam(r, "id")
|
||||
anexo := r.URL.Query().Get("anexo") == "1"
|
||||
|
||||
full, _, err := s.loadCotizacionFull(r.Context(), cotID, false)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "Cotizacion no encontrada")
|
||||
return
|
||||
}
|
||||
|
||||
var contenidoIA, contenidoEditado, avisosRaw []byte
|
||||
err = s.Pool.QueryRow(r.Context(), `
|
||||
SELECT "contenidoIA", "contenidoEditado", "avisos"
|
||||
FROM "PropuestaIA" WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1
|
||||
`, cotID).Scan(&contenidoIA, &contenidoEditado, &avisosRaw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "No existe una propuesta IA generada para esta cotizacion")
|
||||
return
|
||||
}
|
||||
|
||||
var avisos []propuesta.Aviso
|
||||
_ = json.Unmarshal(avisosRaw, &avisos)
|
||||
if !anexo && propuesta.HayBloqueantes(avisos) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "Resuelve los avisos bloqueantes antes de exportar el PDF para el cliente", "avisos": avisos})
|
||||
return
|
||||
}
|
||||
|
||||
var contenido map[string]any
|
||||
if len(contenidoEditado) > 0 {
|
||||
_ = json.Unmarshal(contenidoEditado, &contenido)
|
||||
} else {
|
||||
_ = json.Unmarshal(contenidoIA, &contenido)
|
||||
}
|
||||
|
||||
econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error cargando economia")
|
||||
return
|
||||
}
|
||||
econBytes, _ := json.Marshal(econ)
|
||||
var econMap map[string]any
|
||||
_ = json.Unmarshal(econBytes, &econMap)
|
||||
|
||||
branding := s.getConfigBranding(r.Context())
|
||||
in := pdf.PropuestaPDFInput{
|
||||
CotizacionNumero: full.Numero,
|
||||
ClienteNombre: full.ClienteNombre,
|
||||
ClienteEmpresa: derefStr(full.ClienteEmpresa),
|
||||
Proyecto: full.Proyecto,
|
||||
Moneda: full.Moneda,
|
||||
Fecha: full.Fecha,
|
||||
Contenido: contenido,
|
||||
Economia: econMap,
|
||||
ColorPrimario: branding.ColorPrimario,
|
||||
ColorSecundario: branding.ColorSecundario,
|
||||
LogoBase64: branding.LogoBase64,
|
||||
LogoMime: branding.LogoMime,
|
||||
}
|
||||
|
||||
var pdfBytes []byte
|
||||
var filename string
|
||||
if anexo {
|
||||
pdfBytes, err = pdf.GenerarAnexoInternoPDF(in)
|
||||
filename = fmt.Sprintf("AnexoInterno_%s.pdf", domain.SanitizeFilename(full.Numero))
|
||||
} else {
|
||||
pdfBytes, err = pdf.GenerarPropuestaPDF(in)
|
||||
filename = fmt.Sprintf("PropuestaConsultiva_%s.pdf", domain.SanitizeFilename(full.Numero))
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Error generando PDF de propuesta IA: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(pdfBytes)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
Port: "3000",
|
||||
AppURL: "https://cotizador.urieljareth.org",
|
||||
JWTSecret: "test-secret-key-for-httpapi-tests-32b",
|
||||
}
|
||||
authSvc := auth.NewService(cfg.JWTSecret, false, nil)
|
||||
srv := NewServer(cfg, nil, authSvc, nil, nil)
|
||||
return srv, srv.Router()
|
||||
}
|
||||
|
||||
func makeCookie(t *testing.T, authSvc *auth.Service, sess auth.SessionPayload) *http.Cookie {
|
||||
t.Helper()
|
||||
tok, err := authSvc.SignSession(sess)
|
||||
if err != nil {
|
||||
t.Fatalf("SignSession: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: auth.SessionCookieName, Value: tok}
|
||||
}
|
||||
|
||||
func TestOpenAPIAndSPARouting(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
// 1. OpenAPI 3.1
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/openapi.json", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for /api/openapi.json, got %d", rec.Code)
|
||||
}
|
||||
var spec map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &spec); err != nil {
|
||||
t.Fatalf("invalid openapi json: %v", err)
|
||||
}
|
||||
if spec["openapi"] != "3.1.0" {
|
||||
t.Fatalf("expected openapi 3.1.0, got %v", spec["openapi"])
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "cotizaciones:approve") {
|
||||
t.Fatal("iron-clad rule violation: openapi mentions cotizaciones:approve")
|
||||
}
|
||||
|
||||
// 2. Unknown /api/* route returns 404 JSON, NOT SPA HTML
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/does-not-exist", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 for unknown /api route, got %d", rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Header().Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("expected JSON content-type for unknown /api route, got %q", rec.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
// 3. SPA routes serve HTML
|
||||
for _, p := range []string{"/", "/login", "/cotizaciones", "/cliente/pagos"} {
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, p, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for SPA path %s, got %d", p, rec.Code)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(rec.Body.String()), "<html") && !strings.Contains(strings.ToLower(rec.Body.String()), "<!doctype html") {
|
||||
t.Fatalf("expected HTML body for SPA path %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedRoutesRejectUnauthenticated(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/auth/me"},
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/asesores"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
{http.MethodPut, "/api/configuracion"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodPost, "/api/catalogo"},
|
||||
{http.MethodPut, "/api/categorias/cat-1"},
|
||||
{http.MethodDelete, "/api/categorias/cat-1"},
|
||||
{http.MethodGet, "/api/paquetes/paq-1"},
|
||||
{http.MethodPost, "/api/paquetes/paq-1/manage"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodPost, "/api/clientes"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/enviar"},
|
||||
{http.MethodGet, "/api/cotizaciones/q1/horas"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/nota-horas"},
|
||||
{http.MethodPost, "/api/export/pdf"},
|
||||
{http.MethodGet, "/api/export/pdf/q1"},
|
||||
{http.MethodPost, "/api/export/excel"},
|
||||
{http.MethodGet, "/api/export/excel/q1"},
|
||||
{http.MethodGet, "/api/export/catalogo"},
|
||||
{http.MethodPost, "/api/import/catalogo"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPost, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPatch, "/api/propuesta-ia/q1"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1/pdf"},
|
||||
{http.MethodGet, "/api/cobros/resumen"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/cobros/pagos"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/comprobantes/p1"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s without auth: expected 401, got %d (body: %s)", tc.method, tc.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelAndRoleIsolation(t *testing.T) {
|
||||
srv, router := newTestServer(t)
|
||||
|
||||
clienteCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-cli-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Cliente Demo",
|
||||
Role: "cliente",
|
||||
ClienteID: "cli-1",
|
||||
})
|
||||
asesorCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-ase-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Asesor Demo",
|
||||
Role: "asesor",
|
||||
})
|
||||
adminCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-adm-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Uriel Admin",
|
||||
Role: "admin",
|
||||
})
|
||||
|
||||
// Cliente cannot access staff routes
|
||||
staffPaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
}
|
||||
for _, tc := range staffPaths {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(clienteCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("cliente -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Staff (admin/asesor) cannot access /api/cliente/*
|
||||
clientePaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/cliente/push/config"},
|
||||
{http.MethodPost, "/api/cliente/push/suscribir"},
|
||||
{http.MethodDelete, "/api/cliente/push/suscribir"},
|
||||
}
|
||||
for _, tc := range clientePaths {
|
||||
for _, ck := range []*http.Cookie{adminCookie, asesorCookie} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("staff -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asesor cannot access strictly admin-only routes (including aprobar!)
|
||||
adminOnly := []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/rotate"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/revoke"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodPost, "/api/webhooks"},
|
||||
{http.MethodDelete, "/api/webhooks/w1"},
|
||||
{http.MethodGet, "/api/webhooks/deliveries"},
|
||||
}
|
||||
for _, tc := range adminOnly {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(asesorCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("asesor -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/me works for both admin and cliente without DB
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ck *http.Cookie
|
||||
role string
|
||||
}{
|
||||
{"admin", adminCookie, "admin"},
|
||||
{"cliente", clienteCookie, "cliente"},
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
|
||||
req.AddCookie(tc.ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/me (%s): expected 200, got %d", tc.name, rec.Code)
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
u, _ := out["user"].(map[string]any)
|
||||
if u["role"] != tc.role {
|
||||
t.Fatalf("/api/auth/me (%s): expected role %s, got %v", tc.name, tc.role, u["role"])
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/logout clears session cookie
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/logout: expected 200, got %d", rec.Code)
|
||||
}
|
||||
var cleared bool
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == auth.SessionCookieName && c.MaxAge < 0 {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Fatal("expected logout to clear cotizador-session cookie")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/notify"
|
||||
"cotizador/internal/spa"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Cfg *config.Config
|
||||
Pool *pgxpool.Pool
|
||||
Auth *auth.Service
|
||||
Webhooks *webhooks.Dispatcher
|
||||
Notify *notify.Service
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config, pool *pgxpool.Pool, authSvc *auth.Service, wh *webhooks.Dispatcher, notif *notify.Service) *Server {
|
||||
return &Server{
|
||||
Cfg: cfg,
|
||||
Pool: pool,
|
||||
Auth: authSvc,
|
||||
Webhooks: wh,
|
||||
Notify: notif,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
// API routes
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
// Public
|
||||
r.Get("/health", s.handleHealth)
|
||||
r.Get("/openapi.json", s.handleOpenAPI)
|
||||
r.Post("/auth/login", s.handleLogin)
|
||||
r.Post("/auth/logout", s.handleLogout)
|
||||
r.Get("/auth/me", s.handleMe)
|
||||
r.Get("/aprobar/{token}", s.handleAprobarTokenGet)
|
||||
r.Post("/aprobar/{token}", s.handleAprobarTokenPost)
|
||||
|
||||
// SPA helpers (staff)
|
||||
r.Get("/dashboard", s.handleDashboard)
|
||||
r.Get("/asesores", s.handleAsesores)
|
||||
|
||||
// Admin control plane
|
||||
r.Get("/agent-keys", s.handleAgentKeysList)
|
||||
r.Post("/agent-keys", s.handleAgentKeysCreate)
|
||||
r.Post("/agent-keys/{id}/rotate", s.handleAgentKeysRotate)
|
||||
r.Post("/agent-keys/{id}/revoke", s.handleAgentKeysRevoke)
|
||||
r.Get("/audit-logs", s.handleAuditLogs)
|
||||
r.Get("/webhooks", s.handleWebhooksList)
|
||||
r.Post("/webhooks", s.handleWebhooksCreate)
|
||||
r.Delete("/webhooks/{id}", s.handleWebhooksDelete)
|
||||
r.Get("/webhooks/deliveries", s.handleWebhooksDeliveries)
|
||||
|
||||
// Configuracion
|
||||
r.Get("/configuracion", s.handleConfiguracionGet)
|
||||
r.Put("/configuracion", s.handleConfiguracionPut)
|
||||
|
||||
// Catalogo, Categorias, Paquetes
|
||||
r.Get("/catalogo", s.handleCatalogoList)
|
||||
r.Post("/catalogo", s.handleCatalogoCreate)
|
||||
r.Get("/catalogo/{id}", s.handleCatalogoGet)
|
||||
r.Patch("/catalogo/{id}", s.handleCatalogoPatch)
|
||||
r.Put("/catalogo/{id}", s.handleCatalogoPatch)
|
||||
r.Delete("/catalogo/{id}", s.handleCatalogoDelete)
|
||||
|
||||
r.Get("/categorias", s.handleCategoriasList)
|
||||
r.Post("/categorias", s.handleCategoriasCreate)
|
||||
r.Put("/categorias/{id}", s.handleCategoriasUpdate)
|
||||
r.Delete("/categorias/{id}", s.handleCategoriasDelete)
|
||||
|
||||
r.Get("/paquetes", s.handlePaquetesList)
|
||||
r.Post("/paquetes", s.handlePaquetesCreate)
|
||||
r.Get("/paquetes/{id}", s.handlePaquetesGet)
|
||||
r.Put("/paquetes/{id}", s.handlePaquetesUpdate)
|
||||
r.Delete("/paquetes/{id}", s.handlePaquetesDelete)
|
||||
r.Post("/paquetes/{id}/manage", s.handlePaquetesManage)
|
||||
|
||||
// Clientes
|
||||
r.Get("/clientes", s.handleClientesList)
|
||||
r.Post("/clientes", s.handleClientesCreate)
|
||||
r.Patch("/clientes/{id}", s.handleClientesUpdate)
|
||||
r.Post("/clientes/{id}/acceso", s.handleClienteAccesoCreate)
|
||||
r.Delete("/clientes/{id}/acceso", s.handleClienteAccesoDelete)
|
||||
r.Post("/clientes/{id}/archivar", s.handleClienteArchivar)
|
||||
|
||||
// Cotizaciones
|
||||
r.Get("/cotizaciones", s.handleCotizacionesList)
|
||||
r.Post("/cotizaciones", s.handleCotizacionesCreate)
|
||||
r.Get("/cotizaciones/{id}", s.handleCotizacionesGet)
|
||||
r.Put("/cotizaciones/{id}", s.handleCotizacionesUpdate)
|
||||
r.Delete("/cotizaciones/{id}", s.handleCotizacionesDelete)
|
||||
r.Post("/cotizaciones/{id}/solicitar-aprobacion", s.handleCotizacionSolicitarAprobacion)
|
||||
r.Post("/cotizaciones/{id}/aprobar", s.handleCotizacionAprobar)
|
||||
r.Post("/cotizaciones/{id}/enviar", s.handleCotizacionEnviar)
|
||||
r.Patch("/cotizaciones/{id}/estado", s.handleCotizacionEstado)
|
||||
r.Patch("/cotizaciones/{id}/precio", s.handleCotizacionPrecio)
|
||||
|
||||
// Registro de horas
|
||||
r.Get("/cotizaciones/{id}/horas", s.handleHorasList)
|
||||
r.Post("/cotizaciones/{id}/horas", s.handleHorasCreate)
|
||||
r.Put("/cotizaciones/{id}/horas/{registroId}", s.handleHorasUpdate)
|
||||
r.Patch("/cotizaciones/{id}/horas/{registroId}", s.handleHorasEstadoPago)
|
||||
r.Delete("/cotizaciones/{id}/horas/{registroId}", s.handleHorasDelete)
|
||||
r.Post("/cotizaciones/{id}/nota-horas", s.handleNotaHorasPDF)
|
||||
|
||||
// Cobros recurrentes & comprobantes
|
||||
r.Get("/cobros/resumen", s.handleCobrosResumen)
|
||||
r.Get("/cobros/programas", s.handleProgramasList)
|
||||
r.Post("/cobros/programas", s.handleProgramasCreate)
|
||||
r.Patch("/cobros/programas/{id}", s.handleProgramasUpdate)
|
||||
r.Post("/cobros/generar", s.handleCobrosGenerar)
|
||||
r.Get("/cobros/pagos", s.handlePagosList)
|
||||
r.Post("/cobros/pagos/{id}/aprobar", s.handlePagoAprobar)
|
||||
r.Post("/cobros/pagos/{id}/rechazar", s.handlePagoRechazar)
|
||||
r.Post("/cobros/pagos/{id}/registrar", s.handlePagoRegistrar)
|
||||
r.Post("/cobros/pagos/{id}/anular", s.handlePagoAnular)
|
||||
r.Post("/cobros/pagos/{id}/reabrir", s.handlePagoReabrir)
|
||||
r.Post("/cobros/recordatorios", s.handleCobrosRecordatorios)
|
||||
r.Get("/comprobantes/{pagoId}", s.handleComprobanteGet)
|
||||
|
||||
// Panel de cliente
|
||||
r.Get("/cliente/resumen", s.handleClienteResumen)
|
||||
r.Get("/cliente/cotizaciones", s.handleClienteCotizacionesList)
|
||||
r.Get("/cliente/cotizaciones/{id}", s.handleClienteCotizacionGet)
|
||||
r.Get("/cliente/pagos", s.handleClientePagosList)
|
||||
r.Post("/cliente/pagos/{id}/comprobante", s.handleClienteComprobanteUpload)
|
||||
r.Get("/cliente/push/config", s.handleClientePushConfig)
|
||||
r.Post("/cliente/push/suscribir", s.handleClientePushSubscribe)
|
||||
r.Delete("/cliente/push/suscribir", s.handleClientePushUnsubscribe)
|
||||
|
||||
// Exports, Imports & Propuesta IA
|
||||
r.Get("/export/pdf/{id}", s.handleExportPDFByID)
|
||||
r.Post("/export/pdf", s.handleExportPDFDraft)
|
||||
r.Get("/export/excel/{id}", s.handleExportExcelByID)
|
||||
r.Post("/export/excel", s.handleExportExcelDraft)
|
||||
r.Get("/export/catalogo", s.handleExportCatalogoCSV)
|
||||
r.Get("/export/catalogo/plantilla", s.handleExportCatalogoPlantilla)
|
||||
r.Post("/import/catalogo", s.handleImportCatalogoCSV)
|
||||
|
||||
r.Get("/propuesta-ia/{id}", s.handlePropuestaIAGet)
|
||||
r.Post("/propuesta-ia/{id}", s.handlePropuestaIACreate)
|
||||
r.Patch("/propuesta-ia/{id}", s.handlePropuestaIAPatch)
|
||||
r.Get("/propuesta-ia/{id}/pdf", s.handlePropuestaIAPDF)
|
||||
|
||||
// Explicit JSON 404 for unknown /api/* routes
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"error": "Ruta API no encontrada"})
|
||||
})
|
||||
})
|
||||
|
||||
// Embedded Vite SPA for all non-API routes (including /sw.js, /favicon.ico, /login, /cliente/*, /aprobar/*)
|
||||
r.NotFound(spa.Handler().ServeHTTP)
|
||||
return r
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]any{"error": msg})
|
||||
}
|
||||
|
||||
type ValidationDetail struct {
|
||||
Campo string `json:"campo"`
|
||||
Mensaje string `json:"mensaje"`
|
||||
}
|
||||
|
||||
func writeValidationError(w http.ResponseWriter, detalles []ValidationDetail) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{
|
||||
"error": "Datos invalidos",
|
||||
"detalles": detalles,
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
|
||||
func parseIntQuery(r *http.Request, name string, def, minV, maxV int) int {
|
||||
raw := strings.TrimSpace(r.URL.Query().Get(name))
|
||||
if raw == "" {
|
||||
return def
|
||||
}
|
||||
v, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
if v < minV {
|
||||
return minV
|
||||
}
|
||||
if maxV > 0 && v > maxV {
|
||||
return maxV
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
type BrandingConfig struct {
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
func (s *Server) getAllConfigMap(ctx context.Context) map[string]string {
|
||||
m := map[string]string{}
|
||||
rows, err := s.Pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`)
|
||||
if err != nil {
|
||||
return m
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if rows.Scan(&k, &v) == nil {
|
||||
m[k] = v
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) getConfigBranding(ctx context.Context) BrandingConfig {
|
||||
m := s.getAllConfigMap(ctx)
|
||||
b := BrandingConfig{
|
||||
ColorPrimario: firstNonEmptyStr(m["color_primario"], "#0400C4"),
|
||||
ColorSecundario: firstNonEmptyStr(m["color_secundario"], "#0F172A"),
|
||||
}
|
||||
if rawLogo := strings.TrimSpace(m["logo_base64"]); rawLogo != "" {
|
||||
if strings.HasPrefix(rawLogo, "data:") {
|
||||
// data:image/png;base64,XXXX
|
||||
if idx := strings.Index(rawLogo, ","); idx > 0 {
|
||||
meta := rawLogo[5:idx]
|
||||
b.LogoMime = strings.Split(meta, ";")[0]
|
||||
b.LogoBase64 = rawLogo[idx+1:]
|
||||
}
|
||||
} else if idx := strings.Index(rawLogo, ":"); idx > 0 && strings.Contains(rawLogo[:idx], "/") {
|
||||
// mime:base64
|
||||
b.LogoMime = rawLogo[:idx]
|
||||
b.LogoBase64 = rawLogo[idx+1:]
|
||||
} else {
|
||||
b.LogoMime = "image/png"
|
||||
b.LogoBase64 = rawLogo
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (s *Server) getConfigBancaria(ctx context.Context) map[string]string {
|
||||
m := s.getAllConfigMap(ctx)
|
||||
keys := []string{
|
||||
"razon_social", "rfc", "domicilio_fiscal",
|
||||
"banco_nacional", "cuenta_nacional", "clabe_interbancaria", "clabe_nacional",
|
||||
"banco_internacional", "cuenta_internacional", "cuenta_internacional_swift", "swift", "routing_number",
|
||||
"email_facturacion", "telefono_contacto",
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var seqDigitsRe = regexp.MustCompile(`(\d{3})$`)
|
||||
|
||||
func (s *Server) nextCotizacionSeq(ctx context.Context) int {
|
||||
var latest string
|
||||
err := s.Pool.QueryRow(ctx, `SELECT "numero" FROM "Cotizacion" ORDER BY "createdAt" DESC LIMIT 1`).Scan(&latest)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
if m := seqDigitsRe.FindStringSubmatch(latest); len(m) == 2 {
|
||||
if n, err := strconv.Atoi(m[1]); err == nil && n > 0 {
|
||||
return n + 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func asesorInitials(name string) string {
|
||||
parts := strings.Fields(strings.TrimSpace(name))
|
||||
if len(parts) == 0 {
|
||||
return "UJ"
|
||||
}
|
||||
if len(parts) == 1 {
|
||||
runes := []rune(strings.ToUpper(parts[0]))
|
||||
if len(runes) >= 2 {
|
||||
return string(runes[:2])
|
||||
}
|
||||
return string(runes) + "X"
|
||||
}
|
||||
r1 := []rune(strings.ToUpper(parts[0]))[0]
|
||||
r2 := []rune(strings.ToUpper(parts[1]))[0]
|
||||
return string([]rune{r1, r2})
|
||||
}
|
||||
|
||||
func (s *Server) siguienteNumeroCotizacion(ctx context.Context, asesorName string) string {
|
||||
ini := asesorInitials(asesorName)
|
||||
seq := s.nextCotizacionSeq(ctx)
|
||||
now := time.Now()
|
||||
for tries := 0; tries < 50; tries++ {
|
||||
candidate := domain.GenerarNumeroCotizacion(ini, seq+tries, now)
|
||||
var exists bool
|
||||
_ = s.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "Cotizacion" WHERE "numero" = $1)`, candidate).Scan(&exists)
|
||||
if !exists {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("UJ%02d%02d%s%03d", now.Year()%100, int(now.Month()), ini, seq+50)
|
||||
}
|
||||
|
||||
func firstNonEmptyStr(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package idempotency
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const TTL = 24 * time.Hour
|
||||
|
||||
type HandlerFunc func(rawBody []byte) (statusCode int, responseBody any)
|
||||
|
||||
// Execute wraps a mutating endpoint with Idempotency-Key support (24h TTL, SHA-256 body hash).
|
||||
func Execute(ctx context.Context, pool *pgxpool.Pool, w http.ResponseWriter, r *http.Request, actor *auth.Actor, fn HandlerFunc) {
|
||||
rawBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "No se pudo leer el cuerpo de la solicitud"})
|
||||
return
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||
|
||||
idemHeader := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
|
||||
if idemHeader == "" {
|
||||
status, body := fn(rawBody)
|
||||
writeJSON(w, status, body)
|
||||
return
|
||||
}
|
||||
|
||||
actorKey := "user:" + actor.UserID
|
||||
if actor.IsAgent() {
|
||||
actorKey = "agent:" + actor.KeyID
|
||||
}
|
||||
composedKey := fmt.Sprintf("%s:%s:%s:%s", actorKey, r.Method, r.URL.Path, idemHeader)
|
||||
sum := sha256.Sum256(rawBody)
|
||||
reqHash := hex.EncodeToString(sum[:])
|
||||
|
||||
var existingHash string
|
||||
var existingStatus int
|
||||
var existingBody json.RawMessage
|
||||
var expiraAt time.Time
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT "requestHash", "statusCode", "responseBody", "expiraAt"
|
||||
FROM "IdempotencyKey"
|
||||
WHERE "key" = $1
|
||||
`, composedKey).Scan(&existingHash, &existingStatus, &existingBody, &expiraAt)
|
||||
|
||||
if err == nil {
|
||||
if time.Now().After(expiraAt) {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM "IdempotencyKey" WHERE "key" = $1`, composedKey)
|
||||
} else {
|
||||
if existingHash != reqHash {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{
|
||||
"error": "Idempotency-Key ya fue usada con un cuerpo de solicitud distinto",
|
||||
})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Idempotency-Replayed", "true")
|
||||
w.WriteHeader(existingStatus)
|
||||
_, _ = w.Write(existingBody)
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
// Fall through gracefully on lookup error
|
||||
}
|
||||
|
||||
status, body := fn(rawBody)
|
||||
bodyBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
bodyBytes = []byte(`{}`)
|
||||
}
|
||||
|
||||
if status < 500 {
|
||||
_, _ = pool.Exec(ctx, `
|
||||
INSERT INTO "IdempotencyKey" ("id", "key", "method", "path", "requestHash", "statusCode", "responseBody", "expiraAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT ("key") DO UPDATE SET
|
||||
"requestHash" = EXCLUDED."requestHash",
|
||||
"statusCode" = EXCLUDED."statusCode",
|
||||
"responseBody" = EXCLUDED."responseBody",
|
||||
"expiraAt" = EXCLUDED."expiraAt"
|
||||
`, db.NewID(), composedKey, r.Method, r.URL.Path, reqHash, status, bodyBytes, time.Now().Add(TTL))
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(bodyBytes)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"log"
|
||||
"mime/quotedprintable"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/webhooks"
|
||||
|
||||
webpush "github.com/SherClockHolmes/webpush-go"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
Filename string
|
||||
ContentType string
|
||||
Content []byte
|
||||
}
|
||||
|
||||
type MailMessage struct {
|
||||
To string
|
||||
Subject string
|
||||
Text string
|
||||
HTML string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
cfg *config.Config
|
||||
pool *pgxpool.Pool
|
||||
webhooks *webhooks.Dispatcher
|
||||
}
|
||||
|
||||
func NewService(cfg *config.Config, pool *pgxpool.Pool, wh *webhooks.Dispatcher) *Service {
|
||||
return &Service{cfg: cfg, pool: pool, webhooks: wh}
|
||||
}
|
||||
|
||||
func (s *Service) SMTPConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.SMTPHost != "" && s.cfg.SMTPFrom != ""
|
||||
}
|
||||
|
||||
func (s *Service) VAPIDConfigured() bool {
|
||||
return s != nil && s.cfg != nil && s.cfg.VAPIDPublicKey != "" && s.cfg.VAPIDPrivateKey != ""
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCorreo(msg MailMessage) bool {
|
||||
if !s.SMTPConfigured() {
|
||||
log.Printf("[email] SMTP no configurado; omitiendo correo a %s (%s)", msg.To, msg.Subject)
|
||||
return false
|
||||
}
|
||||
to := strings.TrimSpace(msg.To)
|
||||
if to == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
raw := buildMIMEMessage(s.cfg.SMTPFromName, s.cfg.SMTPFrom, to, msg)
|
||||
addr := fmt.Sprintf("%s:%d", s.cfg.SMTPHost, s.cfg.SMTPPort)
|
||||
|
||||
var err error
|
||||
if s.cfg.SMTPPort == 465 {
|
||||
err = sendSMTPImplicitTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
} else {
|
||||
err = sendSMTPStartTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[email] error enviando correo a %s: %v", to, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sendSMTPImplicitTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
||||
conn, err := tls.DialWithDialer(dialer, "tcp", addr, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func sendSMTPStartTLS(addr, host, user, pass, from, to string, raw []byte) error {
|
||||
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if ok, _ := client.Extension("STARTTLS"); ok {
|
||||
if err := client.StartTLS(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if user != "" {
|
||||
if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
func buildMIMEMessage(fromName, fromAddr, to string, msg MailMessage) []byte {
|
||||
var buf bytes.Buffer
|
||||
fromHeader := fromAddr
|
||||
if fromName != "" {
|
||||
fromHeader = fmt.Sprintf("=?UTF-8?B?%s?= <%s>", base64.StdEncoding.EncodeToString([]byte(fromName)), fromAddr)
|
||||
}
|
||||
subjHeader := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(msg.Subject)))
|
||||
|
||||
fmt.Fprintf(&buf, "From: %s\r\n", fromHeader)
|
||||
fmt.Fprintf(&buf, "To: %s\r\n", to)
|
||||
fmt.Fprintf(&buf, "Subject: %s\r\n", subjHeader)
|
||||
fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&buf, "MIME-Version: 1.0\r\n")
|
||||
|
||||
mixedBoundary := fmt.Sprintf("ujc-mixed-%d", time.Now().UnixNano())
|
||||
altBoundary := fmt.Sprintf("ujc-alt-%d", time.Now().UnixNano())
|
||||
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/mixed; boundary=%q\r\n\r\n", mixedBoundary)
|
||||
fmt.Fprintf(&buf, "--%s\r\n", mixedBoundary)
|
||||
}
|
||||
|
||||
fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=%q\r\n\r\n", altBoundary)
|
||||
|
||||
textBody := msg.Text
|
||||
if textBody == "" {
|
||||
textBody = "Consulta este mensaje en un cliente de correo compatible con HTML."
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, textBody)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
|
||||
if msg.HTML != "" {
|
||||
fmt.Fprintf(&buf, "--%s\r\n", altBoundary)
|
||||
fmt.Fprintf(&buf, "Content-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
writeQP(&buf, msg.HTML)
|
||||
fmt.Fprintf(&buf, "\r\n")
|
||||
}
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", altBoundary)
|
||||
|
||||
for _, att := range msg.Attachments {
|
||||
fmt.Fprintf(&buf, "\r\n--%s\r\n", mixedBoundary)
|
||||
ct := att.ContentType
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&buf, "Content-Type: %s; name=%q\r\n", ct, att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Disposition: attachment; filename=%q\r\n", att.Filename)
|
||||
fmt.Fprintf(&buf, "Content-Transfer-Encoding: base64\r\n\r\n")
|
||||
enc := base64.StdEncoding.EncodeToString(att.Content)
|
||||
for i := 0; i < len(enc); i += 76 {
|
||||
end := i + 76
|
||||
if end > len(enc) {
|
||||
end = len(enc)
|
||||
}
|
||||
buf.WriteString(enc[i:end])
|
||||
buf.WriteString("\r\n")
|
||||
}
|
||||
}
|
||||
if len(msg.Attachments) > 0 {
|
||||
fmt.Fprintf(&buf, "--%s--\r\n", mixedBoundary)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func writeQP(buf *bytes.Buffer, s string) {
|
||||
qw := quotedprintable.NewWriter(buf)
|
||||
_, _ = qw.Write([]byte(s))
|
||||
_ = qw.Close()
|
||||
}
|
||||
|
||||
// EnviarPush sends a Web Push notification to all subscriptions of userID. Returns number delivered.
|
||||
func (s *Service) EnviarPush(ctx context.Context, userID, titulo, cuerpo, urlPath string) int {
|
||||
if !s.VAPIDConfigured() || s.pool == nil || userID == "" {
|
||||
return 0
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT "id", "endpoint", "p256dh", "auth"
|
||||
FROM "SuscripcionPush"
|
||||
WHERE "userId" = $1
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"titulo": titulo,
|
||||
"cuerpo": cuerpo,
|
||||
"url": urlPath,
|
||||
})
|
||||
|
||||
sent := 0
|
||||
var expiredIDs []string
|
||||
for rows.Next() {
|
||||
var id, endpoint, p256dh, authKey string
|
||||
if err := rows.Scan(&id, &endpoint, &p256dh, &authKey); err != nil {
|
||||
continue
|
||||
}
|
||||
sub := &webpush.Subscription{
|
||||
Endpoint: endpoint,
|
||||
Keys: webpush.Keys{
|
||||
P256dh: p256dh,
|
||||
Auth: authKey,
|
||||
},
|
||||
}
|
||||
resp, err := webpush.SendNotification(payload, sub, &webpush.Options{
|
||||
Subscriber: strings.TrimPrefix(s.cfg.VAPIDSubject, "mailto:"),
|
||||
VAPIDPublicKey: s.cfg.VAPIDPublicKey,
|
||||
VAPIDPrivateKey: s.cfg.VAPIDPrivateKey,
|
||||
TTL: 86400,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[push] error enviando a %s: %v", id, err)
|
||||
continue
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode == 404 || resp.StatusCode == 410 {
|
||||
expiredIDs = append(expiredIDs, id)
|
||||
} else if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
sent++
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range expiredIDs {
|
||||
_, _ = s.pool.Exec(ctx, `DELETE FROM "SuscripcionPush" WHERE "id" = $1`, id)
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
func (s *Service) GetAdminEmail(ctx context.Context) string {
|
||||
if s.cfg != nil && s.cfg.AdminNotifyEmail != "" {
|
||||
return s.cfg.AdminNotifyEmail
|
||||
}
|
||||
if s.pool == nil {
|
||||
return ""
|
||||
}
|
||||
var email string
|
||||
_ = s.pool.QueryRow(ctx, `SELECT "email" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&email)
|
||||
return email
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethBorrador(ctx context.Context, cotID, numero, clienteNombre, clienteEmpresa, proyecto, agenteNombre, approvalURL string, totalUnico, totalMensual float64) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
log.Printf("[notify] sin correo de administrador para notificar borrador %s", numero)
|
||||
return
|
||||
}
|
||||
portalURL := fmt.Sprintf("%s/cotizaciones/%s", s.cfg.AppURL, cotID)
|
||||
empresaTxt := ""
|
||||
if clienteEmpresa != "" {
|
||||
empresaTxt = fmt.Sprintf(" (%s)", clienteEmpresa)
|
||||
}
|
||||
subj := fmt.Sprintf("Aprobacion requerida: Cotizacion %s — %s", numero, clienteNombre)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nueva cotizacion pendiente de aprobacion</h2>
|
||||
<p>El agente <strong>%s</strong> preparo el borrador <strong>%s</strong>.</p>
|
||||
<ul>
|
||||
<li><strong>Cliente:</strong> %s%s</li>
|
||||
<li><strong>Proyecto:</strong> %s</li>
|
||||
<li><strong>Pago unico:</strong> %s</li>
|
||||
<li><strong>Pago mensual:</strong> %s</li>
|
||||
</ul>
|
||||
<p style="margin:24px 0">
|
||||
<a href="%s" style="background:#0400C4;color:#ffffff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:bold">Revisar y aprobar cotizacion</a>
|
||||
</p>
|
||||
<p style="font-size:12px;color:#64748b">Tambien puedes revisarla en el panel: <a href="%s">%s</a></p>
|
||||
</div>
|
||||
`, html.EscapeString(agenteNombre), html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(empresaTxt), html.EscapeString(proyecto), domain.FormatCurrency(totalUnico), domain.FormatCurrency(totalMensual), approvalURL, portalURL, portalURL)
|
||||
|
||||
textBody := fmt.Sprintf("Nueva cotizacion %s creada por %s para %s%s.\nAprobar: %s\nPanel: %s", numero, agenteNombre, clienteNombre, empresaTxt, approvalURL, portalURL)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, HTML: htmlBody, Text: textBody})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarJarethWhatsAppFueraVentana(ctx context.Context, numero, clienteNombre, telefono string) {
|
||||
adminEmail := s.GetAdminEmail(ctx)
|
||||
if adminEmail == "" {
|
||||
return
|
||||
}
|
||||
subj := fmt.Sprintf("WhatsApp fuera de ventana 24h — Cotizacion %s", numero)
|
||||
body := fmt.Sprintf("No se pudo enviar la cotizacion %s a %s (%s) por WhatsApp porque excedio la ventana de 24 horas y no hubo fallback de correo.", numero, clienteNombre, telefono)
|
||||
s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, Text: body, HTML: "<p>" + html.EscapeString(body) + "</p>"})
|
||||
}
|
||||
|
||||
func (s *Service) EnviarCotizacionPorCorreo(to, clienteNombre, numero, proyecto string, pdfBytes []byte) bool {
|
||||
subj := fmt.Sprintf("Cotizacion %s — Uriel Jareth Consulting", numero)
|
||||
htmlBody := fmt.Sprintf(`
|
||||
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Cotizacion %s</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Adjuntamos la propuesta economica correspondiente al proyecto <strong>%s</strong>.</p>
|
||||
<p>Quedamos atentos a cualquier duda o comentario.</p>
|
||||
<p style="margin-top:24px;color:#64748b;font-size:13px">Uriel Jareth Consulting</p>
|
||||
</div>
|
||||
`, html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(proyecto))
|
||||
textBody := fmt.Sprintf("Hola %s,\n\nAdjuntamos la cotizacion %s para el proyecto %s.\n\nSaludos,\nUriel Jareth Consulting", clienteNombre, numero, proyecto)
|
||||
return s.EnviarCorreo(MailMessage{
|
||||
To: to,
|
||||
Subject: subj,
|
||||
HTML: htmlBody,
|
||||
Text: textBody,
|
||||
Attachments: []Attachment{
|
||||
{
|
||||
Filename: fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(numero)),
|
||||
ContentType: "application/pdf",
|
||||
Content: pdfBytes,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) NotificarCobrosNuevos(ctx context.Context, pagoIDs []string) {
|
||||
if s.pool == nil || len(pagoIDs) == 0 {
|
||||
return
|
||||
}
|
||||
for _, pid := range pagoIDs {
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pid).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Nuevo cobro programado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tienes un cobro programado por %s (%s) con fecha %s. Sube tu comprobante en %s", clienteNombre, montoStr, concepto, fechaStr, urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Nuevo cobro programado</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Se genero el cobro de <strong>%s</strong> por <strong>%s</strong> correspondiente al <strong>%s</strong>.</p>
|
||||
<p><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Ver y subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, fechaStr, urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Nuevo cobro programado", fmt.Sprintf("%s — %s (%s)", concepto, montoStr, domain.FormatFechaCorta(fecha)), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarVerificacion(ctx context.Context, pagoID string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
fechaStr := domain.FormatFechaCobro(fecha)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Pago verificado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, confirmamos tu pago de %s por %s (%s). Gracias.", clienteNombre, montoStr, concepto, fechaStr),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Confirmamos que tu pago de <strong>%s</strong> por <strong>%s</strong> (%s) ha sido verificado. Gracias.</p>`, html.EscapeString(clienteNombre), montoStr, html.EscapeString(concepto), fechaStr),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Pago verificado", fmt.Sprintf("%s — %s confirmado", concepto, montoStr), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) NotificarRechazo(ctx context.Context, pagoID, motivo string) {
|
||||
if s.pool == nil {
|
||||
return
|
||||
}
|
||||
var concepto, moneda, clienteNombre string
|
||||
var email, userID *string
|
||||
var monto float64
|
||||
var fecha time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT pr."concepto", pr."moneda", p."monto", p."fecha",
|
||||
c."nombre", c."email", u."id"
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."id" = $1
|
||||
`, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
montoStr := domain.FormatMonto(monto, moneda)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
if email != nil && strings.TrimSpace(*email) != "" {
|
||||
s.EnviarCorreo(MailMessage{
|
||||
To: *email,
|
||||
Subject: fmt.Sprintf("Comprobante rechazado: %s (%s)", concepto, montoStr),
|
||||
Text: fmt.Sprintf("Hola %s, tu comprobante para %s (%s) fue rechazado. Motivo: %s. Puedes subir uno nuevo en %s", clienteNombre, concepto, montoStr, motivo, urlPagos),
|
||||
HTML: fmt.Sprintf(`<p>Hola %s,</p><p>Tu comprobante para <strong>%s</strong> (%s) fue rechazado.</p><p><strong>Motivo:</strong> %s</p><p><a href="%s">Subir nuevo comprobante</a></p>`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, html.EscapeString(motivo), urlPagos),
|
||||
})
|
||||
}
|
||||
if userID != nil && *userID != "" {
|
||||
s.EnviarPush(ctx, *userID, "Comprobante rechazado", fmt.Sprintf("%s: %s", concepto, motivo), "/cliente/pagos")
|
||||
}
|
||||
}
|
||||
|
||||
type RecordatoriosResult struct {
|
||||
ClientesNotificados int `json:"clientesNotificados"`
|
||||
PagosRecordados int `json:"pagosRecordados"`
|
||||
PagosVencidosEmit int `json:"pagosVencidosEmitidos"`
|
||||
PagoIDsCubiertos []string `json:"-"`
|
||||
}
|
||||
|
||||
// EnviarRecordatoriosPendientes sends one account-statement reminder per client for overdue/due charges
|
||||
// (estado in pendiente|rechazado, fecha <= hoy) and emits pago.vencido idempotently.
|
||||
func (s *Service) EnviarRecordatoriosPendientes(ctx context.Context, clienteIDFilter string, forzar bool) (*RecordatoriosResult, error) {
|
||||
if s.pool == nil {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
hoy := domain.HoyCalendario()
|
||||
diasEspera := s.cfg.CobrosRecordatorioDias
|
||||
if !forzar && diasEspera <= 0 {
|
||||
return &RecordatoriosResult{}, nil
|
||||
}
|
||||
|
||||
args := []any{hoy}
|
||||
whereCliente := ""
|
||||
if clienteIDFilter != "" {
|
||||
whereCliente = ` AND c."id" = $2`
|
||||
args = append(args, clienteIDFilter)
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt",
|
||||
pr."concepto", pr."moneda",
|
||||
c."id", c."nombre", COALESCE(c."empresa", ''), COALESCE(c."email", ''), COALESCE(c."telefono", ''),
|
||||
COALESCE(u."id", '')
|
||||
FROM "PagoRecurrente" p
|
||||
JOIN "ProgramaPago" pr ON pr."id" = p."programaId"
|
||||
JOIN "Cliente" c ON c."id" = pr."clienteId"
|
||||
LEFT JOIN "User" u ON u."clienteId" = c."id"
|
||||
WHERE p."estado" IN ('pendiente', 'rechazado')
|
||||
AND p."fecha" <= $1`+whereCliente+`
|
||||
ORDER BY c."nombre" ASC, p."fecha" ASC
|
||||
`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type pagoRow struct {
|
||||
ID string
|
||||
ProgramaID string
|
||||
Fecha time.Time
|
||||
Monto float64
|
||||
Estado string
|
||||
UltimoRecordatorioAt *time.Time
|
||||
Concepto string
|
||||
Moneda string
|
||||
ClienteID string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
ClienteEmail string
|
||||
ClienteTelefono string
|
||||
UserID string
|
||||
}
|
||||
|
||||
byClient := map[string][]pagoRow{}
|
||||
var clientOrder []string
|
||||
var vencidosItems []webhooks.PagoVencidoItem
|
||||
|
||||
for rows.Next() {
|
||||
var r pagoRow
|
||||
if err := rows.Scan(
|
||||
&r.ID, &r.ProgramaID, &r.Fecha, &r.Monto, &r.Estado, &r.UltimoRecordatorioAt,
|
||||
&r.Concepto, &r.Moneda,
|
||||
&r.ClienteID, &r.ClienteNombre, &r.ClienteEmpresa, &r.ClienteEmail, &r.ClienteTelefono,
|
||||
&r.UserID,
|
||||
); err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := byClient[r.ClienteID]; !ok {
|
||||
clientOrder = append(clientOrder, r.ClienteID)
|
||||
}
|
||||
byClient[r.ClienteID] = append(byClient[r.ClienteID], r)
|
||||
|
||||
atraso := domain.DiasDeAtraso(r.Fecha, hoy)
|
||||
if atraso > 0 {
|
||||
vencidosItems = append(vencidosItems, webhooks.PagoVencidoItem{
|
||||
PagoID: r.ID,
|
||||
ProgramaID: r.ProgramaID,
|
||||
ClienteID: r.ClienteID,
|
||||
ClienteNombre: r.ClienteNombre,
|
||||
ClienteEmpresa: r.ClienteEmpresa,
|
||||
ClienteEmail: r.ClienteEmail,
|
||||
ClienteTelefono: r.ClienteTelefono,
|
||||
Concepto: r.Concepto,
|
||||
Monto: r.Monto,
|
||||
Moneda: r.Moneda,
|
||||
Fecha: r.Fecha.UTC().Format("2006-01-02"),
|
||||
DiasAtraso: atraso,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort idempotent webhook emission for overdue payments
|
||||
res := &RecordatoriosResult{}
|
||||
if s.webhooks != nil && len(vencidosItems) > 0 {
|
||||
res.PagosVencidosEmit = s.webhooks.EmitirPagosVencidos(ctx, vencidosItems)
|
||||
}
|
||||
|
||||
// Load bank config for statement email
|
||||
bancaria := map[string]string{}
|
||||
cfgRows, err := s.pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`)
|
||||
if err == nil {
|
||||
defer cfgRows.Close()
|
||||
for cfgRows.Next() {
|
||||
var k, v string
|
||||
if cfgRows.Scan(&k, &v) == nil {
|
||||
bancaria[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cutoff := time.Now().Add(-time.Duration(diasEspera) * 24 * time.Hour)
|
||||
for _, cid := range clientOrder {
|
||||
pagos := byClient[cid]
|
||||
if len(pagos) == 0 {
|
||||
continue
|
||||
}
|
||||
if !forzar {
|
||||
needsSend := false
|
||||
for _, p := range pagos {
|
||||
if p.UltimoRecordatorioAt == nil || p.UltimoRecordatorioAt.Before(cutoff) {
|
||||
needsSend = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !needsSend {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
first := pagos[0]
|
||||
totales := map[string]float64{}
|
||||
var rowsHTML strings.Builder
|
||||
var rowsText strings.Builder
|
||||
for _, p := range pagos {
|
||||
totales[p.Moneda] = domain.Round2(totales[p.Moneda] + p.Monto)
|
||||
fStr := domain.FormatFechaCorta(p.Fecha)
|
||||
mStr := domain.FormatMonto(p.Monto, p.Moneda)
|
||||
fmt.Fprintf(&rowsHTML, `<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0">%s</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;text-align:right">%s</td></tr>`,
|
||||
html.EscapeString(fStr), html.EscapeString(p.Concepto), mStr)
|
||||
fmt.Fprintf(&rowsText, "- %s | %s | %s\n", fStr, p.Concepto, mStr)
|
||||
}
|
||||
|
||||
totalStr := domain.FormatTotales(totales)
|
||||
urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL)
|
||||
|
||||
bancoHTML := ""
|
||||
if bancaria["banco_nacional"] != "" || bancaria["clabe_nacional"] != "" {
|
||||
bancoHTML = fmt.Sprintf(`<div style="margin-top:16px;padding:12px;background:#f8fafc;border-radius:8px;font-size:13px">
|
||||
<strong>Datos bancarios</strong><br/>
|
||||
Banco: %s<br/>CLABE: %s<br/>Cuenta: %s<br/>Beneficiario: %s
|
||||
</div>`, html.EscapeString(bancaria["banco_nacional"]), html.EscapeString(bancaria["clabe_nacional"]), html.EscapeString(bancaria["cuenta_nacional"]), html.EscapeString(bancaria["razon_social"]))
|
||||
}
|
||||
|
||||
delivered := false
|
||||
if first.ClienteEmail != "" {
|
||||
ok := s.EnviarCorreo(MailMessage{
|
||||
To: first.ClienteEmail,
|
||||
Subject: fmt.Sprintf("Recordatorio de pagos pendientes (%s) — Uriel Jareth Consulting", totalStr),
|
||||
Text: fmt.Sprintf("Hola %s,\n\nTienes pagos pendientes por %s:\n%s\nPuedes subir tus comprobantes en: %s", first.ClienteNombre, totalStr, rowsText.String(), urlPagos),
|
||||
HTML: fmt.Sprintf(`<div style="font-family:Arial,sans-serif;max-width:600px;color:#0f172a">
|
||||
<h2 style="color:#0400C4">Estado de pagos pendientes</h2>
|
||||
<p>Hola %s,</p>
|
||||
<p>Tienes los siguientes pagos pendientes por un total de <strong>%s</strong>:</p>
|
||||
<table style="width:100%%;border-collapse:collapse;font-size:14px">
|
||||
<thead><tr style="background:#f1f5f9"><th style="padding:6px 8px;text-align:left">Fecha</th><th style="padding:6px 8px;text-align:left">Concepto</th><th style="padding:6px 8px;text-align:right">Monto</th></tr></thead>
|
||||
<tbody>%s</tbody>
|
||||
</table>
|
||||
%s
|
||||
<p style="margin-top:20px"><a href="%s" style="background:#0400C4;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Subir comprobante</a></p>
|
||||
</div>`, html.EscapeString(first.ClienteNombre), totalStr, rowsHTML.String(), bancoHTML, urlPagos),
|
||||
})
|
||||
if ok {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if first.UserID != "" {
|
||||
if n := s.EnviarPush(ctx, first.UserID, "Pagos pendientes", fmt.Sprintf("Saldo pendiente: %s (%d cobro(s))", totalStr, len(pagos)), "/cliente/pagos"); n > 0 {
|
||||
delivered = true
|
||||
}
|
||||
}
|
||||
|
||||
if delivered {
|
||||
res.ClientesNotificados++
|
||||
for _, p := range pagos {
|
||||
_, _ = s.pool.Exec(ctx, `
|
||||
UPDATE "PagoRecurrente"
|
||||
SET "ultimoRecordatorioAt" = NOW(),
|
||||
"recordatoriosEnviados" = "recordatoriosEnviados" + 1,
|
||||
"updatedAt" = NOW()
|
||||
WHERE "id" = $1
|
||||
`, p.ID)
|
||||
res.PagosRecordados++
|
||||
res.PagoIDsCubiertos = append(res.PagoIDsCubiertos, p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type ServicioPDF struct {
|
||||
Nombre string
|
||||
Fase int
|
||||
TipoPago string
|
||||
Precio float64
|
||||
TiempoEntrega string
|
||||
Entregables []string
|
||||
EsPersonalizado bool
|
||||
Horas *float64
|
||||
TarifaHora *float64
|
||||
ModeloCobro string
|
||||
MontoMinimo *float64
|
||||
HorasIncluidas *float64
|
||||
Opcion *string
|
||||
}
|
||||
|
||||
type BonoPDF struct {
|
||||
Numero int
|
||||
Descripcion string
|
||||
}
|
||||
|
||||
// CotizacionPDFData holds client-facing quotation data for PDF generation.
|
||||
// ObservacionesInternas is intentionally NOT declared here so internal notes
|
||||
// can never leak into a client document.
|
||||
type CotizacionPDFData struct {
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
AsesorNombre string
|
||||
Fecha time.Time
|
||||
Vigencia time.Time
|
||||
Moneda string
|
||||
TipoCambio string
|
||||
Proyecto string
|
||||
EsquemaPago string
|
||||
Servicios []ServicioPDF
|
||||
EsDoble bool
|
||||
OpcionesMetadata map[string]domain.MetaOpcion
|
||||
PlanBucefaloNivel *string
|
||||
PlanBucefaloPrecio float64
|
||||
IncluirBonos bool
|
||||
Bonos []BonoPDF
|
||||
IncluirIVA bool
|
||||
Observaciones *string
|
||||
ConfigBancaria map[string]string
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
func servicioPDFToCalc(s ServicioPDF) domain.ServicioCalc {
|
||||
return domain.ServicioCalc{
|
||||
Nombre: s.Nombre,
|
||||
ModeloCobro: s.ModeloCobro,
|
||||
EsPersonalizado: s.EsPersonalizado,
|
||||
Horas: s.Horas,
|
||||
TarifaHora: s.TarifaHora,
|
||||
MontoMinimo: s.MontoMinimo,
|
||||
HorasIncluidas: s.HorasIncluidas,
|
||||
Opcion: s.Opcion,
|
||||
TipoPago: s.TipoPago,
|
||||
Precio: s.Precio,
|
||||
Seleccionado: true,
|
||||
}
|
||||
}
|
||||
|
||||
func serviciosPDFToCalc(list []ServicioPDF) []domain.ServicioCalc {
|
||||
out := make([]domain.ServicioCalc, len(list))
|
||||
for i, s := range list {
|
||||
out[i] = servicioPDFToCalc(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func GenerateCotizacionPDF(data CotizacionPDFData) ([]byte, error) {
|
||||
primary := safeHex(data.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(data.ColorSecundario, defaultDark)
|
||||
|
||||
c := newCanvas(45, 55, 50, 50)
|
||||
logo := registerLogo(c.doc, "cot_logo", data.LogoBase64, data.LogoMime)
|
||||
|
||||
// Footer on every page.
|
||||
c.doc.SetFooterFunc(func() {
|
||||
c.hLine(c.L, c.L+c.W, c.ph-42, colorBorder, 0.5)
|
||||
c.drawSingleLine("Uriel Jareth Consulting", c.L, c.ph-35, c.W, "", 6.5, colorMuted, "C")
|
||||
c.drawSingleLine("urieljareth.com | [email protected] | (445) 182 9943", c.L, c.ph-26, c.W, "", 6.5, colorMuted, "C")
|
||||
})
|
||||
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, data.Moneda)
|
||||
}
|
||||
|
||||
sectionTitle := func(title string, y float64) float64 {
|
||||
y = c.need(20, y)
|
||||
c.rectFill(c.L, y+1, 3, 9, primary)
|
||||
c.drawSingleLine(title, c.L+10, y, c.W-10, "B", 9, dark, "L")
|
||||
return y + 15
|
||||
}
|
||||
|
||||
// ── PAGE 1: COVER ──────────────────────────────
|
||||
c.doc.AddPage()
|
||||
c.rectFill(0, 0, c.pw, c.ph, colorWhite)
|
||||
|
||||
if logo.ok {
|
||||
logo.drawByHeight(c.doc, c.L, 55, 65)
|
||||
} else {
|
||||
c.drawSingleLine("UJ", c.L, 55, 48, "B", 28, primary, "L")
|
||||
c.drawSingleLine("Uriel Jareth Consulting", c.L+48, 70, c.W-48, "", 9, colorMuted, "L")
|
||||
}
|
||||
|
||||
barY := 130.0
|
||||
if logo.ok {
|
||||
barY = 145.0
|
||||
}
|
||||
c.rectFill(c.L, barY, c.W, 4, primary)
|
||||
|
||||
c.drawSingleLine("Cotización", c.L, barY+24, c.W, "B", 36, dark, "L")
|
||||
c.drawSingleLine(data.Numero, c.L, barY+68, c.W, "", 18, primary, "L")
|
||||
|
||||
iy := barY + 110
|
||||
cL := c.L
|
||||
cR := c.L + c.W*0.52
|
||||
colW := c.W * 0.46
|
||||
|
||||
type kv struct{ k, v string }
|
||||
infoL := []kv{{"Cliente", data.ClienteNombre}}
|
||||
if strings.TrimSpace(data.ClienteEmpresa) != "" {
|
||||
infoL = append(infoL, kv{"Empresa", data.ClienteEmpresa})
|
||||
}
|
||||
infoL = append(infoL,
|
||||
kv{"Proyecto", data.Proyecto},
|
||||
kv{"Asesor", data.AsesorNombre},
|
||||
)
|
||||
infoR := []kv{
|
||||
{"Fecha", domain.FormatDateLongMX(data.Fecha)},
|
||||
{"Vigencia", domain.FormatDateLongMX(data.Vigencia)},
|
||||
{"Moneda", data.Moneda},
|
||||
{"Esquema", data.EsquemaPago},
|
||||
}
|
||||
|
||||
maxRows := len(infoL)
|
||||
if len(infoR) > maxRows {
|
||||
maxRows = len(infoR)
|
||||
}
|
||||
for i := 0; i < maxRows; i++ {
|
||||
hL, hR := 0.0, 0.0
|
||||
if i < len(infoL) {
|
||||
c.drawSingleLine(infoL[i].k, cL, iy, colW, "", 9, colorMuted, "L")
|
||||
hL = c.drawText(infoL[i].v, cL, iy+12, colW, "", 11, dark, "L")
|
||||
}
|
||||
if i < len(infoR) {
|
||||
c.drawSingleLine(infoR[i].k, cR, iy, colW, "", 9, colorMuted, "L")
|
||||
hR = c.drawText(infoR[i].v, cR, iy+12, colW, "", 11, dark, "L")
|
||||
}
|
||||
step := hL
|
||||
if hR > step {
|
||||
step = hR
|
||||
}
|
||||
if step < 18 {
|
||||
step = 18
|
||||
}
|
||||
iy += 14 + step
|
||||
}
|
||||
|
||||
// ── PAGE 2+: HOJA RESUMEN ──────────────────────
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
if logo.ok {
|
||||
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
|
||||
}
|
||||
|
||||
c.rectFill(c.L, y, 4, 16, primary)
|
||||
c.drawSingleLine("Hoja Resumen", c.L+12, y, c.W-90, "B", 15, dark, "L")
|
||||
y += 26
|
||||
|
||||
enAtencion := data.ClienteEmpresa
|
||||
if strings.TrimSpace(enAtencion) == "" {
|
||||
enAtencion = data.ClienteNombre
|
||||
}
|
||||
c.drawSingleLine("En atención a: "+enAtencion, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
|
||||
c.drawSingleLine("No. Cotización: "+data.Numero, c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
|
||||
y += 11
|
||||
c.drawSingleLine("Asesor: "+data.AsesorNombre, c.L, y, c.W*0.44, "", 8, colorMuted, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("Fecha: %s | Moneda: %s", domain.FormatDateLongMX(data.Fecha), data.Moneda), c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L")
|
||||
y += 16
|
||||
|
||||
colNombre := c.L
|
||||
colTipo := c.L + c.W - 200
|
||||
colTiempo := c.L + c.W - 120
|
||||
colPrecio := c.L + c.W - 60
|
||||
nombreW := colTipo - colNombre - 16
|
||||
|
||||
drawTableHeader := func() {
|
||||
y = c.need(20, y)
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Servicio", colNombre+6, y+4, nombreW, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Tipo", colTipo+4, y+4, 72, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Entrega", colTiempo+4, y+4, 56, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Precio", colPrecio, y+4, 60, "B", 7, dark, "R")
|
||||
y += 18
|
||||
}
|
||||
|
||||
var unicos, mensuales []ServicioPDF
|
||||
for _, s := range data.Servicios {
|
||||
if s.TipoPago == "mensual" {
|
||||
mensuales = append(mensuales, s)
|
||||
} else {
|
||||
unicos = append(unicos, s)
|
||||
}
|
||||
}
|
||||
|
||||
drawSection := func(servicios []ServicioPDF, tipoLabel, tituloTotal string) {
|
||||
if len(servicios) == 0 {
|
||||
return
|
||||
}
|
||||
currentFase := -1
|
||||
for _, serv := range servicios {
|
||||
if serv.Fase != currentFase {
|
||||
currentFase = serv.Fase
|
||||
y = c.need(20, y)
|
||||
c.rectFill(c.L, y, c.W, 14, colorLightBG)
|
||||
faseLbl := domain.FasesShort[serv.Fase]
|
||||
if faseLbl == "" {
|
||||
faseLbl = fmt.Sprintf("FASE %d", serv.Fase)
|
||||
}
|
||||
c.drawSingleLine(faseLbl, c.L+6, y+3, c.W-12, "B", 7, primary, "L")
|
||||
y += 16
|
||||
}
|
||||
|
||||
detalle := domain.DetalleModelo(servicioPDFToCalc(serv))
|
||||
hNombre := c.textHeight(serv.Nombre, nombreW, "", 8)
|
||||
if hNombre < 11 {
|
||||
hNombre = 11
|
||||
}
|
||||
hTiempo := c.textHeight(serv.TiempoEntrega, 56, "", 7)
|
||||
rowTopH := hNombre
|
||||
if hTiempo > rowTopH {
|
||||
rowTopH = hTiempo
|
||||
}
|
||||
hDetalle := 0.0
|
||||
if detalle != "" {
|
||||
hDetalle = c.textHeight(detalle, nombreW-4, "I", 6.5) + 2
|
||||
}
|
||||
colW := c.W * 0.44
|
||||
half := (len(serv.Entregables) + 1) / 2
|
||||
entH := 0.0
|
||||
for i := 0; i < half; i++ {
|
||||
h1 := c.textHeight("• "+serv.Entregables[i], colW, "", 6.5)
|
||||
h2 := 0.0
|
||||
if i+half < len(serv.Entregables) {
|
||||
h2 = c.textHeight("• "+serv.Entregables[i+half], colW, "", 6.5)
|
||||
}
|
||||
if h2 > h1 {
|
||||
h1 = h2
|
||||
}
|
||||
entH += h1 + 1.5
|
||||
}
|
||||
|
||||
totalServH := rowTopH + 2 + hDetalle + entH + 6
|
||||
y = c.need(totalServH, y)
|
||||
|
||||
c.drawText(serv.Nombre, colNombre+6, y, nombreW, "", 8, dark, "L")
|
||||
c.drawSingleLine(tipoLabel, colTipo+4, y, 72, "", 7, colorMuted, "L")
|
||||
c.drawText(serv.TiempoEntrega, colTiempo+4, y, 56, "", 7, colorMuted, "L")
|
||||
c.drawSingleLine(fmtMoney(serv.Precio), colPrecio, y, 60, "B", 8, dark, "R")
|
||||
y += rowTopH + 2
|
||||
|
||||
if detalle != "" {
|
||||
dh := c.drawText(detalle, colNombre+10, y, nombreW-4, "I", 6.5, colorMuted, "L")
|
||||
y += dh + 2
|
||||
}
|
||||
|
||||
if len(serv.Entregables) > 0 {
|
||||
col1X := colNombre + 10
|
||||
col2X := colNombre + c.W*0.48
|
||||
for i := 0; i < half; i++ {
|
||||
h1 := c.drawText("• "+serv.Entregables[i], col1X, y, colW, "", 6.5, colorMuted, "L")
|
||||
h2 := 0.0
|
||||
if i+half < len(serv.Entregables) {
|
||||
h2 = c.drawText("• "+serv.Entregables[i+half], col2X, y, colW, "", 6.5, colorMuted, "L")
|
||||
}
|
||||
if h2 > h1 {
|
||||
h1 = h2
|
||||
}
|
||||
y += h1 + 1.5
|
||||
}
|
||||
}
|
||||
|
||||
c.hLine(colNombre+6, c.L+c.W, y, colorSubtleSep, 0.2)
|
||||
y += 4
|
||||
}
|
||||
|
||||
y += 3
|
||||
total := 0.0
|
||||
for _, s := range servicios {
|
||||
total += s.Precio
|
||||
}
|
||||
y = c.need(34, y)
|
||||
c.rowBg(y, 18, "#f8fafc")
|
||||
c.drawSingleLine(tituloTotal, colNombre+6, y+4, c.W-80, "B", 8.5, primary, "L")
|
||||
c.drawSingleLine(fmtMoney(total), colPrecio-20, y+4, 80, "B", 8.5, primary, "R")
|
||||
y += 22
|
||||
c.drawSingleLine("(Precios en Moneda Nacional, no incluyen IVA)", colNombre+6, y, c.W-12, "", 6.5, colorMuted, "L")
|
||||
y += 12
|
||||
}
|
||||
|
||||
drawOpcionHeader := func(op string) {
|
||||
meta := data.OpcionesMetadata[op]
|
||||
y = c.need(30, y)
|
||||
y += 4
|
||||
c.rectFill(c.L, y, c.W, 18, primary)
|
||||
title := "OPCIÓN " + op
|
||||
if strings.TrimSpace(meta.Titulo) != "" {
|
||||
title += ": " + meta.Titulo
|
||||
}
|
||||
c.drawSingleLine(title, c.L+8, y+3, c.W-16, "B", 10, colorWhite, "L")
|
||||
y += 22
|
||||
if strings.TrimSpace(meta.Descripcion) != "" {
|
||||
h := c.textHeight(meta.Descripcion, c.W-12, "", 7.5)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(meta.Descripcion, c.L+6, y, c.W-12, "", 7.5, dark, "L")
|
||||
y += h + 4
|
||||
}
|
||||
if strings.TrimSpace(meta.NoIncluye) != "" {
|
||||
lbl := "No incluye: " + meta.NoIncluye
|
||||
h := c.textHeight(lbl, c.W-12, "I", 7)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(lbl, c.L+6, y, c.W-12, "I", 7, colorMuted, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
drawComparativa := func() {
|
||||
calcs := serviciosPDFToCalc(data.Servicios)
|
||||
t1 := domain.CalcularTotalesOpcion(calcs, "1")
|
||||
t2 := domain.CalcularTotalesOpcion(calcs, "2")
|
||||
|
||||
y = c.need(90, y)
|
||||
y += 6
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Comparativa de opciones", c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 18
|
||||
|
||||
cLabel := c.L
|
||||
cOp1 := c.L + c.W*0.45
|
||||
cOp2 := c.L + c.W*0.72
|
||||
wOp1 := c.W*0.27 - 4
|
||||
wOp2 := c.W*0.28 - 4
|
||||
|
||||
t1Tit := data.OpcionesMetadata["1"].Titulo
|
||||
t2Tit := data.OpcionesMetadata["2"].Titulo
|
||||
op1Lbl := "Opción 1"
|
||||
if t1Tit != "" {
|
||||
op1Lbl += " - " + t1Tit
|
||||
}
|
||||
op2Lbl := "Opción 2"
|
||||
if t2Tit != "" {
|
||||
op2Lbl += " - " + t2Tit
|
||||
}
|
||||
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Concepto", cLabel+6, y+4, c.W*0.43, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(op1Lbl, cOp1, y+4, wOp1, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(op2Lbl, cOp2, y+4, wOp2, "B", 7.5, dark, "L")
|
||||
y += 18
|
||||
|
||||
ivaLbl := ""
|
||||
if data.IncluirIVA {
|
||||
ivaLbl = " (c/IVA)"
|
||||
}
|
||||
type compRow struct{ lab, v1, v2 string }
|
||||
filas := []compRow{
|
||||
{"Total único" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalUnico, data.IncluirIVA))},
|
||||
{"Total mensual" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalMensual, data.IncluirIVA))},
|
||||
{"Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas)},
|
||||
}
|
||||
for _, f := range filas {
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine(f.lab, cLabel+6, y, c.W*0.43, "", 8, dark, "L")
|
||||
c.drawSingleLine(f.v1, cOp1, y, wOp1, "B", 8, dark, "L")
|
||||
c.drawSingleLine(f.v2, cOp2, y, wOp2, "B", 8, dark, "L")
|
||||
c.hLine(cLabel+6, c.L+c.W, y+12, colorSubtleSep, 0.2)
|
||||
y += 14
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
filterByOp := func(list []ServicioPDF, op string) []ServicioPDF {
|
||||
var out []ServicioPDF
|
||||
for _, s := range list {
|
||||
if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if data.EsDoble {
|
||||
for _, op := range []string{"1", "2"} {
|
||||
drawOpcionHeader(op)
|
||||
drawTableHeader()
|
||||
u := filterByOp(unicos, op)
|
||||
me := filterByOp(mensuales, op)
|
||||
if len(u) > 0 {
|
||||
drawSection(u, "Único", fmt.Sprintf("Total Pago Único - Opción %s", op))
|
||||
}
|
||||
if len(me) > 0 {
|
||||
drawSection(me, "Mensual", fmt.Sprintf("Total Pago Mensual - Opción %s", op))
|
||||
}
|
||||
}
|
||||
drawComparativa()
|
||||
} else {
|
||||
drawTableHeader()
|
||||
if len(unicos) > 0 {
|
||||
drawSection(unicos, "Único", "Total Pago Único")
|
||||
}
|
||||
if len(mensuales) > 0 {
|
||||
drawSection(mensuales, "Mensual", "Total Pago Mensual")
|
||||
}
|
||||
}
|
||||
|
||||
if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" {
|
||||
y = c.need(20, y)
|
||||
nivel := strings.TrimSpace(*data.PlanBucefaloNivel)
|
||||
precio := data.PlanBucefaloPrecio
|
||||
if precio <= 0 {
|
||||
precio = domain.BucefaloPrecio(strings.ToLower(nivel))
|
||||
}
|
||||
c.rowBg(y, 16, colorLightBG)
|
||||
c.drawSingleLine("Plan Bucéfalo CRM - "+capitalize(nivel), colNombre+6, y+3, c.W-80, "B", 7.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(precio), colPrecio-20, y+3, 80, "B", 7.5, dark, "R")
|
||||
y += 20
|
||||
}
|
||||
|
||||
if data.IncluirBonos {
|
||||
y = c.need(90, y)
|
||||
y += 4
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Bonos (Pago en una exhibición)", c.L+10, y, c.W-10, "B", 9, dark, "L")
|
||||
y += 16
|
||||
|
||||
respaldo := []string{
|
||||
"Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)",
|
||||
"Bono 2: Workshop Estratégico de Buyer Persona",
|
||||
"Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible",
|
||||
"Bono 4: 1 año de Membresía Premium",
|
||||
"Bono 5: Un mes gratis de Bucéfalo CRM, Marketing y Ventas",
|
||||
"Bono 6: Script de Ventas con más de 100 complementos",
|
||||
}
|
||||
var bonos []string
|
||||
if len(data.Bonos) > 0 {
|
||||
for _, b := range data.Bonos {
|
||||
bonos = append(bonos, fmt.Sprintf("Bono %d: %s", b.Numero, b.Descripcion))
|
||||
}
|
||||
} else {
|
||||
bonos = respaldo
|
||||
}
|
||||
for _, b := range bonos {
|
||||
txt := "• " + b
|
||||
h := c.textHeight(txt, c.W-16, "", 7.5)
|
||||
y = c.need(h+3, y)
|
||||
c.drawText(txt, c.L+8, y, c.W-16, "", 7.5, dark, "L")
|
||||
y += h + 3
|
||||
}
|
||||
}
|
||||
|
||||
// ── OBSERVACIONES (solo cliente) ───────────────
|
||||
if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" {
|
||||
y += 6
|
||||
y = sectionTitle("Observaciones", y)
|
||||
raw := strings.ReplaceAll(*data.Observaciones, "\r\n", "\n")
|
||||
for _, p := range strings.Split(raw, "\n") {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
lines := c.splitLines(p, c.W-4, "", 7.5)
|
||||
lh := lineHeight(7.5)
|
||||
for _, ln := range lines {
|
||||
y = c.need(lh+2, y)
|
||||
c.drawSingleLine(ln, c.L+2, y, c.W-4, "", 7.5, dark, "L")
|
||||
y += lh
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
|
||||
// ── T&C PAGE ───────────────────────────────────
|
||||
c.doc.AddPage()
|
||||
y = c.mTop
|
||||
|
||||
if logo.ok {
|
||||
logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22)
|
||||
}
|
||||
|
||||
c.rectFill(c.L, y, 4, 16, primary)
|
||||
c.drawSingleLine("Términos y Condiciones", c.L+12, y, c.W-90, "B", 15, dark, "L")
|
||||
y += 28
|
||||
|
||||
drawBullets := func(title string, items []string, yStart float64) float64 {
|
||||
yy := sectionTitle(title, yStart)
|
||||
for _, item := range items {
|
||||
txt := "• " + item
|
||||
h := c.textHeight(txt, c.W-4, "", 7.5)
|
||||
yy = c.need(h+4, yy)
|
||||
c.drawText(txt, c.L+2, yy, c.W-4, "", 7.5, dark, "L")
|
||||
yy += h + 4
|
||||
}
|
||||
return yy + 6
|
||||
}
|
||||
|
||||
y = drawBullets("Condiciones", []string{
|
||||
"Esta cotización tiene una vigencia de 15 días hábiles.",
|
||||
"Cualquier ajuste al proyecto después de la aprobación del contenido afectará la fecha de entrega y por consiguiente el costo.",
|
||||
"El cliente deberá proporcionar la información solicitada por Uriel Jareth Consulting en tiempo y forma.",
|
||||
"Si la falta de información provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizarán por separado.",
|
||||
"Los pagos correspondientes a los servicios mensuales deberán realizarse en los primeros 5 días del mes.",
|
||||
"Todo el material e información necesarios para la realización del sitio web deberán ser entregados en un plazo máximo de 40 días naturales a partir del arranque del proyecto.",
|
||||
}, y)
|
||||
|
||||
y = drawBullets("¿Qué no incluye el proyecto?", []string{
|
||||
"Generación de diseños, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.",
|
||||
"Redacción de entradas de Blog.",
|
||||
"Integración de Servicios de terceros ajenos a los cotizados.",
|
||||
"Servicio de Recuperación de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.",
|
||||
"Creación de Redes Sociales (En caso de requerir el servicio incluirá un costo adicional).",
|
||||
}, y)
|
||||
|
||||
y = drawBullets("Notas", []string{
|
||||
"El presente proyecto deberá tener un responsable oficial.",
|
||||
"La Hora Centinela tiene un precio de $700.00 MXN.",
|
||||
"Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberación (buy-out fee).",
|
||||
"Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generará costo extra del 15% al 30% para retomar el proyecto.",
|
||||
}, y)
|
||||
|
||||
y += 6
|
||||
y = c.need(120, y)
|
||||
y = sectionTitle("Datos Bancarios", y)
|
||||
|
||||
bank := extractBankInfo(data.ConfigBancaria)
|
||||
boxH := 48.0
|
||||
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
|
||||
c.drawSingleLine("Transferencia Nacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
|
||||
if bank.CuentaNacional != "" {
|
||||
c.drawSingleLine("Cuenta: "+bank.CuentaNacional, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
|
||||
}
|
||||
if bank.ClabeNacional != "" {
|
||||
c.drawSingleLine("CLABE: "+bank.ClabeNacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Razón Social: "+bank.RazonSocial, c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
|
||||
c.drawSingleLine("RFC: "+bank.RFC, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
|
||||
if bank.BancoNacional != "" {
|
||||
c.drawSingleLine("Banco: "+bank.BancoNacional, c.L+8, y+37, c.W*0.43, "", 6.5, dark, "L")
|
||||
}
|
||||
y += boxH + 6
|
||||
|
||||
y = c.need(boxH+6, y)
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5)
|
||||
c.drawSingleLine("Transferencia Internacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L")
|
||||
c.drawSingleLine("Beneficiario: "+bank.RazonSocial, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L")
|
||||
if bank.ClabeInternacional != "" {
|
||||
c.drawSingleLine("CLABE: "+bank.ClabeInternacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Banco: BBVA México", c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L")
|
||||
c.drawSingleLine("SWIFT: "+bank.Swift, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L")
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"codeberg.org/go-pdf/fpdf"
|
||||
"golang.org/x/image/font/gofont/gobold"
|
||||
"golang.org/x/image/font/gofont/gobolditalic"
|
||||
"golang.org/x/image/font/gofont/goitalic"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/webp"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
fontFamily = "Go"
|
||||
|
||||
defaultPrimary = "#0400C4"
|
||||
defaultDark = "#0F172A"
|
||||
colorMuted = "#64748b"
|
||||
colorBorder = "#cbd5e1"
|
||||
colorLightBG = "#f1f5f9"
|
||||
colorWhite = "#ffffff"
|
||||
colorSubtleSep = "#e5e7eb"
|
||||
)
|
||||
|
||||
var (
|
||||
hexColorRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
||||
swiftRe = regexp.MustCompile(`(?i)SWIFT[^:]*:\s*(\S+)`)
|
||||
clabeRe = regexp.MustCompile(`(?i)CLABE[^:]*:\s*(\S+)`)
|
||||
)
|
||||
|
||||
func safeHex(v, fallback string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if hexColorRe.MatchString(v) {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func parseHexRGB(hexStr, fallback string) (int, int, int) {
|
||||
h := strings.TrimPrefix(safeHex(hexStr, fallback), "#")
|
||||
r, _ := strconv.ParseInt(h[0:2], 16, 64)
|
||||
g, _ := strconv.ParseInt(h[2:4], 16, 64)
|
||||
b, _ := strconv.ParseInt(h[4:6], 16, 64)
|
||||
return int(r), int(g), int(b)
|
||||
}
|
||||
|
||||
func capitalize(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
r := []rune(s)
|
||||
r[0] = unicode.ToUpper(r[0])
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func formatMoney(amount float64, moneda string) string {
|
||||
if moneda == "" || strings.EqualFold(moneda, "MXN") {
|
||||
return domain.FormatCurrency(amount)
|
||||
}
|
||||
return domain.FormatMonto(amount, moneda)
|
||||
}
|
||||
|
||||
type bankInfo struct {
|
||||
RazonSocial string
|
||||
RFC string
|
||||
CuentaNacional string
|
||||
ClabeNacional string
|
||||
BancoNacional string
|
||||
ClabeInternacional string
|
||||
Swift string
|
||||
}
|
||||
|
||||
func extractBankInfo(cfg map[string]string) bankInfo {
|
||||
if cfg == nil {
|
||||
cfg = map[string]string{}
|
||||
}
|
||||
razon := strings.TrimSpace(cfg["razon_social"])
|
||||
if razon == "" {
|
||||
razon = "URIEL JARETH ALVARADO ORTIZ"
|
||||
}
|
||||
rfc := strings.TrimSpace(cfg["rfc"])
|
||||
if rfc == "" {
|
||||
rfc = "AAOU970201SU7"
|
||||
}
|
||||
cuentaNac := strings.TrimSpace(cfg["cuenta_nacional"])
|
||||
clabeNac := strings.TrimSpace(cfg["clabe_interbancaria"])
|
||||
if clabeNac == "" {
|
||||
clabeNac = cuentaNac
|
||||
}
|
||||
bancoNac := ""
|
||||
if cuentaNac != "" {
|
||||
bancoNac = "BBVA"
|
||||
}
|
||||
swift := "BCMRMXMMPYM"
|
||||
clabeInt := ""
|
||||
if intl := cfg["cuenta_internacional_swift"]; intl != "" {
|
||||
if m := swiftRe.FindStringSubmatch(intl); len(m) > 1 {
|
||||
swift = m[1]
|
||||
}
|
||||
if m := clabeRe.FindStringSubmatch(intl); len(m) > 1 {
|
||||
clabeInt = m[1]
|
||||
}
|
||||
}
|
||||
return bankInfo{
|
||||
RazonSocial: razon,
|
||||
RFC: rfc,
|
||||
CuentaNacional: cuentaNac,
|
||||
ClabeNacional: clabeNac,
|
||||
BancoNacional: bancoNac,
|
||||
ClabeInternacional: clabeInt,
|
||||
Swift: swift,
|
||||
}
|
||||
}
|
||||
|
||||
type logoAsset struct {
|
||||
name string
|
||||
w float64
|
||||
h float64
|
||||
ok bool
|
||||
}
|
||||
|
||||
// prepareLogoBytes decodes base64 and normalizes PNG/JPEG/WebP into a format fpdf safely accepts.
|
||||
// WebP (and non-standard PNGs) are decoded and re-encoded as standard 8-bit PNG.
|
||||
func prepareLogoBytes(b64, mime string) ([]byte, string, error) {
|
||||
b64 = strings.TrimSpace(b64)
|
||||
if b64 == "" {
|
||||
return nil, "", fmt.Errorf("empty logo")
|
||||
}
|
||||
// Strip optional data URI prefix.
|
||||
if idx := strings.Index(b64, ","); idx != -1 && strings.HasPrefix(b64[:idx], "data:") {
|
||||
if mime == "" {
|
||||
header := b64[len("data:"):idx]
|
||||
if semi := strings.Index(header, ";"); semi != -1 {
|
||||
mime = header[:semi]
|
||||
}
|
||||
}
|
||||
b64 = b64[idx+1:]
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
raw, err = base64.RawStdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
if len(raw) < 8 {
|
||||
return nil, "", fmt.Errorf("logo too short")
|
||||
}
|
||||
|
||||
m := strings.ToLower(strings.TrimSpace(mime))
|
||||
isWebP := m == "image/webp" || (len(raw) >= 12 && string(raw[0:4]) == "RIFF" && string(raw[8:12]) == "WEBP")
|
||||
if isWebP {
|
||||
img, err := webp.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
isJPEG := m == "image/jpeg" || m == "image/jpg" || (raw[0] == 0xFF && raw[1] == 0xD8)
|
||||
if isJPEG {
|
||||
if _, err := jpeg.DecodeConfig(bytes.NewReader(raw)); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return raw, "JPG", nil
|
||||
}
|
||||
|
||||
isPNG := m == "image/png" || bytes.Equal(raw[0:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})
|
||||
if isPNG {
|
||||
// Re-encode through image/png so interlaced or 16-bit PNGs always work with fpdf.
|
||||
img, err := png.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
// Fallback: try generic image decode -> PNG.
|
||||
img, _, err := image.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := png.Encode(&out, img); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out.Bytes(), "PNG", nil
|
||||
}
|
||||
|
||||
func registerLogo(doc *fpdf.Fpdf, name, b64, mime string) logoAsset {
|
||||
imgBytes, imgType, err := prepareLogoBytes(b64, mime)
|
||||
if err != nil {
|
||||
return logoAsset{}
|
||||
}
|
||||
opts := fpdf.ImageOptions{ImageType: imgType, ReadDpi: false}
|
||||
info := doc.RegisterImageOptionsReader(name, opts, bytes.NewReader(imgBytes))
|
||||
if info == nil || !doc.Ok() {
|
||||
doc.ClearError()
|
||||
return logoAsset{}
|
||||
}
|
||||
return logoAsset{
|
||||
name: name,
|
||||
w: info.Width(),
|
||||
h: info.Height(),
|
||||
ok: info.Width() > 0 && info.Height() > 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (l logoAsset) drawByHeight(doc *fpdf.Fpdf, x, y, targetH float64) {
|
||||
if !l.ok {
|
||||
return
|
||||
}
|
||||
doc.ImageOptions(l.name, x, y, 0, targetH, false, fpdf.ImageOptions{}, 0, "")
|
||||
}
|
||||
|
||||
func (l logoAsset) drawRightAlignedByHeight(doc *fpdf.Fpdf, rightX, y, targetH float64) {
|
||||
if !l.ok {
|
||||
return
|
||||
}
|
||||
w := targetH * (l.w / l.h)
|
||||
if w > 90 {
|
||||
w = 90
|
||||
targetH = w * (l.h / l.w)
|
||||
}
|
||||
doc.ImageOptions(l.name, rightX-w, y, w, targetH, false, fpdf.ImageOptions{}, 0, "")
|
||||
}
|
||||
|
||||
func (l logoAsset) drawFit(doc *fpdf.Fpdf, x, y, maxW, maxH float64) (float64, float64) {
|
||||
if !l.ok {
|
||||
return 0, 0
|
||||
}
|
||||
scale := maxW / l.w
|
||||
if sh := maxH / l.h; sh < scale {
|
||||
scale = sh
|
||||
}
|
||||
w := l.w * scale
|
||||
h := l.h * scale
|
||||
doc.ImageOptions(l.name, x, y, w, h, false, fpdf.ImageOptions{}, 0, "")
|
||||
return w, h
|
||||
}
|
||||
|
||||
type canvas struct {
|
||||
doc *fpdf.Fpdf
|
||||
pw float64
|
||||
ph float64
|
||||
mTop float64
|
||||
mBottom float64
|
||||
mLeft float64
|
||||
mRight float64
|
||||
W float64
|
||||
L float64
|
||||
maxY float64
|
||||
}
|
||||
|
||||
func newCanvas(top, bottom, left, right float64) *canvas {
|
||||
doc := fpdf.New("P", "pt", "Letter", "")
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "", goregular.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "B", gobold.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "I", goitalic.TTF)
|
||||
doc.AddUTF8FontFromBytes(fontFamily, "BI", gobolditalic.TTF)
|
||||
doc.SetMargins(left, top, right)
|
||||
doc.SetAutoPageBreak(false, 0)
|
||||
doc.SetCellMargin(0)
|
||||
doc.SetFont(fontFamily, "", 10)
|
||||
|
||||
pw, ph := doc.GetPageSize()
|
||||
return &canvas{
|
||||
doc: doc,
|
||||
pw: pw,
|
||||
ph: ph,
|
||||
mTop: top,
|
||||
mBottom: bottom,
|
||||
mLeft: left,
|
||||
mRight: right,
|
||||
W: pw - left - right,
|
||||
L: left,
|
||||
maxY: ph - bottom - 5,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *canvas) need(h, y float64) float64 {
|
||||
if y+h > c.maxY {
|
||||
c.doc.AddPage()
|
||||
return c.mTop
|
||||
}
|
||||
return y
|
||||
}
|
||||
|
||||
func (c *canvas) setFont(style string, size float64) {
|
||||
c.doc.SetFont(fontFamily, style, size)
|
||||
}
|
||||
|
||||
func (c *canvas) setTextColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, defaultDark)
|
||||
c.doc.SetTextColor(r, g, b)
|
||||
}
|
||||
|
||||
func (c *canvas) setFillColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, colorWhite)
|
||||
c.doc.SetFillColor(r, g, b)
|
||||
}
|
||||
|
||||
func (c *canvas) setDrawColor(hex string) {
|
||||
r, g, b := parseHexRGB(hex, colorBorder)
|
||||
c.doc.SetDrawColor(r, g, b)
|
||||
}
|
||||
|
||||
func lineHeight(size float64) float64 {
|
||||
return size * 1.25
|
||||
}
|
||||
|
||||
func (c *canvas) splitLines(txt string, width float64, style string, size float64) []string {
|
||||
c.setFont(style, size)
|
||||
if width <= 1 {
|
||||
return []string{txt}
|
||||
}
|
||||
rawLines := strings.Split(strings.ReplaceAll(txt, "\r\n", "\n"), "\n")
|
||||
var out []string
|
||||
for _, rl := range rawLines {
|
||||
if rl == "" {
|
||||
out = append(out, "")
|
||||
continue
|
||||
}
|
||||
parts := c.doc.SplitText(rl, width)
|
||||
if len(parts) == 0 {
|
||||
out = append(out, rl)
|
||||
} else {
|
||||
out = append(out, parts...)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return []string{""}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *canvas) textHeight(txt string, width float64, style string, size float64) float64 {
|
||||
lines := c.splitLines(txt, width, style, size)
|
||||
return float64(len(lines)) * lineHeight(size)
|
||||
}
|
||||
|
||||
// drawText writes multi-line wrapped text starting at (x, y) and returns total height drawn.
|
||||
func (c *canvas) drawText(txt string, x, y, width float64, style string, size float64, color, align string) float64 {
|
||||
if align == "" {
|
||||
align = "L"
|
||||
}
|
||||
lines := c.splitLines(txt, width, style, size)
|
||||
lh := lineHeight(size)
|
||||
c.setFont(style, size)
|
||||
c.setTextColor(color)
|
||||
curY := y
|
||||
for _, ln := range lines {
|
||||
c.doc.SetXY(x, curY)
|
||||
c.doc.CellFormat(width, lh, ln, "", 0, align, false, 0, "")
|
||||
curY += lh
|
||||
}
|
||||
return float64(len(lines)) * lh
|
||||
}
|
||||
|
||||
// drawSingleLine writes text on one line without wrapping.
|
||||
func (c *canvas) drawSingleLine(txt string, x, y, width float64, style string, size float64, color, align string) {
|
||||
if align == "" {
|
||||
align = "L"
|
||||
}
|
||||
c.setFont(style, size)
|
||||
c.setTextColor(color)
|
||||
c.doc.SetXY(x, y)
|
||||
if width <= 0 {
|
||||
width = c.doc.GetStringWidth(txt) + 2
|
||||
}
|
||||
c.doc.CellFormat(width, lineHeight(size), txt, "", 0, align, false, 0, "")
|
||||
}
|
||||
|
||||
func (c *canvas) rectFill(x, y, w, h float64, fillHex string) {
|
||||
c.setFillColor(fillHex)
|
||||
c.doc.Rect(x, y, w, h, "F")
|
||||
}
|
||||
|
||||
func (c *canvas) rectFillStroke(x, y, w, h float64, fillHex, strokeHex string, lw float64) {
|
||||
c.setFillColor(fillHex)
|
||||
c.setDrawColor(strokeHex)
|
||||
c.doc.SetLineWidth(lw)
|
||||
c.doc.Rect(x, y, w, h, "DF")
|
||||
}
|
||||
|
||||
func (c *canvas) hLine(x1, x2, y float64, strokeHex string, lw float64) {
|
||||
c.setDrawColor(strokeHex)
|
||||
c.doc.SetLineWidth(lw)
|
||||
c.doc.Line(x1, y, x2, y)
|
||||
}
|
||||
|
||||
func (c *canvas) circleFill(cx, cy, r float64, fillHex string) {
|
||||
c.setFillColor(fillHex)
|
||||
c.doc.Circle(cx, cy, r, "F")
|
||||
}
|
||||
|
||||
func (c *canvas) rowBg(y, h float64, bgHex string) {
|
||||
c.rectFill(c.L, y, c.W, h, bgHex)
|
||||
c.hLine(c.L, c.L+c.W, y+h, colorBorder, 0.3)
|
||||
}
|
||||
|
||||
func (c *canvas) bytes() ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := c.doc.Output(&buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type RegistroHoraPDF struct {
|
||||
Fecha time.Time
|
||||
HoraInicio string
|
||||
HoraFin string
|
||||
Horas float64
|
||||
TarifaHora float64
|
||||
Descripcion string
|
||||
EstadoPago string
|
||||
}
|
||||
|
||||
type NotaHorasPDFData struct {
|
||||
Titulo string
|
||||
Numero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
Proyecto string
|
||||
AsesorNombre string
|
||||
Moneda string
|
||||
IncluirIVA bool
|
||||
Modo string
|
||||
MostrarEstado bool
|
||||
MostrarBancarios bool
|
||||
Registros []RegistroHoraPDF
|
||||
ConfigBancaria map[string]string
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
FechaEmision time.Time
|
||||
}
|
||||
|
||||
type notaHorasGrupo struct {
|
||||
Clave string
|
||||
Etiqueta string
|
||||
Count int
|
||||
Horas float64
|
||||
Importe float64
|
||||
}
|
||||
|
||||
func modoAgrupacionLabel(modo string) string {
|
||||
switch modo {
|
||||
case "dia":
|
||||
return "Por día"
|
||||
case "semana":
|
||||
return "Por semana"
|
||||
case "mes":
|
||||
return "Por mes"
|
||||
default:
|
||||
return "Detalle"
|
||||
}
|
||||
}
|
||||
|
||||
func etiquetaTotalNota(titulo string) string {
|
||||
low := strings.ToLower(titulo)
|
||||
switch {
|
||||
case strings.Contains(low, "pagadas"):
|
||||
return "Total pagado"
|
||||
case strings.Contains(low, "por pagar"):
|
||||
return "Total a pagar"
|
||||
default:
|
||||
return "Total"
|
||||
}
|
||||
}
|
||||
|
||||
func GenerateNotaHorasPDF(data NotaHorasPDFData) ([]byte, error) {
|
||||
primary := safeHex(data.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(data.ColorSecundario, defaultDark)
|
||||
muted := "#6b7280"
|
||||
border := "#d1d5db"
|
||||
headBG := "#f3f4f6"
|
||||
|
||||
titulo := strings.TrimSpace(data.Titulo)
|
||||
if titulo == "" {
|
||||
titulo = "Nota de horas por pagar"
|
||||
}
|
||||
modo := strings.ToLower(strings.TrimSpace(data.Modo))
|
||||
if modo != "detalle" && modo != "dia" && modo != "semana" && modo != "mes" {
|
||||
modo = "detalle"
|
||||
}
|
||||
modoLabel := modoAgrupacionLabel(modo)
|
||||
|
||||
emitida := data.FechaEmision
|
||||
if emitida.IsZero() {
|
||||
emitida = time.Now()
|
||||
}
|
||||
|
||||
// Copy and sort records chronologically.
|
||||
regs := make([]RegistroHoraPDF, len(data.Registros))
|
||||
copy(regs, data.Registros)
|
||||
sort.Slice(regs, func(i, j int) bool {
|
||||
if regs[i].Fecha.Equal(regs[j].Fecha) {
|
||||
return regs[i].HoraInicio < regs[j].HoraInicio
|
||||
}
|
||||
return regs[i].Fecha.Before(regs[j].Fecha)
|
||||
})
|
||||
|
||||
// Totals.
|
||||
var totalHoras, subtotal float64
|
||||
for _, r := range regs {
|
||||
totalHoras += r.Horas
|
||||
subtotal += r.Horas * r.TarifaHora
|
||||
}
|
||||
totalHoras = domain.Round2(totalHoras)
|
||||
subtotal = domain.Round2(subtotal)
|
||||
iva := 0.0
|
||||
if data.IncluirIVA {
|
||||
iva = domain.Round2(subtotal * domain.IVARate)
|
||||
}
|
||||
total := domain.Round2(subtotal + iva)
|
||||
|
||||
// Periodo text.
|
||||
periodoTexto := "Periodo: todos los registros"
|
||||
if len(regs) > 0 {
|
||||
minF := domain.FormatFechaRegistro(regs[0].Fecha)
|
||||
maxF := domain.FormatFechaRegistro(regs[len(regs)-1].Fecha)
|
||||
if minF == maxF {
|
||||
periodoTexto = "Periodo: " + minF
|
||||
} else {
|
||||
periodoTexto = fmt.Sprintf("Periodo: %s al %s", minF, maxF)
|
||||
}
|
||||
}
|
||||
|
||||
// Grouping if not detalle.
|
||||
var grupos []notaHorasGrupo
|
||||
if modo != "detalle" {
|
||||
m := make(map[string]*notaHorasGrupo)
|
||||
for _, r := range regs {
|
||||
per := domain.PeriodoAgrupacionDe(r.Fecha, modo)
|
||||
g, ok := m[per.Clave]
|
||||
if !ok {
|
||||
g = ¬aHorasGrupo{Clave: per.Clave, Etiqueta: per.Etiqueta}
|
||||
m[per.Clave] = g
|
||||
}
|
||||
g.Count++
|
||||
g.Horas += r.Horas
|
||||
g.Importe += r.Horas * r.TarifaHora
|
||||
}
|
||||
for _, g := range m {
|
||||
g.Horas = domain.Round2(g.Horas)
|
||||
g.Importe = domain.Round2(g.Importe)
|
||||
grupos = append(grupos, *g)
|
||||
}
|
||||
sort.Slice(grupos, func(i, j int) bool {
|
||||
return grupos[i].Clave < grupos[j].Clave
|
||||
})
|
||||
}
|
||||
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, data.Moneda)
|
||||
}
|
||||
|
||||
c := newCanvas(45, 55, 50, 50)
|
||||
c.maxY = c.ph - c.mBottom
|
||||
logo := registerLogo(c.doc, "nota_logo", data.LogoBase64, data.LogoMime)
|
||||
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
// ── ENCABEZADO ────────────────────────────────
|
||||
logoBottom := y
|
||||
if logo.ok {
|
||||
_, lh := logo.drawFit(c.doc, c.L, y, 46, 46)
|
||||
logoBottom = y + lh
|
||||
}
|
||||
txtX := c.L
|
||||
if logo.ok {
|
||||
txtX = c.L + 58
|
||||
}
|
||||
titleW := c.W - 170
|
||||
if logo.ok {
|
||||
titleW = c.W - 58 - 115
|
||||
}
|
||||
hTit := c.drawText(titulo, txtX, y+2, titleW, "B", 18, dark, "L")
|
||||
sub := fmt.Sprintf("Cotización %s · %s", data.Numero, data.Proyecto)
|
||||
hSub := c.drawText(sub, txtX, y+2+hTit+1, titleW, "", 9, muted, "L")
|
||||
c.drawSingleLine("Emitida: "+domain.FormatFechaRegistro(emitida), c.L, y+2, c.W, "", 9, muted, "R")
|
||||
|
||||
yTextEnd := y + 2 + hTit + 1 + hSub + 6
|
||||
y = y + 50
|
||||
if logoBottom+6 > y {
|
||||
y = logoBottom + 6
|
||||
}
|
||||
if yTextEnd > y {
|
||||
y = yTextEnd
|
||||
}
|
||||
c.hLine(c.L, c.L+c.W, y, primary, 2.5)
|
||||
y += 14
|
||||
|
||||
// ── META ──────────────────────────────────────
|
||||
cliente := data.ClienteEmpresa
|
||||
if strings.TrimSpace(cliente) == "" {
|
||||
cliente = data.ClienteNombre
|
||||
}
|
||||
drawMetaLine := func(label, val string) {
|
||||
c.setFont("B", 9.5)
|
||||
lw := c.doc.GetStringWidth(label) + 2
|
||||
c.drawSingleLine(label, c.L, y, lw, "B", 9.5, dark, "L")
|
||||
h := c.drawText(val, c.L+lw, y, c.W-lw, "", 9.5, dark, "L")
|
||||
y += h + 2
|
||||
}
|
||||
drawMetaLine("Cliente: ", cliente)
|
||||
if strings.TrimSpace(data.ClienteEmpresa) != "" && strings.TrimSpace(data.ClienteNombre) != "" {
|
||||
drawMetaLine("Contacto: ", data.ClienteNombre)
|
||||
}
|
||||
if strings.TrimSpace(data.AsesorNombre) != "" {
|
||||
drawMetaLine("Asesor: ", data.AsesorNombre)
|
||||
}
|
||||
hPer := c.drawText(fmt.Sprintf("%s · Desglose %s", periodoTexto, strings.ToLower(modoLabel)), c.L, y, c.W, "", 8.5, muted, "L")
|
||||
y += hPer + 12
|
||||
|
||||
// ── TABLA ─────────────────────────────────────
|
||||
if modo == "detalle" {
|
||||
wEstado := 0.0
|
||||
if data.MostrarEstado {
|
||||
wEstado = 58.0
|
||||
}
|
||||
cFecha := c.L
|
||||
wFecha, wHorario, wHoras, wTarifa, wImporte := 62.0, 72.0, 42.0, 52.0, 58.0
|
||||
cHorario := cFecha + wFecha
|
||||
cHoras := cHorario + wHorario
|
||||
cTarifa := cHoras + wHoras
|
||||
cImporte := cTarifa + wTarifa
|
||||
cDesc := cImporte + wImporte + 6
|
||||
estadoPad := 0.0
|
||||
if wEstado > 0 {
|
||||
estadoPad = 6.0
|
||||
}
|
||||
wDesc := c.L + c.W - cDesc - wEstado - estadoPad
|
||||
cEstado := c.L + c.W - wEstado
|
||||
|
||||
drawHeader := func(yy float64) float64 {
|
||||
c.rectFill(c.L, yy, c.W, 16, headBG)
|
||||
c.drawSingleLine("FECHA", cFecha+4, yy+4, wFecha-4, "B", 7, dark, "L")
|
||||
c.drawSingleLine("HORARIO", cHorario+4, yy+4, wHorario-4, "B", 7, dark, "L")
|
||||
c.drawSingleLine("HORAS", cHoras, yy+4, wHoras-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("TARIFA", cTarifa, yy+4, wTarifa-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("IMPORTE", cImporte, yy+4, wImporte-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("DESCRIPCIÓN", cDesc, yy+4, wDesc, "B", 7, dark, "L")
|
||||
if wEstado > 0 {
|
||||
c.drawSingleLine("ESTADO", cEstado, yy+4, wEstado, "B", 7, dark, "L")
|
||||
}
|
||||
return yy + 16
|
||||
}
|
||||
|
||||
y = drawHeader(y)
|
||||
for _, r := range regs {
|
||||
descH := c.textHeight(r.Descripcion, wDesc, "", 8)
|
||||
rowH := descH + 8
|
||||
if rowH < 16 {
|
||||
rowH = 16
|
||||
}
|
||||
if y+rowH > c.maxY {
|
||||
y = drawHeader(c.need(rowH+16, y))
|
||||
}
|
||||
c.drawSingleLine(domain.FormatFechaRegistro(r.Fecha), cFecha+4, y+4, wFecha-4, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%s-%s", r.HoraInicio, r.HoraFin), cHorario+4, y+4, wHorario-4, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%.2f", r.Horas), cHoras, y+4, wHoras-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(r.TarifaHora), cTarifa, y+4, wTarifa-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(r.Horas*r.TarifaHora), cImporte, y+4, wImporte-2, "", 8, dark, "R")
|
||||
c.drawText(r.Descripcion, cDesc, y+4, wDesc, "", 8, dark, "L")
|
||||
if wEstado > 0 {
|
||||
est := "Por pagar"
|
||||
if domain.EsPagada(r.EstadoPago) {
|
||||
est = "Pagada"
|
||||
}
|
||||
c.drawSingleLine(est, cEstado, y+4, wEstado, "", 8, dark, "L")
|
||||
}
|
||||
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
|
||||
y += rowH
|
||||
}
|
||||
} else {
|
||||
wReg, wHor, wImp := 90.0, 90.0, 90.0
|
||||
cPer := c.L
|
||||
wPer := c.W - wReg - wHor - wImp
|
||||
cReg := cPer + wPer
|
||||
cHor := cReg + wReg
|
||||
cImp := cHor + wHor
|
||||
|
||||
drawHeader := func(yy float64) float64 {
|
||||
c.rectFill(c.L, yy, c.W, 16, headBG)
|
||||
c.drawSingleLine(strings.ToUpper(modoLabel), cPer+4, yy+4, wPer-6, "B", 7, dark, "L")
|
||||
c.drawSingleLine("REGISTROS", cReg, yy+4, wReg-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("HORAS", cHor, yy+4, wHor-2, "B", 7, dark, "R")
|
||||
c.drawSingleLine("IMPORTE", cImp, yy+4, wImp-2, "B", 7, dark, "R")
|
||||
return yy + 16
|
||||
}
|
||||
|
||||
y = drawHeader(y)
|
||||
for _, g := range grupos {
|
||||
rowH := 16.0
|
||||
if y+rowH > c.maxY {
|
||||
y = drawHeader(c.need(rowH+16, y))
|
||||
}
|
||||
c.drawSingleLine(g.Etiqueta, cPer+4, y+4, wPer-6, "", 8, dark, "L")
|
||||
c.drawSingleLine(fmt.Sprintf("%d", g.Count), cReg, y+4, wReg-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmt.Sprintf("%.2f", g.Horas), cHor, y+4, wHor-2, "", 8, dark, "R")
|
||||
c.drawSingleLine(fmtMoney(g.Importe), cImp, y+4, wImp-2, "", 8, dark, "R")
|
||||
c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3)
|
||||
y += rowH
|
||||
}
|
||||
}
|
||||
|
||||
// ── TOTALES ───────────────────────────────────
|
||||
y += 12
|
||||
totW := 240.0
|
||||
totX := c.L + c.W - totW
|
||||
drawTotalLine := func(label, val string, bold, topLine bool) {
|
||||
y = c.need(20, y)
|
||||
if topLine {
|
||||
c.hLine(totX, totX+totW, y, primary, 1.2)
|
||||
y += 5
|
||||
}
|
||||
style := ""
|
||||
size := 9.0
|
||||
lblColor := muted
|
||||
step := 15.0
|
||||
if bold {
|
||||
style = "B"
|
||||
size = 12.0
|
||||
lblColor = dark
|
||||
step = 18.0
|
||||
}
|
||||
c.drawSingleLine(label, totX, y, totW-95, style, size, lblColor, "L")
|
||||
c.drawSingleLine(val, totX+totW-95, y, 95, style, size, dark, "R")
|
||||
y += step
|
||||
}
|
||||
|
||||
drawTotalLine("Total de horas", fmt.Sprintf("%.2f h", totalHoras), false, false)
|
||||
drawTotalLine("Subtotal", fmtMoney(subtotal), false, false)
|
||||
if data.IncluirIVA {
|
||||
drawTotalLine("IVA (16%)", fmtMoney(iva), false, false)
|
||||
}
|
||||
drawTotalLine(etiquetaTotalNota(titulo), fmtMoney(total), true, true)
|
||||
|
||||
// ── DATOS PARA EL PAGO ────────────────────────
|
||||
if data.MostrarBancarios {
|
||||
dp := extractBankInfo(data.ConfigBancaria)
|
||||
boxH := 52.0
|
||||
y = c.need(boxH+34, y) + 16
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine("Datos para el pago", c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 16
|
||||
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
|
||||
c.drawSingleLine("Transferencia Nacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
|
||||
if dp.CuentaNacional != "" {
|
||||
c.drawSingleLine("Cuenta: "+dp.CuentaNacional, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
if dp.ClabeNacional != "" {
|
||||
c.drawSingleLine("CLABE: "+dp.ClabeNacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
c.drawSingleLine("RFC: "+dp.RFC, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.BancoNacional != "" {
|
||||
c.drawSingleLine("Banco: "+dp.BancoNacional, c.L+8, y+42, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
y += boxH + 8
|
||||
|
||||
if dp.ClabeInternacional != "" || dp.Swift != "" {
|
||||
y = c.need(boxH, y)
|
||||
c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5)
|
||||
c.drawSingleLine("Transferencia Internacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L")
|
||||
c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.ClabeInternacional != "" {
|
||||
c.drawSingleLine("CLABE: "+dp.ClabeInternacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
c.drawSingleLine("Banco: BBVA México", c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
if dp.Swift != "" {
|
||||
c.drawSingleLine("SWIFT: "+dp.Swift, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L")
|
||||
}
|
||||
y += boxH + 8
|
||||
}
|
||||
}
|
||||
|
||||
// ── PIE ───────────────────────────────────────
|
||||
y = c.need(30, y) + 14
|
||||
c.drawText(
|
||||
"Documento generado desde el Cotizador. Conteo de horas trabajadas para cobro del proyecto.",
|
||||
c.L, y, c.W, "", 8, muted, "C",
|
||||
)
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/HugoSmits86/nativewebp"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/font/sfnt"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
func f64(v float64) *float64 { return &v }
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func makeTestImage() image.Image {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 32, 16))
|
||||
for y := 0; y < 16; y++ {
|
||||
for x := 0; x < 32; x++ {
|
||||
img.Set(x, y, color.NRGBA{R: 4, G: 0, B: 196, A: 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func makePNGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, makeTestImage()); err != nil {
|
||||
t.Fatalf("png encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeJPEGLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, makeTestImage(), &jpeg.Options{Quality: 85}); err != nil {
|
||||
t.Fatalf("jpeg encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func makeWebPLogoB64(t *testing.T) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := nativewebp.Encode(&buf, makeTestImage(), nil); err != nil {
|
||||
t.Fatalf("webp encode: %v", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
|
||||
func assertValidPDF(t *testing.T, b []byte, minPages int) {
|
||||
t.Helper()
|
||||
if len(b) < 500 {
|
||||
t.Fatalf("PDF too small: %d bytes", len(b))
|
||||
}
|
||||
if !bytes.HasPrefix(b, []byte("%PDF-")) {
|
||||
t.Fatalf("missing %%PDF- header: %q", b[:min(20, len(b))])
|
||||
}
|
||||
if !bytes.Contains(b, []byte("%%EOF")) {
|
||||
t.Fatalf("missing %%%%EOF trailer")
|
||||
}
|
||||
pages := bytes.Count(b, []byte("/Type /Page\n")) + bytes.Count(b, []byte("/Type /Page ")) + bytes.Count(b, []byte("/Type /Page/"))
|
||||
if pages < minPages {
|
||||
t.Fatalf("expected at least %d pages, counted %d", minPages, pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoFontGlyphCoverage(t *testing.T) {
|
||||
f, err := sfnt.Parse(goregular.TTF)
|
||||
if err != nil {
|
||||
t.Fatalf("parse goregular: %v", err)
|
||||
}
|
||||
var buf sfnt.Buffer
|
||||
const chars = "áéíóúüñÁÉÍÓÚÜÑ¿¡•·—×○$€%"
|
||||
for _, r := range chars {
|
||||
idx, err := f.GlyphIndex(&buf, r)
|
||||
if err != nil || idx == 0 {
|
||||
t.Errorf("goregular missing glyph for %q (U+%04X)", r, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCotizacionPDFDataHasNoObservacionesInternas(t *testing.T) {
|
||||
rt := reflect.TypeOf(CotizacionPDFData{})
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
name := strings.ToLower(rt.Field(i).Name)
|
||||
if strings.Contains(name, "interna") {
|
||||
t.Fatalf("CotizacionPDFData must never declare internal observations field, found %q", rt.Field(i).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFSingleAndLogos(t *testing.T) {
|
||||
fecha := time.Date(2026, 5, 10, 12, 0, 0, 0, time.UTC)
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
obs := "Primer párrafo con acentos: diseño, campaña y año.\n\n" + strings.Repeat("Observación extendida para probar el salto de línea automático en el PDF. ", 15)
|
||||
|
||||
baseData := CotizacionPDFData{
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "María José Peña",
|
||||
ClienteEmpresa: "Industrias del Bajío S.A.",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: vigencia,
|
||||
Moneda: "MXN",
|
||||
TipoCambio: "N/A",
|
||||
Proyecto: "Rediseño Web y Campaña de Adquisición",
|
||||
EsquemaPago: "50% anticipo, 50% entrega",
|
||||
Servicios: []ServicioPDF{
|
||||
{
|
||||
Nombre: "Auditoría SEO y Técnica",
|
||||
Fase: 0,
|
||||
TipoPago: "unico",
|
||||
Precio: 8500,
|
||||
TiempoEntrega: "7 días",
|
||||
Entregables: []string{"Reporte técnico", "Mapa de palabras clave", "Plan de acción"},
|
||||
ModeloCobro: "fijo",
|
||||
},
|
||||
{
|
||||
Nombre: "Desarrollo a la medida",
|
||||
Fase: 1,
|
||||
TipoPago: "unico",
|
||||
Precio: 14000,
|
||||
TiempoEntrega: "15 días",
|
||||
Entregables: []string{"Arquitectura", "Implementación", "Pruebas QA"},
|
||||
ModeloCobro: "horas",
|
||||
EsPersonalizado: true,
|
||||
Horas: f64(20),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Soporte Mensual Retainer",
|
||||
Fase: 2,
|
||||
TipoPago: "mensual",
|
||||
Precio: 7500,
|
||||
TiempoEntrega: "Mensual",
|
||||
Entregables: []string{"Monitoreo continuo", "Actualizaciones de seguridad"},
|
||||
ModeloCobro: "retainer",
|
||||
MontoMinimo: f64(7500),
|
||||
HorasIncluidas: f64(10),
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
{
|
||||
Nombre: "Horas Centinela bajo demanda",
|
||||
Fase: 3,
|
||||
TipoPago: "mensual",
|
||||
Precio: 0,
|
||||
TiempoEntrega: "Según consumo",
|
||||
ModeloCobro: "demanda",
|
||||
TarifaHora: f64(700),
|
||||
},
|
||||
},
|
||||
PlanBucefaloNivel: str("estandar"),
|
||||
PlanBucefaloPrecio: 3500,
|
||||
IncluirBonos: true,
|
||||
Bonos: []BonoPDF{
|
||||
{Numero: 1, Descripcion: "Workshop estratégico de diseño"},
|
||||
{Numero: 2, Descripcion: "Un mes gratis de Bucéfalo CRM"},
|
||||
},
|
||||
IncluirIVA: true,
|
||||
Observaciones: &obs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"razon_social": "URIEL JARETH ALVARADO ORTIZ",
|
||||
"rfc": "AAOU970201SU7",
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
b64 string
|
||||
mime string
|
||||
}{
|
||||
{"no_logo", "", ""},
|
||||
{"png_logo", makePNGLogoB64(t), "image/png"},
|
||||
{"jpeg_logo", makeJPEGLogoB64(t), "image/jpeg"},
|
||||
{"webp_logo", makeWebPLogoB64(t), "image/webp"},
|
||||
{"data_uri_png", "data:image/png;base64," + makePNGLogoB64(t), ""},
|
||||
{"corrupt_logo_fallback", "not-valid-base64!!!", "image/png"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := baseData
|
||||
d.LogoBase64 = tc.b64
|
||||
d.LogoMime = tc.mime
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF(%s) error: %v", tc.name, err)
|
||||
}
|
||||
// Cover + Resumen + T&C = at least 3 pages
|
||||
assertValidPDF(t, out, 3)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateCotizacionPDFDoblePropuesta(t *testing.T) {
|
||||
fecha := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
|
||||
d := CotizacionPDFData{
|
||||
Numero: "UJ2606UR002",
|
||||
ClienteNombre: "Carlos Núñez",
|
||||
ClienteEmpresa: "Núñez Logistics",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Fecha: fecha,
|
||||
Vigencia: domain.CalcularVigencia(fecha),
|
||||
Moneda: "MXN",
|
||||
Proyecto: "Transformación Digital",
|
||||
EsquemaPago: "Mensual",
|
||||
EsDoble: true,
|
||||
IncluirIVA: true,
|
||||
IncluirBonos: true, // exercises fallback bonos
|
||||
OpcionesMetadata: map[string]domain.MetaOpcion{
|
||||
"1": {Titulo: "Esencial", Descripcion: "Arranque rápido con foco en captación.", NoIncluye: "Producción de video"},
|
||||
"2": {Titulo: "Crecimiento", Descripcion: "Estrategia integral con automatización.", NoIncluye: "Pauta publicitaria"},
|
||||
},
|
||||
Servicios: []ServicioPDF{
|
||||
{Nombre: "Auditoría inicial", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(6)},
|
||||
{Nombre: "Landing Page", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "15 días", Opcion: str("1"), Horas: f64(15)},
|
||||
{Nombre: "Sitio Web Completo", Fase: 1, TipoPago: "unico", Precio: 28000, TiempoEntrega: "30 días", Opcion: str("2"), Horas: f64(35)},
|
||||
{Nombre: "Gestión Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")},
|
||||
},
|
||||
ColorPrimario: "not-a-hex",
|
||||
ColorSecundario: "",
|
||||
}
|
||||
|
||||
out, err := GenerateCotizacionPDF(d)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCotizacionPDF doble error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, out, 3)
|
||||
}
|
||||
|
||||
func TestGenerateNotaHorasPDFAllModes(t *testing.T) {
|
||||
base := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
|
||||
var regs []RegistroHoraPDF
|
||||
for i := 0; i < 35; i++ {
|
||||
estado := "por_pagar"
|
||||
if i%3 == 0 {
|
||||
estado = "pagada"
|
||||
}
|
||||
regs = append(regs, RegistroHoraPDF{
|
||||
Fecha: base.AddDate(0, 0, i*2),
|
||||
HoraInicio: "09:00",
|
||||
HoraFin: "11:30",
|
||||
Horas: 2.5,
|
||||
TarifaHora: 700,
|
||||
Descripcion: "Optimización de campaña y diseño de pruebas A/B con revisión de métricas",
|
||||
EstadoPago: estado,
|
||||
})
|
||||
}
|
||||
|
||||
for _, modo := range []string{"detalle", "dia", "semana", "mes"} {
|
||||
t.Run(modo, func(t *testing.T) {
|
||||
out, err := GenerateNotaHorasPDF(NotaHorasPDFData{
|
||||
Titulo: "Nota de horas por pagar",
|
||||
Numero: "UJ2605UR001",
|
||||
ClienteNombre: "Ana Gómez",
|
||||
ClienteEmpresa: "Gómez Tech",
|
||||
Proyecto: "Soporte Continuo",
|
||||
AsesorNombre: "Uriel Jareth",
|
||||
Moneda: "MXN",
|
||||
IncluirIVA: true,
|
||||
Modo: modo,
|
||||
MostrarEstado: modo == "detalle",
|
||||
MostrarBancarios: true,
|
||||
Registros: regs,
|
||||
ConfigBancaria: map[string]string{
|
||||
"cuenta_nacional": "0123456789",
|
||||
"clabe_interbancaria": "012180001234567890",
|
||||
"cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM",
|
||||
},
|
||||
LogoBase64: makeWebPLogoB64(t),
|
||||
LogoMime: "image/webp",
|
||||
FechaEmision: time.Date(2026, 7, 15, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateNotaHorasPDF(%s) error: %v", modo, err)
|
||||
}
|
||||
minPages := 1
|
||||
if modo == "detalle" {
|
||||
minPages = 2
|
||||
}
|
||||
assertValidPDF(t, out, minPages)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerarPropuestaYAnexoInternoPDF(t *testing.T) {
|
||||
contenido := map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []map[string]any{
|
||||
{"id": "C01", "textoLiteral": "Perdemos cotizaciones porque tardamos días en responder por WhatsApp.", "quienLoDijo": "el director comercial"},
|
||||
},
|
||||
"materialesPendientes": []map[string]any{
|
||||
{"texto": "Accesos a Google Ads y Meta Business", "bloqueaEntrega": true},
|
||||
},
|
||||
"decisionesPendientes": []map[string]any{
|
||||
{"texto": "Definir presupuesto mensual de pauta", "quienDecide": "Dirección General"},
|
||||
},
|
||||
"mencionesFueraDeAlcance": []string{"Producción de video corporativo"},
|
||||
"redFlags": []map[string]any{
|
||||
{"senal": "El cliente espera resultados en 48 horas", "severidad": "alta"},
|
||||
},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []map[string]any{
|
||||
{"id": "D01", "urgencia": "rojo", "titulo": "Fuga de leads", "descripcion": "No hay seguimiento estructurado en CRM.", "confianza": "confirmado"},
|
||||
{"id": "D02", "urgencia": "ambar", "titulo": "Sitio lento", "descripcion": "Tiempo de carga superior a 6 segundos.", "confianza": "estimado"},
|
||||
{"id": "D03", "urgencia": "verde", "titulo": "Buena reputación", "descripcion": "Reseñas de 4.9 estrellas en Google.", "confianza": "confirmado"},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []map[string]any{
|
||||
{
|
||||
"tipo": "dinero",
|
||||
"descripcion": "Leads perdidos por falta de seguimiento oportuno",
|
||||
"montoAnualMXN": 480000.0,
|
||||
"confianza": "estimado",
|
||||
"factores": []map[string]any{
|
||||
{"nombre": "leads_perdidos_mes", "valor": 8.0, "confianza": "estimado"},
|
||||
{"nombre": "ticket_promedio", "valor": 5000.0, "confianza": "estimado"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Cálculo conservador basado en promedio de los últimos 6 meses.",
|
||||
},
|
||||
"resultados": []map[string]any{
|
||||
{"enunciado": "Responder a cada prospecto en menos de 5 minutos", "metrica": "Tiempo de primera respuesta", "periodoMedicion": "60 días"},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Sistema de Captación y Seguimiento Comercial",
|
||||
"subtitulo": "Propuesta diseñada para eliminar fugas de prospectos y multiplicar conversiones.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []map[string]any{
|
||||
{"refPartida": "P01", "descripcionResultado": "Diagnóstico completo para detectar cuellos de botella en captación."},
|
||||
},
|
||||
"beneficios": []map[string]any{
|
||||
{"etiqueta": "Cero leads perdidos", "texto": "Cada consulta entra automáticamente al embudo con recordatorios.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []map[string]any{
|
||||
{"texto": "No incluye inversión en pauta publicitaria de Meta o Google.", "razon": "El cliente paga directo a la plataforma"},
|
||||
},
|
||||
"backlogEvolucion": []map[string]any{
|
||||
{"problema": "Integración con ERP contable", "momentoSugerido": "Trimestre 2"},
|
||||
},
|
||||
"notasInternas": []string{"NO_ENVIAR_SECRETO_ASESOR: negociar alcance antes de dar descuento"},
|
||||
},
|
||||
}
|
||||
|
||||
economia := map[string]any{
|
||||
"partidas": []map[string]any{
|
||||
{"refPartida": "P01", "nombre": "Auditoría Comercial", "fase": 0, "tipoPago": "unico", "precio": 8000.0, "tiempoEntrega": "7 días", "entregables": []string{"Mapa de embudo"}},
|
||||
{"refPartida": "P02", "nombre": "Implementación CRM", "fase": 1, "tipoPago": "unico", "precio": 22000.0, "tiempoEntrega": "15 días", "entregables": []string{"Flujos", "Capacitación"}},
|
||||
},
|
||||
"planBucefalo": map[string]any{"nivel": "estandar", "precio": 3500.0},
|
||||
"totales": map[string]any{
|
||||
"subtotalUnico": 30000.0,
|
||||
"subtotalMensual": 3500.0,
|
||||
"ivaUnico": 4800.0,
|
||||
"ivaMensual": 560.0,
|
||||
"totalUnico": 34800.0,
|
||||
"totalMensual": 4060.0,
|
||||
"totalPrimerAnio": 83520.0,
|
||||
"incluyeIva": true,
|
||||
},
|
||||
"moneda": "MXN",
|
||||
"asesor": "Uriel Jareth",
|
||||
}
|
||||
|
||||
in := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR010",
|
||||
ClienteNombre: "Roberto Peña",
|
||||
ClienteEmpresa: "Peña Industrial",
|
||||
Proyecto: "CRM y Captación",
|
||||
Moneda: "MXN",
|
||||
Fecha: time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC),
|
||||
Contenido: contenido,
|
||||
Economia: economia,
|
||||
ColorPrimario: "#0400C4",
|
||||
ColorSecundario: "#0F172A",
|
||||
LogoBase64: makePNGLogoB64(t),
|
||||
LogoMime: "image/png",
|
||||
}
|
||||
|
||||
propPDF, err := GenerarPropuestaPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarPropuestaPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, propPDF, 1)
|
||||
|
||||
anexoPDF, err := GenerarAnexoInternoPDF(in)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerarAnexoInternoPDF error: %v", err)
|
||||
}
|
||||
assertValidPDF(t, anexoPDF, 1)
|
||||
|
||||
// Empty maps should also succeed safely.
|
||||
emptyIn := PropuestaPDFInput{
|
||||
CotizacionNumero: "UJ2606UR011",
|
||||
ClienteNombre: "Cliente Vacío",
|
||||
Proyecto: "Proyecto Mínimo",
|
||||
}
|
||||
if out, err := GenerarPropuestaPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarPropuestaPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
if out, err := GenerarAnexoInternoPDF(emptyIn); err != nil {
|
||||
t.Fatalf("empty GenerarAnexoInternoPDF error: %v", err)
|
||||
} else {
|
||||
assertValidPDF(t, out, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalcularRatioPropuesta(t *testing.T) {
|
||||
if r := calcularRatioPropuesta(10000, nil); r != nil {
|
||||
t.Fatalf("expected nil for nil valorAnual")
|
||||
}
|
||||
if r := calcularRatioPropuesta(10000, f64(0)); r != nil {
|
||||
t.Fatalf("expected nil for zero valorAnual")
|
||||
}
|
||||
cases := []struct {
|
||||
total, valor float64
|
||||
want string
|
||||
}{
|
||||
{5000, 100000, "subcotizado"},
|
||||
{20000, 100000, "en_rango"},
|
||||
{35000, 100000, "alto"},
|
||||
{50000, 100000, "objecion_probable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
r := calcularRatioPropuesta(tc.total, f64(tc.valor))
|
||||
if r == nil || r.Lectura != tc.want {
|
||||
t.Fatalf("calcularRatioPropuesta(%v,%v) = %+v, want %q", tc.total, tc.valor, r, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
type PropuestaPDFInput struct {
|
||||
CotizacionNumero string
|
||||
ClienteNombre string
|
||||
ClienteEmpresa string
|
||||
Proyecto string
|
||||
Moneda string
|
||||
Fecha time.Time
|
||||
Contenido map[string]any
|
||||
Economia map[string]any
|
||||
ColorPrimario string
|
||||
ColorSecundario string
|
||||
LogoBase64 string
|
||||
LogoMime string
|
||||
}
|
||||
|
||||
// Internal typed shapes mirroring src/lib/propuesta/schemas.ts and economia.ts.
|
||||
type propuestaContenido struct {
|
||||
Hechos struct {
|
||||
Citas []struct {
|
||||
ID string `json:"id"`
|
||||
TextoLiteral string `json:"textoLiteral"`
|
||||
QuienLoDijo string `json:"quienLoDijo"`
|
||||
} `json:"citas"`
|
||||
MaterialesPendientes []struct {
|
||||
Texto string `json:"texto"`
|
||||
BloqueaEntrega bool `json:"bloqueaEntrega"`
|
||||
} `json:"materialesPendientes"`
|
||||
DecisionesPendientes []struct {
|
||||
Texto string `json:"texto"`
|
||||
QuienDecide string `json:"quienDecide"`
|
||||
} `json:"decisionesPendientes"`
|
||||
MencionesFueraDeAlcance []string `json:"mencionesFueraDeAlcance"`
|
||||
RedFlags []struct {
|
||||
Senal string `json:"senal"`
|
||||
Severidad string `json:"severidad"`
|
||||
} `json:"redFlags"`
|
||||
} `json:"hechos"`
|
||||
Diagnostico struct {
|
||||
Hallazgos []struct {
|
||||
ID string `json:"id"`
|
||||
Urgencia string `json:"urgencia"`
|
||||
Titulo string `json:"titulo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"hallazgos"`
|
||||
ValorProblema struct {
|
||||
Dimensiones []struct {
|
||||
Tipo string `json:"tipo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Factores []struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Valor float64 `json:"valor"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"factores"`
|
||||
MontoAnualMXN *float64 `json:"montoAnualMXN"`
|
||||
Confianza string `json:"confianza"`
|
||||
} `json:"dimensiones"`
|
||||
NotaMetodologia string `json:"notaMetodologia"`
|
||||
} `json:"valorProblema"`
|
||||
Resultados []struct {
|
||||
Enunciado string `json:"enunciado"`
|
||||
Metrica string `json:"metrica"`
|
||||
LineaBase *string `json:"lineaBase"`
|
||||
PeriodoMedicion string `json:"periodoMedicion"`
|
||||
} `json:"resultados"`
|
||||
} `json:"diagnostico"`
|
||||
Redaccion struct {
|
||||
Hero struct {
|
||||
Titulo string `json:"titulo"`
|
||||
Subtitulo string `json:"subtitulo"`
|
||||
} `json:"hero"`
|
||||
CitaDestacadaID string `json:"citaDestacadaId"`
|
||||
Alcance []struct {
|
||||
RefPartida string `json:"refPartida"`
|
||||
DescripcionResultado string `json:"descripcionResultado"`
|
||||
} `json:"alcance"`
|
||||
Beneficios []struct {
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
Texto string `json:"texto"`
|
||||
HallazgoID string `json:"hallazgoId"`
|
||||
} `json:"beneficios"`
|
||||
Exclusiones []struct {
|
||||
Texto string `json:"texto"`
|
||||
Razon string `json:"razon"`
|
||||
} `json:"exclusiones"`
|
||||
BacklogEvolucion []struct {
|
||||
Problema string `json:"problema"`
|
||||
MomentoSugerido string `json:"momentoSugerido"`
|
||||
} `json:"backlogEvolucion"`
|
||||
NotasInternas []string `json:"notasInternas"`
|
||||
} `json:"redaccion"`
|
||||
}
|
||||
|
||||
type propuestaPartida struct {
|
||||
RefPartida string `json:"refPartida"`
|
||||
Nombre string `json:"nombre"`
|
||||
Fase int `json:"fase"`
|
||||
TipoPago string `json:"tipoPago"`
|
||||
Precio float64 `json:"precio"`
|
||||
TiempoEntrega string `json:"tiempoEntrega"`
|
||||
ModeloCobro string `json:"modeloCobro"`
|
||||
Entregables []string `json:"entregables"`
|
||||
}
|
||||
|
||||
type propuestaEconomia struct {
|
||||
Partidas []propuestaPartida `json:"partidas"`
|
||||
Totales struct {
|
||||
SubtotalUnico float64 `json:"subtotalUnico"`
|
||||
SubtotalMensual float64 `json:"subtotalMensual"`
|
||||
IVAUnico float64 `json:"ivaUnico"`
|
||||
IVAMensual float64 `json:"ivaMensual"`
|
||||
TotalUnico float64 `json:"totalUnico"`
|
||||
TotalMensual float64 `json:"totalMensual"`
|
||||
TotalPrimerAnio float64 `json:"totalPrimerAnio"`
|
||||
IncluyeIVA bool `json:"incluyeIva"`
|
||||
} `json:"totales"`
|
||||
Moneda string `json:"moneda"`
|
||||
Asesor string `json:"asesor"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
} `json:"planBucefalo"`
|
||||
}
|
||||
|
||||
func decodeMapInto[T any](src map[string]any) T {
|
||||
var out T
|
||||
if len(src) == 0 {
|
||||
return out
|
||||
}
|
||||
b, err := json.Marshal(src)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
_ = json.Unmarshal(b, &out)
|
||||
return out
|
||||
}
|
||||
|
||||
var (
|
||||
colorSemaforo = map[string]string{
|
||||
"rojo": "#dc2626",
|
||||
"ambar": "#d97706",
|
||||
"azul": "#0400C4",
|
||||
"verde": "#16a34a",
|
||||
}
|
||||
etiquetaSemaforo = map[string]string{
|
||||
"rojo": "Problema crítico",
|
||||
"ambar": "Área de mejora",
|
||||
"azul": "Oportunidad",
|
||||
"verde": "Ventaja existente",
|
||||
}
|
||||
etiquetaConfianza = map[string]string{
|
||||
"confirmado": "Confirmado",
|
||||
"estimado": "Estimado",
|
||||
"por_validar": "Por validar",
|
||||
}
|
||||
)
|
||||
|
||||
func detalleDePartida(p propuestaPartida) string {
|
||||
var trozos []string
|
||||
if len(p.Entregables) > 0 {
|
||||
limit := len(p.Entregables)
|
||||
if limit > 4 {
|
||||
limit = 4
|
||||
}
|
||||
trozos = append(trozos, strings.Join(p.Entregables[:limit], " · "))
|
||||
}
|
||||
if strings.TrimSpace(p.TiempoEntrega) != "" {
|
||||
trozos = append(trozos, "Entrega: "+p.TiempoEntrega)
|
||||
}
|
||||
if p.TipoPago == "mensual" {
|
||||
trozos = append(trozos, "Servicio mensual")
|
||||
}
|
||||
return strings.Join(trozos, " | ")
|
||||
}
|
||||
|
||||
type ratioResult struct {
|
||||
Ratio float64
|
||||
Lectura string
|
||||
}
|
||||
|
||||
func calcularRatioPropuesta(totalPrimerAnio float64, valorAnual *float64) *ratioResult {
|
||||
if valorAnual == nil || *valorAnual <= 0 {
|
||||
return nil
|
||||
}
|
||||
ratio := totalPrimerAnio / *valorAnual
|
||||
lectura := "objecion_probable"
|
||||
switch {
|
||||
case ratio < 0.1:
|
||||
lectura = "subcotizado"
|
||||
case ratio <= 0.25:
|
||||
lectura = "en_rango"
|
||||
case ratio <= 0.4:
|
||||
lectura = "alto"
|
||||
}
|
||||
return &ratioResult{
|
||||
Ratio: math.Round(ratio*1000) / 1000,
|
||||
Lectura: lectura,
|
||||
}
|
||||
}
|
||||
|
||||
func GenerarPropuestaPDF(in PropuestaPDFInput) ([]byte, error) {
|
||||
primary := safeHex(in.ColorPrimario, defaultPrimary)
|
||||
dark := safeHex(in.ColorSecundario, defaultDark)
|
||||
muted := colorMuted
|
||||
border := "#e2e8f0"
|
||||
|
||||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||||
|
||||
moneda := in.Moneda
|
||||
if moneda == "" {
|
||||
moneda = econ.Moneda
|
||||
}
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, moneda)
|
||||
}
|
||||
|
||||
fecha := in.Fecha
|
||||
if fecha.IsZero() {
|
||||
fecha = time.Now()
|
||||
}
|
||||
vigencia := domain.CalcularVigencia(fecha)
|
||||
clienteDisplay := in.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisplay) == "" {
|
||||
clienteDisplay = in.ClienteNombre
|
||||
}
|
||||
|
||||
c := newCanvas(50, 55, 50, 50)
|
||||
c.doc.AliasNbPages("{nb}")
|
||||
logo := registerLogo(c.doc, "prop_logo", in.LogoBase64, in.LogoMime)
|
||||
|
||||
c.doc.SetFooterFunc(func() {
|
||||
c.hLine(c.L, c.L+c.W, c.ph-42, border, 0.5)
|
||||
leftTxt := fmt.Sprintf("%s · Propuesta consultiva · %s", in.CotizacionNumero, clienteDisplay)
|
||||
c.drawSingleLine(leftTxt, c.L, c.ph-35, c.W-60, "", 7, muted, "L")
|
||||
rightTxt := fmt.Sprintf("%d / {nb}", c.doc.PageNo())
|
||||
c.drawSingleLine(rightTxt, c.L, c.ph-35, c.W, "", 7, muted, "R")
|
||||
})
|
||||
|
||||
c.doc.AddPage()
|
||||
y := c.mTop
|
||||
|
||||
titulo := func(t string) {
|
||||
y = c.need(26, y)
|
||||
c.rectFill(c.L, y+1, 3, 10, primary)
|
||||
c.drawSingleLine(strings.ToUpper(t), c.L+10, y, c.W-10, "B", 10, dark, "L")
|
||||
y += 20
|
||||
}
|
||||
parrafo := func(t string, size float64, color string) {
|
||||
raw := strings.ReplaceAll(t, "\r\n", "\n")
|
||||
for _, p := range strings.Split(raw, "\n") {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
h := c.textHeight(p, c.W, "", size)
|
||||
y = c.need(h+4, y)
|
||||
c.drawText(p, c.L, y, c.W, "", size, color, "L")
|
||||
y += h + 4
|
||||
}
|
||||
}
|
||||
|
||||
// ── HERO ──
|
||||
if logo.ok {
|
||||
logo.drawByHeight(c.doc, c.L, y, 26)
|
||||
y += 34
|
||||
}
|
||||
c.drawSingleLine("PROPUESTA CONSULTIVA", c.L, y, c.W, "B", 8.5, primary, "L")
|
||||
y += 16
|
||||
|
||||
heroTit := strings.TrimSpace(prop.Redaccion.Hero.Titulo)
|
||||
if heroTit == "" {
|
||||
heroTit = in.Proyecto
|
||||
}
|
||||
if heroTit != "" {
|
||||
hTit := c.drawText(heroTit, c.L, y, c.W, "B", 20, dark, "L")
|
||||
y += hTit + 8
|
||||
}
|
||||
if strings.TrimSpace(prop.Redaccion.Hero.Subtitulo) != "" {
|
||||
parrafo(prop.Redaccion.Hero.Subtitulo, 10, muted)
|
||||
y += 8
|
||||
}
|
||||
|
||||
metaParts := []string{
|
||||
clienteDisplay,
|
||||
in.CotizacionNumero,
|
||||
domain.FormatDateShort(fecha),
|
||||
"Vigencia " + domain.FormatDateShort(vigencia),
|
||||
}
|
||||
if strings.TrimSpace(econ.Asesor) != "" {
|
||||
metaParts = append(metaParts, econ.Asesor)
|
||||
}
|
||||
meta := strings.Join(metaParts, " · ")
|
||||
hMeta := c.drawText(meta, c.L, y, c.W, "", 8, muted, "L")
|
||||
y += hMeta + 12
|
||||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||||
y += 18
|
||||
|
||||
// ── DIAGNÓSTICO ──
|
||||
if len(prop.Diagnostico.Hallazgos) > 0 || prop.Redaccion.CitaDestacadaID != "" {
|
||||
titulo("Diagnóstico")
|
||||
for _, cita := range prop.Hechos.Citas {
|
||||
if cita.ID != "" && cita.ID == prop.Redaccion.CitaDestacadaID {
|
||||
texto := fmt.Sprintf("\"%s\"", cita.TextoLiteral)
|
||||
h := c.textHeight(texto, c.W-22, "I", 11)
|
||||
y = c.need(h+22, y)
|
||||
c.rectFill(c.L, y-3, 2.5, h+10, primary)
|
||||
c.drawText(texto, c.L+12, y, c.W-22, "I", 11, dark, "L")
|
||||
y += h + 4
|
||||
c.drawSingleLine("— "+cita.QuienLoDijo, c.L+12, y, c.W-22, "", 7.5, muted, "L")
|
||||
y += 18
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, hal := range prop.Diagnostico.Hallazgos {
|
||||
cuerpo := fmt.Sprintf("%s — %s", hal.Titulo, hal.Descripcion)
|
||||
h := c.textHeight(cuerpo, c.W-24, "", 9)
|
||||
y = c.need(h+16, y)
|
||||
dotColor := colorSemaforo[hal.Urgencia]
|
||||
if dotColor == "" {
|
||||
dotColor = muted
|
||||
}
|
||||
c.circleFill(c.L+4.5, y+5, 3.2, dotColor)
|
||||
c.drawText(cuerpo, c.L+16, y, c.W-24, "", 9, dark, "L")
|
||||
y += h + 1
|
||||
subLbl := fmt.Sprintf("%s · %s", etiquetaSemaforo[hal.Urgencia], etiquetaConfianza[hal.Confianza])
|
||||
c.drawSingleLine(subLbl, c.L+16, y, c.W-24, "", 7, muted, "L")
|
||||
y += 13
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── VALOR DEL PROBLEMA ──
|
||||
dims := prop.Diagnostico.ValorProblema.Dimensiones
|
||||
if len(dims) > 0 {
|
||||
titulo("Lo que cuesta no resolverlo")
|
||||
for _, dim := range dims {
|
||||
montoTxt := "sin cuantificar"
|
||||
if dim.MontoAnualMXN != nil {
|
||||
montoTxt = fmt.Sprintf("%s al año", fmtMoney(*dim.MontoAnualMXN))
|
||||
}
|
||||
linea := fmt.Sprintf("%s — %s", dim.Descripcion, montoTxt)
|
||||
h := c.textHeight(linea, c.W-14, "", 9)
|
||||
y = c.need(h+14, y)
|
||||
c.drawText(linea, c.L+6, y, c.W-14, "", 9, dark, "L")
|
||||
y += h + 1
|
||||
c.drawSingleLine(etiquetaConfianza[dim.Confianza], c.L+6, y, c.W-14, "", 7, muted, "L")
|
||||
y += 13
|
||||
}
|
||||
if strings.TrimSpace(prop.Diagnostico.ValorProblema.NotaMetodologia) != "" {
|
||||
y += 2
|
||||
parrafo(prop.Diagnostico.ValorProblema.NotaMetodologia, 8, muted)
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── RESULTADOS ──
|
||||
if len(prop.Diagnostico.Resultados) > 0 {
|
||||
titulo("Resultados a lograr")
|
||||
for _, r := range prop.Diagnostico.Resultados {
|
||||
t := fmt.Sprintf("• %s (%s, %s)", r.Enunciado, r.Metrica, r.PeriodoMedicion)
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── ALCANCE ──
|
||||
titulo("Alcance de la inversión")
|
||||
descPorRef := make(map[string]string, len(prop.Redaccion.Alcance))
|
||||
for _, a := range prop.Redaccion.Alcance {
|
||||
descPorRef[a.RefPartida] = a.DescripcionResultado
|
||||
}
|
||||
for _, p := range econ.Partidas {
|
||||
descripcion := descPorRef[p.RefPartida]
|
||||
respaldo := ""
|
||||
if descripcion == "" {
|
||||
respaldo = detalleDePartida(p)
|
||||
}
|
||||
hNombre := c.textHeight(p.Nombre, c.W*0.68, "B", 9.5)
|
||||
subTxt := descripcion
|
||||
if subTxt == "" {
|
||||
subTxt = respaldo
|
||||
}
|
||||
hDesc := 0.0
|
||||
if subTxt != "" {
|
||||
hDesc = c.textHeight(subTxt, c.W*0.68, "", 8)
|
||||
}
|
||||
y = c.need(hNombre+hDesc+14, y)
|
||||
c.drawText(p.Nombre, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(p.Precio), c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||||
y += hNombre + 2
|
||||
if subTxt != "" {
|
||||
c.drawText(subTxt, c.L, y, c.W*0.68, "", 8, muted, "L")
|
||||
y += hDesc + 10
|
||||
} else {
|
||||
y += 8
|
||||
}
|
||||
}
|
||||
|
||||
if econ.PlanBucefalo != nil && strings.TrimSpace(econ.PlanBucefalo.Nivel) != "" {
|
||||
etiqueta := "CRM Bucéfalo — plan " + capitalize(econ.PlanBucefalo.Nivel)
|
||||
hE := c.textHeight(etiqueta, c.W*0.68, "B", 9.5)
|
||||
y = c.need(hE+22, y)
|
||||
c.drawText(etiqueta, c.L, y, c.W*0.68, "B", 9.5, dark, "L")
|
||||
c.drawSingleLine(fmtMoney(econ.PlanBucefalo.Precio)+" / mes", c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R")
|
||||
y += hE + 2
|
||||
c.drawSingleLine("Servicio mensual", c.L, y, c.W*0.68, "", 8, muted, "L")
|
||||
y += 20
|
||||
}
|
||||
|
||||
y = c.need(58, y)
|
||||
c.hLine(c.L, c.L+c.W, y, border, 0.5)
|
||||
y += 10
|
||||
|
||||
// ── CAJA DE TOTALES ──
|
||||
tot := econ.Totales
|
||||
fila := func(etiqueta, valor string, fuerte bool) {
|
||||
step := 15.0
|
||||
size := 9.0
|
||||
lblStyle := ""
|
||||
lblColor := muted
|
||||
valColor := dark
|
||||
if fuerte {
|
||||
step = 18.0
|
||||
size = 10.5
|
||||
lblStyle = "B"
|
||||
lblColor = dark
|
||||
valColor = primary
|
||||
}
|
||||
y = c.need(step, y)
|
||||
c.drawSingleLine(etiqueta, c.L, y, c.W*0.6, lblStyle, size, lblColor, "L")
|
||||
c.drawSingleLine(valor, c.L+c.W*0.6, y, c.W*0.4, "B", size, valColor, "R")
|
||||
y += step
|
||||
}
|
||||
|
||||
if tot.SubtotalUnico > 0 {
|
||||
fila("Subtotal pago único", fmtMoney(tot.SubtotalUnico), false)
|
||||
if tot.IncluyeIVA {
|
||||
fila("IVA 16%", fmtMoney(tot.IVAUnico), false)
|
||||
fila("Total pago único", fmtMoney(tot.TotalUnico), true)
|
||||
} else {
|
||||
fila("Total pago único (sin IVA)", fmtMoney(tot.TotalUnico), true)
|
||||
}
|
||||
}
|
||||
if tot.SubtotalMensual > 0 {
|
||||
if tot.SubtotalUnico > 0 {
|
||||
y += 4
|
||||
}
|
||||
fila("Subtotal mensual", fmtMoney(tot.SubtotalMensual), false)
|
||||
if tot.IncluyeIVA {
|
||||
fila("IVA 16%", fmtMoney(tot.IVAMensual), false)
|
||||
fila("Total mensual", fmtMoney(tot.TotalMensual), true)
|
||||
} else {
|
||||
fila("Total mensual (sin IVA)", fmtMoney(tot.TotalMensual), true)
|
||||
}
|
||||
}
|
||||
|
||||
y = c.need(20, y)
|
||||
notaIVA := "Los precios son en Moneda Nacional (MXN) y no incluyen IVA. Facturación CFDI."
|
||||
if tot.IncluyeIVA {
|
||||
notaIVA = "Los precios por partida son en Moneda Nacional (MXN) y no incluyen IVA; el IVA se desglosa arriba. Facturación CFDI."
|
||||
}
|
||||
hNota := c.drawText(notaIVA, c.L, y, c.W, "", 7.5, muted, "L")
|
||||
y += hNota + 16
|
||||
|
||||
// ── BENEFICIOS ──
|
||||
if len(prop.Redaccion.Beneficios) > 0 {
|
||||
titulo("Por qué tiene sentido")
|
||||
for _, b := range prop.Redaccion.Beneficios {
|
||||
hEt := c.textHeight(b.Etiqueta, c.W*0.24, "B", 9)
|
||||
hTx := c.textHeight(b.Texto, c.W*0.72, "", 8.5)
|
||||
h := hEt
|
||||
if hTx > h {
|
||||
h = hTx
|
||||
}
|
||||
y = c.need(h+9, y)
|
||||
c.drawText(b.Etiqueta, c.L, y, c.W*0.24, "B", 9, dark, "L")
|
||||
c.drawText(b.Texto, c.L+c.W*0.27, y, c.W*0.72, "", 8.5, muted, "L")
|
||||
y += h + 9
|
||||
}
|
||||
y += 8
|
||||
}
|
||||
|
||||
// ── EXCLUSIONES ──
|
||||
if len(prop.Redaccion.Exclusiones) > 0 {
|
||||
titulo("Qué no incluye esta propuesta")
|
||||
for _, e := range prop.Redaccion.Exclusiones {
|
||||
t2 := "× " + e.Texto
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
// ── PENDIENTES ──
|
||||
mats := prop.Hechos.MaterialesPendientes
|
||||
decs := prop.Hechos.DecisionesPendientes
|
||||
if len(mats) > 0 || len(decs) > 0 {
|
||||
titulo("Qué necesitamos de ustedes")
|
||||
for _, mm := range mats {
|
||||
suffix := ""
|
||||
if mm.BloqueaEntrega {
|
||||
suffix = " (el avance queda condicionado a esto)"
|
||||
}
|
||||
t2 := "○ " + mm.Texto + suffix
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
for _, dd := range decs {
|
||||
t2 := fmt.Sprintf("· %s (decide: %s)", dd.Texto, dd.QuienDecide)
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, muted, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
// ── BACKLOG ──
|
||||
if len(prop.Redaccion.BacklogEvolucion) > 0 {
|
||||
titulo("Registrado para más adelante")
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine("No comprometido en esta propuesta.", c.L, y, c.W, "I", 7.5, muted, "L")
|
||||
y += 14
|
||||
for _, b := range prop.Redaccion.BacklogEvolucion {
|
||||
t2 := fmt.Sprintf("· %s (%s)", b.Problema, b.MomentoSugerido)
|
||||
h := c.textHeight(t2, c.W-8, "", 8.5)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
|
||||
// GenerarAnexoInternoPDF renders the internal-only advisor annex as a separate document
|
||||
// with an unmistakable red banner so it can never be confused with the client proposal.
|
||||
func GenerarAnexoInternoPDF(in PropuestaPDFInput) ([]byte, error) {
|
||||
prop := decodeMapInto[propuestaContenido](in.Contenido)
|
||||
econ := decodeMapInto[propuestaEconomia](in.Economia)
|
||||
|
||||
moneda := in.Moneda
|
||||
if moneda == "" {
|
||||
moneda = econ.Moneda
|
||||
}
|
||||
fmtMoney := func(n float64) string {
|
||||
return formatMoney(n, moneda)
|
||||
}
|
||||
|
||||
dark := defaultDark
|
||||
muted := colorMuted
|
||||
redBanner := "#b91c1c"
|
||||
|
||||
c := newCanvas(50, 55, 50, 50)
|
||||
c.doc.AddPage()
|
||||
|
||||
c.rectFill(0, 0, c.pw, 36, redBanner)
|
||||
c.drawSingleLine("USO INTERNO — NO ENVIAR AL CLIENTE", c.L, 11, c.W, "B", 13, colorWhite, "L")
|
||||
y := 56.0
|
||||
|
||||
clienteDisplay := in.ClienteEmpresa
|
||||
if strings.TrimSpace(clienteDisplay) == "" {
|
||||
clienteDisplay = in.ClienteNombre
|
||||
}
|
||||
metaParts := []string{in.CotizacionNumero, clienteDisplay}
|
||||
if strings.TrimSpace(econ.Asesor) != "" {
|
||||
metaParts = append(metaParts, econ.Asesor)
|
||||
}
|
||||
c.drawSingleLine(strings.Join(metaParts, " · "), c.L, y, c.W, "", 9, muted, "L")
|
||||
y += 24
|
||||
|
||||
var valorAnualSum float64
|
||||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||||
if dim.MontoAnualMXN != nil {
|
||||
valorAnualSum += *dim.MontoAnualMXN
|
||||
}
|
||||
}
|
||||
var valorAnual *float64
|
||||
if valorAnualSum > 0 {
|
||||
v := valorAnualSum
|
||||
valorAnual = &v
|
||||
}
|
||||
r := calcularRatioPropuesta(econ.Totales.TotalPrimerAnio, valorAnual)
|
||||
|
||||
seccion := func(t string) {
|
||||
y = c.need(24, y)
|
||||
c.drawSingleLine(t, c.L, y, c.W, "B", 11, dark, "L")
|
||||
y += 18
|
||||
}
|
||||
linea := func(k, v string) {
|
||||
y = c.need(15, y)
|
||||
c.drawSingleLine(k, c.L, y, c.W*0.5, "", 9, muted, "L")
|
||||
c.drawSingleLine(v, c.L+c.W*0.5, y, c.W*0.5, "B", 9, dark, "R")
|
||||
y += 15
|
||||
}
|
||||
|
||||
confirmados := 0
|
||||
for _, h := range prop.Diagnostico.Hallazgos {
|
||||
if h.Confianza == "confirmado" {
|
||||
confirmados++
|
||||
}
|
||||
}
|
||||
|
||||
valorAnualTxt := "sin cuantificar"
|
||||
if valorAnual != nil {
|
||||
valorAnualTxt = fmtMoney(*valorAnual)
|
||||
}
|
||||
ratioTxt := "no calculable"
|
||||
if r != nil {
|
||||
ratioTxt = fmt.Sprintf("%.1f%% — %s", r.Ratio*100, strings.ReplaceAll(r.Lectura, "_", " "))
|
||||
}
|
||||
|
||||
seccion("Ponderación de la cotización")
|
||||
linea("Inversión del primer año", fmtMoney(econ.Totales.TotalPrimerAnio))
|
||||
linea("Valor anual del problema", valorAnualTxt)
|
||||
linea("Ratio precio / valor", ratioTxt)
|
||||
linea("Hallazgos en el diagnóstico", fmt.Sprintf("%d", len(prop.Diagnostico.Hallazgos)))
|
||||
linea("Cifras confirmadas", fmt.Sprintf("%d", confirmados))
|
||||
linea("Exclusiones definidas", fmt.Sprintf("%d", len(prop.Redaccion.Exclusiones)))
|
||||
linea("Materiales pendientes", fmt.Sprintf("%d", len(prop.Hechos.MaterialesPendientes)))
|
||||
linea("Decisiones pendientes", fmt.Sprintf("%d", len(prop.Hechos.DecisionesPendientes)))
|
||||
linea("Red flags detectadas", fmt.Sprintf("%d", len(prop.Hechos.RedFlags)))
|
||||
y += 6
|
||||
|
||||
if len(prop.Diagnostico.ValorProblema.Dimensiones) > 0 {
|
||||
seccion("De dónde sale el valor anual")
|
||||
sinConfirmar := false
|
||||
for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones {
|
||||
montoTxt := "sin cifra"
|
||||
if dim.MontoAnualMXN != nil {
|
||||
montoTxt = fmtMoney(*dim.MontoAnualMXN)
|
||||
}
|
||||
y = c.need(14, y)
|
||||
c.drawSingleLine(fmt.Sprintf("%s: %s", dim.Tipo, montoTxt), c.L, y, c.W, "B", 9, dark, "L")
|
||||
y += 13
|
||||
hasConfirmed := false
|
||||
if len(dim.Factores) > 0 {
|
||||
partes := make([]string, 0, len(dim.Factores))
|
||||
for _, f := range dim.Factores {
|
||||
if f.Confianza == "confirmado" {
|
||||
hasConfirmed = true
|
||||
}
|
||||
partes = append(partes, fmt.Sprintf("%s = %g (%s)", f.Nombre, f.Valor, f.Confianza))
|
||||
}
|
||||
desglose := strings.Join(partes, " x ")
|
||||
h := c.textHeight(desglose, c.W-10, "", 8)
|
||||
y = c.need(h+8, y)
|
||||
c.drawText(desglose, c.L+6, y, c.W-10, "", 8, muted, "L")
|
||||
y += h + 8
|
||||
}
|
||||
if dim.MontoAnualMXN != nil && !hasConfirmed {
|
||||
sinConfirmar = true
|
||||
}
|
||||
}
|
||||
if sinConfirmar {
|
||||
alerta := "Ojo: hay una cifra que descansa entera en factores estimados. Antes de fiarte del ratio, revisa que no falte un factor — la aritmética puede cuadrar y aun así estar inflada."
|
||||
h := c.textHeight(alerta, c.W, "B", 8.5)
|
||||
y = c.need(h+12, y)
|
||||
c.drawText(alerta, c.L, y, c.W, "B", 8.5, redBanner, "L")
|
||||
y += h + 14
|
||||
}
|
||||
y += 4
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
var nota string
|
||||
switch r.Lectura {
|
||||
case "subcotizado":
|
||||
nota = "La inversión es menos del 10% de lo que el problema le cuesta al cliente cada año. Probablemente subcotizaste."
|
||||
case "objecion_probable":
|
||||
nota = "La inversión supera el 40% del valor anual del problema. Prepara la conversación de precio: se responde con alcance, no con descuento."
|
||||
case "alto":
|
||||
nota = "La inversión está en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el número."
|
||||
default:
|
||||
nota = "La inversión cae en el rango de referencia (15-25% del valor anual)."
|
||||
}
|
||||
h := c.textHeight(nota, c.W, "I", 8.5)
|
||||
y = c.need(h+12, y)
|
||||
c.drawText(nota, c.L, y, c.W, "I", 8.5, muted, "L")
|
||||
y += h + 16
|
||||
}
|
||||
|
||||
if len(prop.Hechos.RedFlags) > 0 {
|
||||
seccion("Red flags")
|
||||
for _, rf := range prop.Hechos.RedFlags {
|
||||
t := fmt.Sprintf("· [%s] %s", rf.Severidad, rf.Senal)
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
if len(prop.Redaccion.NotasInternas) > 0 {
|
||||
seccion("Notas para el asesor")
|
||||
for _, n := range prop.Redaccion.NotasInternas {
|
||||
t := "· " + n
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
y += 10
|
||||
}
|
||||
|
||||
if len(prop.Hechos.MencionesFueraDeAlcance) > 0 {
|
||||
seccion("Se mencionó y quedó fuera")
|
||||
for _, m := range prop.Hechos.MencionesFueraDeAlcance {
|
||||
t := "· " + m
|
||||
h := c.textHeight(t, c.W-8, "", 9)
|
||||
y = c.need(h+6, y)
|
||||
c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L")
|
||||
y += h + 6
|
||||
}
|
||||
}
|
||||
|
||||
return c.bytes()
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultMinimaxBaseURL = "https://api.minimax.io/anthropic"
|
||||
DefaultMinimaxModel = "MiniMax-M3"
|
||||
anthropicVersion = "2023-06-01"
|
||||
maxTransitoriosDef = 3
|
||||
)
|
||||
|
||||
// UsoTokens acumula el consumo de tokens reportado por el endpoint de mensajes.
|
||||
type UsoTokens struct {
|
||||
Entrada int `json:"entrada"`
|
||||
Salida int `json:"salida"`
|
||||
CacheLectura int `json:"cacheLectura"`
|
||||
CacheEscritura int `json:"cacheEscritura"`
|
||||
}
|
||||
|
||||
// BloqueSystem representa un bloque del prompt de sistema con cache opcional.
|
||||
type BloqueSystem struct {
|
||||
Texto string
|
||||
Cachear bool
|
||||
}
|
||||
|
||||
// Herramienta define la herramienta de salida estructurada para tool-calling.
|
||||
type Herramienta struct {
|
||||
Nombre string
|
||||
Descripcion string
|
||||
InputSchema map[string]any
|
||||
Validar func(datos map[string]any) []string
|
||||
}
|
||||
|
||||
// OpcionesLlamada configura una invocacion con tool-calling y bucle de validacion.
|
||||
type OpcionesLlamada struct {
|
||||
System []BloqueSystem
|
||||
MensajeUsuario string
|
||||
Herramienta Herramienta
|
||||
MaxIntentos int
|
||||
MaxTokens int
|
||||
}
|
||||
|
||||
// ResultadoLlamada contiene la salida validada, el uso acumulado y los intentos.
|
||||
type ResultadoLlamada struct {
|
||||
Datos map[string]any
|
||||
Uso UsoTokens
|
||||
Intentos int
|
||||
}
|
||||
|
||||
// ClienteIA habla con el endpoint compatible con Anthropic Messages de MiniMax
|
||||
// usando net/http puro (sin SDK externo).
|
||||
type ClienteIA struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Model string
|
||||
HTTPClient *http.Client
|
||||
Sleep func(ctx context.Context, d time.Duration) error
|
||||
}
|
||||
|
||||
// NuevoClienteIA construye el cliente de MiniMax leyendo MINIMAX_API_KEY,
|
||||
// MINIMAX_BASE_URL y MINIMAX_MODEL (desde cfg si se pasa, o desde el entorno).
|
||||
// Rechaza explicitamente una clave vacia y advierte cuando solo ANTHROPIC_API_KEY
|
||||
// esta presente para evitar enviar credenciales al proveedor equivocado.
|
||||
func NuevoClienteIA(cfg *config.Config) (*ClienteIA, error) {
|
||||
var apiKey, baseURL, model string
|
||||
if cfg != nil {
|
||||
apiKey = strings.TrimSpace(cfg.MinimaxAPIKey)
|
||||
baseURL = strings.TrimSpace(cfg.MinimaxBaseURL)
|
||||
model = strings.TrimSpace(cfg.MinimaxModel)
|
||||
} else {
|
||||
apiKey = strings.TrimSpace(os.Getenv("MINIMAX_API_KEY"))
|
||||
baseURL = strings.TrimSpace(os.Getenv("MINIMAX_BASE_URL"))
|
||||
model = strings.TrimSpace(os.Getenv("MINIMAX_MODEL"))
|
||||
}
|
||||
|
||||
if apiKey == "" {
|
||||
if strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY")) != "" {
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY (se detecto ANTHROPIC_API_KEY en el entorno, pero NO se usa para evitar mandar credenciales al proveedor equivocado). Define MINIMAX_API_KEY en .env.",
|
||||
)
|
||||
}
|
||||
return nil, errors.New(
|
||||
"Falta MINIMAX_API_KEY. Definela en .env. No uses ANTHROPIC_API_KEY: la clave de MiniMax nunca debe enviarse a api.anthropic.com.",
|
||||
)
|
||||
}
|
||||
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultMinimaxBaseURL
|
||||
}
|
||||
baseURL = strings.TrimRight(baseURL, "/")
|
||||
|
||||
if model == "" {
|
||||
model = DefaultMinimaxModel
|
||||
}
|
||||
|
||||
return &ClienteIA{
|
||||
APIKey: apiKey,
|
||||
BaseURL: baseURL,
|
||||
Model: model,
|
||||
HTTPClient: &http.Client{
|
||||
Timeout: 120 * time.Second,
|
||||
},
|
||||
Sleep: sleepContext,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NormalizarRespuesta corrige rarezas observadas en las respuestas de MiniMax
|
||||
// antes de validar: a veces envuelve elementos de arrays en `{item: {...}}`.
|
||||
// Solo desenvuelve cuando "item" es la UNICA clave del objeto.
|
||||
func NormalizarRespuesta(v any) any {
|
||||
switch val := v.(type) {
|
||||
case []any:
|
||||
out := make([]any, len(val))
|
||||
for i, elem := range val {
|
||||
out[i] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
if len(val) == 1 {
|
||||
if inner, ok := val["item"]; ok {
|
||||
return NormalizarRespuesta(inner)
|
||||
}
|
||||
}
|
||||
out := make(map[string]any, len(val))
|
||||
for k, elem := range val {
|
||||
out[k] = NormalizarRespuesta(elem)
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
type apiCacheControl struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type apiSystemBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
CacheControl *apiCacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type apiTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"input_schema"`
|
||||
}
|
||||
|
||||
type apiToolChoice struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type apiMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type apiRequest struct {
|
||||
Model string `json:"model"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
System []apiSystemBlock `json:"system,omitempty"`
|
||||
Tools []apiTool `json:"tools,omitempty"`
|
||||
ToolChoice *apiToolChoice `json:"tool_choice,omitempty"`
|
||||
Messages []apiMessage `json:"messages"`
|
||||
}
|
||||
|
||||
type apiContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input any `json:"input,omitempty"`
|
||||
}
|
||||
|
||||
type apiUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
Content []apiContentBlock `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage apiUsage `json:"usage"`
|
||||
}
|
||||
|
||||
type apiHTTPError struct {
|
||||
Status int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *apiHTTPError) Error() string {
|
||||
return fmt.Sprintf("error HTTP %d del proveedor IA: %s", e.Status, e.Body)
|
||||
}
|
||||
|
||||
var (
|
||||
reTransitorio400 = regexp.MustCompile(`(?i)unexpected|internal|parse|unknown`)
|
||||
reTransitorioRed = regexp.MustCompile(`(?i)ECONN|ETIMEDOUT|socket|network|connection reset|EOF|timeout`)
|
||||
)
|
||||
|
||||
func esTransitorio(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
var httpErr *apiHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.Status {
|
||||
case http.StatusRequestTimeout, http.StatusConflict, http.StatusTooManyRequests:
|
||||
return true
|
||||
}
|
||||
if httpErr.Status >= 500 {
|
||||
return true
|
||||
}
|
||||
if httpErr.Status == http.StatusBadRequest && reTransitorio400.MatchString(httpErr.Body) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return true
|
||||
}
|
||||
return reTransitorioRed.MatchString(err.Error())
|
||||
}
|
||||
|
||||
func sleepContext(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensaje(ctx context.Context, reqBody apiRequest) (*apiResponse, error) {
|
||||
payload, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error serializando solicitud IA: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(c.BaseURL, "/") + "/v1/messages"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creando solicitud HTTP: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", c.APIKey)
|
||||
req.Header.Set("anthropic-version", anthropicVersion)
|
||||
|
||||
httpClient := c.HTTPClient
|
||||
if httpClient == nil {
|
||||
httpClient = &http.Client{Timeout: 120 * time.Second}
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
bodyStr := strings.TrimSpace(string(raw))
|
||||
if len(bodyStr) > 1000 {
|
||||
bodyStr = bodyStr[:1000]
|
||||
}
|
||||
return nil, &apiHTTPError{Status: resp.StatusCode, Body: bodyStr}
|
||||
}
|
||||
|
||||
var parsed apiResponse
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
return nil, fmt.Errorf("error decodificando respuesta IA: %w", err)
|
||||
}
|
||||
return &parsed, nil
|
||||
}
|
||||
|
||||
func (c *ClienteIA) crearMensajeConReintentos(ctx context.Context, reqBody apiRequest, maxTransitorios int) (*apiResponse, error) {
|
||||
if maxTransitorios <= 0 {
|
||||
maxTransitorios = maxTransitoriosDef
|
||||
}
|
||||
sleepFn := c.Sleep
|
||||
if sleepFn == nil {
|
||||
sleepFn = sleepContext
|
||||
}
|
||||
|
||||
var ultimo error
|
||||
for i := 1; i <= maxTransitorios; i++ {
|
||||
res, err := c.crearMensaje(ctx, reqBody)
|
||||
if err == nil {
|
||||
return res, nil
|
||||
}
|
||||
ultimo = err
|
||||
if !esTransitorio(err) || i == maxTransitorios {
|
||||
return nil, err
|
||||
}
|
||||
backoff := time.Duration(1<<(i-1)) * time.Second // 1s, 2s
|
||||
if sleepErr := sleepFn(ctx, backoff); sleepErr != nil {
|
||||
return nil, sleepErr
|
||||
}
|
||||
}
|
||||
return nil, ultimo
|
||||
}
|
||||
|
||||
// LlamarConHerramienta invoca al modelo exigiendo una llamada a opts.Herramienta,
|
||||
// normaliza rarezas de MiniMax, valida contra el contrato y reintenta devolviendo
|
||||
// los errores exactos de validacion hasta opts.MaxIntentos.
|
||||
func (c *ClienteIA) LlamarConHerramienta(ctx context.Context, opts OpcionesLlamada) (*ResultadoLlamada, error) {
|
||||
maxIntentos := opts.MaxIntentos
|
||||
if maxIntentos <= 0 {
|
||||
maxIntentos = 3
|
||||
}
|
||||
maxTokens := opts.MaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 8000
|
||||
}
|
||||
|
||||
systemBlocks := make([]apiSystemBlock, 0, len(opts.System))
|
||||
for _, b := range opts.System {
|
||||
blk := apiSystemBlock{
|
||||
Type: "text",
|
||||
Text: b.Texto,
|
||||
}
|
||||
if b.Cachear {
|
||||
blk.CacheControl = &apiCacheControl{Type: "ephemeral"}
|
||||
}
|
||||
systemBlocks = append(systemBlocks, blk)
|
||||
}
|
||||
|
||||
tools := []apiTool{
|
||||
{
|
||||
Name: opts.Herramienta.Nombre,
|
||||
Description: opts.Herramienta.Descripcion,
|
||||
InputSchema: opts.Herramienta.InputSchema,
|
||||
},
|
||||
}
|
||||
|
||||
toolChoice := &apiToolChoice{
|
||||
Type: "tool",
|
||||
Name: opts.Herramienta.Nombre,
|
||||
}
|
||||
|
||||
mensajes := []apiMessage{
|
||||
{Role: "user", Content: opts.MensajeUsuario},
|
||||
}
|
||||
|
||||
var uso UsoTokens
|
||||
var ultimoError string
|
||||
|
||||
for intento := 1; intento <= maxIntentos; intento++ {
|
||||
res, err := c.crearMensajeConReintentos(ctx, apiRequest{
|
||||
Model: c.Model,
|
||||
MaxTokens: maxTokens,
|
||||
System: systemBlocks,
|
||||
Tools: tools,
|
||||
ToolChoice: toolChoice,
|
||||
Messages: mensajes,
|
||||
}, maxTransitoriosDef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uso.Entrada += res.Usage.InputTokens
|
||||
uso.Salida += res.Usage.OutputTokens
|
||||
uso.CacheLectura += res.Usage.CacheReadInputTokens
|
||||
uso.CacheEscritura += res.Usage.CacheCreationInputTokens
|
||||
|
||||
var bloquesTool []apiContentBlock
|
||||
var candidatos []apiContentBlock
|
||||
for _, blk := range res.Content {
|
||||
if blk.Type == "tool_use" {
|
||||
bloquesTool = append(bloquesTool, blk)
|
||||
if blk.Name == opts.Herramienta.Nombre {
|
||||
candidatos = append(candidatos, blk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var primerFallo *apiContentBlock
|
||||
for i := range candidatos {
|
||||
cand := candidatos[i]
|
||||
norm := NormalizarRespuesta(cand.Input)
|
||||
datos, ok := norm.(map[string]any)
|
||||
var errs []string
|
||||
if !ok {
|
||||
errs = []string{"La entrada de la herramienta debe ser un objeto JSON."}
|
||||
} else if opts.Herramienta.Validar != nil {
|
||||
errs = opts.Herramienta.Validar(datos)
|
||||
}
|
||||
if len(errs) == 0 {
|
||||
return &ResultadoLlamada{
|
||||
Datos: datos,
|
||||
Uso: uso,
|
||||
Intentos: intento,
|
||||
}, nil
|
||||
}
|
||||
if primerFallo == nil {
|
||||
cp := cand
|
||||
primerFallo = &cp
|
||||
ultimoError = strings.Join(errs, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
if len(bloquesTool) > 0 {
|
||||
if primerFallo == nil {
|
||||
ultimoError = fmt.Sprintf("El modelo llamo a una herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
}
|
||||
userBlocks := make([]any, 0, len(bloquesTool)+1)
|
||||
for _, b := range bloquesTool {
|
||||
content := fmt.Sprintf("Herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
||||
if primerFallo != nil && b.ID == primerFallo.ID {
|
||||
content = ultimoError
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": b.ID,
|
||||
"is_error": true,
|
||||
"content": content,
|
||||
})
|
||||
}
|
||||
userBlocks = append(userBlocks, map[string]any{
|
||||
"type": "text",
|
||||
"text": fmt.Sprintf(
|
||||
"La llamada no cumple el schema. Corrige EXACTAMENTE estos errores y vuelve a llamar a %s:\n\n%s\n\nRevisa que cada objeto este en el array que le corresponde y que no falte ningun campo obligatorio. No agregues campos que el schema no declara.",
|
||||
opts.Herramienta.Nombre,
|
||||
ultimoError,
|
||||
),
|
||||
})
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{Role: "user", Content: userBlocks},
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
ultimoError = "El modelo respondio con prosa en vez de llamar a la herramienta."
|
||||
mensajes = append(mensajes,
|
||||
apiMessage{Role: "assistant", Content: res.Content},
|
||||
apiMessage{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf("Debes responder llamando a la herramienta %s. No escribas prosa suelta.", opts.Herramienta.Nombre),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("El paso %q agoto %d intentos.\nUltimo error:\n%s", opts.Herramienta.Nombre, maxIntentos, ultimoError)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"cotizador/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PartidaEconomia representa una linea cotizada canonica.
|
||||
// Ref (P01, P02...) es lo unico que identifica la partida ante el modelo de IA;
|
||||
// los precios e importes nunca viajan al prompt y solo los usa el renderizador
|
||||
// o los calculos internos.
|
||||
type PartidaEconomia struct {
|
||||
Ref string `json:"refPartida"`
|
||||
Nombre string `json:"nombre"`
|
||||
Fase int `json:"fase"`
|
||||
TipoPago string `json:"tipoPago"`
|
||||
Precio float64 `json:"precio"`
|
||||
TiempoEntrega string `json:"tiempoEntrega"`
|
||||
Entregables []string `json:"entregables"`
|
||||
ModeloCobro string `json:"modeloCobro"`
|
||||
Horas *float64 `json:"horas"`
|
||||
TarifaHora *float64 `json:"tarifaHora"`
|
||||
MontoMinimo *float64 `json:"montoMinimo"`
|
||||
HorasIncluidas *float64 `json:"horasIncluidas"`
|
||||
}
|
||||
|
||||
// RatioValor resume la lectura precio/valor del anexo interno.
|
||||
type RatioValor struct {
|
||||
Ratio float64 `json:"ratio"`
|
||||
Etiqueta string `json:"etiqueta"`
|
||||
Nota string `json:"nota"`
|
||||
}
|
||||
|
||||
// EconomiaCotizacion agrupa las partidas seleccionadas, el plan Bucefalo
|
||||
// (si fue contratado) y los totales canonicos de la cotizacion.
|
||||
type EconomiaCotizacion struct {
|
||||
Partidas []PartidaEconomia `json:"partidas"`
|
||||
PlanBucefalo *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
} `json:"planBucefalo"`
|
||||
Totales domain.TotalesCotizacion `json:"totales"`
|
||||
Moneda string `json:"moneda"`
|
||||
}
|
||||
|
||||
// CalcularRatio calcula el ratio precio/valor para el anexo interno comparando
|
||||
// el desembolso total del primer ano contra el costo anual del problema del cliente.
|
||||
//
|
||||
// Cortes:
|
||||
// - < 0.10: subcotizado
|
||||
// - <= 0.25: en_rango
|
||||
// - <= 0.40: alto
|
||||
// - > 0.40: objecion_probable
|
||||
func CalcularRatio(totalPrimerAnio, valorAnual float64) RatioValor {
|
||||
if valorAnual <= 0 {
|
||||
return RatioValor{
|
||||
Ratio: 0,
|
||||
Etiqueta: "",
|
||||
Nota: "Sin valor anual cuantificado del problema.",
|
||||
}
|
||||
}
|
||||
|
||||
ratio := totalPrimerAnio / valorAnual
|
||||
var etiqueta, nota string
|
||||
switch {
|
||||
case ratio < 0.10:
|
||||
etiqueta = "subcotizado"
|
||||
nota = "La inversion es menos del 10% de lo que el problema le cuesta al cliente cada ano. Probablemente subcotizaste."
|
||||
case ratio <= 0.25:
|
||||
etiqueta = "en_rango"
|
||||
nota = "La inversion cae en el rango de referencia (15-25% del valor anual)."
|
||||
case ratio <= 0.40:
|
||||
etiqueta = "alto"
|
||||
nota = "La inversion esta en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el numero."
|
||||
default:
|
||||
etiqueta = "objecion_probable"
|
||||
nota = "La inversion supera el 40% del valor anual del problema. Prepara la conversacion de precio: se responde con alcance, no con descuento."
|
||||
}
|
||||
|
||||
return RatioValor{
|
||||
Ratio: math.Round(ratio*1000) / 1000,
|
||||
Etiqueta: etiqueta,
|
||||
Nota: nota,
|
||||
}
|
||||
}
|
||||
|
||||
// CargarEconomiaCotizacion carga desde PostgreSQL las partidas seleccionadas,
|
||||
// el plan Bucefalo (si aplica) y los totales canonicos de una cotizacion.
|
||||
func CargarEconomiaCotizacion(ctx context.Context, pool *pgxpool.Pool, cotizacionID string) (*EconomiaCotizacion, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
|
||||
var moneda string
|
||||
var incluirIVA bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT "moneda", "incluirIva"
|
||||
FROM "Cotizacion"
|
||||
WHERE "id" = $1
|
||||
`, cotizacionID).Scan(&moneda, &incluirIVA)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", cotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error consultando cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT
|
||||
COALESCE(NULLIF(cat."nombre", ''), NULLIF(sc."nombre", ''), 'Servicio') AS nombre,
|
||||
sc."fase",
|
||||
sc."tipoPago",
|
||||
sc."precio",
|
||||
sc."tiempoEntrega",
|
||||
sc."entregables",
|
||||
sc."modeloCobro",
|
||||
sc."horas",
|
||||
sc."tarifaHora",
|
||||
sc."montoMinimo",
|
||||
sc."horasIncluidas"
|
||||
FROM "ServicioCotizado" sc
|
||||
LEFT JOIN "ServicioCatalogo" cat ON cat."id" = sc."servicioCatalogoId"
|
||||
WHERE sc."cotizacionId" = $1 AND sc."seleccionado" = true
|
||||
ORDER BY sc."fase" ASC, sc."createdAt" ASC
|
||||
`, cotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando servicios de cotizacion %s: %w", cotizacionID, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
partidas := make([]PartidaEconomia, 0)
|
||||
paraTotales := make([]domain.ServicioCalc, 0)
|
||||
idx := 0
|
||||
|
||||
for rows.Next() {
|
||||
var p PartidaEconomia
|
||||
var entregablesRaw []byte
|
||||
if err := rows.Scan(
|
||||
&p.Nombre,
|
||||
&p.Fase,
|
||||
&p.TipoPago,
|
||||
&p.Precio,
|
||||
&p.TiempoEntrega,
|
||||
&entregablesRaw,
|
||||
&p.ModeloCobro,
|
||||
&p.Horas,
|
||||
&p.TarifaHora,
|
||||
&p.MontoMinimo,
|
||||
&p.HorasIncluidas,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("error leyendo servicio cotizado: %w", err)
|
||||
}
|
||||
idx++
|
||||
p.Ref = fmt.Sprintf("P%02d", idx)
|
||||
p.Entregables = parseStringSliceJSON(entregablesRaw)
|
||||
partidas = append(partidas, p)
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
Nombre: p.Nombre,
|
||||
ModeloCobro: p.ModeloCobro,
|
||||
TipoPago: p.TipoPago,
|
||||
Precio: p.Precio,
|
||||
Seleccionado: true,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("error iterando servicios cotizados: %w", err)
|
||||
}
|
||||
|
||||
var plan *struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}
|
||||
var nivelPlan string
|
||||
var precioPlan float64
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT "nivel", "precio"
|
||||
FROM "PlanBucefaloCotizacion"
|
||||
WHERE "cotizacionId" = $1 AND "seleccionado" = true
|
||||
LIMIT 1
|
||||
`, cotizacionID).Scan(&nivelPlan, &precioPlan)
|
||||
if err == nil {
|
||||
plan = &struct {
|
||||
Nivel string `json:"nivel"`
|
||||
Precio float64 `json:"precio"`
|
||||
}{
|
||||
Nivel: nivelPlan,
|
||||
Precio: precioPlan,
|
||||
}
|
||||
// El plan Bucefalo se cobra mensual y entra a los totales igual que en el PDF economico.
|
||||
paraTotales = append(paraTotales, domain.ServicioCalc{
|
||||
TipoPago: "mensual",
|
||||
Precio: precioPlan,
|
||||
Seleccionado: true,
|
||||
})
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("error consultando plan Bucefalo de %s: %w", cotizacionID, err)
|
||||
}
|
||||
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: partidas,
|
||||
PlanBucefalo: plan,
|
||||
Totales: domain.CalcularTotalesCotizacion(paraTotales, incluirIVA),
|
||||
Moneda: moneda,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseStringSliceJSON(raw []byte) []string {
|
||||
if len(raw) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
var out []string
|
||||
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
|
||||
return []string{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// GenerarInput encapsula los datos de entrada para generar una propuesta consultiva.
|
||||
type GenerarInput struct {
|
||||
CotizacionID string
|
||||
Transcripcion string
|
||||
NotasAdicionales string
|
||||
}
|
||||
|
||||
// GenerarResult devuelve el contenido estructurado de la propuesta, la traza
|
||||
// de consumo/intentos, los avisos de validacion y el modelo usado.
|
||||
type GenerarResult struct {
|
||||
Contenido map[string]any
|
||||
Traza map[string]any
|
||||
Avisos []Aviso
|
||||
Modelo string
|
||||
}
|
||||
|
||||
type pasoTraza struct {
|
||||
Paso string `json:"paso"`
|
||||
Intentos int `json:"intentos"`
|
||||
Uso UsoTokens `json:"uso"`
|
||||
}
|
||||
|
||||
// GenerarPropuesta ejecuta el pipeline consultivo de tres pasos (extraccion,
|
||||
// diagnostico, redaccion) contra MiniMax y valida la salida contra las reglas
|
||||
// de negocio y la economia canonica de la cotizacion.
|
||||
func GenerarPropuesta(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, in GenerarInput) (*GenerarResult, error) {
|
||||
if pool == nil {
|
||||
return nil, errors.New("pool de base de datos no inicializado")
|
||||
}
|
||||
if strings.TrimSpace(in.CotizacionID) == "" {
|
||||
return nil, errors.New("CotizacionID es obligatorio")
|
||||
}
|
||||
|
||||
var proyecto, observaciones, observacionesInternas, clienteNombre, clienteEmpresa string
|
||||
var esDoble bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
c."proyecto",
|
||||
c."esDoble",
|
||||
COALESCE(c."observaciones", ''),
|
||||
COALESCE(c."observacionesInternas", ''),
|
||||
cl."nombre",
|
||||
COALESCE(cl."empresa", '')
|
||||
FROM "Cotizacion" c
|
||||
JOIN "Cliente" cl ON cl."id" = c."clienteId"
|
||||
WHERE c."id" = $1
|
||||
`, in.CotizacionID).Scan(
|
||||
&proyecto,
|
||||
&esDoble,
|
||||
&observaciones,
|
||||
&observacionesInternas,
|
||||
&clienteNombre,
|
||||
&clienteEmpresa,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, fmt.Errorf("Cotizacion %s no encontrada", in.CotizacionID)
|
||||
}
|
||||
return nil, fmt.Errorf("error cargando contexto de cotizacion %s: %w", in.CotizacionID, err)
|
||||
}
|
||||
|
||||
if esDoble {
|
||||
return nil, errors.New(
|
||||
"Esta cotizacion es de doble propuesta y el documento consultivo todavia no las soporta: sumaria las dos opciones como si fueran una sola. Genera la propuesta desde una cotizacion de opcion unica.",
|
||||
)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT "notas"
|
||||
FROM "ServicioCotizado"
|
||||
WHERE "cotizacionId" = $1 AND "notas" IS NOT NULL AND BTRIM("notas") <> ''
|
||||
ORDER BY "fase" ASC, "createdAt" ASC
|
||||
`, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error consultando notas de partidas: %w", err)
|
||||
}
|
||||
var notasLista []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if err := rows.Scan(&n); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error leyendo nota de partida: %w", err)
|
||||
}
|
||||
if trimmed := strings.TrimSpace(n); trimmed != "" {
|
||||
notasLista = append(notasLista, trimmed)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("error iterando notas de partidas: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
if extra := strings.TrimSpace(in.NotasAdicionales); extra != "" {
|
||||
notasLista = append(notasLista, extra)
|
||||
}
|
||||
notasCombinadas := strings.Join(notasLista, "\n")
|
||||
|
||||
economia, err := CargarEconomiaCotizacion(ctx, pool, in.CotizacionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(economia.Partidas) == 0 {
|
||||
return nil, errors.New("La cotizacion no tiene partidas seleccionadas. Agrega servicios antes de generar la propuesta.")
|
||||
}
|
||||
|
||||
cliente, err := NuevoClienteIA(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entrada := ContextoEntrada{
|
||||
Transcripcion: in.Transcripcion,
|
||||
Notas: notasCombinadas,
|
||||
Observaciones: observaciones,
|
||||
Cliente: clienteNombre,
|
||||
Empresa: clienteEmpresa,
|
||||
Proyecto: proyecto,
|
||||
}
|
||||
|
||||
return ejecutarPipeline(ctx, cliente, entrada, economia, observacionesInternas)
|
||||
}
|
||||
|
||||
func ejecutarPipeline(
|
||||
ctx context.Context,
|
||||
cliente *ClienteIA,
|
||||
entrada ContextoEntrada,
|
||||
economia *EconomiaCotizacion,
|
||||
notasInternas string,
|
||||
) (*GenerarResult, error) {
|
||||
system := []BloqueSystem{{Texto: SystemBase, Cachear: true}}
|
||||
pasos := make([]pasoTraza, 0, 3)
|
||||
var totalUso UsoTokens
|
||||
acumular := func(u UsoTokens) {
|
||||
totalUso.Entrada += u.Entrada
|
||||
totalUso.Salida += u.Salida
|
||||
totalUso.CacheLectura += u.CacheLectura
|
||||
totalUso.CacheEscritura += u.CacheEscritura
|
||||
}
|
||||
|
||||
r1, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso1(entrada),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "Registra las citas literales, los hechos, los pendientes y las red flags extraidos del material de la reunion.",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 5,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "extraccion", Intentos: r1.Intentos, Uso: r1.Uso})
|
||||
acumular(r1.Uso)
|
||||
|
||||
r2, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso2(entrada, r1.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_diagnostico",
|
||||
Descripcion: "Registra los hallazgos con su semaforo de urgencia, el valor anual del problema y los resultados de negocio a lograr.",
|
||||
InputSchema: SchemaDiagnostico(),
|
||||
Validar: ValidarDiagnostico,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 8000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "diagnostico", Intentos: r2.Intentos, Uso: r2.Uso})
|
||||
acumular(r2.Uso)
|
||||
|
||||
r3, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{
|
||||
System: system,
|
||||
MensajeUsuario: MensajePaso3(entrada, r1.Datos, r2.Datos, economia),
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_propuesta",
|
||||
Descripcion: "Registra la redaccion final de la propuesta consultiva para el cliente.",
|
||||
InputSchema: SchemaRedaccion(),
|
||||
Validar: ValidarRedaccion,
|
||||
},
|
||||
MaxIntentos: 4,
|
||||
MaxTokens: 12000,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pasos = append(pasos, pasoTraza{Paso: "redaccion", Intentos: r3.Intentos, Uso: r3.Uso})
|
||||
acumular(r3.Uso)
|
||||
|
||||
contenido := map[string]any{
|
||||
"hechos": r1.Datos,
|
||||
"diagnostico": r2.Datos,
|
||||
"redaccion": r3.Datos,
|
||||
}
|
||||
|
||||
fuentesCliente := strings.Join([]string{entrada.Transcripcion, entrada.Observaciones, entrada.Notas}, "\n")
|
||||
avisos := ValidarPropuesta(contenido, economia, fuentesCliente, notasInternas)
|
||||
|
||||
traza := map[string]any{
|
||||
"modelo": cliente.Model,
|
||||
"pasos": pasos,
|
||||
"totalUso": totalUso,
|
||||
}
|
||||
|
||||
return &GenerarResult{
|
||||
Contenido: contenido,
|
||||
Traza: traza,
|
||||
Avisos: avisos,
|
||||
Modelo: cliente.Model,
|
||||
}, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,876 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/domain"
|
||||
)
|
||||
|
||||
// ─────────────────────────── economia.go ───────────────────────────
|
||||
|
||||
func TestCalcularRatio(t *testing.T) {
|
||||
// Sin valor anual / cero / negativo -> sin etiqueta ni division entre cero
|
||||
for _, val := range []float64{0, -5, -1000} {
|
||||
r := CalcularRatio(100000, val)
|
||||
if r.Ratio != 0 || r.Etiqueta != "" {
|
||||
t.Fatalf("valorAnual=%v: esperado Ratio=0 Etiqueta=\"\", obtuve %+v", val, r)
|
||||
}
|
||||
if r.Nota == "" {
|
||||
t.Fatalf("valorAnual=%v: esperaba Nota explicativa", val)
|
||||
}
|
||||
}
|
||||
|
||||
casos := []struct {
|
||||
nombre string
|
||||
total float64
|
||||
valor float64
|
||||
etiqueta string
|
||||
ratio float64
|
||||
}{
|
||||
{"5% subcotizado", 50000, 1000000, "subcotizado", 0.05},
|
||||
{"corte exacto 10% en_rango", 100000, 1000000, "en_rango", 0.1},
|
||||
{"20% en_rango", 200000, 1000000, "en_rango", 0.2},
|
||||
{"corte exacto 25% en_rango", 250000, 1000000, "en_rango", 0.25},
|
||||
{"35% alto", 350000, 1000000, "alto", 0.35},
|
||||
{"corte exacto 40% alto", 400000, 1000000, "alto", 0.4},
|
||||
{"60% objecion_probable", 600000, 1000000, "objecion_probable", 0.6},
|
||||
{"redondeo a 3 decimales", 123456, 1000000, "en_rango", 0.123},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := CalcularRatio(tc.total, tc.valor)
|
||||
if got.Etiqueta != tc.etiqueta {
|
||||
t.Fatalf("etiqueta: esperado %q, obtuve %q (ratio=%v)", tc.etiqueta, got.Etiqueta, got.Ratio)
|
||||
}
|
||||
if got.Ratio != tc.ratio {
|
||||
t.Fatalf("ratio: esperado %v, obtuve %v", tc.ratio, got.Ratio)
|
||||
}
|
||||
if got.Nota == "" {
|
||||
t.Fatalf("se esperaba Nota no vacia para %q", tc.etiqueta)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── cliente_ia.go ───────────────────────────
|
||||
|
||||
func TestNuevoClienteIA(t *testing.T) {
|
||||
t.Run("rechaza clave faltante nombrando MINIMAX_API_KEY y ANTHROPIC_API_KEY", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error sin MINIMAX_API_KEY")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "MINIMAX_API_KEY") || !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") {
|
||||
t.Fatalf("mensaje debe mencionar MINIMAX_API_KEY y ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("advierte explicitamente si solo ANTHROPIC_API_KEY esta definida", func(t *testing.T) {
|
||||
t.Setenv("MINIMAX_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_API_KEY", "sk-ant-solo-prueba")
|
||||
_, err := NuevoClienteIA(&config.Config{})
|
||||
if err == nil {
|
||||
t.Fatal("esperaba error cuando solo ANTHROPIC_API_KEY esta definida")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") || !strings.Contains(err.Error(), "MINIMAX_API_KEY") {
|
||||
t.Fatalf("error debe advertir sobre ANTHROPIC_API_KEY: %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("defaults e ignorar ANTHROPIC_BASE_URL", func(t *testing.T) {
|
||||
t.Setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
|
||||
c, err := NuevoClienteIA(&config.Config{MinimaxAPIKey: "clave-prueba"})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !strings.Contains(c.BaseURL, "api.minimax.io") {
|
||||
t.Fatalf("BaseURL esperado de MiniMax, obtuve %q", c.BaseURL)
|
||||
}
|
||||
if strings.Contains(c.BaseURL, "api.anthropic.com") {
|
||||
t.Fatalf("ANTHROPIC_BASE_URL no debe secuestrar BaseURL: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M3" {
|
||||
t.Fatalf("Model por defecto esperado MiniMax-M3, obtuve %q", c.Model)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("respeta MINIMAX_BASE_URL y MINIMAX_MODEL", func(t *testing.T) {
|
||||
c, err := NuevoClienteIA(&config.Config{
|
||||
MinimaxAPIKey: "clave-prueba",
|
||||
MinimaxBaseURL: "https://ejemplo.local/anthropic/",
|
||||
MinimaxModel: "MiniMax-M2",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if c.BaseURL != "https://ejemplo.local/anthropic" {
|
||||
t.Fatalf("BaseURL inesperado: %q", c.BaseURL)
|
||||
}
|
||||
if c.Model != "MiniMax-M2" {
|
||||
t.Fatalf("Model inesperado: %q", c.Model)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizarRespuesta(t *testing.T) {
|
||||
casos := []struct {
|
||||
nombre string
|
||||
in any
|
||||
want any
|
||||
}{
|
||||
{
|
||||
"desenvuelve {item: X} cuando item es la unica clave",
|
||||
map[string]any{"item": map[string]any{"a": 1}},
|
||||
map[string]any{"a": 1},
|
||||
},
|
||||
{
|
||||
"desenvuelve dentro de arrays",
|
||||
[]any{map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"item": map[string]any{"a": 2}}},
|
||||
[]any{map[string]any{"a": 1}, map[string]any{"a": 2}},
|
||||
},
|
||||
{
|
||||
"desenvuelve en profundidad",
|
||||
map[string]any{"lista": []any{map[string]any{"item": map[string]any{"x": []any{map[string]any{"item": 5}}}}}},
|
||||
map[string]any{"lista": []any{map[string]any{"x": []any{5}}}},
|
||||
},
|
||||
{
|
||||
"NO toca un objeto con item junto a otras claves",
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
map[string]any{"item": 1, "otro": 2},
|
||||
},
|
||||
{
|
||||
"deja intactos valores simples",
|
||||
"texto",
|
||||
"texto",
|
||||
},
|
||||
{
|
||||
"deja intacto nil",
|
||||
nil,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"no altera un objeto normal",
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
map[string]any{"a": 1, "b": []any{1, 2}},
|
||||
},
|
||||
{
|
||||
"caso real: alcance envuelto",
|
||||
map[string]any{"alcance": []any{map[string]any{"item": map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}},
|
||||
map[string]any{"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range casos {
|
||||
t.Run(tc.nombre, func(t *testing.T) {
|
||||
got := NormalizarRespuesta(tc.in)
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("esperado %#v, obtuve %#v", tc.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClienteIAToolCallingRetryYFeedback(t *testing.T) {
|
||||
var calls int32
|
||||
var sawToolChoice, sawCacheControl, sawToolResultError bool
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&calls, 1)
|
||||
if r.URL.Path != "/v1/messages" {
|
||||
t.Errorf("path inesperado: %s", r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("x-api-key") != "test-key" {
|
||||
t.Errorf("x-api-key faltante o invalido: %q", r.Header.Get("x-api-key"))
|
||||
}
|
||||
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("body JSON invalido: %v", err)
|
||||
}
|
||||
if tc, ok := body["tool_choice"].(map[string]any); ok && tc["type"] == "tool" && tc["name"] == "registrar_hechos" {
|
||||
sawToolChoice = true
|
||||
}
|
||||
if sys, ok := body["system"].([]any); ok && len(sys) > 0 {
|
||||
if s0, ok := sys[0].(map[string]any); ok {
|
||||
if cc, ok := s0["cache_control"].(map[string]any); ok && cc["type"] == "ephemeral" {
|
||||
sawCacheControl = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Llamada 1: fallo transitorio 429
|
||||
if n == 1 {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
_, _ = w.Write([]byte(`{"error":"rate_limit"}`))
|
||||
return
|
||||
}
|
||||
// Llamada 2: devuelve tool_use invalido (cita muy corta -> dispara feedback loop)
|
||||
if n == 2 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_1",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_1",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"id": "C01", "textoLiteral": "corta", "quienLoDijo": "socio"}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 100, "output_tokens": 50, "cache_creation_input_tokens": 80},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Llamada 3: verificar que llego tool_result con is_error=true y responder valido envuelto en {item:...}
|
||||
if msgs, ok := body["messages"].([]any); ok && len(msgs) >= 3 {
|
||||
if last, ok := msgs[len(msgs)-1].(map[string]any); ok {
|
||||
if blocks, ok := last["content"].([]any); ok {
|
||||
for _, b := range blocks {
|
||||
if bm, ok := b.(map[string]any); ok && bm["type"] == "tool_result" && bm["is_error"] == true {
|
||||
sawToolResultError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_2",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_2",
|
||||
"name": "registrar_hechos",
|
||||
"input": map[string]any{
|
||||
"citas": []any{map[string]any{"item": map[string]any{
|
||||
"id": "C01",
|
||||
"textoLiteral": "no llevamos control de quien contesta el whatsapp el fin de semana",
|
||||
"quienLoDijo": "el socio",
|
||||
}}},
|
||||
"hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"input_tokens": 120, "output_tokens": 60, "cache_read_input_tokens": 80},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := cliente.LlamarConHerramienta(context.Background(), OpcionesLlamada{
|
||||
System: []BloqueSystem{{Texto: SystemBase, Cachear: true}},
|
||||
MensajeUsuario: "extrae hechos",
|
||||
Herramienta: Herramienta{
|
||||
Nombre: "registrar_hechos",
|
||||
Descripcion: "test",
|
||||
InputSchema: SchemaHechos(),
|
||||
Validar: ValidarHechos,
|
||||
},
|
||||
MaxIntentos: 3,
|
||||
MaxTokens: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("error inesperado: %v", err)
|
||||
}
|
||||
if !sawToolChoice {
|
||||
t.Fatal("esperaba tool_choice: {type: tool, name: registrar_hechos}")
|
||||
}
|
||||
if !sawCacheControl {
|
||||
t.Fatal("esperaba cache_control: {type: ephemeral}")
|
||||
}
|
||||
if !sawToolResultError {
|
||||
t.Fatal("esperaba feedback loop con tool_result is_error=true")
|
||||
}
|
||||
if res.Intentos != 2 {
|
||||
t.Fatalf("esperaba 2 intentos de validacion (mas 1 reintento HTTP 429), obtuve %d", res.Intentos)
|
||||
}
|
||||
if res.Uso.Entrada != 220 || res.Uso.Salida != 110 || res.Uso.CacheEscritura != 80 || res.Uso.CacheLectura != 80 {
|
||||
t.Fatalf("acumulacion de uso incorrecta: %+v", res.Uso)
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── prompts.go & schemas ───────────────────────────
|
||||
|
||||
func TestSystemBaseCacheInvariants(t *testing.T) {
|
||||
anioActual := strconv.Itoa(time.Now().Year())
|
||||
if strings.Contains(SystemBase, anioActual) {
|
||||
t.Fatalf("SystemBase no debe contener el anio actual (%s)", anioActual)
|
||||
}
|
||||
if regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener fechas ISO")
|
||||
}
|
||||
if regexp.MustCompile(`UJ\d{4}`).MatchString(SystemBase) {
|
||||
t.Fatal("SystemBase no debe contener folios de cotizacion")
|
||||
}
|
||||
if len(SystemBase) <= 2500 {
|
||||
t.Fatalf("SystemBase debe superar el minimo cacheable (>2500 chars), tiene %d", len(SystemBase))
|
||||
}
|
||||
|
||||
for _, p := range []string{"P1.", "P2.", "P3.", "P4.", "P5.", "P6.", "P7.", "P8."} {
|
||||
if !strings.Contains(SystemBase, p) {
|
||||
t.Fatalf("SystemBase debe declarar principio %s", p)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{
|
||||
"rojo:", "ambar:", "azul:", "verde:", "entre pares",
|
||||
"Bucefalo", "ningun otro CRM", "USD", "garantizado",
|
||||
"sinergias", "UNICAMENTE servicios digitales",
|
||||
"nombres de empleados", "MATERIAL ES POBRE", "contenido de valor",
|
||||
} {
|
||||
if !strings.Contains(SystemBase, s) {
|
||||
t.Fatalf("SystemBase debe contener %q", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBloqueContextoYMensajesSinPrecios(t *testing.T) {
|
||||
sinNada := BloqueContexto(ContextoEntrada{Cliente: "Ana", Proyecto: "P"})
|
||||
if !strings.Contains(sinNada, "No se entrego transcripcion") {
|
||||
t.Fatal("sin transcripcion debe declararlo explicitamente")
|
||||
}
|
||||
if strings.Contains(sinNada, "()") {
|
||||
t.Fatal("sin empresa no debe imprimir parentesis vacios")
|
||||
}
|
||||
|
||||
conTodo := BloqueContexto(ContextoEntrada{
|
||||
Transcripcion: "TRANS", Notas: "NOTAS", Observaciones: "OBS",
|
||||
Cliente: "Ana", Empresa: "ACME", Proyecto: "P",
|
||||
})
|
||||
for _, needle := range []string{"TRANS", "NOTAS", "OBS", "(ACME)"} {
|
||||
if !strings.Contains(conTodo, needle) {
|
||||
t.Fatalf("BloqueContexto debe incluir %q", needle)
|
||||
}
|
||||
}
|
||||
|
||||
econ := &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12345, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12345, IVAUnico: 1975.2, TotalUnico: 14320.2, TotalPrimerAnio: 14320.2, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
ctx := ContextoEntrada{Transcripcion: "t", Cliente: "Ana", Empresa: "ACME", Proyecto: "P"}
|
||||
hechos := map[string]any{"citas": []any{}, "hechos": []any{}}
|
||||
diag := map[string]any{"hallazgos": []any{}, "valorProblema": map[string]any{"dimensiones": []any{}, "notaMetodologia": ""}}
|
||||
|
||||
m1 := MensajePaso1(ctx)
|
||||
m2 := MensajePaso2(ctx, hechos, econ)
|
||||
m3 := MensajePaso3(ctx, hechos, diag, econ)
|
||||
|
||||
if !strings.Contains(m1, "registrar_hechos") || !strings.Contains(m1, "TEXTUALES") {
|
||||
t.Fatal("MensajePaso1 debe pedir registrar_hechos y citas TEXTUALES")
|
||||
}
|
||||
if !strings.Contains(m2, "registrar_diagnostico") {
|
||||
t.Fatal("MensajePaso2 debe pedir registrar_diagnostico")
|
||||
}
|
||||
if !strings.Contains(m3, "registrar_propuesta") {
|
||||
t.Fatal("MensajePaso3 debe pedir registrar_propuesta")
|
||||
}
|
||||
|
||||
for nombre, msg := range map[string]string{"paso 2": m2, "paso 3": m3} {
|
||||
if strings.Contains(msg, "12345") || strings.Contains(msg, "14320") {
|
||||
t.Fatalf("%s NO puede filtrar precios o totales", nombre)
|
||||
}
|
||||
if !strings.Contains(msg, "P01") {
|
||||
t.Fatalf("%s SI debe incluir refPartida P01", nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolSchemasZeroUJCPriceKeys(t *testing.T) {
|
||||
schemas := []map[string]any{SchemaHechos(), SchemaDiagnostico(), SchemaRedaccion()}
|
||||
rawBytes, err := json.Marshal(schemas)
|
||||
if err != nil {
|
||||
t.Fatalf("error serializando schemas: %v", err)
|
||||
}
|
||||
todos := string(rawBytes)
|
||||
|
||||
prohibidos := []string{"precio", "total", "subtotal", "iva", "montoMinimo", "tarifaHora", "descuento"}
|
||||
for _, p := range prohibidos {
|
||||
if strings.Contains(todos, `"`+p+`"`) {
|
||||
t.Fatalf("ningun tool schema puede declarar propiedad de dinero UJC %q", p)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(todos, `"montoAnualMXN"`) {
|
||||
t.Fatal("SchemaDiagnostico debe incluir montoAnualMXN (costo del problema del cliente)")
|
||||
}
|
||||
if strings.Contains(todos, `"$schema"`) {
|
||||
t.Fatal("los tool schemas no deben llevar $schema")
|
||||
}
|
||||
if strings.Contains(todos, `"calculo"`) {
|
||||
t.Fatal("la dimension de valorProblema debe ser plana, sin objeto calculo")
|
||||
}
|
||||
if !strings.Contains(todos, `"additionalProperties"`) || !strings.Contains(todos, `"description"`) {
|
||||
t.Fatal("los tool schemas deben conservar additionalProperties y description")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidadoresSchemaPasos(t *testing.T) {
|
||||
// Hechos vacios validos (material pobre)
|
||||
if errs := ValidarHechos(map[string]any{
|
||||
"citas": []any{}, "hechos": []any{}, "materialesPendientes": []any{},
|
||||
"decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{},
|
||||
}); len(errs) != 0 {
|
||||
t.Fatalf("hechos vacios deben ser validos: %v", errs)
|
||||
}
|
||||
|
||||
// Diagnostico: omitir montoAnualMXN se tolera y rellena nil; con monto y <2 factores se rechaza
|
||||
dimSinMonto := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{}, "confianza": "por_validar", "hechos": []any{},
|
||||
}
|
||||
diag := map[string]any{
|
||||
"hallazgos": []any{map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Titulo valido",
|
||||
"descripcion": strings.Repeat("x", 25), "confianza": "confirmado",
|
||||
"citas": []any{}, "hechos": []any{},
|
||||
}},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{dimSinMonto},
|
||||
"notaMetodologia": "sin cifras",
|
||||
},
|
||||
"resultados": []any{},
|
||||
}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) != 0 {
|
||||
t.Fatalf("diagnostico omitiendo montoAnualMXN debe validar: %v", errs)
|
||||
}
|
||||
if val, exists := dimSinMonto["montoAnualMXN"]; !exists || val != nil {
|
||||
t.Fatalf("omitir montoAnualMXN debe rellenar nil, obtuve exists=%v val=%v", exists, val)
|
||||
}
|
||||
|
||||
// Con montoAnualMXN y solo 1 factor -> error
|
||||
dimUnFactor := map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas en atencion",
|
||||
"factores": []any{map[string]any{"nombre": "a", "valor": 1.0, "confianza": "estimado"}},
|
||||
"montoAnualMXN": 1.0, "confianza": "estimado", "hechos": []any{},
|
||||
}
|
||||
diag["valorProblema"].(map[string]any)["dimensiones"] = []any{dimUnFactor}
|
||||
if errs := ValidarDiagnostico(diag); len(errs) == 0 {
|
||||
t.Fatal("esperaba rechazo al declarar montoAnualMXN con menos de 2 factores")
|
||||
}
|
||||
|
||||
// Redaccion estricta rechaza propiedad desconocida `precioTotal`
|
||||
red := map[string]any{
|
||||
"hero": map[string]any{"titulo": "Titulo valido", "subtitulo": strings.Repeat("x", 25)},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": strings.Repeat("x", 25)}},
|
||||
"beneficios": []any{},
|
||||
"exclusiones": []any{map[string]any{"texto": strings.Repeat("x", 20), "razon": "porque si"}},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{},
|
||||
"precioTotal": 99999,
|
||||
}
|
||||
if errs := ValidarRedaccion(red); len(errs) == 0 {
|
||||
t.Fatal("ValidarRedaccion debe rechazar propiedades desconocidas")
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── validacion.go ───────────────────────────
|
||||
|
||||
const citaPrueba = "no llevamos control de quien contesta el whatsapp el fin de semana"
|
||||
|
||||
func econPrueba() *EconomiaCotizacion {
|
||||
return &EconomiaCotizacion{
|
||||
Partidas: []PartidaEconomia{
|
||||
{Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"},
|
||||
},
|
||||
Totales: domain.TotalesCotizacion{
|
||||
SubtotalUnico: 12000, IVAUnico: 1920, TotalUnico: 13920, TotalPrimerAnio: 13920, IncluyeIVA: true,
|
||||
},
|
||||
Moneda: "MXN",
|
||||
}
|
||||
}
|
||||
|
||||
func propuestaBase() map[string]any {
|
||||
return map[string]any{
|
||||
"hechos": map[string]any{
|
||||
"citas": []any{
|
||||
map[string]any{"id": "C01", "textoLiteral": citaPrueba, "quienLoDijo": "el socio"},
|
||||
},
|
||||
"hechos": []any{
|
||||
map[string]any{"id": "H01", "enunciado": "No hay control de la atencion", "confianza": "confirmado", "citas": []any{"C01"}},
|
||||
},
|
||||
"materialesPendientes": []any{map[string]any{"texto": "Accesos al dominio", "bloqueaEntrega": true}},
|
||||
"decisionesPendientes": []any{map[string]any{"texto": "Definir responsable de atencion", "quienDecide": "el socio"}},
|
||||
"mencionesFueraDeAlcance": []any{},
|
||||
"redFlags": []any{},
|
||||
},
|
||||
"diagnostico": map[string]any{
|
||||
"hallazgos": []any{
|
||||
map[string]any{
|
||||
"id": "D01", "urgencia": "rojo", "titulo": "Prospectos sin seguimiento",
|
||||
"descripcion": "Los mensajes del fin de semana se pierden.",
|
||||
"confianza": "confirmado", "citas": []any{"C01"}, "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"valorProblema": map[string]any{
|
||||
"dimensiones": []any{
|
||||
map[string]any{
|
||||
"tipo": "tiempo", "descripcion": "Horas perdidas de atencion",
|
||||
"factores": []any{
|
||||
map[string]any{"nombre": "horas por semana", "valor": 8.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "semanas", "valor": 52.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "costo por hora", "valor": 400.0, "confianza": "estimado"},
|
||||
},
|
||||
"montoAnualMXN": 166400.0, "confianza": "estimado", "hechos": []any{"H01"},
|
||||
},
|
||||
},
|
||||
"notaMetodologia": "Ocho horas por semana a costo cargado.",
|
||||
},
|
||||
"resultados": []any{
|
||||
map[string]any{
|
||||
"enunciado": "Ningun mensaje sin respuesta en mas de 24 horas",
|
||||
"metrica": "tiempo de respuesta", "lineaBase": nil, "periodoMedicion": "mensual",
|
||||
},
|
||||
},
|
||||
},
|
||||
"redaccion": map[string]any{
|
||||
"hero": map[string]any{
|
||||
"titulo": "Propuesta de digitalizacion",
|
||||
"subtitulo": "Ordenar la atencion para dejar de perder prospectos.",
|
||||
},
|
||||
"citaDestacadaId": "C01",
|
||||
"alcance": []any{
|
||||
map[string]any{"refPartida": "P01", "descripcionResultado": "Un lugar a donde mandar a los prospectos que llegan de los anuncios."},
|
||||
},
|
||||
"beneficios": []any{
|
||||
map[string]any{"etiqueta": "Respuesta", "texto": "Cada mensaje queda registrado y con responsable.", "hallazgoId": "D01"},
|
||||
},
|
||||
"exclusiones": []any{
|
||||
map[string]any{"texto": "No incluye migrar el historico de pedidos de los ultimos 4 anos.", "razon": "Se evalua en fase 2."},
|
||||
},
|
||||
"backlogEvolucion": []any{},
|
||||
"notasInternas": []any{"El socio es quien decide."},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func tieneRegla(avisos []Aviso, regla string) bool {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func severidadRegla(avisos []Aviso, regla string) string {
|
||||
for _, a := range avisos {
|
||||
if a.Regla == regla {
|
||||
return a.Severidad
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestNormalizarTexto(t *testing.T) {
|
||||
if got := NormalizarTexto("¿Cómo estás, Juan?"); got != "como estas juan" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "como estas juan", got)
|
||||
}
|
||||
if got := NormalizarTexto(" a b "); got != "a b" {
|
||||
t.Fatalf("esperado %q, obtuve %q", "a b", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidarPropuestaTodasLasReglas(t *testing.T) {
|
||||
econ := econPrueba()
|
||||
fuentes := "El socio dijo: " + citaPrueba + ". Nada mas."
|
||||
|
||||
t.Run("propuesta limpia sin bloqueantes", func(t *testing.T) {
|
||||
avisos := ValidarPropuesta(propuestaBase(), econ, fuentes, "")
|
||||
if HayBloqueantes(avisos) {
|
||||
t.Fatalf("propuesta limpia no debe producir bloqueantes: %+v", avisos)
|
||||
}
|
||||
if len(avisos) != 0 {
|
||||
t.Fatalf("propuesta limpia no debe producir avisos: %+v", avisos)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R0 fuga de notas internas 7-gramas", func(t *testing.T) {
|
||||
interno := "el socio pidio descuento antes de entender el alcance del proyecto completo"
|
||||
|
||||
// Fuga en hero
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Contexto del proyecto: " + interno + "."
|
||||
av := ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") || severidadRegla(av, "R0") != "bloqueante" {
|
||||
t.Fatalf("R0 debe bloquear fuga en hero: %+v", av)
|
||||
}
|
||||
|
||||
// Fuga en hallazgo
|
||||
p = propuestaBase()
|
||||
p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)["descripcion"] = "Observado: " + interno + "."
|
||||
av = ValidarPropuesta(p, econ, fuentes, interno)
|
||||
if !tieneRegla(av, "R0") {
|
||||
t.Fatalf("R0 debe revisar todos los campos visibles (hallazgo): %+v", av)
|
||||
}
|
||||
|
||||
// Sin fuga -> ok
|
||||
if tieneRegla(ValidarPropuesta(propuestaBase(), econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe disparar si no hay fuga")
|
||||
}
|
||||
|
||||
// En notasInternas del propio resultado -> NO se imprime, NO dispara R0
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["notasInternas"] = []any{interno}
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, interno), "R0") {
|
||||
t.Fatal("R0 no debe quejarse de notasInternas (no se imprimen)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R2 y R2b referencias de partidas", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"].([]any)[0].(map[string]any)["refPartida"] = "P99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2") || severidadRegla(av, "R2") != "bloqueante" {
|
||||
t.Fatalf("R2 debe bloquear partida inventada P99: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["alcance"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R2b") || severidadRegla(av, "R2b") != "advertencia" {
|
||||
t.Fatalf("R2b debe advertir partida cotizada no descrita: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R3 cita destacada existe y es literal", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["citaDestacadaId"] = "C09"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") || severidadRegla(av, "R3") != "bloqueante" {
|
||||
t.Fatalf("R3 debe bloquear cita inexistente: %+v", av)
|
||||
}
|
||||
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "esto nunca lo dijo nadie en la reunion"
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R3") {
|
||||
t.Fatalf("R3 debe bloquear cita no literal: %+v", av)
|
||||
}
|
||||
|
||||
// Tolera acentos, mayusculas y puntuacion
|
||||
p = propuestaBase()
|
||||
p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "NO LLEVAMOS CONTROL, de quién contesta... el WhatsApp el fin de semana!"
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R3") {
|
||||
t.Fatal("R3 debe tolerar acentos, mayusculas y puntuacion")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R4 confirmado sin evidencia", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
h0 := p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)
|
||||
h0["citas"] = []any{}
|
||||
h0["hechos"] = []any{}
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R4") || severidadRegla(av, "R4") != "advertencia" {
|
||||
t.Fatalf("R4 debe advertir hallazgo confirmado sin citas ni hechos: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R5 aritmetica dentro de 2% y R5b sin factores confirmados", func(t *testing.T) {
|
||||
// No cuadra -> R5 bloqueante
|
||||
p := propuestaBase()
|
||||
dim := p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = 999999.0
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5") || severidadRegla(av, "R5") != "bloqueante" {
|
||||
t.Fatalf("R5 debe bloquear aritmetica inconsistente: %+v", av)
|
||||
}
|
||||
|
||||
// Cuadra por suma dentro de 2% -> sin R5
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["factores"] = []any{
|
||||
map[string]any{"nombre": "a", "valor": 10000.0, "confianza": "confirmado"},
|
||||
map[string]any{"nombre": "b", "valor": 5000.0, "confianza": "estimado"},
|
||||
}
|
||||
dim["montoAnualMXN"] = 15100.0 // diferencia < 1%
|
||||
if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R5") {
|
||||
t.Fatal("R5 debe aceptar suma dentro del margen de 2%")
|
||||
}
|
||||
|
||||
// Sin cifra (nil) -> sin R5 ni R5b
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
dim["montoAnualMXN"] = nil
|
||||
dim["factores"] = []any{}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if tieneRegla(av, "R5") || tieneRegla(av, "R5b") {
|
||||
t.Fatalf("sin montoAnualMXN no debe disparar R5 ni R5b: %+v", av)
|
||||
}
|
||||
|
||||
// Solo estimados -> R5b advertencia
|
||||
p = propuestaBase()
|
||||
dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any)
|
||||
for _, f := range dim["factores"].([]any) {
|
||||
f.(map[string]any)["confianza"] = "estimado"
|
||||
}
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R5b") || severidadRegla(av, "R5b") != "advertencia" {
|
||||
t.Fatalf("R5b debe advertir cuando ningun factor es confirmado: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("R6 hallazgoId colgante", func(t *testing.T) {
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["hallazgoId"] = "D99"
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "R6") || severidadRegla(av, "R6") != "advertencia" {
|
||||
t.Fatalf("R6 debe advertir beneficio colgante: %+v", av)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("MARCA MONEDA GARANTIA PII", func(t *testing.T) {
|
||||
// MARCA
|
||||
p := propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Lo integramos con HubSpot sin problema alguno."
|
||||
av := ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MARCA") || severidadRegla(av, "MARCA") != "bloqueante" {
|
||||
t.Fatalf("MARCA debe bloquear otro CRM: %+v", av)
|
||||
}
|
||||
|
||||
// MONEDA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Una inversion de 1,800 USD al mes para tu negocio."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "MONEDA") || severidadRegla(av, "MONEDA") != "bloqueante" {
|
||||
t.Fatalf("MONEDA debe bloquear USD: %+v", av)
|
||||
}
|
||||
|
||||
// GARANTIA
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Te garantizamos la posicion numero uno en Google."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "GARANTIA") || severidadRegla(av, "GARANTIA") != "bloqueante" {
|
||||
t.Fatalf("GARANTIA debe bloquear promesa garantizada: %+v", av)
|
||||
}
|
||||
|
||||
// PII (advertencia, no bloqueante)
|
||||
p = propuestaBase()
|
||||
p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "El sueldo de quien atiende sale muy caro hoy en dia."
|
||||
av = ValidarPropuesta(p, econ, fuentes, "")
|
||||
if !tieneRegla(av, "PII") || severidadRegla(av, "PII") != "advertencia" || HayBloqueantes(av) {
|
||||
t.Fatalf("PII debe ser advertencia no bloqueante: %+v", av)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────── pipeline.go ───────────────────────────
|
||||
|
||||
func TestEjecutarPipelineTresPasos(t *testing.T) {
|
||||
base := propuestaBase()
|
||||
var step int32
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&step, 1)
|
||||
var toolName string
|
||||
var payload any
|
||||
switch n {
|
||||
case 1:
|
||||
toolName = "registrar_hechos"
|
||||
payload = base["hechos"]
|
||||
case 2:
|
||||
toolName = "registrar_diagnostico"
|
||||
payload = base["diagnostico"]
|
||||
case 3:
|
||||
toolName = "registrar_propuesta"
|
||||
payload = base["redaccion"]
|
||||
default:
|
||||
t.Fatalf("llamada inesperada #%d", n)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "msg_" + strconv.Itoa(int(n)),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "tool_use",
|
||||
"id": "tu_" + strconv.Itoa(int(n)),
|
||||
"name": toolName,
|
||||
"input": payload,
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{
|
||||
"input_tokens": 100 * int(n),
|
||||
"output_tokens": 50 * int(n),
|
||||
"cache_read_input_tokens": 40,
|
||||
"cache_creation_input_tokens": 10,
|
||||
},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cliente := &ClienteIA{
|
||||
APIKey: "test-key",
|
||||
BaseURL: srv.URL,
|
||||
Model: "MiniMax-M3",
|
||||
HTTPClient: srv.Client(),
|
||||
Sleep: func(context.Context, time.Duration) error { return nil },
|
||||
}
|
||||
|
||||
res, err := ejecutarPipeline(
|
||||
context.Background(),
|
||||
cliente,
|
||||
ContextoEntrada{
|
||||
Transcripcion: "El socio dijo: " + citaPrueba + ".",
|
||||
Cliente: "Juan Perez",
|
||||
Empresa: "ACME",
|
||||
Proyecto: "MKT Digital",
|
||||
},
|
||||
econPrueba(),
|
||||
"nota confidencial que no debe aparecer en la propuesta final jamas",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("error en pipeline: %v", err)
|
||||
}
|
||||
if res.Modelo != "MiniMax-M3" {
|
||||
t.Fatalf("Modelo esperado MiniMax-M3, obtuve %q", res.Modelo)
|
||||
}
|
||||
if HayBloqueantes(res.Avisos) {
|
||||
t.Fatalf("no esperaba bloqueantes en pipeline limpio: %+v", res.Avisos)
|
||||
}
|
||||
if res.Contenido["hechos"] == nil || res.Contenido["diagnostico"] == nil || res.Contenido["redaccion"] == nil {
|
||||
t.Fatalf("Contenido incompleto: %+v", res.Contenido)
|
||||
}
|
||||
totalUso, ok := res.Traza["totalUso"].(UsoTokens)
|
||||
if !ok || totalUso.Entrada != 600 || totalUso.Salida != 300 || totalUso.CacheLectura != 120 || totalUso.CacheEscritura != 30 {
|
||||
t.Fatalf("Traza totalUso incorrecta: %#v", res.Traza["totalUso"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package propuesta
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// Aviso describe un hallazgo de validacion post-generacion.
|
||||
// Severidad: "bloqueante" | "advertencia".
|
||||
type Aviso struct {
|
||||
Regla string `json:"regla"`
|
||||
Severidad string `json:"severidad"`
|
||||
Mensaje string `json:"mensaje"`
|
||||
Campo string `json:"campo,omitempty"`
|
||||
}
|
||||
|
||||
// NormalizarTexto quita acentos, pasa a minusculas, elimina puntuacion y
|
||||
// colapsa espacios. Laxa a proposito para sobrevivir al ruido de transcripcion.
|
||||
func NormalizarTexto(s string) string {
|
||||
decomposed := norm.NFD.String(s)
|
||||
var b strings.Builder
|
||||
b.Grow(len(decomposed))
|
||||
for _, r := range decomposed {
|
||||
if unicode.Is(unicode.Mn, r) {
|
||||
continue
|
||||
}
|
||||
r = unicode.ToLower(r)
|
||||
if unicode.IsLetter(r) || unicode.IsNumber(r) {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
return strings.Join(strings.Fields(b.String()), " ")
|
||||
}
|
||||
|
||||
var (
|
||||
reOtroCRM = regexp.MustCompile(`(?i)\b(hubspot|salesforce|pipedrive|zoho|go\s*high\s*level|gohighlevel|clientify|kommo|monday\s*crm)\b`)
|
||||
rePromesaGarantia = regexp.MustCompile(`(?i)\bgarantiza(mos|do|da|r|remos)?\b|\baseguramos\s+(ventas|resultados|posici)`)
|
||||
reMontoUSD = regexp.MustCompile(`(?i)\b(usd|d[oóÓ]lares|dlls?)\b|\$\s*[\d,.]+\s*(usd|dls)\b`)
|
||||
reTemaSensible = regexp.MustCompile(`(?i)\b(sueldo|salario|n[oóÓ]mina|despido|demanda laboral|incapacidad|embarazo|enfermedad)\b`)
|
||||
)
|
||||
|
||||
type campoVisible struct {
|
||||
campo string
|
||||
texto string
|
||||
}
|
||||
|
||||
func getMap(m map[string]any, key string) map[string]any {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
if sub, ok := m[key].(map[string]any); ok {
|
||||
return sub
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSlice(m map[string]any, key string) []any {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
if arr, ok := m[key].([]any); ok {
|
||||
return arr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getString(m map[string]any, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
if s, ok := m[key].(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// textoVisible recopila TODOS los campos de texto que terminan impresos en el
|
||||
// documento del cliente (excluyendo notasInternas, redFlags y razon de exclusiones).
|
||||
func textoVisible(contenido map[string]any) []campoVisible {
|
||||
hechos := getMap(contenido, "hechos")
|
||||
diag := getMap(contenido, "diagnostico")
|
||||
red := getMap(contenido, "redaccion")
|
||||
hero := getMap(red, "hero")
|
||||
vp := getMap(diag, "valorProblema")
|
||||
|
||||
out := []campoVisible{
|
||||
{campo: "hero.titulo", texto: getString(hero, "titulo")},
|
||||
{campo: "hero.subtitulo", texto: getString(hero, "subtitulo")},
|
||||
{campo: "valorProblema.notaMetodologia", texto: getString(vp, "notaMetodologia")},
|
||||
}
|
||||
|
||||
citaDestID := getString(red, "citaDestacadaId")
|
||||
for _, raw := range getSlice(hechos, "citas") {
|
||||
c, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
id := getString(c, "id")
|
||||
if id != "" && id == citaDestID {
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("citas.%s.textoLiteral", id), texto: getString(c, "textoLiteral")},
|
||||
campoVisible{campo: fmt.Sprintf("citas.%s.quienLoDijo", id), texto: getString(c, "quienLoDijo")},
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(diag, "hallazgos") {
|
||||
h, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("hallazgos[%d].titulo", i), texto: getString(h, "titulo")},
|
||||
campoVisible{campo: fmt.Sprintf("hallazgos[%d].descripcion", i), texto: getString(h, "descripcion")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(vp, "dimensiones") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
texto: getString(d, "descripcion"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(diag, "resultados") {
|
||||
r, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].enunciado", i), texto: getString(r, "enunciado")},
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].metrica", i), texto: getString(r, "metrica")},
|
||||
campoVisible{campo: fmt.Sprintf("resultados[%d].periodoMedicion", i), texto: getString(r, "periodoMedicion")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "alcance") {
|
||||
a, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("alcance[%d]", i),
|
||||
texto: getString(a, "descripcionResultado"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "beneficios") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("beneficios[%d]", i),
|
||||
texto: getString(b, "etiqueta") + " " + getString(b, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "exclusiones") {
|
||||
e, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("exclusiones[%d]", i),
|
||||
texto: getString(e, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(red, "backlogEvolucion") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("backlog[%d].problema", i), texto: getString(b, "problema")},
|
||||
campoVisible{campo: fmt.Sprintf("backlog[%d].momentoSugerido", i), texto: getString(b, "momentoSugerido")},
|
||||
)
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(hechos, "materialesPendientes") {
|
||||
m, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, campoVisible{
|
||||
campo: fmt.Sprintf("materiales[%d]", i),
|
||||
texto: getString(m, "texto"),
|
||||
})
|
||||
}
|
||||
|
||||
for i, raw := range getSlice(hechos, "decisionesPendientes") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out = append(out,
|
||||
campoVisible{campo: fmt.Sprintf("decisiones[%d].texto", i), texto: getString(d, "texto")},
|
||||
campoVisible{campo: fmt.Sprintf("decisiones[%d].quienDecide", i), texto: getString(d, "quienDecide")},
|
||||
)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func ngramas(texto string, n int) map[string]struct{} {
|
||||
palabras := strings.Fields(NormalizarTexto(texto))
|
||||
out := make(map[string]struct{})
|
||||
if n <= 0 || len(palabras) < n {
|
||||
return out
|
||||
}
|
||||
for i := 0; i+n <= len(palabras); i++ {
|
||||
out[strings.Join(palabras[i:i+n], " ")] = struct{}{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func truncar(s string, max int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= max {
|
||||
return s
|
||||
}
|
||||
return string(r[:max])
|
||||
}
|
||||
|
||||
// ValidarPropuesta ejecuta las reglas deterministicas post-generacion:
|
||||
// R0, R2, R2b, R3, R4, R5, R5b, R6, MARCA, MONEDA, GARANTIA y PII.
|
||||
func ValidarPropuesta(contenido map[string]any, economia *EconomiaCotizacion, fuentesCliente string, notasInternas string) []Aviso {
|
||||
avisos := make([]Aviso, 0)
|
||||
visible := textoVisible(contenido)
|
||||
|
||||
hechos := getMap(contenido, "hechos")
|
||||
diag := getMap(contenido, "diagnostico")
|
||||
red := getMap(contenido, "redaccion")
|
||||
vp := getMap(diag, "valorProblema")
|
||||
|
||||
// ── R0 (bloqueante): fuga de notas internas del asesor (7-gramas) ──
|
||||
if strings.TrimSpace(notasInternas) != "" {
|
||||
internos := ngramas(notasInternas, 7)
|
||||
if len(internos) > 0 {
|
||||
for _, v := range visible {
|
||||
palabras := strings.Fields(NormalizarTexto(v.texto))
|
||||
for i := 0; i+7 <= len(palabras); i++ {
|
||||
g := strings.Join(palabras[i:i+7], " ")
|
||||
if _, leaked := internos[g]; leaked {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R0",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: fmt.Sprintf("Texto de las notas internas aparece en el documento del cliente: %q", g),
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── R2 (bloqueante) / R2b (advertencia): correspondencia de partidas ──
|
||||
refsReales := make(map[string]bool)
|
||||
if economia != nil {
|
||||
for _, p := range economia.Partidas {
|
||||
refsReales[p.Ref] = true
|
||||
}
|
||||
}
|
||||
refsUsadas := make(map[string]bool)
|
||||
for _, raw := range getSlice(red, "alcance") {
|
||||
a, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ref := getString(a, "refPartida")
|
||||
refsUsadas[ref] = true
|
||||
if !refsReales[ref] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R2",
|
||||
Severidad: "bloqueante",
|
||||
Campo: "alcance " + ref,
|
||||
Mensaje: fmt.Sprintf("La partida %s no existe en la cotizacion.", ref),
|
||||
})
|
||||
}
|
||||
}
|
||||
if economia != nil {
|
||||
for _, real := range economia.Partidas {
|
||||
if !refsUsadas[real.Ref] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R2b",
|
||||
Severidad: "advertencia",
|
||||
Campo: real.Ref,
|
||||
Mensaje: fmt.Sprintf("La partida %q (%s) esta cotizada pero no aparece descrita.", real.Nombre, real.Ref),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── R3 (bloqueante): cita destacada existe y aparece literal en fuentesCliente ──
|
||||
citaID := getString(red, "citaDestacadaId")
|
||||
var citaEncontrada map[string]any
|
||||
for _, raw := range getSlice(hechos, "citas") {
|
||||
c, ok := raw.(map[string]any)
|
||||
if ok && getString(c, "id") == citaID && citaID != "" {
|
||||
citaEncontrada = c
|
||||
break
|
||||
}
|
||||
}
|
||||
if citaEncontrada == nil {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R3",
|
||||
Severidad: "bloqueante",
|
||||
Campo: "citaDestacadaId",
|
||||
Mensaje: fmt.Sprintf("citaDestacadaId %s no corresponde a ninguna cita extraida.", citaID),
|
||||
})
|
||||
} else if strings.TrimSpace(fuentesCliente) != "" {
|
||||
textoLiteral := getString(citaEncontrada, "textoLiteral")
|
||||
if !strings.Contains(NormalizarTexto(fuentesCliente), NormalizarTexto(textoLiteral)) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R3",
|
||||
Severidad: "bloqueante",
|
||||
Campo: citaID,
|
||||
Mensaje: fmt.Sprintf("La cita destacada no aparece literal en las fuentes: \"%s...\"", truncar(textoLiteral, 70)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R4 (advertencia): hallazgo confirmado sin citas ni hechos ──
|
||||
idsHallazgo := make(map[string]bool)
|
||||
for i, raw := range getSlice(diag, "hallazgos") {
|
||||
h, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if id := getString(h, "id"); id != "" {
|
||||
idsHallazgo[id] = true
|
||||
}
|
||||
if getString(h, "confianza") == "confirmado" && len(getSlice(h, "citas"))+len(getSlice(h, "hechos")) == 0 {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R4",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("hallazgos[%d]", i),
|
||||
Mensaje: fmt.Sprintf("%q se declara confirmado sin citas ni hechos. Deberia ser por_validar.", getString(h, "titulo")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R5 (bloqueante) y R5b (advertencia): aritmetica y evidencia del valor anual ──
|
||||
for i, raw := range getSlice(vp, "dimensiones") {
|
||||
d, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rawMonto, exists := d["montoAnualMXN"]
|
||||
if !exists || rawMonto == nil {
|
||||
continue
|
||||
}
|
||||
m, ok := asNumber(rawMonto)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
factores := getSlice(d, "factores")
|
||||
producto := 1.0
|
||||
suma := 0.0
|
||||
confirmados := 0
|
||||
for _, fRaw := range factores {
|
||||
f, ok := fRaw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
val, _ := asNumber(f["valor"])
|
||||
producto *= val
|
||||
suma += val
|
||||
if getString(f, "confianza") == "confirmado" {
|
||||
confirmados++
|
||||
}
|
||||
}
|
||||
|
||||
base := math.Max(math.Abs(m), 1.0)
|
||||
cuadra := math.Abs(producto-m)/base < 0.02 || math.Abs(suma-m)/base < 0.02
|
||||
if !cuadra {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R5",
|
||||
Severidad: "bloqueante",
|
||||
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
Mensaje: fmt.Sprintf("montoAnualMXN %v no cuadra con sus factores (producto %v, suma %v).", m, producto, suma),
|
||||
})
|
||||
}
|
||||
if confirmados == 0 {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R5b",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i),
|
||||
Mensaje: fmt.Sprintf(
|
||||
"La cifra de %v no tiene ni un factor confirmado: descansa entera en estimaciones. Revisa el desglose antes de fiarte del ratio precio/valor.",
|
||||
m,
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── R6 (advertencia): referencias colgantes de hallazgoId en beneficios ──
|
||||
for i, raw := range getSlice(red, "beneficios") {
|
||||
b, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
hid := getString(b, "hallazgoId")
|
||||
if !idsHallazgo[hid] {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "R6",
|
||||
Severidad: "advertencia",
|
||||
Campo: fmt.Sprintf("beneficios[%d]", i),
|
||||
Mensaje: fmt.Sprintf("El beneficio apunta al hallazgo %s, que no existe.", hid),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Filtros de contenido sobre lo visible al cliente ──
|
||||
for _, v := range visible {
|
||||
if reOtroCRM.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "MARCA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Menciona un CRM que no es Bucefalo.",
|
||||
})
|
||||
}
|
||||
if reMontoUSD.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "MONEDA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Contiene un monto o referencia en USD.",
|
||||
})
|
||||
}
|
||||
if rePromesaGarantia.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "GARANTIA",
|
||||
Severidad: "bloqueante",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Promete un resultado garantizado.",
|
||||
})
|
||||
}
|
||||
if reTemaSensible.MatchString(v.texto) {
|
||||
avisos = append(avisos, Aviso{
|
||||
Regla: "PII",
|
||||
Severidad: "advertencia",
|
||||
Campo: v.campo,
|
||||
Mensaje: "Menciona un tema laboral, salarial o de salud. Revisalo antes de enviar.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return avisos
|
||||
}
|
||||
|
||||
// HayBloqueantes devuelve true si algun aviso tiene severidad "bloqueante".
|
||||
func HayBloqueantes(avisos []Aviso) bool {
|
||||
for _, a := range avisos {
|
||||
if a.Severidad == "bloqueante" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/db"
|
||||
"cotizador/internal/domain"
|
||||
"cotizador/internal/notify"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// GenerarCobros idempotently creates missing PagoRecurrente rows up to `hasta` (defaults to today MX).
|
||||
// Returns the IDs of newly inserted PagoRecurrente rows.
|
||||
func GenerarCobros(ctx context.Context, pool *pgxpool.Pool, programaID string, hasta *time.Time) ([]string, error) {
|
||||
limite := domain.HoyCalendario()
|
||||
if hasta != nil {
|
||||
y, m, d := domain.ACalendario(*hasta)
|
||||
limite = time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT "id", "monto", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin"
|
||||
FROM "ProgramaPago"
|
||||
WHERE "activo" = true
|
||||
`
|
||||
var args []any
|
||||
if programaID != "" {
|
||||
query += ` AND "id" = $1`
|
||||
args = append(args, programaID)
|
||||
}
|
||||
|
||||
rows, err := pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type prog struct {
|
||||
ID string
|
||||
Monto float64
|
||||
Frecuencia string
|
||||
DiaSemana *int
|
||||
DiaMes *int
|
||||
FechaInicio time.Time
|
||||
FechaFin *time.Time
|
||||
}
|
||||
var programas []prog
|
||||
for rows.Next() {
|
||||
var p prog
|
||||
if err := rows.Scan(&p.ID, &p.Monto, &p.Frecuencia, &p.DiaSemana, &p.DiaMes, &p.FechaInicio, &p.FechaFin); err != nil {
|
||||
continue
|
||||
}
|
||||
programas = append(programas, p)
|
||||
}
|
||||
|
||||
var creados []string
|
||||
for _, p := range programas {
|
||||
fechas := domain.FechasPeriodo(domain.ProgramaCalendario{
|
||||
Frecuencia: p.Frecuencia,
|
||||
DiaSemana: p.DiaSemana,
|
||||
DiaMes: p.DiaMes,
|
||||
FechaInicio: p.FechaInicio,
|
||||
FechaFin: p.FechaFin,
|
||||
}, limite)
|
||||
for _, f := range fechas {
|
||||
newID := db.NewID()
|
||||
var insertedID string
|
||||
err := pool.QueryRow(ctx, `
|
||||
INSERT INTO "PagoRecurrente" ("id", "programaId", "fecha", "monto", "estado", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'pendiente', NOW(), NOW())
|
||||
ON CONFLICT ("programaId", "fecha") DO NOTHING
|
||||
RETURNING "id"
|
||||
`, newID, p.ID, f, p.Monto).Scan(&insertedID)
|
||||
if err == nil && insertedID != "" {
|
||||
creados = append(creados, insertedID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return creados, nil
|
||||
}
|
||||
|
||||
// Start runs the recurring charges & reminder scheduler (20s initial delay, every 60 minutes).
|
||||
func Start(ctx context.Context, pool *pgxpool.Pool, notifier *notify.Service) {
|
||||
runOnce := func() {
|
||||
cctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
nuevos, err := GenerarCobros(cctx, pool, "", nil)
|
||||
if err != nil {
|
||||
log.Printf("[scheduler] error generando cobros: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var cubiertos []string
|
||||
if domain.HoraMexico(time.Now()) >= domain.HoraRecordatorios {
|
||||
res, err := notifier.EnviarRecordatoriosPendientes(cctx, "", false)
|
||||
if err != nil {
|
||||
log.Printf("[scheduler] error enviando recordatorios: %v", err)
|
||||
} else if res != nil {
|
||||
cubiertos = res.PagoIDsCubiertos
|
||||
if res.ClientesNotificados > 0 || res.PagosVencidosEmit > 0 {
|
||||
log.Printf("[scheduler] recordatorios=%d clientes (%d pagos), pago.vencido=%d", res.ClientesNotificados, res.PagosRecordados, res.PagosVencidosEmit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notify newly created charges not already covered by a reminder in this same tick
|
||||
var porAvisar []string
|
||||
for _, id := range nuevos {
|
||||
if !slices.Contains(cubiertos, id) {
|
||||
porAvisar = append(porAvisar, id)
|
||||
}
|
||||
}
|
||||
if len(porAvisar) > 0 {
|
||||
notifier.NotificarCobrosNuevos(cctx, porAvisar)
|
||||
log.Printf("[scheduler] %d cobro(s) nuevo(s) generados y notificados", len(porAvisar))
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(20 * time.Second):
|
||||
}
|
||||
runOnce()
|
||||
|
||||
ticker := time.NewTicker(60 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
runOnce()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,376 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// AgentKeyPreset defines a named agent API key preset.
|
||||
type AgentKeyPreset struct {
|
||||
Nombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
}
|
||||
|
||||
// DefaultAgentPresets returns the 5 standard agent API key presets matching scripts/provision-agent-keys.ts.
|
||||
func DefaultAgentPresets() []AgentKeyPreset {
|
||||
return []AgentKeyPreset{
|
||||
{
|
||||
Nombre: "sales-agent",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "jefe-operaciones",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 120,
|
||||
},
|
||||
{
|
||||
Nombre: "cobranza",
|
||||
Scopes: []string{
|
||||
"clientes:leer",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "entrega",
|
||||
Scopes: []string{
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
},
|
||||
RateLimitPerMin: 60,
|
||||
},
|
||||
{
|
||||
Nombre: "n8n-ecosystem",
|
||||
Scopes: []string{
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
},
|
||||
RateLimitPerMin: 180,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type provisionOpts struct {
|
||||
List bool
|
||||
Preset bool
|
||||
Rotate bool
|
||||
Nombre string
|
||||
Scopes []string
|
||||
RateLimitPerMin int
|
||||
HasRateLimit bool
|
||||
}
|
||||
|
||||
func parseProvisionArgs(args []string) (provisionOpts, error) {
|
||||
opts := provisionOpts{RateLimitPerMin: 60}
|
||||
for i := 0; i < len(args); i++ {
|
||||
tok := args[i]
|
||||
if !strings.HasPrefix(tok, "--") {
|
||||
continue
|
||||
}
|
||||
key := tok[2:]
|
||||
var val string
|
||||
hasEq := false
|
||||
if eq := strings.IndexByte(key, '='); eq >= 0 {
|
||||
val = key[eq+1:]
|
||||
key = key[:eq]
|
||||
hasEq = true
|
||||
}
|
||||
|
||||
nextVal := func() string {
|
||||
if hasEq {
|
||||
return val
|
||||
}
|
||||
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
|
||||
i++
|
||||
return args[i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "list":
|
||||
opts.List = true
|
||||
case "preset":
|
||||
opts.Preset = true
|
||||
case "rotate":
|
||||
opts.Rotate = true
|
||||
case "nombre":
|
||||
opts.Nombre = strings.TrimSpace(nextVal())
|
||||
case "scopes":
|
||||
raw := nextVal()
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
s := strings.TrimSpace(part)
|
||||
if s != "" {
|
||||
opts.Scopes = append(opts.Scopes, s)
|
||||
}
|
||||
}
|
||||
case "rate-limit":
|
||||
raw := strings.TrimSpace(nextVal())
|
||||
if raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err == nil && n > 0 {
|
||||
opts.RateLimitPerMin = n
|
||||
opts.HasRateLimit = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !opts.List && !opts.Preset && opts.Nombre == "" {
|
||||
return opts, errors.New("Uso: provision-keys --list | --preset [--rotate] | --nombre <nombre> --scopes <a,b> [--rate-limit 60] [--rotate]")
|
||||
}
|
||||
|
||||
if !opts.List && !opts.Preset {
|
||||
for _, sc := range opts.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
return opts, fmt.Errorf("Scope invalido: %q. Validos: %s", sc, strings.Join(auth.AgentScopes, ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
func dedupeStrings(in []string) []string {
|
||||
seen := make(map[string]struct{}, len(in))
|
||||
out := make([]string, 0, len(in))
|
||||
for _, s := range in {
|
||||
if _, ok := seen[s]; ok {
|
||||
continue
|
||||
}
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type listedKey struct {
|
||||
ID string `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Prefijo string `json:"prefijo"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin int `json:"rateLimitPerMin"`
|
||||
Activo bool `json:"activo"`
|
||||
RevokedAt *time.Time `json:"revokedAt"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type provisionResult struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Action string `json:"action"`
|
||||
ID string `json:"id"`
|
||||
Prefijo string `json:"prefijo"`
|
||||
Scopes []string `json:"scopes"`
|
||||
RateLimitPerMin int `json:"rateLimitPerMin"`
|
||||
Activo *bool `json:"activo,omitempty"`
|
||||
RawKey string `json:"rawKey,omitempty"`
|
||||
}
|
||||
|
||||
// RunProvisionKeys ports scripts/provision-agent-keys.ts to Go.
|
||||
func RunProvisionKeys(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||
return runProvisionKeysWithWriter(ctx, pool, args, os.Stdout)
|
||||
}
|
||||
|
||||
func runProvisionKeysWithWriter(ctx context.Context, pool *pgxpool.Pool, args []string, out io.Writer) error {
|
||||
opts, err := parseProvisionArgs(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.List {
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdAt"
|
||||
FROM "AgentApiKey"
|
||||
ORDER BY "createdAt" ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list agent keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys := make([]listedKey, 0)
|
||||
for rows.Next() {
|
||||
var k listedKey
|
||||
if err := rows.Scan(&k.ID, &k.Nombre, &k.Prefijo, &k.Scopes, &k.RateLimitPerMin, &k.Activo, &k.RevokedAt, &k.LastUsedAt, &k.CreatedAt); err != nil {
|
||||
return fmt.Errorf("scan agent key: %w", err)
|
||||
}
|
||||
if k.Scopes == nil {
|
||||
k.Scopes = []string{}
|
||||
}
|
||||
keys = append(keys, k)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return writeIndentedJSON(out, map[string]any{
|
||||
"ok": true,
|
||||
"keys": keys,
|
||||
})
|
||||
}
|
||||
|
||||
var targets []AgentKeyPreset
|
||||
if opts.Preset {
|
||||
targets = DefaultAgentPresets()
|
||||
} else {
|
||||
targets = []AgentKeyPreset{
|
||||
{
|
||||
Nombre: opts.Nombre,
|
||||
Scopes: opts.Scopes,
|
||||
RateLimitPerMin: opts.RateLimitPerMin,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
results := make([]provisionResult, 0, len(targets))
|
||||
for _, target := range targets {
|
||||
var existingID, existingNombre, existingPrefijo string
|
||||
var existingScopes []string
|
||||
var existingRateLimit int
|
||||
var existingActivo bool
|
||||
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo"
|
||||
FROM "AgentApiKey"
|
||||
WHERE "nombre" = $1
|
||||
`, target.Nombre).Scan(&existingID, &existingNombre, &existingPrefijo, &existingScopes, &existingRateLimit, &existingActivo)
|
||||
|
||||
exists := true
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
exists = false
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("lookup agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
|
||||
if exists && !opts.Rotate {
|
||||
activo := existingActivo
|
||||
if existingScopes == nil {
|
||||
existingScopes = []string{}
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: existingNombre,
|
||||
Action: "exists",
|
||||
ID: existingID,
|
||||
Prefijo: existingPrefijo,
|
||||
Scopes: existingScopes,
|
||||
RateLimitPerMin: existingRateLimit,
|
||||
Activo: &activo,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
var scopesFinal []string
|
||||
if len(target.Scopes) > 0 {
|
||||
scopesFinal = dedupeStrings(target.Scopes)
|
||||
} else if exists {
|
||||
scopesFinal = existingScopes
|
||||
}
|
||||
if len(scopesFinal) == 0 {
|
||||
return fmt.Errorf("Debes indicar --scopes al crear la clave %q", target.Nombre)
|
||||
}
|
||||
|
||||
rawKey, prefijo, keyHash := auth.GenerateAPIKey()
|
||||
|
||||
if exists {
|
||||
rateLimit := target.RateLimitPerMin
|
||||
if !opts.Preset && !opts.HasRateLimit && existingRateLimit > 0 {
|
||||
rateLimit = existingRateLimit
|
||||
}
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = existingRateLimit
|
||||
}
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = 60
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
UPDATE "AgentApiKey"
|
||||
SET "prefijo" = $1,
|
||||
"keyHash" = $2,
|
||||
"scopes" = $3,
|
||||
"rateLimitPerMin" = $4,
|
||||
"activo" = true,
|
||||
"revokedAt" = NULL,
|
||||
"updatedAt" = NOW()
|
||||
WHERE "id" = $5
|
||||
`, prefijo, keyHash, scopesFinal, rateLimit, existingID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("rotate agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: existingNombre,
|
||||
Action: "rotated",
|
||||
ID: existingID,
|
||||
Prefijo: prefijo,
|
||||
Scopes: scopesFinal,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RawKey: rawKey,
|
||||
})
|
||||
} else {
|
||||
newID := db.NewID()
|
||||
rateLimit := target.RateLimitPerMin
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = 60
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, true, NOW(), NOW())
|
||||
`, newID, target.Nombre, prefijo, keyHash, scopesFinal, rateLimit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create agent key %s: %w", target.Nombre, err)
|
||||
}
|
||||
results = append(results, provisionResult{
|
||||
Nombre: target.Nombre,
|
||||
Action: "created",
|
||||
ID: newID,
|
||||
Prefijo: prefijo,
|
||||
Scopes: scopesFinal,
|
||||
RateLimitPerMin: rateLimit,
|
||||
RawKey: rawKey,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return writeIndentedJSON(out, map[string]any{
|
||||
"ok": true,
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
func writeIndentedJSON(w io.Writer, v any) error {
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(w, string(b))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
"cotizador/internal/db"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type servicioRow struct {
|
||||
ID string
|
||||
Nombre string
|
||||
Fase int
|
||||
Nivel *string
|
||||
}
|
||||
|
||||
// Run executes the idempotent database seed matching prisma/seed.ts.
|
||||
func Run(ctx context.Context, pool *pgxpool.Pool, cfg *config.Config) error {
|
||||
if cfg == nil {
|
||||
cfg = &config.Config{}
|
||||
}
|
||||
|
||||
log.Println("Seeding database...")
|
||||
|
||||
// ── USERS ──
|
||||
adminEmail := strings.TrimSpace(cfg.SeedAdminEmail)
|
||||
if adminEmail == "" {
|
||||
adminEmail = "[email protected]"
|
||||
}
|
||||
adminName := strings.TrimSpace(cfg.SeedAdminName)
|
||||
if adminName == "" {
|
||||
adminName = "Administrador"
|
||||
}
|
||||
adminPassword := cfg.SeedAdminPassword
|
||||
if adminPassword == "" {
|
||||
log.Printf(` AVISO: SEED_ADMIN_PASSWORD no definida. Si el usuario %s no existe, se creara con password "admin123" — cambiala de inmediato.`, adminEmail)
|
||||
}
|
||||
rawAdminPass := adminPassword
|
||||
if rawAdminPass == "" {
|
||||
rawAdminPass = "admin123"
|
||||
}
|
||||
adminHash, err := auth.HashPassword(rawAdminPass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash password admin: %w", err)
|
||||
}
|
||||
|
||||
if adminPassword != "" {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO UPDATE SET
|
||||
"password" = EXCLUDED."password",
|
||||
"updatedAt" = NOW()
|
||||
`, db.NewID(), adminEmail, adminHash, adminName)
|
||||
} else {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO NOTHING
|
||||
`, db.NewID(), adminEmail, adminHash, adminName)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert admin user: %w", err)
|
||||
}
|
||||
|
||||
asesorEmail := strings.TrimSpace(cfg.SeedAsesorEmail)
|
||||
if asesorEmail != "" {
|
||||
asesorName := strings.TrimSpace(cfg.SeedAsesorName)
|
||||
if asesorName == "" {
|
||||
asesorName = "Asesor"
|
||||
}
|
||||
asesorPassword := cfg.SeedAsesorPass
|
||||
rawAsesorPass := asesorPassword
|
||||
if rawAsesorPass == "" {
|
||||
rawAsesorPass = "asesor123"
|
||||
}
|
||||
asesorHash, err := auth.HashPassword(rawAsesorPass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash password asesor: %w", err)
|
||||
}
|
||||
if asesorPassword != "" {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO UPDATE SET
|
||||
"password" = EXCLUDED."password",
|
||||
"updatedAt" = NOW()
|
||||
`, db.NewID(), asesorEmail, asesorHash, asesorName)
|
||||
} else {
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW())
|
||||
ON CONFLICT ("email") DO NOTHING
|
||||
`, db.NewID(), asesorEmail, asesorHash, asesorName)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert asesor user: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── CATEGORIAS (must be created BEFORE servicios for FK) ──
|
||||
categorias := DefaultCategorias()
|
||||
catMap := make(map[string]string, len(categorias))
|
||||
for _, cat := range categorias {
|
||||
var catID string
|
||||
err := pool.QueryRow(ctx, `
|
||||
INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW())
|
||||
ON CONFLICT ("nombre") DO UPDATE SET
|
||||
"color" = EXCLUDED."color",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
RETURNING "id"
|
||||
`, db.NewID(), cat.Nombre, cat.Descripcion, cat.Color, cat.Orden).Scan(&catID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert categoria %s: %w", cat.Nombre, err)
|
||||
}
|
||||
catMap[cat.Nombre] = catID
|
||||
}
|
||||
|
||||
// ── SERVICIOS CATALOGO ──
|
||||
catAlias := DefaultCatAlias()
|
||||
servicios := DefaultServicios()
|
||||
for _, s := range servicios {
|
||||
catNombre, ok := catAlias[s.Categoria]
|
||||
if !ok {
|
||||
catNombre = "Desarrollo Personalizado"
|
||||
}
|
||||
var catID *string
|
||||
if id, exists := catMap[catNombre]; exists {
|
||||
idCopy := id
|
||||
catID = &idCopy
|
||||
}
|
||||
var variante *string
|
||||
if s.Variante != "" {
|
||||
v := s.Variante
|
||||
variante = &v
|
||||
}
|
||||
var nivel *string
|
||||
if s.Nivel != "" {
|
||||
n := s.Nivel
|
||||
nivel = &n
|
||||
}
|
||||
entregablesJSON, err := json.Marshal(s.EntregablesDefault)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal entregables %s: %w", s.Nombre, err)
|
||||
}
|
||||
servicioID := ServicioID(s.Nombre, s.Orden)
|
||||
soloAdmin := IsSoloAdmin(servicioID, s.Nombre, s.SoloAdmin)
|
||||
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioCatalogo" (
|
||||
"id", "nombre", "descripcion", "fase", "tipoPago", "precioBase",
|
||||
"tiempoEntrega", "entregablesDefault", "categoriaId", "variante",
|
||||
"nivel", "activo", "soloAdmin", "orden", "createdAt", "updatedAt"
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, $8::jsonb, $9, $10,
|
||||
$11, true, $12, $13, NOW(), NOW()
|
||||
)
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"soloAdmin" = CASE WHEN EXCLUDED."soloAdmin" THEN true ELSE "ServicioCatalogo"."soloAdmin" END
|
||||
`,
|
||||
servicioID, s.Nombre, s.Descripcion, s.Fase, s.TipoPago, s.PrecioBase,
|
||||
s.TiempoEntrega, string(entregablesJSON), catID, variante,
|
||||
nivel, soloAdmin, s.Orden,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicio %s: %w", servicioID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Load all services currently in DB for package mapping (mirrors prisma.servicioCatalogo.findMany()).
|
||||
rows, err := pool.Query(ctx, `SELECT "id", "nombre", "fase", "nivel" FROM "ServicioCatalogo"`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("query servicios: %w", err)
|
||||
}
|
||||
var allServicios []servicioRow
|
||||
for rows.Next() {
|
||||
var r servicioRow
|
||||
if err := rows.Scan(&r.ID, &r.Nombre, &r.Fase, &r.Nivel); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan servicio: %w", err)
|
||||
}
|
||||
allServicios = append(allServicios, r)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("iterate servicios: %w", err)
|
||||
}
|
||||
|
||||
// ── PAQUETE GENERAL ──
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ('paquete-general', 'General', 'Paquete completo de servicios de marketing digital', true, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO NOTHING
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert paquete-general: %w", err)
|
||||
}
|
||||
|
||||
fasesGeneral := DefaultFasesGeneral()
|
||||
faseMap := make(map[int]string, len(fasesGeneral))
|
||||
for _, fg := range fasesGeneral {
|
||||
faseID := fmt.Sprintf("fase-general-%d", fg.Orden)
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, 'paquete-general', $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
`, faseID, fg.Nombre, fg.Orden)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert fase %s: %w", faseID, err)
|
||||
}
|
||||
faseMap[fg.Orden] = faseID
|
||||
}
|
||||
|
||||
for _, s := range allServicios {
|
||||
fasePaqueteID, ok := faseMap[s.Fase]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), s.ID, fasePaqueteID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicioPaquete general (%s -> %s): %w", s.ID, fasePaqueteID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── PAQUETES RECOMENDADOS PYME ──
|
||||
for _, pq := range DefaultPaquetesPyme() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, true, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"descripcion" = EXCLUDED."descripcion",
|
||||
"activo" = true,
|
||||
"updatedAt" = NOW()
|
||||
`, pq.ID, pq.Nombre, pq.Descripcion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert paquete %s: %w", pq.ID, err)
|
||||
}
|
||||
|
||||
for _, fase := range pq.Fases {
|
||||
faseID := fmt.Sprintf("fase-%s-%d", pq.ID, fase.Orden)
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"nombre" = EXCLUDED."nombre",
|
||||
"orden" = EXCLUDED."orden",
|
||||
"updatedAt" = NOW()
|
||||
`, faseID, pq.ID, fase.Nombre, fase.Orden)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert fase %s: %w", faseID, err)
|
||||
}
|
||||
|
||||
for _, ref := range fase.Servicios {
|
||||
servicioCatalogoID, err := findServicioID(allServicios, ref.Nombre, ref.Nivel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING
|
||||
`, db.NewID(), servicioCatalogoID, faseID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert servicioPaquete (%s -> %s): %w", servicioCatalogoID, faseID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── BONOS (only insert when table is empty) ──
|
||||
var bonoCount int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Bono"`).Scan(&bonoCount); err != nil {
|
||||
return fmt.Errorf("count bonos: %w", err)
|
||||
}
|
||||
if bonoCount == 0 {
|
||||
for _, bono := range DefaultBonos() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Bono" ("id", "numero", "titulo", "descripcion", "activo")
|
||||
VALUES ($1, $2, $3, $4, true)
|
||||
`, db.NewID(), bono.Numero, bono.Titulo, bono.Descripcion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert bono %d: %w", bono.Numero, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── FINANCIAMIENTO PLANES ──
|
||||
for _, plan := range DefaultFinanciamientoPlanes() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "FinanciamientoPlan" ("id", "meses", "tasa", "comision", "montoMinimo", "iva")
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT ("meses") DO NOTHING
|
||||
`, db.NewID(), plan.Meses, plan.Tasa, plan.Comision, plan.MontoMinimo, plan.IVA)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert financiamiento %d meses: %w", plan.Meses, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── CONFIGURACION (ON CONFLICT DO NOTHING to preserve production branding/bank settings) ──
|
||||
for _, c := range DefaultConfigs() {
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt")
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT ("clave") DO NOTHING
|
||||
`, db.NewID(), c.Clave, c.Valor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert configuracion %s: %w", c.Clave, err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Seed completed successfully!")
|
||||
return nil
|
||||
}
|
||||
|
||||
func findServicioID(all []servicioRow, nombre, nivel string) (string, error) {
|
||||
var matches []string
|
||||
for _, s := range all {
|
||||
sNivel := ""
|
||||
if s.Nivel != nil {
|
||||
sNivel = *s.Nivel
|
||||
}
|
||||
if s.Nombre == nombre && sNivel == nivel {
|
||||
matches = append(matches, s.ID)
|
||||
}
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
return "", fmt.Errorf("Paquete PyME: '%s' (nivel=%q) resolvio %d servicios", nombre, nivel, len(matches))
|
||||
}
|
||||
return matches[0], nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
)
|
||||
|
||||
func TestSeedDataCounts(t *testing.T) {
|
||||
categorias := DefaultCategorias()
|
||||
if len(categorias) != 7 {
|
||||
t.Fatalf("expected 7 categorias, got %d", len(categorias))
|
||||
}
|
||||
|
||||
servicios := DefaultServicios()
|
||||
if len(servicios) != 58 {
|
||||
t.Fatalf("expected 58 servicios (exact count in prisma/seed.ts), got %d", len(servicios))
|
||||
}
|
||||
|
||||
// 1 paquete-general + 6 paquetes PyME = 7 paquetes total
|
||||
paquetesPyme := DefaultPaquetesPyme()
|
||||
if len(paquetesPyme) != 6 {
|
||||
t.Fatalf("expected 6 paquetes PyME (7 total with paquete-general), got %d", len(paquetesPyme))
|
||||
}
|
||||
if len(DefaultFasesGeneral()) != 4 {
|
||||
t.Fatalf("expected 4 fases in paquete-general, got %d", len(DefaultFasesGeneral()))
|
||||
}
|
||||
|
||||
bonos := DefaultBonos()
|
||||
if len(bonos) != 6 {
|
||||
t.Fatalf("expected 6 bonos, got %d", len(bonos))
|
||||
}
|
||||
|
||||
planes := DefaultFinanciamientoPlanes()
|
||||
if len(planes) != 4 {
|
||||
t.Fatalf("expected 4 financiamiento planes, got %d", len(planes))
|
||||
}
|
||||
expectedMeses := []int{3, 6, 9, 12}
|
||||
for i, m := range expectedMeses {
|
||||
if planes[i].Meses != m {
|
||||
t.Errorf("plan[%d].Meses = %d, want %d", i, planes[i].Meses, m)
|
||||
}
|
||||
}
|
||||
|
||||
configs := DefaultConfigs()
|
||||
if len(configs) != 16 {
|
||||
t.Fatalf("expected 16 config keys, got %d", len(configs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicioIDsAndSoloAdmin(t *testing.T) {
|
||||
servicios := DefaultServicios()
|
||||
seen := make(map[string]bool, len(servicios))
|
||||
soloAdminIDs := make(map[string]bool)
|
||||
|
||||
for _, s := range servicios {
|
||||
id := ServicioID(s.Nombre, s.Orden)
|
||||
if seen[id] {
|
||||
t.Fatalf("duplicate servicio ID: %s", id)
|
||||
}
|
||||
seen[id] = true
|
||||
|
||||
if IsSoloAdmin(id, s.Nombre, s.SoloAdmin) {
|
||||
soloAdminIDs[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Verify exact known slug IDs from prisma/seed.ts
|
||||
for _, want := range []string{
|
||||
"auditoria-en-sitio-web-2",
|
||||
"configuracion-y-puesta-en-marc-12",
|
||||
"plan-mensual-crm-bucefalo-18",
|
||||
"logo-e-identidad-101",
|
||||
"estrategia-empresarial-en-ecom-100",
|
||||
} {
|
||||
if !seen[want] {
|
||||
t.Errorf("expected slug ID %q not found in DefaultServicios", want)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify soloAdmin flags on Bucefalo CRM items
|
||||
if len(soloAdminIDs) != 2 {
|
||||
t.Fatalf("expected exactly 2 soloAdmin servicios, got %d: %v", len(soloAdminIDs), soloAdminIDs)
|
||||
}
|
||||
if !soloAdminIDs["configuracion-y-puesta-en-marc-12"] {
|
||||
t.Errorf("expected configuracion-y-puesta-en-marc-12 to be soloAdmin")
|
||||
}
|
||||
if !soloAdminIDs["plan-mensual-crm-bucefalo-18"] {
|
||||
t.Errorf("expected plan-mensual-crm-bucefalo-18 to be soloAdmin")
|
||||
}
|
||||
|
||||
// Accented/case-insensitive Bucefalo detection
|
||||
if !IsSoloAdmin("otro-1", "Servicio Bucéfalo Extra", false) {
|
||||
t.Errorf("expected accented Bucéfalo name to trigger soloAdmin")
|
||||
}
|
||||
if IsSoloAdmin("auditoria-en-sitio-web-2", "Auditoria en Sitio Web", false) {
|
||||
t.Errorf("expected normal service NOT to trigger soloAdmin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoriasAndPaqueteReferences(t *testing.T) {
|
||||
catSet := make(map[string]bool)
|
||||
for _, c := range DefaultCategorias() {
|
||||
catSet[c.Nombre] = true
|
||||
}
|
||||
|
||||
catAlias := DefaultCatAlias()
|
||||
var rows []servicioRow
|
||||
for _, s := range DefaultServicios() {
|
||||
catNombre, ok := catAlias[s.Categoria]
|
||||
if !ok {
|
||||
t.Errorf("servicio %q has unknown categoria alias %q", s.Nombre, s.Categoria)
|
||||
}
|
||||
if !catSet[catNombre] {
|
||||
t.Errorf("catAlias %q -> %q not found in DefaultCategorias", s.Categoria, catNombre)
|
||||
}
|
||||
var nivelPtr *string
|
||||
if s.Nivel != "" {
|
||||
n := s.Nivel
|
||||
nivelPtr = &n
|
||||
}
|
||||
rows = append(rows, servicioRow{
|
||||
ID: ServicioID(s.Nombre, s.Orden),
|
||||
Nombre: s.Nombre,
|
||||
Fase: s.Fase,
|
||||
Nivel: nivelPtr,
|
||||
})
|
||||
}
|
||||
|
||||
// Every service referenced in all 6 PyME packages must resolve uniquely
|
||||
for _, pq := range DefaultPaquetesPyme() {
|
||||
if !strings.HasPrefix(pq.ID, "paquete-") {
|
||||
t.Errorf("unexpected paquete ID %q", pq.ID)
|
||||
}
|
||||
for _, f := range pq.Fases {
|
||||
for _, ref := range f.Servicios {
|
||||
id, err := findServicioID(rows, ref.Nombre, ref.Nivel)
|
||||
if err != nil {
|
||||
t.Errorf("paquete %s fase %d: %v", pq.ID, f.Orden, err)
|
||||
}
|
||||
if id == "" {
|
||||
t.Errorf("paquete %s fase %d: empty id for %s", pq.ID, f.Orden, ref.Nombre)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigKeysUnique(t *testing.T) {
|
||||
seen := make(map[string]bool)
|
||||
for _, c := range DefaultConfigs() {
|
||||
if seen[c.Clave] {
|
||||
t.Fatalf("duplicate config clave: %s", c.Clave)
|
||||
}
|
||||
seen[c.Clave] = true
|
||||
}
|
||||
for _, required := range []string{"razon_social", "rfc", "clabe_interbancaria", "color_primario", "color_secundario", "logo_base64", "iva"} {
|
||||
if !seen[required] {
|
||||
t.Errorf("missing required config key %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisionArgsAndPresets(t *testing.T) {
|
||||
// Presets sanity
|
||||
presets := DefaultAgentPresets()
|
||||
if len(presets) != 5 {
|
||||
t.Fatalf("expected 5 agent presets, got %d", len(presets))
|
||||
}
|
||||
for _, p := range presets {
|
||||
for _, sc := range p.Scopes {
|
||||
if !auth.IsValidScope(sc) {
|
||||
t.Errorf("preset %s has invalid scope %q", p.Nombre, sc)
|
||||
}
|
||||
if strings.Contains(sc, "aprobar") {
|
||||
t.Errorf("preset %s must NEVER contain an approval scope: %q", p.Nombre, sc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --list
|
||||
opts, err := parseProvisionArgs([]string{"--list"})
|
||||
if err != nil || !opts.List {
|
||||
t.Fatalf("expected --list to parse cleanly, got opts=%+v err=%v", opts, err)
|
||||
}
|
||||
|
||||
// --preset --rotate
|
||||
opts, err = parseProvisionArgs([]string{"--preset", "--rotate"})
|
||||
if err != nil || !opts.Preset || !opts.Rotate {
|
||||
t.Fatalf("expected --preset --rotate to parse cleanly, got opts=%+v err=%v", opts, err)
|
||||
}
|
||||
|
||||
// --nombre with valid scopes and rate limit
|
||||
opts, err = parseProvisionArgs([]string{
|
||||
"--nombre", "custom-agent",
|
||||
"--scopes", "catalogo:leer,clientes:leer",
|
||||
"--rate-limit", "90",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if opts.Nombre != "custom-agent" || len(opts.Scopes) != 2 || opts.RateLimitPerMin != 90 || !opts.HasRateLimit {
|
||||
t.Fatalf("unexpected parsed opts: %+v", opts)
|
||||
}
|
||||
|
||||
// invalid scope rejected
|
||||
_, err = parseProvisionArgs([]string{"--nombre", "bad", "--scopes", "cotizaciones:aprobar"})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for invalid approval scope")
|
||||
}
|
||||
|
||||
// missing action rejected
|
||||
_, err = parseProvisionArgs([]string{})
|
||||
if err == nil {
|
||||
t.Fatalf("expected usage error when no flags given")
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user