Snapshot inicial wk-bot en produccion: cobranza acumulada completa, Conekta, SPEI, directorio
This commit is contained in:
commit
729a45e4fa
61 files changed
+13111
No files matched your search
@@ -0,0 +1,16 @@
|
|||||||
|
# === OPENAI ===
|
||||||
|
OPENAI_API_KEY=sk-...
|
||||||
|
|
||||||
|
# === EVOLUTION API (WhatsApp) ===
|
||||||
|
EVOLUTION_API_URL=https://evo.tudominio.com
|
||||||
|
EVOLUTION_API_KEY=tu-api-key-evolution
|
||||||
|
EVOLUTION_INSTANCE=wk-bot
|
||||||
|
|
||||||
|
# === REDIS ===
|
||||||
|
REDIS_URL=redis://redis:6379
|
||||||
|
|
||||||
|
# === GOOGLE SHEETS ===
|
||||||
|
GOOGLE_SHEET_ID=1ABC...XYZ # ID del spreadsheet de histórico
|
||||||
|
GOOGLE_SHEET_RANGE=Histórico de Contratos!A1:O200
|
||||||
|
# JSON completo de la service account (una sola línea)
|
||||||
|
GOOGLE_SERVICE_ACCOUNT_JSON={"type":"service_account","project_id":"..."}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
# Secretos — NUNCA subir
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Entorno virtual de Python
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
|
# Datos y temporales
|
||||||
|
*.log
|
||||||
|
n8n/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# CLAUDE.md — wk-bot
|
||||||
|
|
||||||
|
## Qué es este proyecto
|
||||||
|
Bot de WhatsApp para Carlos Paulino Sánchez Cazares (WK Financing Solutions).
|
||||||
|
Recibe mensajes en lenguaje natural, genera cotizaciones de arrendamiento vehicular y devuelve PDFs listos para reenviar al cliente.
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
- **EvolutionAPI** → canal WhatsApp (self-hosted en VPS)
|
||||||
|
- **n8n** → orquestador de flujos (webhook entrante/saliente)
|
||||||
|
- **FastAPI** → motor de cálculo financiero + generación de PDF
|
||||||
|
- **GPT-4o-mini** → agente de interpretación de mensajes (openai)
|
||||||
|
- **Google Sheets** → histórico de contratos (~100 registros)
|
||||||
|
- **Redis** → sesión activa (última cotización por número de WhatsApp)
|
||||||
|
- **ReportLab** → generación de PDF con formato WK Consulting
|
||||||
|
|
||||||
|
## Flujo principal
|
||||||
|
```
|
||||||
|
WhatsApp → EvolutionAPI webhook → n8n → POST /webhook/message (FastAPI)
|
||||||
|
→ Agente clasifica intención (cotización o consulta)
|
||||||
|
→ Si cotización: calcula + genera PDF → devuelve archivo
|
||||||
|
→ Si consulta: busca en Sheets → devuelve texto
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tipos de solicitud que maneja el agente
|
||||||
|
1. **Cotización directa** — parámetros en el mensaje
|
||||||
|
2. **Replicar histórico** — "con parámetros del GT3" o "parámetros de Diego Corona"
|
||||||
|
3. **Modificar última** — "a esta súbele 2pts a la tasa" (lee Redis)
|
||||||
|
4. **Consulta de parámetros** — "¿qué tasa traía el GT3?" → responde texto, NUNCA PDF
|
||||||
|
|
||||||
|
## Fórmula financiera (CRÍTICO)
|
||||||
|
```python
|
||||||
|
nuevo_precio = precio_referencia - renta_anticipada_$
|
||||||
|
pago_anual = npf.pmt(tasa_anual, plazo_anios, -nuevo_precio, valor_residual_$)
|
||||||
|
renta_mensual = pago_anual / 12 # Ya incluye IVA
|
||||||
|
```
|
||||||
|
- renta_anticipada puede venir como % del precio o como monto directo en $
|
||||||
|
- valor_residual siempre como % del precio_referencia
|
||||||
|
- comisión = 3% del precio_referencia por default
|
||||||
|
|
||||||
|
## Mapeo de campos Google Sheets → PDF impreso
|
||||||
|
| Sheets | PDF | Ejemplo |
|
||||||
|
|--------------|-------------|--------------------------|
|
||||||
|
| anio + kms | MODELO | 2024 (20,000 KMS) |
|
||||||
|
| modelo | TIPO | ESCALADE |
|
||||||
|
| marca | MARCA | CADILLAC |
|
||||||
|
|
||||||
|
## Variables de entorno requeridas
|
||||||
|
Ver `.env.example`. Nunca hardcodear en código.
|
||||||
|
|
||||||
|
## Estructura de archivos
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.py # FastAPI app entry point
|
||||||
|
agents/
|
||||||
|
interpreter.py # Agente GPT-4o-mini: clasifica + extrae parámetros
|
||||||
|
api/
|
||||||
|
webhook.py # POST /webhook/message (entrada desde n8n)
|
||||||
|
services/
|
||||||
|
calculator.py # Motor financiero (fórmula PAGO)
|
||||||
|
pdf_generator.py # Genera PDF formato WK Consulting
|
||||||
|
sheets.py # Lee Google Sheets (histórico contratos)
|
||||||
|
session.py # Redis: guarda/lee última cotización por número
|
||||||
|
whatsapp.py # Envía mensajes/archivos via EvolutionAPI
|
||||||
|
models/
|
||||||
|
schemas.py # Pydantic models
|
||||||
|
utils/
|
||||||
|
logger.py # Logging estructurado
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas importantes
|
||||||
|
- El agente SIEMPRE responde texto cuando la intención es consultar parámetros
|
||||||
|
- "A esta" o "la última" = leer la sesión Redis del número de WhatsApp
|
||||||
|
- Si Paulino pide 2 cotizaciones en un mensaje (ej. "24 y 36 meses") → generar 2 PDFs
|
||||||
|
- "Quita el concepto de comisión" = eliminar la fila entera del PDF, no solo el monto
|
||||||
|
- "Seguro a cargo del cliente" = aparece en PDF como nota pero NO suma al pago inicial
|
||||||
|
- "VR sin anualizar" = mostrar solo VR total, eliminar desglose por año del PDF
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
libreoffice \
|
||||||
|
--no-install-recommends \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY . .
|
||||||
|
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
Binary file not shown.
@@ -0,0 +1,138 @@
|
|||||||
|
# wk-bot — Bot de Cotizaciones WK Financing Solutions
|
||||||
|
|
||||||
|
Bot de WhatsApp que genera cotizaciones de arrendamiento vehicular a partir de mensajes en lenguaje natural.
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
- **FastAPI** — API y motor de cálculo
|
||||||
|
- **GPT-4o-mini** — interpretación de mensajes
|
||||||
|
- **ReportLab** — generación de PDF
|
||||||
|
- **Redis** — sesión activa (última cotización)
|
||||||
|
- **Google Sheets** — histórico de contratos
|
||||||
|
- **EvolutionAPI** — canal WhatsApp
|
||||||
|
- **n8n** — orquestador
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Setup Local
|
||||||
|
|
||||||
|
### 1. Clonar y configurar entorno
|
||||||
|
```bash
|
||||||
|
git clone <repo>
|
||||||
|
cd wk-bot
|
||||||
|
cp .env.example .env
|
||||||
|
# Editar .env con tus credenciales
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Instalar dependencias
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Validar el motor financiero
|
||||||
|
```bash
|
||||||
|
python tests/test_calculator.py
|
||||||
|
```
|
||||||
|
Ajusta la `tasa_anual` en el test hasta que los valores coincidan con los PDFs de ejemplo de Paulino. Esa tasa es la que debes calibrar.
|
||||||
|
|
||||||
|
### 4. Levantar con Docker
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Verificar salud
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8000/health
|
||||||
|
# {"status": "ok"}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuración Google Sheets
|
||||||
|
|
||||||
|
1. Crear Service Account en Google Cloud Console
|
||||||
|
2. Compartir el Google Sheet con el email de la Service Account (lector)
|
||||||
|
3. Copiar el JSON de credenciales en `GOOGLE_SERVICE_ACCOUNT_JSON` del `.env` (una sola línea)
|
||||||
|
4. Copiar el ID del Sheet en `GOOGLE_SHEET_ID`
|
||||||
|
|
||||||
|
El ID del Sheet está en la URL: `https://docs.google.com/spreadsheets/d/**ID_AQUI**/edit`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuración n8n
|
||||||
|
|
||||||
|
Crear un workflow en n8n con este flujo:
|
||||||
|
|
||||||
|
```
|
||||||
|
EvolutionAPI Webhook (trigger)
|
||||||
|
→ HTTP Request (POST) a http://wk-bot:8000/webhook/message
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"numero": "{{$json.data.key.remoteJid}}",
|
||||||
|
"mensaje": "{{$json.data.message.conversation}}",
|
||||||
|
"instance": "{{$json.instance}}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
El bot responde directamente a WhatsApp vía EvolutionAPI desde el backend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Estructura del proyecto
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.py # FastAPI app
|
||||||
|
agents/
|
||||||
|
interpreter.py # GPT-4o-mini: clasifica + extrae parámetros
|
||||||
|
api/
|
||||||
|
webhook.py # POST /webhook/message + lógica de orquestación
|
||||||
|
services/
|
||||||
|
calculator.py # Fórmula PAGO/PMT financiera
|
||||||
|
pdf_generator.py # Genera PDF formato WK Consulting
|
||||||
|
sheets.py # Lee histórico desde Google Sheets
|
||||||
|
session.py # Redis: última cotización por número
|
||||||
|
whatsapp.py # Envía mensajes/PDFs via EvolutionAPI
|
||||||
|
models/
|
||||||
|
schemas.py # Pydantic models
|
||||||
|
utils/
|
||||||
|
logger.py
|
||||||
|
tests/
|
||||||
|
test_calculator.py # Valida motor financiero contra PDFs reales
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tipos de solicitud que maneja
|
||||||
|
|
||||||
|
| Mensaje de Paulino | Respuesta del bot |
|
||||||
|
|---|---|
|
||||||
|
| Parámetros directos | PDF cotización |
|
||||||
|
| "Con parámetros del GT3" | Busca en Sheets → PDF |
|
||||||
|
| "A esta súbele 2pts a la tasa" | Lee Redis → modifica → PDF |
|
||||||
|
| "¿Qué tasa traía el GT3?" | Texto por WhatsApp |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mapeo de campos
|
||||||
|
|
||||||
|
| Google Sheets | PDF impreso |
|
||||||
|
|---|---|
|
||||||
|
| `anio` + `kms` | MODELO — ej. `2024 (20,000 KMS)` |
|
||||||
|
| `modelo` (versión) | TIPO — ej. `ESCALADE` |
|
||||||
|
| `marca` | MARCA — ej. `CADILLAC` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deploy en EasyPanel
|
||||||
|
|
||||||
|
1. Crear nuevo proyecto en EasyPanel
|
||||||
|
2. Conectar repositorio Git
|
||||||
|
3. Seleccionar `docker-compose.yml`
|
||||||
|
4. Agregar variables de entorno desde `.env.example`
|
||||||
|
5. Asignar dominio/subdominio (ej. `wkbot.tudominio.com`)
|
||||||
|
6. Deploy
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Primer paso antes de codificar
|
||||||
|
|
||||||
|
Ejecutar `tests/test_calculator.py` y encontrar la tasa exacta con la que Paulino calculó los dos PDFs de ejemplo. Esa tasa te confirma que la fórmula está bien implementada.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
version: "3.9"
|
||||||
|
services:
|
||||||
|
wk-bot:
|
||||||
|
build: .
|
||||||
|
container_name: wk-bot
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "8001:8000"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
- redis
|
||||||
|
volumes:
|
||||||
|
- ./src:/app/src
|
||||||
|
- ./web:/app/web
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
container_name: wk-bot-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
volumes:
|
||||||
|
redis_data:
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn[standard]==0.30.6
|
||||||
|
pydantic==2.8.2
|
||||||
|
openai==1.45.0
|
||||||
|
numpy-financial==1.0.0
|
||||||
|
reportlab==4.2.2
|
||||||
|
python-docx==1.1.2
|
||||||
|
redis==5.0.8
|
||||||
|
gspread==6.1.2
|
||||||
|
httpx==0.27.2
|
||||||
|
python-multipart==0.0.9
|
||||||
|
pdfplumber==0.11.4
|
||||||
|
apscheduler==3.10.4
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,332 @@
|
|||||||
|
"""
|
||||||
|
Agente intérprete de mensajes de WhatsApp para WK Financing Solutions.
|
||||||
|
|
||||||
|
Recibe texto en lenguaje natural y clasifica la intención + extrae parámetros
|
||||||
|
usando GPT-4o-mini con structured outputs.
|
||||||
|
|
||||||
|
Ejemplos de mensajes que maneja:
|
||||||
|
- "Cadillac Escalade 2024, precio 2mdp, anticipo 978,940, tasa 27.8%, 24 meses"
|
||||||
|
→ cotizacion_directa con todos los parámetros
|
||||||
|
- "A esta súbele 2 puntos a la tasa"
|
||||||
|
→ modificar_ultima con campos_a_modificar={"tasa_anual_delta": 0.02}
|
||||||
|
- "Dame los parámetros del Range Rover del mes pasado"
|
||||||
|
→ replicar_historico con referencia_historico="Range Rover"
|
||||||
|
- "¿Qué tasa traía el GT3?"
|
||||||
|
→ consulta_parametros con referencia_historico="GT3"
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
||||||
|
|
||||||
|
SYSTEM_PROMPT = """\
|
||||||
|
Eres el asistente de Carlos Paulino Sánchez Cazares, agente de arrendamiento \
|
||||||
|
vehicular en WK Financing Solutions, Puebla, México.
|
||||||
|
|
||||||
|
Tu única tarea es interpretar sus mensajes y devolver JSON estructurado.
|
||||||
|
|
||||||
|
## INTENCIONES
|
||||||
|
|
||||||
|
Clasifica cada mensaje en UNA de estas intenciones:
|
||||||
|
|
||||||
|
1. "cotizacion_directa" — tiene parámetros suficientes para generar un PDF \
|
||||||
|
(mínimo: precio, tasa, anticipo, plazo). Marca, tipo y año son OPCIONALES: \
|
||||||
|
si no se mencionan, devuélvelos como null. NO clasifiques como \
|
||||||
|
mensaje_incompleto solo porque falte la marca, el tipo o el año. \
|
||||||
|
IMPORTANTE: aunque exista una ÚLTIMA COTIZACIÓN en el contexto, NO copies \
|
||||||
|
marca/tipo/anio de ahí si el mensaje nuevo NO los menciona — déjalos null. \
|
||||||
|
La última cotización solo se usa como referencia para modificar_ultima, \
|
||||||
|
no para rellenar huecos en cotizaciones nuevas.
|
||||||
|
2. "modificar_ultima" — quiere ajustar la última cotización. Frases clave: \
|
||||||
|
"a esta", "la misma", "esta igual", "súbele", "bájale", "ponle", "cámbialo".
|
||||||
|
3. "replicar_historico" — quiere replicar parámetros financieros de un \
|
||||||
|
contrato del histórico para un vehículo (posiblemente distinto). \
|
||||||
|
Frases clave: "con parámetros del X", "como el X", "igual que el X", \
|
||||||
|
"parámetros X" (cuando el mensaje trae otros datos como precio/vehículo). \
|
||||||
|
Ejemplos: \
|
||||||
|
- "Range Rover pr 2,500,000 parámetros SMARTYPARK" → replicar_historico, \
|
||||||
|
referencia_historico="SMARTYPARK", parametros con marca=Range Rover y \
|
||||||
|
precio_referencia=2500000 (los financieros se completarán con los del \
|
||||||
|
histórico después). \
|
||||||
|
- "con parámetros del GT3" → replicar_historico, referencia_historico="GT3". \
|
||||||
|
En esta intención SIEMPRE rellena `parametros` con los datos explícitos del \
|
||||||
|
mensaje (precio, marca, tipo, etc.) — nunca lo dejes null.
|
||||||
|
4. "consulta_parametros" — pregunta por datos de un contrato sin generar PDF. \
|
||||||
|
Frases clave: "parámetros de X", "¿qué tasa traía?", "pásame los parámetros \
|
||||||
|
de...", "cuánto fue...". Cualquier mensaje del tipo "parámetros <nombre>" \
|
||||||
|
(cliente, marca o vehículo) DEBE clasificarse como consulta_parametros con \
|
||||||
|
referencia_historico=<nombre>, AUNQUE no estés seguro de que existe — el \
|
||||||
|
bot buscará en el histórico y responderá si no lo encuentra. \
|
||||||
|
NUNCA generes PDF para esta intención, SOLO texto.
|
||||||
|
5. "mensaje_incompleto" — quiere cotizar pero faltan datos críticos \
|
||||||
|
(precio, tasa, anticipo, VR o plazo). Indica qué falta en \
|
||||||
|
"parametros_faltantes" (usa exactamente: "precio", "tasa", "anticipo", \
|
||||||
|
"VR", "plazo"). Si el usuario no menciona VR explícitamente, debe aparecer \
|
||||||
|
en faltantes — NO asumas VR=0. Si el usuario dice "VR 0%" o "sin VR", el \
|
||||||
|
campo valor_residual_pct=0 es válido y NO se considera faltante. \
|
||||||
|
NUNCA incluyas marca, tipo ni año como faltantes — los tres son opcionales.
|
||||||
|
6. "consulta_pago" — pregunta por el día o monto de pago de un cliente o \
|
||||||
|
vehículo. Frases clave: "¿cuándo paga X?", "¿cuánto paga X?", "día de pago \
|
||||||
|
X", "monto X", "pago X". En esta intención SIEMPRE devuelve \
|
||||||
|
`consulta_texto` como un JSON STRING con la forma: \
|
||||||
|
`{"cliente_query": "...", "vehiculo_query": "..."}` \
|
||||||
|
donde al menos uno de los dos campos no sea null. Reglas: \
|
||||||
|
- Si el término parece nombre de empresa, persona o razón social (mayúsculas, \
|
||||||
|
sigla, "S.A. DE C.V.") → `cliente_query`. \
|
||||||
|
- Si parece marca/modelo (Cayenne, Hilux, Range Rover, X6, Kenworth, etc.) \
|
||||||
|
→ `vehiculo_query`. \
|
||||||
|
- Si hay ambos ("el Cayenne de SMARTYPARK") → llena los dos. \
|
||||||
|
IMPORTANTE: el término de búsqueda de vehículo puede venir con o sin \
|
||||||
|
artículo (el, la, los, las, un, una). SIEMPRE extrae solo el nombre del \
|
||||||
|
vehículo sin el artículo. Más ejemplos: \
|
||||||
|
- "cuando paga navigator" → `{"vehiculo_query": "navigator", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
- "cuando paga la navigator" → `{"vehiculo_query": "navigator", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
- "cuanto paga el X6" → `{"vehiculo_query": "X6", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
- "cuanto paga X6" → `{"vehiculo_query": "X6", "cliente_query": null}` \
|
||||||
|
- "cuando se cobra GLE 53" → `{"vehiculo_query": "GLE 53", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
- "cuando paga la GLE 53" → `{"vehiculo_query": "GLE 53", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
Ejemplos completos: \
|
||||||
|
- "¿cuándo paga el Cayenne?" → `{"vehiculo_query": "Cayenne", \
|
||||||
|
"cliente_query": null}` \
|
||||||
|
- "¿cuánto paga SMARTYPARK?" → `{"cliente_query": "SMARTYPARK", \
|
||||||
|
"vehiculo_query": null}` \
|
||||||
|
- "¿cuándo paga el Cayenne de SMARTYPARK?" → \
|
||||||
|
`{"cliente_query": "SMARTYPARK", "vehiculo_query": "Cayenne"}` \
|
||||||
|
- "¿cuánto paga PRO13CTUM el X6?" → \
|
||||||
|
`{"cliente_query": "PRO13CTUM", "vehiculo_query": "X6"}` \
|
||||||
|
NUNCA generes PDF para esta intención, SOLO consulta de pagos.
|
||||||
|
|
||||||
|
## REGLAS DE EXTRACCIÓN
|
||||||
|
|
||||||
|
**Vehículo:**
|
||||||
|
- marca: fabricante (CADILLAC, BMW, PORSCHE, LAND ROVER, etc.)
|
||||||
|
- tipo: versión específica (ESCALADE, GT3, M5, RANGE ROVER SPORT, etc.)
|
||||||
|
- anio: año modelo
|
||||||
|
- kms: kilómetros (0 si no se mencionan o es 0km)
|
||||||
|
- unidades: número de unidades si se mencionan; null si no
|
||||||
|
- IMPORTANTE: cuando el mensaje trae dos datos entre paréntesis, uno suele \
|
||||||
|
ser `unidades` (acompañado de la palabra "unidad/unidades") y el otro `kms` \
|
||||||
|
(acompañado de "km/kms/kilómetros"). Ejemplos: \
|
||||||
|
"(30 unidades) (50,000 kms)" → unidades=30, kms=50000; \
|
||||||
|
"(20,000 kms, 5 unidades)" → kms=20000, unidades=5; \
|
||||||
|
"(35,000 kms)" → kms=35000, unidades=null; \
|
||||||
|
"(30 unidades)" → unidades=30, kms=0. \
|
||||||
|
NUNCA tomes un número entre paréntesis sin la palabra "km/unidades" para \
|
||||||
|
inferir kms o unidades — déjalos en su default.
|
||||||
|
|
||||||
|
**Financieros:**
|
||||||
|
- precio_referencia: en pesos ("2M" = 2000000, "1,650k" = 1650000)
|
||||||
|
- tasa_anual: SIEMPRE como decimal (25% = 0.25, "tasa 25" = 0.25)
|
||||||
|
- renta_anticipada: si viene como % → decimal (30% = 0.30); si viene como \
|
||||||
|
monto $ → el número directo. Indicar en es_monto_directo si es monto.
|
||||||
|
- valor_residual_pct: como decimal (15% = 0.15); null si no se menciona
|
||||||
|
- valor_residual_monto: monto directo si se da en pesos; null si no
|
||||||
|
- plazo_meses: entero en MESES (24, 36, 48, 60). Acepta múltiples formatos: \
|
||||||
|
"48", "48m", "48 meses", "4 años" → 48; "5 años" → 60; "3 años" → 36. \
|
||||||
|
Si el usuario escribe un número pequeño (1–6) sin unidad, asume AÑOS y \
|
||||||
|
multiplica por 12 (ej. "4" → 48). Si es 12–72, asume meses.
|
||||||
|
- anualizar_vr: true por default, false solo si dice "sin anualizar"
|
||||||
|
|
||||||
|
**Extras:**
|
||||||
|
- incluir_comision: true por default, false si dice "sin comisión" o "quita comisión"
|
||||||
|
- comision_pct: 0.03 por default, otro valor si lo especifica
|
||||||
|
- seguro_monto: monto en pesos si se especifica; null si no
|
||||||
|
- seguro_descripcion: texto descriptivo del seguro si aplica; null si no
|
||||||
|
|
||||||
|
**Cliente:**
|
||||||
|
- cliente: nombre del cliente; null si "a quien corresponda" o no se menciona
|
||||||
|
- atencion: a quién va dirigida; null si no se menciona
|
||||||
|
|
||||||
|
**Histórico y modificaciones:**
|
||||||
|
- referencia_historico: identificador del contrato/vehículo referenciado \
|
||||||
|
("GT3", "Diego Corona", "Range Rover")
|
||||||
|
- campos_a_modificar: SOLO para modificar_ultima. Diccionario con los campos \
|
||||||
|
que cambian. REGLA CRÍTICA: para un mismo campo usa delta O absoluto, NUNCA \
|
||||||
|
ambos. Si rellenas `tasa_anual_delta`, deja `tasa_anual` en null. Si \
|
||||||
|
rellenas `tasa_anual`, deja `tasa_anual_delta` en null.
|
||||||
|
|
||||||
|
REGLA CRÍTICA #2 — Abreviaturas y alcance:
|
||||||
|
- "ra" / "RA" / "anticipo" / "anticipada" = renta_anticipada (NO tasa).
|
||||||
|
- "vr" / "VR" / "residual" = valor_residual_pct.
|
||||||
|
- "tasa" / "interés" / "rate" = tasa_anual.
|
||||||
|
- "plazo" / "meses" = plazo_meses.
|
||||||
|
- "comisión" / "com" / "apertura" = comision_pct / incluir_comision.
|
||||||
|
SOLO modifica el campo que el usuario mencione. "Bájale ra a 10%" NUNCA \
|
||||||
|
debe modificar tasa. Si solo cambia un campo, los demás quedan en null.
|
||||||
|
|
||||||
|
Ejemplos:
|
||||||
|
- "súbele 2pts a la tasa" → tasa_anual_delta=0.02, tasa_anual=null
|
||||||
|
- "bájale la tasa a 21" → tasa_anual=0.21, tasa_anual_delta=null
|
||||||
|
- "bájale ra a 10%" → renta_anticipada=0.10 (NO TOCA TASA)
|
||||||
|
- "ra 25%" → renta_anticipada=0.25 (NO TOCA TASA)
|
||||||
|
- "ponle VR de 20%" → valor_residual_pct=0.20, valor_residual_pct_delta=null
|
||||||
|
- "bájale la RA 5 pts" → renta_anticipada_delta=-0.05, renta_anticipada=null
|
||||||
|
- "com 2%" → comision_pct=0.02 (abrevia "comisión")
|
||||||
|
- "com 3%" → comision_pct=0.03
|
||||||
|
- "comisión 2%" / "comision 2%" → comision_pct=0.02
|
||||||
|
- "ponle com 2%" → comision_pct=0.02
|
||||||
|
- "cambia la comisión a 2%" → comision_pct=0.02
|
||||||
|
- "quita la comisión" / "sin comisión" → incluir_comision=false
|
||||||
|
|
||||||
|
**Múltiples plazos:**
|
||||||
|
Si pide "24 y 36 meses", generar un parametro por cada plazo en \
|
||||||
|
"plazos_multiples": [24, 36].
|
||||||
|
|
||||||
|
## RESPUESTA
|
||||||
|
|
||||||
|
Responde SOLO un objeto JSON con la estructura definida. Sin markdown, sin texto extra.
|
||||||
|
"""
|
||||||
|
|
||||||
|
RESPONSE_SCHEMA = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "interpretacion",
|
||||||
|
"strict": True,
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"intencion": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"cotizacion_directa",
|
||||||
|
"modificar_ultima",
|
||||||
|
"replicar_historico",
|
||||||
|
"consulta_parametros",
|
||||||
|
"mensaje_incompleto",
|
||||||
|
"consulta_pago",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"parametros": {
|
||||||
|
"type": ["object", "null"],
|
||||||
|
"properties": {
|
||||||
|
"marca": {"type": ["string", "null"]},
|
||||||
|
"tipo": {"type": ["string", "null"]},
|
||||||
|
"anio": {"type": ["integer", "null"]},
|
||||||
|
"kms": {"type": ["integer", "null"]},
|
||||||
|
"precio_referencia": {"type": ["number", "null"]},
|
||||||
|
"tasa_anual": {"type": ["number", "null"]},
|
||||||
|
"renta_anticipada": {"type": ["number", "null"]},
|
||||||
|
"es_monto_directo": {"type": ["boolean", "null"]},
|
||||||
|
"valor_residual_pct": {"type": ["number", "null"]},
|
||||||
|
"valor_residual_monto": {"type": ["number", "null"]},
|
||||||
|
"plazo_meses": {"type": ["integer", "null"]},
|
||||||
|
"anualizar_vr": {"type": ["boolean", "null"]},
|
||||||
|
"incluir_comision": {"type": ["boolean", "null"]},
|
||||||
|
"comision_pct": {"type": ["number", "null"]},
|
||||||
|
"seguro_monto": {"type": ["number", "null"]},
|
||||||
|
"seguro_descripcion": {"type": ["string", "null"]},
|
||||||
|
"cliente": {"type": ["string", "null"]},
|
||||||
|
"atencion": {"type": ["string", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"marca", "tipo", "anio", "kms",
|
||||||
|
"precio_referencia", "tasa_anual",
|
||||||
|
"renta_anticipada", "es_monto_directo",
|
||||||
|
"valor_residual_pct", "valor_residual_monto",
|
||||||
|
"plazo_meses", "anualizar_vr",
|
||||||
|
"incluir_comision", "comision_pct",
|
||||||
|
"seguro_monto", "seguro_descripcion",
|
||||||
|
"cliente", "atencion",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
"plazos_multiples": {
|
||||||
|
"type": ["array", "null"],
|
||||||
|
"items": {"type": "integer"},
|
||||||
|
},
|
||||||
|
"referencia_historico": {"type": ["string", "null"]},
|
||||||
|
"campos_a_modificar": {
|
||||||
|
"type": ["object", "null"],
|
||||||
|
"properties": {
|
||||||
|
"tasa_anual": {"type": ["number", "null"]},
|
||||||
|
"tasa_anual_delta": {"type": ["number", "null"]},
|
||||||
|
"renta_anticipada": {"type": ["number", "null"]},
|
||||||
|
"renta_anticipada_delta": {"type": ["number", "null"]},
|
||||||
|
"valor_residual_pct": {"type": ["number", "null"]},
|
||||||
|
"valor_residual_pct_delta": {"type": ["number", "null"]},
|
||||||
|
"plazo_meses": {"type": ["integer", "null"]},
|
||||||
|
"incluir_comision": {"type": ["boolean", "null"]},
|
||||||
|
"comision_pct": {"type": ["number", "null"]},
|
||||||
|
"seguro_monto": {"type": ["number", "null"]},
|
||||||
|
"anualizar_vr": {"type": ["boolean", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"tasa_anual", "tasa_anual_delta",
|
||||||
|
"renta_anticipada", "renta_anticipada_delta",
|
||||||
|
"valor_residual_pct", "valor_residual_pct_delta",
|
||||||
|
"plazo_meses", "incluir_comision", "comision_pct",
|
||||||
|
"seguro_monto", "anualizar_vr",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
"parametros_faltantes": {
|
||||||
|
"type": ["array", "null"],
|
||||||
|
"items": {"type": "string"},
|
||||||
|
},
|
||||||
|
"consulta_texto": {"type": ["string", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"intencion",
|
||||||
|
"parametros",
|
||||||
|
"plazos_multiples",
|
||||||
|
"referencia_historico",
|
||||||
|
"campos_a_modificar",
|
||||||
|
"parametros_faltantes",
|
||||||
|
"consulta_texto",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def interpretar_mensaje(
|
||||||
|
mensaje: str,
|
||||||
|
ultima_cotizacion: dict | None = None,
|
||||||
|
contexto_historico: dict | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Interpreta el mensaje de Paulino y devuelve la intención + parámetros.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
mensaje: texto del mensaje de WhatsApp
|
||||||
|
ultima_cotizacion: params de la última cotización (desde Redis)
|
||||||
|
contexto_historico: params del contrato referenciado (desde Sheets)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict con intencion, parametros, campos_a_modificar, etc.
|
||||||
|
"""
|
||||||
|
mensajes = [{"role": "system", "content": SYSTEM_PROMPT}]
|
||||||
|
|
||||||
|
contexto_parts = []
|
||||||
|
if ultima_cotizacion:
|
||||||
|
contexto_parts.append(
|
||||||
|
f"ÚLTIMA COTIZACIÓN GENERADA:\n{json.dumps(ultima_cotizacion, ensure_ascii=False)}"
|
||||||
|
)
|
||||||
|
if contexto_historico:
|
||||||
|
contexto_parts.append(
|
||||||
|
f"PARÁMETROS DEL CONTRATO REFERENCIADO:\n{json.dumps(contexto_historico, ensure_ascii=False)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
mensaje_completo = mensaje
|
||||||
|
if contexto_parts:
|
||||||
|
mensaje_completo = "\n\n".join(contexto_parts) + f"\n\nMENSAJE DE PAULINO:\n{mensaje}"
|
||||||
|
|
||||||
|
mensajes.append({"role": "user", "content": mensaje_completo})
|
||||||
|
|
||||||
|
response = await client.chat.completions.create(
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
messages=mensajes,
|
||||||
|
temperature=0.1,
|
||||||
|
response_format=RESPONSE_SCHEMA,
|
||||||
|
)
|
||||||
|
|
||||||
|
return json.loads(response.choices[0].message.content)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,118 @@
|
|||||||
|
"""
|
||||||
|
API REST de administración de recordatorios.
|
||||||
|
|
||||||
|
Cualquier usuario autorizado (con token válido) puede ver y gestionar
|
||||||
|
TODOS los recordatorios, no solo los suyos. La identidad del token solo
|
||||||
|
se usa como default al crear (si no se especifica `numero` en el body).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from src.services import recordatorios
|
||||||
|
from src.services.scheduler import sincronizar_jobs
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/admin")
|
||||||
|
|
||||||
|
|
||||||
|
NOMBRES_CONOCIDOS = {
|
||||||
|
"2222127552": "Paulino",
|
||||||
|
"2225072517": "Vianney",
|
||||||
|
"2225548174": "Gustavo",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _nombre(numero: str) -> str:
|
||||||
|
"""Devuelve el nombre conocido o los últimos 10 dígitos."""
|
||||||
|
return NOMBRES_CONOCIDOS.get(numero, (numero or "")[-10:])
|
||||||
|
|
||||||
|
|
||||||
|
async def _verificar_token(token: str) -> str:
|
||||||
|
"""Devuelve el número asociado al token o lanza 401."""
|
||||||
|
numero = await recordatorios.validar_token_admin(token)
|
||||||
|
if not numero:
|
||||||
|
raise HTTPException(status_code=401, detail="Link expirado o inválido")
|
||||||
|
return numero
|
||||||
|
|
||||||
|
|
||||||
|
class RecordatorioIn(BaseModel):
|
||||||
|
tipo: str
|
||||||
|
hora: str
|
||||||
|
dias: list[int]
|
||||||
|
activo: bool = True
|
||||||
|
# Opcional: para quién es el recordatorio. Si no se manda, se usa el
|
||||||
|
# número del token (legacy behavior).
|
||||||
|
numero: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ping")
|
||||||
|
async def ping(token: str = Query(..., description="Token de admin")):
|
||||||
|
numero = await _verificar_token(token)
|
||||||
|
return {"numero": numero, "nombre": _nombre(numero), "valid": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/recordatorios")
|
||||||
|
async def listar(token: str = Query(...)):
|
||||||
|
"""Devuelve TODOS los recordatorios (no solo los del usuario del token)."""
|
||||||
|
await _verificar_token(token)
|
||||||
|
items = await recordatorios.get_recordatorios()
|
||||||
|
# Enriquecemos con el nombre del owner para el UI.
|
||||||
|
for r in items:
|
||||||
|
r["nombre"] = _nombre(r.get("numero", ""))
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/recordatorios")
|
||||||
|
async def crear(body: RecordatorioIn, token: str = Query(...)):
|
||||||
|
"""Crea un recordatorio para `body.numero` (o el del token por default)."""
|
||||||
|
numero_token = await _verificar_token(token)
|
||||||
|
data = body.model_dump()
|
||||||
|
numero_destino = (data.get("numero") or "").strip() or numero_token
|
||||||
|
data["numero"] = numero_destino
|
||||||
|
data["nombre"] = _nombre(numero_destino)
|
||||||
|
nuevo = await recordatorios.crear_recordatorio(data)
|
||||||
|
await sincronizar_jobs()
|
||||||
|
return nuevo
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/recordatorios/{id}")
|
||||||
|
async def actualizar(id: str, body: RecordatorioIn, token: str = Query(...)):
|
||||||
|
"""Actualiza cualquier recordatorio (sin chequear ownership)."""
|
||||||
|
await _verificar_token(token)
|
||||||
|
data = body.model_dump()
|
||||||
|
# Permite mover un recordatorio a otro número si se incluye en el body.
|
||||||
|
if data.get("numero"):
|
||||||
|
data["nombre"] = _nombre(data["numero"])
|
||||||
|
else:
|
||||||
|
data.pop("numero", None)
|
||||||
|
actualizado = await recordatorios.actualizar_recordatorio(id, data)
|
||||||
|
if not actualizado:
|
||||||
|
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
|
||||||
|
await sincronizar_jobs()
|
||||||
|
return actualizado
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/recordatorios/{id}")
|
||||||
|
async def eliminar(id: str, token: str = Query(...)):
|
||||||
|
"""Elimina cualquier recordatorio (sin chequear ownership)."""
|
||||||
|
await _verificar_token(token)
|
||||||
|
ok = await recordatorios.eliminar_recordatorio(id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
|
||||||
|
await sincronizar_jobs()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/recordatorios/{id}/toggle")
|
||||||
|
async def toggle(id: str, token: str = Query(...)):
|
||||||
|
"""Activa/desactiva cualquier recordatorio (sin chequear ownership)."""
|
||||||
|
await _verificar_token(token)
|
||||||
|
actualizado = await recordatorios.toggle_activo(id)
|
||||||
|
if not actualizado:
|
||||||
|
raise HTTPException(status_code=404, detail="Recordatorio no encontrado")
|
||||||
|
await sincronizar_jobs()
|
||||||
|
return actualizado
|
||||||
@@ -0,0 +1,658 @@
|
|||||||
|
"""
|
||||||
|
Página HTML de administración de recordatorios (estética neumórfica).
|
||||||
|
|
||||||
|
Una sola SPA inline (sin dependencias externas excepto Google Fonts).
|
||||||
|
Se sirve desde GET /admin/ui?token=XXX. El JS hace fetch a
|
||||||
|
/admin/recordatorios?token=XXX para CRUD.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
|
||||||
|
from src.services import recordatorios
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/admin/ui", response_class=HTMLResponse)
|
||||||
|
async def ui(token: str = Query(...)):
|
||||||
|
numero = await recordatorios.validar_token_admin(token)
|
||||||
|
if not numero:
|
||||||
|
return HTMLResponse(_HTML_EXPIRED, status_code=401)
|
||||||
|
return HTMLResponse(_HTML_PAGE.replace("__TOKEN__", token))
|
||||||
|
|
||||||
|
|
||||||
|
# ── Página de token expirado ───────────────────────────────────────
|
||||||
|
|
||||||
|
_HTML_EXPIRED = """<!DOCTYPE html>
|
||||||
|
<html lang="es"><head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Link expirado · Recordatorios WK</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
:root{
|
||||||
|
--bg:#e8eaf0; --surface:#eef0f5;
|
||||||
|
--shadow-light:rgba(255,255,255,0.85);
|
||||||
|
--shadow-dark:rgba(180,185,200,0.6);
|
||||||
|
--text-primary:#2d3148; --text-secondary:#7b82a0; --text-tertiary:#a8aec4;
|
||||||
|
--accent:#4f8ef7; --accent-glow:rgba(79,142,247,0.25);
|
||||||
|
--nm-out:6px 6px 14px var(--shadow-dark), -6px -6px 14px var(--shadow-light);
|
||||||
|
--nm-subtle:3px 3px 8px var(--shadow-dark), -3px -3px 8px var(--shadow-light);
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box;-webkit-font-smoothing:antialiased;}
|
||||||
|
body{
|
||||||
|
font-family:'DM Sans',-apple-system,system-ui,sans-serif;
|
||||||
|
background:var(--bg); margin:0; padding:0;
|
||||||
|
min-height:100vh; display:flex; align-items:center; justify-content:center;
|
||||||
|
color:var(--text-primary); padding:24px;
|
||||||
|
}
|
||||||
|
.card{
|
||||||
|
background:var(--surface); border-radius:28px;
|
||||||
|
box-shadow:var(--nm-out); padding:40px 32px;
|
||||||
|
max-width:380px; width:100%; text-align:center;
|
||||||
|
}
|
||||||
|
.icon-wrap{
|
||||||
|
width:80px; height:80px; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-out);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
margin:0 auto 24px; font-size:36px;
|
||||||
|
}
|
||||||
|
h1{ font-size:22px; font-weight:600; margin:0 0 12px; color:var(--text-primary); }
|
||||||
|
p{ color:var(--text-secondary); font-size:15px; line-height:1.55; margin:0; }
|
||||||
|
strong{ color:var(--accent); font-weight:600; }
|
||||||
|
</style>
|
||||||
|
</head><body>
|
||||||
|
<div class="card">
|
||||||
|
<div class="icon-wrap">🔒</div>
|
||||||
|
<h1>Link expirado</h1>
|
||||||
|
<p>Este link de configuración ya no es válido. Envía la palabra <strong>recordatorio</strong> al bot de WhatsApp para obtener uno nuevo.</p>
|
||||||
|
</div>
|
||||||
|
</body></html>"""
|
||||||
|
|
||||||
|
|
||||||
|
# ── SPA principal ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_HTML_PAGE = """<!DOCTYPE html>
|
||||||
|
<html lang="es"><head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Recordatorios WK · Cotizador Collina</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
:root{
|
||||||
|
--bg:#e8eaf0; --surface:#eef0f5;
|
||||||
|
--shadow-light:rgba(255,255,255,0.85);
|
||||||
|
--shadow-dark:rgba(180,185,200,0.6);
|
||||||
|
--text-primary:#2d3148; --text-secondary:#7b82a0; --text-tertiary:#a8aec4;
|
||||||
|
--accent:#4f8ef7; --accent-glow:rgba(79,142,247,0.25);
|
||||||
|
--accent-soft:rgba(79,142,247,0.08);
|
||||||
|
--success:#34c98a; --danger:#f06070;
|
||||||
|
--nm-out:6px 6px 14px var(--shadow-dark), -6px -6px 14px var(--shadow-light);
|
||||||
|
--nm-in:inset 4px 4px 10px var(--shadow-dark), inset -4px -4px 10px var(--shadow-light);
|
||||||
|
--nm-subtle:3px 3px 8px var(--shadow-dark), -3px -3px 8px var(--shadow-light);
|
||||||
|
}
|
||||||
|
*{ box-sizing:border-box; -webkit-font-smoothing:antialiased; }
|
||||||
|
html,body{ background:var(--bg); }
|
||||||
|
body{
|
||||||
|
font-family:'DM Sans',-apple-system,system-ui,sans-serif;
|
||||||
|
margin:0; padding:24px 16px 96px;
|
||||||
|
color:var(--text-primary); min-height:100vh;
|
||||||
|
}
|
||||||
|
.container{ max-width:480px; margin:0 auto; }
|
||||||
|
|
||||||
|
/* ── Header ── */
|
||||||
|
.header{ text-align:center; margin-bottom:28px; }
|
||||||
|
.header .icon-wrap{
|
||||||
|
width:72px; height:72px; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-out);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
margin:0 auto 16px; font-size:32px;
|
||||||
|
}
|
||||||
|
.header h1{
|
||||||
|
font-size:22px; font-weight:700; margin:0 0 4px;
|
||||||
|
color:var(--text-primary); letter-spacing:-0.3px;
|
||||||
|
}
|
||||||
|
.header .subtitle{
|
||||||
|
font-size:14px; color:var(--text-secondary); margin:0; font-weight:500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Lista de recordatorios ── */
|
||||||
|
#list{ display:flex; flex-direction:column; gap:14px; }
|
||||||
|
.rec-card{
|
||||||
|
background:var(--surface); border-radius:22px;
|
||||||
|
box-shadow:var(--nm-out); padding:18px;
|
||||||
|
opacity:0; transform:translateY(12px);
|
||||||
|
animation:fadeUp .45s cubic-bezier(.34,1.56,.64,1) forwards;
|
||||||
|
}
|
||||||
|
@keyframes fadeUp{ to{ opacity:1; transform:translateY(0); } }
|
||||||
|
|
||||||
|
.rec-top{ display:flex; align-items:center; gap:14px; }
|
||||||
|
.avatar{
|
||||||
|
width:48px; height:48px; flex-shrink:0; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-subtle);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
font-size:22px;
|
||||||
|
}
|
||||||
|
.rec-info{ flex:1; min-width:0; }
|
||||||
|
.rec-name{
|
||||||
|
font-size:15px; font-weight:600; color:var(--text-primary);
|
||||||
|
margin:0 0 4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
|
||||||
|
}
|
||||||
|
.rec-meta{
|
||||||
|
display:flex; align-items:center; gap:8px; flex-wrap:wrap;
|
||||||
|
font-size:12.5px; color:var(--text-secondary); font-weight:500;
|
||||||
|
}
|
||||||
|
.pill{
|
||||||
|
background:var(--accent-soft); color:var(--accent);
|
||||||
|
padding:3px 10px; border-radius:12px;
|
||||||
|
font-size:11.5px; font-weight:600; text-transform:capitalize;
|
||||||
|
letter-spacing:0.2px;
|
||||||
|
}
|
||||||
|
.dot{ color:var(--text-tertiary); }
|
||||||
|
|
||||||
|
/* ── Toggle neumórfico ── */
|
||||||
|
.toggle{
|
||||||
|
width:46px; height:26px; border-radius:14px;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-in);
|
||||||
|
position:relative; cursor:pointer; flex-shrink:0;
|
||||||
|
transition:background .35s cubic-bezier(.34,1.56,.64,1);
|
||||||
|
}
|
||||||
|
.toggle::after{
|
||||||
|
content:''; position:absolute; top:3px; left:3px;
|
||||||
|
width:20px; height:20px; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-subtle);
|
||||||
|
transition:transform .35s cubic-bezier(.34,1.56,.64,1), background .25s;
|
||||||
|
}
|
||||||
|
.toggle.on{ background:var(--accent); box-shadow:var(--nm-in), 0 0 0 1px var(--accent-glow); }
|
||||||
|
.toggle.on::after{ transform:translateX(20px); background:#fff; }
|
||||||
|
|
||||||
|
/* ── Acciones de la card ── */
|
||||||
|
.rec-actions{
|
||||||
|
display:flex; justify-content:flex-end; gap:10px;
|
||||||
|
margin-top:14px; padding-top:12px;
|
||||||
|
border-top:1px solid rgba(168,174,196,0.18);
|
||||||
|
}
|
||||||
|
.icon-btn{
|
||||||
|
width:38px; height:38px; border-radius:12px;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-subtle);
|
||||||
|
border:none; cursor:pointer; font-size:15px;
|
||||||
|
color:var(--text-secondary);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
transition:all .15s ease;
|
||||||
|
}
|
||||||
|
.icon-btn:hover{ color:var(--accent); }
|
||||||
|
.icon-btn:active{ box-shadow:var(--nm-in); transform:scale(.96); }
|
||||||
|
.icon-btn.danger:hover{ color:var(--danger); }
|
||||||
|
|
||||||
|
/* ── Empty state ── */
|
||||||
|
.empty{
|
||||||
|
text-align:center; padding:48px 24px;
|
||||||
|
background:var(--surface); border-radius:22px;
|
||||||
|
box-shadow:var(--nm-out); color:var(--text-secondary);
|
||||||
|
font-size:14.5px; line-height:1.6;
|
||||||
|
}
|
||||||
|
.empty .icon-wrap{
|
||||||
|
width:64px; height:64px; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-in);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
margin:0 auto 16px; font-size:28px; opacity:0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Botón "Nuevo recordatorio" ── */
|
||||||
|
.add-btn{
|
||||||
|
display:flex; align-items:center; justify-content:center; gap:12px;
|
||||||
|
width:100%; padding:16px; margin-top:24px;
|
||||||
|
background:var(--surface); color:var(--text-primary);
|
||||||
|
border:none; border-radius:18px; cursor:pointer;
|
||||||
|
box-shadow:var(--nm-out);
|
||||||
|
font:600 15px/1 'DM Sans',sans-serif;
|
||||||
|
transition:all .15s ease;
|
||||||
|
}
|
||||||
|
.add-btn:active{ box-shadow:var(--nm-in); }
|
||||||
|
.add-circle{
|
||||||
|
width:36px; height:36px; border-radius:50%;
|
||||||
|
background:var(--accent); color:#fff;
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
font-size:22px; font-weight:300; line-height:1;
|
||||||
|
box-shadow:0 4px 12px var(--accent-glow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Modal ── */
|
||||||
|
.modal-backdrop{
|
||||||
|
position:fixed; inset:0; background:rgba(45,49,72,0.28);
|
||||||
|
backdrop-filter:blur(8px); -webkit-backdrop-filter:blur(8px);
|
||||||
|
display:none; align-items:flex-end; justify-content:center;
|
||||||
|
z-index:100; padding:0;
|
||||||
|
}
|
||||||
|
.modal-backdrop.show{ display:flex; animation:fade .25s ease; }
|
||||||
|
@keyframes fade{ from{ opacity:0; } to{ opacity:1; } }
|
||||||
|
|
||||||
|
.modal{
|
||||||
|
background:var(--surface); border-radius:28px 28px 0 0;
|
||||||
|
width:100%; max-width:480px; max-height:92vh; overflow-y:auto;
|
||||||
|
padding:24px 22px 28px;
|
||||||
|
box-shadow:0 -8px 32px rgba(45,49,72,0.18);
|
||||||
|
transform:translateY(100%);
|
||||||
|
animation:slideUp .42s cubic-bezier(.34,1.56,.64,1) forwards;
|
||||||
|
}
|
||||||
|
@keyframes slideUp{ to{ transform:translateY(0); } }
|
||||||
|
|
||||||
|
.modal-handle{
|
||||||
|
width:48px; height:5px; border-radius:3px;
|
||||||
|
background:var(--text-tertiary); opacity:0.4;
|
||||||
|
margin:0 auto 18px;
|
||||||
|
}
|
||||||
|
.modal h2{
|
||||||
|
font-size:18px; font-weight:600; margin:0 0 20px;
|
||||||
|
text-align:center; color:var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.field{ margin-bottom:18px; }
|
||||||
|
.field label{
|
||||||
|
display:block; font-size:12.5px; font-weight:600;
|
||||||
|
color:var(--text-secondary); margin-bottom:8px;
|
||||||
|
text-transform:uppercase; letter-spacing:0.5px;
|
||||||
|
}
|
||||||
|
.input{
|
||||||
|
width:100%; padding:14px 16px;
|
||||||
|
background:var(--surface); color:var(--text-primary);
|
||||||
|
border:none; border-radius:14px; box-shadow:var(--nm-in);
|
||||||
|
font:500 15px/1 'DM Sans',sans-serif; outline:none;
|
||||||
|
appearance:none; -webkit-appearance:none;
|
||||||
|
}
|
||||||
|
select.input{
|
||||||
|
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1l5 5 5-5' stroke='%237b82a0' stroke-width='1.8' fill='none' stroke-linecap='round'/></svg>");
|
||||||
|
background-repeat:no-repeat; background-position:right 18px center;
|
||||||
|
padding-right:42px;
|
||||||
|
}
|
||||||
|
input[type=time].input{ font-variant-numeric:tabular-nums; }
|
||||||
|
|
||||||
|
.days{ display:grid; grid-template-columns:repeat(7,1fr); gap:8px; }
|
||||||
|
.day{
|
||||||
|
background:var(--surface); box-shadow:var(--nm-subtle);
|
||||||
|
border:none; border-radius:12px; cursor:pointer;
|
||||||
|
padding:12px 0; text-align:center;
|
||||||
|
font:600 14px/1 'DM Sans',sans-serif;
|
||||||
|
color:var(--text-secondary);
|
||||||
|
transition:all .18s ease;
|
||||||
|
}
|
||||||
|
.day:active{ transform:scale(.94); }
|
||||||
|
.day.active{
|
||||||
|
background:var(--accent); color:#fff;
|
||||||
|
box-shadow:var(--nm-subtle), 0 0 0 1px var(--accent-glow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-actions{
|
||||||
|
display:flex; gap:12px; margin-top:26px;
|
||||||
|
}
|
||||||
|
.btn{
|
||||||
|
flex:1; padding:14px; border:none; border-radius:14px;
|
||||||
|
cursor:pointer; font:600 15px/1 'DM Sans',sans-serif;
|
||||||
|
transition:all .15s ease;
|
||||||
|
}
|
||||||
|
.btn-secondary{
|
||||||
|
background:var(--surface); color:var(--text-secondary);
|
||||||
|
box-shadow:var(--nm-subtle);
|
||||||
|
}
|
||||||
|
.btn-secondary:active{ box-shadow:var(--nm-in); }
|
||||||
|
.btn-primary{
|
||||||
|
background:var(--accent); color:#fff;
|
||||||
|
box-shadow:0 6px 18px var(--accent-glow);
|
||||||
|
}
|
||||||
|
.btn-primary:active{ transform:scale(.98); box-shadow:0 3px 10px var(--accent-glow); }
|
||||||
|
|
||||||
|
/* ── Pantalla de token expirado (oculta por default) ── */
|
||||||
|
.expired-screen{
|
||||||
|
position:fixed; inset:0; z-index:300;
|
||||||
|
background:var(--bg);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
padding:24px;
|
||||||
|
}
|
||||||
|
.expired-card{
|
||||||
|
background:var(--surface); border-radius:28px;
|
||||||
|
box-shadow:var(--nm-out); padding:40px 32px;
|
||||||
|
max-width:380px; width:100%; text-align:center;
|
||||||
|
}
|
||||||
|
.expired-icon{
|
||||||
|
width:80px; height:80px; border-radius:50%;
|
||||||
|
background:var(--surface); box-shadow:var(--nm-out);
|
||||||
|
display:flex; align-items:center; justify-content:center;
|
||||||
|
margin:0 auto 24px; font-size:36px;
|
||||||
|
}
|
||||||
|
.expired-card h1{
|
||||||
|
font-size:22px; font-weight:600; margin:0 0 12px;
|
||||||
|
color:var(--text-primary);
|
||||||
|
}
|
||||||
|
.expired-card p{
|
||||||
|
color:var(--text-secondary); font-size:15px; line-height:1.55; margin:0;
|
||||||
|
}
|
||||||
|
.expired-card strong{ color:var(--accent); font-weight:600; }
|
||||||
|
|
||||||
|
/* ── Toast ── */
|
||||||
|
.toast{
|
||||||
|
position:fixed; left:50%; bottom:32px;
|
||||||
|
transform:translate(-50%,120%);
|
||||||
|
background:#2d3148; color:#fff;
|
||||||
|
padding:12px 22px; border-radius:20px;
|
||||||
|
font:500 14px/1 'DM Sans',sans-serif;
|
||||||
|
box-shadow:0 8px 24px rgba(45,49,72,0.32);
|
||||||
|
z-index:200; opacity:0; pointer-events:none;
|
||||||
|
}
|
||||||
|
.toast.show{
|
||||||
|
animation:toastIn .45s cubic-bezier(.34,1.56,.64,1) forwards;
|
||||||
|
}
|
||||||
|
@keyframes toastIn{
|
||||||
|
0%{ transform:translate(-50%,120%); opacity:0; }
|
||||||
|
60%{ transform:translate(-50%,-8%); opacity:1; }
|
||||||
|
100%{ transform:translate(-50%,0); opacity:1; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head><body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="header">
|
||||||
|
<div class="icon-wrap">🔔</div>
|
||||||
|
<h1>Recordatorios WK</h1>
|
||||||
|
<p class="subtitle" id="userName">Cargando…</p>
|
||||||
|
</div>
|
||||||
|
<div id="list"></div>
|
||||||
|
<button class="add-btn" onclick="openModal()">
|
||||||
|
<span class="add-circle">+</span>
|
||||||
|
<span>Nuevo recordatorio</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-backdrop" id="modal" onclick="if(event.target===this)closeModal()">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-handle"></div>
|
||||||
|
<h2 id="modalTitle">Nuevo recordatorio</h2>
|
||||||
|
|
||||||
|
<div class="field">
|
||||||
|
<label>Para quién</label>
|
||||||
|
<select id="numero" class="input" onchange="onNumeroChange()">
|
||||||
|
<option value="2222127552">Paulino</option>
|
||||||
|
<option value="2225072517">Vianney</option>
|
||||||
|
<option value="2225548174">Gustavo</option>
|
||||||
|
<option value="__other__">Otro número…</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="field" id="otherNumeroField" style="display:none">
|
||||||
|
<label>Número (10 dígitos, +521 se agrega automáticamente)</label>
|
||||||
|
<input type="tel" id="numeroOtro" class="input"
|
||||||
|
inputmode="numeric" pattern="[0-9]*" maxlength="10"
|
||||||
|
placeholder="2221234567"
|
||||||
|
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="field">
|
||||||
|
<label>Tipo de reporte</label>
|
||||||
|
<select id="tipo" class="input">
|
||||||
|
<option value="diario">Diario (cobros del día)</option>
|
||||||
|
<option value="semanal">Semanal (lun-vie)</option>
|
||||||
|
<option value="mensual">Mensual (VR + extraordinarias)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="field">
|
||||||
|
<label>Hora (zona México)</label>
|
||||||
|
<input type="time" id="hora" class="input" value="08:00">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="field">
|
||||||
|
<label>Días de la semana</label>
|
||||||
|
<div class="days" id="days">
|
||||||
|
<button type="button" class="day" data-d="0">L</button>
|
||||||
|
<button type="button" class="day" data-d="1">M</button>
|
||||||
|
<button type="button" class="day" data-d="2">X</button>
|
||||||
|
<button type="button" class="day" data-d="3">J</button>
|
||||||
|
<button type="button" class="day" data-d="4">V</button>
|
||||||
|
<button type="button" class="day" data-d="5">S</button>
|
||||||
|
<button type="button" class="day" data-d="6">D</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
|
||||||
|
<button class="btn btn-primary" onclick="guardar()">Guardar</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<section id="expired" class="expired-screen" style="display:none">
|
||||||
|
<div class="expired-card">
|
||||||
|
<div class="expired-icon">🔒</div>
|
||||||
|
<h1>Link expirado</h1>
|
||||||
|
<p>Envía <strong>recordatorio</strong> al bot de WhatsApp para obtener uno nuevo.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const TOKEN = "__TOKEN__";
|
||||||
|
const API = "/admin/recordatorios";
|
||||||
|
const NOMBRES = {
|
||||||
|
"2222127552": "Paulino",
|
||||||
|
"2225072517": "Vianney",
|
||||||
|
"2225548174": "Gustavo",
|
||||||
|
};
|
||||||
|
const EMOJIS = {
|
||||||
|
"2222127552": "👨💼",
|
||||||
|
"2225072517": "👩💼",
|
||||||
|
"2225548174": "👨💻",
|
||||||
|
};
|
||||||
|
const DAY_NAMES = ["L","M","X","J","V","S","D"];
|
||||||
|
const TIPO_LABEL = { diario:"Diario", semanal:"Semanal", mensual:"Mensual" };
|
||||||
|
|
||||||
|
let recordatorios = [];
|
||||||
|
let editingId = null;
|
||||||
|
let currentNumero = null;
|
||||||
|
|
||||||
|
function nombreDe(numero){
|
||||||
|
if(!numero) return "";
|
||||||
|
if(NOMBRES[numero]) return NOMBRES[numero];
|
||||||
|
// Formato +52 1 222 123 4567 para números desconocidos.
|
||||||
|
const s = String(numero);
|
||||||
|
if(s.length === 10){
|
||||||
|
return "+52 1 " + s.slice(0,3) + " " + s.slice(3,6) + " " + s.slice(6);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
function emojiDe(numero){ return EMOJIS[numero] || "👤"; }
|
||||||
|
|
||||||
|
function esConocido(numero){ return !!NOMBRES[numero]; }
|
||||||
|
|
||||||
|
function onNumeroChange(){
|
||||||
|
const sel = document.getElementById("numero");
|
||||||
|
const wrap = document.getElementById("otherNumeroField");
|
||||||
|
const input = document.getElementById("numeroOtro");
|
||||||
|
if(sel.value === "__other__"){
|
||||||
|
wrap.style.display = "block";
|
||||||
|
setTimeout(() => input.focus(), 50);
|
||||||
|
} else {
|
||||||
|
wrap.style.display = "none";
|
||||||
|
input.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toast(msg){
|
||||||
|
const t = document.getElementById("toast");
|
||||||
|
t.textContent = msg;
|
||||||
|
t.classList.remove("show");
|
||||||
|
void t.offsetWidth;
|
||||||
|
t.classList.add("show");
|
||||||
|
setTimeout(() => t.classList.remove("show"), 2600);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showExpired(){
|
||||||
|
// Oculta TODO lo demás y muestra solo la pantalla de expirado.
|
||||||
|
document.querySelectorAll(".container, .modal-backdrop, .toast")
|
||||||
|
.forEach(el => { el.style.display = "none"; });
|
||||||
|
const exp = document.getElementById("expired");
|
||||||
|
if(exp) exp.style.display = "flex";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPing(){
|
||||||
|
try{
|
||||||
|
const res = await fetch("/admin/ping?token=" + TOKEN);
|
||||||
|
if(!res.ok){ showExpired(); return false; }
|
||||||
|
const data = await res.json();
|
||||||
|
currentNumero = data.numero;
|
||||||
|
document.getElementById("userName").textContent =
|
||||||
|
"Sesión de " + data.nombre + " · gestionas los recordatorios de todos";
|
||||||
|
return true;
|
||||||
|
} catch(e){
|
||||||
|
showExpired();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(){
|
||||||
|
const ok = await loadPing();
|
||||||
|
if(!ok) return;
|
||||||
|
const res = await fetch(API + "?token=" + TOKEN);
|
||||||
|
if(!res.ok) return;
|
||||||
|
recordatorios = await res.json();
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(){
|
||||||
|
const list = document.getElementById("list");
|
||||||
|
if(!recordatorios.length){
|
||||||
|
list.innerHTML = `
|
||||||
|
<div class="empty">
|
||||||
|
<div class="icon-wrap">📭</div>
|
||||||
|
<div>No tienes recordatorios todavía.<br>Crea uno con el botón de abajo.</div>
|
||||||
|
</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
list.innerHTML = recordatorios.map((r, i) => {
|
||||||
|
const ownerNumero = r.numero || "";
|
||||||
|
const ownerName = r.nombre || nombreDe(ownerNumero);
|
||||||
|
const emoji = emojiDe(ownerNumero);
|
||||||
|
const tipo = TIPO_LABEL[r.tipo] || r.tipo;
|
||||||
|
const dias = (r.dias || []).map(d => DAY_NAMES[d]).join(" ");
|
||||||
|
return `
|
||||||
|
<div class="rec-card" style="animation-delay:${i*50}ms;">
|
||||||
|
<div class="rec-top">
|
||||||
|
<div class="avatar">${emoji}</div>
|
||||||
|
<div class="rec-info">
|
||||||
|
<div class="rec-name">${ownerName}</div>
|
||||||
|
<div class="rec-meta">
|
||||||
|
<span>${r.hora}</span>
|
||||||
|
<span class="dot">·</span>
|
||||||
|
<span class="pill">${tipo}</span>
|
||||||
|
<span class="dot">·</span>
|
||||||
|
<span>${dias}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="toggle ${r.activo ? 'on' : ''}" onclick="toggle('${r.id}')"></div>
|
||||||
|
</div>
|
||||||
|
<div class="rec-actions">
|
||||||
|
<button class="icon-btn" onclick="edit('${r.id}')" title="Editar">✏️</button>
|
||||||
|
<button class="icon-btn danger" onclick="del('${r.id}')" title="Eliminar">🗑</button>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function openModal(r){
|
||||||
|
editingId = r ? r.id : null;
|
||||||
|
document.getElementById("modalTitle").textContent =
|
||||||
|
r ? "Editar recordatorio" : "Nuevo recordatorio";
|
||||||
|
const ownerNumero = r ? (r.numero || currentNumero) : currentNumero;
|
||||||
|
const numeroSelect = document.getElementById("numero");
|
||||||
|
const numeroOtro = document.getElementById("numeroOtro");
|
||||||
|
if(numeroSelect){
|
||||||
|
if(ownerNumero && esConocido(ownerNumero)){
|
||||||
|
numeroSelect.value = ownerNumero;
|
||||||
|
numeroOtro.value = "";
|
||||||
|
} else if(ownerNumero){
|
||||||
|
numeroSelect.value = "__other__";
|
||||||
|
numeroOtro.value = String(ownerNumero);
|
||||||
|
} else {
|
||||||
|
numeroSelect.value = currentNumero && esConocido(currentNumero)
|
||||||
|
? currentNumero : numeroSelect.options[0].value;
|
||||||
|
numeroOtro.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onNumeroChange();
|
||||||
|
document.getElementById("tipo").value = r ? r.tipo : "diario";
|
||||||
|
document.getElementById("hora").value = r ? r.hora : "08:00";
|
||||||
|
const dias = r ? r.dias : [0,1,2,3,4];
|
||||||
|
document.querySelectorAll(".day").forEach(d => {
|
||||||
|
const v = parseInt(d.dataset.d);
|
||||||
|
d.classList.toggle("active", dias.includes(v));
|
||||||
|
});
|
||||||
|
document.getElementById("modal").classList.add("show");
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal(){
|
||||||
|
document.getElementById("modal").classList.remove("show");
|
||||||
|
editingId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll(".day").forEach(d => {
|
||||||
|
d.addEventListener("click", () => d.classList.toggle("active"));
|
||||||
|
});
|
||||||
|
|
||||||
|
function edit(id){
|
||||||
|
const r = recordatorios.find(x => x.id === id);
|
||||||
|
if(r) openModal(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggle(id){
|
||||||
|
const res = await fetch(API + "/" + id + "/toggle?token=" + TOKEN, { method:"PATCH" });
|
||||||
|
if(res.ok){ await load(); toast("Actualizado"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function del(id){
|
||||||
|
if(!confirm("¿Eliminar este recordatorio?")) return;
|
||||||
|
const res = await fetch(API + "/" + id + "?token=" + TOKEN, { method:"DELETE" });
|
||||||
|
if(res.ok){ await load(); toast("Eliminado"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function guardar(){
|
||||||
|
const tipo = document.getElementById("tipo").value;
|
||||||
|
const hora = document.getElementById("hora").value;
|
||||||
|
const sel = document.getElementById("numero").value;
|
||||||
|
let numero = sel;
|
||||||
|
if(sel === "__other__"){
|
||||||
|
numero = (document.getElementById("numeroOtro").value || "").trim();
|
||||||
|
if(!/^\\d{10}$/.test(numero)){
|
||||||
|
alert("El número debe tener exactamente 10 dígitos (sin +521).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const dias = Array.from(document.querySelectorAll(".day.active"))
|
||||||
|
.map(d => parseInt(d.dataset.d));
|
||||||
|
if(!dias.length){ alert("Selecciona al menos un día"); return; }
|
||||||
|
if(!hora){ alert("Indica la hora"); return; }
|
||||||
|
if(!numero){ alert("Selecciona para quién"); return; }
|
||||||
|
const body = { tipo, hora, dias, activo:true, numero };
|
||||||
|
const url = editingId ? API + "/" + editingId + "?token=" + TOKEN
|
||||||
|
: API + "?token=" + TOKEN;
|
||||||
|
const method = editingId ? "PUT" : "POST";
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers:{ "Content-Type":"application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if(res.ok){
|
||||||
|
closeModal();
|
||||||
|
await load();
|
||||||
|
toast("Guardado");
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
alert("Error: " + (err.detail || res.statusText));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
</script>
|
||||||
|
</body></html>"""
|
||||||
@@ -0,0 +1,670 @@
|
|||||||
|
"""
|
||||||
|
API REST + UI del panel de cobranza acumulada.
|
||||||
|
|
||||||
|
Cada token está scoped al número del usuario que lo generó: el panel solo
|
||||||
|
ve y muta SU versión de la cobranza. Reutiliza `validar_token_admin` para
|
||||||
|
compartir el mismo storage (`admin_token:{token}`) que los recordatorios.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from src.services import cobranza_acumulada, pagos, recordatorios, whatsapp
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/admin/cobranza")
|
||||||
|
|
||||||
|
|
||||||
|
# ── Contactos para el "reenviar a contacto" del panel ───────────
|
||||||
|
# Mismas tres personas conocidas del bot. Cualquiera con un token puede
|
||||||
|
# reenviar un link a estos contactos.
|
||||||
|
CONTACTOS = {
|
||||||
|
"Paulino": "2222127552",
|
||||||
|
"Vianney": "2225072517",
|
||||||
|
"Gustavo": "2225548174",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def _numero_token(token: str) -> str:
|
||||||
|
n = await recordatorios.validar_token_admin(token)
|
||||||
|
if not n:
|
||||||
|
raise HTTPException(status_code=401, detail="Link expirado o inválido")
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def _wa_address(numero_10: str) -> str:
|
||||||
|
"""Convierte 10 dígitos en la dirección WhatsApp que espera EvolutionAPI."""
|
||||||
|
return f"521{numero_10}@s.whatsapp.net"
|
||||||
|
|
||||||
|
|
||||||
|
def _instance() -> str:
|
||||||
|
return os.getenv("EVOLUTION_INSTANCE", "wk-bot")
|
||||||
|
|
||||||
|
|
||||||
|
def _mensaje_cobro(cliente: str, vehiculo: str, concepto: str,
|
||||||
|
monto: float, link: str) -> str:
|
||||||
|
return (
|
||||||
|
f"Hola, le saludamos de WK Financing. Le compartimos su pago pendiente:\n\n"
|
||||||
|
f"Cliente: {cliente}\n"
|
||||||
|
f"Vehículo: {vehiculo}\n"
|
||||||
|
f"Concepto: {concepto}\n"
|
||||||
|
f"Monto a pagar: ${monto:,.2f}\n\n"
|
||||||
|
f"Puede pagar con tarjeta, transferencia SPEI o efectivo en Oxxo desde este link:\n{link}\n\n"
|
||||||
|
f"Gracias por su preferencia."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Pydantic ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class IdBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
|
||||||
|
|
||||||
|
class MarcarPagadoBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
nota: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AbonoBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
monto: float
|
||||||
|
concepto: str | None = ""
|
||||||
|
|
||||||
|
|
||||||
|
class RenglonEditBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
cliente: str | None = None
|
||||||
|
vehiculo: str | None = None
|
||||||
|
# Modelo nuevo: un solo `monto` por renglón (su concepto).
|
||||||
|
monto: float | None = None
|
||||||
|
tasa_mensual: float | None = None
|
||||||
|
telefono: str | None = None
|
||||||
|
fecha_alta: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class TelefonoBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
telefono: str
|
||||||
|
# Nombre opcional asociado al override (heredado de un contacto del
|
||||||
|
# dropdown o capturado en el input "Nombre (opcional)" del modal).
|
||||||
|
# Compatible con clientes viejos que no manden el campo.
|
||||||
|
nombre: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DirectorioBody(BaseModel):
|
||||||
|
nombre_norm: str
|
||||||
|
telefono: str # 10 dígitos o "" para borrar
|
||||||
|
|
||||||
|
|
||||||
|
class ContactoManualCreateBody(BaseModel):
|
||||||
|
nombre: str
|
||||||
|
telefono: str # 10 dígitos exactos
|
||||||
|
|
||||||
|
|
||||||
|
class ContactoManualEditBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
nombre: str | None = None
|
||||||
|
telefono: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AbonoIdBody(BaseModel):
|
||||||
|
id_renglon: str
|
||||||
|
id_abono: str
|
||||||
|
|
||||||
|
|
||||||
|
class RenglonManualBody(BaseModel):
|
||||||
|
cliente: str
|
||||||
|
vehiculo: str
|
||||||
|
tipo: str # renta | vr | extra
|
||||||
|
monto: float
|
||||||
|
tasa_mensual: float | None = 0.0
|
||||||
|
dia_pago: int | None = None # solo para renta
|
||||||
|
fecha_vencimiento: str | None = "" # solo para vr/extra (ISO YYYY-MM-DD)
|
||||||
|
|
||||||
|
|
||||||
|
class CuentaSPEIBody(BaseModel):
|
||||||
|
id: str | None = None
|
||||||
|
beneficiario: str
|
||||||
|
banco: str
|
||||||
|
cuenta: str | None = ""
|
||||||
|
clabe: str | None = ""
|
||||||
|
incluir_en_mensaje: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class PlantillaBody(BaseModel):
|
||||||
|
saludo: str | None = None
|
||||||
|
despedida: str | None = None
|
||||||
|
incluir_vehiculo: bool | None = None
|
||||||
|
incluir_monto: bool | None = None
|
||||||
|
incluir_cliente: bool | None = None
|
||||||
|
incluir_fecha_limite: bool | None = None
|
||||||
|
incluir_link: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class EnviarMensajeBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
texto: str
|
||||||
|
|
||||||
|
|
||||||
|
class ReenviarMensajeBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
contacto: str
|
||||||
|
texto: str
|
||||||
|
|
||||||
|
|
||||||
|
class GenerarCobroBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
tipo: str # "saldo" | "sinmora" | "personal"
|
||||||
|
monto: float | None = None
|
||||||
|
concepto: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class EnviarClienteBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
link: str
|
||||||
|
monto: float
|
||||||
|
concepto: str
|
||||||
|
|
||||||
|
|
||||||
|
class ReenviarContactoBody(BaseModel):
|
||||||
|
id: str
|
||||||
|
contacto: str # nombre del contacto (Paulino/Vianney/Gustavo)
|
||||||
|
link: str
|
||||||
|
monto: float
|
||||||
|
concepto: str
|
||||||
|
|
||||||
|
|
||||||
|
class LoteFila(BaseModel):
|
||||||
|
id: str
|
||||||
|
tipo: str # "saldo" | "sinmora" | "personal"
|
||||||
|
monto: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class CobrarLoteBody(BaseModel):
|
||||||
|
concepto: str
|
||||||
|
filas: list[LoteFila]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Endpoints ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@router.get("/api/validate")
|
||||||
|
async def validate(token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
from src.api.admin import NOMBRES_CONOCIDOS # noqa
|
||||||
|
nombre = NOMBRES_CONOCIDOS.get(numero, numero[-10:])
|
||||||
|
return {"numero": numero, "nombre": nombre, "valid": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/renglones")
|
||||||
|
async def listar(token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.listar(numero)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/marcar-pagado")
|
||||||
|
async def marcar_pagado(body: MarcarPagadoBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.marcar_pagado(numero, body.id, body.nota or "")
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/abono")
|
||||||
|
async def abono(body: AbonoBody, token: str = Query(...)):
|
||||||
|
"""COMPAT: crea un abono ya pagado (resta del saldo de inmediato).
|
||||||
|
|
||||||
|
El flujo nuevo de "abono pendiente" se inicia desde `/api/generar-cobro`
|
||||||
|
con tipo='personal' y se confirma con `/api/abono/saldar`.
|
||||||
|
"""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
if body.monto <= 0:
|
||||||
|
raise HTTPException(status_code=400, detail="Monto debe ser > 0")
|
||||||
|
ok = await cobranza_acumulada.registrar_abono(
|
||||||
|
numero, body.id, body.monto, body.concepto or "",
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/abono/saldar")
|
||||||
|
async def abono_saldar(body: AbonoIdBody, token: str = Query(...)):
|
||||||
|
"""Marca un abono pendiente como pagado y baja el saldo del renglón."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.saldar_abono(
|
||||||
|
numero, body.id_renglon, body.id_abono,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón o abono no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/abono/cancelar")
|
||||||
|
async def abono_cancelar(body: AbonoIdBody, token: str = Query(...)):
|
||||||
|
"""Elimina un abono pendiente (creado por error). No toca los pagados."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.cancelar_abono(
|
||||||
|
numero, body.id_renglon, body.id_abono,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="Renglón o abono pendiente no encontrado",
|
||||||
|
)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/renglon")
|
||||||
|
async def editar(body: RenglonEditBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
campos = {k: v for k, v in body.model_dump().items() if k != "id" and v is not None}
|
||||||
|
ok = await cobranza_acumulada.editar_renglon(numero, body.id, campos)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/renglon")
|
||||||
|
async def eliminar(body: IdBody, token: str = Query(...)):
|
||||||
|
"""Borra cualquier renglón (sheet o manual)."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.eliminar_renglon(numero, body.id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/renglon-manual")
|
||||||
|
async def renglon_manual_crear(body: RenglonManualBody, token: str = Query(...)):
|
||||||
|
"""Crea un renglón con origen='manual'. Sobrevive a reiniciar/acumular."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
nuevo, err = await cobranza_acumulada.crear_renglon_manual(
|
||||||
|
numero,
|
||||||
|
cliente=body.cliente,
|
||||||
|
vehiculo=body.vehiculo,
|
||||||
|
tipo=body.tipo,
|
||||||
|
monto=body.monto,
|
||||||
|
tasa_mensual=body.tasa_mensual or 0.0,
|
||||||
|
dia_pago=body.dia_pago,
|
||||||
|
fecha_vencimiento=body.fecha_vencimiento or "",
|
||||||
|
)
|
||||||
|
if err:
|
||||||
|
status = 409 if err.lower().startswith("ya existe") else 400
|
||||||
|
raise HTTPException(status_code=status, detail=err)
|
||||||
|
return nuevo
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/telefono")
|
||||||
|
async def telefono(body: TelefonoBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.guardar_telefono(
|
||||||
|
numero, body.id, body.telefono, body.nombre or "",
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=400, detail="Teléfono inválido o renglón no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/cargar-dia")
|
||||||
|
async def cargar_dia(token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.acumular_dia(numero)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/deshacer")
|
||||||
|
async def deshacer(token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
res = await cobranza_acumulada.deshacer(numero)
|
||||||
|
if not res:
|
||||||
|
raise HTTPException(status_code=404, detail="Nada que deshacer")
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/directorio")
|
||||||
|
async def directorio_listar(token: str = Query(...)):
|
||||||
|
"""Devuelve TODOS los clientes del Sheet con su teléfono del directorio
|
||||||
|
(vacío si aún no se registró). Para la pestaña Directorio del panel.
|
||||||
|
"""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
return {"clientes": await cobranza_acumulada.listar_directorio(numero)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/directorio")
|
||||||
|
async def directorio_guardar(body: DirectorioBody, token: str = Query(...)):
|
||||||
|
"""Guarda/actualiza/borra el teléfono de un cliente en el directorio."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.guardar_telefono_directorio(
|
||||||
|
numero, body.nombre_norm, body.telefono,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="nombre_norm vacío o teléfono inválido (debe ser 10 dígitos o cadena vacía)",
|
||||||
|
)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Contactos manuales (no vienen del Sheet) ────────────────────
|
||||||
|
|
||||||
|
@router.post("/api/contacto-manual")
|
||||||
|
async def contacto_manual_crear(
|
||||||
|
body: ContactoManualCreateBody, token: str = Query(...),
|
||||||
|
):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
nuevo = await cobranza_acumulada.agregar_contacto_manual(
|
||||||
|
numero, body.nombre, body.telefono,
|
||||||
|
)
|
||||||
|
if nuevo is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Nombre vacío (>100) o teléfono inválido (10 dígitos exactos)",
|
||||||
|
)
|
||||||
|
return nuevo
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/contacto-manual")
|
||||||
|
async def contacto_manual_editar(
|
||||||
|
body: ContactoManualEditBody, token: str = Query(...),
|
||||||
|
):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.editar_contacto_manual(
|
||||||
|
numero, body.id, nombre=body.nombre, telefono=body.telefono,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Contacto no encontrado o datos inválidos",
|
||||||
|
)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/contacto-manual")
|
||||||
|
async def contacto_manual_eliminar(body: IdBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.eliminar_contacto_manual(numero, body.id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Contacto no encontrado")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/duplicados")
|
||||||
|
async def listar_duplicados(token: str = Query(...)):
|
||||||
|
"""Devuelve los grupos de renglones que comparten identificador único."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.detectar_duplicados(numero)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/eliminar-duplicados")
|
||||||
|
async def borrar_duplicados(token: str = Query(...)):
|
||||||
|
"""Conserva el más antiguo de cada grupo y borra el resto. Deshacible."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.eliminar_duplicados(numero)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Generación de cobro Conekta y envíos ────────────────────────
|
||||||
|
|
||||||
|
def _monto_para_cobro(r: dict, tipo: str, monto_in: float | None) -> float:
|
||||||
|
"""Resuelve el monto según el tipo de cobro elegido en el panel."""
|
||||||
|
if tipo == "saldo":
|
||||||
|
return float(r.get("saldo") or 0.0)
|
||||||
|
if tipo == "sinmora":
|
||||||
|
return float(r.get("capital") or 0.0) - float(r.get("abonado") or 0.0)
|
||||||
|
if tipo == "personal":
|
||||||
|
return float(monto_in or 0.0)
|
||||||
|
raise HTTPException(status_code=400, detail=f"Tipo de cobro inválido: {tipo}")
|
||||||
|
|
||||||
|
|
||||||
|
async def _generar_cobro_para_renglon(
|
||||||
|
numero: str, renglon: dict, tipo: str,
|
||||||
|
monto_in: float | None, concepto: str | None,
|
||||||
|
) -> dict:
|
||||||
|
"""Crea el link Conekta y devuelve el resumen del cobro.
|
||||||
|
|
||||||
|
Para tipo='personal' además crea un abono PENDIENTE en el renglón y
|
||||||
|
enlaza la referencia con `id_abono`, de modo que el webhook Conekta
|
||||||
|
pueda marcarlo como pagado individualmente.
|
||||||
|
"""
|
||||||
|
monto = round(_monto_para_cobro(renglon, tipo, monto_in), 2)
|
||||||
|
if monto <= 0:
|
||||||
|
raise HTTPException(status_code=400, detail="Monto inválido")
|
||||||
|
concepto_final = (
|
||||||
|
concepto or f"Pago WK Financing - {renglon.get('cliente','')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
id_abono = ""
|
||||||
|
if tipo == "personal":
|
||||||
|
nuevo = await cobranza_acumulada.crear_abono_pendiente(
|
||||||
|
numero, renglon["id"], monto, concepto_final,
|
||||||
|
)
|
||||||
|
if not nuevo:
|
||||||
|
raise HTTPException(status_code=400, detail="No se pudo registrar el abono pendiente")
|
||||||
|
id_abono = nuevo["id"]
|
||||||
|
|
||||||
|
# Referencia que el webhook Conekta interpreta.
|
||||||
|
# - 3 partes : {numero}:{id_renglon}:{tipo} (saldo|sinmora|personal-legacy)
|
||||||
|
# - 4 partes : {numero}:{id_renglon}:abono:{id_abono} (abono específico)
|
||||||
|
if tipo == "personal" and id_abono:
|
||||||
|
ref = f"{numero}:{renglon['id']}:abono:{id_abono}"
|
||||||
|
else:
|
||||||
|
ref = f"{numero}:{renglon['id']}:{tipo}"
|
||||||
|
desc = f"{concepto_final} ({renglon.get('vehiculo','')})"
|
||||||
|
res = await pagos.crear_link_cobro(
|
||||||
|
monto=monto,
|
||||||
|
descripcion=desc,
|
||||||
|
cliente_nombre=renglon.get("cliente", "Cliente"),
|
||||||
|
referencia=ref,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"link": res.get("link"),
|
||||||
|
"id_cobro": res.get("id"),
|
||||||
|
"monto": monto,
|
||||||
|
"concepto": concepto_final,
|
||||||
|
"id_abono": id_abono, # vacío si no es personal
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _buscar_renglon(numero: str, id: str) -> dict:
|
||||||
|
renglones = await cobranza_acumulada.listar(numero)
|
||||||
|
for r in renglones:
|
||||||
|
if r.get("id") == id:
|
||||||
|
return r
|
||||||
|
raise HTTPException(status_code=404, detail="Renglón no encontrado")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/generar-cobro")
|
||||||
|
async def generar_cobro(body: GenerarCobroBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
r = await _buscar_renglon(numero, body.id)
|
||||||
|
try:
|
||||||
|
return await _generar_cobro_para_renglon(
|
||||||
|
numero, r, body.tipo, body.monto, body.concepto,
|
||||||
|
)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error generando cobro Conekta")
|
||||||
|
raise HTTPException(status_code=502, detail="Conekta no respondió")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/enviar-cliente")
|
||||||
|
async def enviar_cliente(body: EnviarClienteBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
r = await _buscar_renglon(numero, body.id)
|
||||||
|
# `_buscar_renglon` ya devuelve renglón decorado con telefono_efectivo
|
||||||
|
# (override > directorio > "").
|
||||||
|
tel = r.get("telefono_efectivo") or r.get("telefono") or ""
|
||||||
|
if not tel:
|
||||||
|
raise HTTPException(status_code=400, detail="El renglón no tiene teléfono")
|
||||||
|
texto = _mensaje_cobro(
|
||||||
|
cliente=r.get("cliente", ""),
|
||||||
|
vehiculo=r.get("vehiculo", ""),
|
||||||
|
concepto=body.concepto,
|
||||||
|
monto=body.monto,
|
||||||
|
link=body.link,
|
||||||
|
)
|
||||||
|
ok = await whatsapp.enviar_texto(_wa_address(tel), texto, _instance())
|
||||||
|
return {"enviado": bool(ok)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reenviar-contacto")
|
||||||
|
async def reenviar_contacto(body: ReenviarContactoBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
r = await _buscar_renglon(numero, body.id)
|
||||||
|
destino = CONTACTOS.get(body.contacto)
|
||||||
|
if not destino:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Contacto desconocido: {body.contacto}")
|
||||||
|
texto = (
|
||||||
|
f"📋 Link de cobro para reenviar al cliente\n\n"
|
||||||
|
f"Cliente: {r.get('cliente','')}\n"
|
||||||
|
f"Vehículo: {r.get('vehiculo','')}\n"
|
||||||
|
f"Concepto: {body.concepto}\n"
|
||||||
|
f"Monto: ${body.monto:,.2f}\n\n"
|
||||||
|
f"{body.link}"
|
||||||
|
)
|
||||||
|
ok = await whatsapp.enviar_texto(_wa_address(destino), texto, _instance())
|
||||||
|
return {"enviado": bool(ok), "contacto": body.contacto}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/cobrar-lote")
|
||||||
|
async def cobrar_lote(body: CobrarLoteBody, token: str = Query(...)):
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
renglones = {r.get("id"): r for r in await cobranza_acumulada.listar(numero)}
|
||||||
|
enviados = 0
|
||||||
|
omitidos_sin_tel: list[str] = []
|
||||||
|
errores: list[str] = []
|
||||||
|
|
||||||
|
for fila in body.filas:
|
||||||
|
r = renglones.get(fila.id)
|
||||||
|
if not r:
|
||||||
|
errores.append(fila.id)
|
||||||
|
continue
|
||||||
|
# `listar()` ya decoró con telefono_efectivo (override > directorio).
|
||||||
|
tel_efectivo = r.get("telefono_efectivo") or ""
|
||||||
|
if not tel_efectivo:
|
||||||
|
omitidos_sin_tel.append(r.get("cliente", fila.id))
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
cobro = await _generar_cobro_para_renglon(
|
||||||
|
numero, r, fila.tipo, fila.monto, body.concepto,
|
||||||
|
)
|
||||||
|
except HTTPException as e:
|
||||||
|
logger.warning("Lote: error en %s: %s", fila.id, e.detail)
|
||||||
|
errores.append(r.get("cliente", fila.id))
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Lote: excepción generando cobro para %s", fila.id)
|
||||||
|
errores.append(r.get("cliente", fila.id))
|
||||||
|
continue
|
||||||
|
texto = _mensaje_cobro(
|
||||||
|
cliente=r.get("cliente", ""),
|
||||||
|
vehiculo=r.get("vehiculo", ""),
|
||||||
|
concepto=body.concepto,
|
||||||
|
monto=cobro["monto"],
|
||||||
|
link=cobro["link"],
|
||||||
|
)
|
||||||
|
ok = await whatsapp.enviar_texto(_wa_address(tel_efectivo), texto, _instance())
|
||||||
|
if ok:
|
||||||
|
enviados += 1
|
||||||
|
else:
|
||||||
|
errores.append(r.get("cliente", fila.id))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enviados": enviados,
|
||||||
|
"omitidos_sin_telefono": omitidos_sin_tel,
|
||||||
|
"errores": errores,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Config GLOBAL (cuentas SPEI + plantilla del mensaje) ────────
|
||||||
|
|
||||||
|
@router.get("/api/config")
|
||||||
|
async def config_obtener(token: str = Query(...)):
|
||||||
|
"""Devuelve la config global (cuentas + plantilla). Mismo para todos."""
|
||||||
|
await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.obtener_config_global()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/config/cuenta")
|
||||||
|
async def config_cuenta_upsert(body: CuentaSPEIBody, token: str = Query(...)):
|
||||||
|
await _numero_token(token)
|
||||||
|
nuevo, err = await cobranza_acumulada.upsert_cuenta_global(body.model_dump())
|
||||||
|
if err:
|
||||||
|
raise HTTPException(status_code=400, detail=err)
|
||||||
|
return nuevo
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/config/cuenta")
|
||||||
|
async def config_cuenta_eliminar(body: IdBody, token: str = Query(...)):
|
||||||
|
await _numero_token(token)
|
||||||
|
ok = await cobranza_acumulada.eliminar_cuenta_global(body.id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=404, detail="Cuenta no encontrada")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/config/plantilla")
|
||||||
|
async def config_plantilla_guardar(body: PlantillaBody, token: str = Query(...)):
|
||||||
|
await _numero_token(token)
|
||||||
|
return await cobranza_acumulada.guardar_plantilla_global(
|
||||||
|
body.model_dump(exclude_none=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Envío genérico (mensaje pre-armado por el frontend) ─────────
|
||||||
|
|
||||||
|
@router.post("/api/enviar-mensaje-cliente")
|
||||||
|
async def enviar_mensaje_cliente(body: EnviarMensajeBody, token: str = Query(...)):
|
||||||
|
"""Envía un texto YA armado al cliente del renglón (override > directorio)."""
|
||||||
|
numero = await _numero_token(token)
|
||||||
|
r = await _buscar_renglon(numero, body.id)
|
||||||
|
tel = r.get("telefono_efectivo") or r.get("telefono") or ""
|
||||||
|
if not tel:
|
||||||
|
raise HTTPException(status_code=400, detail="El renglón no tiene teléfono")
|
||||||
|
if not (body.texto or "").strip():
|
||||||
|
raise HTTPException(status_code=400, detail="Texto vacío")
|
||||||
|
ok = await whatsapp.enviar_texto(_wa_address(tel), body.texto, _instance())
|
||||||
|
return {"enviado": bool(ok)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reenviar-mensaje-contacto")
|
||||||
|
async def reenviar_mensaje_contacto(body: ReenviarMensajeBody, token: str = Query(...)):
|
||||||
|
"""Envía un texto YA armado al contacto seleccionado (Paulino/Vianney/Gustavo)."""
|
||||||
|
await _numero_token(token)
|
||||||
|
destino = CONTACTOS.get(body.contacto)
|
||||||
|
if not destino:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Contacto desconocido: {body.contacto}")
|
||||||
|
if not (body.texto or "").strip():
|
||||||
|
raise HTTPException(status_code=400, detail="Texto vacío")
|
||||||
|
ok = await whatsapp.enviar_texto(_wa_address(destino), body.texto, _instance())
|
||||||
|
return {"enviado": bool(ok), "contacto": body.contacto}
|
||||||
|
|
||||||
|
|
||||||
|
# ── UI (HTML) ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_HTML_PATH = Path(__file__).resolve().parents[2] / "web" / "cobranza.html"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ui", response_class=HTMLResponse)
|
||||||
|
async def ui(token: str = Query(...)):
|
||||||
|
"""Sirve el panel reemplazando __TOKEN__ por el token validado.
|
||||||
|
|
||||||
|
NO valida el token aquí: el HTML llama a /api/validate al cargar y
|
||||||
|
muestra la pantalla de "Acceso expirado" si está roto. Esto permite
|
||||||
|
cargar el panel aunque el token expire entre TTLs.
|
||||||
|
"""
|
||||||
|
if not _HTML_PATH.exists():
|
||||||
|
return HTMLResponse(
|
||||||
|
"<h1>Panel de cobranza no instalado</h1>",
|
||||||
|
status_code=500,
|
||||||
|
)
|
||||||
|
html = _HTML_PATH.read_text(encoding="utf-8")
|
||||||
|
return HTMLResponse(html.replace("__TOKEN__", token))
|
||||||
+3196
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,123 @@
|
|||||||
|
"""
|
||||||
|
Webhook entrante de Conekta. NO requiere autorización: el endpoint lo
|
||||||
|
consume el dashboard de Conekta directamente.
|
||||||
|
|
||||||
|
La referencia (`metadata.referencia`) puede venir en dos formatos:
|
||||||
|
"{numero_wa_10}:{id_renglon}:{tipo}" (3 partes)
|
||||||
|
tipo ∈ {"saldo", "sinmora", "personal"}
|
||||||
|
"{numero_wa_10}:{id_renglon}:abono:{id_abono}" (4 partes)
|
||||||
|
tipo = "abono" → marca ESE abono pendiente como pagado
|
||||||
|
|
||||||
|
Cuando llega `charge.paid` o `order.paid`:
|
||||||
|
- "saldo" o "sinmora" → marca el renglón como pagado.
|
||||||
|
- "personal" → COMPAT: registra el monto como abono ya pagado.
|
||||||
|
- "abono" + id_abono → marca ESE abono específico como pagado
|
||||||
|
(el saldo del renglón baja por ese monto;
|
||||||
|
si el saldo llega a <=0.5, cierre automático).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Request
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_ref(ref: str) -> tuple[str, str, str, str] | None:
|
||||||
|
"""Devuelve (numero, id_renglon, tipo, id_abono) o None.
|
||||||
|
|
||||||
|
`id_abono` es "" cuando no aplica (3 partes).
|
||||||
|
"""
|
||||||
|
if not ref or ":" not in ref:
|
||||||
|
return None
|
||||||
|
partes = ref.split(":")
|
||||||
|
if len(partes) < 3:
|
||||||
|
return None
|
||||||
|
numero = partes[0].strip()
|
||||||
|
id_renglon = partes[1].strip()
|
||||||
|
tipo = partes[2].strip().lower()
|
||||||
|
if not numero or not id_renglon:
|
||||||
|
return None
|
||||||
|
if tipo == "abono":
|
||||||
|
if len(partes) < 4 or not partes[3].strip():
|
||||||
|
return None
|
||||||
|
return numero, id_renglon, "abono", partes[3].strip()
|
||||||
|
if tipo in {"saldo", "sinmora", "personal"}:
|
||||||
|
return numero, id_renglon, tipo, ""
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/webhook/conekta")
|
||||||
|
async def webhook_conekta(request: Request):
|
||||||
|
try:
|
||||||
|
payload = await request.json()
|
||||||
|
except Exception:
|
||||||
|
logger.warning("Webhook Conekta sin JSON parseable")
|
||||||
|
return {"ok": False}
|
||||||
|
|
||||||
|
evento = payload.get("type", "")
|
||||||
|
|
||||||
|
if evento not in ("charge.paid", "order.paid"):
|
||||||
|
# Otros eventos (chargeback, refund, etc.) los ignoramos por ahora.
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
data_obj = (payload.get("data") or {}).get("object") or {}
|
||||||
|
metadata = data_obj.get("metadata") or {}
|
||||||
|
# Conekta puede anidar metadata adentro del order si el charge es hijo.
|
||||||
|
if not metadata:
|
||||||
|
order = data_obj.get("order") or {}
|
||||||
|
metadata = order.get("metadata") or {}
|
||||||
|
ref = metadata.get("referencia", "") or ""
|
||||||
|
monto_cent = data_obj.get("amount") or 0
|
||||||
|
monto = monto_cent / 100.0
|
||||||
|
logger.info(
|
||||||
|
"Pago confirmado Conekta: evento=%s ref=%s monto=$%.2f",
|
||||||
|
evento, ref, monto,
|
||||||
|
)
|
||||||
|
|
||||||
|
parsed = _parse_ref(ref)
|
||||||
|
if not parsed:
|
||||||
|
logger.warning("Referencia Conekta sin formato esperable: %r", ref)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
numero, id_renglon, tipo, id_abono = parsed
|
||||||
|
|
||||||
|
# Imports tardíos para evitar ciclos.
|
||||||
|
from src.services import cobranza_acumulada
|
||||||
|
|
||||||
|
try:
|
||||||
|
if tipo == "abono":
|
||||||
|
ok = await cobranza_acumulada.saldar_abono(
|
||||||
|
numero, id_renglon, id_abono,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Abono pendiente saldado vía Conekta: %s renglón=%s abono=%s monto=$%.2f ok=%s",
|
||||||
|
numero, id_renglon, id_abono, monto, ok,
|
||||||
|
)
|
||||||
|
elif tipo == "personal":
|
||||||
|
# COMPAT con cobros generados antes del flujo nuevo (sin id_abono).
|
||||||
|
await cobranza_acumulada.registrar_abono(
|
||||||
|
numero, id_renglon, monto,
|
||||||
|
concepto="Pago Conekta",
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Abono registrado (legacy): %s renglón=%s monto=$%.2f",
|
||||||
|
numero, id_renglon, monto,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await cobranza_acumulada.marcar_pagado(
|
||||||
|
numero, id_renglon,
|
||||||
|
nota=f"Pagado vía Conekta (${monto:,.2f})",
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Renglón saldado: %s renglón=%s monto=$%.2f tipo=%s",
|
||||||
|
numero, id_renglon, monto, tipo,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"Error aplicando pago Conekta a %s renglón=%s",
|
||||||
|
numero, id_renglon,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from src.api.admin import router as admin_router
|
||||||
|
from src.api.admin_ui import router as admin_ui_router
|
||||||
|
from src.api.cobranza_api import router as cobranza_router
|
||||||
|
from src.api.webhook import router as webhook_router
|
||||||
|
from src.api.webhook_conekta import router as conekta_router
|
||||||
|
from src.services.scheduler import start_scheduler, stop_scheduler
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
# Arranque del scheduler de recordatorios. Si falla (Redis caído,
|
||||||
|
# etc.) loguea pero no impide arrancar la API.
|
||||||
|
await start_scheduler()
|
||||||
|
yield
|
||||||
|
await stop_scheduler()
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="WK Bot", version="1.0.0", lifespan=lifespan)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(webhook_router)
|
||||||
|
app.include_router(admin_router)
|
||||||
|
app.include_router(admin_ui_router)
|
||||||
|
app.include_router(conekta_router)
|
||||||
|
app.include_router(cobranza_router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
async def health():
|
||||||
|
return {"status": "ok"}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,76 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class CotizacionParams(BaseModel):
|
||||||
|
# Datos del vehículo
|
||||||
|
marca: str
|
||||||
|
tipo: str # versión específica (ESCALADE, GT3, etc.)
|
||||||
|
anio: int
|
||||||
|
kms: Optional[int] = None # None = 0km
|
||||||
|
unidades: Optional[int] = None # >1 para flotillas ("(15 UNIDADES)")
|
||||||
|
|
||||||
|
# Datos financieros
|
||||||
|
precio_referencia: float
|
||||||
|
tasa_anual: float # decimal: 0.28 = 28%
|
||||||
|
renta_anticipada: float # decimal si es %, monto si es_monto_directo=True
|
||||||
|
es_monto_directo_ra: bool = False # True si RA vino como $ no como %
|
||||||
|
valor_residual_pct: float = 0.0 # decimal: 0.15 = 15%
|
||||||
|
plazo_meses: int # 24, 36, 48, 60
|
||||||
|
anualizar_vr: bool = True # False = "VR sin anualizar"
|
||||||
|
|
||||||
|
# Extras
|
||||||
|
seguro: Optional[float] = None # monto en pesos, None = no incluido
|
||||||
|
seguro_a_cargo_cliente: bool = False # aparece en PDF pero no suma al inicial
|
||||||
|
seguro_desde_anio: Optional[int] = None # ej. 2 = a partir del año 2
|
||||||
|
incluir_comision: bool = True
|
||||||
|
comision_override: Optional[float] = None # si se especifica monto exacto
|
||||||
|
incluir_placas: bool = False
|
||||||
|
placas_monto: Optional[float] = None
|
||||||
|
|
||||||
|
# Cliente
|
||||||
|
nombre_cliente: Optional[str] = None
|
||||||
|
atencion: Optional[str] = None
|
||||||
|
|
||||||
|
# Control
|
||||||
|
encabezado: str = "COTIZACION ARRENDAMIENTO DE AUTO" # puede cambiar
|
||||||
|
|
||||||
|
|
||||||
|
class CotizacionResult(BaseModel):
|
||||||
|
renta_anticipada_monto: float
|
||||||
|
valor_residual_total: float
|
||||||
|
valor_residual_por_anio: Optional[dict] = None # {1: x, 2: y, 3: z}
|
||||||
|
comision_monto: float
|
||||||
|
total_pago_inicial: float
|
||||||
|
renta_mensual: float
|
||||||
|
nuevo_precio: float
|
||||||
|
|
||||||
|
|
||||||
|
class WebhookMessage(BaseModel):
|
||||||
|
numero: str # número de WhatsApp del remitente
|
||||||
|
mensaje: str # texto del mensaje (puede venir vacío si es adjunto)
|
||||||
|
instance: str # instancia EvolutionAPI
|
||||||
|
# Adjunto para flujo de clonación: EvolutionAPI entrega documentos con
|
||||||
|
# mediaType="document" y el binario en base64.
|
||||||
|
pdf_base64: Optional[str] = None
|
||||||
|
media_type: Optional[str] = None
|
||||||
|
mime_type: Optional[str] = None
|
||||||
|
# Claves del mensaje original de EvolutionAPI (permiten descargar el PDF
|
||||||
|
# con /chat/getBase64FromMediaMessage cuando n8n no lo manda inline).
|
||||||
|
message_key: Optional[dict] = None
|
||||||
|
message_data: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ConsultaResult(BaseModel):
|
||||||
|
texto_respuesta: str
|
||||||
|
|
||||||
|
|
||||||
|
class InterpretacionResult(BaseModel):
|
||||||
|
intencion: str # "cotizacion" | "consulta_parametros"
|
||||||
|
params: Optional[CotizacionParams] = None
|
||||||
|
params_multiples: Optional[list[CotizacionParams]] = None # para "24 y 36 meses"
|
||||||
|
consulta_texto: Optional[str] = None # respuesta lista si es consulta
|
||||||
|
necesita_historico: bool = False
|
||||||
|
referencia_historico: Optional[str] = None # "GT3", "Diego Corona", etc.
|
||||||
|
usar_ultima_cotizacion: bool = False
|
||||||
|
modificaciones: Optional[dict] = None # {"tasa_anual": +0.02} para ajustes
|
||||||
Whitespace-only changes.
@@ -0,0 +1,123 @@
|
|||||||
|
import numpy_financial as npf
|
||||||
|
from src.models.schemas import CotizacionParams, CotizacionResult
|
||||||
|
|
||||||
|
|
||||||
|
def calcular_tasa_implicita(
|
||||||
|
precio_referencia: float,
|
||||||
|
renta_anticipada: float,
|
||||||
|
valor_residual: float,
|
||||||
|
plazo_meses: int,
|
||||||
|
renta_mensual: float,
|
||||||
|
) -> float | None:
|
||||||
|
"""Resuelve por bisección la tasa anual que produce `renta_mensual`.
|
||||||
|
|
||||||
|
Usa la misma fórmula PMT que `calcular_cotizacion`:
|
||||||
|
pago_anual = pmt(tasa, plazo_anios, -(precio - ra), vr)
|
||||||
|
renta_mensual = pago_anual / 12
|
||||||
|
|
||||||
|
Args:
|
||||||
|
precio_referencia: precio base del vehículo.
|
||||||
|
renta_anticipada: monto del anticipo en pesos.
|
||||||
|
valor_residual: monto del valor residual en pesos.
|
||||||
|
plazo_meses: plazo del contrato en meses.
|
||||||
|
renta_mensual: renta mensual objetivo a despejar.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tasa anual como porcentaje con 6 decimales (ej. 27.368421). None si
|
||||||
|
no converge o si los inputs son inválidos.
|
||||||
|
"""
|
||||||
|
if plazo_meses <= 0 or renta_mensual <= 0 or precio_referencia <= 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
nuevo_precio = precio_referencia - renta_anticipada
|
||||||
|
if nuevo_precio <= 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
plazo_anios = plazo_meses / 12
|
||||||
|
objetivo = renta_mensual
|
||||||
|
|
||||||
|
def renta_para(tasa: float) -> float:
|
||||||
|
pago_anual = npf.pmt(tasa, plazo_anios, -nuevo_precio, valor_residual)
|
||||||
|
return float(pago_anual) / 12
|
||||||
|
|
||||||
|
bajo, alto = 0.0, 2.0 # 0% – 200% anual
|
||||||
|
# Verifica que la función cambia de signo en el intervalo.
|
||||||
|
r_bajo = renta_para(bajo) - objetivo
|
||||||
|
r_alto = renta_para(alto) - objetivo
|
||||||
|
if r_bajo * r_alto > 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
for _ in range(100):
|
||||||
|
medio = (bajo + alto) / 2
|
||||||
|
r_medio = renta_para(medio) - objetivo
|
||||||
|
if abs(r_medio) <= 0.10: # tolerancia de 10 centavos
|
||||||
|
return round(medio * 100, 6)
|
||||||
|
if r_bajo * r_medio < 0:
|
||||||
|
alto = medio
|
||||||
|
r_alto = r_medio
|
||||||
|
else:
|
||||||
|
bajo = medio
|
||||||
|
r_bajo = r_medio
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def calcular_cotizacion(p: CotizacionParams) -> CotizacionResult:
|
||||||
|
precio = p.precio_referencia
|
||||||
|
plazo_anios = p.plazo_meses / 12
|
||||||
|
|
||||||
|
# Renta anticipada
|
||||||
|
if p.es_monto_directo_ra:
|
||||||
|
ra_monto = p.renta_anticipada
|
||||||
|
else:
|
||||||
|
ra_monto = precio * p.renta_anticipada
|
||||||
|
|
||||||
|
# Valor residual
|
||||||
|
vr_total = precio * p.valor_residual_pct
|
||||||
|
|
||||||
|
# Valor residual por año
|
||||||
|
vr_por_anio = None
|
||||||
|
if vr_total > 0 and p.anualizar_vr:
|
||||||
|
anios = int(plazo_anios)
|
||||||
|
vr_base = vr_total / anios
|
||||||
|
# Último año puede tener diferencia por redondeo
|
||||||
|
vr_por_anio = {i + 1: round(vr_base, 2) for i in range(anios)}
|
||||||
|
diferencia = round(vr_total - sum(vr_por_anio.values()), 2)
|
||||||
|
vr_por_anio[anios] = round(vr_por_anio[anios] + diferencia, 2)
|
||||||
|
|
||||||
|
# Nuevo precio (base del financiamiento)
|
||||||
|
nuevo_precio = precio - ra_monto
|
||||||
|
|
||||||
|
# Renta mensual usando fórmula PAGO/PMT
|
||||||
|
# npf.pmt(rate, nper, pv, fv) — fv es el VR como valor positivo
|
||||||
|
pago_anual = npf.pmt(p.tasa_anual, plazo_anios, -nuevo_precio, vr_total)
|
||||||
|
renta_mensual = round(float(pago_anual) / 12, 2)
|
||||||
|
|
||||||
|
# Comisión por apertura
|
||||||
|
if not p.incluir_comision:
|
||||||
|
comision = 0.0
|
||||||
|
elif p.comision_override is not None:
|
||||||
|
comision = p.comision_override
|
||||||
|
else:
|
||||||
|
comision = round(precio * 0.03, 2)
|
||||||
|
|
||||||
|
# Seguro (solo suma al inicial si no es "a cargo del cliente")
|
||||||
|
seguro_para_inicial = 0.0
|
||||||
|
if p.seguro and not p.seguro_a_cargo_cliente:
|
||||||
|
seguro_para_inicial = p.seguro
|
||||||
|
|
||||||
|
# Placas
|
||||||
|
placas = p.placas_monto if (p.incluir_placas and p.placas_monto) else 0.0
|
||||||
|
|
||||||
|
# Total pago inicial
|
||||||
|
total_inicial = round(ra_monto + seguro_para_inicial + comision + placas, 2)
|
||||||
|
|
||||||
|
return CotizacionResult(
|
||||||
|
renta_anticipada_monto=round(ra_monto, 2),
|
||||||
|
valor_residual_total=round(vr_total, 2),
|
||||||
|
valor_residual_por_anio=vr_por_anio,
|
||||||
|
comision_monto=round(comision, 2),
|
||||||
|
total_pago_inicial=total_inicial,
|
||||||
|
renta_mensual=renta_mensual,
|
||||||
|
nuevo_precio=round(nuevo_precio, 2),
|
||||||
|
)
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,81 @@
|
|||||||
|
"""
|
||||||
|
Descarga de media desde EvolutionAPI v2.
|
||||||
|
|
||||||
|
Cuando el webhook de EvolutionAPI entrega un mensaje con un documento adjunto,
|
||||||
|
no incluye el base64 por default. Hay que llamar al endpoint
|
||||||
|
POST /chat/getBase64FromMediaMessage/{instance} con el `key` del mensaje para
|
||||||
|
obtener el binario codificado.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
EVOLUTION_URL = os.getenv("EVOLUTION_API_URL")
|
||||||
|
EVOLUTION_KEY = os.getenv("EVOLUTION_API_KEY")
|
||||||
|
EVOLUTION_INSTANCE = os.getenv("EVOLUTION_INSTANCE")
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict:
|
||||||
|
return {
|
||||||
|
"apikey": EVOLUTION_KEY or "",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def descargar_pdf_base64(
|
||||||
|
message_key: dict,
|
||||||
|
message_data: Optional[dict] = None,
|
||||||
|
instance: Optional[str] = None,
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Descarga el base64 de un documento recibido vía EvolutionAPI.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message_key: dict con remoteJid, id, fromMe (el `key` del webhook).
|
||||||
|
message_data: objeto `message` completo del webhook (opcional, algunos
|
||||||
|
deployments de Evolution lo aceptan directamente).
|
||||||
|
instance: nombre de la instancia; si no viene, usa EVOLUTION_INSTANCE.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
String base64 del PDF o None si la descarga falla.
|
||||||
|
"""
|
||||||
|
if not EVOLUTION_URL:
|
||||||
|
logger.error("EVOLUTION_API_URL no configurada")
|
||||||
|
return None
|
||||||
|
if not message_key:
|
||||||
|
logger.error("descargar_pdf_base64: message_key vacío")
|
||||||
|
return None
|
||||||
|
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/chat/getBase64FromMediaMessage/{inst}"
|
||||||
|
|
||||||
|
# Formato aceptado por Evolution v2: {"message": {"key": {...}}, "convertToMp4": false}
|
||||||
|
payload: dict = {
|
||||||
|
"message": {"key": message_key},
|
||||||
|
"convertToMp4": False,
|
||||||
|
}
|
||||||
|
if message_data:
|
||||||
|
payload["message"]["message"] = message_data
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error descargando media de Evolution: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Evolution v2 devuelve {"base64": "...", "mimetype": "...", "fileName": "..."}
|
||||||
|
# o, en algunas versiones, anidado en "media".
|
||||||
|
b64 = data.get("base64")
|
||||||
|
if not b64 and isinstance(data.get("media"), dict):
|
||||||
|
b64 = data["media"].get("base64")
|
||||||
|
if not b64:
|
||||||
|
logger.error("Respuesta de Evolution sin base64: %s", str(data)[:200])
|
||||||
|
return None
|
||||||
|
return b64
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""
|
||||||
|
Detección de marca + tipo de vehículo a partir del input del usuario.
|
||||||
|
|
||||||
|
Primero intenta matchear contra una lista de marcas conocidas (barato,
|
||||||
|
inmediato). Si el input solo trae el modelo (ej. "Hilux 2025 pr 520,000"),
|
||||||
|
consulta a GPT-4o-mini para inferir la marca desde el nombre del modelo.
|
||||||
|
El `tipo` se extrae limpiando marca, año, precio y palabras clave del input.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_openai_client: AsyncOpenAI | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client() -> AsyncOpenAI:
|
||||||
|
global _openai_client
|
||||||
|
if _openai_client is None:
|
||||||
|
_openai_client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
||||||
|
return _openai_client
|
||||||
|
|
||||||
|
|
||||||
|
MARCAS = {
|
||||||
|
"TOYOTA", "VOLKSWAGEN", "BMW", "PORSCHE", "MERCEDES BENZ", "MERCEDES",
|
||||||
|
"AUDI", "MAZDA", "NISSAN", "FORD", "CHEVROLET", "GMC", "CADILLAC",
|
||||||
|
"LINCOLN", "LAND ROVER", "CUPRA", "HONDA", "HYUNDAI", "KIA", "SEAT",
|
||||||
|
"VOLVO", "JEEP", "DODGE", "RAM", "RENAULT", "PEUGEOT", "CITROEN",
|
||||||
|
"FIAT", "ALFA ROMEO", "FERRARI", "LAMBORGHINI", "MASERATI", "BENTLEY",
|
||||||
|
"ROLLS ROYCE", "ASTON MARTIN", "JAGUAR", "MINI", "SUBARU", "MITSUBISHI",
|
||||||
|
"SUZUKI", "ISUZU", "KENWORTH", "PETERBILT", "FREIGHTLINER", "INTERNATIONAL",
|
||||||
|
"MACK", "VOLVO TRUCKS", "SCANIA", "MAN", "DAF", "IVECO", "GML", "JAC",
|
||||||
|
"SINOTRUK", "SITRAK", "DEVELON", "BOBCAT", "CATERPILLAR", "JOHN DEERE",
|
||||||
|
"KOMATSU", "CASE", "ADM", "CARROCERIAS LAREDO",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Las marcas multi-palabra se prueban primero para evitar matches parciales
|
||||||
|
# (ej. "MERCEDES BENZ" antes que "MERCEDES").
|
||||||
|
_MARCAS_ORDENADAS = sorted(MARCAS, key=lambda m: (-len(m), m))
|
||||||
|
|
||||||
|
|
||||||
|
PALABRAS_RUIDO = re.compile(
|
||||||
|
r"\b(PR|PRECIO|REFERENCIA|DE|PARA|EL|LA|DAME|COTIZAR|COTIZAME|ARMA)\b",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _limpiar_tipo(input_upper: str, marca: str) -> str:
|
||||||
|
t = input_upper
|
||||||
|
if marca:
|
||||||
|
t = t.replace(marca, " ")
|
||||||
|
t = PALABRAS_RUIDO.sub(" ", t)
|
||||||
|
t = re.sub(r"\$[\d,]+\.?\d*", " ", t)
|
||||||
|
t = re.sub(r"\b\d{4}\b", " ", t) # año
|
||||||
|
t = re.sub(r"\b\d+[KkMm]?\b", " ", t) # montos / números sueltos
|
||||||
|
t = re.sub(r"[^A-ZÁÉÍÓÚÑ0-9 ]", " ", t) # signos y símbolos
|
||||||
|
t = " ".join(t.split()).strip()
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
async def detectar_marca(input_usuario: str, tipo_vehiculo: str = "") -> tuple[str, str]:
|
||||||
|
"""Devuelve (marca, tipo) en mayúsculas a partir del texto del usuario.
|
||||||
|
|
||||||
|
- Paso 1: matchea marcas conocidas dentro del input.
|
||||||
|
- Paso 2: si no hay marca y hay un `tipo_vehiculo` (extraído antes por el
|
||||||
|
intérprete o por regex), pregunta a GPT-4o-mini qué marca corresponde
|
||||||
|
a ese modelo.
|
||||||
|
- Paso 3: extrae un `tipo` limpio quitando marca, año, precio y ruido.
|
||||||
|
"""
|
||||||
|
if not input_usuario:
|
||||||
|
return ("", (tipo_vehiculo or "").upper().strip())
|
||||||
|
|
||||||
|
input_upper = input_usuario.upper()
|
||||||
|
|
||||||
|
marca_detectada = ""
|
||||||
|
for marca in _MARCAS_ORDENADAS:
|
||||||
|
if re.search(rf"\b{re.escape(marca)}\b", input_upper):
|
||||||
|
marca_detectada = marca
|
||||||
|
break
|
||||||
|
|
||||||
|
if not marca_detectada and tipo_vehiculo:
|
||||||
|
modelo = tipo_vehiculo.strip()
|
||||||
|
prompt = (
|
||||||
|
f"¿De qué marca automotriz es el vehículo llamado '{modelo}'? "
|
||||||
|
"Responde ÚNICAMENTE el nombre de la marca en mayúsculas, sin "
|
||||||
|
"explicación. Si es maquinaria o no lo sabes, responde DESCONOCIDA."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
client = _get_client()
|
||||||
|
resp = await client.chat.completions.create(
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
messages=[{"role": "user", "content": prompt}],
|
||||||
|
max_tokens=20,
|
||||||
|
temperature=0,
|
||||||
|
)
|
||||||
|
marca_gpt = (resp.choices[0].message.content or "").strip().upper()
|
||||||
|
if marca_gpt and marca_gpt != "DESCONOCIDA":
|
||||||
|
marca_detectada = marca_gpt
|
||||||
|
except Exception:
|
||||||
|
logger.exception("GPT no pudo inferir marca para modelo=%r", modelo)
|
||||||
|
|
||||||
|
tipo_limpio = _limpiar_tipo(input_upper, marca_detectada)
|
||||||
|
if not tipo_limpio and tipo_vehiculo:
|
||||||
|
tipo_limpio = tipo_vehiculo.upper().strip()
|
||||||
|
|
||||||
|
return (marca_detectada, tipo_limpio)
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
"""
|
||||||
|
Capa de pagos agnóstica. De inicio integra Conekta vía su API REST
|
||||||
|
(no usamos el SDK de Python: cambia de versión y agrega dependencia).
|
||||||
|
|
||||||
|
Expone una sola función pública:
|
||||||
|
crear_link_cobro(monto, descripcion, cliente_nombre, ...) -> dict
|
||||||
|
|
||||||
|
Que internamente delega al proveedor activo (env var PROVEEDOR_PAGOS).
|
||||||
|
Retorna {"link", "id", "proveedor"} o lanza Exception.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PROVEEDOR_ACTIVO = os.getenv("PROVEEDOR_PAGOS", "conekta")
|
||||||
|
CONEKTA_PRIVATE_KEY = os.getenv("CONEKTA_PRIVATE_KEY", "")
|
||||||
|
CONEKTA_API_URL = "https://api.conekta.io"
|
||||||
|
CONEKTA_API_VERSION = "application/vnd.conekta-v2.2.0+json"
|
||||||
|
|
||||||
|
# Conekta valida `name` con un regex propio. Empíricamente rechaza:
|
||||||
|
# vacíos, saltos de línea, guion largo (—), puntos, paréntesis y otros
|
||||||
|
# símbolos comunes en razones sociales (ej. "S.A. DE C.V. (CITY SPORT)").
|
||||||
|
# Mínimo ~3 caracteres útiles, máximo 250.
|
||||||
|
#
|
||||||
|
# Política conservadora: whitelist de caracteres "seguros".
|
||||||
|
_CONEKTA_NAME_FALLBACK = "Pago WK Financing"
|
||||||
|
# Letras latinas con acentos + ñ, dígitos, espacios, guion y coma.
|
||||||
|
_RE_NOMBRE_SEGURO = re.compile(r"[^A-Za-z0-9ÁÉÍÓÚÜÑáéíóúüñ \-,]+")
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitizar_nombre_conekta(texto: str | None) -> str:
|
||||||
|
"""Devuelve un `name` válido para checkout/line_item de Conekta.
|
||||||
|
|
||||||
|
Reglas:
|
||||||
|
- Vacío / None tras strip → fallback.
|
||||||
|
- Normaliza em/en dash a guion normal "-".
|
||||||
|
- DEJA SOLO: letras (con acentos y ñ), dígitos, espacios, "-" y ",".
|
||||||
|
Cualquier otro carácter (puntos, paréntesis, &, /, símbolos de control,
|
||||||
|
saltos de línea, etc.) se reemplaza por espacio.
|
||||||
|
- Colapsa espacios y recorta extremos.
|
||||||
|
- Recorta a 250 chars.
|
||||||
|
- Si queda con <3 chars útiles → fallback.
|
||||||
|
"""
|
||||||
|
s = (texto or "").strip()
|
||||||
|
if not s:
|
||||||
|
return _CONEKTA_NAME_FALLBACK
|
||||||
|
# Normaliza guiones largos / em dash / en dash a "-".
|
||||||
|
s = s.replace("—", "-").replace("–", "-").replace("―", "-")
|
||||||
|
# Whitelist: cualquier cosa fuera del set seguro → espacio.
|
||||||
|
s = _RE_NOMBRE_SEGURO.sub(" ", s)
|
||||||
|
# Colapsa espacios.
|
||||||
|
s = re.sub(r"\s+", " ", s).strip()
|
||||||
|
if len(s) < 3:
|
||||||
|
return _CONEKTA_NAME_FALLBACK
|
||||||
|
return s[:250]
|
||||||
|
|
||||||
|
|
||||||
|
async def crear_link_cobro(
|
||||||
|
monto: float,
|
||||||
|
descripcion: str,
|
||||||
|
cliente_nombre: str,
|
||||||
|
cliente_email: str | None = None,
|
||||||
|
cliente_telefono: str | None = None,
|
||||||
|
referencia: str | None = None,
|
||||||
|
dias_expiracion: int = 30,
|
||||||
|
) -> dict:
|
||||||
|
"""Genera un link de cobro con el proveedor activo.
|
||||||
|
|
||||||
|
Retorna: {"link": str, "id": str, "proveedor": str}
|
||||||
|
Lanza Exception si falla.
|
||||||
|
"""
|
||||||
|
if PROVEEDOR_ACTIVO == "conekta":
|
||||||
|
return await _crear_link_conekta(
|
||||||
|
monto=monto,
|
||||||
|
descripcion=descripcion,
|
||||||
|
cliente_nombre=cliente_nombre,
|
||||||
|
cliente_email=cliente_email,
|
||||||
|
cliente_telefono=cliente_telefono,
|
||||||
|
referencia=referencia,
|
||||||
|
dias_expiracion=dias_expiracion,
|
||||||
|
)
|
||||||
|
raise NotImplementedError(f"Proveedor de pagos no soportado: {PROVEEDOR_ACTIVO}")
|
||||||
|
|
||||||
|
|
||||||
|
async def _crear_link_conekta(
|
||||||
|
monto: float,
|
||||||
|
descripcion: str,
|
||||||
|
cliente_nombre: str,
|
||||||
|
cliente_email: str | None,
|
||||||
|
cliente_telefono: str | None,
|
||||||
|
referencia: str | None,
|
||||||
|
dias_expiracion: int,
|
||||||
|
) -> dict:
|
||||||
|
if not CONEKTA_PRIVATE_KEY:
|
||||||
|
raise RuntimeError("CONEKTA_PRIVATE_KEY no está seteada")
|
||||||
|
|
||||||
|
# Conekta usa Basic Auth con la private key como usuario y password vacío.
|
||||||
|
auth_str = base64.b64encode(f"{CONEKTA_PRIVATE_KEY}:".encode()).decode()
|
||||||
|
|
||||||
|
monto_centavos = int(round(monto * 100))
|
||||||
|
expires_at = int(time.time()) + (dias_expiracion * 86400)
|
||||||
|
|
||||||
|
# Conekta exige email en customer_info para crear PaymentLink — sin
|
||||||
|
# él responde 422. Si no se proporciona, cae a un email default.
|
||||||
|
customer_info: dict = {
|
||||||
|
"name": cliente_nombre,
|
||||||
|
"email": cliente_email or "soporte@collinasystems.com",
|
||||||
|
}
|
||||||
|
if cliente_telefono:
|
||||||
|
customer_info["phone"] = cliente_telefono
|
||||||
|
|
||||||
|
name_sanitizado = _sanitizar_nombre_conekta(descripcion)
|
||||||
|
logger.info("Conekta checkout name → %r (monto=%d centavos)", name_sanitizado, monto_centavos)
|
||||||
|
|
||||||
|
body = {
|
||||||
|
"name": name_sanitizado,
|
||||||
|
"type": "PaymentLink",
|
||||||
|
"recurrent": False,
|
||||||
|
"expires_at": expires_at,
|
||||||
|
"allowed_payment_methods": ["cash", "card", "bank_transfer"],
|
||||||
|
"needs_shipping_contact": False,
|
||||||
|
"order_template": {
|
||||||
|
"currency": "MXN",
|
||||||
|
"line_items": [{
|
||||||
|
"name": name_sanitizado,
|
||||||
|
"unit_price": monto_centavos,
|
||||||
|
"quantity": 1,
|
||||||
|
}],
|
||||||
|
"customer_info": customer_info,
|
||||||
|
"metadata": {"referencia": referencia or ""},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Accept": CONEKTA_API_VERSION,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Basic {auth_str}",
|
||||||
|
}
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
f"{CONEKTA_API_URL}/checkouts",
|
||||||
|
json=body,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
if resp.status_code not in (200, 201):
|
||||||
|
logger.error(
|
||||||
|
"Conekta /checkouts respondió %s: %s",
|
||||||
|
resp.status_code, resp.text[:1000],
|
||||||
|
)
|
||||||
|
raise RuntimeError(f"Conekta respondió {resp.status_code}")
|
||||||
|
|
||||||
|
data = resp.json()
|
||||||
|
# Loguear la respuesta completa la PRIMERA vez para confirmar el campo
|
||||||
|
# exacto donde viene la URL del checkout. Quitar este log luego.
|
||||||
|
logger.info("Conekta /checkouts OK — payload completo: %s", data)
|
||||||
|
|
||||||
|
# La URL del checkout puede venir como `url` o anidada en `checkout.url`
|
||||||
|
# según versión de la API; probamos ambos.
|
||||||
|
link = data.get("url") or (data.get("checkout") or {}).get("url")
|
||||||
|
if not link:
|
||||||
|
logger.error("Conekta no devolvió URL del checkout: %s", data)
|
||||||
|
raise RuntimeError("Conekta no devolvió URL del checkout")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"link": link,
|
||||||
|
"id": data.get("id") or "",
|
||||||
|
"proveedor": "conekta",
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
"""
|
||||||
|
Extractor de parámetros financieros desde un PDF de cotización WK.
|
||||||
|
|
||||||
|
Usa pdfplumber, que detecta tablas automáticamente a partir de los bordes del
|
||||||
|
PDF. `page.extract_table()` devuelve directamente la estructura
|
||||||
|
`[[etiqueta, valor], ...]` cuando el layout es una tabla de dos columnas,
|
||||||
|
que es exactamente el formato de las cotizaciones WK. Como fallback, si
|
||||||
|
`extract_table()` no encuentra nada, se parsea `extract_text()` línea por
|
||||||
|
línea emparejando cada etiqueta con la línea siguiente.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _limpiar(texto: str | None) -> str:
|
||||||
|
if not texto:
|
||||||
|
return ""
|
||||||
|
return " ".join(texto.split()).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_monto(valor: str) -> float:
|
||||||
|
"""Convierte '$ 1,650,000.00' / '1650000' en float. 0.0 si falla."""
|
||||||
|
if not valor:
|
||||||
|
return 0.0
|
||||||
|
limpio = re.sub(r"[^\d.]", "", valor.replace(",", ""))
|
||||||
|
if not limpio:
|
||||||
|
return 0.0
|
||||||
|
if limpio.count(".") > 1:
|
||||||
|
partes = limpio.split(".")
|
||||||
|
limpio = "".join(partes[:-1]) + "." + partes[-1]
|
||||||
|
try:
|
||||||
|
return float(limpio)
|
||||||
|
except ValueError:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_int(valor: str) -> int:
|
||||||
|
m = re.search(r"(\d+)", valor or "")
|
||||||
|
return int(m.group(1)) if m else 0
|
||||||
|
|
||||||
|
|
||||||
|
def _buscar_por_tokens(tabla: dict[str, str], tokens: list[str]) -> str:
|
||||||
|
"""Primer valor cuya clave contenga TODOS los tokens (case-insensitive)."""
|
||||||
|
tokens_up = [t.upper() for t in tokens]
|
||||||
|
for clave, valor in tabla.items():
|
||||||
|
if all(tok in clave for tok in tokens_up):
|
||||||
|
return valor
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _buscar_alternativas(tabla: dict[str, str], alternativas: list[list[str]]) -> str:
|
||||||
|
"""Prueba múltiples conjuntos de tokens y devuelve el primero que matchee.
|
||||||
|
|
||||||
|
Útil cuando el cliente puede escribir la misma etiqueta de varias formas
|
||||||
|
(ej. 'VALOR RESIDUAL TOTAL' vs 'VALOR RESIDUAL ANUAL').
|
||||||
|
"""
|
||||||
|
for tokens in alternativas:
|
||||||
|
val = _buscar_por_tokens(tabla, tokens)
|
||||||
|
if val:
|
||||||
|
return val
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
# Ordinales para el desglose de VR por año. Soporta:
|
||||||
|
# "AÑO 1", "ANO 1" (formato antiguo)
|
||||||
|
# "1ER AÑO", "1 ER AÑO", "1RO AÑO" (formato nuevo "1er AÑO")
|
||||||
|
# "2 DO AÑO", "2DO AÑO" (formato nuevo "2 do AÑO")
|
||||||
|
# "3ER AÑO", "4TO AÑO", "5TO AÑO" (3er / 4to / 5to)
|
||||||
|
# "PRIMER AÑO", "SEGUNDO AÑO", ... (cardinales en texto)
|
||||||
|
_ORDINALES_ANO: dict[int, list[list[str]]] = {
|
||||||
|
1: [["AÑO 1"], ["ANO 1"], ["1ER", "AÑO"], ["1ER", "ANO"],
|
||||||
|
["1RO", "AÑO"], ["1RO", "ANO"], ["PRIMER", "AÑO"], ["PRIMER", "ANO"]],
|
||||||
|
2: [["AÑO 2"], ["ANO 2"], ["2DO", "AÑO"], ["2DO", "ANO"],
|
||||||
|
["2 DO", "AÑO"], ["2 DO", "ANO"], ["SEGUNDO", "AÑO"], ["SEGUNDO", "ANO"]],
|
||||||
|
3: [["AÑO 3"], ["ANO 3"], ["3ER", "AÑO"], ["3ER", "ANO"],
|
||||||
|
["3RO", "AÑO"], ["3RO", "ANO"], ["TERCER", "AÑO"], ["TERCER", "ANO"]],
|
||||||
|
4: [["AÑO 4"], ["ANO 4"], ["4TO", "AÑO"], ["4TO", "ANO"],
|
||||||
|
["4 TO", "AÑO"], ["4 TO", "ANO"], ["CUARTO", "AÑO"], ["CUARTO", "ANO"]],
|
||||||
|
5: [["AÑO 5"], ["ANO 5"], ["5TO", "AÑO"], ["5TO", "ANO"],
|
||||||
|
["5 TO", "AÑO"], ["5 TO", "ANO"], ["QUINTO", "AÑO"], ["QUINTO", "ANO"]],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _tabla_desde_extract_table(page) -> dict[str, str]:
|
||||||
|
"""Construye {etiqueta_upper: valor} desde page.extract_table().
|
||||||
|
|
||||||
|
pdfplumber a veces colapsa varias filas visuales en una sola celda con
|
||||||
|
'\\n' como separador (cuando los bordes de la tabla no se detectan bien).
|
||||||
|
Por eso dividimos etiqueta y valor por '\\n' y las emparejamos por
|
||||||
|
posición para recuperar las filas originales.
|
||||||
|
"""
|
||||||
|
tabla: dict[str, str] = {}
|
||||||
|
try:
|
||||||
|
filas = page.extract_table() or []
|
||||||
|
except Exception:
|
||||||
|
logger.exception("pdfplumber.extract_table() falló")
|
||||||
|
filas = []
|
||||||
|
|
||||||
|
filas_expandidas: list[tuple[str, str]] = []
|
||||||
|
for fila in filas:
|
||||||
|
if not fila or len(fila) < 2:
|
||||||
|
continue
|
||||||
|
col_etiqueta = fila[0] or ""
|
||||||
|
col_valor = fila[-1] or ""
|
||||||
|
etiquetas = [e.strip() for e in col_etiqueta.split("\n")]
|
||||||
|
valores = [v.strip() for v in col_valor.split("\n")]
|
||||||
|
total = max(len(etiquetas), len(valores))
|
||||||
|
for i in range(total):
|
||||||
|
et = etiquetas[i] if i < len(etiquetas) else ""
|
||||||
|
val = valores[i] if i < len(valores) else ""
|
||||||
|
if et or val:
|
||||||
|
filas_expandidas.append((et, val))
|
||||||
|
|
||||||
|
for et, val in filas_expandidas:
|
||||||
|
etiqueta = _limpiar(et).upper()
|
||||||
|
valor = _limpiar(val)
|
||||||
|
if etiqueta and valor:
|
||||||
|
tabla.setdefault(etiqueta, valor)
|
||||||
|
return tabla
|
||||||
|
|
||||||
|
|
||||||
|
def _tabla_desde_texto(page) -> dict[str, str]:
|
||||||
|
"""Fallback: empareja cada línea de etiqueta con la siguiente línea que
|
||||||
|
parezca un valor (monto, texto corto, 'NO INCLUIDO', etc.)."""
|
||||||
|
try:
|
||||||
|
texto = page.extract_text() or ""
|
||||||
|
except Exception:
|
||||||
|
logger.exception("pdfplumber.extract_text() falló")
|
||||||
|
return {}
|
||||||
|
lineas = [l.strip() for l in texto.splitlines() if l.strip()]
|
||||||
|
tabla: dict[str, str] = {}
|
||||||
|
i = 0
|
||||||
|
while i < len(lineas) - 1:
|
||||||
|
etiqueta = lineas[i].upper()
|
||||||
|
valor = lineas[i + 1]
|
||||||
|
# Una "etiqueta" razonable tiene letras; un "valor" puede ser $, número
|
||||||
|
# o texto corto. Evito emparejar dos líneas de puro texto largo.
|
||||||
|
if re.search(r"[A-Z]", etiqueta) and valor:
|
||||||
|
tabla.setdefault(etiqueta, valor)
|
||||||
|
i += 2
|
||||||
|
return tabla
|
||||||
|
|
||||||
|
|
||||||
|
def extraer_parametros_pdf(base64_str: str) -> dict:
|
||||||
|
"""Extrae los campos de una cotización WK y devuelve ratios + metadata.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: si el base64 es inválido, el PDF no tiene texto, o no se
|
||||||
|
encuentra el precio de referencia (sin precio no hay ratios).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
pdf_bytes = base64.b64decode(base64_str)
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(f"base64 inválido: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
import pdfplumber
|
||||||
|
except ImportError as e:
|
||||||
|
raise ValueError(f"pdfplumber no instalado: {e}")
|
||||||
|
|
||||||
|
tabla: dict[str, str] = {}
|
||||||
|
try:
|
||||||
|
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
|
||||||
|
if not pdf.pages:
|
||||||
|
raise ValueError("PDF sin páginas")
|
||||||
|
page = pdf.pages[0]
|
||||||
|
tabla = _tabla_desde_extract_table(page)
|
||||||
|
if not tabla:
|
||||||
|
logger.info("extract_table() vacío, usando fallback por texto")
|
||||||
|
tabla = _tabla_desde_texto(page)
|
||||||
|
except ValueError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(f"No se pudo abrir el PDF: {e}")
|
||||||
|
|
||||||
|
if not tabla:
|
||||||
|
raise ValueError("PDF sin texto extraíble")
|
||||||
|
|
||||||
|
precio = _parse_monto(_buscar_por_tokens(tabla, ["PRECIO", "REFERENCIA"]))
|
||||||
|
if precio <= 0:
|
||||||
|
raise ValueError("No se encontró precio de referencia")
|
||||||
|
|
||||||
|
plazo_meses = _parse_int(_buscar_por_tokens(tabla, ["PLAZO"])) or 48
|
||||||
|
|
||||||
|
renta_mensual = _parse_monto(_buscar_por_tokens(tabla, ["RENTA", "MENSUAL"]))
|
||||||
|
comision = _parse_monto(_buscar_por_tokens(tabla, ["COMISION"]))
|
||||||
|
renta_anticipada = _parse_monto(_buscar_por_tokens(tabla, ["RENTA", "ANTICIPADA"]))
|
||||||
|
# VR: el template viejo usaba "VALOR RESIDUAL TOTAL"; el nuevo usa
|
||||||
|
# "VALOR RESIDUAL ANUAL (dividido en 4 años)". Aceptamos ambos.
|
||||||
|
valor_residual_total = _parse_monto(
|
||||||
|
_buscar_alternativas(
|
||||||
|
tabla,
|
||||||
|
[
|
||||||
|
["VALOR", "RESIDUAL", "TOTAL"],
|
||||||
|
["VALOR", "RESIDUAL", "ANUAL"],
|
||||||
|
["VALOR", "RESIDUAL"], # último recurso: cualquier etiqueta VR
|
||||||
|
],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# "TOTAL PAGO INICIAL" (template viejo) o "PAGO INICIAL TOTAL" (nuevo).
|
||||||
|
total_pago_inicial = _parse_monto(
|
||||||
|
_buscar_alternativas(
|
||||||
|
tabla,
|
||||||
|
[
|
||||||
|
["TOTAL", "PAGO", "INICIAL"],
|
||||||
|
["PAGO", "INICIAL", "TOTAL"],
|
||||||
|
["TOTAL", "PAGO"],
|
||||||
|
["PAGO", "INICIAL"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
seguro_descripcion = _buscar_por_tokens(tabla, ["SEGURO"]) or ""
|
||||||
|
placas_descripcion = _buscar_por_tokens(tabla, ["PLACAS"]) or ""
|
||||||
|
|
||||||
|
# Vehículo (marca/tipo/anio/unidades) — útil para el flujo
|
||||||
|
# "cambiar unidades" donde no llega un mensaje con vehículo nuevo.
|
||||||
|
marca_str = _limpiar(_buscar_por_tokens(tabla, ["MARCA"])).upper()
|
||||||
|
tipo_str = _limpiar(_buscar_por_tokens(tabla, ["TIPO"])).upper()
|
||||||
|
modelo_str = _buscar_por_tokens(tabla, ["MODELO"]) or ""
|
||||||
|
|
||||||
|
anio_match = re.search(r"\b(19|20)\d{2}\b", modelo_str)
|
||||||
|
anio_original = int(anio_match.group(0)) if anio_match else 0
|
||||||
|
|
||||||
|
unidades_match = re.search(r"\((\d+)\s+UNIDADES?\)", modelo_str, re.IGNORECASE)
|
||||||
|
unidades_originales = int(unidades_match.group(1)) if unidades_match else 1
|
||||||
|
|
||||||
|
def vr_ano(n: int) -> float:
|
||||||
|
alternativas = _ORDINALES_ANO.get(n, [[f"AÑO {n}"], [f"ANO {n}"]])
|
||||||
|
val = _buscar_alternativas(tabla, alternativas)
|
||||||
|
return _parse_monto(val)
|
||||||
|
|
||||||
|
vr_anos = {n: vr_ano(n) for n in range(1, 6)}
|
||||||
|
|
||||||
|
def ratio(monto: float) -> float:
|
||||||
|
return round(monto / precio, 6) if precio else 0.0
|
||||||
|
|
||||||
|
resultado = {
|
||||||
|
"marca_original": marca_str,
|
||||||
|
"tipo_original": tipo_str,
|
||||||
|
"anio_original": anio_original,
|
||||||
|
"unidades_originales": unidades_originales,
|
||||||
|
"precio_referencia_original": precio,
|
||||||
|
"plazo_meses": plazo_meses,
|
||||||
|
"renta_mensual_pct": ratio(renta_mensual),
|
||||||
|
"seguro_descripcion": seguro_descripcion,
|
||||||
|
"comision_pct": ratio(comision),
|
||||||
|
"placas_descripcion": placas_descripcion,
|
||||||
|
"renta_anticipada_pct": ratio(renta_anticipada),
|
||||||
|
"valor_residual_pct": ratio(valor_residual_total),
|
||||||
|
"vr_ano_1_pct": ratio(vr_anos[1]),
|
||||||
|
"vr_ano_2_pct": ratio(vr_anos[2]),
|
||||||
|
"vr_ano_3_pct": ratio(vr_anos[3]),
|
||||||
|
"vr_ano_4_pct": ratio(vr_anos[4]),
|
||||||
|
"vr_ano_5_pct": ratio(vr_anos[5]),
|
||||||
|
"total_pago_inicial_pct": ratio(total_pago_inicial),
|
||||||
|
# Valores absolutos del PDF original (útiles para debug / mensajes).
|
||||||
|
"_renta_mensual": renta_mensual,
|
||||||
|
"_comision": comision,
|
||||||
|
"_renta_anticipada": renta_anticipada,
|
||||||
|
"_valor_residual": valor_residual_total,
|
||||||
|
"_vr_ano_1": vr_anos[1],
|
||||||
|
"_vr_ano_2": vr_anos[2],
|
||||||
|
"_vr_ano_3": vr_anos[3],
|
||||||
|
"_vr_ano_4": vr_anos[4],
|
||||||
|
"_vr_ano_5": vr_anos[5],
|
||||||
|
"_total_pago_inicial": total_pago_inicial,
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"PDF clonado: precio=%.2f plazo=%s renta=%.2f com=%.2f RA=%.2f VR=%.2f",
|
||||||
|
precio, plazo_meses, renta_mensual, comision, renta_anticipada,
|
||||||
|
valor_residual_total,
|
||||||
|
)
|
||||||
|
return resultado
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
|
||||||
|
from src.models.schemas import CotizacionParams, CotizacionResult
|
||||||
|
|
||||||
|
TEMPLATE_PATH = Path(__file__).resolve().parents[2] / "Plantilla_WK2.docm"
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_money(value: float) -> str:
|
||||||
|
if value == 0:
|
||||||
|
return ""
|
||||||
|
return f"$ {value:,.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _get_paragraph_text(paragraph) -> str:
|
||||||
|
"""Get full text of a paragraph by joining all runs."""
|
||||||
|
return "".join(run.text for run in paragraph.runs)
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_in_paragraph(paragraph, replacements: dict[str, str]):
|
||||||
|
"""Replace placeholders that may be split across multiple runs."""
|
||||||
|
full_text = _get_paragraph_text(paragraph)
|
||||||
|
if not any(key in full_text for key in replacements):
|
||||||
|
return
|
||||||
|
for key, val in replacements.items():
|
||||||
|
full_text = full_text.replace(key, val)
|
||||||
|
# Strip whitespace padding from template
|
||||||
|
full_text = full_text.strip()
|
||||||
|
# Put all text in first run, clear the rest
|
||||||
|
if paragraph.runs:
|
||||||
|
paragraph.runs[0].text = full_text
|
||||||
|
for run in paragraph.runs[1:]:
|
||||||
|
run.text = ""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _open_docm_as_docx(docm_path: str, dest_path: str):
|
||||||
|
"""Copy a .docm and patch its content type so python-docx can open it."""
|
||||||
|
with zipfile.ZipFile(docm_path, "r") as zin:
|
||||||
|
with zipfile.ZipFile(dest_path, "w") as zout:
|
||||||
|
for item in zin.infolist():
|
||||||
|
data = zin.read(item.filename)
|
||||||
|
if item.filename == "[Content_Types].xml":
|
||||||
|
data = data.replace(
|
||||||
|
b"application/vnd.ms-word.document.macroEnabled.main+xml",
|
||||||
|
b"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||||
|
)
|
||||||
|
zout.writestr(item, data)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_replacements(params: CotizacionParams, result: CotizacionResult) -> dict[str, str]:
|
||||||
|
fecha_hoy = date.today().strftime("%d/%m/%Y")
|
||||||
|
nombre_cliente = params.nombre_cliente or "A QUIEN CORRESPONDA"
|
||||||
|
atencion = params.atencion or "A QUIEN CORRESPONDA"
|
||||||
|
|
||||||
|
modelo_str = str(params.anio)
|
||||||
|
detalles_modelo = []
|
||||||
|
if params.kms and params.kms > 0:
|
||||||
|
detalles_modelo.append(f"{params.kms:,} KMS")
|
||||||
|
if getattr(params, "unidades", None) and params.unidades > 1:
|
||||||
|
detalles_modelo.append(f"{params.unidades} UNIDADES")
|
||||||
|
if detalles_modelo:
|
||||||
|
modelo_str += " (" + ", ".join(detalles_modelo) + ")"
|
||||||
|
|
||||||
|
# Encabezado: "ARRENDAMIENTO DE UNIDAD" vs "ARRENDAMIENTO DE FLOTILLA".
|
||||||
|
es_flotilla = bool(getattr(params, "unidades", None)) and params.unidades > 1
|
||||||
|
unidad_titulo = "FLOTILLA" if es_flotilla else "UNIDAD"
|
||||||
|
|
||||||
|
# Seguro
|
||||||
|
seguro_de_unidad = "DE UNIDAD"
|
||||||
|
if params.seguro_a_cargo_cliente:
|
||||||
|
seguro_val = "A CARGO DEL CLIENTE"
|
||||||
|
elif params.seguro and params.seguro > 0:
|
||||||
|
seguro_val = _fmt_money(params.seguro)
|
||||||
|
else:
|
||||||
|
seguro_val = "NO INCLUIDO"
|
||||||
|
|
||||||
|
# Si la comisión está "quitada", mostramos $ 0.00 explícito para que el
|
||||||
|
# cliente vea que se le está regalando (no que desaparezca la fila).
|
||||||
|
if params.incluir_comision:
|
||||||
|
comision_val = _fmt_money(result.comision_monto)
|
||||||
|
else:
|
||||||
|
comision_val = "$ 0.00"
|
||||||
|
|
||||||
|
if params.incluir_placas and params.placas_monto:
|
||||||
|
placas_val = _fmt_money(params.placas_monto)
|
||||||
|
else:
|
||||||
|
placas_val = "NO APLICA"
|
||||||
|
|
||||||
|
# Valor residual
|
||||||
|
vr_total = _fmt_money(result.valor_residual_total) if result.valor_residual_total > 0 else ""
|
||||||
|
vr_by_year = ["", "", "", "", ""]
|
||||||
|
if result.valor_residual_por_anio and params.anualizar_vr:
|
||||||
|
for anio, monto in result.valor_residual_por_anio.items():
|
||||||
|
idx = int(anio) - 1
|
||||||
|
if 0 <= idx < 5:
|
||||||
|
vr_by_year[idx] = _fmt_money(monto)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"$FECHA$": fecha_hoy,
|
||||||
|
"$A QUIEN CORRESPONDA1$": nombre_cliente,
|
||||||
|
"$A QUIEN CORRESPONDA2$": atencion,
|
||||||
|
"$MARCA$": params.marca.upper(),
|
||||||
|
"$TIPO$": params.tipo.upper(),
|
||||||
|
"$MODELO$": modelo_str,
|
||||||
|
"$PRECIO$": _fmt_money(params.precio_referencia),
|
||||||
|
"$MESES$": f"{params.plazo_meses} MESES",
|
||||||
|
"$RENTA$": _fmt_money(result.renta_mensual),
|
||||||
|
"$DE UNIDAD$": seguro_de_unidad,
|
||||||
|
"$SEGURO$": seguro_val,
|
||||||
|
"$COMISION$": comision_val,
|
||||||
|
"$PLACASYPERMISO$": placas_val,
|
||||||
|
"$ANTICIPADA$": _fmt_money(result.renta_anticipada_monto),
|
||||||
|
"$RESIDUALTOTAL$": vr_total,
|
||||||
|
"$RESIDUAL1$": vr_by_year[0],
|
||||||
|
"$RESIDUAL2$": vr_by_year[1],
|
||||||
|
"$RESIDUAL3$": vr_by_year[2],
|
||||||
|
"$RESIDUAL4$": vr_by_year[3],
|
||||||
|
"$RESIDUAL5$": vr_by_year[4],
|
||||||
|
"$TOTAL$": _fmt_money(result.total_pago_inicial),
|
||||||
|
"$UNIDAD$": unidad_titulo,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _build_docx(params: CotizacionParams, result: CotizacionResult, tmpdir: str) -> str:
|
||||||
|
"""Construye el .docx final dentro de tmpdir y devuelve su ruta."""
|
||||||
|
docx_path = os.path.join(tmpdir, "cotizacion.docx")
|
||||||
|
_open_docm_as_docx(str(TEMPLATE_PATH), docx_path)
|
||||||
|
|
||||||
|
doc = Document(docx_path)
|
||||||
|
replacements = _build_replacements(params, result)
|
||||||
|
|
||||||
|
# Replace placeholders in paragraphs and tables
|
||||||
|
for paragraph in doc.paragraphs:
|
||||||
|
_replace_in_paragraph(paragraph, replacements)
|
||||||
|
if "ARRENDAMIENTO DE" in paragraph.text.upper():
|
||||||
|
paragraph.runs[0].text = " " + paragraph.runs[0].text
|
||||||
|
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
for cell in row.cells:
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
_replace_in_paragraph(paragraph, replacements)
|
||||||
|
# Align all cells to the left and strip leading/trailing whitespace
|
||||||
|
for row in table.rows:
|
||||||
|
for cell in row.cells:
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||||
|
runs = paragraph.runs
|
||||||
|
if runs:
|
||||||
|
runs[0].text = runs[0].text.lstrip()
|
||||||
|
runs[-1].text = runs[-1].text.rstrip()
|
||||||
|
|
||||||
|
# Remove empty paragraphs inside multi-paragraph cells
|
||||||
|
# (e.g. RESIDUAL4/5 are paragraphs inside the same row as COMISION, PLACAS, etc.)
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
cells = row.cells
|
||||||
|
if len(cells) < 2:
|
||||||
|
continue
|
||||||
|
left_cell = cells[0]
|
||||||
|
right_cell = cells[-1]
|
||||||
|
left_paras = list(left_cell.paragraphs)
|
||||||
|
right_paras = list(right_cell.paragraphs)
|
||||||
|
if len(right_paras) <= 1:
|
||||||
|
continue
|
||||||
|
# Walk paired paragraphs in reverse to safely remove
|
||||||
|
for i in range(len(right_paras) - 1, -1, -1):
|
||||||
|
r_text = right_paras[i].text.strip()
|
||||||
|
if not r_text or re.search(r'\$[A-Z][A-Z0-9 ]+\$', r_text):
|
||||||
|
# Remove paragraph XML from right cell
|
||||||
|
right_paras[i]._element.getparent().remove(right_paras[i]._element)
|
||||||
|
# Remove matching paragraph from left cell if it exists
|
||||||
|
if i < len(left_paras):
|
||||||
|
left_paras[i]._element.getparent().remove(left_paras[i]._element)
|
||||||
|
|
||||||
|
# Remove rows where right cell is entirely empty
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows[:]:
|
||||||
|
if not row.cells[-1].text.strip():
|
||||||
|
row._tr.getparent().remove(row._tr)
|
||||||
|
|
||||||
|
doc.save(docx_path)
|
||||||
|
return docx_path
|
||||||
|
|
||||||
|
|
||||||
|
def _docx_to_pdf_bytes(docx_path: str, tmpdir: str) -> bytes:
|
||||||
|
"""Convierte el .docx a PDF y devuelve los bytes del PDF."""
|
||||||
|
soffice_cmd = "soffice" if shutil.which("soffice") else "libreoffice"
|
||||||
|
subprocess.run(
|
||||||
|
[soffice_cmd, "--headless", "--convert-to", "pdf", "--outdir", tmpdir, docx_path],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=60,
|
||||||
|
)
|
||||||
|
pdf_path = os.path.join(tmpdir, "cotizacion.pdf")
|
||||||
|
with open(pdf_path, "rb") as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
|
||||||
|
def _slug(texto: str) -> str:
|
||||||
|
"""Normaliza marca/tipo para usar como parte de un filename."""
|
||||||
|
t = (texto or "").strip().upper()
|
||||||
|
return re.sub(r"[^A-Z0-9]+", "_", t).strip("_") or "X"
|
||||||
|
|
||||||
|
|
||||||
|
def generar_pdf(params: CotizacionParams, result: CotizacionResult) -> bytes:
|
||||||
|
tmpdir = tempfile.mkdtemp()
|
||||||
|
try:
|
||||||
|
docx_path = _build_docx(params, result, tmpdir)
|
||||||
|
return _docx_to_pdf_bytes(docx_path, tmpdir)
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def generar_pdf_y_docx(params: CotizacionParams, result: CotizacionResult) -> tuple[bytes, str]:
|
||||||
|
"""Genera el PDF y deja una copia persistente del .docx en /tmp.
|
||||||
|
|
||||||
|
El archivo queda en un subdirectorio único (`/tmp/wk_docx_XXXX/`) para
|
||||||
|
evitar colisiones, pero el filename visible es limpio:
|
||||||
|
`Cotizacion_<MARCA>_<TIPO>_<plazo>m.docx`. El caller debe borrar el
|
||||||
|
directorio padre cuando ya no necesite el archivo.
|
||||||
|
"""
|
||||||
|
tmpdir = tempfile.mkdtemp()
|
||||||
|
try:
|
||||||
|
docx_tmp = _build_docx(params, result, tmpdir)
|
||||||
|
pdf_bytes = _docx_to_pdf_bytes(docx_tmp, tmpdir)
|
||||||
|
|
||||||
|
marca = _slug(params.marca)
|
||||||
|
tipo = _slug(params.tipo)
|
||||||
|
filename = f"Cotizacion_{marca}_{tipo}_{params.plazo_meses}m.docx"
|
||||||
|
dest_dir = tempfile.mkdtemp(prefix="wk_docx_", dir="/tmp")
|
||||||
|
docx_dest = os.path.join(dest_dir, filename)
|
||||||
|
shutil.copy(docx_tmp, docx_dest)
|
||||||
|
return pdf_bytes, docx_dest
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""
|
||||||
|
Gestión de recordatorios de cobranza automática.
|
||||||
|
|
||||||
|
Storage: Redis (persistente, una sola key con JSON list).
|
||||||
|
Tokens admin: Redis con TTL 30 min, asociados a un número de WhatsApp.
|
||||||
|
|
||||||
|
Estructura de cada recordatorio:
|
||||||
|
{
|
||||||
|
"id": str (uuid4),
|
||||||
|
"numero": str (10 dígitos, ej "2222127552"),
|
||||||
|
"nombre": str (ej "Paulino"),
|
||||||
|
"tipo": str ("diario" | "semanal" | "mensual"),
|
||||||
|
"hora": str (ej "08:30"),
|
||||||
|
"dias": list[int] (0=lunes...6=domingo),
|
||||||
|
"activo": bool,
|
||||||
|
"creado": str (ISO datetime),
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from src.services.session import get_client
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
KEY_ALL = "recordatorios:all"
|
||||||
|
ADMIN_TOKEN_TTL = 1800 # 30 minutos
|
||||||
|
MEXICO = ZoneInfo("America/Mexico_City")
|
||||||
|
|
||||||
|
|
||||||
|
async def get_recordatorios() -> list[dict]:
|
||||||
|
"""Devuelve TODOS los recordatorios. [] si Redis no responde o vacío."""
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(KEY_ALL)
|
||||||
|
if not data:
|
||||||
|
return []
|
||||||
|
return json.loads(data)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error leyendo recordatorios de Redis")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def _save_all(recordatorios: list[dict]) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.set(KEY_ALL, json.dumps(recordatorios, ensure_ascii=False))
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error guardando recordatorios en Redis")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
async def get_recordatorios_by_numero(numero: str) -> list[dict]:
|
||||||
|
"""Filtra por el número (10 dígitos) del owner."""
|
||||||
|
todos = await get_recordatorios()
|
||||||
|
return [r for r in todos if r.get("numero") == numero]
|
||||||
|
|
||||||
|
|
||||||
|
async def crear_recordatorio(data: dict) -> dict:
|
||||||
|
"""Crea un recordatorio nuevo. data debe traer: numero, tipo, hora, dias."""
|
||||||
|
nuevo = {
|
||||||
|
"id": str(uuid.uuid4()),
|
||||||
|
"numero": data["numero"],
|
||||||
|
"nombre": data.get("nombre", ""),
|
||||||
|
"tipo": data.get("tipo", "diario"),
|
||||||
|
"hora": data.get("hora", "08:00"),
|
||||||
|
"dias": data.get("dias", [0, 1, 2, 3, 4]),
|
||||||
|
"activo": bool(data.get("activo", True)),
|
||||||
|
"creado": datetime.now(MEXICO).isoformat(),
|
||||||
|
}
|
||||||
|
todos = await get_recordatorios()
|
||||||
|
todos.append(nuevo)
|
||||||
|
await _save_all(todos)
|
||||||
|
return nuevo
|
||||||
|
|
||||||
|
|
||||||
|
async def actualizar_recordatorio(id: str, data: dict) -> dict | None:
|
||||||
|
"""Actualiza solo los campos editables (tipo, hora, dias, activo, nombre)."""
|
||||||
|
todos = await get_recordatorios()
|
||||||
|
for i, r in enumerate(todos):
|
||||||
|
if r.get("id") == id:
|
||||||
|
for key in ("nombre", "tipo", "hora", "dias", "activo"):
|
||||||
|
if key in data and data[key] is not None:
|
||||||
|
r[key] = data[key]
|
||||||
|
todos[i] = r
|
||||||
|
await _save_all(todos)
|
||||||
|
return r
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def eliminar_recordatorio(id: str) -> bool:
|
||||||
|
todos = await get_recordatorios()
|
||||||
|
nuevos = [r for r in todos if r.get("id") != id]
|
||||||
|
if len(nuevos) == len(todos):
|
||||||
|
return False
|
||||||
|
await _save_all(nuevos)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def toggle_activo(id: str) -> dict | None:
|
||||||
|
todos = await get_recordatorios()
|
||||||
|
for i, r in enumerate(todos):
|
||||||
|
if r.get("id") == id:
|
||||||
|
r["activo"] = not bool(r.get("activo", False))
|
||||||
|
todos[i] = r
|
||||||
|
await _save_all(todos)
|
||||||
|
return r
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── Tokens de administración ──────────────────────────────────────
|
||||||
|
|
||||||
|
async def crear_token_admin(numero: str) -> str:
|
||||||
|
"""Genera un token UUID4 asociado al número, TTL 30 min."""
|
||||||
|
token = str(uuid.uuid4())
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(f"admin_token:{token}", ADMIN_TOKEN_TTL, numero)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error creando token admin")
|
||||||
|
raise
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
async def validar_token_admin(token: str) -> str | None:
|
||||||
|
"""Devuelve el número asociado al token, o None si inválido/expirado."""
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
numero = await r.get(f"admin_token:{token}")
|
||||||
|
return numero if numero else None
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error validando token admin")
|
||||||
|
return None
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
"""
|
||||||
|
APScheduler para recordatorios de cobranza.
|
||||||
|
|
||||||
|
Cada recordatorio activo se traduce en un CronTrigger con día(s) de la
|
||||||
|
semana + hora. APScheduler corre en el mismo event loop de FastAPI.
|
||||||
|
|
||||||
|
Convención día_of_week APScheduler: 0=Lunes ... 6=Domingo (igual que Python).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||||
|
from apscheduler.triggers.cron import CronTrigger
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
MEXICO = ZoneInfo("America/Mexico_City")
|
||||||
|
scheduler = AsyncIOScheduler(timezone=MEXICO)
|
||||||
|
|
||||||
|
|
||||||
|
async def ejecutar_cobranza_automatica(numero_wa: str, tipo: str, instance: str) -> None:
|
||||||
|
"""Genera y envía un reporte de cobranza por WhatsApp.
|
||||||
|
|
||||||
|
numero_wa: '521XXXXXXXXXX@s.whatsapp.net'
|
||||||
|
tipo: 'diario' | 'semanal' | 'mensual'
|
||||||
|
instance: nombre de la instancia EvolutionAPI
|
||||||
|
"""
|
||||||
|
# Imports tardíos para evitar ciclos: webhook importa schemas que importan
|
||||||
|
# cosas de services, etc.
|
||||||
|
from src.services.sheets import generar_reporte_cobros
|
||||||
|
from src.api.webhook import (
|
||||||
|
_formatear_reporte,
|
||||||
|
_formatear_reporte_semanal,
|
||||||
|
_formatear_reporte_mensual,
|
||||||
|
)
|
||||||
|
from src.services import whatsapp
|
||||||
|
|
||||||
|
try:
|
||||||
|
hoy = datetime.now(MEXICO).date()
|
||||||
|
reporte = generar_reporte_cobros(
|
||||||
|
hoy=hoy,
|
||||||
|
semanal=(tipo == "semanal"),
|
||||||
|
mensual=(tipo == "mensual"),
|
||||||
|
)
|
||||||
|
if tipo == "semanal":
|
||||||
|
texto = _formatear_reporte_semanal(reporte)
|
||||||
|
elif tipo == "mensual":
|
||||||
|
texto = _formatear_reporte_mensual(reporte)
|
||||||
|
else:
|
||||||
|
texto = _formatear_reporte(reporte)
|
||||||
|
await whatsapp.enviar_texto(numero_wa, texto, instance)
|
||||||
|
logger.info(
|
||||||
|
"Recordatorio %s enviado a %s a las %s",
|
||||||
|
tipo, numero_wa, datetime.now(MEXICO).isoformat(timespec="seconds"),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error ejecutando cobranza automática (%s → %s)", tipo, numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def sincronizar_jobs() -> None:
|
||||||
|
"""Re-registra los jobs en APScheduler según los recordatorios activos.
|
||||||
|
|
||||||
|
Quita primero todos los jobs con prefijo 'rec_'. Luego registra los
|
||||||
|
activos desde Redis. Idempotente: se puede llamar tras cada cambio.
|
||||||
|
"""
|
||||||
|
from src.services.recordatorios import get_recordatorios
|
||||||
|
|
||||||
|
instance = os.getenv("EVOLUTION_INSTANCE", "wk-bot")
|
||||||
|
|
||||||
|
# Limpia jobs viejos
|
||||||
|
for job in list(scheduler.get_jobs()):
|
||||||
|
if job.id.startswith("rec_"):
|
||||||
|
try:
|
||||||
|
scheduler.remove_job(job.id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
recordatorios = await get_recordatorios()
|
||||||
|
except Exception:
|
||||||
|
logger.exception("No se pudieron leer recordatorios; sin jobs activos")
|
||||||
|
return
|
||||||
|
|
||||||
|
registrados = 0
|
||||||
|
for r in recordatorios:
|
||||||
|
if not r.get("activo"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
hora_str = r.get("hora") or "08:00"
|
||||||
|
hora, minuto = hora_str.split(":")
|
||||||
|
dias = r.get("dias") or []
|
||||||
|
if not dias:
|
||||||
|
continue
|
||||||
|
dias_cron = ",".join(str(d) for d in dias)
|
||||||
|
# MX usa prefijo 521 + 10 dígitos para WhatsApp.
|
||||||
|
numero_wa = f"521{r['numero']}@s.whatsapp.net"
|
||||||
|
scheduler.add_job(
|
||||||
|
ejecutar_cobranza_automatica,
|
||||||
|
CronTrigger(
|
||||||
|
day_of_week=dias_cron,
|
||||||
|
hour=int(hora),
|
||||||
|
minute=int(minuto),
|
||||||
|
timezone=MEXICO,
|
||||||
|
),
|
||||||
|
args=[numero_wa, r.get("tipo", "diario"), instance],
|
||||||
|
id=f"rec_{r['id']}",
|
||||||
|
replace_existing=True,
|
||||||
|
)
|
||||||
|
registrados += 1
|
||||||
|
except Exception:
|
||||||
|
logger.exception("No se pudo registrar recordatorio %s", r.get("id"))
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Scheduler sincronizado: %d job(s) activo(s)", registrados,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def acumular_cobranza_global() -> None:
|
||||||
|
"""Job 9:30 am: para cada número con cobranza activa, acumula los
|
||||||
|
vencimientos del día. Itera las keys `cobranza_acumulada:*` en Redis.
|
||||||
|
"""
|
||||||
|
from src.services import cobranza_acumulada
|
||||||
|
from src.services.session import get_client
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
numeros: list[str] = []
|
||||||
|
async for key in r.scan_iter(match="cobranza_acumulada:*"):
|
||||||
|
num = key.split(":", 1)[1] if ":" in key else key
|
||||||
|
if num:
|
||||||
|
numeros.append(num)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("No se pudo escanear keys de cobranza_acumulada")
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info("acumular_cobranza_global: %d usuarios con cobranza activa", len(numeros))
|
||||||
|
for num in numeros:
|
||||||
|
try:
|
||||||
|
res = await cobranza_acumulada.acumular_dia(num)
|
||||||
|
logger.info(
|
||||||
|
"Auto-acumulado para %s: +%s renglones (total %s)",
|
||||||
|
num, res.get("agregados"), res.get("total"),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error acumulando cobranza para %s", num)
|
||||||
|
|
||||||
|
|
||||||
|
def _registrar_job_cobranza_acumulada() -> None:
|
||||||
|
"""Registra el job diario 9:30 am (configurable por env COBRANZA_HORA_ACUMULA)."""
|
||||||
|
hora_str = os.getenv("COBRANZA_HORA_ACUMULA", "09:30")
|
||||||
|
try:
|
||||||
|
hh, mm = hora_str.split(":")
|
||||||
|
hh_i, mm_i = int(hh), int(mm)
|
||||||
|
except Exception:
|
||||||
|
logger.warning("COBRANZA_HORA_ACUMULA inválida %r — usando 09:30", hora_str)
|
||||||
|
hh_i, mm_i = 9, 30
|
||||||
|
scheduler.add_job(
|
||||||
|
acumular_cobranza_global,
|
||||||
|
CronTrigger(hour=hh_i, minute=mm_i, timezone=MEXICO),
|
||||||
|
id="cobranza_acumulada_diaria",
|
||||||
|
replace_existing=True,
|
||||||
|
)
|
||||||
|
logger.info("Job cobranza_acumulada_diaria registrado a las %02d:%02d MX", hh_i, mm_i)
|
||||||
|
|
||||||
|
|
||||||
|
async def start_scheduler() -> None:
|
||||||
|
"""Arranca el scheduler y sincroniza jobs. No crashea si Redis falla."""
|
||||||
|
try:
|
||||||
|
if not scheduler.running:
|
||||||
|
scheduler.start()
|
||||||
|
await sincronizar_jobs()
|
||||||
|
_registrar_job_cobranza_acumulada()
|
||||||
|
logger.info("Scheduler iniciado")
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error iniciando scheduler — continuando sin jobs")
|
||||||
|
|
||||||
|
|
||||||
|
async def stop_scheduler() -> None:
|
||||||
|
try:
|
||||||
|
if scheduler.running:
|
||||||
|
scheduler.shutdown(wait=False)
|
||||||
|
logger.info("Scheduler detenido")
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error deteniendo scheduler")
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
import redis.asyncio as aioredis
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379")
|
||||||
|
SESSION_TTL = 86400 # 24 horas
|
||||||
|
CLONACION_TTL = 1800 # 30 minutos
|
||||||
|
SELECCION_TTL = 1800 # 30 minutos
|
||||||
|
PARCIAL_TTL = 1800 # 30 minutos
|
||||||
|
CONTRATO_ACTIVO_TTL = 1800 # 30 minutos
|
||||||
|
DOCX_PENDIENTE_TTL = 1800 # 30 minutos
|
||||||
|
|
||||||
|
_client: aioredis.Redis | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_client() -> aioredis.Redis:
|
||||||
|
global _client
|
||||||
|
if _client is None:
|
||||||
|
_client = aioredis.from_url(REDIS_URL, decode_responses=True)
|
||||||
|
return _client
|
||||||
|
|
||||||
|
|
||||||
|
def _normalizar_numero(numero: str) -> str:
|
||||||
|
"""Elimina @s.whatsapp.net y cualquier sufijo para usar solo dígitos."""
|
||||||
|
return numero.split("@")[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _key(numero_wa: str) -> str:
|
||||||
|
return f"sesion:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _key_clonacion(numero_wa: str) -> str:
|
||||||
|
return f"clonacion:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _key_seleccion(numero_wa: str) -> str:
|
||||||
|
return f"seleccion:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _key_parcial(numero_wa: str) -> str:
|
||||||
|
return f"parcial:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _key_contrato_activo(numero_wa: str) -> str:
|
||||||
|
return f"contrato_activo:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _key_docx_pendiente(numero_wa: str) -> str:
|
||||||
|
return f"docx_pendiente:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
# ── Última cotización (sesión activa) ──
|
||||||
|
|
||||||
|
async def guardar_ultima_cotizacion(numero_wa: str, datos: dict) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(_key(numero_wa), SESSION_TTL, json.dumps(datos, ensure_ascii=False))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar sesión para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_ultima_cotizacion(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al obtener sesión para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_sesion(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar sesión para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Selección pendiente (cuando hay varios matches en el histórico) ──
|
||||||
|
|
||||||
|
async def guardar_seleccion_pendiente(numero_wa: str, opciones: list | dict) -> None:
|
||||||
|
"""Guarda la lista de opciones que Paulino tiene que elegir (TTL 30 min)."""
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(
|
||||||
|
_key_seleccion(numero_wa),
|
||||||
|
SELECCION_TTL,
|
||||||
|
json.dumps(opciones, ensure_ascii=False),
|
||||||
|
)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar selección para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_seleccion_pendiente(numero_wa: str):
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key_seleccion(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer selección para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_seleccion_pendiente(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_seleccion(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar selección para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Clonación pendiente (flujo 2-pasos: PDF adjunto → precio nuevo) ──
|
||||||
|
|
||||||
|
async def guardar_clonacion_pendiente(numero_wa: str, params_dict: dict) -> None:
|
||||||
|
"""Guarda los % extraídos del PDF original (TTL 30 min)."""
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(
|
||||||
|
_key_clonacion(numero_wa),
|
||||||
|
CLONACION_TTL,
|
||||||
|
json.dumps(params_dict, ensure_ascii=False),
|
||||||
|
)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar clonación para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_clonacion_pendiente(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key_clonacion(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer clonación para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_clonacion_pendiente(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_clonacion(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar clonación para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Params parciales (cotización que se arma en varios mensajes) ──
|
||||||
|
|
||||||
|
async def guardar_params_parciales(numero_wa: str, params: dict) -> None:
|
||||||
|
"""Guarda los parámetros de cotización acumulados hasta ahora (TTL 30 min).
|
||||||
|
|
||||||
|
Permite que Paulino mande la cotización en pedacitos: el bot la recuerda
|
||||||
|
y pregunta solo lo que falta en cada turno.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(
|
||||||
|
_key_parcial(numero_wa),
|
||||||
|
PARCIAL_TTL,
|
||||||
|
json.dumps(params, ensure_ascii=False),
|
||||||
|
)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar parciales para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_params_parciales(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key_parcial(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer parciales para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_params_parciales(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_parcial(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar parciales para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Contrato activo (set de parámetros elegido desde consulta) ──
|
||||||
|
#
|
||||||
|
# Cuando Paulino hace "parámetros CLIENTE" y escoge un contrato del listado,
|
||||||
|
# guardamos ese contrato como "activo". Si el siguiente mensaje trae un
|
||||||
|
# vehículo + precio, se genera una cotización replicando ese set de
|
||||||
|
# parámetros, sin que tenga que escribir "parámetros X" de nuevo.
|
||||||
|
|
||||||
|
async def guardar_contrato_activo(numero_wa: str, contrato: dict) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(
|
||||||
|
_key_contrato_activo(numero_wa),
|
||||||
|
CONTRATO_ACTIVO_TTL,
|
||||||
|
json.dumps(contrato, ensure_ascii=False, default=str),
|
||||||
|
)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar contrato_activo para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_contrato_activo(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key_contrato_activo(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer contrato_activo para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_contrato_activo(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_contrato_activo(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar contrato_activo para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── DOCX pendiente (editable Word post-PDF) ──
|
||||||
|
#
|
||||||
|
# Al enviar el PDF de una cotización, guardamos la ruta del .docx asociado.
|
||||||
|
# El usuario puede pedirlo respondiendo "Sí" durante 30 min. Pasado ese
|
||||||
|
# tiempo, la key expira y un proceso externo / la siguiente cotización
|
||||||
|
# borra el archivo huérfano.
|
||||||
|
|
||||||
|
async def guardar_docx_pendiente(numero_wa: str, ruta: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(_key_docx_pendiente(numero_wa), DOCX_PENDIENTE_TTL, ruta)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar docx_pendiente para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_docx_pendiente(numero_wa: str) -> str | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
return await r.get(_key_docx_pendiente(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer docx_pendiente para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_docx_pendiente(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_docx_pendiente(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar docx_pendiente para %s", numero_wa)
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,89 @@
|
|||||||
|
import os
|
||||||
|
import httpx
|
||||||
|
import base64
|
||||||
|
from src.utils.logger import logger
|
||||||
|
|
||||||
|
EVOLUTION_URL = os.getenv("EVOLUTION_API_URL") # ej. https://evo.tudominio.com
|
||||||
|
EVOLUTION_KEY = os.getenv("EVOLUTION_API_KEY")
|
||||||
|
EVOLUTION_INSTANCE = os.getenv("EVOLUTION_INSTANCE") # nombre de la instancia
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict:
|
||||||
|
return {
|
||||||
|
"apikey": EVOLUTION_KEY,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def enviar_texto(numero: str, mensaje: str, instance: str = None) -> bool:
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/message/sendText/{inst}"
|
||||||
|
payload = {
|
||||||
|
"number": numero,
|
||||||
|
"text": mensaje,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
logger.info(f"Texto enviado a {numero}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error enviando texto a {numero}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def enviar_pdf(numero: str, pdf_bytes: bytes, filename: str, instance: str = None) -> bool:
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/message/sendMedia/{inst}"
|
||||||
|
|
||||||
|
pdf_b64 = base64.b64encode(pdf_bytes).decode()
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"number": numero,
|
||||||
|
"mediatype": "document",
|
||||||
|
"mimetype": "application/pdf",
|
||||||
|
"media": pdf_b64,
|
||||||
|
"fileName": filename,
|
||||||
|
"caption": "",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
logger.info(f"PDF '{filename}' enviado a {numero}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error enviando PDF a {numero}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def enviar_documento(
|
||||||
|
numero: str,
|
||||||
|
file_bytes: bytes,
|
||||||
|
filename: str,
|
||||||
|
mimetype: str,
|
||||||
|
instance: str = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Envía un documento arbitrario (docx, xlsx, etc.) vía EvolutionAPI."""
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/message/sendMedia/{inst}"
|
||||||
|
|
||||||
|
b64 = base64.b64encode(file_bytes).decode()
|
||||||
|
payload = {
|
||||||
|
"number": numero,
|
||||||
|
"mediatype": "document",
|
||||||
|
"mimetype": mimetype,
|
||||||
|
"media": b64,
|
||||||
|
"fileName": filename,
|
||||||
|
"caption": "",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
logger.info(f"Documento '{filename}' enviado a {numero}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error enviando documento a {numero}: {e}")
|
||||||
|
return False
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,217 @@
|
|||||||
|
"""
|
||||||
|
Agente intérprete de mensajes de WhatsApp para WK Financing Solutions.
|
||||||
|
|
||||||
|
Recibe texto en lenguaje natural y clasifica la intención + extrae parámetros
|
||||||
|
usando GPT-4o-mini con structured outputs.
|
||||||
|
|
||||||
|
Ejemplos de mensajes que maneja:
|
||||||
|
- "Cadillac Escalade 2024, precio 2mdp, anticipo 978,940, tasa 27.8%, 24 meses"
|
||||||
|
→ cotizacion_directa con todos los parámetros
|
||||||
|
- "A esta súbele 2 puntos a la tasa"
|
||||||
|
→ modificar_ultima con campos_a_modificar={"tasa_anual_delta": 0.02}
|
||||||
|
- "Dame los parámetros del Range Rover del mes pasado"
|
||||||
|
→ replicar_historico con referencia_historico="Range Rover"
|
||||||
|
- "¿Qué tasa traía el GT3?"
|
||||||
|
→ consulta_parametros con referencia_historico="GT3"
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
||||||
|
|
||||||
|
SYSTEM_PROMPT = """\
|
||||||
|
Eres el asistente de Carlos Paulino Sánchez Cazares, agente de arrendamiento \
|
||||||
|
vehicular en WK Financing Solutions, Puebla, México.
|
||||||
|
|
||||||
|
Tu única tarea es interpretar sus mensajes y devolver JSON estructurado.
|
||||||
|
|
||||||
|
## INTENCIONES
|
||||||
|
|
||||||
|
Clasifica cada mensaje en UNA de estas intenciones:
|
||||||
|
|
||||||
|
1. "cotizacion_directa" — tiene parámetros suficientes para generar un PDF \
|
||||||
|
(mínimo: marca, tipo, precio, tasa, anticipo, plazo).
|
||||||
|
2. "modificar_ultima" — quiere ajustar la última cotización. Frases clave: \
|
||||||
|
"a esta", "la misma", "esta igual", "súbele", "bájale", "ponle", "cámbialo".
|
||||||
|
3. "replicar_historico" — quiere replicar un contrato del histórico. \
|
||||||
|
Frases clave: "con parámetros del...", "como el...", "igual que el...".
|
||||||
|
4. "consulta_parametros" — pregunta por datos de un contrato sin generar PDF. \
|
||||||
|
Frases clave: "¿qué tasa traía?", "pásame los parámetros de...", "cuánto fue...".\
|
||||||
|
NUNCA generes PDF para esta intención, SOLO texto.
|
||||||
|
5. "mensaje_incompleto" — quiere cotizar pero faltan datos críticos. Indica \
|
||||||
|
qué parámetros faltan en el campo "parametros_faltantes".
|
||||||
|
|
||||||
|
## REGLAS DE EXTRACCIÓN
|
||||||
|
|
||||||
|
**Vehículo:**
|
||||||
|
- marca: fabricante (CADILLAC, BMW, PORSCHE, LAND ROVER, etc.)
|
||||||
|
- tipo: versión específica (ESCALADE, GT3, M5, RANGE ROVER SPORT, etc.)
|
||||||
|
- anio: año modelo
|
||||||
|
- kms: kilómetros (0 si no se mencionan o es 0km)
|
||||||
|
|
||||||
|
**Financieros:**
|
||||||
|
- precio_referencia: en pesos ("2M" = 2000000, "1,650k" = 1650000)
|
||||||
|
- tasa_anual: SIEMPRE como decimal (25% = 0.25, "tasa 25" = 0.25)
|
||||||
|
- renta_anticipada: si viene como % → decimal (30% = 0.30); si viene como \
|
||||||
|
monto $ → el número directo. Indicar en es_monto_directo si es monto.
|
||||||
|
- valor_residual_pct: como decimal (15% = 0.15); null si no se menciona
|
||||||
|
- valor_residual_monto: monto directo si se da en pesos; null si no
|
||||||
|
- plazo_meses: 24, 36, 48 o 60
|
||||||
|
- anualizar_vr: true por default, false solo si dice "sin anualizar"
|
||||||
|
|
||||||
|
**Extras:**
|
||||||
|
- incluir_comision: true por default, false si dice "sin comisión" o "quita comisión"
|
||||||
|
- comision_pct: 0.03 por default, otro valor si lo especifica
|
||||||
|
- seguro_monto: monto en pesos si se especifica; null si no
|
||||||
|
- seguro_descripcion: texto descriptivo del seguro si aplica; null si no
|
||||||
|
|
||||||
|
**Cliente:**
|
||||||
|
- cliente: nombre del cliente; null si "a quien corresponda" o no se menciona
|
||||||
|
- atencion: a quién va dirigida; null si no se menciona
|
||||||
|
|
||||||
|
**Histórico y modificaciones:**
|
||||||
|
- referencia_historico: identificador del contrato/vehículo referenciado \
|
||||||
|
("GT3", "Diego Corona", "Range Rover")
|
||||||
|
- campos_a_modificar: SOLO para modificar_ultima. Diccionario con los campos \
|
||||||
|
que cambian. Ejemplos:
|
||||||
|
- "súbele 2pts a la tasa" → {"tasa_anual_delta": 0.02}
|
||||||
|
- "bájale la tasa a 21" → {"tasa_anual": 0.21}
|
||||||
|
- "ponle VR de 20%" → {"valor_residual_pct": 0.20}
|
||||||
|
- "quita la comisión" → {"incluir_comision": false}
|
||||||
|
|
||||||
|
**Múltiples plazos:**
|
||||||
|
Si pide "24 y 36 meses", generar un parametro por cada plazo en \
|
||||||
|
"plazos_multiples": [24, 36].
|
||||||
|
|
||||||
|
## RESPUESTA
|
||||||
|
|
||||||
|
Responde SOLO un objeto JSON con la estructura definida. Sin markdown, sin texto extra.
|
||||||
|
"""
|
||||||
|
|
||||||
|
RESPONSE_SCHEMA = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "interpretacion",
|
||||||
|
"strict": True,
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"intencion": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"cotizacion_directa",
|
||||||
|
"modificar_ultima",
|
||||||
|
"replicar_historico",
|
||||||
|
"consulta_parametros",
|
||||||
|
"mensaje_incompleto",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"parametros": {
|
||||||
|
"type": ["object", "null"],
|
||||||
|
"properties": {
|
||||||
|
"marca": {"type": ["string", "null"]},
|
||||||
|
"tipo": {"type": ["string", "null"]},
|
||||||
|
"anio": {"type": ["integer", "null"]},
|
||||||
|
"kms": {"type": ["integer", "null"]},
|
||||||
|
"precio_referencia": {"type": ["number", "null"]},
|
||||||
|
"tasa_anual": {"type": ["number", "null"]},
|
||||||
|
"renta_anticipada": {"type": ["number", "null"]},
|
||||||
|
"es_monto_directo": {"type": ["boolean", "null"]},
|
||||||
|
"valor_residual_pct": {"type": ["number", "null"]},
|
||||||
|
"valor_residual_monto": {"type": ["number", "null"]},
|
||||||
|
"plazo_meses": {"type": ["integer", "null"]},
|
||||||
|
"anualizar_vr": {"type": ["boolean", "null"]},
|
||||||
|
"incluir_comision": {"type": ["boolean", "null"]},
|
||||||
|
"comision_pct": {"type": ["number", "null"]},
|
||||||
|
"seguro_monto": {"type": ["number", "null"]},
|
||||||
|
"seguro_descripcion": {"type": ["string", "null"]},
|
||||||
|
"cliente": {"type": ["string", "null"]},
|
||||||
|
"atencion": {"type": ["string", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"marca", "tipo", "anio", "kms",
|
||||||
|
"precio_referencia", "tasa_anual",
|
||||||
|
"renta_anticipada", "es_monto_directo",
|
||||||
|
"valor_residual_pct", "valor_residual_monto",
|
||||||
|
"plazo_meses", "anualizar_vr",
|
||||||
|
"incluir_comision", "comision_pct",
|
||||||
|
"seguro_monto", "seguro_descripcion",
|
||||||
|
"cliente", "atencion",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
"plazos_multiples": {
|
||||||
|
"type": ["array", "null"],
|
||||||
|
"items": {"type": "integer"},
|
||||||
|
},
|
||||||
|
"referencia_historico": {"type": ["string", "null"]},
|
||||||
|
"campos_a_modificar": {
|
||||||
|
"type": ["object", "null"],
|
||||||
|
"additionalProperties": True,
|
||||||
|
},
|
||||||
|
"parametros_faltantes": {
|
||||||
|
"type": ["array", "null"],
|
||||||
|
"items": {"type": "string"},
|
||||||
|
},
|
||||||
|
"consulta_texto": {"type": ["string", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"intencion",
|
||||||
|
"parametros",
|
||||||
|
"plazos_multiples",
|
||||||
|
"referencia_historico",
|
||||||
|
"campos_a_modificar",
|
||||||
|
"parametros_faltantes",
|
||||||
|
"consulta_texto",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def interpretar_mensaje(
|
||||||
|
mensaje: str,
|
||||||
|
ultima_cotizacion: dict | None = None,
|
||||||
|
contexto_historico: dict | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Interpreta el mensaje de Paulino y devuelve la intención + parámetros.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
mensaje: texto del mensaje de WhatsApp
|
||||||
|
ultima_cotizacion: params de la última cotización (desde Redis)
|
||||||
|
contexto_historico: params del contrato referenciado (desde Sheets)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict con intencion, parametros, campos_a_modificar, etc.
|
||||||
|
"""
|
||||||
|
mensajes = [{"role": "system", "content": SYSTEM_PROMPT}]
|
||||||
|
|
||||||
|
contexto_parts = []
|
||||||
|
if ultima_cotizacion:
|
||||||
|
contexto_parts.append(
|
||||||
|
f"ÚLTIMA COTIZACIÓN GENERADA:\n{json.dumps(ultima_cotizacion, ensure_ascii=False)}"
|
||||||
|
)
|
||||||
|
if contexto_historico:
|
||||||
|
contexto_parts.append(
|
||||||
|
f"PARÁMETROS DEL CONTRATO REFERENCIADO:\n{json.dumps(contexto_historico, ensure_ascii=False)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
mensaje_completo = mensaje
|
||||||
|
if contexto_parts:
|
||||||
|
mensaje_completo = "\n\n".join(contexto_parts) + f"\n\nMENSAJE DE PAULINO:\n{mensaje}"
|
||||||
|
|
||||||
|
mensajes.append({"role": "user", "content": mensaje_completo})
|
||||||
|
|
||||||
|
response = await client.chat.completions.create(
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
messages=mensajes,
|
||||||
|
temperature=0.1,
|
||||||
|
response_format=RESPONSE_SCHEMA,
|
||||||
|
)
|
||||||
|
|
||||||
|
return json.loads(response.choices[0].message.content)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,434 @@
|
|||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
|
||||||
|
from fastapi import APIRouter, BackgroundTasks, HTTPException, Response
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from src.agents.interpreter import interpretar_mensaje
|
||||||
|
from src.models.schemas import CotizacionParams, WebhookMessage
|
||||||
|
from src.services.calculator import calcular_cotizacion
|
||||||
|
from src.services.pdf_generator import generar_pdf
|
||||||
|
from src.services.evolution_media import descargar_pdf_base64
|
||||||
|
from src.services.pdf_extractor import extraer_parametros_pdf
|
||||||
|
from src.services.sheets import buscar_contrato, obtener_contrato
|
||||||
|
from src.services import session, whatsapp
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
# ── Request models ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class InterpretarRequest(BaseModel):
|
||||||
|
mensaje: str
|
||||||
|
numero_wa: str
|
||||||
|
|
||||||
|
|
||||||
|
class CotizarRequest(CotizacionParams):
|
||||||
|
numero_wa: str
|
||||||
|
|
||||||
|
|
||||||
|
# ── Nuevos endpoints ───────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/interpretar")
|
||||||
|
async def interpretar(req: InterpretarRequest):
|
||||||
|
"""Interpreta un mensaje y retorna intención + parámetros."""
|
||||||
|
ultima = None
|
||||||
|
try:
|
||||||
|
ultima = await session.obtener_ultima_cotizacion(req.numero_wa)
|
||||||
|
except Exception:
|
||||||
|
logger.warning("No se pudo leer sesión Redis para %s", req.numero_wa)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resultado = await interpretar_mensaje(
|
||||||
|
req.mensaje,
|
||||||
|
ultima_cotizacion=ultima if ultima else None,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=502, detail=f"Error al interpretar mensaje: {e}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"intencion": resultado.get("intencion"),
|
||||||
|
"parametros": resultado.get("parametros"),
|
||||||
|
"plazos_multiples": resultado.get("plazos_multiples"),
|
||||||
|
"referencia_historico": resultado.get("referencia_historico"),
|
||||||
|
"campos_a_modificar": resultado.get("campos_a_modificar"),
|
||||||
|
"parametros_faltantes": resultado.get("parametros_faltantes"),
|
||||||
|
"consulta_texto": resultado.get("consulta_texto"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/cotizar")
|
||||||
|
async def cotizar(req: CotizarRequest):
|
||||||
|
"""Calcula cotización, genera PDF y guarda en sesión."""
|
||||||
|
params = CotizacionParams(**req.model_dump(exclude={"numero_wa"}))
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = calcular_cotizacion(params)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=422, detail=f"Error en cálculo: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
pdf_bytes = generar_pdf(params, result)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=f"Error generando PDF: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
await session.guardar_ultima_cotizacion(req.numero_wa, params.model_dump())
|
||||||
|
except Exception:
|
||||||
|
logger.warning("No se pudo guardar sesión Redis para %s", req.numero_wa)
|
||||||
|
|
||||||
|
filename = f"Cotizacion_{params.marca}_{params.tipo}_{params.anio}_{params.plazo_meses}m.pdf"
|
||||||
|
return Response(
|
||||||
|
content=pdf_bytes,
|
||||||
|
media_type="application/pdf",
|
||||||
|
headers={"Content-Disposition": f'inline; filename="{filename}"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/contrato/{query}")
|
||||||
|
async def contrato(query: str):
|
||||||
|
"""Busca un contrato en el histórico de Google Sheets."""
|
||||||
|
resultado = obtener_contrato(query)
|
||||||
|
if resultado is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"No se encontró contrato para '{query}'")
|
||||||
|
return resultado
|
||||||
|
|
||||||
|
|
||||||
|
# ── Endpoint existente (n8n webhook) ───────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/webhook/message")
|
||||||
|
async def recibir_mensaje(msg: WebhookMessage, background_tasks: BackgroundTasks):
|
||||||
|
"""Punto de entrada desde n8n."""
|
||||||
|
background_tasks.add_task(procesar_mensaje, msg)
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
async def procesar_mensaje(msg: WebhookMessage):
|
||||||
|
numero = msg.numero
|
||||||
|
mensaje = (msg.mensaje or "").strip()
|
||||||
|
|
||||||
|
logger.info("Mensaje de %s: %s", numero, mensaje[:80])
|
||||||
|
|
||||||
|
try:
|
||||||
|
# ── PASO 1 clonación: llegó un PDF adjunto ──
|
||||||
|
if _es_pdf_adjunto(msg):
|
||||||
|
await _iniciar_clonacion_desde_pdf(msg)
|
||||||
|
return
|
||||||
|
|
||||||
|
# ── PASO 2 clonación: hay clonación pendiente + precio nuevo ──
|
||||||
|
clonacion = await session.obtener_clonacion_pendiente(numero)
|
||||||
|
if clonacion and mensaje:
|
||||||
|
manejado = await _completar_clonacion(msg, clonacion)
|
||||||
|
if manejado:
|
||||||
|
return
|
||||||
|
|
||||||
|
ultima = await session.obtener_ultima_cotizacion(numero)
|
||||||
|
resultado = await interpretar_mensaje(mensaje, ultima_cotizacion=ultima)
|
||||||
|
|
||||||
|
if resultado.get("referencia_historico"):
|
||||||
|
if resultado["intencion"] == "consulta_parametros":
|
||||||
|
contrato_data = obtener_contrato(resultado["referencia_historico"])
|
||||||
|
if contrato_data:
|
||||||
|
texto = "\n".join(f"{k}: {v}" for k, v in contrato_data.items())
|
||||||
|
else:
|
||||||
|
texto = f"No encontré el contrato '{resultado['referencia_historico']}' en el histórico."
|
||||||
|
await whatsapp.enviar_texto(numero, texto, msg.instance)
|
||||||
|
return
|
||||||
|
|
||||||
|
contrato_data = obtener_contrato(resultado["referencia_historico"])
|
||||||
|
if contrato_data:
|
||||||
|
resultado = await interpretar_mensaje(
|
||||||
|
mensaje,
|
||||||
|
ultima_cotizacion=ultima,
|
||||||
|
contexto_historico=contrato_data,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
f"No encontré el contrato '{resultado['referencia_historico']}' en el histórico.",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if resultado["intencion"] == "consulta_parametros":
|
||||||
|
texto = resultado.get("consulta_texto") or "No entendí qué dato buscas."
|
||||||
|
await whatsapp.enviar_texto(numero, texto, msg.instance)
|
||||||
|
return
|
||||||
|
|
||||||
|
if resultado["intencion"] == "mensaje_incompleto":
|
||||||
|
faltantes = resultado.get("parametros_faltantes", [])
|
||||||
|
texto = f"Me faltan datos: {', '.join(faltantes)}. ¿Puedes completarlos?"
|
||||||
|
await whatsapp.enviar_texto(numero, texto, msg.instance)
|
||||||
|
return
|
||||||
|
|
||||||
|
parametros = resultado.get("parametros")
|
||||||
|
if not parametros:
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
"No pude extraer los parámetros. ¿Puedes darme marca, tipo, año, precio y plazo?",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if resultado["intencion"] == "modificar_ultima" and ultima:
|
||||||
|
mods = resultado.get("campos_a_modificar", {})
|
||||||
|
parametros = {**ultima, **_aplicar_modificaciones(ultima, mods)}
|
||||||
|
|
||||||
|
plazos = resultado.get("plazos_multiples") or [parametros.get("plazo_meses")]
|
||||||
|
for plazo in plazos:
|
||||||
|
p = {**parametros, "plazo_meses": plazo}
|
||||||
|
params = CotizacionParams(**p)
|
||||||
|
await _generar_y_enviar(params, numero, msg.instance)
|
||||||
|
|
||||||
|
await session.guardar_ultima_cotizacion(numero, parametros)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error procesando mensaje de %s: %s", numero, e, exc_info=True)
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
"Hubo un error procesando tu solicitud. Intenta de nuevo.",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _generar_y_enviar(params: CotizacionParams, numero: str, instance: str):
|
||||||
|
result = calcular_cotizacion(params)
|
||||||
|
pdf_bytes = generar_pdf(params, result)
|
||||||
|
filename = f"Cotizacion_{params.marca}_{params.tipo}_{params.anio}_{params.plazo_meses}m.pdf"
|
||||||
|
await whatsapp.enviar_pdf(numero, pdf_bytes, filename, instance)
|
||||||
|
logger.info("PDF enviado: %s a %s", filename, numero)
|
||||||
|
|
||||||
|
|
||||||
|
def _aplicar_modificaciones(base: dict, mods: dict) -> dict:
|
||||||
|
resultado = copy.deepcopy(base)
|
||||||
|
for campo, valor in mods.items():
|
||||||
|
if campo.endswith("_delta"):
|
||||||
|
campo_real = campo.replace("_delta", "")
|
||||||
|
resultado[campo_real] = resultado.get(campo_real, 0) + valor
|
||||||
|
else:
|
||||||
|
resultado[campo] = valor
|
||||||
|
return resultado
|
||||||
|
|
||||||
|
|
||||||
|
# ── Flujo de clonación desde PDF ───────────────────────────────
|
||||||
|
|
||||||
|
def _es_pdf_adjunto(msg: WebhookMessage) -> bool:
|
||||||
|
"""Detecta que el mensaje trae un PDF (ya sea inline o descargable)."""
|
||||||
|
mt = (msg.media_type or "").lower()
|
||||||
|
mime = (msg.mime_type or "").lower()
|
||||||
|
if "pdf" in mime:
|
||||||
|
return True
|
||||||
|
if "document" in mt: # "document", "documentMessage"
|
||||||
|
return True
|
||||||
|
return bool(msg.pdf_base64)
|
||||||
|
|
||||||
|
|
||||||
|
async def _iniciar_clonacion_desde_pdf(msg: WebhookMessage) -> None:
|
||||||
|
"""PASO 1: extrae parámetros del PDF y guarda en Redis."""
|
||||||
|
numero = msg.numero
|
||||||
|
|
||||||
|
pdf_b64 = msg.pdf_base64
|
||||||
|
if not pdf_b64 and msg.message_key:
|
||||||
|
logger.info("PDF sin base64 inline, descargando de Evolution para %s", numero)
|
||||||
|
pdf_b64 = await descargar_pdf_base64(
|
||||||
|
msg.message_key,
|
||||||
|
message_data=msg.message_data,
|
||||||
|
instance=msg.instance,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not pdf_b64:
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
"No pude leer el PDF. ¿Puedes mandarlo de nuevo?",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
datos = await extraer_parametros_pdf(pdf_b64)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error extrayendo PDF de %s: %s", numero, e)
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
"No pude leer el PDF. ¿Puedes reenviarlo o dictarme los parámetros?",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
await session.guardar_clonacion_pendiente(numero, datos)
|
||||||
|
resumen_parts = []
|
||||||
|
if datos.get("tasa_anual") is not None:
|
||||||
|
resumen_parts.append(f"Tasa {datos['tasa_anual']*100:.2f}%")
|
||||||
|
if datos.get("renta_anticipada_pct") is not None:
|
||||||
|
resumen_parts.append(f"RA {datos['renta_anticipada_pct']*100:.2f}%")
|
||||||
|
if datos.get("valor_residual_pct") is not None:
|
||||||
|
resumen_parts.append(f"VR {datos['valor_residual_pct']*100:.2f}%")
|
||||||
|
if datos.get("plazo_meses"):
|
||||||
|
resumen_parts.append(f"{datos['plazo_meses']}m")
|
||||||
|
resumen = " · ".join(resumen_parts) if resumen_parts else "parámetros leídos"
|
||||||
|
|
||||||
|
await whatsapp.enviar_texto(
|
||||||
|
numero,
|
||||||
|
f"Parámetros listos ✅ ({resumen})\nMándame el vehículo y precio de referencia.",
|
||||||
|
msg.instance,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parsear_vehiculo_y_precio(texto: str) -> dict | None:
|
||||||
|
"""Extrae {marca, tipo, anio, precio} de un mensaje corto tipo
|
||||||
|
'Hilux 2025 pr 520,000' / 'Escalade 2024 2m' / 'BMW M5 2023 precio 1.8mdp'.
|
||||||
|
|
||||||
|
Devuelve None si no se encuentra un precio interpretable.
|
||||||
|
Se usa en el PASO 2 de clonación, donde tasa/plazo/anticipo ya están en
|
||||||
|
Redis y solo hace falta el vehículo + precio base.
|
||||||
|
"""
|
||||||
|
if not texto:
|
||||||
|
return None
|
||||||
|
t = texto.strip()
|
||||||
|
|
||||||
|
# 1) Precio: busca "pr", "precio", "$" o un número grande al final.
|
||||||
|
precio: float | None = None
|
||||||
|
precio_span: tuple[int, int] | None = None
|
||||||
|
|
||||||
|
# a) "2M", "1.8 mdp", "1,650k"
|
||||||
|
m = re.search(
|
||||||
|
r"(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)\s*(mdp|mill(?:ones)?|m(?!(?:es|\w))|k)\b",
|
||||||
|
t,
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
if m:
|
||||||
|
num = float(m.group(1).replace(",", ""))
|
||||||
|
unidad = m.group(2).lower()
|
||||||
|
if unidad.startswith("k"):
|
||||||
|
precio = num * 1_000
|
||||||
|
else:
|
||||||
|
precio = num * 1_000_000
|
||||||
|
precio_span = m.span()
|
||||||
|
|
||||||
|
# b) "pr 520,000" / "precio 520000" / "$520,000"
|
||||||
|
if precio is None:
|
||||||
|
m = re.search(
|
||||||
|
r"(?:pr|precio|\$)\s*:?\s*([\d]{1,3}(?:[,\.]\d{3})+|\d{5,})",
|
||||||
|
t,
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
if m:
|
||||||
|
crudo = m.group(1).replace(",", "").replace(".", "")
|
||||||
|
try:
|
||||||
|
precio = float(crudo)
|
||||||
|
precio_span = m.span()
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# c) número suelto >= 50,000
|
||||||
|
if precio is None:
|
||||||
|
for m in re.finditer(r"\b(\d{1,3}(?:[,\.]\d{3})+|\d{5,})\b", t):
|
||||||
|
crudo = m.group(1).replace(",", "").replace(".", "")
|
||||||
|
try:
|
||||||
|
val = float(crudo)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if val >= 50_000:
|
||||||
|
precio = val
|
||||||
|
precio_span = m.span()
|
||||||
|
break
|
||||||
|
|
||||||
|
if precio is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 2) Año: 4 dígitos 19xx/20xx
|
||||||
|
anio: int | None = None
|
||||||
|
m_anio = re.search(r"\b(19|20)\d{2}\b", t)
|
||||||
|
if m_anio:
|
||||||
|
try:
|
||||||
|
anio = int(m_anio.group(0))
|
||||||
|
except ValueError:
|
||||||
|
anio = None
|
||||||
|
|
||||||
|
# 3) Vehículo: texto antes del precio, sin el año, sin palabras clave.
|
||||||
|
resto = t[: precio_span[0]] if precio_span else t
|
||||||
|
if m_anio and m_anio.start() < (precio_span[0] if precio_span else len(t)):
|
||||||
|
resto = resto.replace(m_anio.group(0), " ")
|
||||||
|
resto = re.sub(
|
||||||
|
r"\b(pr|precio|de|a|el|la|cotizar|cotizame|dame|arma|para)\b",
|
||||||
|
" ",
|
||||||
|
resto,
|
||||||
|
flags=re.IGNORECASE,
|
||||||
|
)
|
||||||
|
resto = re.sub(r"[,\.$:]+", " ", resto)
|
||||||
|
resto = " ".join(resto.split()).strip()
|
||||||
|
if not resto:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Heurística simple: primera palabra = marca, resto = tipo.
|
||||||
|
partes = resto.split(" ", 1)
|
||||||
|
marca = partes[0].upper()
|
||||||
|
tipo = (partes[1] if len(partes) > 1 else partes[0]).upper()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"marca": marca,
|
||||||
|
"tipo": tipo,
|
||||||
|
"anio": anio,
|
||||||
|
"precio_referencia": precio,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _completar_clonacion(msg: WebhookMessage, clonacion: dict) -> bool:
|
||||||
|
"""PASO 2: aplica los % guardados al precio nuevo del mensaje actual.
|
||||||
|
|
||||||
|
Devuelve True si se procesó como clonación (y ya se respondió al usuario);
|
||||||
|
False si el mensaje no trae precio/vehículo y debe seguir el flujo normal.
|
||||||
|
"""
|
||||||
|
numero = msg.numero
|
||||||
|
|
||||||
|
# NO usar el intérprete general aquí: clasificaría el mensaje como
|
||||||
|
# "mensaje_incompleto" porque no trae tasa/plazo/anticipo, que precisamente
|
||||||
|
# estamos tomando del PDF clonado. Parseamos con regex en su lugar.
|
||||||
|
parseo = _parsear_vehiculo_y_precio(msg.mensaje or "")
|
||||||
|
if not parseo:
|
||||||
|
return False
|
||||||
|
|
||||||
|
precio = parseo["precio_referencia"]
|
||||||
|
marca = parseo["marca"]
|
||||||
|
tipo = parseo["tipo"]
|
||||||
|
anio = parseo["anio"]
|
||||||
|
|
||||||
|
tasa = clonacion.get("tasa_anual") or 0.0
|
||||||
|
ra_pct = clonacion.get("renta_anticipada_pct") or 0.0
|
||||||
|
vr_pct = clonacion.get("valor_residual_pct") or 0.0
|
||||||
|
plazo = clonacion.get("plazo_meses") or 36
|
||||||
|
comision_pct = clonacion.get("comision_pct")
|
||||||
|
incluir_comision = True
|
||||||
|
comision_override = None
|
||||||
|
if comision_pct is not None:
|
||||||
|
if comision_pct <= 0:
|
||||||
|
incluir_comision = False
|
||||||
|
else:
|
||||||
|
comision_override = round(float(precio) * float(comision_pct), 2)
|
||||||
|
|
||||||
|
cotizacion = CotizacionParams(
|
||||||
|
marca=marca,
|
||||||
|
tipo=tipo,
|
||||||
|
anio=anio or 0,
|
||||||
|
kms=None,
|
||||||
|
precio_referencia=float(precio),
|
||||||
|
tasa_anual=float(tasa),
|
||||||
|
renta_anticipada=float(ra_pct),
|
||||||
|
es_monto_directo_ra=False,
|
||||||
|
valor_residual_pct=float(vr_pct),
|
||||||
|
plazo_meses=int(plazo),
|
||||||
|
incluir_comision=incluir_comision,
|
||||||
|
comision_override=comision_override,
|
||||||
|
seguro=None, # seguro NO incluido en clonación
|
||||||
|
)
|
||||||
|
|
||||||
|
await _generar_y_enviar(cotizacion, numero, msg.instance)
|
||||||
|
await session.guardar_ultima_cotizacion(numero, cotizacion.model_dump())
|
||||||
|
await session.limpiar_clonacion_pendiente(numero)
|
||||||
|
return True
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from src.api.webhook import router as webhook_router
|
||||||
|
|
||||||
|
app = FastAPI(title="WK Bot", version="1.0.0")
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(webhook_router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
async def health():
|
||||||
|
return {"status": "ok"}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,75 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class CotizacionParams(BaseModel):
|
||||||
|
# Datos del vehículo
|
||||||
|
marca: str
|
||||||
|
tipo: str # versión específica (ESCALADE, GT3, etc.)
|
||||||
|
anio: int
|
||||||
|
kms: Optional[int] = None # None = 0km
|
||||||
|
|
||||||
|
# Datos financieros
|
||||||
|
precio_referencia: float
|
||||||
|
tasa_anual: float # decimal: 0.28 = 28%
|
||||||
|
renta_anticipada: float # decimal si es %, monto si es_monto_directo=True
|
||||||
|
es_monto_directo_ra: bool = False # True si RA vino como $ no como %
|
||||||
|
valor_residual_pct: float = 0.0 # decimal: 0.15 = 15%
|
||||||
|
plazo_meses: int # 24, 36, 48, 60
|
||||||
|
anualizar_vr: bool = True # False = "VR sin anualizar"
|
||||||
|
|
||||||
|
# Extras
|
||||||
|
seguro: Optional[float] = None # monto en pesos, None = no incluido
|
||||||
|
seguro_a_cargo_cliente: bool = False # aparece en PDF pero no suma al inicial
|
||||||
|
seguro_desde_anio: Optional[int] = None # ej. 2 = a partir del año 2
|
||||||
|
incluir_comision: bool = True
|
||||||
|
comision_override: Optional[float] = None # si se especifica monto exacto
|
||||||
|
incluir_placas: bool = False
|
||||||
|
placas_monto: Optional[float] = None
|
||||||
|
|
||||||
|
# Cliente
|
||||||
|
nombre_cliente: Optional[str] = None
|
||||||
|
atencion: Optional[str] = None
|
||||||
|
|
||||||
|
# Control
|
||||||
|
encabezado: str = "COTIZACION ARRENDAMIENTO DE AUTO" # puede cambiar
|
||||||
|
|
||||||
|
|
||||||
|
class CotizacionResult(BaseModel):
|
||||||
|
renta_anticipada_monto: float
|
||||||
|
valor_residual_total: float
|
||||||
|
valor_residual_por_anio: Optional[dict] = None # {1: x, 2: y, 3: z}
|
||||||
|
comision_monto: float
|
||||||
|
total_pago_inicial: float
|
||||||
|
renta_mensual: float
|
||||||
|
nuevo_precio: float
|
||||||
|
|
||||||
|
|
||||||
|
class WebhookMessage(BaseModel):
|
||||||
|
numero: str # número de WhatsApp del remitente
|
||||||
|
mensaje: str # texto del mensaje (puede venir vacío si es adjunto)
|
||||||
|
instance: str # instancia EvolutionAPI
|
||||||
|
# Adjunto para flujo de clonación: EvolutionAPI entrega documentos con
|
||||||
|
# mediaType="document" y el binario en base64.
|
||||||
|
pdf_base64: Optional[str] = None
|
||||||
|
media_type: Optional[str] = None
|
||||||
|
mime_type: Optional[str] = None
|
||||||
|
# Claves del mensaje original de EvolutionAPI (permiten descargar el PDF
|
||||||
|
# con /chat/getBase64FromMediaMessage cuando n8n no lo manda inline).
|
||||||
|
message_key: Optional[dict] = None
|
||||||
|
message_data: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ConsultaResult(BaseModel):
|
||||||
|
texto_respuesta: str
|
||||||
|
|
||||||
|
|
||||||
|
class InterpretacionResult(BaseModel):
|
||||||
|
intencion: str # "cotizacion" | "consulta_parametros"
|
||||||
|
params: Optional[CotizacionParams] = None
|
||||||
|
params_multiples: Optional[list[CotizacionParams]] = None # para "24 y 36 meses"
|
||||||
|
consulta_texto: Optional[str] = None # respuesta lista si es consulta
|
||||||
|
necesita_historico: bool = False
|
||||||
|
referencia_historico: Optional[str] = None # "GT3", "Diego Corona", etc.
|
||||||
|
usar_ultima_cotizacion: bool = False
|
||||||
|
modificaciones: Optional[dict] = None # {"tasa_anual": +0.02} para ajustes
|
||||||
Whitespace-only changes.
@@ -0,0 +1,63 @@
|
|||||||
|
import numpy_financial as npf
|
||||||
|
from src.models.schemas import CotizacionParams, CotizacionResult
|
||||||
|
|
||||||
|
|
||||||
|
def calcular_cotizacion(p: CotizacionParams) -> CotizacionResult:
|
||||||
|
precio = p.precio_referencia
|
||||||
|
plazo_anios = p.plazo_meses / 12
|
||||||
|
|
||||||
|
# Renta anticipada
|
||||||
|
if p.es_monto_directo_ra:
|
||||||
|
ra_monto = p.renta_anticipada
|
||||||
|
else:
|
||||||
|
ra_monto = precio * p.renta_anticipada
|
||||||
|
|
||||||
|
# Valor residual
|
||||||
|
vr_total = precio * p.valor_residual_pct
|
||||||
|
|
||||||
|
# Valor residual por año
|
||||||
|
vr_por_anio = None
|
||||||
|
if vr_total > 0 and p.anualizar_vr:
|
||||||
|
anios = int(plazo_anios)
|
||||||
|
vr_base = vr_total / anios
|
||||||
|
# Último año puede tener diferencia por redondeo
|
||||||
|
vr_por_anio = {i + 1: round(vr_base, 2) for i in range(anios)}
|
||||||
|
diferencia = round(vr_total - sum(vr_por_anio.values()), 2)
|
||||||
|
vr_por_anio[anios] = round(vr_por_anio[anios] + diferencia, 2)
|
||||||
|
|
||||||
|
# Nuevo precio (base del financiamiento)
|
||||||
|
nuevo_precio = precio - ra_monto
|
||||||
|
|
||||||
|
# Renta mensual usando fórmula PAGO/PMT
|
||||||
|
# npf.pmt(rate, nper, pv, fv) — fv es el VR como valor positivo
|
||||||
|
pago_anual = npf.pmt(p.tasa_anual, plazo_anios, -nuevo_precio, vr_total)
|
||||||
|
renta_mensual = round(float(pago_anual) / 12, 2)
|
||||||
|
|
||||||
|
# Comisión por apertura
|
||||||
|
if not p.incluir_comision:
|
||||||
|
comision = 0.0
|
||||||
|
elif p.comision_override is not None:
|
||||||
|
comision = p.comision_override
|
||||||
|
else:
|
||||||
|
comision = round(precio * 0.03, 2)
|
||||||
|
|
||||||
|
# Seguro (solo suma al inicial si no es "a cargo del cliente")
|
||||||
|
seguro_para_inicial = 0.0
|
||||||
|
if p.seguro and not p.seguro_a_cargo_cliente:
|
||||||
|
seguro_para_inicial = p.seguro
|
||||||
|
|
||||||
|
# Placas
|
||||||
|
placas = p.placas_monto if (p.incluir_placas and p.placas_monto) else 0.0
|
||||||
|
|
||||||
|
# Total pago inicial
|
||||||
|
total_inicial = round(ra_monto + seguro_para_inicial + comision + placas, 2)
|
||||||
|
|
||||||
|
return CotizacionResult(
|
||||||
|
renta_anticipada_monto=round(ra_monto, 2),
|
||||||
|
valor_residual_total=round(vr_total, 2),
|
||||||
|
valor_residual_por_anio=vr_por_anio,
|
||||||
|
comision_monto=round(comision, 2),
|
||||||
|
total_pago_inicial=total_inicial,
|
||||||
|
renta_mensual=renta_mensual,
|
||||||
|
nuevo_precio=round(nuevo_precio, 2),
|
||||||
|
)
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""
|
||||||
|
Descarga de media desde EvolutionAPI v2.
|
||||||
|
|
||||||
|
Cuando el webhook de EvolutionAPI entrega un mensaje con un documento adjunto,
|
||||||
|
no incluye el base64 por default. Hay que llamar al endpoint
|
||||||
|
POST /chat/getBase64FromMediaMessage/{instance} con el `key` del mensaje para
|
||||||
|
obtener el binario codificado.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
EVOLUTION_URL = os.getenv("EVOLUTION_API_URL")
|
||||||
|
EVOLUTION_KEY = os.getenv("EVOLUTION_API_KEY")
|
||||||
|
EVOLUTION_INSTANCE = os.getenv("EVOLUTION_INSTANCE")
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict:
|
||||||
|
return {
|
||||||
|
"apikey": EVOLUTION_KEY or "",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def descargar_pdf_base64(
|
||||||
|
message_key: dict,
|
||||||
|
message_data: Optional[dict] = None,
|
||||||
|
instance: Optional[str] = None,
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Descarga el base64 de un documento recibido vía EvolutionAPI.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message_key: dict con remoteJid, id, fromMe (el `key` del webhook).
|
||||||
|
message_data: objeto `message` completo del webhook (opcional, algunos
|
||||||
|
deployments de Evolution lo aceptan directamente).
|
||||||
|
instance: nombre de la instancia; si no viene, usa EVOLUTION_INSTANCE.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
String base64 del PDF o None si la descarga falla.
|
||||||
|
"""
|
||||||
|
if not EVOLUTION_URL:
|
||||||
|
logger.error("EVOLUTION_API_URL no configurada")
|
||||||
|
return None
|
||||||
|
if not message_key:
|
||||||
|
logger.error("descargar_pdf_base64: message_key vacío")
|
||||||
|
return None
|
||||||
|
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/chat/getBase64FromMediaMessage/{inst}"
|
||||||
|
|
||||||
|
# Formato aceptado por Evolution v2: {"message": {"key": {...}}, "convertToMp4": false}
|
||||||
|
payload: dict = {
|
||||||
|
"message": {"key": message_key},
|
||||||
|
"convertToMp4": False,
|
||||||
|
}
|
||||||
|
if message_data:
|
||||||
|
payload["message"]["message"] = message_data
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error descargando media de Evolution: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Evolution v2 devuelve {"base64": "...", "mimetype": "...", "fileName": "..."}
|
||||||
|
# o, en algunas versiones, anidado en "media".
|
||||||
|
b64 = data.get("base64")
|
||||||
|
if not b64 and isinstance(data.get("media"), dict):
|
||||||
|
b64 = data["media"].get("base64")
|
||||||
|
if not b64:
|
||||||
|
logger.error("Respuesta de Evolution sin base64: %s", str(data)[:200])
|
||||||
|
return None
|
||||||
|
return b64
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""
|
||||||
|
Extractor de parámetros financieros desde un PDF de cotización WK.
|
||||||
|
|
||||||
|
Se usa en el flujo de clonación: Paulino manda un PDF adjunto, extraemos los
|
||||||
|
porcentajes clave (tasa, renta anticipada, valor residual, comisión, plazo) y
|
||||||
|
los guardamos en Redis para aplicarlos a un precio nuevo en el siguiente paso.
|
||||||
|
|
||||||
|
Estrategia:
|
||||||
|
1. Intentar extracción de texto con PyMuPDF (rápido, sin costo).
|
||||||
|
2. Mandar el texto a GPT-4o-mini pidiendo JSON estructurado.
|
||||||
|
3. Si PyMuPDF falla (PDF escaneado, sin texto), caer a envío directo del PDF
|
||||||
|
como input al modelo con visión.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
||||||
|
|
||||||
|
PROMPT_EXTRACCION = """\
|
||||||
|
Eres un extractor de datos de cotizaciones de arrendamiento vehicular de \
|
||||||
|
WK Consulting. Recibes el texto de un PDF y debes devolver SOLO un JSON con \
|
||||||
|
los montos y parámetros exactos que aparecen impresos.
|
||||||
|
|
||||||
|
IMPORTANTE: el PDF tiene campos que se parecen entre sí. NO los confundas:
|
||||||
|
|
||||||
|
- "PRECIO DE REFERENCIA" → `precio_referencia` (monto en pesos).
|
||||||
|
- "RENTA ANTICIPADA" → `renta_anticipada_monto` (monto en pesos). \
|
||||||
|
NO es la comisión. NO es la renta mensual.
|
||||||
|
- "COMISIÓN POR APERTURA" o "COMISION" → `comision_monto` (monto en pesos). \
|
||||||
|
NO es la renta anticipada.
|
||||||
|
- "VALOR RESIDUAL TOTAL" o "VALOR RESIDUAL" (al final del contrato) → \
|
||||||
|
`valor_residual_total_monto` (monto en pesos). Si solo ves el desglose \
|
||||||
|
por año, súmalos. Si dice "NO APLICA" o "$0.00", devuelve 0.
|
||||||
|
- "RENTA MENSUAL" / "PAGO MENSUAL" → IGNORA, no se usa aquí.
|
||||||
|
|
||||||
|
Para el plazo:
|
||||||
|
- Busca "PLAZO" o "__ MESES" o "__ AÑOS" en el texto.
|
||||||
|
- Si hay tabla de valor residual por año (AÑO 1, AÑO 2, AÑO 3, AÑO 4), \
|
||||||
|
el plazo en meses = (número de años de VR) * 12. \
|
||||||
|
Ej. VR año 1,2,3,4 → plazo_meses = 48.
|
||||||
|
|
||||||
|
Para la tasa:
|
||||||
|
- Si aparece impresa como "TASA" o "% ANUAL" o "INTERÉS", devuélvela \
|
||||||
|
como decimal (30% → 0.30).
|
||||||
|
- Si NO aparece impresa (común en WK), devuelve null — se calculará aparte.
|
||||||
|
|
||||||
|
Otros:
|
||||||
|
- `marca`: fabricante (CADILLAC, PORSCHE, BMW, TOYOTA, etc.).
|
||||||
|
- `tipo`: versión/modelo impreso en "TIPO" o "MODELO" (ESCALADE, CAYENNE, \
|
||||||
|
HILUX, etc.).
|
||||||
|
- `anio`: año modelo impreso.
|
||||||
|
|
||||||
|
Los `_pct` los calcula otro sistema: tú SOLO devuelves los montos exactos \
|
||||||
|
que aparecen en el PDF. No estimes, no conviertas, no interpretes.
|
||||||
|
|
||||||
|
Responde SOLO el JSON, sin markdown ni texto adicional.
|
||||||
|
"""
|
||||||
|
|
||||||
|
RESPONSE_SCHEMA = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "extraccion_pdf",
|
||||||
|
"strict": True,
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"precio_referencia": {"type": ["number", "null"]},
|
||||||
|
"renta_anticipada_monto": {"type": ["number", "null"]},
|
||||||
|
"valor_residual_total_monto": {"type": ["number", "null"]},
|
||||||
|
"comision_monto": {"type": ["number", "null"]},
|
||||||
|
"tasa_anual": {"type": ["number", "null"]},
|
||||||
|
"plazo_meses": {"type": ["integer", "null"]},
|
||||||
|
"marca": {"type": ["string", "null"]},
|
||||||
|
"tipo": {"type": ["string", "null"]},
|
||||||
|
"anio": {"type": ["integer", "null"]},
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"precio_referencia", "renta_anticipada_monto",
|
||||||
|
"valor_residual_total_monto", "comision_monto",
|
||||||
|
"tasa_anual", "plazo_meses", "marca", "tipo", "anio",
|
||||||
|
],
|
||||||
|
"additionalProperties": False,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _extraer_texto_pdf(pdf_bytes: bytes) -> str:
|
||||||
|
"""Extrae texto plano del PDF. Devuelve '' si falla o no hay texto."""
|
||||||
|
try:
|
||||||
|
import fitz # PyMuPDF
|
||||||
|
except ImportError:
|
||||||
|
logger.warning("PyMuPDF no instalado; no se puede extraer texto del PDF")
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
partes = [page.get_text() for page in doc]
|
||||||
|
doc.close()
|
||||||
|
return "\n".join(partes).strip()
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error extrayendo texto del PDF con PyMuPDF")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
async def extraer_parametros_pdf(pdf_base64_str: str) -> dict:
|
||||||
|
"""Extrae los parámetros financieros de un PDF en base64.
|
||||||
|
|
||||||
|
Devuelve un dict con las claves del schema (puede contener nulls).
|
||||||
|
Lanza RuntimeError si la extracción falla por completo.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
pdf_bytes = base64.b64decode(pdf_base64_str)
|
||||||
|
except Exception as e:
|
||||||
|
raise RuntimeError(f"base64 inválido: {e}")
|
||||||
|
|
||||||
|
texto = _extraer_texto_pdf(pdf_bytes)
|
||||||
|
|
||||||
|
if texto:
|
||||||
|
contenido = (
|
||||||
|
"Texto extraído del PDF de cotización WK:\n\n"
|
||||||
|
f"{texto}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Sin texto: mandamos el PDF como data URL para que el modelo lo lea.
|
||||||
|
# GPT-4o-mini acepta documentos vía file input; como fallback ligero,
|
||||||
|
# pedimos al usuario reenviar si el texto está vacío.
|
||||||
|
raise RuntimeError(
|
||||||
|
"No se pudo extraer texto del PDF (¿es escaneado?). "
|
||||||
|
"Pídele a Paulino que lo reenvíe."
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.chat.completions.create(
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": PROMPT_EXTRACCION},
|
||||||
|
{"role": "user", "content": contenido},
|
||||||
|
],
|
||||||
|
temperature=0.0,
|
||||||
|
response_format=RESPONSE_SCHEMA,
|
||||||
|
)
|
||||||
|
crudo = json.loads(response.choices[0].message.content)
|
||||||
|
return _derivar_porcentajes(crudo)
|
||||||
|
|
||||||
|
|
||||||
|
def _derivar_porcentajes(crudo: dict) -> dict:
|
||||||
|
"""Convierte los montos extraídos del PDF en los % que espera el bot.
|
||||||
|
|
||||||
|
Los `_pct` se calculan aquí (no en el LLM) para evitar que el modelo
|
||||||
|
confunda campos. `clonacion_pendiente` en Redis espera las mismas llaves
|
||||||
|
que consume webhook._completar_clonacion: tasa_anual, renta_anticipada_pct,
|
||||||
|
valor_residual_pct, plazo_meses, comision_pct, marca, tipo, anio.
|
||||||
|
"""
|
||||||
|
precio = crudo.get("precio_referencia") or 0
|
||||||
|
ra_monto = crudo.get("renta_anticipada_monto") or 0
|
||||||
|
vr_monto = crudo.get("valor_residual_total_monto") or 0
|
||||||
|
com_monto = crudo.get("comision_monto") or 0
|
||||||
|
|
||||||
|
def pct(monto: float) -> float | None:
|
||||||
|
if not precio or precio <= 0:
|
||||||
|
return None
|
||||||
|
return round(monto / precio, 4)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"tasa_anual": crudo.get("tasa_anual"),
|
||||||
|
"renta_anticipada_pct": pct(ra_monto) if precio else None,
|
||||||
|
"valor_residual_pct": pct(vr_monto) if precio else 0.0,
|
||||||
|
"plazo_meses": crudo.get("plazo_meses"),
|
||||||
|
"comision_pct": pct(com_monto) if precio else 0.0,
|
||||||
|
"marca": crudo.get("marca"),
|
||||||
|
"tipo": crudo.get("tipo"),
|
||||||
|
"anio": crudo.get("anio"),
|
||||||
|
# Mantengo los montos originales por si se quieren mostrar/debuggear.
|
||||||
|
"_precio_referencia_original": precio or None,
|
||||||
|
"_renta_anticipada_monto": ra_monto or None,
|
||||||
|
"_valor_residual_total_monto": vr_monto or None,
|
||||||
|
"_comision_monto": com_monto or None,
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
|
||||||
|
from src.models.schemas import CotizacionParams, CotizacionResult
|
||||||
|
|
||||||
|
TEMPLATE_PATH = Path(__file__).resolve().parents[2] / "Plantilla_WK2.docm"
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_money(value: float) -> str:
|
||||||
|
if value == 0:
|
||||||
|
return ""
|
||||||
|
return f"$ {value:,.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _get_paragraph_text(paragraph) -> str:
|
||||||
|
"""Get full text of a paragraph by joining all runs."""
|
||||||
|
return "".join(run.text for run in paragraph.runs)
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_in_paragraph(paragraph, replacements: dict[str, str]):
|
||||||
|
"""Replace placeholders that may be split across multiple runs."""
|
||||||
|
full_text = _get_paragraph_text(paragraph)
|
||||||
|
if not any(key in full_text for key in replacements):
|
||||||
|
return
|
||||||
|
for key, val in replacements.items():
|
||||||
|
full_text = full_text.replace(key, val)
|
||||||
|
# Strip whitespace padding from template
|
||||||
|
full_text = full_text.strip()
|
||||||
|
# Put all text in first run, clear the rest
|
||||||
|
if paragraph.runs:
|
||||||
|
paragraph.runs[0].text = full_text
|
||||||
|
for run in paragraph.runs[1:]:
|
||||||
|
run.text = ""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _open_docm_as_docx(docm_path: str, dest_path: str):
|
||||||
|
"""Copy a .docm and patch its content type so python-docx can open it."""
|
||||||
|
with zipfile.ZipFile(docm_path, "r") as zin:
|
||||||
|
with zipfile.ZipFile(dest_path, "w") as zout:
|
||||||
|
for item in zin.infolist():
|
||||||
|
data = zin.read(item.filename)
|
||||||
|
if item.filename == "[Content_Types].xml":
|
||||||
|
data = data.replace(
|
||||||
|
b"application/vnd.ms-word.document.macroEnabled.main+xml",
|
||||||
|
b"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||||
|
)
|
||||||
|
zout.writestr(item, data)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_replacements(params: CotizacionParams, result: CotizacionResult) -> dict[str, str]:
|
||||||
|
fecha_hoy = date.today().strftime("%d/%m/%Y")
|
||||||
|
nombre_cliente = params.nombre_cliente or "A QUIEN CORRESPONDA"
|
||||||
|
atencion = params.atencion or "A QUIEN CORRESPONDA"
|
||||||
|
|
||||||
|
modelo_str = str(params.anio)
|
||||||
|
if params.kms and params.kms > 0:
|
||||||
|
modelo_str += f" ({params.kms:,} KMS)"
|
||||||
|
|
||||||
|
# Seguro
|
||||||
|
seguro_de_unidad = "DE UNIDAD"
|
||||||
|
if params.seguro_a_cargo_cliente:
|
||||||
|
seguro_val = "A CARGO DEL CLIENTE"
|
||||||
|
elif params.seguro and params.seguro > 0:
|
||||||
|
seguro_val = _fmt_money(params.seguro)
|
||||||
|
else:
|
||||||
|
seguro_val = "NO INCLUIDO"
|
||||||
|
|
||||||
|
comision_val = _fmt_money(result.comision_monto) if params.incluir_comision else ""
|
||||||
|
|
||||||
|
if params.incluir_placas and params.placas_monto:
|
||||||
|
placas_val = _fmt_money(params.placas_monto)
|
||||||
|
else:
|
||||||
|
placas_val = "NO APLICA"
|
||||||
|
|
||||||
|
# Valor residual
|
||||||
|
vr_total = _fmt_money(result.valor_residual_total) if result.valor_residual_total > 0 else ""
|
||||||
|
vr_by_year = ["", "", "", "", ""]
|
||||||
|
if result.valor_residual_por_anio and params.anualizar_vr:
|
||||||
|
for anio, monto in result.valor_residual_por_anio.items():
|
||||||
|
idx = int(anio) - 1
|
||||||
|
if 0 <= idx < 5:
|
||||||
|
vr_by_year[idx] = _fmt_money(monto)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"$FECHA$": fecha_hoy,
|
||||||
|
"$A QUIEN CORRESPONDA1$": nombre_cliente,
|
||||||
|
"$A QUIEN CORRESPONDA2$": atencion,
|
||||||
|
"$MARCA$": params.marca.upper(),
|
||||||
|
"$TIPO$": params.tipo.upper(),
|
||||||
|
"$MODELO$": modelo_str,
|
||||||
|
"$PRECIO$": _fmt_money(params.precio_referencia),
|
||||||
|
"$MESES$": f"{params.plazo_meses} MESES",
|
||||||
|
"$RENTA$": _fmt_money(result.renta_mensual),
|
||||||
|
"$DE UNIDAD$": seguro_de_unidad,
|
||||||
|
"$SEGURO$": seguro_val,
|
||||||
|
"$COMISION$": comision_val,
|
||||||
|
"$PLACASYPERMISO$": placas_val,
|
||||||
|
"$ANTICIPADA$": _fmt_money(result.renta_anticipada_monto),
|
||||||
|
"$RESIDUALTOTAL$": vr_total,
|
||||||
|
"$RESIDUAL1$": vr_by_year[0],
|
||||||
|
"$RESIDUAL2$": vr_by_year[1],
|
||||||
|
"$RESIDUAL3$": vr_by_year[2],
|
||||||
|
"$RESIDUAL4$": vr_by_year[3],
|
||||||
|
"$RESIDUAL5$": vr_by_year[4],
|
||||||
|
"$TOTAL$": _fmt_money(result.total_pago_inicial),
|
||||||
|
"$UNIDAD$": "UNIDAD",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def generar_pdf(params: CotizacionParams, result: CotizacionResult) -> bytes:
|
||||||
|
tmpdir = tempfile.mkdtemp()
|
||||||
|
try:
|
||||||
|
docx_path = os.path.join(tmpdir, "cotizacion.docx")
|
||||||
|
_open_docm_as_docx(str(TEMPLATE_PATH), docx_path)
|
||||||
|
|
||||||
|
doc = Document(docx_path)
|
||||||
|
replacements = _build_replacements(params, result)
|
||||||
|
|
||||||
|
# Replace placeholders in paragraphs and tables
|
||||||
|
for paragraph in doc.paragraphs:
|
||||||
|
_replace_in_paragraph(paragraph, replacements)
|
||||||
|
if "ARRENDAMIENTO DE UNIDAD" in paragraph.text:
|
||||||
|
paragraph.runs[0].text = " " + paragraph.runs[0].text
|
||||||
|
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
for cell in row.cells:
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
_replace_in_paragraph(paragraph, replacements)
|
||||||
|
# Align all cells to the left and strip leading/trailing whitespace
|
||||||
|
for row in table.rows:
|
||||||
|
for cell in row.cells:
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||||
|
runs = paragraph.runs
|
||||||
|
if runs:
|
||||||
|
runs[0].text = runs[0].text.lstrip()
|
||||||
|
runs[-1].text = runs[-1].text.rstrip()
|
||||||
|
|
||||||
|
# Remove empty paragraphs inside multi-paragraph cells
|
||||||
|
# (e.g. RESIDUAL4/5 are paragraphs inside the same row as COMISION, PLACAS, etc.)
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
cells = row.cells
|
||||||
|
if len(cells) < 2:
|
||||||
|
continue
|
||||||
|
left_cell = cells[0]
|
||||||
|
right_cell = cells[-1]
|
||||||
|
left_paras = list(left_cell.paragraphs)
|
||||||
|
right_paras = list(right_cell.paragraphs)
|
||||||
|
if len(right_paras) <= 1:
|
||||||
|
continue
|
||||||
|
# Walk paired paragraphs in reverse to safely remove
|
||||||
|
for i in range(len(right_paras) - 1, -1, -1):
|
||||||
|
r_text = right_paras[i].text.strip()
|
||||||
|
if not r_text or re.search(r'\$[A-Z][A-Z0-9 ]+\$', r_text):
|
||||||
|
# Remove paragraph XML from right cell
|
||||||
|
right_paras[i]._element.getparent().remove(right_paras[i]._element)
|
||||||
|
# Remove matching paragraph from left cell if it exists
|
||||||
|
if i < len(left_paras):
|
||||||
|
left_paras[i]._element.getparent().remove(left_paras[i]._element)
|
||||||
|
|
||||||
|
# Remove rows where right cell is entirely empty
|
||||||
|
for table in doc.tables:
|
||||||
|
for row in table.rows[:]:
|
||||||
|
if not row.cells[-1].text.strip():
|
||||||
|
row._tr.getparent().remove(row._tr)
|
||||||
|
|
||||||
|
doc.save(docx_path)
|
||||||
|
|
||||||
|
# Convert to PDF with LibreOffice (soffice on macOS, libreoffice on Linux)
|
||||||
|
soffice_cmd = "soffice" if shutil.which("soffice") else "libreoffice"
|
||||||
|
subprocess.run(
|
||||||
|
[soffice_cmd, "--headless", "--convert-to", "pdf", "--outdir", tmpdir, docx_path],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
pdf_path = os.path.join(tmpdir, "cotizacion.pdf")
|
||||||
|
with open(pdf_path, "rb") as f:
|
||||||
|
return f.read()
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
import redis.asyncio as aioredis
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
||||||
|
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
|
||||||
|
SESSION_TTL = 86400 # 24 horas
|
||||||
|
CLONACION_TTL = 1800 # 30 minutos
|
||||||
|
|
||||||
|
_client: aioredis.Redis | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_client() -> aioredis.Redis:
|
||||||
|
global _client
|
||||||
|
if _client is None:
|
||||||
|
_client = aioredis.Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
|
||||||
|
return _client
|
||||||
|
|
||||||
|
|
||||||
|
def _normalizar_numero(numero_wa: str) -> str:
|
||||||
|
"""Normaliza el JID de WhatsApp a un formato canónico.
|
||||||
|
|
||||||
|
Evolution a veces envía variantes:
|
||||||
|
- "5212228733600@s.whatsapp.net"
|
||||||
|
- "5212228733600:12@s.whatsapp.net" (con device suffix)
|
||||||
|
- "5212228733600" (sin dominio)
|
||||||
|
Todos deben apuntar a la misma clave de Redis.
|
||||||
|
"""
|
||||||
|
if not numero_wa:
|
||||||
|
return ""
|
||||||
|
n = numero_wa.strip()
|
||||||
|
# Quitar device suffix del formato "num:device@dominio"
|
||||||
|
if "@" in n:
|
||||||
|
local, dominio = n.split("@", 1)
|
||||||
|
if ":" in local:
|
||||||
|
local = local.split(":", 1)[0]
|
||||||
|
n = f"{local}@{dominio}"
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def _key(numero_wa: str) -> str:
|
||||||
|
return f"sesion:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
async def guardar_ultima_cotizacion(numero_wa: str, datos: dict) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(_key(numero_wa), SESSION_TTL, json.dumps(datos, ensure_ascii=False))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar sesión para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_ultima_cotizacion(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al obtener sesión para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_sesion(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar sesión para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Clonación pendiente (flujo 2-pasos: PDF adjunto → precio nuevo) ──
|
||||||
|
|
||||||
|
def _key_clonacion(numero_wa: str) -> str:
|
||||||
|
return f"clonacion:{_normalizar_numero(numero_wa)}"
|
||||||
|
|
||||||
|
|
||||||
|
async def guardar_clonacion_pendiente(numero_wa: str, params_dict: dict) -> None:
|
||||||
|
"""Guarda los % extraídos del PDF original (TTL 30 min)."""
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.setex(
|
||||||
|
_key_clonacion(numero_wa),
|
||||||
|
CLONACION_TTL,
|
||||||
|
json.dumps(params_dict, ensure_ascii=False),
|
||||||
|
)
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al guardar clonación para %s", numero_wa)
|
||||||
|
|
||||||
|
|
||||||
|
async def obtener_clonacion_pendiente(numero_wa: str) -> dict | None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
data = await r.get(_key_clonacion(numero_wa))
|
||||||
|
return json.loads(data) if data else None
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al leer clonación para %s", numero_wa)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def limpiar_clonacion_pendiente(numero_wa: str) -> None:
|
||||||
|
try:
|
||||||
|
r = get_client()
|
||||||
|
await r.delete(_key_clonacion(numero_wa))
|
||||||
|
except ConnectionError:
|
||||||
|
logger.error("Redis no disponible al limpiar clonación para %s", numero_wa)
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
import gspread
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
GOOGLE_SHEET_ID = os.getenv("GOOGLE_SHEET_ID")
|
||||||
|
GOOGLE_SHEET_NAME = os.getenv("GOOGLE_SHEET_NAME", "Contratos")
|
||||||
|
|
||||||
|
COLUMNAS = [
|
||||||
|
"fecha", "cliente", "atencion", "marca", "tipo", "anio", "kms",
|
||||||
|
"precio_referencia", "renta_anticipada", "tasa_anual", "plazo_meses",
|
||||||
|
"valor_residual_pct", "incluir_comision", "comision_pct",
|
||||||
|
"seguro_monto", "seguro_descripcion", "anualizar_vr", "renta_mensual",
|
||||||
|
]
|
||||||
|
|
||||||
|
_gc: gspread.Client | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client() -> gspread.Client | None:
|
||||||
|
global _gc
|
||||||
|
if _gc is not None:
|
||||||
|
return _gc
|
||||||
|
creds_json = os.getenv("GOOGLE_CREDENTIALS_JSON")
|
||||||
|
if not creds_json:
|
||||||
|
logger.warning("GOOGLE_CREDENTIALS_JSON no configurado")
|
||||||
|
return None
|
||||||
|
creds_dict = json.loads(creds_json)
|
||||||
|
_gc = gspread.service_account_from_dict(creds_dict)
|
||||||
|
return _gc
|
||||||
|
|
||||||
|
|
||||||
|
def _get_all_records() -> list[dict]:
|
||||||
|
gc = _get_client()
|
||||||
|
if gc is None:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
sh = gc.open_by_key(GOOGLE_SHEET_ID)
|
||||||
|
ws = sh.worksheet(GOOGLE_SHEET_NAME)
|
||||||
|
rows = ws.get_all_values()
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error leyendo Google Sheets")
|
||||||
|
return []
|
||||||
|
if len(rows) < 2:
|
||||||
|
return []
|
||||||
|
records = []
|
||||||
|
for row in rows[1:]:
|
||||||
|
d = {}
|
||||||
|
for i, col in enumerate(COLUMNAS):
|
||||||
|
d[col] = row[i] if i < len(row) else ""
|
||||||
|
records.append(d)
|
||||||
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
def buscar_contrato(query: str) -> list[dict]:
|
||||||
|
"""Busca contratos donde marca + tipo + anio contengan el query (max 5).
|
||||||
|
|
||||||
|
Si varias filas pertenecen a la misma flotilla (mismo cliente + vehículo
|
||||||
|
+ parámetros financieros + fecha), se consolidan en un único registro con
|
||||||
|
montos sumados y un campo extra `unidades`.
|
||||||
|
"""
|
||||||
|
records = _get_all_records()
|
||||||
|
q = query.lower().strip()
|
||||||
|
matches = []
|
||||||
|
for r in records:
|
||||||
|
texto = f"{r.get('marca', '')} {r.get('tipo', '')} {r.get('anio', '')}".lower()
|
||||||
|
if q in texto:
|
||||||
|
matches.append(r)
|
||||||
|
consolidados = _agrupar_flotillas(matches)
|
||||||
|
return consolidados[-5:]
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_num(valor) -> float:
|
||||||
|
"""Convierte strings tipo '1,234.50' o '15%' a float. Devuelve 0.0 si falla."""
|
||||||
|
if valor is None:
|
||||||
|
return 0.0
|
||||||
|
if isinstance(valor, (int, float)):
|
||||||
|
return float(valor)
|
||||||
|
s = str(valor).strip().replace("$", "").replace(",", "").replace("%", "")
|
||||||
|
if not s:
|
||||||
|
return 0.0
|
||||||
|
try:
|
||||||
|
return float(s)
|
||||||
|
except ValueError:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _agrupar_flotillas(records: list[dict]) -> list[dict]:
|
||||||
|
"""Agrupa filas que pertenecen a la misma flotilla.
|
||||||
|
|
||||||
|
Criterio: mismo cliente + marca + tipo + anio + tasa_anual + plazo_meses
|
||||||
|
+ renta_anticipada_pct + valor_residual_pct + fecha. La fecha discrimina
|
||||||
|
lotes distintos del mismo vehículo (ej. SLUTEN Frison T6 17/09 vs 02/10).
|
||||||
|
"""
|
||||||
|
grupos: dict[tuple, list[dict]] = {}
|
||||||
|
orden: list[tuple] = []
|
||||||
|
for r in records:
|
||||||
|
clave = (
|
||||||
|
(r.get("cliente") or "").strip().lower(),
|
||||||
|
(r.get("marca") or "").strip().lower(),
|
||||||
|
(r.get("tipo") or "").strip().lower(),
|
||||||
|
(r.get("anio") or "").strip(),
|
||||||
|
(r.get("tasa_anual") or "").strip(),
|
||||||
|
(r.get("plazo_meses") or "").strip(),
|
||||||
|
(r.get("renta_anticipada") or "").strip(),
|
||||||
|
(r.get("valor_residual_pct") or "").strip(),
|
||||||
|
(r.get("fecha") or "").strip(),
|
||||||
|
)
|
||||||
|
if clave not in grupos:
|
||||||
|
grupos[clave] = []
|
||||||
|
orden.append(clave)
|
||||||
|
grupos[clave].append(r)
|
||||||
|
|
||||||
|
consolidados: list[dict] = []
|
||||||
|
for clave in orden:
|
||||||
|
filas = grupos[clave]
|
||||||
|
if len(filas) == 1:
|
||||||
|
consolidados.append({**filas[0], "unidades": 1, "fecha_lote": filas[0].get("fecha", "")})
|
||||||
|
continue
|
||||||
|
|
||||||
|
base = dict(filas[0])
|
||||||
|
precio_ref_total = sum(_parse_num(f.get("precio_referencia")) for f in filas)
|
||||||
|
renta_mensual_total = sum(_parse_num(f.get("renta_mensual")) for f in filas)
|
||||||
|
seguro_total = sum(_parse_num(f.get("seguro_monto")) for f in filas)
|
||||||
|
|
||||||
|
# renta_anticipada y comision vienen como %; los montos se suman
|
||||||
|
# conservando el porcentaje (igual para todas las filas del grupo).
|
||||||
|
base["precio_referencia"] = precio_ref_total
|
||||||
|
base["renta_mensual"] = renta_mensual_total
|
||||||
|
base["seguro_monto"] = seguro_total
|
||||||
|
base["unidades"] = len(filas)
|
||||||
|
base["fecha_lote"] = base.get("fecha", "")
|
||||||
|
consolidados.append(base)
|
||||||
|
|
||||||
|
return consolidados
|
||||||
|
|
||||||
|
|
||||||
|
def obtener_contrato(query: str) -> dict | None:
|
||||||
|
"""Retorna el contrato más reciente que haga match con el query."""
|
||||||
|
matches = buscar_contrato(query)
|
||||||
|
return matches[-1] if matches else None
|
||||||
|
|
||||||
|
|
||||||
|
def listar_contratos_recientes(n: int = 10) -> list[dict]:
|
||||||
|
"""Retorna los últimos n contratos ordenados por fecha descendente."""
|
||||||
|
records = _get_all_records()
|
||||||
|
return list(reversed(records[-n:]))
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import os
|
||||||
|
import httpx
|
||||||
|
import base64
|
||||||
|
from src.utils.logger import logger
|
||||||
|
|
||||||
|
EVOLUTION_URL = os.getenv("EVOLUTION_API_URL") # ej. https://evo.tudominio.com
|
||||||
|
EVOLUTION_KEY = os.getenv("EVOLUTION_API_KEY")
|
||||||
|
EVOLUTION_INSTANCE = os.getenv("EVOLUTION_INSTANCE") # nombre de la instancia
|
||||||
|
|
||||||
|
|
||||||
|
def _headers() -> dict:
|
||||||
|
return {
|
||||||
|
"apikey": EVOLUTION_KEY,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def enviar_texto(numero: str, mensaje: str, instance: str = None) -> bool:
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/message/sendText/{inst}"
|
||||||
|
payload = {
|
||||||
|
"number": numero,
|
||||||
|
"text": mensaje,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
logger.info(f"Texto enviado a {numero}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error enviando texto a {numero}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def enviar_pdf(numero: str, pdf_bytes: bytes, filename: str, instance: str = None) -> bool:
|
||||||
|
inst = instance or EVOLUTION_INSTANCE
|
||||||
|
url = f"{EVOLUTION_URL}/message/sendMedia/{inst}"
|
||||||
|
|
||||||
|
pdf_b64 = base64.b64encode(pdf_bytes).decode()
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"number": numero,
|
||||||
|
"mediatype": "document",
|
||||||
|
"mimetype": "application/pdf",
|
||||||
|
"media": pdf_b64,
|
||||||
|
"fileName": filename,
|
||||||
|
"caption": "",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
resp = await client.post(url, json=payload, headers=_headers())
|
||||||
|
resp.raise_for_status()
|
||||||
|
logger.info(f"PDF '{filename}' enviado a {numero}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error enviando PDF a {numero}: {e}")
|
||||||
|
return False
|
||||||
Whitespace-only changes.
@@ -0,0 +1,10 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
|
||||||
|
handlers=[logging.StreamHandler(sys.stdout)],
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("wk-bot")
|
||||||
Whitespace-only changes.
@@ -0,0 +1,10 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
|
||||||
|
handlers=[logging.StreamHandler(sys.stdout)],
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("wk-bot")
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""
|
||||||
|
Genera PDFs de prueba con los parámetros calibrados.
|
||||||
|
Ejecutar: python tests/gen_pdf_samples.py
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
from src.services.calculator import calcular_cotizacion
|
||||||
|
from src.services.pdf_generator import generar_pdf
|
||||||
|
from src.models.schemas import CotizacionParams
|
||||||
|
|
||||||
|
|
||||||
|
def gen_escalade():
|
||||||
|
p = CotizacionParams(
|
||||||
|
marca="Cadillac", tipo="Escalade", anio=2024, kms=20000,
|
||||||
|
precio_referencia=2_000_000,
|
||||||
|
tasa_anual=0.278108,
|
||||||
|
renta_anticipada=978_940.03,
|
||||||
|
es_monto_directo_ra=True,
|
||||||
|
valor_residual_pct=0.0,
|
||||||
|
plazo_meses=24,
|
||||||
|
seguro=None,
|
||||||
|
comision_override=60_000,
|
||||||
|
)
|
||||||
|
r = calcular_cotizacion(p)
|
||||||
|
pdf_bytes = generar_pdf(p, r)
|
||||||
|
with open("tests/output/escalade_2024.pdf", "wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
print(f" tests/output/escalade_2024.pdf ({len(pdf_bytes):,} bytes)")
|
||||||
|
print(f" Renta mensual: ${r.renta_mensual:,.2f}")
|
||||||
|
print(f" Total pago inicial: ${r.total_pago_inicial:,.2f}")
|
||||||
|
|
||||||
|
|
||||||
|
def gen_range_rover():
|
||||||
|
p = CotizacionParams(
|
||||||
|
marca="Land Rover", tipo="Range Rover Sport Dynamic SE PHEV", anio=2025,
|
||||||
|
precio_referencia=2_808_364,
|
||||||
|
tasa_anual=0.334363,
|
||||||
|
renta_anticipada=431_916.36,
|
||||||
|
es_monto_directo_ra=True,
|
||||||
|
valor_residual_pct=0.2815,
|
||||||
|
plazo_meses=36,
|
||||||
|
seguro=40_000,
|
||||||
|
seguro_a_cargo_cliente=False,
|
||||||
|
comision_override=28_083.64,
|
||||||
|
anualizar_vr=True,
|
||||||
|
)
|
||||||
|
r = calcular_cotizacion(p)
|
||||||
|
pdf_bytes = generar_pdf(p, r)
|
||||||
|
with open("tests/output/range_rover_sport_2025.pdf", "wb") as f:
|
||||||
|
f.write(pdf_bytes)
|
||||||
|
print(f" tests/output/range_rover_sport_2025.pdf ({len(pdf_bytes):,} bytes)")
|
||||||
|
print(f" Renta mensual: ${r.renta_mensual:,.2f}")
|
||||||
|
print(f" Total pago inicial: ${r.total_pago_inicial:,.2f}")
|
||||||
|
print(f" VR Total: ${r.valor_residual_total:,.2f}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
gen_escalade()
|
||||||
|
gen_range_rover()
|
||||||
|
print("\nPDFs generados en tests/output/")
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,70 @@
|
|||||||
|
"""
|
||||||
|
Prueba rápida del motor financiero.
|
||||||
|
Valida contra las 2 cotizaciones reales de los PDFs de ejemplo.
|
||||||
|
Ejecutar: python tests/test_calculator.py
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
from src.services.calculator import calcular_cotizacion
|
||||||
|
from src.models.schemas import CotizacionParams
|
||||||
|
|
||||||
|
|
||||||
|
def test_cadillac_escalade():
|
||||||
|
"""
|
||||||
|
PDF: Cadillac Escalade 2024
|
||||||
|
Precio ref: 2,000,000 | Plazo: 24m | RA: 978,940.03 (directo)
|
||||||
|
Comisión: 60,000 | Total inicial: 1,038,940.03
|
||||||
|
Renta mensual: 61,014.18
|
||||||
|
"""
|
||||||
|
p = CotizacionParams(
|
||||||
|
marca="Cadillac", tipo="Escalade", anio=2024, kms=20000,
|
||||||
|
precio_referencia=2_000_000,
|
||||||
|
tasa_anual=0.278108, # calibrada contra PDF real
|
||||||
|
renta_anticipada=978_940.03,
|
||||||
|
es_monto_directo_ra=True,
|
||||||
|
valor_residual_pct=0.0,
|
||||||
|
plazo_meses=24,
|
||||||
|
seguro=None,
|
||||||
|
comision_override=60_000,
|
||||||
|
)
|
||||||
|
r = calcular_cotizacion(p)
|
||||||
|
print("=== CADILLAC ESCALADE 2024 ===")
|
||||||
|
print(f"Renta mensual: ${r.renta_mensual:,.2f} (esperado: ~$61,014.18)")
|
||||||
|
print(f"Total pago inicial: ${r.total_pago_inicial:,.2f} (esperado: $1,038,940.03)")
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def test_range_rover_sport():
|
||||||
|
"""
|
||||||
|
PDF: Range Rover Sport Dynamic SE PHEV 2025
|
||||||
|
Precio ref: 2,808,364 | Plazo: 36m | RA: 431,916.36 | VR Total: 790,520.41
|
||||||
|
Comisión: 28,083.64 | Seguro: 40,000 | Total inicial: 500,000
|
||||||
|
Renta mensual: 98,333.33
|
||||||
|
"""
|
||||||
|
p = CotizacionParams(
|
||||||
|
marca="Land Rover", tipo="Range Rover Sport Dynamic SE PHEV", anio=2025,
|
||||||
|
precio_referencia=2_808_364,
|
||||||
|
tasa_anual=0.334363, # calibrada contra PDF real
|
||||||
|
renta_anticipada=431_916.36,
|
||||||
|
es_monto_directo_ra=True,
|
||||||
|
valor_residual_pct=0.2815,
|
||||||
|
plazo_meses=36,
|
||||||
|
seguro=40_000,
|
||||||
|
seguro_a_cargo_cliente=False,
|
||||||
|
comision_override=28_083.64,
|
||||||
|
anualizar_vr=True,
|
||||||
|
)
|
||||||
|
r = calcular_cotizacion(p)
|
||||||
|
print("=== RANGE ROVER SPORT PHEV 2025 ===")
|
||||||
|
print(f"Renta mensual: ${r.renta_mensual:,.2f} (esperado: ~$98,333.33)")
|
||||||
|
print(f"VR Total: ${r.valor_residual_total:,.2f} (esperado: $790,520.41)")
|
||||||
|
print(f"VR por año: {r.valor_residual_por_anio}")
|
||||||
|
print(f"Total pago inicial: ${r.total_pago_inicial:,.2f} (esperado: $500,000.00)")
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_cadillac_escalade()
|
||||||
|
test_range_rover_sport()
|
||||||
|
print("✅ Tests ejecutados. Ajusta la tasa_anual hasta que los valores coincidan con los PDFs.")
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
"""
|
||||||
|
Tests para el agente intérprete de mensajes.
|
||||||
|
Usa mock de la API de OpenAI para no hacer llamadas reales.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Set a dummy key before importing so the module-level client doesn't fail
|
||||||
|
os.environ.setdefault("OPENAI_API_KEY", "test-key")
|
||||||
|
|
||||||
|
from src.agents.interpreter import interpretar_mensaje
|
||||||
|
|
||||||
|
|
||||||
|
def _mock_response(content: dict):
|
||||||
|
"""Crea un mock de respuesta de OpenAI con el contenido dado."""
|
||||||
|
mock = AsyncMock()
|
||||||
|
mock.choices = [AsyncMock()]
|
||||||
|
mock.choices[0].message.content = json.dumps(content)
|
||||||
|
return mock
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@patch("src.agents.interpreter.client")
|
||||||
|
async def test_cotizacion_directa(mock_client):
|
||||||
|
respuesta = {
|
||||||
|
"intencion": "cotizacion_directa",
|
||||||
|
"parametros": {
|
||||||
|
"marca": "CADILLAC",
|
||||||
|
"tipo": "ESCALADE",
|
||||||
|
"anio": 2024,
|
||||||
|
"kms": 20000,
|
||||||
|
"precio_referencia": 2000000,
|
||||||
|
"tasa_anual": 0.278,
|
||||||
|
"renta_anticipada": 978940,
|
||||||
|
"es_monto_directo": True,
|
||||||
|
"valor_residual_pct": None,
|
||||||
|
"valor_residual_monto": None,
|
||||||
|
"plazo_meses": 24,
|
||||||
|
"anualizar_vr": True,
|
||||||
|
"incluir_comision": True,
|
||||||
|
"comision_pct": 0.03,
|
||||||
|
"seguro_monto": None,
|
||||||
|
"seguro_descripcion": None,
|
||||||
|
"cliente": None,
|
||||||
|
"atencion": None,
|
||||||
|
},
|
||||||
|
"plazos_multiples": None,
|
||||||
|
"referencia_historico": None,
|
||||||
|
"campos_a_modificar": None,
|
||||||
|
"parametros_faltantes": None,
|
||||||
|
"consulta_texto": None,
|
||||||
|
}
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=_mock_response(respuesta))
|
||||||
|
|
||||||
|
result = await interpretar_mensaje(
|
||||||
|
"Cadillac Escalade 2024 20mil kms, precio 2mdp, anticipo 978,940, tasa 27.8%, 24 meses"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["intencion"] == "cotizacion_directa"
|
||||||
|
assert result["parametros"]["marca"] == "CADILLAC"
|
||||||
|
assert result["parametros"]["precio_referencia"] == 2000000
|
||||||
|
assert result["parametros"]["plazo_meses"] == 24
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@patch("src.agents.interpreter.client")
|
||||||
|
async def test_modificar_ultima(mock_client):
|
||||||
|
respuesta = {
|
||||||
|
"intencion": "modificar_ultima",
|
||||||
|
"parametros": None,
|
||||||
|
"plazos_multiples": None,
|
||||||
|
"referencia_historico": None,
|
||||||
|
"campos_a_modificar": {"tasa_anual_delta": 0.02},
|
||||||
|
"parametros_faltantes": None,
|
||||||
|
"consulta_texto": None,
|
||||||
|
}
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=_mock_response(respuesta))
|
||||||
|
|
||||||
|
ultima = {"marca": "CADILLAC", "tasa_anual": 0.278}
|
||||||
|
result = await interpretar_mensaje(
|
||||||
|
"A esta súbele 2 puntos a la tasa",
|
||||||
|
ultima_cotizacion=ultima,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["intencion"] == "modificar_ultima"
|
||||||
|
assert result["campos_a_modificar"]["tasa_anual_delta"] == 0.02
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@patch("src.agents.interpreter.client")
|
||||||
|
async def test_consulta_parametros(mock_client):
|
||||||
|
respuesta = {
|
||||||
|
"intencion": "consulta_parametros",
|
||||||
|
"parametros": None,
|
||||||
|
"plazos_multiples": None,
|
||||||
|
"referencia_historico": "GT3",
|
||||||
|
"campos_a_modificar": None,
|
||||||
|
"parametros_faltantes": None,
|
||||||
|
"consulta_texto": "¿Qué tasa traía el GT3?",
|
||||||
|
}
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=_mock_response(respuesta))
|
||||||
|
|
||||||
|
result = await interpretar_mensaje("¿Qué tasa traía el GT3?")
|
||||||
|
|
||||||
|
assert result["intencion"] == "consulta_parametros"
|
||||||
|
assert result["referencia_historico"] == "GT3"
|
||||||
|
assert result["consulta_texto"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@patch("src.agents.interpreter.client")
|
||||||
|
async def test_mensaje_incompleto(mock_client):
|
||||||
|
respuesta = {
|
||||||
|
"intencion": "mensaje_incompleto",
|
||||||
|
"parametros": {
|
||||||
|
"marca": "BMW",
|
||||||
|
"tipo": "M5",
|
||||||
|
"anio": 2025,
|
||||||
|
"kms": 0,
|
||||||
|
"precio_referencia": None,
|
||||||
|
"tasa_anual": None,
|
||||||
|
"renta_anticipada": None,
|
||||||
|
"es_monto_directo": None,
|
||||||
|
"valor_residual_pct": None,
|
||||||
|
"valor_residual_monto": None,
|
||||||
|
"plazo_meses": None,
|
||||||
|
"anualizar_vr": True,
|
||||||
|
"incluir_comision": True,
|
||||||
|
"comision_pct": 0.03,
|
||||||
|
"seguro_monto": None,
|
||||||
|
"seguro_descripcion": None,
|
||||||
|
"cliente": None,
|
||||||
|
"atencion": None,
|
||||||
|
},
|
||||||
|
"plazos_multiples": None,
|
||||||
|
"referencia_historico": None,
|
||||||
|
"campos_a_modificar": None,
|
||||||
|
"parametros_faltantes": ["precio_referencia", "tasa_anual", "renta_anticipada", "plazo_meses"],
|
||||||
|
"consulta_texto": None,
|
||||||
|
}
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=_mock_response(respuesta))
|
||||||
|
|
||||||
|
result = await interpretar_mensaje("Cotízame un BMW M5 2025")
|
||||||
|
|
||||||
|
assert result["intencion"] == "mensaje_incompleto"
|
||||||
|
assert "precio_referencia" in result["parametros_faltantes"]
|
||||||
|
assert result["parametros"]["marca"] == "BMW"
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""
|
||||||
|
Tests para el servicio de sesión Redis.
|
||||||
|
Usa fakeredis para no necesitar un servidor Redis real.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
import fakeredis.aioredis
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.services import session
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _patch_redis(monkeypatch):
|
||||||
|
"""Reemplaza el cliente Redis real con fakeredis."""
|
||||||
|
fake = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||||
|
monkeypatch.setattr(session, "_client", fake)
|
||||||
|
monkeypatch.setattr(session, "get_client", lambda: fake)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_guardar_y_obtener():
|
||||||
|
datos = {"marca": "CADILLAC", "tipo": "ESCALADE", "precio_referencia": 2000000}
|
||||||
|
await session.guardar_ultima_cotizacion("5212345678", datos)
|
||||||
|
|
||||||
|
resultado = await session.obtener_ultima_cotizacion("5212345678")
|
||||||
|
assert resultado == datos
|
||||||
|
assert resultado["marca"] == "CADILLAC"
|
||||||
|
assert resultado["precio_referencia"] == 2000000
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_expiracion():
|
||||||
|
datos = {"marca": "BMW", "tipo": "M5"}
|
||||||
|
await session.guardar_ultima_cotizacion("5299999999", datos)
|
||||||
|
|
||||||
|
r = session.get_client()
|
||||||
|
ttl = await r.ttl("sesion:5299999999")
|
||||||
|
assert 86399 <= ttl <= 86400
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_sesion_inexistente():
|
||||||
|
resultado = await session.obtener_ultima_cotizacion("0000000000")
|
||||||
|
assert resultado is None
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
Tests para el servicio de Google Sheets.
|
||||||
|
Usa unittest.mock para simular gspread.
|
||||||
|
"""
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.services import sheets
|
||||||
|
|
||||||
|
HEADER = [
|
||||||
|
"fecha", "cliente", "atencion", "marca", "tipo", "anio", "kms",
|
||||||
|
"precio_referencia", "renta_anticipada", "tasa_anual", "plazo_meses",
|
||||||
|
"valor_residual_pct", "incluir_comision", "comision_pct",
|
||||||
|
"seguro_monto", "seguro_descripcion", "anualizar_vr", "renta_mensual",
|
||||||
|
]
|
||||||
|
|
||||||
|
ROWS = [
|
||||||
|
HEADER,
|
||||||
|
["2025-01-15", "Diego Corona", "Diego", "LAND ROVER", "RANGE ROVER SPORT", "2025", "0",
|
||||||
|
"2808364", "431916.36", "0.334363", "36", "0.2815", "true", "0.01",
|
||||||
|
"40000", "Seguro anual", "true", "98333.33"],
|
||||||
|
["2025-02-10", "Juan Pérez", "Juan", "PORSCHE", "911 GT3", "2024", "5000",
|
||||||
|
"4500000", "1350000", "0.28", "24", "0.15", "true", "0.03",
|
||||||
|
"", "", "true", "150000"],
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _mock_worksheet():
|
||||||
|
ws = MagicMock()
|
||||||
|
ws.get_all_values.return_value = ROWS
|
||||||
|
sh = MagicMock()
|
||||||
|
sh.worksheet.return_value = ws
|
||||||
|
gc = MagicMock()
|
||||||
|
gc.open_by_key.return_value = sh
|
||||||
|
return gc
|
||||||
|
|
||||||
|
|
||||||
|
@patch.object(sheets, "_gc", None)
|
||||||
|
@patch.object(sheets, "_get_client")
|
||||||
|
def test_buscar_contrato_encontrado(mock_get_client):
|
||||||
|
mock_get_client.return_value = _mock_worksheet()
|
||||||
|
resultados = sheets.buscar_contrato("Range Rover")
|
||||||
|
|
||||||
|
assert len(resultados) == 1
|
||||||
|
assert resultados[0]["marca"] == "LAND ROVER"
|
||||||
|
assert resultados[0]["tipo"] == "RANGE ROVER SPORT"
|
||||||
|
assert resultados[0]["cliente"] == "Diego Corona"
|
||||||
|
|
||||||
|
|
||||||
|
@patch.object(sheets, "_gc", None)
|
||||||
|
@patch.object(sheets, "_get_client")
|
||||||
|
def test_buscar_contrato_no_encontrado(mock_get_client):
|
||||||
|
mock_get_client.return_value = _mock_worksheet()
|
||||||
|
resultados = sheets.buscar_contrato("Ferrari F40")
|
||||||
|
|
||||||
|
assert resultados == []
|
||||||
|
|
||||||
|
|
||||||
|
@patch.dict("os.environ", {}, clear=True)
|
||||||
|
@patch.object(sheets, "_gc", None)
|
||||||
|
def test_sin_credenciales():
|
||||||
|
# Forzar que _get_client retorne None (sin GOOGLE_CREDENTIALS_JSON)
|
||||||
|
original = sheets._get_client
|
||||||
|
sheets._gc = None
|
||||||
|
|
||||||
|
resultados = sheets.buscar_contrato("GT3")
|
||||||
|
assert resultados == []
|
||||||
+1598
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user