source: main/waeup.aaue/trunk/src/waeup/aaue/interswitch/browser.py @ 17469

Last change on this file since 17469 was 17469, checked in by Henrik Bettermann, 16 months ago

Configure application payments.

  • Property svn:executable set to *
File size: 20.4 KB
Line 
1    # -*- coding: utf-8 -*-
2## $Id: browser.py 17429 2023-06-05 04:34:30Z henrik $
3##
4## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
5## This program is free software; you can redistribute it and/or modify
6## it under the terms of the GNU General Public License as published by
7## the Free Software Foundation; either version 2 of the License, or
8## (at your option) any later version.
9##
10## This program is distributed in the hope that it will be useful,
11## but WITHOUT ANY WARRANTY; without even the implied warranty ofself.context.amount_auth
12## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13## GNU General Public License for more details.
14##
15## You should have received a copy of the GNU General Public License
16## along with this program; if not, write to the Free Software
17## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18##
19import httplib
20import hashlib
21import grok
22import os
23import csv
24from xml.dom import minidom
25from zope.interface import Interface
26from zope.component import queryAdapter
27from waeup.kofa.interfaces import CLEARED
28from kofacustom.nigeria.interswitch.browser import (
29    InterswitchPaymentRequestWebservicePageStudent,
30    InterswitchPaymentRequestWebservicePageApplicant,
31    InterswitchPaymentVerifyWebservicePageApplicant,
32    InterswitchPaymentVerifyWebservicePageStudent,
33    InterswitchPageStudent, InterswitchPageApplicant,
34    module_activated,
35    )
36from waeup.aaue.students.interfaces import ICustomStudentOnlinePayment
37from waeup.aaue.applicants.interfaces import ICustomApplicantOnlinePayment
38from waeup.aaue.students.utils import SFEECHANGES
39from waeup.aaue.interfaces import MessageFactory as _
40
41PRODUCT_ID = '5845'
42SITE_NAME = 'aaue.waeup.org'
43PROVIDER_ACCT = '0200244434'
44PROVIDER_BANK_ID = '11'
45PROVIDER_ITEM_NAME = 'WAeAC Portal Fee'
46INSTITUTION_NAME = 'AAU Ekpoma'
47CURRENCY = '566'
48GATEWAY_AMT = 200.0
49POST_ACTION = 'https://webpay.interswitchng.com/paydirect/pay'
50
51HOST = 'webpay.interswitchng.com'
52URL = '/paydirect/api/v1/gettransaction.json'
53HTTPS = True
54MAC = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
55
56httplib.HTTPSConnection.debuglevel = 0
57
58BANK_ACCOUNTS = {
59    'edohis':   ('1222577132', '117'),
60    'union':    ('1019763348', '7'),
61    'sport':    ('1021941220', '7'),
62    'access':   ('1012688013', '123'),
63    'notebook': ('4011210501', '51'),
64    'library':  ('2000122995', '8'),
65    'fac1':     ('1022438743', '7'),
66    'fac2':     ('2000249757', '8'),
67    'fac3':     ('1012678566', '123'),
68    'matricgown': ('2000249757', '8'),
69    'lapel':      ('2000249757', '8'),
70
71    'acceptance': ('2000249757', '8'),
72
73    'hostel_maintenance': ('1006406795', '123'),
74    'bed_allocation':     ('1006406795', '123'),
75    'late_registration':  ('5210006575', '51'),
76    'ent_combined':       ('6220029828', '51'),
77    'ent_registration_0': ('6220029828', '51'),
78    'ent_registration_1': ('6220029828', '51'),
79    'ent_registration_2': ('6220029828', '51'),
80    'ent_text_book_0':    ('6220029828', '51'),
81    'ent_text_book_1':    ('6220029828', '51'),
82    'ent_text_book_2':    ('6220029828', '51'),
83    'gst_registration_1': ('1010893123', '117'),
84    'gst_registration_2': ('1010893123', '117'),
85    'gst_text_book_0':    ('1010893123', '117'),
86    'gst_text_book_1':    ('1010893123', '117'),
87    'gst_text_book_2':    ('1010893123', '117'),
88    'gst_text_book_3':    ('1010893123', '117'),
89
90    'postgrad': ('1010827641', '117'),
91    }
92
93FEE_NAMES = {
94    'edohis':     'Edo State Health Insurance Scheme',
95    'union':      'Student Union Dues',
96    'sport':      'Sport Development Fee',
97    'access':     'Access Card Fee',
98    'notebook':   'Branded Notebook',
99    'library':    'Library Development Fee',
100    'tuition':    'Tuition',
101    'acceptance': 'Acceptance Fee',
102    'matricgown': 'Matriculation Gown Fee',
103    'lapel':      'File/Lapel Fee',
104    'lmsplus':    'LMS Plus Fee',
105    'nuga':       'NUGA Fee',
106    }
107
108
109SCHOOLFEES = dict()
110
111for year in SFEECHANGES:
112    schoolfees_path = os.path.join(
113        os.path.dirname(__file__), '../students/schoolfees_%s.csv' %year)
114    reader = csv.DictReader(open(schoolfees_path, 'rb'))
115    SCHOOLFEES[year] = {item['code']:item for item in reader}
116
117acceptancefees_path = os.path.join(
118    os.path.dirname(__file__), '../students/acceptancefees.csv')
119reader = csv.DictReader(open(acceptancefees_path, 'rb'))
120ACCEPTANCEFEES = {item['code']:item for item in reader}
121
122class CustomInterswitchPageApplicant(InterswitchPageApplicant):
123    """ View which sends a POST request to the Interswitch
124    CollegePAY payment gateway.
125
126    So far only PT application has been configured.
127    """
128    grok.context(ICustomApplicantOnlinePayment)
129    action = POST_ACTION
130    site_name = SITE_NAME
131    currency = CURRENCY
132    provider_bank_id = PROVIDER_BANK_ID
133    provider_acct = PROVIDER_ACCT
134    pay_item_id = '101'
135    product_id = PRODUCT_ID
136
137    def update(self):
138        if not module_activated(
139            self.context.__parent__.__parent__.year, self.context):
140            self.flash(_('Forbidden'), type='danger')
141            self.redirect(self.url(self.context, '@@index'))
142            return
143        error = self.init_update()
144        if error:
145            self.flash(error, type='danger')
146            self.redirect(self.url(self.context, '@@index'))
147            return
148        # Already now it becomes an Interswitch payment. We set the net amount
149        # and add the gateway amount.
150        if not self.context.r_company:
151            self.context.net_amt = self.context.amount_auth
152            self.context.amount_auth += GATEWAY_AMT
153            self.context.gateway_amt = GATEWAY_AMT
154            self.context.r_company = u'interswitch'
155        xmldict = {}
156        provider_amt = 3000.0
157        if self.applicant.__parent__.code in ('ver2019', 'send2019'):
158            provider_amt = 0.0
159        xmldict['institution_acct'] = '1012332141'
160        xmldict['institution_bank_id'] = '123'
161        if self.applicant.applicant_id.startswith('dsh'):
162            xmldict['institution_acct'] = '1014847058'
163            xmldict['institution_bank_id'] = '7'
164        if self.applicant.applicant_id.startswith('ijmbe'):
165            xmldict['institution_acct'] = '1012278272'
166            xmldict['institution_bank_id'] = '123'
167        xmldict['detail_ref'] = self.context.p_id
168        xmldict['provider_amt'] = 100 * provider_amt
169        xmldict['provider_acct'] = PROVIDER_ACCT
170        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
171        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
172        xmldict['institution_item_name'] = self.context.category
173        xmldict['institution_name'] = INSTITUTION_NAME
174        xmldict['institution_amt'] = 100 * self.context.net_amt
175        if not self.context.provider_amt:
176            self.context.provider_amt = provider_amt
177            self.context.amount_auth += provider_amt
178        if provider_amt:
179            xmltext = """<payment_item_detail>
180<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
181<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" />
182<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" />
183</item_details>
184</payment_item_detail>""" % xmldict
185        else:
186            xmltext = """<payment_item_detail>
187<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
188<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" />
189</item_details>
190</payment_item_detail>""" % xmldict
191        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
192        xmlitems = ''
193        xmldoc = minidom.parseString(xmltext)
194        itemlist = xmldoc.getElementsByTagName('item_detail')
195        for s in itemlist:
196            xmlitems += "%s (%s %s, %s (%s)),  " % (
197                s.attributes['item_name'].value,
198                u'\u20a6',
199                int(s.attributes['item_amt'].value)/100,
200                s.attributes['acct_num'].value,
201                s.attributes['bank_id'].value,
202                )
203        self.context.p_split_data = xmlitems
204        self.amount_auth = int(100 * self.context.amount_auth)
205        hashargs = (
206            self.context.p_id +
207            PRODUCT_ID +
208            self.pay_item_id +
209            str(int(self.amount_auth)) +
210            self.site_redirect_url +
211            MAC)
212        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
213        return
214
215class CustomInterswitchPageStudent(InterswitchPageStudent):
216    """ View which sends a POST request to the Interswitch
217    CollegePAY payment gateway.
218    """
219    grok.context(ICustomStudentOnlinePayment)
220    action = POST_ACTION
221    site_name = SITE_NAME
222    currency = CURRENCY
223    pay_item_id = '101'
224    product_id = PRODUCT_ID
225
226    def update(self):
227        if not module_activated(
228            self.context.student.current_session, self.context):
229            self.flash(_('Forbidden'), type='danger')
230            self.redirect(self.url(self.context, '@@index'))
231            return
232        error = self.init_update()
233        if error:
234            self.flash(error, type='danger')
235            self.redirect(self.url(self.context, '@@index'))
236            return
237        student = self.student
238        category = self.context.p_category
239        # To guarantee that cleared students pay both acceptance fee
240        # and school fees, the page can only be accessed
241        # for school fee payments if acceptance/clearance fee has
242        # been successfully queried/paid beforehand. This
243        # requirement applies to students in state 'cleared' and
244        # entry_session greater than 2012 only.
245        if self.context.p_category.startswith('schoolfee') and \
246            student.state == CLEARED and \
247            student.entry_session > 2012:
248            acceptance_fee_paid = False
249            for ticket in student['payments'].values():
250                if ticket.p_state == 'paid' and \
251                    ticket.p_category.startswith('clearance'):
252                    acceptance_fee_paid = True
253                    break
254            if not acceptance_fee_paid:
255                self.flash(
256                    _('Please pay acceptance fee first.'), type="danger")
257                self.redirect(self.url(self.context, '@@index'))
258                return
259        # Already now it becomes an Interswitch payment. We set the net amount
260        # and add the gateway amount.
261        if not self.context.r_company:
262            self.context.net_amt = self.context.amount_auth
263            self.context.amount_auth += GATEWAY_AMT
264            self.context.gateway_amt = GATEWAY_AMT
265            self.context.r_company = u'interswitch'
266        xmldict = self.xmldict
267        # Provider data
268        xmldict['detail_ref'] = self.context.p_id
269        xmldict['provider_acct'] = PROVIDER_ACCT
270        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
271        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
272        # Institution data
273        xmldict['institution_acct'] = '00000000'
274        xmldict['institution_bank_id'] = '00'
275        provider_amt = 0.0
276        if category.startswith('clearance'):
277            provider_amt = 1500.0
278        elif category.startswith('hostel_maintenance'):
279            provider_amt = 1000.0
280        elif category in ('schoolfee', 'schoolfee_1', 'schoolfee_incl'):
281            provider_amt = 2500.0
282        xmldict['provider_amt'] = 100 * provider_amt
283        xmldict['institution_item_name'] = self.context.category
284        xmldict['institution_name'] = INSTITUTION_NAME
285        xmldict['institution_amt'] = 100 * self.context.net_amt
286        if not self.context.provider_amt:
287            self.context.provider_amt = provider_amt
288            self.context.amount_auth += provider_amt
289        xmltext = ''
290
291        # School fee
292        if category.startswith('schoolfee'):
293            # collect additional fees
294            if self.context.p_category in ('schoolfee_1', 'schoolfee_incl'):
295                xmltext = """<payment_item_detail>
296<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
297                item_id = 1
298
299                if student.entry_session < 2013:
300                    sorted_items = SCHOOLFEES[12][student.certcode].items()
301                elif student.entry_session < 2014:
302                    sorted_items = SCHOOLFEES[13][student.certcode].items()
303                elif student.entry_session < 2015:
304                    sorted_items = SCHOOLFEES[14][student.certcode].items()
305                elif student.entry_session < 2020:
306                    sorted_items = SCHOOLFEES[15][student.certcode].items()
307                elif student.entry_session < 2021:
308                    sorted_items = SCHOOLFEES[20][student.certcode].items()
309                elif student.entry_session < 2022:
310                    sorted_items = SCHOOLFEES[21][student.certcode].items()
311                else:
312                    sorted_items = SCHOOLFEES[22][student.certcode].items()
313                sorted_items.insert(0, sorted_items.pop(4))
314                for item in sorted_items:
315                    try:
316                        item_amt = 100 * int(item[1])
317                        if self.context.p_category == 'schoolfee_1' and item[0] == 'tuition':
318                            item_amt /= 2
319                        acct_num = ''
320                        bank_id = ''
321                        item_name = ''
322                        # Find appropriate bank
323                        try:
324                            bank = BANK_ACCOUNTS[item[0]]
325                        except: # transfer to faculty account
326                            if student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
327                                bank = BANK_ACCOUNTS['fac1']
328                            elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
329                                bank = BANK_ACCOUNTS['fac2']
330                            elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
331                                bank = BANK_ACCOUNTS['fac3']
332                        acct_num = bank[0]
333                        bank_id = bank[1]
334                        item_name = FEE_NAMES[item[0]]
335                        xmltext += """
336<item_detail item_id="%s" item_name="%s" item_amt="%d" bank_id="%s" acct_num="%s" />""" % (item_id, item_name, item_amt, bank_id, acct_num)
337                        item_id += 1
338                    except:
339                        pass
340                xmldict['item_id'] = item_id
341                xmltext += """
342<item_detail item_id="%(item_id)d" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
343</item_details>
344</payment_item_detail>""" % xmldict
345            # no additional charges, determine faculty bank only
346            else:
347                if student.is_postgrad:
348                    bank = BANK_ACCOUNTS['postgrad']
349                elif student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
350                    bank = BANK_ACCOUNTS['fac1']
351                elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
352                    bank = BANK_ACCOUNTS['fac2']
353                elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
354                    bank = BANK_ACCOUNTS['fac3']
355                xmldict['institution_acct'] = bank[0]
356                xmldict['institution_bank_id'] = bank[1]
357
358
359        # Clearance (acceptance) fee
360
361        elif category.startswith('clearance'):
362            # collect additional fees
363            if self.context.p_category == 'clearance_incl':
364                xmltext = """<payment_item_detail>
365<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
366                item_id = 1
367                for item in ACCEPTANCEFEES[student.certcode].items():
368                    try:
369                        item_amt = 100 * int(item[1])
370                        bank = BANK_ACCOUNTS[item[0]]
371                        acct_num = bank[0]
372                        bank_id = bank[1]
373                        item_name = FEE_NAMES[item[0]]
374                        xmltext += """
375<item_detail item_id="%s" item_name="%s" item_amt="%d" bank_id="%s" acct_num="%s" />""" % (item_id, item_name, item_amt, bank_id, acct_num)
376                        item_id += 1
377                    except:
378                        pass
379                xmldict['item_id'] = item_id
380                xmltext += """
381<item_detail item_id="%(item_id)d" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
382</item_details>
383</payment_item_detail>""" % xmldict
384            # no additional charges, determine faculty bank only
385            else:
386                if student.is_postgrad:
387                    bank = BANK_ACCOUNTS['postgrad']
388                else:
389                    bank = BANK_ACCOUNTS['acceptance']
390                xmldict['institution_acct'] = bank[0]
391                xmldict['institution_bank_id'] = bank[1]
392
393        # Other fees
394        elif category in BANK_ACCOUNTS.keys():
395            bank = BANK_ACCOUNTS[category]
396            xmldict['institution_acct'] = bank[0]
397            xmldict['institution_bank_id'] = bank[1]
398
399        if not xmltext and provider_amt == 0:
400            xmltext = """<payment_item_detail>
401<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
402<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" />
403</item_details>
404</payment_item_detail>""" % xmldict
405        elif not xmltext:
406            xmltext = """<payment_item_detail>
407<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
408<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" />
409<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" />
410</item_details>
411</payment_item_detail>""" % xmldict
412        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
413        xmlitems = ''
414        xmldoc = minidom.parseString(xmltext)
415        itemlist = xmldoc.getElementsByTagName('item_detail')
416        for s in itemlist:
417            xmlitems += "%s (%s %s, %s (%s)),  " % (
418                s.attributes['item_name'].value,
419                u'\u20a6',
420                int(s.attributes['item_amt'].value)/100,
421                s.attributes['acct_num'].value,
422                s.attributes['bank_id'].value,
423                )
424        self.context.p_split_data = xmlitems
425        self.context.provider_amt = provider_amt
426        self.amount_auth = int(100 * self.context.amount_auth)
427        hashargs = (
428            self.context.p_id +
429            PRODUCT_ID +
430            self.pay_item_id +
431            str(int(self.amount_auth)) +
432            self.site_redirect_url +
433            MAC)
434        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
435        return
436
437
438class CustomInterswitchPaymentRequestWebservicePageApplicant(
439    InterswitchPaymentRequestWebservicePageApplicant):
440    """Request webservice view for the CollegePAY gateway
441    """
442    grok.context(ICustomApplicantOnlinePayment)
443    gateway_host = HOST
444    gateway_url = URL
445    https = HTTPS
446
447class CustomInterswitchPaymentVerifyWebservicePageApplicant(
448    InterswitchPaymentVerifyWebservicePageApplicant):
449    """Payment verify view for the CollegePAY gateway
450    """
451    grok.context(ICustomApplicantOnlinePayment)
452    gateway_host = HOST
453    gateway_url = URL
454    https = HTTPS
455    mac = MAC
456    product_id = PRODUCT_ID
457
458class CustomInterswitchPaymentRequestWebservicePageStudent(
459    InterswitchPaymentRequestWebservicePageStudent):
460    """Request webservice view for the CollegePAY gateway
461    """
462    grok.context(ICustomStudentOnlinePayment)
463    gateway_host = HOST
464    gateway_url = URL
465    https = HTTPS
466    mac = MAC
467    product_id = PRODUCT_ID
468
469class CustomInterswitchPaymentVerifyWebservicePageStudent(
470    InterswitchPaymentVerifyWebservicePageStudent):
471    """Payment verify view for the CollegePAY gateway
472    """
473    grok.context(ICustomStudentOnlinePayment)
474    gateway_host = HOST
475    gateway_url = URL
476    https = HTTPS
477    mac = MAC
478    product_id = PRODUCT_ID
Note: See TracBrowser for help on using the repository browser.