mirror of
https://github.com/marcogll/telegram_new_socias.git
synced 2026-01-13 13:15:16 +00:00
feat: Implement a new links menu, consolidate the main action keyboard into a ui module, and update employee ID generation logic.
This commit is contained in:
@@ -1,4 +1,18 @@
|
||||
import os
|
||||
import importlib
|
||||
import importlib.metadata as importlib_metadata
|
||||
|
||||
# Compatibilidad para entornos donde packages_distributions no existe (p.ej. Python 3.9 con importlib recortado).
|
||||
if not hasattr(importlib_metadata, "packages_distributions"):
|
||||
try:
|
||||
import importlib_metadata as backport_metadata # type: ignore
|
||||
if hasattr(backport_metadata, "packages_distributions"):
|
||||
importlib_metadata.packages_distributions = backport_metadata.packages_distributions # type: ignore[attr-defined]
|
||||
else:
|
||||
importlib_metadata.packages_distributions = lambda: {} # type: ignore[assignment]
|
||||
except Exception:
|
||||
importlib_metadata.packages_distributions = lambda: {} # type: ignore[assignment]
|
||||
|
||||
import google.generativeai as genai
|
||||
|
||||
def classify_reason(text: str) -> str:
|
||||
|
||||
@@ -18,6 +18,7 @@ from telegram.ext import (
|
||||
)
|
||||
|
||||
from modules.database import log_request
|
||||
from modules.ui import main_actions_keyboard
|
||||
|
||||
# --- 1. CARGA DE ENTORNO ---
|
||||
load_dotenv() # Carga las variables del archivo .env
|
||||
@@ -304,8 +305,14 @@ async def finalizar(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
||||
fecha_ini = "ERROR_FECHA"
|
||||
# Derivados
|
||||
num_ext_texto = numero_a_texto(r.get(NUM_EXTERIOR, ""), r.get(NUM_INTERIOR, ""))
|
||||
curp_base = (r.get(CURP) or "").upper()
|
||||
n_empleado = f"{(curp_base + 'XXXX')[:4]}{fecha_ini.replace('-', '')}"
|
||||
# El número de empleado debe ser solo la fecha de inicio en formato AAMMDD.
|
||||
try:
|
||||
fecha_inicio_dt = datetime.strptime(fecha_ini, "%Y-%m-%d")
|
||||
n_empleado = fecha_inicio_dt.strftime("%y%m%d")
|
||||
except Exception:
|
||||
# Fallback defensivo para no romper el flujo si viene un formato raro.
|
||||
fecha_compacta = fecha_ini.replace("-", "")
|
||||
n_empleado = fecha_compacta[-6:] if len(fecha_compacta) >= 6 else fecha_compacta or "N/A"
|
||||
|
||||
# PAYLOAD ESTRUCTURADO PARA N8N
|
||||
payload = {
|
||||
@@ -378,18 +385,22 @@ async def finalizar(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
||||
await update.message.reply_text(
|
||||
"✅ *¡Registro Exitoso!*\n\n"
|
||||
"Bienvenida a la familia Soul/Vanity. Tu contrato se está generando y te avisaremos pronto.\n"
|
||||
"¡Nos vemos el primer día! ✨"
|
||||
"¡Nos vemos el primer día! ✨",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
else:
|
||||
await update.message.reply_text("⚠️ Se guardaron tus datos pero hubo un error de conexión. RH lo revisará manualmente.")
|
||||
await update.message.reply_text(
|
||||
"⚠️ Se guardaron tus datos pero hubo un error de conexión. RH lo revisará manualmente.",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
|
||||
context.user_data.clear()
|
||||
return ConversationHandler.END
|
||||
|
||||
async def cancelar(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
||||
await update.message.reply_text(
|
||||
"Proceso cancelado. ⏸️\nCuando quieras retomar, escribe /contrato.",
|
||||
reply_markup=ReplyKeyboardRemove()
|
||||
"Proceso cancelado. ⏸️\nPuedes retomarlo con /welcome o ir al menú con /start.",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
context.user_data.clear()
|
||||
return ConversationHandler.END
|
||||
|
||||
@@ -5,6 +5,7 @@ from datetime import datetime, date
|
||||
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
|
||||
from telegram.ext import CommandHandler, ContextTypes, ConversationHandler, MessageHandler, filters
|
||||
from modules.database import log_request
|
||||
from modules.ui import main_actions_keyboard
|
||||
from modules.ai import classify_reason
|
||||
|
||||
# Helpers de webhooks
|
||||
@@ -342,18 +343,30 @@ async def recibir_motivo_fin(update: Update, context: ContextTypes.DEFAULT_TYPE)
|
||||
f"- Estatus inicial: {payload.get('status_inicial', 'N/A')}"
|
||||
)
|
||||
if enviados > 0:
|
||||
await update.message.reply_text(f"✅ Solicitud de *{tipo_solicitud_texto}* enviada a tu Manager.\n\n{resumen}")
|
||||
await update.message.reply_text(
|
||||
f"✅ Solicitud de *{tipo_solicitud_texto}* enviada a tu Manager.\n\n{resumen}",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
else:
|
||||
await update.message.reply_text(f"⚠️ No hay webhook configurado o falló el envío. RH lo revisará.\n\n{resumen}")
|
||||
await update.message.reply_text(
|
||||
f"⚠️ No hay webhook configurado o falló el envío. RH lo revisará.\n\n{resumen}",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error enviando webhook: {e}")
|
||||
await update.message.reply_text("⚠️ Error enviando la solicitud.")
|
||||
await update.message.reply_text(
|
||||
"⚠️ Error enviando la solicitud.",
|
||||
reply_markup=main_actions_keyboard()
|
||||
)
|
||||
|
||||
return ConversationHandler.END
|
||||
|
||||
|
||||
async def cancelar(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
||||
await update.message.reply_text("Solicitud cancelada.")
|
||||
await update.message.reply_text(
|
||||
"Solicitud cancelada. ⏸️\nPuedes volver a iniciar con /vacaciones o /permiso, o ir al menú con /start.",
|
||||
reply_markup=main_actions_keyboard(),
|
||||
)
|
||||
return ConversationHandler.END
|
||||
|
||||
# Handlers separados pero comparten lógica
|
||||
|
||||
13
modules/ui.py
Normal file
13
modules/ui.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from telegram import ReplyKeyboardMarkup
|
||||
|
||||
|
||||
def main_actions_keyboard() -> ReplyKeyboardMarkup:
|
||||
"""Teclado inferior con comandos directos (un toque lanza el flujo)."""
|
||||
return ReplyKeyboardMarkup(
|
||||
[
|
||||
["/welcome"],
|
||||
["/vacaciones", "/permiso"],
|
||||
["/links", "/start"],
|
||||
],
|
||||
resize_keyboard=True,
|
||||
)
|
||||
Reference in New Issue
Block a user