From 09b1b5b945fed6aa217b5fc555e8150ac0f5f6ed Mon Sep 17 00:00:00 2001 From: Luis Angel Rendon Arrazola Date: Thu, 30 Mar 2023 15:00:14 -0500 Subject: [PATCH] ScripPython --- SyncReferences2IONOS.py | 147 ++++++++++++++++++++++++++++++++++++++++ config/config.json | 22 ++++++ log/Referencias.txt | 1 + log/fechayHora.txt | 1 + 4 files changed, 171 insertions(+) create mode 100644 SyncReferences2IONOS.py create mode 100644 config/config.json create mode 100644 log/Referencias.txt create mode 100644 log/fechayHora.txt diff --git a/SyncReferences2IONOS.py b/SyncReferences2IONOS.py new file mode 100644 index 0000000..eb3020e --- /dev/null +++ b/SyncReferences2IONOS.py @@ -0,0 +1,147 @@ +import pyodbc as po +import json +import shutil +import os +import datetime +import zipfile +import requests +import urllib3 +import os.path +import sys +import datetime as dt + + + +CurrentPath = os.path.dirname(os.path.realpath(__file__)) +log_file = "./log/Referencias.txt" + +if not os.path.isfile(CurrentPath + log_file): + with open(CurrentPath + log_file, 'w') as f: + f.write("") + +CurrentPath = os.path.dirname(os.path.realpath(__file__)) +log_file1 = "./log/fechayHora.txt" + +if not os.path.isfile(CurrentPath + log_file1): + with open(CurrentPath + log_file1, 'w') as f: + f.write("") + + +urllib3.disable_warnings() +CurrentPath = os.path.dirname(os.path.realpath(__file__)) +with open(CurrentPath+"/config/config.json") as json_data_file: + config = json.load(json_data_file) + ServerSIR = config['ServerSIR'] + DatabaseSIR = config['DatabaseSIR'] + UsernameSIR = config['DBUserSIR'] + PasswordSIR = config['DBPasswordSIR'] + RepositoryArchivoElectronicoOficial = config['RepositoryArchivoElectronicoOficial'] + '''RepositoryArchivoElectronicoOficial = 'c:/data/temp/''' + TempFolder= 'c:/tmp/' + today = datetime.date.today() + YEAR = today.year + + + +def ZipReference(foldername, TempFolder, Cliente): + zipobj = zipfile.ZipFile(TempFolder+ '_____'+ Cliente + '.zip', 'w', zipfile.ZIP_DEFLATED) + rootlen = len(TempFolder) + 1 + for base, dirs, files in os.walk(TempFolder): + for file in files: + fn = os.path.join(base, file) + zipobj.write(fn, fn[rootlen:]) + + +def WriteToLogDate(log_file, referencia): + fecha = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + with open(log_file, 'a') as f: + f.write(f"{fecha} - {referencia}\n") + f.flush() + +def WriteToLog(referencia): + processed_files = [] + with open('./log/Referencias.txt', 'r') as f: + for line in f: + processed_files.append(line.strip()) + + referencia = referencia.replace('[', '') + referencia = referencia.replace(']', '') + if referencia in processed_files: + print(f"El archivo {referencia} ya ha sido procesado.") + return False + + with open('./log/Referencias.txt', 'a') as f: + f.write(f"{referencia}\n") + f.flush() + + log_file = "./log/fechayHora.txt" + WriteToLogDate(log_file, referencia) + + print(f"El archivo {referencia} ha sido registrado.") + return True + + +def CreateFolderContent(): + try: + # Leer archivo de registro y obtener lista de referencias procesadas + processed_references = [] + with open('./log/Referencias.txt', 'r') as f: + for line in f: + reference = line.strip() + processed_references.append(reference) + + # Obtener archivos a procesar + files2process = [] + cnxn = po.connect( + "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + ServerSIR + + ";DATABASE=" + DatabaseSIR + + ";UID=" + UsernameSIR + + ";PWD=" + PasswordSIR + ) + cursor = cnxn.cursor() + cursor.execute("""SELECT P.sReferencia, p.Archivo, P.Aduana, P.Patente, P.Pedimento, P.[Pedimento Fecha Pago], Peds.nTipoCambio, + P.Clave, P.Cliente FROM SIR.Admin.SIR_VT_PedimPagados P + INNER JOIN SIR.SIR.SIR_149_PEDIMENTO AS Peds ON Peds.nIdPedimento149=ID + WHERE P.ClienteClave=2096 and p.[Pedimento FechaPago]>=CAST( GETDATE()-2 AS Date )""") + for row in cursor: + referencia = row[0] + archivoM = row[1] + cliente = row[8] + referenceFolder = TempFolder + referencia + if os.path.exists(referenceFolder): + shutil.rmtree(referenceFolder) + shutil.copytree(RepositoryArchivoElectronicoOficial + str(YEAR) + '/' + referencia, referenceFolder) + zip_file = referenceFolder+'_____'+cliente+'.zip' + if os.path.exists(zip_file): + # Verificar si la referencia ya ha sido procesada + if referencia in processed_references: + print(f"La referencia {referencia} ya ha sido procesada.") + else: + files2process.append(zip_file) + else: + ZipReference(referencia, referenceFolder, cliente) + files2process.append(zip_file) + + for file in files2process: + # Obtener referencia del archivo + filename = os.path.basename(file) + reference = filename.split('_____')[0] + + # Procesar archivo + if WriteToLog(reference): + processed_references.append(reference) + URL = 'http://localhost:5000/api/AmazonInvoice/UploadSIRReference?ArchivoM='+archivoM + multiple_files = [] + multiple_files.append(('files', (file.replace(TempFolder,''), open(file, 'rb'), 'application/zip'))) + data = { + "ArchivoM": archivoM + } + r = requests.post(url=URL,files=multiple_files, verify=False, timeout=30) + except Exception as e: + print("Error: %s" % e) + +''' contents = [os.path.join(TempFolder, i) for i in os.listdir(TempFolder)] +[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents] ''' +CreateFolderContent() + + diff --git a/config/config.json b/config/config.json new file mode 100644 index 0000000..bec49ce --- /dev/null +++ b/config/config.json @@ -0,0 +1,22 @@ +{ + "server": ".", + "database": "GEMCO", + "username": "sa", + "password": "Chispa10", + "smtp_server": "smtp.ionos.com", + "smtp_port": 587, + "smtp_username": "noreply@gemcousa.mx", + "smtp_password": "Mx77lf%02", + "sender": "noreply@gemcousa.mx", + "recipient": "lrendon@gemcousa.com", + "ServerSIR": "192.168.100.11", + "DatabaseSIR": "SIR", + "DBUserSIR": "usersir", + "DBPasswordSIR": "S1r22$Us", + + "RepositoryArchivoElectronicoOficial": "Z:/Recursos/ControlDocumentos/IMPORTADORA AMAZON MEXICO S DE RL DE CV/" + + +} + + diff --git a/log/Referencias.txt b/log/Referencias.txt new file mode 100644 index 0000000..178a7a7 --- /dev/null +++ b/log/Referencias.txt @@ -0,0 +1 @@ +23-00401I diff --git a/log/fechayHora.txt b/log/fechayHora.txt new file mode 100644 index 0000000..bdfe38d --- /dev/null +++ b/log/fechayHora.txt @@ -0,0 +1 @@ +2023-03-30 14:15:40 - 23-00401I