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

Last change on this file since 17468 was 17468, checked in by Henrik Bettermann, 19 months ago

Configure more payment categories.

  • Property svn:executable set to *
File size: 20.1 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 = 2000.0
157        if self.applicant.applicant_id.startswith('trans'):
158            provider_amt = 3000.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        xmltext = """<payment_item_detail>
179<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
180<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" />
181<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" />
182</item_details>
183</payment_item_detail>""" % xmldict
184        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
185        xmlitems = ''
186        xmldoc = minidom.parseString(xmltext)
187        itemlist = xmldoc.getElementsByTagName('item_detail')
188        for s in itemlist:
189            xmlitems += "%s (%s %s, %s (%s)),  " % (
190                s.attributes['item_name'].value,
191                u'\u20a6',
192                int(s.attributes['item_amt'].value)/100,
193                s.attributes['acct_num'].value,
194                s.attributes['bank_id'].value,
195                )
196        self.context.p_split_data = xmlitems
197        self.amount_auth = int(100 * self.context.amount_auth)
198        hashargs = (
199            self.context.p_id +
200            PRODUCT_ID +
201            self.pay_item_id +
202            str(int(self.amount_auth)) +
203            self.site_redirect_url +
204            MAC)
205        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
206        return
207
208class CustomInterswitchPageStudent(InterswitchPageStudent):
209    """ View which sends a POST request to the Interswitch
210    CollegePAY payment gateway.
211    """
212    grok.context(ICustomStudentOnlinePayment)
213    action = POST_ACTION
214    site_name = SITE_NAME
215    currency = CURRENCY
216    pay_item_id = '101'
217    product_id = PRODUCT_ID
218
219    def update(self):
220        if not module_activated(
221            self.context.student.current_session, self.context):
222            self.flash(_('Forbidden'), type='danger')
223            self.redirect(self.url(self.context, '@@index'))
224            return
225        error = self.init_update()
226        if error:
227            self.flash(error, type='danger')
228            self.redirect(self.url(self.context, '@@index'))
229            return
230        student = self.student
231        category = self.context.p_category
232        # To guarantee that cleared students pay both acceptance fee
233        # and school fees, the page can only be accessed
234        # for school fee payments if acceptance/clearance fee has
235        # been successfully queried/paid beforehand. This
236        # requirement applies to students in state 'cleared' and
237        # entry_session greater than 2012 only.
238        if self.context.p_category.startswith('schoolfee') and \
239            student.state == CLEARED and \
240            student.entry_session > 2012:
241            acceptance_fee_paid = False
242            for ticket in student['payments'].values():
243                if ticket.p_state == 'paid' and \
244                    ticket.p_category.startswith('clearance'):
245                    acceptance_fee_paid = True
246                    break
247            if not acceptance_fee_paid:
248                self.flash(
249                    _('Please pay acceptance fee first.'), type="danger")
250                self.redirect(self.url(self.context, '@@index'))
251                return
252        # Already now it becomes an Interswitch payment. We set the net amount
253        # and add the gateway amount.
254        if not self.context.r_company:
255            self.context.net_amt = self.context.amount_auth
256            self.context.amount_auth += GATEWAY_AMT
257            self.context.gateway_amt = GATEWAY_AMT
258            self.context.r_company = u'interswitch'
259        xmldict = self.xmldict
260        # Provider data
261        xmldict['detail_ref'] = self.context.p_id
262        xmldict['provider_acct'] = PROVIDER_ACCT
263        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
264        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
265        # Institution data
266        xmldict['institution_acct'] = '00000000'
267        xmldict['institution_bank_id'] = '00'
268        provider_amt = 0.0
269        if category.startswith('clearance'):
270            provider_amt = 1500.0
271        elif category.startswith('hostel_maintenance'):
272            provider_amt = 1000.0
273        elif category in ('schoolfee', 'schoolfee_1', 'schoolfee_incl'):
274            provider_amt = 2500.0
275        xmldict['provider_amt'] = 100 * provider_amt
276        xmldict['institution_item_name'] = self.context.category
277        xmldict['institution_name'] = INSTITUTION_NAME
278        xmldict['institution_amt'] = 100 * self.context.net_amt
279        if not self.context.provider_amt:
280            self.context.provider_amt = provider_amt
281            self.context.amount_auth += provider_amt
282        xmltext = ''
283
284        # School fee
285        if category.startswith('schoolfee'):
286            # collect additional fees
287            if self.context.p_category in ('schoolfee_1', 'schoolfee_incl'):
288                xmltext = """<payment_item_detail>
289<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
290                item_id = 1
291
292                if student.entry_session < 2013:
293                    sorted_items = SCHOOLFEES[12][student.certcode].items()
294                elif student.entry_session < 2014:
295                    sorted_items = SCHOOLFEES[13][student.certcode].items()
296                elif student.entry_session < 2015:
297                    sorted_items = SCHOOLFEES[14][student.certcode].items()
298                elif student.entry_session < 2020:
299                    sorted_items = SCHOOLFEES[15][student.certcode].items()
300                elif student.entry_session < 2021:
301                    sorted_items = SCHOOLFEES[20][student.certcode].items()
302                elif student.entry_session < 2022:
303                    sorted_items = SCHOOLFEES[21][student.certcode].items()
304                else:
305                    sorted_items = SCHOOLFEES[22][student.certcode].items()
306                sorted_items.insert(0, sorted_items.pop(4))
307                for item in sorted_items:
308                    try:
309                        item_amt = 100 * int(item[1])
310                        if self.context.p_category == 'schoolfee_1' and item[0] == 'tuition':
311                            item_amt /= 2
312                        acct_num = ''
313                        bank_id = ''
314                        item_name = ''
315                        # Find appropriate bank
316                        try:
317                            bank = BANK_ACCOUNTS[item[0]]
318                        except: # transfer to faculty account
319                            if student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
320                                bank = BANK_ACCOUNTS['fac1']
321                            elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
322                                bank = BANK_ACCOUNTS['fac2']
323                            elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
324                                bank = BANK_ACCOUNTS['fac3']
325                        acct_num = bank[0]
326                        bank_id = bank[1]
327                        item_name = FEE_NAMES[item[0]]
328                        xmltext += """
329<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)
330                        item_id += 1
331                    except:
332                        pass
333                xmldict['item_id'] = item_id
334                xmltext += """
335<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" />
336</item_details>
337</payment_item_detail>""" % xmldict
338            # no additional charges, determine faculty bank only
339            else:
340                if student.is_postgrad:
341                    bank = BANK_ACCOUNTS['postgrad']
342                elif student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
343                    bank = BANK_ACCOUNTS['fac1']
344                elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
345                    bank = BANK_ACCOUNTS['fac2']
346                elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
347                    bank = BANK_ACCOUNTS['fac3']
348                xmldict['institution_acct'] = bank[0]
349                xmldict['institution_bank_id'] = bank[1]
350
351
352        # Clearance (acceptance) fee
353
354        elif category.startswith('clearance'):
355            # collect additional fees
356            if self.context.p_category == 'clearance_incl':
357                xmltext = """<payment_item_detail>
358<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
359                item_id = 1
360                for item in ACCEPTANCEFEES[student.certcode].items():
361                    try:
362                        item_amt = 100 * int(item[1])
363                        bank = BANK_ACCOUNTS[item[0]]
364                        acct_num = bank[0]
365                        bank_id = bank[1]
366                        item_name = FEE_NAMES[item[0]]
367                        xmltext += """
368<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)
369                        item_id += 1
370                    except:
371                        pass
372                xmldict['item_id'] = item_id
373                xmltext += """
374<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" />
375</item_details>
376</payment_item_detail>""" % xmldict
377            # no additional charges, determine faculty bank only
378            else:
379                if student.is_postgrad:
380                    bank = BANK_ACCOUNTS['postgrad']
381                else:
382                    bank = BANK_ACCOUNTS['acceptance']
383                xmldict['institution_acct'] = bank[0]
384                xmldict['institution_bank_id'] = bank[1]
385
386        # Other fees
387        elif category in BANK_ACCOUNTS.keys():
388            bank = BANK_ACCOUNTS[category]
389            xmldict['institution_acct'] = bank[0]
390            xmldict['institution_bank_id'] = bank[1]
391
392        if not xmltext and provider_amt == 0:
393            xmltext = """<payment_item_detail>
394<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
395<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" />
396</item_details>
397</payment_item_detail>""" % xmldict
398        elif not xmltext:
399            xmltext = """<payment_item_detail>
400<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
401<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" />
402<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" />
403</item_details>
404</payment_item_detail>""" % xmldict
405        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
406        xmlitems = ''
407        xmldoc = minidom.parseString(xmltext)
408        itemlist = xmldoc.getElementsByTagName('item_detail')
409        for s in itemlist:
410            xmlitems += "%s (%s %s, %s (%s)),  " % (
411                s.attributes['item_name'].value,
412                u'\u20a6',
413                int(s.attributes['item_amt'].value)/100,
414                s.attributes['acct_num'].value,
415                s.attributes['bank_id'].value,
416                )
417        self.context.p_split_data = xmlitems
418        self.context.provider_amt = provider_amt
419        self.amount_auth = int(100 * self.context.amount_auth)
420        hashargs = (
421            self.context.p_id +
422            PRODUCT_ID +
423            self.pay_item_id +
424            str(int(self.amount_auth)) +
425            self.site_redirect_url +
426            MAC)
427        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
428        return
429
430
431class CustomInterswitchPaymentRequestWebservicePageApplicant(
432    InterswitchPaymentRequestWebservicePageApplicant):
433    """Request webservice view for the CollegePAY gateway
434    """
435    grok.context(ICustomApplicantOnlinePayment)
436    gateway_host = HOST
437    gateway_url = URL
438    https = HTTPS
439
440class CustomInterswitchPaymentVerifyWebservicePageApplicant(
441    InterswitchPaymentVerifyWebservicePageApplicant):
442    """Payment verify view for the CollegePAY gateway
443    """
444    grok.context(ICustomApplicantOnlinePayment)
445    gateway_host = HOST
446    gateway_url = URL
447    https = HTTPS
448    mac = MAC
449    product_id = PRODUCT_ID
450
451class CustomInterswitchPaymentRequestWebservicePageStudent(
452    InterswitchPaymentRequestWebservicePageStudent):
453    """Request webservice view for the CollegePAY gateway
454    """
455    grok.context(ICustomStudentOnlinePayment)
456    gateway_host = HOST
457    gateway_url = URL
458    https = HTTPS
459    mac = MAC
460    product_id = PRODUCT_ID
461
462class CustomInterswitchPaymentVerifyWebservicePageStudent(
463    InterswitchPaymentVerifyWebservicePageStudent):
464    """Payment verify view for the CollegePAY gateway
465    """
466    grok.context(ICustomStudentOnlinePayment)
467    gateway_host = HOST
468    gateway_url = URL
469    https = HTTPS
470    mac = MAC
471    product_id = PRODUCT_ID
Note: See TracBrowser for help on using the repository browser.