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

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

Reapply psutil deprecation patch from waeup.kofa.

  • Property svn:keywords set to Id
File size: 10.1 KB
Line 
1## $Id: utils.py 11970 2014-11-16 13:21:27Z 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"""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
31
32
33def send_mail(from_name, from_addr,
34              rcpt_name, rcpt_addr,
35              subject, body, config):
36    """Wrapper for the real SMTP functionality in :mod:`waeup.ikoba.smtp`.
37
38    Merely here to stay compatible with lots of calls to this place.
39    """
40    mail_id = send_mail_internally(
41        from_name, from_addr, rcpt_name, rcpt_addr,
42        subject, body, config)
43    return True
44
45
46#: A list of phone prefixes (order num, country, prefix).
47#: Items with same order num will be sorted alphabetically.
48#: The lower the order num, the higher the precedence.
49INT_PHONE_PREFIXES = [
50    (99, _('Germany'), '49'),
51    (1, _('Nigeria'), '234'),
52    (99, _('U.S.'), '1'),
53    ]
54
55
56def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
57    """Sorted tuples of phone prefixes.
58
59    Ordered as shown above and formatted for use in select boxes.
60
61    If request is given, we'll try to translate all country names in
62    order to sort alphabetically correctly.
63
64    XXX: This is a function (and not a constant) as different
65    languages might give different orders. This is not tested yet.
66
67    XXX: If we really want to use alphabetic ordering here, we might
68    think about caching results of translations.
69    """
70    if request is not None:
71        data = [
72            (x, translate(y, context=request), z)
73            for x, y, z in data]
74    return tuple([
75        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
76        for x in sorted(data)
77        ])
78
79
80class IkobaUtils(grok.GlobalUtility):
81    """A collection of parameters and methods subject to customization.
82
83    """
84    grok.implements(IIkobaUtils)
85    # This the only place where we define the portal language
86    # which is used for the translation of system messages
87    # (e.g. object histories).
88    PORTAL_LANGUAGE = 'en'
89
90    PREFERRED_LANGUAGES_DICT = {
91        'en': (1, u'English'),
92        'fr': (2, u'Français'),
93        'de': (3, u'Deutsch'),
94        'ha': (4, u'Hausa'),
95        'yo': (5, u'Yoruba'),
96        'ig': (6, u'Igbo'),
97        }
98
99    #: A function to return
100    @classmethod
101    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
102        return sorted_phone_prefixes(data, request)
103
104    EXAM_SUBJECTS_DICT = {
105        'math': 'Mathematics',
106        'computer_science': 'Computer Science',
107        }
108
109    #: Exam grades. The tuple is sorted as it should be displayed in
110    #: select boxes.
111    EXAM_GRADES = (
112        ('A', 'Best'),
113        ('B', 'Better'),
114        ('C', 'Good'),
115        )
116
117    INST_TYPES_DICT = {
118        'none': '',
119        'faculty': 'Faculty of',
120        'department': 'Department of',
121        'school': 'School of',
122        'office': 'Office for',
123        'centre': 'Centre for',
124        'institute': 'Institute of',
125        'school_for': 'School for',
126        'college': 'College of',
127        'directorate': 'Directorate of',
128        }
129
130    STUDY_MODES_DICT = {
131        'transfer': 'Transfer',
132        'ug_ft': 'Undergraduate Full-Time',
133        'ug_pt': 'Undergraduate Part-Time',
134        'pg_ft': 'Postgraduate Full-Time',
135        'pg_pt': 'Postgraduate Part-Time',
136        }
137
138    APP_CATS_DICT = {
139        'basic': 'Basic Application',
140        'no': 'no application',
141        'pg': 'Postgraduate',
142        'sandwich': 'Sandwich',
143        'cest': 'Part-Time, Diploma, Certificate'
144        }
145
146    SEMESTER_DICT = {
147        1: '1st Semester',
148        2: '2nd Semester',
149        3: 'Combined',
150        9: 'N/A'
151        }
152
153    SPECIAL_HANDLING_DICT = {
154        'regular': 'Regular Hostel',
155        'blocked': 'Blocked Hostel',
156        'pg': 'Postgraduate Hostel'
157        }
158
159    SPECIAL_APP_DICT = {
160        'transcript': 'Transcript Fee Payment',
161        'clearance': 'Acceptance Fee',
162        }
163
164    PAYMENT_CATEGORIES = {
165        'schoolfee': 'School Fee',
166        'clearance': 'Acceptance Fee',
167        'bed_allocation': 'Bed Allocation Fee',
168        'hostel_maintenance': 'Hostel Maintenance Fee',
169        'transfer': 'Transfer Fee',
170        'gown': 'Gown Hire Fee',
171        'application': 'Application Fee',
172        'transcript': 'Transcript Fee',
173        }
174
175    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
176
177    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
178
179    BALANCE_PAYMENT_CATEGORIES = {
180        'schoolfee': 'School Fee',
181        }
182
183    MODE_GROUPS = {
184        'All': ('all',),
185        'Undergraduate Full-Time': ('ug_ft',),
186        'Undergraduate Part-Time': ('ug_pt',),
187        'Postgraduate Full-Time': ('pg_ft',),
188        'Postgraduate Part-Time': ('pg_pt',),
189        }
190
191    #: Set positive number for allowed max, negative for required min
192    #: avail.
193    #:
194    #: Use integer for bytes value, float for percent
195    #: value. `cpu-load`, of course, accepts float values only.
196    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
197    #: `cpu-load` = CPU load in percent.
198    SYSTEM_MAX_LOAD = {
199        'swap-mem': None,
200        'virt-mem': None,
201        'cpu-load': 100.0,
202        }
203
204    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
205                        from_username, usertype, portal, body, subject):
206        """Send an email with data provided by forms.
207        """
208        config = grok.getSite()['configuration']
209        text = _(u"""Fullname: ${a}
210User Id: ${b}
211User Type: ${c}
212Portal: ${d}
213
214${e}
215""")
216        text = _(text, mapping={
217            'a': from_name,
218            'b': from_username,
219            'c': usertype,
220            'd': portal,
221            'e': body})
222        body = translate(text, 'waeup.ikoba',
223            target_language=self.PORTAL_LANGUAGE)
224        if not (from_addr and rcpt_addr):
225            return False
226        return send_mail(
227            from_name, from_addr, rcpt_name, rcpt_addr,
228            subject, body, config)
229
230    @property
231    def tzinfo(self):
232        # For Nigeria: pytz.timezone('Africa/Lagos')
233        # For Germany: pytz.timezone('Europe/Berlin')
234        return pytz.utc
235
236    def fullname(self, firstname, lastname, middlename=None):
237        """Full name constructor.
238        """
239        # We do not necessarily have the middlename attribute
240        if middlename:
241            name = '%s %s %s' % (firstname, middlename, lastname)
242        else:
243            name = '%s %s' % (firstname, lastname)
244        return string.capwords(
245            name.replace('-', ' - ')).replace(' - ', '-')
246
247    def genPassword(self, length=8, chars=string.letters + string.digits):
248        """Generate a random password.
249        """
250        return ''.join([r().choice(chars) for i in range(length)])
251
252    def sendCredentials(self, user, password=None, url_info=None, msg=None):
253        """Send credentials as email.
254
255        Input is the customer for which credentials are sent and the
256        password.
257
258        Returns True or False to indicate successful operation.
259        """
260        subject = 'Your Ikoba credentials'
261        text = _(u"""Dear ${a},
262
263${b}
264Application and Registration Portal of
265${c}.
266
267Your user name: ${d}
268Your password: ${e}
269${f}
270
271Please remember your user name and keep
272your password secret!
273
274Please also note that passwords are case-sensitive.
275
276Regards
277""")
278        config = grok.getSite()['configuration']
279        from_name = config.name_admin
280        from_addr = config.email_admin
281        rcpt_name = user.title
282        rcpt_addr = user.email
283        text = _(text, mapping={
284            'a': rcpt_name,
285            'b': msg,
286            'c': config.name,
287            'd': user.name,
288            'e': password,
289            'f': url_info})
290
291        body = translate(text, 'waeup.ikoba',
292            target_language=self.PORTAL_LANGUAGE)
293        return send_mail(
294            from_name, from_addr, rcpt_name, rcpt_addr,
295            subject, body, config)
296
297    def getPaymentItem(self, payment):
298        """Return payment item.
299
300        This method can be used to customize the display_item property method.
301        """
302        return payment.p_item
303
304    def expensive_actions_allowed(self, type=None, request=None):
305        """Tell, whether expensive actions are currently allowed.
306
307        Check system load/health (or other external circumstances) and
308        locally set values to see, whether expensive actions should be
309        allowed (`True`) or better avoided (`False`).
310
311        Use this to allow or forbid exports, report generations, or
312        similar actions.
313        """
314        max_values = self.SYSTEM_MAX_LOAD
315        for (key, func) in (
316            ('swap-mem', psutil.swap_memory),
317            ('virt-mem', psutil.virtual_memory),
318            ):
319            max_val = max_values.get(key, None)
320            if max_val is None:
321                continue
322            mem_val = func()
323            if isinstance(max_val, float):
324                # percents
325                if max_val < 0.0:
326                    max_val = 100.0 + max_val
327                if mem_val.percent > max_val:
328                    return False
329            else:
330                # number of bytes
331                if max_val < 0:
332                    max_val = mem_val.total + max_val
333                if mem_val.used > max_val:
334                    return False
335        return True
Note: See TracBrowser for help on using the repository browser.