From ebebcb4c4d47f1af25ad1fb9095640607be5a79f Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Fri, 23 Jul 2021 18:45:12 +0200
Subject: [PATCH] caluire-axel: handle wrong messages on pay_invoice (#55793)

---
 passerelle/contrib/caluire_axel/models.py | 27 ++++++++++++--
 tests/test_caluire_axel.py                | 44 +++++++++++++++++++++++
 2 files changed, 69 insertions(+), 2 deletions(-)

diff --git a/passerelle/contrib/caluire_axel/models.py b/passerelle/contrib/caluire_axel/models.py
index bfa2fd7c..568faad4 100644
--- a/passerelle/contrib/caluire_axel/models.py
+++ b/passerelle/contrib/caluire_axel/models.py
@@ -1212,20 +1212,43 @@ class CaluireAxel(BaseResource):
             'IDENTMODEREGLEMENT': 'INCB',
         }
         try:
             result = schemas.set_paiement(self, {'PORTAIL': {'SETPAIEMENT': post_data}})
         except axel.AxelError as e:
             raise APIError(
                 'Axel error: %s' % e,
                 err_code='error',
-                data={'xml_request': e.xml_request, 'xml_response': e.xml_response},
+                data={
+                    'xml_request': e.xml_request,
+                    'xml_response': e.xml_response,
+                    'regie_id': regie_id,
+                    'family_id': family_id,
+                    'invoice': invoice,
+                    'post_data': post_data,
+                    'kwargs': kwargs,
+                },
+            )
+        try:
+            code = int(result.json_response['DATA']['PORTAIL']['SETPAIEMENT']['CODE'])
+        except (KeyError, ValueError):
+            raise APIError(
+                'Wrong pay-invoice response',
+                err_code='pay-invoice-code-response-error',
+                data={
+                    'regie_id': regie_id,
+                    'family_id': family_id,
+                    'invoice': invoice,
+                    'post_data': post_data,
+                    'kwargs': kwargs,
+                    'result': result.json_response,
+                },
+                http_status=500,
             )
 
-        code = result.json_response['DATA']['PORTAIL']['SETPAIEMENT']['CODE']
         if code < 0:
             raise APIError('Wrong pay-invoice status', err_code='pay-invoice-code-error-%s' % code)
 
         return {
             'created': True,
             'data': {
                 'xml_request': result.xml_request,
                 'xml_response': result.xml_response,
diff --git a/tests/test_caluire_axel.py b/tests/test_caluire_axel.py
index 88cdd87a..f95c823f 100644
--- a/tests/test_caluire_axel.py
+++ b/tests/test_caluire_axel.py
@@ -3284,16 +3284,18 @@ def test_pay_invoice_endpoint_axel_error(app, resource):
     with mock_data(content, 'GetFacturesaPayer'):
         with mock.patch('passerelle.contrib.caluire_axel.schemas.set_paiement') as operation:
             operation.side_effect = AxelError('FooBar')
             resp = app.post_json(
                 '/caluire-axel/test/regie/MAREGIE/invoice/XXX-42/pay?NameID=yyy', params=payload
             )
     assert resp.json['err_desc'] == "Axel error: FooBar"
     assert resp.json['err'] == 'error'
+    for key in ('xml_request', 'xml_response', 'regie_id', 'family_id', 'invoice', 'post_data', 'kwargs'):
+        assert key in resp.json['data'].keys()
 
     content2 = '''
 <PORTAIL>
   <SETPAIEMENT>
     <CODE>-3</CODE>
   </SETPAIEMENT>
 </PORTAIL>'''
     with mock.patch('passerelle.contrib.caluire_axel.models.CaluireAxel.soap_client') as client:
@@ -3330,16 +3332,58 @@ def test_pay_invoice_endpoint_no_result(app, resource):
             % xml.read()
         )
     with mock_data(content, 'GetFacturesaPayer'):
         resp = app.post_json('/caluire-axel/test/regie/MAREGIE/invoice/XXX-35/pay?NameID=yyy', params=payload)
     assert resp.json['err_desc'] == "Invoice not found"
     assert resp.json['err'] == 'not-found'
 
 
+def test_pay_invoice_endpoint_wrong_response(app, resource):
+    payload = {
+        'transaction_date': '2021-06-15T12:00:00',
+        'transaction_id': 'foo',
+    }
+    with mock.patch(
+        'passerelle.contrib.caluire_axel.models.CaluireAxel.get_invoice',
+        return_value={'amount': '44.9'},
+    ):
+        with mock.patch('passerelle.contrib.caluire_axel.schemas.set_paiement') as operation:
+            operation.return_value = OperationResult(
+                json_response={'DATA': {'PORTAIL': {}}},
+                xml_request='',
+                xml_response='',
+            )
+            resp = app.post_json(
+                '/caluire-axel/test/regie/MAREGIE/invoice/XXX-42/pay?NameID=yyy',
+                params=payload,
+                status=500,
+            )
+        assert resp.json['err'] == 'pay-invoice-code-response-error'
+        assert resp.json['err_desc'] == 'Wrong pay-invoice response'
+        for key in 'regie_id', 'family_id', 'invoice', 'post_data', 'kwargs', 'result':
+            assert key in resp.json['data'].keys()
+
+        with mock.patch('passerelle.contrib.caluire_axel.schemas.set_paiement') as operation:
+            operation.return_value = OperationResult(
+                json_response={'DATA': {'PORTAIL': {'SETPAIEMENT': {'CODE': 'oups'}}}},
+                xml_request='',
+                xml_response='',
+            )
+            resp = app.post_json(
+                '/caluire-axel/test/regie/MAREGIE/invoice/XXX-42/pay?NameID=yyy',
+                params=payload,
+                status=500,
+            )
+        assert resp.json['err'] == 'pay-invoice-code-response-error'
+        assert resp.json['err_desc'] == 'Wrong pay-invoice response'
+        for key in 'regie_id', 'family_id', 'invoice', 'post_data', 'kwargs', 'result':
+            assert key in resp.json['data'].keys()
+
+
 def test_pay_invoice_endpoint(app, resource):
     payload = {
         'transaction_date': '2021-06-15T12:00:00',
         'transaction_id': 'foo',
     }
     Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
     filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/invoices.xml')
     with open(filepath) as xml:
-- 
2.30.2

