## $Id: browser.py 16283 2020-10-15 20:23:45Z henrik $
##
## Copyright (C) 2012 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 httplib
import hashlib
import grok
from xml.dom import minidom
from zope.interface import Interface
from zope.component import queryAdapter
from waeup.kofa.interfaces import CLEARED
from kofacustom.nigeria.interswitch.browser import (
    InterswitchPaymentRequestWebservicePageStudent,
    InterswitchPaymentRequestWebservicePageApplicant,
    InterswitchPaymentVerifyWebservicePageApplicant,
    InterswitchPaymentVerifyWebservicePageStudent,
    InterswitchPageStudent, InterswitchPageApplicant,
    )
from waeup.aaue.students.interfaces import ICustomStudentOnlinePayment
from waeup.aaue.applicants.interfaces import ICustomApplicantOnlinePayment
from waeup.aaue.interfaces import MessageFactory as _

PRODUCT_ID_PT = '5040'
PRODUCT_ID_REGULAR = '5845'
SITE_NAME = 'aaue.waeup.org'
PROVIDER_ACCT = '5100189030'
PROVIDER_BANK_ID = '307'
PROVIDER_ITEM_NAME = 'WAeAC'
INSTITUTION_NAME = 'AAU Ekpoma'
CURRENCY = '566'
GATEWAY_AMT = 200.0
POST_ACTION = 'https://webpay.interswitchng.com/paydirect/pay'

HOST = 'webpay.interswitchng.com'
URL = '/paydirect/api/v1/gettransaction.json'
HTTPS = True
MAC_REGULAR = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
MAC_PT = '74424F1DFECD6058F153148255CDD55E16724B4F380ADB2C63C5D1D7A5675759010C8153DCB930AAF2D38903CBF7CE32B8A6BA2C16BBC46721DF2E3F3E4548E3'

httplib.HTTPSConnection.debuglevel = 0


def gateway_net_amt(fee):
    if fee > GATEWAY_AMT:
        return fee - GATEWAY_AMT
    return 0.0

def contr_agreement_applicant(applicant):
    if applicant.__parent__ in (
        'fp',
        'ptee',
        'dsh',
        'bridge',
        'ijmbe',
        ):
        return 'first'
    return 'second'

def contr_agreement_student(student):
    if student.current_mode in (
        'found',
        'bridge',
        'ug_dsh',
        'de_dsh',
        'ug_pt',
        'de_pt',
        'dp_pt',
        'ijmbe',
        ):
        return 'first'
    return 'second'

class CustomInterswitchPageApplicant(InterswitchPageApplicant):
    """ View which sends a POST request to the Interswitch
    CollegePAY payment gateway.

    So far only PT application has been configured.
    """
    grok.context(ICustomApplicantOnlinePayment)
    action = POST_ACTION
    site_name = SITE_NAME
    currency = CURRENCY
    provider_bank_id = PROVIDER_BANK_ID
    provider_acct = PROVIDER_ACCT
    institution_acct = '1010835352'
    institution_bank_id = '117'

    def update(self):

        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        self.context.r_company = u'interswitch'
        provider_amt = 2000.0
        fedex_amt = 0.0
        if contr_agreement_applicant(self.context.__parent__) == 'first':
            self.product_id = PRODUCT_ID_PT
            self.pay_item_id = '101'
            self.mac = MAC_PT
        else:
            self.product_id = PRODUCT_ID_REGULAR
            self.pay_item_id = '109'
            self.mac = MAC_REGULAR
            if self.applicant.__parent__.prefix in ('utme', 'ude'):
                provider_amt = 1000.0
            elif self.applicant.__parent__.prefix in ('trans', 'cert'):
                self.institution_acct = '1010827641'
                self.institution_bank_id = '117'
                self.provider_bank_id = '10'
                self.provider_acct = '0427773399'
                if self.applicant.applicant_id[:5] in ('cert7', 'cert8'):
                    provider_amt = 0.0
                if self.applicant.applicant_id[:6] in ('trans5', 'trans6'):
                    self.institution_acct = '5210006575'
                    self.institution_bank_id = '51'
                #if self.applicant.applicant_id[:6] in ('trans1', 'trans6'):
                #    fedex_amt = 10500.0
                if self.context.p_category == 'app_balance':
                    provider_amt = 0.0
            elif self.applicant.applicant_id.startswith('bridge'): # easier to test
                self.institution_acct = '1014847058'
                self.institution_bank_id = '7'
            elif self.applicant.applicant_id.startswith('dsh'): # easier to test
                self.institution_acct = '1014847058'
                self.institution_bank_id = '7'
            elif self.applicant.__parent__.prefix in ('ver', 'send'):
                provider_amt = 0.0
            elif self.applicant.__parent__.prefix == 'fedex':
                provider_amt = 0.0
                self.institution_acct = '0001115694'
                self.institution_bank_id = '10'
        xmldict = {}
        xmldict['detail_ref'] = self.context.p_id
        xmldict['provider_amt'] = 100 * provider_amt
        xmldict['provider_acct'] = self.provider_acct
        xmldict['provider_bank_id'] = self.provider_bank_id
        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
        xmldict['institution_acct'] = self.institution_acct
        xmldict['institution_bank_id'] = self.institution_bank_id
        xmldict['institution_item_name'] = self.category
        xmldict['institution_name'] = INSTITUTION_NAME
        xmldict['fedex_amt'] = 100 * fedex_amt
        xmldict['institution_amt'] = 100 * (
            self.context.amount_auth - provider_amt - fedex_amt - GATEWAY_AMT)

        xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict

        if provider_amt == 0.0:
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict

        if fedex_amt:
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
<item_detail item_id="3" item_name="FedEx" item_amt="%(fedex_amt)d" bank_id="10" acct_num="0001115694" />
</item_details>
</payment_item_detail>""" % xmldict

        if self.applicant.applicant_id.startswith('pg'):
            handbook_amount = 2000.0
            xmldict['handbook_amount'] = 100 * handbook_amount
            xmldict['institution_amt'] = 100 * (
                self.context.amount_auth - provider_amt - handbook_amount -GATEWAY_AMT)
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
<item_detail item_id="3" item_name="PG Handbook" item_amt="%(handbook_amount)d" bank_id="117" acct_num="1010827641" />
</item_details>
</payment_item_detail>""" % xmldict

        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
        self.context.provider_amt = provider_amt
        self.context.gateway_amt = GATEWAY_AMT
        xmlitems = ''
        xmldoc = minidom.parseString(xmltext)
        itemlist = xmldoc.getElementsByTagName('item_detail')
        for s in itemlist:
            xmlitems += "%s: %s, N%s, %s (%s)  " % (
                s.attributes['item_id'].value,
                s.attributes['item_name'].value,
                int(s.attributes['item_amt'].value)/100,
                s.attributes['acct_num'].value,
                s.attributes['bank_id'].value,
                )
        self.context.p_split_data = xmlitems
        self.amount_auth = int(100 * self.context.amount_auth)
        hashargs = (
            self.context.p_id +
            self.product_id +
            self.pay_item_id +
            str(int(self.amount_auth)) +
            self.site_redirect_url +
            self.mac)
        self.hashvalue = hashlib.sha512(hashargs).hexdigest()

        return

class CustomInterswitchPageStudent(InterswitchPageStudent):
    """ View which sends a POST request to the Interswitch
    CollegePAY payment gateway.
    """
    grok.context(ICustomStudentOnlinePayment)
    action = POST_ACTION
    site_name = SITE_NAME
    currency = CURRENCY
    pay_item_id = '000'

    def update(self):
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        self.context.r_company = u'interswitch'
        student = self.student
        p_session = self.context.p_session
        try:
            academic_session = grok.getSite()['configuration'][str(p_session)]
        except KeyError:
            self.flash(_(u'Session configuration object is not available.'),
                       type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        if contr_agreement_student(student) == 'first':
            self.product_id = PRODUCT_ID_PT
            self.mac = MAC_PT
        else:
            self.product_id = PRODUCT_ID_REGULAR
            self.mac = MAC_REGULAR

        # To guarantee that cleared students pay both acceptance fee
        # and school fees, the page can only be accessed
        # for school fee payments if acceptance/clearance fee has
        # been successfully queried/paid beforehand. This
        # requirement applies to students in state 'cleared' and
        # entry_session greater than 2012 only.
        if self.context.p_category.startswith('schoolfee') and \
            student.state == CLEARED and \
            student.entry_session > 2012:
            acceptance_fee_paid = False
            for ticket in student['payments'].values():
                if ticket.p_state == 'paid' and \
                    ticket.p_category.startswith('clearance'):
                    acceptance_fee_paid = True
                    break
            if not acceptance_fee_paid:
                self.flash(
                    _('Please pay acceptance fee first.'), type="danger")
                self.redirect(self.url(self.context, '@@index'))
                return

        xmldict = self.xmldict
        xmltext = ""
        xmldict['institution_acct'] = '1010827641'
        xmldict['institution_bank_id'] = '117'
        xmldict['detail_ref'] = self.context.p_id
        xmldict['provider_acct'] = PROVIDER_ACCT
        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
        xmldict['institution_item_name'] = self.category
        xmldict['institution_name'] = INSTITUTION_NAME
        provider_amt = 0.0

        # Schoolfee
        if self.context.p_category.startswith('schoolfee'):
            if contr_agreement_student(student) == 'first':
                # First agreement
                provider_amt = 1900.0
                joint_venture_amt = 0.0
                aaue_share_amt = 0.0
                student_union_due_amt = gateway_net_amt(
                    academic_session.union_fee)
                student_welfare_assurance_amt = gateway_net_amt(
                    academic_session.welfare_fee)
                sports_amt = gateway_net_amt(
                    academic_session.sports_fee)
                library_amt = gateway_net_amt(
                    academic_session.library_fee)
                library_amt_pg = gateway_net_amt(
                    academic_session.library_pg_fee)
                xmldict['student_union_bank_id'] = '31'
                xmldict['student_union_acct'] = '0051005007'
                xmldict['aaue_share_bank_id'] = '117'
                xmldict['aaue_share_acct'] = '1010827641'
                xmldict['joint_venture_bank_id'] = '117'
                xmldict['joint_venture_acct'] = '1010827641'
                xmldict['institution_acct'] = '1014847058'
                xmldict['institution_bank_id'] = '7'
                if student.current_mode == 'found':
                    self.pay_item_id = '103'
                else:
                    self.pay_item_id = '105'
            else:
                # Second agreement
                joint_venture_amt = 1000.0
                aaue_share_amt = 1500.0
                provider_amt = 1500.0
                student_union_due_amt = gateway_net_amt(
                    academic_session.union_fee)
                student_welfare_assurance_amt = gateway_net_amt(
                    academic_session.welfare_fee)
                sports_amt = gateway_net_amt(
                    academic_session.sports_fee)
                library_amt = gateway_net_amt(
                    academic_session.library_fee)
                library_amt_pg = gateway_net_amt(
                    academic_session.library_pg_fee)
                xmldict['student_union_bank_id'] = '7'
                xmldict['student_union_acct'] = '1019763348'
                xmldict['aaue_share_bank_id'] = '117'
                xmldict['aaue_share_acct'] = '1010827641'
                xmldict['joint_venture_bank_id'] = '117'
                xmldict['joint_venture_acct'] = '1010827641'
                self.pay_item_id = '107'
                if student.is_postgrad:
                    self.pay_item_id = '111'
                    xmldict['institution_acct'] = '5210006575'
                    xmldict['institution_bank_id'] = '51'
                if student.current_mode == 'ijmbe':
                    self.pay_item_id = '119'
                    xmldict['joint_venture_bank_id'] = '117'
                    xmldict['joint_venture_acct'] = '1010827641'

            xmldict['provider_amt'] = 100 * provider_amt
            xmldict['joint_venture_amt'] = 100 * joint_venture_amt
            xmldict['aaue_share_amt'] = 100 * aaue_share_amt
            if self.context.p_item == 'Balance':
                xmldict['institution_amt'] = 100 * (
                    gateway_net_amt(self.context.amount_auth))
            elif self.context.p_category == 'schoolfee_2':
                xmldict['institution_amt'] = 100 * gateway_net_amt(
                    self.context.amount_auth)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
            elif self.context.p_category in ('schoolfee_incl', 'schoolfee_1') \
                and student.current_mode != 'ijmbe':
                # Schoolfee including additional fees
                xmldict['student_union_due_amt'] = 100 * student_union_due_amt
                xmldict['student_welfare_assurance_amt'] = 100 * student_welfare_assurance_amt

                if student.entry_session >= 2018 and student.is_fresh:
                    xmldict['sports_amt'] = 100 * sports_amt
                    if student.is_postgrad:
                        xmldict['library_amt'] = 100 * library_amt_pg
                    else:
                        xmldict['library_amt'] = 100 * library_amt
                    xmldict['institution_amt'] = 100 * (
                        gateway_net_amt(self.context.amount_auth)
                        - provider_amt
                        - joint_venture_amt
                        - aaue_share_amt
                        - student_union_due_amt
                        - student_welfare_assurance_amt
                        - sports_amt
                        - library_amt)
                    xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
<item_detail item_id="3" item_name="Student Union" item_amt="%(student_union_due_amt)d" bank_id="%(student_union_bank_id)s" acct_num="%(student_union_acct)s" />
<item_detail item_id="4" item_name="Student Welfare Assurance" item_amt="%(student_welfare_assurance_amt)d" bank_id="123" acct_num="1006407792" />
<item_detail item_id="5" item_name="Sports Development Fee" item_amt="%(sports_amt)d" bank_id="123" acct_num="1006407792" />
<item_detail item_id="6" item_name="Library Development Fee" item_amt="%(library_amt)d" bank_id="8" acct_num="2000122995" />""" % xmldict
                    if contr_agreement_student(student) == 'second':
                        xmltext += """"
<item_detail item_id="7" item_name="Joint Venture" item_amt="%(joint_venture_amt)d" bank_id="%(joint_venture_bank_id)s" acct_num="%(joint_venture_acct)s" />
<item_detail item_id="8" item_name="AAUE Share" item_amt="%(aaue_share_amt)d" bank_id="%(aaue_share_bank_id)s" acct_num="%(aaue_share_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
                    else:
                        xmltext += """"
</item_details>
</payment_item_detail>"""
                else:
                    xmldict['institution_amt'] = 100 * (
                        gateway_net_amt(self.context.amount_auth)
                        - provider_amt
                        - joint_venture_amt
                        - aaue_share_amt
                        - student_union_due_amt
                        - student_welfare_assurance_amt)
                    xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
<item_detail item_id="3" item_name="Student Union" item_amt="%(student_union_due_amt)d" bank_id="%(student_union_bank_id)s" acct_num="%(student_union_acct)s" />
<item_detail item_id="4" item_name="Student Welfare Assurance" item_amt="%(student_welfare_assurance_amt)d" bank_id="123" acct_num="1006407792" />""" % xmldict
                    if contr_agreement_student(student) == 'second':
                        xmltext += """"
<item_detail item_id="5" item_name="Joint Venture" item_amt="%(joint_venture_amt)d" bank_id="%(joint_venture_bank_id)s" acct_num="%(joint_venture_acct)s" />
<item_detail item_id="6" item_name="AAUE Share" item_amt="%(aaue_share_amt)d" bank_id="%(aaue_share_bank_id)s" acct_num="%(aaue_share_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
                    else:
                        xmltext += """"
</item_details>
</payment_item_detail>"""
            elif contr_agreement_student(student) == 'second':
                # Schoolfee without Student Union Fee ands Student Welfare Assurance
                xmldict['institution_amt'] = 100 * (
                    gateway_net_amt(self.context.amount_auth)
                    - provider_amt
                    - joint_venture_amt
                    - aaue_share_amt)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
<item_detail item_id="3" item_name="Joint Venture" item_amt="%(joint_venture_amt)d" bank_id="%(joint_venture_bank_id)s" acct_num="%(joint_venture_acct)s" />
<item_detail item_id="4" item_name="AAUE Share" item_amt="%(aaue_share_amt)d" bank_id="%(aaue_share_bank_id)s" acct_num="%(aaue_share_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
            else:
                xmldict['institution_amt'] = 100 * (
                    gateway_net_amt(self.context.amount_auth)
                    - provider_amt)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict


        # Clearance
        elif self.context.p_category.startswith('clearance'):
            xmldict['institution_acct'] = '1010835352'
            provider_amt = 0.0
            if contr_agreement_student(student) == 'first':
                # First agreement
                if student.current_mode == 'found':
                    self.pay_item_id = '102'
                else:
                    self.pay_item_id = '104'
                xmldict['institution_acct'] = '1014847058'
                xmldict['institution_bank_id'] = '7'
            else:
                # Second agreement
                self.pay_item_id = '102'
                if student.is_postgrad:
                    self.pay_item_id = '110'
                    xmldict['institution_acct'] = '5210006575'
                    xmldict['institution_bank_id'] = '51'
                if student.current_mode == 'ijmbe':
                    self.pay_item_id = '120'
                # ivama: Acceptance fee split is unique to "ug_ft"
                # The reason for split is perculiar to them only...
                # That amount was deducted from UTME application fee because
                # some regulatory body have pegged the application fee which
                # didn't affect another programmes.
                if student.current_mode == 'ug_ft':
                    provider_amt = 1500.0
            xmldict['provider_amt'] = 100 * provider_amt
            if self.context.p_category.endswith('_incl'):
                # Clearance including additional fees
                gown_fee_amt = gateway_net_amt(academic_session.matric_gown_fee)
                aaue_lf_fee_amt = gateway_net_amt(academic_session.lapel_fee)
                xmldict['gown_fee_amt'] = 100 * gown_fee_amt
                xmldict['aaue_lf_fee_amt'] = 100 * aaue_lf_fee_amt
                xmldict['institution_amt'] = 100 * (
                    gateway_net_amt(self.context.amount_auth)
                    - gown_fee_amt
                    - aaue_lf_fee_amt
                    - provider_amt)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="Matriculation Gown Fee" item_amt="%(gown_fee_amt)d" bank_id="117" acct_num=" 1010835352" />
<item_detail item_id="3" item_name="AAU File-Lapel Fee" item_amt="%(aaue_lf_fee_amt)d" bank_id="117" acct_num=" 1010835352" />""" % xmldict
                if provider_amt:
                    xmltext += """"
<item_detail item_id="4" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
                else:
                    xmltext += """"
</item_details>
</payment_item_detail>"""

            elif student.current_mode == 'bridge':
                # Clearance without any surcharge
                xmldict['institution_amt'] = 100 * gateway_net_amt(
                    self.context.amount_auth)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict

            else:
                # Clearance without additional fees
                xmldict['institution_amt'] = 100 * (
                    gateway_net_amt(self.context.amount_auth)
                    - provider_amt)
                xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />""" % xmldict
                if provider_amt:
                        xmltext += """"
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
                else:
                        xmltext += """"
</item_details>
</payment_item_detail>""" 

        # Union Dues
        elif self.context.p_category == 'union':
            self.pay_item_id = '103'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))
            if contr_agreement_student(student) == 'first':
                # First agreement
                xmldict['institution_acct'] = '0051005007'
                xmldict['institution_bank_id'] = '31'
            else:
                # Second agreement
                xmldict['institution_bank_id'] = '7'
                xmldict['institution_acct'] = '1019763348'

        # Lapel/File
        elif self.context.p_category == 'lapel':
            self.pay_item_id = '104'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Welfare Assurance
        elif self.context.p_category == 'welfare':
            self.pay_item_id = '105'
            xmldict['institution_acct'] = '1006407792'
            xmldict['institution_bank_id'] = '123'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # ID Card
        elif self.context.p_category == 'id_card':
            self.pay_item_id = '000'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Matric Gown
        elif self.context.p_category == 'matric_gown':
            self.pay_item_id = '106'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Concessional
        elif self.context.p_category == 'concessional':
            self.pay_item_id = '107'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Hostel Maintenance
        elif self.context.p_category == 'hostel_maintenance':
            provider_amt = 500.0
            self.pay_item_id = '109'
            xmldict['provider_amt'] = 100 * provider_amt
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth) - provider_amt)
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict

        # GST Fees
        elif self.context.p_category.startswith('gst_'):
            if contr_agreement_student(student) == 'first':
                self.pay_item_id = '115'
            else:
                self.pay_item_id = '116'
            xmldict['institution_acct'] = '1010893123'
            xmldict['institution_bank_id'] = '117'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # ENT Fees
        elif self.context.p_category.startswith('ent_'):
            if contr_agreement_student(student) == 'first':
                self.pay_item_id = '114'
            else:
                self.pay_item_id = '118'
            xmldict['institution_acct'] = '6220029828'
            xmldict['institution_bank_id'] = '51'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Faculty and Departmental Dues
        elif self.context.p_category == 'fac_dep':
            xmldict['institution_acct'] = '1016425386'
            xmldict['institution_bank_id'] = '117'
            self.pay_item_id = '117'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Restitution Fee
        elif self.context.p_category == 'restitution':
            self.pay_item_id = '117'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Faculty Laboratory Due
        elif self.context.p_category in ('lab_1', 'lab_2'):
            xmldict['institution_acct'] = '1016425386'
            xmldict['institution_bank_id'] = '117'
            self.pay_item_id = '117'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))

        # Sports Fee
        #elif self.context.p_category == 'sports':
        #    self.pay_item_id = '105'
        #    xmldict['institution_amt'] = 100 * (
        #        gateway_net_amt(self.context.amount_auth))

        # Library Fee
        #elif self.context.p_category == 'library':
        #    self.pay_item_id = '105'
        #    xmldict['institution_amt'] = 100 * (
        #        gateway_net_amt(self.context.amount_auth))

        # Library PG Fee
        #elif self.context.p_category == 'library_pg':
        #    self.pay_item_id = '105'
        #    xmldict['institution_amt'] = 100 * (
        #        gateway_net_amt(self.context.amount_auth))

        # Sports & Library Fee    temporarily in 2020
        elif self.context.p_category == 'sports_library':
            self.pay_item_id = '105'
            xmldict['sports_amt'] = 100 * 3000.0
            xmldict['library_amt'] = 100 * 1000.0
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="Sports Development Fee" item_amt="%(sports_amt)d" bank_id="123" acct_num="1006407792" />
<item_detail item_id="2" item_name="Library Development Fee" item_amt="%(library_amt)d" bank_id="8" acct_num="2000122995" />
</item_details>
</payment_item_detail>""" % xmldict

        # Late Registration Fee
        elif self.context.p_category == 'late_registration':
            if contr_agreement_student(student) == 'first':
                self.pay_item_id = '113'
            else:
                self.pay_item_id = '123'
            xmldict['institution_amt'] = 100 * (
                gateway_net_amt(self.context.amount_auth))
            if student.is_postgrad:
                xmldict['institution_acct'] = '5210006575'
                xmldict['institution_bank_id'] = '51'
        if not xmltext:
            xmltext = """<payment_item_detail>
<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
</item_details>
</payment_item_detail>""" % xmldict
        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
        self.context.provider_amt = provider_amt
        self.context.gateway_amt = self.context.amount_auth - gateway_net_amt(
            self.context.amount_auth)
        xmlitems = ''
        xmldoc = minidom.parseString(xmltext)
        itemlist = xmldoc.getElementsByTagName('item_detail')
        for s in itemlist:
            xmlitems += "%s: %s, N%s, %s (%s)  " % (
                s.attributes['item_id'].value,
                s.attributes['item_name'].value,
                int(s.attributes['item_amt'].value)/100,
                s.attributes['acct_num'].value,
                s.attributes['bank_id'].value,
                )
        self.context.p_split_data = xmlitems
        self.amount_auth = int(100 * self.context.amount_auth)
        hashargs = (
            self.context.p_id +
            self.product_id +
            self.pay_item_id +
            str(int(self.amount_auth)) +
            self.site_redirect_url +
            self.mac)
        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
        return


class CustomInterswitchPaymentRequestWebservicePageApplicant(
    InterswitchPaymentRequestWebservicePageApplicant):
    """Request webservice view for the CollegePAY gateway
    """
    grok.context(ICustomApplicantOnlinePayment)
    gateway_host = HOST
    gateway_url = URL
    https = HTTPS

    @property
    def mac(self):
        if contr_agreement_applicant(self.context.__parent__) == 'first':
            return MAC_PT
        return MAC_REGULAR

    @property
    def product_id(self):
        if contr_agreement_applicant(self.context.__parent__) == 'first':
            return PRODUCT_ID_PT
        return PRODUCT_ID_REGULAR

class CustomInterswitchPaymentVerifyWebservicePageApplicant(
    InterswitchPaymentVerifyWebservicePageApplicant):
    """Payment verify view for the CollegePAY gateway
    """
    grok.context(ICustomApplicantOnlinePayment)
    gateway_host = HOST
    gateway_url = URL
    https = HTTPS

    @property
    def mac(self):
        if contr_agreement_applicant(self.context.__parent__) == 'first':
            return MAC_PT
        return MAC_REGULAR

    @property
    def product_id(self):
        if contr_agreement_applicant(self.context.__parent__) == 'first':
            return PRODUCT_ID_PT
        return PRODUCT_ID_REGULAR

class CustomInterswitchPaymentRequestWebservicePageStudent(
    InterswitchPaymentRequestWebservicePageStudent):
    """Request webservice view for the CollegePAY gateway
    """
    grok.context(ICustomStudentOnlinePayment)
    gateway_host = HOST
    gateway_url = URL
    https = HTTPS

    @property
    def mac(self):
        if contr_agreement_student(self.context.student) == 'first':
            return MAC_PT
        return MAC_REGULAR

    @property
    def product_id(self):
        if contr_agreement_student(self.context.student) == 'first':
            return PRODUCT_ID_PT
        return PRODUCT_ID_REGULAR

class CustomInterswitchPaymentVerifyWebservicePageStudent(
    InterswitchPaymentVerifyWebservicePageStudent):
    """Payment verify view for the CollegePAY gateway
    """
    grok.context(ICustomStudentOnlinePayment)
    gateway_host = HOST
    gateway_url = URL
    https = HTTPS

    @property
    def mac(self):
        if contr_agreement_student(self.context.student) == 'first':
            return MAC_PT
        return MAC_REGULAR

    @property
    def product_id(self):
        if contr_agreement_student(self.context.student) == 'first':
            return PRODUCT_ID_PT
        return PRODUCT_ID_REGULAR
