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

Last change on this file since 15430 was 15430, checked in by Henrik Bettermann, 5 years ago

Make maximum number of files listed in finished subfolder customizable.

  • Property svn:keywords set to Id
File size: 12.9 KB
Line 
1## $Id: utils.py 15430 2019-05-28 06:14:44Z 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
24from copy import deepcopy
25from random import SystemRandom as r
26from zope.i18n import translate
27from waeup.kofa.interfaces import IKofaUtils
28from waeup.kofa.interfaces import MessageFactory as _
29from waeup.kofa.smtp import send_mail as send_mail_internally
30from waeup.kofa.utils.helpers import get_sorted_preferred
31from waeup.kofa.utils.degrees import DEGREES_DICT
32
33
34def send_mail(from_name, from_addr,
35              rcpt_name, rcpt_addr,
36              subject, body, config):
37    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
38
39    Merely here to stay compatible with lots of calls to this place.
40    """
41    mail_id = send_mail_internally(
42        from_name, from_addr, rcpt_name, rcpt_addr,
43        subject, body, config)
44    return True
45
46
47#: A list of phone prefixes (order num, country, prefix).
48#: Items with same order num will be sorted alphabetically.
49#: The lower the order num, the higher the precedence.
50INT_PHONE_PREFIXES = [
51    (99, _('Germany'), '49'),
52    (1, _('Nigeria'), '234'),
53    (99, _('U.S.'), '1'),
54    ]
55
56
57def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
58    """Sorted tuples of phone prefixes.
59
60    Ordered as shown above and formatted for use in select boxes.
61
62    If request is given, we'll try to translate all country names in
63    order to sort alphabetically correctly.
64
65    XXX: This is a function (and not a constant) as different
66    languages might give different orders. This is not tested yet.
67
68    XXX: If we really want to use alphabetic ordering here, we might
69    think about caching results of translations.
70    """
71    if request is not None:
72        data = [
73            (x, translate(y, context=request), z)
74            for x, y, z in data]
75    return tuple([
76        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
77        for x in sorted(data)
78        ])
79
80
81class KofaUtils(grok.GlobalUtility):
82    """A collection of parameters and methods subject to customization.
83    """
84    grok.implements(IKofaUtils)
85
86    #: This the only place where we define the portal language
87    #: which is used for the translation of system messages
88    #: (e.g. object histories) pdf slips.
89    PORTAL_LANGUAGE = 'en'
90
91    DEGREES_DICT = DEGREES_DICT
92
93    PREFERRED_LANGUAGES_DICT = {
94        'en': (1, u'English'),
95        'fr': (2, u'Français'),
96        'de': (3, u'Deutsch'),
97        'ha': (4, u'Hausa'),
98        'yo': (5, u'Yoruba'),
99        'ig': (6, u'Igbo'),
100        }
101
102    #: A function to return
103    @classmethod
104    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
105        return sorted_phone_prefixes(data, request)
106
107    EXAM_SUBJECTS_DICT = {
108        'math': 'Mathematics',
109        'computer_science': 'Computer Science',
110        }
111
112    #: Exam grades. The tuple is sorted as it should be displayed in
113    #: select boxes.
114    EXAM_GRADES = (
115        ('A', 'Best'),
116        ('B', 'Better'),
117        ('C', 'Good'),
118        )
119
120    INST_TYPES_DICT = {
121        'none': '',
122        'faculty': 'Faculty of',
123        'department': 'Department of',
124        'school': 'School of',
125        'office': 'Office for',
126        'centre': 'Centre for',
127        'institute': 'Institute of',
128        'school_for': 'School for',
129        'college': 'College of',
130        'directorate': 'Directorate of',
131        }
132
133    STUDY_MODES_DICT = {
134        'transfer': 'Transfer',
135        'ug_ft': 'Undergraduate Full-Time',
136        'ug_pt': 'Undergraduate Part-Time',
137        'pg_ft': 'Postgraduate Full-Time',
138        'pg_pt': 'Postgraduate Part-Time',
139        }
140
141    DISABLE_PAYMENT_GROUP_DICT = {
142        'sf_all': 'School Fee - All Students',
143        }
144
145    APP_CATS_DICT = {
146        'basic': 'Basic Application',
147        'no': 'no application',
148        'pg': 'Postgraduate',
149        'sandwich': 'Sandwich',
150        'cest': 'Part-Time, Diploma, Certificate'
151        }
152
153    SEMESTER_DICT = {
154        1: '1st Semester',
155        2: '2nd Semester',
156        3: 'Combined',
157        9: 'N/A'
158        }
159
160    COURSE_CATEGORY_DICT = {
161        }
162
163    SPECIAL_HANDLING_DICT = {
164        'regular': 'Regular Hostel',
165        'blocked': 'Blocked Hostel',
166        'pg': 'Postgraduate Hostel'
167        }
168
169    SPECIAL_APP_DICT = {
170        'transcript': 'Transcript Fee Payment',
171        'clearance': 'Acceptance Fee',
172        }
173
174    PAYMENT_CATEGORIES = {
175        'schoolfee': 'School Fee',
176        'clearance': 'Acceptance Fee',
177        'bed_allocation': 'Bed Allocation Fee',
178        'hostel_maintenance': 'Hostel Maintenance Fee',
179        'transfer': 'Transfer Fee',
180        'gown': 'Gown Hire Fee',
181        'application': 'Application Fee',
182        'transcript': 'Transcript Fee',
183        'late_registration': 'Late Course Registration Fee'
184        }
185
186    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
187
188    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
189
190    REPORTABLE_PAYMENT_CATEGORIES = {
191        'schoolfee': 'School Fee',
192        'clearance': 'Acceptance Fee',
193        'hostel_maintenance': 'Hostel Maintenance Fee',
194        'gown': 'Gown Hire Fee',
195        }
196
197    BALANCE_PAYMENT_CATEGORIES = {
198        'schoolfee': 'School Fee',
199        }
200
201    MODE_GROUPS = {
202        'All': ('all',),
203        'Undergraduate Full-Time': ('ug_ft',),
204        'Undergraduate Part-Time': ('ug_pt',),
205        'Postgraduate Full-Time': ('pg_ft',),
206        'Postgraduate Part-Time': ('pg_pt',),
207        }
208
209    VERDICTS_DICT = {
210        '0': _('(not yet)'),
211        'A': 'Successful student',
212        'B': 'Student with carryover courses',
213        'C': 'Student on probation',
214        }
215
216    #: Set positive number for allowed max, negative for required min
217    #: avail.
218    #: Use integer for bytes value, float for percent
219    #: value. `cpu-load`, of course, accepts float values only.
220    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
221    #: `cpu-load` = CPU load in percent.
222    SYSTEM_MAX_LOAD = {
223        'swap-mem': None,
224        'virt-mem': None,
225        'cpu-load': 100.0,
226        }
227
228    #: Maximum number of files listed in `finished` subfolder
229    MAX_FILES = 100
230
231    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
232                        from_username, usertype, portal, body, subject):
233        """Send an email with data provided by forms.
234        """
235        config = grok.getSite()['configuration']
236        text = _(u"""Fullname: ${a}
237User Id: ${b}
238User Type: ${c}
239Portal: ${d}
240
241${e}
242""")
243        text = _(text, mapping={
244            'a': from_name,
245            'b': from_username,
246            'c': usertype,
247            'd': portal,
248            'e': body})
249        body = translate(text, 'waeup.kofa',
250            target_language=self.PORTAL_LANGUAGE)
251        if not (from_addr and rcpt_addr):
252            return False
253        return send_mail(
254            from_name, from_addr, rcpt_name, rcpt_addr,
255            subject, body, config)
256
257    @property
258    def tzinfo(self):
259        """Time zone of the university.
260        """
261        # For Nigeria: pytz.timezone('Africa/Lagos')
262        # For Germany: pytz.timezone('Europe/Berlin')
263        return pytz.utc
264
265    def fullname(self, firstname, lastname, middlename=None):
266        """Construct fullname.
267        """
268        # We do not necessarily have the middlename attribute
269        if middlename:
270            name = '%s %s %s' % (firstname, middlename, lastname)
271        else:
272            name = '%s %s' % (firstname, lastname)
273        if '<' in name:
274            return 'XXX'
275        return string.capwords(
276            name.replace('-', ' - ')).replace(' - ', '-')
277
278    def genPassword(self, length=4, chars=string.letters + string.digits):
279        """Generate a random password.
280        """
281        return ''.join([
282            r().choice(string.uppercase) +
283            r().choice(string.lowercase) +
284            r().choice(string.digits) for i in range(length)])
285
286    def sendCredentials(self, user, password=None, url_info=None, msg=None):
287        """Send credentials as email. Input is the user for which credentials
288        are sent and the password. Method returns True or False to indicate
289        successful operation.
290        """
291        subject = 'Your Kofa credentials'
292        text = _(u"""Dear ${a},
293
294${b}
295Student Registration and Information Portal of
296${c}.
297
298Your user name: ${d}
299Your password: ${e}
300${f}
301
302Please remember your user name and keep
303your password secret!
304
305Please also note that passwords are case-sensitive.
306
307Regards
308""")
309        config = grok.getSite()['configuration']
310        from_name = config.name_admin
311        from_addr = config.email_admin
312        rcpt_name = user.title
313        rcpt_addr = user.email
314        text = _(text, mapping={
315            'a': rcpt_name,
316            'b': msg,
317            'c': config.name,
318            'd': user.name,
319            'e': password,
320            'f': url_info})
321
322        body = translate(text, 'waeup.kofa',
323            target_language=self.PORTAL_LANGUAGE)
324        return send_mail(
325            from_name, from_addr, rcpt_name, rcpt_addr,
326            subject, body, config)
327
328    def inviteReferee(self, referee, applicant, url_info=None):
329        """Send invitation email to referee.
330        """
331        config = grok.getSite()['configuration']
332        subject = 'Request for referee report from %s' % config.name
333        text = _(u"""Dear ${a},
334
335The candidate with Id ${b} and name ${c} applied to
336the ${d} to study ${e} for the ${f} session.
337The candidate has listed you as referee. You are thus required to kindly use
338the link below to provide your referral remarks on or before
339${g}.
340
341${h}
342
343Thank You
344
345The Secretary
346Post Graduate School
347${d}
348""")
349        from_name = config.name_admin
350        from_addr = config.email_admin
351        rcpt_name = referee.name
352        rcpt_addr = referee.email
353        session = '%s/%s' % (
354            applicant.__parent__.year, applicant.__parent__.year+1)
355        text = _(text, mapping={
356            'a': rcpt_name,
357            'b': applicant.applicant_id,
358            'c': applicant.display_fullname,
359            'd': config.name,
360            'e': applicant.course1.title,
361            'f': session,
362            'g': applicant.__parent__.enddate,
363            'h': url_info,
364            })
365
366        body = translate(text, 'waeup.kofa',
367            target_language=self.PORTAL_LANGUAGE)
368        return send_mail(
369            from_name, from_addr, rcpt_name, rcpt_addr,
370            subject, body, config)
371
372    def getPaymentItem(self, payment):
373        """Return payment item. This method can be used to customize the
374        `display_item` property attribute, e.g. in order to hide bed coordinates
375        if maintenance fee is not paid.
376        """
377        return payment.p_item
378
379    def expensive_actions_allowed(self, type=None, request=None):
380        """Tell, whether expensive actions are currently allowed.
381        Check system load/health (or other external circumstances) and
382        locally set values to see, whether expensive actions should be
383        allowed (`True`) or better avoided (`False`).
384        Use this to allow or forbid exports, report generations, or
385        similar actions.
386        """
387        max_values = self.SYSTEM_MAX_LOAD
388        for (key, func) in (
389            ('swap-mem', psutil.swap_memory),
390            ('virt-mem', psutil.virtual_memory),
391            ):
392            max_val = max_values.get(key, None)
393            if max_val is None:
394                continue
395            mem_val = func()
396            if isinstance(max_val, float):
397                # percents
398                if max_val < 0.0:
399                    max_val = 100.0 + max_val
400                if mem_val.percent > max_val:
401                    return False
402            else:
403                # number of bytes
404                if max_val < 0:
405                    max_val = mem_val.total + max_val
406                if mem_val.used > max_val:
407                    return False
408        return True
409
410    def export_disabled_message(self):
411        export_disabled_message = grok.getSite()[
412            'configuration'].export_disabled_message
413        if export_disabled_message:
414            return export_disabled_message
415        return None
416
417    def format_float(self, value, prec):
418        # cut floating point value
419        value = int(pow(10, prec)*value) / (1.0*pow(10, prec))
420        return '{:{width}.{prec}f}'.format(value, width=0, prec=prec)
Note: See TracBrowser for help on using the repository browser.