## $Id: tests.py 14087 2016-08-18 06:01:42Z 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
##
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.students.tests.test_browser import StudentsFullSetup
from waeup.kofa.applicants.tests.test_browser import (
    ApplicantsFullSetup, session_1)
from waeup.kofa.configuration import SessionConfiguration
from waeup.aaue.testing import FunctionalLayer
from waeup.aaue.etranzact.browser import ERROR_PART1, ERROR_PART2


# 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[:-2]
        print "WARNING: external tests are skipped!"
        print "WARNING: edit %s to enable them." % myself
        return
    return func

class EtranzactTestsStudent(StudentsFullSetup):
    """Tests for the eTranzact payment gateway.
    """

    layer = FunctionalLayer

    CONFIRMATION_NO = '500856521315472785095'

    def setUp(self):
        super(EtranzactTestsStudent, self).setUp()
        # Managers can add online payment tickets
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.student['studycourse'].certificate.school_fee_1 = 1234.0
        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 = ['clearance_incl']
        self.browser.getControl("Create ticket").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        value1 = ctrl.options[0]

        self.browser.open(self.payments_path + '/addop')
        self.browser.getControl(name="form.p_category").value = ['schoolfee_incl']
        self.browser.getControl("Create ticket").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        value2 = ctrl.options[1]
        self.p_id = value2
        self.payment = self.student['payments'][value2]
        self.browser.getLink(value2).click()
        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.payment_url = self.browser.url

    def test_enterpin(self):
        self.student['studycourse'].entry_session = 2013
        self.browser.open(self.payment_url)
        self.browser.getLink("Query eTranzact History").click()
        self.assertTrue(
            'Please pay acceptance fee firs' in self.browser.contents)
        self.assertFalse(
            'Confirmation Number (PIN)' in self.browser.contents)
        self.student['payments'].values()[0].approve()
        self.browser.getLink("Query eTranzact History").click()
        self.assertFalse(
            'Please pay acceptance fee firs' in self.browser.contents)
        self.assertTrue(
            'Confirmation Number (PIN)' in self.browser.contents)

    def test_webservice(self):
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-PLUS-NEW'
            % self.p_id)
        self.assertEqual(self.browser.contents,
            'PayeeName=TESTER, Anna~'
            'Faculty=fac1~'
            'Department=dep1~'
            'Level=100~'
            'ProgrammeType=CERT1~'
            'StudyType=ug_ft~'
            'Session=2004/2005~'
            'PayeeID=%s~'
            'Amount=1234.0~'
            'FeeStatus=unpaid~'
            'Semester=N/A~'
            'PaymentType=School Fee Plus~'
            'MatricNumber=E1000000~'
            'Email=aa@aa.ng~'
            'PhoneNumber=1234' % self.p_id)

        self.browser.open('http://localhost/app/feerequest')
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Missing PAYEE_ID' + ERROR_PART2)

        self.browser.open('http://localhost/app/feerequest?NONSENSE=nonsense')
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Missing PAYEE_ID' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=nonsense&PAYMENT_TYPE=SCHOOL-FEE-NEW')
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Invalid PAYEE_ID' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=NONSENSE'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Invalid PAYMENT_TYPE' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Invalid PAYMENT_TYPE' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=ACCEPTANCE-FEE'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Wrong PAYMENT_TYPE' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=APPLICATION-FEE'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Wrong PAYMENT_TYPE' + ERROR_PART2)

        # Change payment state
        self.student['payments'][self.p_id].p_state = 'paid'

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-NEW'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'PAYEE_ID already used' + ERROR_PART2)

        # Change workflow state and payment state
        IWorkflowState(self.student).setState('returning')
        self.student['payments'][self.p_id].p_state = 'unpaid'

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-NEW'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Wrong PAYMENT_TYPE' + ERROR_PART2)

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-BALANCE'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Not a balance payment' + ERROR_PART2)

        # Change payment item
        self.payment.p_item = u'Balance'
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-PLUS-RETURNING'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Balance payment' + ERROR_PART2)

        # Change study mode
        self.certificate.study_mode = 'special_pg_pt'
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-BALANCE'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Part-time student' + ERROR_PART2)
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-PT-BALANCE'
            % self.p_id)
        self.assertEqual(self.browser.contents,
            'PayeeName=TESTER, Anna~'
            'Faculty=fac1~'
            'Department=dep1~'
            'Level=100~'
            'ProgrammeType=Balance~'
            'StudyType=special_pg_pt~'
            'Session=2004/2005~'
            'PayeeID=%s~'
            'Amount=1234.0~'
            'FeeStatus=unpaid~'
            'Semester=N/A~'
            'PaymentType=School Fee Plus~'
            'MatricNumber=E1000000~'
            'Email=aa@aa.ng~'
            'PhoneNumber=1234' % self.p_id)

        # Change payment item
        self.payment.p_item = u'CERT1'

        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-PLUS-RETURNING'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Postgrad student' + ERROR_PART2)

        # Cange payment category and study mode
        self.payment.p_category = 'schoolfee'
        self.certificate.study_mode = 'ug_ft'
        
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-RETURNING'
            % self.p_id)
        self.assertEqual(self.browser.contents,
            'PayeeName=TESTER, Anna~'
            'Faculty=fac1~'
            'Department=dep1~'
            'Level=100~'
            'ProgrammeType=CERT1~'
            'StudyType=ug_ft~'
            'Session=2004/2005~'
            'PayeeID=%s~'
            'Amount=1234.0~'
            'FeeStatus=unpaid~'
            'Semester=N/A~'
            'PaymentType=School Fee~'
            'MatricNumber=E1000000~'
            'Email=aa@aa.ng~'
            'PhoneNumber=1234' % self.p_id)

        IWorkflowState(self.student).setState('cleared')
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-FP-NEW'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Not a foundation programme student' + ERROR_PART2)
        self.certificate.study_mode = 'found'
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=SCHOOL-FEE-NEW'
            % self.p_id)
        self.assertEqual(self.browser.contents, ERROR_PART1 + 'Foundation programme student' + ERROR_PART2)

    @external_test
    def test_etranzact_query_history(self):

        self.browser.open(self.payment_url + '/query_history?confirmation_number=%s'
            % self.CONFIRMATION_NO)
        self.assertMatches('...Invalid or unsuccessful callback:...',
                          self.browser.contents)
        #self.assertMatches('...Wrong amount...',
        #                  self.browser.contents)
        #self.student['payments'][value].amount_auth = self.student[
        #    'payments'][value].r_amount_approved
        #self.browser.open(self.payment_url + '/query_history?confirmation_number=%s'
        #    % self.CONFIRMATION_NO)
        #self.assertMatches('...Wrong transaction id...',
        #                  self.browser.contents)

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

    layer = FunctionalLayer

    CONFIRMATION_NO = '500856521315472785095'

    def setUp(self):
        super(EtranzactTestsApplicants, self).setUp()
        self.applicantscontainer.application_fee = 200.0
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.manage_path)
        #IWorkflowState(self.student).setState('started')
        super(EtranzactTestsApplicants, self).fill_correct_values()
        self.browser.getControl(name="transition").value = ['start']
        self.browser.getControl(name="form.nationality").value = ['NG']
        #self.browser.getControl(name="form.programme_type").value = ['direct']
        self.browser.getControl("Save").click()
        self.browser.getControl("Add online").click()
        self.assertTrue(
            'Session configuration object is not available'
            in self.browser.contents)
        configuration = SessionConfiguration()
        configuration.academic_session = session_1
        self.applicantscontainer.application_fee = 1000.0
        self.app['configuration'].addSessionConfiguration(configuration)
        self.browser.open(self.manage_path)
        self.browser.getControl("Add online").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        self.assertMatches('...Amount Authorized...',
                           self.browser.contents)
        self.assertMatches(
            '...<span>1000.0</span>...',
            self.browser.contents)
        self.payment_url = self.browser.url
        self.browser.open(self.manage_path)
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[0]
        self.p_id = value

    def test_webservice(self):
        self.browser.open(
            'http://localhost/app/feerequest?PAYEE_ID=%s&PAYMENT_TYPE=APPLICATION-FEE'
            % self.p_id)
        self.assertEqual(self.browser.contents,
            'PayeeName=TESTER, John Anthony~'
            'Faculty=N/A~'
            'Department=N/A~'
            'Level=N/A~'
            'ProgrammeType=This is the app%s container~'
            'StudyType=N/A~'
            'Session=%s/%s~'
            'PayeeID=%s~'
            'Amount=1000.0~'
            'FeeStatus=unpaid~'
            'Semester=N/A~'
            'PaymentType=Application Fee~'
            'MatricNumber=%s~'
            'Email=xx@yy.zz~'
            'PhoneNumber=None' % (
                session_1, session_1, session_1+1,
                self.p_id,self.applicant.applicant_id))

    @external_test
    def test_etranzact_query_history(self):

        self.browser.open(self.payment_url + '/query_history?confirmation_number=%s'
            % self.CONFIRMATION_NO)
        self.assertMatches('...Invalid or unsuccessful callback:...',
                          self.browser.contents)
        #self.assertMatches('...Wrong amount...',
        #                  self.browser.contents)
        #self.applicant[value].amount_auth = self.applicant[
        #    value].r_amount_approved
        #self.browser.open(self.payment_url + '/query_history?confirmation_number=%s'
        #    % self.CONFIRMATION_NO)
        #self.assertMatches('...Wrong transaction id...',
        #                  self.browser.contents)
