## $Id: tests.py 13887 2016-06-07 20:35:15Z 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.applicants.tests.test_browser import ApplicantsFullSetup
from waeup.uniben.configuration import CustomSessionConfiguration
from waeup.uniben.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

SAMPLE_IMAGE = os.path.join(os.path.dirname(__file__), 'test_image.jpg')

def external_test(func):
    if not EXTERNAL_TESTS:
        myself = __file__
        if myself.endswith('.pyc'):
            myself = myself[:-2]
        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>' in self.browser.contents)
        self.payment_url = self.browser.url

#    def callback_url(self, payment_url, resp, apprAmt):
#        return payment_url + (
#            '/isw_callback?echo=' +
#            '&resp=%s' +
#            '&desc=Something went wrong' +
#            '&txnRef=p1331792385335' +
#            '&payRef=' + '&retRef=' +
#            '&cardNum=0' +
#            '&apprAmt=%s' +
#            '&url=http://xyz') % (resp, apprAmt)

    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.assertTrue('<input type="hidden" name="pay_item_id" value="5700" />'
                           in self.browser.contents)
        self.assertTrue('Total Amount Authorized:'
                           in self.browser.contents)
        self.assertEqual(self.student.current_mode, 'ug_ft')
        self.assertTrue(
            '<input type="hidden" name="amount" value="4000000" />'
            in self.browser.contents)
        self.assertTrue(
            'item_name="School Fee" item_amt="3835000" bank_id="8" acct_num="2017506430"'
            in self.browser.contents)
        self.assertTrue(
            'item_name="BT Education" item_amt="150000" bank_id="117" acct_num="1010764827"'
            in 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()

        ## Next session payment can't be made ...
        #self.assertMatches(
        #    '...You have not yet paid your current/active session...',
        #    self.browser.contents)
        ## current session payment must be approved first.
        #self.student['payments'][current_payment_key].approve()
        #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, 1500.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        self.assertTrue('<input type="hidden" name="pay_item_id" value="5701" />'
                           in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="2000000" />'
            in self.browser.contents)
        self.assertTrue(
            'item_name="School Fee" item_amt="1835000" bank_id="8" acct_num="2017506430"'
            in self.browser.contents)
        self.assertTrue(
            'item_name="BT Education" item_amt="150000" bank_id="117" acct_num="1010764827"'
            in self.browser.contents)

        # Create clearance fee ticket
        #self.browser.open(self.payments_path + '/addop')
        #self.browser.getControl(name="form.p_category").value = ['clearance']
        #self.browser.getControl("Create ticket").click()
        #ctrl = self.browser.getControl(name='val_id')
        #value = ctrl.options[2]
        #self.browser.getLink(value).click()
        #self.assertMatches(
        #    '...<span>45000.0</span>...',
        #    self.browser.contents)
        ## Manager can access InterswitchForm
        #self.browser.getLink("CollegePAY", index=0).click()
        #self.assertEqual(self.student['payments'][value].provider_amt, 1500.0)
        #self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        #self.assertMatches('...<input type="hidden" name="pay_item_id" value="5702" />...',
        #                   self.browser.contents)
        #self.assertMatches('...Total Amount Authorized:...',
        #                   self.browser.contents)
        #self.assertMatches(
        #    '...<input type="hidden" name="amount" value="4500000.0" />...',
        #    self.browser.contents)
        #self.assertMatches(
        #    '...item_name="Acceptance Fee" item_amt="4335000" bank_id="7" acct_num="1003475516"...',
        #    self.browser.contents)
        #self.assertMatches(
        #    '...item_name="BT Education" item_amt="150000" bank_id="117" acct_num="1010764827"...',
        #    self.browser.contents)

        # Create gown fee ticket
        configuration.maint_fee = 987.0
        self.app['configuration']['2004'].gown_fee = 234.0
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['gown']
        self.browser.getControl("Create ticket").click()
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[2]
        self.browser.getLink(value).click()
        self.assertTrue(
            '<span>234.0</span>',
            self.browser.contents)
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        self.assertTrue('<input type="hidden" name="pay_item_id" value="5704" />'
                           in self.browser.contents)
        self.assertTrue('Total Amount Authorized:'
                           in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="23400" />'
            in self.browser.contents)
        self.assertTrue(
            '<item_detail item_id="1" item_name="Gown Hire Fee" item_amt="8400" bank_id="8" acct_num="2017506430" />'
            in self.browser.contents)
        self.assertFalse(
            'item_name="BT Education"' in self.browser.contents)

        # Create hostel application ticket
        #self.browser.open(self.payments_path + '/addop')
        #self.browser.getControl(name="form.p_category").value = ['hostel_application']
        #self.browser.getControl("Create ticket").click()
        #ctrl = self.browser.getControl(name='val_id')
        #value = ctrl.options[3]
        #self.browser.getLink(value).click()
        #self.assertTrue(
        #    '<span>1000.0</span>' in self.browser.contents)
        #self.student['payments'][value].approve()

        # Create temp maint fee ticket
        #self.browser.open(self.payments_path + '/addop')
        #self.browser.getControl(name="form.p_category").value = ['tempmaint_1']
        #self.browser.getControl("Create ticket").click()
        #ctrl = self.browser.getControl(name='val_id')
        #value = ctrl.options[4]
        #self.browser.getLink(value).click()
        #self.assertTrue(
        #    '<span>8150.0</span>' in self.browser.contents)
        # Manager can access InterswitchForm
        #self.browser.getLink("CollegePAY", index=0).click()
        #self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        #self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        #self.assertTrue('<input type="hidden" name="pay_item_id" value="5705" />'
        #                 in self.browser.contents)
        #self.assertMatches('...Total Amount Authorized:...',
        #                   self.browser.contents)
        #self.assertTrue(
        #    '<input type="hidden" name="amount" value="815000" />'
        #    in self.browser.contents)
        #self.assertTrue(
        #    '<item_detail item_id="1" item_name="Hostel Maintenance Fee" item_amt="800000" bank_id="129" acct_num="0014419432" />'
        #    in self.browser.contents)
        #self.assertFalse(
        #    'item_name="BT Education"' in self.browser.contents)

        # Create previous session fee ticket
        configuration = createObject('waeup.SessionConfiguration')
        configuration.academic_session = 2003
        configuration.clearance_fee = 3456.0
        self.app['configuration'].addSessionConfiguration(configuration)
        self.student['studycourse'].entry_session = 2002
        #self.browser.open(self.payments_path + '/addpp')
        #self.browser.getControl(name="form.p_category").value = ['clearance']
        #self.browser.getControl(name="form.p_session").value = ['2003']
        #self.browser.getControl(name="form.p_level").value = ['300']
        #self.browser.getControl("Create ticket").click()
        #ctrl = self.browser.getControl(name='val_id')
        #value = ctrl.options[5]
        #self.browser.getLink(value).click()
        #self.assertMatches(
        #    '...<span>45000.0</span>...',
        #    self.browser.contents)
        ## Manager can access InterswitchForm
        #self.browser.getLink("CollegePAY", index=0).click()
        #self.assertEqual(self.student['payments'][value].provider_amt, 1500.0)
        #self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        #self.assertMatches('...<input type="hidden" name="pay_item_id" value="5702" />...',
        #                   self.browser.contents)
        #self.assertMatches('...Total Amount Authorized:...',
        #                   self.browser.contents)
        ##self.assertMatches(
        #    '...<input type="hidden" name="amount" value="4500000.0" />...',
        #    self.browser.contents)
        #self.assertMatches(
        #    '...<item_detail item_id="1" item_name="Acceptance Fee" item_amt="4335000" bank_id="7" acct_num="1003475516" />...',
        #    self.browser.contents)

        # Create balance payment ticket
        self.browser.open(self.payments_path + '/addbp')
        self.browser.getControl(name="form.p_category").value = ['schoolfee']
        self.browser.getControl(name="form.balance_session").value = ['2003']
        self.browser.getControl(name="form.balance_level").value = ['300']
        self.browser.getControl(name="form.balance_amount").value = '200'
        self.browser.getControl("Create ticket").click()
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[3]
        self.browser.getLink(value).click()
        self.assertTrue(
            '<span>200.0</span>' in self.browser.contents)
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        self.assertTrue('<input type="hidden" name="pay_item_id" value="5701" />'
                           in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="20000" />'
            in self.browser.contents)
        self.assertTrue(
            'item_name="School Fee" item_amt="5000" bank_id="8" acct_num="2017506430"'
            in self.browser.contents)
        self.assertFalse(
            'item_name="BT Education"' in self.browser.contents)

        # Create JUPEB fee ticket
        self.app['configuration']['2004'].jupeb_fee = 345.0
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['jupeb']
        self.browser.getControl("Create ticket").click()
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[4]
        self.browser.getLink(value).click()
        self.assertTrue(
            '<span>345.0</span>',
            self.browser.contents)
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
        self.assertEqual(self.student['payments'][value].gateway_amt, 150.0)
        self.assertTrue('<input type="hidden" name="pay_item_id" value="5717" />'
                           in self.browser.contents)
        self.assertTrue('Total Amount Authorized:'
                           in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="34500" />'
            in self.browser.contents)
        self.assertTrue(
            '<item_detail item_id="1" item_name="JUPEB Examination Fee" item_amt="19500" bank_id="8" acct_num="2017506430" />'
            in self.browser.contents)
        self.assertFalse(
            'item_name="BT Education"' in self.browser.contents)

#    @external_test
#    def test_callback(self):

        # Manager can call callback manually
#        self.browser.open(self.callback_url(self.payment_url, 'XX', '300'))
#        self.assertMatches('...Unsuccessful callback: Something went wrong...',
#                          self.browser.contents)
#        self.assertMatches('...Failed...',
#                           self.browser.contents)
#        self.browser.open(self.payment_url + '/isw_callback')
#        self.assertMatches('...Unsuccessful callback: Incomplete query string...',
#                          self.browser.contents)
#        self.assertMatches('...Failed...',
#                           self.browser.contents)
#        self.browser.open(self.callback_url(self.payment_url, '00', '300000'))
#        self.assertMatches('...Wrong amount...',
#                          self.browser.contents)
#        self.browser.open(self.callback_url(self.payment_url, '00', '4000000'))
#        self.assertMatches('...Valid callback received...',
#                          self.browser.contents)

    def test_interswitch_form_ticket_expired(self):
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        acc_payment = createObject('waeup.StudentOnlinePayment')
        acc_payment.p_state = 'unpaid'
        acc_payment.p_category = 'clearance'
        acc_payment.p_id = 'xyz'
        acc_payment.pay_item_id = '123'
        acc_payment.amount_auth = 876.0
        self.student['payments']['xyz'] = acc_payment
        self.browser.open(self.payments_path + '/xyz')
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<input type="hidden" name="pay_item_id" value="5702" />'
                           in self.browser.contents)
        self.assertTrue('Total Amount Authorized:'
                           in self.browser.contents)
        self.assertEqual(self.student.current_mode, 'ug_ft')
        self.assertTrue(
            '<input type="hidden" name="amount" value="87600" />'
            in self.browser.contents)
        delta = timedelta(days=8)
        acc_payment.creation_date -= delta
        self.browser.open(self.payments_path + '/xyz')
        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)
        acc_payment.creation_date += delta
        self.browser.open(self.payments_path + '/xyz')
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)

    def test_pay_twice(self):
        # Create second ticket
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['schoolfee']
        self.browser.getControl("Create ticket").click()
        # Pay first ticket
        self.student['payments'][self.value].approve()
        # Try to pay second ticket
        self.browser.open(self.payments_path)
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[1]
        self.browser.getLink(value).click()
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches(
            '...alert alert-danger">This type of payment has already been made...',
            self.browser.contents)

    @external_test
    def test_webservice(self):
        # First we have open InterswitchPageStudent to set provider_amt
        # and gateway_amt
        self.browser.open(self.payment_url + '/goto_interswitch')
        # Now we can call the webservice
        self.browser.open(self.payment_url + '/request_webservice')
        self.assertMatches('...Unsuccessful callback...',
                          self.browser.contents)
        # The payment is now in state failed ...
        self.assertMatches('...<span>Failed</span>...',
                          self.browser.contents)
        # ... and the catalog has been updated
        cat = getUtility(ICatalog, name='payments_catalog')
        results = list(
            cat.searchResults(p_state=('failed', 'failed')))
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].p_state, 'failed')

        # Let's replace the p_id with a valid p_id of the Uniben
        # live system. This is definitely not an appropriate
        # solution for testing, but we have no choice since
        # Interswitch doesn't provide any interface
        # for testing.
        payment = self.student['payments'][self.value]
        payment.p_id = 'p3547789850240'
        self.browser.open(self.payment_url + '/request_webservice')
        self.assertMatches('...Callback amount does not match...',
                          self.browser.contents)
        # The payment is now in state failed ...
        self.assertMatches('...<span>Failed</span>...',
                          self.browser.contents)
        # Let's replace the amount autorized with the amount of the
        # live system payment
        payment.amount_auth = payment.r_amount_approved
        self.browser.open(self.payment_url + '/request_webservice')
        self.assertMatches('...Successful payment...',
                          self.browser.contents)
        # The payment is now in state paid ...
        self.assertMatches('...<span>Paid</span>...',
                          self.browser.contents)
        # ... and the catalog has been updated
        cat = getUtility(ICatalog, name='payments_catalog')
        results = list(
            cat.searchResults(p_state=('paid', 'paid')))
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].p_state, 'paid')
        # Approval is logged in students.log ...
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'students.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.mgr - '
            'waeup.uniben.interswitch.browser.CustomInterswitchPaymentRequestWebservicePageStudent - '
            'B1000000 - successful schoolfee payment: p3547789850240\n'
            in logcontent)
        # ... and in payments.log
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'payments.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            '"zope.mgr",B1000000,p3547789850240,schoolfee,'
            '12000.0,00,1500.0,150.0,0.0,,,\n'
            in logcontent)


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

    layer = FunctionalLayer

    def setUp(self):
        super(InterswitchTestsApplicants, self).setUp()
        configuration = CustomSessionConfiguration()
        configuration.academic_session = datetime.now().year - 2
        self.applicantscontainer.application_fee = 1000.0
        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.browser.getControl("Add online").click()
        self.assertMatches('...passport photo before making payment...',
                           self.browser.contents)
        self.browser.open(self.manage_path)
        super(InterswitchTestsApplicants, self).fill_correct_values()
        #self.browser.getControl(name="form.nationality").value = ['NG']
        #self.browser.getControl(name="transition").value = ['start']
        image = open(SAMPLE_IMAGE, 'rb')
        ctrl = self.browser.getControl(name='form.passport')
        file_ctrl = ctrl.mech_control
        file_ctrl.add_file(image, filename='myphoto.jpg')
        self.browser.getControl("Save").click()
        self.browser.getControl("Add online").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        #ctrl = self.browser.getControl(name='val_id')
        #value = ctrl.options[0]
        #self.browser.getLink(value).click()
        self.payment_url = self.browser.url

    def test_interswitch_form(self):
        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertTrue(
            '<span>1000.0</span>' in self.browser.contents)
        # Manager can access InterswitchForm
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertMatches('...Total Amount Authorized:...',
                           self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="100000" />'
            in self.browser.contents)
        delta = timedelta(days=8)
        self.applicant.values()[0].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)

    @external_test
    def test_webservice(self):

        self.browser.open(self.payment_url + '/request_webservice')
        self.assertMatches('...Unsuccessful callback...',
                          self.browser.contents)
        # The payment is now in state failed
        self.assertMatches('...<span>Failed</span>...',
                          self.browser.contents)
