## $Id: tests.py 14737 2017-08-01 07:12:58Z 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, timedelta, date
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.applicants.tests.test_browser import ApplicantsFullSetup
from waeup.kofa.configuration import SessionConfiguration
from waeup.kofa.students.payments import StudentOnlinePayment
from kofacustom.nigeria.interswitch.helpers import query_interswitch
from kofacustom.nigeria.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 InterswitchTestsStudents(StudentsFullSetup):
    """Tests for the Interswitch payment gateway.
    """

    layer = FunctionalLayer

    def setUp(self):
        super(InterswitchTestsStudents, self).setUp()
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.payments_path)
        IWorkflowState(self.student).setState('cleared')
        self.student.nationality = u'NG'
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['schoolfee']
        self.browser.getControl("Create ticket").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        self.value = ctrl.options[0]
        self.browser.getLink(self.value).click()
        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertTrue('<span>40000.0</span>', self.browser.contents)
        self.payment_url = self.browser.url
        self.payment = self.student['payments'][self.value]

    def test_interswitch_form(self):
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        # The total amount to be processed by Interswitch
        # has been reduced by the Interswitch fee of 150 Nairas
        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
                           self.browser.contents)
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
        self.assertEqual(self.student.current_mode, 'ug_ft')
        self.assertMatches(
            '...<input type="hidden" name="amount" value="4000000" />...',
            self.browser.contents)

        # Create school fee ticket for returning students. Payment is made
        # for next session.
        current_payment_key = self.student['payments'].keys()[0]
        self.certificate.study_mode = u'ug_pt'
        IWorkflowState(self.student).setState('returning')
        configuration = createObject('waeup.SessionConfiguration')
        configuration.academic_session = 2005
        self.app['configuration'].addSessionConfiguration(configuration)
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['schoolfee']
        self.browser.getControl("Create ticket").click()

        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[1]
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
        self.browser.getLink(value).click()
        self.browser.getLink("CollegePAY", index=0).click()
        # Split amounts have been set.
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
                           self.browser.contents)
        self.assertMatches(
            '...<input type="hidden" name="amount" value="2000000" />...',
            self.browser.contents)

    def test_interswitch_form_ticket_expired(self):
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
                           self.browser.contents)
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
        self.assertEqual(self.student.current_mode, 'ug_ft')
        self.assertMatches(
            '...<input type="hidden" name="amount" value="4000000" />...',
            self.browser.contents)
        delta = timedelta(days=8)
        self.payment.creation_date -= delta
        self.browser.open(self.payment_url)
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches(
            '...This payment ticket is too old. Please create a new ticket...',
            self.browser.contents)
        delta = timedelta(days=2)
        self.payment.creation_date += delta
        self.browser.open(self.payment_url)
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)

    def test_interswitch_form_ticket_expired_tz(self):
        # The form copes with timezones when calculating expirements.
        # We should not have TZ data in timestamps processed, but it looks
        # like we get some with imports :-/
        self.browser.getLink("CollegePAY", index=0).click()
        delta = timedelta(days=8)
        self.payment.creation_date -= delta
        from pytz import timezone
        self.payment.creation_date = timezone("Europe/Berlin").localize(
            self.payment.creation_date)
        self.browser.open(self.payment_url)
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches(
            '...This payment ticket is too old. Please create a new ticket...',
            self.browser.contents)
        delta = timedelta(days=2)
        self.payment.creation_date += delta
        self.browser.open(self.payment_url)
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)

    @external_test
    def test_query_interswitch_SOAP(self):
        host = 'webpay.interswitchng.com'
        url = '/paydirect/services/TransactionQueryWs.asmx'
        https = True
        mac = None
        product_id = '5845' # AAUE regular
        payment = StudentOnlinePayment()
        payment.p_id ='p4465649308559'
        payment.amount_auth = 60250.0
        success, msg, log = query_interswitch(
            payment, product_id, host, url, https, mac)
        self.assertEqual('Successful callback received', msg)
        self.assertTrue(success)
        self.assertTrue(
            '00:Approved Successful:6025000:3154:p4465649308559:'
            'ZIB|WEB|ABAL|3-11-2015|021336:000457580882' in log)

    @external_test
    def test_query_interswitch_JSON(self):
        host = 'webpay.interswitchng.com'
        url = '/paydirect/api/v1/gettransaction.json'
        mac = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
        https = True
        product_id = '5845' # AAUE regular
        payment = StudentOnlinePayment()
        payment.p_id ='p4465649308559'
        payment.amount_auth = 1.0
        success, msg, log = query_interswitch(
            payment, product_id, host, url, https, mac)
        self.assertFalse(success)
        self.assertTrue('Unsuccessful callback:' in msg)
        self.assertTrue('Amount Inconsistency' in log)
        payment.amount_auth = 60250.0
        success, msg, log = query_interswitch(
            payment, product_id, host, url, https, mac)
        self.assertEqual('Successful callback received', msg)
        self.assertTrue(success)
        self.assertTrue(
            "{u'SplitAccounts': [], "
            "u'MerchantReference': u'p4465649308559', "
            "u'PaymentReference': u'ZIB|WEB|ABAL|3-11-2015|021336', "
            "u'TransactionDate': u'2015-11-03T16:40:54.487', "
            "u'RetrievalReferenceNumber': u'000457580882', "
            "u'ResponseDescription': u'Approved Successful', "
            "u'Amount': 6025000, "
            "u'CardNumber': u'3154', "
            "u'ResponseCode': u'00', "
            "u'LeadBankCbnCode': None, "
            "u'LeadBankName': None}" in log)

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
        self.app['configuration'].addSessionConfiguration(configuration)
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.manage_path)
        #IWorkflowState(self.student).setState('started')
        super(InterswitchTestsApplicants, self).fill_correct_values()
        self.applicantscontainer.application_fee = 1000.0
        self.browser.getControl(name="form.nationality").value = ['NG']
        self.browser.getControl(name="transition").value = ['start']
        self.browser.getControl("Save").click()
        self.browser.getControl("Add online").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        self.payment = self.applicant.values()[0]
        self.payment_url = self.browser.url

    def test_interswitch_form(self):
        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertMatches(
            '...<span>1000.0</span>...',
            self.browser.contents)
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", 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.payment.creation_date -= delta
        self.browser.open(self.payment_url)
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches(
            '...This payment ticket is too old. Please create a new ticket...',
            self.browser.contents)
        delta = timedelta(days=2)
        self.payment.creation_date += delta
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)

