feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
@@ -3,6 +3,7 @@ DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=postgres
|
||||
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||
DB_NAME=cotizador_e3
|
||||
|
||||
# Auth
|
||||
@@ -12,3 +13,4 @@ JWT_SECRET=change-me-to-a-secure-jwt-secret
|
||||
# Server
|
||||
API_HOST=0.0.0.0
|
||||
API_PORT=8000
|
||||
ALLOW_LEGACY_API_KEY=false
|
||||
|
||||
+36
-441
@@ -1,457 +1,52 @@
|
||||
# Cotizador E3 — API Documentation for AI Skills
|
||||
# Cotizador — Uriel Jareth Consulting — Guía de API para Agentes
|
||||
|
||||
## Overview
|
||||
## Arquitectura unificada
|
||||
|
||||
REST API for Consultoría E3's digital marketing quotation system. Allows AI agents to manage clients, browse service catalogs, create quotations, calculate financing, generate PDF/Excel documents, and manage the full sales pipeline.
|
||||
- **API principal (Next.js `/api/**`):** `https://cotizador.urieljareth.org/api` — OpenAPI 3.1 en `GET /api/openapi.json`.
|
||||
- Incluye catálogo, clientes, cotizaciones, flujo de aprobación humana, envío por correo/WhatsApp, PDF/Excel, cobros recurrentes, claves de agentes, auditoría y webhooks HMAC-SHA256.
|
||||
- **API Python en paridad (FastAPI):** `https://cotizador-api.urieljareth.org` — Swagger en `/docs`.
|
||||
- Valida las mismas claves `AgentApiKey` (SHA-256) contra la misma PostgreSQL, aplica scopes, rate limit, auditoría (`AuditLog`), paridad de cálculo (`calculators.py`) y lectura de `/cobros/programas` y `/cobros/pagos`.
|
||||
- La vieja `API_KEY` ilimitada está desactivada por defecto (`ALLOW_LEGACY_API_KEY=false`).
|
||||
|
||||
**Base URL:** `http://localhost:8000`
|
||||
**Auth:** API Key via `X-API-Key` header or `Authorization: Bearer <key>`
|
||||
**Content-Type:** `application/json`
|
||||
**OpenAPI Spec:** `GET /openapi.json` (no auth required)
|
||||
## Autenticación y alcances (`AgentApiKey`)
|
||||
|
||||
---
|
||||
Envía la clave con prefijo `ujc_live_*` en `X-API-Key: ujc_live_...` o `Authorization: Bearer ujc_live_...`.
|
||||
|
||||
## Domain Context
|
||||
Alcances válidos (jamás existe un scope de aprobación):
|
||||
- `catalogo:leer` — catálogo, categorías, paquetes, bonos, financiamiento
|
||||
- `clientes:leer` / `clientes:escribir` — consultar, crear y editar clientes
|
||||
- `cotizaciones:leer` — listar y leer cotizaciones
|
||||
- `cotizaciones:leer_aceptadas` — solo cotizaciones en estado `aceptada` (y sus PDFs)
|
||||
- `cotizaciones:borrador` — crear y editar borradores (nunca aprobar ni cambiar estado)
|
||||
- `cotizaciones:enviar` — enviar cotizaciones **ya aprobadas** vía `POST /api/cotizaciones/:id/enviar`
|
||||
- `cobros:leer` / `cobros:registrar` — consultar programas/cobros y registrar pagos fuera del panel
|
||||
|
||||
Consultoría E3 is a digital marketing agency in Querétaro, México. Services are organized in 4 project phases:
|
||||
Headers de rate limit en respuestas de agente: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (y `Retry-After` en `429`).
|
||||
Para `POST` mutantes se soporta `Idempotency-Key` (TTL 24h; replay devuelve `X-Idempotency-Replayed: true`, cuerpo distinto devuelve `409`).
|
||||
|
||||
- **Fase 0 — Auditoría / Acompañamiento:** Initial assessments and ongoing consulting
|
||||
- **Fase 1 — Setup e Infraestructura:** One-time setup (websites, branding, CRM config)
|
||||
- **Fase 2 — Publicidad y Manejo:** Ongoing advertising and social media management
|
||||
- **Fase 3 — Contenido y SEO:** Content creation and search engine optimization
|
||||
## Flujo de aprobación humana (regla de hierro)
|
||||
|
||||
Two payment types:
|
||||
- **unico:** One-time payment
|
||||
- **mensual:** Monthly recurring payment
|
||||
Estados: `borrador` → `aprobada` → `enviada` → `aceptada` | `rechazada` | `vencida`.
|
||||
|
||||
Currency: MXN (Mexican Pesos) or USD. IVA (tax) rate: 16%.
|
||||
1. Un agente con `cotizaciones:borrador` crea la cotización con `POST /api/cotizaciones`. **Siempre** nace en `borrador`.
|
||||
2. El servidor genera un enlace firmado de un solo uso (expira en 72h) y lo envía por correo exclusivamente a Jareth (`ADMIN_NOTIFY_EMAIL`), además de emitir el webhook `cotizacion.creada` (sin exponer el token raw).
|
||||
3. Jareth aprueba desde el panel (`POST /api/cotizaciones/:id/aprobar`) o desde `/aprobar/<token>` (`POST /api/aprobar/<token>` con `{ "confirmar": true }`). Ningún agente ni asesor puede aprobar (`403` + `AuditLog`).
|
||||
4. Una vez en `aprobada` (con `aprobadaAt`), el agente con `cotizaciones:enviar` puede ejecutar `POST /api/cotizaciones/:id/enviar` con `canal: "email" | "whatsapp_chatwoot"` y opcionalmente `verificarContacto` (email o teléfono del prospecto; si no coincide → `403`). Sin aprobación previa devuelve `409`.
|
||||
|
||||
---
|
||||
## Webhooks salientes (HMAC-SHA256)
|
||||
|
||||
## Authentication
|
||||
Eventos: `cotizacion.creada`, `cotizacion.aprobada`, `cotizacion.enviada`, `cotizacion.aceptada`, `cotizacion.rechazada`, `cotizacion.vencida`, `pago.registrado`, `pago.vencido`.
|
||||
|
||||
### API Key (for agents)
|
||||
```
|
||||
X-API-Key: your-api-key-here
|
||||
```
|
||||
or
|
||||
```
|
||||
Authorization: Bearer your-api-key-here
|
||||
```
|
||||
Headers enviados:
|
||||
- `X-Cotizador-Event`
|
||||
- `X-Cotizador-Timestamp`
|
||||
- `X-Cotizador-Delivery-Id`
|
||||
- `X-Cotizador-Signature: sha256=<hmac_sha256_hex>`
|
||||
|
||||
### JWT (for human login)
|
||||
```
|
||||
POST /auth/login
|
||||
Body: { "email": "[email protected]", "password": "secret" }
|
||||
Response: { "user": { "id", "name", "email", "role" } }
|
||||
Sets cookie: cotizador-session (httpOnly, 7 days)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Endpoints Reference
|
||||
|
||||
### Health & Info
|
||||
|
||||
#### GET /health
|
||||
Health check endpoint. No auth required.
|
||||
- **Response:** `{ "status": "ok", "timestamp": "2026-05-03T..." }`
|
||||
|
||||
#### GET /api-info
|
||||
API capabilities and version info.
|
||||
- **Response:** `{ "name": "Cotizador E3 API", "version": "1.0.0", "capabilities": [...] }`
|
||||
|
||||
---
|
||||
|
||||
### Clients (Clientes)
|
||||
|
||||
#### GET /clientes
|
||||
List clients with optional search and pagination.
|
||||
- **Query params:** `?q=texto&page=1&limit=50`
|
||||
- **Response:** `{ "data": [Cliente], "meta": { "total", "page", "limit", "pages" } }`
|
||||
|
||||
#### POST /clientes
|
||||
Create a new client.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Juan Pérez",
|
||||
"empresa": "ACME Corp",
|
||||
"email": "[email protected]",
|
||||
"telefono": "4421234567"
|
||||
}
|
||||
```
|
||||
- **Response (201):** Full Cliente object with `id`
|
||||
|
||||
#### GET /clientes/{id}
|
||||
Get client details including recent quotations.
|
||||
- **Response:** Cliente object + `cotizaciones` array
|
||||
|
||||
#### PUT /clientes/{id}
|
||||
Update client information.
|
||||
- **Body:** Same as POST (all fields optional for update)
|
||||
|
||||
#### DELETE /clientes/{id}
|
||||
Delete client. Returns 409 if client has quotations.
|
||||
- **Response (200):** `{ "ok": true }`
|
||||
- **Error (409):** `{ "error": "Cliente tiene N cotizaciones asociadas" }`
|
||||
|
||||
---
|
||||
|
||||
### Service Catalog (Catálogo)
|
||||
|
||||
#### GET /catalogo
|
||||
List all active services with optional filters.
|
||||
- **Query params:** `?fase=0&tipoPago=mensual&categoriaId=xxx&q=seo`
|
||||
- **Response:** Array of ServicioCatalogo objects
|
||||
|
||||
Each service:
|
||||
```json
|
||||
{
|
||||
"id": "cuid",
|
||||
"nombre": "Posicionamiento SEO",
|
||||
"descripcion": "...",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precioBase": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregablesDefault": ["Keyword research", "On-page optimization"],
|
||||
"categoriaId": "cuid",
|
||||
"variante": null,
|
||||
"activo": true,
|
||||
"orden": 0
|
||||
}
|
||||
```
|
||||
|
||||
#### POST /catalogo
|
||||
Create a new service.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Nuevo Servicio",
|
||||
"descripcion": "Descripción del servicio",
|
||||
"fase": 1,
|
||||
"tipoPago": "unico",
|
||||
"precioBase": 5000,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregablesDefault": ["Entregable 1", "Entregable 2"],
|
||||
"categoriaId": "cuid",
|
||||
"variante": null,
|
||||
"orden": 0
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /catalogo/{id}
|
||||
Get service details with category info.
|
||||
|
||||
#### PUT /catalogo/{id}
|
||||
Update service. Same body as POST.
|
||||
|
||||
#### DELETE /catalogo/{id}
|
||||
Soft-delete if used in quotations, hard-delete otherwise.
|
||||
- **Response:** `{ "ok": true, "archived": true|false }`
|
||||
|
||||
---
|
||||
|
||||
### Categories (Categorías)
|
||||
|
||||
Available: SEO (#10b981), Marketing (#6366f1), Paid Media (#f59e0b), Desarrollo Web (#3b82f6), Automatizaciones (#8b5cf6), CRM (#ec4899), Desarrollo Personalizado (#14b8a6)
|
||||
|
||||
#### GET /categorias
|
||||
List all categories ordered by `orden`.
|
||||
|
||||
#### POST /categorias
|
||||
- **Body:** `{ "nombre": "Nueva Cat", "descripcion": "...", "color": "#6b7280", "orden": 0 }`
|
||||
|
||||
#### GET /categorias/{id}
|
||||
Get category with its services.
|
||||
|
||||
#### PUT /categorias/{id}
|
||||
- **Body:** `{ "nombre", "descripcion", "color", "orden", "activo" }`
|
||||
|
||||
#### DELETE /categorias/{id}
|
||||
Returns 409 if category has associated services.
|
||||
|
||||
---
|
||||
|
||||
### Quotations (Cotizaciones)
|
||||
|
||||
#### GET /cotizaciones
|
||||
List quotations with filters.
|
||||
- **Query params:** `?estado=borrador&asesorId=xxx&clienteId=xxx&q=texto&desde=2026-01-01&hasta=2026-12-31&page=1&limit=50`
|
||||
- **Response:** Array with full relations (cliente, asesor, servicios+catalogo, planBucefalo)
|
||||
|
||||
#### POST /cotizaciones
|
||||
Create a complete quotation. Auto-creates client if not found.
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"numero": "UJ2605AG001",
|
||||
"fecha": "2026-05-03",
|
||||
"vigencia": "2026-05-24",
|
||||
"moneda": "MXN",
|
||||
"tipoCambio": "NA",
|
||||
"proyecto": "MKT Digital",
|
||||
"esquemaPago": "Pago Unico/Mensual",
|
||||
"incluirBonos": false,
|
||||
"incluirFinanciamiento": false,
|
||||
"observaciones": "",
|
||||
"asesorId": "cuid",
|
||||
"cliente": {
|
||||
"nombre": "Juan Pérez",
|
||||
"empresa": "ACME Corp",
|
||||
"email": "[email protected]",
|
||||
"telefono": "4421234567"
|
||||
},
|
||||
"servicios": [
|
||||
{
|
||||
"catalogoId": "cuid",
|
||||
"nombre": "SEO On-Page",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precio": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregables": ["Keyword research", "On-page SEO"]
|
||||
}
|
||||
],
|
||||
"planBucefalo": {
|
||||
"nivel": "basico",
|
||||
"precio": 1000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /cotizaciones/{id}
|
||||
Get quotation with all relations.
|
||||
|
||||
#### PUT /cotizaciones/{id}
|
||||
Update quotation. Replaces all services in a transaction.
|
||||
- **Body:** Same as POST without `numero` and `asesorId`. Optional `estado`.
|
||||
|
||||
#### DELETE /cotizaciones/{id}
|
||||
Hard-delete with cascade.
|
||||
|
||||
#### PATCH /cotizaciones/{id}/precio
|
||||
Update price of a single service.
|
||||
- **Body:** `{ "servicioId": "cuid", "precio": 7500 }`
|
||||
|
||||
#### PATCH /cotizaciones/{id}/estado
|
||||
Change quotation status.
|
||||
- **Body:** `{ "estado": "enviada" }` — `borrador`, `enviada`, `aprobada`, `rechazada`
|
||||
|
||||
#### POST /cotizaciones/{id}/duplicate
|
||||
Duplicate quotation as new copy in `borrador` state.
|
||||
|
||||
---
|
||||
|
||||
### Packages (Paquetes)
|
||||
|
||||
#### GET /paquetes
|
||||
List active packages with nested phases and services.
|
||||
|
||||
#### POST /paquetes
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"nombre": "Paquete Básico",
|
||||
"descripcion": "...",
|
||||
"fases": [
|
||||
{ "nombre": "Auditoría", "orden": 0 },
|
||||
{ "nombre": "Setup", "orden": 1 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /paquetes/{id}
|
||||
Get package with full nested structure.
|
||||
|
||||
#### PUT /paquetes/{id}
|
||||
- **Body:** `{ "nombre", "descripcion", "activo" }`
|
||||
|
||||
#### DELETE /paquetes/{id}
|
||||
Hard-delete with cascade.
|
||||
|
||||
#### POST /paquetes/{id}/manage
|
||||
Multi-action endpoint:
|
||||
- `{ "action": "addFase", "nombre": "Fase 3", "orden": 2 }`
|
||||
- `{ "action": "updateFase", "faseId": "cuid", "nombre": "New Name", "orden": 1 }`
|
||||
- `{ "action": "deleteFase", "faseId": "cuid" }`
|
||||
- `{ "action": "addServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
||||
- `{ "action": "removeServicio", "servicioCatalogoId": "cuid", "fasePaqueteId": "cuid" }`
|
||||
|
||||
---
|
||||
|
||||
### Configuration (Configuración)
|
||||
|
||||
Allowed keys: `color_primario`, `color_secundario`, `logo_base64`, `razon_social`, `rfc`, `domicilio_fiscal`, `cuenta_nacional`, `clabe_interbancaria`, `cuenta_internacional`, `cuenta_internacional_swift`, `hora_centinela`, `anualidad_hosting`, `iva`, `terminos_condiciones`, `no_incluye`, `notas_adicionales`
|
||||
|
||||
#### GET /configuracion
|
||||
- **Response:** `{ "color_primario": "#2563eb", "razon_social": "...", ... }`
|
||||
|
||||
#### PUT /configuracion
|
||||
Bulk upsert. Only whitelisted keys processed.
|
||||
- **Body:** `{ "color_primario": "#ff0000", "razon_social": "Nuevo Nombre" }`
|
||||
|
||||
---
|
||||
|
||||
### Bonuses (Bonos)
|
||||
|
||||
Available: Centinela Web, Workshop Buyer Persona, Workshop Propuesta de Valor, Membresía Premium, Mes Gratis CRM, Script de Ventas
|
||||
|
||||
#### GET /bonos
|
||||
|
||||
---
|
||||
|
||||
### Financing (Financiamiento)
|
||||
|
||||
| Months | Rate | Commission | Min Amount |
|
||||
|--------|------|------------|------------|
|
||||
| 3 | 7.7% | 2.5% | $300 |
|
||||
| 6 | 10.7% | 2.5% | $600 |
|
||||
| 9 | 13.7% | 2.5% | $900 |
|
||||
| 12 | 16.7% | 2.5% | $1,200 |
|
||||
|
||||
#### GET /financiamiento/planes
|
||||
|
||||
#### POST /financiamiento/calcular
|
||||
- **Body:** `{ "monto": 50000, "meses": 6 }`
|
||||
- **Response:** `{ "pagoMensual", "ivaMensual", "totalMensual", "comisionTotal", "granTotal" }`
|
||||
|
||||
#### GET /financiamiento/simulacion/{cotizacion_id}
|
||||
Auto-calculate financing for existing quotation.
|
||||
|
||||
---
|
||||
|
||||
### Export
|
||||
|
||||
#### POST /export/pdf — PDF from draft data
|
||||
#### GET /export/pdf/{id} — PDF from saved quotation
|
||||
#### POST /export/excel — Excel from draft data
|
||||
#### GET /export/excel/{id} — Excel from saved quotation
|
||||
#### GET /export/catalogo — CSV of active services
|
||||
#### GET /export/catalogo/plantilla — CSV import template
|
||||
|
||||
---
|
||||
|
||||
### Import
|
||||
|
||||
#### POST /import/catalogo
|
||||
Bulk import services from CSV. `multipart/form-data` with `file` field.
|
||||
- **Response:** `{ "creados": 5, "omitidos": 2, "errores": [...] }`
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
### Quotation Number
|
||||
Format: `UJ{YY}{MM}{AsesorInitials}{sequence}` — e.g., `UJ2605AG001`
|
||||
|
||||
### Quotation Validity
|
||||
15 business days from issue (excludes Sat/Sun).
|
||||
|
||||
### CRM Bucefalo Plans
|
||||
basico=$1,000/mes, estandar=$3,500/mes, premium=$4,500/mes, empresarial=$7,500/mes
|
||||
|
||||
### Client Deduplication
|
||||
Matched by `(nombre, empresa)` pair.
|
||||
|
||||
### Service Soft-Delete
|
||||
If referenced by quotations → `activo=false`. Otherwise hard-delete.
|
||||
|
||||
### Financing Formula
|
||||
```
|
||||
comisionTotal = monto × comision%
|
||||
montoConComision = monto + comisionTotal
|
||||
pagoMensual = montoConComision × (1 + tasa) / meses
|
||||
ivaMensual = pagoMensual × 0.16
|
||||
totalMensual = pagoMensual + ivaMensual
|
||||
granTotal = totalMensual × meses
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Responses
|
||||
|
||||
### Success (paginated)
|
||||
```json
|
||||
{
|
||||
"data": [...],
|
||||
"meta": { "total": 45, "page": 1, "limit": 50, "pages": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
### Error
|
||||
```json
|
||||
{ "error": "Message", "detail": "Details", "code": "ERROR_CODE" }
|
||||
```
|
||||
|
||||
### HTTP Codes
|
||||
200=OK, 201=Created, 204=No Content, 400=Bad Request, 401=Unauthorized, 404=Not Found, 409=Conflict, 500=Server Error
|
||||
|
||||
---
|
||||
|
||||
## Agent Workflows
|
||||
|
||||
### Create quotation
|
||||
```
|
||||
1. GET /catalogo?fase=0 → audit services
|
||||
2. GET /catalogo?fase=1 → setup services
|
||||
3. GET /catalogo?fase=2&tipoPago=mensual → ongoing services
|
||||
4. POST /financiamiento/calcular → simulate payments
|
||||
5. POST /cotizaciones → create quotation
|
||||
6. GET /export/pdf/{id} → generate PDF
|
||||
```
|
||||
|
||||
### Review pipeline
|
||||
```
|
||||
1. GET /cotizaciones?estado=borrador → pending
|
||||
2. GET /cotizaciones?estado=enviada → awaiting
|
||||
3. GET /cotizaciones?estado=aprobada → won
|
||||
```
|
||||
|
||||
### Negotiate price
|
||||
```
|
||||
1. GET /cotizaciones/{id} → current state
|
||||
2. PATCH /cotizaciones/{id}/precio → adjust price
|
||||
3. GET /export/pdf/{id} → regenerate PDF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Integration — removed (2026-07-28)
|
||||
|
||||
The `/mcp` endpoint and the `api/app/mcp/` package no longer exist. Agents should use
|
||||
the REST endpoints documented above, authenticating with `X-API-Key` or a Bearer JWT.
|
||||
|
||||
It was removed for three reasons: nobody was using it; its transport had been broken
|
||||
for some time (it constructed a `StreamableHTTPServerTransport` per request with no
|
||||
session handling, returning 500 even with valid credentials); and its unpinned SDK
|
||||
took the entire API down in production when `mcp` released 2.0.0 and dropped
|
||||
`Server.list_tools()`.
|
||||
|
||||
To bring it back: `git show edb500f5:api/app/mcp/server.py`. Pin the SDK to the 1.x
|
||||
series and fix the transport before mounting it again.
|
||||
|
||||
---
|
||||
|
||||
## Environment
|
||||
|
||||
```
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_NAME=cotizador_e3
|
||||
API_KEY=your-secret-api-key
|
||||
JWT_SECRET=your-jwt-secret
|
||||
```
|
||||
|
||||
## Run
|
||||
## Provisioning de claves (operador)
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
||||
# Swagger: http://localhost:8000/docs
|
||||
# ReDoc: http://localhost:8000/redoc
|
||||
# OpenAPI: http://localhost:8000/openapi.json
|
||||
npx tsx scripts/provision-agent-keys.ts --preset
|
||||
npx tsx scripts/provision-agent-keys.ts --list
|
||||
npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate
|
||||
```
|
||||
|
||||
+294
-13
@@ -1,18 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Header, HTTPException, status
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.config import settings
|
||||
from app.database import get_pool
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_DAYS = 7
|
||||
|
||||
# Rate limiter en memoria con ventana deslizante de 60 segundos por key_id.
|
||||
_WINDOW_SECS = 60.0
|
||||
_rate_buckets: dict[str, list[float]] = {}
|
||||
|
||||
|
||||
def hash_secret(raw: str) -> str:
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
@@ -36,30 +51,296 @@ def decode_token(token: str) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
async def get_api_key(x_api_key: str | None = Header(None)) -> str | None:
|
||||
if x_api_key and x_api_key == settings.API_KEY:
|
||||
return x_api_key
|
||||
return None
|
||||
def _client_ip(request: Request | None) -> str | None:
|
||||
if request is None:
|
||||
return None
|
||||
xff = request.headers.get("x-forwarded-for")
|
||||
if xff:
|
||||
first = xff.split(",")[0].strip()
|
||||
if first:
|
||||
return first
|
||||
xri = request.headers.get("x-real-ip")
|
||||
if xri:
|
||||
return xri.strip()
|
||||
return request.client.host if request.client else None
|
||||
|
||||
|
||||
def check_rate_limit(key_id: str, limit_per_min: int, now: float | None = None) -> dict[str, Any]:
|
||||
now_ts = now if now is not None else time.time()
|
||||
limit = max(1, limit_per_min or 60)
|
||||
cutoff = now_ts - _WINDOW_SECS
|
||||
stamps = [ts for ts in _rate_buckets.get(key_id, []) if ts > cutoff]
|
||||
|
||||
if len(stamps) >= limit:
|
||||
oldest = stamps[0] if stamps else now_ts
|
||||
reset_ts = oldest + _WINDOW_SECS
|
||||
retry_after = max(1, math.ceil(reset_ts - now_ts))
|
||||
_rate_buckets[key_id] = stamps
|
||||
return {
|
||||
"ok": False,
|
||||
"limit": limit,
|
||||
"remaining": 0,
|
||||
"reset_at": math.ceil(reset_ts),
|
||||
"retry_after": retry_after,
|
||||
}
|
||||
|
||||
stamps.append(now_ts)
|
||||
_rate_buckets[key_id] = stamps
|
||||
oldest = stamps[0] if stamps else now_ts
|
||||
reset_ts = oldest + _WINDOW_SECS
|
||||
return {
|
||||
"ok": True,
|
||||
"limit": limit,
|
||||
"remaining": max(0, limit - len(stamps)),
|
||||
"reset_at": math.ceil(reset_ts),
|
||||
"retry_after": 0,
|
||||
}
|
||||
|
||||
|
||||
async def registrar_auditoria(
|
||||
conn,
|
||||
auth: dict | None,
|
||||
accion: str,
|
||||
recurso_tipo: str,
|
||||
recurso_id: str | None = None,
|
||||
exito: bool = True,
|
||||
detalle: dict[str, Any] | None = None,
|
||||
ip: str | None = None,
|
||||
) -> None:
|
||||
"""Registra una entrada en AuditLog (best-effort; nunca tumba el request)."""
|
||||
try:
|
||||
actor_tipo = "system"
|
||||
actor_id: str | None = None
|
||||
actor_nombre = "system"
|
||||
|
||||
if auth:
|
||||
atype = auth.get("auth_type")
|
||||
if atype == "jwt":
|
||||
actor_tipo = "user"
|
||||
actor_id = auth.get("userId")
|
||||
actor_nombre = auth.get("email") or auth.get("name") or str(actor_id or "user")
|
||||
elif atype == "agent":
|
||||
actor_tipo = "agent"
|
||||
actor_id = auth.get("key_id")
|
||||
actor_nombre = auth.get("nombre") or "agent"
|
||||
elif atype == "legacy_api_key":
|
||||
actor_tipo = "system"
|
||||
actor_nombre = "legacy_api_key"
|
||||
|
||||
ip_final = ip or (auth.get("ip") if auth else None)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "AuditLog"
|
||||
(id, "actorTipo", "actorId", "actorNombre", accion, "recursoTipo",
|
||||
"recursoId", ip, exito, detalle, "createdAt")
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW())
|
||||
""",
|
||||
uuid.uuid4().hex[:25],
|
||||
actor_tipo,
|
||||
actor_id,
|
||||
actor_nombre,
|
||||
accion,
|
||||
recurso_tipo,
|
||||
recurso_id,
|
||||
ip_final,
|
||||
exito,
|
||||
json.dumps(detalle) if detalle is not None else None,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _validate_agent_key(raw_key: str, ip: str | None) -> dict | None:
|
||||
pool = await get_pool()
|
||||
key_hash = hash_secret(raw_key)
|
||||
row = await pool.fetchrow(
|
||||
"""
|
||||
SELECT id, nombre, prefijo, scopes, "rateLimitPerMin", "lastUsedAt"
|
||||
FROM "AgentApiKey"
|
||||
WHERE "keyHash" = $1 AND activo = true AND "revokedAt" IS NULL
|
||||
""",
|
||||
key_hash,
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
|
||||
rl = check_rate_limit(row["id"], row["rateLimitPerMin"])
|
||||
actor = {
|
||||
"auth_type": "agent",
|
||||
"key_id": row["id"],
|
||||
"nombre": row["nombre"],
|
||||
"prefijo": row["prefijo"],
|
||||
"scopes": list(row["scopes"] or []),
|
||||
"rate_limit": row["rateLimitPerMin"],
|
||||
"ip": ip,
|
||||
}
|
||||
if not rl["ok"]:
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
actor,
|
||||
"auth.rate_limit",
|
||||
"api",
|
||||
exito=False,
|
||||
detalle={"limit": rl["limit"]},
|
||||
ip=ip,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Limite de peticiones por minuto excedido",
|
||||
headers={
|
||||
"X-RateLimit-Limit": str(rl["limit"]),
|
||||
"X-RateLimit-Remaining": "0",
|
||||
"X-RateLimit-Reset": str(rl["reset_at"]),
|
||||
"Retry-After": str(rl["retry_after"]),
|
||||
},
|
||||
)
|
||||
|
||||
last_used = row["lastUsedAt"]
|
||||
now_dt = datetime.now(timezone.utc)
|
||||
if last_used is None or (
|
||||
now_dt - (last_used.replace(tzinfo=timezone.utc) if last_used.tzinfo is None else last_used)
|
||||
).total_seconds() > 60:
|
||||
try:
|
||||
await pool.execute(
|
||||
'UPDATE "AgentApiKey" SET "lastUsedAt" = NOW() WHERE id = $1',
|
||||
row["id"],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return actor
|
||||
|
||||
|
||||
async def require_auth(
|
||||
request: Request,
|
||||
authorization: str | None = Header(None),
|
||||
x_api_key: str | None = Header(None),
|
||||
) -> dict:
|
||||
if x_api_key and x_api_key == settings.API_KEY:
|
||||
return {"auth_type": "api_key"}
|
||||
ip = _client_ip(request)
|
||||
bearer_token: str | None = None
|
||||
|
||||
if authorization:
|
||||
scheme, _, token = authorization.partition(" ")
|
||||
if scheme.lower() == "bearer" and token:
|
||||
payload = decode_token(token)
|
||||
if scheme.lower() == "bearer" and token.strip():
|
||||
bearer_token = token.strip()
|
||||
# 1. Intentar JWT humano primero
|
||||
payload = decode_token(bearer_token)
|
||||
if payload:
|
||||
return {"auth_type": "jwt", **payload}
|
||||
if x_api_key == settings.API_KEY:
|
||||
return {"auth_type": "api_key"}
|
||||
if payload.get("role") == "cliente":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Acceso restringido al panel de cliente",
|
||||
)
|
||||
return {"auth_type": "jwt", "ip": ip, **payload}
|
||||
|
||||
raw_key = (x_api_key or "").strip() or bearer_token
|
||||
if raw_key:
|
||||
# 2. Validar contra AgentApiKey en PostgreSQL (SHA-256)
|
||||
agent_actor = await _validate_agent_key(raw_key, ip)
|
||||
if agent_actor:
|
||||
return agent_actor
|
||||
|
||||
# 3. Compatibilidad legacy SOLO si ALLOW_LEGACY_API_KEY=true explicitamente
|
||||
if settings.ALLOW_LEGACY_API_KEY and raw_key == settings.API_KEY:
|
||||
return {"auth_type": "legacy_api_key", "scopes": [], "ip": ip}
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or missing authentication credentials",
|
||||
detail="Credenciales de autenticacion invalidas o ausentes",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
def require_scope(*required_scopes: str, mode: str = "any"):
|
||||
async def _checker(
|
||||
request: Request,
|
||||
auth: dict = Depends(require_auth),
|
||||
) -> dict:
|
||||
atype = auth.get("auth_type")
|
||||
if atype in ("jwt", "legacy_api_key"):
|
||||
return auth
|
||||
|
||||
scopes = set(auth.get("scopes") or [])
|
||||
ok = (
|
||||
all(s in scopes for s in required_scopes)
|
||||
if mode == "all"
|
||||
else any(s in scopes for s in required_scopes)
|
||||
)
|
||||
if not ok:
|
||||
pool = await get_pool()
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"auth.scope_insuficiente",
|
||||
"api",
|
||||
exito=False,
|
||||
detalle={
|
||||
"path": request.url.path,
|
||||
"requiredScopes": list(required_scopes),
|
||||
"actorScopes": list(scopes),
|
||||
},
|
||||
ip=auth.get("ip"),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Alcance insuficiente. Requerido: {', '.join(required_scopes)}",
|
||||
)
|
||||
return auth
|
||||
|
||||
return _checker
|
||||
|
||||
|
||||
async def require_staff_human(
|
||||
request: Request,
|
||||
auth: dict = Depends(require_auth),
|
||||
) -> dict:
|
||||
atype = auth.get("auth_type")
|
||||
if atype == "jwt" and auth.get("role") != "cliente":
|
||||
return auth
|
||||
if atype == "legacy_api_key":
|
||||
return auth
|
||||
|
||||
pool = await get_pool()
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"auth.staff_requerido",
|
||||
"api",
|
||||
exito=False,
|
||||
detalle={"path": request.url.path, "auth_type": atype},
|
||||
ip=auth.get("ip"),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Accion restringida a personal humano",
|
||||
)
|
||||
|
||||
|
||||
async def require_admin_human(
|
||||
request: Request,
|
||||
auth: dict = Depends(require_auth),
|
||||
) -> dict:
|
||||
if auth.get("auth_type") == "jwt" and auth.get("role") == "admin":
|
||||
return auth
|
||||
|
||||
pool = await get_pool()
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"auth.admin_requerido",
|
||||
"api",
|
||||
exito=False,
|
||||
detalle={"path": request.url.path, "auth_type": auth.get("auth_type")},
|
||||
ip=auth.get("ip"),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Accion restringida exclusivamente a un administrador humano",
|
||||
)
|
||||
|
||||
|
||||
def es_agente_solo_aceptadas(auth: dict) -> bool:
|
||||
if auth.get("auth_type") != "agent":
|
||||
return False
|
||||
scopes = set(auth.get("scopes") or [])
|
||||
return "cotizaciones:leer_aceptadas" in scopes and "cotizaciones:leer" not in scopes
|
||||
|
||||
@@ -6,8 +6,10 @@ class Settings(BaseSettings):
|
||||
DB_PORT: int = 5432
|
||||
DB_USER: str = "postgres"
|
||||
DB_PASSWORD: str = "postgres"
|
||||
# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||
DB_NAME: str = "cotizador_e3"
|
||||
API_KEY: str = "change-me-to-a-secure-random-key"
|
||||
ALLOW_LEGACY_API_KEY: bool = False
|
||||
JWT_SECRET: str = "change-me-to-a-secure-jwt-secret"
|
||||
API_HOST: str = "0.0.0.0"
|
||||
API_PORT: int = 8000
|
||||
|
||||
@@ -41,9 +41,9 @@ class HealthResponse(BaseModel):
|
||||
|
||||
|
||||
class APIInfoResponse(BaseModel):
|
||||
name: str = "Cotizador E3 API"
|
||||
name: str = "Cotizador — Uriel Jareth Consulting API"
|
||||
version: str = "1.0.0"
|
||||
description: str = "API para sistema de cotizaciones de marketing digital"
|
||||
description: str = "API para el sistema de cotizaciones de Uriel Jareth Consulting"
|
||||
capabilities: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ ALLOWED_CONFIG_KEYS: set[str] = {
|
||||
"logo_base64",
|
||||
"razon_social",
|
||||
"rfc",
|
||||
"domicilio_fiscal",
|
||||
"domicilio_fiscal", # Opcional interno; no se imprime en documentos generados
|
||||
"cuenta_nacional",
|
||||
"clabe_interbancaria",
|
||||
"cuenta_internacional",
|
||||
@@ -28,7 +28,7 @@ class ConfigUpdate(BaseModel):
|
||||
description="Key-value config pairs. Only whitelisted keys are processed.",
|
||||
json_schema_extra={
|
||||
"examples": [
|
||||
{"color_primario": "#ff0000", "razon_social": "Nueva Empresa SA de CV"}
|
||||
{"color_primario": "#0400C4", "razon_social": "Uriel Jareth Consulting"}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
@@ -5,6 +5,8 @@ from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
ESTADOS_PATTERN = "^(borrador|aprobada|enviada|aceptada|rechazada|vencida)$"
|
||||
|
||||
|
||||
class ServicioCotizadoInput(BaseModel):
|
||||
catalogoId: str = Field(..., min_length=1, description="ID del servicio del catálogo o 'custom-...' para partidas personalizadas")
|
||||
@@ -14,14 +16,12 @@ class ServicioCotizadoInput(BaseModel):
|
||||
precio: float = Field(..., ge=0, description="Precio (puede diferir del precioBase)")
|
||||
tiempoEntrega: str
|
||||
entregables: list[str] = Field(default_factory=list)
|
||||
# Partidas por tiempo (sin catálogo). modeloCobro: "fijo" | "horas" | "retainer".
|
||||
esPersonalizado: bool = False
|
||||
horas: float | None = Field(None, ge=0)
|
||||
tarifaHora: float | None = Field(None, ge=0)
|
||||
modeloCobro: str | None = Field(None, pattern="^(fijo|horas|retainer)$")
|
||||
modeloCobro: str | None = Field(None, pattern="^(fijo|horas|retainer|demanda)$")
|
||||
montoMinimo: float | None = Field(None, ge=0)
|
||||
horasIncluidas: float | None = Field(None, ge=0)
|
||||
# Doble propuesta: "1" | "2" | "ambas". None en cotizaciones normales.
|
||||
opcion: str | None = Field(None, pattern="^(1|2|ambas)$")
|
||||
|
||||
|
||||
@@ -50,55 +50,18 @@ class CotizacionCreate(BaseModel):
|
||||
moneda: str = Field("MXN", pattern="^(MXN|USD)$")
|
||||
tipoCambio: str = "NA"
|
||||
proyecto: str = "MKT Digital"
|
||||
esquemaPago: str = Field("Pago Unico/Mensual", pattern="^(Pago Unico|Mensual|Pago Unico/Mensual)$")
|
||||
esquemaPago: str = Field("Pago Unico/Mensual", pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$")
|
||||
incluirBonos: bool = False
|
||||
incluirFinanciamiento: bool = False
|
||||
incluirIva: bool = True
|
||||
esDoble: bool = False
|
||||
opciones: dict[str, MetaOpcionInput] | None = None
|
||||
observaciones: str = ""
|
||||
asesorId: str = Field(..., min_length=1)
|
||||
asesorId: str | None = None
|
||||
cliente: ClienteInput
|
||||
servicios: list[ServicioCotizadoInput] = Field(..., min_length=1)
|
||||
planBucefalo: PlanBucefaloInput | None = None
|
||||
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"examples": [
|
||||
{
|
||||
"numero": "UJ2605AG001",
|
||||
"fecha": "2026-05-03",
|
||||
"vigencia": "2026-05-24",
|
||||
"moneda": "MXN",
|
||||
"tipoCambio": "NA",
|
||||
"proyecto": "MKT Digital",
|
||||
"esquemaPago": "Pago Unico/Mensual",
|
||||
"incluirBonos": False,
|
||||
"incluirFinanciamiento": False,
|
||||
"observaciones": "",
|
||||
"asesorId": "cuid-asesor",
|
||||
"cliente": {
|
||||
"nombre": "Juan Pérez",
|
||||
"empresa": "ACME Corp",
|
||||
"email": "[email protected]",
|
||||
"telefono": "4421234567",
|
||||
},
|
||||
"servicios": [
|
||||
{
|
||||
"catalogoId": "cuid-servicio",
|
||||
"nombre": "SEO On-Page",
|
||||
"fase": 3,
|
||||
"tipoPago": "mensual",
|
||||
"precio": 2900,
|
||||
"tiempoEntrega": "7 - 14 dias",
|
||||
"entregables": ["Keyword research"],
|
||||
}
|
||||
],
|
||||
"planBucefalo": {"nivel": "basico", "precio": 1000},
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CotizacionUpdate(BaseModel):
|
||||
fecha: datetime | None = None
|
||||
@@ -106,20 +69,21 @@ class CotizacionUpdate(BaseModel):
|
||||
moneda: str | None = Field(None, pattern="^(MXN|USD)$")
|
||||
tipoCambio: str | None = None
|
||||
proyecto: str | None = None
|
||||
esquemaPago: str | None = Field(None, pattern="^(Pago Unico|Mensual|Pago Unico/Mensual)$")
|
||||
esquemaPago: str | None = Field(None, pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$")
|
||||
incluirBonos: bool | None = None
|
||||
incluirFinanciamiento: bool | None = None
|
||||
incluirIva: bool | None = None
|
||||
esDoble: bool | None = None
|
||||
opciones: dict[str, MetaOpcionInput] | None = None
|
||||
observaciones: str | None = None
|
||||
estado: str | None = Field(None, pattern="^(borrador|enviada|aprobada|rechazada)$")
|
||||
estado: str | None = Field(None, pattern=ESTADOS_PATTERN)
|
||||
cliente: ClienteInput | None = None
|
||||
servicios: list[ServicioCotizadoInput] | None = None
|
||||
planBucefalo: PlanBucefaloInput | None = None
|
||||
|
||||
|
||||
class CambiarEstadoRequest(BaseModel):
|
||||
estado: str = Field(..., pattern="^(borrador|enviada|aprobada|rechazada)$")
|
||||
estado: str = Field(..., pattern=ESTADOS_PATTERN)
|
||||
|
||||
|
||||
class ActualizarPrecioRequest(BaseModel):
|
||||
@@ -139,11 +103,23 @@ class CotizacionResponse(BaseModel):
|
||||
estado: str
|
||||
incluirBonos: bool
|
||||
incluirFinanciamiento: bool
|
||||
incluirIva: bool = True
|
||||
esDoble: bool = False
|
||||
opcionesMetadata: dict[str, Any] | None = None
|
||||
observaciones: str | None
|
||||
clienteId: str
|
||||
asesorId: str
|
||||
aprobadaPorId: str | None = None
|
||||
aprobadaAt: datetime | None = None
|
||||
aprobacionMetodo: str | None = None
|
||||
enviadaAt: datetime | None = None
|
||||
enviadaPor: str | None = None
|
||||
enviadaCanal: str | None = None
|
||||
enviadaDestino: str | None = None
|
||||
aceptadaAt: datetime | None = None
|
||||
rechazadaAt: datetime | None = None
|
||||
vencidaAt: datetime | None = None
|
||||
creadaPorAgente: str | None = None
|
||||
createdAt: datetime
|
||||
updatedAt: datetime
|
||||
cliente: dict[str, Any] | None = None
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.models.export_ import BonoResponse
|
||||
from app.services.calculators import BONOS
|
||||
|
||||
@@ -10,5 +10,5 @@ router = APIRouter(prefix="/bonos", tags=["Bonos"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[BonoResponse])
|
||||
async def get_bonos(_auth: dict = Depends(require_auth)):
|
||||
async def get_bonos(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [BonoResponse(**b) for b in BONOS]
|
||||
|
||||
@@ -5,7 +5,7 @@ import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.dependencies import get_db
|
||||
from app.models.catalogo import (
|
||||
ServicioCatalogoCreate,
|
||||
@@ -63,7 +63,7 @@ def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse:
|
||||
)
|
||||
async def list_catalogo(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
fase: int | None = Query(None, ge=0, le=3),
|
||||
tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"),
|
||||
categoriaId: str | None = Query(None),
|
||||
@@ -121,7 +121,7 @@ async def list_catalogo(
|
||||
async def create_catalogo(
|
||||
body: ServicioCatalogoCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
if body.categoriaId:
|
||||
cat = await db.fetchrow(
|
||||
@@ -168,7 +168,7 @@ async def create_catalogo(
|
||||
async def get_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
@@ -195,7 +195,7 @@ async def update_catalogo(
|
||||
servicio_id: str,
|
||||
body: ServicioCatalogoUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
@@ -265,7 +265,7 @@ async def update_catalogo(
|
||||
async def delete_catalogo(
|
||||
servicio_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow(
|
||||
'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id
|
||||
|
||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
|
||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/categorias", tags=["Categorias"])
|
||||
|
||||
@router.get("", response_model=list[CategoriaResponse])
|
||||
async def list_categorias(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
@@ -33,7 +33,7 @@ async def list_categorias(
|
||||
)
|
||||
async def create_categoria(
|
||||
body: CategoriaCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -64,7 +64,7 @@ async def create_categoria(
|
||||
)
|
||||
async def get_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
@@ -93,7 +93,7 @@ async def get_categoria(
|
||||
async def update_categoria(
|
||||
categoria_id: str,
|
||||
body: CategoriaUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
@@ -166,7 +166,7 @@ async def update_categoria(
|
||||
)
|
||||
async def delete_categoria(
|
||||
categoria_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
|
||||
@@ -5,7 +5,7 @@ import math
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.dependencies import PaginationParams, get_db
|
||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||
from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse
|
||||
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/clientes", tags=["Clientes"])
|
||||
)
|
||||
async def list_clientes(
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:leer")),
|
||||
pagination: PaginationParams = Depends(PaginationParams),
|
||||
q: str | None = Query(None, description="Search by nombre, empresa, or email"),
|
||||
):
|
||||
@@ -79,7 +79,7 @@ async def list_clientes(
|
||||
async def create_cliente(
|
||||
body: ClienteCreate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:escribir")),
|
||||
):
|
||||
row = await db.fetchrow(
|
||||
'INSERT INTO "Cliente" (nombre, empresa, email, telefono) '
|
||||
@@ -109,7 +109,7 @@ async def create_cliente(
|
||||
async def get_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:leer")),
|
||||
):
|
||||
row = await db.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not row:
|
||||
@@ -146,7 +146,7 @@ async def update_cliente(
|
||||
cliente_id: str,
|
||||
body: ClienteUpdate,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("clientes:escribir")),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
@@ -192,7 +192,7 @@ async def update_cliente(
|
||||
async def delete_cliente(
|
||||
cliente_id: str,
|
||||
db: Connection = Depends(get_db),
|
||||
auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id)
|
||||
if not existing:
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.auth import require_scope
|
||||
from app.dependencies import get_db, parse_date
|
||||
|
||||
router = APIRouter(prefix="/cobros", tags=["Cobros"])
|
||||
|
||||
|
||||
@router.get("/programas", summary="Listar programas de cobro recurrente")
|
||||
async def list_programas_cobro(
|
||||
activo: bool | None = Query(None),
|
||||
clienteId: str | None = Query(None),
|
||||
db: Connection = Depends(get_db),
|
||||
_auth: dict = Depends(require_scope("cobros:leer")),
|
||||
):
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if activo is not None:
|
||||
conditions.append(f"p.activo = ${idx}")
|
||||
params.append(activo)
|
||||
idx += 1
|
||||
if clienteId:
|
||||
conditions.append(f'p."clienteId" = ${idx}')
|
||||
params.append(clienteId)
|
||||
idx += 1
|
||||
|
||||
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
||||
rows = await db.fetch(
|
||||
f"""
|
||||
SELECT p.*,
|
||||
c.nombre AS cliente_nombre,
|
||||
c.empresa AS cliente_empresa,
|
||||
(SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p.id) AS pagos_count
|
||||
FROM "ProgramaPago" p
|
||||
JOIN "Cliente" c ON c.id = p."clienteId"
|
||||
{where}
|
||||
ORDER BY p.activo DESC, p."createdAt" DESC
|
||||
""",
|
||||
*params,
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"clienteId": r["clienteId"],
|
||||
"cotizacionId": r["cotizacionId"],
|
||||
"concepto": r["concepto"],
|
||||
"monto": float(r["monto"]),
|
||||
"moneda": r["moneda"],
|
||||
"frecuencia": r["frecuencia"],
|
||||
"diaSemana": r["diaSemana"],
|
||||
"diaMes": r["diaMes"],
|
||||
"fechaInicio": r["fechaInicio"].isoformat() if r["fechaInicio"] else None,
|
||||
"fechaFin": r["fechaFin"].isoformat() if r["fechaFin"] else None,
|
||||
"activo": r["activo"],
|
||||
"cliente": {
|
||||
"id": r["clienteId"],
|
||||
"nombre": r["cliente_nombre"],
|
||||
"empresa": r["cliente_empresa"],
|
||||
},
|
||||
"_count": {"pagos": int(r["pagos_count"])},
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.get("/pagos", summary="Listar cobros recurrentes con filtros")
|
||||
async def list_pagos_cobro(
|
||||
estado: str | None = Query(None, description="pendiente | en_revision | verificado | rechazado | anulado | por_pagar"),
|
||||
clienteId: str | None = Query(None),
|
||||
programaId: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
db: Connection = Depends(get_db),
|
||||
_auth: dict = Depends(require_scope("cobros:leer")),
|
||||
):
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if estado == "por_pagar":
|
||||
conditions.append("pr.estado IN ('pendiente', 'rechazado')")
|
||||
elif estado:
|
||||
conditions.append(f"pr.estado = ${idx}")
|
||||
params.append(estado)
|
||||
idx += 1
|
||||
|
||||
if clienteId:
|
||||
conditions.append(f'p."clienteId" = ${idx}')
|
||||
params.append(clienteId)
|
||||
idx += 1
|
||||
|
||||
if programaId:
|
||||
conditions.append(f'pr."programaId" = ${idx}')
|
||||
params.append(programaId)
|
||||
idx += 1
|
||||
|
||||
desde_dt = parse_date(desde)
|
||||
if desde_dt:
|
||||
conditions.append(f"pr.fecha >= ${idx}")
|
||||
params.append(desde_dt)
|
||||
idx += 1
|
||||
|
||||
hasta_dt = parse_date(hasta)
|
||||
if hasta_dt:
|
||||
conditions.append(f"pr.fecha <= ${idx}")
|
||||
params.append(hasta_dt)
|
||||
idx += 1
|
||||
|
||||
where = "WHERE " + " AND ".join(conditions) if conditions else ""
|
||||
rows = await db.fetch(
|
||||
f"""
|
||||
SELECT pr.*,
|
||||
p.concepto AS programa_concepto,
|
||||
p.moneda AS programa_moneda,
|
||||
p."clienteId" AS programa_cliente_id,
|
||||
c.nombre AS cliente_nombre,
|
||||
c.empresa AS cliente_empresa
|
||||
FROM "PagoRecurrente" pr
|
||||
JOIN "ProgramaPago" p ON p.id = pr."programaId"
|
||||
JOIN "Cliente" c ON c.id = p."clienteId"
|
||||
{where}
|
||||
ORDER BY pr.fecha DESC
|
||||
""",
|
||||
*params,
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"programaId": r["programaId"],
|
||||
"fecha": r["fecha"].isoformat() if r["fecha"] else None,
|
||||
"monto": float(r["monto"]),
|
||||
"estado": r["estado"],
|
||||
"verificadoAt": r["verificadoAt"].isoformat() if r["verificadoAt"] else None,
|
||||
"rechazadoAt": r["rechazadoAt"].isoformat() if r["rechazadoAt"] else None,
|
||||
"rechazoMotivo": r["rechazoMotivo"],
|
||||
"ultimoRecordatorioAt": r["ultimoRecordatorioAt"].isoformat() if r["ultimoRecordatorioAt"] else None,
|
||||
"recordatoriosEnviados": r["recordatoriosEnviados"],
|
||||
"nota": r["nota"],
|
||||
"programa": {
|
||||
"concepto": r["programa_concepto"],
|
||||
"moneda": r["programa_moneda"],
|
||||
"cliente": {
|
||||
"id": r["programa_cliente_id"],
|
||||
"nombre": r["cliente_nombre"],
|
||||
"empresa": r["cliente_empresa"],
|
||||
},
|
||||
},
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
@@ -6,14 +6,14 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS
|
||||
from app.models.common import ErrorResponse, OkResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/configuracion", tags=["Configuración"])
|
||||
|
||||
|
||||
@router.get("", response_model=ConfigResponse)
|
||||
async def get_configuracion(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch("SELECT clave, valor FROM Configuracion")
|
||||
@@ -24,7 +24,7 @@ async def get_configuracion(
|
||||
@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}})
|
||||
async def update_configuracion(
|
||||
body: ConfigUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
allowed = body.get_allowed()
|
||||
|
||||
+384
-98
@@ -6,7 +6,13 @@ from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.auth import require_auth
|
||||
from app.auth import (
|
||||
es_agente_solo_aceptadas,
|
||||
registrar_auditoria,
|
||||
require_auth,
|
||||
require_scope,
|
||||
require_staff_human,
|
||||
)
|
||||
from app.database import get_pool
|
||||
from app.dependencies import PaginationParams, parse_date
|
||||
from app.models.common import Meta, OkResponse, PaginatedResponse
|
||||
@@ -26,9 +32,14 @@ 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."""
|
||||
async def _insert_servicio_cotizado(
|
||||
conn,
|
||||
cotizacion_id: str,
|
||||
svc,
|
||||
bucefalo_servicio_id,
|
||||
now,
|
||||
es_doble: bool = False,
|
||||
) -> None:
|
||||
es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-")
|
||||
|
||||
if es_personalizado:
|
||||
@@ -39,8 +50,8 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
catalogo_id = svc.catalogoId
|
||||
|
||||
modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo")
|
||||
# Doble propuesta: por defecto "ambas"; None en cotizaciones normales.
|
||||
opcion = (svc.opcion or "ambas") if es_doble else None
|
||||
precio_final = 0 if modelo_cobro == "demanda" else svc.precio
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -64,7 +75,7 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
opcion,
|
||||
svc.fase,
|
||||
svc.tipoPago,
|
||||
svc.precio,
|
||||
precio_final,
|
||||
svc.tiempoEntrega,
|
||||
json.dumps(svc.entregables),
|
||||
None,
|
||||
@@ -73,7 +84,6 @@ async def _insert_servicio_cotizado(conn, cotizacion_id: str, svc, bucefalo_serv
|
||||
|
||||
|
||||
def _parse_json(val):
|
||||
"""asyncpg devuelve columnas jsonb como str; las parsea a dict/list."""
|
||||
if isinstance(val, str):
|
||||
try:
|
||||
return json.loads(val)
|
||||
@@ -86,6 +96,7 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=
|
||||
d = dict(cot)
|
||||
if "opcionesMetadata" in d:
|
||||
d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"])
|
||||
d.pop("observacionesInternas", None)
|
||||
d["cliente"] = dict(cliente) if cliente else None
|
||||
d["asesor"] = dict(asesor) if asesor else None
|
||||
d["servicios"] = [dict(s) for s in servicios] if servicios else []
|
||||
@@ -93,8 +104,6 @@ def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=
|
||||
return d
|
||||
|
||||
|
||||
# LEFT JOIN: los servicios personalizados no tienen servicioCatalogoId y un JOIN
|
||||
# interno los dejaría fuera de la respuesta. COALESCE conserva el nombre custom.
|
||||
_SERVICIOS_SQL = """
|
||||
SELECT sc.*, sc."servicioCatalogoId" as "catalogoId",
|
||||
COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId"
|
||||
@@ -119,8 +128,6 @@ async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None:
|
||||
|
||||
|
||||
async def _fetch_cotizaciones_full(conn, cot_rows) -> list[dict]:
|
||||
"""Versión batch de _fetch_cotizacion_full: 4 queries en total para toda la
|
||||
página en lugar de 4 por cotización (evita N+1 en el listado)."""
|
||||
if not cot_rows:
|
||||
return []
|
||||
|
||||
@@ -193,7 +200,7 @@ async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. GET /cotizaciones — List with filters + pagination
|
||||
# 1. GET /cotizaciones
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("", response_model=PaginatedResponse[CotizacionResponse])
|
||||
async def list_cotizaciones(
|
||||
@@ -204,17 +211,33 @@ async def list_cotizaciones(
|
||||
q: str | None = Query(None),
|
||||
desde: str | None = Query(None),
|
||||
hasta: str | None = Query(None),
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
solo_aceptadas = es_agente_solo_aceptadas(auth)
|
||||
if solo_aceptadas and estado and estado != "aceptada":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.leer_bloqueado",
|
||||
"cotizacion",
|
||||
exito=False,
|
||||
detalle={"estadoSolicitado": estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Tu clave solo permite consultar cotizaciones aceptadas",
|
||||
)
|
||||
|
||||
estado_efectivo = "aceptada" if solo_aceptadas else estado
|
||||
|
||||
conditions: list[str] = []
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
if estado:
|
||||
conditions.append(f'c.estado = ${idx}')
|
||||
params.append(estado)
|
||||
if estado_efectivo:
|
||||
conditions.append(f"c.estado = ${idx}")
|
||||
params.append(estado_efectivo)
|
||||
idx += 1
|
||||
if asesorId:
|
||||
conditions.append(f'c."asesorId" = ${idx}')
|
||||
@@ -226,18 +249,18 @@ async def list_cotizaciones(
|
||||
idx += 1
|
||||
if q:
|
||||
conditions.append(
|
||||
f'(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})'
|
||||
f"(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})"
|
||||
)
|
||||
params.append(f"%{q}%")
|
||||
idx += 1
|
||||
desde_dt = parse_date(desde)
|
||||
if desde_dt:
|
||||
conditions.append(f'c.fecha >= ${idx}')
|
||||
conditions.append(f"c.fecha >= ${idx}")
|
||||
params.append(desde_dt)
|
||||
idx += 1
|
||||
hasta_dt = parse_date(hasta)
|
||||
if hasta_dt:
|
||||
conditions.append(f'c.fecha <= ${idx}')
|
||||
conditions.append(f"c.fecha <= ${idx}")
|
||||
params.append(hasta_dt)
|
||||
idx += 1
|
||||
|
||||
@@ -263,7 +286,6 @@ async def list_cotizaciones(
|
||||
)
|
||||
|
||||
cotizaciones = await _fetch_cotizaciones_full(pool, rows)
|
||||
|
||||
pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0
|
||||
|
||||
return PaginatedResponse(
|
||||
@@ -273,12 +295,29 @@ async def list_cotizaciones(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. POST /cotizaciones — Create
|
||||
# 2. POST /cotizaciones — Create (SIEMPRE borrador)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.post("", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(require_auth)):
|
||||
async def create_cotizacion(
|
||||
body: CotizacionCreate,
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
asesor_id = body.asesorId
|
||||
if not asesor_id:
|
||||
if auth.get("auth_type") == "jwt" and auth.get("userId"):
|
||||
asesor_id = auth["userId"]
|
||||
else:
|
||||
admin = await conn.fetchrow(
|
||||
'SELECT id FROM "User" WHERE role = \'admin\' ORDER BY "createdAt" ASC LIMIT 1'
|
||||
)
|
||||
if not admin:
|
||||
raise HTTPException(status_code=500, detail="No hay usuario administrador configurado")
|
||||
asesor_id = admin["id"]
|
||||
|
||||
creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None
|
||||
|
||||
async with conn.transaction():
|
||||
cliente_id = await _find_or_create_cliente(
|
||||
conn,
|
||||
@@ -293,13 +332,15 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
opciones_json = None
|
||||
if body.esDoble and body.opciones:
|
||||
opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO "Cotizacion"
|
||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||
"creadaPorAgente", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18)
|
||||
""",
|
||||
cot_id,
|
||||
body.numero,
|
||||
@@ -311,16 +352,17 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
body.esquemaPago,
|
||||
body.incluirBonos,
|
||||
body.incluirFinanciamiento,
|
||||
body.incluirIva,
|
||||
body.esDoble,
|
||||
opciones_json,
|
||||
body.observaciones or None,
|
||||
cliente_id,
|
||||
body.asesorId,
|
||||
asesor_id,
|
||||
creada_por_agente,
|
||||
now,
|
||||
)
|
||||
|
||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||
|
||||
for svc in body.servicios:
|
||||
await _insert_servicio_cotizado(conn, cot_id, svc, bucefalo_servicio_id, now, body.esDoble)
|
||||
|
||||
@@ -338,32 +380,58 @@ async def create_cotizacion(body: CotizacionCreate, _auth: dict = Depends(requir
|
||||
now,
|
||||
)
|
||||
|
||||
row = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id)
|
||||
result = dict(row)
|
||||
result["opcionesMetadata"] = _parse_json(result.get("opcionesMetadata"))
|
||||
return result
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.crear",
|
||||
"cotizacion",
|
||||
recurso_id=cot_id,
|
||||
exito=True,
|
||||
detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. GET /cotizaciones/{id} — Get with relations
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def get_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
pool = await get_pool()
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
if not full:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
full = await _fetch_cotizacion_full(pool, cot_id)
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. PUT /cotizaciones/{id} — Update
|
||||
# 3. GET /cotizaciones/{id}
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.get("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def get_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
if not full:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if es_agente_solo_aceptadas(auth) and full["estado"] != "aceptada":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.leer_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": full["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Tu clave solo permite consultar cotizaciones aceptadas",
|
||||
)
|
||||
return full
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. PUT /cotizaciones/{id}
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.put("/{cotizacion_id}", response_model=CotizacionResponse)
|
||||
async def update_cotizacion(
|
||||
cotizacion_id: str,
|
||||
body: CotizacionUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
@@ -371,6 +439,58 @@ async def update_cotizacion(
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if auth.get("auth_type") == "agent":
|
||||
if existing["estado"] != "borrador":
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.editar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": existing["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes solo pueden editar cotizaciones en borrador",
|
||||
)
|
||||
if body.estado is not None and body.estado != "borrador":
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": existing["estado"], "intento": body.estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes no pueden cambiar el estado de la cotización",
|
||||
)
|
||||
|
||||
if body.estado is not None and body.estado != existing["estado"]:
|
||||
# Si un humano intenta cambiar estado en PUT, exige las mismas reglas que PATCH /estado
|
||||
if body.estado == "aprobada" and not (auth.get("auth_type") == "jwt" and auth.get("role") == "admin"):
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"intento": "aprobada"},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede aprobar una cotización",
|
||||
)
|
||||
if body.estado == "enviada" and (existing["estado"] != "aprobada" or existing["aprobadaAt"] is None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="La cotización debe estar aprobada antes de marcarse como enviada",
|
||||
)
|
||||
|
||||
async with conn.transaction():
|
||||
cliente_id = existing["clienteId"]
|
||||
if body.cliente:
|
||||
@@ -386,54 +506,55 @@ async def update_cotizacion(
|
||||
params: list = []
|
||||
idx = 1
|
||||
|
||||
def _add(field: str, col: str, val):
|
||||
def _add(col: str, val):
|
||||
nonlocal idx
|
||||
if val is not None:
|
||||
updates.append(f'{col} = ${idx}')
|
||||
params.append(val)
|
||||
idx += 1
|
||||
updates.append(f'{col} = ${idx}')
|
||||
params.append(val)
|
||||
idx += 1
|
||||
|
||||
_add("fecha", "fecha", body.fecha)
|
||||
_add("vigencia", "vigencia", body.vigencia)
|
||||
_add("moneda", "moneda", body.moneda)
|
||||
_add("tipoCambio", '"tipoCambio"', body.tipoCambio)
|
||||
_add("proyecto", "proyecto", body.proyecto)
|
||||
_add("esquemaPago", '"esquemaPago"', body.esquemaPago)
|
||||
_add("incluirBonos", '"incluirBonos"', body.incluirBonos)
|
||||
_add("incluirFinanciamiento", '"incluirFinanciamiento"', body.incluirFinanciamiento)
|
||||
_add("esDoble", '"esDoble"', body.esDoble)
|
||||
_add("observaciones", "observaciones", body.observaciones)
|
||||
_add("estado", "estado", body.estado)
|
||||
|
||||
es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"]
|
||||
if body.fecha is not None:
|
||||
_add("fecha", body.fecha)
|
||||
if body.vigencia is not None:
|
||||
_add("vigencia", body.vigencia)
|
||||
if body.moneda is not None:
|
||||
_add("moneda", body.moneda)
|
||||
if body.tipoCambio is not None:
|
||||
_add('"tipoCambio"', body.tipoCambio)
|
||||
if body.proyecto is not None:
|
||||
_add("proyecto", body.proyecto)
|
||||
if body.esquemaPago is not None:
|
||||
_add('"esquemaPago"', body.esquemaPago)
|
||||
if body.incluirBonos is not None:
|
||||
_add('"incluirBonos"', body.incluirBonos)
|
||||
if body.incluirFinanciamiento is not None:
|
||||
_add('"incluirFinanciamiento"', body.incluirFinanciamiento)
|
||||
if body.incluirIva is not None:
|
||||
_add('"incluirIva"', body.incluirIva)
|
||||
if body.esDoble is not None:
|
||||
# opcionesMetadata se sincroniza con esDoble: dict (json) si doble, NULL si no.
|
||||
meta_json = None
|
||||
if es_doble_final and body.opciones:
|
||||
meta_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()})
|
||||
updates.append(f'"opcionesMetadata" = ${idx}')
|
||||
params.append(meta_json)
|
||||
idx += 1
|
||||
|
||||
_add('"esDoble"', body.esDoble)
|
||||
if body.opciones is not None:
|
||||
_add('"opcionesMetadata"', json.dumps({k: v.model_dump() for k, v in body.opciones.items()}))
|
||||
if body.observaciones is not None:
|
||||
_add("observaciones", body.observaciones)
|
||||
if body.estado is not None and auth.get("auth_type") != "agent":
|
||||
_add("estado", body.estado)
|
||||
if cliente_id != existing["clienteId"]:
|
||||
updates.append(f'"clienteId" = ${idx}')
|
||||
params.append(cliente_id)
|
||||
idx += 1
|
||||
_add('"clienteId"', cliente_id)
|
||||
|
||||
if updates:
|
||||
updates.append(f'"updatedAt" = ${idx}')
|
||||
params.append(datetime.now(timezone.utc))
|
||||
idx += 1
|
||||
updates.append('"updatedAt" = NOW()')
|
||||
params.append(cotizacion_id)
|
||||
await conn.execute(
|
||||
f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}',
|
||||
*params,
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"]
|
||||
|
||||
if body.servicios is not None:
|
||||
await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id)
|
||||
bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn)
|
||||
now = datetime.now(timezone.utc)
|
||||
for svc in body.servicios:
|
||||
await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final)
|
||||
|
||||
@@ -442,7 +563,6 @@ async def update_cotizacion(
|
||||
'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1',
|
||||
cotizacion_id,
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
if existing_plan:
|
||||
await conn.execute(
|
||||
'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4',
|
||||
@@ -470,20 +590,40 @@ async def update_cotizacion(
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
return full
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.actualizar",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
)
|
||||
|
||||
return await _fetch_cotizacion_full(pool, cotizacion_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. DELETE /cotizaciones/{id}
|
||||
# 5. DELETE /cotizaciones/{id} (solo personal humano)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.delete("/{cotizacion_id}", response_model=OkResponse)
|
||||
async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
async def delete_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_staff_human),
|
||||
):
|
||||
pool = await get_pool()
|
||||
existing = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
existing = await pool.fetchrow('SELECT id, numero FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
await pool.execute('DELETE FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.eliminar",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
detalle={"numero": existing["numero"]},
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@@ -494,13 +634,28 @@ async def delete_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_au
|
||||
async def update_precio_servicio(
|
||||
cotizacion_id: str,
|
||||
body: ActualizarPrecioRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
cot = await pool.fetchrow('SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
cot = await pool.fetchrow('SELECT id, estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not cot:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
if auth.get("auth_type") == "agent" and cot["estado"] != "borrador":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.editar_precio_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"estadoActual": cot["estado"]},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes solo pueden editar precios en cotizaciones en borrador",
|
||||
)
|
||||
|
||||
svc = await pool.fetchrow(
|
||||
'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2',
|
||||
body.servicioId,
|
||||
@@ -518,13 +673,13 @@ async def update_precio_servicio(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. PATCH /cotizaciones/{id}/estado
|
||||
# 7. PATCH /cotizaciones/{id}/estado (PARIDAD ESTRICTA DE APROBACIÓN)
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.patch("/{cotizacion_id}/estado", response_model=OkResponse)
|
||||
async def cambiar_estado(
|
||||
cotizacion_id: str,
|
||||
body: CambiarEstadoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
auth: dict = Depends(require_auth),
|
||||
):
|
||||
if body.estado not in ESTADOS_COTIZACION:
|
||||
raise HTTPException(
|
||||
@@ -533,13 +688,127 @@ async def cambiar_estado(
|
||||
)
|
||||
|
||||
pool = await get_pool()
|
||||
result = await pool.execute(
|
||||
'UPDATE "Cotizacion" SET estado = $1, "updatedAt" = NOW() WHERE id = $2',
|
||||
body.estado,
|
||||
cotizacion_id,
|
||||
)
|
||||
if result == "UPDATE 0":
|
||||
existing = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
|
||||
# REGLA DE HIERRO: Ningún agente puede cambiar estado (ni aprobar ni enviar por este endpoint).
|
||||
if auth.get("auth_type") == "agent":
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": existing["estado"], "intento": body.estado},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Los agentes no pueden aprobar ni cambiar el estado directamente. Usa el flujo de aprobación humana y POST /api/cotizaciones/:id/enviar.",
|
||||
)
|
||||
|
||||
es_admin = auth.get("auth_type") == "jwt" and auth.get("role") == "admin"
|
||||
actual = existing["estado"]
|
||||
nuevo = body.estado
|
||||
|
||||
if nuevo == "aprobada":
|
||||
if not es_admin:
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
"cotizacion.aprobar_bloqueado",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=False,
|
||||
detalle={"actual": actual, "intento": nuevo},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede aprobar una cotización",
|
||||
)
|
||||
if actual != "borrador":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Solo se puede aprobar una cotización en borrador (estado actual: {actual})",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'aprobada',
|
||||
"aprobadaPorId" = $1,
|
||||
"aprobadaAt" = NOW(),
|
||||
"aprobacionMetodo" = 'web_admin',
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $2
|
||||
""",
|
||||
auth.get("userId"),
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo == "enviada":
|
||||
if actual != "aprobada" or existing["aprobadaAt"] is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="La cotización debe estar aprobada antes de marcarse como enviada",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'enviada',
|
||||
"enviadaAt" = NOW(),
|
||||
"enviadaCanal" = 'manual',
|
||||
"enviadaPor" = $1,
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $2
|
||||
""",
|
||||
f"user:{auth.get('email') or auth.get('userId')}",
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo == "borrador":
|
||||
if not es_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Solo un administrador humano puede regresar a borrador",
|
||||
)
|
||||
await pool.execute(
|
||||
"""
|
||||
UPDATE "Cotizacion"
|
||||
SET estado = 'borrador',
|
||||
"aprobadaPorId" = NULL,
|
||||
"aprobadaAt" = NULL,
|
||||
"aprobacionMetodo" = NULL,
|
||||
"updatedAt" = NOW()
|
||||
WHERE id = $1
|
||||
""",
|
||||
cotizacion_id,
|
||||
)
|
||||
elif nuevo in ("aceptada", "rechazada", "vencida"):
|
||||
if actual != "enviada":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Solo se puede pasar a {nuevo} desde estado enviada (estado actual: {actual})",
|
||||
)
|
||||
col_map = {
|
||||
"aceptada": '"aceptadaAt"',
|
||||
"rechazada": '"rechazadaAt"',
|
||||
"vencida": '"vencidaAt"',
|
||||
}
|
||||
col = col_map[nuevo]
|
||||
await pool.execute(
|
||||
f'UPDATE "Cotizacion" SET estado = $1, {col} = NOW(), "updatedAt" = NOW() WHERE id = $2',
|
||||
nuevo,
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
await registrar_auditoria(
|
||||
pool,
|
||||
auth,
|
||||
f"cotizacion.estado_{nuevo}",
|
||||
"cotizacion",
|
||||
recurso_id=cotizacion_id,
|
||||
exito=True,
|
||||
detalle={"anterior": actual, "nuevo": nuevo},
|
||||
)
|
||||
return OkResponse(ok=True)
|
||||
|
||||
|
||||
@@ -547,7 +816,10 @@ async def cambiar_estado(
|
||||
# 8. POST /cotizaciones/{id}/duplicate
|
||||
# ---------------------------------------------------------------------------
|
||||
@router.post("/{cotizacion_id}/duplicate", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require_auth)):
|
||||
async def duplicate_cotizacion(
|
||||
cotizacion_id: str,
|
||||
auth: dict = Depends(require_scope("cotizaciones:borrador")),
|
||||
):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
@@ -563,6 +835,8 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
cotizacion_id,
|
||||
)
|
||||
|
||||
creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None
|
||||
|
||||
async with conn.transaction():
|
||||
now = datetime.now(timezone.utc)
|
||||
new_id = _cuid()
|
||||
@@ -572,9 +846,10 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
"""
|
||||
INSERT INTO "Cotizacion"
|
||||
(id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago",
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "esDoble", "opcionesMetadata",
|
||||
observaciones, "clienteId", "asesorId", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$16)
|
||||
estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble",
|
||||
"opcionesMetadata", observaciones, "clienteId", "asesorId",
|
||||
"creadaPorAgente", "createdAt", "updatedAt")
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18)
|
||||
""",
|
||||
new_id,
|
||||
new_numero,
|
||||
@@ -586,11 +861,13 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
original["esquemaPago"],
|
||||
original["incluirBonos"],
|
||||
original["incluirFinanciamiento"],
|
||||
original["incluirIva"],
|
||||
original["esDoble"],
|
||||
original["opcionesMetadata"],
|
||||
original["observaciones"],
|
||||
original["clienteId"],
|
||||
original["asesorId"],
|
||||
creada_por_agente,
|
||||
now,
|
||||
)
|
||||
|
||||
@@ -640,5 +917,14 @@ async def duplicate_cotizacion(cotizacion_id: str, _auth: dict = Depends(require
|
||||
now,
|
||||
)
|
||||
|
||||
full = await _fetch_cotizacion_full(pool, new_id)
|
||||
return full
|
||||
await registrar_auditoria(
|
||||
conn,
|
||||
auth,
|
||||
"cotizacion.duplicar",
|
||||
"cotizacion",
|
||||
recurso_id=new_id,
|
||||
exito=True,
|
||||
detalle={"origenId": cotizacion_id, "numero": new_numero},
|
||||
)
|
||||
|
||||
return await _fetch_cotizacion_full(pool, new_id)
|
||||
|
||||
+20
-14
@@ -15,7 +15,7 @@ from asyncpg import Connection
|
||||
from app.dependencies import get_db
|
||||
from app.models.export_ import ExportDraft
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import es_agente_solo_aceptadas, require_scope
|
||||
from app.services.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename
|
||||
from app.services.pdf_generator import generate_cotizacion_pdf
|
||||
from app.services.excel_generator import generate_cotizacion_excel
|
||||
@@ -86,13 +86,12 @@ def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) ->
|
||||
"planBucefaloNivel": draft.planBucefaloNivel,
|
||||
"planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0,
|
||||
"incluirBonos": draft.incluirBonos,
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -188,13 +187,12 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
"planBucefaloNivel": plan_nivel,
|
||||
"planBucefaloPrecio": float(plan["precio"]) if plan else 0,
|
||||
"incluirBonos": cot["incluirBonos"],
|
||||
"colorPrimario": branding.get("color_primario", "#2563eb"),
|
||||
"colorSecundario": branding.get("color_secundario", "#1e293b"),
|
||||
"colorPrimario": branding.get("color_primario") or "#0400C4",
|
||||
"colorSecundario": branding.get("color_secundario") or "#0F172A",
|
||||
"logoBase64": logo_b64,
|
||||
"logoMime": logo_mime,
|
||||
"configBancaria": branding,
|
||||
"razonSocial": branding.get("razon_social", "Cotizador E3"),
|
||||
"domicilioFiscal": branding.get("domicilio_fiscal"),
|
||||
"razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting",
|
||||
}
|
||||
|
||||
|
||||
@@ -203,7 +201,7 @@ async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[st
|
||||
@router.post("/pdf")
|
||||
async def export_pdf_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -223,9 +221,13 @@ async def export_pdf_draft(
|
||||
@router.get("/pdf/{cotizacion_id}")
|
||||
async def export_pdf_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
pdf_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not pdf_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -247,7 +249,7 @@ async def export_pdf_saved(
|
||||
@router.post("/excel")
|
||||
async def export_excel_draft(
|
||||
body: ExportDraft,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
branding = await _load_branding(db)
|
||||
@@ -267,9 +269,13 @@ async def export_excel_draft(
|
||||
@router.get("/excel/{cotizacion_id}")
|
||||
async def export_excel_saved(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
if es_agente_solo_aceptadas(_auth):
|
||||
row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id)
|
||||
if row_est and row_est["estado"] != "aceptada":
|
||||
raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas")
|
||||
excel_data = await _build_pdf_data_from_db(db, cotizacion_id)
|
||||
if not excel_data:
|
||||
raise HTTPException(status_code=404, detail="Cotización no encontrada")
|
||||
@@ -290,7 +296,7 @@ async def export_excel_saved(
|
||||
|
||||
@router.get("/catalogo", response_class=PlainTextResponse)
|
||||
async def export_catalogo_csv(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
rows = await db.fetch(
|
||||
|
||||
@@ -11,7 +11,7 @@ from app.models.export_ import (
|
||||
PlanBucefaloResponse,
|
||||
)
|
||||
from app.models.common import ErrorResponse
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope
|
||||
from app.services.calculators import (
|
||||
calcular_financiamiento,
|
||||
FINANCIAMIENTO_PLANES,
|
||||
@@ -28,7 +28,7 @@ class PlanResponse(FinanciamientoResponse):
|
||||
|
||||
|
||||
@router.get("/planes", response_model=list[PlanResponse])
|
||||
async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
async def get_planes(_auth: dict = Depends(require_scope("catalogo:leer"))):
|
||||
return [
|
||||
PlanResponse(
|
||||
meses=p["meses"],
|
||||
@@ -47,7 +47,7 @@ async def get_planes(_auth: dict = Depends(require_auth)):
|
||||
)
|
||||
async def calcular(
|
||||
body: FinanciamientoRequest,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
):
|
||||
plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None)
|
||||
if not plan:
|
||||
@@ -77,7 +77,7 @@ async def calcular(
|
||||
)
|
||||
async def simulacion(
|
||||
cotizacion_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
cot = await db.fetchrow(
|
||||
|
||||
@@ -28,9 +28,9 @@ async def health_check():
|
||||
@router.get("/api-info", response_model=APIInfoResponse)
|
||||
async def api_info():
|
||||
return APIInfoResponse(
|
||||
name="Cotizador E3 API",
|
||||
name="Cotizador — Uriel Jareth Consulting API",
|
||||
version="1.0.0",
|
||||
description="API para el sistema de cotizaciones de Consultoría E3",
|
||||
description="API para el sistema de cotizaciones de Uriel Jareth Consulting",
|
||||
capabilities=[
|
||||
"Gestión de cotizaciones",
|
||||
"Catálogo de servicios",
|
||||
|
||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from asyncpg import Connection
|
||||
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_staff_human
|
||||
|
||||
router = APIRouter(prefix="/import", tags=["Import"])
|
||||
|
||||
@@ -17,7 +17,7 @@ REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"}
|
||||
@router.post("/catalogo")
|
||||
async def import_catalogo_csv(
|
||||
file: UploadFile = File(...),
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
db: Connection = Depends(get_db),
|
||||
):
|
||||
content = await file.read()
|
||||
|
||||
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.database import get_pool
|
||||
from app.dependencies import get_db
|
||||
from app.auth import require_auth
|
||||
from app.auth import require_scope, require_staff_human
|
||||
from app.models.paquete import (
|
||||
PaqueteCreate,
|
||||
PaqueteUpdate,
|
||||
@@ -128,7 +128,7 @@ async def _build_paquete_response(conn, paquete_row: dict) -> dict:
|
||||
|
||||
@router.get("", response_model=list[PaqueteResponse])
|
||||
async def list_paquetes(
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
rows = await conn.fetch(
|
||||
@@ -145,7 +145,7 @@ async def list_paquetes(
|
||||
)
|
||||
async def create_paquete(
|
||||
body: PaqueteCreate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -179,7 +179,7 @@ async def create_paquete(
|
||||
)
|
||||
async def get_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_scope("catalogo:leer")),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
row = await conn.fetchrow(
|
||||
@@ -203,7 +203,7 @@ async def get_paquete(
|
||||
async def update_paquete(
|
||||
paquete_id: str,
|
||||
body: PaqueteUpdate,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
existing = await conn.fetchrow(
|
||||
@@ -260,7 +260,7 @@ async def update_paquete(
|
||||
)
|
||||
async def delete_paquete(
|
||||
paquete_id: str,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
result = await conn.execute(
|
||||
@@ -281,7 +281,7 @@ async def delete_paquete(
|
||||
async def manage_paquete(
|
||||
paquete_id: str,
|
||||
body: ManageAction,
|
||||
_auth: dict = Depends(require_auth),
|
||||
_auth: dict = Depends(require_staff_human),
|
||||
conn=Depends(get_db),
|
||||
):
|
||||
paquete = await conn.fetchrow(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
|
||||
IVA_RATE = 0.16
|
||||
@@ -8,11 +9,12 @@ IVA_RATE = 0.16
|
||||
# Tarifa por hora sugerida para partidas personalizadas (Hora Centinela).
|
||||
TARIFA_HORA_DEFAULT = 700
|
||||
|
||||
# Modelos de cobro de una partida (espejo del frontend TS).
|
||||
# Modelos de cobro de una partida (espejo exacto de src/lib/calculators.ts).
|
||||
MODELOS_COBRO: dict[str, str] = {
|
||||
"fijo": "Precio fijo",
|
||||
"horas": "Por horas",
|
||||
"retainer": "Retainer (minimo + adicionales)",
|
||||
"demanda": "Bajo demanda / por hora",
|
||||
}
|
||||
|
||||
# Doble propuesta: cada partida va en la Opcion 1, la 2 o en ambas (espejo del TS).
|
||||
@@ -39,7 +41,7 @@ PLANES_BUCEFALO = [
|
||||
{"nivel": "empresarial", "label": "Empresarial", "precio": 7500},
|
||||
]
|
||||
|
||||
ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"]
|
||||
ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"]
|
||||
|
||||
FINANCIAMIENTO_PLANES = [
|
||||
{"meses": 3, "tasa": 0.077, "comision": 2.5, "montoMinimo": 300},
|
||||
@@ -58,8 +60,12 @@ BONOS = [
|
||||
]
|
||||
|
||||
|
||||
def _r2(n: float) -> float:
|
||||
return round(n + 1e-12, 2) if n >= 0 else -round(-n + 1e-12, 2)
|
||||
|
||||
|
||||
def calcular_precio_horas(horas: float, tarifa_hora: float) -> float:
|
||||
return round((horas or 0) * (tarifa_hora or 0), 2)
|
||||
return _r2((horas or 0) * (tarifa_hora or 0))
|
||||
|
||||
|
||||
def describir_retainer(monto_minimo: float, horas_incluidas: float, tarifa_hora: float) -> str:
|
||||
@@ -81,6 +87,8 @@ def detalle_modelo(serv: dict) -> str:
|
||||
serv.get("horasIncluidas") or 0,
|
||||
serv.get("tarifaHora") or 0,
|
||||
)
|
||||
if modelo == "demanda":
|
||||
return f"{format_currency(serv.get('tarifaHora') or 0)}/hr · segun consumo"
|
||||
horas = serv.get("horas")
|
||||
tarifa = serv.get("tarifaHora")
|
||||
if (modelo == "horas" or serv.get("esPersonalizado")) and horas and tarifa:
|
||||
@@ -91,20 +99,51 @@ def detalle_modelo(serv: dict) -> str:
|
||||
def calcular_totales_opcion(servicios: list[dict], opcion: str) -> dict:
|
||||
"""Totales de una opcion: suma sus partidas + las marcadas 'ambas'.
|
||||
|
||||
Espejo de calcularTotalesOpcion en TS. Respeta la regla de retainer: el total
|
||||
usa `precio`, no `horas x tarifa`. Las horas son informativas.
|
||||
Espejo exacto de calcularTotalesOpcion en TS. Respeta la regla de retainer:
|
||||
el total usa precio, no horas x tarifa. Las horas son informativas.
|
||||
"""
|
||||
rel = [s for s in servicios if s.get("opcion") == "ambas" or s.get("opcion") == opcion]
|
||||
total_unico = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "unico")
|
||||
total_mensual = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "mensual")
|
||||
horas = sum((s.get("horas") or 0) for s in rel)
|
||||
return {
|
||||
"totalUnico": round(total_unico, 2),
|
||||
"totalMensual": round(total_mensual, 2),
|
||||
"horas": round(horas, 2),
|
||||
"totalUnico": _r2(total_unico),
|
||||
"totalMensual": _r2(total_mensual),
|
||||
"horas": _r2(horas),
|
||||
}
|
||||
|
||||
|
||||
def calcular_totales_cotizacion(
|
||||
servicios: list[dict],
|
||||
incluir_iva: bool = True,
|
||||
) -> dict:
|
||||
"""Espejo exacto de calcularTotalesCotizacion en src/lib/calculators.ts."""
|
||||
activos = [s for s in servicios if s.get("seleccionado", True) is not False]
|
||||
subtotal_unico = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "unico"))
|
||||
subtotal_mensual = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "mensual"))
|
||||
|
||||
iva_unico = _r2(subtotal_unico * IVA_RATE) if incluir_iva else 0.0
|
||||
iva_mensual = _r2(subtotal_mensual * IVA_RATE) if incluir_iva else 0.0
|
||||
|
||||
total_unico = _r2(subtotal_unico + iva_unico)
|
||||
total_mensual = _r2(subtotal_mensual + iva_mensual)
|
||||
|
||||
return {
|
||||
"subtotalUnico": subtotal_unico,
|
||||
"subtotalMensual": subtotal_mensual,
|
||||
"ivaUnico": iva_unico,
|
||||
"ivaMensual": iva_mensual,
|
||||
"totalUnico": total_unico,
|
||||
"totalMensual": total_mensual,
|
||||
"totalPrimerAnio": _r2(total_unico + total_mensual * 12),
|
||||
"incluyeIva": incluir_iva,
|
||||
}
|
||||
|
||||
|
||||
def con_iva(monto: float, incluir_iva: bool = True) -> float:
|
||||
return _r2((monto or 0) * (1 + IVA_RATE if incluir_iva else 1))
|
||||
|
||||
|
||||
def bucefalo_precio(nivel: str) -> float:
|
||||
for p in PLANES_BUCEFALO:
|
||||
if p["nivel"] == nivel:
|
||||
@@ -113,32 +152,37 @@ def bucefalo_precio(nivel: str) -> float:
|
||||
|
||||
|
||||
def calcular_vigencia(fecha: datetime | date) -> datetime:
|
||||
"""Suma exactamente 15 dias habiles (lunes a viernes), espejo de calculators.ts."""
|
||||
if isinstance(fecha, datetime):
|
||||
vigencia = fecha.replace()
|
||||
else:
|
||||
vigencia = datetime.combine(fecha, datetime.min.time())
|
||||
dias_habiles = 0
|
||||
while dias_habiles < 15:
|
||||
vigencia = vigencia.replace(day=vigencia.day + 1) if vigencia.day < 28 else vigencia + __import__("datetime").timedelta(days=1)
|
||||
vigencia = vigencia + __import__("datetime").timedelta(days=1)
|
||||
dia = vigencia.weekday()
|
||||
if dia < 5:
|
||||
vigencia = vigencia + timedelta(days=1)
|
||||
if vigencia.weekday() < 5:
|
||||
dias_habiles += 1
|
||||
return vigencia
|
||||
|
||||
|
||||
def calcular_financiamiento(monto: float, meses: int, tasa: float, comision: float, iva: float = IVA_RATE) -> dict:
|
||||
def calcular_financiamiento(
|
||||
monto: float,
|
||||
meses: int,
|
||||
tasa: float,
|
||||
comision: float,
|
||||
iva: float = IVA_RATE,
|
||||
) -> dict:
|
||||
comision_total = (monto * comision) / 100
|
||||
monto_con_comision = monto + comision_total
|
||||
pago_mensual = monto_con_comision * (1 + tasa) / meses
|
||||
iva_mensual = pago_mensual * iva
|
||||
total_mensual = pago_mensual + iva_mensual
|
||||
return {
|
||||
"pagoMensual": round(pago_mensual, 2),
|
||||
"ivaMensual": round(iva_mensual, 2),
|
||||
"totalMensual": round(total_mensual, 2),
|
||||
"comisionTotal": round(comision_total, 2),
|
||||
"granTotal": round(total_mensual * meses, 2),
|
||||
"pagoMensual": _r2(pago_mensual),
|
||||
"ivaMensual": _r2(iva_mensual),
|
||||
"totalMensual": _r2(total_mensual),
|
||||
"comisionTotal": _r2(comision_total),
|
||||
"granTotal": _r2(total_mensual * meses),
|
||||
}
|
||||
|
||||
|
||||
@@ -151,7 +195,6 @@ def generar_numero_cotizacion(iniciales: str, secuencia: int) -> str:
|
||||
|
||||
|
||||
def sanitize_filename(name: str) -> str:
|
||||
import re
|
||||
name = re.sub(r"[^\w\s.\-]", "", name)
|
||||
name = re.sub(r"\s+", " ", name)
|
||||
return name.strip()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Excel Generator for Cotizador E3 — port of src/lib/excel-builder.ts using openpyxl.
|
||||
"""Excel Generator for Cotizador — Uriel Jareth Consulting — port of src/lib/excel-builder.ts using openpyxl.
|
||||
|
||||
Mantiene paridad de layout con el builder de TypeScript: mismas columnas, merges,
|
||||
celdas dinámicas (wrapText + altura calculada) para que el texto nunca se salga.
|
||||
@@ -94,10 +94,10 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
||||
data: dict with quotation data (same as PDF generator)
|
||||
saved: if True, uses real quotation number instead of "BORRADOR"
|
||||
"""
|
||||
config_color = data.get("colorPrimario", "#2563eb")
|
||||
config_color = data.get("colorPrimario") or "#0400C4"
|
||||
PRIMARY = _argb(config_color)
|
||||
PRIMARY_LIGHT = _argb(config_color, alpha="18")
|
||||
SECONDARY = _argb(data.get("colorSecundario", "#1e293b"))
|
||||
SECONDARY = _argb(data.get("colorSecundario") or "#0F172A")
|
||||
WHITE = "FFFFFFFF"
|
||||
LIGHT_BG = "FFF8FAFC"
|
||||
MUTED = "FF64748B"
|
||||
@@ -118,8 +118,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
||||
light_fill = PatternFill(start_color=LIGHT_BG, end_color=LIGHT_BG, fill_type="solid")
|
||||
white_fill = PatternFill(start_color=WHITE, end_color=WHITE, fill_type="solid")
|
||||
|
||||
razon_social = data.get("razonSocial", "Cotizador E3")
|
||||
domicilio_fiscal = data.get("domicilioFiscal")
|
||||
razon_social = data.get("razonSocial") or "Uriel Jareth Consulting"
|
||||
cliente_nombre = data.get("clienteNombre", "")
|
||||
cliente_empresa = data.get("clienteEmpresa", "")
|
||||
asesor_nombre = data.get("asesorNombre", "")
|
||||
@@ -135,7 +134,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
||||
numero_label = data.get("numero", "BORRADOR") if saved else "BORRADOR"
|
||||
|
||||
wb = Workbook()
|
||||
wb.properties.creator = "Cotizador E3"
|
||||
wb.properties.creator = "Cotizador — Uriel Jareth Consulting"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# HOJA RESUMEN
|
||||
@@ -525,12 +524,7 @@ def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> byte
|
||||
dw.merge_cells(f"B{r}:J{r}")
|
||||
dw[f"B{r}"].value = razon_social
|
||||
dw[f"B{r}"].font = Font(bold=True, size=10, name="Calibri", color=PRIMARY)
|
||||
if domicilio_fiscal:
|
||||
r += 1
|
||||
dw.merge_cells(f"B{r}:J{r}")
|
||||
dw[f"B{r}"].value = domicilio_fiscal
|
||||
dw[f"B{r}"].font = iva_font
|
||||
_set_wrapped(dw, r, "B", domicilio_fiscal, ent_width, font_size=9)
|
||||
# Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados.
|
||||
|
||||
output = io.BytesIO()
|
||||
wb.save(output)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""PDF Generator for Cotizador E3 — port of pdf-generator.ts using ReportLab."""
|
||||
"""PDF Generator for Cotizador — Uriel Jareth Consulting — port of pdf-generator.ts using ReportLab."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,8 +15,8 @@ from reportlab.lib.utils import ImageReader
|
||||
|
||||
from app.services.calculators import FASES_SHORT, PLANES_BUCEFALO, bucefalo_precio, detalle_modelo, calcular_totales_opcion
|
||||
|
||||
PRIMARY_DEFAULT = "#2563eb"
|
||||
DARK_DEFAULT = "#1e293b"
|
||||
PRIMARY_DEFAULT = "#0400C4"
|
||||
DARK_DEFAULT = "#0F172A"
|
||||
MUTED = "#64748b"
|
||||
BORDER = "#cbd5e1"
|
||||
LIGHT_BG = "#f1f5f9"
|
||||
|
||||
+8
-7
@@ -1,4 +1,4 @@
|
||||
"""Cotizador E3 — FastAPI Application
|
||||
"""Cotizador — Uriel Jareth Consulting (FastAPI Application)
|
||||
|
||||
REST API for digital marketing quotation management.
|
||||
Optimized for n8n workflows and other integrations.
|
||||
@@ -25,13 +25,13 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Cotizador E3 API",
|
||||
title="Cotizador — Uriel Jareth Consulting API",
|
||||
description=(
|
||||
"API REST para el sistema de cotizaciones de marketing digital de Consultoría E3. "
|
||||
"API REST para el sistema de cotizaciones de Uriel Jareth Consulting. "
|
||||
"Optimizada para integración con n8n y otros consumidores. "
|
||||
"Autenticación por X-API-Key o Bearer JWT."
|
||||
),
|
||||
version="1.0.0",
|
||||
version="2.0.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
@@ -42,7 +42,8 @@ app = FastAPI(
|
||||
{"name": "Clientes", "description": "Gestión de clientes"},
|
||||
{"name": "Catálogo", "description": "Catálogo de servicios de marketing digital"},
|
||||
{"name": "Categorías", "description": "Categorías de servicios"},
|
||||
{"name": "Cotizaciones", "description": "Cotizaciones — CRUD completo con servicios y plan CRM"},
|
||||
{"name": "Cotizaciones", "description": "Cotizaciones — CRUD con paridad de aprobación humana"},
|
||||
{"name": "Cobros", "description": "Consulta de programas y pagos recurrentes (scope cobros:leer)"},
|
||||
{"name": "Paquetes", "description": "Paquetes de servicios con fases"},
|
||||
{"name": "Configuración", "description": "Configuración de la empresa (key-value)"},
|
||||
{"name": "Bonos", "description": "Bonos disponibles para cotizaciones"},
|
||||
@@ -108,8 +109,8 @@ app.include_router(import_.router)
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return {
|
||||
"name": "Cotizador E3 API",
|
||||
"version": "1.0.0",
|
||||
"name": "Cotizador — Uriel Jareth Consulting API",
|
||||
"version": "2.0.0",
|
||||
"docs": "/docs",
|
||||
"openapi": "/openapi.json",
|
||||
"health": "/health",
|
||||
|
||||
Reference in New Issue
Block a user