269 lines
8.9 KiB
Python
269 lines
8.9 KiB
Python
|
|
import logging
|
||
|
|
import os
|
||
|
|
import smtplib
|
||
|
|
from datetime import datetime
|
||
|
|
from email import encoders
|
||
|
|
from email.mime.base import MIMEBase
|
||
|
|
from email.mime.multipart import MIMEMultipart
|
||
|
|
from email.mime.text import MIMEText
|
||
|
|
from email.utils import formatdate
|
||
|
|
|
||
|
|
from config import (
|
||
|
|
SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_USE_TLS,
|
||
|
|
EMAIL_FROM, EMAIL_TO, SMTP_FROM_NAME,
|
||
|
|
)
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
LOGO_URL = "https://www.criterion.com.py/tema/images/Logo_Criterion_V1_enc_az.png"
|
||
|
|
|
||
|
|
|
||
|
|
def _escapar_html(texto):
|
||
|
|
return str(texto).replace("&", "&").replace("<", "<").replace(">", ">")
|
||
|
|
|
||
|
|
|
||
|
|
def _construir_html_error(row_id, directorio_zips, error, traceback_texto):
|
||
|
|
"""
|
||
|
|
Arma el cuerpo HTML del correo de error con el mismo formato que usan los
|
||
|
|
avisos de Bot 1 (n8n): logo, título en rojo, tabla de detalle y pie con
|
||
|
|
la acción requerida.
|
||
|
|
"""
|
||
|
|
fecha_hora = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
|
||
|
|
|
||
|
|
return f"""<!DOCTYPE html>
|
||
|
|
<html>
|
||
|
|
<head>
|
||
|
|
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
|
||
|
|
<title>BOT DNIT | ERROR DE PROCESAMIENTO</title>
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
|
||
|
|
<img src='{LOGO_URL}' width='255'>
|
||
|
|
|
||
|
|
<h2 style='text-align:center; margin:10px 0; color:#c0392b;'>
|
||
|
|
Bot DNIT: Error en el Procesamiento
|
||
|
|
</h2>
|
||
|
|
|
||
|
|
<p>
|
||
|
|
El bot RUC DNIT (Bot 2) se detuvo por un error al procesar una fila pendiente de <code>control_descargas_dnit</code>. La corrida quedó cortada y la fila no se marcó como procesada.
|
||
|
|
</p>
|
||
|
|
|
||
|
|
<table border='1' cellpadding='6' cellspacing='0' style='border-collapse:collapse; width:100%;'>
|
||
|
|
<thead>
|
||
|
|
<tr>
|
||
|
|
<th width='30%'>Detalle</th>
|
||
|
|
<th width='70%'>Valor</th>
|
||
|
|
</tr>
|
||
|
|
</thead>
|
||
|
|
<tbody>
|
||
|
|
<tr>
|
||
|
|
<td>Fila (id)</td>
|
||
|
|
<td>{_escapar_html(row_id)}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>directorio_zips</td>
|
||
|
|
<td>{_escapar_html(directorio_zips)}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Error</td>
|
||
|
|
<td>{_escapar_html(error)}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Fecha/Hora</td>
|
||
|
|
<td>{fecha_hora}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Detalle técnico</td>
|
||
|
|
<td><pre style='white-space:pre-wrap; margin:0; font-size:12px;'>{_escapar_html(traceback_texto)}</pre></td>
|
||
|
|
</tr>
|
||
|
|
</tbody>
|
||
|
|
<tfoot>
|
||
|
|
<tr>
|
||
|
|
<td colspan='2' style='text-align:left;'>
|
||
|
|
<strong>Acción requerida:</strong> Revisar el log del bot y la fila id={_escapar_html(row_id)} en control_descargas_dnit antes de reintentar.
|
||
|
|
</td>
|
||
|
|
</tr>
|
||
|
|
</tfoot>
|
||
|
|
</table>
|
||
|
|
|
||
|
|
</body>
|
||
|
|
</html>"""
|
||
|
|
|
||
|
|
|
||
|
|
MESES_ES = [
|
||
|
|
"enero", "febrero", "marzo", "abril", "mayo", "junio",
|
||
|
|
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
|
||
|
|
]
|
||
|
|
|
||
|
|
|
||
|
|
def _mes_procesado():
|
||
|
|
"""
|
||
|
|
Mes/año de la corrida (no el de los datos del DNIT, que no viene indicado
|
||
|
|
en directorio_zips ni en la fila de control_descargas_dnit). Nombres de
|
||
|
|
mes en español a mano para no depender del locale del contenedor.
|
||
|
|
"""
|
||
|
|
ahora = datetime.now()
|
||
|
|
return f"{MESES_ES[ahora.month - 1].capitalize()} {ahora.year}"
|
||
|
|
|
||
|
|
|
||
|
|
def _construir_html_resultado(directorio_zips, resumen):
|
||
|
|
"""
|
||
|
|
Arma el cuerpo HTML del correo que avisa que una fila terminó de
|
||
|
|
procesarse sin errores, con el mismo formato que _construir_html_error
|
||
|
|
pero en verde (éxito) y con el resumen de lo generado.
|
||
|
|
"""
|
||
|
|
return f"""<!DOCTYPE html>
|
||
|
|
<html>
|
||
|
|
<head>
|
||
|
|
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
|
||
|
|
<title>BOT DNIT | PROCESAMIENTO FINALIZADO</title>
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
|
||
|
|
<img src='{LOGO_URL}' width='255'>
|
||
|
|
|
||
|
|
<h2 style='text-align:center; margin:10px 0; color:#1e8449;'>
|
||
|
|
Bot DNIT: Procesamiento Finalizado
|
||
|
|
</h2>
|
||
|
|
|
||
|
|
<table border='1' cellpadding='6' cellspacing='0' style='border-collapse:collapse; width:100%;'>
|
||
|
|
<thead>
|
||
|
|
<tr>
|
||
|
|
<th width='30%'>Detalle</th>
|
||
|
|
<th width='70%'>Valor</th>
|
||
|
|
</tr>
|
||
|
|
</thead>
|
||
|
|
<tbody>
|
||
|
|
<tr>
|
||
|
|
<td>Mes Procesado</td>
|
||
|
|
<td>{_mes_procesado()}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Directorio ZIPS</td>
|
||
|
|
<td>{_escapar_html(directorio_zips)}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Carpetas Descomprimidas</td>
|
||
|
|
<td>{resumen['carpetas_descomprimidas']}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Personas Jurídicas Nuevas</td>
|
||
|
|
<td>{resumen['rucs_faltantes']}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>CSV de Personas Jurídicas Nuevas</td>
|
||
|
|
<td>{_escapar_html(", ".join(os.path.basename(r) for r in resumen['rutas_rucs_faltantes']) or "(sin filas)")}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Personas Físicas - Actualizar</td>
|
||
|
|
<td>{resumen['fisicas_a_generar']}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>Personas Físicas - No encontradas en la BD</td>
|
||
|
|
<td>{resumen['fisicas_no_encontradas']}</td>
|
||
|
|
</tr>
|
||
|
|
<tr>
|
||
|
|
<td>CSV - Personas Físicas</td>
|
||
|
|
<td>{_escapar_html(", ".join(os.path.basename(r) for r in resumen['rutas_fisicas_password']) or "(sin filas)")}</td>
|
||
|
|
</tr>
|
||
|
|
</tbody>
|
||
|
|
</table>
|
||
|
|
|
||
|
|
</body>
|
||
|
|
</html>"""
|
||
|
|
|
||
|
|
|
||
|
|
def enviar_mail(destinatarios, texto, asunto, adjunto=None):
|
||
|
|
"""
|
||
|
|
Envía un correo HTML por SMTP. Estructura tomada como referencia del
|
||
|
|
enviar_mail() del bot de Empleos IPS, adaptada a la config de este
|
||
|
|
proyecto (config.py / .env) y con soporte para puerto 465 (SSL implícito,
|
||
|
|
caso TurboSMTP) además de 587/25 (STARTTLS).
|
||
|
|
|
||
|
|
destinatarios: lista de direcciones de correo (strings).
|
||
|
|
texto: cuerpo HTML del correo.
|
||
|
|
asunto: asunto del correo.
|
||
|
|
adjunto: ruta local opcional a un archivo para adjuntar.
|
||
|
|
|
||
|
|
Nunca deja que un fallo de correo corte la corrida del bot: devuelve
|
||
|
|
{"estado": "1"/"0", "msg": "..."} en vez de propagar la excepción.
|
||
|
|
"""
|
||
|
|
def _retornar(estado, msg, nivel_log=logging.INFO):
|
||
|
|
logger.log(nivel_log, msg)
|
||
|
|
return {"estado": estado, "msg": msg}
|
||
|
|
|
||
|
|
if not SMTP_USER or not SMTP_PASSWORD:
|
||
|
|
return _retornar("0", "Faltan credenciales SMTP en variables de entorno.", logging.WARNING)
|
||
|
|
|
||
|
|
if not texto:
|
||
|
|
return _retornar("0", "Se esperaba el cuerpo del correo.", logging.ERROR)
|
||
|
|
|
||
|
|
if not destinatarios:
|
||
|
|
return _retornar("0", "No se encontraron correos válidos para enviar.", logging.ERROR)
|
||
|
|
|
||
|
|
try:
|
||
|
|
msg = MIMEMultipart()
|
||
|
|
msg["From"] = f"{SMTP_FROM_NAME} <{EMAIL_FROM}>"
|
||
|
|
msg["To"] = ", ".join(destinatarios)
|
||
|
|
msg["Subject"] = asunto
|
||
|
|
msg["Date"] = formatdate(localtime=True)
|
||
|
|
|
||
|
|
msg.attach(MIMEText(texto, "html", "utf-8"))
|
||
|
|
|
||
|
|
if adjunto:
|
||
|
|
if not os.path.exists(adjunto):
|
||
|
|
return _retornar("0", f"El archivo adjunto no existe: {adjunto}", logging.WARNING)
|
||
|
|
|
||
|
|
with open(adjunto, "rb") as f:
|
||
|
|
part = MIMEBase("application", "octet-stream")
|
||
|
|
part.set_payload(f.read())
|
||
|
|
encoders.encode_base64(part)
|
||
|
|
part.add_header(
|
||
|
|
"Content-Disposition",
|
||
|
|
f'attachment; filename="{os.path.basename(adjunto)}"',
|
||
|
|
)
|
||
|
|
msg.attach(part)
|
||
|
|
|
||
|
|
# El puerto 465 es SSL implícito (hay que conectar ya cifrado con
|
||
|
|
# SMTP_SSL); STARTTLS (SMTP_USE_TLS) es para 587/25, donde se conecta
|
||
|
|
# en plano y se sube a TLS después. Usar SMTP + starttls() contra 465
|
||
|
|
# (como TurboSMTP) falla la conexión.
|
||
|
|
server_cls = smtplib.SMTP_SSL if SMTP_PORT == 465 else smtplib.SMTP
|
||
|
|
with server_cls(SMTP_HOST, SMTP_PORT, timeout=30) as server:
|
||
|
|
if SMTP_PORT != 465 and SMTP_USE_TLS:
|
||
|
|
server.starttls()
|
||
|
|
server.login(SMTP_USER, SMTP_PASSWORD)
|
||
|
|
server.sendmail(from_addr=EMAIL_FROM, to_addrs=destinatarios, msg=msg.as_string())
|
||
|
|
|
||
|
|
s = "s" if len(destinatarios) != 1 else ""
|
||
|
|
return _retornar(
|
||
|
|
"1", f"Correo{s} enviado{s} exitosamente a: {', '.join(destinatarios)} | Asunto: {asunto}",
|
||
|
|
)
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
return _retornar("0", f"Error SMTP, no se pudo enviar el correo. Asunto: {asunto} | {e!r}", logging.ERROR)
|
||
|
|
|
||
|
|
|
||
|
|
def _destinatarios_configurados():
|
||
|
|
return [d.strip() for d in EMAIL_TO.split(",") if d.strip()]
|
||
|
|
|
||
|
|
|
||
|
|
def enviar_correo_error(row_id, directorio_zips, error, traceback_texto):
|
||
|
|
"""
|
||
|
|
Envía un correo HTML de notificación cuando el bot corta la corrida por
|
||
|
|
un error.
|
||
|
|
"""
|
||
|
|
asunto = f"BOT DNIT - Error procesando"
|
||
|
|
cuerpo_html = _construir_html_error(row_id, directorio_zips, error, traceback_texto)
|
||
|
|
enviar_mail(_destinatarios_configurados(), cuerpo_html, asunto)
|
||
|
|
|
||
|
|
|
||
|
|
def enviar_correo_resultado(row_id, directorio_zips, resumen):
|
||
|
|
"""
|
||
|
|
Envía un correo HTML de notificación cuando una fila terminó de
|
||
|
|
procesarse sin errores, con el resumen de lo generado.
|
||
|
|
"""
|
||
|
|
asunto = f"BOT DNIT - Procesamiento finalizado"
|
||
|
|
cuerpo_html = _construir_html_resultado(directorio_zips, resumen)
|
||
|
|
enviar_mail(_destinatarios_configurados(), cuerpo_html, asunto)
|