## $Id: browser.py 17963 2024-11-26 02:34:19Z 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
##

from kofacustom.nigeria.remita.studentsbrowser import (
    module_activated,
    RemitaRequestPaymentStatusPageStudent,
    RemitaVerifyPaymentStatusPageStudent,
    RemitaPageStudent)
from kofacustom.nigeria.remita.applicantsbrowser import (
    RemitaRequestPaymentStatusPageApplicant,
    RemitaVerifyPaymentStatusPageApplicant,
    RemitaPageApplicant)

# Temporarily we can use the test portal like in kofacustom.nigeria
MERCHANTID = '2067163382'
HOST = 'login.remita.net'
HTTPS = True
API_KEY = '309418'
SERVICETYPEID = '4430731'

class CustomRemitaRequestPaymentStatusPageStudent(
    RemitaRequestPaymentStatusPageStudent):
    """ Request webservice view for the Remita gateway.
    """

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

    def render(self):
        if self.context.p_category == 'plag_test'\
            and self.context.p_state  == 'paid':
            self.redirect(self.url(self.context, 'plagtestinfo'))
        else:
            self.redirect(self.url(self.context, '@@index'))
        return

class CustomRemitaVerifyPaymentStatusPageStudent(
    RemitaVerifyPaymentStatusPageStudent):
    """ Request webservice view for the Remita gateway.
    """

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

    def update(self):
        super(CustomRemitaVerifyPaymentStatusPageStudent, self).update()
        # Repair: Uniben allows also previous session students to book a bed
        if self.context.p_category == 'bed_allocation' and self.context.p_state == 'paid' and self.context.ac == None:
            flashtype, msg, log = self.context.doAfterStudentPayment()
            if log is not None:
                self.context.student.writeLogMessage(self, log)
            self.flash(msg, type=flashtype)
        return

class CustomRemitaPageStudent(RemitaPageStudent):
    """ View which sends a POST request to the Remita payment gateway.
    """

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

    init_url = '/remita/ecomm/split/init.reg'

    @property
    def serviceTypeId(self):
        student = self.context.student
        if self.context.p_category == 'schoolfee':
            if student.current_mode.startswith('dp_'):
                return '2067090482'
            if student.current_mode in ('pg_ft', 'pgd_ft'):
                return '2067090691'
            if student.current_mode in ('pg_pt', 'pgd_pt', 'special_pg_pt'):
                return '2067091011'
            if student.current_mode == 'ug_sw':
                return '2066967204'
            if student.current_mode.endswith('ug_ft'):
                return '2067091395'
            if student.current_mode == 'ug_pt':
                return '2067091679'
            if student.current_mode == 'special_ft':
                return '2750318564' # Module 2
            if student.is_jupeb:
                return '1946888188'
            if student.current_mode == 'cdl':
                return '9541632464'
        if self.context.p_category == 'bed_allocation':
            if student.is_postgrad:
                return '2067086599'
            return '2067089893'
        if self.context.p_category == 'hostel_maintenance':
            if student.is_postgrad:
                return '2067089226'
            return '2066966390'
        if self.context.p_category == 'clearance':
            if student.current_mode.startswith('dp_'):
                return '2067080314'
            if student.is_jupeb:
                return '1947201668'
            if student.is_postgrad:
                return '2067086157'
            if student.current_mode == 'ug_pt':
                return '2072765946'
            if student.current_mode == 'cdl':
                return '8242101527'
            return '2067089446'
        if self.context.p_category == 'jupeb':
            return '1947198586'
        if self.context.p_category == 'plag_test':
            return '2051987298'
        #if self.context.p_category == 'pharmd_1':
        #    return '2750314820' # Clerkship
        if self.context.p_category == 'pharmd_2': 
            return '2750174184' # Module 1
        if self.context.p_category == 'medical_quest':
            return '512570052'
        if self.context.p_category == 'flc_modules':
            return '757257557'
        return ''

    def dynamic_provider_amt(self, student):
        if student.entry_session >= 2024:
            return 5000.0
        return 2000.0

    @property
    def lineitems(self):
        inst_bankcode = "000"
        inst_acct = "0040217361011"
        provider_amt = 0.0
        student_union = 0.0
        jupeb_amt = 0.0
        reduced_inst_amt = 0.0
        lab_amt = 0.0
        if self.context.p_category in ('schoolfee', 'schoolfee_1') and \
            not self.context.p_item == 'Balance':
            provider_amt = self.dynamic_provider_amt(self.context.student)
            if self.context.student.current_mode == 'ug_ft':
                student_union = 2500.0
        elif self.context.p_category == 'clearance':
            provider_amt = 5000.0
        elif self.context.p_category == 'bed_allocation':
            provider_amt = 1000.0

        inst_amt = self.context.amount_auth - provider_amt - student_union

        lineitems = (
                      {"lineItemsId":"itemid1","beneficiaryName":"Uniben",
                      "beneficiaryAccount":inst_acct,"bankCode":inst_bankcode,
                      "beneficiaryAmount":inst_amt,"deductFeeFrom":"1"},
                    )
        if provider_amt:
            lineitems += ({"lineItemsId":"itemid2","beneficiaryName":"WAeAC",
                          "beneficiaryAccount":"1014261520","bankCode":"057",
                          "beneficiaryAmount":provider_amt,"deductFeeFrom":"0"},)
        if student_union:
            lineitems += ({"lineItemsId":"itemid3","beneficiaryName":"Student Union",
                          "beneficiaryAccount":"0025636203","bankCode":"039",
                          "beneficiaryAmount":student_union,"deductFeeFrom":"0"},)

        # We overwrite linetems in case of postgrad student school fee payments
        if self.context.student.is_postgrad and self.context.p_category == 'schoolfee':
            microfinance_amt = 0.1 * inst_amt
            inst_amt -= microfinance_amt
            lineitems = (
                          {"lineItemsId":"itemid1","beneficiaryName":"Uniben",
                          "beneficiaryAccount":inst_acct,"bankCode":inst_bankcode,
                          "beneficiaryAmount":inst_amt,"deductFeeFrom":"1"},
                        )
            lineitems += ({"lineItemsId":"itemid2","beneficiaryName":"SPGS Scheme",
                          "beneficiaryAccount":"0025636203","bankCode":"039",
                          "beneficiaryAmount":microfinance_amt,"deductFeeFrom":"0"},
                         {"lineItemsId":"itemid3","beneficiaryName":"WAeAC",
                          "beneficiaryAccount":"1014261520","bankCode":"057",
                          "beneficiaryAmount":provider_amt,"deductFeeFrom":"0"},)

        ## Disabled on 24/02/21
        ## Reenabled on 19/09/23 (ticket #1327)
        ## We overwrite linetems in case of JUPEB students
        if self.context.student.is_jupeb:
            if self.context.p_category == 'clearance':
                provider_amt = self.dynamic_provider_amt(self.context.student)
                reduced_inst_amt = 0.7 * inst_amt
                jupeb_amt = 0.3 * inst_amt
            elif self.context.p_category == 'schoolfee' and \
                not self.context.p_item == 'Balance':
                provider_amt = self.dynamic_provider_amt(self.context.student)
                #if self.context.student.depcode in ('AGR_JUP','EDU_JUP','ENG_JUP',
                #                               'LSC_JUP','MED_JUP','PSC_JUP'):
                #    lab_amt = 10000
                reduced_inst_amt = 0.7 * (inst_amt - lab_amt)
                jupeb_amt = 0.3 * (inst_amt - lab_amt) + lab_amt
            lineitems = (
                          {"lineItemsId":"itemid1","beneficiaryName":"Uniben",
                          "beneficiaryAccount":inst_acct,"bankCode":inst_bankcode,
                          "beneficiaryAmount":reduced_inst_amt,"deductFeeFrom":"1"},
                        )
            lineitems += ({"lineItemsId":"itemid2","beneficiaryName":"JUPEB",
                          "beneficiaryAccount":"0025636203","bankCode":"039",
                          "beneficiaryAmount":jupeb_amt,"deductFeeFrom":"0"},)
            if provider_amt:
                lineitems += ({"lineItemsId":"itemid3","beneficiaryName":"WAeAC",
                              "beneficiaryAccount":"1014261520","bankCode":"057",
                              "beneficiaryAmount":provider_amt,"deductFeeFrom":"0"},)
            if student_union:
                lineitems += ({"lineItemsId":"itemid4","beneficiaryName":"Student Union",
                              "beneficiaryAccount":"0025636203","bankCode":"039",
                              "beneficiaryAmount":student_union,"deductFeeFrom":"0"},)


        # Split pharmd school fee payments into 3 parts if students decide to pay the
        # entire school fee at once. If the amount is less than N240000, the student
        # has obviously paid the first installment of N80000 (pharmd_1)
        # (disabled on 16/03/18)
        #if self.context.p_category == 'schoolfee' \
        #    and self.context.student.current_mode == 'special_ft' \
        #    and self.context.amount_auth >= 240000:
        #    pcn_amt = 80000.0
        #    inst_amt -= pcn_amt
        #    lineitems = (
        #                  {"lineItemsId":"itemid1","beneficiaryName":"Uniben",
        #                  "beneficiaryAccount":inst_acct,"bankCode":inst_bankcode,
        #                  "beneficiaryAmount":inst_amt,"deductFeeFrom":"1"},
        #                  {"lineItemsId":"itemid2","beneficiaryName":"PCN",
        #                  "beneficiaryAccount":"0020197061015","bankCode":inst_bankcode,
        #                  "beneficiaryAmount":pcn_amt,"deductFeeFrom":"0"},
        #                  {"lineItemsId":"itemid3","beneficiaryName":"WAeAC",
        #                  "beneficiaryAccount":"1014261520","bankCode":"057",
        #                  "beneficiaryAmount":provider_amt,"deductFeeFrom":"0"}
        #                )
        self.context.provider_amt = provider_amt
        self.context.net_amt = inst_amt
        return lineitems

    def update(self):
        if not module_activated(
            self.context.student.current_session, self.context):
            return
        self.orderId = self.context.p_id
        self.amount = str(self.context.amount_auth)
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        self.context.r_company = u'remita'
        return

class CustomRemitaRequestPaymentStatusPageApplicant(
    RemitaRequestPaymentStatusPageApplicant):
    """ Request webservice view for the Remita gateway.
    """

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


class CustomRemitaVerifyPaymentStatusPageApplicant(
    RemitaVerifyPaymentStatusPageApplicant):
    """ Request webservice view for the Remita gateway.
    """

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

class CustomRemitaPageApplicant(RemitaPageApplicant):
    """ View which sends a POST request to the Remita payment gateway.
    """

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

    init_url = '/remita/ecomm/split/init.reg'

    @property
    def serviceTypeId(self):
        applicant = self.context.__parent__
        if applicant.__parent__.prefix.startswith('dp'):
            return '2066963437'
        if applicant.__parent__.prefix in ('spft', ):
            return '2067086388'
        if applicant.__parent__.prefix == 'pre':
            return '1946882248'
        if applicant.__parent__.prefix in ('pude','putme','cbt',
                                           'ab','ak','akj','ase'):
            return '2066965951'
        if applicant.__parent__.prefix in ('tscs', 'tscf'):
            return '698984179'
        if applicant.__parent__.prefix == 'flc':
            return '757257557'     
        if applicant.__parent__.prefix in ('pt', 'ptext'):
            return '2072815846'
        if applicant.__parent__.prefix.startswith('pg'):
            return '2067086388'   
        if applicant.__parent__.prefix in ('sandwich'):
            return '2072760654'
        if applicant.__parent__.prefix == 'cdl':
            return '8197875656'
        return ''

    @property
    def demo_lineitems(self):
        lineitems = (
                      {"lineItemsId":"itemid1","beneficiaryName":"Klaus Mueller",
                      "beneficiaryAccount":"6020067886","bankCode":"011",
                      "beneficiaryAmount":self.context.amount_auth/2,"deductFeeFrom":"1"},
                      {"lineItemsId":"itemid2","beneficiaryName":"Werner Rumm",
                      "beneficiaryAccount":"0360883515","bankCode":"050",
                      "beneficiaryAmount":self.context.amount_auth/2,"deductFeeFrom":"0"}
                    )
        return lineitems

    @property
    def lineitems(self):
        applicant = self.context.__parent__
        if applicant.applicant_id.startswith('dp'):
            inst_acct = "0040217361038"
        else:
            inst_acct = "0040217361011"
        provider_amt = 1000.0
        if applicant.__parent__.prefix == 'pre':
            provider_amt = 2000.0
        if applicant.__parent__.prefix.startswith('tsc'):
            provider_amt = 2500.0
            if applicant.order == 'c':
                provider_amt = 2500.0
        if applicant.__parent__.prefix.startswith('ase'):
            provider_amt = 1000.0
        if applicant.__parent__.prefix == 'pude':
            provider_amt = 2000.0
        if applicant.__parent__.prefix == 'cdl':
            provider_amt = 0.0
        if applicant.__parent__.prefix == 'cbt':
            provider_amt = 300.0
        if applicant.__parent__.prefix in ('pt', 'ptext', 'sandwich'):
            provider_amt = 2000.0
        if applicant.__parent__.prefix.startswith('pg'):
            provider_amt = 2000.0
        if self.context.p_item == 'Balance':
            provider_amt = 0.0
        inst_amt = self.context.amount_auth - provider_amt
        lineitems = (
                      {"lineItemsId":"itemid1","beneficiaryName":"Uniben",
                      "beneficiaryAccount":inst_acct,"bankCode":"000",
                      "beneficiaryAmount":inst_amt,"deductFeeFrom":"1"},
                    )
        if provider_amt:
            lineitems += ({"lineItemsId":"itemid2","beneficiaryName":"WAeAC",
                          "beneficiaryAccount":"1014261520","bankCode":"057",
                          "beneficiaryAmount":provider_amt,"deductFeeFrom":"0"},)
        self.context.provider_amt = provider_amt
        self.context.net_amt = inst_amt
        return lineitems

    def update(self):
        if not module_activated(
            self.context.__parent__.__parent__.year, self.context):
            return
        self.orderId = self.context.p_id
        self.amount = str(self.context.amount_auth)
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        self.context.r_company = u'remita'
        return