Skip to content

Commit

Permalink
Merge branch 'master' into cleaning_defs
Browse files Browse the repository at this point in the history
  • Loading branch information
egarciadiaz authored Sep 26, 2023
2 parents ef9c7a6 + 7ef06c4 commit 729eb23
Show file tree
Hide file tree
Showing 11 changed files with 1,081 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[bumpversion]
current_version = 3.0.0
current_version = 3.6.0
14 changes: 7 additions & 7 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ on:
jobs:
build:

runs-on: ubuntu-latest
runs-on: ubuntu-20.04
strategy:
fail-fast: false
# You can use PyPy versions in python-version.
Expand All @@ -33,25 +33,25 @@ jobs:
if: matrix.python-version == '2.7'
run: |
sudo apt update
sudo apt install python2 python-pip
sudo apt install python2 python2-dev
curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py
sudo python2 get-pip.py
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2
printf '1\n' | sudo update-alternatives --config python
cd /usr/bin
sudo ln -s /usr/bin/pip2 ./pip
- name: Upgrade pip
run: |
pip install --upgrade pip setuptools wheel
- name: Install dependencies
run: |
pip install -r requirements-dev.txt
pip install .
# if [[ $TRAVIS_PYTHON_VERSION == 2.6 ]]; then pip install unittest2; fi
pip install coveralls
- name: Run test
if: matrix.python-version == '2.7'
run: |
python setup.py test
- name: Run test
if: matrix.python-version == '3.11'
run: |
coverage run setup.py test
python -m unittest discover -v
2 changes: 1 addition & 1 deletion gestionatr/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# -*- coding: utf-8 -*-
__version__ = '3.1.8'
__version__ = '3.6.0'
124 changes: 124 additions & 0 deletions gestionatr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import six
import sys
import click
import re
from suds.cache import NoCache
from suds.client import Client
from suds.transport.https import HttpAuthenticated
Expand All @@ -15,6 +16,7 @@
from gestionatr.input.messages import message_gas
from gestionatr.input.messages.message import except_f1
from gestionatr.output.messages.sw_p0 import ENVELOP_BY_DISTR
from gestionatr.output.messages.sw_a5_29 import ENVELOP_GAS_BY_DISTR
from gestionatr.exceptions import *

from gestionatr import __version__
Expand All @@ -38,6 +40,25 @@
</MensajeSolicitudInformacionAlRegistroDePS>
"""

A29_TEMPLATE = """
<sctdapplication xmlns="http://localhost/sctd/A529">
<cabecera>
<codenvio>GML</codenvio>
<empresaemisora>{emisora}</empresaemisora>
<empresadestino>{destino}</empresadestino>
<fechacomunicacion>{fecha_solicitud}</fechacomunicacion>
<horacomunicacion>{hora_solicitud}</horacomunicacion>
<codproceso>29</codproceso>
<tipomensaje>A5</tipomensaje>
</cabecera>
<a529>
<fechacreacion>{fecha_solicitud}</fechacreacion>
<horacreacion>{hora_solicitud}</horacreacion>
<cups>{cups}</cups>
<historicoconsumo>N</historicoconsumo>
</a529>
</sctdapplication>
"""

def get_gestionatr_version(ctx, param, value):
if not value or ctx.resilient_parsing:
Expand Down Expand Up @@ -80,6 +101,89 @@ def test(filename, sector):
sys.stdout.flush()


def request_atr_29(url, user, password, xml_str=None, params=None):
import random
import re
from datetime import datetime
if xml_str is None and params is None:
raise ValueError("XML or params must be passed to request_A5")
if xml_str is None and params:
codi_receptor = params['destino']
params['fecha_solicitud'] = datetime.now().strftime('%Y-%m-%d')
params['hora_solicitud'] = datetime.now().strftime('%H:%M:%S')
params['solicitud'] = 10**11 + int((random.random() * 10**11))
xml_str = re.sub(r'\s+<', '<', A29_TEMPLATE)
xml_str = re.sub(r'\s+$', '', xml_str)
xml_str = re.sub(r'\n', '', xml_str).format(**params)
else:
codi_receptor = xml_str.split("<empresadestino>")[1].split("</empresadestino>")[0]

base64string = base64.encodestring(str('%s:%s' % (user, password))).replace('\n', '')
headers = {
"Authorization": "Basic %s" % base64string,
"content-type": 'text/xml; charset=utf-8',
}

# Clean XML
xml_str = xml_str.strip()
xml_str = xml_str.replace("'utf-8'", "'UTF-8'")
xml_str = xml_str.replace("<?xml version='1.0' encoding='UTF-8'?>", "")
xml_str = xml_str.replace("""<sctdapplication xmlns="http://localhost/sctd/A529">""", "")
xml_str = xml_str.replace("""</sctdapplication>""", "")
xml_str = xml_str.replace("<", "<a529:")
xml_str = xml_str.replace("<a529:/", "</a529:")

# Fem sempre 2 intents: amb el que esta definit per aquella distri i si va malament amb una plantilla base que
# sol funcionar en la majoria. Aixi si una distri no la tenim documentada es fa el intent amb les 2 plantilles
# principals que tenim. La "altres" i la "reintent"

distri_envelop = ENVELOP_GAS_BY_DISTR.get(codi_receptor, ENVELOP_GAS_BY_DISTR.get("altres"))
error = None
for envelop in [distri_envelop]:
xml_str_to_use = xml_str
soap_content = envelop['template'].format(xml_str=xml_str_to_use)

# Send request
h = headers.copy()
h.update(envelop['extra_headers'])
res = requests.post(url, data=soap_content, headers=h, auth=(user, password))
res = res.content
try:
def find_child(element, child_name):
res = None
if child_name in element.tag:
return element
for child in element:
res = find_child(child, child_name)
if res is not None:
break
return res

res = re.sub(r'\<[^: \n/]+:', '<', res)
res = re.sub(r'\</[^: \n/]+:', '</', res)
res = res.replace("<consultaCupsResponse>", """<sctdapplication>""")
res = res.replace("</consultaCupsResponse>", """</sctdapplication>""", 1)
aux = etree.fromstring(res)
aux_res = find_child(aux, "sctdapplication")

res = etree.tostring(aux_res)
return res
except A529FaultError as A529efe:
if not error:
error = A529efe
except Exception as e:
if not error:
error = e

if error:
if isinstance(error, A529FaultError):
raise error
else:
print(error)

return res


def request_p0(url, user, password, xml_str=None, params=None):
import random
import re
Expand Down Expand Up @@ -187,4 +291,24 @@ def sollicitar_p0(url, user, password, file=None, emisora=None, destino=None, cu
res = etree.fromstring(res)
print(etree.tostring(res, pretty_print=True))

@atr.command(name='a529')
@click.option('-u', '--url', default='http://localhost', help=u'URL del webservice', show_default=True)
@click.option('-s', '--user', default='admin', help=u'User del webservice', show_default=True)
@click.option('-p', '--password', default='admin', help=u'Password del webservice', show_default=True)
@click.option('-f', '--file', help=u'Fitxer 29 pas A5 per enviar', show_default=True)
@click.option('--emisora', help='Código REE empresa emisora')
@click.option('--destino', help='Código REE empresa destino')
@click.option('--cups', help='CUPS')
def sollicitar_a529(url, user, password, file=None, emisora=None, destino=None, cups=None):
params = None
from lxml import etree
if emisora and destino and cups:
params = {
'emisora': emisora,
'destino': destino,
'cups': cups
}

res = request_atr_29(url, user, password, file, params)
res = etree.fromstring(res)
print(etree.tostring(res, pretty_print=True))
1 change: 1 addition & 0 deletions gestionatr/defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2249,6 +2249,7 @@
('11', u'Pendiente envío de fichero de coeficientes de reparto variables para el año en curso'),
('13', u'Información aplicación descuento por retardo en activación autoconsumo imputable al distribuidor'),
('14', u'Información aplicación descuento por retardo en activación autoconsumo NO imputable al distribuidor'),
('15', u'Alta en autoconsumo colectivo comunicada por un participante'),
]

TABLA_110 = [('01', u'Acompaña curva de carga'),
Expand Down
4 changes: 4 additions & 0 deletions gestionatr/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
class P0FaultError(Exception):
pass


class A529FaultError(Exception):
pass
Loading

0 comments on commit 729eb23

Please sign in to comment.