From 21f881f2b0ecb60078f7f33a0297784622f57d8e Mon Sep 17 00:00:00 2001
From: Emmanuel Cazenave <ecazenave@entrouvert.com>
Date: Wed, 20 Nov 2019 15:39:16 +0100
Subject: [PATCH 3/3] mdel: adapt filenames and routing (#36870)

---
 passerelle/apps/mdel/mdel.py   | 48 ++++++++++++++++++++++-------
 passerelle/apps/mdel/models.py | 12 ++++++--
 tests/test_mdel.py             | 55 +++++++++++++++++++++++++++++++++-
 3 files changed, 100 insertions(+), 15 deletions(-)

diff --git a/passerelle/apps/mdel/mdel.py b/passerelle/apps/mdel/mdel.py
index 02bc4ac4..d8db1cf2 100644
--- a/passerelle/apps/mdel/mdel.py
+++ b/passerelle/apps/mdel/mdel.py
@@ -25,7 +25,7 @@ from dateutil.parser import parse as dateutil_parse
 from django.core.files.storage import default_storage
 from django.core.files.base import ContentFile
 
-from utils import ElementFactory
+from utils import ElementFactory, MELODIE
 
 from passerelle.utils.jsonresponse import APIError
 
@@ -71,6 +71,7 @@ class Common(MDELBase):
     def __init__(self, *args, **kwargs):
         self.flow_type = args[0]
         self.num = args[1]
+        self.doc = kwargs.get('doc')
         super(Common, self).__init__()
 
     def save(self, folder):
@@ -134,8 +135,10 @@ class Common(MDELBase):
             ElementFactory('FichierFormulaire')
         ])
 
-        if not form_files:
+        if not form_files and not self.doc:
             form_files = [self.code + '-doc-.xml']
+        if not form_files and self.doc:
+            form_files = [self.doc.filename]
 
         for f in form_files:
             document.find('FichierFormulaire').append(
@@ -154,9 +157,9 @@ class Message(Common):
 
     def __init__(
             self, flow_type, num, zip_code, date=None,
-            platform_id='1', form_files=None, attached_files=None):
+            platform_id='1', form_files=None, attached_files=None, software=None, doc=None):
 
-        super(Message, self).__init__(flow_type, num)
+        super(Message, self).__init__(flow_type, num, doc=doc)
 
         etree._namespace_map[self.ns_uri] = self.ns_prefix
 
@@ -176,10 +179,16 @@ class Message(Common):
         body = ElementFactory('Body', namespace=self.ns_uri)
         content = ElementFactory('Content', namespace=self.ns_uri)
         aller = ElementFactory('Aller', namespace=self.ns_uri)
+
+        code = self.code
+        if 'AEC-LA' in self.flow_type and software == MELODIE:
+            aller.append(ElementFactory('NumeroDemarche', text='EtatCivil'))
+            code = 'ActeEtatCivil-XML'
+
         aller.extend([
             self.teledemarche_xml(num, date, platform_id),
             self.routage_xml(zip_code),
-            self.document_xml(self.code, form_files)
+            self.document_xml(code, form_files)
         ])
 
         [aller.append(f) for f in self.piecejointe_xml(attached_files) if f]
@@ -198,19 +207,28 @@ class Description(Common):
 
     def __init__(
             self, flow_type, num, zip_code, date=None,
-            platform_id='1', form_files=[], attached_files=[]):
+            platform_id='1', form_files=[], attached_files=[],
+            software=None, step=None, doc=None
+    ):
 
         super(Description, self).__init__(
             flow_type, num, zip_code, date,
-            platform_id, form_files, attached_files
+            platform_id, form_files, attached_files, doc=doc
         )
+        self.software = software
+        self.step = step
 
         root = ElementFactory('EnteteMetierEnveloppe', attrib={'xmlns': self.xmlns})
 
+        code = self.code
+        if 'AEC-LA' in self.flow_type and self.software == MELODIE:
+            root.append(ElementFactory('NumeroDemarche', text='EtatCivil'))
+            code = 'ActeEtatCivil-XML'
+
         root.extend([
             self.teledemarche_xml(num, date, platform_id),
             self.routage_xml(zip_code),
-            self.document_xml(self.code, form_files)
+            self.document_xml(code, form_files)
         ])
 
         for f in self.piecejointe_xml(attached_files):
@@ -220,6 +238,8 @@ class Description(Common):
 
     @property
     def filename(self):
+        if 'AEC-LA' in self.flow_type and self.software == MELODIE:
+            return '%s-EtatCivil-ent-%s.xml' % (self.num, self.step)
         return '%s-ent-.xml' % self.code
 
 
@@ -227,12 +247,18 @@ class Data(MDELBase):
     """Class describing a -doc.xml file
     """
 
-    def __init__(self, demand_id, data):
+    def __init__(self, demand_id, data, software=None, step=None):
         self.data = self.data_validator(data)
         self.demand_id = demand_id
+        self.software = software
+        self.step = step
 
     @property
     def filename(self):
+        if 'AEC-LA' in self.demand_id and self.software == MELODIE:
+            return '%s-doc-ActeEtatCivil-XML-1-%s.xml' % (
+                self.demand_id.replace('AEC-LA', 'EtatCivil'), self.step
+            )
         return '%s-doc-.xml' % self.demand_id
 
     def save(self, folder):
@@ -439,11 +465,11 @@ class AECData(Data):
         'titulaire_prenoms'
     ]
 
-    def __init__(self, demand_id, data):
+    def __init__(self, demand_id, data, software, demand_num):
         self.root_element = 'EnveloppeMetierType'
         self.root_attributes = {'canal_utilise': '0'}
 
-        super(AECData, self).__init__(demand_id, data)
+        super(AECData, self).__init__(demand_id, data, software, demand_num)
 
 
 def json_to_xml(path, value, parent):
diff --git a/passerelle/apps/mdel/models.py b/passerelle/apps/mdel/models.py
index b476d759..2bd3a13d 100644
--- a/passerelle/apps/mdel/models.py
+++ b/passerelle/apps/mdel/models.py
@@ -179,6 +179,8 @@ class Demand(models.Model):
 
     @property
     def name(self):
+        if self.resource.software == MELODIE and self.flow_type == 'AEC-LA':
+            return '%s-%s-%d' % (self.num, 'EtatCivil', self.step)
         return '%s-%s--%d' % (self.num, self.flow_type, self.step)
 
     @property
@@ -318,18 +320,22 @@ class Demand(models.Model):
                 formdata['qualite_demandeur'] = formdata['qualite_demandeur_autre']
                 formdata['qualite_demandeur_raw'] = 'Autre'
 
-            doc = mdel.AECData(self.demand_id, formdata)
+            doc = mdel.AECData(self.demand_id, formdata, self.resource.software, self.step)
             doc.save(inputs_dir)
             input_files['demande'] = doc.filename
 
         submission_date = formdata.get('receipt_time', None)
 
-        message = mdel.Message(flow_type, demand_num, code_insee, date=submission_date)
+        message = mdel.Message(
+            flow_type, demand_num, code_insee, date=submission_date,
+            software=self.resource.software, doc=doc
+        )
         message.save(inputs_dir)
         input_files['message'] = message.filename
 
         description = mdel.Description(flow_type, demand_num, code_insee, date=submission_date,
-                                       attached_files=attached_files)
+                                       attached_files=attached_files,
+                                       software=self.resource.software, step=self.step, doc=doc)
         description.save(inputs_dir)
         input_files['enveloppe'] = description.filename
 
diff --git a/tests/test_mdel.py b/tests/test_mdel.py
index 82fc8699..187a86c5 100644
--- a/tests/test_mdel.py
+++ b/tests/test_mdel.py
@@ -30,7 +30,7 @@ import pytest
 
 from passerelle.apps.mdel.models import MDEL, Demand
 from passerelle.apps.mdel.mdel import Message, Description, AttachedFile, get_resource_base_dir
-from passerelle.apps.mdel.utils import parse_date
+from passerelle.apps.mdel.utils import parse_date, MELODIE
 
 import utils
 
@@ -68,6 +68,11 @@ def setup(db):
     return utils.setup_access_rights(MDEL.objects.create(slug='test'))
 
 
+@pytest.fixture
+def melodie_conn(db):
+    return utils.setup_access_rights(MDEL.objects.create(slug='test', software=MELODIE))
+
+
 @pytest.fixture(params=[
                 json.loads(get_file_from_test_base_dir('formdata_aec_naiss.json')),
                 json.loads(get_file_from_test_base_dir('formdata_aec_mariage.json')),
@@ -527,3 +532,51 @@ def test_date_parsing():
     with pytest.raises(APIError) as error:
         date = parse_date('28-02-2018')
     assert 'date u\'28-02-2018\' not iso-formated' in str(error)
+
+
+def test_aec_melodie(app, melodie_conn):
+    aec_payload = json.loads(get_file_from_test_base_dir('formdata_aec_naiss.json'))
+    resp = app.post_json('/mdel/test/create', params=aec_payload, status=200)
+
+    assert resp.json['data']['demand_id'] == '15-4-AEC-LA'
+
+    basedir = os.path.join(get_resource_base_dir(), 'test', 'inputs', '15-4-EtatCivil-0')
+    assert os.path.exists(basedir)
+    check_zip_file(
+        basedir + '.zip',
+        ['message.xml', '15-4-EtatCivil-ent-0.xml', '15-4-EtatCivil-doc-ActeEtatCivil-XML-1-0.xml']
+    )
+
+    doc = os.path.join(basedir, '15-4-EtatCivil-doc-ActeEtatCivil-XML-1-0.xml')
+    assert os.path.exists(doc)
+    validate_schema(doc, AEC_XSD)
+
+    ent = os.path.join(basedir, '15-4-EtatCivil-ent-0.xml')
+    assert os.path.exists(ent)
+    root = letree.parse(ent).getroot()
+    num_dem = root[0]
+    assert letree.QName(num_dem).localname == 'NumeroDemarche'
+    assert num_dem.text == 'EtatCivil'
+    ns = {'ns': 'http://finances.gouv.fr/dgme/gf/composants/teledemarchexml/donnee/metier'}
+    assert root.find('ns:Document/ns:Code', namespaces=ns).text == 'ActeEtatCivil-XML'
+    assert root.find('ns:Document/ns:Nom', namespaces=ns).text == 'ActeEtatCivil-XML'
+    assert root.find('ns:Document/ns:FichierFormulaire/ns:FichierDonnees', namespaces=ns).text == \
+        '15-4-EtatCivil-doc-ActeEtatCivil-XML-1-0.xml'
+
+    message = os.path.join(basedir, 'message.xml')
+    assert os.path.exists(message)
+    root = letree.parse(message).getroot()
+    ns = {
+        'ns1': 'http://finances.gouv.fr/dgme/gf/composants/teledemarchexml/donnee/metier',
+        'ns2': 'http://finances.gouv.fr/dgme/pec/message/v1'
+    }
+    assert root.find('ns2:Body/ns2:Content/ns2:Aller/ns1:NumeroDemarche', namespaces=ns).text \
+        == 'EtatCivil'
+    assert root.find('ns2:Body/ns2:Content/ns2:Aller/ns1:Document/ns1:Code', namespaces=ns).text \
+        == 'ActeEtatCivil-XML'
+    assert root.find('ns2:Body/ns2:Content/ns2:Aller/ns1:Document/ns1:Nom', namespaces=ns).text \
+        == 'ActeEtatCivil-XML'
+    assert root.find(
+        'ns2:Body/ns2:Content/ns2:Aller/ns1:Document/ns1:FichierFormulaire/ns1:FichierDonnees',
+        namespaces=ns
+    ).text == '15-4-EtatCivil-doc-ActeEtatCivil-XML-1-0.xml'
-- 
2.20.1

