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

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

Send email after final submission of application form.

  • Property svn:keywords set to Id
File size: 16.4 KB
RevLine 
[7358]1## $Id: utils.py 16976 2022-06-29 10:24:59Z 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',
[16828]138        'transferred': 'Transferred',
[7843]139        'ug_ft': 'Undergraduate Full-Time',
140        'ug_pt': 'Undergraduate Part-Time',
[7993]141        'pg_ft': 'Postgraduate Full-Time',
142        'pg_pt': 'Postgraduate Part-Time',
[7681]143        }
144
[11451]145    DISABLE_PAYMENT_GROUP_DICT = {
146        'sf_all': 'School Fee - All Students',
147        }
148
[7841]149    APP_CATS_DICT = {
[7843]150        'basic': 'Basic Application',
[7681]151        'no': 'no application',
152        'pg': 'Postgraduate',
153        'sandwich': 'Sandwich',
154        'cest': 'Part-Time, Diploma, Certificate'
155        }
156
[7841]157    SEMESTER_DICT = {
[10437]158        1: '1st Semester',
159        2: '2nd Semester',
[7681]160        3: 'Combined',
[16812]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',
[7681]168        }
169
[14638]170    COURSE_CATEGORY_DICT = {
171        }
172
[9400]173    SPECIAL_HANDLING_DICT = {
174        'regular': 'Regular Hostel',
175        'blocked': 'Blocked Hostel',
[10831]176        'pg': 'Postgraduate Hostel'
[9400]177        }
178
[10831]179    SPECIAL_APP_DICT = {
180        'transcript': 'Transcript Fee Payment',
[11575]181        'clearance': 'Acceptance Fee',
[10831]182        }
183
[9405]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',
[9866]191        'application': 'Application Fee',
[15553]192        'app_balance': 'Application Fee Balance',
[10449]193        'transcript': 'Transcript Fee',
[15664]194        'late_registration': 'Late Course Registration Fee',
[15685]195        'combi': 'Combi Payment',
[9405]196        }
197
[16431]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
[15432]204    def selectable_payment_categories(self, student):
205        return self.PAYMENT_CATEGORIES
[9730]206
[16431]207    def selectable_payment_options(self, student):
208        return self.PAYMENT_OPTIONS
209
[15432]210    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
[9862]211
[12564]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
[9868]219    BALANCE_PAYMENT_CATEGORIES = {
[9867]220        'schoolfee': 'School Fee',
221        }
[9864]222
[15664]223    COMBI_PAYMENT_CATEGORIES = {
224        'gown': 'Gown Hire Fee',
225        'transcript': 'Transcript Fee',
226        'late_registration': 'Late Course Registration Fee',
227        }
228
[9649]229    MODE_GROUPS = {
[11814]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',),
[9649]235        }
236
[13125]237    VERDICTS_DICT = {
238        '0': _('(not yet)'),
239        'A': 'Successful student',
240        'B': 'Student with carryover courses',
241        'C': 'Student on probation',
242        }
243
[11800]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,
[11969]249    #: `cpu-load` = CPU load in percent.
[11800]250    SYSTEM_MAX_LOAD = {
251        'swap-mem': None,
252        'virt-mem': None,
253        'cpu-load': 100.0,
254        }
255
[15430]256    #: Maximum number of files listed in `finished` subfolder
257    MAX_FILES = 100
258
[15833]259    #: Maximum size in Bytes of passport images in the applicants and
260    #: students section
261    MAX_PASSPORT_SIZE = 50 * 1024
262
[15609]263    #: Temporary passwords and parents password validity period
264    TEMP_PASSWORD_MINUTES = 10
265
[11814]266    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
[16299]267                        from_username, usertype, portal, body, subject,
268                        bcc_to=None):
[7358]269        """Send an email with data provided by forms.
270        """
271        config = grok.getSite()['configuration']
[16213]272        text = _(u"""${e}
[7358]273
[16213]274---
275${a} (id: ${b})
276${d}
[7734]277""")
[11814]278        text = _(text, mapping={
279            'a': from_name,
280            'b': from_username,
281            'c': usertype,
282            'd': portal,
283            'e': body})
[7811]284        body = translate(text, 'waeup.kofa',
[7734]285            target_language=self.PORTAL_LANGUAGE)
[8436]286        if not (from_addr and rcpt_addr):
287            return False
[7400]288        return send_mail(
[11814]289            from_name, from_addr, rcpt_name, rcpt_addr,
[16299]290            subject, body, config, None, bcc_to)
[7359]291
[15964]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
[8181]298    @property
299    def tzinfo(self):
[13124]300        """Time zone of the university.
301        """
[8181]302        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]303        # For Germany: pytz.timezone('Europe/Berlin')
[8181]304        return pytz.utc
305
[11814]306    def fullname(self, firstname, lastname, middlename=None):
[13124]307        """Construct fullname.
[7477]308        """
[7359]309        # We do not necessarily have the middlename attribute
310        if middlename:
[8603]311            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]312        else:
[8603]313            name = '%s %s' % (firstname, lastname)
[13492]314        if '<' in name:
315            return 'XXX'
[11814]316        return string.capwords(
317            name.replace('-', ' - ')).replace(' - ', '-')
[7365]318
[15287]319    def genPassword(self, length=4, chars=string.letters + string.digits):
[7477]320        """Generate a random password.
321        """
[15287]322        return ''.join([
323            r().choice(string.uppercase) +
324            r().choice(string.lowercase) +
325            r().choice(string.digits) for i in range(length)])
[7365]326
[8853]327    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[13124]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.
[7365]331        """
[7819]332        subject = 'Your Kofa credentials'
[7734]333        text = _(u"""Dear ${a},
[7365]334
[7734]335${b}
[7365]336Student Registration and Information Portal of
[7734]337${c}.
[7365]338
[7734]339Your user name: ${d}
340Your password: ${e}
[8853]341${f}
[7365]342
343Please remember your user name and keep
344your password secret!
345
[7382]346Please also note that passwords are case-sensitive.
347
[7365]348Regards
[7734]349""")
[7399]350        config = grok.getSite()['configuration']
351        from_name = config.name_admin
[7402]352        from_addr = config.email_admin
[7407]353        rcpt_name = user.title
354        rcpt_addr = user.email
[11814]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})
[7734]362
[7811]363        body = translate(text, 'waeup.kofa',
[7734]364            target_language=self.PORTAL_LANGUAGE)
[7399]365        return send_mail(
[11814]366            from_name, from_addr, rcpt_name, rcpt_addr,
367            subject, body, config)
[9987]368
[16551]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
[16976]407    def informApplicant(self, applicant):
408        """Inform applicant that the application form was successfully
409        submitted.
410        """
411        if not getattr(applicant.__parent__, 'send_email', False):
412            return
413        subject = 'Your application form was successfully submitted'
414        text = _(u"""Dear ${a},
415
416Your application ${b} has been successfully submitted to ${c}.
417
418Regards
419""")
420        config = grok.getSite()['configuration']
421        from_name = config.name_admin
422        from_addr = config.email_admin
423        rcpt_name = applicant.display_fullname
424        rcpt_addr = applicant.email
425        session = '%s/%s' % (
426            applicant.__parent__.year, applicant.__parent__.year+1)
427        text = _(text, mapping={
428            'a': rcpt_name,
429            'b': applicant.applicant_id,
430            'c': config.name,
431            })
432        body = translate(text, 'waeup.kofa',
433            target_language=self.PORTAL_LANGUAGE)
434        return send_mail(
435            from_name, from_addr, rcpt_name, rcpt_addr,
436            subject, body, config)
437
[14014]438    def inviteReferee(self, referee, applicant, url_info=None):
439        """Send invitation email to referee.
440        """
441        config = grok.getSite()['configuration']
442        subject = 'Request for referee report from %s' % config.name
443        text = _(u"""Dear ${a},
444
[14040]445The candidate with Id ${b} and name ${c} applied to
446the ${d} to study ${e} for the ${f} session.
[16777]447The candidate has listed you as referee. You are, therefore, required to,
448kindly, provide your referral remarks on or before ${g}. Please use the
449following form:
[14014]450
[14040]451${h}
452
453Thank You
454
455The Secretary
[16777]456School of Postgraduate Studies
[14040]457${d}
[14014]458""")
459        from_name = config.name_admin
460        from_addr = config.email_admin
461        rcpt_name = referee.name
462        rcpt_addr = referee.email
[14040]463        session = '%s/%s' % (
464            applicant.__parent__.year, applicant.__parent__.year+1)
[14014]465        text = _(text, mapping={
466            'a': rcpt_name,
[14040]467            'b': applicant.applicant_id,
468            'c': applicant.display_fullname,
469            'd': config.name,
470            'e': applicant.course1.title,
471            'f': session,
472            'g': applicant.__parent__.enddate,
473            'h': url_info,
474            })
[14014]475
476        body = translate(text, 'waeup.kofa',
477            target_language=self.PORTAL_LANGUAGE)
478        return send_mail(
479            from_name, from_addr, rcpt_name, rcpt_addr,
480            subject, body, config)
481
[9987]482    def getPaymentItem(self, payment):
[13124]483        """Return payment item. This method can be used to customize the
484        `display_item` property attribute, e.g. in order to hide bed coordinates
485        if maintenance fee is not paid.
[9987]486        """
487        return payment.p_item
[11815]488
489    def expensive_actions_allowed(self, type=None, request=None):
490        """Tell, whether expensive actions are currently allowed.
491        Check system load/health (or other external circumstances) and
492        locally set values to see, whether expensive actions should be
493        allowed (`True`) or better avoided (`False`).
494        Use this to allow or forbid exports, report generations, or
495        similar actions.
496        """
497        max_values = self.SYSTEM_MAX_LOAD
[11816]498        for (key, func) in (
499            ('swap-mem', psutil.swap_memory),
[11818]500            ('virt-mem', psutil.virtual_memory),
[11816]501            ):
502            max_val = max_values.get(key, None)
503            if max_val is None:
504                continue
505            mem_val = func()
[11815]506            if isinstance(max_val, float):
[11816]507                # percents
[11821]508                if max_val < 0.0:
509                    max_val = 100.0 + max_val
[11816]510                if mem_val.percent > max_val:
[11815]511                    return False
512            else:
[11816]513                # number of bytes
[11821]514                if max_val < 0:
515                    max_val = mem_val.total + max_val
[11816]516                if mem_val.used > max_val:
[11815]517                    return False
518        return True
[13198]519
520    def export_disabled_message(self):
521        export_disabled_message = grok.getSite()[
522            'configuration'].export_disabled_message
523        if export_disabled_message:
524            return export_disabled_message
[14473]525        return None
526
527    def format_float(self, value, prec):
[15476]528        # >>> 4.6 * 100
529        # 459.99999999999994
530        value = decimal.Decimal(str(value))
[14473]531        # cut floating point value
532        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
533        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.