## $Id: browser.py 17792 2024-05-16 11:15:56Z 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 csv
from kofacustom.nigeria.etranzact.applicantsbrowser import (
    EtranzactPageApplicant, EtranzactReceiveResponseApplicant,
    EtranzactRequestPaymentStatusPageApplicant)
from kofacustom.nigeria.etranzact.studentsbrowser import (
    EtranzactPageStudent, EtranzactReceiveResponseStudent,
    EtranzactRequestPaymentStatusPageStudent, webconnect_module_activated)
from kofacustom.nigeria.etranzact.payoutletbrowser import (
    EtranzactEnterPinPageStudent, EtranzactEnterPinPageApplicant,
    EtranzactQueryHistoryPageStudent, EtranzactQueryHistoryPageApplicant,
    payoutlet_module_activated)
from kofacustom.nigeria.etranzact.payoutletwebservice  import NigeriaPaymentDataWebservice
from kofacustom.nigeria.etranzact.credobrowser  import (
    CredoPageStudent, CredoPageApplicant,
    CredoVerifyPaymentStatusPageStudent, CredoVerifyPaymentStatusPageApplicant)

# Temporarily we can use the test portal like in kofacustom.nigeria

from kofacustom.nigeria.etranzact.tests import (
    HOST, HTTPS)

HOST = 'www.etranzactng.net'
HTTPS = True
GATEWAY_AMT = 0.0 # is beeing added by Etranzact
LOGO_URL = 'https://iuokada.waeup.org/static_custom/iou_logo.png'

WEBCONNECT_STUD_PARAMS = {
    'schoolfee': ('7007139588','QIgl9a35R30A1RGK'),
    'schoolfee40': ('7007139589','3coU0eolOEbEUeO3'),
    'secondinstal': ('7007139590','zGpEjy6CdPxCHqen'),
    'transcript_local': ('7007139592','ndgxUtzJgHRkvXlB'),
    'transcript': ('7007139592','ndgxUtzJgHRkvXlB'),
    'transcript_overseas': ('7007139592','ndgxUtzJgHRkvXlB'),
    'registration': ('7007139599','KGHjZ2hRbaDJGBX8'),
    'book': ('7007139600','rrKE2Ua7eu8TF0Is'),
    'parentsconsult': ('7007139598','HsqjOlAB5xfQNDyo'),
    'sundry': ('7007139591','0XkOFShPnWn8tY5O'),
    'health_insurance':('7007140478', 'Be24m7O7iODZXcYF'),
    }

def determine_appl_params(payment):
    terminal_id = ''
    secret_key = ''
    if payment.__parent__.__parent__.prefix.startswith('pg'):
        terminal_id = '7007139606'
        secret_key = 'E64s3IN9cXRJeltY'
    else:
        terminal_id = '7007139604'
        secret_key = 'vlEEJxvJBjC468g1'
    return terminal_id, secret_key

def determine_stud_params(payment):
    terminal_id = ''
    secret_key = ''
    for key in WEBCONNECT_STUD_PARAMS.keys():
        if payment.p_category == key:
            terminal_id = WEBCONNECT_STUD_PARAMS[key][0]
            secret_key = WEBCONNECT_STUD_PARAMS[key][1]
    if not terminal_id:
        terminal_id = WEBCONNECT_STUD_PARAMS['sundry'][0]
        secret_key = WEBCONNECT_STUD_PARAMS['sundry'][1]
    return terminal_id, secret_key

class CustomEtranzactPageApplicant(EtranzactPageApplicant):

    host = HOST
    https = HTTPS
    logo_url = LOGO_URL
    gateway_amt = GATEWAY_AMT

    @property
    def terminal_id(self):
        return determine_appl_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_appl_params(self.context)[1]

    def update(self):
        if not webconnect_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'
        self.amount = "%.1f" % self.context.amount_auth
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        return

class CustomEtranzactReceiveResponseApplicant(EtranzactReceiveResponseApplicant):

    @property
    def terminal_id(self):
        return determine_appl_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_appl_params(self.context)[1]

class CustomEtranzactRequestPaymentStatusPageApplicant(
    EtranzactRequestPaymentStatusPageApplicant):

    host = HOST
    https = HTTPS
    logo_url = LOGO_URL

    @property
    def terminal_id(self):
        return determine_appl_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_appl_params(self.context)[1]

class CustomEtranzactPageStudent(EtranzactPageStudent):

    host = HOST
    https = HTTPS
    logo_url = LOGO_URL
    gateway_amt = GATEWAY_AMT

    @property
    def terminal_id(self):
        return determine_stud_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_stud_params(self.context)[1]

    def update(self):
        if not webconnect_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'
        self.amount = "%.1f" % self.context.amount_auth
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        return

class CustomEtranzactReceiveResponseStudent(EtranzactReceiveResponseStudent):

    @property
    def terminal_id(self):
        return determine_stud_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_stud_params(self.context)[1]

class CustomEtranzactRequestPaymentStatusPageStudent(
    EtranzactRequestPaymentStatusPageStudent):

    host = HOST
    https = HTTPS
    logo_url = LOGO_URL

    @property
    def terminal_id(self):
        return determine_stud_params(self.context)[0]

    @property
    def secret_key(self):
        return determine_stud_params(self.context)[1]





# Payoutlet customizations

class CustomEtranzactEnterPinPageStudent(EtranzactEnterPinPageStudent):
    """Enter confirmation PIN and submit to `EtranzactQueryHistoryPageStudent`
    """
    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 CustomEtranzactEnterPinPageApplicant(EtranzactEnterPinPageApplicant):
    """Enter confirmation PIN and submit to `EtranzactQueryHistoryPageApplicant`
    """
    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 CustomEtranzactQueryHistoryPageStudent(EtranzactQueryHistoryPageStudent):
    """ Query history of Etranzact payments
    """
    terminal_id = '7007134590'
    host = HOST
    https = HTTPS

class CustomEtranzactQueryHistoryPageApplicant(EtranzactQueryHistoryPageApplicant):
    """ Query history of Etranzact payments
    """
    terminal_id = '7009158847'
    host = HOST
    https = HTTPS

class CustomPaymentDataWebservice(NigeriaPaymentDataWebservice):
    """A simple webservice to publish payment and payer details on request from
    accepted IP addresses without authentication.
    """
    #ACCEPTED_IP = ('195.219.3.181', '195.219.3.184')
    ACCEPTED_IP = None

    CATEGORY_MAPPING = {
        'IUO_SCHOOL_FEES_FULL_PAYMENT': ('schoolfee',),
        'IUO_SCHOOL_FEES_FIRST_INSTALLMENT': ('schoolfee40',),
        'IUO_SCHOOL_FEES_OTHER_INSTALLMENT': ('secondinstal',),

        'IUO_SUNDRY_FEES': ('combi',),

        'IUO_MATRICULATION_FEE': ('matric',),
        'IUO_LATE_REGISTRATION_FEE': ('late_registration',),
        'IUO_WAEC/NECO_VERIFICATION_FEE': ('waecneco',),
        'IUO_JAMB_VERIFICATION': ('jambver',),
        'IUO_CONVOCATION_FEE': ('conv',),
        'IUO_ALUMNI_FEE': ('alumni',),
        'IUO_SCIENCE_BENCE_FEE': ('science',),
        'IUO_LETTER_OF_IDENTIFICATION_FEE': ('lo_ident',),
        'IUO_CHANGE_OF_COURSE_FEE': ('change_course',),
        'IUO_IUITS_FEE': ('iuits',),
        'IUO_FINES_FEE': ('fine',),
        'IUO_PHARMACY_LAB_SUPPORT_FEE': ('pharmlab',),
        'IUO_MAKEUP_FEE': ('resit1', 'resit2', 'resit3', 'resit4',
                           'resit5', 'resit6', 'resit7', 'resit8',
                           'resit9',),
        'IUO_CLINICAL_FEE_MEDICAL_STUDENTS': ('clinical',),
        'IUO_TRANSCRIPT_FEE_INTERNATIONAL': ('transcript_overseas',),
        'IUO_TRANCRIPT_FEE_LOCAL': ('transcript_local', 'transcript'),
        'IUO_ACCEPTANCE_FEE': ('clearance',),
        'IUO_CLEARANCE_FEE': ('grad_clearance',),
        'IUO_ID_CARD_FEE': ('id_card',),
        'IUO_REGISTRATION_FEE': ('registration',),
        'IUO_DEVELOPMENT_FEE': ('develop',),
        'IUO_MUNICIPAL_FEE': ('municipal_fresh','municipal_returning'),
        'IUO_BOOK_DEPOSIT': ('book',),
        'IUO_PARENTS_CONSULTATIVE_FORUM_FEE': ('parentsconsult',),

        'IUO_APPLICATION_FORM_UNDERGRADUATE': ('application',),
        'IUO_APPLICATION_FORM_POSTGRADUATE': ('application',),

        'IUO_MAKE_UP_REGISTRATION_FEE': ('makeup_admin',),
        'IUO_STUDENT_HEALTH_INSURANCE': ('health_insurance',),

        'IUO_COMBI_PAYMENT': ('combi',),

        'JUPEB_FORM_FEE': ('jupeb_form',),
        'JUPEB_ACCEPTANCE_FEE': ('jupeb_acc',),
        'JUPEB_SCIENCE_COURSE': ('jupeb_sci',),
        'JUPEB_ARTS_COURSE': ('jupeb_arts',),
        'JUPEB_HOSTEL_FEE': ('jupeb_hostel',),
        'JUPEB_REGISTRATION_FEE': ('jupeb_reg',),
         }

# Credo customizations

SECRET_API_KEY = "1PRI1279pI28Y9kCqZs9PlvM6ZjjZx4dXBdV8a"
API_PUBLIC_KEY = "1PUB1279tj5IbnXbUFd78YT3ew8XHeyLJP3tEm"
CREDO_HOST = "api.credocentral.com"

scodes_path = os.path.join(
    os.path.dirname(__file__), 'servicecodes.csv')
reader = csv.DictReader(open(scodes_path, 'rb'))
SCODES = {line['p_category']:line['serviceCode'] for line in reader}

class CustomCredoPageStudent(CredoPageStudent):

    host = CREDO_HOST
    api_public_key = API_PUBLIC_KEY

    @property
    def serviceCode(self):
        return SCODES.get(self.context.p_category, None)

class CustomCredoPageApplicant(CredoPageApplicant):

    host = CREDO_HOST
    api_public_key = API_PUBLIC_KEY

    @property
    def serviceCode(self):
        return SCODES.get(self.context.p_category, None)

class CustomCredoVerifyPaymentStatusPageStudent(CredoVerifyPaymentStatusPageStudent):

    host = CREDO_HOST
    secret_api_key = SECRET_API_KEY

class CustomCredoVerifyPaymentStatusPageApplicant(CredoVerifyPaymentStatusPageApplicant):

    host = CREDO_HOST
    secret_api_key = SECRET_API_KEY