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

Last change on this file since 17650 was 17376, checked in by Henrik Bettermann, 20 months ago

Enable customization of certificate select box entries also in the students section.

  • Property svn:keywords set to Id
File size: 17.2 KB
Line 
1## $Id: utils.py 17376 2023-04-06 17:29:31Z 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    MONTHS_DICT = {
105        '1': _('January'),
106        '2': _('February'),
107        '3': _('March'),
108        '4': _('April'),
109        '5': _('May'),
110        '6': _('June'),
111        '7': _('July'),
112        '8': _('August'),
113        '9': _('September'),
114        '10': _('October'),
115        '11': _('November'),
116        '12': _('December'),
117        }
118
119    #: A function to return
120    @classmethod
121    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
122        return sorted_phone_prefixes(data, request)
123
124    EXAM_SUBJECTS_DICT = {
125        'math': 'Mathematics',
126        'computer_science': 'Computer Science',
127        }
128
129    #: Exam grades. The tuple is sorted as it should be displayed in
130    #: select boxes.
131    EXAM_GRADES = (
132        ('A', 'Best'),
133        ('B', 'Better'),
134        ('C', 'Good'),
135        )
136
137    INST_TYPES_DICT = {
138        'none': '',
139        'faculty': 'Faculty of',
140        'department': 'Department of',
141        'school': 'School of',
142        'office': 'Office for',
143        'centre': 'Centre for',
144        'centre_of': 'Centre of',
145        'institute': 'Institute of',
146        'school_for': 'School for',
147        'college': 'College of',
148        'directorate': 'Directorate of',
149        }
150
151    STUDY_MODES_DICT = {
152        'transfer': 'Transfer',
153        'transferred': 'Transferred',
154        'ug_ft': 'Undergraduate Full-Time',
155        'ug_pt': 'Undergraduate Part-Time',
156        'pg_ft': 'Postgraduate Full-Time',
157        'pg_pt': 'Postgraduate Part-Time',
158        }
159
160    DISABLE_PAYMENT_GROUP_DICT = {
161        'sf_all': 'School Fee - All Students',
162        }
163
164    APP_CATS_DICT = {
165        'basic': 'Basic Application',
166        'no': 'no application',
167        'pg': 'Postgraduate',
168        'sandwich': 'Sandwich',
169        'cest': 'Part-Time, Diploma, Certificate'
170        }
171
172    SEMESTER_DICT = {
173        1: '1st Semester',
174        2: '2nd Semester',
175        3: 'Combined',
176        4: '1st Term',
177        5: '2nd Term',
178        6: '3rd Term',
179        9: 'N/A',
180        11: 'Module I',
181        12: 'Module II',
182        13: 'Module III',
183        }
184
185    COURSE_CATEGORY_DICT = {
186        }
187
188    SPECIAL_HANDLING_DICT = {
189        'regular': 'Regular Hostel',
190        'blocked': 'Blocked Hostel',
191        'pg': 'Postgraduate Hostel'
192        }
193
194    SPECIAL_APP_DICT = {
195        'transcript': 'Transcript Fee Payment',
196        'clearance': 'Acceptance Fee',
197        }
198
199    PAYMENT_CATEGORIES = {
200        'schoolfee': 'School Fee',
201        'clearance': 'Acceptance Fee',
202        'bed_allocation': 'Bed Allocation Fee',
203        'hostel_maintenance': 'Hostel Maintenance Fee',
204        'transfer': 'Transfer Fee',
205        'gown': 'Gown Hire Fee',
206        'application': 'Application Fee',
207        'app_balance': 'Application Fee Balance',
208        'transcript': 'Transcript Fee',
209        'late_registration': 'Late Course Registration Fee',
210        'combi': 'Combi Payment',
211        'donation': 'Donation',
212        }
213
214    #: If PAYMENT_OPTIONS is empty, payment option fields won't show up.
215    PAYMENT_OPTIONS = {
216        #'credit_card': 'Credit Card',
217        #'debit_card': 'Debit Card',
218        }
219
220    def selectable_payment_categories(self, student):
221        return self.PAYMENT_CATEGORIES
222
223    def selectable_payment_options(self, student):
224        return self.PAYMENT_OPTIONS
225
226    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
227
228    REPORTABLE_PAYMENT_CATEGORIES = {
229        'schoolfee': 'School Fee',
230        'clearance': 'Acceptance Fee',
231        'hostel_maintenance': 'Hostel Maintenance Fee',
232        'gown': 'Gown Hire Fee',
233        }
234
235    BALANCE_PAYMENT_CATEGORIES = {
236        'schoolfee': 'School Fee',
237        }
238
239    APPLICANT_BALANCE_PAYMENT_CATEGORIES = {
240        'donation': 'Donation',
241        }
242
243    COMBI_PAYMENT_CATEGORIES = {
244        'gown': 'Gown Hire Fee',
245        'transcript': 'Transcript Fee',
246        'late_registration': 'Late Course Registration Fee',
247        }
248
249    MODE_GROUPS = {
250        'All': ('all',),
251        'Undergraduate Full-Time': ('ug_ft',),
252        'Undergraduate Part-Time': ('ug_pt',),
253        'Postgraduate Full-Time': ('pg_ft',),
254        'Postgraduate Part-Time': ('pg_pt',),
255        }
256
257    VERDICTS_DICT = {
258        '0': _('(not yet)'),
259        'A': 'Successful student',
260        'B': 'Student with carryover courses',
261        'C': 'Student on probation',
262        }
263
264    #: Set positive number for allowed max, negative for required min
265    #: avail.
266    #: Use integer for bytes value, float for percent
267    #: value. `cpu-load`, of course, accepts float values only.
268    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
269    #: `cpu-load` = CPU load in percent.
270    SYSTEM_MAX_LOAD = {
271        'swap-mem': None,
272        'virt-mem': None,
273        'cpu-load': 100.0,
274        }
275
276    #: Maximum number of files listed in `finished` subfolder
277    MAX_FILES = 100
278
279    #: Maximum size in Bytes of passport images in the applicants and
280    #: students section
281    MAX_PASSPORT_SIZE = 50 * 1024
282
283    #: Temporary passwords and parents password validity period
284    TEMP_PASSWORD_MINUTES = 10
285
286    def sortCertificates(self, context, resultset):
287        """Sort already filtered certificates in `CertificateSource`.
288        """
289        return sorted(resultset, key=lambda value: value.code)
290
291    def getCertTitle(self, context, value):
292        """Compose the titles in `CertificateSource`.
293        """
294        return "%s - %s" % (value.code, value.title)
295
296    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
297                        from_username, usertype, portal, body, subject,
298                        bcc_to=None):
299        """Send an email with data provided by forms.
300        """
301        config = grok.getSite()['configuration']
302        text = _(u"""${e}
303
304---
305${a} (id: ${b})
306${d}
307""")
308        text = _(text, mapping={
309            'a': from_name,
310            'b': from_username,
311            'c': usertype,
312            'd': portal,
313            'e': body})
314        body = translate(text, 'waeup.kofa',
315            target_language=self.PORTAL_LANGUAGE)
316        if not (from_addr and rcpt_addr):
317            return False
318        return send_mail(
319            from_name, from_addr, rcpt_name, rcpt_addr,
320            subject, body, config, None, bcc_to)
321
322    def getUsers(self):
323        users = sorted(
324            grok.getSite()['users'].items(), key=lambda x: x[1].title)
325        for key, val in users:
326            yield(dict(name=key, val="%s (%s)" % (val.title, val.name)))
327
328    @property
329    def tzinfo(self):
330        """Time zone of the university.
331        """
332        # For Nigeria: pytz.timezone('Africa/Lagos')
333        # For Germany: pytz.timezone('Europe/Berlin')
334        return pytz.utc
335
336    def fullname(self, firstname, lastname, middlename=None):
337        """Construct fullname.
338        """
339        # We do not necessarily have the middlename attribute
340        if middlename:
341            name = '%s %s %s' % (firstname, middlename, lastname)
342        else:
343            name = '%s %s' % (firstname, lastname)
344        if '<' in name:
345            return 'XXX'
346        return string.capwords(
347            name.replace('-', ' - ')).replace(' - ', '-')
348
349    def genPassword(self, length=4, chars=string.letters + string.digits):
350        """Generate a random password.
351        """
352        return ''.join([
353            r().choice(string.uppercase) +
354            r().choice(string.lowercase) +
355            r().choice(string.digits) for i in range(length)])
356
357    def sendCredentials(self, user, password=None, url_info=None, msg=None):
358        """Send credentials as email. Input is the user for which credentials
359        are sent and the password. Method returns True or False to indicate
360        successful operation.
361        """
362        subject = _('Your Kofa credentials')
363        text = _(u"""Dear ${a},
364
365${b}
366Student Registration and Information Portal of
367${c}.
368
369Your user name: ${d}
370Your password: ${e}
371${f}
372
373Please remember your user name and keep
374your password secret!
375
376Please also note that passwords are case-sensitive.
377
378Regards
379""")
380        config = grok.getSite()['configuration']
381        from_name = config.name_admin
382        from_addr = config.email_admin
383        rcpt_name = user.title
384        rcpt_addr = user.email
385        text = _(text, mapping={
386            'a': rcpt_name,
387            'b': msg,
388            'c': config.name,
389            'd': user.name,
390            'e': password,
391            'f': url_info})
392
393        body = translate(text, 'waeup.kofa',
394            target_language=self.PORTAL_LANGUAGE)
395        return send_mail(
396            from_name, from_addr, rcpt_name, rcpt_addr,
397            subject, body, config)
398
399    def informNewStudent(self, user, pw, login_url, rpw_url):
400        """Inform student that a new student account has been created.
401        """
402        subject = _('Your new Kofa student account')
403        text = _(u"""Dear ${a},
404
405Your student record of the Student Registration and Information Portal of
406${b} has been created for you.
407
408Your user name: ${c}
409Your password: ${d}
410Login: ${e}
411
412Or request a new secure password here: ${f}
413
414Regards
415""")
416        config = grok.getSite()['configuration']
417        from_name = config.name_admin
418        from_addr = config.email_admin
419        rcpt_name = user.title
420        rcpt_addr = user.email
421
422        text = _(text, mapping={
423            'a': rcpt_name,
424            'b': config.name,
425            'c': user.name,
426            'd': pw,
427            'e': login_url,
428            'f': rpw_url
429            })
430        body = translate(text, 'waeup.kofa',
431            target_language=self.PORTAL_LANGUAGE)
432        return send_mail(
433            from_name, from_addr, rcpt_name, rcpt_addr,
434            subject, body, config)
435
436
437    def informApplicant(self, applicant):
438        """Inform applicant that the application form was successfully
439        submitted.
440        """
441        if not getattr(applicant.__parent__, 'send_email', False):
442            return
443        subject = 'Your application form was successfully submitted'
444        text = _(u"""Dear ${a},
445
446Your application ${b} has been successfully submitted to ${c}.
447
448Regards
449""")
450        config = grok.getSite()['configuration']
451        from_name = config.name_admin
452        from_addr = config.email_admin
453        rcpt_name = applicant.display_fullname
454        rcpt_addr = applicant.email
455        session = '%s/%s' % (
456            applicant.__parent__.year, applicant.__parent__.year+1)
457        text = _(text, mapping={
458            'a': rcpt_name,
459            'b': applicant.applicant_id,
460            'c': config.name,
461            })
462        body = translate(text, 'waeup.kofa',
463            target_language=self.PORTAL_LANGUAGE)
464        return send_mail(
465            from_name, from_addr, rcpt_name, rcpt_addr,
466            subject, body, config)
467
468    def inviteReferee(self, referee, applicant, url_info=None):
469        """Send invitation email to referee.
470        """
471        config = grok.getSite()['configuration']
472        subject = 'Request for referee report from %s' % config.name
473        text = _(u"""Dear ${a},
474
475The candidate with Id ${b} and name ${c} applied to
476the ${d} to study ${e} for the ${f} session.
477The candidate has listed you as referee. You are, therefore, required to,
478kindly, provide your referral remarks on or before ${g}. Please use the
479following form:
480
481${h}
482
483Thank You
484
485The Secretary
486School of Postgraduate Studies
487${d}
488""")
489        from_name = config.name_admin
490        from_addr = config.email_admin
491        rcpt_name = referee.name
492        rcpt_addr = referee.email
493        session = '%s/%s' % (
494            applicant.__parent__.year, applicant.__parent__.year+1)
495        text = _(text, mapping={
496            'a': rcpt_name,
497            'b': applicant.applicant_id,
498            'c': applicant.display_fullname,
499            'd': config.name,
500            'e': applicant.course1.title,
501            'f': session,
502            'g': applicant.__parent__.enddate,
503            'h': url_info,
504            })
505
506        body = translate(text, 'waeup.kofa',
507            target_language=self.PORTAL_LANGUAGE)
508        return send_mail(
509            from_name, from_addr, rcpt_name, rcpt_addr,
510            subject, body, config)
511
512    def getPaymentItem(self, payment):
513        """Return payment item. This method can be used to customize the
514        `display_item` property attribute, e.g. in order to hide bed coordinates
515        if maintenance fee is not paid.
516        """
517        return payment.p_item
518
519    def expensive_actions_allowed(self, type=None, request=None):
520        """Tell, whether expensive actions are currently allowed.
521        Check system load/health (or other external circumstances) and
522        locally set values to see, whether expensive actions should be
523        allowed (`True`) or better avoided (`False`).
524        Use this to allow or forbid exports, report generations, or
525        similar actions.
526        """
527        max_values = self.SYSTEM_MAX_LOAD
528        for (key, func) in (
529            ('swap-mem', psutil.swap_memory),
530            ('virt-mem', psutil.virtual_memory),
531            ):
532            max_val = max_values.get(key, None)
533            if max_val is None:
534                continue
535            mem_val = func()
536            if isinstance(max_val, float):
537                # percents
538                if max_val < 0.0:
539                    max_val = 100.0 + max_val
540                if mem_val.percent > max_val:
541                    return False
542            else:
543                # number of bytes
544                if max_val < 0:
545                    max_val = mem_val.total + max_val
546                if mem_val.used > max_val:
547                    return False
548        return True
549
550    def export_disabled_message(self):
551        export_disabled_message = grok.getSite()[
552            'configuration'].export_disabled_message
553        if export_disabled_message:
554            return export_disabled_message
555        return None
556
557    def format_float(self, value, prec):
558        # >>> 4.6 * 100
559        # 459.99999999999994
560        value = decimal.Decimal(str(value))
561        # cut floating point value
562        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
563        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.