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

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

Fix KofaUtils? (interface), add SYSTEM_MAX_LOAD dict.

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