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

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

Add 'Modules Level'.

  • Property svn:keywords set to Id
File size: 15.3 KB
RevLine 
[7358]1## $Id: utils.py 16812 2022-02-16 15:50:47Z 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##
[7819]18"""General helper utilities for Kofa.
[7358]19"""
20import grok
[11815]21import psutil
[7365]22import string
[8181]23import pytz
[15476]24import decimal
[9866]25from copy import deepcopy
[8181]26from random import SystemRandom as r
[7734]27from zope.i18n import translate
[7819]28from waeup.kofa.interfaces import IKofaUtils
[7811]29from waeup.kofa.interfaces import MessageFactory as _
30from waeup.kofa.smtp import send_mail as send_mail_internally
[7969]31from waeup.kofa.utils.helpers import get_sorted_preferred
[13617]32from waeup.kofa.utils.degrees import DEGREES_DICT
[7358]33
[11814]34
35def send_mail(from_name, from_addr,
36              rcpt_name, rcpt_addr,
[16299]37              subject, body, config,
38              cc=None, bcc=None):
[7811]39    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
[7382]40
[7471]41    Merely here to stay compatible with lots of calls to this place.
[7400]42    """
[7471]43    mail_id = send_mail_internally(
44        from_name, from_addr, rcpt_name, rcpt_addr,
[16299]45        subject, body, config, cc, bcc)
[7399]46    return True
47
[11814]48
[7874]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'),
[11814]54    (1, _('Nigeria'), '234'),
[7874]55    (99, _('U.S.'), '1'),
56    ]
57
[11814]58
59def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
[7874]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([
[11814]78        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
[7874]79        for x in sorted(data)
80        ])
81
[11814]82
[7831]83class KofaUtils(grok.GlobalUtility):
[7678]84    """A collection of parameters and methods subject to customization.
[7358]85    """
[7831]86    grok.implements(IKofaUtils)
[13132]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.
[7744]91    PORTAL_LANGUAGE = 'en'
[7358]92
[13617]93    DEGREES_DICT = DEGREES_DICT
94
[7701]95    PREFERRED_LANGUAGES_DICT = {
[11814]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'),
[7701]102        }
103
[7874]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)
[7871]108
[7841]109    EXAM_SUBJECTS_DICT = {
[7843]110        'math': 'Mathematics',
111        'computer_science': 'Computer Science',
[7841]112        }
[7836]113
[7917]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        )
[7836]121
[7841]122    INST_TYPES_DICT = {
[8084]123        'none': '',
[7681]124        'faculty': 'Faculty of',
125        'department': 'Department of',
126        'school': 'School of',
127        'office': 'Office for',
128        'centre': 'Centre for',
[16811]129        'centre_of': 'Centre of',
[7681]130        'institute': 'Institute of',
131        'school_for': 'School for',
[8084]132        'college': 'College of',
[10302]133        'directorate': 'Directorate of',
[7681]134        }
135
[7841]136    STUDY_MODES_DICT = {
[9131]137        'transfer': 'Transfer',
[7843]138        'ug_ft': 'Undergraduate Full-Time',
139        'ug_pt': 'Undergraduate Part-Time',
[7993]140        'pg_ft': 'Postgraduate Full-Time',
141        'pg_pt': 'Postgraduate Part-Time',
[7681]142        }
143
[11451]144    DISABLE_PAYMENT_GROUP_DICT = {
145        'sf_all': 'School Fee - All Students',
146        }
147
[7841]148    APP_CATS_DICT = {
[7843]149        'basic': 'Basic Application',
[7681]150        'no': 'no application',
151        'pg': 'Postgraduate',
152        'sandwich': 'Sandwich',
153        'cest': 'Part-Time, Diploma, Certificate'
154        }
155
[7841]156    SEMESTER_DICT = {
[10437]157        1: '1st Semester',
158        2: '2nd Semester',
[7681]159        3: 'Combined',
[16812]160        4: '1st Term',
161        5: '2nd Term',
162        6: '3rd Term',
163        9: 'N/A',
164        11: 'Module I',
165        12: 'Module II',
166        13: 'Module III',
[7681]167        }
168
[14638]169    COURSE_CATEGORY_DICT = {
170        }
171
[9400]172    SPECIAL_HANDLING_DICT = {
173        'regular': 'Regular Hostel',
174        'blocked': 'Blocked Hostel',
[10831]175        'pg': 'Postgraduate Hostel'
[9400]176        }
177
[10831]178    SPECIAL_APP_DICT = {
179        'transcript': 'Transcript Fee Payment',
[11575]180        'clearance': 'Acceptance Fee',
[10831]181        }
182
[9405]183    PAYMENT_CATEGORIES = {
184        'schoolfee': 'School Fee',
185        'clearance': 'Acceptance Fee',
186        'bed_allocation': 'Bed Allocation Fee',
187        'hostel_maintenance': 'Hostel Maintenance Fee',
188        'transfer': 'Transfer Fee',
189        'gown': 'Gown Hire Fee',
[9866]190        'application': 'Application Fee',
[15553]191        'app_balance': 'Application Fee Balance',
[10449]192        'transcript': 'Transcript Fee',
[15664]193        'late_registration': 'Late Course Registration Fee',
[15685]194        'combi': 'Combi Payment',
[9405]195        }
196
[16431]197    #: If PAYMENT_OPTIONS is empty, payment option fields won't show up.
198    PAYMENT_OPTIONS = {
199        #'credit_card': 'Credit Card',
200        #'debit_card': 'Debit Card',
201        }
202
[15432]203    def selectable_payment_categories(self, student):
204        return self.PAYMENT_CATEGORIES
[9730]205
[16431]206    def selectable_payment_options(self, student):
207        return self.PAYMENT_OPTIONS
208
[15432]209    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
[9862]210
[12564]211    REPORTABLE_PAYMENT_CATEGORIES = {
212        'schoolfee': 'School Fee',
213        'clearance': 'Acceptance Fee',
214        'hostel_maintenance': 'Hostel Maintenance Fee',
215        'gown': 'Gown Hire Fee',
216        }
217
[9868]218    BALANCE_PAYMENT_CATEGORIES = {
[9867]219        'schoolfee': 'School Fee',
220        }
[9864]221
[15664]222    COMBI_PAYMENT_CATEGORIES = {
223        'gown': 'Gown Hire Fee',
224        'transcript': 'Transcript Fee',
225        'late_registration': 'Late Course Registration Fee',
226        }
227
[9649]228    MODE_GROUPS = {
[11814]229        'All': ('all',),
230        'Undergraduate Full-Time': ('ug_ft',),
231        'Undergraduate Part-Time': ('ug_pt',),
232        'Postgraduate Full-Time': ('pg_ft',),
233        'Postgraduate Part-Time': ('pg_pt',),
[9649]234        }
235
[13125]236    VERDICTS_DICT = {
237        '0': _('(not yet)'),
238        'A': 'Successful student',
239        'B': 'Student with carryover courses',
240        'C': 'Student on probation',
241        }
242
[11800]243    #: Set positive number for allowed max, negative for required min
244    #: avail.
245    #: Use integer for bytes value, float for percent
246    #: value. `cpu-load`, of course, accepts float values only.
247    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
[11969]248    #: `cpu-load` = CPU load in percent.
[11800]249    SYSTEM_MAX_LOAD = {
250        'swap-mem': None,
251        'virt-mem': None,
252        'cpu-load': 100.0,
253        }
254
[15430]255    #: Maximum number of files listed in `finished` subfolder
256    MAX_FILES = 100
257
[15833]258    #: Maximum size in Bytes of passport images in the applicants and
259    #: students section
260    MAX_PASSPORT_SIZE = 50 * 1024
261
[15609]262    #: Temporary passwords and parents password validity period
263    TEMP_PASSWORD_MINUTES = 10
264
[11814]265    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
[16299]266                        from_username, usertype, portal, body, subject,
267                        bcc_to=None):
[7358]268        """Send an email with data provided by forms.
269        """
270        config = grok.getSite()['configuration']
[16213]271        text = _(u"""${e}
[7358]272
[16213]273---
274${a} (id: ${b})
275${d}
[7734]276""")
[11814]277        text = _(text, mapping={
278            'a': from_name,
279            'b': from_username,
280            'c': usertype,
281            'd': portal,
282            'e': body})
[7811]283        body = translate(text, 'waeup.kofa',
[7734]284            target_language=self.PORTAL_LANGUAGE)
[8436]285        if not (from_addr and rcpt_addr):
286            return False
[7400]287        return send_mail(
[11814]288            from_name, from_addr, rcpt_name, rcpt_addr,
[16299]289            subject, body, config, None, bcc_to)
[7359]290
[15964]291    def getUsers(self):
292        users = sorted(
293            grok.getSite()['users'].items(), key=lambda x: x[1].title)
294        for key, val in users:
295            yield(dict(name=key, val="%s (%s)" % (val.title, val.name)))
296
[8181]297    @property
298    def tzinfo(self):
[13124]299        """Time zone of the university.
300        """
[8181]301        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]302        # For Germany: pytz.timezone('Europe/Berlin')
[8181]303        return pytz.utc
304
[11814]305    def fullname(self, firstname, lastname, middlename=None):
[13124]306        """Construct fullname.
[7477]307        """
[7359]308        # We do not necessarily have the middlename attribute
309        if middlename:
[8603]310            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]311        else:
[8603]312            name = '%s %s' % (firstname, lastname)
[13492]313        if '<' in name:
314            return 'XXX'
[11814]315        return string.capwords(
316            name.replace('-', ' - ')).replace(' - ', '-')
[7365]317
[15287]318    def genPassword(self, length=4, chars=string.letters + string.digits):
[7477]319        """Generate a random password.
320        """
[15287]321        return ''.join([
322            r().choice(string.uppercase) +
323            r().choice(string.lowercase) +
324            r().choice(string.digits) for i in range(length)])
[7365]325
[8853]326    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[13124]327        """Send credentials as email. Input is the user for which credentials
328        are sent and the password. Method returns True or False to indicate
329        successful operation.
[7365]330        """
[7819]331        subject = 'Your Kofa credentials'
[7734]332        text = _(u"""Dear ${a},
[7365]333
[7734]334${b}
[7365]335Student Registration and Information Portal of
[7734]336${c}.
[7365]337
[7734]338Your user name: ${d}
339Your password: ${e}
[8853]340${f}
[7365]341
342Please remember your user name and keep
343your password secret!
344
[7382]345Please also note that passwords are case-sensitive.
346
[7365]347Regards
[7734]348""")
[7399]349        config = grok.getSite()['configuration']
350        from_name = config.name_admin
[7402]351        from_addr = config.email_admin
[7407]352        rcpt_name = user.title
353        rcpt_addr = user.email
[11814]354        text = _(text, mapping={
355            'a': rcpt_name,
356            'b': msg,
357            'c': config.name,
358            'd': user.name,
359            'e': password,
360            'f': url_info})
[7734]361
[7811]362        body = translate(text, 'waeup.kofa',
[7734]363            target_language=self.PORTAL_LANGUAGE)
[7399]364        return send_mail(
[11814]365            from_name, from_addr, rcpt_name, rcpt_addr,
366            subject, body, config)
[9987]367
[16551]368    def informNewStudent(self, user, pw, login_url, rpw_url):
369        """Inform student that a new student account has been created.
370        """
371        subject = 'Your new Kofa student account'
372        text = _(u"""Dear ${a},
373
374Your student record of the Student Registration and Information Portal of
375${b} has been created for you.
376
377Your user name: ${c}
378Your password: ${d}
379Login: ${e}
380
381Or request a new secure password here: ${f}
382
383Regards
384""")
385        config = grok.getSite()['configuration']
386        from_name = config.name_admin
387        from_addr = config.email_admin
388        rcpt_name = user.title
389        rcpt_addr = user.email
390
391        text = _(text, mapping={
392            'a': rcpt_name,
393            'b': config.name,
394            'c': user.name,
395            'd': pw,
396            'e': login_url,
397            'f': rpw_url
398            })
399        body = translate(text, 'waeup.kofa',
400            target_language=self.PORTAL_LANGUAGE)
401        return send_mail(
402            from_name, from_addr, rcpt_name, rcpt_addr,
403            subject, body, config)
404
405
[14014]406    def inviteReferee(self, referee, applicant, url_info=None):
407        """Send invitation email to referee.
408        """
409        config = grok.getSite()['configuration']
410        subject = 'Request for referee report from %s' % config.name
411        text = _(u"""Dear ${a},
412
[14040]413The candidate with Id ${b} and name ${c} applied to
414the ${d} to study ${e} for the ${f} session.
[16777]415The candidate has listed you as referee. You are, therefore, required to,
416kindly, provide your referral remarks on or before ${g}. Please use the
417following form:
[14014]418
[14040]419${h}
420
421Thank You
422
423The Secretary
[16777]424School of Postgraduate Studies
[14040]425${d}
[14014]426""")
427        from_name = config.name_admin
428        from_addr = config.email_admin
429        rcpt_name = referee.name
430        rcpt_addr = referee.email
[14040]431        session = '%s/%s' % (
432            applicant.__parent__.year, applicant.__parent__.year+1)
[14014]433        text = _(text, mapping={
434            'a': rcpt_name,
[14040]435            'b': applicant.applicant_id,
436            'c': applicant.display_fullname,
437            'd': config.name,
438            'e': applicant.course1.title,
439            'f': session,
440            'g': applicant.__parent__.enddate,
441            'h': url_info,
442            })
[14014]443
444        body = translate(text, 'waeup.kofa',
445            target_language=self.PORTAL_LANGUAGE)
446        return send_mail(
447            from_name, from_addr, rcpt_name, rcpt_addr,
448            subject, body, config)
449
[9987]450    def getPaymentItem(self, payment):
[13124]451        """Return payment item. This method can be used to customize the
452        `display_item` property attribute, e.g. in order to hide bed coordinates
453        if maintenance fee is not paid.
[9987]454        """
455        return payment.p_item
[11815]456
457    def expensive_actions_allowed(self, type=None, request=None):
458        """Tell, whether expensive actions are currently allowed.
459        Check system load/health (or other external circumstances) and
460        locally set values to see, whether expensive actions should be
461        allowed (`True`) or better avoided (`False`).
462        Use this to allow or forbid exports, report generations, or
463        similar actions.
464        """
465        max_values = self.SYSTEM_MAX_LOAD
[11816]466        for (key, func) in (
467            ('swap-mem', psutil.swap_memory),
[11818]468            ('virt-mem', psutil.virtual_memory),
[11816]469            ):
470            max_val = max_values.get(key, None)
471            if max_val is None:
472                continue
473            mem_val = func()
[11815]474            if isinstance(max_val, float):
[11816]475                # percents
[11821]476                if max_val < 0.0:
477                    max_val = 100.0 + max_val
[11816]478                if mem_val.percent > max_val:
[11815]479                    return False
480            else:
[11816]481                # number of bytes
[11821]482                if max_val < 0:
483                    max_val = mem_val.total + max_val
[11816]484                if mem_val.used > max_val:
[11815]485                    return False
486        return True
[13198]487
488    def export_disabled_message(self):
489        export_disabled_message = grok.getSite()[
490            'configuration'].export_disabled_message
491        if export_disabled_message:
492            return export_disabled_message
[14473]493        return None
494
495    def format_float(self, value, prec):
[15476]496        # >>> 4.6 * 100
497        # 459.99999999999994
498        value = decimal.Decimal(str(value))
[14473]499        # cut floating point value
500        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
501        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.