From dc8550b63e888b60110c0f042918a1074c0d676c Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Sun, 18 Dec 2022 23:22:52 +0100
Subject: [PATCH 3/3] toulouse-maelis: pass get-direct-debit order parameters
 in QS (#72563)

---
 functests/toulouse_maelis/test_invoice.py     |  4 +--
 .../toulouse_maelis/invoice_schemas.py        | 22 ---------------
 passerelle/contrib/toulouse_maelis/models.py  | 28 +++++++++++++++----
 tests/test_toulouse_maelis.py                 | 23 +++++++++++----
 4 files changed, 42 insertions(+), 35 deletions(-)

diff --git a/functests/toulouse_maelis/test_invoice.py b/functests/toulouse_maelis/test_invoice.py
index da2c4562..1d8e1ede 100644
--- a/functests/toulouse_maelis/test_invoice.py
+++ b/functests/toulouse_maelis/test_invoice.py
@@ -20,17 +20,17 @@ def test_direct_debit_order(conn, create_data):
         'bank/firstName': 'John Ross',
     }
     resp = requests.post(url, json=payload)
     resp.raise_for_status()
     res = resp.json()
     assert res['data'] == 'ok'
 
     url = conn + '/get-rl1-direct-debit-order?NameID=%s' % create_data['name_id']
-    payload = {
+    params = {
         'codeRegie': '1',
         'dateRef': '2023-01-01',
     }
-    resp = requests.post(url, json=payload)
+    resp = requests.get(url, params=params)
     resp.raise_for_status()
     res = resp.json()
     res['data']['numPerson'] = 'N/A'
     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 7e2af4a2..76e81ed3 100644
--- a/passerelle/contrib/toulouse_maelis/invoice_schemas.py
+++ b/passerelle/contrib/toulouse_maelis/invoice_schemas.py
@@ -69,30 +69,8 @@ ADD_DIRECT_DEBIT_ORDER_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': ['codeRegie', 'dateRef'],
-    'properties': {
-        '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}$',
-        },
-    },
-    'additionalProperties': False,
-    'unflatten': True,
-}
diff --git a/passerelle/contrib/toulouse_maelis/models.py b/passerelle/contrib/toulouse_maelis/models.py
index 8e2a052e..ee06102c 100644
--- a/passerelle/contrib/toulouse_maelis/models.py
+++ b/passerelle/contrib/toulouse_maelis/models.py
@@ -13,16 +13,17 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 from urllib.parse import urljoin
 
 import zeep
 from django.contrib.postgres.fields import JSONField
 from django.db import models
+from django.utils.dateparse import parse_date
 from django.utils.timezone import now
 from zeep.helpers import serialize_object
 from zeep.wsse.username import UsernameToken
 
 from passerelle.base.models import BaseResource, HTTPResource
 from passerelle.utils.api import endpoint
 from passerelle.utils.conversion import simplify
 from passerelle.utils.jsonresponse import APIError
@@ -1564,27 +1565,42 @@ class ToulouseMaelis(BaseResource, HTTPResource):
         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-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}}
+        parameters={
+            'NameID': {'description': 'Publik NameID'},
+            'codeRegie': {'description': 'Code de la régie'},
+            'dateRef': {
+                'description': 'Date de référence',
+                'example_value': '2023-01-01',
+            },
         },
     )
-    def get_rl1_direct_debit_order(self, request, NameID, post_data):
+    def get_rl1_direct_debit_order(self, request, NameID, codeRegie, dateRef):
+        try:
+            dateRef = parse_date(dateRef)
+        except ValueError:
+            raise APIError('invalid value for parameter dateRef (not a valid date)')
+        if not dateRef:
+            raise APIError('invalid value for parameter dateRef (YYYY-MM-DD expected)')
         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)
+        payload = {
+            'dossierNumber': family_id,
+            'numPerson': family['RL1']['num'],
+            'codeRegie': codeRegie,
+            'dateRef': dateRef,
+        }
+        response = self.call('Invoice', 'getDirectDebitOrder', **payload)
         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)
     family_id = models.CharField(blank=False, max_length=128)
diff --git a/tests/test_toulouse_maelis.py b/tests/test_toulouse_maelis.py
index c46efe03..49ba5036 100644
--- a/tests/test_toulouse_maelis.py
+++ b/tests/test_toulouse_maelis.py
@@ -8,16 +8,17 @@
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU Affero General Public License for more details.
 #
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+import datetime
 import logging
 import os
 from unittest import mock
 
 import pytest
 import responses
 from requests.exceptions import ConnectionError
 from zeep import Settings
@@ -3298,16 +3299,17 @@ def test_update_child_indicator_wrong_referential_key_error(con, app):
         resp.json['err_desc']
         == "indicatorList/0/code key value 'plop' do not belong to 'ChildIndicator' required referential"
     )
 
 
 def test_add_rl1_direct_debit_order(all_services, con, app):
     def request_check(request):
         assert request.dossierNumber == 1312
+        assert request.bank['dateStart'] == datetime.datetime(2023, 1, 1, 0, 0)
 
     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,
     )
@@ -3386,62 +3388,73 @@ def test_get_rl1_direct_debit_order(all_services, con, app):
     )
     url = get_endpoint('get-rl1-direct-debit-order')
     params = {
         '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)
+    resp = app.get(url + '?NameID=local', params=params)
+
     assert resp.json['err'] == 0
     assert resp.json['data'] == {
         'bankBIC': 'BDFEFR2T',
         'bankIBAN': 'FR7630001007941234567890185',
         'bankRUM': 'xxx',
         'dateStart': '2023-01-01T00:00:00+01:00',
         'bankAddress': '75049 PARIS cedex 01',
         'civility': 'x',
         'lastName': 'Ewing',
         'firstName': 'John Ross',
     }
 
 
 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.get(url + '?NameID=local', params=params)
+    assert resp.json['err'] == 1
+    assert resp.json['err_class'] == 'passerelle.utils.jsonresponse.APIError'
+    assert resp.json['err_desc'] == 'invalid value for parameter dateRef (YYYY-MM-DD expected)'
 
-    resp = app.post_json(url + '?NameID=local', params=params, status=400)
+    params = {
+        'codeRegie': '22',
+        'dateRef': '2023-02-31',
+    }
+
+    resp = app.get(url + '?NameID=local', params=params)
     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}$'"
+    assert resp.json['err_desc'] == 'invalid value for parameter dateRef (not a valid date)'
 
 
 def test_get_rl1_direct_debit_order_not_linked_error(con, app):
     url = get_endpoint('get-rl1-direct-debit-order')
     params = {
         'codeRegie': '22',
         'dateRef': '2023-01-01',
     }
 
-    resp = app.post_json(url + '?NameID=local', params=params)
+    resp = app.get(url + '?NameID=local', params=params)
     assert resp.json['err'] == 'not-linked'
     assert resp.json['err_desc'] == 'User not linked to family'
 
 
 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-rl1-direct-debit-order')
     params = {
         '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)
+    resp = app.get(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

