## $Id: browser.py 12975 2015-05-21 17:05:42Z 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 zope.interface import Interface
from zope.component import queryAdapter
from waeup.kofa.interfaces import CLEARED
from kofacustom.nigeria.interswitch.browser import (
    InterswitchPaymentRequestWebservicePageStudent,
    InterswitchPaymentRequestWebservicePageApplicant,
    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 = '5040'
SITE_NAME = 'aaue.waeup.org'
PROVIDER_ACCT = '1010764827'
PROVIDER_BANK_ID = '117'
PROVIDER_ITEM_NAME = 'BT Education'
INSTITUTION_NAME = 'AAU Ekpoma'
CURRENCY = '566'
GATEWAY_AMT = 250.0
#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'

#POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
#POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
#POST_ACTION = 'https://stageserv.interswitchng.com/test_paydirect/pay'
POST_ACTION = 'https://webpay.interswitchng.com/paydirect/pay'

HOST = 'webpay.interswitchng.com'
#HOST = 'stageserv.interswitchng.com'
HTTPS = True

URL = '/paydirect/services/TransactionQueryWs.asmx'
#URL = '/test_paydirect/services/TransactionQueryWS.asmx'
httplib.HTTPSConnection.debuglevel = 0

class CustomInterswitchPageApplicant(InterswitchPageApplicant):
    """ View which sends a POST request to the Interswitch
    CollegePAY payment gateway.
    """
    grok.context(ICustomApplicantOnlinePayment)
    action = POST_ACTION
    site_name = SITE_NAME
    currency = CURRENCY
    pay_item_id = '101'
    product_id = PRODUCT_ID
    mac = '74424F1DFECD6058F153148255CDD55E16724B4F380ADB2C63C5D1D7A5675759010C8153DCB930AAF2D38903CBF7CE32B8A6BA2C16BBC46721DF2E3F3E4548E3'

    def update(self):

        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        xmldict = {}
        provider_amt = 1000.0
        xmldict['institution_acct'] = '1010835352'
        xmldict['institution_bank_id'] = '117'
        xmldict['detail_ref'] = self.context.p_id
        xmldict['provider_amt'] = 100 * provider_amt
        xmldict['provider_acct'] = PROVIDER_ACCT
        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
        xmldict['institution_amt'] = 100 * (self.context.amount_auth - provider_amt - GATEWAY_AMT)
        xmldict['institution_item_name'] = self.context.p_category
        xmldict['institution_name'] = INSTITUTION_NAME
        # Interswitch amount is not part of the xml data
        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
        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
        self.context.provider_amt = provider_amt
        self.context.gateway_amt = GATEWAY_AMT

        hashargs = (
            self.context.p_id +
            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
    product_id = PRODUCT_ID
    pay_item_id = '101'
    mac = '74424F1DFECD6058F153148255CDD55E16724B4F380ADB2C63C5D1D7A5675759010C8153DCB930AAF2D38903CBF7CE32B8A6BA2C16BBC46721DF2E3F3E4548E3'

    def update(self):
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        student = self.student

        # 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 2013 only.
        if self.context.p_category == '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 == '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 = ""
        # Provider data
        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

        if self.context.p_category == 'schoolfee':
            if student.faccode == 'FCETA':
                xmldict['institution_acct'] = '1190118227'
                xmldict['institution_bank_id'] = '123'
            else:
                xmldict['institution_bank_id'] = '7'
                xmldict['institution_acct'] = '1014847058'
            if student.current_mode == 'found':
                self.pay_item_id = '103'
            else:
                self.pay_item_id = '105'
            provider_amt = 1900.0
            joint_venture_amt = 1100.0
            aaue_share_amt = 1000.0
            student_union_due_amt = 1000.0
            student_welfare_assurance_amt = 500.0
            xmldict['provider_amt'] = 100 * provider_amt
            xmldict['joint_venture_amt'] = 100 * joint_venture_amt
            xmldict['aaue_share_amt'] = 100 * aaue_share_amt
            xmldict['student_union_due_amt'] = 100 * student_union_due_amt
            xmldict['student_welfare_assurance_amt'] = 100 * student_welfare_assurance_amt
            xmldict['institution_amt'] = 100 * (
                self.context.amount_auth
                - provider_amt
                - joint_venture_amt
                - aaue_share_amt
                - student_union_due_amt
                - student_welfare_assurance_amt
                - GATEWAY_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="51" acct_num="5060023759" />
<item_detail item_id="4" item_name="AAUE Share" item_amt="%(aaue_share_amt)d" bank_id="51" acct_num="5060020947" />
<item_detail item_id="5" item_name="Student Union" item_amt="%(student_union_due_amt)d" bank_id="123" acct_num="1006360118" />
<item_detail item_id="6" item_name="Student Welfare Assurance" item_amt="%(student_welfare_assurance_amt)d" bank_id="31" acct_num="1006407792" />
</item_details>
</payment_item_detail>""" % xmldict
        elif self.context.p_category == 'clearance':
            if student.current_mode == 'found':
                self.pay_item_id = '102'
            else:
                self.pay_item_id = '104'
            xmldict['institution_acct'] = '1014066976'
            xmldict['institution_bank_id'] = '117'
            provider_amt = 0.0
            gown_fee_amt = 2000.0
            aaue_fl_fee_amt = 800.0
            xmldict['gown_fee_amt'] = 100 * gown_fee_amt
            xmldict['aaue_fl_fee_amt'] = 100 * aaue_fl_fee_amt
            xmldict['institution_amt'] = 100 * (
                self.context.amount_auth
                - gown_fee_amt
                - aaue_fl_fee_amt
                - GATEWAY_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="51" acct_num="5060020947" />
<item_detail item_id="3" item_name="AAU File-Lapel Fee" item_amt="%(aaue_fl_fee_amt)d" bank_id="51" acct_num="4010660109" />
</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
        hashargs = (
            self.context.p_id +
            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)
    product_id = PRODUCT_ID
    gateway_host = HOST
    gateway_url = URL
    https = HTTPS

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