diff --git a/NotificacionCruce/config.json b/NotificacionCruce/config.json new file mode 100644 index 0000000..d93aa04 --- /dev/null +++ b/NotificacionCruce/config.json @@ -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" +} + + + + \ No newline at end of file diff --git a/NotificacionCruce/notificacionn.py b/NotificacionCruce/notificacionn.py new file mode 100644 index 0000000..6cf086f --- /dev/null +++ b/NotificacionCruce/notificacionn.py @@ -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"" + message += f"

Factura {invoice}

" + message += f"" + message += f"" + message += f"
Fecha ActualInvoiceCajaVigenciaDODANotificacion
{fechaActual}{invoice}{caja}{vigenciaDoda}{notificacion}

" + + # message += f"

CorreosResponsables:

" + # message += "" + + # message += f"

NotificacionAA:

" + # message += "" + + message += "" + 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) + + + + + + + + + diff --git a/SyncReferences2IONOS.py b/SyncReferences2IONOS/SyncReferences2IONOS.py similarity index 83% rename from SyncReferences2IONOS.py rename to SyncReferences2IONOS/SyncReferences2IONOS.py index 8cb3748..409e34a 100644 --- a/SyncReferences2IONOS.py +++ b/SyncReferences2IONOS/SyncReferences2IONOS.py @@ -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) diff --git a/config/config.json b/SyncReferences2IONOS/config/config.json similarity index 100% rename from config/config.json rename to SyncReferences2IONOS/config/config.json diff --git a/SyncReferences2IONOS/log/Referencias.txt b/SyncReferences2IONOS/log/Referencias.txt new file mode 100644 index 0000000..c43a6c7 --- /dev/null +++ b/SyncReferences2IONOS/log/Referencias.txt @@ -0,0 +1,5 @@ + +23-00733I +23-00492I +23-00493I +23-00681I diff --git a/SyncReferences2IONOS/log/fechayHora.txt b/SyncReferences2IONOS/log/fechayHora.txt new file mode 100644 index 0000000..59e2129 --- /dev/null +++ b/SyncReferences2IONOS/log/fechayHora.txt @@ -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 diff --git a/log/Referencias.txt b/log/Referencias.txt deleted file mode 100644 index 9fc2b64..0000000 --- a/log/Referencias.txt +++ /dev/null @@ -1,3 +0,0 @@ -23-00307I -23-00429I -23-00648I diff --git a/log/fechayHora.txt b/log/fechayHora.txt deleted file mode 100644 index 0e725d3..0000000 --- a/log/fechayHora.txt +++ /dev/null @@ -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