Se Creo el codigo de python de la notificacion del cruce y se acomodo el codigo de SynReferences2IONOS

SyncUpdate2IONOS
Luis Rendon 1 year ago
parent a64b378e1a
commit 7e1c5c50d1
  1. 18
      NotificacionCruce/config.json
  2. 296
      NotificacionCruce/notificacionn.py
  3. 32
      SyncReferences2IONOS/SyncReferences2IONOS.py
  4. 0
      SyncReferences2IONOS/config/config.json
  5. 5
      SyncReferences2IONOS/log/Referencias.txt
  6. 5
      SyncReferences2IONOS/log/fechayHora.txt
  7. 3
      log/Referencias.txt
  8. 3
      log/fechayHora.txt

@ -0,0 +1,18 @@
{
"server": ".",
"database": "ZINC",
"username": "sa",
"password": "Chispa10",
"EmailUser": "noreply@gemcousa.mx",
"EmailPassword": "Mx77lf%02",
"EmailServer": "smtp.ionos.com",
"EmailPort": 587,
"ServerSIR": "192.168.100.11",
"DatabaseSIR": "SIR",
"DBUserSIR": "usersir",
"DBPasswordSIR": "S1r22$Us"
}

@ -0,0 +1,296 @@
# import json
# import pyodbc
# import smtplib
# from email.mime.multipart import MIMEMultipart
# from email.mime.text import MIMEText
# # Cargar la configuración desde el archivo JSON
# with open('config.json', 'r') as config_file:
# config = json.load(config_file)
# # Cargar la configuración de correo desde el archivo JSON
# with open('config.json', 'r') as email_config_file:
# email_config = json.load(email_config_file)
# # Crear la cadena de conexión
# conn_str = (
# f"DRIVER=ODBC Driver 17 for SQL Server;"
# f"SERVER={config['server']};"
# f"DATABASE={config['database']};"
# f"UID={config['username']};"
# f"PWD={config['password']};"
# )
# # Conectarse a la base de datos
# try:
# conn = pyodbc.connect(conn_str)
# print("Conexión exitosa")
# # Crear el cursor y ejecutar el procedimiento almacenado
# cursor = conn.cursor()
# fecha = '2023-08-28' # Ejemplo de fecha
# cursor.execute("{CALL NotificacionCruze(?)}", fecha)
# # Recuperar los resultados del procedimiento almacenado
# rows = cursor.fetchall()
# # Configurar el servidor de correo electrónico saliente (SMTP) desde el archivo JSON
# smtp_server = email_config['EmailServer']
# smtp_port = email_config['EmailPort']
# # Tus credenciales de correo electrónico desde el archivo JSON
# sender_email = email_config['EmailUser']
# sender_password = email_config['EmailPassword']
# factura_data = {}
# # Iterar a través de los resultados y agruparlos por factura
# for row in rows:
# invoice = row.Invoice
# if invoice not in factura_data:
# factura_data[invoice] = []
# factura_data[invoice].append(row)
# # Iterar a través de las facturas y enviar un solo correo por factura
# for invoice, factura_rows in factura_data.items():
# # Obtener los datos comunes para la factura (fecha, invoice, caja, vigenciaDoda, notificacion)
# first_row = factura_rows[0]
# fechaActual = first_row.FechaActual
# invoice = first_row.Invoice
# caja = first_row.Caja
# vigenciaDoda = first_row.VigenciaDODA
# notificacion = first_row.Notificacion
# # ...
# # Crear un diccionario para almacenar los correos de CorreosResponsables y NotificacionAA por factura
# correos_por_factura = {}
# # Iterar a través de los resultados y agrupar los correos por factura
# for row in rows:
# invoice = row.Invoice
# if invoice not in correos_por_factura:
# correos_por_factura[invoice] = {'CorreosResponsables': [], 'NotificacionAA': []}
# correos_responsables = row.CorreosResponsables.split(',') if row.CorreosResponsables else []
# notificacion_aa = row.NotificacionAA.split(',') if row.NotificacionAA else []
# correos_por_factura[invoice]['CorreosResponsables'].extend(correos_responsables)
# correos_por_factura[invoice]['NotificacionAA'].extend(notificacion_aa)
# # ...
# # Iterar a través de las facturas y enviar correos
# for invoice, correos_en_factura in correos_por_factura.items():
# correos_responsables = correos_en_factura['CorreosResponsables']
# notificacion_aa = correos_en_factura['NotificacionAA']
# # Crear y enviar correos a CorreosResponsables
# for destinatario in correos_responsables:
# # Crear el mensaje de correo electrónico
# msg_correo_responsable = MIMEMultipart()
# msg_correo_responsable['From'] = sender_email
# msg_correo_responsable['To'] = destinatario
# msg_correo_responsable['Subject'] = f"Información de factura {invoice} - CorreosResponsables"
# # Crear el cuerpo del mensaje con los datos de la factura
# message = f"Fecha Actual: {fechaActual}\nInvoice: {invoice}\nCaja: {caja}\nVigenciaDODA: {vigenciaDoda}\nNotificacion: {notificacion}"
# msg_correo_responsable.attach(MIMEText(message, 'plain'))
# try:
# # Establecer la conexión al servidor SMTP
# server = smtplib.SMTP(smtp_server, smtp_port)
# server.starttls()
# server.login(sender_email, sender_password)
# # Enviar el correo
# server.sendmail(sender_email, destinatario, msg_correo_responsable.as_string())
# print(f"Correo enviado a CorreosResponsables: {destinatario}")
# # Cerrar la conexión SMTP
# server.quit()
# except Exception as e:
# print(f"Error al enviar correo a CorreosResponsables: {destinatario} - {e}")
# # Crear y enviar correos a NotificacionAA
# for destinatario in notificacion_aa:
# # Crear el mensaje de correo electrónico
# msg_notificacion_aa = MIMEMultipart()
# msg_notificacion_aa['From'] = sender_email
# msg_notificacion_aa['To'] = destinatario
# msg_notificacion_aa['Subject'] = f"Información de factura {invoice} - NotificacionAA"
# # Crear el cuerpo del mensaje con los datos de la factura
# message = f"Fecha Actual: {fechaActual}\nInvoice: {invoice}\nCaja: {caja}\nVigenciaDODA: {vigenciaDoda}\nNotificacion: {notificacion}"
# msg_notificacion_aa.attach(MIMEText(message, 'plain'))
# try:
# # Establecer la conexión al servidor SMTP
# server = smtplib.SMTP(smtp_server, smtp_port)
# server.starttls()
# server.login(sender_email, sender_password)
# # Enviar el correo
# server.sendmail(sender_email, destinatario, msg_notificacion_aa.as_string())
# print(f"Correo enviado a NotificacionAA: {destinatario}")
# # Cerrar la conexión SMTP
# server.quit()
# except Exception as e:
# print(f"Error al enviar correo a NotificacionAA: {destinatario} - {e}")
# # ...
# except Exception as e:
# print("Error al conectarse:", e)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pyodbc
import json
import datetime
# Cargar la información de conexión desde el archivo JSON
with open('config.json', 'r') as config_file:
config = json.load(config_file)
# Crear una cadena de conexión usando la información del archivo JSON
conn_str = (
f"DRIVER=ODBC Driver 17 for SQL Server;"
f"SERVER={config['server']};"
f"DATABASE={config['database']};"
f"UID={config['username']};"
f"PWD={config['password']};"
)
# Conectar a la base de datos
conn = pyodbc.connect(conn_str)
try:
cursor = conn.cursor()
fecha = '2023-09-11' # Ejemplo de fecha
# fecha = datetime.date.today()
cursor.execute("{CALL NotificacionCruze(?)}", fecha)
# Recuperar los resultados del procedimiento almacenado
rows = cursor.fetchall()
# Configurar el servidor de correo electrónico saliente (SMTP) desde el archivo JSON
with open('config.json', 'r') as email_config_file:
email_config = json.load(email_config_file)
smtp_server = email_config['EmailServer']
smtp_port = email_config['EmailPort']
# Tus credenciales de correo electrónico desde el archivo JSON
sender_email = email_config['EmailUser']
sender_password = email_config['EmailPassword']
factura_data = {}
# Iterar a través de los resultados y agruparlos por factura
for row in rows:
invoice = row.Invoice
if invoice not in factura_data:
factura_data[invoice] = []
factura_data[invoice].append(row)
# Crear un diccionario para almacenar los correos de CorreosResponsables y NotificacionAA por factura
correos_por_factura = {}
# Iterar a través de los resultados y agrupar los correos por factura
for row in rows:
invoice = row.Invoice
if invoice not in correos_por_factura:
correos_por_factura[invoice] = {'CorreosResponsables': [], 'NotificacionAA': []}
correos_responsables = row.CorreosResponsables.split(',') if row.CorreosResponsables else []
notificacion_aa = row.NotificacionAA.split(',') if row.NotificacionAA else []
correos_por_factura[invoice]['CorreosResponsables'].extend(correos_responsables)
correos_por_factura[invoice]['NotificacionAA'].extend(notificacion_aa)
# Iterar a través de las facturas y enviar correos
for invoice, correos_en_factura in correos_por_factura.items():
correos_responsables = correos_en_factura['CorreosResponsables']
notificacion_aa = correos_en_factura['NotificacionAA']
# Obtener los datos comunes para la factura (fecha, invoice, caja, vigenciaDoda, notificacion)
first_row = factura_data[invoice][0]
fechaActual = first_row.FechaActual
caja = first_row.Caja
vigenciaDoda = first_row.VigenciaDODA
notificacion = first_row.Notificacion
# Crear el mensaje de correo electrónico
msg = MIMEMultipart()
msg['From'] = sender_email
msg['Subject'] = f"Información de factura {invoice}"
# Crear el cuerpo del mensaje con los datos de la factura en una tabla
message = f"<html><body>"
message += f"<h2>Factura {invoice}</h2>"
message += f"<table border='1'><tr><th>Fecha Actual</th><th>Invoice</th><th>Caja</th><th>VigenciaDODA</th><th>Notificacion</th></tr>"
message += f"<tr><td>{fechaActual}</td><td>{invoice}</td><td>{caja}</td><td>{vigenciaDoda}</td><td>{notificacion}</td></tr>"
message += f"</table><br>"
# message += f"<h3>CorreosResponsables:</h3>"
# message += "<ul>"
# for destinatario in correos_responsables:
# message += f"<li>{destinatario}</li>"
# message += "</ul>"
# message += f"<h3>NotificacionAA:</h3>"
# message += "<ul>"
# for destinatario in notificacion_aa:
# message += f"<li>{destinatario}</li>"
# message += "</ul>"
message += "</body></html>"
msg.attach(MIMEText(message, 'html'))
try:
# Establecer la conexión al servidor SMTP
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
# Enviar el correo a todos los destinatarios de CorreosResponsables y NotificacionAA
destinatarios = correos_responsables + notificacion_aa
server.sendmail(sender_email, destinatarios, msg.as_string())
print(f"Correo enviado a CorreosResponsables y NotificacionAA de factura {invoice}")
# Cerrar la conexión SMTP
server.quit()
except Exception as e:
print(f"Error al enviar correo de factura {invoice}: {e}")
except Exception as e:
print("Error al conectarse:", e)

@ -83,6 +83,7 @@ def WriteToLog(referencia):
def CreateFolderContent():
try:
# Leer archivo de registro y obtener lista de referencias procesadas
processed_references = []
with open('./log/Referencias.txt', 'r') as f:
@ -134,15 +135,14 @@ def CreateFolderContent():
reference = filename.split('_____')[0]
# Procesar archivo
if WriteToLog(reference):
processed_references.append(reference)
URL = 'https://www.gemcousa.mx/GEMCOBackend/api/AmazonInvoice/UploadSIRReference?ArchivoM=' +\
URL = 'http://localhost:5000/api/AmazonInvoice/UploadSIRReference?ArchivoM=' +\
archivoM+'&aduana='+aduana+'&patente='+patente + \
'&pedimento='+pedimento+'&fPago=' + \
str(fPago)+'&TipoCambio='+str(tipoCambio)+'&clave='+clave
multiple_files = []
multiple_files.append(('files', (file.replace(TempFolder,''), open(file, 'rb'), 'application/zip')))
data = {
multiple_files = []
multiple_files.append(('files', (file.replace(TempFolder,''), open(file, 'rb'), 'application/zip')))
data = {
"ArchivoM": archivoM,
'aduana': aduana,
'patente': patente,
@ -152,9 +152,23 @@ def CreateFolderContent():
'clave': clave
}
print( f"la referencia {reference} ya ha sido posteada." )
r = requests.post(url=URL,files=multiple_files, verify=False, timeout=30)
}
print( f"la referencia {reference} ya ha sido posteada." )
r = requests.post(url=URL,files=multiple_files, verify=False, timeout=9000)
print(r.text.strip('["]'))
response_text = r.text.strip('[]\"')
if response_text != 'false':
WriteToLog(reference)
processed_references.append(reference)
else:
print(f"La referencia {reference} no se pudo procesar. Respuesta del servidor: {response_text}")
# if r.text.strip('false'):
# WriteToLog(reference)
# processed_references.append(reference)
# if WriteToLog(reference):
# processed_references.append(reference)
except Exception as e:
print("Error: %s" % e)
# WriteToLog(r.text)

@ -0,0 +1,5 @@
23-00733I
23-00492I
23-00493I
23-00681I

@ -0,0 +1,5 @@
2023-05-03 18:54:24 - 23-00733I
2023-05-03 18:54:40 - 23-00492I
2023-05-03 18:55:21 - 23-00493I
2023-05-03 18:55:57 - 23-00681I

@ -1,3 +0,0 @@
23-00307I
23-00429I
23-00648I

@ -1,3 +0,0 @@
2023-04-11 17:13:14 - 23-00307I
2023-04-11 17:13:26 - 23-00429I
2023-04-11 17:13:27 - 23-00648I
Loading…
Cancel
Save