From b113829f2ec9a9bb37429413af222403cf97a537 Mon Sep 17 00:00:00 2001
From: Emmanuel Cazenave <ecazenave@entrouvert.com>
Date: Fri, 10 May 2019 17:03:03 +0200
Subject: [PATCH] expose transaction capabilities (#32969)

And implement the first one, manual validation for
systempayv2 and paybox.
---
 eopayment/__init__.py      |  8 ++++++++
 eopayment/paybox.py        | 11 ++++++++++-
 eopayment/systempayv2.py   | 12 +++++++++++-
 tests/test_base_payment.py | 30 +++++++++++++++++++++++++++++-
 tests/test_paybox.py       | 30 ++++++++++++++++++++++++++++++
 tests/test_systempayv2.py  | 20 ++++++++++++++++++++
 6 files changed, 108 insertions(+), 3 deletions(-)

diff --git a/eopayment/__init__.py b/eopayment/__init__.py
index f2f1239..b4c6402 100644
--- a/eopayment/__init__.py
+++ b/eopayment/__init__.py
@@ -192,3 +192,11 @@ class Payment(object):
            - bank_data -- the transaction dictionary received from the bank
         '''
         return self.backend.validate(amount, bank_data, **kwargs)
+
+    def get_parameters(self, scope='global'):
+        res = []
+        for param in self.backend.description.get('parameters', []):
+            if param.get('scope', 'global') != scope:
+                continue
+            res.append(param)
+        return res
diff --git a/eopayment/paybox.py b/eopayment/paybox.py
index 4c34731..cf17ace 100644
--- a/eopayment/paybox.py
+++ b/eopayment/paybox.py
@@ -247,10 +247,17 @@ class Payment(PaymentCommon):
                 'required': False,
                 'choices': PAYMENT_MODES.keys()
             },
+            {
+                'name': 'manual_validation',
+                'caption': 'Validation manuelle',
+                'type': bool,
+                'default': False,
+                'scope': 'transaction'
+            }
         ]
     }
 
-    def request(self, amount, email, name=None, orderid=None, **kwargs):
+    def request(self, amount, email, name=None, orderid=None, manual_validation=None, **kwargs):
         d = OrderedDict()
         d['PBX_SITE'] = force_text(self.site)
         d['PBX_RANG'] = force_text(self.rang).strip()[-2:]
@@ -283,6 +290,8 @@ class Payment(PaymentCommon):
         if capture_day:
             d['PBX_DIFF'] = capture_day.zfill(2)
         d['PBX_AUTOSEULE'] = PAYMENT_MODES[self.capture_mode]
+        if manual_validation:
+            d['PBX_AUTOSEULE'] = PAYMENT_MODES['AUTHOR_CAPTURE']
         if automatic_return_url:
             d['PBX_REPONDRE_A'] = force_text(automatic_return_url)
         d = d.items()
diff --git a/eopayment/systempayv2.py b/eopayment/systempayv2.py
index 31731fd..d25a89f 100644
--- a/eopayment/systempayv2.py
+++ b/eopayment/systempayv2.py
@@ -246,6 +246,13 @@ class Payment(PaymentCommon):
             {'name': 'secret_production',
                 'caption': _(u'Secret pour la configuration de PRODUCTION'),
                 'validation': lambda value: str.isdigit(value), },
+            {
+                'name': 'manual_validation',
+                'caption': 'Validation manuelle',
+                'type': bool,
+                'default': False,
+                'scope': 'transaction'
+            }
         ]
     }
 
@@ -267,9 +274,10 @@ class Payment(PaymentCommon):
         options = add_vads(options)
         self.options = options
 
+
     def request(self, amount, name=None, first_name=None, last_name=None,
                 address=None, email=None, phone=None, orderid=None, info1=None,
-                info2=None, info3=None, next_url=None, **kwargs):
+                info2=None, info3=None, next_url=None, manual_validation=None, **kwargs):
         '''
            Create the URL string to send a request to SystemPay
         '''
@@ -338,6 +346,8 @@ class Payment(PaymentCommon):
         capture_day = fields.pop('capture_day')
         if capture_day:
             fields['vads_capture_delay'] = capture_day
+        if manual_validation:
+            fields['vads_validation_mode'] = '1'
         check_vads(fields)
         fields[SIGNATURE] = force_text(self.signature(fields))
         self.logger.debug('%s request contains fields: %s', __name__, fields)
diff --git a/tests/test_base_payment.py b/tests/test_base_payment.py
index 7ea551e..bb23959 100644
--- a/tests/test_base_payment.py
+++ b/tests/test_base_payment.py
@@ -14,7 +14,22 @@ def do_mock_backend(monkeypatch):
             'parameters': [
                 {
                     'name': 'capture_day',
-                }
+                },
+                {
+                    'name': 'manual_validation',
+                    'caption': 'Validation manuelle',
+                    'type': bool,
+                    'default': False,
+                    'scope': 'transaction'
+                },
+                {
+                    'name': 'global_param',
+                    'caption': 'Global Param',
+                    'type': bool,
+                    'default': False,
+                    'scope': 'global'
+                },
+
             ]
         }
 
@@ -64,3 +79,16 @@ def test_paris_timezone(freezer, monkeypatch):
         # converted to Europe/Paris it is already 2018-10-03
         # so 2018-10-03 for capture_date is invalid
         payment.request(amount=12.2, capture_date=capture_date)
+
+
+def test_get_parameters(monkeypatch):
+    _, payment = do_mock_backend(monkeypatch)
+
+    global_parameters = payment.get_parameters()
+    assert len(global_parameters) == 2
+    assert global_parameters[0]['name'] == 'capture_day'
+    assert global_parameters[1]['name'] == 'global_param'
+
+    transaction_parameters = payment.get_parameters(scope='transaction')
+    assert len(transaction_parameters) == 1
+    assert transaction_parameters[0]['name'] == 'manual_validation'
diff --git a/tests/test_paybox.py b/tests/test_paybox.py
index 9f38090..443d811 100644
--- a/tests/test_paybox.py
+++ b/tests/test_paybox.py
@@ -253,3 +253,33 @@ ZdzrudBlevZXpr6iYwIDAQAB
 z0Dkz0NjxvU+5WzQZh9Uuxr/egRCwV4NMRWqu0zaVVioeBvl4/5CWm4f4/1L9+0m
 FBFKOZhgBJnkC+l6+XhT4aYWKaQ4ocmOMV92yjeXTE4='''
         self.assertTrue(paybox.verify(data, base64.b64decode(sig64), key=pkey))
+
+    def test_request_manual_validation(self):
+        params = BACKEND_PARAMS.copy()
+        time = '2018-08-21T10:26:32+02:00'
+        email = 'user@entrouvert.com'
+        order_id = '20180821'
+        transaction = '1234'
+        amount = '42.99'
+
+        backend = eopayment.Payment('paybox', params)
+
+        transaction_id, kind, what = backend.request(
+                Decimal(amount), email=email, orderid=order_id,
+                transaction_id=transaction, time=time)
+        root = ET.fromstring(str(what))
+        form_params = dict((
+            (node.attrib['name'], node.attrib['value']) for node in root
+            if node.attrib['type'] == 'hidden'))
+        self.assertIn('PBX_AUTOSEULE', form_params)
+        self.assertEqual(form_params['PBX_AUTOSEULE'], 'N')
+
+        transaction_id, kind, what = backend.request(
+                Decimal(amount), email=email, orderid=order_id,
+                transaction_id=transaction, time=time, manual_validation=True)
+        root = ET.fromstring(str(what))
+        form_params = dict((
+            (node.attrib['name'], node.attrib['value']) for node in root
+            if node.attrib['type'] == 'hidden'))
+        self.assertIn('PBX_AUTOSEULE', form_params)
+        self.assertEqual(form_params['PBX_AUTOSEULE'], 'O')
diff --git a/tests/test_systempayv2.py b/tests/test_systempayv2.py
index 1df7282..c6f9188 100644
--- a/tests/test_systempayv2.py
+++ b/tests/test_systempayv2.py
@@ -98,3 +98,23 @@ def test_systempayv2_deferred_payment():
     data['capture_date'] = (datetime.now().date() + timedelta(days=4))
     transaction_id, f, form = p.request(**data)
     assert get_field(form, 'vads_capture_delay')['value'] == '4'
+
+
+def test_manual_validation():
+    params = {
+        'secret_test': u'1122334455667788',
+        'vads_site_id': u'12345678',
+        'vads_ctx_mode': u'TEST',
+    }
+    data = {
+        'amount': 15.24, 'orderid': '654321', 'first_name': u'John',
+        'last_name': u'Doe'
+    }
+
+    backend = eopayment.Payment('systempayv2', params)
+    transaction_id, f, form = backend.request(**data.copy())
+    assert get_field(form, 'vads_validation_mode')['value'] == ''
+
+    data['manual_validation'] = True
+    transaction_id, f, form = backend.request(**data.copy())
+    assert get_field(form, 'vads_validation_mode')['value'] == '1'
-- 
2.20.1

