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

Last change on this file since 17808 was 17798, checked in by Henrik Bettermann, 4 months ago

Make the certificate's longtitle customizable.

  • Property svn:keywords set to Id
File size: 17.3 KB
RevLine 
[7358]1## $Id: utils.py 17798 2024-05-22 07:25:56Z 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
[17094]104    MONTHS_DICT = {
[17211]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'),
[17094]117        }
118
[7874]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)
[7871]123
[7841]124    EXAM_SUBJECTS_DICT = {
[7843]125        'math': 'Mathematics',
126        'computer_science': 'Computer Science',
[7841]127        }
[7836]128
[7917]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        )
[7836]136
[7841]137    INST_TYPES_DICT = {
[8084]138        'none': '',
[7681]139        'faculty': 'Faculty of',
140        'department': 'Department of',
141        'school': 'School of',
142        'office': 'Office for',
143        'centre': 'Centre for',
[16811]144        'centre_of': 'Centre of',
[7681]145        'institute': 'Institute of',
146        'school_for': 'School for',
[8084]147        'college': 'College of',
[10302]148        'directorate': 'Directorate of',
[7681]149        }
150
[7841]151    STUDY_MODES_DICT = {
[9131]152        'transfer': 'Transfer',
[16828]153        'transferred': 'Transferred',
[7843]154        'ug_ft': 'Undergraduate Full-Time',
155        'ug_pt': 'Undergraduate Part-Time',
[7993]156        'pg_ft': 'Postgraduate Full-Time',
157        'pg_pt': 'Postgraduate Part-Time',
[7681]158        }
159
[11451]160    DISABLE_PAYMENT_GROUP_DICT = {
161        'sf_all': 'School Fee - All Students',
162        }
163
[7841]164    APP_CATS_DICT = {
[7843]165        'basic': 'Basic Application',
[7681]166        'no': 'no application',
167        'pg': 'Postgraduate',
168        'sandwich': 'Sandwich',
169        'cest': 'Part-Time, Diploma, Certificate'
170        }
171
[7841]172    SEMESTER_DICT = {
[10437]173        1: '1st Semester',
174        2: '2nd Semester',
[7681]175        3: 'Combined',
[16812]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',
[7681]183        }
184
[14638]185    COURSE_CATEGORY_DICT = {
186        }
187
[9400]188    SPECIAL_HANDLING_DICT = {
189        'regular': 'Regular Hostel',
190        'blocked': 'Blocked Hostel',
[10831]191        'pg': 'Postgraduate Hostel'
[9400]192        }
193
[10831]194    SPECIAL_APP_DICT = {
195        'transcript': 'Transcript Fee Payment',
[11575]196        'clearance': 'Acceptance Fee',
[10831]197        }
198
[9405]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',
[9866]206        'application': 'Application Fee',
[15553]207        'app_balance': 'Application Fee Balance',
[10449]208        'transcript': 'Transcript Fee',
[15664]209        'late_registration': 'Late Course Registration Fee',
[15685]210        'combi': 'Combi Payment',
[17016]211        'donation': 'Donation',
[9405]212        }
213
[16431]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
[15432]220    def selectable_payment_categories(self, student):
221        return self.PAYMENT_CATEGORIES
[9730]222
[16431]223    def selectable_payment_options(self, student):
224        return self.PAYMENT_OPTIONS
225
[15432]226    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
[9862]227
[12564]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
[9868]235    BALANCE_PAYMENT_CATEGORIES = {
[9867]236        'schoolfee': 'School Fee',
237        }
[9864]238
[17016]239    APPLICANT_BALANCE_PAYMENT_CATEGORIES = {
240        'donation': 'Donation',
241        }
242
[15664]243    COMBI_PAYMENT_CATEGORIES = {
244        'gown': 'Gown Hire Fee',
245        'transcript': 'Transcript Fee',
246        'late_registration': 'Late Course Registration Fee',
247        }
248
[9649]249    MODE_GROUPS = {
[11814]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',),
[9649]255        }
256
[13125]257    VERDICTS_DICT = {
258        '0': _('(not yet)'),
259        'A': 'Successful student',
260        'B': 'Student with carryover courses',
261        'C': 'Student on probation',
262        }
263
[11800]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,
[11969]269    #: `cpu-load` = CPU load in percent.
[11800]270    SYSTEM_MAX_LOAD = {
271        'swap-mem': None,
272        'virt-mem': None,
273        'cpu-load': 100.0,
274        }
275
[15430]276    #: Maximum number of files listed in `finished` subfolder
277    MAX_FILES = 100
278
[15833]279    #: Maximum size in Bytes of passport images in the applicants and
280    #: students section
281    MAX_PASSPORT_SIZE = 50 * 1024
282
[15609]283    #: Temporary passwords and parents password validity period
284    TEMP_PASSWORD_MINUTES = 10
285
[17376]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):
[17798]292        """Compose the titles in `CertificateSource.
[17376]293        """
294        return "%s - %s" % (value.code, value.title)
295
[17798]296    def getCertLongTitle(self, value):
297        """Compose certificate's longtitle.
298        """
299        return "%s (%s)" % (value.title, value.code)
300
[11814]301    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
[16299]302                        from_username, usertype, portal, body, subject,
303                        bcc_to=None):
[7358]304        """Send an email with data provided by forms.
305        """
306        config = grok.getSite()['configuration']
[16213]307        text = _(u"""${e}
[7358]308
[16213]309---
310${a} (id: ${b})
311${d}
[7734]312""")
[11814]313        text = _(text, mapping={
314            'a': from_name,
315            'b': from_username,
316            'c': usertype,
317            'd': portal,
318            'e': body})
[7811]319        body = translate(text, 'waeup.kofa',
[7734]320            target_language=self.PORTAL_LANGUAGE)
[8436]321        if not (from_addr and rcpt_addr):
322            return False
[7400]323        return send_mail(
[11814]324            from_name, from_addr, rcpt_name, rcpt_addr,
[16299]325            subject, body, config, None, bcc_to)
[7359]326
[15964]327    def getUsers(self):
328        users = sorted(
329            grok.getSite()['users'].items(), key=lambda x: x[1].title)
330        for key, val in users:
331            yield(dict(name=key, val="%s (%s)" % (val.title, val.name)))
332
[8181]333    @property
334    def tzinfo(self):
[13124]335        """Time zone of the university.
336        """
[8181]337        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]338        # For Germany: pytz.timezone('Europe/Berlin')
[8181]339        return pytz.utc
340
[11814]341    def fullname(self, firstname, lastname, middlename=None):
[13124]342        """Construct fullname.
[7477]343        """
[7359]344        # We do not necessarily have the middlename attribute
345        if middlename:
[8603]346            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]347        else:
[8603]348            name = '%s %s' % (firstname, lastname)
[13492]349        if '<' in name:
350            return 'XXX'
[11814]351        return string.capwords(
352            name.replace('-', ' - ')).replace(' - ', '-')
[7365]353
[15287]354    def genPassword(self, length=4, chars=string.letters + string.digits):
[7477]355        """Generate a random password.
356        """
[15287]357        return ''.join([
358            r().choice(string.uppercase) +
359            r().choice(string.lowercase) +
360            r().choice(string.digits) for i in range(length)])
[7365]361
[8853]362    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[13124]363        """Send credentials as email. Input is the user for which credentials
364        are sent and the password. Method returns True or False to indicate
365        successful operation.
[7365]366        """
[17064]367        subject = _('Your Kofa credentials')
[7734]368        text = _(u"""Dear ${a},
[7365]369
[7734]370${b}
[7365]371Student Registration and Information Portal of
[7734]372${c}.
[7365]373
[7734]374Your user name: ${d}
375Your password: ${e}
[8853]376${f}
[7365]377
378Please remember your user name and keep
379your password secret!
380
[7382]381Please also note that passwords are case-sensitive.
382
[7365]383Regards
[7734]384""")
[7399]385        config = grok.getSite()['configuration']
386        from_name = config.name_admin
[7402]387        from_addr = config.email_admin
[7407]388        rcpt_name = user.title
389        rcpt_addr = user.email
[11814]390        text = _(text, mapping={
391            'a': rcpt_name,
392            'b': msg,
393            'c': config.name,
394            'd': user.name,
395            'e': password,
396            'f': url_info})
[7734]397
[7811]398        body = translate(text, 'waeup.kofa',
[7734]399            target_language=self.PORTAL_LANGUAGE)
[7399]400        return send_mail(
[11814]401            from_name, from_addr, rcpt_name, rcpt_addr,
402            subject, body, config)
[9987]403
[16551]404    def informNewStudent(self, user, pw, login_url, rpw_url):
405        """Inform student that a new student account has been created.
406        """
[17067]407        subject = _('Your new Kofa student account')
[16551]408        text = _(u"""Dear ${a},
409
410Your student record of the Student Registration and Information Portal of
411${b} has been created for you.
412
413Your user name: ${c}
414Your password: ${d}
415Login: ${e}
416
417Or request a new secure password here: ${f}
418
419Regards
420""")
421        config = grok.getSite()['configuration']
422        from_name = config.name_admin
423        from_addr = config.email_admin
424        rcpt_name = user.title
425        rcpt_addr = user.email
426
427        text = _(text, mapping={
428            'a': rcpt_name,
429            'b': config.name,
430            'c': user.name,
431            'd': pw,
432            'e': login_url,
433            'f': rpw_url
434            })
435        body = translate(text, 'waeup.kofa',
436            target_language=self.PORTAL_LANGUAGE)
437        return send_mail(
438            from_name, from_addr, rcpt_name, rcpt_addr,
439            subject, body, config)
440
441
[16976]442    def informApplicant(self, applicant):
443        """Inform applicant that the application form was successfully
444        submitted.
445        """
446        if not getattr(applicant.__parent__, 'send_email', False):
447            return
448        subject = 'Your application form was successfully submitted'
449        text = _(u"""Dear ${a},
450
451Your application ${b} has been successfully submitted to ${c}.
452
453Regards
454""")
455        config = grok.getSite()['configuration']
456        from_name = config.name_admin
457        from_addr = config.email_admin
458        rcpt_name = applicant.display_fullname
459        rcpt_addr = applicant.email
460        session = '%s/%s' % (
461            applicant.__parent__.year, applicant.__parent__.year+1)
462        text = _(text, mapping={
463            'a': rcpt_name,
464            'b': applicant.applicant_id,
465            'c': config.name,
466            })
467        body = translate(text, 'waeup.kofa',
468            target_language=self.PORTAL_LANGUAGE)
469        return send_mail(
470            from_name, from_addr, rcpt_name, rcpt_addr,
471            subject, body, config)
472
[14014]473    def inviteReferee(self, referee, applicant, url_info=None):
474        """Send invitation email to referee.
475        """
476        config = grok.getSite()['configuration']
477        subject = 'Request for referee report from %s' % config.name
478        text = _(u"""Dear ${a},
479
[14040]480The candidate with Id ${b} and name ${c} applied to
481the ${d} to study ${e} for the ${f} session.
[16777]482The candidate has listed you as referee. You are, therefore, required to,
483kindly, provide your referral remarks on or before ${g}. Please use the
484following form:
[14014]485
[14040]486${h}
487
488Thank You
489
490The Secretary
[16777]491School of Postgraduate Studies
[14040]492${d}
[14014]493""")
494        from_name = config.name_admin
495        from_addr = config.email_admin
496        rcpt_name = referee.name
497        rcpt_addr = referee.email
[14040]498        session = '%s/%s' % (
499            applicant.__parent__.year, applicant.__parent__.year+1)
[14014]500        text = _(text, mapping={
501            'a': rcpt_name,
[14040]502            'b': applicant.applicant_id,
503            'c': applicant.display_fullname,
504            'd': config.name,
505            'e': applicant.course1.title,
506            'f': session,
507            'g': applicant.__parent__.enddate,
508            'h': url_info,
509            })
[14014]510
511        body = translate(text, 'waeup.kofa',
512            target_language=self.PORTAL_LANGUAGE)
513        return send_mail(
514            from_name, from_addr, rcpt_name, rcpt_addr,
515            subject, body, config)
516
[9987]517    def getPaymentItem(self, payment):
[13124]518        """Return payment item. This method can be used to customize the
519        `display_item` property attribute, e.g. in order to hide bed coordinates
520        if maintenance fee is not paid.
[9987]521        """
522        return payment.p_item
[11815]523
524    def expensive_actions_allowed(self, type=None, request=None):
525        """Tell, whether expensive actions are currently allowed.
526        Check system load/health (or other external circumstances) and
527        locally set values to see, whether expensive actions should be
528        allowed (`True`) or better avoided (`False`).
529        Use this to allow or forbid exports, report generations, or
530        similar actions.
531        """
532        max_values = self.SYSTEM_MAX_LOAD
[11816]533        for (key, func) in (
534            ('swap-mem', psutil.swap_memory),
[11818]535            ('virt-mem', psutil.virtual_memory),
[11816]536            ):
537            max_val = max_values.get(key, None)
538            if max_val is None:
539                continue
540            mem_val = func()
[11815]541            if isinstance(max_val, float):
[11816]542                # percents
[11821]543                if max_val < 0.0:
544                    max_val = 100.0 + max_val
[11816]545                if mem_val.percent > max_val:
[11815]546                    return False
547            else:
[11816]548                # number of bytes
[11821]549                if max_val < 0:
550                    max_val = mem_val.total + max_val
[11816]551                if mem_val.used > max_val:
[11815]552                    return False
553        return True
[13198]554
555    def export_disabled_message(self):
556        export_disabled_message = grok.getSite()[
557            'configuration'].export_disabled_message
558        if export_disabled_message:
559            return export_disabled_message
[14473]560        return None
561
562    def format_float(self, value, prec):
[15476]563        # >>> 4.6 * 100
564        # 459.99999999999994
565        value = decimal.Decimal(str(value))
[14473]566        # cut floating point value
567        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
568        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.