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

Last change on this file since 16828 was 16828, checked in by Henrik Bettermann, 3 years ago

Add importers for previous study course data.

  • Property svn:keywords set to Id
File size: 15.3 KB
Line 
1## $Id: utils.py 16828 2022-02-22 22:08:37Z 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
24import decimal
25from copy import deepcopy
26from random import SystemRandom as r
27from zope.i18n import translate
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.helpers import get_sorted_preferred
32from waeup.kofa.utils.degrees import DEGREES_DICT
33
34
35def send_mail(from_name, from_addr,
36              rcpt_name, rcpt_addr,
37              subject, body, config,
38              cc=None, bcc=None):
39    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
40
41    Merely here to stay compatible with lots of calls to this place.
42    """
43    mail_id = send_mail_internally(
44        from_name, from_addr, rcpt_name, rcpt_addr,
45        subject, body, config, cc, bcc)
46    return True
47
48
49#: A list of phone prefixes (order num, country, prefix).
50#: Items with same order num will be sorted alphabetically.
51#: The lower the order num, the higher the precedence.
52INT_PHONE_PREFIXES = [
53    (99, _('Germany'), '49'),
54    (1, _('Nigeria'), '234'),
55    (99, _('U.S.'), '1'),
56    ]
57
58
59def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
60    """Sorted tuples of phone prefixes.
61
62    Ordered as shown above and formatted for use in select boxes.
63
64    If request is given, we'll try to translate all country names in
65    order to sort alphabetically correctly.
66
67    XXX: This is a function (and not a constant) as different
68    languages might give different orders. This is not tested yet.
69
70    XXX: If we really want to use alphabetic ordering here, we might
71    think about caching results of translations.
72    """
73    if request is not None:
74        data = [
75            (x, translate(y, context=request), z)
76            for x, y, z in data]
77    return tuple([
78        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
79        for x in sorted(data)
80        ])
81
82
83class KofaUtils(grok.GlobalUtility):
84    """A collection of parameters and methods subject to customization.
85    """
86    grok.implements(IKofaUtils)
87
88    #: This the only place where we define the portal language
89    #: which is used for the translation of system messages
90    #: (e.g. object histories) pdf slips.
91    PORTAL_LANGUAGE = 'en'
92
93    DEGREES_DICT = DEGREES_DICT
94
95    PREFERRED_LANGUAGES_DICT = {
96        'en': (1, u'English'),
97        'fr': (2, u'Français'),
98        'de': (3, u'Deutsch'),
99        'ha': (4, u'Hausa'),
100        'yo': (5, u'Yoruba'),
101        'ig': (6, u'Igbo'),
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        'centre_of': 'Centre of',
130        'institute': 'Institute of',
131        'school_for': 'School for',
132        'college': 'College of',
133        'directorate': 'Directorate of',
134        }
135
136    STUDY_MODES_DICT = {
137        'transfer': 'Transfer',
138        'transferred': 'Transferred',
139        'ug_ft': 'Undergraduate Full-Time',
140        'ug_pt': 'Undergraduate Part-Time',
141        'pg_ft': 'Postgraduate Full-Time',
142        'pg_pt': 'Postgraduate Part-Time',
143        }
144
145    DISABLE_PAYMENT_GROUP_DICT = {
146        'sf_all': 'School Fee - All Students',
147        }
148
149    APP_CATS_DICT = {
150        'basic': 'Basic Application',
151        'no': 'no application',
152        'pg': 'Postgraduate',
153        'sandwich': 'Sandwich',
154        'cest': 'Part-Time, Diploma, Certificate'
155        }
156
157    SEMESTER_DICT = {
158        1: '1st Semester',
159        2: '2nd Semester',
160        3: 'Combined',
161        4: '1st Term',
162        5: '2nd Term',
163        6: '3rd Term',
164        9: 'N/A',
165        11: 'Module I',
166        12: 'Module II',
167        13: 'Module III',
168        }
169
170    COURSE_CATEGORY_DICT = {
171        }
172
173    SPECIAL_HANDLING_DICT = {
174        'regular': 'Regular Hostel',
175        'blocked': 'Blocked Hostel',
176        'pg': 'Postgraduate Hostel'
177        }
178
179    SPECIAL_APP_DICT = {
180        'transcript': 'Transcript Fee Payment',
181        'clearance': 'Acceptance Fee',
182        }
183
184    PAYMENT_CATEGORIES = {
185        'schoolfee': 'School Fee',
186        'clearance': 'Acceptance Fee',
187        'bed_allocation': 'Bed Allocation Fee',
188        'hostel_maintenance': 'Hostel Maintenance Fee',
189        'transfer': 'Transfer Fee',
190        'gown': 'Gown Hire Fee',
191        'application': 'Application Fee',
192        'app_balance': 'Application Fee Balance',
193        'transcript': 'Transcript Fee',
194        'late_registration': 'Late Course Registration Fee',
195        'combi': 'Combi Payment',
196        }
197
198    #: If PAYMENT_OPTIONS is empty, payment option fields won't show up.
199    PAYMENT_OPTIONS = {
200        #'credit_card': 'Credit Card',
201        #'debit_card': 'Debit Card',
202        }
203
204    def selectable_payment_categories(self, student):
205        return self.PAYMENT_CATEGORIES
206
207    def selectable_payment_options(self, student):
208        return self.PAYMENT_OPTIONS
209
210    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
211
212    REPORTABLE_PAYMENT_CATEGORIES = {
213        'schoolfee': 'School Fee',
214        'clearance': 'Acceptance Fee',
215        'hostel_maintenance': 'Hostel Maintenance Fee',
216        'gown': 'Gown Hire Fee',
217        }
218
219    BALANCE_PAYMENT_CATEGORIES = {
220        'schoolfee': 'School Fee',
221        }
222
223    COMBI_PAYMENT_CATEGORIES = {
224        'gown': 'Gown Hire Fee',
225        'transcript': 'Transcript Fee',
226        'late_registration': 'Late Course Registration Fee',
227        }
228
229    MODE_GROUPS = {
230        'All': ('all',),
231        'Undergraduate Full-Time': ('ug_ft',),
232        'Undergraduate Part-Time': ('ug_pt',),
233        'Postgraduate Full-Time': ('pg_ft',),
234        'Postgraduate Part-Time': ('pg_pt',),
235        }
236
237    VERDICTS_DICT = {
238        '0': _('(not yet)'),
239        'A': 'Successful student',
240        'B': 'Student with carryover courses',
241        'C': 'Student on probation',
242        }
243
244    #: Set positive number for allowed max, negative for required min
245    #: avail.
246    #: Use integer for bytes value, float for percent
247    #: value. `cpu-load`, of course, accepts float values only.
248    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
249    #: `cpu-load` = CPU load in percent.
250    SYSTEM_MAX_LOAD = {
251        'swap-mem': None,
252        'virt-mem': None,
253        'cpu-load': 100.0,
254        }
255
256    #: Maximum number of files listed in `finished` subfolder
257    MAX_FILES = 100
258
259    #: Maximum size in Bytes of passport images in the applicants and
260    #: students section
261    MAX_PASSPORT_SIZE = 50 * 1024
262
263    #: Temporary passwords and parents password validity period
264    TEMP_PASSWORD_MINUTES = 10
265
266    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
267                        from_username, usertype, portal, body, subject,
268                        bcc_to=None):
269        """Send an email with data provided by forms.
270        """
271        config = grok.getSite()['configuration']
272        text = _(u"""${e}
273
274---
275${a} (id: ${b})
276${d}
277""")
278        text = _(text, mapping={
279            'a': from_name,
280            'b': from_username,
281            'c': usertype,
282            'd': portal,
283            'e': body})
284        body = translate(text, 'waeup.kofa',
285            target_language=self.PORTAL_LANGUAGE)
286        if not (from_addr and rcpt_addr):
287            return False
288        return send_mail(
289            from_name, from_addr, rcpt_name, rcpt_addr,
290            subject, body, config, None, bcc_to)
291
292    def getUsers(self):
293        users = sorted(
294            grok.getSite()['users'].items(), key=lambda x: x[1].title)
295        for key, val in users:
296            yield(dict(name=key, val="%s (%s)" % (val.title, val.name)))
297
298    @property
299    def tzinfo(self):
300        """Time zone of the university.
301        """
302        # For Nigeria: pytz.timezone('Africa/Lagos')
303        # For Germany: pytz.timezone('Europe/Berlin')
304        return pytz.utc
305
306    def fullname(self, firstname, lastname, middlename=None):
307        """Construct fullname.
308        """
309        # We do not necessarily have the middlename attribute
310        if middlename:
311            name = '%s %s %s' % (firstname, middlename, lastname)
312        else:
313            name = '%s %s' % (firstname, lastname)
314        if '<' in name:
315            return 'XXX'
316        return string.capwords(
317            name.replace('-', ' - ')).replace(' - ', '-')
318
319    def genPassword(self, length=4, chars=string.letters + string.digits):
320        """Generate a random password.
321        """
322        return ''.join([
323            r().choice(string.uppercase) +
324            r().choice(string.lowercase) +
325            r().choice(string.digits) for i in range(length)])
326
327    def sendCredentials(self, user, password=None, url_info=None, msg=None):
328        """Send credentials as email. Input is the user for which credentials
329        are sent and the password. Method returns True or False to indicate
330        successful operation.
331        """
332        subject = 'Your Kofa credentials'
333        text = _(u"""Dear ${a},
334
335${b}
336Student Registration and Information Portal of
337${c}.
338
339Your user name: ${d}
340Your password: ${e}
341${f}
342
343Please remember your user name and keep
344your password secret!
345
346Please also note that passwords are case-sensitive.
347
348Regards
349""")
350        config = grok.getSite()['configuration']
351        from_name = config.name_admin
352        from_addr = config.email_admin
353        rcpt_name = user.title
354        rcpt_addr = user.email
355        text = _(text, mapping={
356            'a': rcpt_name,
357            'b': msg,
358            'c': config.name,
359            'd': user.name,
360            'e': password,
361            'f': url_info})
362
363        body = translate(text, 'waeup.kofa',
364            target_language=self.PORTAL_LANGUAGE)
365        return send_mail(
366            from_name, from_addr, rcpt_name, rcpt_addr,
367            subject, body, config)
368
369    def informNewStudent(self, user, pw, login_url, rpw_url):
370        """Inform student that a new student account has been created.
371        """
372        subject = 'Your new Kofa student account'
373        text = _(u"""Dear ${a},
374
375Your student record of the Student Registration and Information Portal of
376${b} has been created for you.
377
378Your user name: ${c}
379Your password: ${d}
380Login: ${e}
381
382Or request a new secure password here: ${f}
383
384Regards
385""")
386        config = grok.getSite()['configuration']
387        from_name = config.name_admin
388        from_addr = config.email_admin
389        rcpt_name = user.title
390        rcpt_addr = user.email
391
392        text = _(text, mapping={
393            'a': rcpt_name,
394            'b': config.name,
395            'c': user.name,
396            'd': pw,
397            'e': login_url,
398            'f': rpw_url
399            })
400        body = translate(text, 'waeup.kofa',
401            target_language=self.PORTAL_LANGUAGE)
402        return send_mail(
403            from_name, from_addr, rcpt_name, rcpt_addr,
404            subject, body, config)
405
406
407    def inviteReferee(self, referee, applicant, url_info=None):
408        """Send invitation email to referee.
409        """
410        config = grok.getSite()['configuration']
411        subject = 'Request for referee report from %s' % config.name
412        text = _(u"""Dear ${a},
413
414The candidate with Id ${b} and name ${c} applied to
415the ${d} to study ${e} for the ${f} session.
416The candidate has listed you as referee. You are, therefore, required to,
417kindly, provide your referral remarks on or before ${g}. Please use the
418following form:
419
420${h}
421
422Thank You
423
424The Secretary
425School of Postgraduate Studies
426${d}
427""")
428        from_name = config.name_admin
429        from_addr = config.email_admin
430        rcpt_name = referee.name
431        rcpt_addr = referee.email
432        session = '%s/%s' % (
433            applicant.__parent__.year, applicant.__parent__.year+1)
434        text = _(text, mapping={
435            'a': rcpt_name,
436            'b': applicant.applicant_id,
437            'c': applicant.display_fullname,
438            'd': config.name,
439            'e': applicant.course1.title,
440            'f': session,
441            'g': applicant.__parent__.enddate,
442            'h': url_info,
443            })
444
445        body = translate(text, 'waeup.kofa',
446            target_language=self.PORTAL_LANGUAGE)
447        return send_mail(
448            from_name, from_addr, rcpt_name, rcpt_addr,
449            subject, body, config)
450
451    def getPaymentItem(self, payment):
452        """Return payment item. This method can be used to customize the
453        `display_item` property attribute, e.g. in order to hide bed coordinates
454        if maintenance fee is not paid.
455        """
456        return payment.p_item
457
458    def expensive_actions_allowed(self, type=None, request=None):
459        """Tell, whether expensive actions are currently allowed.
460        Check system load/health (or other external circumstances) and
461        locally set values to see, whether expensive actions should be
462        allowed (`True`) or better avoided (`False`).
463        Use this to allow or forbid exports, report generations, or
464        similar actions.
465        """
466        max_values = self.SYSTEM_MAX_LOAD
467        for (key, func) in (
468            ('swap-mem', psutil.swap_memory),
469            ('virt-mem', psutil.virtual_memory),
470            ):
471            max_val = max_values.get(key, None)
472            if max_val is None:
473                continue
474            mem_val = func()
475            if isinstance(max_val, float):
476                # percents
477                if max_val < 0.0:
478                    max_val = 100.0 + max_val
479                if mem_val.percent > max_val:
480                    return False
481            else:
482                # number of bytes
483                if max_val < 0:
484                    max_val = mem_val.total + max_val
485                if mem_val.used > max_val:
486                    return False
487        return True
488
489    def export_disabled_message(self):
490        export_disabled_message = grok.getSite()[
491            'configuration'].export_disabled_message
492        if export_disabled_message:
493            return export_disabled_message
494        return None
495
496    def format_float(self, value, prec):
497        # >>> 4.6 * 100
498        # 459.99999999999994
499        value = decimal.Decimal(str(value))
500        # cut floating point value
501        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
502        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.