Proyecto completo con configuracion de variables de entorno para EasyPanel
This commit is contained in:
46
backend/.env.example
Normal file
46
backend/.env.example
Normal file
@@ -0,0 +1,46 @@
|
||||
# Plantilla de variables de entorno del BACKEND.
|
||||
# Copia este archivo como .env y completa los valores reales.
|
||||
# En EasyPanel estas variables se configuran en el panel del servicio (pestaña Environment).
|
||||
|
||||
# --- PostgreSQL (Chatwoot) ---
|
||||
PG_HOST=
|
||||
PG_DATABASE=
|
||||
PG_USER=
|
||||
PG_PASSWORD=
|
||||
PG_PORT=5432
|
||||
|
||||
# --- SQL Server ---
|
||||
SQL_SERVER=
|
||||
SQL_DATABASE=
|
||||
SQL_USERNAME=
|
||||
SQL_PASSWORD=
|
||||
|
||||
# --- Fuentes de datos ---
|
||||
GITHUB_BASE=
|
||||
|
||||
# --- Supabase (leads) ---
|
||||
SUPABASE_URL=
|
||||
SUPABASE_KEY=
|
||||
SUPABASE_TABLA_LEADS=datos_unificados
|
||||
|
||||
# --- Supabase (pauta) ---
|
||||
SUPABASE_PAUTA_URL=
|
||||
SUPABASE_PAUTA_KEY=
|
||||
SUPABASE_TABLA_PAUTA=basebi_programacion
|
||||
|
||||
# --- Supabase (cartera) ---
|
||||
CARTERA_URL=
|
||||
CARTERA_KEY=
|
||||
SUPABASE_TABLA_CARTERA=cartera_junta
|
||||
SUPABASE_TABLA_ALIAS=alias_normalizacion
|
||||
SUPABASE_TABLA_CONJUNTO=conjunto_pauta
|
||||
|
||||
# --- Meta / Google Sheets ---
|
||||
META_CSV_URL=
|
||||
|
||||
# --- Servidor (opcional) ---
|
||||
# Puerto en el que corre la API. EasyPanel suele asignar 8001 internamente.
|
||||
PORT=8001
|
||||
# Origenes permitidos para CORS, separados por coma. Usa * para permitir todos.
|
||||
# Ejemplo producción: https://dashboard.tudominio.com
|
||||
CORS_ORIGINS=*
|
||||
79
backend/cache_manager.py
Normal file
79
backend/cache_manager.py
Normal file
@@ -0,0 +1,79 @@
|
||||
# backend/cache_manager.py
|
||||
"""Caché global en memoria con refresco en segundo plano (igual que el dashboard de ventas)."""
|
||||
import time
|
||||
import threading
|
||||
from typing import Any, Callable, Dict, Tuple
|
||||
|
||||
_CACHE: Dict[str, Tuple[float, Any]] = {}
|
||||
_LOCK = threading.Lock()
|
||||
_DEFAULT_TTL = 900 # 15 min
|
||||
|
||||
|
||||
def _make_key(prefix: str, args: tuple) -> str:
|
||||
return prefix + ":" + "|".join(str(a) for a in args)
|
||||
|
||||
|
||||
def cache_get_or_set(prefix: str, args: tuple, loader: Callable[[], Any], ttl: int = _DEFAULT_TTL) -> Any:
|
||||
key = _make_key(prefix, args)
|
||||
now = time.time()
|
||||
with _LOCK:
|
||||
hit = _CACHE.get(key)
|
||||
if hit and (now - hit[0] < ttl):
|
||||
return hit[1]
|
||||
value = loader()
|
||||
with _LOCK:
|
||||
_CACHE[key] = (now, value)
|
||||
return value
|
||||
|
||||
|
||||
def cache_keys():
|
||||
with _LOCK:
|
||||
return list(_CACHE.keys())
|
||||
|
||||
|
||||
def cache_refresh_existing(loader_for_key):
|
||||
for key in cache_keys():
|
||||
try:
|
||||
nuevo = loader_for_key(key)
|
||||
if nuevo is not None:
|
||||
with _LOCK:
|
||||
_CACHE[key] = (time.time(), nuevo)
|
||||
except Exception as e:
|
||||
print(f"[cache refresh] {key}: {e}")
|
||||
|
||||
|
||||
def cache_invalidate(prefix: str = None) -> None:
|
||||
with _LOCK:
|
||||
if prefix is None:
|
||||
_CACHE.clear()
|
||||
else:
|
||||
for k in list(_CACHE.keys()):
|
||||
if k.startswith(prefix + ":"):
|
||||
del _CACHE[k]
|
||||
|
||||
|
||||
def cache_stats() -> dict:
|
||||
with _LOCK:
|
||||
return {"entradas": len(_CACHE), "claves": list(_CACHE.keys())}
|
||||
|
||||
|
||||
_background_started = False
|
||||
|
||||
|
||||
def start_background_refresh(refresh_fn: Callable[[], None], interval: int = 900):
|
||||
global _background_started
|
||||
if _background_started:
|
||||
return
|
||||
_background_started = True
|
||||
|
||||
def _loop():
|
||||
while True:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
refresh_fn()
|
||||
except Exception as e:
|
||||
print(f"[background refresh] error: {e}")
|
||||
|
||||
t = threading.Thread(target=_loop, daemon=True)
|
||||
t.start()
|
||||
print(f"[cache] refresco en segundo plano cada {interval}s iniciado")
|
||||
BIN
backend/cartera_junta_export - copia.xlsx
Normal file
BIN
backend/cartera_junta_export - copia.xlsx
Normal file
Binary file not shown.
87860
backend/cartera_junta_export.csv
Normal file
87860
backend/cartera_junta_export.csv
Normal file
File diff suppressed because it is too large
Load Diff
BIN
backend/cartera_junta_export.xlsx
Normal file
BIN
backend/cartera_junta_export.xlsx
Normal file
Binary file not shown.
271
backend/data_manager.py
Normal file
271
backend/data_manager.py
Normal file
@@ -0,0 +1,271 @@
|
||||
# backend/data_manager.py
|
||||
"""
|
||||
Capa de acceso a datos del módulo LEADS.
|
||||
- PostgreSQL (Chatwoot): leads de pauta (consolidado en UNA sola consulta).
|
||||
- SQL Server (Académico): matrículas y cursos.
|
||||
- GitHub: mapa de campañas (frases -> programa/sede), config editable.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
from datetime import datetime
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class DataManager:
|
||||
def __init__(self):
|
||||
# PostgreSQL (Chatwoot)
|
||||
self.pg_host = os.getenv("PG_HOST", "191.98.134.81")
|
||||
self.pg_db = os.getenv("PG_DATABASE", "chatwoot_production")
|
||||
self.pg_user = os.getenv("PG_USER", "postgres")
|
||||
self.pg_pass = os.getenv("PG_PASSWORD", "")
|
||||
self.pg_port = os.getenv("PG_PORT", "5432")
|
||||
# SQL Server (Académico)
|
||||
self.sql_server = os.getenv("SQL_SERVER", "191.98.134.80")
|
||||
self.sql_db = os.getenv("SQL_DATABASE", "BDUS_CK000040_0001")
|
||||
self.sql_user = os.getenv("SQL_USERNAME", "")
|
||||
self.sql_pass = os.getenv("SQL_PASSWORD", "")
|
||||
# GitHub
|
||||
base = os.getenv("GITHUB_BASE", "")
|
||||
self.github_campanias_url = f"{base}/campanias.json" if base else ""
|
||||
self.campanias = []
|
||||
self._cargar_campanias()
|
||||
|
||||
# ── Conexiones ──────────────────────────────────────────────
|
||||
def pg_conn(self):
|
||||
import psycopg2
|
||||
return psycopg2.connect(
|
||||
host=self.pg_host, dbname=self.pg_db, user=self.pg_user,
|
||||
password=self.pg_pass, port=self.pg_port,
|
||||
)
|
||||
|
||||
def sql_conn(self):
|
||||
import pyodbc
|
||||
conn_str = (
|
||||
f"DRIVER={{SQL Server}};SERVER={self.sql_server};"
|
||||
f"DATABASE={self.sql_db};UID={self.sql_user};PWD={self.sql_pass}"
|
||||
)
|
||||
return pyodbc.connect(conn_str)
|
||||
|
||||
# ── Config de campañas (GitHub, opcional) ───────────────────
|
||||
def _cargar_campanias(self):
|
||||
if not self.github_campanias_url:
|
||||
self.campanias = []
|
||||
return
|
||||
try:
|
||||
r = requests.get(self.github_campanias_url, timeout=5)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
self.campanias = data.get("campanias", []) if isinstance(data, dict) else data
|
||||
except Exception:
|
||||
self.campanias = []
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# CHATWOOT — UN SOLO QUERY CONSOLIDADO DE LEADS
|
||||
# Reemplaza los 4 queries del PBI (procesados, asignados,
|
||||
# contactados, etiquetas) por uno solo. El resto se calcula
|
||||
# en Python (Cantidad_Veces, Ultima_Etiqueta, Estado/Objeción).
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def traer_leads_chatwoot(self):
|
||||
"""Leads de PAUTA (igual que el PBI): un mensaje cuenta como lead solo si su
|
||||
texto coincide con una FRASE de campaña y está dentro del rango de fechas de
|
||||
esa campaña. El mapa de campañas está incrustado (como en el Power BI)."""
|
||||
sql = """
|
||||
SELECT DISTINCT ON (m.id)
|
||||
REGEXP_REPLACE(c.phone_number, '[^0-9]', '', 'g') AS telefono,
|
||||
u.name AS asesor,
|
||||
(m.created_at - INTERVAL '5 hours') AS fecha_creada,
|
||||
cv.cached_label_list AS etiquetas,
|
||||
map.cargo AS programa,
|
||||
map.sede AS sede,
|
||||
map.codigo AS codigo,
|
||||
map.origen AS origen
|
||||
FROM messages m
|
||||
JOIN conversations cv ON m.conversation_id = cv.id
|
||||
JOIN contacts c ON cv.contact_id = c.id
|
||||
LEFT JOIN users u ON cv.assignee_id = u.id
|
||||
JOIN (VALUES
|
||||
('📚 Me interesa el', 'TERC', '200', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-10-01', '2025-12-31'),
|
||||
('📚 Me interesa el', 'TEAC', '227', 'Lima', 'Domingo', 'Pauta_wsp', '2026-01-15', '2026-03-30'),
|
||||
('Hola! 🚨', 'TEAC', '191', 'Piura', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 💯 Me interesa', 'TERC', '193', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 💼', 'TEAC', '195', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 💸', 'TEAC', '197', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! ⚡', 'TEAC', '198', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 🦺', 'TERC', '199', 'Piura', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 🍾', 'TEAC', '201', 'Arequipa', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('¡Hola! 📚', 'TERC', '200', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 🥶', 'TEAC', '202', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎯', 'TEAC', '203', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 🌞', 'TERC', '204', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🗿', 'TERC', '205', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 😎', 'TEAC', '206', 'Piura', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-04-01'),
|
||||
('Hola! 🎓', 'TEAC', '207', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 👀', 'TEAC', '208', 'Trujillo', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎮', 'TERC', '209', 'Piura', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-30'),
|
||||
('Hola! 👾', 'TERC', '210', 'Arequipa', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-25'),
|
||||
('Hola! 🕹️', 'TERC', '211', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-04-01'),
|
||||
('Hola! 🚀', 'TEAC', '212', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🛸', 'TERC', '213', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🦾', 'Amoniaco', '63a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('Hola! 🛠️', 'Diseño Chillers', '64a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-04-30'),
|
||||
('¡Hola! 🥽', 'VRF', '65a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('¡Hola! ❄️ Estoy interesado Seminario', 'Cámaras', '66a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-05-28'),
|
||||
('¡Hola! 🤩', 'Diseño de Sistemas', '67a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-12-31'),
|
||||
('¡Hola! 🙌🏼', 'Metrado y Costeo', '68a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-12-31'),
|
||||
('¡Hola! 🥽', 'VRF', '69a', 'Lima', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 🧊 Más información del Seminario', 'VRF', '71a', 'Arequipa', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 📐 Más información del Seminario', 'VRF', '72a', 'Trujillo', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 👾 Más información del Seminario en Instalación', 'VRF', '73a', 'Piura', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 🖥️ Estoy interesado en sus Seminarios', 'Seminarios', '74a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
(' 🙋 Deseo más info. del Diplomado ', 'Diplomado REF', '75a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
('💸 Deseo más info. del Seminario', 'CAD', '76a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
('🦾 Estoy interesado Instalación de Sistemas', 'VRF', '77a', 'Lima', '-', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🙀 Estoy interesado Seminario', 'SUPER.OBRAS', '78a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('🛠️ más info del Seminario Diseño de Chillers', 'Diseño', '79a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('👾Estoy interesado en el Seminario Refrigeración', 'CO2', '80a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('Hola! 👉', 'TEAC', '214', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🤝', 'TEAC', '215', 'Lima', 'Domingo', 'Pauta_wsp', '2025-12-01', '2026-03-15'),
|
||||
('🆕 Me interesa', 'TERC', '217', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🌬️', 'TEAC', '218', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🌍', 'TERC', '219', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎟️', 'TEAC', '220', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-03-31'),
|
||||
('Hola! 🌈', 'TERC', '221', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('¡Hola! ❄️ Me interesa el programa', 'TEAC', '222', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🔝', 'TERC', '223', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('🔋 Me interesa', 'TEAC', '224', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('¡Hola! 🌡️', 'TEAC', '225', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('¡Hola! ☃️', 'TERC', '226', 'Lima', 'Sábado', 'Pauta_wsp', '2026-01-01', '2026-04-15'),
|
||||
('¡Hola! 📚', 'TERC', '227', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-10'),
|
||||
('¡Hola! 🗺️', 'TEAC', '228', 'Arequipa','Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-05'),
|
||||
('¡Hola! 🌤️', 'TEAC', '229', 'Piura', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! ⚡', 'TEAC', '230', 'Trujillo','Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-07'),
|
||||
('¡Hola! 🎤', 'TERC', '231', 'Lima', 'Domingo', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! 👾 Me interesa el programa', 'TEAC', '232', 'Lima', 'Domingo', 'Pauta_wsp', '2026-02-26', '2026-05-30'),
|
||||
('¡Hola! 🍨', 'TEAC', '233', 'Lima', 'Sábado', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! 🐶 Me interesa', 'TEAC', '234', 'Piura', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 💸 Me interesa', 'TERC', '235', 'Arequipa', 'Semipresencial', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🗿 Me interesa', 'TERC', '236', 'Trujillo', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🦺 Me interesa', 'TEAC', '237', 'Lima', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🍾 Me interesa', 'TEAC', '238', 'Lima', 'Domingo', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('💡 deseo más info del programa', 'TERC', '239', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🎯 Me interesa el programa', 'TERC', '240', 'Lima', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('¡Hola! 🤝 Me interesa el programa', 'TERC', '241', 'Lima', 'Sábado', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('🪐 Me interesa el programa', 'TERC', '242', 'Piura', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('🎓 Me interesa el programa', 'TEAC', '243', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-06-30'),
|
||||
('💼 Me interesa el programa ', 'TEAC', '244', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-06-30'),
|
||||
('☃️ Me interesa el programa', 'TEAC', '245', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🔋 Me interesa el programa', 'TERC', '246', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('😎 Me interesa el programa', 'TEAC', '247', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🌈Me interesa el programa', 'TEAC', '248', 'Lima', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('⭐ Me interesa el programa', 'TEAC', '249', 'Lima', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🕵️ Me interesa el programa', 'TEAC', '250', 'Piura', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('📈 Me interesa el programa', 'TEAC', '251', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🗺️ Me interesa el programa', 'TEAC', '252', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-06', '2026-07-30'),
|
||||
('🎮 Me interesa el programa', 'TEAC', '253', 'Trujillo', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🏞️ Me interesa el programa', 'TERC', '254', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('⚙️ Me interesa el programa', 'TERC', '255', 'Piura', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('⚡ Me interesa el programa', 'TERC', '256', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-05-08', '2026-12-31'),
|
||||
('🎟️ Me interesa el programa', 'TERC', '257', 'Trujillo', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('🕑 Me interesa el', 'TERC', '258', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('📚 Me interesa el programa', 'TEAC', '259', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🤗 Me interesa el programa', 'TEAC', '260', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🕹️ Me interesa el programa', 'TERC', '261', 'Lima', 'Domingo', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🐶 Me interesa el programa', 'TEAC', '262', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-11', '2026-08-30'),
|
||||
('🍨 Me interesa el programa', 'TERC', '263', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('⛱️ Me interesa el programa de Aire Acondicionado', 'TEAC', '264', 'Lima', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('🌤️ Me interesa el programa', 'TEAC', '265', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('⛱️ Me interesa el programa de Refrigeración comercial', 'TERC', '266', 'Lima', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('¡Hola! Vengo de su web, quiero saber', 'TEAC', '0', 'Lima', '-', 'Web_Whatsapp', '2025-11-01', '2026-12-31')
|
||||
) AS map(frase_busqueda, cargo, codigo, sede, dia, origen, fecha_inicio, fecha_fin)
|
||||
ON m.content LIKE '%' || map.frase_busqueda || '%'
|
||||
AND m.created_at >= CAST(map.fecha_inicio AS TIMESTAMP)
|
||||
AND m.created_at <= CAST(map.fecha_fin AS TIMESTAMP) + INTERVAL '1 day'
|
||||
WHERE m.sender_type = 'Contact'
|
||||
ORDER BY m.id ASC, m.created_at ASC
|
||||
"""
|
||||
conn = self.pg_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# SQL SERVER — CURSOS (igual que el PBI: Fact_SQL_Base_Cursos)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def traer_cursos(self):
|
||||
sql = """
|
||||
SELECT
|
||||
rp.num_indice,
|
||||
rp.dsc_det_programa,
|
||||
p.dsc_programa,
|
||||
rp.cod_frecuencia,
|
||||
rp.fch_inicio,
|
||||
rp.cod_estado,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado NOT IN ('ANU')) AS Inscritos_Totales,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado = 'RET') AS Inscritos_Retirados,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado NOT IN ('ANU','RET','SUS')) AS Inscritos_Activos
|
||||
FROM sgede_RP_programa rp
|
||||
INNER JOIN sgeca_programa p ON rp.cod_programa = p.cod_programa
|
||||
WHERE YEAR(rp.fch_inicio) IN (2025, 2026)
|
||||
ORDER BY rp.fch_inicio ASC
|
||||
"""
|
||||
conn = self.sql_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# SQL SERVER — MATRÍCULAS (Fact_SQL_Base_Matriculas, resumido)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def traer_matriculas(self):
|
||||
sql = """
|
||||
SELECT
|
||||
sgeca_matricula.num_matricula,
|
||||
sgeca_matricula.num_indice,
|
||||
sgeca_matricula.fch_matricula,
|
||||
sgeca_matricula.cod_estado AS estado_matricula,
|
||||
REPLACE(sgema_alumno.dsc_telefono_1,' ','') AS dsc_telefono_1,
|
||||
sgeca_programa.dsc_programa,
|
||||
sgede_RP_programa.dsc_det_programa AS dsc_promocion,
|
||||
ISNULL((SELECT sgede_cronograma_matricula.imp_saldo FROM sgede_cronograma_matricula
|
||||
WHERE sgede_cronograma_matricula.cod_localidad = sgeca_matricula.cod_localidad
|
||||
AND sgede_cronograma_matricula.num_matricula = sgeca_matricula.num_matricula
|
||||
AND sgede_cronograma_matricula.num_refinanciamiento = 1
|
||||
AND sgede_cronograma_matricula.num_cuota = 0), 0) AS imp_saldo_matricula,
|
||||
ISNULL((SELECT sgede_cronograma_matricula.imp_saldo FROM sgede_cronograma_matricula
|
||||
WHERE sgede_cronograma_matricula.cod_localidad = sgeca_matricula.cod_localidad
|
||||
AND sgede_cronograma_matricula.num_matricula = sgeca_matricula.num_matricula
|
||||
AND sgede_cronograma_matricula.num_refinanciamiento = 1
|
||||
AND sgede_cronograma_matricula.num_cuota = 1), 0) AS imp_saldo_cuota1
|
||||
FROM sgeca_matricula
|
||||
INNER JOIN sgeca_programa ON sgeca_matricula.cod_programa = sgeca_programa.cod_programa
|
||||
LEFT JOIN sgede_RP_programa ON sgeca_matricula.cod_periodo = sgede_RP_programa.cod_detalle
|
||||
AND sgeca_matricula.cod_programa = sgede_RP_programa.cod_programa
|
||||
AND sgeca_matricula.num_indice = sgede_RP_programa.num_indice
|
||||
INNER JOIN sgema_alumno ON sgeca_matricula.cod_alumno = sgema_alumno.cod_alumno
|
||||
WHERE sgeca_matricula.cod_localidad LIKE 'SCENT'
|
||||
AND sgeca_matricula.fch_matricula BETWEEN '01-11-2024 00:00:00.000' AND '31-12-2026 23:59:00.000'
|
||||
AND sgeca_matricula.cod_estado <> 'ANU'
|
||||
"""
|
||||
conn = self.sql_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
# --- fin data_manager ---
|
||||
722
backend/data_manager_v2.py
Normal file
722
backend/data_manager_v2.py
Normal file
@@ -0,0 +1,722 @@
|
||||
# backend/data_manager.py (v2 - reescrito completo)
|
||||
"""Capa de acceso a datos del módulo LEADS."""
|
||||
import os
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ── Mapa de campañas (frase -> programa/sede/rango fechas), igual que el PBI ──
|
||||
CAMPANIAS = [
|
||||
('📚 Me interesa el', 'TERC', '200', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-10-01', '2025-12-31'),
|
||||
('📚 Me interesa el', 'TEAC', '227', 'Lima', 'Domingo', 'Pauta_wsp', '2026-01-15', '2026-03-30'),
|
||||
('Hola! 🚨', 'TEAC', '191', 'Piura', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 💯 Me interesa', 'TERC', '193', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 💼', 'TEAC', '195', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 💸', 'TEAC', '197', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! ⚡', 'TEAC', '198', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 🦺', 'TERC', '199', 'Piura', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 🍾', 'TEAC', '201', 'Arequipa', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('¡Hola! 📚', 'TERC', '200', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 🥶', 'TEAC', '202', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎯', 'TEAC', '203', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 🌞', 'TERC', '204', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🗿', 'TERC', '205', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('Hola! 😎', 'TEAC', '206', 'Piura', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-04-01'),
|
||||
('Hola! 🎓', 'TEAC', '207', 'Arequipa', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-01-31'),
|
||||
('Hola! 👀', 'TEAC', '208', 'Trujillo', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎮', 'TERC', '209', 'Piura', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-30'),
|
||||
('Hola! 👾', 'TERC', '210', 'Arequipa', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-02-25'),
|
||||
('Hola! 🕹️', 'TERC', '211', 'Trujillo', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-04-01'),
|
||||
('Hola! 🚀', 'TEAC', '212', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🛸', 'TERC', '213', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🦾', 'Amoniaco', '63a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('Hola! 🛠️', 'Diseño Chillers', '64a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-04-30'),
|
||||
('¡Hola! 🥽', 'VRF', '65a', 'Lima', '-', 'Pauta_wsp', '2025-09-01', '2026-02-28'),
|
||||
('¡Hola! ❄️ Estoy interesado Seminario', 'Cámaras', '66a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-05-28'),
|
||||
('¡Hola! 🤩', 'Diseño de Sistemas', '67a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-12-31'),
|
||||
('¡Hola! 🙌🏼', 'Metrado y Costeo', '68a', 'Lima', '-', 'Pauta_wsp', '2026-02-01', '2026-12-31'),
|
||||
('¡Hola! 🥽', 'VRF', '69a', 'Lima', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 🧊 Más información del Seminario', 'VRF', '71a', 'Arequipa', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 📐 Más información del Seminario', 'VRF', '72a', 'Trujillo', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 👾 Más información del Seminario en Instalación', 'VRF', '73a', 'Piura', '-', 'Pauta_wsp', '2026-03-01', '2026-06-30'),
|
||||
(' 🖥️ Estoy interesado en sus Seminarios', 'Seminarios', '74a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
(' 🙋 Deseo más info. del Diplomado ', 'Diplomado REF', '75a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
('💸 Deseo más info. del Seminario', 'CAD', '76a', 'Lima', '-', 'Pauta_wsp', '2026-04-01', '2026-07-30'),
|
||||
('🦾 Estoy interesado Instalación de Sistemas', 'VRF', '77a', 'Lima', '-', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🙀 Estoy interesado Seminario', 'SUPER.OBRAS', '78a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('🛠️ más info del Seminario Diseño de Chillers', 'Diseño', '79a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('👾Estoy interesado en el Seminario Refrigeración', 'CO2', '80a', 'Lima', '-', 'Pauta_wsp', '2026-05-15', '2026-07-30'),
|
||||
('📱 Estoy interesado Instalación', 'VRF', '81a', 'Lima', '-', 'Pauta_wsp', '2026-06-25', '2026-08-30'),
|
||||
('🧊 Más información del Seminario', 'VRF', '82a', 'Arequipa', '-', 'Pauta_wsp', '2026-07-01', '2026-08-30'),
|
||||
('📐 Más información del Seminario', 'VRF', '83a', 'Trujillo', '-', 'Pauta_wsp', '2026-07-01', '2026-08-30'),
|
||||
('👾 Más información del Seminario', 'VRF', '84a', 'Piura', '-', 'Pauta_wsp', '2026-07-01', '2026-08-30'),
|
||||
('🛠️ más info del Seminario Virtual ', 'Diseño de Chillers', '85a', 'Lima', '-', 'Pauta_wsp', '2026-07-01', '2026-09-30'),
|
||||
('Hola! 👉', 'TEAC', '214', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🤝', 'TEAC', '215', 'Lima', 'Domingo', 'Pauta_wsp', '2025-12-01', '2026-03-15'),
|
||||
('🆕 Me interesa', 'TERC', '217', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🌬️', 'TEAC', '218', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🌍', 'TERC', '219', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🎟️', 'TEAC', '220', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-03-31'),
|
||||
('Hola! 🌈', 'TERC', '221', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('¡Hola! ❄️ Me interesa el programa', 'TEAC', '222', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('Hola! 🔝', 'TERC', '223', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('🔋 Me interesa', 'TEAC', '224', 'Lima', 'Sábado', 'Pauta_wsp', '2025-09-01', '2026-04-15'),
|
||||
('¡Hola! 🌡️', 'TEAC', '225', 'Lima', 'Domingo', 'Pauta_wsp', '2025-09-01', '2026-12-31'),
|
||||
('¡Hola! ☃️', 'TERC', '226', 'Lima', 'Sábado', 'Pauta_wsp', '2026-01-01', '2026-04-15'),
|
||||
('¡Hola! 📚', 'TERC', '227', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-10'),
|
||||
('¡Hola! 🗺️', 'TEAC', '228', 'Arequipa', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-05'),
|
||||
('¡Hola! 🌤️', 'TEAC', '229', 'Piura', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! ⚡', 'TEAC', '230', 'Trujillo', 'Semipresencial', 'Pauta_wsp', '2026-02-01', '2026-05-07'),
|
||||
('¡Hola! 🎤', 'TERC', '231', 'Lima', 'Domingo', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! 👾 Me interesa el programa', 'TEAC', '232', 'Lima', 'Domingo', 'Pauta_wsp', '2026-02-26', '2026-05-30'),
|
||||
('¡Hola! 🍨', 'TEAC', '233', 'Lima', 'Sábado', 'Pauta_wsp', '2026-02-01', '2026-05-30'),
|
||||
('¡Hola! 🐶 Me interesa', 'TEAC', '234', 'Piura', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 💸 Me interesa', 'TERC', '235', 'Arequipa', 'Semipresencial', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🗿 Me interesa', 'TERC', '236', 'Trujillo', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🦺 Me interesa', 'TEAC', '237', 'Lima', 'Sábado', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🍾 Me interesa', 'TEAC', '238', 'Lima', 'Domingo', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('💡 deseo más info del programa', 'TERC', '239', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-03-01', '2026-05-30'),
|
||||
('¡Hola! 🎯 Me interesa el programa', 'TERC', '240', 'Lima', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('¡Hola! 🤝 Me interesa el programa', 'TERC', '241', 'Lima', 'Sábado', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('🪐 Me interesa el programa', 'TERC', '242', 'Piura', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-05-30'),
|
||||
('🎓 Me interesa el programa', 'TEAC', '243', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-06-30'),
|
||||
('💼 Me interesa el programa ', 'TEAC', '244', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-04-01', '2026-06-30'),
|
||||
('☃️ Me interesa el programa', 'TEAC', '245', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🔋 Me interesa el programa', 'TERC', '246', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('😎 Me interesa el programa', 'TEAC', '247', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('🌈Me interesa el programa', 'TEAC', '248', 'Lima', 'Sabado', 'Pauta_wsp', '2026-04-16', '2026-07-30'),
|
||||
('⭐ Me interesa el programa', 'TEAC', '249', 'Lima', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🕵️ Me interesa el programa', 'TEAC', '250', 'Piura', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('📈 Me interesa el programa', 'TEAC', '251', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🗺️ Me interesa el programa', 'TEAC', '252', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-06', '2026-07-30'),
|
||||
('🎮 Me interesa el programa', 'TEAC', '253', 'Trujillo', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-07-30'),
|
||||
('🏞️ Me interesa el programa', 'TERC', '254', 'Arequipa', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('⚙️ Me interesa el programa', 'TERC', '255', 'Piura', 'Domingo', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('⚡ Me interesa el programa', 'TERC', '256', 'Trujillo', 'Domingo', 'Pauta_wsp', '2026-05-08', '2026-12-31'),
|
||||
('🎟️ Me interesa el programa', 'TERC', '257', 'Trujillo', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('🕑 Me interesa el', 'TERC', '258', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-01', '2026-12-31'),
|
||||
('📚 Me interesa el programa', 'TEAC', '259', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🤗 Me interesa el programa', 'TEAC', '260', 'Lima', 'Semipresencial', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🕹️ Me interesa el programa', 'TERC', '261', 'Lima', 'Domingo', 'Pauta_wsp', '2026-05-11', '2026-12-31'),
|
||||
('🐶 Me interesa el programa', 'TEAC', '262', 'Piura', 'Sabado', 'Pauta_wsp', '2026-05-11', '2026-08-30'),
|
||||
('🍨 Me interesa el programa', 'TERC', '263', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('⛱️ Me interesa el programa de Aire Acondicionado', 'TEAC', '264', 'Lima', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('🌤️ Me interesa el programa', 'TEAC', '265', 'Arequipa', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('⛱️ Me interesa el programa de Refrigeración comercial', 'TERC', '266', 'Lima', 'Sabado', 'Pauta_wsp', '2026-05-15', '2026-08-30'),
|
||||
('¡Hola! Vengo de su web, quiero saber', 'TEAC', '0', 'Lima', '-', 'Web_Whatsapp', '2025-11-01', '2026-12-31'),
|
||||
]
|
||||
|
||||
|
||||
def _values_sql():
|
||||
"""Construye el bloque VALUES (...) del mapa de campañas para el JOIN."""
|
||||
filas = []
|
||||
for frase, cargo, codigo, sede, dia, origen, fi, ff in CAMPANIAS:
|
||||
f = frase.replace("'", "''")
|
||||
filas.append(f"('{f}','{cargo}','{codigo}','{sede}','{dia}','{origen}','{fi}','{ff}')")
|
||||
return ",\n".join(filas)
|
||||
|
||||
|
||||
class DataManager:
|
||||
def __init__(self):
|
||||
self.pg_host = os.getenv("PG_HOST", "191.98.134.81")
|
||||
self.pg_db = os.getenv("PG_DATABASE", "chatwoot_production")
|
||||
self.pg_user = os.getenv("PG_USER", "postgres")
|
||||
self.pg_pass = os.getenv("PG_PASSWORD", "")
|
||||
self.pg_port = os.getenv("PG_PORT", "5432")
|
||||
self.sql_server = os.getenv("SQL_SERVER", "191.98.134.80")
|
||||
self.sql_db = os.getenv("SQL_DATABASE", "BDUS_CK000040_0001")
|
||||
self.sql_user = os.getenv("SQL_USERNAME", "")
|
||||
self.sql_pass = os.getenv("SQL_PASSWORD", "")
|
||||
|
||||
def pg_conn(self):
|
||||
import psycopg2
|
||||
return psycopg2.connect(
|
||||
host=self.pg_host, dbname=self.pg_db, user=self.pg_user,
|
||||
password=self.pg_pass, port=self.pg_port,
|
||||
)
|
||||
|
||||
def sql_conn(self):
|
||||
import pyodbc
|
||||
conn_str = (
|
||||
f"DRIVER={{SQL Server}};SERVER={self.sql_server};"
|
||||
f"DATABASE={self.sql_db};UID={self.sql_user};PWD={self.sql_pass}"
|
||||
)
|
||||
return pyodbc.connect(conn_str)
|
||||
|
||||
# ── CHATWOOT: leads de pauta (mapa de campañas, dedup por mensaje) ──
|
||||
def traer_leads_chatwoot(self):
|
||||
sql = f"""
|
||||
SELECT DISTINCT ON (m.id)
|
||||
-- Normalización IGUAL que el PBI: quitar '+51' y '+', quedando el número
|
||||
REPLACE(REPLACE(c.phone_number, '+51', ''), '+', '') AS telefono,
|
||||
u.name AS asesor,
|
||||
m.created_at AS fecha_creada,
|
||||
cv.cached_label_list AS etiquetas,
|
||||
map.cargo AS programa, map.sede AS sede,
|
||||
map.codigo AS codigo, map.origen AS origen
|
||||
FROM messages m
|
||||
JOIN conversations cv ON m.conversation_id = cv.id
|
||||
JOIN contacts c ON cv.contact_id = c.id
|
||||
LEFT JOIN users u ON cv.assignee_id = u.id
|
||||
JOIN (VALUES
|
||||
{_values_sql()}
|
||||
) AS map(frase_busqueda, cargo, codigo, sede, dia, origen, fecha_inicio, fecha_fin)
|
||||
ON m.content LIKE '%' || map.frase_busqueda || '%'
|
||||
AND m.created_at >= CAST(map.fecha_inicio AS TIMESTAMP)
|
||||
AND m.created_at <= CAST(map.fecha_fin AS TIMESTAMP) + INTERVAL '1 day'
|
||||
WHERE m.sender_type = 'Contact'
|
||||
ORDER BY m.id ASC
|
||||
"""
|
||||
conn = self.pg_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ── SQL SERVER: cursos ──
|
||||
def traer_cursos(self):
|
||||
sql = """
|
||||
SELECT rp.num_indice, rp.dsc_det_programa, p.dsc_programa,
|
||||
rp.cod_frecuencia, rp.fch_inicio, rp.cod_estado,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado NOT IN ('ANU')) AS Inscritos_Totales,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado = 'RET') AS Inscritos_Retirados,
|
||||
(SELECT COUNT(*) FROM sgeca_matricula m
|
||||
WHERE m.cod_periodo = rp.cod_detalle AND m.num_indice = rp.num_indice
|
||||
AND m.cod_estado NOT IN ('ANU','RET','SUS')) AS Inscritos_Activos
|
||||
FROM sgede_RP_programa rp
|
||||
INNER JOIN sgeca_programa p ON rp.cod_programa = p.cod_programa
|
||||
WHERE YEAR(rp.fch_inicio) IN (2025, 2026)
|
||||
ORDER BY rp.fch_inicio ASC
|
||||
"""
|
||||
conn = self.sql_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ── SUPABASE: mapa num_indice → pauta (tabla basebi_programacion) ──
|
||||
def traer_pauta_cursos(self):
|
||||
"""Devuelve dict {str(num_indice): {pauta, estado, contar}} desde Supabase.
|
||||
Fuente: tabla BaseBI_Programacion de SharePoint, subida a Supabase."""
|
||||
url = os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
tabla = os.getenv("SUPABASE_TABLA_PAUTA", "basebi_programacion")
|
||||
if not url or not key:
|
||||
return {}
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{url}/rest/v1/{tabla}",
|
||||
params={"select": "num_indice,pauta_codigo,estado,contar"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
mapa = {}
|
||||
for row in r.json():
|
||||
ni = row.get("num_indice")
|
||||
if ni is None:
|
||||
continue
|
||||
pa = row.get("pauta_codigo")
|
||||
mapa[str(ni)] = {
|
||||
"pauta": (str(pa).strip() if pa not in (None, "") else None),
|
||||
"estado": (str(row.get("estado") or "").strip().upper()),
|
||||
"contar": (str(row.get("contar") or "").strip().upper()),
|
||||
}
|
||||
return mapa
|
||||
except Exception as e:
|
||||
print(f"[traer_pauta_cursos] {e}")
|
||||
return {}
|
||||
|
||||
# ── SUPABASE: valores de programa/sede no identificados (para la campanita) ──
|
||||
def traer_no_identificados(self):
|
||||
"""Compara cartera_junta vs alias_normalizacion y devuelve los valores de
|
||||
programa/sede que NO están en el diccionario (correcto).
|
||||
Retorna {'programa': [{'valor','veces'}], 'sede': [...]}."""
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t_cart = os.getenv("SUPABASE_TABLA_CARTERA", "cartera_junta")
|
||||
t_alias = os.getenv("SUPABASE_TABLA_ALIAS", "alias_normalizacion")
|
||||
vacio = {"programa": [], "sede": []}
|
||||
if not url or not key:
|
||||
return vacio
|
||||
headers = {"apikey": key, "Authorization": f"Bearer {key}"}
|
||||
try:
|
||||
# 1) valores conocidos (correcto) por tipo
|
||||
r = requests.get(f"{url}/rest/v1/{t_alias}",
|
||||
params={"select": "tipo,correcto"}, headers=headers, timeout=30)
|
||||
r.raise_for_status()
|
||||
conocidos = {"PROGRAMA": set(), "SEDE": set()}
|
||||
for row in r.json():
|
||||
tipo = str(row.get("tipo") or "").upper()
|
||||
corr = " ".join(str(row.get("correcto") or "").upper().split())
|
||||
if tipo in conocidos:
|
||||
conocidos[tipo].add(corr)
|
||||
|
||||
# 2) traer de cartera_junta los valores que NO estén en los conocidos
|
||||
def _desconocidos(columna, tipo):
|
||||
conj = conocidos.get(tipo, set())
|
||||
if not conj:
|
||||
return []
|
||||
lista = ",".join('"' + v.replace('"', '') + '"' for v in conj)
|
||||
rr = requests.get(
|
||||
f"{url}/rest/v1/{t_cart}",
|
||||
params={"select": columna, columna: f"not.in.({lista})", "limit": "5000"},
|
||||
headers=headers, timeout=30)
|
||||
rr.raise_for_status()
|
||||
cont = {}
|
||||
for row in rr.json():
|
||||
v = " ".join(str(row.get(columna) or "").upper().split())
|
||||
cont[v] = cont.get(v, 0) + 1
|
||||
return [{"valor": k, "veces": n}
|
||||
for k, n in sorted(cont.items(), key=lambda x: -x[1])]
|
||||
|
||||
return {"programa": _desconocidos("programa", "PROGRAMA"),
|
||||
"sede": _desconocidos("sede", "SEDE")}
|
||||
except Exception as e:
|
||||
print(f"[traer_no_identificados] {e}")
|
||||
return vacio
|
||||
|
||||
# ── SUPABASE: diccionario alias (para normalizar campanias como la cartera) ──
|
||||
def traer_alias_map(self):
|
||||
"""{'PROGRAMA': {alias:correcto}, 'SEDE': {alias:correcto}}."""
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_ALIAS", "alias_normalizacion")
|
||||
out = {"PROGRAMA": {}, "SEDE": {}}
|
||||
if not url or not key:
|
||||
return out
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{t}", params={"select": "tipo,alias,correcto"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
for row in r.json():
|
||||
tipo = str(row.get("tipo") or "").upper()
|
||||
al = " ".join(str(row.get("alias") or "").upper().split())
|
||||
co = str(row.get("correcto") or "")
|
||||
if tipo in out:
|
||||
out[tipo][al] = co
|
||||
except Exception as e:
|
||||
print(f"[traer_alias_map] {e}")
|
||||
return out
|
||||
|
||||
# ── SUPABASE: mapa codigo → (sede, programa) desde campanias (normalizado) ──
|
||||
def traer_campanias_map(self):
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CAMPANIAS", "campanias")
|
||||
out = {}
|
||||
if not url or not key:
|
||||
return out
|
||||
alias = self.traer_alias_map()
|
||||
|
||||
def _norm(v, tipo):
|
||||
s = " ".join(str(v or "").upper().split())
|
||||
return alias.get(tipo, {}).get(s, s)
|
||||
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{t}", params={"select": "codigo,sede,cargo"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
for row in r.json():
|
||||
cod = " ".join(str(row.get("codigo") or "").upper().split())
|
||||
if not cod:
|
||||
continue
|
||||
out[cod] = (_norm(row.get("sede"), "SEDE"), _norm(row.get("cargo"), "PROGRAMA"))
|
||||
except Exception as e:
|
||||
print(f"[traer_campanias_map] {e}")
|
||||
return out
|
||||
|
||||
# ── SUPABASE: filas de cartera_junta para contar (telefono, sede, programa, fecha) ──
|
||||
def traer_cartera_rows(self):
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CARTERA", "cartera_junta")
|
||||
out = []
|
||||
if not url or not key:
|
||||
return out
|
||||
headers = {"apikey": key, "Authorization": f"Bearer {key}"}
|
||||
paso, desde = 1000, 0
|
||||
try:
|
||||
while True:
|
||||
r = requests.get(
|
||||
f"{url}/rest/v1/{t}",
|
||||
params={"select": "telefono,sede,programa,fecha_creada,asesor,es_origen,canal",
|
||||
"offset": str(desde), "limit": str(paso)},
|
||||
headers=headers, timeout=60)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
if not data:
|
||||
break
|
||||
out.extend(data)
|
||||
if len(data) < paso:
|
||||
break
|
||||
desde += paso
|
||||
except Exception as e:
|
||||
print(f"[traer_cartera_rows] {e}")
|
||||
return out
|
||||
|
||||
# ── SUPABASE: mapa pauta → [conjuntos de anuncios] (tabla conjunto_pauta) ──
|
||||
def traer_conjunto_pauta(self):
|
||||
"""Devuelve dict {pauta(str): [conjunto, ...]} desde la tabla conjunto_pauta.
|
||||
Una pauta puede tener varios conjuntos de anuncios."""
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CONJUNTO", "conjunto_pauta")
|
||||
out = {}
|
||||
if not url or not key:
|
||||
return out
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{t}",
|
||||
params={"select": "conjunto,pauta"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"},
|
||||
timeout=30)
|
||||
r.raise_for_status()
|
||||
for row in r.json():
|
||||
pa = str(row.get("pauta") or "").strip()
|
||||
co = " ".join(str(row.get("conjunto") or "").split())
|
||||
if not pa or not co:
|
||||
continue
|
||||
out.setdefault(pa, []).append(co)
|
||||
except Exception as e:
|
||||
print(f"[traer_conjunto_pauta] {e}")
|
||||
return out
|
||||
|
||||
# ── GOOGLE SHEET (CSV publicado): importe gastado por conjunto de anuncios ──
|
||||
def traer_meta_importe(self):
|
||||
"""Lee el CSV publicado de Meta_Ads_Adsets y devuelve una lista de dicts:
|
||||
[{conjunto, importe, inicio}, ...] (una por fila del CSV, inicio = 'Inicio del informe').
|
||||
Se conserva la fecha para poder filtrar por periodo (Importe Pauta en el Mes)."""
|
||||
import csv, io
|
||||
url = os.getenv("META_CSV_URL", "")
|
||||
out = []
|
||||
if not url:
|
||||
return out
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
r.encoding = "utf-8"
|
||||
rows = list(csv.reader(io.StringIO(r.text)))
|
||||
if not rows:
|
||||
return out
|
||||
enc = [" ".join(str(h or "").split()).lower() for h in rows[0]]
|
||||
|
||||
def _idx(*claves):
|
||||
for k in claves:
|
||||
for i, h in enumerate(enc):
|
||||
if k in h:
|
||||
return i
|
||||
return -1
|
||||
|
||||
# OJO: buscar "nombre del conjunto..." primero (hay tambien "ID del conjunto...").
|
||||
i_conj = _idx("nombre del conjunto de anuncios", "nombre del conjunto")
|
||||
i_imp = _idx("importe gastado")
|
||||
i_ini = _idx("inicio del informe")
|
||||
i_res = _idx("resultados")
|
||||
if i_conj < 0 or i_imp < 0:
|
||||
print(f"[traer_meta_importe] columnas no encontradas: {enc}")
|
||||
return out
|
||||
for fila in rows[1:]:
|
||||
if len(fila) <= max(i_conj, i_imp):
|
||||
continue
|
||||
co = " ".join(str(fila[i_conj] or "").split())
|
||||
if not co:
|
||||
continue
|
||||
raw = str(fila[i_imp] or "").strip().replace(",", "")
|
||||
try:
|
||||
val = float(raw) if raw else 0.0
|
||||
except ValueError:
|
||||
val = 0.0
|
||||
rraw = str(fila[i_res] or "").strip().replace(",", "") if i_res >= 0 and len(fila) > i_res else ""
|
||||
try:
|
||||
res = float(rraw) if rraw else 0.0
|
||||
except ValueError:
|
||||
res = 0.0
|
||||
ini = str(fila[i_ini] or "").strip() if i_ini >= 0 and len(fila) > i_ini else ""
|
||||
out.append({"conjunto": co, "importe": val, "resultados": res, "inicio": ini})
|
||||
except Exception as e:
|
||||
print(f"[traer_meta_importe] {e}")
|
||||
return out
|
||||
|
||||
# ── CHATWOOT: leads asignados (mensaje "Asignado a..."/auto-asignado, ultimo por telefono) ──
|
||||
def traer_leads_asignados(self):
|
||||
"""Devuelve [{telefono, fecha_asignada(date, -5h), user_name}] tomando el
|
||||
mensaje de asignacion mas reciente por telefono."""
|
||||
sql = """
|
||||
SELECT * FROM (
|
||||
SELECT DISTINCT ON (c.phone_number)
|
||||
REPLACE(REPLACE(c.phone_number, '+51', ''), '+', '') AS telefono,
|
||||
m.id AS message_id,
|
||||
(m.created_at - INTERVAL '5 hours') AS created_at,
|
||||
COALESCE(u.name, 'Sin Asesor') AS user_name
|
||||
FROM messages m
|
||||
JOIN conversations cv ON m.conversation_id = cv.id
|
||||
JOIN contacts c ON cv.contact_id = c.id
|
||||
LEFT JOIN users u ON cv.assignee_id = u.id
|
||||
WHERE (
|
||||
m.content LIKE 'Asignado a %' OR
|
||||
m.content LIKE '% auto-asignado%'
|
||||
)
|
||||
ORDER BY c.phone_number, m.id DESC
|
||||
) AS t
|
||||
ORDER BY message_id DESC
|
||||
"""
|
||||
conn = self.pg_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ── SUPABASE: actualizar/insertar la pauta de un conjunto en conjunto_pauta ──
|
||||
def upsert_conjunto_pauta(self, conjunto, pauta):
|
||||
"""Si el conjunto ya existe en conjunto_pauta, actualiza su pauta; si no, lo crea.
|
||||
Si pauta viene vacia, elimina el vinculo (deja el conjunto sin pauta)."""
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CONJUNTO", "conjunto_pauta")
|
||||
h = {"apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
||||
co = str(conjunto).strip(); pa = str(pauta or "").strip()
|
||||
# ¿existe el conjunto?
|
||||
r = requests.get(f"{url}/rest/v1/{t}",
|
||||
params={"select": "conjunto", "conjunto": f"eq.{co}"},
|
||||
headers=h, timeout=30)
|
||||
r.raise_for_status()
|
||||
existe = len(r.json()) > 0
|
||||
if not pa:
|
||||
# sin pauta -> borrar vinculo si existia
|
||||
if existe:
|
||||
requests.delete(f"{url}/rest/v1/{t}", params={"conjunto": f"eq.{co}"},
|
||||
headers=h, timeout=30).raise_for_status()
|
||||
return {"conjunto": co, "pauta": None}
|
||||
if existe:
|
||||
requests.patch(f"{url}/rest/v1/{t}", params={"conjunto": f"eq.{co}"},
|
||||
headers=h, json={"pauta": pa}, timeout=30).raise_for_status()
|
||||
else:
|
||||
requests.post(f"{url}/rest/v1/{t}", headers=h,
|
||||
json={"conjunto": co, "pauta": pa}, timeout=30).raise_for_status()
|
||||
return {"conjunto": co, "pauta": pa}
|
||||
|
||||
# ── SUPABASE: conjuntos de anuncios SIN pauta conectada (del Sheet, no en conjunto_pauta) ──
|
||||
def traer_conjuntos_sin_pauta(self):
|
||||
"""Lista de conjuntos del Google Sheet que NO estan en conjunto_pauta."""
|
||||
conj_pauta = self.traer_conjunto_pauta() # {pauta: [conjuntos]}
|
||||
conectados = set()
|
||||
for cjs in conj_pauta.values():
|
||||
for c in cjs:
|
||||
conectados.add(" ".join(str(c).split()).upper())
|
||||
vistos = {}
|
||||
for f in self.traer_meta_importe():
|
||||
nombre = " ".join(str(f.get("conjunto")).split())
|
||||
if not nombre:
|
||||
continue
|
||||
if " ".join(nombre.split()).upper() not in conectados:
|
||||
vistos[nombre] = True
|
||||
return sorted(vistos.keys())
|
||||
|
||||
# ── SUPABASE: programa_pautas -> {num_indice: [pautas]} (muchos-a-muchos) ──
|
||||
def traer_programa_pautas(self):
|
||||
url = os.getenv("SUPABASE_PAUTA_URL", ""); key = os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_PROGRAMA_PAUTAS", "programa_pautas")
|
||||
out = {}
|
||||
if not url or not key:
|
||||
return out
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{t}", params={"select": "num_indice,pauta"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
for row in r.json():
|
||||
ni = str(row.get("num_indice") or "").strip()
|
||||
pa = str(row.get("pauta") or "").strip()
|
||||
if ni and pa:
|
||||
out.setdefault(ni, []).append(pa)
|
||||
except Exception as e:
|
||||
print(f"[traer_programa_pautas] {e}")
|
||||
return out
|
||||
|
||||
# ── SUPABASE: agregar un vinculo num_indice<->pauta en programa_pautas (upsert) ──
|
||||
def agregar_programa_pauta(self, num_indice, pauta):
|
||||
url = os.getenv("SUPABASE_PAUTA_URL", ""); key = os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_PROGRAMA_PAUTAS", "programa_pautas")
|
||||
h = {"apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
||||
ni = str(num_indice).strip(); pa = str(pauta).strip()
|
||||
# ¿ya existe ese par?
|
||||
r = requests.get(f"{url}/rest/v1/{t}",
|
||||
params={"select": "id", "num_indice": f"eq.{ni}", "pauta": f"eq.{pa}"},
|
||||
headers=h, timeout=30)
|
||||
r.raise_for_status()
|
||||
if len(r.json()) > 0:
|
||||
return {"num_indice": ni, "pauta": pa, "ya_existia": True}
|
||||
rr = requests.post(f"{url}/rest/v1/{t}", headers=h,
|
||||
json={"num_indice": ni, "pauta": pa}, timeout=30)
|
||||
rr.raise_for_status()
|
||||
return {"num_indice": ni, "pauta": pa, "ya_existia": False}
|
||||
|
||||
# ── SUPABASE: num_indices que YA usan una pauta en basebi_programacion ──
|
||||
def num_indices_de_pauta(self, pauta):
|
||||
url = os.getenv("SUPABASE_PAUTA_URL", ""); key = os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
tabla = os.getenv("SUPABASE_TABLA_PAUTA", "basebi_programacion")
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{tabla}",
|
||||
params={"select": "num_indice", "pauta_codigo": f"eq.{str(pauta).strip()}"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
return [str(x.get("num_indice")).strip() for x in r.json() if x.get("num_indice") is not None]
|
||||
except Exception as e:
|
||||
print(f"[num_indices_de_pauta] {e}")
|
||||
return []
|
||||
|
||||
# ── SUPABASE: guardar pauta y/o contar de un num_indice en basebi_programacion (upsert) ──
|
||||
def guardar_pauta_basebi(self, num_indice, pauta, contar=None):
|
||||
url = os.getenv("SUPABASE_PAUTA_URL", ""); key = os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
tabla = os.getenv("SUPABASE_TABLA_PAUTA", "basebi_programacion")
|
||||
h = {"apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
||||
ni = str(num_indice).strip(); pa = str(pauta or "").strip()
|
||||
campos = {}
|
||||
if pa:
|
||||
campos["pauta_codigo"] = pa # solo actualizar pauta si viene con valor
|
||||
if contar is not None:
|
||||
campos["contar"] = str(contar).strip().upper() # "SI" / "NO"
|
||||
if not campos:
|
||||
return {"num_indice": ni, "sin_cambios": True}
|
||||
r = requests.get(f"{url}/rest/v1/{tabla}",
|
||||
params={"select": "num_indice", "num_indice": f"eq.{ni}"},
|
||||
headers=h, timeout=30)
|
||||
r.raise_for_status()
|
||||
existe = len(r.json()) > 0
|
||||
if existe:
|
||||
rr = requests.patch(f"{url}/rest/v1/{tabla}",
|
||||
params={"num_indice": f"eq.{ni}"},
|
||||
headers=h, json=campos, timeout=30)
|
||||
else:
|
||||
rr = requests.post(f"{url}/rest/v1/{tabla}",
|
||||
headers=h, json={"num_indice": ni, **campos}, timeout=30)
|
||||
rr.raise_for_status()
|
||||
return {"num_indice": ni, "pauta": pa, "contar": campos.get("contar"), "creado": not existe}
|
||||
|
||||
# ── SUPABASE: vincular un conjunto de anuncios a una pauta (insert en conjunto_pauta) ──
|
||||
def guardar_conjunto_pauta(self, conjunto, pauta):
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CONJUNTO", "conjunto_pauta")
|
||||
h = {"apikey": key, "Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
||||
rr = requests.post(f"{url}/rest/v1/{t}", headers=h,
|
||||
json={"conjunto": str(conjunto).strip(), "pauta": str(pauta).strip()},
|
||||
timeout=30)
|
||||
rr.raise_for_status()
|
||||
return {"conjunto": conjunto, "pauta": pauta}
|
||||
|
||||
# ── CHATWOOT: plantillas enviadas (para matriz de plantillas cobradas) ──
|
||||
def traer_plantillas(self):
|
||||
"""Devuelve [{plantilla, telefono, user_name, created_at_peru,
|
||||
hora_anterior_contacto, siguiente_mensaje_1}] de mensajes de plantilla
|
||||
con content_attributes vacio (ISBLANK)."""
|
||||
sql = """
|
||||
SELECT
|
||||
m.additional_attributes -> 'template_params' ->> 'name' AS plantilla,
|
||||
REPLACE(REPLACE(c.phone_number, '+51', ''), '+', '') AS telefono,
|
||||
u.name AS user_name,
|
||||
(m.created_at - INTERVAL '5 hours') AS created_at_peru,
|
||||
(SELECT (mp.created_at - INTERVAL '5 hours') FROM messages mp
|
||||
WHERE mp.conversation_id = m.conversation_id AND mp.id < m.id
|
||||
AND mp.sender_type = 'Contact' ORDER BY mp.id DESC LIMIT 1) AS hora_anterior_contacto,
|
||||
(SELECT m2.content FROM messages m2
|
||||
WHERE m2.conversation_id = m.conversation_id AND m2.id > m.id
|
||||
AND m2.sender_type = 'Contact' ORDER BY m2.id ASC LIMIT 1) AS siguiente_mensaje_1
|
||||
FROM messages m
|
||||
JOIN conversations cv ON m.conversation_id = cv.id
|
||||
JOIN contacts c ON cv.contact_id = c.id
|
||||
LEFT JOIN users u ON cv.assignee_id = u.id
|
||||
WHERE m.sender_type = 'User'
|
||||
AND m.additional_attributes -> 'template_params' ->> 'name' IS NOT NULL
|
||||
AND (m.content_attributes IS NULL
|
||||
OR m.content_attributes::text = '{}'
|
||||
OR m.content_attributes::text = 'null')
|
||||
"""
|
||||
conn = self.pg_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
filas = [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
conn.close()
|
||||
return filas
|
||||
|
||||
# ── SUPABASE: campanias -> {codigo(pauta): {sede, cargo}} (crudo, sin normalizar) ──
|
||||
def traer_campanias_sede_cargo(self):
|
||||
url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
t = os.getenv("SUPABASE_TABLA_CAMPANIAS", "campanias")
|
||||
out = {}
|
||||
if not url or not key:
|
||||
return out
|
||||
try:
|
||||
r = requests.get(f"{url}/rest/v1/{t}", params={"select": "codigo,sede,cargo"},
|
||||
headers={"apikey": key, "Authorization": f"Bearer {key}"}, timeout=30)
|
||||
r.raise_for_status()
|
||||
for row in r.json():
|
||||
cod = str(row.get("codigo") or "").strip()
|
||||
if cod:
|
||||
out[cod] = {"sede": str(row.get("sede") or "").strip(),
|
||||
"cargo": str(row.get("cargo") or "").strip()}
|
||||
except Exception as e:
|
||||
print(f"[traer_campanias_sede_cargo] {e}")
|
||||
return out
|
||||
|
||||
# ── SQL SERVER: matrículas ──
|
||||
def traer_matriculas(self):
|
||||
sql = """
|
||||
SELECT
|
||||
sgeca_matricula.num_matricula, sgeca_matricula.num_indice,
|
||||
sgeca_matricula.fch_matricula,
|
||||
sgeca_matricula.cod_estado AS estado_matricula,
|
||||
REPLACE(REPLACE(REPLACE(sgema_alumno.dsc_telefono_1,' ',''),'+51',''),'+','') AS dsc_telefono_1,
|
||||
REPLACE(REPLACE(REPLACE(sgema_alumno.dsc_telefono_2,' ',''),'+51',''),'+','') AS dsc_telefono_2,
|
||||
sgeca_matricula.cod_moneda,
|
||||
ISNULL((SELECT SUM(c.imp_total - ISNULL(c.imp_dscto,0))
|
||||
FROM sgede_cronograma_matricula c
|
||||
WHERE c.cod_localidad = sgeca_matricula.cod_localidad
|
||||
AND c.num_matricula = sgeca_matricula.num_matricula
|
||||
AND c.num_refinanciamiento = 1), 0) AS INV_NETA,
|
||||
(SELECT rhuma_trabajador.dsc_apellido_paterno + ' ' +
|
||||
SUBSTRING(rhuma_trabajador.dsc_apellido_materno, 1, 1) + '. ' +
|
||||
rhuma_trabajador.dsc_nombres
|
||||
FROM rhuma_trabajador
|
||||
WHERE rhuma_trabajador.cod_trabajador = sgeca_matricula.cod_vendedor) AS dsc_vendedor,
|
||||
sgeca_programa.dsc_programa,
|
||||
sgede_RP_programa.dsc_det_programa AS dsc_promocion,
|
||||
ISNULL((SELECT sgede_cronograma_matricula.imp_saldo FROM sgede_cronograma_matricula
|
||||
WHERE sgede_cronograma_matricula.cod_localidad = sgeca_matricula.cod_localidad
|
||||
AND sgede_cronograma_matricula.num_matricula = sgeca_matricula.num_matricula
|
||||
AND sgede_cronograma_matricula.num_refinanciamiento = 1
|
||||
AND sgede_cronograma_matricula.num_cuota = 0), 0) AS imp_saldo_matricula,
|
||||
ISNULL((SELECT sgede_cronograma_matricula.imp_saldo FROM sgede_cronograma_matricula
|
||||
WHERE sgede_cronograma_matricula.cod_localidad = sgeca_matricula.cod_localidad
|
||||
AND sgede_cronograma_matricula.num_matricula = sgeca_matricula.num_matricula
|
||||
AND sgede_cronograma_matricula.num_refinanciamiento = 1
|
||||
AND sgede_cronograma_matricula.num_cuota = 1), 0) AS imp_saldo_cuota1
|
||||
FROM sgeca_matricula
|
||||
INNER JOIN sgeca_programa ON sgeca_matricula.cod_programa = sgeca_programa.cod_programa
|
||||
LEFT JOIN sgede_RP_programa ON sgeca_matricula.cod_periodo = sgede_RP_programa.cod_detalle
|
||||
AND sgeca_matricula.cod_programa = sgede_RP_programa.cod_programa
|
||||
AND sgeca_matricula.num_indice = sgede_RP_programa.num_indice
|
||||
INNER JOIN sgema_alumno ON sgeca_matricula.cod_alumno = sgema_alumno.cod_alumno
|
||||
WHERE sgeca_matricula.cod_localidad LIKE 'SCENT'
|
||||
AND sgeca_matricula.fch_matricula BETWEEN '01-11-2024 00:00:00.000' AND '31-12-2026 23:59:00.000'
|
||||
AND sgeca_matricula.cod_estado <> 'ANU'
|
||||
"""
|
||||
conn = self.sql_conn()
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
return [dict(zip(cols, r)) for r in rows]
|
||||
86
backend/diag_base.json
Normal file
86
backend/diag_base.json
Normal file
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"2026|2|TODOS|TODOS|TODOS": {
|
||||
"leads_recibidos": 6186,
|
||||
"leads_procesados": 1489,
|
||||
"total_matriculados": 117,
|
||||
"cursos_programados": 7,
|
||||
"pauta_total_imp": 4255.16,
|
||||
"always_total_imp": 1730.51,
|
||||
"webform_total_rec": 151,
|
||||
"webform_total_matr": 15,
|
||||
"asignados_total": 1390,
|
||||
"matriz_cursos_filas": 6
|
||||
},
|
||||
"2026|2|TODOS|TEAC|LIMA": {
|
||||
"leads_recibidos": 2198,
|
||||
"leads_procesados": 499,
|
||||
"total_matriculados": 53,
|
||||
"cursos_programados": 3,
|
||||
"pauta_total_imp": 4255.16,
|
||||
"always_total_imp": 810.03,
|
||||
"webform_total_rec": 94,
|
||||
"webform_total_matr": 9,
|
||||
"asignados_total": 1390,
|
||||
"matriz_cursos_filas": 2
|
||||
},
|
||||
"2026|2|TODOS|TERC|AREQUIPA": {
|
||||
"leads_recibidos": 325,
|
||||
"leads_procesados": 64,
|
||||
"total_matriculados": 10,
|
||||
"cursos_programados": 1,
|
||||
"pauta_total_imp": 4255.16,
|
||||
"always_total_imp": 0,
|
||||
"webform_total_rec": 5,
|
||||
"webform_total_matr": 0,
|
||||
"asignados_total": 1390,
|
||||
"matriz_cursos_filas": 1
|
||||
},
|
||||
"2026|1|TODOS|TODOS|TODOS": {
|
||||
"leads_recibidos": 7417,
|
||||
"leads_procesados": 2370,
|
||||
"total_matriculados": 128,
|
||||
"cursos_programados": 9,
|
||||
"pauta_total_imp": 4499.9,
|
||||
"always_total_imp": 776.0,
|
||||
"webform_total_rec": 143,
|
||||
"webform_total_matr": 15,
|
||||
"asignados_total": 1529,
|
||||
"matriz_cursos_filas": 5
|
||||
},
|
||||
"2026|1|TODOS|SEMINARIOS|LIMA": {
|
||||
"leads_recibidos": 946,
|
||||
"leads_procesados": 342,
|
||||
"total_matriculados": 22,
|
||||
"cursos_programados": 1,
|
||||
"pauta_total_imp": 4499.9,
|
||||
"always_total_imp": 0,
|
||||
"webform_total_rec": 1,
|
||||
"webform_total_matr": 0,
|
||||
"asignados_total": 1529,
|
||||
"matriz_cursos_filas": 0
|
||||
},
|
||||
"2026|7|TODOS|TODOS|TODOS": {
|
||||
"leads_recibidos": 1664,
|
||||
"leads_procesados": 1435,
|
||||
"total_matriculados": 59,
|
||||
"cursos_programados": 16,
|
||||
"pauta_total_imp": 2212.41,
|
||||
"always_total_imp": 1540.57,
|
||||
"webform_total_rec": 34,
|
||||
"webform_total_matr": 1,
|
||||
"asignados_total": 2275,
|
||||
"matriz_cursos_filas": 16
|
||||
},
|
||||
"2026|7|TODOS|TEAC|PIURA": {
|
||||
"leads_recibidos": 104,
|
||||
"leads_procesados": 102,
|
||||
"total_matriculados": 1,
|
||||
"cursos_programados": 1,
|
||||
"pauta_total_imp": 2212.41,
|
||||
"always_total_imp": 172.48,
|
||||
"webform_total_rec": 0,
|
||||
"webform_total_matr": 0,
|
||||
"asignados_total": 2275,
|
||||
"matriz_cursos_filas": 1
|
||||
}
|
||||
}
|
||||
38
backend/diag_base.py
Normal file
38
backend/diag_base.py
Normal file
@@ -0,0 +1,38 @@
|
||||
# diag_base.py — Captura los numeros ACTUALES (antes de optimizar) para comparar despues.
|
||||
import json
|
||||
import services as S
|
||||
|
||||
combos = [
|
||||
("2026","2","TODOS","TODOS","TODOS"),
|
||||
("2026","2","TODOS","TEAC","LIMA"),
|
||||
("2026","2","TODOS","TERC","AREQUIPA"),
|
||||
("2026","1","TODOS","TODOS","TODOS"),
|
||||
("2026","1","TODOS","SEMINARIOS","LIMA"),
|
||||
("2026","7","TODOS","TODOS","TODOS"),
|
||||
("2026","7","TODOS","TEAC","PIURA"),
|
||||
]
|
||||
|
||||
def resumen(d):
|
||||
k = d["kpis"]
|
||||
return {
|
||||
"leads_recibidos": k["leads_recibidos"],
|
||||
"leads_procesados": k["leads_procesados"],
|
||||
"total_matriculados": k["total_matriculados"],
|
||||
"cursos_programados": k["cursos_programados"],
|
||||
"pauta_total_imp": d["tabla_pauta"]["total"].get("importe"),
|
||||
"always_total_imp": d["matriz_always"]["total"]["importe"],
|
||||
"webform_total_rec": d["matriz_webform"]["total"]["recibidos"],
|
||||
"webform_total_matr": d["matriz_webform"]["total"]["matriculas"],
|
||||
"asignados_total": d["matriz_asignados"]["total"],
|
||||
"matriz_cursos_filas": len(d["matriz_cursos"]["filas"]),
|
||||
}
|
||||
|
||||
out = {}
|
||||
for c in combos:
|
||||
d = S.leads_dashboard(*c)
|
||||
out["|".join(c)] = resumen(d)
|
||||
print("|".join(c), "->", out["|".join(c)])
|
||||
|
||||
with open("diag_base.json", "w", encoding="utf-8") as f:
|
||||
json.dump(out, f, indent=2, ensure_ascii=False)
|
||||
print("\nGuardado: diag_base.json (linea base ANTES de optimizar)")
|
||||
28
backend/diag_canal.py
Normal file
28
backend/diag_canal.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# diag_canal.py — Revisa num_indice 1161: pauta en basebi vs conjuntos.
|
||||
import services as S
|
||||
|
||||
NI = "1161"
|
||||
pm = S._pauta_cruda() # {num_indice: {pauta, estado, contar}}
|
||||
cp = S._conjunto_pauta() # {pauta: [conjuntos]}
|
||||
|
||||
info = pm.get(NI)
|
||||
print(f"num_indice {NI} en basebi_programacion:", info)
|
||||
cod = info.get("pauta") if info else None
|
||||
print(f" -> pauta (cod): {cod!r}")
|
||||
print(f" -> conjuntos por esa pauta: {cp.get(str(cod).strip()) if cod else '(sin cod)'}")
|
||||
|
||||
# Buscar en la matriz esa fila
|
||||
d = S.leads_dashboard("2026","5","TODOS","TODOS","TODOS")["matriz_cursos"]
|
||||
for c in d["filas"]:
|
||||
if str(c["num_indice"]) == NI:
|
||||
print(f"\nEn la matriz -> pauta={c['pauta']!r} conjuntos={c.get('conjuntos')}")
|
||||
break
|
||||
else:
|
||||
print(f"\n(num_indice {NI} no esta en la matriz de mayo)")
|
||||
|
||||
# Buscar en conjunto_pauta si algun conjunto tiene ese nombre TEAC_TRUJILLO_MAY...
|
||||
print("\nBuscando conjunto 'TEAC_TRUJILLO_MAY' en conjunto_pauta:")
|
||||
for pauta, cjs in cp.items():
|
||||
for cj in cjs:
|
||||
if "TEAC_TRUJILLO_MAY" in str(cj).upper():
|
||||
print(f" pauta={pauta!r} -> {cj}")
|
||||
43
backend/diag_content.py
Normal file
43
backend/diag_content.py
Normal file
@@ -0,0 +1,43 @@
|
||||
# diag_content.py — Revisa que valores toma content_attributes (para replicar ISBLANK).
|
||||
# Ejecutar dentro de backend/: python diag_content.py
|
||||
from data_manager_v2 import DataManager
|
||||
|
||||
dm = DataManager()
|
||||
conn = dm.pg_conn()
|
||||
cur = conn.cursor()
|
||||
|
||||
# Distribucion de content_attributes en los mensajes de plantilla
|
||||
sql = """
|
||||
SELECT
|
||||
CASE
|
||||
WHEN m.content_attributes IS NULL THEN '(NULL)'
|
||||
WHEN m.content_attributes::text = '{}' THEN '(vacio {})'
|
||||
WHEN m.content_attributes::text = 'null' THEN "(texto 'null')"
|
||||
ELSE 'CON DATOS'
|
||||
END AS tipo,
|
||||
COUNT(*) AS n
|
||||
FROM messages m
|
||||
WHERE m.sender_type = 'User'
|
||||
AND m.additional_attributes -> 'template_params' ->> 'name' IS NOT NULL
|
||||
GROUP BY 1
|
||||
ORDER BY 2 DESC
|
||||
"""
|
||||
cur.execute(sql)
|
||||
print("== content_attributes en mensajes de plantilla ==")
|
||||
for tipo, n in cur.fetchall():
|
||||
print(f" {tipo:16} {n}")
|
||||
|
||||
# Muestra 3 ejemplos de cada tipo con datos
|
||||
print("\n== ejemplos de content_attributes CON DATOS (primeros 3) ==")
|
||||
cur.execute("""
|
||||
SELECT m.additional_attributes -> 'template_params' ->> 'name', m.content_attributes::text
|
||||
FROM messages m
|
||||
WHERE m.sender_type='User'
|
||||
AND m.additional_attributes -> 'template_params' ->> 'name' IS NOT NULL
|
||||
AND m.content_attributes IS NOT NULL
|
||||
AND m.content_attributes::text NOT IN ('{}','null')
|
||||
LIMIT 3
|
||||
""")
|
||||
for nombre, ca in cur.fetchall():
|
||||
print(f" {nombre}: {ca[:120]}")
|
||||
conn.close()
|
||||
12
backend/diag_importe.py
Normal file
12
backend/diag_importe.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# diag_importe.py — Verifica matriz_asignados (pivot asesor x dia).
|
||||
import services as S
|
||||
|
||||
d = S.matriz_asignados("2026", "7", "TODOS")
|
||||
print("MES 7 2026 TOTAL asignados:", d["total"])
|
||||
print("dias (columnas):", d["dias"][:5], "...", d["dias"][-3:])
|
||||
print("\nPor asesor (total):")
|
||||
for f in d["filas"]:
|
||||
dias_con = {k:v for k,v in f["por_dia"].items() if v}
|
||||
print(f" {f['asesor']:22} total={f['total']:4} dias con datos: {len(dias_con)}")
|
||||
print("\ntotal_por_dia (primeros 10):", {k:v for k,v in list(d['total_por_dia'].items())[:10]})
|
||||
print("OK.")
|
||||
22
backend/diag_multi.py
Normal file
22
backend/diag_multi.py
Normal file
@@ -0,0 +1,22 @@
|
||||
# diag_multi.py — Revisa programa_pautas y la suma por num_indice.
|
||||
import services as S
|
||||
from cache_manager import cache_invalidate
|
||||
|
||||
# forzar leer fresco de supabase
|
||||
cache_invalidate("programa_pautas")
|
||||
cache_invalidate("pautas_de_indice")
|
||||
|
||||
pp = S._programa_pautas() # {num_indice: [pautas]} SOLO de la tabla nueva
|
||||
print("== Tabla programa_pautas (lo que se guardo) ==")
|
||||
if not pp:
|
||||
print(" (VACIA - no se guardo nada, o no se lee)")
|
||||
for ni, ps in pp.items():
|
||||
print(f" num_indice {ni} -> {ps}")
|
||||
|
||||
ppi = S._pautas_de_indice() # combinado basebi + nueva
|
||||
print("\n== num_indices con VARIAS pautas (basebi + nueva) ==")
|
||||
multi = {ni: ps for ni, ps in ppi.items() if len(ps) > 1}
|
||||
for ni, ps in list(multi.items())[:15]:
|
||||
print(f" num_indice {ni} -> {ps}")
|
||||
if not multi:
|
||||
print(" (ninguno con varias)")
|
||||
12
backend/diag_plantillas.py
Normal file
12
backend/diag_plantillas.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# diag_plantillas.py — Verifica otros_general (endpoint liviano).
|
||||
import time, services as S
|
||||
|
||||
for mes in ["TODOS", "1", "2"]:
|
||||
t0 = time.time()
|
||||
d = S.otros_general("2026", mes, "TODOS")
|
||||
seg = time.time() - t0
|
||||
p = d["matriz_plantillas"]["total"]
|
||||
print(f"MES {mes:6} ({seg:.1f}s) plantillas_env={p['enviadas']} matric={p['matriculas']} "
|
||||
f"always_filas={len(d['matriz_always']['filas'])} webform_filas={len(d['matriz_webform']['filas'])} "
|
||||
f"asignados_total={d['matriz_asignados']['total']}")
|
||||
print("OK. (2da vez el mismo mes debe ser instantaneo por cache)")
|
||||
58
backend/diag_webform.py
Normal file
58
backend/diag_webform.py
Normal file
@@ -0,0 +1,58 @@
|
||||
# diag_webform.py — Compara WEB_FORMULARIO enero: datos_unificados vs cartera_junta (local xlsx).
|
||||
# Usa el export local para cartera (rapido) y baja solo enero de datos_unificados.
|
||||
import os, requests
|
||||
from datetime import datetime
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
SUP_URL = os.getenv("SUPABASE_URL"); SUP_KEY = os.getenv("SUPABASE_KEY")
|
||||
|
||||
def _norm_tel(v):
|
||||
s = str(v or "")
|
||||
for x in ("+51","+"," ","-","(",")"): s=s.replace(x,"")
|
||||
s=s.strip()
|
||||
if not s or set(s)=={"0"}: return ""
|
||||
if s.isdigit() and len(s)<=6: return ""
|
||||
return s
|
||||
|
||||
def _ene(v):
|
||||
for fmt in ("%d/%m/%Y","%Y-%m-%d"):
|
||||
try:
|
||||
d=datetime.strptime(str(v)[:10],fmt).date()
|
||||
return d.year==2026 and d.month==1
|
||||
except: pass
|
||||
return False
|
||||
|
||||
# datos_unificados WEB_FORMULARIO enero
|
||||
h={"apikey":SUP_KEY,"Authorization":f"Bearer {SUP_KEY}"}
|
||||
out=[]; desde=0
|
||||
while True:
|
||||
r=requests.get(f"{SUP_URL}/rest/v1/datos_unificados",
|
||||
params={"select":"Telefono,Canal,Fechacreada","offset":str(desde),"limit":"1000"},headers=h,timeout=60)
|
||||
r.raise_for_status(); d=r.json()
|
||||
if not d: break
|
||||
out.extend(d)
|
||||
if len(d)<1000: break
|
||||
desde+=1000
|
||||
du=[_norm_tel(r["Telefono"]) for r in out if str(r.get("Canal","")).upper()=="WEB_FORMULARIO" and _ene(r.get("Fechacreada"))]
|
||||
du=set(t for t in du if t)
|
||||
print("datos_unificados WEB_FORMULARIO enero (tel unicos):", len(du))
|
||||
|
||||
# cartera desde el excel local
|
||||
import openpyxl, glob
|
||||
xf=max(glob.glob("cartera_junta_export.xlsx"), default=None)
|
||||
wb=openpyxl.load_workbook("cartera_junta_export.xlsx", read_only=True); ws=wb.active
|
||||
rows=list(ws.iter_rows(values_only=True)); hdr=rows[0]; ci={h:i for i,h in enumerate(hdr)}
|
||||
tel_all=set(str(r[ci["telefono"]]).strip() for r in rows[1:]) # todos los tel de cartera
|
||||
tel_web_ene=set()
|
||||
for r in rows[1:]:
|
||||
if str(r[ci["canal"]]).strip().upper()=="WEB_FORMULARIO" and str(r[ci["fecha_creada"]])[:7]=="2026-01":
|
||||
tel_web_ene.add(str(r[ci["telefono"]]).strip())
|
||||
print("cartera WEB_FORMULARIO enero (tel):", len(tel_web_ene))
|
||||
|
||||
falt_total=[t for t in du if t not in tel_all]
|
||||
falt_web=[t for t in du if t not in tel_web_ene]
|
||||
print(f"\nDe {len(du)} tel de datos_unificados enero:")
|
||||
print(f" NO estan en cartera por NINGUN canal: {len(falt_total)}")
|
||||
print(f" estan en cartera pero NO como WEB_FORMULARIO enero: {len(falt_web)-len(falt_total)}")
|
||||
print(" ejemplos NO en cartera:", falt_total[:10])
|
||||
150
backend/export_base_junta.py
Normal file
150
backend/export_base_junta.py
Normal file
@@ -0,0 +1,150 @@
|
||||
# backend/export_base_junta.py
|
||||
"""
|
||||
Une los leads de Postgre (Fact_Leads_Procesados, mapa de campañas) + Supabase,
|
||||
deduplica por teléfono quedándose con el MÁS ANTIGUO (desempate: Pauta_wsp_face),
|
||||
y exporta un Excel con: Telefono, Canal, Fecha Creada.
|
||||
|
||||
Uso: py -3.12 export_base_junta.py
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from dotenv import load_dotenv
|
||||
from data_manager_v2 import DataManager
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Canal preferido en caso de empate de fecha
|
||||
CANAL_PREFERIDO = "Pauta_wsp_face"
|
||||
|
||||
|
||||
def _norm_tel(v):
|
||||
s = str(v or "")
|
||||
for x in ("+51", "+", " ", "-", "(", ")"):
|
||||
s = s.replace(x, "")
|
||||
return s.strip()
|
||||
|
||||
|
||||
def _txt(v):
|
||||
"""Texto en MAYÚSCULAS; '-' o vacío → ''."""
|
||||
s = str(v or "").strip()
|
||||
if s == "-":
|
||||
s = ""
|
||||
return s.upper()
|
||||
|
||||
|
||||
def _to_dt(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
s = str(v)[:19]
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y"):
|
||||
try:
|
||||
return datetime.strptime(s[:len(fmt) + 2] if "%H" in fmt else s[:10], fmt)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def traer_postgre(dm):
|
||||
"""Mismos leads que Fact_Leads_Procesados (mapa de campañas): tel, fecha, canal(origen)."""
|
||||
filas = dm.traer_leads_chatwoot() # ya aplica el mapa de campañas y trae 'origen'
|
||||
out = []
|
||||
for f in filas:
|
||||
tel = _norm_tel(f.get("telefono"))
|
||||
if not tel:
|
||||
continue
|
||||
out.append({
|
||||
"telefono": tel,
|
||||
"fecha": _to_dt(f.get("fecha_creada")),
|
||||
"canal": _txt(f.get("origen")),
|
||||
"sede": _txt(f.get("sede")),
|
||||
"programa": _txt(f.get("programa")),
|
||||
"codigo": _txt(f.get("codigo")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def traer_supabase(dm):
|
||||
"""Lee la tabla de Supabase con columnas: telefono, fechacreada, canal."""
|
||||
try:
|
||||
from supabase import create_client
|
||||
url = os.getenv("SUPABASE_URL", "")
|
||||
key = os.getenv("SUPABASE_KEY", "")
|
||||
if not url or not key:
|
||||
print("⚠️ Falta SUPABASE_URL / SUPABASE_KEY en .env — se omite Supabase")
|
||||
return []
|
||||
sb = create_client(url, key)
|
||||
tabla = os.getenv("SUPABASE_TABLA_LEADS", "leads") # ajustar nombre real si difiere
|
||||
res = sb.table(tabla).select("Telefono,Fechacreada,Canal,Sede,Programa,Codigo").execute()
|
||||
out = []
|
||||
for r in (res.data or []):
|
||||
tel = _norm_tel(r.get("Telefono"))
|
||||
if not tel:
|
||||
continue
|
||||
out.append({
|
||||
"telefono": tel,
|
||||
"fecha": _to_dt(r.get("Fechacreada")),
|
||||
"canal": _txt(r.get("Canal")),
|
||||
"sede": _txt(r.get("Sede")),
|
||||
"programa": _txt(r.get("Programa")),
|
||||
"codigo": _txt(r.get("Codigo")),
|
||||
})
|
||||
return out
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error leyendo Supabase: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def main():
|
||||
dm = DataManager()
|
||||
print("Trayendo Postgre (Fact_Leads_Procesados)...")
|
||||
pg = traer_postgre(dm)
|
||||
print(f" Postgre: {len(pg)} filas")
|
||||
print("Trayendo Supabase...")
|
||||
sup = traer_supabase(dm)
|
||||
print(f" Supabase: {len(sup)} filas")
|
||||
|
||||
todos = pg + sup
|
||||
print(f"Total combinado (con repetidos): {len(todos)}")
|
||||
|
||||
# Dedup por teléfono: quedarse con el MÁS ANTIGUO.
|
||||
# Desempate (misma fecha): preferir CANAL_PREFERIDO.
|
||||
FUTURO = datetime(9999, 1, 1)
|
||||
mejor = {}
|
||||
for r in todos:
|
||||
tel = r["telefono"]
|
||||
f = r["fecha"] or FUTURO
|
||||
actual = mejor.get(tel)
|
||||
if actual is None:
|
||||
mejor[tel] = r
|
||||
continue
|
||||
fa = actual["fecha"] or FUTURO
|
||||
if f < fa:
|
||||
mejor[tel] = r
|
||||
elif f == fa:
|
||||
# empate de fecha → preferir el canal preferido
|
||||
if r["canal"] == CANAL_PREFERIDO and actual["canal"] != CANAL_PREFERIDO:
|
||||
mejor[tel] = r
|
||||
|
||||
final = list(mejor.values())
|
||||
print(f"Teléfonos únicos (sin repetir): {len(final)}")
|
||||
|
||||
# Exportar a Excel
|
||||
import openpyxl
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Base_Junta"
|
||||
ws.append(["Telefono", "Canal", "Fecha Creada", "Sede", "Programa", "Codigo"])
|
||||
for r in sorted(final, key=lambda x: (x["fecha"] or FUTURO)):
|
||||
fecha = r["fecha"].strftime("%d/%m/%Y") if r["fecha"] and r["fecha"] != FUTURO else ""
|
||||
ws.append([r["telefono"], r["canal"], fecha,
|
||||
r.get("sede", ""), r.get("programa", ""), r.get("codigo", "")])
|
||||
salida = os.path.join(os.path.dirname(__file__), "base_junta.xlsx")
|
||||
wb.save(salida)
|
||||
print(f"\n✅ Exportado: {salida}")
|
||||
print(f" Filas: {len(final)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
64
backend/export_cartera.py
Normal file
64
backend/export_cartera.py
Normal file
@@ -0,0 +1,64 @@
|
||||
# export_cartera.py — Exporta TODA la tabla cartera_junta de Supabase a Excel/CSV.
|
||||
# Ejecutar dentro de backend/: python export_cartera.py
|
||||
import os, csv, requests
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
URL = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
|
||||
KEY = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
|
||||
TABLA = os.getenv("SUPABASE_TABLA_CARTERA", "cartera_junta")
|
||||
HEAD = {"apikey": KEY, "Authorization": f"Bearer {KEY}"}
|
||||
|
||||
def traer_todo():
|
||||
filas, paso, desde = [], 1000, 0
|
||||
while True:
|
||||
r = requests.get(f"{URL}/rest/v1/{TABLA}",
|
||||
params={"select": "*", "offset": str(desde), "limit": str(paso)},
|
||||
headers=HEAD, timeout=120)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
if not data:
|
||||
break
|
||||
filas.extend(data)
|
||||
print(f" descargadas {len(filas)} filas...")
|
||||
if len(data) < paso:
|
||||
break
|
||||
desde += paso
|
||||
return filas
|
||||
|
||||
print(f"Descargando '{TABLA}' de Supabase...")
|
||||
filas = traer_todo()
|
||||
print(f"Total: {len(filas)} filas")
|
||||
|
||||
if not filas:
|
||||
print("Sin datos. Revisa CARTERA_URL / CARTERA_KEY en .env")
|
||||
raise SystemExit
|
||||
|
||||
# columnas = union de todas las claves, en orden de la primera fila
|
||||
cols = list(filas[0].keys())
|
||||
for f in filas:
|
||||
for k in f.keys():
|
||||
if k not in cols:
|
||||
cols.append(k)
|
||||
|
||||
# 1) CSV siempre
|
||||
csv_path = "cartera_junta_export.csv"
|
||||
with open(csv_path, "w", newline="", encoding="utf-8-sig") as fout:
|
||||
w = csv.DictWriter(fout, fieldnames=cols)
|
||||
w.writeheader()
|
||||
for f in filas:
|
||||
w.writerow({c: f.get(c, "") for c in cols})
|
||||
print(f"CSV generado: {csv_path}")
|
||||
|
||||
# 2) Excel si openpyxl esta disponible
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
wb = Workbook(); ws = wb.active; ws.title = "cartera_junta"
|
||||
ws.append(cols)
|
||||
for f in filas:
|
||||
ws.append([f.get(c, "") for c in cols])
|
||||
xlsx_path = "cartera_junta_export.xlsx"
|
||||
wb.save(xlsx_path)
|
||||
print(f"Excel generado: {xlsx_path}")
|
||||
except ImportError:
|
||||
print("(openpyxl no instalado -> solo CSV. Para Excel: pip install openpyxl)")
|
||||
894
backend/leads_logic.py
Normal file
894
backend/leads_logic.py
Normal file
@@ -0,0 +1,894 @@
|
||||
# backend/leads_logic.py
|
||||
"""
|
||||
Lógica del módulo LEADS. Traduce las medidas DAX del PBI a Python.
|
||||
Columnas calculadas replicadas:
|
||||
- Cantidad_Veces -> 1ª aparición de un teléfono = lead único
|
||||
- Ultima_Etiqueta / ESTADO/OBJECION -> limpieza de cached_label_list
|
||||
- Tipo_Programa / Sede -> clasificación por dsc_programa
|
||||
Medidas replicadas:
|
||||
- Leads_Totales_Pauta_Unico, Leads_Procesados_Pauta_Unicos,
|
||||
Leads_Procesados_Contactados_Unicos, % Procesados, % Contactados,
|
||||
Total_Matriculas, Cant_inscritos_Mes, Ocupabilidad,
|
||||
Cursos (Inicios / Suspendidos / Ya Iniciados), Matrículas por día,
|
||||
tabla Estado/Objeción.
|
||||
"""
|
||||
from datetime import datetime, date
|
||||
|
||||
# Etiquetas de sistema que se eliminan para hallar el estado/objeción real (igual que el DAX)
|
||||
ETIQUETAS_SISTEMA = {
|
||||
"atención_humana", "negociación", "supervisor", "grupo_arequipa",
|
||||
"grupo_trujillo", "sin_respuesta",
|
||||
}
|
||||
META_POR_TIPO = {
|
||||
"PROGRAMAS TEAC": 22, "PROGRAMAS TERC": 22,
|
||||
"PROVINCIA TEAC": 18, "PROVINCIA TERC": 18,
|
||||
"SEMINARIOS": 15,
|
||||
}
|
||||
|
||||
|
||||
# ── Helpers de fecha ────────────────────────────────────────────
|
||||
def _to_date(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v.date()
|
||||
if isinstance(v, date):
|
||||
return v
|
||||
s = str(v)[:10]
|
||||
for fmt in ("%Y-%m-%d", "%d-%m-%Y", "%d/%m/%Y"):
|
||||
try:
|
||||
return datetime.strptime(s, fmt).date()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _en_periodo(d, ano, mes, dia):
|
||||
"""True si la fecha cae en el filtro (ano/mes/dia; 'TODOS' = sin filtrar)."""
|
||||
if d is None:
|
||||
return False
|
||||
if ano not in ("TODOS", None) and d.year != int(ano):
|
||||
return False
|
||||
if mes not in ("TODOS", None) and d.month != int(mes):
|
||||
return False
|
||||
if dia not in ("TODOS", None) and d.day != int(dia):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# ── Clasificadores (igual que columnas calculadas DAX) ──────────
|
||||
def clasificar_tipo_programa(dsc_programa):
|
||||
up = str(dsc_programa or "").upper()
|
||||
otros = ["CERTIFICACIÓN", "CERTIFICACION", "CURSO A MEDIDA", "MASTERCLASS",
|
||||
"TALLER DE REFRIGERACIÓN DOM", "GESTIÓN DE VENTA", "GESTION DE VENTA"]
|
||||
for o in otros:
|
||||
if o.upper() in up:
|
||||
return "OTROS"
|
||||
return None # el tipo PROGRAMAS/PROVINCIA se arma con sede+programa abajo
|
||||
|
||||
|
||||
def clasificar_sede(dsc_programa):
|
||||
up = str(dsc_programa or "").upper()
|
||||
if "AREQUIPA" in up: return "AREQUIPA"
|
||||
if "TRUJILLO" in up: return "TRUJILLO"
|
||||
if "PIURA" in up: return "PIURA"
|
||||
return "LIMA"
|
||||
|
||||
|
||||
def sede_por_codigo_map():
|
||||
"""{codigo: SEDE} tomado del mapa de campañas (la sede que le corresponde a
|
||||
cada código, SIN reasignar por asesor). Usado por el filtro SEDE de leads,
|
||||
para que coincida con 'sede del código' (no con sede_act)."""
|
||||
from data_manager_v2 import CAMPANIAS
|
||||
out = {}
|
||||
for fila in CAMPANIAS:
|
||||
cod = str(fila[2]).strip() # índice 2 = codigo
|
||||
sede = str(fila[3]).strip().upper() # índice 3 = sede
|
||||
if cod:
|
||||
out[cod] = sede
|
||||
return out
|
||||
|
||||
|
||||
# ── Grupo de PROGRAMA para el filtro: TEAC / TERC / SEMINARIOS / OTROS ──
|
||||
def grupo_programa_curso(dsc_programa):
|
||||
"""Reduce el tipo detallado a 4 grupos para el filtro PROGRAMA (cursos/matrículas).
|
||||
TEAC = PROGRAMAS TEAC + PROVINCIA TEAC
|
||||
TERC = PROGRAMAS TERC + PROVINCIA TERC
|
||||
SEMINARIOS = SEMINARIOS
|
||||
OTROS = OTROS + CARRERA"""
|
||||
tp = tipo_programa_curso(dsc_programa)
|
||||
if tp in ("PROGRAMAS TEAC", "PROVINCIA TEAC"):
|
||||
return "TEAC"
|
||||
if tp in ("PROGRAMAS TERC", "PROVINCIA TERC"):
|
||||
return "TERC"
|
||||
if tp == "SEMINARIOS":
|
||||
return "SEMINARIOS"
|
||||
return "OTROS" # OTROS + CARRERA
|
||||
|
||||
|
||||
def grupo_programa_lead(cargo):
|
||||
"""Grupo de programa para un LEAD, según su 'cargo' (del mapa de campañas).
|
||||
TEAC → TEAC, TERC → TERC, resto (VRF/CO2/DIPLOMADO/etc.) → SEMINARIOS."""
|
||||
c = str(cargo or "").strip().upper()
|
||||
if c == "TEAC":
|
||||
return "TEAC"
|
||||
if c == "TERC":
|
||||
return "TERC"
|
||||
return "SEMINARIOS"
|
||||
|
||||
|
||||
def grupo_tipo_cohorte(tp):
|
||||
"""Reduce 'PROGRAMAS TEAC'/'PROVINCIA TEAC'/... a los 3 grupos de la tabla por Sede:
|
||||
TEAC = PROGRAMAS/PROVINCIA TEAC, TERC = PROGRAMAS/PROVINCIA TERC, resto = SEMINARIOS."""
|
||||
t = str(tp or "").upper()
|
||||
if "TEAC" in t:
|
||||
return "TEAC"
|
||||
if "TERC" in t:
|
||||
return "TERC"
|
||||
return "SEMINARIOS"
|
||||
|
||||
|
||||
# Réplica del DAX Sede_Act: la sede del lead se decide por el ASESOR;
|
||||
# si el asesor no está en la lista, usa la sede de la campaña.
|
||||
_SEDE_POR_ASESOR = {
|
||||
"almendra peralta": "Arequipa",
|
||||
"juan carlos aguilar": "Piura",
|
||||
"diego lázaro": "Trujillo",
|
||||
"diego lazaro": "Trujillo",
|
||||
"verónica la rosa": "Lima",
|
||||
"veronica la rosa": "Lima",
|
||||
"dayana balabarca": "Lima",
|
||||
"milagros vargas": "Lima",
|
||||
"carmen montoya": "Lima",
|
||||
"diana chávez": "Lima",
|
||||
"diana chavez": "Lima",
|
||||
"copito rivera": "Lima",
|
||||
}
|
||||
|
||||
|
||||
def sede_act(asesor, sede_campania):
|
||||
return _SEDE_POR_ASESOR.get(str(asesor or "").strip().lower(), sede_campania)
|
||||
|
||||
|
||||
def tipo_programa_cohorte(sede, programa_cat):
|
||||
"""Igual al DAX 'Tipo Programa': combina sede + (TEAC/TERC) -> categoría."""
|
||||
s = str(sede or "").upper()
|
||||
p = str(programa_cat or "").upper()
|
||||
if s == "LIMA" and p == "TEAC": return "PROGRAMAS TEAC"
|
||||
if s == "LIMA" and p == "TERC": return "PROGRAMAS TERC"
|
||||
if s in ("TRUJILLO", "PIURA", "AREQUIPA") and p == "TEAC": return "PROVINCIA TEAC"
|
||||
if s in ("TRUJILLO", "PIURA", "AREQUIPA") and p == "TERC": return "PROVINCIA TERC"
|
||||
return "SEMINARIOS"
|
||||
|
||||
|
||||
def tipo_programa_curso(dsc_programa):
|
||||
"""Réplica EXACTA del DAX Tipo_Programa (columna calculada de Fact_SQL_Base_Cursos).
|
||||
Usa CONTAINSSTRING en el mismo ORDEN que el PBI (el orden importa)."""
|
||||
p = str(dsc_programa or "")
|
||||
def has(s): # CONTAINSSTRING es sensible a may/min en DAX; comparamos tal cual
|
||||
return s in p
|
||||
|
||||
# 1) OTROS
|
||||
if (has("CERTIFICACIÓN") or has("CURSO A MEDIDA") or has("MASTERCLASS")
|
||||
or has("TALLER DE REFRIGERACIÓN DOM")
|
||||
or has("GESTIÓN DE VENTA DE EQUIPOS DE AIRE ACONDICIONADO Y EQUIPOS DE REFRIGERACIÓN")):
|
||||
return "OTROS"
|
||||
if (has("CERTIFICACION FUNDAMENTOS DE CHILLER MODULAR INVERT- LG")
|
||||
or has("PIURA - CERTIFICACIÓN MIDEA: TECNOLOGIA INVERTER")
|
||||
or has("AREQUIPA - CERTIFICACIÓN MIDEA - TECNOLOGÍA INVERTER")
|
||||
or has("CERTIFICACIÓN: OPERACIÓN Y MANTENIMIENTO DE REFRIGERADORES MIDEA")
|
||||
or has("TRUJILLO - CERTIFICACIÓN MIDEA: TECNOLOGÍA INVERTER")
|
||||
or has("CERTIFICACIÓN MIDEA: AIRE ACOND INVERTER (INTROD., FUNC., INST. Y MANT.)")):
|
||||
return "OTROS"
|
||||
# 2) CARRERA
|
||||
if has("CARRERA TECNICA DE AIRE ACONDICIONADO Y REFRIGERACION"):
|
||||
return "CARRERA"
|
||||
# 3) PROVINCIA TEAC
|
||||
if (has("TRUJILLO - TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")
|
||||
or has("PIURA - TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")
|
||||
or has("AREQUIPA - TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")
|
||||
or has("TRUJILLO - VIRTUAL TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")):
|
||||
return "PROVINCIA TEAC"
|
||||
# 4) PROVINCIA TERC
|
||||
if (has("AREQUIPA - TECNICO ESPECIALISTA EN REFRIGERACION DOMÉSTICA Y COMERCIAL")
|
||||
or has("PIURA - TECNICO ESPECIALISTA EN REFRIGERACION DOMÉSTICA Y COMERCIAL")
|
||||
or has("TRUJILLO - TECNICO ESPECIALISTA EN REFRIGERACION DOMÉSTICA Y COMERCIAL")):
|
||||
return "PROVINCIA TERC"
|
||||
# 5) SEMINARIOS
|
||||
if (has("CO2") or has("CERTIF") or has("SEM:") or has("MASTERCLASS") or has("DISEÑO")
|
||||
or has("DIPLOMADO") or has("SEM.") or has("DUCTOS") or has("SEMINARIO") or has("SEMINARIOS")):
|
||||
return "SEMINARIOS"
|
||||
# 6) PROGRAMAS TEAC (Lima)
|
||||
if (has("MANTENIMIENTO EN AIRE ACONDICIONADO")
|
||||
or has("TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")
|
||||
or has("TALLER - TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")
|
||||
or has("CONTINUIDAD-TECNICO ESPECIALISTA EN AA (4M)")
|
||||
or has("VIRTUAL TECNICO ESPECIALISTA EN AIRE ACONDICIONADO")):
|
||||
return "PROGRAMAS TEAC"
|
||||
# 7) PROGRAMAS TERC (Lima)
|
||||
if (has("INSTALACION EN REFRIGERACION COMERCIAL")
|
||||
or has("MANTENIMIENTO EN REFRIGERACIÓN COMERCIAL")
|
||||
or has("CONTINUIDAD-TECNICO ESPECIALISTA EN REFRIGERACIÓN COMERCIAL (4M)")
|
||||
or has("TECNICO ESPECIALISTA EN REFRIGERACION COMERCIAL")):
|
||||
return "PROGRAMAS TERC"
|
||||
return "SEMINARIOS"
|
||||
|
||||
|
||||
def meta_curso(dsc_programa):
|
||||
"""Meta por curso según Tipo_Programa (igual que el DAX Meta_Curso):
|
||||
PROGRAMAS TEAC/TERC=22, PROVINCIA TEAC/TERC=18, resto=15."""
|
||||
tp = tipo_programa_curso(dsc_programa)
|
||||
if tp in ("PROGRAMAS TEAC", "PROGRAMAS TERC"):
|
||||
return 22
|
||||
if tp in ("PROVINCIA TEAC", "PROVINCIA TERC"):
|
||||
return 18
|
||||
return 15
|
||||
|
||||
|
||||
# ── ESTADO/OBJECION (réplica EXACTA del DAX: cadena de SUBSTITUTE) ──
|
||||
# El DAX quita comas y espacios (pega todas las etiquetas), elimina las de
|
||||
# sistema, y luego reduce combinaciones concatenadas a un estado final.
|
||||
_SUST = [
|
||||
("atención_humana", ""), ("negociación", ""), ("supervisor", ""),
|
||||
("grupo_arequipa", ""), ("grupo_trujillo", ""), ("sin_respuesta", ""),
|
||||
("interesadovendido", "vendido"), ("próximo_inicio", "proxima_fecha"),
|
||||
("inicio", ""), ("aprobación", ""), ("negociacion", ""), ("no_acepta", ""),
|
||||
("pendiente", ""),
|
||||
("revisando_informaciónsólo_consulta", "sólo_consulta"),
|
||||
("contacto_iniciadovendido", "vendido"),
|
||||
("revisando_informacióninteresado", "interesado"),
|
||||
("revisando_informaciónvendido", "vendido"),
|
||||
("sólo_consultainteresado", "interesado"),
|
||||
("revisando_informaciónno_califica", "no_califica"),
|
||||
("interesadopor_pagar", "por_pagar"),
|
||||
("revisando_informaciónprecio_elevado", "precio_elevado"),
|
||||
("proxima_fechavendido", "vendido"),
|
||||
("sólo_consultavendido", "vendido"),
|
||||
("vendidointeresado", "vendido"),
|
||||
("revisando_informaciónproxima_fecha", "proxima_fecha"),
|
||||
("contacto_iniciadosólo_consulta", "sólo_consulta"),
|
||||
]
|
||||
|
||||
|
||||
def estado_objecion(etiquetas):
|
||||
"""Réplica del DAX ESTADO/OBJECION (versión de 28 sustituciones del PBI)."""
|
||||
if etiquetas is None:
|
||||
return "no trabajado"
|
||||
s = str(etiquetas).replace(",", "").replace(" ", "")
|
||||
for buscar, reemplazar in _SUST:
|
||||
s = s.replace(buscar, reemplazar)
|
||||
s = s.strip()
|
||||
return s if s else "no trabajado"
|
||||
|
||||
|
||||
# ── Ultima_Etiqueta (réplica EXACTA del DAX, usada para "Total Contactados") ──
|
||||
_ULTIMA_NO_TRABAJADO = {
|
||||
"", "(en blanco)", "aprobación", "atencion humana", "atención humana",
|
||||
"grupo arequipa", "grupo trujillo", "importacion masiva", "inicio",
|
||||
"negociacion", "sin respuesta", "pendiente",
|
||||
}
|
||||
|
||||
|
||||
def ultima_etiqueta(etiquetas):
|
||||
if etiquetas is None or str(etiquetas).strip() == "":
|
||||
return "NO TRABAJADO"
|
||||
partes = str(etiquetas).split(", ")
|
||||
limpia = partes[-1].replace("_", " ").strip()
|
||||
if limpia in _ULTIMA_NO_TRABAJADO:
|
||||
return "NO TRABAJADO"
|
||||
return limpia if limpia else "NO TRABAJADO"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
# PROCESAMIENTO DE LEADS (calcula Cantidad_Veces y agrupa)
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
def procesar_leads(filas_chatwoot):
|
||||
"""Marca el lead único (1ª vez de cada teléfono) y arma estructura limpia.
|
||||
Ordenamos por fecha para que la 1ª aparición de cada teléfono sea la 'única'."""
|
||||
# Ordenar por fecha ascendente (el query puede venir ordenado por id)
|
||||
filas_chatwoot = sorted(filas_chatwoot, key=lambda f: (_to_date(f.get("fecha_creada")) or date.min))
|
||||
# Teléfonos de prueba a excluir (igual que el PBI: 924374783)
|
||||
EXCLUIR = {"924374783"}
|
||||
vistos = set()
|
||||
out = []
|
||||
for f in filas_chatwoot:
|
||||
tel = str(f.get("telefono") or "").strip()
|
||||
if not tel or tel in EXCLUIR:
|
||||
continue
|
||||
es_unico = tel not in vistos
|
||||
vistos.add(tel)
|
||||
fecha = _to_date(f.get("fecha_creada"))
|
||||
asesor = (f.get("asesor") or "").strip()
|
||||
sede_campania = (f.get("sede") or "").strip() or "SIN SEDE"
|
||||
sede = sede_act(asesor, sede_campania) # réplica DAX Sede_Act (reasigna por asesor)
|
||||
cargo = (f.get("programa") or "").strip() # TEAC / TERC / VRF / etc. (del mapa campañas)
|
||||
out.append({
|
||||
"telefono": tel,
|
||||
"asesor": asesor,
|
||||
"fecha": fecha,
|
||||
"estado": estado_objecion(f.get("etiquetas")),
|
||||
"ultima": ultima_etiqueta(f.get("etiquetas")),
|
||||
"sede": sede,
|
||||
"cargo": cargo, # TEAC / TERC / VRF / CO2 / etc.
|
||||
"tipo_programa": tipo_programa_cohorte(sede, cargo), # PROGRAMAS/PROVINCIA/SEMINARIOS
|
||||
"codigo": (f.get("codigo") or "").strip() or "-", # código de campaña
|
||||
"es_unico": es_unico,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
# KPIs DEL MÓDULO LEADS
|
||||
# ════════════════════════════════════════════════════════════════
|
||||
def kpis_leads(leads, cursos, matriculas, ano, mes, dia):
|
||||
# Leads en el periodo (solo únicos = Cantidad_Veces == 1)
|
||||
leads_periodo = [l for l in leads if l["es_unico"] and _en_periodo(l["fecha"], ano, mes, dia)]
|
||||
|
||||
recibidos = len(leads_periodo)
|
||||
procesados = sum(1 for l in leads_periodo if l["asesor"])
|
||||
contactados = sum(1 for l in leads_periodo if l["asesor"] and l["ultima"] != "NO TRABAJADO")
|
||||
|
||||
pct_procesados = (procesados / recibidos) if recibidos > 0 else 0.0
|
||||
pct_contactados = (contactados / procesados) if procesados > 0 else 0.0
|
||||
|
||||
# ── Cursos del periodo (por fecha de inicio) ──
|
||||
cursos_periodo = [c for c in cursos if _en_periodo(_to_date(c.get("fch_inicio")), ano, mes, dia)]
|
||||
cursos_programados = len(cursos_periodo)
|
||||
suspendidos = sum(1 for c in cursos_periodo if str(c.get("cod_estado", "")).strip().upper() == "SUS")
|
||||
hoy = date.today()
|
||||
iniciados = sum(1 for c in cursos_periodo
|
||||
if str(c.get("cod_estado", "")).strip().upper() != "SUS"
|
||||
and (_to_date(c.get("fch_inicio")) or hoy) <= hoy)
|
||||
|
||||
# ── Total matriculados (= medida Matriculas_Totales del PBI) ──
|
||||
# Cuenta matrículas ALU/PRE cuya FECHA DE MATRÍCULA cae en el mes,
|
||||
# excluyendo 2 vendedoras. El Calendario del PBI va por fch_matricula.
|
||||
VENDEDORES_EXCLUIDOS = {"CALDERON S. LISSA GENA", "CRUZ G. FIORELLA MELISSA"}
|
||||
total_matriculados = sum(
|
||||
1 for m in matriculas
|
||||
if str(m.get("estado_matricula", "")).strip().upper() in ("ALU", "PRE")
|
||||
and str(m.get("dsc_vendedor", "")).strip() not in VENDEDORES_EXCLUIDOS
|
||||
and _en_periodo(_to_date(m.get("fch_matricula")), ano, mes, dia)
|
||||
)
|
||||
# Ocupabilidad (PBI): SUM(Inscritos) / SUM(Meta).
|
||||
# Excluye cursos suspendidos (SUS) y num_indice excluidos manualmente.
|
||||
# (Ver FUTUROS_CAMBIOS.md: mover esta lista a GitHub/Supabase)
|
||||
CURSOS_EXCLUIDOS = {"1154", "1121"}
|
||||
cursos_ocup = [c for c in cursos_periodo
|
||||
if str(c.get("cod_estado", "")).strip().upper() != "SUS"
|
||||
and str(c.get("num_indice", "")).strip() not in CURSOS_EXCLUIDOS]
|
||||
sum_meta = sum(meta_curso(c.get("dsc_programa")) for c in cursos_ocup)
|
||||
sum_inscritos_cursos = sum(int(c.get("Inscritos_Totales", 0) or 0) for c in cursos_ocup)
|
||||
|
||||
# ── Matrículas en los cursos del mes ──
|
||||
# Matrículas ALU/PRE que: (1) se hicieron en el mes (fch_matricula) Y
|
||||
# (2) son de un curso que INICIA en el mes (dsc_promocion = dsc_det_programa
|
||||
# de los cursos del periodo). Réplica de Cant_inscritos_Mes del PBI.
|
||||
promos_periodo = {str(c.get("dsc_det_programa", "")).strip()
|
||||
for c in cursos_periodo if str(c.get("dsc_det_programa", "")).strip()}
|
||||
mats_mes = [m for m in matriculas
|
||||
if str(m.get("dsc_promocion", "")).strip() in promos_periodo
|
||||
and str(m.get("estado_matricula", "")).strip().upper() in ("ALU", "PRE")
|
||||
and _en_periodo(_to_date(m.get("fch_matricula")), ano, mes, dia)]
|
||||
matriculas_mes = len({str(m.get("num_matricula")) for m in mats_mes})
|
||||
|
||||
ocupabilidad = (sum_inscritos_cursos / sum_meta) if sum_meta > 0 else 0.0
|
||||
|
||||
return {
|
||||
"leads_recibidos": recibidos,
|
||||
"leads_procesados": procesados,
|
||||
"leads_contactados": contactados,
|
||||
"pct_procesados": round(pct_procesados * 100, 2),
|
||||
"pct_contactados": round(pct_contactados * 100, 2),
|
||||
"total_matriculados": total_matriculados,
|
||||
"matriculas_mes": matriculas_mes,
|
||||
"ocupabilidad": round(ocupabilidad * 100, 2),
|
||||
"cursos_programados": cursos_programados,
|
||||
"cursos_reprogramados": 0, # requiere SharePoint (fase 2)
|
||||
"cursos_suspendidos": suspendidos,
|
||||
"cursos_iniciados": iniciados,
|
||||
}
|
||||
|
||||
|
||||
# ── Tabla Estado/Objeción (agrupa por Ultima_Etiqueta + desglose por asesor) ──
|
||||
def tabla_estado_objecion(leads, ano, mes, dia):
|
||||
leads_periodo = [l for l in leads if l["es_unico"]
|
||||
and l["asesor"] and _en_periodo(l["fecha"], ano, mes, dia)]
|
||||
agg = {} # estado -> total
|
||||
por_asesor = {} # estado -> {asesor: cantidad}
|
||||
telefonos = {} # (estado, asesor) -> [telefonos]
|
||||
for l in leads_periodo:
|
||||
est = l["ultima"] or "NO TRABAJADO"
|
||||
ase = l["asesor"] or "SIN ASESOR"
|
||||
agg[est] = agg.get(est, 0) + 1
|
||||
por_asesor.setdefault(est, {})
|
||||
por_asesor[est][ase] = por_asesor[est].get(ase, 0) + 1
|
||||
telefonos.setdefault((est, ase), []).append(l["telefono"])
|
||||
filas = []
|
||||
for estado in sorted(agg.keys(), key=lambda x: x.lower()):
|
||||
asesores = sorted(por_asesor[estado].items(), key=lambda x: -x[1])
|
||||
filas.append({
|
||||
"estado": estado,
|
||||
"cantidad": agg[estado],
|
||||
"asesores": [
|
||||
{"asesor": a, "cantidad": c,
|
||||
"telefonos": sorted(telefonos.get((estado, a), []))}
|
||||
for a, c in asesores
|
||||
],
|
||||
})
|
||||
total = sum(agg.values())
|
||||
return {"filas": filas, "total": total}
|
||||
|
||||
|
||||
# ── Matrículas por día (gráfico de línea) ──
|
||||
# Cuenta TODAS las matrículas del día (misma base que Total Matriculados):
|
||||
# estado ALU/PRE, excluyendo las 2 vendedoras, por día de fch_matricula.
|
||||
def matriculas_por_dia(matriculas, cursos, ano, mes, dia):
|
||||
VENDEDORES_EXCLUIDOS = {"CALDERON S. LISSA GENA", "CRUZ G. FIORELLA MELISSA"}
|
||||
conteo = {} # dia -> total
|
||||
por_tipo = {} # dia -> {tipo_programa: cantidad}
|
||||
for m in matriculas:
|
||||
if str(m.get("estado_matricula", "")).strip().upper() not in ("ALU", "PRE"):
|
||||
continue
|
||||
if str(m.get("dsc_vendedor", "")).strip() in VENDEDORES_EXCLUIDOS:
|
||||
continue
|
||||
d = _to_date(m.get("fch_matricula"))
|
||||
if not _en_periodo(d, ano, mes, dia):
|
||||
continue
|
||||
conteo[d.day] = conteo.get(d.day, 0) + 1
|
||||
tp = tipo_programa_curso(m.get("dsc_programa")) # TEAC/TERC/PROVINCIA.../SEMINARIOS/OTROS
|
||||
por_tipo.setdefault(d.day, {})
|
||||
por_tipo[d.day][tp] = por_tipo[d.day].get(tp, 0) + 1
|
||||
|
||||
def _detalle(day):
|
||||
items = sorted(por_tipo.get(day, {}).items(), key=lambda x: -x[1])
|
||||
return [{"tipo": t, "cantidad": c} for t, c in items]
|
||||
|
||||
import calendar
|
||||
if mes not in ("TODOS", None) and ano not in ("TODOS", None):
|
||||
ndias = calendar.monthrange(int(ano), int(mes))[1]
|
||||
return [{"dia": d, "cantidad": conteo.get(d, 0), "detalle": _detalle(d)}
|
||||
for d in range(1, ndias + 1)]
|
||||
return [{"dia": d, "cantidad": conteo[d], "detalle": _detalle(d)}
|
||||
for d in sorted(conteo.keys())]
|
||||
|
||||
|
||||
# ── Gráfico "Leads por Programa": serie diaria Totales vs Procesados ──
|
||||
def leads_por_dia(leads, ano, mes, dia):
|
||||
lp = [l for l in leads if l["es_unico"] and _en_periodo(l["fecha"], ano, mes, dia)]
|
||||
tot = {} # dia -> totales
|
||||
proc = {} # dia -> procesados (con asesor)
|
||||
for l in lp:
|
||||
d = l["fecha"].day
|
||||
tot[d] = tot.get(d, 0) + 1
|
||||
if l["asesor"]:
|
||||
proc[d] = proc.get(d, 0) + 1
|
||||
import calendar
|
||||
if mes not in ("TODOS", None) and ano not in ("TODOS", None):
|
||||
ndias = calendar.monthrange(int(ano), int(mes))[1]
|
||||
dias = range(1, ndias + 1)
|
||||
else:
|
||||
dias = sorted(set(list(tot.keys()) + list(proc.keys())))
|
||||
return [{"dia": d, "totales": tot.get(d, 0), "procesados": proc.get(d, 0)} for d in dias]
|
||||
|
||||
|
||||
# ── Tabla por Sede_Act -> Tipo_Programa con 4 medidas (cohorte de leads) ──
|
||||
def tabla_pauta(leads, matriculas, ano, mes, dia, importe_por_pauta_periodo=None,
|
||||
resultados_por_pauta_periodo=None, campanias_sede_cargo=None):
|
||||
importe_por_pauta_periodo = importe_por_pauta_periodo or {}
|
||||
resultados_por_pauta_periodo = resultados_por_pauta_periodo or {}
|
||||
campanias_sede_cargo = campanias_sede_cargo or {}
|
||||
# 1) Leads únicos del periodo con su teléfono, fecha, sede y tipo
|
||||
lp = [l for l in leads if l["es_unico"] and _en_periodo(l["fecha"], ano, mes, dia)]
|
||||
# mapa teléfono -> fecha del lead (para "matrícula posterior al lead")
|
||||
fecha_lead = {}
|
||||
for l in lp:
|
||||
fecha_lead.setdefault(l["telefono"], l["fecha"])
|
||||
|
||||
# 2) Matrículas que cruzan por teléfono y son POSTERIORES a la fecha del lead
|
||||
# (réplica de Matriculas_Cohorte_Lead e Inversion_x_Pauta_Cohorte)
|
||||
mat_por_tel = {} # telefono -> {"mats": set(num_matricula), "inv": float}
|
||||
for m in matriculas:
|
||||
tel = str(m.get("dsc_telefono_1") or "").strip()
|
||||
if tel not in fecha_lead:
|
||||
continue
|
||||
fm = _to_date(m.get("fch_matricula"))
|
||||
fl = fecha_lead[tel]
|
||||
if not fm or not fl or not (fm > fl):
|
||||
continue
|
||||
# INV_NETA_FINAL: si DOL, ×3.34
|
||||
try: inv = float(m.get("INV_NETA", 0) or 0)
|
||||
except: inv = 0.0
|
||||
if str(m.get("cod_moneda", "")).strip().upper() == "DOL":
|
||||
inv *= 3.34
|
||||
e = mat_por_tel.setdefault(tel, {"mats": set(), "inv": 0.0})
|
||||
e["mats"].add(str(m.get("num_matricula")))
|
||||
e["inv"] += inv
|
||||
|
||||
# 3) Agrupar por Sede -> Tipo_Programa -> Código
|
||||
def _nuevo():
|
||||
return {"recibidos": 0, "procesados": 0, "mats": set(), "inv": 0.0}
|
||||
grupos = {} # sede -> tipo -> codigo -> métricas
|
||||
for l in lp:
|
||||
sede = l["sede"]; tp = grupo_tipo_cohorte(l["tipo_programa"]); cod = l.get("codigo", "-"); tel = l["telefono"]
|
||||
g = grupos.setdefault(sede, {}).setdefault(tp, {}).setdefault(cod, _nuevo())
|
||||
g["recibidos"] += 1
|
||||
if l["asesor"]:
|
||||
g["procesados"] += 1
|
||||
if tel in mat_por_tel:
|
||||
g["mats"] |= mat_por_tel[tel]["mats"]
|
||||
g["inv"] += mat_por_tel[tel]["inv"]
|
||||
|
||||
def _fila(d):
|
||||
return {"recibidos": d["recibidos"], "procesados": d["procesados"],
|
||||
"matriculas": len(d["mats"]), "inversion": round(d["inv"], 0)}
|
||||
|
||||
# IMPORTE y RESULTADOS por PAUTA -> se asignan a su (sede, tipo) de CAMPANIAS,
|
||||
# una sola vez por pauta (no por sede del lead), para NO duplicar.
|
||||
# imp_st[(sede,tipo)][cod] = importe ; res_st[(sede,tipo)][cod] = resultados
|
||||
imp_st = {}
|
||||
res_st = {}
|
||||
for cod, imp_val in importe_por_pauta_periodo.items():
|
||||
info = campanias_sede_cargo.get(str(cod).strip())
|
||||
if not info:
|
||||
continue
|
||||
se = str(info.get("sede") or "").upper()
|
||||
tp = grupo_tipo_cohorte(tipo_programa_cohorte(se, info.get("cargo")))
|
||||
imp_st.setdefault((se, tp), {})[str(cod).strip()] = float(imp_val or 0.0)
|
||||
for cod, res_val in resultados_por_pauta_periodo.items():
|
||||
info = campanias_sede_cargo.get(str(cod).strip())
|
||||
if not info:
|
||||
continue
|
||||
se = str(info.get("sede") or "").upper()
|
||||
tp = grupo_tipo_cohorte(tipo_programa_cohorte(se, info.get("cargo")))
|
||||
res_st.setdefault((se, tp), {})[str(cod).strip()] = int(res_val or 0)
|
||||
|
||||
filas = []
|
||||
for sede in sorted(grupos.keys()):
|
||||
subfilas = []
|
||||
s_rec = s_proc = 0; s_mats = set(); s_inv = 0.0; s_imp = 0.0; s_res = 0
|
||||
for tp in sorted(grupos[sede].keys()):
|
||||
cods = grupos[sede][tp]
|
||||
imp_map = imp_st.get((sede.upper(), tp), {}) # importe por pauta de esta sede/tipo
|
||||
res_map = res_st.get((sede.upper(), tp), {})
|
||||
# métricas del tipo (sumando sus códigos)
|
||||
t_rec = t_proc = 0; t_mats = set(); t_inv = 0.0; t_imp = 0.0; t_res = 0
|
||||
codigos = []
|
||||
for cod in sorted(cods.keys()):
|
||||
d = cods[cod]
|
||||
imp_cod = float(imp_map.get(str(cod).strip(), 0.0))
|
||||
res_cod = int(res_map.get(str(cod).strip(), 0))
|
||||
codigos.append({"codigo": cod, **_fila(d), "importe": round(imp_cod, 2),
|
||||
"resultados": res_cod})
|
||||
t_rec += d["recibidos"]; t_proc += d["procesados"]
|
||||
t_mats |= d["mats"]; t_inv += d["inv"]; t_imp += imp_cod; t_res += res_cod
|
||||
subfilas.append({
|
||||
"tipo": tp, "recibidos": t_rec, "procesados": t_proc,
|
||||
"matriculas": len(t_mats), "inversion": round(t_inv, 0),
|
||||
"importe": round(t_imp, 2), "resultados": t_res, "codigos": codigos,
|
||||
})
|
||||
s_rec += t_rec; s_proc += t_proc; s_mats |= t_mats; s_inv += t_inv; s_imp += t_imp; s_res += t_res
|
||||
filas.append({
|
||||
"sede": sede, "recibidos": s_rec, "procesados": s_proc,
|
||||
"matriculas": len(s_mats), "inversion": round(s_inv, 0),
|
||||
"importe": round(s_imp, 2), "resultados": s_res, "subfilas": subfilas,
|
||||
})
|
||||
# Totales
|
||||
t_rec = sum(f["recibidos"] for f in filas)
|
||||
t_proc = sum(f["procesados"] for f in filas)
|
||||
t_inv = round(sum(f["inversion"] for f in filas), 0)
|
||||
# Total de importe/resultados: suma de TODAS las pautas que estan en campanias
|
||||
# (una vez cada una), aunque no tengan fila con leads. Asi el total no se pierde.
|
||||
t_imp = round(sum(float(v or 0.0) for cod, v in importe_por_pauta_periodo.items()
|
||||
if str(cod).strip() in campanias_sede_cargo), 2)
|
||||
t_res = sum(int(v or 0) for cod, v in resultados_por_pauta_periodo.items()
|
||||
if str(cod).strip() in campanias_sede_cargo)
|
||||
# matrículas total: unión global
|
||||
all_mats = set()
|
||||
for tel, e in mat_por_tel.items():
|
||||
all_mats |= e["mats"]
|
||||
return {"filas": filas, "total": {"recibidos": t_rec, "procesados": t_proc,
|
||||
"matriculas": len(all_mats), "inversion": t_inv,
|
||||
"importe": t_imp, "resultados": t_res}}
|
||||
|
||||
|
||||
# ── Personalizado: replica la columna Fact_SQL_Base_Cursos[Personalizado] (M) ──
|
||||
# Base = dsc_det_programa, limpiando saltos de línea, luego cadena de reemplazos.
|
||||
_PERS_REEMPLAZOS = [
|
||||
("TECNICO ESPECIALISTA EN AIRE ACONDICIONADO", "TEAC"),
|
||||
("TECNICO ESPECIALISTA EN REFRIGERACION COMERCIAL", "TERC"),
|
||||
("TECNICO ESPECIALISTA EN REFRIGERACION DOMÉSTICA Y COMERCIAL", "TERC"),
|
||||
("CARRERA TECNICA DE AIRE ACONDICIONADO Y REFRIGERACION ", "CARRERA"),
|
||||
("VIRTUAL SEMINARIO SUPERVISION DE OBRAS EN AIRE ACONDICIONADO", "SUPERVISION DE OBRAS"),
|
||||
("SEMINARIO APLICACIÓN DE VARIADORES DE FRECUENCIA EN SISTEMAS HVAC", "VARIADORES DE FRECUENCIA"),
|
||||
("VIRTUAL - SISTEMAS DE REFRIGERACION CON CO2 - FASE SUBCRITICA Y TRANSCRITICA", "REFRIGERACION CON CO2"),
|
||||
("VIRTUAL SEMINARIO DISEÑO DE CAMARAS DE REFRIGERACION CON SISTEMAS CON FREON", "DISEÑO DE CAMARAS"),
|
||||
("VIRTUAL SEM. DETERMINACIÓN DE CAPACIDAD DE EQUIPOS DE AIRE ACONDICIONADO- CARGAS TÉRMICAS -(A/A)", "CARGAS TERMICAS"),
|
||||
("VIRTUAL SEMINARIO DIBUJO TECNICO Y DISEÑO ASISTIDO POR COMPUTADORA (CAD) PARA HVAC -(A/A)", "DIBUJO TECNICO (CAD)"),
|
||||
("VIRTUAL SEMINARIO: SISTEMAS DE REFRIGERACIÓN INDUSTRIAL POR AMONIACO (NH3)", "AMONIACO (NH3)"),
|
||||
("SEMINARIO VIRTUAL METRADO , COSTEO Y PRESUPUESTOS DE HVAC (AA)", "METRADO, COSTEO Y PRESUPUESTOS"),
|
||||
("CARRERA TECNICA LIMA GESTION DE EMPRESAS", "GESTION DE EMPRESAS"),
|
||||
("VIRTUAL SEMINARIO DISEÑO DE CHILLERS PARA PROCESOS INDUSTRIALES DE REFRIGERACIÓN", "DISEÑO DE CHILLERS"),
|
||||
("VIRTUAL SEMINARIO PRACTICO VENTILACION DE SOTANO Y PREZURIZACION DE ESCALERA -(A/A)", "VENTILACION DE SOTANO"),
|
||||
("SEMINARIO USO DE SOFTWARE EN CÁLCULOS DE AIRE ACONDICIONADO", "SOFTWARE EN CALCULOS DE A/A"),
|
||||
("DISEÑO DE SISTEMAS DE AIRE ACONDICIONADO", "DISEÑO DE SISTEMAS DE A/A"),
|
||||
("SEMINARIO INSTALACIÓN DE SISTEMAS DE A/A DE VOLUMEN VARIABLE VRV/VRF - SAB", "VOLUMEN VARIABLE VRF"),
|
||||
# Seminarios VRF por sede y CO2 → nombre corto (la frecuencia se conserva al final)
|
||||
("PIURA - SEMINARIO INSTALACIÓN DE SISTEMAS DE A/A DE VOLUMEN VARIABLE - VRF", "PIURA - VRF"),
|
||||
("AREQUIPA - SEMINARIO INSTALACIÓN DE SISTEMAS DE A/A DE VOLUMEN VARIABLE - VRF", "AREQUIPA - VRF"),
|
||||
("TRUJILLO - SEMINARIO INSTALACIÓN DE SISTEMAS DE A/A DE VOLUMEN VARIABLE - VRF", "TRUJILLO - VRF"),
|
||||
("VIRTUAL - DISEÑO Y OPERACIÓN DE SISTEMAS DE REFRIGERACIÓN CON CO2 EN FASE SUBCRITICA Y TRANSCRITICA", "CO2"),
|
||||
# Reemplazos sobre Nombre_Programa_Detalle (bloque ductos y otros)
|
||||
("VIRTUAL - DIMENSIONAMIENTO DE", ""),
|
||||
("METÁLICOS EN AIRE ACONDICIONADO Y VENTILACIÓN", ""),
|
||||
("MASTERCLASS: PROGRAMACIÓN DE CONTROLADORES PARA REFRIGERACIÓN", "PROGRAMACION DE CONTROLADORES"),
|
||||
("DIPLOMADO INTERNACIONAL DE AIRE ACONDICIONADO", "DIPLOMADO DE A/A"),
|
||||
# Reemplazos finales (sedes/carreras/masterclass)
|
||||
("AREQUIPA - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - TAR", "AREQUIPA - CARRERA - TARDE"),
|
||||
("PIURA - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - TAR", "PIURA - CARRERA - TARDE"),
|
||||
("TRUJILLO - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - TAR", "TRUJILLO - CARRERA - TARDE"),
|
||||
("AREQUIPA - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - MAN", "AREQUIPA - CARRERA - MAÑANA"),
|
||||
("PIURA - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - MAN", "PIURA - CARRERA - MAÑANA"),
|
||||
("TRUJILLO - CARRERA TÉCNICA DE AIRE ACONDICIONADO Y REFRIGERACIÓN - MAN", "TRUJILLO - CARRERA - MAÑANA"),
|
||||
("GESTIÓN DE VENTA DE EQUIPOS DE AIRE ACONDICIONADO Y EQUIPOS DE REFRIGERACIÓN - NOC", "GESTIÓN DE VENTA - NOC"),
|
||||
("MASTERCLASS SELECCIÓN E INSTALACIÓN DE TARJETAS ELECTRÓNICAS UNIVERSALES EN EQUIPOS DE A/A .INVERTER - MAN", "MASTERCLASS TARJETAS UNIVERSALES - MAN"),
|
||||
("MASTERCLASS: SISTEMAS DE A/A CON VRF - SAB", "MASTERCLASS: A/A CON VRF - SAB"),
|
||||
("GESTIÓN DE VENTA DE EQUIPOS DE AIRE ACONDICIONADO Y EQUIPOS DE REFRIGERACIÓN - TAR", "GESTIÓN DE VENTA - TAR"),
|
||||
]
|
||||
|
||||
|
||||
def personalizado_curso(dsc_programa, cod_frecuencia=""):
|
||||
"""Replica Fact_SQL_Base_Cursos[Personalizado] del PBI:
|
||||
base = dsc_programa & ' - ' & cod_frecuencia (NO dsc_det_programa)."""
|
||||
s = f"{str(dsc_programa or '')} - {str(cod_frecuencia or '')}"
|
||||
# Text.Clean + reemplazar saltos de línea por espacio, luego Trim
|
||||
s = s.replace("\r", " ").replace("\n", " ")
|
||||
s = "".join(ch for ch in s if ch >= " " or ch == " ") # Text.Clean (quita control)
|
||||
s = s.strip()
|
||||
for buscar, reemplazo in _PERS_REEMPLAZOS:
|
||||
s = s.replace(buscar, reemplazo)
|
||||
# colapsar espacios múltiples que pudieran quedar de reemplazos vacíos
|
||||
s = " ".join(s.split())
|
||||
return s
|
||||
|
||||
|
||||
# ── Matriz por Curso (num_indice): Personalizado + métricas de leads por pauta ──
|
||||
# NOTA: las métricas de leads cruzan por el CÓDIGO DE PAUTA del curso, que viene de
|
||||
# SharePoint (no disponible aún). Por eso salen en 0 hasta conectar esa fuente.
|
||||
# Ver FUTUROS_CAMBIOS.md punto 5. Lo que sí se calcula: Personalizado y Fecha Inicio.
|
||||
def matriz_cursos(cursos, leads, ano, mes, dia, pauta_map=None,
|
||||
campanias_map=None, cartera_all=None, cartera_asig=None,
|
||||
mat_por_indice=None, cartera_tels=None, cartera_origen=None,
|
||||
importe_por_pauta=None, importe_por_pauta_periodo=None,
|
||||
cartera_canal=None, conjunto_por_pauta=None, pautas_por_indice=None):
|
||||
pauta_map = pauta_map or {}
|
||||
pautas_por_indice = pautas_por_indice or {} # {num_indice: [pautas]} (muchos-a-muchos)
|
||||
campanias_map = campanias_map or {}
|
||||
cartera_all = cartera_all or {}
|
||||
cartera_asig = cartera_asig or {}
|
||||
mat_por_indice = mat_por_indice or {}
|
||||
cartera_tels = cartera_tels or set()
|
||||
cartera_origen = cartera_origen or {}
|
||||
importe_por_pauta = importe_por_pauta or {}
|
||||
importe_por_pauta_periodo = importe_por_pauta_periodo or {}
|
||||
conjunto_por_pauta = conjunto_por_pauta or {} # {pauta: [conjuntos de anuncios]}
|
||||
# cartera_canal = {"PAUTA": {"all","asig","tels"}, "OTROS": {...}} para el desglose por canal
|
||||
cartera_canal = cartera_canal or {}
|
||||
|
||||
CURSOS_EXCLUIDOS = {"1121", "1154"}
|
||||
|
||||
def _excluir(c):
|
||||
ni = str(c.get("num_indice", ""))
|
||||
if ni in CURSOS_EXCLUIDOS:
|
||||
return True
|
||||
info = pauta_map.get(ni)
|
||||
if not info:
|
||||
return False # sin info en Supabase → no se excluye
|
||||
# Excluir SUSPENDIDO o contar = NO
|
||||
return info.get("contar") == "NO" or info.get("estado") == "SUSPENDIDO"
|
||||
|
||||
cursos_periodo = [c for c in cursos
|
||||
if _en_periodo(_to_date(c.get("fch_inicio")), ano, mes, dia)
|
||||
and not _excluir(c)]
|
||||
|
||||
# Leads únicos agrupados por codigo (= Pauta). Históricos y del mes (filtro fecha).
|
||||
leads_unicos = [l for l in leads if l.get("es_unico")]
|
||||
hist_por_cod = {} # codigo → set teléfonos
|
||||
hist_ases_cod = {} # codigo → set teléfonos con asesor
|
||||
mes_por_cod = {} # codigo → set teléfonos (en periodo filtrado)
|
||||
mes_ases_cod = {} # codigo → set teléfonos con asesor (en periodo)
|
||||
for l in leads_unicos:
|
||||
cod = l.get("codigo", "-")
|
||||
tel = l["telefono"]
|
||||
hist_por_cod.setdefault(cod, set()).add(tel)
|
||||
if l.get("asesor"):
|
||||
hist_ases_cod.setdefault(cod, set()).add(tel)
|
||||
if _en_periodo(l["fecha"], ano, mes, dia):
|
||||
mes_por_cod.setdefault(cod, set()).add(tel)
|
||||
if l.get("asesor"):
|
||||
mes_ases_cod.setdefault(cod, set()).add(tel)
|
||||
|
||||
# Construir filas con sus medidas
|
||||
pre = []
|
||||
for c in sorted(cursos_periodo, key=lambda x: (_to_date(x.get("fch_inicio")) or date.min)):
|
||||
nombre = personalizado_curso(c.get("dsc_programa"), c.get("cod_frecuencia"))
|
||||
fch = _to_date(c.get("fch_inicio"))
|
||||
ni = str(c.get("num_indice", "")).strip()
|
||||
# LISTA de pautas del num_indice (muchos-a-muchos). Si no hay en la tabla nueva,
|
||||
# usa la de basebi (compatibilidad).
|
||||
cods = pautas_por_indice.get(ni)
|
||||
if not cods:
|
||||
_info = pauta_map.get(ni)
|
||||
cods = [_info.get("pauta")] if _info and _info.get("pauta") else []
|
||||
cods = [str(x).strip() for x in cods if x]
|
||||
# Leads = union de telefonos de TODAS las pautas (sin duplicar)
|
||||
def _union(mapa):
|
||||
s = set()
|
||||
for cd in cods:
|
||||
s |= mapa.get(cd, set())
|
||||
return len(s)
|
||||
nuevos = _union(hist_por_cod)
|
||||
nuevos_a = _union(hist_ases_cod)
|
||||
nuevos_m = _union(mes_por_cod)
|
||||
nuevos_ma = _union(mes_ases_cod)
|
||||
pre.append({
|
||||
"num_indice": ni,
|
||||
"personalizado": nombre,
|
||||
"fch": fch,
|
||||
"pauta": cods[0] if cods else None, # pauta principal (para mostrar)
|
||||
"pautas": cods, # todas las pautas (para sumar)
|
||||
"fecha_inicio": fch.strftime("%d/%m/%Y") if fch else "",
|
||||
"leads_nuevos": nuevos,
|
||||
"leads_nuevos_asesor": nuevos_a,
|
||||
"leads_nuevos_mes": nuevos_m,
|
||||
"leads_nuevos_mes_asesor": nuevos_ma,
|
||||
})
|
||||
|
||||
# Índice HISTÓRICO completo (TODOS los cursos, sin filtro de fecha) por
|
||||
# personalizado → lista de (fecha, leads_nuevos). Para el acumulado.
|
||||
hist_cursos = {}
|
||||
for c in cursos:
|
||||
if _excluir(c):
|
||||
continue
|
||||
nom = personalizado_curso(c.get("dsc_programa"), c.get("cod_frecuencia"))
|
||||
f = _to_date(c.get("fch_inicio"))
|
||||
info = pauta_map.get(str(c.get("num_indice", "")))
|
||||
cd = info.get("pauta") if info else None
|
||||
nv = len(hist_por_cod.get(cd, ())) if cd else 0
|
||||
hist_cursos.setdefault(nom, []).append((f, nv))
|
||||
|
||||
# Leads_Acumulados_Historico: suma de leads_nuevos de TODOS los cursos del
|
||||
# MISMO personalizado con fecha <= la del curso actual (histórico completo).
|
||||
filas = []
|
||||
for r in pre:
|
||||
acum = sum(nv for (f, nv) in hist_cursos.get(r["personalizado"], [])
|
||||
if f and r["fch"] and f <= r["fch"])
|
||||
# CARTERA TOTAL: teléfonos únicos de cartera_junta con la misma SEDE+PROGRAMA
|
||||
# del curso (según su pauta → campanias) cuya fecha_creada <= fch_inicio del curso.
|
||||
# cartera_total = todos; cartera_total_asig = solo con asesor asignado.
|
||||
cartera_total = 0
|
||||
cartera_total_asig = 0
|
||||
cod = r.get("pauta")
|
||||
cods = r.get("pautas") or ([cod] if cod else [])
|
||||
if cods and r["fch"]:
|
||||
# Cartera = union de telefonos de la sede+programa de TODAS las pautas del num_indice
|
||||
tels_all = {}; tels_asig = {}
|
||||
for cd in cods:
|
||||
sp = campanias_map.get(str(cd).upper())
|
||||
if not sp:
|
||||
continue
|
||||
for tel, fx in cartera_all.get(sp, {}).items():
|
||||
if fx and (tel not in tels_all or fx < tels_all[tel]):
|
||||
tels_all[tel] = fx
|
||||
for tel, fx in cartera_asig.get(sp, {}).items():
|
||||
if fx and (tel not in tels_asig or fx < tels_asig[tel]):
|
||||
tels_asig[tel] = fx
|
||||
cartera_total = sum(1 for fx in tels_all.values() if fx <= r["fch"])
|
||||
cartera_total_asig = sum(1 for fx in tels_asig.values() if fx <= r["fch"])
|
||||
# MATRÍCULAS NO IDENTIFICADAS: matrículas de este curso (num_indice) cuyo teléfono
|
||||
# (tel_1, o tel_2 si el 1 está vacío) NO aparece en cartera_junta. Sin filtro de fecha.
|
||||
_ni = r["num_indice"]
|
||||
_ni = _ni[:-2] if _ni.endswith(".0") else _ni
|
||||
_mats = mat_por_indice.get(_ni, []) # lista de (telefono, fecha_matricula)
|
||||
_tels_no_iden = [ph for (ph, fm) in _mats if ph not in cartera_tels]
|
||||
matriculas_no_iden = len(_tels_no_iden)
|
||||
# MATRICULAS LEADS NUEVOS: matrícula hecha dentro de 45 días DESPUÉS del origen
|
||||
# del lead (registro es_origen=SI de ese teléfono en la cartera).
|
||||
mat_leads_nuevos = 0
|
||||
mat_leads_antiguos = 0
|
||||
_tels_nuevos = []
|
||||
_tels_antiguos = []
|
||||
for (ph, fm) in _mats:
|
||||
if not ph or not fm:
|
||||
continue
|
||||
forig = cartera_origen.get(ph)
|
||||
if forig is None:
|
||||
continue
|
||||
dias = (fm - forig).days
|
||||
if 0 <= dias <= 45:
|
||||
mat_leads_nuevos += 1
|
||||
_tels_nuevos.append(ph)
|
||||
else:
|
||||
# >45 días, o matrícula anterior al origen del lead (dias<0) → Antiguo
|
||||
mat_leads_antiguos += 1
|
||||
_tels_antiguos.append(ph)
|
||||
# IMPORTE PAUTA: gasto de Meta Ads sumando TODAS las pautas del num_indice.
|
||||
importe_pauta = round(sum(float(importe_por_pauta.get(str(cd), 0.0)) for cd in cods), 2)
|
||||
# IMPORTE PAUTA EN EL MES: igual, pero solo del periodo filtrado.
|
||||
importe_pauta_mes = round(sum(float(importe_por_pauta_periodo.get(str(cd), 0.0)) for cd in cods), 2)
|
||||
|
||||
# ── SUBFILAS por CANAL (PAUTA / OTROS) ── mismo criterio que la fila padre
|
||||
# (SEDE+PROGRAMA vía campanias, misma fecha) + filtro de canal desde cartera.
|
||||
def _subfila(clave):
|
||||
cc = cartera_canal.get(clave, {})
|
||||
c_all = cc.get("all", {}); c_asig = cc.get("asig", {}); c_tels = cc.get("tels", set())
|
||||
ct = ct_asig = 0
|
||||
l_rec = l_proc = 0
|
||||
l_rec_mes = l_proc_mes = 0
|
||||
if cod and r["fch"]:
|
||||
sp = campanias_map.get(str(cod).upper())
|
||||
if sp:
|
||||
fa = c_all.get(sp, {})
|
||||
fg = c_asig.get(sp, {})
|
||||
# Cartera Total/Asig del canal: fecha_creada <= inicio del curso (igual que padre)
|
||||
ct = sum(1 for fx in fa.values() if fx and fx <= r["fch"])
|
||||
ct_asig = sum(1 for fx in fg.values() if fx and fx <= r["fch"])
|
||||
# L. Recibidos/Procesados del canal = misma cartera del canal (mismo corte)
|
||||
l_rec = ct
|
||||
l_proc = ct_asig
|
||||
# "del Mes" = fecha_creada en el periodo filtrado
|
||||
l_rec_mes = sum(1 for fx in fa.values() if _en_periodo(fx, ano, mes, dia))
|
||||
l_proc_mes = sum(1 for fx in fg.values() if _en_periodo(fx, ano, mes, dia))
|
||||
# Matrículas del curso, clasificadas por canal:
|
||||
# - NO identificadas (tel NO en cartera) -> todas a OTROS.
|
||||
# - identificadas -> al canal de su telefono (c_tels), regla 45 dias.
|
||||
mt_noiden = mt_nuevos = mt_antiguos = 0
|
||||
for (ph, fm) in _mats:
|
||||
if not ph:
|
||||
continue
|
||||
en_cartera = ph in cartera_tels
|
||||
if not en_cartera:
|
||||
# no identificada: solo cuenta en la subfila OTROS
|
||||
if clave == "OTROS":
|
||||
mt_noiden += 1
|
||||
continue
|
||||
# identificada: solo cuenta si su tel pertenece a ESTE canal
|
||||
if ph not in c_tels:
|
||||
continue
|
||||
forig = cartera_origen.get(ph)
|
||||
if fm and forig:
|
||||
d = (fm - forig).days
|
||||
if 0 <= d <= 45: mt_nuevos += 1
|
||||
else: mt_antiguos += 1
|
||||
return {"canal": clave, "cartera_total": ct, "cartera_total_asig": ct_asig,
|
||||
"leads_nuevos": l_rec, "leads_nuevos_asesor": l_proc,
|
||||
"leads_nuevos_mes": l_rec_mes, "leads_nuevos_mes_asesor": l_proc_mes,
|
||||
"matriculas_no_iden": mt_noiden, "mat_leads_nuevos": mt_nuevos,
|
||||
"mat_leads_antiguos": mt_antiguos}
|
||||
subfilas = [_subfila("PAUTA"), _subfila("WEB"), _subfila("OTROS")] if cartera_canal else []
|
||||
|
||||
filas.append({
|
||||
"num_indice": r["num_indice"],
|
||||
"personalizado": r["personalizado"],
|
||||
"fecha_inicio": r["fecha_inicio"],
|
||||
"pauta": r.get("pauta"),
|
||||
"importe_pauta": importe_pauta,
|
||||
"importe_pauta_mes": importe_pauta_mes,
|
||||
"cartera_total": cartera_total,
|
||||
"cartera_total_asig": cartera_total_asig,
|
||||
"matriculas_no_iden": matriculas_no_iden,
|
||||
"matriculas_no_iden_tels": _tels_no_iden,
|
||||
"mat_leads_nuevos": mat_leads_nuevos,
|
||||
"mat_leads_antiguos": mat_leads_antiguos,
|
||||
"mat_leads_nuevos_tels": _tels_nuevos,
|
||||
"mat_leads_antiguos_tels": _tels_antiguos,
|
||||
"leads_acumulados": acum,
|
||||
"leads_nuevos": r["leads_nuevos"],
|
||||
"leads_nuevos_asesor": r["leads_nuevos_asesor"],
|
||||
"leads_nuevos_mes": r["leads_nuevos_mes"],
|
||||
"leads_nuevos_mes_asesor": r["leads_nuevos_mes_asesor"],
|
||||
"subfilas_canal": subfilas,
|
||||
"conjuntos": [cj for cd in cods for cj in conjunto_por_pauta.get(str(cd).strip(), [])],
|
||||
"contar": (pauta_map.get(str(r["num_indice"]).strip()) or {}).get("contar") or "SI",
|
||||
})
|
||||
return {"filas": filas}
|
||||
202
backend/main.py
Normal file
202
backend/main.py
Normal file
@@ -0,0 +1,202 @@
|
||||
# backend/main.py
|
||||
"""API REST del Dashboard de LEADS (FastAPI)."""
|
||||
from fastapi import FastAPI, Query, HTTPException, Body
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from datetime import datetime
|
||||
import os
|
||||
import uvicorn
|
||||
from dotenv import load_dotenv
|
||||
|
||||
import services
|
||||
from cache_manager import start_background_refresh, cache_stats
|
||||
|
||||
load_dotenv()
|
||||
|
||||
app = FastAPI(title="Dashboard Leads API", version="1.0")
|
||||
|
||||
# Origenes permitidos para CORS. Por defecto "*" (todos). En produccion se puede
|
||||
# limitar con la variable de entorno CORS_ORIGINS (dominios separados por coma).
|
||||
_cors = os.getenv("CORS_ORIGINS", "*")
|
||||
_origins = ["*"] if _cors.strip() == "*" else [o.strip() for o in _cors.split(",") if o.strip()]
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware, allow_origins=_origins, allow_credentials=True,
|
||||
allow_methods=["*"], allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _startup():
|
||||
# Precarga en SEGUNDO PLANO (hilo aparte) para no bloquear el arranque del server.
|
||||
import threading
|
||||
def _precarga_bg():
|
||||
print("[startup] Precargando datos de Leads (2do plano)...")
|
||||
try:
|
||||
services.precargar_todo()
|
||||
print("[startup] Precarga completa.")
|
||||
except Exception as e:
|
||||
print(f"[startup] Precarga falló: {e}")
|
||||
threading.Thread(target=_precarga_bg, daemon=True).start()
|
||||
# Otros General en un hilo aparte (sus consultas son mas pesadas)
|
||||
def _precarga_otros_bg():
|
||||
try:
|
||||
services.precargar_otros_general()
|
||||
except Exception as e:
|
||||
print(f"[startup] Precarga Otros falló: {e}")
|
||||
threading.Thread(target=_precarga_otros_bg, daemon=True).start()
|
||||
start_background_refresh(services.refrescar_todo, interval=900)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
return {"status": "ok", "hora": datetime.now().isoformat()}
|
||||
|
||||
|
||||
@app.get("/api/cache/stats")
|
||||
def stats():
|
||||
return cache_stats()
|
||||
|
||||
|
||||
@app.post("/api/cache/refresh")
|
||||
def refresh():
|
||||
services.refrescar_todo()
|
||||
return {"status": "refrescado"}
|
||||
|
||||
|
||||
@app.get("/api/leads/filtros")
|
||||
def get_filtros():
|
||||
try:
|
||||
return services.opciones_filtros()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/leads")
|
||||
def get_leads(
|
||||
ano: str = Query("TODOS"),
|
||||
mes: str = Query("TODOS"),
|
||||
dia: str = Query("TODOS"),
|
||||
programa: str = Query("TODOS"),
|
||||
sede: str = Query("TODOS"),
|
||||
):
|
||||
try:
|
||||
return services.leads_dashboard(ano, mes, dia, programa, sede)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/otros-general")
|
||||
def get_otros_general(
|
||||
ano: str = Query("TODOS"),
|
||||
mes: str = Query("TODOS"),
|
||||
dia: str = Query("TODOS"),
|
||||
):
|
||||
try:
|
||||
return services.otros_general(ano, mes, dia)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/conjuntos-sin-pauta")
|
||||
def get_conjuntos_sin_pauta():
|
||||
try:
|
||||
return {"conjuntos": services.conjuntos_sin_pauta()}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/programas-ocultos")
|
||||
def get_programas_ocultos():
|
||||
try:
|
||||
return services.programas_ocultos()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.post("/api/programas-ocultos/encender")
|
||||
def post_encender_programas(body: dict = Body(...)):
|
||||
try:
|
||||
nis = body.get("num_indices") or []
|
||||
return services.encender_programas(nis)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/programas-disponibles")
|
||||
def get_programas_disponibles():
|
||||
try:
|
||||
return services.programas_disponibles()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/leyenda-anuncios")
|
||||
def get_leyenda():
|
||||
try:
|
||||
return services.leyenda_anuncios()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.post("/api/leyenda-anuncios/guardar")
|
||||
def post_leyenda(body: dict = Body(...)):
|
||||
try:
|
||||
cambios = body.get("cambios") or []
|
||||
return services.guardar_leyenda(cambios)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/pauta/uso")
|
||||
def get_uso_pauta(pauta: str = Query(...), excluir: str = Query("")):
|
||||
try:
|
||||
return services.uso_de_pauta(pauta, excluir)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.post("/api/curso/guardar-pauta")
|
||||
def post_guardar_pauta(body: dict = Body(...)):
|
||||
try:
|
||||
ni = str(body.get("num_indice", "")).strip()
|
||||
pa = str(body.get("pauta", "")).strip()
|
||||
cj = body.get("conjunto") or None
|
||||
contar = body.get("contar") # "SI" / "NO" / None
|
||||
if not ni:
|
||||
raise HTTPException(status_code=400, detail="num_indice es obligatorio")
|
||||
return services.guardar_edicion_curso(ni, pa, cj, contar)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/ultima-actualizacion")
|
||||
def get_ultima_actualizacion():
|
||||
try:
|
||||
return services.ultima_actualizacion()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/leads/alertas")
|
||||
def get_alertas():
|
||||
"""Valores de programa/sede en cartera_junta que NO están en el diccionario."""
|
||||
try:
|
||||
return services.alertas()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/debug/cursos")
|
||||
def debug_cursos(ano: str = "2026", mes: str = "1"):
|
||||
"""Diagnóstico: lista cursos del periodo con inscritos, tipo y meta."""
|
||||
try:
|
||||
return services.debug_cursos(ano, mes)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
port = int(os.getenv("PORT", "8001"))
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False)
|
||||
6
backend/requirements.txt
Normal file
6
backend/requirements.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
python-dotenv
|
||||
pyodbc
|
||||
psycopg2-binary
|
||||
requests
|
||||
984
backend/services.py
Normal file
984
backend/services.py
Normal file
@@ -0,0 +1,984 @@
|
||||
# backend/services.py
|
||||
"""Servicios: traen datos crudos (cacheados) y arman la respuesta del módulo Leads."""
|
||||
from data_manager_v2 import DataManager
|
||||
import leads_logic as L
|
||||
from cache_manager import cache_get_or_set
|
||||
|
||||
_DM = None
|
||||
|
||||
|
||||
def get_dm() -> DataManager:
|
||||
global _DM
|
||||
if _DM is None:
|
||||
_DM = DataManager()
|
||||
return _DM
|
||||
|
||||
|
||||
# ── Datos crudos cacheados (consultas pesadas, una sola vez) ────
|
||||
def _leads_crudos():
|
||||
return cache_get_or_set("leads_raw", ("GLOBAL",),
|
||||
lambda: L.procesar_leads(get_dm().traer_leads_chatwoot()))
|
||||
|
||||
|
||||
def _cursos_crudos():
|
||||
return cache_get_or_set("cursos_raw", ("GLOBAL",), lambda: get_dm().traer_cursos())
|
||||
|
||||
|
||||
def _matriculas_crudas():
|
||||
return cache_get_or_set("mat_raw", ("GLOBAL",), lambda: get_dm().traer_matriculas())
|
||||
|
||||
|
||||
def _pauta_cruda():
|
||||
return cache_get_or_set("pauta_raw", ("GLOBAL",), lambda: get_dm().traer_pauta_cursos())
|
||||
|
||||
|
||||
def _programa_pautas():
|
||||
"""{num_indice: [pautas]} desde la tabla programa_pautas (muchos-a-muchos)."""
|
||||
return cache_get_or_set("programa_pautas", ("GLOBAL",),
|
||||
lambda: get_dm().traer_programa_pautas())
|
||||
|
||||
|
||||
def _pautas_de_indice():
|
||||
"""{num_indice: [pautas]} combinando:
|
||||
- la pauta de basebi_programacion (1 por num_indice), y
|
||||
- las pautas extra de programa_pautas (varias).
|
||||
Sin duplicados. Un num_indice puede terminar con varias pautas que se SUMAN."""
|
||||
def _load():
|
||||
pm = _pauta_cruda() # {num_indice: {pauta,...}}
|
||||
extra = _programa_pautas() # {num_indice: [pautas]}
|
||||
out = {}
|
||||
for ni, info in pm.items():
|
||||
p = info.get("pauta")
|
||||
if p:
|
||||
out.setdefault(str(ni).strip(), []).append(str(p).strip())
|
||||
for ni, pautas in extra.items():
|
||||
lst = out.setdefault(str(ni).strip(), [])
|
||||
for p in pautas:
|
||||
if str(p).strip() not in lst:
|
||||
lst.append(str(p).strip())
|
||||
return out
|
||||
return cache_get_or_set("pautas_de_indice", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
def _campanias_map():
|
||||
return cache_get_or_set("campanias_map", ("GLOBAL",),
|
||||
lambda: get_dm().traer_campanias_map())
|
||||
|
||||
|
||||
def _conjunto_pauta():
|
||||
return cache_get_or_set("conjunto_pauta", ("GLOBAL",),
|
||||
lambda: get_dm().traer_conjunto_pauta())
|
||||
|
||||
|
||||
def _meta_filas():
|
||||
"""Filas crudas del CSV de Meta: [{conjunto, importe, inicio}, ...]."""
|
||||
return cache_get_or_set("meta_filas", ("GLOBAL",),
|
||||
lambda: get_dm().traer_meta_importe())
|
||||
|
||||
|
||||
def _importe_por_pauta():
|
||||
"""{pauta: importe_gastado_total} = suma del importe de TODAS las filas de los
|
||||
conjuntos ligados a esa pauta (conjunto_pauta × Meta CSV). Sin filtro de fecha."""
|
||||
def _load():
|
||||
conj_pauta = _conjunto_pauta() # {pauta: [conjunto,...]}
|
||||
imp_norm = {}
|
||||
for f in _meta_filas():
|
||||
k = " ".join(str(f.get("conjunto")).split()).upper()
|
||||
imp_norm[k] = imp_norm.get(k, 0.0) + float(f.get("importe") or 0.0)
|
||||
out = {}
|
||||
for pauta, conjuntos in conj_pauta.items():
|
||||
total = sum(imp_norm.get(" ".join(str(co).split()).upper(), 0.0) for co in conjuntos)
|
||||
out[str(pauta).strip()] = round(total, 2)
|
||||
return out
|
||||
return cache_get_or_set("importe_pauta", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
def _importe_por_pauta_periodo(ano, mes, dia):
|
||||
"""{pauta: importe} sumando solo las filas del CSV cuyo 'Inicio del informe'
|
||||
cae dentro del periodo filtrado (año/mes/día). Respeta el filtro de arriba."""
|
||||
def _load():
|
||||
conj_pauta = _conjunto_pauta()
|
||||
imp_norm = {}
|
||||
sin_filtro = (ano in ("TODOS", None) and mes in ("TODOS", None) and dia in ("TODOS", None))
|
||||
for f in _meta_filas():
|
||||
fx = L._to_date(f.get("inicio"))
|
||||
if sin_filtro:
|
||||
pass # sin filtro: cuenta todo (incluye filas sin fecha) = total
|
||||
elif not L._en_periodo(fx, ano, mes, dia):
|
||||
continue
|
||||
k = " ".join(str(f.get("conjunto")).split()).upper()
|
||||
imp_norm[k] = imp_norm.get(k, 0.0) + float(f.get("importe") or 0.0)
|
||||
out = {}
|
||||
for pauta, conjuntos in conj_pauta.items():
|
||||
total = sum(imp_norm.get(" ".join(str(co).split()).upper(), 0.0) for co in conjuntos)
|
||||
out[str(pauta).strip()] = round(total, 2)
|
||||
return out
|
||||
return cache_get_or_set("importe_pauta_periodo", (ano, mes, dia), _load)
|
||||
|
||||
|
||||
def _resultados_por_pauta_periodo(ano, mes, dia):
|
||||
"""{pauta: resultados} sumando solo las filas del CSV cuyo 'Inicio del informe'
|
||||
cae en el periodo filtrado. Analogo a _importe_por_pauta_periodo pero con Resultados."""
|
||||
def _load():
|
||||
conj_pauta = _conjunto_pauta()
|
||||
res_norm = {}
|
||||
sin_filtro = (ano in ("TODOS", None) and mes in ("TODOS", None) and dia in ("TODOS", None))
|
||||
for f in _meta_filas():
|
||||
if not sin_filtro and not L._en_periodo(L._to_date(f.get("inicio")), ano, mes, dia):
|
||||
continue
|
||||
k = " ".join(str(f.get("conjunto")).split()).upper()
|
||||
res_norm[k] = res_norm.get(k, 0.0) + float(f.get("resultados") or 0.0)
|
||||
out = {}
|
||||
for pauta, conjuntos in conj_pauta.items():
|
||||
total = sum(res_norm.get(" ".join(str(co).split()).upper(), 0.0) for co in conjuntos)
|
||||
out[str(pauta).strip()] = int(total)
|
||||
return out
|
||||
return cache_get_or_set("resultados_pauta_periodo", (ano, mes, dia), _load)
|
||||
|
||||
|
||||
def _campanias_sede_cargo():
|
||||
return cache_get_or_set("campanias_sc", ("GLOBAL",),
|
||||
lambda: get_dm().traer_campanias_sede_cargo())
|
||||
|
||||
|
||||
def matriz_always(ano="TODOS", mes="TODOS", dia="TODOS", sede="TODOS", programa="TODOS"):
|
||||
"""Matriz de gasto Meta Ads de pautas ALWAYS (con gasto pero SIN num_indice).
|
||||
Agrupa Sede -> Programa (TEAC/TERC/SEMINARIOS) con Importe, Resultados,
|
||||
Leads Nuevos (fecha_creada en el mes) y Leads Nuevos Asignados (con asesor).
|
||||
Sede/programa salen de la tabla campanias. Pautas sin campanias NO se cuentan."""
|
||||
def _load():
|
||||
conj_pauta = _conjunto_pauta() # {pauta: [conjuntos]}
|
||||
camp = _campanias_sede_cargo() # {pauta: {sede,cargo}}
|
||||
pauta_map = _pauta_cruda() # {num_indice: {pauta,...}}
|
||||
con_indice = {str(v.get("pauta")).strip() for v in pauta_map.values() if v.get("pauta")}
|
||||
|
||||
# Leads nuevos (unicos) por pauta = codigo, cuya fecha_creada cae en el mes filtrado
|
||||
leads = _leads_crudos()
|
||||
leads_nuevos = {} # codigo -> nº leads unicos del mes
|
||||
leads_nuevos_asig = {} # codigo -> nº leads unicos del mes con asesor
|
||||
tel_lead_mes = {} # telefono -> (codigo, fecha_creada) del lead unico del mes
|
||||
for l in leads:
|
||||
if not l.get("es_unico"):
|
||||
continue
|
||||
if not L._en_periodo(l.get("fecha"), ano, mes, dia):
|
||||
continue
|
||||
cod = str(l.get("codigo") or "").strip()
|
||||
if not cod:
|
||||
continue
|
||||
leads_nuevos[cod] = leads_nuevos.get(cod, 0) + 1
|
||||
if str(l.get("asesor") or "").strip():
|
||||
leads_nuevos_asig[cod] = leads_nuevos_asig.get(cod, 0) + 1
|
||||
tel = str(l.get("telefono") or "").strip()
|
||||
if tel:
|
||||
tel_lead_mes[tel] = (cod, l.get("fecha"))
|
||||
|
||||
# MATRICULAS por pauta: matriculas cuyo telefono = un lead nuevo del mes, y con
|
||||
# fch_matricula >= fecha_creada del lead. Cuenta CADA matricula (una vez c/u),
|
||||
# atribuida a la pauta del lead. Cruce por telefono (tel_1, o tel_2 si vacio).
|
||||
matriculas_pauta = {} # codigo -> nº matriculas
|
||||
venta_pauta = {} # codigo -> suma INV_NETA en soles (DOL ×3.34)
|
||||
_vistas = set() # (num_matricula) para no contar 2 veces
|
||||
for m in _matriculas_crudas():
|
||||
t1 = str(m.get("dsc_telefono_1") or "").strip()
|
||||
t2 = str(m.get("dsc_telefono_2") or "").strip()
|
||||
ph = t1 if t1 else t2
|
||||
if ph not in tel_lead_mes:
|
||||
continue
|
||||
cod, f_lead = tel_lead_mes[ph]
|
||||
fm = L._to_date(m.get("fch_matricula"))
|
||||
if not fm or not f_lead or fm < f_lead:
|
||||
continue # matricula anterior al ingreso del lead -> no cuenta
|
||||
nm = str(m.get("num_matricula"))
|
||||
if nm in _vistas:
|
||||
continue
|
||||
_vistas.add(nm)
|
||||
matriculas_pauta[cod] = matriculas_pauta.get(cod, 0) + 1
|
||||
# INV_NETA en soles: si moneda DOL, ×3.34 (igual que tabla por Sede)
|
||||
try:
|
||||
inv = float(m.get("INV_NETA", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
inv = 0.0
|
||||
if str(m.get("cod_moneda", "")).strip().upper() == "DOL":
|
||||
inv *= 3.34
|
||||
venta_pauta[cod] = venta_pauta.get(cod, 0.0) + inv
|
||||
|
||||
# Importe y Resultados por conjunto, filtrando por el MES de arriba
|
||||
imp = {}; res = {}
|
||||
sin_filtro = (ano in ("TODOS", None) and mes in ("TODOS", None) and dia in ("TODOS", None))
|
||||
for f in _meta_filas():
|
||||
if not sin_filtro and not L._en_periodo(L._to_date(f.get("inicio")), ano, mes, dia):
|
||||
continue
|
||||
k = " ".join(str(f.get("conjunto")).split()).upper()
|
||||
imp[k] = imp.get(k, 0.0) + float(f.get("importe") or 0.0)
|
||||
res[k] = res.get(k, 0.0) + float(f.get("resultados") or 0.0)
|
||||
|
||||
# Acumular por Sede -> Programa -> Pauta (solo pautas ALWAYS que esten en campanias)
|
||||
from collections import defaultdict
|
||||
grupos = defaultdict(lambda: defaultdict(lambda: {"importe": 0.0, "resultados": 0.0,
|
||||
"nuevos": 0, "nuevos_asig": 0,
|
||||
"matriculas": 0, "venta": 0.0, "pautas": []}))
|
||||
for pauta, conjuntos in conj_pauta.items():
|
||||
p = str(pauta).strip()
|
||||
if p in con_indice: # tiene num_indice -> NO es always
|
||||
continue
|
||||
info = camp.get(p)
|
||||
if not info: # no esta en campanias -> no se cuenta
|
||||
continue
|
||||
se = str(info.get("sede") or "").upper()
|
||||
gr = L.grupo_programa_lead(info.get("cargo")) # TEAC/TERC/SEMINARIOS
|
||||
ti = sum(imp.get(" ".join(str(c).split()).upper(), 0.0) for c in conjuntos)
|
||||
tr = sum(res.get(" ".join(str(c).split()).upper(), 0.0) for c in conjuntos)
|
||||
if ti == 0 and tr == 0:
|
||||
continue # sin gasto en el mes -> no aparece
|
||||
# filtros de arriba
|
||||
if sede not in ("TODOS", None) and se != str(sede).upper():
|
||||
continue
|
||||
if programa not in ("TODOS", None) and gr != str(programa).upper():
|
||||
continue
|
||||
nv = leads_nuevos.get(p, 0)
|
||||
na = leads_nuevos_asig.get(p, 0)
|
||||
mt = matriculas_pauta.get(p, 0)
|
||||
vv = venta_pauta.get(p, 0.0)
|
||||
g = grupos[se][gr]
|
||||
g["importe"] += ti
|
||||
g["resultados"] += tr
|
||||
g["nuevos"] += nv
|
||||
g["nuevos_asig"] += na
|
||||
g["matriculas"] += mt
|
||||
g["venta"] += vv
|
||||
g["pautas"].append({"pauta": p, "importe": round(ti, 2), "resultados": int(tr),
|
||||
"nuevos": nv, "nuevos_asig": na, "matriculas": mt,
|
||||
"venta": round(vv, 0)})
|
||||
|
||||
# Armar filas: Sede -> subfilas por programa -> pautas (solo con gasto)
|
||||
filas = []
|
||||
for se in sorted(grupos.keys()):
|
||||
subs = []
|
||||
s_imp = s_res = 0.0; s_nv = s_na = s_mt = 0; s_vv = 0.0
|
||||
for gr in ("TEAC", "TERC", "SEMINARIOS"):
|
||||
if gr in grupos[se]:
|
||||
d = grupos[se][gr]
|
||||
pautas = sorted(d["pautas"], key=lambda x: -x["importe"])
|
||||
subs.append({"programa": gr, "importe": round(d["importe"], 2),
|
||||
"resultados": int(d["resultados"]),
|
||||
"nuevos": d["nuevos"], "nuevos_asig": d["nuevos_asig"],
|
||||
"matriculas": d["matriculas"], "venta": round(d["venta"], 0),
|
||||
"pautas": pautas})
|
||||
s_imp += d["importe"]; s_res += d["resultados"]
|
||||
s_nv += d["nuevos"]; s_na += d["nuevos_asig"]; s_mt += d["matriculas"]; s_vv += d["venta"]
|
||||
filas.append({"sede": se, "importe": round(s_imp, 2), "resultados": int(s_res),
|
||||
"nuevos": s_nv, "nuevos_asig": s_na, "matriculas": s_mt,
|
||||
"venta": round(s_vv, 0), "subfilas": subs})
|
||||
tot_i = round(sum(f["importe"] for f in filas), 2)
|
||||
tot_r = int(sum(f["resultados"] for f in filas))
|
||||
tot_nv = sum(f["nuevos"] for f in filas)
|
||||
tot_na = sum(f["nuevos_asig"] for f in filas)
|
||||
tot_mt = sum(f["matriculas"] for f in filas)
|
||||
tot_vv = round(sum(f["venta"] for f in filas), 0)
|
||||
return {"filas": filas, "total": {"importe": tot_i, "resultados": tot_r,
|
||||
"nuevos": tot_nv, "nuevos_asig": tot_na,
|
||||
"matriculas": tot_mt, "venta": tot_vv}}
|
||||
|
||||
return cache_get_or_set("matriz_always", (ano, mes, dia, sede, programa), _load)
|
||||
|
||||
|
||||
def matriz_web_formulario(ano="TODOS", mes="TODOS", dia="TODOS", sede="TODOS", programa="TODOS"):
|
||||
"""Matriz de leads con canal WEB_FORMULARIO (cartera_junta), agrupados Sede -> Programa.
|
||||
Valores: Leads Recibidos (todos), Leads Procesados (con asesor), Matriculas y
|
||||
Valor Venta (cruce por telefono, fch_matricula >= fecha_creada del lead)."""
|
||||
def _load():
|
||||
rows = _cartera_rows_cache()
|
||||
# 1) leads WEB_FORMULARIO cuya fila es el ORIGEN del telefono en TODA la cartera
|
||||
# (es_origen=SI) y con fecha_creada en el periodo. Asi NO cuenta si el telefono
|
||||
# ya vino antes por otro canal (igual criterio que las demas tablas).
|
||||
vistos = {} # telefono -> {fecha, sede, prog, asesor}
|
||||
for r in rows:
|
||||
if str(r.get("canal") or "").strip().upper() != "WEB_FORMULARIO":
|
||||
continue
|
||||
if str(r.get("es_origen") or "").strip().upper() != "SI":
|
||||
continue # solo el origen real del telefono
|
||||
tel = str(r.get("telefono") or "").strip()
|
||||
if not tel:
|
||||
continue
|
||||
f = L._to_date(r.get("fecha_creada"))
|
||||
if not L._en_periodo(f, ano, mes, dia):
|
||||
continue
|
||||
# sede y programa YA vienen normalizados en cartera_junta. Reducir a 4 grupos.
|
||||
se = " ".join(str(r.get("sede") or "").upper().split()) or "SIN SEDE"
|
||||
pr = " ".join(str(r.get("programa") or "").upper().split())
|
||||
if pr == "TEAC":
|
||||
gr = "TEAC"
|
||||
elif pr == "TERC":
|
||||
gr = "TERC"
|
||||
elif pr in ("SEMINARIOS", "VRF", "CO2", "DIPLOMADO", "VENTILACIÓN", "VENTILACION"):
|
||||
gr = "SEMINARIOS"
|
||||
else:
|
||||
gr = "OTROS"
|
||||
vistos[tel] = {"fecha": f, "sede": se, "prog": gr,
|
||||
"asesor": str(r.get("asesor") or "").strip()}
|
||||
|
||||
# 2) matriculas por telefono (num_matricula, fecha, inv en soles)
|
||||
from collections import defaultdict
|
||||
mat_por_tel = defaultdict(list)
|
||||
for m in _matriculas_crudas():
|
||||
t1 = str(m.get("dsc_telefono_1") or "").strip()
|
||||
t2 = str(m.get("dsc_telefono_2") or "").strip()
|
||||
ph = t1 if t1 else t2
|
||||
if not ph:
|
||||
continue
|
||||
fm = L._to_date(m.get("fch_matricula"))
|
||||
try:
|
||||
inv = float(m.get("INV_NETA", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
inv = 0.0
|
||||
if str(m.get("cod_moneda", "")).strip().upper() == "DOL":
|
||||
inv *= 3.34
|
||||
mat_por_tel[ph].append((str(m.get("num_matricula")), fm, inv))
|
||||
|
||||
# 3) agrupar Sede -> Programa
|
||||
grupos = defaultdict(lambda: defaultdict(lambda: {"recibidos": 0, "procesados": 0,
|
||||
"matriculas": 0, "venta": 0.0}))
|
||||
for tel, info in vistos.items():
|
||||
se = info["sede"]; gr = info["prog"]; f_lead = info["fecha"]
|
||||
if sede not in ("TODOS", None) and se != str(sede).upper():
|
||||
continue
|
||||
if programa not in ("TODOS", None) and gr != str(programa).upper():
|
||||
continue
|
||||
g = grupos[se][gr]
|
||||
g["recibidos"] += 1
|
||||
if info["asesor"]:
|
||||
g["procesados"] += 1
|
||||
for (nm, fm, inv) in mat_por_tel.get(tel, []):
|
||||
if fm and f_lead and fm >= f_lead:
|
||||
g["matriculas"] += 1
|
||||
g["venta"] += inv
|
||||
|
||||
# 4) filas
|
||||
filas = []
|
||||
for se in sorted(grupos.keys()):
|
||||
subs = []
|
||||
s_rec = s_proc = s_mt = 0; s_vv = 0.0
|
||||
for gr in ("TEAC", "TERC", "SEMINARIOS", "OTROS"):
|
||||
if gr in grupos[se]:
|
||||
d = grupos[se][gr]
|
||||
subs.append({"programa": gr, "recibidos": d["recibidos"],
|
||||
"procesados": d["procesados"], "matriculas": d["matriculas"],
|
||||
"venta": round(d["venta"], 0)})
|
||||
s_rec += d["recibidos"]; s_proc += d["procesados"]
|
||||
s_mt += d["matriculas"]; s_vv += d["venta"]
|
||||
filas.append({"sede": se, "recibidos": s_rec, "procesados": s_proc,
|
||||
"matriculas": s_mt, "venta": round(s_vv, 0), "subfilas": subs})
|
||||
tot = {"recibidos": sum(f["recibidos"] for f in filas),
|
||||
"procesados": sum(f["procesados"] for f in filas),
|
||||
"matriculas": sum(f["matriculas"] for f in filas),
|
||||
"venta": round(sum(f["venta"] for f in filas), 0)}
|
||||
return {"filas": filas, "total": tot}
|
||||
|
||||
return cache_get_or_set("matriz_webform", (ano, mes, dia, sede, programa), _load)
|
||||
|
||||
|
||||
def _leads_asignados_crudos():
|
||||
return cache_get_or_set("leads_asignados", ("GLOBAL",),
|
||||
lambda: get_dm().traer_leads_asignados())
|
||||
|
||||
|
||||
def matriz_asignados(ano="TODOS", mes="TODOS", dia="TODOS"):
|
||||
"""Matriz pivot: filas = asesor (user_name) con sus telefonos; columnas = dias del
|
||||
mes; valor = cantidad de telefonos asignados a ese asesor ese dia.
|
||||
Fecha = created_at del mensaje de asignacion (ya con -5h)."""
|
||||
def _load():
|
||||
import calendar
|
||||
from collections import defaultdict
|
||||
rows = _leads_asignados_crudos()
|
||||
# dias del mes filtrado (columnas)
|
||||
if mes not in ("TODOS", None) and ano not in ("TODOS", None):
|
||||
ndias = calendar.monthrange(int(ano), int(mes))[1]
|
||||
dias_cols = list(range(1, ndias + 1))
|
||||
else:
|
||||
dias_cols = list(range(1, 32))
|
||||
|
||||
# asesores excluidos de esta matriz
|
||||
EXCLUIR = {"SIN ASESOR", "COPITO RIVERA"}
|
||||
# asesor -> dia -> [telefonos]
|
||||
por = defaultdict(lambda: defaultdict(list))
|
||||
for r in rows:
|
||||
f = L._to_date(r.get("created_at"))
|
||||
if not L._en_periodo(f, ano, mes, dia):
|
||||
continue
|
||||
ase = str(r.get("user_name") or "Sin Asesor").strip() or "Sin Asesor"
|
||||
if ase.upper() in EXCLUIR:
|
||||
continue
|
||||
tel = str(r.get("telefono") or "").strip()
|
||||
por[ase][f.day].append(tel)
|
||||
|
||||
filas = []
|
||||
tot_por_dia = defaultdict(int)
|
||||
for ase in sorted(por.keys()):
|
||||
pordia = {d: len(por[ase].get(d, [])) for d in dias_cols}
|
||||
total = sum(pordia.values())
|
||||
# telefonos por dia (para expandir con +)
|
||||
tels_dia = {d: sorted(por[ase].get(d, [])) for d in dias_cols if por[ase].get(d)}
|
||||
for d, n in pordia.items():
|
||||
tot_por_dia[d] += n
|
||||
filas.append({"asesor": ase, "por_dia": pordia, "total": total, "tels_dia": tels_dia})
|
||||
filas.sort(key=lambda x: -x["total"])
|
||||
total_gral = sum(f["total"] for f in filas)
|
||||
return {"dias": dias_cols, "filas": filas,
|
||||
"total_por_dia": {d: tot_por_dia.get(d, 0) for d in dias_cols},
|
||||
"total": total_gral}
|
||||
return cache_get_or_set("matriz_asignados", (ano, mes, dia), _load)
|
||||
|
||||
|
||||
def _plantillas_crudas():
|
||||
return cache_get_or_set("plantillas_raw", ("GLOBAL",),
|
||||
lambda: get_dm().traer_plantillas())
|
||||
|
||||
|
||||
def matriz_plantillas(ano="TODOS", mes="TODOS", dia="TODOS"):
|
||||
"""Matriz de plantillas COBRADAS por plantilla. Columnas:
|
||||
ENVIADAS = Mas_de_24h=SI, created_at_peru en el periodo filtrado
|
||||
RESPONDIDAS= de esas, con respuesta del contacto (siguiente_mensaje_1)
|
||||
ASIGNADAS = de esas, con asesor Y respondida por el contacto
|
||||
MATRICULAS = matriculas de esos telefonos (fch_matricula >= envio mas antiguo). Sin filtro de mes.
|
||||
VENTA = INV_NETA (DOL x3.34) de esas matriculas."""
|
||||
from datetime import timedelta, datetime
|
||||
from collections import defaultdict
|
||||
|
||||
def _load():
|
||||
rows = _plantillas_crudas()
|
||||
UMBRAL = timedelta(hours=24)
|
||||
|
||||
def _lleno(s):
|
||||
return s is not None and str(s).strip() != ""
|
||||
|
||||
enviadas = defaultdict(int)
|
||||
respondidas = defaultdict(int)
|
||||
asignadas = defaultdict(int)
|
||||
prim_por_tel = {} # telefono -> (fecha_envio, plantilla) la cobrada mas antigua DEL PERIODO
|
||||
|
||||
for r in rows:
|
||||
plantilla = r.get("plantilla")
|
||||
envio = r.get("created_at_peru")
|
||||
f = L._to_date(envio)
|
||||
# ENVIADAS/RESP/ASIG respetan el filtro de mes (por created_at_peru)
|
||||
if not L._en_periodo(f, ano, mes, dia):
|
||||
continue
|
||||
anterior = r.get("hora_anterior_contacto")
|
||||
sig = r.get("siguiente_mensaje_1")
|
||||
es_si = False
|
||||
if plantilla == "descuento_egresados_seminarios":
|
||||
es_si = True
|
||||
elif anterior is not None and (envio - anterior) > UMBRAL:
|
||||
es_si = True
|
||||
if not es_si:
|
||||
continue
|
||||
enviadas[plantilla] += 1
|
||||
if _lleno(sig):
|
||||
respondidas[plantilla] += 1
|
||||
if _lleno(r.get("user_name")) and _lleno(sig):
|
||||
asignadas[plantilla] += 1
|
||||
tel = str(r.get("telefono") or "").strip()
|
||||
if tel and envio is not None:
|
||||
if tel not in prim_por_tel or envio < prim_por_tel[tel][0]:
|
||||
prim_por_tel[tel] = (envio, plantilla)
|
||||
|
||||
# MATRICULAS + VENTA de los telefonos filtrados (sin filtro de mes en la matricula)
|
||||
mat_por_tel = defaultdict(list)
|
||||
for m in _matriculas_crudas():
|
||||
t1 = str(m.get("dsc_telefono_1") or "").strip()
|
||||
t2 = str(m.get("dsc_telefono_2") or "").strip()
|
||||
ph = t1 if t1 else t2
|
||||
if not ph:
|
||||
continue
|
||||
fm = m.get("fch_matricula")
|
||||
if isinstance(fm, datetime): fm = fm.date()
|
||||
try:
|
||||
inv = float(m.get("INV_NETA", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
inv = 0.0
|
||||
if str(m.get("cod_moneda", "")).strip().upper() == "DOL":
|
||||
inv *= 3.34
|
||||
mat_por_tel[ph].append((str(m.get("num_matricula")), fm, inv))
|
||||
|
||||
matriculas = defaultdict(int)
|
||||
venta = defaultdict(float)
|
||||
_vistas = set()
|
||||
for tel, (fenvio, plantilla) in prim_por_tel.items():
|
||||
fenvio_d = fenvio.date() if hasattr(fenvio, "date") else fenvio
|
||||
for (nm, fm, inv) in mat_por_tel.get(tel, []):
|
||||
if not fm or nm in _vistas:
|
||||
continue
|
||||
if fm >= fenvio_d:
|
||||
_vistas.add(nm)
|
||||
matriculas[plantilla] += 1
|
||||
venta[plantilla] += inv
|
||||
|
||||
filas = []
|
||||
for p in sorted(enviadas.keys(), key=lambda x: -enviadas[x]):
|
||||
filas.append({"plantilla": p, "enviadas": enviadas[p],
|
||||
"respondidas": respondidas.get(p, 0),
|
||||
"asignadas": asignadas.get(p, 0),
|
||||
"matriculas": matriculas.get(p, 0),
|
||||
"venta": round(venta.get(p, 0.0), 0)})
|
||||
tot = {"enviadas": sum(enviadas.values()), "respondidas": sum(respondidas.values()),
|
||||
"asignadas": sum(asignadas.values()), "matriculas": sum(matriculas.values()),
|
||||
"venta": round(sum(venta.values()), 0)}
|
||||
return {"filas": filas, "total": tot}
|
||||
|
||||
return cache_get_or_set("matriz_plantillas", (ano, mes, dia), _load)
|
||||
|
||||
|
||||
def _norm_ni(x):
|
||||
"""Normaliza num_indice a texto (quita el '.0' si viniera como float)."""
|
||||
s = str(x or "").strip()
|
||||
return s[:-2] if s.endswith(".0") else s
|
||||
|
||||
|
||||
def _mat_por_indice():
|
||||
"""{num_indice: [(telefono_resuelto, fecha_matricula), ...]} desde las matrículas.
|
||||
Teléfono resuelto = dsc_telefono_1 si existe; si no, dsc_telefono_2."""
|
||||
def _load():
|
||||
from collections import defaultdict
|
||||
out = defaultdict(list)
|
||||
for m in _matriculas_crudas():
|
||||
ni = _norm_ni(m.get("num_indice"))
|
||||
t1 = str(m.get("dsc_telefono_1") or "").strip()
|
||||
t2 = str(m.get("dsc_telefono_2") or "").strip()
|
||||
fm = L._to_date(m.get("fch_matricula"))
|
||||
out[ni].append((t1 if t1 else t2, fm))
|
||||
return out
|
||||
return cache_get_or_set("mat_por_indice", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
def _cartera_rows_cache():
|
||||
"""Filas crudas de cartera_junta cacheadas (se bajan de Supabase UNA sola vez).
|
||||
Evita re-descargar las 86k filas en cada llamada/cambio de mes."""
|
||||
return cache_get_or_set("cartera_rows", ("GLOBAL",),
|
||||
lambda: get_dm().traer_cartera_rows())
|
||||
|
||||
|
||||
def _cartera_idx():
|
||||
"""Devuelve {'all':..., 'asig':...}, cada uno {(sede,programa):{telefono:fecha_min}}.
|
||||
'all' = todos los teléfonos; 'asig' = solo los que tienen asesor (no vacío).
|
||||
Se baja la cartera UNA vez y queda cacheado."""
|
||||
def _load():
|
||||
from collections import defaultdict
|
||||
CANAL_PAUTA = {"COPITO", "PAUTA_WSP", "PAUTA_WSP_FACE"}
|
||||
CANAL_WEB = {"WEB_FORMULARIO", "WEB_WHATSAPP", "WHATSAPP WEB"}
|
||||
|
||||
def _clase(canal):
|
||||
if canal in CANAL_PAUTA: return "PAUTA"
|
||||
if canal in CANAL_WEB: return "WEB"
|
||||
return "OTROS"
|
||||
|
||||
# PASO 1: DEDUP por (sede, prog, telefono) -> quedarse con la fila mas antigua.
|
||||
# Se guarda la fecha, si tiene asesor, y el CANAL de esa fila ganadora.
|
||||
# (Asi el canal de PAUTA/OTROS se decide DESPUES de deduplicar, como pide el usuario.)
|
||||
ganador = {} # (sede, prog, tel) -> {"f":fecha, "asesor":bool, "canal":canal}
|
||||
tels = set()
|
||||
tels_canal = {} # telefono -> canal de su fila ganadora GLOBAL (para matriculas)
|
||||
gan_global = {} # telefono -> fecha ganadora global (para decidir canal de matriculas)
|
||||
origen = {}
|
||||
for r in _cartera_rows_cache():
|
||||
tel = str(r.get("telefono") or "").strip()
|
||||
if not tel:
|
||||
continue
|
||||
tels.add(tel)
|
||||
sede = " ".join(str(r.get("sede") or "").upper().split())
|
||||
prog = " ".join(str(r.get("programa") or "").upper().split())
|
||||
canal = " ".join(str(r.get("canal") or "").upper().split())
|
||||
f = L._to_date(r.get("fecha_creada"))
|
||||
if str(r.get("es_origen") or "").upper() == "SI" and f is not None:
|
||||
origen[tel] = f
|
||||
if f is None:
|
||||
continue
|
||||
con_asesor = bool(str(r.get("asesor") or "").strip())
|
||||
# ganador por sede+prog+tel (para la tabla)
|
||||
k = (sede, prog, tel)
|
||||
g = ganador.get(k)
|
||||
if g is None or f < g["f"]:
|
||||
ganador[k] = {"f": f, "asesor": con_asesor, "canal": canal}
|
||||
# ganador global por tel (para clasificar matriculas por canal)
|
||||
if tel not in gan_global or f < gan_global[tel]:
|
||||
gan_global[tel] = f
|
||||
tels_canal[tel] = canal
|
||||
|
||||
# PASO 2: armar indices con la fila ganadora ya deduplicada
|
||||
idx_all = defaultdict(dict); idx_asig = defaultdict(dict)
|
||||
# por clase (PAUTA/WEB/OTROS): {clase: {"all":..,"asig":..}}
|
||||
CLASES = ("PAUTA", "WEB", "OTROS")
|
||||
idx_cl = {cl: {"all": defaultdict(dict), "asig": defaultdict(dict)} for cl in CLASES}
|
||||
tels_cl = {cl: set() for cl in CLASES}
|
||||
for (sede, prog, tel), g in ganador.items():
|
||||
f = g["f"]; cl = _clase(g["canal"])
|
||||
idx_all[(sede, prog)][tel] = f
|
||||
if g["asesor"]: idx_asig[(sede, prog)][tel] = f
|
||||
idx_cl[cl]["all"][(sede, prog)][tel] = f
|
||||
if g["asesor"]: idx_cl[cl]["asig"][(sede, prog)][tel] = f
|
||||
# telefonos por clase (segun ganador GLOBAL) para matriculas
|
||||
for tel, canal in tels_canal.items():
|
||||
tels_cl[_clase(canal)].add(tel)
|
||||
|
||||
out = {"all": idx_all, "asig": idx_asig, "tels": tels, "origen": origen}
|
||||
for cl in CLASES:
|
||||
out[f"all_{cl.lower()}"] = idx_cl[cl]["all"]
|
||||
out[f"asig_{cl.lower()}"] = idx_cl[cl]["asig"]
|
||||
out[f"tels_{cl.lower()}"] = tels_cl[cl]
|
||||
return out
|
||||
return cache_get_or_set("cartera_idx", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
# ── Respuesta del dashboard de Leads (con filtros) ──────────────
|
||||
def leads_dashboard(ano="TODOS", mes="TODOS", dia="TODOS", programa="TODOS", sede="TODOS"):
|
||||
def _load():
|
||||
leads = _leads_crudos()
|
||||
cursos = _cursos_crudos()
|
||||
mats = _matriculas_crudas()
|
||||
|
||||
# Filtro por PROGRAMA (4 grupos: TEAC / TERC / SEMINARIOS / OTROS).
|
||||
# Recalcula toda la pantalla filtrando las listas base ANTES de calcular.
|
||||
# - leads: grupo por 'cargo' del código de campaña
|
||||
# - cursos y matrículas: grupo por dsc_programa
|
||||
if programa not in ("TODOS", None):
|
||||
g = str(programa).upper()
|
||||
leads = [l for l in leads if L.grupo_programa_lead(l.get("cargo")) == g]
|
||||
cursos = [c for c in cursos if L.grupo_programa_curso(c.get("dsc_programa")) == g]
|
||||
mats = [m for m in mats if L.grupo_programa_curso(m.get("dsc_programa")) == g]
|
||||
|
||||
# Filtro por SEDE (recalcula toda la pantalla). Se filtran las listas base
|
||||
# ANTES de calcular, para no tocar las funciones de cálculo existentes.
|
||||
# - leads: sede POR CÓDIGO de campaña (NO sede_act; coincide con conteo real)
|
||||
# - cursos y matrículas: sede por clasificar_sede(dsc_programa)
|
||||
if sede not in ("TODOS", None):
|
||||
s = str(sede).upper()
|
||||
sede_cod = L.sede_por_codigo_map()
|
||||
leads = [l for l in leads
|
||||
if sede_cod.get(str(l.get("codigo") or "").strip()) == s]
|
||||
cursos = [c for c in cursos if L.clasificar_sede(c.get("dsc_programa")) == s]
|
||||
mats = [m for m in mats if L.clasificar_sede(m.get("dsc_programa")) == s]
|
||||
|
||||
kpis = L.kpis_leads(leads, cursos, mats, ano, mes, dia)
|
||||
tabla = L.tabla_estado_objecion(leads, ano, mes, dia)
|
||||
por_dia = L.matriculas_por_dia(mats, cursos, ano, mes, dia)
|
||||
leads_dia = L.leads_por_dia(leads, ano, mes, dia)
|
||||
pauta = L.tabla_pauta(leads, mats, ano, mes, dia,
|
||||
_importe_por_pauta_periodo(ano, mes, dia),
|
||||
_resultados_por_pauta_periodo(ano, mes, dia),
|
||||
_campanias_sede_cargo())
|
||||
ci = _cartera_idx()
|
||||
cartera_canal = {
|
||||
"PAUTA": {"all": ci.get("all_pauta"), "asig": ci.get("asig_pauta"), "tels": ci.get("tels_pauta")},
|
||||
"WEB": {"all": ci.get("all_web"), "asig": ci.get("asig_web"), "tels": ci.get("tels_web")},
|
||||
"OTROS": {"all": ci.get("all_otros"), "asig": ci.get("asig_otros"), "tels": ci.get("tels_otros")},
|
||||
}
|
||||
matriz = L.matriz_cursos(cursos, leads, ano, mes, dia, _pauta_cruda(),
|
||||
_campanias_map(), ci.get("all"), ci.get("asig"),
|
||||
_mat_por_indice(), ci.get("tels"), ci.get("origen"),
|
||||
_importe_por_pauta(),
|
||||
_importe_por_pauta_periodo(ano, mes, dia),
|
||||
cartera_canal, _conjunto_pauta(), _pautas_de_indice())
|
||||
return {"kpis": kpis, "estado_objecion": tabla, "matriculas_por_dia": por_dia,
|
||||
"leads_por_dia": leads_dia, "tabla_pauta": pauta, "matriz_cursos": matriz}
|
||||
|
||||
return cache_get_or_set("leads_dash", (ano, mes, dia, programa, sede), _load)
|
||||
|
||||
|
||||
def otros_general(ano="TODOS", mes="TODOS", dia="TODOS"):
|
||||
"""Solo las 4 matrices de la pagina 'Otros General' (sin KPIs/graficos/tabla_pauta).
|
||||
Mas liviano que leads_dashboard -> filtrar por mes es mas rapido."""
|
||||
def _load():
|
||||
return {
|
||||
"matriz_always": matriz_always(ano, mes, dia, "TODOS", "TODOS"),
|
||||
"matriz_webform": matriz_web_formulario(ano, mes, dia, "TODOS", "TODOS"),
|
||||
"matriz_asignados": matriz_asignados(ano, mes, dia),
|
||||
"matriz_plantillas": matriz_plantillas(ano, mes, dia),
|
||||
}
|
||||
return cache_get_or_set("otros_general", (ano, mes, dia), _load)
|
||||
|
||||
|
||||
def conjuntos_sin_pauta():
|
||||
"""Lista de conjuntos de anuncios sin pauta (para el desplegable del pop-up)."""
|
||||
return get_dm().traer_conjuntos_sin_pauta()
|
||||
|
||||
|
||||
def programas_ocultos():
|
||||
"""Programas con contar=NO en basebi_programacion (ocultos de la matriz).
|
||||
Cada item: {num_indice, dsc_det_programa, fch_inicio, pauta}."""
|
||||
pm = _pauta_cruda()
|
||||
ocultos_ni = {ni for ni, info in pm.items() if str(info.get("contar") or "").upper() == "NO"}
|
||||
prog_de_ni = {}
|
||||
fch_de_ni = {}
|
||||
for c in _cursos_crudos():
|
||||
ni = _norm_ni(c.get("num_indice"))
|
||||
prog_de_ni[ni] = str(c.get("dsc_det_programa") or c.get("dsc_programa") or "").strip()
|
||||
f = L._to_date(c.get("fch_inicio"))
|
||||
fch_de_ni[ni] = f.strftime("%d/%m/%Y") if f else ""
|
||||
filas = []
|
||||
for ni in ocultos_ni:
|
||||
filas.append({"num_indice": ni,
|
||||
"dsc_det_programa": prog_de_ni.get(ni, "(sin nombre)"),
|
||||
"fch_inicio": fch_de_ni.get(ni, ""),
|
||||
"pauta": (pm.get(ni) or {}).get("pauta") or ""})
|
||||
filas.sort(key=lambda x: x["dsc_det_programa"])
|
||||
return {"filas": filas}
|
||||
|
||||
|
||||
def encender_programas(num_indices):
|
||||
"""Pone contar=SI a los num_indice dados en basebi_programacion (los reactiva)."""
|
||||
from cache_manager import cache_invalidate
|
||||
dm = get_dm()
|
||||
for ni in num_indices:
|
||||
dm.guardar_pauta_basebi(ni, "", "SI") # pauta vacia -> no toca pauta, solo contar
|
||||
for pref in ("pauta_raw", "leads_dash", "otros_general", "leads_filtros"):
|
||||
cache_invalidate(pref)
|
||||
return {"encendidos": len(num_indices)}
|
||||
|
||||
|
||||
def programas_disponibles():
|
||||
"""Lista de dsc_det_programa de cursos con fch_inicio >= 2026-01-01 (para el
|
||||
desplegable de Programa en la Leyenda). Cada item: {num_indice, dsc_det_programa}."""
|
||||
from datetime import date
|
||||
corte = date(2026, 1, 1)
|
||||
vistos = {}
|
||||
for c in _cursos_crudos():
|
||||
f = L._to_date(c.get("fch_inicio"))
|
||||
if not f or f < corte:
|
||||
continue
|
||||
ni = _norm_ni(c.get("num_indice"))
|
||||
nombre = str(c.get("dsc_det_programa") or c.get("dsc_programa") or "").strip()
|
||||
if not nombre:
|
||||
continue
|
||||
finicio = f.strftime("%d/%m/%Y")
|
||||
label = f"{nombre} · {finicio}"
|
||||
vistos[ni] = {"num_indice": ni, "dsc_det_programa": nombre,
|
||||
"fch_inicio": finicio, "label": label}
|
||||
filas = sorted(vistos.values(), key=lambda x: x["label"])
|
||||
return {"programas": filas}
|
||||
|
||||
|
||||
def leyenda_anuncios():
|
||||
"""Tabla: todos los conjuntos del Sheet con su pauta (si tiene) y el programa
|
||||
(dsc_det_programa) del num_indice que usa esa pauta. Cacheado (usa insumos ya
|
||||
en memoria) para que abrir la Leyenda sea rapido."""
|
||||
def _load():
|
||||
conj_pauta = _conjunto_pauta() # cacheado
|
||||
pauta_de_conj = {}
|
||||
for pa, cjs in conj_pauta.items():
|
||||
for c in cjs:
|
||||
pauta_de_conj[" ".join(str(c).split())] = str(pa).strip()
|
||||
# pauta -> [num_indices] usando TODAS las vinculaciones (basebi + programa_pautas)
|
||||
ni_de_pauta = {}
|
||||
for ni, pautas in _pautas_de_indice().items():
|
||||
for p in pautas:
|
||||
ni_de_pauta.setdefault(str(p).strip(), []).append(str(ni).strip())
|
||||
prog_de_ni = {}
|
||||
for c in _cursos_crudos(): # cacheado
|
||||
prog_de_ni[_norm_ni(c.get("num_indice"))] = str(c.get("dsc_det_programa") or c.get("dsc_programa") or "").strip()
|
||||
def _programa(pauta):
|
||||
if not pauta:
|
||||
return ""
|
||||
nis = ni_de_pauta.get(str(pauta).strip(), [])
|
||||
nombres = [prog_de_ni.get(n, "") for n in nis if prog_de_ni.get(n)]
|
||||
return " | ".join(sorted(set(nombres)))
|
||||
filas = []
|
||||
vistos = set()
|
||||
for f in _meta_filas(): # cacheado (CSV de Meta)
|
||||
co = " ".join(str(f.get("conjunto")).split())
|
||||
if not co or co in vistos:
|
||||
continue
|
||||
vistos.add(co)
|
||||
pa = pauta_de_conj.get(co, "")
|
||||
filas.append({"conjunto": co, "pauta": pa, "programa": _programa(pa)})
|
||||
filas.sort(key=lambda x: x["conjunto"])
|
||||
return {"filas": filas}
|
||||
return cache_get_or_set("leyenda_anuncios", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
def guardar_leyenda(cambios):
|
||||
"""cambios = [{conjunto, pauta, num_indice?}].
|
||||
- conjunto -> pauta: upsert en conjunto_pauta.
|
||||
- si viene num_indice: conecta ese num_indice a la pauta en basebi_programacion.
|
||||
Invalida solo cachés dependientes de pauta/conjunto (no la cartera)."""
|
||||
from cache_manager import cache_invalidate
|
||||
dm = get_dm()
|
||||
for c in cambios:
|
||||
conjunto = c.get("conjunto")
|
||||
pauta = (c.get("pauta") or "").strip()
|
||||
ni = c.get("num_indice")
|
||||
if conjunto:
|
||||
dm.upsert_conjunto_pauta(conjunto, pauta)
|
||||
# si eligió un programa (num_indice), AGREGAR el vínculo num_indice<->pauta
|
||||
# en programa_pautas (muchos-a-muchos, se SUMA, no reemplaza).
|
||||
if ni and pauta:
|
||||
dm.agregar_programa_pauta(str(ni).strip(), pauta)
|
||||
for pref in ("conjunto_pauta", "pauta_raw", "programa_pautas", "pautas_de_indice",
|
||||
"meta_filas", "importe_pauta", "importe_pauta_periodo",
|
||||
"resultados_pauta_periodo", "leads_dash", "otros_general",
|
||||
"matriz_always", "matriz_plantillas", "leyenda_anuncios"):
|
||||
cache_invalidate(pref)
|
||||
return {"guardados": len(cambios)}
|
||||
|
||||
|
||||
def uso_de_pauta(pauta, excluir_num_indice=None):
|
||||
"""Verifica si una pauta ya esta en uso. Devuelve los cursos (dsc_det_programa)
|
||||
y conjuntos que la usan (para la advertencia antes de guardar)."""
|
||||
dm = get_dm()
|
||||
nis = dm.num_indices_de_pauta(pauta)
|
||||
excl = str(excluir_num_indice or "").strip()
|
||||
nis = [n for n in nis if n != excl]
|
||||
# dsc_det_programa de esos num_indice (desde cursos de SQL, ya cacheados)
|
||||
cursos = _cursos_crudos()
|
||||
detalle = []
|
||||
for c in cursos:
|
||||
ni = _norm_ni(c.get("num_indice"))
|
||||
if ni in nis:
|
||||
detalle.append({"num_indice": ni,
|
||||
"dsc_det_programa": str(c.get("dsc_det_programa") or c.get("dsc_programa") or "").strip()})
|
||||
conjuntos = _conjunto_pauta().get(str(pauta).strip(), [])
|
||||
return {"en_uso": bool(nis) or bool(conjuntos),
|
||||
"cursos": detalle, "num_indices": nis, "conjuntos": conjuntos}
|
||||
|
||||
|
||||
def guardar_edicion_curso(num_indice, pauta, conjunto=None, contar=None):
|
||||
"""Guarda pauta y contar (SI/NO) en basebi_programacion (upsert) y, si se eligió,
|
||||
vincula el conjunto a esa pauta en conjunto_pauta. Invalida SOLO los cachés que
|
||||
dependen de pauta/conjunto (NO la cartera, para que la recarga sea rápida)."""
|
||||
from cache_manager import cache_invalidate
|
||||
dm = get_dm()
|
||||
res = dm.guardar_pauta_basebi(num_indice, pauta, contar)
|
||||
if conjunto:
|
||||
dm.guardar_conjunto_pauta(conjunto, pauta)
|
||||
# invalidar solo lo afectado por pauta/conjunto (la cartera NO se re-baja)
|
||||
for pref in ("pauta_raw", "pautas_de_indice", "conjunto_pauta", "meta_filas",
|
||||
"importe_pauta", "importe_pauta_periodo", "resultados_pauta_periodo",
|
||||
"leads_dash", "otros_general", "matriz_always", "matriz_plantillas",
|
||||
"leads_filtros"):
|
||||
cache_invalidate(pref)
|
||||
return res
|
||||
|
||||
|
||||
def _tipo_de_curso(c):
|
||||
"""Categoría de tipo de programa para el filtro (PROGRAMAS/PROVINCIA/SEMINARIOS/OTROS)."""
|
||||
dscp = c.get("dsc_programa", "")
|
||||
otros = L.clasificar_tipo_programa(dscp)
|
||||
if otros == "OTROS":
|
||||
return "OTROS"
|
||||
up = str(dscp).upper()
|
||||
cat = "TEAC" if ("AIRE ACONDICIONADO" in up or "TEAC" in up) else (
|
||||
"TERC" if ("REFRIGERACION COMERCIAL" in up or "REFRIGERACIÓN COMERCIAL" in up or "TERC" in up) else "SEM")
|
||||
sede = L.clasificar_sede(dscp)
|
||||
return L.tipo_programa_cohorte(sede, cat)
|
||||
|
||||
|
||||
# ── Listas para los filtros (años, tipos de programa) ───────────
|
||||
def opciones_filtros():
|
||||
def _load():
|
||||
cursos = _cursos_crudos()
|
||||
anos = sorted({L._to_date(c.get("fch_inicio")).year for c in cursos
|
||||
if L._to_date(c.get("fch_inicio"))}, reverse=True)
|
||||
# Grupos de programa fijos para el filtro PROGRAMA
|
||||
tipos = ["TEAC", "TERC", "SEMINARIOS", "OTROS"]
|
||||
return {"anos": anos or [2026], "tipos": tipos}
|
||||
return cache_get_or_set("leads_filtros", ("GLOBAL",), _load)
|
||||
|
||||
|
||||
# ── Alertas: valores de programa/sede no identificados en cartera_junta ──
|
||||
def alertas():
|
||||
return cache_get_or_set("leads_alertas", ("GLOBAL",),
|
||||
lambda: get_dm().traer_no_identificados())
|
||||
|
||||
|
||||
# ── Diagnóstico de cursos (para cuadrar ocupabilidad) ───────────
|
||||
def debug_cursos(ano, mes):
|
||||
cursos = _cursos_crudos()
|
||||
periodo = [c for c in cursos if L._en_periodo(L._to_date(c.get("fch_inicio")), ano, mes, "TODOS")]
|
||||
detalle = []
|
||||
tot_insc = 0
|
||||
tot_meta = 0
|
||||
for c in periodo:
|
||||
insc = int(c.get("Inscritos_Totales", 0) or 0)
|
||||
meta = L.meta_curso(c.get("dsc_programa"))
|
||||
tp = L.tipo_programa_curso(c.get("dsc_programa"))
|
||||
tot_insc += insc
|
||||
tot_meta += meta
|
||||
detalle.append({
|
||||
"num_indice": c.get("num_indice"),
|
||||
"dsc_programa": c.get("dsc_programa"),
|
||||
"fch_inicio": str(c.get("fch_inicio"))[:10],
|
||||
"cod_estado": c.get("cod_estado"),
|
||||
"inscritos": insc,
|
||||
"tipo": tp,
|
||||
"meta": meta,
|
||||
})
|
||||
return {
|
||||
"num_cursos": len(periodo),
|
||||
"suma_inscritos": tot_insc,
|
||||
"suma_meta": tot_meta,
|
||||
"ocupabilidad": round((tot_insc / tot_meta * 100), 2) if tot_meta else 0,
|
||||
"cursos": detalle,
|
||||
}
|
||||
|
||||
|
||||
# ── Precarga / refresco ─────────────────────────────────────────
|
||||
def _periodos_actual_anterior():
|
||||
"""[(ano, mes), ...] = mes actual y mes anterior (segun fecha de hoy)."""
|
||||
from datetime import date
|
||||
hoy = date.today()
|
||||
ano, mes = hoy.year, hoy.month
|
||||
if mes == 1:
|
||||
prev = (ano - 1, 12)
|
||||
else:
|
||||
prev = (ano, mes - 1)
|
||||
return [(str(ano), str(mes)), (str(prev[0]), str(prev[1]))]
|
||||
|
||||
|
||||
def precargar_todo():
|
||||
"""Precarga en segundo plano: insumos crudos + el dashboard del mes actual y
|
||||
anterior (con filtros en TODOS), para que el usuario no espere al abrir/filtrar."""
|
||||
try:
|
||||
_leads_crudos(); _cursos_crudos(); _matriculas_crudas()
|
||||
_leads_asignados_crudos()
|
||||
# Dashboard (Leads) del mes actual y anterior (lo mas usado). Otros General
|
||||
# NO se precarga aqui (sus consultas son pesadas); se calcula al entrar.
|
||||
for (a, m) in _periodos_actual_anterior():
|
||||
leads_dashboard(a, m, "TODOS", "TODOS", "TODOS")
|
||||
print(f"[precarga] listo {a}-{m}")
|
||||
_marcar_actualizacion()
|
||||
except Exception as e:
|
||||
print(f"[precarga] {e}")
|
||||
|
||||
|
||||
def precargar_otros_general():
|
||||
"""Precarga (aparte, mas pesada) las 4 matrices de Otros General del mes actual
|
||||
y anterior. Se llama en su propio hilo para no bloquear."""
|
||||
try:
|
||||
_plantillas_crudas()
|
||||
_cartera_rows_cache() # baja la cartera 1 vez (queda cacheada para todas las matrices)
|
||||
for (a, m) in _periodos_actual_anterior():
|
||||
otros_general(a, m, "TODOS")
|
||||
print(f"[precarga-otros] listo {a}-{m}")
|
||||
except Exception as e:
|
||||
print(f"[precarga-otros] {e}")
|
||||
|
||||
|
||||
# Hora de la última actualización (hora Perú)
|
||||
_ULTIMA_ACTUALIZACION = None
|
||||
|
||||
|
||||
def _marcar_actualizacion():
|
||||
global _ULTIMA_ACTUALIZACION
|
||||
from datetime import datetime, timezone, timedelta
|
||||
peru = timezone(timedelta(hours=-5))
|
||||
_ULTIMA_ACTUALIZACION = datetime.now(peru).strftime("%d/%m/%Y %H:%M")
|
||||
|
||||
|
||||
def ultima_actualizacion():
|
||||
return {"hora": _ULTIMA_ACTUALIZACION}
|
||||
|
||||
|
||||
def refrescar_todo():
|
||||
from cache_manager import cache_invalidate
|
||||
cache_invalidate() # vaciar y recargar TODO
|
||||
precargar_todo() # leads (mes actual/anterior)
|
||||
precargar_otros_general() # cartera + Otros General (para que no quede vacia)
|
||||
_marcar_actualizacion()
|
||||
Reference in New Issue
Block a user