feat: Implement direct MySQL database integration for onboarding and duplicate checks, add Gemini AI support, and update webhook and email configurations.

This commit is contained in:
Marco Gallegos
2025-12-18 15:58:01 -06:00
parent 8387a5851a
commit 1151d3af3d
5 changed files with 127 additions and 178 deletions

View File

@@ -5,8 +5,7 @@ from sqlalchemy.orm import sessionmaker
from models.users_alma_models import Base as BaseUsersAlma, User
from models.vanity_hr_models import Base as BaseVanityHr, DataEmpleadas, Vacaciones, Permisos
from models.vanity_attendance_models import Base as BaseVanityAttendance, AsistenciaRegistros, HorarioEmpleadas
import gspread
from google.oauth2.service_account import Credentials
# --- DATABASE (MySQL) SETUP ---
def _build_engine(db_name_env_var):
@@ -36,69 +35,50 @@ SessionUsersAlma = sessionmaker(autocommit=False, autoflush=False, bind=engine_u
SessionVanityHr = sessionmaker(autocommit=False, autoflush=False, bind=engine_vanity_hr) if engine_vanity_hr else None
SessionVanityAttendance = sessionmaker(autocommit=False, autoflush=False, bind=engine_vanity_attendance) if engine_vanity_attendance else None
# --- GOOGLE SHEETS SETUP ---
GSHEET_URL = os.getenv("GOOGLE_SHEET_URL")
GOOGLE_CREDENTIALS_FILE = os.getenv("GOOGLE_CREDENTIALS_FILE", "google_credentials.json")
SHEET_COLUMN_INDEX = 40 # AN is the 40th column
def get_gsheet_client():
"""Returns an authenticated gspread client or None if it fails."""
if not GSHEET_URL:
logging.warning("GOOGLE_SHEET_URL is not configured. Duplicate checking is disabled.")
return None
creds = None
scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
gsa_creds_dict = {
"type": os.getenv("GSA_TYPE"),
"project_id": os.getenv("GSA_PROJECT_ID"),
"private_key_id": os.getenv("GSA_PRIVATE_KEY_ID"),
"private_key": (os.getenv("GSA_PRIVATE_KEY") or "").replace("\\n", "\n"),
"client_email": os.getenv("GSA_CLIENT_EMAIL"),
"client_id": os.getenv("GSA_CLIENT_ID"),
"auth_uri": os.getenv("GSA_AUTH_URI"),
"token_uri": os.getenv("GSA_TOKEN_URI"),
"auth_provider_x509_cert_url": os.getenv("GSA_AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.getenv("GSA_CLIENT_X509_CERT_URL"),
}
if all(gsa_creds_dict.values()):
try:
creds = Credentials.from_service_account_info(gsa_creds_dict, scopes=scopes)
except Exception as e:
logging.error(f"Error processing Google credentials from environment: {e}")
return None
elif os.path.exists(GOOGLE_CREDENTIALS_FILE):
try:
creds = Credentials.from_service_account_file(GOOGLE_CREDENTIALS_FILE, scopes=scopes)
except Exception as e:
logging.error(f"Error processing credentials file '{GOOGLE_CREDENTIALS_FILE}': {e}")
return None
else:
logging.warning("Google credentials not found (neither environment variables nor file). Duplicate checking is disabled.")
return None
try:
return gspread.authorize(creds)
except Exception as e:
logging.error(f"Error authorizing gspread client: {e}")
return None
# --- GOOGLE SHEETS SETUP (REMOVED) ---
# Duplicate checking is now done via database.
def chat_id_exists(chat_id: int) -> bool:
"""Checks if a Telegram chat_id already exists in the Google Sheet."""
client = get_gsheet_client()
if not client:
"""Checks if a Telegram chat_id already exists in the USERS_ALMA.users table."""
if not SessionUsersAlma:
logging.warning("SessionUsersAlma not initialized. Cannot check if chat_id exists.")
return False
session = SessionUsersAlma()
try:
exists = session.query(User).filter(User.telegram_id == str(chat_id)).first() is not None
return exists
except Exception as e:
logging.error(f"Error checking if chat_id exists in DB: {e}")
return False
finally:
session.close()
def register_user(user_data: dict) -> bool:
"""Registers a new user in the USERS_ALMA.users table."""
if not SessionUsersAlma:
logging.warning("SessionUsersAlma not initialized. Cannot register user.")
return False
session = SessionUsersAlma()
try:
spreadsheet = client.open_by_url(GSHEET_URL)
worksheet = spreadsheet.get_worksheet(0)
chat_ids_in_sheet = worksheet.col_values(SHEET_COLUMN_INDEX)
return str(chat_id) in chat_ids_in_sheet
except gspread.exceptions.SpreadsheetNotFound:
logging.error("Could not find the spreadsheet at the provided URL.")
return False
new_user = User(
telegram_id=str(user_data.get("chat_id")),
username=user_data.get("telegram_user"),
first_name=user_data.get("first_name"),
last_name=f"{user_data.get('apellido_paterno', '')} {user_data.get('apellido_materno', '')}".strip(),
email=user_data.get("email"),
cell_phone=user_data.get("celular"),
role='user' # Default role
)
session.add(new_user)
session.commit()
logging.info(f"User {user_data.get('chat_id')} registered successfully in DB.")
return True
except Exception as e:
logging.error(f"Error reading the spreadsheet: {e}")
session.rollback()
logging.error(f"Error registering user in DB: {e}")
return False
finally:
session.close()

View File

@@ -18,7 +18,7 @@ from telegram.ext import (
)
from modules.logger import log_request
from modules.database import chat_id_exists
from modules.database import chat_id_exists, register_user
from modules.ui import main_actions_keyboard
# --- 1. CARGA DE ENTORNO ---
@@ -404,6 +404,19 @@ async def finalizar(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
except Exception as e:
logging.error(f"Error enviando webhook a {url}: {e}")
# --- REGISTRO EN BASE DE DATOS ---
db_ok = register_user({
**meta,
**payload["metadata"],
**payload["candidato"],
**payload["contacto"]
})
if db_ok:
logging.info(f"Usuario {meta['chat_id']} registrado en la base de datos.")
else:
logging.error(f"Fallo al registrar usuario {meta['chat_id']} en la base de datos.")
if enviado:
await update.message.reply_text(
"✅ *¡Registro Exitoso!*\n\n"