## $Id: tests.py 15345 2019-03-06 21:33:16Z 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.kofa.configuration import SessionConfiguration
from waeup.kofa.university.faculty import Faculty
from waeup.kofa.university.department import Department
from kofacustom.dspg.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()

    def test_interswitch_form(self):
        # Manager can access InterswitchForm
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.payments_path)
        IWorkflowState(self.student).setState('cleared')
        self.student.nationality = u'NG'
        # ND FT Non-Deltan Fresh Student School Fee
        self.certificate.study_mode = 'nd_ft'
        self.certificate.school_fee_3 = 30000.0
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['schoolfee']
        self.browser.getControl("Create ticket").click()
        self.assertTrue('You have to pay NADESU/SA/SUG Dues first'
            in self.browser.contents)
        payment = createObject('waeup.StudentOnlinePayment')
        payment.p_category = u'dep_sug'
        payment.p_session = self.student.current_session
        payment.p_id = u'anyid'
        payment.p_state = u'paid'
        self.student['payments']['anykey'] = payment
        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[1]
        self.browser.getLink(self.value).click()
        self.assertTrue('<span>30000.0</span>'  in self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<input type="hidden" name="pay_item_id" value="102" />'
            in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="3000000" />' in
            self.browser.contents)
        self.assertTrue(
            'item_name="School Fee" item_amt="2575000" bank_id="117" acct_num="1012808851"' in
            self.browser.contents)
        # ND FT Non-Deltan Fresh Student Acceptance Fee
        self.app['configuration']['2004'].clearance_fee = 12345.0
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['clearance']
        self.browser.getControl("Create ticket").click()
        self.assertTrue('ticket created' in self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        self.value = ctrl.options[2]
        self.browser.getLink(self.value).click()
        self.assertTrue('Amount Authorized' in self.browser.contents)
        self.assertTrue('<span>12345.0</span>' in self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<input type="hidden" name="pay_item_id" value="103" />'
                           in self.browser.contents)
        self.assertTrue(
            '<input type="hidden" name="amount" value="1234500" />' in
            self.browser.contents)
        self.assertTrue(
            'item_name="Acceptance" item_amt="1159500" bank_id="51" acct_num="5210039869"' in
            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.assertMatches('...<input type="hidden" name="pay_item_id" value="103" />...',
                           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="87600" />...',
            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_pt_payments(self):
        # Add SPAT certificate
        certificate = createObject('waeup.Certificate')
        certificate.code = u'CERT2'
        certificate.application_category = 'basic' # can be anything
        certificate.start_level = 100
        certificate.end_level = 500
        certificate.study_mode = u'ug_ft' # can be anything
        self.app['faculties']['SPAT'] = Faculty(code=u'SPAT')
        self.app['faculties']['SPAT']['dep2'] = Department(code=u'dep2')
        department = self.app['faculties']['SPAT']['dep2']
        self.app['faculties']['SPAT']['dep2'].certificates.addCertificate(
            certificate)
        certificate.school_fee_3 = 30000.0
        self.student['studycourse'].certificate = certificate
        # Manager can access InterswitchForm
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.payments_path)
        IWorkflowState(self.student).setState('cleared')
        self.student.nationality = u'NG'
        # ND PT Non-Deltan Fresh Student School Fee
        self.certificate.study_mode = 'nd_ft'
        self.certificate.school_fee_3 = 30000.0
        # dep_sug tickets cannot be created
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['dep_sug']
        self.browser.getControl("Create ticket").click()
        self.assertTrue('Amount could not be determined' in self.browser.contents)
        #self.assertTrue('ticket created' in self.browser.contents)
        #ctrl = self.browser.getControl(name='val_id')
        #dep_sug_pid = ctrl.options[0]
        #self.assertTrue(self.student['payments'][dep_sug_pid].amount_auth == 1650)
        #self.browser.getLink(dep_sug_pid).click()
        #self.browser.getLink("CollegePAY", index=0).click()
        #self.student['payments'][dep_sug_pid].p_state = 'paid'
        #self.assertTrue(
        #    '<item_detail item_id="1" item_name="Students Welfare" '
        #    'item_amt="50000" bank_id="11" acct_num="0037892949" />'
        #    in self.browser.contents)
        # Add school fee ticket
        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.assertTrue('<span>30000.0</span>'  in self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<item_detail item_id="1" item_name="School Fee 1" item_amt="1545000" bank_id="117" acct_num="1015220292" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="2" item_name="School Fee 2" item_amt="1030000" bank_id="123" acct_num="1002883141" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="3" item_name="WAEAC" item_amt="280000" bank_id="8" acct_num="2028964403" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="4" item_name="Technology Fee" item_amt="120000" bank_id="10" acct_num="0032256360" />'
            in self.browser.contents)

    def test_interswitch_form_dep_sug_payments(self):
        # Manager can access InterswitchForm
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.payments_path)
        IWorkflowState(self.student).setState('cleared')
        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['dep_sug']
        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.assertTrue('<span>3150.0</span>'  in self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<item_detail item_id="1" item_name="SUG" item_amt="100000" bank_id="11" acct_num="0038079930" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="2" item_name="Students Welfare" item_amt="50000" bank_id="11" acct_num="0037892949" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="3" item_name="Anti-Cult Book" item_amt="90000" bank_id="11" acct_num="0037892949" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="4" item_name="NADESSTU" item_amt="50000" bank_id="11" acct_num="0036375968" />'
            in self.browser.contents)

    @external_test
    def test_webservice(self):
        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.payment_url = self.browser.url
        # 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 - '
            'kofacustom.dspg.interswitch.browser.CustomInterswitchPaymentRequestWebservicePageStudent - '
            'X1000000 - 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",X1000000,p3547789850240,schoolfee,'
            '12000.0,00,0.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 = SessionConfiguration()
        configuration.academic_session = datetime.now().year - 2
        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')
        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()


    def test_interswitch_form(self):
        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.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertTrue('span>1000.0</span>' in self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.getLink("CollegePAY", index=0).click()
        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)
        # ND PT Application Fee
        self.applicantscontainer.application_category = 'ndpt'
        self.certificate.application_category = 'ndpt'
        self.browser.open(self.manage_path)
        self.browser.getControl("Add online").click()
        self.browser.getLink("CollegePAY", index=0).click()
        self.assertTrue('<item_detail item_id="1" item_name="Application 1" item_amt="15000" bank_id="117" acct_num="1015220292" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="2" item_name="Application 2" item_amt="10000" bank_id="123" acct_num="1002883141" />'
            in self.browser.contents)
        self.assertTrue('<item_detail item_id="3" item_name="WAEAC" item_amt="50000" bank_id="8" acct_num="2028964403" />'
            in 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)
