## $Id: tests.py 17254 2022-12-30 09:25:50Z henrik $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## 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 General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
import os
from datetime import datetime, date, timedelta
from zope.component import createObject, getUtility
from zope.catalog.interfaces import ICatalog
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.students.tests.test_browser import StudentsFullSetup
from waeup.kofa.students.payments import StudentOnlinePayment
from waeup.kofa.applicants.tests.test_browser import ApplicantsFullSetup
from waeup.kofa.configuration import SessionConfiguration
from kofacustom.nigeria.interswitch.helpers import confirm_transaction
from kofacustom.lpng.testing import FunctionalLayer

# Also run tests that send requests to external servers?
#   If you enable this, please make sure the external services
#   do exist really and are not bothered by being spammed by a test programme.
EXTERNAL_TESTS = False

def external_test(func):
    if not EXTERNAL_TESTS:
        myself = __file__
        if myself.endswith('.pyc'):
            myself = myself[:-1]
        print "WARNING: external tests are skipped!"
        print "WARNING: edit %s to enable them." % myself
        return
    return func


class InterswitchTestsApplicants(ApplicantsFullSetup):
    """Tests for the Interswitch payment gateway.
    """

    layer = FunctionalLayer

    def setUp(self):
        super(InterswitchTestsApplicants, self).setUp()
        configuration = SessionConfiguration()
        configuration.academic_session = datetime.now().year - 2
        configuration.interswitch_webcheckout_enabled = True
        self.app['configuration'].addSessionConfiguration(configuration)
        self.configuration = configuration
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.manage_path)
        #IWorkflowState(self.student).setState('started')
        self.browser.getControl(name="form.firstname").value = 'John'
        self.browser.getControl(name="form.middlename").value = 'Anthony'
        self.browser.getControl(name="form.lastname").value = 'Tester'
        self.browser.getControl(name="form.date_of_birth").value = '09/09/1988'
        self.browser.getControl(name="form.sex").value = ['m']
        self.browser.getControl(name="form.vin").value = '1234'
        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
        self.applicantscontainer.application_fee = 1000.0
        self.browser.getControl(name="transition").value = ['start']
        self.browser.getControl("Save").click()


    def test_webcheckout_form(self):
        self.browser.getControl("Make").click()
        self.browser.getControl(name="form.balance_amount").value = '500'
        self.browser.getControl(name="form.p_category").value = ['donation']
        self.browser.getControl(name="form.p_option").value = ['NGN']
        self.browser.getControl("Create ticket").click()

        self.assertMatches('...ticket created...',
                           self.browser.contents)

        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertMatches(
            '...<span>500.0</span>...',
            self.browser.contents)
        self.payment_url = self.browser.url
        # Manager can access InterswitchForm
        self.browser.getLink("Pay via Interswitch", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
        self.assertMatches(
            '...<input type="hidden" name="amount" value="100000" />...',
            self.browser.contents)
        delta = timedelta(days=8)
        self.applicant.values()[0].creation_date -= delta
        self.browser.open(self.payment_url)
        self.browser.getLink("Pay via Interswitch", index=0).click()
        self.assertMatches(
            '...This payment ticket is too old. Please create a new ticket...',
            self.browser.contents)


# WebCheckout tests

    # https://webpay.interswitchng.com/collections/api/v1/gettransaction.json?merchantcode=MX76823&transactionreference=p6709347986663&amount=100

    @external_test
    def test_confirm_transaction(self):
        host = 'webpay.interswitchng.com'
        url = '/collections/api/v1/gettransaction.json'
        https = True
        merchant_code = 'MX76823'
        payment = StudentOnlinePayment()
        payment.p_id ='p4465649308559'
        success, msg, log = confirm_transaction(
            payment, merchant_code, host, url, https)
        self.assertFalse(success)
        self.assertTrue('Unsuccessful callback:' in msg)
        self.assertTrue('Transaction not Found' in log)

        payment.p_id ='p6709347986663'
        payment.amount_auth = 1.0
        success, msg, log = confirm_transaction(
            payment, merchant_code, host, url, https)
        self.assertTrue('Amount Inconsistency' in log)
        payment.amount_auth = 100.0
        success, msg, log = confirm_transaction(
            payment, merchant_code, host, url, https)
        self.assertEqual('Successful callback received', msg)
        self.assertTrue(success)
        self.assertTrue(
            "{u'SplitAccounts': [], "
            "u'RemittanceAmount': 0, "
            "u'MerchantReference': u'p6709347986663', "
            "u'PaymentReference': u'FBN|WEB|MX76823|13-12-2022|935097929|608001', "
            "u'TransactionDate': u'2022-12-13T01:34:21', "
            "u'RetrievalReferenceNumber': u'814212374638', "
            "u'ResponseDescription': u'Approved by Financial Institution', "
            "u'Amount': 10000, "
            "u'CardNumber': u'', "
            "u'ResponseCode': u'00', "
            "u'BankCode': u'011'}" in log)
