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

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

Make selection of processors and exporters customizable.

  • Property svn:keywords set to Id
File size: 8.8 KB
Line 
1## $Id: utils.py 12283 2014-12-21 11:26:41Z 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 copy import deepcopy
25from random import SystemRandom as r
26from zope.i18n import translate
27from waeup.ikoba.interfaces import IIkobaUtils
28from waeup.ikoba.interfaces import MessageFactory as _
29from waeup.ikoba.smtp import send_mail as send_mail_internally
30from waeup.ikoba.utils.helpers import get_sorted_preferred
31from waeup.ikoba.customers.export import EXPORTER_NAMES as CUSTOMER_EXPORTER_NAMES
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    #: A function to return
101    @classmethod
102    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
103        return sorted_phone_prefixes(data, request)
104
105    CON_CATS_DICT = {
106        'sample': 'Sample Category',
107        'license': 'License',
108        'no': 'no contract',
109        }
110
111    EXAM_SUBJECTS_DICT = {
112        'math': 'Mathematics',
113        'computer_science': 'Computer Science',
114        }
115
116    #: Exam grades. The tuple is sorted as it should be displayed in
117    #: select boxes.
118    EXAM_GRADES = (
119        ('A', 'Best'),
120        ('B', 'Better'),
121        ('C', 'Good'),
122        )
123
124    PAYMENT_CATEGORIES = {
125        'license': 'License Fee',
126        }
127
128    #: Set positive number for allowed max, negative for required min
129    #: avail.
130    #:
131    #: Use integer for bytes value, float for percent
132    #: value. `cpu-load`, of course, accepts float values only.
133    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
134    #: `cpu-load` = CPU load in percent.
135    SYSTEM_MAX_LOAD = {
136        'swap-mem': None,
137        'virt-mem': None,
138        'cpu-load': 100.0,
139        }
140
141    EXPORTER_NAMES = CUSTOMER_EXPORTER_NAMES + (
142        'pdfdocuments',
143        'htmldocuments',
144        'users',
145        'products')
146
147    BATCH_PROCESSOR_NAMES = (
148        'customerprocessor',
149        'customersampledocumentprocessor',
150        'samplecontractprocessor',
151        'productprocessor',
152        'pdfdocumentprocessor',
153        'htmldocumentprocessor',
154        'userprocessor')
155
156    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
157                        from_username, usertype, portal, body, subject):
158        """Send an email with data provided by forms.
159        """
160        config = grok.getSite()['configuration']
161        text = _(u"""Fullname: ${a}
162User Id: ${b}
163User Type: ${c}
164Portal: ${d}
165
166${e}
167""")
168        text = _(text, mapping={
169            'a': from_name,
170            'b': from_username,
171            'c': usertype,
172            'd': portal,
173            'e': body})
174        body = translate(text, 'waeup.ikoba',
175            target_language=self.PORTAL_LANGUAGE)
176        if not (from_addr and rcpt_addr):
177            return False
178        return send_mail(
179            from_name, from_addr, rcpt_name, rcpt_addr,
180            subject, body, config)
181
182    @property
183    def tzinfo(self):
184        # For Nigeria: pytz.timezone('Africa/Lagos')
185        # For Germany: pytz.timezone('Europe/Berlin')
186        return pytz.utc
187
188    def fullname(self, firstname, lastname, middlename=None):
189        """Full name constructor.
190        """
191        # We do not necessarily have the middlename attribute
192        if middlename:
193            name = '%s %s %s' % (firstname, middlename, lastname)
194        else:
195            name = '%s %s' % (firstname, lastname)
196        return string.capwords(
197            name.replace('-', ' - ')).replace(' - ', '-')
198
199    def genPassword(self, length=8, chars=string.letters + string.digits):
200        """Generate a random password.
201        """
202        return ''.join([r().choice(chars) for i in range(length)])
203
204    def sendCredentials(self, user, password=None, url_info=None, msg=None):
205        """Send credentials as email.
206
207        Input is the customer for which credentials are sent and the
208        password.
209
210        Returns True or False to indicate successful operation.
211        """
212        subject = 'Your Ikoba credentials'
213        text = _(u"""Dear ${a},
214
215${b}
216Registration and Application Portal of
217${c}.
218
219Your user name: ${d}
220Your password: ${e}
221${f}
222
223Please remember your user name and keep
224your password secret!
225
226Please also note that passwords are case-sensitive.
227
228Regards
229""")
230        config = grok.getSite()['configuration']
231        from_name = config.name_admin
232        from_addr = config.email_admin
233        rcpt_name = user.title
234        rcpt_addr = user.email
235        text = _(text, mapping={
236            'a': rcpt_name,
237            'b': msg,
238            'c': config.name,
239            'd': user.name,
240            'e': password,
241            'f': url_info})
242
243        body = translate(text, 'waeup.ikoba',
244            target_language=self.PORTAL_LANGUAGE)
245        return send_mail(
246            from_name, from_addr, rcpt_name, rcpt_addr,
247            subject, body, config)
248
249    def getPaymentItem(self, payment):
250        """Return payment item.
251
252        This method can be used to customize the display_item property method.
253        """
254        return payment.p_item
255
256    def expensive_actions_allowed(self, type=None, request=None):
257        """Tell, whether expensive actions are currently allowed.
258
259        Check system load/health (or other external circumstances) and
260        locally set values to see, whether expensive actions should be
261        allowed (`True`) or better avoided (`False`).
262
263        Use this to allow or forbid exports, report generations, or
264        similar actions.
265        """
266        max_values = self.SYSTEM_MAX_LOAD
267        for (key, func) in (
268            ('swap-mem', psutil.swap_memory),
269            ('virt-mem', psutil.virtual_memory),
270            ):
271            max_val = max_values.get(key, None)
272            if max_val is None:
273                continue
274            mem_val = func()
275            if isinstance(max_val, float):
276                # percents
277                if max_val < 0.0:
278                    max_val = 100.0 + max_val
279                if mem_val.percent > max_val:
280                    return False
281            else:
282                # number of bytes
283                if max_val < 0:
284                    max_val = mem_val.total + max_val
285                if mem_val.used > max_val:
286                    return False
287        return True
Note: See TracBrowser for help on using the repository browser.