Skip to content

Commit

Permalink
Autoformat with python -m black .
Browse files Browse the repository at this point in the history
  • Loading branch information
reingart committed Jun 6, 2021
1 parent d6088f6 commit 7e34a25
Show file tree
Hide file tree
Showing 55 changed files with 24,686 additions and 16,518 deletions.
174 changes: 106 additions & 68 deletions cot.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from builtins import str
from builtins import object

__author__ = "Mariano Reingart ([email protected])"
__copyright__ = "Copyright (C) 2010 Mariano Reingart"
__license__ = "LGPL 3.0"
Expand All @@ -30,35 +31,53 @@
from .utils import WebClient

HOMO = False
CACERT = "conf/arba.crt" # establecimiento de canal seguro (en producción)
CACERT = "conf/arba.crt" # establecimiento de canal seguro (en producción)

##URL = "https://cot.ec.gba.gob.ar/TransporteBienes/SeguridadCliente/presentarRemitos.do"
# Nuevo servidor para el "Remito Electrónico Automático"
URL = "http://cot.test.arba.gov.ar/TransporteBienes/SeguridadCliente/presentarRemitos.do" # testing
#URL = "https://cot.arba.gov.ar/TransporteBienes/SeguridadCliente/presentarRemitos.do" # prod.
# URL = "https://cot.arba.gov.ar/TransporteBienes/SeguridadCliente/presentarRemitos.do" # prod.


class COT(object):
"Interfaz para el servicio de Remito Electronico ARBA"
_public_methods_ = ['Conectar', 'PresentarRemito', 'LeerErrorValidacion',
'LeerValidacionRemito',
'AnalizarXml', 'ObtenerTagXml']
_public_attrs_ = ['Usuario', 'Password', 'XmlResponse',
'Version', 'Excepcion', 'Traceback', 'InstallDir',
'CuitEmpresa', 'NumeroComprobante', 'CodigoIntegridad', 'NombreArchivo',
'TipoError', 'CodigoError', 'MensajeError',
'NumeroUnico', 'Procesado', 'COT',
]

_public_methods_ = [
"Conectar",
"PresentarRemito",
"LeerErrorValidacion",
"LeerValidacionRemito",
"AnalizarXml",
"ObtenerTagXml",
]
_public_attrs_ = [
"Usuario",
"Password",
"XmlResponse",
"Version",
"Excepcion",
"Traceback",
"InstallDir",
"CuitEmpresa",
"NumeroComprobante",
"CodigoIntegridad",
"NombreArchivo",
"TipoError",
"CodigoError",
"MensajeError",
"NumeroUnico",
"Procesado",
"COT",
]

_reg_progid_ = "COT"
_reg_clsid_ = "{7518B2CF-23E9-4821-BC55-D15966E15620}"

Version = "%s %s" % (__version__, HOMO and 'Homologación' or '')
Version = "%s %s" % (__version__, HOMO and "Homologación" or "")

def __init__(self):
self.Usuario = self.Password = None
self.TipoError = self.CodigoError = self.MensajeError = ""
self.LastID = self.LastCMP = self.CAE = self.CAEA = self.Vencimiento = ''
self.LastID = self.LastCMP = self.CAE = self.CAEA = self.Vencimiento = ""
self.InstallDir = INSTALL_DIR
self.client = None
self.xml = None
Expand All @@ -71,7 +90,7 @@ def limpiar(self):
self.Excepcion = self.Traceback = ""
self.TipoError = self.CodigoError = self.MensajeError = ""
self.CuitEmpresa = self.NumeroComprobante = ""
self.NombreArchivo = self.CodigoIntegridad = ""
self.NombreArchivo = self.CodigoIntegridad = ""
self.COT = self.NumeroUnico = self.Procesado = ""

def Conectar(self, url=None, proxy="", wrapper=None, cacert=None, trace=False):
Expand All @@ -86,52 +105,66 @@ def PresentarRemito(self, filename, testing=""):
self.Excepcion = "Archivo no encontrado: %s" % filename
return False

archivo = open(filename,"rb")
archivo = open(filename, "rb")
if not testing:
response = self.client(user=self.Usuario, password=self.Password,
file=archivo)
response = self.client(
user=self.Usuario, password=self.Password, file=archivo
)
else:
response = open(testing).read()
self.XmlResponse = response
self.xml = SimpleXMLElement(response)
if 'tipoError' in self.xml:
self.xml = SimpleXMLElement(response)
if "tipoError" in self.xml:
self.TipoError = str(self.xml.tipoError)
self.CodigoError = str(self.xml.codigoError)
self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace")
if 'cuitEmpresa' in self.xml:
self.MensajeError = (
str(self.xml.mensajeError)
.decode("latin1")
.encode("ascii", "replace")
)
if "cuitEmpresa" in self.xml:
self.CuitEmpresa = str(self.xml.cuitEmpresa)
self.NumeroComprobante = str(self.xml.numeroComprobante)
self.NombreArchivo = str(self.xml.nombreArchivo)
self.CodigoIntegridad = str(self.xml.codigoIntegridad)
if 'validacionesRemitos' in self.xml:
self.CodigoIntegridad = str(self.xml.codigoIntegridad)
if "validacionesRemitos" in self.xml:
for remito in self.xml.validacionesRemitos.remito:
try:
cot = remito.cot
except AttributeError:
cot = ""
d = {
'NumeroUnico': str(remito.numeroUnico),
'COT': str(cot),
'Procesado': str(remito.procesado),
'Errores': [],
}
if 'errores' in remito:
"NumeroUnico": str(remito.numeroUnico),
"COT": str(cot),
"Procesado": str(remito.procesado),
"Errores": [],
}
if "errores" in remito:
for error in remito.errores.error:
d['Errores'].append((
str(error.codigo),
str(error.descripcion).decode('latin1').encode("ascii", "replace")))
d["Errores"].append(
(
str(error.codigo),
str(error.descripcion)
.decode("latin1")
.encode("ascii", "replace"),
)
)
self.remitos.append(d)
# establecer valores del primer remito (sin eliminarlo)
self.LeerValidacionRemito(pop=False)
return True
return True
except Exception as e:
ex = traceback.format_exception( sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
self.Traceback = ''.join(ex)
try:
self.Excepcion = traceback.format_exception_only( sys.exc_info()[0], sys.exc_info()[1])[0]
except:
self.Excepcion = u"<no disponible>"
return False
ex = traceback.format_exception(
sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
)
self.Traceback = "".join(ex)
try:
self.Excepcion = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)[0]
except:
self.Excepcion = u"<no disponible>"
return False

def LeerValidacionRemito(self, pop=True):
"Leeo el próximo remito"
Expand All @@ -141,10 +174,10 @@ def LeerValidacionRemito(self, pop=True):
remito = self.remitos[0]
if pop:
del self.remitos[0]
self.NumeroUnico = remito['NumeroUnico']
self.Procesado = remito['Procesado']
self.COT = remito['COT']
self.errores = remito['Errores']
self.NumeroUnico = remito["NumeroUnico"]
self.Procesado = remito["Procesado"]
self.COT = remito["COT"]
self.errores = remito["Errores"]
return True
else:
self.NumeroUnico = ""
Expand All @@ -169,7 +202,7 @@ def AnalizarXml(self, xml=""):
"Analiza un mensaje XML (por defecto la respuesta)"
try:
if not xml:
xml = self.XmlResponse
xml = self.XmlResponse
self.xml = SimpleXMLElement(xml)
return True
except Exception as e:
Expand All @@ -184,52 +217,57 @@ def ObtenerTagXml(self, *tags):
xml = self.xml
# por cada tag, lo busco segun su nombre o posición
for tag in tags:
xml = xml(tag) # atajo a getitem y getattr
xml = xml(tag) # atajo a getitem y getattr
# vuelvo a convertir a string el objeto xml encontrado
return str(xml)
except Exception as e:
self.Excepcion = u"%s" % (e)


# busco el directorio de instalación (global para que no cambie si usan otra dll)
if not hasattr(sys, "frozen"):
if not hasattr(sys, "frozen"):
basepath = __file__
elif sys.frozen=='dll':
elif sys.frozen == "dll":
import win32api

basepath = win32api.GetModuleFileName(sys.frozendllhandle)
else:
basepath = sys.executable
INSTALL_DIR = os.path.dirname(os.path.abspath(basepath))


if __name__=="__main__":
if __name__ == "__main__":

if "--register" in sys.argv or "--unregister" in sys.argv:
import win32com.server.register

win32com.server.register.UseCommandLine(COT)
sys.exit(0)
elif len(sys.argv)<4:
print("Se debe especificar el nombre de archivo, usuario y clave como argumentos!")
elif len(sys.argv) < 4:
print(
"Se debe especificar el nombre de archivo, usuario y clave como argumentos!"
)
sys.exit(1)

cot = COT()
filename = sys.argv[1] # TB_20111111112_000000_20080124_000001.txt
cot.Usuario = sys.argv[2] # 20267565393
filename = sys.argv[1] # TB_20111111112_000000_20080124_000001.txt
cot.Usuario = sys.argv[2] # 20267565393
cot.Password = sys.argv[3] # 23456

if '--testing' in sys.argv:
#test_response = "cot_response_multiple_errores.xml"
#test_response = "cot_response_2_errores.xml"
#test_response = "cot_response_3_sinerrores.xml"
if "--testing" in sys.argv:
# test_response = "cot_response_multiple_errores.xml"
# test_response = "cot_response_2_errores.xml"
# test_response = "cot_response_3_sinerrores.xml"
test_response = "cot_respuesta_2019.xml"
else:
test_response = ""

if not HOMO:
for i, arg in enumerate(sys.argv):
if arg.startswith("--prod"):
URL = URL.replace("http://cot.test.arba.gov.ar",
"https://cot.arba.gov.ar")
URL = URL.replace(
"http://cot.test.arba.gov.ar", "https://cot.arba.gov.ar"
)
print("Usando URL:", URL)
break
if arg.startswith("https"):
Expand All @@ -239,9 +277,9 @@ def ObtenerTagXml(self, *tags):

proxy = None if not "--proxy" in sys.argv else "user:pass@host:1234"

cot.Conectar(URL, trace='--trace' in sys.argv, cacert=CACERT, proxy=proxy)
cot.Conectar(URL, trace="--trace" in sys.argv, cacert=CACERT, proxy=proxy)
cot.PresentarRemito(filename, testing=test_response)

if cot.Excepcion:
print("Excepcion:", cot.Excepcion)
print("Traceback:", cot.Traceback)
Expand All @@ -253,7 +291,7 @@ def ObtenerTagXml(self, *tags):
print("Codigo Integridad:", cot.CodigoIntegridad)

print("Error General:", cot.TipoError, "|", cot.CodigoError, "|", cot.MensajeError)

# recorro los remitos devueltos e imprimo sus datos por cada uno:
while cot.LeerValidacionRemito():
print("Numero Unico:", cot.NumeroUnico)
Expand All @@ -264,6 +302,6 @@ def ObtenerTagXml(self, *tags):

# Ejemplos de uso ObtenerTagXml
if False:
print("cuit", cot.ObtenerTagXml('cuitEmpresa'))
print("p0", cot.ObtenerTagXml('validacionesRemitos', 'remito', 0, 'procesado'))
print("p1", cot.ObtenerTagXml('validacionesRemitos', 'remito', 1, 'procesado'))
print("cuit", cot.ObtenerTagXml("cuitEmpresa"))
print("p0", cot.ObtenerTagXml("validacionesRemitos", "remito", 0, "procesado"))
print("p1", cot.ObtenerTagXml("validacionesRemitos", "remito", 1, "procesado"))
Loading

0 comments on commit 7e34a25

Please sign in to comment.