## $Id: tests.py 14805 2017-08-18 07:41:11Z henrik $
##
## Copyright (C) 2017 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 unittest
import random
import json
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 kofacustom.nigeria.students.payments import NigeriaStudentOnlinePayment
from kofacustom.nigeria.testing import FunctionalLayer

from kofacustom.nigeria.remita.helpers import (
    get_JSON_POST_response, get_payment_status_via_rrr, query_remita)

# 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 = True

MERCHANTID = '2547916'
HOST = 'www.remitademo.net'
HTTPS = False
API_KEY = '1946'
SERVICETYPEID = '4430731'

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 HelperTests(unittest.TestCase):

    merchantId = MERCHANTID
    host = HOST
    https = HTTPS
    api_key = API_KEY
    serviceTypeId = SERVICETYPEID

    responseurl = 'http://xxxx'

    url = '/remita/ecomm/split/init.reg'  # /remita/ecomm/v2/init.reg
    lineitems = (
                  {"lineItemsId":"itemid1","beneficiaryName":"Oshadami Mike",
                  "beneficiaryAccount":"6020067886","bankCode":"011",
                  "beneficiaryAmount":"500","deductFeeFrom":"1"},
                  {"lineItemsId":"itemid2","beneficiaryName":"Ogunseye Mujib",
                  "beneficiaryAccount":"0360883515","bankCode":"050",
                  "beneficiaryAmount":"500","deductFeeFrom":"0"}
                )
    amount = 1000.0

    def _get_transaction_data(self):
        self.orderId = str(random.randint(100000000, 999999999))
        resp = get_JSON_POST_response(
                merchantId=self.merchantId, serviceTypeId=self.serviceTypeId,
                api_key=self.api_key, orderId=self.orderId,
                amount=self.amount, responseurl=self.responseurl,
                host=self.host, url=self.url, https=self.https,
                fullname='Anton Meier', email='am@xxx.de',
                lineitems=self.lineitems)
        return resp

    @external_test
    def test_get_JSON_POST_response(self):
        resp = self._get_transaction_data()
        self.rrr = resp['RRR']
        assert resp == {
            u'status': u'Payment Reference generated',
            u'orderID': self.orderId,
            u'RRR': self.rrr,
            u'statuscode': u'025'}
        resp = get_JSON_POST_response(
                merchantId=self.merchantId, serviceTypeId=self.serviceTypeId,
                api_key=self.api_key, orderId=self.orderId,
                amount=self.amount, responseurl=self.responseurl,
                host=self.host, url=self.url, https=self.https,
                fullname='Anton Meier', email='am@xxx.de',
                lineitems=self.lineitems)
        assert resp == {
            u'status': u'Duplicate Order Ref',
            u'statuscode': u'028'}

        resp = get_payment_status_via_rrr(
                merchantId=self.merchantId,
                api_key=self.api_key,
                RRR=self.rrr,
                host=self.host,
                https=self.https,
                )
        assert resp['orderId'] == self.orderId
        assert resp['status'] == '021'
        assert resp['amount'] == self.amount
        assert resp['RRR'] == self.rrr
        assert resp['message'] == u'Transaction Pending'

class RemitaTestsStudents(StudentsFullSetup):
    """Tests for the Remita payment gateway.
    """

    layer = FunctionalLayer

    merchantId = MERCHANTID
    host = HOST
    https = HTTPS
    api_key = API_KEY
    serviceTypeId = SERVICETYPEID

    responseurl = 'http://xxxx'

    # successful transaction
    # (hopefully this transaction remains in the Remita database)
    orderId = '3456346346'
    rrr = u'280007640804'
    amount = 1000.0

    # pending transaction
    #orderId_p = '987698769876'
    rrr_p = u'320007640976'

    def setUp(self):
        super(RemitaTestsStudents, self).setUp()
        self.app['configuration']['2004'].remita_enabled = True
        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]

    @external_test
    def test_query_remita(self):
        #requery pending transaction
        qr = query_remita(
            self.payment,
            merchantId=self.merchantId,
            api_key=self.api_key,
            RRR=self.rrr_p,
            host=self.host,
            https=self.https,
            verify=False)
        assert qr == (
            False,
            u'Unsuccessful response: ${a}',
            u'unsuccessful response for schoolfee payment %s: Transaction Pending'
            % self.payment.p_id)

        #requery successful transaction
        self.payment.amount_auth = 1000.0
        self.payment.p_id = self.orderId
        qr = query_remita(
            self.payment,
            merchantId=self.merchantId,
            api_key=self.api_key,
            RRR=self.rrr,
            host=self.host,
            https=self.https,
            verify=False)
        assert qr[0] == True
        assert qr[1] == u'Successful response received'

    @external_test
    def test_student_remita_form(self):
        # Manager can access Remita form
        self.browser.getLink("Pay via Remita").click()
        # The RRR has been retrieved
        self.assertTrue('<input name="rrr" type="hidden" value="%s">'
            % self.payment.r_pay_reference
            in self.browser.contents)
        self.assertTrue(
            'action="http://www.remitademo.net/remita/ecomm/finalize.reg"'
            in self.browser.contents)
        self.assertEqual(self.payment.r_company, 'remita')
        # Retrieval has been logged
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'students.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.mgr - kofacustom.nigeria.remita.studentsbrowser.RemitaPageStudent'
            ' - K1000000 - RRR retrieved: %s, ServiceTypeId: %s'
            % (self.payment.r_pay_reference, self.serviceTypeId) in logcontent)

        # Means of testing end here.
        return

    @external_test
    def test_requery_verify_payment_status(self):
        # Manager can access Remita form
        self.browser.getLink("Requery Remita Payment Status").click()
        self.assertTrue('Remita Retrieval Reference not found.'
            in self.browser.contents)
        self.payment.r_pay_reference = self.rrr
        self.browser.getLink("Requery Remita Payment Status").click()
        self.assertTrue('Response amount does not match.'
            in self.browser.contents)
        self.payment.amount_auth = self.amount
        self.browser.getLink("Requery Remita Payment Status").click()
        self.assertTrue('Response order id does not match.'
            in self.browser.contents)
        self.payment.p_id = self.orderId
        self.browser.getLink("Requery Remita Payment Status").click()
        self.assertTrue('Successful payment' in self.browser.contents)
        self.assertEqual(self.payment.r_desc, 'Approved')
        self.assertEqual(self.payment.r_amount_approved , 1000.0)
        self.assertEqual(self.payment.r_code, '01')
        self.browser.getLink("Verify Remita Payment Status").click()
        self.assertTrue('Successful response received' in self.browser.contents)
        return

class RemitaTestsWebserviceStudent(StudentsFullSetup):
    """Tests for the Remita payment gateway.
    """
    layer = FunctionalLayer

    merchantId = MERCHANTID
    host = HOST
    https = HTTPS
    api_key = API_KEY

    responseurl = 'http://xxxx'

    # successful transaction
    # (hopefully this transaction remains in the Remita database)
    orderId = '3456346346'
    rrr = u'280007640804'
    amount = 1000.0

    @external_test
    def test_payment_notification_listener_student(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 = self.orderId
        self.student['payments']['anykey'] = payment
        data = [{'orderRef': self.orderId, 'rrr': self.rrr},]
        # Send POST request with wrong payment amount
        payment.amount_auth = 2000.0
        self.browser.post('http://localhost/app/paymentnotificationlistener',
            json.dumps(data), 'application/json; charset=utf-8')
        self.assertEqual('0 (1)', self.browser.contents)
        # Send POST request with correct payment amount
        payment.amount_auth = self.amount
        self.browser.post('http://localhost/app/paymentnotificationlistener',
            json.dumps(data), 'application/json; charset=utf-8')
        self.assertEqual('1 (1)', self.browser.contents)
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'students.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
            ' - K1000000 - valid response for schoolfee payment %s: '
            % self.orderId   in logcontent)
        self.assertTrue(
            'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
            ' - K1000000 - successful schoolfee payment: %s'
            % self.orderId in logcontent)
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'main.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.anybody - PaymentNotificationListenerWebservice request: '
            '[{"rrr": "%s", "orderRef": "%s"}]'
            % (self.rrr, self.orderId) in logcontent)
        return

class RemitaTestsWebserviceApplicant(ApplicantsFullSetup):
    """Tests for the Remita payment gateway.
    """
    layer = FunctionalLayer

    merchantId = MERCHANTID
    host = HOST
    https = HTTPS
    api_key = API_KEY

    responseurl = 'http://xxxx'

    # successful transaction
    # (hopefully this transaction remains in the Remita database)
    orderId = '3456346346'
    rrr = u'280007640804'
    amount = 1000.0

    @external_test
    def test_payment_notification_listener_applicant(self):
        self.applicantscontainer.application_fee = self.amount
        payment = createObject('waeup.ApplicantOnlinePayment')
        payment.p_category = u'application'
        payment.p_session = self.applicantscontainer.year
        payment.p_item = u'My Certificate'
        payment.p_id = self.orderId
        payment.amount_auth = self.amount
        self.applicant['anykey'] = payment
        IWorkflowState(self.applicant).setState('started')
        # Send POST request
        data = [{'orderRef': self.orderId, 'rrr': self.rrr},]
        self.browser.post('http://localhost/app/paymentnotificationlistener',
            json.dumps(data), 'application/json; charset=utf-8')
        self.assertEqual('1 (1)', self.browser.contents)
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'applicants.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
            ' - %s - valid response for application payment %s: '
            % (self.applicant.applicant_id, self.orderId) in logcontent)
        self.assertTrue(
            'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
            ' - %s - successful payment: %s'
            % (self.applicant.applicant_id, self.orderId) in logcontent)
        return

class RemitaTestsApplicants(ApplicantsFullSetup):
    """Tests for the Remita payment gateway.
    """

    layer = FunctionalLayer

    # successful transaction
    # (hopefully this transaction remains in the Remita database)
    #orderId = '3456346346'
    rrr = u'280007640804'
    serviceTypeId = SERVICETYPEID
    #amount = 1000.0

    def setUp(self):
        super(RemitaTestsApplicants, self).setUp()
        configuration = SessionConfiguration()
        configuration.academic_session = datetime.now().year - 2
        configuration.remita_enabled = True
        self.app['configuration'].addSessionConfiguration(configuration)
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.manage_path)
        #IWorkflowState(self.student).setState('started')
        super(RemitaTestsApplicants, 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

    @external_test
    def test_applicant_remita_form(self):
        # Manager can access Remita form
        self.browser.getLink("Pay via Remita").click()
        # The RRR has been retrieved
        self.assertTrue('<input name="rrr" type="hidden" value="%s">'
            % self.payment.r_pay_reference
            in self.browser.contents)
        self.assertEqual(self.payment.r_company, 'remita')
        # Retrieval has been logged
        logfile = os.path.join(
            self.app['datacenter'].storage, 'logs', 'applicants.log')
        logcontent = open(logfile).read()
        self.assertTrue(
            'zope.mgr - kofacustom.nigeria.remita.applicantsbrowser.RemitaPageApplicant'
            ' - %s - RRR retrieved: %s, ServiceTypeId: %s'
            % (self.applicant.applicant_id,
               self.payment.r_pay_reference,
               self.serviceTypeId)
            in logcontent)
        # Means of testing end here.
        return
