source: main/waeup.ikoba/branches/uli-payments/src/waeup/ikoba/payments/payment.py @ 12696

Last change on this file since 12696 was 12696, checked in by uli, 10 years ago

payment item transformer.

  • Property svn:keywords set to Id
File size: 4.9 KB
Line 
1## $Id: payment.py 12696 2015-03-09 00:53:07Z uli $
2##
3## Copyright (C) 2011 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"""
19These are the payment tickets.
20"""
21import decimal
22import grok
23import uuid
24from datetime import datetime
25from zope.component import getUtilitiesFor
26from zope.event import notify
27from waeup.ikoba.interfaces import MessageFactory as _
28from waeup.ikoba.utils.helpers import attrs_to_fields
29from waeup.ikoba.utils.logger import Logger
30from waeup.ikoba.payments.interfaces import (
31    IPayment, STATE_UNPAID, STATE_FAILED, STATE_PAID,
32    IPaymentGatewayService, IPayer, IPaymentItem, IPayee,
33    IPaymentGatewayServicesLister,
34    )
35
36
37def format_payment_item_values(payment_item_values, currency):
38    """Format tuples (description, currency, amount) for output.
39
40    `currency` passed in is the 'target' currency.
41
42    Returns a list of formated values. Last item is total sum.
43    XXX: we do not really respect currency. If different items
44         have different currencies, we are choked.
45    """
46    result = []
47    total = decimal.Decimal("0.00")
48    for descr, item_currency, amount in payment_item_values:
49        total += amount
50        if item_currency != currency:
51            raise ValueError(
52                "Different currencies in payment items not supported.")
53        result.append((descr, '%s %0.2f' % (item_currency, amount)))
54    result.append((_('Total'), '%s %0.2f' % (currency, total)))
55    return result
56
57
58def get_payment_providers():
59    """Get all payment providers registered.
60    """
61    return dict(
62        getUtilitiesFor(IPaymentGatewayService)
63    )
64
65
66class PaymentGatewayServicesLister(grok.GlobalUtility):
67    grok.implements(IPaymentGatewayServicesLister)
68
69    def __call__(self):
70        """Get all services of payment gateways registered.
71        """
72        return get_payment_providers()
73
74
75class PaymentProviderServiceBase(grok.GlobalUtility):
76
77    grok.baseclass()
78    grok.implements(IPaymentGatewayService)
79
80    title = u'Sample Credit Card Service'
81
82
83@attrs_to_fields
84class Payment(grok.Container, Logger):
85    """This is a payment.
86    """
87    grok.implements(IPayment)
88    grok.provides(IPayment)
89
90    logger_name = 'waeup.ikoba.${sitename}.payments'
91    logger_filename = 'payments.log'
92    logger_format_str = '"%(asctime)s","%(user)s",%(message)s'
93
94    @property
95    def amount(self):
96        """The amount of a payment.
97
98        Equals the sum of items contained.
99        """
100        return sum(
101            [item.amount for item in self.values()],
102            decimal.Decimal("0.00")  # default value
103        )
104
105    def __init__(self):
106        super(Payment, self).__init__()
107        self.creation_date = datetime.utcnow()
108        self.payment_date = None
109        self.payment_id = u'PAY_' + unicode(uuid.uuid4().hex)
110        self.state = STATE_UNPAID
111        return
112
113    def approve(self, payment_date=None):
114        """A payment was approved.
115
116        Successful ending; the payment is marked as payed.
117
118        If `payment_date` is given, it must be a datetime object
119        giving a datetime in UTC timezone.
120
121        Raises ObjectModifiedEvent.
122        """
123        if payment_date is None:
124            payment_date = datetime.utcnow()
125        self.payment_date = payment_date
126        self.state = STATE_PAID
127        notify(grok.ObjectModifiedEvent(self))
128
129    def mark_failed(self, reason=None):
130        """Mark payment as failed.
131
132        Raises ObjectModifiedEvent.
133        """
134        self.state = STATE_FAILED
135        notify(grok.ObjectModifiedEvent(self))
136
137    def add_payment_item(self, item):
138        """Add `item`
139
140        Returns the key under which the `item` was stored. Please do
141        not make anby assumptions about the key. It will be a
142        string. That is all we can tell.
143
144        """
145        cnt = 0
146        while str(cnt) in self:
147            cnt += 1
148        self[str(cnt)] = item
149        return str(cnt)
150
151
152@attrs_to_fields
153class Payer(object):
154    """A Payment is for testing.
155
156    It cannot be stored in ZODB.
157    """
158    grok.implements(IPayer)
159
160
161@attrs_to_fields
162class PaymentItem(grok.Model):
163
164    grok.implements(IPaymentItem)
165
166    def __init__(self):
167        super(PaymentItem, self).__init__()
168
169
170@attrs_to_fields
171class Payee(object):
172    """Someone being paid.
173
174    This is for testing only and cannot be stored in ZODB.
175    """
176    grok.implements(IPayee)
Note: See TracBrowser for help on using the repository browser.