## $Id: tests.py 16910 2022-03-28 08:36:02Z 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
import random
from datetime import datetime, timedelta, date
from zope.component import createObject, getUtility
from zope.catalog.interfaces import ICatalog
from xml.dom.minidom import parseString
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 waeup.kofa.browser.tests.test_pdf import samples_dir
from kofacustom.nigeria.interswitch.helpers import (
    query_interswitch, get_SOAP_response_paydirect, SOAP_post,
    create_paydirect_booking
    )
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_1 = True
EXTERNAL_TESTS_2 = True

PAYDIRECT_HOST = 'sandbox.interswitchng.com'
PAYDIRECT_URL = '/bookonhold/bookonhold.asmx'
MERCHANT_ID = '6033'

def external_test_1(func):
    if not EXTERNAL_TESTS_1:
        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

def external_test_2(func):
    if not EXTERNAL_TESTS_2:
        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)
        self.browser.open(self.payments_path)
        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("Pay via Interswitch 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)

        # 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()
        self.browser.open(self.payments_path)
        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("Pay via Interswitch 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, 300.0)
        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
                           self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="2030000" />' in
            self.browser.contents)

    def test_interswitch_form_ticket_expired(self):
        # Manager can access InterswitchForm
        self.browser.getLink("Pay via Interswitch 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.assertTrue(
            '<input type="hidden" name="amount" value="4030000" />' in
            self.browser.contents)
        delta = timedelta(days=8)
        self.payment.creation_date -= delta
        self.browser.open(self.payment_url)
        self.browser.getLink("Pay via Interswitch 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("Pay via Interswitch CollegePAY").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("Pay via Interswitch CollegePAY", index=0).click()
        delta = timedelta(days=9) # In European summertime, 8 days is not enough
        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("Pay via Interswitch 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("Pay via Interswitch CollegePAY").click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)

    @external_test_1
    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, False)
        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_1
    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, False)
        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, False)
        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)

# PAYDirect tests

    @external_test_2
    def test_SOAP_paydirect(self):
        payment = createObject('waeup.StudentOnlinePayment')
        payment.p_category = u'schoolfee'
        payment.p_session = self.student.current_session
        payment.p_item = u'My Certificate'
        payment.p_id = 'p' + str(random.randint(10000000000, 90000000000))
        payment.amount_auth = 1000.0
        item_code = '01'
        self.student['payments'][payment.p_id] = payment
        result_xml = create_paydirect_booking(
            MERCHANT_ID, payment, item_code, PAYDIRECT_HOST, PAYDIRECT_URL, True)
        result_xml = get_SOAP_response_paydirect(
            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
        doc=parseString(result_xml)
        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
        amount=doc.getElementsByTagName('Amount')[0].firstChild
        self.assertEqual(status, 'Pending')
        self.assertEqual(amount, None)
        p_id = 'p5812734587097'
        result_xml = get_SOAP_response_paydirect(MERCHANT_ID, p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
        doc=parseString(result_xml)
        self.assertEqual(doc.getElementsByTagName('PaymentStatus'), [])

    @external_test_2
    def test_paydirect_pending(self):
        # Manager can access InterswitchForm
        self.browser.getLink("Pay via Interswitch PAYDirect").click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
        self.assertEqual(self.student.current_mode, 'ug_ft')
        # 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()
        self.browser.open(self.payments_path)
        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("Pay via Interswitch PAYDirect").click()
        # Split amounts have been set.
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
        ref_number = '%s%s' % (MERCHANT_ID,value[1:])
        self.assertTrue(ref_number in self.browser.contents)
        self.assertEqual(self.student['payments'][value].r_pay_reference, None)
        self.browser.getControl("Requery").click()
        self.assertTrue('pending' in self.browser.contents)
        # Reference number has been saved
        self.assertEqual(self.student['payments'][value].r_pay_reference, ref_number)
        # Students can download reference number slip
        self.browser.getLink("Pay via Interswitch PAYDirect").click()
        self.browser.getLink("Download reference number slip").click()
        self.assertEqual(self.browser.headers['Status'], '200 Ok')
        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
        path = os.path.join(samples_dir(), 'refnumberslip.pdf')
        open(path, 'wb').write(self.browser.contents)
        print "Sample PDF refnumberslip.pdf written to %s" % path

    @external_test_2
    def test_paydirect_completed(self):
        payment = createObject('waeup.StudentOnlinePayment')
        payment.p_category = u'schoolfee'
        payment.p_session = self.student.current_session
        payment.p_item = u'My Certificate'
        # p6214352306153 has been manually set completed by Interswitch
        payment.p_id = u'p6214352306153'
        payment.amount_auth = 10.0 # 300 will be added
        self.student['payments'][payment.p_id] = payment
        result_xml = get_SOAP_response_paydirect(
            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
        doc=parseString(result_xml)
        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
        refnumber=doc.getElementsByTagName('ReferenceNumber')[0].firstChild.data
        amount=float(doc.getElementsByTagName('Amount')[0].firstChild.data)
        self.assertEqual(status, 'Completed')
        self.assertEqual(amount, 1000)
        self.assertEqual(refnumber, '60336214352306153')
        # Now we login and check what will happen with the student after payment
        self.browser.open(self.payments_path)
        self.browser.getLink(payment.p_id).click()
        self.browser.getLink("Pay via Interswitch PAYDirect").click()
        # 300 has been added
        self.assertEqual(payment.amount_auth, 310)
        self.assertEqual(payment.net_amt, 10)

        # Unfortunately the payment 60336214352306153 was done without surcharge.
        # Therefore we have to deduct 300 again in this test.
        payment.amount_auth = 10.0

        # Reference number has been saved 
        self.browser.getControl("Requery").click()
        self.assertEqual(
            self.student['payments'][payment.p_id].r_pay_reference, '60336214352306153')
        # Payment is made
        self.assertEqual(
            self.student['payments'][payment.p_id].p_state, 'paid')
        # Rubbish has been stored too
        self.assertTrue(
            self.student['payments'][payment.p_id].r_desc.startswith('Channel Name: Bank Branc'))
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'students.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
            '- K1000000 - valid callback for schoolfee payment %s: Completed' % payment.p_id in logcontent)
        self.assertTrue(
            'zope.mgr - K1000000 - First school fee payment made' in logcontent)
        self.assertTrue(
            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
            '- K1000000 - successful schoolfee payment: %s' % payment.p_id in logcontent)

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("Pay via Interswitch 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("Pay via Interswitch", 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("Pay via Interswitch", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
