[7191] | 1 | ## $Id: utils.py 15528 2019-07-29 12:04:20Z 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 | ## |
---|
[13076] | 18 | """General helper functions and utilities for the students section. |
---|
[6651] | 19 | """ |
---|
[7150] | 20 | import grok |
---|
[15234] | 21 | import textwrap |
---|
[8595] | 22 | from time import time |
---|
[15163] | 23 | from cStringIO import StringIO |
---|
[7318] | 24 | from reportlab.lib import colors |
---|
[7019] | 25 | from reportlab.lib.units import cm |
---|
| 26 | from reportlab.lib.pagesizes import A4 |
---|
[9015] | 27 | from reportlab.lib.styles import getSampleStyleSheet |
---|
| 28 | from reportlab.platypus import Paragraph, Image, Table, Spacer |
---|
[14256] | 29 | from reportlab.platypus.doctemplate import LayoutError |
---|
[11589] | 30 | from zope.event import notify |
---|
[9922] | 31 | from zope.schema.interfaces import ConstraintNotSatisfied |
---|
[9015] | 32 | from zope.component import getUtility, createObject |
---|
[7019] | 33 | from zope.formlib.form import setUpEditWidgets |
---|
[9015] | 34 | from zope.i18n import translate |
---|
[8596] | 35 | from waeup.kofa.interfaces import ( |
---|
[9762] | 36 | IExtFileStore, IKofaUtils, RETURNING, PAID, CLEARED, |
---|
[15163] | 37 | academic_sessions_vocab, IFileStoreNameChooser) |
---|
[7811] | 38 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
| 39 | from waeup.kofa.students.interfaces import IStudentsUtils |
---|
[10706] | 40 | from waeup.kofa.students.workflow import ADMITTED |
---|
[11589] | 41 | from waeup.kofa.students.vocabularies import StudyLevelSource, MatNumNotInSource |
---|
[9910] | 42 | from waeup.kofa.browser.pdf import ( |
---|
[9965] | 43 | ENTRY1_STYLE, format_html, NOTE_STYLE, HEADING_STYLE, |
---|
[11550] | 44 | get_signature_tables, get_qrcode) |
---|
[9910] | 45 | from waeup.kofa.browser.interfaces import IPDFCreator |
---|
[10256] | 46 | from waeup.kofa.utils.helpers import to_timezone |
---|
[6651] | 47 | |
---|
[7318] | 48 | SLIP_STYLE = [ |
---|
| 49 | ('VALIGN',(0,0),(-1,-1),'TOP'), |
---|
| 50 | #('FONT', (0,0), (-1,-1), 'Helvetica', 11), |
---|
| 51 | ] |
---|
[7019] | 52 | |
---|
[7318] | 53 | CONTENT_STYLE = [ |
---|
| 54 | ('VALIGN',(0,0),(-1,-1),'TOP'), |
---|
| 55 | #('FONT', (0,0), (-1,-1), 'Helvetica', 8), |
---|
| 56 | #('TEXTCOLOR',(0,0),(-1,0),colors.white), |
---|
[9906] | 57 | #('BACKGROUND',(0,0),(-1,0),colors.black), |
---|
| 58 | ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), |
---|
| 59 | ('BOX', (0,0), (-1,-1), 1, colors.black), |
---|
[7318] | 60 | ] |
---|
[7304] | 61 | |
---|
[7318] | 62 | FONT_SIZE = 10 |
---|
| 63 | FONT_COLOR = 'black' |
---|
| 64 | |
---|
[8112] | 65 | def trans(text, lang): |
---|
| 66 | # shortcut |
---|
| 67 | return translate(text, 'waeup.kofa', target_language=lang) |
---|
| 68 | |
---|
[10261] | 69 | def formatted_text(text, color=FONT_COLOR, lang='en'): |
---|
[7511] | 70 | """Turn `text`, `color` and `size` into an HTML snippet. |
---|
[7318] | 71 | |
---|
[7511] | 72 | The snippet is suitable for use with reportlab and generating PDFs. |
---|
| 73 | Wraps the `text` into a ``<font>`` tag with passed attributes. |
---|
| 74 | |
---|
| 75 | Also non-strings are converted. Raw strings are expected to be |
---|
| 76 | utf-8 encoded (usually the case for widgets etc.). |
---|
| 77 | |
---|
[7804] | 78 | Finally, a br tag is added if widgets contain div tags |
---|
| 79 | which are not supported by reportlab. |
---|
| 80 | |
---|
[7511] | 81 | The returned snippet is unicode type. |
---|
| 82 | """ |
---|
| 83 | if not isinstance(text, unicode): |
---|
| 84 | if isinstance(text, basestring): |
---|
| 85 | text = text.decode('utf-8') |
---|
| 86 | else: |
---|
| 87 | text = unicode(text) |
---|
[9717] | 88 | if text == 'None': |
---|
| 89 | text = '' |
---|
[13665] | 90 | # Very long matriculation numbers need to be wrapped |
---|
| 91 | if text.find(' ') == -1 and len(text.split('/')) > 6: |
---|
| 92 | text = '/'.join(text.split('/')[:5]) + \ |
---|
| 93 | '/ ' + '/'.join(text.split('/')[5:]) |
---|
[8141] | 94 | # Mainly for boolean values we need our customized |
---|
| 95 | # localisation of the zope domain |
---|
[10261] | 96 | text = translate(text, 'zope', target_language=lang) |
---|
[7804] | 97 | text = text.replace('</div>', '<br /></div>') |
---|
[9910] | 98 | tag1 = u'<font color="%s">' % (color) |
---|
[7511] | 99 | return tag1 + u'%s</font>' % text |
---|
| 100 | |
---|
[8481] | 101 | def generate_student_id(): |
---|
[8410] | 102 | students = grok.getSite()['students'] |
---|
| 103 | new_id = students.unique_student_id |
---|
| 104 | return new_id |
---|
[6742] | 105 | |
---|
[7186] | 106 | def set_up_widgets(view, ignore_request=False): |
---|
[7019] | 107 | view.adapters = {} |
---|
| 108 | view.widgets = setUpEditWidgets( |
---|
| 109 | view.form_fields, view.prefix, view.context, view.request, |
---|
| 110 | adapters=view.adapters, for_display=True, |
---|
| 111 | ignore_request=ignore_request |
---|
| 112 | ) |
---|
| 113 | |
---|
[11550] | 114 | def render_student_data(studentview, context, omit_fields=(), |
---|
[14292] | 115 | lang='en', slipname=None, no_passport=False): |
---|
[7318] | 116 | """Render student table for an existing frame. |
---|
| 117 | """ |
---|
| 118 | width, height = A4 |
---|
[7186] | 119 | set_up_widgets(studentview, ignore_request=True) |
---|
[7318] | 120 | data_left = [] |
---|
[11550] | 121 | data_middle = [] |
---|
[7019] | 122 | style = getSampleStyleSheet() |
---|
[7280] | 123 | img = getUtility(IExtFileStore).getFileByContext( |
---|
| 124 | studentview.context, attr='passport.jpg') |
---|
| 125 | if img is None: |
---|
[7811] | 126 | from waeup.kofa.browser import DEFAULT_PASSPORT_IMAGE_PATH |
---|
[7280] | 127 | img = open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb') |
---|
[7318] | 128 | doc_img = Image(img.name, width=4*cm, height=4*cm, kind='bound') |
---|
| 129 | data_left.append([doc_img]) |
---|
| 130 | #data.append([Spacer(1, 12)]) |
---|
[9141] | 131 | |
---|
[10261] | 132 | f_label = trans(_('Name:'), lang) |
---|
[9910] | 133 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[9911] | 134 | f_text = formatted_text(studentview.context.display_fullname) |
---|
[9910] | 135 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 136 | data_middle.append([f_label,f_text]) |
---|
[9141] | 137 | |
---|
[7019] | 138 | for widget in studentview.widgets: |
---|
[9141] | 139 | if 'name' in widget.name: |
---|
[7019] | 140 | continue |
---|
[9911] | 141 | f_label = translate( |
---|
[7811] | 142 | widget.label.strip(), 'waeup.kofa', |
---|
[10261] | 143 | target_language=lang) |
---|
[9911] | 144 | f_label = Paragraph('%s:' % f_label, ENTRY1_STYLE) |
---|
[10261] | 145 | f_text = formatted_text(widget(), lang=lang) |
---|
[9910] | 146 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 147 | data_middle.append([f_label,f_text]) |
---|
[9141] | 148 | |
---|
[9452] | 149 | if getattr(studentview.context, 'certcode', None): |
---|
[10250] | 150 | if not 'certificate' in omit_fields: |
---|
[10261] | 151 | f_label = trans(_('Study Course:'), lang) |
---|
[10250] | 152 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 153 | f_text = formatted_text( |
---|
[10650] | 154 | studentview.context['studycourse'].certificate.longtitle) |
---|
[10250] | 155 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 156 | data_middle.append([f_label,f_text]) |
---|
[10250] | 157 | if not 'department' in omit_fields: |
---|
[10261] | 158 | f_label = trans(_('Department:'), lang) |
---|
[10250] | 159 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 160 | f_text = formatted_text( |
---|
| 161 | studentview.context[ |
---|
[10650] | 162 | 'studycourse'].certificate.__parent__.__parent__.longtitle, |
---|
[10250] | 163 | ) |
---|
| 164 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 165 | data_middle.append([f_label,f_text]) |
---|
[10250] | 166 | if not 'faculty' in omit_fields: |
---|
[10261] | 167 | f_label = trans(_('Faculty:'), lang) |
---|
[10250] | 168 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 169 | f_text = formatted_text( |
---|
| 170 | studentview.context[ |
---|
[10650] | 171 | 'studycourse'].certificate.__parent__.__parent__.__parent__.longtitle, |
---|
[10250] | 172 | ) |
---|
| 173 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 174 | data_middle.append([f_label,f_text]) |
---|
[10688] | 175 | if not 'current_mode' in omit_fields: |
---|
| 176 | studymodes_dict = getUtility(IKofaUtils).STUDY_MODES_DICT |
---|
[11535] | 177 | sm = studymodes_dict[studentview.context.current_mode] |
---|
[10688] | 178 | f_label = trans(_('Study Mode:'), lang) |
---|
| 179 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 180 | f_text = formatted_text(sm) |
---|
| 181 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 182 | data_middle.append([f_label,f_text]) |
---|
[10250] | 183 | if not 'entry_session' in omit_fields: |
---|
[10261] | 184 | f_label = trans(_('Entry Session:'), lang) |
---|
[10250] | 185 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[11535] | 186 | entry_session = studentview.context.entry_session |
---|
[10250] | 187 | entry_session = academic_sessions_vocab.getTerm(entry_session).title |
---|
| 188 | f_text = formatted_text(entry_session) |
---|
| 189 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 190 | data_middle.append([f_label,f_text]) |
---|
[11535] | 191 | # Requested by Uniben, does not really make sense |
---|
| 192 | if not 'current_level' in omit_fields: |
---|
| 193 | f_label = trans(_('Current Level:'), lang) |
---|
| 194 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 195 | current_level = studentview.context['studycourse'].current_level |
---|
| 196 | studylevelsource = StudyLevelSource().factory |
---|
| 197 | current_level = studylevelsource.getTitle( |
---|
| 198 | studentview.context, current_level) |
---|
| 199 | f_text = formatted_text(current_level) |
---|
| 200 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 201 | data_middle.append([f_label,f_text]) |
---|
[10256] | 202 | if not 'date_of_birth' in omit_fields: |
---|
[10261] | 203 | f_label = trans(_('Date of Birth:'), lang) |
---|
[10256] | 204 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 205 | date_of_birth = studentview.context.date_of_birth |
---|
| 206 | tz = getUtility(IKofaUtils).tzinfo |
---|
| 207 | date_of_birth = to_timezone(date_of_birth, tz) |
---|
| 208 | if date_of_birth is not None: |
---|
| 209 | date_of_birth = date_of_birth.strftime("%d/%m/%Y") |
---|
| 210 | f_text = formatted_text(date_of_birth) |
---|
| 211 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
[11550] | 212 | data_middle.append([f_label,f_text]) |
---|
[9141] | 213 | |
---|
[14292] | 214 | if no_passport: |
---|
[14294] | 215 | table = Table(data_middle,style=SLIP_STYLE) |
---|
[14292] | 216 | table.hAlign = 'LEFT' |
---|
| 217 | return table |
---|
| 218 | |
---|
[11550] | 219 | # append QR code to the right |
---|
| 220 | if slipname: |
---|
| 221 | url = studentview.url(context, slipname) |
---|
| 222 | data_right = [[get_qrcode(url, width=70.0)]] |
---|
| 223 | table_right = Table(data_right,style=SLIP_STYLE) |
---|
| 224 | else: |
---|
| 225 | table_right = None |
---|
| 226 | |
---|
[7318] | 227 | table_left = Table(data_left,style=SLIP_STYLE) |
---|
[11550] | 228 | table_middle = Table(data_middle,style=SLIP_STYLE, colWidths=[5*cm, 5*cm]) |
---|
| 229 | table = Table([[table_left, table_middle, table_right],],style=SLIP_STYLE) |
---|
[7019] | 230 | return table |
---|
| 231 | |
---|
[10261] | 232 | def render_table_data(tableheader, tabledata, lang='en'): |
---|
[7318] | 233 | """Render children table for an existing frame. |
---|
| 234 | """ |
---|
[7304] | 235 | data = [] |
---|
[7318] | 236 | #data.append([Spacer(1, 12)]) |
---|
[7304] | 237 | line = [] |
---|
| 238 | style = getSampleStyleSheet() |
---|
| 239 | for element in tableheader: |
---|
[10261] | 240 | field = '<strong>%s</strong>' % formatted_text(element[0], lang=lang) |
---|
[7310] | 241 | field = Paragraph(field, style["Normal"]) |
---|
[7304] | 242 | line.append(field) |
---|
| 243 | data.append(line) |
---|
| 244 | for ticket in tabledata: |
---|
| 245 | line = [] |
---|
| 246 | for element in tableheader: |
---|
[7511] | 247 | field = formatted_text(getattr(ticket,element[1],u' ')) |
---|
[7318] | 248 | field = Paragraph(field, style["Normal"]) |
---|
[7304] | 249 | line.append(field) |
---|
| 250 | data.append(line) |
---|
[7310] | 251 | table = Table(data,colWidths=[ |
---|
[7318] | 252 | element[2]*cm for element in tableheader], style=CONTENT_STYLE) |
---|
[7304] | 253 | return table |
---|
| 254 | |
---|
[10261] | 255 | def render_transcript_data(view, tableheader, levels_data, lang='en'): |
---|
[10250] | 256 | """Render children table for an existing frame. |
---|
| 257 | """ |
---|
| 258 | data = [] |
---|
| 259 | style = getSampleStyleSheet() |
---|
[14473] | 260 | format_float = getUtility(IKofaUtils).format_float |
---|
[10250] | 261 | for level in levels_data: |
---|
| 262 | level_obj = level['level'] |
---|
[10251] | 263 | tickets = level['tickets_1'] + level['tickets_2'] + level['tickets_3'] |
---|
| 264 | headerline = [] |
---|
| 265 | tabledata = [] |
---|
[15203] | 266 | if 'evel' in view.level_dict.get('ticket.level', str(level_obj.level)): |
---|
| 267 | subheader = '%s %s, %s' % ( |
---|
| 268 | trans(_('Session'), lang), |
---|
| 269 | view.session_dict[level_obj.level_session], |
---|
| 270 | view.level_dict.get('ticket.level', str(level_obj.level))) |
---|
| 271 | else: |
---|
| 272 | subheader = '%s %s, %s %s' % ( |
---|
| 273 | trans(_('Session'), lang), |
---|
| 274 | view.session_dict[level_obj.level_session], |
---|
| 275 | trans(_('Level'), lang), |
---|
[15212] | 276 | view.level_dict.get(level_obj.level, str(level_obj.level))) |
---|
[10250] | 277 | data.append(Paragraph(subheader, HEADING_STYLE)) |
---|
| 278 | for element in tableheader: |
---|
| 279 | field = '<strong>%s</strong>' % formatted_text(element[0]) |
---|
| 280 | field = Paragraph(field, style["Normal"]) |
---|
[10251] | 281 | headerline.append(field) |
---|
| 282 | tabledata.append(headerline) |
---|
[10250] | 283 | for ticket in tickets: |
---|
[10251] | 284 | ticketline = [] |
---|
[10250] | 285 | for element in tableheader: |
---|
| 286 | field = formatted_text(getattr(ticket,element[1],u' ')) |
---|
| 287 | field = Paragraph(field, style["Normal"]) |
---|
[10251] | 288 | ticketline.append(field) |
---|
| 289 | tabledata.append(ticketline) |
---|
[10250] | 290 | table = Table(tabledata,colWidths=[ |
---|
| 291 | element[2]*cm for element in tableheader], style=CONTENT_STYLE) |
---|
| 292 | data.append(table) |
---|
[14473] | 293 | sgpa = format_float(level['sgpa'], 2) |
---|
| 294 | sgpa = '%s: %s' % (trans('Sessional GPA (rectified)', lang), sgpa) |
---|
| 295 | #sgpa = '%s: %.2f' % (trans('Sessional GPA (rectified)', lang), level['sgpa']) |
---|
[10261] | 296 | data.append(Paragraph(sgpa, style["Normal"])) |
---|
[15333] | 297 | if getattr(level_obj, 'transcript_remark', None): |
---|
[15331] | 298 | remark = '%s: %s' % ( |
---|
[15333] | 299 | trans('Transcript Remark', lang), |
---|
| 300 | getattr(level_obj, 'transcript_remark')) |
---|
[15331] | 301 | data.append(Paragraph(remark, style["Normal"])) |
---|
[10250] | 302 | return data |
---|
| 303 | |
---|
[8112] | 304 | def docs_as_flowables(view, lang='en'): |
---|
| 305 | """Create reportlab flowables out of scanned docs. |
---|
| 306 | """ |
---|
| 307 | # XXX: fix circular import problem |
---|
[12448] | 308 | from waeup.kofa.browser.fileviewlets import FileManager |
---|
[8112] | 309 | from waeup.kofa.browser import DEFAULT_IMAGE_PATH |
---|
| 310 | style = getSampleStyleSheet() |
---|
| 311 | data = [] |
---|
[7318] | 312 | |
---|
[8112] | 313 | # Collect viewlets |
---|
| 314 | fm = FileManager(view.context, view.request, view) |
---|
| 315 | fm.update() |
---|
| 316 | if fm.viewlets: |
---|
| 317 | sc_translation = trans(_('Scanned Documents'), lang) |
---|
[9910] | 318 | data.append(Paragraph(sc_translation, HEADING_STYLE)) |
---|
[8112] | 319 | # Insert list of scanned documents |
---|
| 320 | table_data = [] |
---|
| 321 | for viewlet in fm.viewlets: |
---|
[10020] | 322 | if viewlet.file_exists: |
---|
| 323 | # Show viewlet only if file exists |
---|
| 324 | f_label = Paragraph(trans(viewlet.label, lang), ENTRY1_STYLE) |
---|
| 325 | img_path = getattr(getUtility(IExtFileStore).getFileByContext( |
---|
| 326 | view.context, attr=viewlet.download_name), 'name', None) |
---|
| 327 | #f_text = Paragraph(trans(_('(not provided)'),lang), ENTRY1_STYLE) |
---|
| 328 | if img_path is None: |
---|
| 329 | pass |
---|
| 330 | elif not img_path[-4:] in ('.jpg', '.JPG'): |
---|
| 331 | # reportlab requires jpg images, I think. |
---|
| 332 | f_text = Paragraph('%s (not displayable)' % ( |
---|
| 333 | viewlet.title,), ENTRY1_STYLE) |
---|
| 334 | else: |
---|
| 335 | f_text = Image(img_path, width=2*cm, height=1*cm, kind='bound') |
---|
| 336 | table_data.append([f_label, f_text]) |
---|
[8112] | 337 | if table_data: |
---|
| 338 | # safety belt; empty tables lead to problems. |
---|
| 339 | data.append(Table(table_data, style=SLIP_STYLE)) |
---|
| 340 | return data |
---|
| 341 | |
---|
[7150] | 342 | class StudentsUtils(grok.GlobalUtility): |
---|
| 343 | """A collection of methods subject to customization. |
---|
| 344 | """ |
---|
| 345 | grok.implements(IStudentsUtils) |
---|
[7019] | 346 | |
---|
[8268] | 347 | def getReturningData(self, student): |
---|
[9005] | 348 | """ Define what happens after school fee payment |
---|
[7841] | 349 | depending on the student's senate verdict. |
---|
| 350 | In the base configuration current level is always increased |
---|
| 351 | by 100 no matter which verdict has been assigned. |
---|
| 352 | """ |
---|
[8268] | 353 | new_level = student['studycourse'].current_level + 100 |
---|
| 354 | new_session = student['studycourse'].current_session + 1 |
---|
| 355 | return new_session, new_level |
---|
| 356 | |
---|
| 357 | def setReturningData(self, student): |
---|
[9005] | 358 | """ Define what happens after school fee payment |
---|
| 359 | depending on the student's senate verdict. |
---|
[13124] | 360 | This method folllows the same algorithm as `getReturningData` but |
---|
[9005] | 361 | it also sets the new values. |
---|
[8268] | 362 | """ |
---|
| 363 | new_session, new_level = self.getReturningData(student) |
---|
[9922] | 364 | try: |
---|
| 365 | student['studycourse'].current_level = new_level |
---|
| 366 | except ConstraintNotSatisfied: |
---|
| 367 | # Do not change level if level exceeds the |
---|
| 368 | # certificate's end_level. |
---|
| 369 | pass |
---|
[8268] | 370 | student['studycourse'].current_session = new_session |
---|
[7615] | 371 | verdict = student['studycourse'].current_verdict |
---|
[8820] | 372 | student['studycourse'].current_verdict = '0' |
---|
[7615] | 373 | student['studycourse'].previous_verdict = verdict |
---|
| 374 | return |
---|
| 375 | |
---|
[9519] | 376 | def _getSessionConfiguration(self, session): |
---|
| 377 | try: |
---|
| 378 | return grok.getSite()['configuration'][str(session)] |
---|
| 379 | except KeyError: |
---|
| 380 | return None |
---|
| 381 | |
---|
[11451] | 382 | def _isPaymentDisabled(self, p_session, category, student): |
---|
| 383 | academic_session = self._getSessionConfiguration(p_session) |
---|
[11452] | 384 | if category == 'schoolfee' and \ |
---|
| 385 | 'sf_all' in academic_session.payment_disabled: |
---|
[11451] | 386 | return True |
---|
| 387 | return False |
---|
| 388 | |
---|
[11641] | 389 | def samePaymentMade(self, student, category, p_item, p_session): |
---|
| 390 | for key in student['payments'].keys(): |
---|
| 391 | ticket = student['payments'][key] |
---|
| 392 | if ticket.p_state == 'paid' and\ |
---|
| 393 | ticket.p_category == category and \ |
---|
| 394 | ticket.p_item == p_item and \ |
---|
| 395 | ticket.p_session == p_session: |
---|
| 396 | return True |
---|
| 397 | return False |
---|
| 398 | |
---|
[9148] | 399 | def setPaymentDetails(self, category, student, |
---|
[9151] | 400 | previous_session, previous_level): |
---|
[13124] | 401 | """Create a payment ticket and set the payment data of a |
---|
[13040] | 402 | student for the payment category specified. |
---|
[7841] | 403 | """ |
---|
[8595] | 404 | p_item = u'' |
---|
| 405 | amount = 0.0 |
---|
[9148] | 406 | if previous_session: |
---|
[9517] | 407 | if previous_session < student['studycourse'].entry_session: |
---|
| 408 | return _('The previous session must not fall below ' |
---|
| 409 | 'your entry session.'), None |
---|
| 410 | if category == 'schoolfee': |
---|
| 411 | # School fee is always paid for the following session |
---|
| 412 | if previous_session > student['studycourse'].current_session: |
---|
| 413 | return _('This is not a previous session.'), None |
---|
| 414 | else: |
---|
| 415 | if previous_session > student['studycourse'].current_session - 1: |
---|
| 416 | return _('This is not a previous session.'), None |
---|
[9148] | 417 | p_session = previous_session |
---|
| 418 | p_level = previous_level |
---|
| 419 | p_current = False |
---|
| 420 | else: |
---|
| 421 | p_session = student['studycourse'].current_session |
---|
| 422 | p_level = student['studycourse'].current_level |
---|
| 423 | p_current = True |
---|
[9519] | 424 | academic_session = self._getSessionConfiguration(p_session) |
---|
| 425 | if academic_session == None: |
---|
[8595] | 426 | return _(u'Session configuration object is not available.'), None |
---|
[9521] | 427 | # Determine fee. |
---|
[7150] | 428 | if category == 'schoolfee': |
---|
[8595] | 429 | try: |
---|
[8596] | 430 | certificate = student['studycourse'].certificate |
---|
| 431 | p_item = certificate.code |
---|
[8595] | 432 | except (AttributeError, TypeError): |
---|
| 433 | return _('Study course data are incomplete.'), None |
---|
[9148] | 434 | if previous_session: |
---|
[9916] | 435 | # Students can pay for previous sessions in all |
---|
| 436 | # workflow states. Fresh students are excluded by the |
---|
| 437 | # update method of the PreviousPaymentAddFormPage. |
---|
[9148] | 438 | if previous_level == 100: |
---|
| 439 | amount = getattr(certificate, 'school_fee_1', 0.0) |
---|
| 440 | else: |
---|
| 441 | amount = getattr(certificate, 'school_fee_2', 0.0) |
---|
| 442 | else: |
---|
| 443 | if student.state == CLEARED: |
---|
| 444 | amount = getattr(certificate, 'school_fee_1', 0.0) |
---|
| 445 | elif student.state == RETURNING: |
---|
[9916] | 446 | # In case of returning school fee payment the |
---|
| 447 | # payment session and level contain the values of |
---|
| 448 | # the session the student has paid for. Payment |
---|
| 449 | # session is always next session. |
---|
[9148] | 450 | p_session, p_level = self.getReturningData(student) |
---|
[9519] | 451 | academic_session = self._getSessionConfiguration(p_session) |
---|
| 452 | if academic_session == None: |
---|
[9916] | 453 | return _( |
---|
| 454 | u'Session configuration object is not available.' |
---|
| 455 | ), None |
---|
[9148] | 456 | amount = getattr(certificate, 'school_fee_2', 0.0) |
---|
| 457 | elif student.is_postgrad and student.state == PAID: |
---|
[9916] | 458 | # Returning postgraduate students also pay for the |
---|
| 459 | # next session but their level always remains the |
---|
| 460 | # same. |
---|
[9148] | 461 | p_session += 1 |
---|
[9519] | 462 | academic_session = self._getSessionConfiguration(p_session) |
---|
| 463 | if academic_session == None: |
---|
[9916] | 464 | return _( |
---|
| 465 | u'Session configuration object is not available.' |
---|
| 466 | ), None |
---|
[9148] | 467 | amount = getattr(certificate, 'school_fee_2', 0.0) |
---|
[7150] | 468 | elif category == 'clearance': |
---|
[9178] | 469 | try: |
---|
| 470 | p_item = student['studycourse'].certificate.code |
---|
| 471 | except (AttributeError, TypeError): |
---|
| 472 | return _('Study course data are incomplete.'), None |
---|
[8595] | 473 | amount = academic_session.clearance_fee |
---|
[7150] | 474 | elif category == 'bed_allocation': |
---|
[8595] | 475 | p_item = self.getAccommodationDetails(student)['bt'] |
---|
| 476 | amount = academic_session.booking_fee |
---|
[9423] | 477 | elif category == 'hostel_maintenance': |
---|
[10681] | 478 | amount = 0.0 |
---|
[9429] | 479 | bedticket = student['accommodation'].get( |
---|
| 480 | str(student.current_session), None) |
---|
[13501] | 481 | if bedticket is not None and bedticket.bed is not None: |
---|
[9429] | 482 | p_item = bedticket.bed_coordinates |
---|
[10681] | 483 | if bedticket.bed.__parent__.maint_fee > 0: |
---|
| 484 | amount = bedticket.bed.__parent__.maint_fee |
---|
| 485 | else: |
---|
| 486 | # fallback |
---|
| 487 | amount = academic_session.maint_fee |
---|
[9429] | 488 | else: |
---|
[13505] | 489 | return _(u'No bed allocated.'), None |
---|
[10449] | 490 | elif category == 'transcript': |
---|
| 491 | amount = academic_session.transcript_fee |
---|
[13574] | 492 | elif category == 'transfer': |
---|
| 493 | amount = academic_session.transfer_fee |
---|
[13031] | 494 | elif category == 'late_registration': |
---|
| 495 | amount = academic_session.late_registration_fee |
---|
[8595] | 496 | if amount in (0.0, None): |
---|
[9517] | 497 | return _('Amount could not be determined.'), None |
---|
[11641] | 498 | if self.samePaymentMade(student, category, p_item, p_session): |
---|
| 499 | return _('This type of payment has already been made.'), None |
---|
[11451] | 500 | if self._isPaymentDisabled(p_session, category, student): |
---|
[13797] | 501 | return _('This category of payments has been disabled.'), None |
---|
[8708] | 502 | payment = createObject(u'waeup.StudentOnlinePayment') |
---|
[8951] | 503 | timestamp = ("%d" % int(time()*10000))[1:] |
---|
[8595] | 504 | payment.p_id = "p%s" % timestamp |
---|
| 505 | payment.p_category = category |
---|
| 506 | payment.p_item = p_item |
---|
| 507 | payment.p_session = p_session |
---|
| 508 | payment.p_level = p_level |
---|
[9148] | 509 | payment.p_current = p_current |
---|
[8595] | 510 | payment.amount_auth = amount |
---|
| 511 | return None, payment |
---|
[7019] | 512 | |
---|
[9868] | 513 | def setBalanceDetails(self, category, student, |
---|
[9864] | 514 | balance_session, balance_level, balance_amount): |
---|
[13124] | 515 | """Create a balance payment ticket and set the payment data |
---|
| 516 | as selected by the student. |
---|
[9864] | 517 | """ |
---|
[9868] | 518 | p_item = u'Balance' |
---|
[9864] | 519 | p_session = balance_session |
---|
| 520 | p_level = balance_level |
---|
| 521 | p_current = False |
---|
| 522 | amount = balance_amount |
---|
| 523 | academic_session = self._getSessionConfiguration(p_session) |
---|
| 524 | if academic_session == None: |
---|
| 525 | return _(u'Session configuration object is not available.'), None |
---|
[9874] | 526 | if amount in (0.0, None) or amount < 0: |
---|
| 527 | return _('Amount must be greater than 0.'), None |
---|
[9864] | 528 | payment = createObject(u'waeup.StudentOnlinePayment') |
---|
| 529 | timestamp = ("%d" % int(time()*10000))[1:] |
---|
| 530 | payment.p_id = "p%s" % timestamp |
---|
[9868] | 531 | payment.p_category = category |
---|
[9864] | 532 | payment.p_item = p_item |
---|
| 533 | payment.p_session = p_session |
---|
| 534 | payment.p_level = p_level |
---|
| 535 | payment.p_current = p_current |
---|
| 536 | payment.amount_auth = amount |
---|
| 537 | return None, payment |
---|
| 538 | |
---|
[12896] | 539 | def increaseMatricInteger(self, student): |
---|
| 540 | """Increase counter for matric numbers. |
---|
| 541 | This counter can be a centrally stored attribute or an attribute of |
---|
| 542 | faculties, departments or certificates. In the base package the counter |
---|
[13124] | 543 | is as an attribute of the site configuration container. |
---|
[12896] | 544 | """ |
---|
| 545 | grok.getSite()['configuration'].next_matric_integer += 1 |
---|
| 546 | return |
---|
| 547 | |
---|
[11595] | 548 | def constructMatricNumber(self, student): |
---|
[12896] | 549 | """Fetch the matric number counter which fits the student and |
---|
| 550 | construct the new matric number of the student. |
---|
[12902] | 551 | In the base package the counter is returned which is as an attribute |
---|
[13124] | 552 | of the site configuration container. |
---|
[12896] | 553 | """ |
---|
[11595] | 554 | next_integer = grok.getSite()['configuration'].next_matric_integer |
---|
| 555 | if next_integer == 0: |
---|
[11619] | 556 | return _('Matriculation number cannot be set.'), None |
---|
| 557 | return None, unicode(next_integer) |
---|
[11589] | 558 | |
---|
| 559 | def setMatricNumber(self, student): |
---|
[13124] | 560 | """Set matriculation number of student. If the student's matric number |
---|
| 561 | is unset a new matric number is |
---|
[12896] | 562 | constructed according to the matriculation number construction rules |
---|
[13124] | 563 | defined in the `constructMatricNumber` method. The new matric number is |
---|
[12896] | 564 | set, the students catalog updated. The corresponding matric number |
---|
| 565 | counter is increased by one. |
---|
[11589] | 566 | |
---|
| 567 | This method is tested but not used in the base package. It can |
---|
| 568 | be used in custom packages by adding respective views |
---|
[13124] | 569 | and by customizing `increaseMatricInteger` and `constructMatricNumber` |
---|
[12896] | 570 | according to the university's matriculation number construction rules. |
---|
[11589] | 571 | |
---|
[12896] | 572 | The method can be disabled by setting the counter to zero. |
---|
[11589] | 573 | """ |
---|
| 574 | if student.matric_number is not None: |
---|
| 575 | return _('Matriculation number already set.'), None |
---|
[11590] | 576 | if student.certcode is None: |
---|
| 577 | return _('No certificate assigned.'), None |
---|
[11619] | 578 | error, matric_number = self.constructMatricNumber(student) |
---|
| 579 | if error: |
---|
| 580 | return error, None |
---|
[11589] | 581 | try: |
---|
[11592] | 582 | student.matric_number = matric_number |
---|
[11589] | 583 | except MatNumNotInSource: |
---|
[13224] | 584 | return _('Matriculation number %s exists.' % matric_number), None |
---|
[11589] | 585 | notify(grok.ObjectModifiedEvent(student)) |
---|
[12896] | 586 | self.increaseMatricInteger(student) |
---|
[11595] | 587 | return None, matric_number |
---|
[11589] | 588 | |
---|
[7186] | 589 | def getAccommodationDetails(self, student): |
---|
[9219] | 590 | """Determine the accommodation data of a student. |
---|
[7841] | 591 | """ |
---|
[7150] | 592 | d = {} |
---|
| 593 | d['error'] = u'' |
---|
[8685] | 594 | hostels = grok.getSite()['hostels'] |
---|
| 595 | d['booking_session'] = hostels.accommodation_session |
---|
| 596 | d['allowed_states'] = hostels.accommodation_states |
---|
[8688] | 597 | d['startdate'] = hostels.startdate |
---|
| 598 | d['enddate'] = hostels.enddate |
---|
| 599 | d['expired'] = hostels.expired |
---|
[7150] | 600 | # Determine bed type |
---|
| 601 | studycourse = student['studycourse'] |
---|
[7369] | 602 | certificate = getattr(studycourse,'certificate',None) |
---|
[7150] | 603 | entry_session = studycourse.entry_session |
---|
| 604 | current_level = studycourse.current_level |
---|
[9187] | 605 | if None in (entry_session, current_level, certificate): |
---|
| 606 | return d |
---|
[7369] | 607 | end_level = certificate.end_level |
---|
[9148] | 608 | if current_level == 10: |
---|
| 609 | bt = 'pr' |
---|
| 610 | elif entry_session == grok.getSite()['hostels'].accommodation_session: |
---|
[7150] | 611 | bt = 'fr' |
---|
| 612 | elif current_level >= end_level: |
---|
| 613 | bt = 'fi' |
---|
| 614 | else: |
---|
| 615 | bt = 're' |
---|
| 616 | if student.sex == 'f': |
---|
| 617 | sex = 'female' |
---|
| 618 | else: |
---|
| 619 | sex = 'male' |
---|
| 620 | special_handling = 'regular' |
---|
| 621 | d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt) |
---|
| 622 | return d |
---|
[7019] | 623 | |
---|
[13247] | 624 | def checkAccommodationRequirements(self, student, acc_details): |
---|
| 625 | if acc_details.get('expired', False): |
---|
| 626 | startdate = acc_details.get('startdate') |
---|
| 627 | enddate = acc_details.get('enddate') |
---|
| 628 | if startdate and enddate: |
---|
| 629 | tz = getUtility(IKofaUtils).tzinfo |
---|
| 630 | startdate = to_timezone( |
---|
| 631 | startdate, tz).strftime("%d/%m/%Y %H:%M:%S") |
---|
| 632 | enddate = to_timezone( |
---|
| 633 | enddate, tz).strftime("%d/%m/%Y %H:%M:%S") |
---|
| 634 | return _("Outside booking period: ${a} - ${b}", |
---|
| 635 | mapping = {'a': startdate, 'b': enddate}) |
---|
| 636 | else: |
---|
| 637 | return _("Outside booking period.") |
---|
| 638 | if not acc_details.get('bt'): |
---|
| 639 | return _("Your data are incomplete.") |
---|
| 640 | if not student.state in acc_details['allowed_states']: |
---|
| 641 | return _("You are in the wrong registration state.") |
---|
| 642 | if student['studycourse'].current_session != acc_details[ |
---|
| 643 | 'booking_session']: |
---|
| 644 | return _('Your current session does not ' |
---|
| 645 | 'match accommodation session.') |
---|
[15306] | 646 | bsession = str(acc_details['booking_session']) |
---|
| 647 | if bsession in student['accommodation'].keys() \ |
---|
| 648 | and not 'booking expired' in \ |
---|
| 649 | student['accommodation'][bsession].bed_coordinates: |
---|
[13247] | 650 | return _('You already booked a bed space in ' |
---|
| 651 | 'current accommodation session.') |
---|
| 652 | return |
---|
| 653 | |
---|
[13457] | 654 | def selectBed(self, available_beds, desired_hostel=None): |
---|
| 655 | """Select a bed from a filtered list of available beds. |
---|
| 656 | In the base configuration beds are sorted by the sort id |
---|
| 657 | of the hostel and the bed number. The first bed found in |
---|
| 658 | this sorted list is taken. |
---|
[7841] | 659 | """ |
---|
[13457] | 660 | sorted_beds = sorted(available_beds, |
---|
| 661 | key=lambda bed: 1000 * bed.__parent__.sort_id + bed.bed_number) |
---|
[15312] | 662 | if desired_hostel and desired_hostel != 'no': |
---|
[13457] | 663 | # Filter desired hostel beds |
---|
| 664 | filtered_beds = [bed for bed in sorted_beds |
---|
| 665 | if bed.bed_id.startswith(desired_hostel)] |
---|
| 666 | if not filtered_beds: |
---|
| 667 | return |
---|
| 668 | return filtered_beds[0] |
---|
| 669 | return sorted_beds[0] |
---|
[7150] | 670 | |
---|
[9981] | 671 | def _admissionText(self, student, portal_language): |
---|
[9979] | 672 | inst_name = grok.getSite()['configuration'].name |
---|
| 673 | text = trans(_( |
---|
| 674 | 'This is to inform you that you have been provisionally' |
---|
| 675 | ' admitted into ${a} as follows:', mapping = {'a': inst_name}), |
---|
| 676 | portal_language) |
---|
| 677 | return text |
---|
| 678 | |
---|
[10686] | 679 | def renderPDFAdmissionLetter(self, view, student=None, omit_fields=(), |
---|
| 680 | pre_text=None, post_text=None,): |
---|
[9191] | 681 | """Render pdf admission letter. |
---|
| 682 | """ |
---|
| 683 | if student is None: |
---|
| 684 | return |
---|
| 685 | style = getSampleStyleSheet() |
---|
[9949] | 686 | creator = self.getPDFCreator(student) |
---|
[9979] | 687 | portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE |
---|
[9191] | 688 | data = [] |
---|
| 689 | doc_title = view.label |
---|
| 690 | author = '%s (%s)' % (view.request.principal.title, |
---|
| 691 | view.request.principal.id) |
---|
[9944] | 692 | footer_text = view.label.split('\n') |
---|
| 693 | if len(footer_text) > 1: |
---|
| 694 | # We can add a department in first line |
---|
| 695 | footer_text = footer_text[1] |
---|
| 696 | else: |
---|
| 697 | # Only the first line is used for the footer |
---|
| 698 | footer_text = footer_text[0] |
---|
[9191] | 699 | if getattr(student, 'student_id', None) is not None: |
---|
| 700 | footer_text = "%s - %s - " % (student.student_id, footer_text) |
---|
| 701 | |
---|
[10702] | 702 | # Text before student data |
---|
[10686] | 703 | if pre_text is None: |
---|
| 704 | html = format_html(self._admissionText(student, portal_language)) |
---|
| 705 | else: |
---|
| 706 | html = format_html(pre_text) |
---|
[11875] | 707 | if html: |
---|
| 708 | data.append(Paragraph(html, NOTE_STYLE)) |
---|
| 709 | data.append(Spacer(1, 20)) |
---|
[9191] | 710 | |
---|
| 711 | # Student data |
---|
[11550] | 712 | data.append(render_student_data(view, student, |
---|
| 713 | omit_fields, lang=portal_language, |
---|
| 714 | slipname='admission_slip.pdf')) |
---|
[9191] | 715 | |
---|
[10702] | 716 | # Text after student data |
---|
[9191] | 717 | data.append(Spacer(1, 20)) |
---|
[10686] | 718 | if post_text is None: |
---|
| 719 | datelist = student.history.messages[0].split()[0].split('-') |
---|
| 720 | creation_date = u'%s/%s/%s' % (datelist[2], datelist[1], datelist[0]) |
---|
[10702] | 721 | post_text = trans(_( |
---|
[10686] | 722 | 'Your Kofa student record was created on ${a}.', |
---|
| 723 | mapping = {'a': creation_date}), |
---|
| 724 | portal_language) |
---|
[10702] | 725 | #html = format_html(post_text) |
---|
| 726 | #data.append(Paragraph(html, NOTE_STYLE)) |
---|
[9191] | 727 | |
---|
| 728 | # Create pdf stream |
---|
| 729 | view.response.setHeader( |
---|
| 730 | 'Content-Type', 'application/pdf') |
---|
| 731 | pdf_stream = creator.create_pdf( |
---|
| 732 | data, None, doc_title, author=author, footer=footer_text, |
---|
[10702] | 733 | note=post_text) |
---|
[9191] | 734 | return pdf_stream |
---|
| 735 | |
---|
[9949] | 736 | def getPDFCreator(self, context): |
---|
| 737 | """Get a pdf creator suitable for `context`. |
---|
| 738 | The default implementation always returns the default creator. |
---|
| 739 | """ |
---|
| 740 | return getUtility(IPDFCreator) |
---|
| 741 | |
---|
[8257] | 742 | def renderPDF(self, view, filename='slip.pdf', student=None, |
---|
[9906] | 743 | studentview=None, |
---|
[10439] | 744 | tableheader=[], tabledata=[], |
---|
[9555] | 745 | note=None, signatures=None, sigs_in_footer=(), |
---|
[10250] | 746 | show_scans=True, topMargin=1.5, |
---|
| 747 | omit_fields=()): |
---|
[14151] | 748 | """Render pdf slips for various pages (also some pages |
---|
| 749 | in the applicants module). |
---|
[7841] | 750 | """ |
---|
[10261] | 751 | portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE |
---|
[9916] | 752 | # XXX: tell what the different parameters mean |
---|
[8112] | 753 | style = getSampleStyleSheet() |
---|
[9949] | 754 | creator = self.getPDFCreator(student) |
---|
[8112] | 755 | data = [] |
---|
| 756 | doc_title = view.label |
---|
| 757 | author = '%s (%s)' % (view.request.principal.title, |
---|
| 758 | view.request.principal.id) |
---|
[9913] | 759 | footer_text = view.label.split('\n') |
---|
[13304] | 760 | if len(footer_text) > 1: |
---|
| 761 | # We can add a department in first line, second line is used |
---|
[9913] | 762 | footer_text = footer_text[1] |
---|
| 763 | else: |
---|
[9917] | 764 | # Only the first line is used for the footer |
---|
[9913] | 765 | footer_text = footer_text[0] |
---|
[7714] | 766 | if getattr(student, 'student_id', None) is not None: |
---|
[7310] | 767 | footer_text = "%s - %s - " % (student.student_id, footer_text) |
---|
[7150] | 768 | |
---|
[7318] | 769 | # Insert student data table |
---|
[7310] | 770 | if student is not None: |
---|
[8112] | 771 | bd_translation = trans(_('Base Data'), portal_language) |
---|
[9910] | 772 | data.append(Paragraph(bd_translation, HEADING_STYLE)) |
---|
[10261] | 773 | data.append(render_student_data( |
---|
[11550] | 774 | studentview, view.context, omit_fields, lang=portal_language, |
---|
| 775 | slipname=filename)) |
---|
[7304] | 776 | |
---|
[7318] | 777 | # Insert widgets |
---|
[9191] | 778 | if view.form_fields: |
---|
[9910] | 779 | data.append(Paragraph(view.title, HEADING_STYLE)) |
---|
[9191] | 780 | separators = getattr(self, 'SEPARATORS_DICT', {}) |
---|
| 781 | table = creator.getWidgetsTable( |
---|
| 782 | view.form_fields, view.context, None, lang=portal_language, |
---|
| 783 | separators=separators) |
---|
| 784 | data.append(table) |
---|
[7318] | 785 | |
---|
[8112] | 786 | # Insert scanned docs |
---|
[9550] | 787 | if show_scans: |
---|
| 788 | data.extend(docs_as_flowables(view, portal_language)) |
---|
[7318] | 789 | |
---|
[9452] | 790 | # Insert history |
---|
[15337] | 791 | if filename == 'clearance_slip.pdf': |
---|
[9452] | 792 | hist_translation = trans(_('Workflow History'), portal_language) |
---|
[9910] | 793 | data.append(Paragraph(hist_translation, HEADING_STYLE)) |
---|
[9452] | 794 | data.extend(creator.fromStringList(student.history.messages)) |
---|
| 795 | |
---|
[10438] | 796 | # Insert content tables (optionally on second page) |
---|
[10439] | 797 | if hasattr(view, 'tabletitle'): |
---|
| 798 | for i in range(len(view.tabletitle)): |
---|
| 799 | if tabledata[i] and tableheader[i]: |
---|
| 800 | #data.append(PageBreak()) |
---|
| 801 | #data.append(Spacer(1, 20)) |
---|
| 802 | data.append(Paragraph(view.tabletitle[i], HEADING_STYLE)) |
---|
| 803 | data.append(Spacer(1, 8)) |
---|
| 804 | contenttable = render_table_data(tableheader[i],tabledata[i]) |
---|
| 805 | data.append(contenttable) |
---|
[7318] | 806 | |
---|
[9010] | 807 | # Insert signatures |
---|
[9965] | 808 | # XXX: We are using only sigs_in_footer in waeup.kofa, so we |
---|
| 809 | # do not have a test for the following lines. |
---|
[9555] | 810 | if signatures and not sigs_in_footer: |
---|
[9010] | 811 | data.append(Spacer(1, 20)) |
---|
[9966] | 812 | # Render one signature table per signature to |
---|
| 813 | # get date and signature in line. |
---|
| 814 | for signature in signatures: |
---|
| 815 | signaturetables = get_signature_tables(signature) |
---|
| 816 | data.append(signaturetables[0]) |
---|
[9010] | 817 | |
---|
[7150] | 818 | view.response.setHeader( |
---|
| 819 | 'Content-Type', 'application/pdf') |
---|
[8112] | 820 | try: |
---|
| 821 | pdf_stream = creator.create_pdf( |
---|
[8257] | 822 | data, None, doc_title, author=author, footer=footer_text, |
---|
[9948] | 823 | note=note, sigs_in_footer=sigs_in_footer, topMargin=topMargin) |
---|
[8112] | 824 | except IOError: |
---|
| 825 | view.flash('Error in image file.') |
---|
| 826 | return view.redirect(view.url(view.context)) |
---|
[14256] | 827 | except LayoutError, err: |
---|
| 828 | view.flash( |
---|
| 829 | 'PDF file could not be created. Reportlab error message: %s' |
---|
| 830 | % escape(err.message), |
---|
| 831 | type="danger") |
---|
| 832 | return view.redirect(view.url(view.context)) |
---|
[8112] | 833 | return pdf_stream |
---|
[7620] | 834 | |
---|
[14915] | 835 | def GPABoundaries(self, faccode=None, depcode=None, certcode=None): |
---|
[14914] | 836 | return ((1, 'Fail'), |
---|
| 837 | (1.5, 'Pass'), |
---|
| 838 | (2.4, '3rd Class'), |
---|
| 839 | (3.5, '2nd Class Lower'), |
---|
| 840 | (4.5, '2nd Class Upper'), |
---|
| 841 | (5, '1st Class')) |
---|
[10576] | 842 | |
---|
[14461] | 843 | def getClassFromCGPA(self, gpa, student): |
---|
| 844 | """Determine the class of degree. In some custom packages |
---|
| 845 | this class depends on e.g. the entry session of the student. In the |
---|
| 846 | base package, it does not. |
---|
| 847 | """ |
---|
[14914] | 848 | if gpa < self.GPABoundaries()[0][0]: |
---|
| 849 | return 0, self.GPABoundaries()[0][1] |
---|
| 850 | if gpa < self.GPABoundaries()[1][0]: |
---|
| 851 | return 1, self.GPABoundaries()[1][1] |
---|
| 852 | if gpa < self.GPABoundaries()[2][0]: |
---|
| 853 | return 2, self.GPABoundaries()[2][1] |
---|
| 854 | if gpa < self.GPABoundaries()[3][0]: |
---|
| 855 | return 3, self.GPABoundaries()[3][1] |
---|
| 856 | if gpa < self.GPABoundaries()[4][0]: |
---|
| 857 | return 4, self.GPABoundaries()[4][1] |
---|
| 858 | if gpa <= self.GPABoundaries()[5][0]: |
---|
| 859 | return 5, self.GPABoundaries()[5][1] |
---|
[15102] | 860 | return |
---|
[10445] | 861 | |
---|
[14159] | 862 | def getDegreeClassNumber(self, level_obj): |
---|
| 863 | """Get degree class number (used for SessionResultsPresentation |
---|
[14157] | 864 | reports). |
---|
| 865 | """ |
---|
[14410] | 866 | if level_obj.gpa_params[1] == 0: |
---|
| 867 | # No credits weighted |
---|
| 868 | return 6 |
---|
[14461] | 869 | return self.getClassFromCGPA( |
---|
| 870 | level_obj.cumulative_params[0], level_obj.student)[0] |
---|
[14157] | 871 | |
---|
[15163] | 872 | def _saveTranscriptPDF(self, student, transcript): |
---|
| 873 | """Create a transcript PDF file and store it in student folder. |
---|
| 874 | """ |
---|
| 875 | file_store = getUtility(IExtFileStore) |
---|
| 876 | file_id = IFileStoreNameChooser(student).chooseName( |
---|
| 877 | attr="final_transcript.pdf") |
---|
| 878 | file_store.createFile(file_id, StringIO(transcript)) |
---|
| 879 | return |
---|
| 880 | |
---|
[10250] | 881 | def renderPDFTranscript(self, view, filename='transcript.pdf', |
---|
| 882 | student=None, |
---|
| 883 | studentview=None, |
---|
[15163] | 884 | note=None, |
---|
| 885 | signatures=(), |
---|
| 886 | sigs_in_footer=(), |
---|
| 887 | digital_sigs=(), |
---|
[10250] | 888 | show_scans=True, topMargin=1.5, |
---|
| 889 | omit_fields=(), |
---|
[14292] | 890 | tableheader=None, |
---|
[15163] | 891 | no_passport=False, |
---|
| 892 | save_file=False): |
---|
[14583] | 893 | """Render pdf slip of a transcripts. |
---|
[10250] | 894 | """ |
---|
[10261] | 895 | portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE |
---|
[10250] | 896 | # XXX: tell what the different parameters mean |
---|
| 897 | style = getSampleStyleSheet() |
---|
| 898 | creator = self.getPDFCreator(student) |
---|
| 899 | data = [] |
---|
| 900 | doc_title = view.label |
---|
| 901 | author = '%s (%s)' % (view.request.principal.title, |
---|
| 902 | view.request.principal.id) |
---|
| 903 | footer_text = view.label.split('\n') |
---|
| 904 | if len(footer_text) > 2: |
---|
| 905 | # We can add a department in first line |
---|
| 906 | footer_text = footer_text[1] |
---|
| 907 | else: |
---|
| 908 | # Only the first line is used for the footer |
---|
| 909 | footer_text = footer_text[0] |
---|
| 910 | if getattr(student, 'student_id', None) is not None: |
---|
| 911 | footer_text = "%s - %s - " % (student.student_id, footer_text) |
---|
| 912 | |
---|
| 913 | # Insert student data table |
---|
| 914 | if student is not None: |
---|
| 915 | #bd_translation = trans(_('Base Data'), portal_language) |
---|
| 916 | #data.append(Paragraph(bd_translation, HEADING_STYLE)) |
---|
[10261] | 917 | data.append(render_student_data( |
---|
[11550] | 918 | studentview, view.context, |
---|
| 919 | omit_fields, lang=portal_language, |
---|
[14292] | 920 | slipname=filename, |
---|
| 921 | no_passport=no_passport)) |
---|
[10250] | 922 | |
---|
| 923 | transcript_data = view.context.getTranscriptData() |
---|
| 924 | levels_data = transcript_data[0] |
---|
| 925 | |
---|
| 926 | contextdata = [] |
---|
[10261] | 927 | f_label = trans(_('Course of Study:'), portal_language) |
---|
[10250] | 928 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[10650] | 929 | f_text = formatted_text(view.context.certificate.longtitle) |
---|
[10250] | 930 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 931 | contextdata.append([f_label,f_text]) |
---|
| 932 | |
---|
[10261] | 933 | f_label = trans(_('Faculty:'), portal_language) |
---|
[10250] | 934 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 935 | f_text = formatted_text( |
---|
[10650] | 936 | view.context.certificate.__parent__.__parent__.__parent__.longtitle) |
---|
[10250] | 937 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 938 | contextdata.append([f_label,f_text]) |
---|
| 939 | |
---|
[10261] | 940 | f_label = trans(_('Department:'), portal_language) |
---|
[10250] | 941 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
| 942 | f_text = formatted_text( |
---|
[10650] | 943 | view.context.certificate.__parent__.__parent__.longtitle) |
---|
[10250] | 944 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 945 | contextdata.append([f_label,f_text]) |
---|
| 946 | |
---|
[10261] | 947 | f_label = trans(_('Entry Session:'), portal_language) |
---|
[10250] | 948 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[10256] | 949 | f_text = formatted_text( |
---|
| 950 | view.session_dict.get(view.context.entry_session)) |
---|
[10250] | 951 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 952 | contextdata.append([f_label,f_text]) |
---|
| 953 | |
---|
[10261] | 954 | f_label = trans(_('Entry Mode:'), portal_language) |
---|
[10250] | 955 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[10256] | 956 | f_text = formatted_text(view.studymode_dict.get( |
---|
| 957 | view.context.entry_mode)) |
---|
[10250] | 958 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 959 | contextdata.append([f_label,f_text]) |
---|
| 960 | |
---|
[10262] | 961 | f_label = trans(_('Cumulative GPA:'), portal_language) |
---|
[10250] | 962 | f_label = Paragraph(f_label, ENTRY1_STYLE) |
---|
[14473] | 963 | format_float = getUtility(IKofaUtils).format_float |
---|
| 964 | cgpa = format_float(transcript_data[1], 3) |
---|
| 965 | f_text = formatted_text('%s (%s)' % ( |
---|
| 966 | cgpa, self.getClassFromCGPA(transcript_data[1], student)[1])) |
---|
[10250] | 967 | f_text = Paragraph(f_text, ENTRY1_STYLE) |
---|
| 968 | contextdata.append([f_label,f_text]) |
---|
| 969 | |
---|
| 970 | contexttable = Table(contextdata,style=SLIP_STYLE) |
---|
| 971 | data.append(contexttable) |
---|
| 972 | |
---|
| 973 | transcripttables = render_transcript_data( |
---|
[10261] | 974 | view, tableheader, levels_data, lang=portal_language) |
---|
[10250] | 975 | data.extend(transcripttables) |
---|
| 976 | |
---|
| 977 | # Insert signatures |
---|
| 978 | # XXX: We are using only sigs_in_footer in waeup.kofa, so we |
---|
| 979 | # do not have a test for the following lines. |
---|
| 980 | if signatures and not sigs_in_footer: |
---|
| 981 | data.append(Spacer(1, 20)) |
---|
| 982 | # Render one signature table per signature to |
---|
| 983 | # get date and signature in line. |
---|
| 984 | for signature in signatures: |
---|
| 985 | signaturetables = get_signature_tables(signature) |
---|
| 986 | data.append(signaturetables[0]) |
---|
| 987 | |
---|
[15163] | 988 | # Insert digital signatures |
---|
| 989 | if digital_sigs: |
---|
| 990 | data.append(Spacer(1, 20)) |
---|
| 991 | sigs = digital_sigs.split('\n') |
---|
| 992 | for sig in sigs: |
---|
| 993 | data.append(Paragraph(sig, NOTE_STYLE)) |
---|
| 994 | |
---|
[10250] | 995 | view.response.setHeader( |
---|
| 996 | 'Content-Type', 'application/pdf') |
---|
| 997 | try: |
---|
| 998 | pdf_stream = creator.create_pdf( |
---|
| 999 | data, None, doc_title, author=author, footer=footer_text, |
---|
| 1000 | note=note, sigs_in_footer=sigs_in_footer, topMargin=topMargin) |
---|
| 1001 | except IOError: |
---|
[10261] | 1002 | view.flash(_('Error in image file.')) |
---|
[10250] | 1003 | return view.redirect(view.url(view.context)) |
---|
[15163] | 1004 | if save_file: |
---|
| 1005 | self._saveTranscriptPDF(student, pdf_stream) |
---|
| 1006 | return |
---|
[10250] | 1007 | return pdf_stream |
---|
| 1008 | |
---|
[13898] | 1009 | def renderPDFCourseticketsOverview( |
---|
[15423] | 1010 | self, view, name, session, data, lecturers, orientation, |
---|
[15246] | 1011 | title_length, note): |
---|
[14583] | 1012 | """Render pdf slip of course tickets for a lecturer. |
---|
| 1013 | """ |
---|
[15423] | 1014 | filename = '%s_%s_%s_%s.pdf' % ( |
---|
| 1015 | name, view.context.code, session, view.request.principal.id) |
---|
[13898] | 1016 | session = academic_sessions_vocab.getTerm(session).title |
---|
[14702] | 1017 | creator = getUtility(IPDFCreator, name=orientation) |
---|
[13898] | 1018 | style = getSampleStyleSheet() |
---|
[15197] | 1019 | pdf_data = [] |
---|
| 1020 | pdf_data += [Paragraph( |
---|
[14151] | 1021 | translate(_('<b>Lecturer(s): ${a}</b>', |
---|
| 1022 | mapping = {'a':lecturers})), style["Normal"]),] |
---|
| 1023 | pdf_data += [Paragraph( |
---|
| 1024 | translate(_('<b>Credits: ${a}</b>', |
---|
| 1025 | mapping = {'a':view.context.credits})), style["Normal"]),] |
---|
[14314] | 1026 | # Not used in base package. |
---|
| 1027 | if data[1]: |
---|
| 1028 | pdf_data += [Paragraph( |
---|
[14709] | 1029 | translate(_('<b>${a}</b>', |
---|
[14314] | 1030 | mapping = {'a':data[1][0]})), style["Normal"]),] |
---|
| 1031 | pdf_data += [Paragraph( |
---|
[14709] | 1032 | translate(_('<b>${a}</b>', |
---|
[14708] | 1033 | mapping = {'a':data[1][1]})), style["Normal"]),] |
---|
| 1034 | |
---|
| 1035 | pdf_data += [Paragraph( |
---|
| 1036 | translate(_('<b>Total Students: ${a}</b>', |
---|
| 1037 | mapping = {'a':data[1][2]})), style["Normal"]),] |
---|
| 1038 | pdf_data += [Paragraph( |
---|
[14319] | 1039 | translate(_('<b>Total Pass: ${a} (${b}%)</b>', |
---|
[14708] | 1040 | mapping = {'a':data[1][3],'b':data[1][4]})), style["Normal"]),] |
---|
[14319] | 1041 | pdf_data += [Paragraph( |
---|
| 1042 | translate(_('<b>Total Fail: ${a} (${b}%)</b>', |
---|
[14708] | 1043 | mapping = {'a':data[1][5],'b':data[1][6]})), style["Normal"]),] |
---|
[13899] | 1044 | pdf_data.append(Spacer(1, 20)) |
---|
[15246] | 1045 | colWidths = [None] * len(data[0][0]) |
---|
[15528] | 1046 | pdf_data += [Table(data[0], colWidths=colWidths, style=CONTENT_STYLE, |
---|
| 1047 | repeatRows=1)] |
---|
[15234] | 1048 | # Process title if too long |
---|
| 1049 | title = " ".join(view.context.title.split()) |
---|
| 1050 | ct = textwrap.fill(title, title_length) |
---|
[15526] | 1051 | ft = "" # title |
---|
| 1052 | #if len(textwrap.wrap(title, title_length)) > 1: |
---|
| 1053 | # ft = textwrap.wrap(title, title_length)[0] + ' ...' |
---|
[15197] | 1054 | doc_title = translate(_('${a} (${b})\nAcademic Session ${d}', |
---|
| 1055 | mapping = {'a':ct, |
---|
[14151] | 1056 | 'b':view.context.code, |
---|
| 1057 | 'd':session})) |
---|
[15423] | 1058 | if name == 'attendance': |
---|
| 1059 | doc_title += _('\nAttendance Sheet') |
---|
| 1060 | if name == 'coursetickets': |
---|
| 1061 | doc_title += _('\nCourse Tickets Overview') |
---|
[15526] | 1062 | #footer_title = translate(_('${a} (${b}) - ${d}', |
---|
| 1063 | # mapping = {'a':ft, |
---|
| 1064 | # 'b':view.context.code, |
---|
| 1065 | # 'd':session})) |
---|
| 1066 | footer_title = translate(_('${b} - ${d}', |
---|
| 1067 | mapping = {'b':view.context.code, |
---|
[14705] | 1068 | 'd':session})) |
---|
[13898] | 1069 | author = '%s (%s)' % (view.request.principal.title, |
---|
| 1070 | view.request.principal.id) |
---|
| 1071 | view.response.setHeader( |
---|
| 1072 | 'Content-Type', 'application/pdf') |
---|
| 1073 | view.response.setHeader( |
---|
| 1074 | 'Content-Disposition:', 'attachment; filename="%s' % filename) |
---|
| 1075 | pdf_stream = creator.create_pdf( |
---|
[15246] | 1076 | pdf_data, None, doc_title, author, footer_title + ' -', note |
---|
[13898] | 1077 | ) |
---|
| 1078 | return pdf_stream |
---|
| 1079 | |
---|
[14584] | 1080 | def warnCreditsOOR(self, studylevel, course=None): |
---|
| 1081 | """Return message if credits are out of range. In the base |
---|
| 1082 | package only maximum credits is set. |
---|
[9830] | 1083 | """ |
---|
[14582] | 1084 | if course and studylevel.total_credits + course.credits > 50: |
---|
[14584] | 1085 | return _('Maximum credits exceeded.') |
---|
[14582] | 1086 | elif studylevel.total_credits > 50: |
---|
[14584] | 1087 | return _('Maximum credits exceeded.') |
---|
[14596] | 1088 | return |
---|
[9830] | 1089 | |
---|
[9987] | 1090 | def getBedCoordinates(self, bedticket): |
---|
[13132] | 1091 | """Return descriptive bed coordinates. |
---|
[13124] | 1092 | This method can be used to customize the `display_coordinates` |
---|
[13132] | 1093 | property method in order to display a |
---|
| 1094 | customary description of the bed space. |
---|
[9987] | 1095 | """ |
---|
| 1096 | return bedticket.bed_coordinates |
---|
| 1097 | |
---|
[11772] | 1098 | def clearance_disabled_message(self, student): |
---|
[14583] | 1099 | """Render message if clearance is disabled. |
---|
| 1100 | """ |
---|
[11772] | 1101 | try: |
---|
| 1102 | session_config = grok.getSite()[ |
---|
| 1103 | 'configuration'][str(student.current_session)] |
---|
| 1104 | except KeyError: |
---|
| 1105 | return _('Session configuration object is not available.') |
---|
| 1106 | if not session_config.clearance_enabled: |
---|
| 1107 | return _('Clearance is disabled for this session.') |
---|
| 1108 | return None |
---|
| 1109 | |
---|
[13132] | 1110 | #: A dictionary which maps widget names to headlines. The headline |
---|
| 1111 | #: is rendered in forms and on pdf slips above the respective |
---|
| 1112 | #: display or input widget. There are no separating headlines |
---|
| 1113 | #: in the base package. |
---|
[13129] | 1114 | SEPARATORS_DICT = {} |
---|
[8410] | 1115 | |
---|
[13132] | 1116 | #: A tuple containing names of file upload viewlets which are not shown |
---|
| 1117 | #: on the `StudentClearanceManageFormPage`. Nothing is being skipped |
---|
| 1118 | #: in the base package. This attribute makes only sense, if intermediate |
---|
| 1119 | #: custom packages are being used, like we do for all Nigerian portals. |
---|
[10021] | 1120 | SKIP_UPLOAD_VIEWLETS = () |
---|
| 1121 | |
---|
[13132] | 1122 | #: A tuple containing the names of registration states in which changing of |
---|
| 1123 | #: passport pictures is allowed. |
---|
[13129] | 1124 | PORTRAIT_CHANGE_STATES = (ADMITTED,) |
---|
[10706] | 1125 | |
---|
[12104] | 1126 | #: A tuple containing all exporter names referring to students or |
---|
| 1127 | #: subobjects thereof. |
---|
| 1128 | STUDENT_EXPORTER_NAMES = ('students', 'studentstudycourses', |
---|
| 1129 | 'studentstudylevels', 'coursetickets', |
---|
[12971] | 1130 | 'studentpayments', 'studentunpaidpayments', |
---|
[15051] | 1131 | 'bedtickets', 'sfpaymentsoverview', 'sessionpaymentsoverview', |
---|
[15277] | 1132 | 'studylevelsoverview', 'combocard', 'bursary', |
---|
| 1133 | 'accommodationpayments') |
---|
[12104] | 1134 | |
---|
[12971] | 1135 | #: A tuple containing all exporter names needed for backing |
---|
| 1136 | #: up student data |
---|
| 1137 | STUDENT_BACKUP_EXPORTER_NAMES = ('students', 'studentstudycourses', |
---|
| 1138 | 'studentstudylevels', 'coursetickets', |
---|
| 1139 | 'studentpayments', 'bedtickets') |
---|
| 1140 | |
---|
[8410] | 1141 | #: A prefix used when generating new student ids. Each student id will |
---|
[13129] | 1142 | #: start with this string. The default is 'K' for Kofa. |
---|
[8410] | 1143 | STUDENT_ID_PREFIX = u'K' |
---|