From d4a8a4cfb8812ee45d4e01d904e00e862e394a46 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Sun, 18 Dec 2022 23:20:46 +0100
Subject: [PATCH 2/3] toulouse-maelis: apply direct debit order WS on RL1
 (#72563)

---
 ...n => test_get_rl1_direct_debit_order.json} |  0
 functests/toulouse_maelis/test_invoice.py     |  8 +-
 .../toulouse_maelis/invoice_schemas.py        | 12 +--
 passerelle/contrib/toulouse_maelis/models.py  | 13 ++-
 tests/test_toulouse_maelis.py                 | 98 ++++++++++++++-----
 5 files changed, 85 insertions(+), 46 deletions(-)
 rename functests/toulouse_maelis/data/{test_get_direct_debit_order.json => test_get_rl1_direct_debit_order.json} (100%)

diff --git a/functests/toulouse_maelis/data/test_get_direct_debit_order.json b/functests/toulouse_maelis/data/test_get_rl1_direct_debit_order.json
similarity index 100%
rename from functests/toulouse_maelis/data/test_get_direct_debit_order.json
rename to functests/toulouse_maelis/data/test_get_rl1_direct_debit_order.json
diff --git a/functests/toulouse_maelis/test_invoice.py b/functests/toulouse_maelis/test_invoice.py
index 2938e2ba..da2c4562 100644
--- a/functests/toulouse_maelis/test_invoice.py
+++ b/functests/toulouse_maelis/test_invoice.py
@@ -2,37 +2,35 @@ import requests
 
 from .conftest import diff, link, unlink
 
 
 def test_direct_debit_order(conn, create_data):
     unlink(conn, create_data['name_id'])
     link(conn, create_data)
 
-    url = conn + '/add-direct-debit-order?NameID=%s' % create_data['name_id']
+    url = conn + '/add-rl1-direct-debit-order?NameID=%s' % create_data['name_id']
     payload = {
-        'numPerson': create_data['rl1_num'],
         'codeRegie': '1',
         'bank/bankBIC': 'BDFEFR2T',
         'bank/bankIBAN': 'FR7630001007941234567890185',
         'bank/bankRUM': 'xxx',
         'bank/dateStart': '2023-01-01',
         'bank/bankAddress': '75049 PARIS cedex 01',
         'bank/civility': 'x',
         'bank/lastName': 'Ewing',
         'bank/firstName': 'John Ross',
     }
     resp = requests.post(url, json=payload)
     resp.raise_for_status()
     res = resp.json()
     assert res['data'] == 'ok'
 
-    url = conn + '/get-direct-debit-order?NameID=%s' % create_data['name_id']
+    url = conn + '/get-rl1-direct-debit-order?NameID=%s' % create_data['name_id']
     payload = {
-        'numPerson': create_data['rl1_num'],
         'codeRegie': '1',
         'dateRef': '2023-01-01',
     }
     resp = requests.post(url, json=payload)
     resp.raise_for_status()
     res = resp.json()
     res['data']['numPerson'] = 'N/A'
-    assert diff(res['data'], 'test_get_direct_debit_order.json')
+    assert diff(res['data'], 'test_get_rl1_direct_debit_order.json')
diff --git a/passerelle/contrib/toulouse_maelis/invoice_schemas.py b/passerelle/contrib/toulouse_maelis/invoice_schemas.py
index 01d38e75..7e2af4a2 100644
--- a/passerelle/contrib/toulouse_maelis/invoice_schemas.py
+++ b/passerelle/contrib/toulouse_maelis/invoice_schemas.py
@@ -58,44 +58,36 @@ PERSON_BANK_SCHEMA = {
 }
 
 
 ADD_DIRECT_DEBIT_ORDER_SCHEMA = {
     '$schema': 'http://json-schema.org/draft-04/schema#',
     'title': 'Add direct debit order',
     'description': "Ajout d'autorisation de prélèvement",
     'type': 'object',
-    'required': ['numPerson', 'bank', 'codeRegie'],
+    'required': ['bank', 'codeRegie'],
     'properties': {
-        'numPerson': {
-            'description': 'Numéro MAELIS de la personne',
-            'type': 'string',
-        },
         'bank': PERSON_BANK_SCHEMA,
         'codeRegie': {
             'description': 'Code de la régie',
             'type': 'string',
         },
     },
     'additionalProperties': False,
     'unflatten': True,
 }
 
 
 GET_DIRECT_DEBIT_ORDER_SCHEMA = {
     '$schema': 'http://json-schema.org/draft-04/schema#',
     'title': 'Get direct debit order',
     'description': "Lecture des informations relatives à l'autorisation de prélèvement en cours à la date de référence",
     'type': 'object',
-    'required': ['numPerson', 'codeRegie', 'dateRef'],
+    'required': ['codeRegie', 'dateRef'],
     'properties': {
-        'numPerson': {
-            'description': 'Numéro MAELIS de la personne',
-            'type': 'string',
-        },
         'codeRegie': {
             'description': 'Code de la régie',
             'type': 'string',
         },
         'dateRef': {
             'description': 'Date de référence ',
             'type': 'string',
             'pattern': '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
diff --git a/passerelle/contrib/toulouse_maelis/models.py b/passerelle/contrib/toulouse_maelis/models.py
index 82b3ef0a..8e2a052e 100644
--- a/passerelle/contrib/toulouse_maelis/models.py
+++ b/passerelle/contrib/toulouse_maelis/models.py
@@ -1544,41 +1544,46 @@ class ToulouseMaelis(BaseResource, HTTPResource):
         self.assert_update_indicator_payload_in_referential('ChildIndicator', post_data)
 
         self.call('Family', 'updatePersonIndicatorList', numPerson=child_id, **post_data)
         return {'data': 'ok'}
 
     @endpoint(
         display_category='Facture',
         description="Ajout d'autorisation de prélèvement",
-        name='add-direct-debit-order',
+        name='add-rl1-direct-debit-order',
         perm='can_access',
         parameters={'NameID': {'description': 'Publik NameID'}},
         post={
             'request_body': {'schema': {'application/json': invoice_schemas.ADD_DIRECT_DEBIT_ORDER_SCHEMA}}
         },
     )
-    def add_direct_debit_order(self, request, NameID, post_data):
+    def add_rl1_direct_debit_order(self, request, NameID, post_data):
         family_id = self.get_link(NameID).family_id
+        family = self.get_family_raw(family_id)
+
+        post_data['numPerson'] = family['RL1']['num']
         self.call('Invoice', 'addDirectDebitOrder', dossierNumber=family_id, **post_data)
         return {'data': 'ok'}
 
     @endpoint(
         display_category='Facture',
         description="Lecture des informations relatives à l'autorisation de prélèvement en cours à la date de référence",
-        name='get-direct-debit-order',
+        name='get-rl1-direct-debit-order',
         perm='can_access',
         parameters={'NameID': {'description': 'Publik NameID'}},
         post={
             'request_body': {'schema': {'application/json': invoice_schemas.GET_DIRECT_DEBIT_ORDER_SCHEMA}}
         },
     )
-    def get_direct_debit_order(self, request, NameID, post_data):
+    def get_rl1_direct_debit_order(self, request, NameID, post_data):
         family_id = self.get_link(NameID).family_id
+        family = self.get_family_raw(family_id)
 
+        post_data['numPerson'] = family['RL1']['num']
         response = self.call('Invoice', 'getDirectDebitOrder', dossierNumber=family_id, **post_data)
         data = serialize_object(response)
         return {'data': data}
 
 
 class Link(models.Model):
     resource = models.ForeignKey(ToulouseMaelis, on_delete=models.CASCADE)
     name_id = models.CharField(blank=False, max_length=256)
diff --git a/tests/test_toulouse_maelis.py b/tests/test_toulouse_maelis.py
index 29872a6b..c46efe03 100644
--- a/tests/test_toulouse_maelis.py
+++ b/tests/test_toulouse_maelis.py
@@ -75,16 +75,44 @@ def invoice_service():
     with ResponsesSoap(
         wsdl_url='https://example.org/InvoiceService?wsdl',
         wsdl_content=get_xml_file('InvoiceService.wsdl'),
         settings=Settings(strict=False, xsd_ignore_sequence_order=True),
     )() as mock:
         yield mock
 
 
+@pytest.fixture()
+def all_services():
+    family_service = ResponsesSoap(
+        wsdl_url='https://example.org/FamilyService?wsdl',
+        wsdl_content=get_xml_file('FamilyService.wsdl'),
+        settings=Settings(strict=False, xsd_ignore_sequence_order=True),
+    )
+    invoice_service = ResponsesSoap(
+        wsdl_url='https://example.org/InvoiceService?wsdl',
+        wsdl_content=get_xml_file('InvoiceService.wsdl'),
+        settings=Settings(strict=False, xsd_ignore_sequence_order=True),
+    )
+    with responses.RequestsMock() as mock:
+        mock.add(responses.GET, family_service.wsdl_url, body=family_service.wsdl_content, status=200)
+        mock.add(responses.GET, invoice_service.wsdl_url, body=invoice_service.wsdl_content, status=200)
+
+        def add_soap_response(service, *args, **kwargs):
+            if service == 'family':
+                family_service.add_soap_response(mock, *args, **kwargs)
+            elif service == 'invoice':
+                invoice_service.add_soap_response(mock, *args, **kwargs)
+            else:
+                assert False, 'service not defined'
+
+        mock.add_soap_response = add_soap_response
+        yield mock
+
+
 @pytest.fixture(scope='module')
 def django_db_setup(django_db_setup, django_db_blocker):
     with django_db_blocker.unblock():
         con = setup_access_rights(
             ToulouseMaelis.objects.get_or_create(
                 slug='test',
                 base_wsdl_url='https://example.org/',
                 zeep_wsse_username='maelis-webservice',
@@ -3267,26 +3295,29 @@ def test_update_child_indicator_wrong_referential_key_error(con, app):
     resp = app.post_json(url + '?NameID=local&child_id=613880', params=params)
     assert resp.json['err'] == 'wrong-key'
     assert (
         resp.json['err_desc']
         == "indicatorList/0/code key value 'plop' do not belong to 'ChildIndicator' required referential"
     )
 
 
-def test_add_direct_debit_order(invoice_service, con, app):
+def test_add_rl1_direct_debit_order(all_services, con, app):
     def request_check(request):
         assert request.dossierNumber == 1312
 
-    invoice_service.add_soap_response(
-        'addDirectDebitOrder', get_xml_file('R_add_direct_debit_order.xml'), request_check=request_check
+    all_services.add_soap_response('family', 'readFamily', get_xml_file('R_read_family.xml'))
+    all_services.add_soap_response(
+        'invoice',
+        'addDirectDebitOrder',
+        get_xml_file('R_add_direct_debit_order.xml'),
+        request_check=request_check,
     )
-    url = get_endpoint('add-direct-debit-order')
+    url = get_endpoint('add-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '22',
         'bank/bankBIC': 'BDFEFR2T',
         'bank/bankIBAN': 'FR7630001007941234567890185',
         'bank/bankRUM': 'xxx',
         'bank/dateStart': '2023-01-01',
         'bank/bankAddress': '75049 PARIS cedex 01',
         'bank/civility': 'x',
         'bank/lastName': 'Ewing',
@@ -3294,44 +3325,42 @@ def test_add_direct_debit_order(invoice_service, con, app):
     }
 
     Link.objects.create(resource=con, family_id='1312', name_id='local')
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 0
     assert resp.json['data'] == 'ok'
 
 
-def test_add_direct_debit_order_not_linked_error(con, app):
-    url = get_endpoint('add-direct-debit-order')
+def test_add_rl1_direct_debit_order_not_linked_error(con, app):
+    url = get_endpoint('add-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '22',
         'bank/bankBIC': 'BDFEFR2T',
         'bank/bankIBAN': 'FR7630001007941234567890185',
         'bank/bankRUM': 'xxx',
         'bank/dateStart': '2023-01-01',
         'bank/bankAddress': '75049 PARIS cedex 01',
         'bank/civility': 'x',
         'bank/lastName': 'Ewing',
         'bank/firstName': 'John Ross',
     }
 
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 'not-linked'
     assert resp.json['err_desc'] == 'User not linked to family'
 
 
-def test_add_direct_debit_order_soap_error(invoice_service, con, app):
-    invoice_service.add_soap_response(
-        'addDirectDebitOrder', get_xml_file('R_direct_debit_order_soap_error.xml'), status=500
+def test_add_rl1_direct_debit_order_soap_error(all_services, con, app):
+    all_services.add_soap_response('family', 'readFamily', get_xml_file('R_read_family.xml'))
+    all_services.add_soap_response(
+        'invoice', 'addDirectDebitOrder', get_xml_file('R_direct_debit_order_soap_error.xml'), status=500
     )
-
-    url = get_endpoint('add-direct-debit-order')
+    url = get_endpoint('add-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '12345',
         'bank/bankBIC': 'BDFEFR2T',
         'bank/bankIBAN': 'FR7630001007941234567890185',
         'bank/bankRUM': 'xxx',
         'bank/dateStart': '2023-01-01',
         'bank/bankAddress': '75049 PARIS cedex 01',
         'bank/civility': 'x',
         'bank/lastName': 'Ewing',
@@ -3339,26 +3368,29 @@ def test_add_direct_debit_order_soap_error(invoice_service, con, app):
     }
 
     Link.objects.create(resource=con, family_id='1312', name_id='local')
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 'Invoice-addDirectDebitOrder-soap:Server'
     assert resp.json['err_desc'] == "E520 : La REGIE CS [{0}] n''existe pas dans la base Maelis"
 
 
-def test_get_direct_debit_order(invoice_service, con, app):
+def test_get_rl1_direct_debit_order(all_services, con, app):
     def request_check(request):
         assert request.dossierNumber == 1312
 
-    invoice_service.add_soap_response(
-        'getDirectDebitOrder', get_xml_file('R_get_direct_debit_order.xml'), request_check=request_check
+    all_services.add_soap_response('family', 'readFamily', get_xml_file('R_read_family.xml'))
+    all_services.add_soap_response(
+        'invoice',
+        'getDirectDebitOrder',
+        get_xml_file('R_get_direct_debit_order.xml'),
+        request_check=request_check,
     )
-    url = get_endpoint('get-direct-debit-order')
+    url = get_endpoint('get-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '22',
         'dateRef': '2023-01-01',
     }
 
     Link.objects.create(resource=con, family_id='1312', name_id='local')
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 0
     assert resp.json['data'] == {
@@ -3368,36 +3400,48 @@ def test_get_direct_debit_order(invoice_service, con, app):
         'dateStart': '2023-01-01T00:00:00+01:00',
         'bankAddress': '75049 PARIS cedex 01',
         'civility': 'x',
         'lastName': 'Ewing',
         'firstName': 'John Ross',
     }
 
 
-def test_get_direct_debit_order_not_linked_error(con, app):
-    url = get_endpoint('get-direct-debit-order')
+def test_get_rl1_direct_debit_order_parameter_error(con, app):
+    url = get_endpoint('get-rl1-direct-debit-order')
+    params = {
+        'codeRegie': '22',
+        'dateRef': 'plop',
+    }
+
+    resp = app.post_json(url + '?NameID=local', params=params, status=400)
+    assert resp.json['err'] == 1
+    assert resp.json['err_class'] == 'passerelle.utils.jsonresponse.APIError'
+    assert resp.json['err_desc'] == "dateRef: 'plop' does not match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'"
+
+
+def test_get_rl1_direct_debit_order_not_linked_error(con, app):
+    url = get_endpoint('get-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '22',
         'dateRef': '2023-01-01',
     }
 
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 'not-linked'
     assert resp.json['err_desc'] == 'User not linked to family'
 
 
-def test_get_direct_debit_order_soap_error(invoice_service, con, app):
-    invoice_service.add_soap_response(
-        'getDirectDebitOrder', get_xml_file('R_direct_debit_order_soap_error.xml'), status=500
+def test_get_rl1_direct_debit_order_soap_error(all_services, con, app):
+    all_services.add_soap_response('family', 'readFamily', get_xml_file('R_read_family.xml'))
+    all_services.add_soap_response(
+        'invoice', 'getDirectDebitOrder', get_xml_file('R_direct_debit_order_soap_error.xml'), status=500
     )
-    url = get_endpoint('get-direct-debit-order')
+    url = get_endpoint('get-rl1-direct-debit-order')
     params = {
-        'numPerson': '613878',
         'codeRegie': '12345',
         'dateRef': '2023-01-01',
     }
 
     Link.objects.create(resource=con, family_id='1312', name_id='local')
     resp = app.post_json(url + '?NameID=local', params=params)
     assert resp.json['err'] == 'Invoice-getDirectDebitOrder-soap:Server'
     assert resp.json['err_desc'] == "E520 : La REGIE CS [{0}] n''existe pas dans la base Maelis"
-- 
2.30.2

