views.py
author Nicolas Chauvat <nicolas.chauvat@logilab.fr>
Wed, 23 Jun 2010 19:17:20 +0200
changeset 3 b81e32bb48d6
parent 2 80232b459741
child 5 1e1831e8ba3c
permissions -rw-r--r--
receive and acknowledge server's response

# copyright 2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.

"""cubicweb-cmcicpay views/forms/actions/components for web ui"""

import os

from cubicweb import ValidationError
from cubicweb.web import controller
from cubicweb.selectors import match_user_groups
from cubicweb.view import StartupView
from cubicweb.web.views.urlrewrite import SimpleReqRewriter, rgx

from cubes.cmcicpay import cmcic

# class CmcicController(controller.Controller):
#     __regid__ = 'cmcic'

#     def publish(self, rset=None):
#         self.w(u'<h1>CM-CIC p@iement</h1>')
#         tpe = cmcic.get_tpe(self._cw)
#         self.w(u'<table>')
#         for attr in ['numero','version','code_societe','url_paiement','url_ok','url_ko']:
#             self.w(u'<tr><td>%s</td><td>%s</td></tr>' % (attr, getattr(tpe, attr)))
#         self.w(u'</table>')
#         self.w(repr(self._cw.form))


def get_tpe(_cw):
    return cmcic.get_tpe(os.path.join(_cw.vreg.config.apphome,'tpe'))

## urls

class ConfRewrite(SimpleReqRewriter):
    rules = [
        (rgx('/cmcic'), dict(vid='cmcic')),
        (rgx('/cmcic_info'), dict(vid='cmcic_info')),
        ]
## views

# make this a controller ? XXX
class CmcicView(StartupView):
    __regid__ = 'cmcic'
    templatable = False
    content_type = 'text/plain'

    def call(self):
        #print "Pragma: no-cache'
        tpe = get_tpe(self._cw)
        params = dict(self._cw.form)
        del params['vid']
        rep = tpe.read_paymentresponse(params)
        msg, mac = tpe.paymentresponse_msg(rep)
        if tpe.is_valid_msg(msg, mac):
            if rep.return_code == "Annulation":
                # Payment has been refused
                # The payment may be accepted later
                # put your code here (email sending / Database update)
                print 'cmcic', rep.reference, rep.return_code
                ack = 0

            elif rep.return_code in ("payetest", "paiement"):
                # Payment has been accepeted on the productive server
                # put your code here (email sending / Database update)
                print 'cmcic', rep.reference, rep.return_code
                comment = u'payed by %(brand)s on %(date)s, auth %(numauto)s' % rep.as_dict()
                try:
                    self._cw.session.cnx._repo.shopcart_checkout(rep.reference, comment)
                    ack = 0
                except ValidationError, exc:
                    ack = 1

            #*** ONLY FOR MULTIPART PAYMENT ***#
            elif rep.return_code.startswith("paiement_pf"):
                # Payment has been accepted on the productive server for the part #N
                # return code is like paiement_pf[#N]
                # put your code here (email sending / Database update)
                # You have the amount of the payment part in Rpeification['montantech']
                print 'cmcic', rep.reference, rep.return_code
                ack = 1

            elif rep.return_code.startswith("Annulation_pf"):
                # Payment has been refused on the productive server for the part #N
                # return code is like Annulation_pf[#N]
                # put your code here (email sending / Database update)
                # You have the amount of the payment part in Repification['montantech']
                print 'cmcic', rep.reference, rep.return_code
                ack = 1
        else:
            print "cmcic: the HMAC doesn't match."
            ack = 1 #\n" + mac
        self.w(u'version=%s\ncdr=%s' % (tpe.version, ack))

class CmcicInfoView(StartupView):
    __regid__ = 'cmcic_info'
    title = _('CMCIC paiement')
    __select__ = StartupView.__select__ & match_user_groups('managers')

    def call(self):
        self.w(u'<h1>CM-CIC p@iement</h1>')
        tpe = get_tpe(self._cw)
        self.w(u'<table>')
        for attr in ['numero','version','code_societe','url_paiement','url_ok','url_ko']:
            self.w(u'<tr><td>%s</td><td>%s</td></tr>' % (attr, getattr(tpe, attr)))
        self.w(u'</table>')

# handle callback from payment server

from cubicweb.server.repository import Repository
from logilab.common.decorators import monkeypatch

@monkeypatch(Repository)
def shopcart_checkout(self, eid, comment):
    session = self.internal_session()
    try:
        cart = session.entity_from_eid(eid)
        cart.fire_transition('check out', comment=comment)
        session.commit()
    finally:
        session.close()