source: main/waeup.kofa/trunk/src/waeup/kofa/utils/utils.py @ 13100

Last change on this file since 13100 was 13031, checked in by Henrik Bettermann, 9 years ago

Implement session-specific course registration deadline and
late registration payment.

  • Property svn:keywords set to Id
File size: 10.5 KB
Line 
1## $Id: utils.py 13031 2015-06-04 14:21:23Z 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 Kofa.
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.kofa.interfaces import IKofaUtils
28from waeup.kofa.interfaces import MessageFactory as _
29from waeup.kofa.smtp import send_mail as send_mail_internally
30from waeup.kofa.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.kofa.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 KofaUtils(grok.GlobalUtility):
81    """A collection of parameters and methods subject to customization.
82
83    """
84    grok.implements(IKofaUtils)
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    DISABLE_PAYMENT_GROUP_DICT = {
139        'sf_all': 'School Fee - All Students',
140        }
141
142    APP_CATS_DICT = {
143        'basic': 'Basic Application',
144        'no': 'no application',
145        'pg': 'Postgraduate',
146        'sandwich': 'Sandwich',
147        'cest': 'Part-Time, Diploma, Certificate'
148        }
149
150    SEMESTER_DICT = {
151        1: '1st Semester',
152        2: '2nd Semester',
153        3: 'Combined',
154        9: 'N/A'
155        }
156
157    SPECIAL_HANDLING_DICT = {
158        'regular': 'Regular Hostel',
159        'blocked': 'Blocked Hostel',
160        'pg': 'Postgraduate Hostel'
161        }
162
163    SPECIAL_APP_DICT = {
164        'transcript': 'Transcript Fee Payment',
165        'clearance': 'Acceptance Fee',
166        }
167
168    PAYMENT_CATEGORIES = {
169        'schoolfee': 'School Fee',
170        'clearance': 'Acceptance Fee',
171        'bed_allocation': 'Bed Allocation Fee',
172        'hostel_maintenance': 'Hostel Maintenance Fee',
173        'transfer': 'Transfer Fee',
174        'gown': 'Gown Hire Fee',
175        'application': 'Application Fee',
176        'transcript': 'Transcript Fee',
177        'late_registration': 'Late Course Registration Fee'
178        }
179
180    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
181
182    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
183
184    REPORTABLE_PAYMENT_CATEGORIES = {
185        'schoolfee': 'School Fee',
186        'clearance': 'Acceptance Fee',
187        'hostel_maintenance': 'Hostel Maintenance Fee',
188        'gown': 'Gown Hire Fee',
189        }
190
191    BALANCE_PAYMENT_CATEGORIES = {
192        'schoolfee': 'School Fee',
193        }
194
195    MODE_GROUPS = {
196        'All': ('all',),
197        'Undergraduate Full-Time': ('ug_ft',),
198        'Undergraduate Part-Time': ('ug_pt',),
199        'Postgraduate Full-Time': ('pg_ft',),
200        'Postgraduate Part-Time': ('pg_pt',),
201        }
202
203    #: Set positive number for allowed max, negative for required min
204    #: avail.
205    #:
206    #: Use integer for bytes value, float for percent
207    #: value. `cpu-load`, of course, accepts float values only.
208    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
209    #: `cpu-load` = CPU load in percent.
210    SYSTEM_MAX_LOAD = {
211        'swap-mem': None,
212        'virt-mem': None,
213        'cpu-load': 100.0,
214        }
215
216    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
217                        from_username, usertype, portal, body, subject):
218        """Send an email with data provided by forms.
219        """
220        config = grok.getSite()['configuration']
221        text = _(u"""Fullname: ${a}
222User Id: ${b}
223User Type: ${c}
224Portal: ${d}
225
226${e}
227""")
228        text = _(text, mapping={
229            'a': from_name,
230            'b': from_username,
231            'c': usertype,
232            'd': portal,
233            'e': body})
234        body = translate(text, 'waeup.kofa',
235            target_language=self.PORTAL_LANGUAGE)
236        if not (from_addr and rcpt_addr):
237            return False
238        return send_mail(
239            from_name, from_addr, rcpt_name, rcpt_addr,
240            subject, body, config)
241
242    @property
243    def tzinfo(self):
244        # For Nigeria: pytz.timezone('Africa/Lagos')
245        # For Germany: pytz.timezone('Europe/Berlin')
246        return pytz.utc
247
248    def fullname(self, firstname, lastname, middlename=None):
249        """Full name constructor.
250        """
251        # We do not necessarily have the middlename attribute
252        if middlename:
253            name = '%s %s %s' % (firstname, middlename, lastname)
254        else:
255            name = '%s %s' % (firstname, lastname)
256        return string.capwords(
257            name.replace('-', ' - ')).replace(' - ', '-')
258
259    def genPassword(self, length=8, chars=string.letters + string.digits):
260        """Generate a random password.
261        """
262        return ''.join([r().choice(chars) for i in range(length)])
263
264    def sendCredentials(self, user, password=None, url_info=None, msg=None):
265        """Send credentials as email.
266
267        Input is the applicant for which credentials are sent and the
268        password.
269
270        Returns True or False to indicate successful operation.
271        """
272        subject = 'Your Kofa credentials'
273        text = _(u"""Dear ${a},
274
275${b}
276Student Registration and Information Portal of
277${c}.
278
279Your user name: ${d}
280Your password: ${e}
281${f}
282
283Please remember your user name and keep
284your password secret!
285
286Please also note that passwords are case-sensitive.
287
288Regards
289""")
290        config = grok.getSite()['configuration']
291        from_name = config.name_admin
292        from_addr = config.email_admin
293        rcpt_name = user.title
294        rcpt_addr = user.email
295        text = _(text, mapping={
296            'a': rcpt_name,
297            'b': msg,
298            'c': config.name,
299            'd': user.name,
300            'e': password,
301            'f': url_info})
302
303        body = translate(text, 'waeup.kofa',
304            target_language=self.PORTAL_LANGUAGE)
305        return send_mail(
306            from_name, from_addr, rcpt_name, rcpt_addr,
307            subject, body, config)
308
309    def getPaymentItem(self, payment):
310        """Return payment item.
311
312        This method can be used to customize the display_item property method.
313        """
314        return payment.p_item
315
316    def expensive_actions_allowed(self, type=None, request=None):
317        """Tell, whether expensive actions are currently allowed.
318
319        Check system load/health (or other external circumstances) and
320        locally set values to see, whether expensive actions should be
321        allowed (`True`) or better avoided (`False`).
322
323        Use this to allow or forbid exports, report generations, or
324        similar actions.
325        """
326        max_values = self.SYSTEM_MAX_LOAD
327        for (key, func) in (
328            ('swap-mem', psutil.swap_memory),
329            ('virt-mem', psutil.virtual_memory),
330            ):
331            max_val = max_values.get(key, None)
332            if max_val is None:
333                continue
334            mem_val = func()
335            if isinstance(max_val, float):
336                # percents
337                if max_val < 0.0:
338                    max_val = 100.0 + max_val
339                if mem_val.percent > max_val:
340                    return False
341            else:
342                # number of bytes
343                if max_val < 0:
344                    max_val = mem_val.total + max_val
345                if mem_val.used > max_val:
346                    return False
347        return True
Note: See TracBrowser for help on using the repository browser.