You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PythonCode/SyncReferences2IONOS/SyncReferences2IONOS.py

166 lines
6.5 KiB

2 years ago
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.")
2 years ago
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.")
2 years ago
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={SQL Server};SERVER=" + ServerSIR
2 years ago
+ ";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, Res.sDescripcion,
2 years ago
P.Clave, P.Cliente FROM SIR.Admin.SIR_VT_PedimPagados P
INNER JOIN SIR.SIR.SIR_149_PEDIMENTO AS Peds ON Peds.nIdPedimento149=ID
INNER JOIN SIR.SIR.SIR_216_ARCHIVOS_PEDIMENTO A ON A.nIdArchM3216=Peds.nIdArchM3216
INNER JOIN SIR.SIR.SIR_217_PEDIMENTO_ARCHIVOM3 Rel on A.nIdArchM3216 = Rel.nIdArchM3216
INNER JOIN SIR.SIR.SIR_218_RESPUESTA_VALIDACION Res on Res.nIdArchM3216 = Rel.nIdArchM3216 AND Res.sDescripcion LIKE '%.err'
WHERE P.ClienteClave=2096 and p.[Pedimento FechaPago]>=CAST( GETDATE()-2 AS Date ) """)
2 years ago
for row in cursor:
referencia = row[0]
archivoM = row[1]
2 years ago
aduana = row[2]
patente = row[3]
pedimento = row[4]
fPago = row[5]
tipoCambio = row[6]
descripcion = row[7]
clave = row[8]
cliente = row[9]
2 years ago
referenceFolder = TempFolder + referencia
archivo_sDescripcion = os.path.join(referenceFolder, descripcion)
if referencia in processed_references:
print(f"La referencia {referencia} ya ha sido procesada.")
continue
2 years ago
if os.path.exists(referenceFolder):
shutil.rmtree(referenceFolder)
shutil.copytree(RepositoryArchivoElectronicoOficial + str(YEAR) + '/' + referencia, referenceFolder)
# Validar si el archivo sDescripcion existe en la carpeta del folder
if not os.path.isfile(archivo_sDescripcion):
print(f"El archivo {descripcion} no existe en la carpeta del folder para la referencia {referencia}. Proceso detenido.")
continue
2 years ago
zip_file = referenceFolder+'_____'+cliente+'.zip'
if os.path.exists(zip_file) == False:
ZipReference(referencia, referenceFolder, cliente)
2 years ago
# Procesar archivo
if WriteToLog(referencia):
processed_references.append(referencia)
URL = 'http://localhost:5000/api/AmazonInvoice/UploadSIRReference?ArchivoM=' +\
2 years ago
archivoM+'&aduana='+aduana+'&patente='+patente + \
'&pedimento='+pedimento+'&fPago=' + \
str(fPago)+'&TipoCambio='+str(tipoCambio)+'&clave='+clave
multiple_files = []
multiple_files.append(('files', (zip_file.replace(TempFolder,''), open(zip_file, 'rb'), 'application/zip')))
data = {
2 years ago
"ArchivoM": archivoM,
'aduana': aduana,
'patente': patente,
'pedimento': pedimento,
'fPago' : str(fPago),
'tipoCambio' : str(tipoCambio),
'clave': clave
}
print( f"la referencia {referencia} ya ha sido posteada." )
r = requests.post(url=URL,files=multiple_files, verify=False, timeout=1000000)
2 years ago
except Exception as e:
print("Error: %s" % e)
2 years ago
# WriteToLog(r.text)
2 years ago
''' 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()
#URL = 'https://www.gemcousa.mx/GEMCOBackend/api/AmazonInvoice/UploadSIRReference?ArchivoM=' +\
# URL = 'http://localhost:5000/api/AmazonInvoice/UploadSIRReference?ArchivoM=' +\