## $Id: browser.py 15346 2019-03-06 22:19:56Z 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
##
from datetime import datetime
import httplib
import urllib
import urllib2
import re
from xml.dom.minidom import parseString
import grok
from zope.component import getUtility
from zope.catalog.interfaces import ICatalog
from waeup.kofa.interfaces import IUniversity, CLEARED
from waeup.kofa.payments.interfaces import IPayer
from waeup.kofa.webservices import PaymentDataWebservice
from waeup.kofa.browser.layout import KofaPage, UtilityView
from waeup.kofa.students.viewlets import ApprovePaymentActionButton as APABStudent
from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant
from waeup.kofa.students.viewlets import PaymentReceiptActionButton as PRABStudent
from waeup.kofa.applicants.viewlets import PaymentReceiptActionButton as PRABApplicant
from kofacustom.nigeria.interswitch.browser import (
    InterswitchActionButtonStudent,
    InterswitchRequestWebserviceActionButtonStudent,
    InterswitchActionButtonApplicant,
    InterswitchRequestWebserviceActionButtonApplicant)
from kofacustom.nigeria.interfaces import MessageFactory as _
from kofacustom.nigeria.students.interfaces import INigeriaStudentOnlinePayment
from kofacustom.nigeria.applicants.interfaces import INigeriaApplicantOnlinePayment
from kofacustom.nigeria.etranzact.tests import HOST, TERMINAL_ID, HTTPS, GATEWAY_AMT
from kofacustom.nigeria.etranzact.helpers import query_payoutlet

grok.templatedir('browser_templates')

def payoutlet_module_activated(session, payment):
    if payment.r_company and payment.r_company != 'etranzact':
        return False
    try:
        return getattr(grok.getSite()['configuration'][str(session)],
            'etranzact_payoutlet_enabled', False)
    except KeyError:
        session = datetime.now().year
        try:
            return getattr(grok.getSite()['configuration'][str(session)],
                'etranzact_payoutlet_enabled', False)
        except KeyError:
            return False

class EtranzactEnterPinActionButtonApplicant(APABApplicant):
    grok.context(INigeriaApplicantOnlinePayment)
    grok.require('waeup.payApplicant')
    grok.order(3)
    icon = 'actionicon_pay.png'
    text = _('Pay via Etranzact PayOutlet')
    target = 'enterpin'

    @property
    def target_url(self):
        if not payoutlet_module_activated(
            self.context.__parent__.__parent__.year, self.context):
            return ''
        if self.context.p_state in ('paid', 'waived', 'scholarship'):
            return ''
        return self.view.url(self.view.context, self.target)

class EtranzactEnterPinActionButtonStudent(APABStudent):
    grok.context(INigeriaStudentOnlinePayment)
    grok.require('waeup.payStudent')
    grok.order(10)
    icon = 'actionicon_pay.png'
    text = _('Pay via Etranzact PayOutlet')
    target = 'enterpin'

    @property
    def target_url(self):
        if not payoutlet_module_activated(
            self.context.student.current_session, self.context):
            return ''
        if self.context.p_state in ('paid', 'waived', 'scholarship'):
            return ''
        return self.view.url(self.view.context, self.target)

class EtranzactEnterPinPageStudent(KofaPage):
    """Enter confirmation PIN and submit to `EtranzactQueryHistoryPageStudent`
    """
    grok.context(INigeriaStudentOnlinePayment)
    grok.name('enterpin')
    grok.template('enterpin')
    grok.require('waeup.payStudent')

    buttonname = _('Requery now')
    label = _('Requery Etranzact PayOutlet History')
    action = 'query_payoutlet_history'
    placeholder = _('Confirmation Number (PIN)')
    gateway_amt = GATEWAY_AMT

    def update(self):
        if not payoutlet_module_activated(
            self.context.student.current_session, self.context):
            self.flash(_('Forbidden'), type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        # Already now it becomes an Etranzact payment. We set the net amount
        # and add the gateway amount.
        if not self.context.r_company:
            self.context.net_amt = self.context.amount_auth
            self.context.amount_auth += self.gateway_amt
            self.context.gateway_amt = self.gateway_amt
            self.context.r_company = u'etranzact'
        return

class EtranzactEnterPinPageApplicant(KofaPage):
    """Enter confirmation PIN and submit to `EtranzactQueryHistoryPageApplicant`
    """
    grok.require('waeup.payApplicant')
    grok.context(INigeriaApplicantOnlinePayment)
    grok.name('enterpin')
    grok.template('enterpin')

    buttonname = _('Requery now')
    label = _('Requery Etranzact PayOutlet History')
    action = 'query_payoutlet_history'
    placeholder = _('Confirmation Number (PIN)')
    gateway_amt = GATEWAY_AMT

    def update(self):
        if not payoutlet_module_activated(
            self.context.__parent__.__parent__.year, self.context):
            self.flash(_('Forbidden'), type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        # Already now it becomes an Etranzact payment. We set the net amount
        # and add the gateway amount.
        if not self.context.r_company:
            self.context.net_amt = self.context.amount_auth
            self.context.amount_auth += self.gateway_amt
            self.context.gateway_amt = self.gateway_amt
            self.context.r_company = u'etranzact'
        return

class PayoutletPaymentReceiptActionButtonApplicant(PRABApplicant):

    grok.view(EtranzactEnterPinPageApplicant)

    @property
    def target_url(self):
        if not self.context.r_company:
            return ''
        return self.view.url(self.view.context, self.target)

class PayoutletPaymentReceiptActionButtonStudent(PRABStudent):

    grok.view(EtranzactEnterPinPageStudent)

    @property
    def target_url(self):
        if not self.context.r_company:
            return ''
        return self.view.url(self.view.context, self.target)

class EtranzactQueryHistoryPageStudent(UtilityView, grok.View):
    """ Query history of Etranzact payments
    """
    grok.context(INigeriaStudentOnlinePayment)
    grok.name('query_payoutlet_history')
    grok.require('waeup.payStudent')
    terminal_id = TERMINAL_ID
    host = HOST
    https = HTTPS

    def update(self, confirmation_number=None):
        if not payoutlet_module_activated(
            self.context.student.current_session, self.context):
            self.flash(_('Forbidden'), type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        if self.context.p_state == 'paid':
            self.flash(_('This ticket has already been paid.'))
            return
        student = self.context.student
        success, msg, log = query_payoutlet(
            self.host, self.terminal_id, confirmation_number,
            self.context, self.https)
        student.writeLogMessage(self, log)
        if not success:
            self.flash(msg, type="danger")
            return
        flashtype, msg, log = self.context.doAfterStudentPayment()
        if log is not None:
            student.writeLogMessage(self, log)
        self.flash(msg, type=flashtype)
        return

    def render(self):
        self.redirect(self.url(self.context, '@@index'))
        return

class EtranzactQueryHistoryPageApplicant(UtilityView, grok.View):
    """ Query history of Etranzact payments
    """
    grok.context(INigeriaApplicantOnlinePayment)
    grok.name('query_payoutlet_history')
    grok.require('waeup.payApplicant')
    terminal_id = TERMINAL_ID
    host = HOST
    https = HTTPS

    def update(self, confirmation_number=None):
        if not payoutlet_module_activated(
            self.context.__parent__.__parent__.year, self.context):
            self.flash(_('Forbidden'), type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        if self.context.p_state == 'paid':
            self.flash(_('This ticket has already been paid.'))
            return
        applicant = self.context.__parent__
        success, msg, log = query_payoutlet(
            self.host, self.terminal_id, confirmation_number,
            self.context, self.https)
        applicant.writeLogMessage(self, log)
        if not success:
            self.flash(msg)
            return
        flashtype, msg, log = self.context.doAfterApplicantPayment()
        if log is not None:
            applicant.writeLogMessage(self, log)
        self.flash(msg, type=flashtype)
        return

    def render(self):
        self.redirect(self.url(self.context, '@@index'))
        return