1 | ## $Id: browser.py 13784 2016-03-19 12:51:01Z henrik $ |
---|
2 | ## |
---|
3 | ## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann |
---|
4 | ## This program is free software; you can redistribute it and/or modify |
---|
5 | ## it under the terms of the GNU General Public License as published by |
---|
6 | ## the Free Software Foundation; either version 2 of the License, or |
---|
7 | ## (at your option) any later version. |
---|
8 | ## |
---|
9 | ## This program is distributed in the hope that it will be useful, |
---|
10 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
11 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
12 | ## GNU General Public License for more details. |
---|
13 | ## |
---|
14 | ## You should have received a copy of the GNU General Public License |
---|
15 | ## along with this program; if not, write to the Free Software |
---|
16 | ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
---|
17 | ## |
---|
18 | from datetime import datetime |
---|
19 | import httplib |
---|
20 | import urllib |
---|
21 | import urllib2 |
---|
22 | import re |
---|
23 | from xml.dom.minidom import parseString |
---|
24 | import grok |
---|
25 | from zope.component import getUtility |
---|
26 | from zope.catalog.interfaces import ICatalog |
---|
27 | from waeup.kofa.interfaces import IUniversity, CLEARED |
---|
28 | from waeup.kofa.payments.interfaces import IPayer |
---|
29 | from waeup.kofa.webservices import PaymentDataWebservice |
---|
30 | from waeup.kofa.browser.layout import KofaPage, UtilityView |
---|
31 | from waeup.kofa.students.viewlets import ApprovePaymentActionButton as APABStudent |
---|
32 | from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant |
---|
33 | from waeup.aaue.interfaces import academic_sessions_vocab |
---|
34 | from kofacustom.nigeria.interswitch.browser import ( |
---|
35 | InterswitchActionButtonStudent, |
---|
36 | InterswitchRequestWebserviceActionButtonStudent, |
---|
37 | InterswitchActionButtonApplicant, |
---|
38 | InterswitchRequestWebserviceActionButtonApplicant) |
---|
39 | from waeup.aaue.interfaces import MessageFactory as _ |
---|
40 | from waeup.aaue.students.interfaces import ICustomStudentOnlinePayment |
---|
41 | from waeup.aaue.applicants.interfaces import ICustomApplicantOnlinePayment |
---|
42 | |
---|
43 | ERROR_PART1 = ( |
---|
44 | 'PayeeName=N/A~' |
---|
45 | + 'Faculty=N/A~' |
---|
46 | + 'Department=N/A~' |
---|
47 | + 'Level=N/A~' |
---|
48 | + 'ProgrammeType=N/A~' |
---|
49 | + 'StudyType=N/A~' |
---|
50 | + 'Session=N/A~' |
---|
51 | + 'PayeeID=N/A~' |
---|
52 | + 'Amount=N/A~' |
---|
53 | + 'FeeStatus=') |
---|
54 | ERROR_PART2 = ( |
---|
55 | '~Semester=N/A~' |
---|
56 | + 'PaymentType=N/A~' |
---|
57 | + 'MatricNumber=N/A~' |
---|
58 | + 'Email=N/A~' |
---|
59 | + 'PhoneNumber=N/A') |
---|
60 | |
---|
61 | class CustomPaymentDataWebservice(PaymentDataWebservice): |
---|
62 | """A simple webservice to publish payment and payer details on request from |
---|
63 | accepted IP addresses without authentication. |
---|
64 | |
---|
65 | Etranzact is asking for the PAYEE_ID which is indeed misleading. |
---|
66 | These are not the data of the payee but of the payer. And it's |
---|
67 | not the id of the payer but of the payment. |
---|
68 | """ |
---|
69 | grok.name('feerequest') |
---|
70 | |
---|
71 | #ACCEPTED_IP = ('195.219.3.181', '195.219.3.184') |
---|
72 | ACCEPTED_IP = None |
---|
73 | |
---|
74 | def update(self, PAYEE_ID=None, PAYMENT_TYPE=None): |
---|
75 | if PAYEE_ID == None: |
---|
76 | self.output = ERROR_PART1 + 'Missing PAYEE_ID' + ERROR_PART2 |
---|
77 | return |
---|
78 | real_ip = self.request.get('HTTP_X_FORWARDED_FOR', None) |
---|
79 | # We can forego the logging once eTranzact payments run smoothly |
---|
80 | # and the accepted IP addresses are used. |
---|
81 | if real_ip: |
---|
82 | self.context.logger.info('PaymentDataWebservice called: %s' % real_ip) |
---|
83 | if real_ip and self.ACCEPTED_IP: |
---|
84 | if real_ip not in self.ACCEPTED_IP: |
---|
85 | self.output = ERROR_PART1 + 'Wrong IP address' + ERROR_PART2 |
---|
86 | return |
---|
87 | category_mapping = { |
---|
88 | 'SCHOOL-FEE-NEW': ('schoolfee',), |
---|
89 | 'SCHOOL-FEE-RETURNING': ('schoolfee',), |
---|
90 | 'SCHOOL-FEE-PLUS-NEW': ('schoolfee_incl',), |
---|
91 | 'SCHOOL-FEE-PLUS-RETURNING': ('schoolfee_incl',), |
---|
92 | 'SCHOOL-FEE-PG-NEW': ('schoolfee',), |
---|
93 | 'SCHOOL-FEE-PG-RETURNING': ('schoolfee',), |
---|
94 | 'SCHOOL-FEE-FIRST-INSTALMENT-PLUS': ('schoolfee_1',), |
---|
95 | 'SCHOOL-FEE-SECOND-INSTALMENT': ('schoolfee_2',), |
---|
96 | 'SCHOOL-FEE-BALANCE': ('schoolfee','schoolfee_incl', |
---|
97 | 'schoolfee_1','schoolfee_2'), |
---|
98 | 'ACCEPTANCE-FEE': ('clearance',), |
---|
99 | 'ACCEPTANCE-FEE-PLUS': ('clearance_incl',), |
---|
100 | 'ACCEPTANCE-FEE-PG': ('clearance',), |
---|
101 | 'APPLICATION-FEE': ('application',), |
---|
102 | 'LATE-REGISTRATION': ('late_registration',), |
---|
103 | 'AAU-STUDENT-WELFARE-ASSURANCE': ('welfare',), |
---|
104 | 'HOSTEL-ACCOMMODATION-FEE': ('hostel_maintenance',), |
---|
105 | 'AAU-LAPEL-FILE-FEE': ('lapel',), |
---|
106 | 'MATRICULATION-GOWN-FEE': ('matric_gown',), |
---|
107 | 'CONCESSIONAL-FEE': ('concessional',), |
---|
108 | 'STUDENTS-UNION-DUES': ('union',), |
---|
109 | } |
---|
110 | |
---|
111 | if PAYMENT_TYPE not in category_mapping.keys(): |
---|
112 | self.output = ERROR_PART1 + 'Invalid PAYMENT_TYPE' + ERROR_PART2 |
---|
113 | return |
---|
114 | |
---|
115 | # It seems eTranzact sends a POST request with an empty body but the URL |
---|
116 | # contains a query string. So it's actually a GET request pretended |
---|
117 | # to be a POST request. Although this does not comply with the |
---|
118 | # RFC 2616 HTTP guidelines we may try to fetch the id from the QUERY_STRING |
---|
119 | # value of the request. |
---|
120 | #if PAYEE_ID is None: |
---|
121 | # try: |
---|
122 | # PAYEE_ID = self.request['QUERY_STRING'].split('=')[1] |
---|
123 | # except: |
---|
124 | # self.output = '-4' |
---|
125 | # return |
---|
126 | |
---|
127 | cat = getUtility(ICatalog, name='payments_catalog') |
---|
128 | results = list(cat.searchResults(p_id=(PAYEE_ID, PAYEE_ID))) |
---|
129 | if len(results) != 1: |
---|
130 | self.output = ERROR_PART1 + 'Invalid PAYEE_ID' + ERROR_PART2 |
---|
131 | return |
---|
132 | student = getattr(results[0], 'student', None) |
---|
133 | amount = results[0].amount_auth |
---|
134 | payment_type = results[0].category |
---|
135 | p_category = results[0].p_category |
---|
136 | programme_type = results[0].p_item |
---|
137 | if not programme_type: |
---|
138 | programme_type = 'N/A' |
---|
139 | academic_session = academic_sessions_vocab.getTerm( |
---|
140 | results[0].p_session).title |
---|
141 | status = results[0].p_state |
---|
142 | |
---|
143 | if status == 'paid': |
---|
144 | self.output = ERROR_PART1 + 'PAYEE_ID already used' + ERROR_PART2 |
---|
145 | return |
---|
146 | if p_category not in category_mapping[PAYMENT_TYPE]: |
---|
147 | self.output = ERROR_PART1 + 'Wrong PAYMENT_TYPE' + ERROR_PART2 |
---|
148 | return |
---|
149 | if student and PAYMENT_TYPE.endswith('-RETURNING') \ |
---|
150 | and student.state == CLEARED: |
---|
151 | self.output = ERROR_PART1 + 'Not a returning student' + ERROR_PART2 |
---|
152 | return |
---|
153 | if student and PAYMENT_TYPE.endswith('-NEW') \ |
---|
154 | and student.state != CLEARED: |
---|
155 | self.output = ERROR_PART1 + 'Not a new student' + ERROR_PART2 |
---|
156 | return |
---|
157 | if student and '-PG' in PAYMENT_TYPE and not student.is_postgrad: |
---|
158 | self.output = ERROR_PART1 + 'Not a postgrad student' + ERROR_PART2 |
---|
159 | return |
---|
160 | if student and '-PG' not in PAYMENT_TYPE and student.is_postgrad: |
---|
161 | self.output = ERROR_PART1 + 'Postgrad student' + ERROR_PART2 |
---|
162 | return |
---|
163 | if '-BALANCE' in PAYMENT_TYPE and results[0].p_item != 'Balance': |
---|
164 | self.output = ERROR_PART1 + 'Not a balance payment' + ERROR_PART2 |
---|
165 | return |
---|
166 | if not '-BALANCE' in PAYMENT_TYPE and results[0].p_item == 'Balance': |
---|
167 | self.output = ERROR_PART1 + 'Balance payment' + ERROR_PART2 |
---|
168 | return |
---|
169 | |
---|
170 | try: |
---|
171 | owner = IPayer(results[0]) |
---|
172 | full_name = owner.display_fullname |
---|
173 | matric_no = owner.id |
---|
174 | faculty = owner.faculty |
---|
175 | department = owner.department |
---|
176 | study_type = owner.current_mode |
---|
177 | email = owner.email |
---|
178 | phone = owner.phone |
---|
179 | level = owner.current_level |
---|
180 | except (TypeError, AttributeError): |
---|
181 | self.output = ERROR_PART1 + 'Unknown error' + ERROR_PART2 |
---|
182 | return |
---|
183 | self.output = ( |
---|
184 | 'PayeeName=%s~' + |
---|
185 | 'Faculty=%s~' + |
---|
186 | 'Department=%s~' + |
---|
187 | 'Level=%s~' + |
---|
188 | 'ProgrammeType=%s~' + |
---|
189 | 'StudyType=%s~' + |
---|
190 | 'Session=%s~' + |
---|
191 | 'PayeeID=%s~' + |
---|
192 | 'Amount=%s~' + |
---|
193 | 'FeeStatus=%s~' + |
---|
194 | 'Semester=N/A~' + |
---|
195 | 'PaymentType=%s~' + |
---|
196 | 'MatricNumber=%s~' + |
---|
197 | 'Email=%s~' + |
---|
198 | 'PhoneNumber=%s' |
---|
199 | |
---|
200 | ) % (full_name, faculty, |
---|
201 | department, level, programme_type, study_type, |
---|
202 | academic_session, PAYEE_ID, amount, status, payment_type, |
---|
203 | matric_no, email, phone) |
---|
204 | return |
---|
205 | |
---|
206 | |
---|
207 | # Requerying eTranzact payments |
---|
208 | |
---|
209 | TERMINAL_ID = '0570000070' |
---|
210 | QUERY_URL = 'https://www.etranzact.net/WebConnectPlus/query.jsp' |
---|
211 | |
---|
212 | # Test environment |
---|
213 | #QUERY_URL = 'http://demo.etranzact.com:8080/WebConnect/queryPayoutletTransaction.jsp' |
---|
214 | #TERMINAL_ID = '5009892289' |
---|
215 | |
---|
216 | def query_etranzact(confirmation_number, payment): |
---|
217 | |
---|
218 | postdict = {} |
---|
219 | postdict['TERMINAL_ID'] = TERMINAL_ID |
---|
220 | #postdict['RESPONSE_URL'] = 'http://dummy' |
---|
221 | postdict['CONFIRMATION_NO'] = confirmation_number |
---|
222 | data = urllib.urlencode(postdict) |
---|
223 | payment.conf_number = confirmation_number |
---|
224 | try: |
---|
225 | # eTranzact only accepts HTTP 1.1 requests. Therefore |
---|
226 | # the urllib2 package is required here. |
---|
227 | f = urllib2.urlopen(url=QUERY_URL, data=data) |
---|
228 | success = f.read() |
---|
229 | success = success.replace('\r\n','') |
---|
230 | # eTranzact sends strange HTML tags which must be removed. |
---|
231 | success = re.sub("<.*?>", "", success) |
---|
232 | if 'CUSTOMER_ID' not in success: |
---|
233 | msg = _('Invalid or unsuccessful callback: ${a}', |
---|
234 | mapping = {'a': success}) |
---|
235 | log = 'invalid callback for payment %s: %s' % (payment.p_id, success) |
---|
236 | payment.p_state = 'failed' |
---|
237 | return False, msg, log |
---|
238 | success = success.replace('%20',' ').split('&') |
---|
239 | # We expect at least two parameters |
---|
240 | if len(success) < 2: |
---|
241 | msg = _('Invalid callback: ${a}', mapping = {'a': success}) |
---|
242 | log = 'invalid callback for payment %s: %s' % (payment.p_id, success) |
---|
243 | payment.p_state = 'failed' |
---|
244 | return False, msg, log |
---|
245 | try: |
---|
246 | success_dict = dict([tuple(i.split('=')) for i in success]) |
---|
247 | except ValueError: |
---|
248 | msg = _('Invalid callback: ${a}', mapping = {'a': success}) |
---|
249 | log = 'invalid callback for payment %s: %s' % (payment.p_id, success) |
---|
250 | payment.p_state = 'failed' |
---|
251 | return False, msg, log |
---|
252 | except IOError: |
---|
253 | msg = _('eTranzact IOError') |
---|
254 | log = 'eTranzact IOError' |
---|
255 | return False, msg, log |
---|
256 | payment.r_code = u'ET' |
---|
257 | payment.r_company = u'etranzact' |
---|
258 | payment.r_desc = u'%s' % success_dict.get('TRANS_DESCR') |
---|
259 | payment.r_amount_approved = float(success_dict.get('TRANS_AMOUNT',0.0)) |
---|
260 | payment.r_card_num = None |
---|
261 | payment.r_pay_reference = u'%s' % success_dict.get('RECEIPT_NO') |
---|
262 | if payment.r_amount_approved != payment.amount_auth: |
---|
263 | msg = _('Wrong amount') |
---|
264 | log = 'wrong callback for payment %s: %s' % (payment.p_id, success) |
---|
265 | payment.p_state = 'failed' |
---|
266 | return False, msg, log |
---|
267 | customer_id = success_dict.get('CUSTOMER_ID') |
---|
268 | if payment.p_id != customer_id: |
---|
269 | msg = _('Wrong payment id') |
---|
270 | log = 'wrong callback for payment %s: %s' % (payment.p_id, success) |
---|
271 | payment.p_state = 'failed' |
---|
272 | return False, msg, log |
---|
273 | log = 'valid callback for payment %s: %s' % (payment.p_id, success) |
---|
274 | msg = _('Successful callback received') |
---|
275 | payment.p_state = 'paid' |
---|
276 | payment.payment_date = datetime.utcnow() |
---|
277 | return True, msg, log |
---|
278 | |
---|
279 | class EtranzactEnterPinActionButtonApplicant(APABApplicant): |
---|
280 | grok.context(ICustomApplicantOnlinePayment) |
---|
281 | grok.require('waeup.payApplicant') |
---|
282 | grok.order(3) |
---|
283 | icon = 'actionicon_call.png' |
---|
284 | text = _('Query eTranzact History') |
---|
285 | target = 'enterpin' |
---|
286 | |
---|
287 | class EtranzactEnterPinActionButtonStudent(APABStudent): |
---|
288 | grok.context(ICustomStudentOnlinePayment) |
---|
289 | grok.require('waeup.payStudent') |
---|
290 | grok.order(3) |
---|
291 | icon = 'actionicon_call.png' |
---|
292 | text = _('Query eTranzact History') |
---|
293 | target = 'enterpin' |
---|
294 | |
---|
295 | class EtranzactEnterPinPageStudent(KofaPage): |
---|
296 | """ |
---|
297 | """ |
---|
298 | grok.context(ICustomStudentOnlinePayment) |
---|
299 | grok.name('enterpin') |
---|
300 | grok.template('enterpin') |
---|
301 | grok.require('waeup.payStudent') |
---|
302 | |
---|
303 | buttonname = _('Submit to eTranzact') |
---|
304 | label = _('Requery eTranzact History') |
---|
305 | action = 'query_history' |
---|
306 | placeholder = _('Confirmation Number (PIN)') |
---|
307 | |
---|
308 | def update(self): |
---|
309 | super(EtranzactEnterPinPageStudent, self).update() |
---|
310 | if not self.context.p_category.startswith('schoolfee'): |
---|
311 | return |
---|
312 | student = self.context.student |
---|
313 | if student.state != CLEARED: |
---|
314 | return |
---|
315 | if student.entry_session < 2013: |
---|
316 | return |
---|
317 | for ticket in student['payments'].values(): |
---|
318 | if ticket.p_state == 'paid' and \ |
---|
319 | ticket.p_category.startswith('clearance'): |
---|
320 | return |
---|
321 | self.flash(_('Please pay acceptance fee first.'), type="danger") |
---|
322 | self.redirect(self.url(self.context, '@@index')) |
---|
323 | return |
---|
324 | |
---|
325 | class EtranzactEnterPinPageApplicant(EtranzactEnterPinPageStudent): |
---|
326 | """ |
---|
327 | """ |
---|
328 | grok.require('waeup.payApplicant') |
---|
329 | grok.context(ICustomApplicantOnlinePayment) |
---|
330 | |
---|
331 | class EtranzactQueryHistoryPageStudent(UtilityView, grok.View): |
---|
332 | """ Query history of eTranzact payments |
---|
333 | """ |
---|
334 | grok.context(ICustomStudentOnlinePayment) |
---|
335 | grok.name('query_history') |
---|
336 | grok.require('waeup.payStudent') |
---|
337 | |
---|
338 | def update(self, confirmation_number=None): |
---|
339 | if self.context.p_state == 'paid': |
---|
340 | self.flash(_('This ticket has already been paid.')) |
---|
341 | return |
---|
342 | student = self.context.student |
---|
343 | success, msg, log = query_etranzact(confirmation_number,self.context) |
---|
344 | student.writeLogMessage(self, log) |
---|
345 | if not success: |
---|
346 | self.flash(msg) |
---|
347 | return |
---|
348 | flashtype, msg, log = self.context.doAfterStudentPayment() |
---|
349 | if log is not None: |
---|
350 | student.writeLogMessage(self, log) |
---|
351 | self.flash(msg, type=flashtype) |
---|
352 | return |
---|
353 | |
---|
354 | def render(self): |
---|
355 | self.redirect(self.url(self.context, '@@index')) |
---|
356 | return |
---|
357 | |
---|
358 | class EtranzactQueryHistoryPageApplicant(UtilityView, grok.View): |
---|
359 | """ Query history of eTranzact payments |
---|
360 | """ |
---|
361 | grok.context(ICustomApplicantOnlinePayment) |
---|
362 | grok.name('query_history') |
---|
363 | grok.require('waeup.payApplicant') |
---|
364 | |
---|
365 | def update(self, confirmation_number=None): |
---|
366 | ob_class = self.__implemented__.__name__ |
---|
367 | if self.context.p_state == 'paid': |
---|
368 | self.flash(_('This ticket has already been paid.')) |
---|
369 | return |
---|
370 | applicant = self.context.__parent__ |
---|
371 | success, msg, log = query_etranzact(confirmation_number,self.context) |
---|
372 | applicant.writeLogMessage(self, log) |
---|
373 | if not success: |
---|
374 | self.flash(msg) |
---|
375 | return |
---|
376 | flashtype, msg, log = self.context.doAfterApplicantPayment() |
---|
377 | if log is not None: |
---|
378 | applicant.writeLogMessage(self, log) |
---|
379 | self.flash(msg, type=flashtype) |
---|
380 | return |
---|
381 | |
---|
382 | def render(self): |
---|
383 | self.redirect(self.url(self.context, '@@index')) |
---|
384 | return |
---|
385 | |
---|
386 | # Disable Interswitch viewlets. This could be avoided by defining the |
---|
387 | # action button viewlets of kofacustom.nigeria.interswitch.browser in the |
---|
388 | # context of INigeriaStudentOnlinePayment or INigeriaApplicantOnlinePayment |
---|
389 | # respectively. But then all interswitch.browser modules have to be extended. |
---|
390 | |
---|
391 | #class InterswitchActionButtonStudent(InterswitchActionButtonStudent): |
---|
392 | |
---|
393 | # @property |
---|
394 | # def target_url(self): |
---|
395 | # return '' |
---|
396 | |
---|
397 | #class InterswitchRequestWebserviceActionButtonStudent( |
---|
398 | # InterswitchRequestWebserviceActionButtonStudent): |
---|
399 | |
---|
400 | # @property |
---|
401 | # def target_url(self): |
---|
402 | # return '' |
---|
403 | |
---|
404 | #class InterswitchActionButtonApplicant(InterswitchActionButtonApplicant): |
---|
405 | |
---|
406 | # @property |
---|
407 | # def target_url(self): |
---|
408 | # return '' |
---|
409 | |
---|
410 | #class InterswitchRequestWebserviceActionButtonApplicant( |
---|
411 | # InterswitchRequestWebserviceActionButtonApplicant): |
---|
412 | |
---|
413 | # @property |
---|
414 | # def target_url(self): |
---|
415 | # return '' |
---|