source: main/kofacustom.nigeria/trunk/src/kofacustom/nigeria/remita/applicantsbrowser.py @ 15846

Last change on this file since 15846 was 15842, checked in by Henrik Bettermann, 5 years ago

Show correct buttons if payment state in ('paid', 'waived', 'scholarship').

File size: 11.0 KB
Line 
1## $Id: browser.py 14759 2017-08-03 09:09:54Z henrik $
2##
3## Copyright (C) 2017 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##
18import grok
19import hashlib
20from datetime import datetime, timedelta
21from zope.component import getUtility
22from zope.security import checkPermission
23from waeup.kofa.interfaces import IKofaUtils
24from waeup.kofa.utils.helpers import to_timezone
25from waeup.kofa.browser.layout import UtilityView, KofaPage
26from waeup.kofa.browser.viewlets import ManageActionButton
27from waeup.kofa.applicants.browser import OnlinePaymentDisplayFormPage as OPDPApplicant
28from kofacustom.nigeria.remita.helpers import (
29    get_JSON_POST_response, query_remita, write_payments_log)
30from kofacustom.nigeria.payments.interfaces import INigeriaOnlinePayment
31from kofacustom.nigeria.applicants.interfaces import INigeriaApplicantOnlinePayment
32from kofacustom.nigeria.interfaces import MessageFactory as _
33from kofacustom.nigeria.remita.studentsbrowser import module_activated
34
35from kofacustom.nigeria.remita.tests import (
36    MERCHANTID, HOST, HTTPS, API_KEY, SERVICETYPEID, GATEWAY_AMT)
37
38grok.templatedir('browser_templates')
39
40# Buttons
41
42class RemitaActionButtonApplicant(ManageActionButton):
43    grok.order(1)
44    grok.context(INigeriaOnlinePayment)
45    grok.view(OPDPApplicant)
46    grok.require('waeup.payApplicant')
47    icon = 'actionicon_pay.png'
48    text = _('Pay via Remita')
49    target = 'goto_remita'
50
51    @property
52    def target_url(self):
53        if not module_activated(
54            self.context.__parent__.__parent__.year, self.context):
55            return ''
56        if self.context.p_state != 'unpaid':
57            return ''
58        return self.view.url(self.view.context, self.target)
59
60class RemitaRequestPaymentStatusActionButtonApplicant(ManageActionButton):
61    grok.order(2)
62    grok.context(INigeriaOnlinePayment)
63    grok.view(OPDPApplicant)
64    grok.require('waeup.payApplicant')
65    icon = 'actionicon_call.png'
66    text = _('Requery Remita Payment Status')
67    target = 'request_payment_status'
68
69    @property
70    def target_url(self):
71        if not module_activated(
72            self.context.__parent__.__parent__.year, self.context):
73            return ''
74        if self.context.p_state in ('paid', 'waived', 'scholarship'):
75            return ''
76        return self.view.url(self.view.context, self.target)
77
78class RemitaVerifyPaymentStatusActionButtonApplicant(ManageActionButton):
79    grok.order(3)
80    grok.context(INigeriaOnlinePayment)
81    grok.view(OPDPApplicant)
82    grok.require('waeup.manageApplication')
83    icon = 'actionicon_call.png'
84    text = _('Verify Remita Payment Status')
85    target = 'verify_payment_status'
86
87    @property
88    def target_url(self):
89        if not module_activated(
90            self.context.__parent__.__parent__.year, self.context):
91            return ''
92        if self.context.p_state != 'paid' \
93            or self.context.r_company != u'remita':
94            return ''
95        return self.view.url(self.view.context, self.target)
96
97# Webservice request views
98
99class RemitaRequestPaymentStatusPageApplicant(UtilityView, grok.View):
100    """ Request webservice view for the Remita gateway.
101    """
102    grok.context(INigeriaApplicantOnlinePayment)
103    grok.name('request_payment_status')
104    grok.require('waeup.payApplicant')
105
106    merchantId = MERCHANTID
107    host = HOST
108    https = HTTPS
109    api_key = API_KEY
110
111    def update(self):
112        if not module_activated(
113            self.context.__parent__.__parent__.year, self.context):
114            return
115        if self.context.p_state in ('paid', 'waived', 'scholarship'):
116            self.flash(_('This ticket has already been paid.'), type='danger')
117            return
118        applicant = self.context.__parent__
119        RRR = self.context.r_pay_reference
120        if not RRR:
121            self.flash(_('Remita Retrieval Reference not found.'), type='danger')
122            return
123        # Remita sends a POST request which may contain more information
124        # if a payment was not successful.
125        resp = self.request.form
126        if resp and resp.get('statuscode') not in (None, '025', '00', '01'):
127            self.flash('Transaction status message from Remita: %s'
128                % resp.get('status'), type='warning')
129        success, msg, log = query_remita(
130            self.context,
131            self.merchantId,
132            self.api_key,
133            RRR,
134            self.host,
135            self.https,
136            False)
137        applicant.writeLogMessage(self, log)
138        if not success:
139            self.flash(msg, type='danger')
140            return
141        write_payments_log(applicant.applicant_id, self.context)
142        flashtype, msg, log = self.context.doAfterApplicantPayment()
143        if log is not None:
144            applicant.writeLogMessage(self, log)
145        self.flash(msg, type=flashtype)
146        return
147
148    def render(self):
149        self.redirect(self.url(self.context.__parent__, 'edit'))
150        return
151
152class RemitaVerifyPaymentStatusPageApplicant(UtilityView, grok.View):
153    """ Request webservice view for the Remita gateway.
154    """
155    grok.context(INigeriaApplicantOnlinePayment)
156    grok.name('verify_payment_status')
157    grok.require('waeup.manageApplication')
158
159    merchantId = MERCHANTID
160    host = HOST
161    https = HTTPS
162    api_key = API_KEY
163
164    def update(self):
165        if not module_activated(
166            self.context.__parent__.__parent__.year, self.context):
167            return
168        if self.context.p_state  != 'paid' \
169            or self.context.r_company != u'remita':
170            self.flash(_('This ticket has not been paid.'), type='danger')
171            return
172        applicant = self.context.__parent__
173        RRR = self.context.r_pay_reference
174        if not RRR:
175            self.flash(_('Remita Retrieval Reference not found.'), type='danger')
176            return
177        # Remita sends a POST request which may contain more information
178        # if a payment was not successful.
179        resp = self.request.form
180        if resp and resp.get('statuscode') not in (None, '025', '00', '01'):
181            self.flash('Transaction status message from Remita: %s'
182                % resp.get('status'), type='warning')
183        success, msg, log = query_remita(
184            self.context,
185            self.merchantId,
186            self.api_key,
187            RRR,
188            self.host,
189            self.https,
190            True)
191        applicant.writeLogMessage(self, log)
192        if not success:
193            self.flash(msg, type='danger')
194            return
195        self.flash(msg)
196        return
197
198    def render(self):
199        self.redirect(self.url(self.context))
200        return
201
202
203# Forwarding pages
204
205class RemitaPageApplicant(KofaPage):
206    """ View which sends a POST request to the Remita payment gateway.
207    """
208    grok.context(INigeriaApplicantOnlinePayment)
209    grok.name('goto_remita')
210    grok.template('goto_remita')
211    grok.require('waeup.payApplicant')
212    label = _('Pay via Remita')
213    submit_button = _('Pay now')
214
215    merchantId = MERCHANTID
216    host = HOST
217    https = HTTPS
218    api_key = API_KEY
219    serviceTypeId = SERVICETYPEID
220
221    #orderId = '3456346346'
222    init_url = '/remita/ecomm/split/init.reg'
223    amount='1000'
224    lineitems = (
225                  {"lineItemsId":"itemid1","beneficiaryName":"Klaus Mueller",
226                  "beneficiaryAccount":"6020067886","bankCode":"011",
227                  "beneficiaryAmount":"500","deductFeeFrom":"1"},
228                  {"lineItemsId":"itemid2","beneficiaryName":"Werner Rumm",
229                  "beneficiaryAccount":"0360883515","bankCode":"050",
230                  "beneficiaryAmount":"500","deductFeeFrom":"0"}
231                )
232
233    @property
234    def action(self):
235        if self.https:
236            return 'https://' + self.host + '/remita/ecomm/finalize.reg'
237        return 'http://' + self.host + '/remita/ecomm/finalize.reg'
238
239    def init_update(self):
240        if self.context.p_state == 'paid':
241            return _("Payment ticket can't be re-sent to Remita.")
242        if self.context.r_company and self.context.r_company != 'remita':
243            return _("Payment ticket has been used for another payment gateway.")
244        now = datetime.utcnow()
245        if self.context.creation_date.tzinfo is not None:
246            # That's bad. Please store timezone-naive datetimes only!
247            now = self.context.creation_date.tzinfo.localize(now)
248        time_delta = now - self.context.creation_date
249        if time_delta.days > 7:
250            return _("This payment ticket is too old. Please create a new ticket.")
251        self.responseurl = self.url(self.context, 'request_payment_status')
252        resp = get_JSON_POST_response(
253            merchantId=self.merchantId,
254            serviceTypeId=self.serviceTypeId,
255            api_key=self.api_key,
256            orderId=self.orderId,
257            amount=self.amount,
258            responseurl=self.responseurl,
259            host=self.host,
260            url=self.init_url,
261            https=self.https,
262            fullname=self.context.__parent__.display_fullname,
263            email=self.context.__parent__.email,
264            lineitems=self.lineitems)
265        if resp.get('error'):
266            return resp.get('error')
267        if resp.get('statuscode') not in ('021', '025', '055'):
268            return 'RRR generation message from Remita: ' + resp.get('status')
269        self.rrr = self.context.r_pay_reference = resp['RRR'].rstrip()
270        hashargs =      self.merchantId + self.rrr + self.api_key
271        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
272        self.customer = self.context.__parent__
273        self.customer.writeLogMessage(self,
274            'RRR retrieved: %s, ServiceTypeId: %s'
275            % (self.rrr, self.serviceTypeId))
276        return
277
278    def update(self):
279        if not module_activated(
280            self.context.__parent__.__parent__.year, self.context):
281            return
282        self.orderId = self.context.p_id
283        error = self.init_update()
284        if error:
285            self.flash(error, type='danger')
286            self.redirect(self.url(self.context, '@@index'))
287            return
288        # Already now it becomes a Remita payment. We set the net amount
289        # and add the gateway amount.
290        if not self.context.r_company:
291            self.context.net_amt = self.context.amount_auth
292            self.context.amount_auth += self.gateway_amt
293            self.context.gateway_amt = self.gateway_amt
294            self.context.r_company = u'remita'
295        self.amount_auth = int(100 * self.context.amount_auth)
296        return
Note: See TracBrowser for help on using the repository browser.