source: main/waeup.ikoba/branches/uli-payments/src/waeup/ikoba/utils/utils.py @ 12688

Last change on this file since 12688 was 12553, checked in by Henrik Bettermann, 10 years ago

Notify customer by email after customer and contract transitions.

  • Property svn:keywords set to Id
File size: 10.2 KB
Line 
1## $Id: utils.py 12553 2015-02-03 16:54:56Z henrik $
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"""General helper utilities for Ikoba.
19"""
20import grok
21import psutil
22import string
23import pytz
24from random import SystemRandom as r
25from zope.i18n import translate
26from waeup.ikoba.interfaces import IIkobaUtils
27from waeup.ikoba.interfaces import MessageFactory as _
28from waeup.ikoba.smtp import send_mail as send_mail_internally
29from waeup.ikoba.utils.helpers import (
30    get_sorted_preferred, get_current_principal)
31from waeup.ikoba.payments.currencies import ISO_4217_CURRENCIES
32
33
34def send_mail(from_name, from_addr,
35              rcpt_name, rcpt_addr,
36              subject, body, config):
37    """Wrapper for the real SMTP functionality in :mod:`waeup.ikoba.smtp`.
38
39    Merely here to stay compatible with lots of calls to this place.
40    """
41    mail_id = send_mail_internally(
42        from_name, from_addr, rcpt_name, rcpt_addr,
43        subject, body, config)
44    return True
45
46
47#: A list of phone prefixes (order num, country, prefix).
48#: Items with same order num will be sorted alphabetically.
49#: The lower the order num, the higher the precedence.
50INT_PHONE_PREFIXES = [
51    (99, _('Germany'), '49'),
52    (1, _('Nigeria'), '234'),
53    (99, _('U.S.'), '1'),
54    ]
55
56
57def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
58    """Sorted tuples of phone prefixes.
59
60    Ordered as shown above and formatted for use in select boxes.
61
62    If request is given, we'll try to translate all country names in
63    order to sort alphabetically correctly.
64
65    XXX: This is a function (and not a constant) as different
66    languages might give different orders. This is not tested yet.
67
68    XXX: If we really want to use alphabetic ordering here, we might
69    think about caching results of translations.
70    """
71    if request is not None:
72        data = [
73            (x, translate(y, context=request), z)
74            for x, y, z in data]
75    return tuple([
76        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
77        for x in sorted(data)
78        ])
79
80
81class IkobaUtils(grok.GlobalUtility):
82    """A collection of parameters and methods subject to customization.
83
84    """
85    grok.implements(IIkobaUtils)
86    # This the only place where we define the portal language
87    # which is used for the translation of system messages
88    # (e.g. object histories).
89    PORTAL_LANGUAGE = 'en'
90
91    PREFERRED_LANGUAGES_DICT = {
92        'en': (1, u'English'),
93        'fr': (2, u'Français'),
94        'de': (3, u'Deutsch'),
95        'ha': (4, u'Hausa'),
96        'yo': (5, u'Yoruba'),
97        'ig': (6, u'Igbo'),
98        }
99
100    # CURRENCIES must be equal to or an excerpt of ISO_4217_CURRENCIES
101    CURRENCIES = ISO_4217_CURRENCIES
102
103    #: A function to return
104    @classmethod
105    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
106        return sorted_phone_prefixes(data, request)
107
108    CON_CATS_DICT = {
109        'sample': 'Sample Category',
110        'license': 'License',
111        'no': _('no contract'),
112        }
113
114    PAYMENT_CATEGORIES = {
115        'license': 'License Fee',
116        }
117
118    #: Set positive number for allowed max, negative for required min
119    #: avail.
120    #:
121    #: Use integer for bytes value, float for percent
122    #: value. `cpu-load`, of course, accepts float values only.
123    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
124    #: `cpu-load` = CPU load in percent.
125    SYSTEM_MAX_LOAD = {
126        'swap-mem': None,
127        'virt-mem': None,
128        'cpu-load': 100.0,
129        }
130
131    EXPORTER_NAMES = (
132        'pdfdocuments',
133        'htmldocuments',
134        'restdocuments',
135        'users',
136        'products',
137        'customers',
138        'customersampledocuments',
139        'samplecontracts')
140
141    BATCH_PROCESSOR_NAMES = (
142        'customerprocessor',
143        'customersampledocumentprocessor',
144        'samplecontractprocessor',
145        'productprocessor',
146        'pdfdocumentprocessor',
147        'htmldocumentprocessor',
148        'restdocumentprocessor',
149        'userprocessor')
150
151    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
152                        from_username, usertype, portal, body, subject):
153        """Send an email with data provided by forms.
154        """
155        config = grok.getSite()['configuration']
156        text = _(u"""Fullname: ${a}
157User Id: ${b}
158User Type: ${c}
159Portal: ${d}
160
161${e}
162""")
163        text = _(text, mapping={
164            'a': from_name,
165            'b': from_username,
166            'c': usertype,
167            'd': portal,
168            'e': body})
169        body = translate(text, 'waeup.ikoba',
170            target_language=self.PORTAL_LANGUAGE)
171        if not (from_addr and rcpt_addr):
172            return False
173        return send_mail(
174            from_name, from_addr, rcpt_name, rcpt_addr,
175            subject, body, config)
176
177    @property
178    def tzinfo(self):
179        # For Nigeria: pytz.timezone('Africa/Lagos')
180        # For Germany: pytz.timezone('Europe/Berlin')
181        return pytz.utc
182
183    def fullname(self, firstname, lastname, middlename=None):
184        """Full name constructor.
185        """
186        # We do not necessarily have the middlename attribute
187        if middlename:
188            name = '%s %s %s' % (firstname, middlename, lastname)
189        else:
190            name = '%s %s' % (firstname, lastname)
191        return string.capwords(
192            name.replace('-', ' - ')).replace(' - ', '-')
193
194    def genPassword(self, length=8, chars=string.letters + string.digits):
195        """Generate a random password.
196        """
197        return ''.join([r().choice(chars) for i in range(length)])
198
199    def sendCredentials(self, user, password=None, url_info=None, msg=None):
200        """Send credentials as email.
201
202        Input is the customer for which credentials are sent and the
203        password.
204
205        Returns True or False to indicate successful operation.
206        """
207        subject = 'Your Ikoba credentials'
208        text = _(u"""Dear ${a},
209
210${b}
211Registration and Application Portal of
212${c}.
213
214Your user name: ${d}
215Your password: ${e}
216${f}
217
218Please remember your user name and keep
219your password secret!
220
221Please also note that passwords are case-sensitive.
222
223Regards
224""")
225        config = grok.getSite()['configuration']
226        from_name = config.name_admin
227        from_addr = config.email_admin
228        rcpt_name = user.title
229        rcpt_addr = user.email
230        text = _(text, mapping={
231            'a': rcpt_name,
232            'b': msg,
233            'c': config.name,
234            'd': user.name,
235            'e': password,
236            'f': url_info})
237
238        body = translate(text, 'waeup.ikoba',
239            target_language=self.PORTAL_LANGUAGE)
240        return send_mail(
241            from_name, from_addr, rcpt_name, rcpt_addr,
242            subject, body, config)
243
244    def sendTransitionInfo(self, customer, obj, msg=None):
245        """Send transition information as email.
246
247        Input is the customer for which credentials are sent and the object
248        which was transitioned.
249
250        Returns True or False to indicate successful operation.
251        """
252        config = grok.getSite()['configuration']
253        if not config.email_notification:
254            return
255        subject = 'Ikoba status change information'
256        text = _(u"""Dear ${a},
257
258The status of the following object has been changed:
259
260Object Id: ${c}
261Title: ${d}
262Transition: ${e}
263New state: ${f}
264
265Regards,
266
267${b}
268
269--
270${g}
271""")
272        from_name = config.name_admin
273        from_addr = config.email_admin
274        rcpt_name = customer.title
275        rcpt_addr = customer.email
276
277        user = get_current_principal()
278        if user is None:
279            usertitle = 'system'
280        elif user.id == 'zope.anybody':
281            usertitle = 'Anonymous'
282        else:
283            usertitle = getattr(user, 'public_name', None)
284            if not usertitle:
285                usertitle = user.title
286
287        msg = translate(msg,'waeup.ikoba', target_language=self.PORTAL_LANGUAGE)
288        new_state = translate(obj.translated_state,'waeup.ikoba',
289            target_language=self.PORTAL_LANGUAGE)
290
291        text = _(text, mapping={
292            'a': rcpt_name,
293            'b': usertitle,
294            'c': obj.__name__,
295            'd': obj.title,
296            'e': msg.lower(),
297            'f': new_state,
298            'g': config.name})
299
300        body = translate(text, 'waeup.ikoba',
301            target_language=self.PORTAL_LANGUAGE)
302
303        return send_mail(
304            from_name, from_addr, rcpt_name, rcpt_addr,
305            subject, body, config)
306
307    def expensive_actions_allowed(self, type=None, request=None):
308        """Tell, whether expensive actions are currently allowed.
309
310        Check system load/health (or other external circumstances) and
311        locally set values to see, whether expensive actions should be
312        allowed (`True`) or better avoided (`False`).
313
314        Use this to allow or forbid exports, report generations, or
315        similar actions.
316        """
317        max_values = self.SYSTEM_MAX_LOAD
318        for (key, func) in (
319            ('swap-mem', psutil.swap_memory),
320            ('virt-mem', psutil.virtual_memory),
321            ):
322            max_val = max_values.get(key, None)
323            if max_val is None:
324                continue
325            mem_val = func()
326            if isinstance(max_val, float):
327                # percents
328                if max_val < 0.0:
329                    max_val = 100.0 + max_val
330                if mem_val.percent > max_val:
331                    return False
332            else:
333                # number of bytes
334                if max_val < 0:
335                    max_val = mem_val.total + max_val
336                if mem_val.used > max_val:
337                    return False
338        return True
Note: See TracBrowser for help on using the repository browser.