cfdi-uuid/source/sat/util.py

86 lines
2.1 KiB
Python
Raw Normal View History

2023-01-17 01:07:39 -06:00
#!/usr/bin/env python
2023-01-26 23:08:00 -06:00
import logging
2023-01-17 23:00:39 -06:00
from pathlib import Path
2023-01-17 01:07:39 -06:00
from uuid import UUID
2023-01-17 23:00:39 -06:00
from .cfdi_cert import SATCertificate
2023-01-17 01:07:39 -06:00
from .portal_sat import PortalSAT
2023-01-17 23:00:39 -06:00
from conf import RUTA_FIEL, NOMBRE_FIEL
2023-01-17 01:07:39 -06:00
2023-01-26 23:08:00 -06:00
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
LOG_DATE = '%d/%m/%Y %H:%M:%S'
logging.addLevelName(logging.ERROR, '\033[1;41mERROR\033[1;0m')
logging.addLevelName(logging.DEBUG, '\x1b[33mDEBUG\033[1;0m')
logging.addLevelName(logging.INFO, '\x1b[32mINFO\033[1;0m')
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=LOG_DATE)
log = logging.getLogger(__name__)
2023-01-17 01:07:39 -06:00
def validate_uuid(value):
try:
UUID(value)
return True
except ValueError:
return False
2023-01-17 23:00:39 -06:00
def validate_fiel(rfc):
cert = {}
error = ''
fiel_cer = f'{NOMBRE_FIEL}.cer'
fiel_pem = f'{NOMBRE_FIEL}.pem'
path_fiel = Path(RUTA_FIEL) / rfc.lower()
path_fiel_cer = path_fiel / fiel_cer
path_fiel_pem = path_fiel / fiel_pem
if not path_fiel_cer.exists():
error = f'No se encontró el archivo: {path_fiel_cer}'
return cert, error
if not path_fiel_pem.exists():
error = f'No se encontró el archivo: {path_fiel_pem}'
return cert, error
cert = SATCertificate(str(path_fiel_cer), str(path_fiel_pem))
2023-01-17 23:00:39 -06:00
return cert, error
2023-01-27 15:38:05 -06:00
def get_uuid(rfc, tipo, cfdi_uuid):
2023-01-17 01:07:39 -06:00
data = {'error': '', 'xml': ''}
2023-01-17 23:00:39 -06:00
if not validate_uuid(cfdi_uuid):
2023-01-17 01:07:39 -06:00
data['error'] = 'UUID inválido'
return data
2023-01-27 15:38:05 -06:00
if not tipo.lower() in ('e', 'r'):
data['error'] = 'Tipo inválido, debe ser e o r'
return data
2023-01-17 23:00:39 -06:00
cert, error = validate_fiel(rfc)
if not cert:
data['error'] = error
return data
2023-01-25 23:33:51 -06:00
try:
sat = PortalSAT()
sat.login(cert)
2023-01-17 23:00:39 -06:00
2023-01-25 23:33:51 -06:00
if not sat.is_connect:
sat.logout()
data['error'] = sat.error
2023-01-27 15:38:05 -06:00
log.error(sat.error)
2023-01-25 23:33:51 -06:00
return data
2023-01-17 23:00:39 -06:00
2023-01-27 15:38:05 -06:00
data = sat.get_uuid(tipo, cfdi_uuid)
2023-01-25 23:33:51 -06:00
sat.logout()
except Exception as e:
log.error(e)
data['xml'] = ''
data['error'] = str(e)
2023-01-17 23:00:39 -06:00
2023-01-17 01:07:39 -06:00
return data