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

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

Remove INT_PHONE_PREFIXES from KofaUtils?. It's not used.

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