source: main/waeup.ikoba/trunk/src/waeup/ikoba/utils/utils.py @ 12703

Last change on this file since 12703 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
RevLine 
[7358]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##
[11949]18"""General helper utilities for Ikoba.
[7358]19"""
20import grok
[11815]21import psutil
[7365]22import string
[8181]23import pytz
24from random import SystemRandom as r
[7734]25from zope.i18n import translate
[11949]26from waeup.ikoba.interfaces import IIkobaUtils
27from waeup.ikoba.interfaces import MessageFactory as _
28from waeup.ikoba.smtp import send_mail as send_mail_internally
[12553]29from waeup.ikoba.utils.helpers import (
30    get_sorted_preferred, get_current_principal)
[12378]31from waeup.ikoba.payments.currencies import ISO_4217_CURRENCIES
[7358]32
[11814]33
34def send_mail(from_name, from_addr,
35              rcpt_name, rcpt_addr,
36              subject, body, config):
[11949]37    """Wrapper for the real SMTP functionality in :mod:`waeup.ikoba.smtp`.
[7382]38
[7471]39    Merely here to stay compatible with lots of calls to this place.
[7400]40    """
[7471]41    mail_id = send_mail_internally(
42        from_name, from_addr, rcpt_name, rcpt_addr,
43        subject, body, config)
[7399]44    return True
45
[11814]46
[7874]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'),
[11814]52    (1, _('Nigeria'), '234'),
[7874]53    (99, _('U.S.'), '1'),
54    ]
55
[11814]56
57def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
[7874]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([
[11814]76        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
[7874]77        for x in sorted(data)
78        ])
79
[11814]80
[11949]81class IkobaUtils(grok.GlobalUtility):
[7678]82    """A collection of parameters and methods subject to customization.
[7829]83
[7358]84    """
[11949]85    grok.implements(IIkobaUtils)
[7678]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).
[7744]89    PORTAL_LANGUAGE = 'en'
[7358]90
[7701]91    PREFERRED_LANGUAGES_DICT = {
[11814]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'),
[7701]98        }
99
[12378]100    # CURRENCIES must be equal to or an excerpt of ISO_4217_CURRENCIES
101    CURRENCIES = ISO_4217_CURRENCIES
102
[7874]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)
[7871]107
[12098]108    CON_CATS_DICT = {
[12092]109        'sample': 'Sample Category',
[12078]110        'license': 'License',
[12545]111        'no': _('no contract'),
[12078]112        }
113
[9405]114    PAYMENT_CATEGORIES = {
[11981]115        'license': 'License Fee',
[9405]116        }
117
[11800]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,
[12060]124    #: `cpu-load` = CPU load in percent.
[11800]125    SYSTEM_MAX_LOAD = {
126        'swap-mem': None,
127        'virt-mem': None,
128        'cpu-load': 100.0,
129        }
130
[12297]131    EXPORTER_NAMES = (
[12283]132        'pdfdocuments',
133        'htmldocuments',
[12410]134        'restdocuments',
[12283]135        'users',
[12297]136        'products',
137        'customers',
138        'customersampledocuments',
139        'samplecontracts')
[12283]140
141    BATCH_PROCESSOR_NAMES = (
142        'customerprocessor',
143        'customersampledocumentprocessor',
144        'samplecontractprocessor',
145        'productprocessor',
146        'pdfdocumentprocessor',
147        'htmldocumentprocessor',
[12410]148        'restdocumentprocessor',
[12283]149        'userprocessor')
150
[11814]151    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
152                        from_username, usertype, portal, body, subject):
[7358]153        """Send an email with data provided by forms.
154        """
155        config = grok.getSite()['configuration']
[7734]156        text = _(u"""Fullname: ${a}
157User Id: ${b}
158User Type: ${c}
159Portal: ${d}
[7358]160
[7734]161${e}
162""")
[11814]163        text = _(text, mapping={
164            'a': from_name,
165            'b': from_username,
166            'c': usertype,
167            'd': portal,
168            'e': body})
[11949]169        body = translate(text, 'waeup.ikoba',
[7734]170            target_language=self.PORTAL_LANGUAGE)
[8436]171        if not (from_addr and rcpt_addr):
172            return False
[7400]173        return send_mail(
[11814]174            from_name, from_addr, rcpt_name, rcpt_addr,
175            subject, body, config)
[7359]176
[8181]177    @property
178    def tzinfo(self):
179        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]180        # For Germany: pytz.timezone('Europe/Berlin')
[8181]181        return pytz.utc
182
[11814]183    def fullname(self, firstname, lastname, middlename=None):
[7477]184        """Full name constructor.
185        """
[7359]186        # We do not necessarily have the middlename attribute
187        if middlename:
[8603]188            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]189        else:
[8603]190            name = '%s %s' % (firstname, lastname)
[11814]191        return string.capwords(
192            name.replace('-', ' - ')).replace(' - ', '-')
[7365]193
194    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]195        """Generate a random password.
196        """
[7365]197        return ''.join([r().choice(chars) for i in range(length)])
198
[8853]199    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[7399]200        """Send credentials as email.
201
[11947]202        Input is the customer for which credentials are sent and the
[7399]203        password.
204
205        Returns True or False to indicate successful operation.
[7365]206        """
[11949]207        subject = 'Your Ikoba credentials'
[7734]208        text = _(u"""Dear ${a},
[7365]209
[7734]210${b}
[12192]211Registration and Application Portal of
[7734]212${c}.
[7365]213
[7734]214Your user name: ${d}
215Your password: ${e}
[8853]216${f}
[7365]217
218Please remember your user name and keep
219your password secret!
220
[7382]221Please also note that passwords are case-sensitive.
222
[7365]223Regards
[7734]224""")
[7399]225        config = grok.getSite()['configuration']
226        from_name = config.name_admin
[7402]227        from_addr = config.email_admin
[7407]228        rcpt_name = user.title
229        rcpt_addr = user.email
[11814]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})
[7734]237
[11949]238        body = translate(text, 'waeup.ikoba',
[7734]239            target_language=self.PORTAL_LANGUAGE)
[7399]240        return send_mail(
[11814]241            from_name, from_addr, rcpt_name, rcpt_addr,
242            subject, body, config)
[9987]243
[12553]244    def sendTransitionInfo(self, customer, obj, msg=None):
245        """Send transition information as email.
[9987]246
[12553]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.
[9987]251        """
[12553]252        config = grok.getSite()['configuration']
253        if not config.email_notification:
254            return
255        subject = 'Ikoba status change information'
256        text = _(u"""Dear ${a},
[11815]257
[12553]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
[11815]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
[11816]318        for (key, func) in (
319            ('swap-mem', psutil.swap_memory),
[11818]320            ('virt-mem', psutil.virtual_memory),
[11816]321            ):
322            max_val = max_values.get(key, None)
323            if max_val is None:
324                continue
325            mem_val = func()
[11815]326            if isinstance(max_val, float):
[11816]327                # percents
[11821]328                if max_val < 0.0:
329                    max_val = 100.0 + max_val
[11816]330                if mem_val.percent > max_val:
[11815]331                    return False
332            else:
[11816]333                # number of bytes
[11821]334                if max_val < 0:
335                    max_val = mem_val.total + max_val
[11816]336                if mem_val.used > max_val:
[11815]337                    return False
338        return True
Note: See TracBrowser for help on using the repository browser.