source: main/waeup.kofa/branches/uli-diazo-themed/src/waeup/kofa/utils/utils.py @ 11013

Last change on this file since 11013 was 10831, checked in by Henrik Bettermann, 11 years ago

Implement a special application procedure. This application is meant for supplementary payments by alumni and other persons who are not students of the portal.

Attention: All custom packages have to be adjusted.

  • Property svn:keywords set to Id
File size: 8.5 KB
Line 
1## $Id: utils.py 10831 2013-12-10 06:24:03Z 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 os
21import grok
22import string
23import pytz
24from copy import deepcopy
25from random import SystemRandom as r
26from zope.i18n import translate
27from zope.interface import implements
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.countries import COUNTRIES
32from waeup.kofa.utils.helpers import get_sorted_preferred
33
34def send_mail(from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config):
35    """Wrapper for the real SMTP functionality in :mod:`waeup.kofa.smtp`.
36
37    Merely here to stay compatible with lots of calls to this place.
38    """
39    mail_id = send_mail_internally(
40        from_name, from_addr, rcpt_name, rcpt_addr,
41        subject, body, config)
42    return True
43
44#: A list of phone prefixes (order num, country, prefix).
45#: Items with same order num will be sorted alphabetically.
46#: The lower the order num, the higher the precedence.
47INT_PHONE_PREFIXES = [
48    (99, _('Germany'), '49'),
49    ( 1, _('Nigeria'), '234'),
50    (99, _('U.S.'), '1'),
51    ]
52
53def sorted_phone_prefixes(data = INT_PHONE_PREFIXES, request=None):
54    """Sorted tuples of phone prefixes.
55
56    Ordered as shown above and formatted for use in select boxes.
57
58    If request is given, we'll try to translate all country names in
59    order to sort alphabetically correctly.
60
61    XXX: This is a function (and not a constant) as different
62    languages might give different orders. This is not tested yet.
63
64    XXX: If we really want to use alphabetic ordering here, we might
65    think about caching results of translations.
66    """
67    if request is not None:
68        data = [
69            (x, translate(y, context=request), z)
70            for x, y, z in data]
71    return tuple([
72        ('%s (+%s)' % (x[1],x[2]), '+%s' % x[2])
73        for x in sorted(data)
74        ])
75
76class KofaUtils(grok.GlobalUtility):
77    """A collection of parameters and methods subject to customization.
78
79    """
80    grok.implements(IKofaUtils)
81    # This the only place where we define the portal language
82    # which is used for the translation of system messages
83    # (e.g. object histories).
84    PORTAL_LANGUAGE = 'en'
85
86    PREFERRED_LANGUAGES_DICT = {
87        'en':(1, u'English'),
88        'fr':(2, u'Français'),
89        'de':(3, u'Deutsch'),
90        'ha':(4, u'Hausa'),
91        'yo':(5, u'Yoruba'),
92        'ig':(6, u'Igbo'),
93        }
94
95    #: A function to return
96    @classmethod
97    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
98        return sorted_phone_prefixes(data, request)
99
100    EXAM_SUBJECTS_DICT = {
101        'math': 'Mathematics',
102        'computer_science': 'Computer Science',
103        }
104
105    #: Exam grades. The tuple is sorted as it should be displayed in
106    #: select boxes.
107    EXAM_GRADES = (
108        ('A', 'Best'),
109        ('B', 'Better'),
110        ('C', 'Good'),
111        )
112
113    INST_TYPES_DICT = {
114        'none': '',
115        'faculty': 'Faculty of',
116        'department': 'Department of',
117        'school': 'School of',
118        'office': 'Office for',
119        'centre': 'Centre for',
120        'institute': 'Institute of',
121        'school_for': 'School for',
122        'college': 'College of',
123        'directorate': 'Directorate of',
124        }
125
126    STUDY_MODES_DICT = {
127        'transfer': 'Transfer',
128        'ug_ft': 'Undergraduate Full-Time',
129        'ug_pt': 'Undergraduate Part-Time',
130        'pg_ft': 'Postgraduate Full-Time',
131        'pg_pt': 'Postgraduate Part-Time',
132        }
133
134    APP_CATS_DICT = {
135        'basic': 'Basic Application',
136        'no': 'no application',
137        'pg': 'Postgraduate',
138        'sandwich': 'Sandwich',
139        'cest': 'Part-Time, Diploma, Certificate'
140        }
141
142    SEMESTER_DICT = {
143        1: '1st Semester',
144        2: '2nd Semester',
145        3: 'Combined',
146        9: 'N/A'
147        }
148
149    SPECIAL_HANDLING_DICT = {
150        'regular': 'Regular Hostel',
151        'blocked': 'Blocked Hostel',
152        'pg': 'Postgraduate Hostel'
153        }
154
155    SPECIAL_APP_DICT = {
156        'transcript': 'Transcript Fee Payment',
157        }
158
159    PAYMENT_CATEGORIES = {
160        'schoolfee': 'School Fee',
161        'clearance': 'Acceptance Fee',
162        'bed_allocation': 'Bed Allocation Fee',
163        'hostel_maintenance': 'Hostel Maintenance Fee',
164        'transfer': 'Transfer Fee',
165        'gown': 'Gown Hire Fee',
166        'application': 'Application Fee',
167        'transcript': 'Transcript Fee',
168        }
169
170    SELECTABLE_PAYMENT_CATEGORIES = deepcopy(PAYMENT_CATEGORIES)
171
172    PREVIOUS_PAYMENT_CATEGORIES = deepcopy(SELECTABLE_PAYMENT_CATEGORIES)
173
174    BALANCE_PAYMENT_CATEGORIES = {
175        'schoolfee': 'School Fee',
176        }
177
178    MODE_GROUPS = {
179        'All':('all',),
180        'Undergraduate Full-Time':('ug_ft',),
181        'Undergraduate Part-Time':('ug_pt',),
182        'Postgraduate Full-Time':('pg_ft',),
183        'Postgraduate Part-Time':('pg_pt',),
184        }
185
186    def sendContactForm(self,from_name,from_addr,rcpt_name,rcpt_addr,
187                from_username,usertype,portal,body,subject):
188        """Send an email with data provided by forms.
189        """
190        config = grok.getSite()['configuration']
191        text = _(u"""Fullname: ${a}
192User Id: ${b}
193User Type: ${c}
194Portal: ${d}
195
196${e}
197""")
198        text = _(text,
199            mapping = {
200            'a':from_name,
201            'b':from_username,
202            'c':usertype,
203            'd':portal,
204            'e':body})
205        body = translate(text, 'waeup.kofa',
206            target_language=self.PORTAL_LANGUAGE)
207        if not (from_addr and rcpt_addr):
208            return False
209        return send_mail(
210            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
211
212    @property
213    def tzinfo(self):
214        # For Nigeria: pytz.timezone('Africa/Lagos')
215        # For Germany: pytz.timezone('Europe/Berlin')
216        return pytz.utc
217
218    def fullname(self,firstname,lastname,middlename=None):
219        """Full name constructor.
220        """
221        # We do not necessarily have the middlename attribute
222        if middlename:
223            name = '%s %s %s' % (firstname, middlename, lastname)
224        else:
225            name = '%s %s' % (firstname, lastname)
226        return string.capwords(name.replace('-',' - ')).replace(' - ','-')
227
228
229    def genPassword(self, length=8, chars=string.letters + string.digits):
230        """Generate a random password.
231        """
232        return ''.join([r().choice(chars) for i in range(length)])
233
234
235    def sendCredentials(self, user, password=None, url_info=None, msg=None):
236        """Send credentials as email.
237
238        Input is the applicant for which credentials are sent and the
239        password.
240
241        Returns True or False to indicate successful operation.
242        """
243        subject = 'Your Kofa credentials'
244        text = _(u"""Dear ${a},
245
246${b}
247Student Registration and Information Portal of
248${c}.
249
250Your user name: ${d}
251Your password: ${e}
252${f}
253
254Please remember your user name and keep
255your password secret!
256
257Please also note that passwords are case-sensitive.
258
259Regards
260""")
261        config = grok.getSite()['configuration']
262        from_name = config.name_admin
263        from_addr = config.email_admin
264        rcpt_name = user.title
265        rcpt_addr = user.email
266        text = _(text,
267            mapping = {
268            'a':rcpt_name,
269            'b':msg,
270            'c':config.name,
271            'd':user.name,
272            'e':password,
273            'f':url_info})
274
275        body = translate(text, 'waeup.kofa',
276            target_language=self.PORTAL_LANGUAGE)
277        return send_mail(
278            from_name,from_addr,rcpt_name,rcpt_addr,subject,body,config)
279
280    def getPaymentItem(self, payment):
281        """Return payment item.
282
283        This method can be used to customize the display_item property method.
284        """
285        return payment.p_item
Note: See TracBrowser for help on using the repository browser.