source: main/waeup.kofa/trunk/src/waeup/kofa/students/browser.py @ 17826

Last change on this file since 17826 was 17823, checked in by Henrik Bettermann, 5 months ago

Make _set_exporter_values customizable.

  • Property svn:keywords set to Id
File size: 172.2 KB
RevLine 
[7191]1## $Id: browser.py 17823 2024-06-27 09:18:42Z henrik $
2##
[6621]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"""UI components for students and related components.
19"""
[13935]20import csv
[6621]21import grok
[10458]22import pytz
[13935]23import sys
[15880]24import os
[15626]25import textwrap
[17650]26import segno
[13935]27from cStringIO import StringIO
28from datetime import datetime
29from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
[7275]30from urllib import urlencode
[13935]31from zope.catalog.interfaces import ICatalog
32from zope.component import queryUtility, getUtility, createObject
[7015]33from zope.event import notify
[13935]34from zope.formlib.textwidgets import BytesDisplayWidget
[7723]35from zope.i18n import translate
[9467]36from zope.schema.interfaces import ConstraintNotSatisfied, RequiredMissing
[10080]37from zope.security import checkPermission
[15422]38from zope.securitypolicy.interfaces import IPrincipalRoleManager
[16299]39from waeup.kofa.smtp import encode_address
[13935]40from waeup.kofa.accesscodes import invalidate_accesscode, get_access_code
[7811]41from waeup.kofa.accesscodes.workflow import USED
[15624]42from waeup.kofa.browser.pdf import ENTRY1_STYLE
[13935]43from waeup.kofa.browser.breadcrumbs import Breadcrumb
44from waeup.kofa.browser.interfaces import ICaptchaManager
[9217]45from waeup.kofa.browser.layout import (
[16465]46    KofaPage, KofaFormPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
[13055]47    NullValidator, jsaction, action, UtilityView)
[13200]48from waeup.kofa.browser.pages import (
[13898]49    ContactAdminFormPage, ExportCSVView, doll_up, exports_not_allowed,
50    LocalRoleAssignmentUtilityView)
[9797]51from waeup.kofa.hostels.hostel import NOT_OCCUPIED
[7811]52from waeup.kofa.interfaces import (
[7819]53    IKofaObject, IUserAccount, IExtFileStore, IPasswordValidator, IContactForm,
[13935]54    IKofaUtils, IObjectHistory, academic_sessions, ICSVExporter,
55    academic_sessions_vocab, IDataCenter, DOCLINK)
[7811]56from waeup.kofa.interfaces import MessageFactory as _
[15609]57from waeup.kofa.mandates.mandate import PasswordMandate, ParentsPasswordMandate
[9806]58from waeup.kofa.university.interfaces import (
[16465]59    IDepartment, ICertificate, ICourse, IFlashNotice)
[13935]60from waeup.kofa.university.certificate import (
61    VirtualCertificateExportJobContainer)
62from waeup.kofa.university.department import (
63    VirtualDepartmentExportJobContainer)
[12632]64from waeup.kofa.university.faculty import VirtualFacultyExportJobContainer
[10247]65from waeup.kofa.university.facultiescontainer import (
[13935]66    VirtualFacultiesExportJobContainer)
[9843]67from waeup.kofa.university.course import (
68    VirtualCourseExportJobContainer,)
[9797]69from waeup.kofa.university.vocabularies import course_levels
[9813]70from waeup.kofa.utils.batching import VirtualExportJobContainer
[13935]71from waeup.kofa.utils.helpers import get_current_principal, now
72from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
[7811]73from waeup.kofa.students.interfaces import (
[13935]74    IStudentsContainer, IStudent, IUGStudentClearance, IPGStudentClearance,
[9563]75    IStudentPersonal, IStudentPersonalEdit, IStudentBase, IStudentStudyCourse,
[15163]76    IStudentStudyCourseTransfer,
[13935]77    IStudentAccommodation, IStudentStudyLevel, ICourseTicket, ICourseTicketAdd,
78    IStudentPaymentsContainer, IStudentOnlinePayment, IStudentPreviousPayment,
79    IStudentBalancePayment, IBedTicket, IStudentsUtils, IStudentRequestPW,
[6621]80    )
[9806]81from waeup.kofa.students.catalog import search, StudentQueryResultItem
[9797]82from waeup.kofa.students.vocabularies import StudyLevelSource
[13935]83from waeup.kofa.students.workflow import (
84    ADMITTED, PAID, CLEARANCE, REQUESTED, RETURNING, CLEARED, REGISTERED,
[15163]85    VALIDATED, GRADUATED, TRANSREQ, TRANSVAL, TRANSREL, FORBIDDEN_POSTGRAD_TRANS
[13935]86    )
[6621]87
[9797]88
[13935]89grok.context(IKofaObject)  # Make IKofaObject the default context
[8779]90
[13935]91
[14225]92class TicketError(Exception):
93    """A course ticket could not be added
94    """
95    pass
96
[8737]97# Save function used for save methods in pages
98def msave(view, **data):
99    changed_fields = view.applyData(view.context, **data)
100    # Turn list of lists into single list
101    if changed_fields:
[13935]102        changed_fields = reduce(lambda x, y: x+y, changed_fields.values())
[8737]103    # Inform catalog if certificate has changed
104    # (applyData does this only for the context)
105    if 'certificate' in changed_fields:
106        notify(grok.ObjectModifiedEvent(view.context.student))
107    fields_string = ' + '.join(changed_fields)
108    view.flash(_('Form has been saved.'))
109    if fields_string:
110        view.context.writeLogMessage(view, 'saved: %s' % fields_string)
111    return
112
[16444]113def emit_lock_message(view, msg=None):
[7642]114    """Flash a lock message.
115    """
[16444]116    if msg:
117        view.flash(msg, type="warning")
118        view.redirect(view.url(view.context))
119        return
[11254]120    view.flash(_('The requested form is locked (read-only).'), type="warning")
[7133]121    view.redirect(view.url(view.context))
122    return
123
[8921]124def translated_values(view):
[9685]125    """Translate course ticket attribute values to be displayed on
126    studylevel pages.
127    """
[8921]128    lang = view.request.cookies.get('kofa.language')
129    for value in view.context.values():
[9328]130        # We have to unghostify (according to Tres Seaver) the __dict__
131        # by activating the object, otherwise value_dict will be empty
132        # when calling the first time.
[9330]133        value._p_activate()
[8921]134        value_dict = dict([i for i in value.__dict__.items()])
[11254]135        value_dict['url'] = view.url(value)
[9698]136        value_dict['removable_by_student'] = value.removable_by_student
[8921]137        value_dict['mandatory'] = translate(str(value.mandatory), 'zope',
138            target_language=lang)
139        value_dict['carry_over'] = translate(str(value.carry_over), 'zope',
140            target_language=lang)
[14575]141        value_dict['outstanding'] = translate(str(value.outstanding), 'zope',
142            target_language=lang)
[8921]143        value_dict['automatic'] = translate(str(value.automatic), 'zope',
144            target_language=lang)
[9685]145        value_dict['grade'] = value.grade
146        value_dict['weight'] = value.weight
[14649]147        value_dict['course_category'] = value.course_category
[14946]148        value_dict['total_score'] = value.total_score
[10436]149        semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
[10440]150        value_dict['semester'] = semester_dict[
151            value.semester].replace('mester', 'm.')
[8921]152        yield value_dict
153
[9895]154def addCourseTicket(view, course=None):
155    students_utils = getUtility(IStudentsUtils)
156    ticket = createObject(u'waeup.CourseTicket')
157    ticket.automatic = False
158    ticket.carry_over = False
[14584]159    warning = students_utils.warnCreditsOOR(view.context, course)
160    if warning:
161        view.flash(warning, type="warning")
[9895]162        return False
[15986]163    warning = students_utils.warnCourseAlreadyPassed(view.context, course)
164    if warning:
165        view.flash(warning, type="warning")
166        return False
[9895]167    try:
168        view.context.addCourseTicket(ticket, course)
169    except KeyError:
[11254]170        view.flash(_('The ticket exists.'), type="warning")
[9895]171        return False
[14251]172    except TicketError, error:
[14225]173        # Ticket errors are not being raised in the base package.
[14251]174        view.flash(error, type="warning")
[14225]175        return False
[9895]176    view.flash(_('Successfully added ${a}.',
177        mapping = {'a':ticket.code}))
[9924]178    view.context.writeLogMessage(
179        view,'added: %s|%s|%s' % (
[9925]180        ticket.code, ticket.level, ticket.level_session))
[9895]181    return True
182
[10266]183def level_dict(studycourse):
184    portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
185    level_dict = {}
186    studylevelsource = StudyLevelSource().factory
187    for code in studylevelsource.getValues(studycourse):
188        title = translate(studylevelsource.getTitle(studycourse, code),
189            'waeup.kofa', target_language=portal_language)
190        level_dict[code] = title
191    return level_dict
192
[6629]193class StudentsBreadcrumb(Breadcrumb):
194    """A breadcrumb for the students container.
195    """
196    grok.context(IStudentsContainer)
[7723]197    title = _('Students')
[6629]198
[7459]199    @property
200    def target(self):
201        user = get_current_principal()
202        if getattr(user, 'user_type', None) == 'student':
203            return None
204        return self.viewname
205
[6818]206class StudentBreadcrumb(Breadcrumb):
207    """A breadcrumb for the student container.
208    """
209    grok.context(IStudent)
210
211    def title(self):
[7364]212        return self.context.display_fullname
[6818]213
[6635]214class SudyCourseBreadcrumb(Breadcrumb):
215    """A breadcrumb for the student study course.
216    """
217    grok.context(IStudentStudyCourse)
218
[9140]219    def title(self):
220        if self.context.is_current:
221            return _('Study Course')
222        else:
223            return _('Previous Study Course')
224
[6635]225class PaymentsBreadcrumb(Breadcrumb):
226    """A breadcrumb for the student payments folder.
227    """
[6859]228    grok.context(IStudentPaymentsContainer)
[7723]229    title = _('Payments')
[6635]230
[6870]231class OnlinePaymentBreadcrumb(Breadcrumb):
[7251]232    """A breadcrumb for payments.
[6870]233    """
[6877]234    grok.context(IStudentOnlinePayment)
[6870]235
236    @property
237    def title(self):
238        return self.context.p_id
239
[6635]240class AccommodationBreadcrumb(Breadcrumb):
241    """A breadcrumb for the student accommodation folder.
242    """
243    grok.context(IStudentAccommodation)
[7723]244    title = _('Accommodation')
[6635]245
[6994]246class BedTicketBreadcrumb(Breadcrumb):
247    """A breadcrumb for bed tickets.
248    """
249    grok.context(IBedTicket)
[7009]250
[6994]251    @property
252    def title(self):
[7723]253        return _('Bed Ticket ${a}',
254            mapping = {'a':self.context.getSessionString()})
[6994]255
[6776]256class StudyLevelBreadcrumb(Breadcrumb):
257    """A breadcrumb for course lists.
258    """
259    grok.context(IStudentStudyLevel)
260
261    @property
262    def title(self):
[7834]263        return self.context.level_title
[6776]264
[7819]265class StudentsContainerPage(KofaPage):
[6626]266    """The standard view for student containers.
[6621]267    """
268    grok.context(IStudentsContainer)
269    grok.name('index')
[7240]270    grok.require('waeup.viewStudentsContainer')
[6695]271    grok.template('containerpage')
[11254]272    label = _('Find students')
[10647]273    search_button = _('Find student(s)')
[6642]274    pnav = 4
[6621]275
[6626]276    def update(self, *args, **kw):
[16937]277        prefix = getUtility(IStudentsUtils).STUDENT_ID_PREFIX
278        self.curr_stud_id = "%s%s" % (
[16939]279            prefix, self.context._curr_stud_id - 1)
[6626]280        form = self.request.form
281        self.hitlist = []
[15417]282        if form.get('searchtype', None) in (
283            'suspended', TRANSREQ, TRANSVAL, GRADUATED):
[9795]284            self.searchtype = form['searchtype']
285            self.searchterm = None
286        elif 'searchterm' in form and form['searchterm']:
[6626]287            self.searchterm = form['searchterm']
288            self.searchtype = form['searchtype']
289        elif 'old_searchterm' in form:
290            self.searchterm = form['old_searchterm']
291            self.searchtype = form['old_searchtype']
292        else:
293            if 'search' in form:
[11254]294                self.flash(_('Empty search string'), type="warning")
[6626]295            return
[7068]296        if self.searchtype == 'current_session':
[8081]297            try:
298                self.searchterm = int(self.searchterm)
299            except ValueError:
[11254]300                self.flash(_('Only year dates allowed (e.g. 2011).'),
301                           type="danger")
[8081]302                return
[6626]303        self.hitlist = search(query=self.searchterm,
304            searchtype=self.searchtype, view=self)
305        if not self.hitlist:
[11254]306            self.flash(_('No student found.'), type="warning")
[6626]307        return
308
[7819]309class StudentsContainerManagePage(KofaPage):
[6626]310    """The manage page for student containers.
[6622]311    """
312    grok.context(IStudentsContainer)
313    grok.name('manage')
[7136]314    grok.require('waeup.manageStudent')
[6695]315    grok.template('containermanagepage')
[6642]316    pnav = 4
[13076]317    label = _('Manage students section')
[10647]318    search_button = _('Find student(s)')
[7735]319    remove_button = _('Remove selected')
[16299]320    send_email_button = _('Send bulk email')
[13177]321    doclink = DOCLINK + '/students.html'
[6622]322
[6626]323    def update(self, *args, **kw):
324        form = self.request.form
325        self.hitlist = []
[15417]326        if form.get('searchtype', None) in (
327            'suspended', TRANSREQ, TRANSVAL, GRADUATED):
[9795]328            self.searchtype = form['searchtype']
329            self.searchterm = None
330        elif 'searchterm' in form and form['searchterm']:
[6626]331            self.searchterm = form['searchterm']
332            self.searchtype = form['searchtype']
333        elif 'old_searchterm' in form:
334            self.searchterm = form['old_searchterm']
335            self.searchtype = form['old_searchtype']
336        else:
337            if 'search' in form:
[11254]338                self.flash(_('Empty search string'), type="warning")
[6626]339            return
[8082]340        if self.searchtype == 'current_session':
341            try:
342                self.searchterm = int(self.searchterm)
343            except ValueError:
[11254]344                self.flash(_('Only year dates allowed (e.g. 2011).'),
345                           type="danger")
[8082]346                return
[6626]347        if not 'entries' in form:
348            self.hitlist = search(query=self.searchterm,
349                searchtype=self.searchtype, view=self)
350            if not self.hitlist:
[11254]351                self.flash(_('No student found.'), type="warning")
[16299]352            if 'remove' in form or 'send_email' in form:
[11254]353                self.flash(_('No item selected.'), type="warning")
[6626]354            return
355        entries = form['entries']
356        if isinstance(entries, basestring):
357            entries = [entries]
[16299]358        entries.sort()
[16302]359        if 'send_email' in form and len(entries)>50:
360            self.flash(_(
361                'Maximum of 50 emails can be sent. Please select less students.'),
362                type="warning")
363            return
[6626]364        deleted = []
[16300]365        emails_tobesent = []
[6626]366        for entry in entries:
367            if 'remove' in form:
368                del self.context[entry]
369                deleted.append(entry)
[16299]370            if 'send_email' in form and self.context[entry].email:
[16300]371                emails_tobesent.append((
[16299]372                    self.context[entry].email,
[16300]373                    self.context[entry].student_id))
[16299]374        if 'send_email' in form and not len(emails_tobesent):
375            self.flash(_('No email address found.'), type="warning")
376            return
377        if len(emails_tobesent):
[16300]378            args = {'bcc_to': emails_tobesent}
[16299]379            self.redirect(self.url(self.context) +
380                '/send_bulk_email?%s' % urlencode(args))
381            return
[6626]382        self.hitlist = search(query=self.searchterm,
383            searchtype=self.searchtype, view=self)
384        if len(deleted):
[7723]385            self.flash(_('Successfully removed: ${a}',
386                mapping = {'a':', '.join(deleted)}))
[6622]387        return
388
[7819]389class StudentAddFormPage(KofaAddFormPage):
[6622]390    """Add-form to add a student.
391    """
392    grok.context(IStudentsContainer)
[7136]393    grok.require('waeup.manageStudent')
[6622]394    grok.name('addstudent')
[7357]395    form_fields = grok.AutoFields(IStudent).select(
[7520]396        'firstname', 'middlename', 'lastname', 'reg_number')
[7723]397    label = _('Add student')
[6642]398    pnav = 4
[6622]399
[13108]400    @action(_('Create student'), style='primary')
[6622]401    def addStudent(self, **data):
402        student = createObject(u'waeup.Student')
403        self.applyData(student, **data)
[6652]404        self.context.addStudent(student)
[7723]405        self.flash(_('Student record created.'))
[6651]406        self.redirect(self.url(self.context[student.student_id], 'index'))
[6622]407        return
408
[14293]409    @action(_('Create graduated student'), style='primary')
410    def addGraduatedStudent(self, **data):
411        student = createObject(u'waeup.Student')
412        self.applyData(student, **data)
413        self.context.addStudent(student)
414        IWorkflowState(student).setState(GRADUATED)
[15417]415        notify(grok.ObjectModifiedEvent(student))
[15418]416        history = IObjectHistory(student)
[15419]417        history.addMessage("State 'graduated' set")
[15418]418        self.flash(_('Graduated student record created.'))
[14293]419        self.redirect(self.url(self.context[student.student_id], 'index'))
420        return
421
[9338]422class LoginAsStudentStep1(KofaEditFormPage):
423    """ View to temporarily set a student password.
424    """
425    grok.context(IStudent)
426    grok.name('loginasstep1')
427    grok.require('waeup.loginAsStudent')
428    grok.template('loginasstep1')
429    pnav = 4
430
[15609]431    def update(self):
432        super(LoginAsStudentStep1, self).update()
433        kofa_utils = getUtility(IKofaUtils)
434        self.temp_password_minutes = kofa_utils.TEMP_PASSWORD_MINUTES
435        return
436
[9338]437    def label(self):
438        return _(u'Set temporary password for ${a}',
439            mapping = {'a':self.context.display_fullname})
440
441    @action('Set password now', style='primary')
442    def setPassword(self, *args, **data):
443        kofa_utils = getUtility(IKofaUtils)
444        password = kofa_utils.genPassword()
445        self.context.setTempPassword(self.request.principal.id, password)
446        self.context.writeLogMessage(
447            self, 'temp_password generated: %s' % password)
448        args = {'password':password}
449        self.redirect(self.url(self.context) +
450            '/loginasstep2?%s' % urlencode(args))
451        return
452
453class LoginAsStudentStep2(KofaPage):
454    """ View to temporarily login as student with a temporary password.
455    """
456    grok.context(IStudent)
457    grok.name('loginasstep2')
458    grok.require('waeup.Public')
459    grok.template('loginasstep2')
460    login_button = _('Login now')
461    pnav = 4
462
463    def label(self):
464        return _(u'Login as ${a}',
465            mapping = {'a':self.context.student_id})
466
467    def update(self, SUBMIT=None, password=None):
468        self.password = password
469        if SUBMIT is not None:
470            self.flash(_('You successfully logged in as student.'))
471            self.redirect(self.url(self.context))
472        return
473
[7819]474class StudentBaseDisplayFormPage(KofaDisplayFormPage):
[6631]475    """ Page to display student base data
476    """
[6622]477    grok.context(IStudent)
478    grok.name('index')
[6660]479    grok.require('waeup.viewStudent')
[6695]480    grok.template('basepage')
[9702]481    form_fields = grok.AutoFields(IStudentBase).omit(
[13711]482        'password', 'suspended', 'suspended_comment', 'flash_notice')
[6642]483    pnav = 4
[6622]484
485    @property
486    def label(self):
[8983]487        if self.context.suspended:
[9124]488            return _('${a}: Base Data (account deactivated)',
[8983]489                mapping = {'a':self.context.display_fullname})
490        return  _('${a}: Base Data',
[7723]491            mapping = {'a':self.context.display_fullname})
[6631]492
[6699]493    @property
494    def hasPassword(self):
495        if self.context.password:
[7723]496            return _('set')
497        return _('unset')
[6699]498
[13711]499    def update(self):
500        if self.context.flash_notice:
501            self.flash(self.context.flash_notice, type="warning")
502        super(StudentBaseDisplayFormPage, self).update()
503        return
504
[9141]505class StudentBasePDFFormPage(KofaDisplayFormPage):
506    """ Page to display student base data in pdf files.
507    """
508
[10250]509    def __init__(self, context, request, omit_fields=()):
[9374]510        self.omit_fields = omit_fields
511        super(StudentBasePDFFormPage, self).__init__(context, request)
512
513    @property
514    def form_fields(self):
515        form_fields = grok.AutoFields(IStudentBase)
516        for field in self.omit_fields:
517            form_fields = form_fields.omit(field)
518        return form_fields
519
[13055]520class ContactStudentFormPage(ContactAdminFormPage):
[7229]521    grok.context(IStudent)
[7230]522    grok.name('contactstudent')
[7275]523    grok.require('waeup.viewStudent')
[7229]524    pnav = 4
525    form_fields = grok.AutoFields(IContactForm).select('subject', 'body')
526
[9484]527    def update(self, subject=u'', body=u''):
[13055]528        super(ContactStudentFormPage, self).update()
[7275]529        self.form_fields.get('subject').field.default = subject
[9484]530        self.form_fields.get('body').field.default = body
[9857]531        return
[7275]532
[7229]533    def label(self):
[7723]534        return _(u'Send message to ${a}',
535            mapping = {'a':self.context.display_fullname})
[7229]536
[7459]537    @action('Send message now', style='primary')
[7229]538    def send(self, *args, **data):
[7234]539        try:
[7403]540            email = self.request.principal.email
[7234]541        except AttributeError:
[7403]542            email = self.config.email_admin
543        usertype = getattr(self.request.principal,
544                           'user_type', 'system').title()
[7819]545        kofa_utils = getUtility(IKofaUtils)
[7811]546        success = kofa_utils.sendContactForm(
[7403]547                self.request.principal.title,email,
548                self.context.display_fullname,self.context.email,
549                self.request.principal.id,usertype,
550                self.config.name,
551                data['body'],data['subject'])
[7229]552        if success:
[7723]553            self.flash(_('Your message has been sent.'))
[7229]554        else:
[11254]555            self.flash(_('An smtp server error occurred.'), type="danger")
[7229]556        return
557
[16299]558class SendBulEmailsFormPage(ContactAdminFormPage):
559    grok.context(IStudentsContainer)
560    grok.name('send_bulk_email')
561    grok.require('waeup.manageStudent')
562    pnav = 4
563    form_fields = grok.AutoFields(IContactForm).select('subject', 'body', 'bcc_to')
564    label = _('Send bulk email')
565
566    def update(self, bcc_to=u''):
567        self.form_fields.get('bcc_to').field.default = bcc_to
568        return
569
570    @action('Send message now', style='primary')
571    def send(self, *args, **data):
572        try:
573            email = self.request.principal.email
574        except AttributeError:
575            email = self.config.email_admin
576        usertype = getattr(self.request.principal,
577                           'user_type', 'system').title()
578        kofa_utils = getUtility(IKofaUtils)
579        success = kofa_utils.sendContactForm(
580                self.request.principal.title,email,
581                self.request.principal.title,email, # sent to the sender's address
582                self.request.principal.id,usertype,
583                self.config.name,
584                data['body'],data['subject'],
[16300]585                eval(data['bcc_to'])
586                )
[16299]587        if success:
588            self.flash(_('Your message has been sent.'))
589        else:
590            self.flash(_('An smtp server error occurred.'), type="danger")
591        return
592
[13055]593class ExportPDFAdmissionSlip(UtilityView, grok.View):
[9191]594    """Deliver a PDF Admission slip.
595    """
596    grok.context(IStudent)
597    grok.name('admission_slip.pdf')
598    grok.require('waeup.viewStudent')
599    prefix = 'form'
600
[15757]601    omit_fields = ('date_of_birth', 'current_level')
[10270]602
[9191]603    form_fields = grok.AutoFields(IStudentBase).select('student_id', 'reg_number')
604
[16262]605
606    # Can be used for testing. Just replace 'post_text=None'
607    # by post_text=self.post_text'
608    post_text = '''
609Conratulations!
610
611
612<img src="${test_signature_img_path}" valign="-20" height="38" width="86" />
613
614
615John Tester
616- Registrar -
617'''
618
[9191]619    @property
620    def label(self):
621        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
622        return translate(_('Admission Letter of'),
623            'waeup.kofa', target_language=portal_language) \
624            + ' %s' % self.context.display_fullname
625
626    def render(self):
627        students_utils = getUtility(IStudentsUtils)
[15880]628        letterhead_path = os.path.join(
629            os.path.dirname(__file__), 'static', 'letterhead_admission.jpg')
630        if not os.path.exists(letterhead_path):
631            letterhead_path = None
[9191]632        return students_utils.renderPDFAdmissionLetter(self,
[15880]633            self.context.student, omit_fields=self.omit_fields,
[16262]634            letterhead_path=letterhead_path, post_text=None)
[9191]635
[17650]636class QRCodeView(UtilityView, grok.View):
637    """View which renders a QRCode only.
638    """
639    grok.context(IStudent)
640    grok.name('qrcode_admission_letter.png')
641    grok.require('waeup.viewStudent')
642    scale = 3
643    uri = 'admission_slip.pdf'
644
645    def render(self):
646        qrcode = segno.make(self.url(self.context, self.uri))
647        self.response.setHeader('Content-Type', 'image/png')
648        return qrcode.png_data_uri(
649            scale=self.scale).split(',')[1].decode('base64')
650
[7819]651class StudentBaseManageFormPage(KofaEditFormPage):
[7133]652    """ View to manage student base data
[6631]653    """
654    grok.context(IStudent)
[7133]655    grok.name('manage_base')
[7136]656    grok.require('waeup.manageStudent')
[9124]657    form_fields = grok.AutoFields(IStudentBase).omit(
658        'student_id', 'adm_code', 'suspended')
[6695]659    grok.template('basemanagepage')
[7723]660    label = _('Manage base data')
[6642]661    pnav = 4
[6631]662
[6638]663    def update(self):
664        super(StudentBaseManageFormPage, self).update()
665        self.wf_info = IWorkflowInfo(self.context)
666        return
667
[7723]668    @action(_('Save'), style='primary')
[6638]669    def save(self, **data):
[6701]670        form = self.request.form
[6790]671        password = form.get('password', None)
672        password_ctl = form.get('control_password', None)
673        if password:
[7147]674            validator = getUtility(IPasswordValidator)
675            errors = validator.validate_password(password, password_ctl)
676            if errors:
[11254]677                self.flash( ' '.join(errors), type="danger")
[7147]678                return
679        changed_fields = self.applyData(self.context, **data)
[6771]680        # Turn list of lists into single list
681        if changed_fields:
682            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7147]683        else:
684            changed_fields = []
685        if password:
[9273]686            # Now we know that the form has no errors and can set password
[7147]687            IUserAccount(self.context).setPassword(password)
688            changed_fields.append('password')
689        fields_string = ' + '.join(changed_fields)
[7723]690        self.flash(_('Form has been saved.'))
[6644]691        if fields_string:
[8735]692            self.context.writeLogMessage(self, 'saved: % s' % fields_string)
[6638]693        return
694
[9273]695class StudentTriggerTransitionFormPage(KofaEditFormPage):
[12048]696    """ View to trigger student workflow transitions
[9273]697    """
698    grok.context(IStudent)
699    grok.name('trigtrans')
700    grok.require('waeup.triggerTransition')
701    grok.template('trigtrans')
702    label = _('Trigger registration transition')
703    pnav = 4
704
705    def getTransitions(self):
706        """Return a list of dicts of allowed transition ids and titles.
707
708        Each list entry provides keys ``name`` and ``title`` for
709        internal name and (human readable) title of a single
710        transition.
711        """
712        wf_info = IWorkflowInfo(self.context)
713        allowed_transitions = [t for t in wf_info.getManualTransitions()
714            if not t[0].startswith('pay')]
[10155]715        if self.context.is_postgrad and not self.context.is_special_postgrad:
[9273]716            allowed_transitions = [t for t in allowed_transitions
717                if not t[0] in FORBIDDEN_POSTGRAD_TRANS]
718        return [dict(name='', title=_('No transition'))] +[
719            dict(name=x, title=y) for x, y in allowed_transitions]
720
721    @action(_('Save'), style='primary')
722    def save(self, **data):
723        form = self.request.form
[9701]724        if 'transition' in form and form['transition']:
[9273]725            transition_id = form['transition']
726            wf_info = IWorkflowInfo(self.context)
727            wf_info.fireTransition(transition_id)
728        return
729
[13055]730class StudentActivateView(UtilityView, grok.View):
[9124]731    """ Activate student account
732    """
733    grok.context(IStudent)
734    grok.name('activate')
735    grok.require('waeup.manageStudent')
736
737    def update(self):
738        self.context.suspended = False
739        self.context.writeLogMessage(self, 'account activated')
740        history = IObjectHistory(self.context)
741        history.addMessage('Student account activated')
742        self.flash(_('Student account has been activated.'))
743        self.redirect(self.url(self.context))
744        return
745
746    def render(self):
747        return
748
[13055]749class StudentDeactivateView(UtilityView, grok.View):
[9124]750    """ Deactivate student account
751    """
752    grok.context(IStudent)
753    grok.name('deactivate')
754    grok.require('waeup.manageStudent')
755
756    def update(self):
757        self.context.suspended = True
758        self.context.writeLogMessage(self, 'account deactivated')
759        history = IObjectHistory(self.context)
760        history.addMessage('Student account deactivated')
761        self.flash(_('Student account has been deactivated.'))
762        self.redirect(self.url(self.context))
763        return
764
765    def render(self):
766        return
767
[7819]768class StudentClearanceDisplayFormPage(KofaDisplayFormPage):
[6631]769    """ Page to display student clearance data
770    """
771    grok.context(IStudent)
772    grok.name('view_clearance')
[6660]773    grok.require('waeup.viewStudent')
[6642]774    pnav = 4
[6631]775
776    @property
[8099]777    def separators(self):
778        return getUtility(IStudentsUtils).SEPARATORS_DICT
779
780    @property
[7993]781    def form_fields(self):
[8472]782        if self.context.is_postgrad:
[13103]783            form_fields = grok.AutoFields(IPGStudentClearance)
[7993]784        else:
[13103]785            form_fields = grok.AutoFields(IUGStudentClearance)
[9486]786        if not getattr(self.context, 'officer_comment'):
787            form_fields = form_fields.omit('officer_comment')
[9484]788        else:
[9486]789            form_fields['officer_comment'].custom_widget = BytesDisplayWidget
[7993]790        return form_fields
791
792    @property
[6631]793    def label(self):
[7723]794        return _('${a}: Clearance Data',
795            mapping = {'a':self.context.display_fullname})
[6631]796
[16251]797class ExportPDFStudyCourseBaseDataSlip(UtilityView, grok.View):
[16086]798    """Deliver a PDF base and studycourse data slip.
799    """
800    grok.context(IStudentStudyCourse)
[16251]801    grok.name('studycourse_slip.pdf')
[16086]802    grok.require('waeup.viewStudent')
803    prefix = 'form'
804
805    omit_fields = (
806        'suspended',
807        'adm_code', 'suspended_comment',
808        'current_level',
809        'flash_notice', 'entry_session',
810        'parents_email')
811
812    form_fields = grok.AutoFields(IStudentStudyCourse).omit('certificate')
813
814    @property
815    def title(self):
816        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
817        return translate(_('Current Study Course Data'), 'waeup.kofa',
818            target_language=portal_language)
819
820    @property
821    def label(self):
822        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[16286]823        return translate(_('Study Course Data of'),
[16086]824            'waeup.kofa', target_language=portal_language) \
825            + ' %s' % self.context.student.display_fullname
826
827    def render(self):
828        studentview = StudentBasePDFFormPage(self.context.student,
829            self.request, self.omit_fields)
830        students_utils = getUtility(IStudentsUtils)
831        return students_utils.renderPDF(
832            self, 'basedata_slip.pdf',
833            self.context.student, studentview,
834            omit_fields=self.omit_fields)
835
[16251]836class ExportPDFPersonalDataSlip(UtilityView, grok.View):
837    """Deliver a PDF base and personal data slip.
838    """
839    grok.context(IStudent)
840    grok.name('personal_slip.pdf')
841    grok.require('waeup.viewStudent')
842    prefix = 'form'
843
844    omit_fields = (
845        'suspended',
846        'adm_code', 'suspended_comment',
847        'current_level',
848        'flash_notice', 'entry_session',
849        'parents_email')
850
851    form_fields = grok.AutoFields(IStudentPersonal)
852
853    @property
854    def title(self):
855        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
856        return translate(_('Personal Data'), 'waeup.kofa',
857            target_language=portal_language)
858
859    @property
860    def label(self):
861        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
862        return translate(_('Personal Data of'),
863            'waeup.kofa', target_language=portal_language) \
864            + ' %s' % self.context.student.display_fullname
865
866    def render(self):
867        studentview = StudentBasePDFFormPage(self.context.student,
868            self.request, self.omit_fields)
869        students_utils = getUtility(IStudentsUtils)
870        return students_utils.renderPDF(
871            self, 'personal_slip.pdf',
872            self.context.student, studentview,
873            omit_fields=self.omit_fields)
874
[13056]875class ExportPDFClearanceSlip(grok.View):
[7277]876    """Deliver a PDF slip of the context.
877    """
878    grok.context(IStudent)
[9452]879    grok.name('clearance_slip.pdf')
[7277]880    grok.require('waeup.viewStudent')
881    prefix = 'form'
[9702]882    omit_fields = (
[10694]883        'suspended', 'phone',
[10256]884        'adm_code', 'suspended_comment',
[13711]885        'date_of_birth', 'current_level',
886        'flash_notice')
[7277]887
888    @property
[7993]889    def form_fields(self):
[8472]890        if self.context.is_postgrad:
[13103]891            form_fields = grok.AutoFields(IPGStudentClearance)
[7993]892        else:
[13103]893            form_fields = grok.AutoFields(IUGStudentClearance)
[9486]894        if not getattr(self.context, 'officer_comment'):
895            form_fields = form_fields.omit('officer_comment')
[7993]896        return form_fields
897
898    @property
[7723]899    def title(self):
[7819]900        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]901        return translate(_('Clearance Data'), 'waeup.kofa',
[7723]902            target_language=portal_language)
903
904    @property
[7277]905    def label(self):
[7819]906        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[9026]907        return translate(_('Clearance Slip of'),
[7811]908            'waeup.kofa', target_language=portal_language) \
[7723]909            + ' %s' % self.context.display_fullname
[7277]910
[9969]911    # XXX: not used in waeup.kofa and thus not tested
[9010]912    def _signatures(self):
[9548]913        isStudent = getattr(
914            self.request.principal, 'user_type', None) == 'student'
915        if not isStudent and self.context.state in (CLEARED, ):
[9969]916            return ([_('Student Signature')],
917                    [_('Clearance Officer Signature')])
[9010]918        return
919
[9555]920    def _sigsInFooter(self):
[9548]921        isStudent = getattr(
922            self.request.principal, 'user_type', None) == 'student'
923        if not isStudent and self.context.state in (CLEARED, ):
[9555]924            return (_('Date, Student Signature'),
925                    _('Date, Clearance Officer Signature'),
926                    )
[9557]927        return ()
[9548]928
[7277]929    def render(self):
[9141]930        studentview = StudentBasePDFFormPage(self.context.student,
[9375]931            self.request, self.omit_fields)
[7277]932        students_utils = getUtility(IStudentsUtils)
933        return students_utils.renderPDF(
[9452]934            self, 'clearance_slip.pdf',
[9548]935            self.context.student, studentview, signatures=self._signatures(),
[10250]936            sigs_in_footer=self._sigsInFooter(),
937            omit_fields=self.omit_fields)
[7277]938
[7819]939class StudentClearanceManageFormPage(KofaEditFormPage):
[8120]940    """ Page to manage student clearance data
[6631]941    """
942    grok.context(IStudent)
[8119]943    grok.name('manage_clearance')
[7136]944    grok.require('waeup.manageStudent')
[7134]945    grok.template('clearanceeditpage')
[7723]946    label = _('Manage clearance data')
[11567]947    deletion_warning = _('Are you sure?')
[6642]948    pnav = 4
[6650]949
[7993]950    @property
[8099]951    def separators(self):
952        return getUtility(IStudentsUtils).SEPARATORS_DICT
953
954    @property
[7993]955    def form_fields(self):
[8472]956        if self.context.is_postgrad:
[8977]957            form_fields = grok.AutoFields(IPGStudentClearance).omit('clr_code')
[7993]958        else:
[8977]959            form_fields = grok.AutoFields(IUGStudentClearance).omit('clr_code')
[7993]960        return form_fields
961
[16387]962    @property
963    def do_not_render_buttons(self):
964        if self.context.state != CLEARANCE:
965            return ('Save and request clearance',)
966        return ()
967
[7723]968    @action(_('Save'), style='primary')
[6695]969    def save(self, **data):
[6762]970        msave(self, **data)
[6695]971        return
972
[13055]973class StudentClearView(UtilityView, grok.View):
[7158]974    """ Clear student by clearance officer
975    """
976    grok.context(IStudent)
977    grok.name('clear')
978    grok.require('waeup.clearStudent')
979
980    def update(self):
[13028]981        cdm = getUtility(IStudentsUtils).clearance_disabled_message(
982            self.context)
[11772]983        if cdm:
984            self.flash(cdm)
[9814]985            self.redirect(self.url(self.context,'view_clearance'))
986            return
[7158]987        if self.context.state == REQUESTED:
988            IWorkflowInfo(self.context).fireTransition('clear')
[7723]989            self.flash(_('Student has been cleared.'))
[7158]990        else:
[11254]991            self.flash(_('Student is in wrong state.'), type="warning")
[7158]992        self.redirect(self.url(self.context,'view_clearance'))
993        return
994
995    def render(self):
996        return
997
[16187]998class StudentTempClearancePage(KofaEditFormPage):
999    """ Temporarily clearance by clearance officers.
1000    """
1001    grok.context(IStudent)
1002    grok.name('temp_clearance')
1003    label = _('Clear student temporarily')
1004    grok.require('waeup.clearStudent')
1005    form_fields = grok.AutoFields(
1006        IUGStudentClearance).select('officer_comment')
1007
1008    def update(self):
1009        cdm = getUtility(IStudentsUtils).clearance_disabled_message(
1010            self.context)
1011        if cdm:
1012            self.flash(cdm, type="warning")
1013            self.redirect(self.url(self.context,'view_clearance'))
1014            return
1015        return super(StudentTempClearancePage, self).update()
1016
1017    @action(_('Save comment and clear student temporarily now'), style='primary')
1018    def temp_clear(self, **data):
1019        if self.context.state == REQUESTED:
1020            if self.context.officer_comment \
1021                and self.context.officer_comment.startswith('Temporarily cleared'):
1022                self.flash(
1023                    _('Not allowed: student has already been '
1024                      'temporarily cleared.'),
1025                    type="warning")
1026                self.redirect(self.url(self.context,'view_clearance'))
1027                return
1028            if not data['officer_comment']:
1029                self.flash(_('Please write a comment.'), type="warning")
1030                self.redirect(self.url(self.context,'view_clearance'))
1031                return
1032            message = _('Student has been temporarily cleared.')
1033            self.flash(message)
1034        else:
1035            self.flash(_('Student is in wrong state.'), type="warning")
1036            self.redirect(self.url(self.context,'view_clearance'))
1037            return
1038        user = get_current_principal()
1039        if user is None:
1040            usertitle = 'system'
1041        else:
1042            usertitle = getattr(user, 'public_name', None)
1043            if not usertitle:
1044                usertitle = user.title
1045        comment = data['officer_comment']
1046        data['officer_comment'] = translate(
[16194]1047            _('Temporarily cleared by ${a}. Officer\'s comment:\n${b}',
[16187]1048            mapping = {'a':usertitle, 'b':comment}))
1049        self.applyData(self.context, **data)
1050        self.context.writeLogMessage(
1051            self, 'comment: %s' % comment.replace('\n', '<br>'))
1052        args = {'subject':'You have been temporarily cleared.', 'body':comment}
1053        self.redirect(self.url(self.context) +
1054            '/contactstudent?%s' % urlencode(args))
1055        return
1056
[9484]1057class StudentRejectClearancePage(KofaEditFormPage):
[13028]1058    """ Reject clearance by clearance officers.
[7158]1059    """
1060    grok.context(IStudent)
1061    grok.name('reject_clearance')
[9484]1062    label = _('Reject clearance')
[7158]1063    grok.require('waeup.clearStudent')
[9484]1064    form_fields = grok.AutoFields(
[9486]1065        IUGStudentClearance).select('officer_comment')
[7158]1066
[9814]1067    def update(self):
[13028]1068        cdm = getUtility(IStudentsUtils).clearance_disabled_message(
1069            self.context)
[11772]1070        if cdm:
1071            self.flash(cdm, type="warning")
[9814]1072            self.redirect(self.url(self.context,'view_clearance'))
1073            return
1074        return super(StudentRejectClearancePage, self).update()
1075
[9484]1076    @action(_('Save comment and reject clearance now'), style='primary')
1077    def reject(self, **data):
[7158]1078        if self.context.state == CLEARED:
1079            IWorkflowInfo(self.context).fireTransition('reset4')
[7723]1080            message = _('Clearance has been annulled.')
[11254]1081            self.flash(message, type="warning")
[7158]1082        elif self.context.state == REQUESTED:
1083            IWorkflowInfo(self.context).fireTransition('reset3')
[7723]1084            message = _('Clearance request has been rejected.')
[11254]1085            self.flash(message, type="warning")
[7158]1086        else:
[11254]1087            self.flash(_('Student is in wrong state.'), type="warning")
[7334]1088            self.redirect(self.url(self.context,'view_clearance'))
[7275]1089            return
[9484]1090        self.applyData(self.context, **data)
[9486]1091        comment = data['officer_comment']
[9556]1092        if comment:
1093            self.context.writeLogMessage(
1094                self, 'comment: %s' % comment.replace('\n', '<br>'))
1095            args = {'subject':message, 'body':comment}
1096        else:
1097            args = {'subject':message,}
[7275]1098        self.redirect(self.url(self.context) +
1099            '/contactstudent?%s' % urlencode(args))
[7158]1100        return
1101
[7819]1102class StudentPersonalDisplayFormPage(KofaDisplayFormPage):
[6631]1103    """ Page to display student personal data
1104    """
1105    grok.context(IStudent)
1106    grok.name('view_personal')
[6660]1107    grok.require('waeup.viewStudent')
[6631]1108    form_fields = grok.AutoFields(IStudentPersonal)
[7386]1109    form_fields['perm_address'].custom_widget = BytesDisplayWidget
[9543]1110    form_fields[
1111        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[6642]1112    pnav = 4
[6631]1113
1114    @property
1115    def label(self):
[7723]1116        return _('${a}: Personal Data',
1117            mapping = {'a':self.context.display_fullname})
[6631]1118
[8903]1119class StudentPersonalManageFormPage(KofaEditFormPage):
1120    """ Page to manage personal data
[6631]1121    """
1122    grok.context(IStudent)
[8903]1123    grok.name('manage_personal')
1124    grok.require('waeup.manageStudent')
[9553]1125    form_fields = grok.AutoFields(IStudentPersonal)
1126    form_fields['personal_updated'].for_display = True
[9571]1127    form_fields[
1128        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[8903]1129    label = _('Manage personal data')
[6642]1130    pnav = 4
[6631]1131
[7723]1132    @action(_('Save'), style='primary')
[6762]1133    def save(self, **data):
1134        msave(self, **data)
1135        return
1136
[9543]1137class StudentPersonalEditFormPage(KofaEditFormPage):
[8903]1138    """ Page to edit personal data
1139    """
[9543]1140    grok.context(IStudent)
[8903]1141    grok.name('edit_personal')
1142    grok.require('waeup.handleStudent')
[9563]1143    form_fields = grok.AutoFields(IStudentPersonalEdit).omit('personal_updated')
[8903]1144    label = _('Edit personal data')
1145    pnav = 4
1146
[9543]1147    @action(_('Save/Confirm'), style='primary')
1148    def save(self, **data):
1149        msave(self, **data)
[9569]1150        self.context.personal_updated = datetime.utcnow()
[9543]1151        return
1152
[7819]1153class StudyCourseDisplayFormPage(KofaDisplayFormPage):
[6635]1154    """ Page to display the student study course data
1155    """
1156    grok.context(IStudentStudyCourse)
1157    grok.name('index')
[6660]1158    grok.require('waeup.viewStudent')
[6775]1159    grok.template('studycoursepage')
[6642]1160    pnav = 4
[6635]1161
1162    @property
[8972]1163    def form_fields(self):
1164        if self.context.is_postgrad:
1165            form_fields = grok.AutoFields(IStudentStudyCourse).omit(
[9723]1166                'previous_verdict')
[8972]1167        else:
1168            form_fields = grok.AutoFields(IStudentStudyCourse)
1169        return form_fields
1170
1171    @property
[6635]1172    def label(self):
[9140]1173        if self.context.is_current:
1174            return _('${a}: Study Course',
1175                mapping = {'a':self.context.__parent__.display_fullname})
1176        else:
1177            return _('${a}: Previous Study Course',
1178                mapping = {'a':self.context.__parent__.display_fullname})
[6635]1179
[6912]1180    @property
1181    def current_mode(self):
[7641]1182        if self.context.certificate is not None:
[7841]1183            studymodes_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
[7681]1184            return studymodes_dict[self.context.certificate.study_mode]
[7171]1185        return
[7642]1186
[7171]1187    @property
1188    def department(self):
[15063]1189        try:
1190            if self.context.certificate is not None:
1191                return self.context.certificate.__parent__.__parent__
1192        except AttributeError:
1193            # handle_certificate_removed does only clear
1194            # studycourses with certificate code 'studycourse' but not
[15066]1195            # 'studycourse_1' or 'studycourse_2'. These certificates do
[15063]1196            # still exist but have no parents.
1197            pass
[7171]1198        return
[6912]1199
[7171]1200    @property
1201    def faculty(self):
[15063]1202        try:
1203            if self.context.certificate is not None:
1204                return self.context.certificate.__parent__.__parent__.__parent__
1205        except AttributeError:
1206            # handle_certificate_removed does only clear
1207            # studycourses with certificate code 'studycourse' but not
[15066]1208            # 'studycourse_1' or 'studycourse_2'. These certificates do
[15063]1209            # still exist but have no parents.
1210            pass
[7171]1211        return
1212
[9140]1213    @property
1214    def prev_studycourses(self):
1215        if self.context.is_current:
1216            if self.context.__parent__.get('studycourse_2', None) is not None:
1217                return (
1218                        {'href':self.url(self.context.student) + '/studycourse_1',
1219                        'title':_('First Study Course, ')},
1220                        {'href':self.url(self.context.student) + '/studycourse_2',
1221                        'title':_('Second Study Course')}
1222                        )
1223            if self.context.__parent__.get('studycourse_1', None) is not None:
1224                return (
1225                        {'href':self.url(self.context.student) + '/studycourse_1',
1226                        'title':_('First Study Course')},
1227                        )
1228        return
1229
[7819]1230class StudyCourseManageFormPage(KofaEditFormPage):
[6649]1231    """ Page to edit the student study course data
1232    """
1233    grok.context(IStudentStudyCourse)
[6775]1234    grok.name('manage')
[7136]1235    grok.require('waeup.manageStudent')
[6775]1236    grok.template('studycoursemanagepage')
[7723]1237    label = _('Manage study course')
[6649]1238    pnav = 4
[7723]1239    taboneactions = [_('Save'),_('Cancel')]
1240    tabtwoactions = [_('Remove selected levels'),_('Cancel')]
1241    tabthreeactions = [_('Add study level')]
[6649]1242
[8972]1243    @property
1244    def form_fields(self):
1245        if self.context.is_postgrad:
1246            form_fields = grok.AutoFields(IStudentStudyCourse).omit(
[9723]1247                'previous_verdict')
[8972]1248        else:
1249            form_fields = grok.AutoFields(IStudentStudyCourse)
1250        return form_fields
1251
[6775]1252    def update(self):
[15163]1253        if not self.context.is_current \
1254            or self.context.student.studycourse_locked:
[9139]1255            emit_lock_message(self)
1256            return
[6775]1257        super(StudyCourseManageFormPage, self).update()
[7490]1258        return
[6775]1259
[7723]1260    @action(_('Save'), style='primary')
[6761]1261    def save(self, **data):
[8099]1262        try:
1263            msave(self, **data)
1264        except ConstraintNotSatisfied:
1265            # The selected level might not exist in certificate
[11254]1266            self.flash(_('Current level not available for certificate.'),
1267                       type="warning")
[8099]1268            return
[8081]1269        notify(grok.ObjectModifiedEvent(self.context.__parent__))
[6761]1270        return
1271
[6775]1272    @property
[10266]1273    def level_dicts(self):
[6775]1274        studylevelsource = StudyLevelSource().factory
1275        for code in studylevelsource.getValues(self.context):
1276            title = studylevelsource.getTitle(self.context, code)
1277            yield(dict(code=code, title=title))
1278
[9437]1279    @property
[10266]1280    def session_dicts(self):
[9437]1281        yield(dict(code='', title='--'))
1282        for item in academic_sessions():
1283            code = item[1]
1284            title = item[0]
1285            yield(dict(code=code, title=title))
1286
[11254]1287    @action(_('Add study level'), style='primary')
[6774]1288    def addStudyLevel(self, **data):
[6775]1289        level_code = self.request.form.get('addlevel', None)
[9437]1290        level_session = self.request.form.get('level_session', None)
[15203]1291        if not level_session and not level_code == '0':
[11254]1292            self.flash(_('You must select a session for the level.'),
1293                       type="warning")
1294            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[9437]1295            return
[15203]1296        if level_session and level_code == '0':
1297            self.flash(_('Level zero must not be assigned a session.'),
1298                       type="warning")
1299            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1300            return
[8323]1301        studylevel = createObject(u'waeup.StudentStudyLevel')
[6775]1302        studylevel.level = int(level_code)
[15203]1303        if level_code != '0':
1304            studylevel.level_session = int(level_session)
[6775]1305        try:
[6782]1306            self.context.addStudentStudyLevel(
1307                self.context.certificate,studylevel)
[7723]1308            self.flash(_('Study level has been added.'))
[6775]1309        except KeyError:
[11254]1310            self.flash(_('This level exists.'), type="warning")
1311        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6774]1312        return
1313
[7723]1314    @jsaction(_('Remove selected levels'))
[6775]1315    def delStudyLevels(self, **data):
1316        form = self.request.form
[9701]1317        if 'val_id' in form:
[6775]1318            child_id = form['val_id']
1319        else:
[11254]1320            self.flash(_('No study level selected.'), type="warning")
1321            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6775]1322            return
1323        if not isinstance(child_id, list):
1324            child_id = [child_id]
1325        deleted = []
1326        for id in child_id:
[7723]1327            del self.context[id]
1328            deleted.append(id)
[6775]1329        if len(deleted):
[7723]1330            self.flash(_('Successfully removed: ${a}',
1331                mapping = {'a':', '.join(deleted)}))
[9332]1332            self.context.writeLogMessage(
1333                self,'removed: %s' % ', '.join(deleted))
[11254]1334        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6775]1335        return
[6774]1336
[10459]1337class StudentTranscriptRequestPage(KofaPage):
[13055]1338    """ Page to request transcript by student
[10458]1339    """
1340    grok.context(IStudent)
1341    grok.name('request_transcript')
1342    grok.require('waeup.handleStudent')
[10459]1343    grok.template('transcriptrequest')
[10458]1344    label = _('Request transcript')
1345    ac_prefix = 'TSC'
1346    notice = ''
1347    pnav = 4
[16120]1348    buttonname = _('Request now')
[10458]1349    with_ac = True
1350
1351    def update(self, SUBMIT=None):
[10459]1352        super(StudentTranscriptRequestPage, self).update()
[10458]1353        if not self.context.state == GRADUATED:
[11254]1354            self.flash(_("Wrong state"), type="danger")
[10458]1355            self.redirect(self.url(self.context))
1356            return
1357        if self.with_ac:
1358            self.ac_series = self.request.form.get('ac_series', None)
1359            self.ac_number = self.request.form.get('ac_number', None)
[15163]1360        if getattr(
1361            self.context['studycourse'], 'transcript_comment', None) is not None:
1362            self.correspondence = self.context[
1363                'studycourse'].transcript_comment.replace(
1364                    '\n', '<br>')
[10458]1365        else:
1366            self.correspondence = ''
1367        if SUBMIT is None:
1368            return
1369        if self.with_ac:
1370            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1371            code = get_access_code(pin)
1372            if not code:
[11254]1373                self.flash(_('Activation code is invalid.'), type="warning")
[10458]1374                return
1375            if code.state == USED:
[11254]1376                self.flash(_('Activation code has already been used.'),
1377                           type="warning")
[10458]1378                return
1379            # Mark pin as used (this also fires a pin related transition)
[13089]1380            # and fire transition request_transcript
[10458]1381            comment = _(u"invalidated")
1382            # Here we know that the ac is in state initialized so we do not
1383            # expect an exception, but the owner might be different
1384            if not invalidate_accesscode(pin, comment, self.context.student_id):
[11254]1385                self.flash(_('You are not the owner of this access code.'),
1386                           type="warning")
[10458]1387                return
1388            self.context.clr_code = pin
1389        IWorkflowInfo(self.context).fireTransition('request_transcript')
1390        comment = self.request.form.get('comment', '').replace('\r', '')
1391        address = self.request.form.get('address', '').replace('\r', '')
1392        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1393        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
[15163]1394        old_transcript_comment = getattr(
1395            self.context['studycourse'], 'transcript_comment', None)
[10458]1396        if old_transcript_comment == None:
1397            old_transcript_comment = ''
[15163]1398        self.context['studycourse'].transcript_comment = '''On %s %s wrote:
[10458]1399
1400%s
1401
1402Dispatch Address:
1403%s
1404
1405%s''' % (today, self.request.principal.id, comment, address,
1406         old_transcript_comment)
1407        self.context.writeLogMessage(
1408            self, 'comment: %s' % comment.replace('\n', '<br>'))
1409        self.flash(_('Transcript processing has been started.'))
1410        self.redirect(self.url(self.context))
1411        return
1412
[16120]1413class TOStudentTranscriptRequestPage(StudentTranscriptRequestPage):
1414    """ Page to request transcript by student
1415    """
1416    grok.context(IStudent)
1417    grok.name('request_transcript_for_student')
1418    grok.require('waeup.processTranscript')
1419    grok.template('transcriptrequest')
1420    label = _('Request transcript for student')
1421    with_ac = False
1422
[15163]1423class StudentTranscriptSignView(UtilityView, grok.View):
1424    """ View to sign transcript
1425    """
1426    grok.context(IStudentStudyCourse)
1427    grok.name('sign_transcript')
1428    grok.require('waeup.signTranscript')
1429
1430    def update(self, SUBMIT=None):
1431        if self.context.student.state != TRANSVAL:
1432            self.flash(_('Student is in wrong state.'), type="warning")
1433            self.redirect(self.url(self.context))
1434            return
1435        prev_transcript_signees = getattr(
1436            self.context, 'transcript_signees', None)
1437        if prev_transcript_signees \
1438            and '(%s)' % self.request.principal.id in prev_transcript_signees:
1439            self.flash(_('You have already signed this transcript.'),
1440                type="warning")
1441            self.redirect(self.url(self.context) + '/transcript')
1442            return
1443        self.flash(_('Transcript signed.'))
1444        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1445        self.context.student.__parent__.logger.info(
1446            '%s - %s - Transcript signed'
1447            % (ob_class, self.context.student.student_id))
1448        self.context.student.history.addMessage('Transcript signed')
1449        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1450        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1451        if prev_transcript_signees == None:
1452            prev_transcript_signees = ''
1453        self.context.transcript_signees = (
1454            u"Electronically signed by %s (%s) on %s\n%s"
1455            % (self.request.principal.title, self.request.principal.id, today,
1456            prev_transcript_signees))
1457        self.redirect(self.url(self.context) + '/transcript')
1458        return
1459
1460    def render(self):
1461        return
1462
[15174]1463class StudentTranscriptValidateFormPage(KofaEditFormPage):
1464    """ Page to validate transcript
1465    """
1466    grok.context(IStudentStudyCourse)
1467    grok.name('validate_transcript')
1468    grok.require('waeup.processTranscript')
1469    grok.template('transcriptprocess')
1470    label = _('Validate transcript')
[16120]1471    buttonname1 = _('Save comment')
1472    buttonname2 = _('Save comment and validate transcript')
[15174]1473    pnav = 4
1474
[15333]1475    @property
1476    def remarks(self):
1477        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1478        levelremarks = ''
1479        studylevelsource = StudyLevelSource().factory
1480        for studylevel in self.context.values():
1481            leveltitle = studylevelsource.getTitle(
1482                self.context, studylevel.level)
1483            url = self.url(self.context) + '/%s/remark' % studylevel.level
1484            button_title = translate(
1485                _('Edit'), 'waeup.kofa', target_language=portal_language)
1486            levelremarks += (
1487                '<tr>'
1488                '<td>%s:</td>'
1489                '<td>%s</td> '
1490                '<td><a class="btn btn-primary btn-xs" href="%s">%s</a></td>'
1491                '</tr>'
1492                ) % (
1493                leveltitle, studylevel.transcript_remark, url, button_title)
1494        return levelremarks
1495
[16120]1496    def update(self, SUBMIT=None, SAVE=None):
[15174]1497        super(StudentTranscriptValidateFormPage, self).update()
1498        if self.context.student.state != TRANSREQ:
1499            self.flash(_('Student is in wrong state.'), type="warning")
1500            self.redirect(self.url(self.context))
1501            return
1502        if getattr(self.context, 'transcript_comment', None) is not None:
1503            self.correspondence = self.context.transcript_comment.replace(
1504                '\n', '<br>')
1505        else:
1506            self.correspondence = ''
1507        if getattr(self.context, 'transcript_signees', None) is not None:
1508            self.signees = self.context.transcript_signees.replace(
1509                '\n', '<br><br>')
1510        else:
1511            self.signees = ''
[16120]1512        if SUBMIT is None and SAVE is None:
[15174]1513            return
[16120]1514        if SAVE or SUBMIT:
1515            # Save comment and append old comment
1516            comment = self.request.form.get('comment', '').replace('\r', '')
1517            tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1518            today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1519            old_transcript_comment = getattr(
1520                self.context, 'transcript_comment', None)
1521            if old_transcript_comment == None:
1522                old_transcript_comment = ''
1523            self.context.transcript_comment = '''On %s %s wrote:
[15174]1524
1525%s
1526
[16120]1527%s''' % (today, self.request.principal.id, comment, old_transcript_comment)
1528            self.context.writeLogMessage(
1529                self, 'comment: %s' % comment.replace('\n', '<br>'))
1530        if SUBMIT:
1531            # Fire transition
1532            IWorkflowInfo(self.context.student).fireTransition('validate_transcript')
1533            self.flash(_('Transcript validated.'))
[15174]1534        self.redirect(self.url(self.context) + '/transcript')
1535        return
1536
[15163]1537class StudentTranscriptReleaseFormPage(KofaEditFormPage):
1538    """ Page to release transcript
1539    """
1540    grok.context(IStudentStudyCourse)
1541    grok.name('release_transcript')
1542    grok.require('waeup.processTranscript')
[15174]1543    grok.template('transcriptprocess')
[15163]1544    label = _('Release transcript')
[16120]1545    buttonname1 = None
1546    buttonname2 = _('Save comment and release transcript')
[10458]1547    pnav = 4
1548
[15333]1549    @property
1550    def remarks(self):
1551        levelremarks = ''
1552        studylevelsource = StudyLevelSource().factory
1553        for studylevel in self.context.values():
1554            leveltitle = studylevelsource.getTitle(
1555                self.context, studylevel.level)
1556            levelremarks += "%s: %s <br><br>" % (
1557                leveltitle, studylevel.transcript_remark)
1558        return levelremarks
1559
[10459]1560    def update(self, SUBMIT=None):
[15163]1561        super(StudentTranscriptReleaseFormPage, self).update()
1562        if self.context.student.state != TRANSVAL:
[11254]1563            self.flash(_('Student is in wrong state.'), type="warning")
[10458]1564            self.redirect(self.url(self.context))
[10459]1565            return
[15163]1566        if getattr(self.context, 'transcript_comment', None) is not None:
[10459]1567            self.correspondence = self.context.transcript_comment.replace(
1568                '\n', '<br>')
1569        else:
1570            self.correspondence = ''
[15163]1571        if getattr(self.context, 'transcript_signees', None) is not None:
1572            self.signees = self.context.transcript_signees.replace(
1573                '\n', '<br><br>')
1574        else:
1575            self.signees = ''
[10459]1576        if SUBMIT is None:
1577            return
[15163]1578        # Fire transition
1579        IWorkflowInfo(self.context.student).fireTransition('release_transcript')
1580        self.flash(_('Transcript released and final transcript file saved.'))
[10459]1581        comment = self.request.form.get('comment', '').replace('\r', '')
1582        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1583        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
[15163]1584        old_transcript_comment = getattr(
1585            self.context, 'transcript_comment', None)
[10459]1586        if old_transcript_comment == None:
1587            old_transcript_comment = ''
1588        self.context.transcript_comment = '''On %s %s wrote:
[10458]1589
[10459]1590%s
[10458]1591
[10459]1592%s''' % (today, self.request.principal.id, comment,
1593         old_transcript_comment)
1594        self.context.writeLogMessage(
1595            self, 'comment: %s' % comment.replace('\n', '<br>'))
[15163]1596        # Produce transcript file
1597        self.redirect(self.url(self.context) + '/transcript.pdf')
[10458]1598        return
1599
[10178]1600class StudyCourseTranscriptPage(KofaDisplayFormPage):
1601    """ Page to display the student's transcript.
1602    """
[15163]1603    grok.context(IStudentStudyCourse)
[10178]1604    grok.name('transcript')
[10278]1605    grok.require('waeup.viewTranscript')
[10178]1606    grok.template('transcript')
1607    pnav = 4
1608
[16046]1609    def format_float(self, value, prec):
1610        format_float = getUtility(IKofaUtils).format_float
1611        return format_float(value, prec)
1612
[10178]1613    def update(self):
[15163]1614        final_slip = getUtility(IExtFileStore).getFileByContext(
1615            self.context.student, attr='final_transcript')
1616        if not self.context.student.transcript_enabled or final_slip:
1617            self.flash(_('Forbidden!'), type="warning")
[10266]1618            self.redirect(self.url(self.context))
1619            return
[17497]1620        self.tdata = self.context.getTranscriptData()
1621        #if not self.tdata[1]:
1622        #    self.flash(_('No results yet!'), type="warning")
1623        #    self.redirect(self.url(self.context))
1624        #    return
[10178]1625        super(StudyCourseTranscriptPage, self).update()
1626        self.semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
[10266]1627        self.level_dict = level_dict(self.context)
[15203]1628        self.session_dict = dict([(None, 'None'),] +
[10178]1629            [(item[1], item[0]) for item in academic_sessions()])
1630        self.studymode_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
1631        return
1632
1633    @property
1634    def label(self):
1635        # Here we know that the cookie has been set
1636        return _('${a}: Transcript Data', mapping = {
1637            'a':self.context.student.display_fullname})
1638
[13055]1639class ExportPDFTranscriptSlip(UtilityView, grok.View):
[10250]1640    """Deliver a PDF slip of the context.
1641    """
1642    grok.context(IStudentStudyCourse)
1643    grok.name('transcript.pdf')
[16170]1644    grok.require('waeup.downloadTranscript')
[10250]1645    prefix = 'form'
1646    omit_fields = (
[10688]1647        'department', 'faculty', 'current_mode', 'entry_session', 'certificate',
[16085]1648        'password', 'suspended', 'phone', 'email', 'parents_email',
[13711]1649        'adm_code', 'suspended_comment', 'current_level', 'flash_notice')
[10250]1650
1651    def update(self):
[15163]1652        final_slip = getUtility(IExtFileStore).getFileByContext(
1653            self.context.student, attr='final_transcript')
1654        if not self.context.student.transcript_enabled \
1655            or final_slip:
1656            self.flash(_('Forbidden!'), type="warning")
[10266]1657            self.redirect(self.url(self.context))
1658            return
[17497]1659        tdata = self.context.getTranscriptData()
1660        #if not tdata[1]:
1661        #    self.flash(_('No results yet!'), type="warning")
1662        #    self.redirect(self.url(self.context))
1663        #    return
[13055]1664        super(ExportPDFTranscriptSlip, self).update()
[10250]1665        self.semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
[10266]1666        self.level_dict = level_dict(self.context)
[15203]1667        self.session_dict = dict([(None, 'None'),] +
[10250]1668            [(item[1], item[0]) for item in academic_sessions()])
1669        self.studymode_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
1670        return
1671
1672    @property
1673    def label(self):
1674        # Here we know that the cookie has been set
1675        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1676        return translate(_('Academic Transcript'),
1677            'waeup.kofa', target_language=portal_language)
1678
[10262]1679    def _sigsInFooter(self):
[15163]1680        if getattr(
1681            self.context.student['studycourse'], 'transcript_signees', None):
1682            return ()
[10262]1683        return (_('CERTIFIED TRUE COPY'),)
1684
[10531]1685    def _signatures(self):
[15163]1686        return ()
[10531]1687
[15163]1688    def _digital_sigs(self):
1689        if getattr(
1690            self.context.student['studycourse'], 'transcript_signees', None):
1691            return self.context.student['studycourse'].transcript_signees
1692        return ()
1693
1694    def _save_file(self):
1695        if self.context.student.state == TRANSREL:
1696            return True
1697        return False
1698
[10250]1699    def render(self):
1700        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[10436]1701        Term = translate(_('Term'), 'waeup.kofa', target_language=portal_language)
[10250]1702        Code = translate(_('Code'), 'waeup.kofa', target_language=portal_language)
1703        Title = translate(_('Title'), 'waeup.kofa', target_language=portal_language)
1704        Cred = translate(_('Credits'), 'waeup.kofa', target_language=portal_language)
1705        Score = translate(_('Score'), 'waeup.kofa', target_language=portal_language)
1706        Grade = translate(_('Grade'), 'waeup.kofa', target_language=portal_language)
1707        studentview = StudentBasePDFFormPage(self.context.student,
1708            self.request, self.omit_fields)
1709        students_utils = getUtility(IStudentsUtils)
1710
1711        tableheader = [(Code,'code', 2.5),
1712                         (Title,'title', 7),
[10436]1713                         (Term, 'semester', 1.5),
[10250]1714                         (Cred, 'credits', 1.5),
[14133]1715                         (Score, 'total_score', 1.5),
[10250]1716                         (Grade, 'grade', 1.5),
1717                         ]
1718
[15163]1719        pdfstream = students_utils.renderPDFTranscript(
[10250]1720            self, 'transcript.pdf',
1721            self.context.student, studentview,
1722            omit_fields=self.omit_fields,
[10262]1723            tableheader=tableheader,
[10531]1724            signatures=self._signatures(),
[10262]1725            sigs_in_footer=self._sigsInFooter(),
[15163]1726            digital_sigs=self._digital_sigs(),
1727            save_file=self._save_file(),
[10250]1728            )
[15163]1729        if not pdfstream:
1730            self.redirect(self.url(self.context.student))
1731            return
1732        return pdfstream
[10250]1733
[9138]1734class StudentTransferFormPage(KofaAddFormPage):
1735    """Page to transfer the student.
1736    """
1737    grok.context(IStudent)
1738    grok.name('transfer')
1739    grok.require('waeup.manageStudent')
1740    label = _('Transfer student')
1741    form_fields = grok.AutoFields(IStudentStudyCourseTransfer).omit(
1742        'entry_mode', 'entry_session')
1743    pnav = 4
1744
1745    @jsaction(_('Transfer'))
1746    def transferStudent(self, **data):
1747        error = self.context.transfer(**data)
1748        if error == -1:
[11254]1749            self.flash(_('Current level does not match certificate levels.'),
1750                       type="warning")
[9138]1751        elif error == -2:
[11254]1752            self.flash(_('Former study course record incomplete.'),
1753                       type="warning")
[9138]1754        elif error == -3:
[11254]1755            self.flash(_('Maximum number of transfers exceeded.'),
1756                       type="warning")
[9138]1757        else:
1758            self.flash(_('Successfully transferred.'))
1759        return
1760
[10060]1761class RevertTransferFormPage(KofaEditFormPage):
1762    """View that reverts the previous transfer.
1763    """
1764    grok.context(IStudent)
1765    grok.name('revert_transfer')
1766    grok.require('waeup.manageStudent')
1767    grok.template('reverttransfer')
1768    label = _('Revert previous transfer')
1769
1770    def update(self):
1771        if not self.context.has_key('studycourse_1'):
[11254]1772            self.flash(_('No previous transfer.'), type="warning")
[10060]1773            self.redirect(self.url(self.context))
1774            return
1775        return
1776
1777    @jsaction(_('Revert now'))
1778    def transferStudent(self, **data):
1779        self.context.revert_transfer()
1780        self.flash(_('Previous transfer reverted.'))
1781        self.redirect(self.url(self.context, 'studycourse'))
1782        return
1783
[7819]1784class StudyLevelDisplayFormPage(KofaDisplayFormPage):
[6774]1785    """ Page to display student study levels
1786    """
1787    grok.context(IStudentStudyLevel)
1788    grok.name('index')
1789    grok.require('waeup.viewStudent')
[12873]1790    form_fields = grok.AutoFields(IStudentStudyLevel).omit('level')
[9161]1791    form_fields[
1792        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[6783]1793    grok.template('studylevelpage')
[6774]1794    pnav = 4
1795
[7310]1796    def update(self):
1797        super(StudyLevelDisplayFormPage, self).update()
[15213]1798        if self.context.level == 0:
1799            self.form_fields = self.form_fields.omit('gpa')
[7310]1800        return
1801
[6774]1802    @property
[8141]1803    def translated_values(self):
[8921]1804        return translated_values(self)
[8141]1805
1806    @property
[6774]1807    def label(self):
[7833]1808        # Here we know that the cookie has been set
1809        lang = self.request.cookies.get('kofa.language')
[7811]1810        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]1811            target_language=lang)
[15203]1812        return _('${a}: ${b}', mapping = {
[8736]1813            'a':self.context.student.display_fullname,
[7723]1814            'b':level_title})
[6774]1815
[13055]1816class ExportPDFCourseRegistrationSlip(UtilityView, grok.View):
[7028]1817    """Deliver a PDF slip of the context.
1818    """
1819    grok.context(IStudentStudyLevel)
[9452]1820    grok.name('course_registration_slip.pdf')
[7028]1821    grok.require('waeup.viewStudent')
[15405]1822    form_fields = grok.AutoFields(IStudentStudyLevel).omit(
1823        'level', 'gpa', 'transcript_remark')
[9683]1824    form_fields[
[12874]1825        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7028]1826    prefix = 'form'
[9702]1827    omit_fields = (
[10256]1828        'password', 'suspended', 'phone', 'date_of_birth',
[13711]1829        'adm_code', 'sex', 'suspended_comment', 'current_level',
1830        'flash_notice')
[7028]1831
1832    @property
[7723]1833    def title(self):
[7819]1834        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]1835        return translate(_('Level Data'), 'waeup.kofa',
[7723]1836            target_language=portal_language)
1837
1838    @property
[7028]1839    def label(self):
[7819]1840        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]1841        lang = self.request.cookies.get('kofa.language', portal_language)
1842        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]1843            target_language=lang)
[8141]1844        return translate(_('Course Registration Slip'),
[7811]1845            'waeup.kofa', target_language=portal_language) \
[7723]1846            + ' %s' % level_title
[7028]1847
[10439]1848    @property
1849    def tabletitle(self):
1850        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1851        tabletitle = []
1852        tabletitle.append(translate(_('1st Semester Courses'), 'waeup.kofa',
1853            target_language=portal_language))
1854        tabletitle.append(translate(_('2nd Semester Courses'), 'waeup.kofa',
1855            target_language=portal_language))
1856        tabletitle.append(translate(_('Level Courses'), 'waeup.kofa',
1857            target_language=portal_language))
1858        return tabletitle
1859
[15694]1860    def _signatures(self):
1861        return ()
1862
[15695]1863    def _sigsInFooter(self):
1864        return ()
1865
[7028]1866    def render(self):
[7819]1867        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]1868        Code = translate(_('Code'), 'waeup.kofa', target_language=portal_language)
1869        Title = translate(_('Title'), 'waeup.kofa', target_language=portal_language)
1870        Dept = translate(_('Dept.'), 'waeup.kofa', target_language=portal_language)
1871        Faculty = translate(_('Faculty'), 'waeup.kofa', target_language=portal_language)
1872        Cred = translate(_('Cred.'), 'waeup.kofa', target_language=portal_language)
[9906]1873        #Mand = translate(_('Requ.'), 'waeup.kofa', target_language=portal_language)
[7811]1874        Score = translate(_('Score'), 'waeup.kofa', target_language=portal_language)
[9810]1875        Grade = translate(_('Grade'), 'waeup.kofa', target_language=portal_language)
[9141]1876        studentview = StudentBasePDFFormPage(self.context.student,
[9375]1877            self.request, self.omit_fields)
[7150]1878        students_utils = getUtility(IStudentsUtils)
[10438]1879
1880        tabledata = []
1881        tableheader = []
[10439]1882        for i in range(1,7):
[10438]1883            tabledata.append(sorted(
1884                [value for value in self.context.values() if value.semester == i],
1885                key=lambda value: str(value.semester) + value.code))
1886            tableheader.append([(Code,'code', 2.5),
1887                             (Title,'title', 5),
1888                             (Dept,'dcode', 1.5), (Faculty,'fcode', 1.5),
1889                             (Cred, 'credits', 1.5),
1890                             #(Mand, 'mandatory', 1.5),
1891                             (Score, 'score', 1.5),
1892                             (Grade, 'grade', 1.5),
1893                             #('Auto', 'automatic', 1.5)
1894                             ])
[9906]1895        return students_utils.renderPDF(
1896            self, 'course_registration_slip.pdf',
1897            self.context.student, studentview,
[10438]1898            tableheader=tableheader,
1899            tabledata=tabledata,
[15694]1900            omit_fields=self.omit_fields,
1901            signatures=self._signatures(),
[15695]1902            sigs_in_footer=self._sigsInFooter(),
[9906]1903            )
[7028]1904
[7819]1905class StudyLevelManageFormPage(KofaEditFormPage):
[6792]1906    """ Page to edit the student study level data
1907    """
1908    grok.context(IStudentStudyLevel)
1909    grok.name('manage')
[7136]1910    grok.require('waeup.manageStudent')
[6792]1911    grok.template('studylevelmanagepage')
[9161]1912    form_fields = grok.AutoFields(IStudentStudyLevel).omit(
[12873]1913        'validation_date', 'validated_by', 'total_credits', 'gpa', 'level')
[6792]1914    pnav = 4
[7723]1915    taboneactions = [_('Save'),_('Cancel')]
1916    tabtwoactions = [_('Add course ticket'),
1917        _('Remove selected tickets'),_('Cancel')]
[11254]1918    placeholder = _('Enter valid course code')
[6792]1919
[9895]1920    def update(self, ADD=None, course=None):
[15163]1921        if not self.context.__parent__.is_current \
1922            or self.context.student.studycourse_locked:
[9139]1923            emit_lock_message(self)
1924            return
[6792]1925        super(StudyLevelManageFormPage, self).update()
[9895]1926        if ADD is not None:
1927            if not course:
[11254]1928                self.flash(_('No valid course code entered.'), type="warning")
1929                self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[9895]1930                return
1931            cat = queryUtility(ICatalog, name='courses_catalog')
1932            result = cat.searchResults(code=(course, course))
1933            if len(result) != 1:
[11254]1934                self.flash(_('Course not found.'), type="warning")
[9895]1935            else:
1936                course = list(result)[0]
1937                addCourseTicket(self, course)
[11254]1938            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6792]1939        return
1940
1941    @property
[8921]1942    def translated_values(self):
1943        return translated_values(self)
1944
1945    @property
[6792]1946    def label(self):
[7833]1947        # Here we know that the cookie has been set
1948        lang = self.request.cookies.get('kofa.language')
[7811]1949        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]1950            target_language=lang)
[15203]1951        return _('Manage ${a}',
[7723]1952            mapping = {'a':level_title})
[6792]1953
[7723]1954    @action(_('Save'), style='primary')
[6792]1955    def save(self, **data):
1956        msave(self, **data)
1957        return
1958
[7723]1959    @jsaction(_('Remove selected tickets'))
[6792]1960    def delCourseTicket(self, **data):
1961        form = self.request.form
[9701]1962        if 'val_id' in form:
[6792]1963            child_id = form['val_id']
1964        else:
[11254]1965            self.flash(_('No ticket selected.'), type="warning")
1966            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6792]1967            return
1968        if not isinstance(child_id, list):
1969            child_id = [child_id]
1970        deleted = []
1971        for id in child_id:
[7723]1972            del self.context[id]
1973            deleted.append(id)
[6792]1974        if len(deleted):
[7723]1975            self.flash(_('Successfully removed: ${a}',
1976                mapping = {'a':', '.join(deleted)}))
[9332]1977            self.context.writeLogMessage(
[16030]1978                self,'removed: %s' % (', '.join(deleted)))
[11254]1979        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6792]1980        return
1981
[15333]1982class StudyLevelRemarkFormPage(KofaEditFormPage):
1983    """ Page to edit the student study level transcript remark only
1984    """
1985    grok.context(IStudentStudyLevel)
1986    grok.name('remark')
1987    grok.require('waeup.processTranscript')
1988    grok.template('studylevelremarkpage')
1989    form_fields = grok.AutoFields(IStudentStudyLevel).omit('level')
1990    form_fields['level_session'].for_display = True
1991    form_fields['level_verdict'].for_display = True
1992    form_fields['validation_date'].for_display = True
1993    form_fields['validated_by'].for_display = True
1994
1995    def update(self, ADD=None, course=None):
1996        if self.context.student.studycourse_locked:
1997            emit_lock_message(self)
1998            return
1999        super(StudyLevelRemarkFormPage, self).update()
2000
2001    @property
2002    def label(self):
2003        lang = self.request.cookies.get('kofa.language')
2004        level_title = translate(self.context.level_title, 'waeup.kofa',
2005            target_language=lang)
[15334]2006        return _(
2007            'Edit transcript remark of level ${a}', mapping = {'a':level_title})
[15333]2008
2009    @property
2010    def translated_values(self):
2011        return translated_values(self)
2012
2013    @action(_('Save remark and go and back to transcript validation page'),
2014        style='primary')
2015    def save(self, **data):
2016        msave(self, **data)
[15334]2017        self.redirect(self.url(self.context.student)
2018            + '/studycourse/validate_transcript#tab4')
[15333]2019        return
2020
[13055]2021class ValidateCoursesView(UtilityView, grok.View):
[7334]2022    """ Validate course list by course adviser
2023    """
2024    grok.context(IStudentStudyLevel)
2025    grok.name('validate_courses')
2026    grok.require('waeup.validateStudent')
2027
2028    def update(self):
[9139]2029        if not self.context.__parent__.is_current:
2030            emit_lock_message(self)
2031            return
[15163]2032        if str(self.context.student.current_level) != self.context.__name__:
[13610]2033            self.flash(_('This is not the student\'s current level.'),
[11254]2034                       type="danger")
[8736]2035        elif self.context.student.state == REGISTERED:
2036            IWorkflowInfo(self.context.student).fireTransition(
[7642]2037                'validate_courses')
[7723]2038            self.flash(_('Course list has been validated.'))
[7334]2039        else:
[11254]2040            self.flash(_('Student is in the wrong state.'), type="warning")
[7334]2041        self.redirect(self.url(self.context))
2042        return
2043
2044    def render(self):
2045        return
2046
[13055]2047class RejectCoursesView(UtilityView, grok.View):
[7334]2048    """ Reject course list by course adviser
2049    """
2050    grok.context(IStudentStudyLevel)
2051    grok.name('reject_courses')
2052    grok.require('waeup.validateStudent')
2053
2054    def update(self):
[9139]2055        if not self.context.__parent__.is_current:
2056            emit_lock_message(self)
2057            return
[7334]2058        if str(self.context.__parent__.current_level) != self.context.__name__:
[13610]2059            self.flash(_('This is not the student\'s current level.'),
[11254]2060                       type="danger")
[7334]2061            self.redirect(self.url(self.context))
2062            return
[8736]2063        elif self.context.student.state == VALIDATED:
2064            IWorkflowInfo(self.context.student).fireTransition('reset8')
[7723]2065            message = _('Course list request has been annulled.')
[7334]2066            self.flash(message)
[8736]2067        elif self.context.student.state == REGISTERED:
2068            IWorkflowInfo(self.context.student).fireTransition('reset7')
[13610]2069            message = _('Course list has been unregistered.')
[7334]2070            self.flash(message)
2071        else:
[11254]2072            self.flash(_('Student is in the wrong state.'), type="warning")
[7334]2073            self.redirect(self.url(self.context))
2074            return
2075        args = {'subject':message}
[8736]2076        self.redirect(self.url(self.context.student) +
[7334]2077            '/contactstudent?%s' % urlencode(args))
2078        return
2079
2080    def render(self):
2081        return
2082
[13610]2083class UnregisterCoursesView(UtilityView, grok.View):
[14983]2084    """Unregister course list by student
[13610]2085    """
2086    grok.context(IStudentStudyLevel)
2087    grok.name('unregister_courses')
2088    grok.require('waeup.handleStudent')
2089
2090    def update(self):
2091        if not self.context.__parent__.is_current:
2092            emit_lock_message(self)
2093            return
[14247]2094        try:
2095            deadline = grok.getSite()['configuration'][
2096                str(self.context.level_session)].coursereg_deadline
2097        except (TypeError, KeyError):
2098            deadline = None
2099        if deadline and deadline < datetime.now(pytz.utc):
[13610]2100            self.flash(_(
2101                "Course registration has ended. "
2102                "Unregistration is disabled."), type="warning")
2103        elif str(self.context.__parent__.current_level) != self.context.__name__:
2104            self.flash(_('This is not your current level.'), type="danger")
2105        elif self.context.student.state == REGISTERED:
2106            IWorkflowInfo(self.context.student).fireTransition('reset7')
2107            message = _('Course list has been unregistered.')
2108            self.flash(message)
2109        else:
2110            self.flash(_('You are in the wrong state.'), type="warning")
2111        self.redirect(self.url(self.context))
2112        return
2113
2114    def render(self):
2115        return
2116
[7819]2117class CourseTicketAddFormPage(KofaAddFormPage):
[6808]2118    """Add a course ticket.
[6795]2119    """
2120    grok.context(IStudentStudyLevel)
2121    grok.name('add')
[7136]2122    grok.require('waeup.manageStudent')
[7723]2123    label = _('Add course ticket')
[9420]2124    form_fields = grok.AutoFields(ICourseTicketAdd)
[6795]2125    pnav = 4
2126
[9139]2127    def update(self):
[15163]2128        if not self.context.__parent__.is_current \
2129            or self.context.student.studycourse_locked:
[9139]2130            emit_lock_message(self)
2131            return
2132        super(CourseTicketAddFormPage, self).update()
2133        return
2134
[11254]2135    @action(_('Add course ticket'), style='primary')
[6795]2136    def addCourseTicket(self, **data):
2137        course = data['course']
[9895]2138        success = addCourseTicket(self, course)
2139        if success:
[11254]2140            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6795]2141        return
2142
[7834]2143    @action(_('Cancel'), validator=NullValidator)
[6795]2144    def cancel(self, **data):
2145        self.redirect(self.url(self.context))
2146
[7819]2147class CourseTicketDisplayFormPage(KofaDisplayFormPage):
[6796]2148    """ Page to display course tickets
2149    """
2150    grok.context(ICourseTicket)
2151    grok.name('index')
2152    grok.require('waeup.viewStudent')
[15203]2153    form_fields = grok.AutoFields(ICourseTicket).omit('course_category',
2154        'ticket_session')
[9684]2155    grok.template('courseticketpage')
[6796]2156    pnav = 4
2157
2158    @property
2159    def label(self):
[7723]2160        return _('${a}: Course Ticket ${b}', mapping = {
[8736]2161            'a':self.context.student.display_fullname,
[7723]2162            'b':self.context.code})
[6796]2163
[7819]2164class CourseTicketManageFormPage(KofaEditFormPage):
[6796]2165    """ Page to manage course tickets
2166    """
2167    grok.context(ICourseTicket)
2168    grok.name('manage')
[7136]2169    grok.require('waeup.manageStudent')
[14642]2170    form_fields = grok.AutoFields(ICourseTicket).omit('course_category')
[9420]2171    form_fields['title'].for_display = True
2172    form_fields['fcode'].for_display = True
2173    form_fields['dcode'].for_display = True
2174    form_fields['semester'].for_display = True
2175    form_fields['passmark'].for_display = True
2176    form_fields['credits'].for_display = True
[9698]2177    form_fields['mandatory'].for_display = False
[9420]2178    form_fields['automatic'].for_display = True
[9422]2179    form_fields['carry_over'].for_display = True
[15203]2180    form_fields['ticket_session'].for_display = True
[6796]2181    pnav = 4
[9697]2182    grok.template('courseticketmanagepage')
[6796]2183
[15163]2184    def update(self):
2185        if not self.context.__parent__.__parent__.is_current \
2186            or self.context.student.studycourse_locked:
2187            emit_lock_message(self)
2188            return
2189        super(CourseTicketManageFormPage, self).update()
2190        return
2191
[6796]2192    @property
2193    def label(self):
[7723]2194        return _('Manage course ticket ${a}', mapping = {'a':self.context.code})
[6796]2195
[7459]2196    @action('Save', style='primary')
[6796]2197    def save(self, **data):
2198        msave(self, **data)
2199        return
2200
[7819]2201class PaymentsManageFormPage(KofaEditFormPage):
[6869]2202    """ Page to manage the student payments
[7642]2203
2204    This manage form page is for both students and students officers.
[6869]2205    """
2206    grok.context(IStudentPaymentsContainer)
[6940]2207    grok.name('index')
[10080]2208    grok.require('waeup.viewStudent')
[6869]2209    form_fields = grok.AutoFields(IStudentPaymentsContainer)
2210    grok.template('paymentsmanagepage')
2211    pnav = 4
2212
[10080]2213    @property
2214    def manage_payments_allowed(self):
2215        return checkPermission('waeup.payStudent', self.context)
2216
[6940]2217    def unremovable(self, ticket):
[7251]2218        usertype = getattr(self.request.principal, 'user_type', None)
2219        if not usertype:
2220            return False
[10080]2221        if not self.manage_payments_allowed:
2222            return True
[7251]2223        return (self.request.principal.user_type == 'student' and ticket.r_code)
[6940]2224
[6869]2225    @property
2226    def label(self):
[7723]2227        return _('${a}: Payments',
2228            mapping = {'a':self.context.__parent__.display_fullname})
[6869]2229
[7723]2230    @jsaction(_('Remove selected tickets'))
[6869]2231    def delPaymentTicket(self, **data):
2232        form = self.request.form
[9701]2233        if 'val_id' in form:
[6869]2234            child_id = form['val_id']
2235        else:
[11254]2236            self.flash(_('No payment selected.'), type="warning")
[6940]2237            self.redirect(self.url(self.context))
[6869]2238            return
2239        if not isinstance(child_id, list):
2240            child_id = [child_id]
2241        deleted = []
2242        for id in child_id:
[6992]2243            # Students are not allowed to remove used payment tickets
[10001]2244            ticket = self.context.get(id, None)
2245            if ticket is not None and not self.unremovable(ticket):
[7723]2246                del self.context[id]
2247                deleted.append(id)
[6869]2248        if len(deleted):
[7723]2249            self.flash(_('Successfully removed: ${a}',
2250                mapping = {'a': ', '.join(deleted)}))
[8735]2251            self.context.writeLogMessage(
[8885]2252                self,'removed: %s' % ', '.join(deleted))
[6940]2253        self.redirect(self.url(self.context))
[6869]2254        return
2255
[7819]2256class OnlinePaymentAddFormPage(KofaAddFormPage):
[6869]2257    """ Page to add an online payment ticket
2258    """
2259    grok.context(IStudentPaymentsContainer)
2260    grok.name('addop')
[9729]2261    grok.template('onlinepaymentaddform')
[7181]2262    grok.require('waeup.payStudent')
[15664]2263    form_fields = grok.AutoFields(IStudentOnlinePayment).select('p_combi')
[7723]2264    label = _('Add online payment')
[6869]2265    pnav = 4
[7642]2266
[9729]2267    @property
2268    def selectable_categories(self):
[15432]2269        student = self.context.__parent__
2270        categories = getUtility(
2271            IKofaUtils).selectable_payment_categories(student)
[15104]2272        return sorted(categories.items(), key=lambda value: value[1])
[9729]2273
[16431]2274    @property
2275    def selectable_payment_options(self):
2276        student = self.context.__parent__
2277        options = getUtility(
2278            IKofaUtils).selectable_payment_options(student)
2279        return sorted(options.items(), key=lambda value: value[1])
2280
[7723]2281    @action(_('Create ticket'), style='primary')
[6869]2282    def createTicket(self, **data):
[15664]2283        form = self.request.form
2284        p_category = form.get('form.p_category', None)
[16431]2285        p_option = form.get('form.p_option', None)
[15685]2286        p_combi = form.get('form.p_combi', [])
[15664]2287        if isinstance(form.get('form.p_combi', None), unicode):
2288            p_combi = [p_combi,]
[7024]2289        student = self.context.__parent__
[17176]2290        students_utils = getUtility(IStudentsUtils)
[12470]2291        # The hostel_application payment category is temporarily used
2292        # by Uniben.
[17182]2293        accommodation_session = grok.getSite()['hostels'].accommodation_session
2294        if p_category in ('bed_allocation', 'hostel_application') \
2295            and accommodation_session - student[
2296                'studycourse'].current_session > students_utils.ACCOMMODATION_SPAN:
[7024]2297                self.flash(
[17176]2298                    _('Your current session does not allow ' + \
2299                    'to book accommodation.'), type="danger")
[7024]2300                return
[9423]2301        if 'maintenance' in p_category:
[17182]2302            if str(accommodation_session) not in student['accommodation']:
[11254]2303                self.flash(_('You have not yet booked accommodation.'),
2304                           type="warning")
[9423]2305                return
[9148]2306        error, payment = students_utils.setPaymentDetails(
[15664]2307            p_category, student, None, None, p_combi)
[8595]2308        if error is not None:
[11254]2309            self.flash(error, type="danger")
[8081]2310            return
[13574]2311        if p_category == 'transfer':
[15664]2312            payment.p_item = form['new_programme']
[16431]2313        if p_option:
2314            payment.p_option = p_option
[6869]2315        self.context[payment.p_id] = payment
[7723]2316        self.flash(_('Payment ticket created.'))
[11676]2317        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
[16266]2318        self.redirect(self.url(payment))
[6869]2319        return
2320
[9383]2321    @action(_('Cancel'), validator=NullValidator)
2322    def cancel(self, **data):
2323        self.redirect(self.url(self.context))
2324
[9862]2325class PreviousPaymentAddFormPage(KofaAddFormPage):
[13040]2326    """ Page to add an online payment ticket for previous sessions.
[9148]2327    """
2328    grok.context(IStudentPaymentsContainer)
2329    grok.name('addpp')
[16431]2330    grok.template('previouspaymentaddform')
[9148]2331    grok.require('waeup.payStudent')
[9864]2332    form_fields = grok.AutoFields(IStudentPreviousPayment)
[9148]2333    label = _('Add previous session online payment')
2334    pnav = 4
2335
[9517]2336    def update(self):
[9521]2337        if self.context.student.before_payment:
[11254]2338            self.flash(_("No previous payment to be made."), type="warning")
[9517]2339            self.redirect(self.url(self.context))
2340        super(PreviousPaymentAddFormPage, self).update()
2341        return
2342
[16431]2343    @property
2344    def selectable_payment_options(self):
2345        student = self.context.__parent__
2346        options = getUtility(
2347            IKofaUtils).selectable_payment_options(student)
2348        return sorted(options.items(), key=lambda value: value[1])
2349
[9862]2350    @action(_('Create ticket'), style='primary')
2351    def createTicket(self, **data):
2352        p_category = data['p_category']
[17245]2353        form = self.request.form
2354        p_option = form.get('form.p_option', None)
[9862]2355        previous_session = data.get('p_session', None)
2356        previous_level = data.get('p_level', None)
2357        student = self.context.__parent__
2358        students_utils = getUtility(IStudentsUtils)
2359        error, payment = students_utils.setPaymentDetails(
[15664]2360            p_category, student, previous_session, previous_level, None)
[9862]2361        if error is not None:
[11254]2362            self.flash(error, type="danger")
[9862]2363            return
[16431]2364        if p_option:
2365            payment.p_option = p_option
[9862]2366        self.context[payment.p_id] = payment
2367        self.flash(_('Payment ticket created.'))
[14685]2368        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
[16266]2369        self.redirect(self.url(payment))
[9862]2370        return
2371
2372    @action(_('Cancel'), validator=NullValidator)
2373    def cancel(self, **data):
2374        self.redirect(self.url(self.context))
2375
[9864]2376class BalancePaymentAddFormPage(KofaAddFormPage):
[13040]2377    """ Page to add an online payment which can balance s previous session
2378    payment.
[9864]2379    """
2380    grok.context(IStudentPaymentsContainer)
2381    grok.name('addbp')
[16431]2382    grok.template('previouspaymentaddform')
[9938]2383    grok.require('waeup.manageStudent')
[9864]2384    form_fields = grok.AutoFields(IStudentBalancePayment)
2385    label = _('Add balance')
2386    pnav = 4
2387
[16431]2388    @property
2389    def selectable_payment_options(self):
2390        student = self.context.__parent__
2391        options = getUtility(
2392            IKofaUtils).selectable_payment_options(student)
2393        return sorted(options.items(), key=lambda value: value[1])
2394
[9864]2395    @action(_('Create ticket'), style='primary')
2396    def createTicket(self, **data):
[9868]2397        p_category = data['p_category']
[17245]2398        form = self.request.form
2399        p_option = form.get('form.p_option', None)
[9864]2400        balance_session = data.get('balance_session', None)
2401        balance_level = data.get('balance_level', None)
2402        balance_amount = data.get('balance_amount', None)
2403        student = self.context.__parent__
2404        students_utils = getUtility(IStudentsUtils)
2405        error, payment = students_utils.setBalanceDetails(
[9868]2406            p_category, student, balance_session,
[9864]2407            balance_level, balance_amount)
2408        if error is not None:
[11254]2409            self.flash(error, type="danger")
[9864]2410            return
[16431]2411        if p_option:
2412            payment.p_option = p_option
[9864]2413        self.context[payment.p_id] = payment
2414        self.flash(_('Payment ticket created.'))
[11676]2415        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
[16266]2416        self.redirect(self.url(payment))
[9864]2417        return
2418
2419    @action(_('Cancel'), validator=NullValidator)
2420    def cancel(self, **data):
2421        self.redirect(self.url(self.context))
2422
[7819]2423class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[6869]2424    """ Page to view an online payment ticket
2425    """
[6877]2426    grok.context(IStudentOnlinePayment)
[6869]2427    grok.name('index')
2428    grok.require('waeup.viewStudent')
[15685]2429    form_fields = grok.AutoFields(IStudentOnlinePayment).omit(
2430        'p_item', 'p_combi')
[8170]2431    form_fields[
2432        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2433    form_fields[
2434        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[6869]2435    pnav = 4
2436
2437    @property
2438    def label(self):
[7723]2439        return _('${a}: Online Payment Ticket ${b}', mapping = {
[8736]2440            'a':self.context.student.display_fullname,
[7723]2441            'b':self.context.p_id})
[6869]2442
[13055]2443class OnlinePaymentApproveView(UtilityView, grok.View):
[6930]2444    """ Callback view
2445    """
2446    grok.context(IStudentOnlinePayment)
[8420]2447    grok.name('approve')
2448    grok.require('waeup.managePortal')
[6930]2449
2450    def update(self):
[11580]2451        flashtype, msg, log = self.context.approveStudentPayment()
[8428]2452        if log is not None:
[9770]2453            # Add log message to students.log
[8735]2454            self.context.writeLogMessage(self,log)
[9770]2455            # Add log message to payments.log
2456            self.context.logger.info(
[9779]2457                '%s,%s,%s,%s,%s,,,,,,' % (
[9770]2458                self.context.student.student_id,
2459                self.context.p_id, self.context.p_category,
2460                self.context.amount_auth, self.context.r_code))
[11580]2461        self.flash(msg, type=flashtype)
[6940]2462        return
[6930]2463
2464    def render(self):
[6940]2465        self.redirect(self.url(self.context, '@@index'))
[6930]2466        return
2467
[13055]2468class OnlinePaymentFakeApproveView(OnlinePaymentApproveView):
[8420]2469    """ Approval view for students.
2470
2471    This view is used for browser tests only and
[15941]2472    must be neutralized on custom pages!
[8420]2473    """
2474    grok.name('fake_approve')
2475    grok.require('waeup.payStudent')
2476
[13055]2477class ExportPDFPaymentSlip(UtilityView, grok.View):
[7019]2478    """Deliver a PDF slip of the context.
2479    """
2480    grok.context(IStudentOnlinePayment)
[8262]2481    grok.name('payment_slip.pdf')
[7019]2482    grok.require('waeup.viewStudent')
[15685]2483    form_fields = grok.AutoFields(IStudentOnlinePayment).omit(
2484        'p_item', 'p_combi')
[8173]2485    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2486    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7019]2487    prefix = 'form'
[8258]2488    note = None
[9702]2489    omit_fields = (
[10256]2490        'password', 'suspended', 'phone', 'date_of_birth',
[13711]2491        'adm_code', 'sex', 'suspended_comment', 'current_level',
2492        'flash_notice')
[7019]2493
2494    @property
[8262]2495    def title(self):
2496        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2497        return translate(_('Payment Data'), 'waeup.kofa',
2498            target_language=portal_language)
2499
2500    @property
[7019]2501    def label(self):
[8262]2502        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2503        return translate(_('Online Payment Slip'),
2504            'waeup.kofa', target_language=portal_language) \
2505            + ' %s' % self.context.p_id
[7019]2506
2507    def render(self):
[8262]2508        #if self.context.p_state != 'paid':
2509        #    self.flash('Ticket not yet paid.')
2510        #    self.redirect(self.url(self.context))
2511        #    return
[9141]2512        studentview = StudentBasePDFFormPage(self.context.student,
[9375]2513            self.request, self.omit_fields)
[7150]2514        students_utils = getUtility(IStudentsUtils)
[8262]2515        return students_utils.renderPDF(self, 'payment_slip.pdf',
[10250]2516            self.context.student, studentview, note=self.note,
2517            omit_fields=self.omit_fields)
[7019]2518
[15972]2519class AccommodationDisplayFormPage(KofaDisplayFormPage):
2520    """ Page to view bed tickets.
2521    This manage form page is for both students and students officers.
2522    """
2523    grok.context(IStudentAccommodation)
2524    grok.name('index')
2525    grok.require('waeup.viewStudent')
2526    form_fields = grok.AutoFields(IStudentAccommodation)
2527    grok.template('accommodationpage')
2528    pnav = 4
2529    with_hostel_selection = True
[6992]2530
[15972]2531    @property
2532    def label(self):
2533        return _('${a}: Accommodation',
2534            mapping = {'a':self.context.__parent__.display_fullname})
2535
2536    @property
2537    def desired_hostel(self):
2538        if self.context.desired_hostel == 'no':
2539            return _('No favoured hostel')
2540        if self.context.desired_hostel:
2541            hostel = grok.getSite()['hostels'].get(self.context.desired_hostel)
2542            if hostel is not None:
2543                return hostel.hostel_name
2544        return
2545
2546    def update(self):
2547        if checkPermission('waeup.handleAccommodation', self.context):
2548            self.redirect(self.url(self.context, 'manage'))
2549
[7819]2550class AccommodationManageFormPage(KofaEditFormPage):
[7009]2551    """ Page to manage bed tickets.
[7642]2552
2553    This manage form page is for both students and students officers.
[6635]2554    """
2555    grok.context(IStudentAccommodation)
[15972]2556    grok.name('manage')
[7181]2557    grok.require('waeup.handleAccommodation')
[6635]2558    form_fields = grok.AutoFields(IStudentAccommodation)
[6992]2559    grok.template('accommodationmanagepage')
[6642]2560    pnav = 4
[13457]2561    with_hostel_selection = True
[6635]2562
2563    @property
[15210]2564    def booking_allowed(self):
[13457]2565        students_utils = getUtility(IStudentsUtils)
2566        acc_details  = students_utils.getAccommodationDetails(self.context.student)
2567        error_message = students_utils.checkAccommodationRequirements(
2568            self.context.student, acc_details)
2569        if error_message:
[15210]2570            return False
2571        return True
2572
2573    @property
2574    def actionsgroup1(self):
2575        if not self.booking_allowed:
[13457]2576            return []
[15210]2577        if not self.with_hostel_selection:
2578            return []
[13457]2579        return [_('Save')]
2580
2581    @property
2582    def actionsgroup2(self):
2583        if getattr(self.request.principal, 'user_type', None) == 'student':
[15210]2584            ## Book button can be disabled in custom packages by
2585            ## uncommenting the following lines.
2586            #if not self.booking_allowed:
2587            #    return []
[13457]2588            return [_('Book accommodation')]
2589        return [_('Book accommodation'), _('Remove selected')]
2590
2591    @property
[6635]2592    def label(self):
[7723]2593        return _('${a}: Accommodation',
2594            mapping = {'a':self.context.__parent__.display_fullname})
[6637]2595
[13480]2596    @property
2597    def desired_hostel(self):
[15312]2598        if self.context.desired_hostel == 'no':
2599            return _('No favoured hostel')
[13480]2600        if self.context.desired_hostel:
2601            hostel = grok.getSite()['hostels'].get(self.context.desired_hostel)
2602            if hostel is not None:
2603                return hostel.hostel_name
2604        return
2605
[13457]2606    def getHostels(self):
2607        """Get a list of all stored hostels.
2608        """
2609        yield(dict(name=None, title='--', selected=''))
[15312]2610        selected = ''
2611        if self.context.desired_hostel == 'no':
2612          selected = 'selected'
2613        yield(dict(name='no', title=_('No favoured hostel'), selected=selected))
[13457]2614        for val in grok.getSite()['hostels'].values():
[17458]2615            if val.special_handling == 'blocked':
2616                continue
[13457]2617            selected = ''
2618            if val.hostel_id == self.context.desired_hostel:
2619                selected = 'selected'
2620            yield(dict(name=val.hostel_id, title=val.hostel_name,
2621                       selected=selected))
2622
2623    @action(_('Save'), style='primary')
2624    def save(self):
2625        hostel = self.request.form.get('hostel', None)
2626        self.context.desired_hostel = hostel
2627        self.flash(_('Your selection has been saved.'))
2628        return
2629
[13467]2630    @action(_('Book accommodation'), style='primary')
[13457]2631    def bookAccommodation(self, **data):
2632        self.redirect(self.url(self.context, 'add'))
2633        return
2634
[7723]2635    @jsaction(_('Remove selected'))
[7009]2636    def delBedTickets(self, **data):
[7240]2637        if getattr(self.request.principal, 'user_type', None) == 'student':
[11254]2638            self.flash(_('You are not allowed to remove bed tickets.'),
2639                       type="warning")
[7017]2640            self.redirect(self.url(self.context))
2641            return
[6992]2642        form = self.request.form
[9701]2643        if 'val_id' in form:
[6992]2644            child_id = form['val_id']
2645        else:
[11254]2646            self.flash(_('No bed ticket selected.'), type="warning")
[6992]2647            self.redirect(self.url(self.context))
2648            return
2649        if not isinstance(child_id, list):
2650            child_id = [child_id]
2651        deleted = []
2652        for id in child_id:
[7068]2653            del self.context[id]
2654            deleted.append(id)
[6992]2655        if len(deleted):
[7723]2656            self.flash(_('Successfully removed: ${a}',
2657                mapping = {'a':', '.join(deleted)}))
[8735]2658            self.context.writeLogMessage(
2659                self,'removed: % s' % ', '.join(deleted))
[6992]2660        self.redirect(self.url(self.context))
2661        return
2662
[7819]2663class BedTicketAddPage(KofaPage):
[14891]2664    """ Page to add a bed ticket
[6992]2665    """
2666    grok.context(IStudentAccommodation)
2667    grok.name('add')
[7181]2668    grok.require('waeup.handleAccommodation')
[15709]2669    #grok.template('enterpin')
[6993]2670    ac_prefix = 'HOS'
[7723]2671    label = _('Add bed ticket')
[6992]2672    pnav = 4
[7723]2673    buttonname = _('Create bed ticket')
[6993]2674    notice = ''
[9188]2675    with_ac = True
[15705]2676    with_bedselection = True
[6992]2677
[15709]2678    @property
2679    def getAvailableBeds(self):
[15705]2680        """Get a list of all available beds.
2681        """
2682        cat = queryUtility(ICatalog, name='beds_catalog', default=None)
2683        entries = cat.searchResults(
[15709]2684            bed_type=(self.acc_details['bt'],self.acc_details['bt']))
[15705]2685        available_beds = [
2686            entry for entry in entries if entry.owner == NOT_OCCUPIED]
[15709]2687        desired_hostel = self.context.desired_hostel
2688        # Filter desired hostel beds
[15705]2689        if desired_hostel and desired_hostel != 'no':
2690            filtered_beds = [bed for bed in available_beds
[17335]2691                             if bed.bed_id.split('_')[0] == desired_hostel]
[15709]2692            available_beds = filtered_beds
2693        # Add legible bed coordinates
2694        for bed in available_beds:
2695            hall_title = bed.__parent__.hostel_name
2696            coordinates = bed.coordinates[1:]
2697            block, room_nr, bed_nr = coordinates
2698            bed.temp_bed_coordinates = _(
2699                '${a}, Block ${b}, Room ${c}, Bed ${d}', mapping = {
2700                'a':hall_title, 'b':block,
2701                'c':room_nr, 'd':bed_nr})
[15705]2702        return available_beds
2703
[6992]2704    def update(self, SUBMIT=None):
[8736]2705        student = self.context.student
[7150]2706        students_utils = getUtility(IStudentsUtils)
[15709]2707        self.acc_details  = students_utils.getAccommodationDetails(student)
[13247]2708        error_message = students_utils.checkAccommodationRequirements(
[15709]2709            student, self.acc_details)
2710        cat = queryUtility(ICatalog, name='beds_catalog', default=None)
2711        entries = cat.searchResults(
2712            owner=(student.student_id,student.student_id))
2713        self.show_available_beds = False
[13247]2714        if error_message:
2715            self.flash(error_message, type="warning")
[8688]2716            self.redirect(self.url(self.context))
2717            return
[9188]2718        if self.with_ac:
2719            self.ac_series = self.request.form.get('ac_series', None)
2720            self.ac_number = self.request.form.get('ac_number', None)
[15709]2721        available_beds = self.getAvailableBeds
[6992]2722        if SUBMIT is None:
[15709]2723            if self.with_bedselection and available_beds and not len(entries):
2724                self.show_available_beds = True
[6992]2725            return
[9188]2726        if self.with_ac:
2727            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2728            code = get_access_code(pin)
2729            if not code:
[11254]2730                self.flash(_('Activation code is invalid.'), type="warning")
[9188]2731                return
[7060]2732        # Search and book bed
[7003]2733        if len(entries):
[15709]2734            # If bed space has been manually allocated use this bed ...
[13050]2735            manual = True
[15806]2736            bed = list(entries)[0]
[7060]2737        else:
[15709]2738            # ... else search for available beds
[13050]2739            manual = False
[15709]2740            selected_bed = self.request.form.get('bed', None)
2741            if selected_bed:
2742                # Use selected bed
2743                beds = cat.searchResults(
2744                    bed_id=(selected_bed,selected_bed))
2745                bed = list(beds)[0]
2746                bed.bookBed(student.student_id)
2747            elif available_beds:
2748                # Select bed according to selectBed method
[7150]2749                students_utils = getUtility(IStudentsUtils)
[15705]2750                bed = students_utils.selectBed(available_beds)
[7060]2751                bed.bookBed(student.student_id)
2752            else:
[7723]2753                self.flash(_('There is no free bed in your category ${a}.',
[15709]2754                    mapping = {'a':self.acc_details['bt']}), type="warning")
[13457]2755                self.redirect(self.url(self.context))
[7060]2756                return
[9188]2757        if self.with_ac:
2758            # Mark pin as used (this also fires a pin related transition)
2759            if code.state == USED:
[11254]2760                self.flash(_('Activation code has already been used.'),
2761                           type="warning")
[13050]2762                if not manual:
2763                    # Release the previously booked bed
2764                    bed.owner = NOT_OCCUPIED
2765                    # Catalog must be informed
2766                    notify(grok.ObjectModifiedEvent(bed))
[6992]2767                return
[9188]2768            else:
2769                comment = _(u'invalidated')
2770                # Here we know that the ac is in state initialized so we do not
2771                # expect an exception, but the owner might be different
[13050]2772                success = invalidate_accesscode(
2773                    pin, comment, self.context.student.student_id)
2774                if not success:
[11254]2775                    self.flash(_('You are not the owner of this access code.'),
2776                               type="warning")
[13050]2777                    if not manual:
2778                        # Release the previously booked bed
2779                        bed.owner = NOT_OCCUPIED
2780                        # Catalog must be informed
2781                        notify(grok.ObjectModifiedEvent(bed))
[9188]2782                    return
[7060]2783        # Create bed ticket
[6992]2784        bedticket = createObject(u'waeup.BedTicket')
[9189]2785        if self.with_ac:
2786            bedticket.booking_code = pin
[15709]2787        bedticket.booking_session = self.acc_details['booking_session']
2788        bedticket.bed_type = self.acc_details['bt']
[7006]2789        bedticket.bed = bed
[6996]2790        hall_title = bed.__parent__.hostel_name
[9199]2791        coordinates = bed.coordinates[1:]
[6996]2792        block, room_nr, bed_nr = coordinates
[7723]2793        bc = _('${a}, Block ${b}, Room ${c}, Bed ${d} (${e})', mapping = {
2794            'a':hall_title, 'b':block,
2795            'c':room_nr, 'd':bed_nr,
2796            'e':bed.bed_type})
[7819]2797        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7723]2798        bedticket.bed_coordinates = translate(
[7811]2799            bc, 'waeup.kofa',target_language=portal_language)
[9423]2800        self.context.addBedTicket(bedticket)
[9411]2801        self.context.writeLogMessage(self, 'booked: %s' % bed.bed_id)
[7723]2802        self.flash(_('Bed ticket created and bed booked: ${a}',
[9984]2803            mapping = {'a':bedticket.display_coordinates}))
[6992]2804        self.redirect(self.url(self.context))
2805        return
2806
[7819]2807class BedTicketDisplayFormPage(KofaDisplayFormPage):
[6994]2808    """ Page to display bed tickets
2809    """
2810    grok.context(IBedTicket)
2811    grok.name('index')
[15972]2812    grok.require('waeup.viewStudent')
[9984]2813    form_fields = grok.AutoFields(IBedTicket).omit('bed_coordinates')
[9201]2814    form_fields['booking_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[6994]2815    pnav = 4
2816
2817    @property
2818    def label(self):
[7723]2819        return _('Bed Ticket for Session ${a}',
2820            mapping = {'a':self.context.getSessionString()})
[6994]2821
[13055]2822class ExportPDFBedTicketSlip(UtilityView, grok.View):
[7027]2823    """Deliver a PDF slip of the context.
2824    """
2825    grok.context(IBedTicket)
[9452]2826    grok.name('bed_allocation_slip.pdf')
[15972]2827    grok.require('waeup.viewStudent')
[9984]2828    form_fields = grok.AutoFields(IBedTicket).omit('bed_coordinates')
[8173]2829    form_fields['booking_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7027]2830    prefix = 'form'
[9702]2831    omit_fields = (
[10256]2832        'password', 'suspended', 'phone', 'adm_code',
[13711]2833        'suspended_comment', 'date_of_birth', 'current_level',
2834        'flash_notice')
[7027]2835
2836    @property
[7723]2837    def title(self):
[7819]2838        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]2839        return translate(_('Bed Allocation Data'), 'waeup.kofa',
[7723]2840            target_language=portal_language)
2841
2842    @property
[7027]2843    def label(self):
[7819]2844        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[9201]2845        #return translate(_('Bed Allocation: '),
2846        #    'waeup.kofa', target_language=portal_language) \
2847        #    + ' %s' % self.context.bed_coordinates
2848        return translate(_('Bed Allocation Slip'),
[7811]2849            'waeup.kofa', target_language=portal_language) \
[9201]2850            + ' %s' % self.context.getSessionString()
[7027]2851
2852    def render(self):
[9141]2853        studentview = StudentBasePDFFormPage(self.context.student,
[9375]2854            self.request, self.omit_fields)
[7150]2855        students_utils = getUtility(IStudentsUtils)
[15250]2856        note = None
2857        n = grok.getSite()['hostels'].allocation_expiration
2858        if n:
[15254]2859            note = _("""
[15250]2860<br /><br /><br /><br /><br /><font size="12">
2861Please endeavour to pay your hostel maintenance charge within ${a} days
2862 of being allocated a space or else you are deemed to have
2863 voluntarily forfeited it and it goes back into circulation to be
[15254]2864 available for booking afresh!</font>)
2865""")
[15250]2866            note = _(note, mapping={'a': n})
2867            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2868            note = translate(
2869                note, 'waeup.kofa', target_language=portal_language)
[7186]2870        return students_utils.renderPDF(
[9452]2871            self, 'bed_allocation_slip.pdf',
[10250]2872            self.context.student, studentview,
[15250]2873            omit_fields=self.omit_fields,
2874            note=note)
[7027]2875
[13055]2876class BedTicketRelocationView(UtilityView, grok.View):
[7015]2877    """ Callback view
2878    """
2879    grok.context(IBedTicket)
2880    grok.name('relocate')
2881    grok.require('waeup.manageHostels')
2882
[7059]2883    # Relocate student if student parameters have changed or the bed_type
2884    # of the bed has changed
[7015]2885    def update(self):
[13455]2886        success, msg = self.context.relocateStudent()
2887        if not success:
2888            self.flash(msg, type="warning")
[7068]2889        else:
[13455]2890            self.flash(msg)
[7015]2891        self.redirect(self.url(self.context))
2892        return
2893
2894    def render(self):
2895        return
2896
[7819]2897class StudentHistoryPage(KofaPage):
[11976]2898    """ Page to display student history
[6637]2899    """
2900    grok.context(IStudent)
2901    grok.name('history')
[6660]2902    grok.require('waeup.viewStudent')
[6637]2903    grok.template('studenthistory')
[6642]2904    pnav = 4
[6637]2905
2906    @property
2907    def label(self):
[7723]2908        return _('${a}: History', mapping = {'a':self.context.display_fullname})
[6694]2909
2910# Pages for students only
2911
[7819]2912class StudentBaseEditFormPage(KofaEditFormPage):
[7133]2913    """ View to edit student base data
2914    """
2915    grok.context(IStudent)
2916    grok.name('edit_base')
2917    grok.require('waeup.handleStudent')
2918    form_fields = grok.AutoFields(IStudentBase).select(
[15609]2919        'email', 'phone', 'parents_email')
[7723]2920    label = _('Edit base data')
[7133]2921    pnav = 4
2922
[7723]2923    @action(_('Save'), style='primary')
[7133]2924    def save(self, **data):
2925        msave(self, **data)
2926        return
2927
[7819]2928class StudentChangePasswordPage(KofaEditFormPage):
[11976]2929    """ View to edit student passwords
[6756]2930    """
2931    grok.context(IStudent)
[7114]2932    grok.name('change_password')
[6694]2933    grok.require('waeup.handleStudent')
[7144]2934    grok.template('change_password')
[7723]2935    label = _('Change password')
[6694]2936    pnav = 4
2937
[7723]2938    @action(_('Save'), style='primary')
[7144]2939    def save(self, **data):
2940        form = self.request.form
2941        password = form.get('change_password', None)
2942        password_ctl = form.get('change_password_repeat', None)
2943        if password:
[7147]2944            validator = getUtility(IPasswordValidator)
2945            errors = validator.validate_password(password, password_ctl)
2946            if not errors:
2947                IUserAccount(self.context).setPassword(password)
[12807]2948                # Unset temporary password
2949                self.context.temp_password = None
[8735]2950                self.context.writeLogMessage(self, 'saved: password')
[7723]2951                self.flash(_('Password changed.'))
[6756]2952            else:
[11254]2953                self.flash( ' '.join(errors), type="warning")
[6756]2954        return
2955
[7819]2956class StudentFilesUploadPage(KofaPage):
[16609]2957    """ View to upload passport picture by student. The class name
2958    is historical. The page is only used for the student's portrait.
[7114]2959    """
2960    grok.context(IStudent)
2961    grok.name('change_portrait')
[7127]2962    grok.require('waeup.uploadStudentFile')
[7114]2963    grok.template('filesuploadpage')
[7723]2964    label = _('Upload portrait')
[7114]2965    pnav = 4
2966
[7133]2967    def update(self):
[16671]2968        if not getUtility(IStudentsUtils).allowPortraitChange(self.context):
[16444]2969            emit_lock_message(self,
[17810]2970                _('The requested form is locked.'))
[7133]2971            return
2972        super(StudentFilesUploadPage, self).update()
2973        return
2974
[16609]2975class StudentSignatureUploadPage(KofaPage):
2976    """ View to upload scanned signature by student. Not active
2977    in base package.
2978    """
2979    grok.context(IStudent)
2980    grok.name('change_signature')
2981    grok.require('waeup.uploadStudentFile')
2982    grok.template('filesuploadpage')
2983    label = _('Upload signature')
2984    pnav = 4
2985
2986    def update(self):
2987        SIGNATURE_CHANGE_STATES = getUtility(IStudentsUtils).SIGNATURE_CHANGE_STATES
2988        if self.context.student.state not in SIGNATURE_CHANGE_STATES:
2989            emit_lock_message(self,
2990                _('This form is locked. You are in the wrong state.'))
2991            return
2992        super(StudentSignatureUploadPage, self).update()
2993        return
2994
[7819]2995class StartClearancePage(KofaPage):
[6770]2996    grok.context(IStudent)
2997    grok.name('start_clearance')
2998    grok.require('waeup.handleStudent')
2999    grok.template('enterpin')
[7723]3000    label = _('Start clearance')
[6770]3001    ac_prefix = 'CLR'
3002    notice = ''
3003    pnav = 4
[7723]3004    buttonname = _('Start clearance now')
[9952]3005    with_ac = True
[6770]3006
[7133]3007    @property
3008    def all_required_fields_filled(self):
[13349]3009        if not self.context.email:
[13350]3010            return _("Email address is missing."), 'edit_base'
[13349]3011        if not self.context.phone:
[13350]3012            return _("Phone number is missing."), 'edit_base'
[13349]3013        return
[7133]3014
3015    @property
3016    def portrait_uploaded(self):
3017        store = getUtility(IExtFileStore)
3018        if store.getFileByContext(self.context, attr=u'passport.jpg'):
3019            return True
3020        return False
3021
[6770]3022    def update(self, SUBMIT=None):
[7671]3023        if not self.context.state == ADMITTED:
[11254]3024            self.flash(_("Wrong state"), type="warning")
[6936]3025            self.redirect(self.url(self.context))
3026            return
[7133]3027        if not self.portrait_uploaded:
[11254]3028            self.flash(_("No portrait uploaded."), type="warning")
[7133]3029            self.redirect(self.url(self.context, 'change_portrait'))
3030            return
[13350]3031        if self.all_required_fields_filled:
3032            arf_warning = self.all_required_fields_filled[0]
3033            arf_redirect = self.all_required_fields_filled[1]
[13349]3034            self.flash(arf_warning, type="warning")
[13350]3035            self.redirect(self.url(self.context, arf_redirect))
[7133]3036            return
[9952]3037        if self.with_ac:
3038            self.ac_series = self.request.form.get('ac_series', None)
3039            self.ac_number = self.request.form.get('ac_number', None)
[6770]3040        if SUBMIT is None:
3041            return
[9952]3042        if self.with_ac:
3043            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3044            code = get_access_code(pin)
3045            if not code:
[11254]3046                self.flash(_('Activation code is invalid.'), type="warning")
[9952]3047                return
3048            if code.state == USED:
[11254]3049                self.flash(_('Activation code has already been used.'),
3050                           type="warning")
[9952]3051                return
3052            # Mark pin as used (this also fires a pin related transition)
3053            # and fire transition start_clearance
3054            comment = _(u"invalidated")
3055            # Here we know that the ac is in state initialized so we do not
3056            # expect an exception, but the owner might be different
3057            if not invalidate_accesscode(pin, comment, self.context.student_id):
[11254]3058                self.flash(_('You are not the owner of this access code.'),
3059                           type="warning")
[9952]3060                return
3061            self.context.clr_code = pin
[6770]3062        IWorkflowInfo(self.context).fireTransition('start_clearance')
[7723]3063        self.flash(_('Clearance process has been started.'))
[6770]3064        self.redirect(self.url(self.context,'cedit'))
3065        return
3066
[6695]3067class StudentClearanceEditFormPage(StudentClearanceManageFormPage):
3068    """ View to edit student clearance data by student
3069    """
3070    grok.context(IStudent)
3071    grok.name('cedit')
3072    grok.require('waeup.handleStudent')
[7723]3073    label = _('Edit clearance data')
[6718]3074
[7993]3075    @property
3076    def form_fields(self):
[8472]3077        if self.context.is_postgrad:
[8974]3078            form_fields = grok.AutoFields(IPGStudentClearance).omit(
[13103]3079                'clr_code', 'officer_comment')
[7993]3080        else:
[8974]3081            form_fields = grok.AutoFields(IUGStudentClearance).omit(
[13103]3082                'clr_code', 'officer_comment')
[7993]3083        return form_fields
3084
[6718]3085    def update(self):
3086        if self.context.clearance_locked:
[7145]3087            emit_lock_message(self)
[6718]3088            return
3089        return super(StudentClearanceEditFormPage, self).update()
[6719]3090
[7723]3091    @action(_('Save'), style='primary')
[6722]3092    def save(self, **data):
3093        self.applyData(self.context, **data)
[7723]3094        self.flash(_('Clearance form has been saved.'))
[6722]3095        return
3096
[7253]3097    def dataNotComplete(self):
[7642]3098        """To be implemented in the customization package.
3099        """
[7253]3100        return False
3101
[14102]3102    @action(_('Save and request clearance'), style='primary',
3103            warning=_('You can not edit your data after '
3104            'requesting clearance. You really want to request clearance now?'))
[7186]3105    def requestClearance(self, **data):
[6722]3106        self.applyData(self.context, **data)
[7253]3107        if self.dataNotComplete():
[11254]3108            self.flash(self.dataNotComplete(), type="warning")
[7253]3109            return
[7723]3110        self.flash(_('Clearance form has been saved.'))
[9021]3111        if self.context.clr_code:
3112            self.redirect(self.url(self.context, 'request_clearance'))
3113        else:
3114            # We bypass the request_clearance page if student
3115            # has been imported in state 'clearance started' and
3116            # no clr_code was entered before.
3117            state = IWorkflowState(self.context).getState()
3118            if state != CLEARANCE:
3119                # This shouldn't happen, but the application officer
3120                # might have forgotten to lock the form after changing the state
[11254]3121                self.flash(_('This form cannot be submitted. Wrong state!'),
3122                           type="danger")
[9021]3123                return
3124            IWorkflowInfo(self.context).fireTransition('request_clearance')
3125            self.flash(_('Clearance has been requested.'))
3126            self.redirect(self.url(self.context))
[6722]3127        return
3128
[7819]3129class RequestClearancePage(KofaPage):
[6769]3130    grok.context(IStudent)
3131    grok.name('request_clearance')
3132    grok.require('waeup.handleStudent')
3133    grok.template('enterpin')
[7723]3134    label = _('Request clearance')
3135    notice = _('Enter the CLR access code used for starting clearance.')
[6769]3136    ac_prefix = 'CLR'
3137    pnav = 4
[7723]3138    buttonname = _('Request clearance now')
[9952]3139    with_ac = True
[6769]3140
3141    def update(self, SUBMIT=None):
[9952]3142        if self.with_ac:
3143            self.ac_series = self.request.form.get('ac_series', None)
3144            self.ac_number = self.request.form.get('ac_number', None)
[6769]3145        if SUBMIT is None:
3146            return
[9952]3147        if self.with_ac:
3148            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3149            if self.context.clr_code and self.context.clr_code != pin:
[11254]3150                self.flash(_("This isn't your CLR access code."), type="danger")
[9952]3151                return
[6769]3152        state = IWorkflowState(self.context).getState()
3153        if state != CLEARANCE:
[9021]3154            # This shouldn't happen, but the application officer
3155            # might have forgotten to lock the form after changing the state
[11254]3156            self.flash(_('This form cannot be submitted. Wrong state!'),
3157                       type="danger")
[6769]3158            return
3159        IWorkflowInfo(self.context).fireTransition('request_clearance')
[7723]3160        self.flash(_('Clearance has been requested.'))
[6769]3161        self.redirect(self.url(self.context))
[6789]3162        return
[6806]3163
[8471]3164class StartSessionPage(KofaPage):
[6944]3165    grok.context(IStudentStudyCourse)
[8471]3166    grok.name('start_session')
[6944]3167    grok.require('waeup.handleStudent')
3168    grok.template('enterpin')
[8471]3169    label = _('Start session')
[6944]3170    ac_prefix = 'SFE'
3171    notice = ''
3172    pnav = 4
[8471]3173    buttonname = _('Start now')
[9952]3174    with_ac = True
[6944]3175
3176    def update(self, SUBMIT=None):
[9139]3177        if not self.context.is_current:
3178            emit_lock_message(self)
3179            return
3180        super(StartSessionPage, self).update()
[8471]3181        if not self.context.next_session_allowed:
[11254]3182            self.flash(_("You are not entitled to start session."),
3183                       type="warning")
[6944]3184            self.redirect(self.url(self.context))
3185            return
[9952]3186        if self.with_ac:
3187            self.ac_series = self.request.form.get('ac_series', None)
3188            self.ac_number = self.request.form.get('ac_number', None)
[6944]3189        if SUBMIT is None:
3190            return
[9952]3191        if self.with_ac:
3192            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3193            code = get_access_code(pin)
3194            if not code:
[11254]3195                self.flash(_('Activation code is invalid.'), type="warning")
[6944]3196                return
[9952]3197            # Mark pin as used (this also fires a pin related transition)
3198            if code.state == USED:
[11254]3199                self.flash(_('Activation code has already been used.'),
3200                           type="warning")
[9952]3201                return
3202            else:
3203                comment = _(u"invalidated")
3204                # Here we know that the ac is in state initialized so we do not
3205                # expect an error, but the owner might be different
3206                if not invalidate_accesscode(
3207                    pin,comment,self.context.student.student_id):
[11254]3208                    self.flash(_('You are not the owner of this access code.'),
3209                               type="warning")
[9952]3210                    return
[9637]3211        try:
3212            if self.context.student.state == CLEARED:
3213                IWorkflowInfo(self.context.student).fireTransition(
3214                    'pay_first_school_fee')
3215            elif self.context.student.state == RETURNING:
3216                IWorkflowInfo(self.context.student).fireTransition(
3217                    'pay_school_fee')
3218            elif self.context.student.state == PAID:
3219                IWorkflowInfo(self.context.student).fireTransition(
3220                    'pay_pg_fee')
3221        except ConstraintNotSatisfied:
[11254]3222            self.flash(_('An error occurred, please contact the system administrator.'),
3223                       type="danger")
[9637]3224            return
[8471]3225        self.flash(_('Session started.'))
[6944]3226        self.redirect(self.url(self.context))
3227        return
3228
[7819]3229class AddStudyLevelFormPage(KofaEditFormPage):
[6806]3230    """ Page for students to add current study levels
3231    """
3232    grok.context(IStudentStudyCourse)
3233    grok.name('add')
3234    grok.require('waeup.handleStudent')
3235    grok.template('studyleveladdpage')
3236    form_fields = grok.AutoFields(IStudentStudyCourse)
3237    pnav = 4
3238
3239    @property
3240    def label(self):
3241        studylevelsource = StudyLevelSource().factory
3242        code = self.context.current_level
3243        title = studylevelsource.getTitle(self.context, code)
[7723]3244        return _('Add current level ${a}', mapping = {'a':title})
[6806]3245
3246    def update(self):
[15163]3247        if not self.context.is_current \
3248            or self.context.student.studycourse_locked:
[9139]3249            emit_lock_message(self)
3250            return
[8736]3251        if self.context.student.state != PAID:
[7145]3252            emit_lock_message(self)
[6806]3253            return
[11254]3254        code = self.context.current_level
3255        if code is None:
3256            self.flash(_('Your data are incomplete'), type="danger")
3257            self.redirect(self.url(self.context))
3258            return
[6806]3259        super(AddStudyLevelFormPage, self).update()
3260        return
3261
[7723]3262    @action(_('Create course list now'), style='primary')
[6806]3263    def addStudyLevel(self, **data):
[8323]3264        studylevel = createObject(u'waeup.StudentStudyLevel')
[6806]3265        studylevel.level = self.context.current_level
3266        studylevel.level_session = self.context.current_session
3267        try:
3268            self.context.addStudentStudyLevel(
3269                self.context.certificate,studylevel)
3270        except KeyError:
[11254]3271            self.flash(_('This level exists.'), type="warning")
[13773]3272            self.redirect(self.url(self.context))
3273            return
[9467]3274        except RequiredMissing:
[13773]3275            self.flash(_('Your data are incomplete.'), type="danger")
3276            self.redirect(self.url(self.context))
3277            return
3278        self.flash(_('You successfully created a new course list.'))
3279        self.redirect(self.url(self.context, str(studylevel.level)))
[6806]3280        return
[6808]3281
[7819]3282class StudyLevelEditFormPage(KofaEditFormPage):
[6808]3283    """ Page to edit the student study level data by students
3284    """
3285    grok.context(IStudentStudyLevel)
3286    grok.name('edit')
[9924]3287    grok.require('waeup.editStudyLevel')
[6808]3288    grok.template('studyleveleditpage')
3289    pnav = 4
[12473]3290    placeholder = _('Enter valid course code')
[6808]3291
[9895]3292    def update(self, ADD=None, course=None):
[9139]3293        if not self.context.__parent__.is_current:
3294            emit_lock_message(self)
3295            return
[9257]3296        if self.context.student.state != PAID or \
3297            not self.context.is_current_level:
[7539]3298            emit_lock_message(self)
3299            return
[6808]3300        super(StudyLevelEditFormPage, self).update()
[9895]3301        if ADD is not None:
3302            if not course:
[11254]3303                self.flash(_('No valid course code entered.'), type="warning")
[9895]3304                return
3305            cat = queryUtility(ICatalog, name='courses_catalog')
3306            result = cat.searchResults(code=(course, course))
3307            if len(result) != 1:
[11254]3308                self.flash(_('Course not found.'), type="warning")
[9895]3309                return
3310            course = list(result)[0]
[15970]3311            if course.former_course:
3312                self.flash(_('Former courses can\'t be added.'), type="warning")
3313                return
[9895]3314            addCourseTicket(self, course)
[6808]3315        return
3316
3317    @property
3318    def label(self):
[7833]3319        # Here we know that the cookie has been set
3320        lang = self.request.cookies.get('kofa.language')
[7811]3321        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]3322            target_language=lang)
[8920]3323        return _('Edit course list of ${a}',
[7723]3324            mapping = {'a':level_title})
[6808]3325
3326    @property
[8921]3327    def translated_values(self):
3328        return translated_values(self)
3329
[9280]3330    def _delCourseTicket(self, **data):
[6808]3331        form = self.request.form
[9701]3332        if 'val_id' in form:
[6808]3333            child_id = form['val_id']
3334        else:
[11254]3335            self.flash(_('No ticket selected.'), type="warning")
[6808]3336            self.redirect(self.url(self.context, '@@edit'))
3337            return
3338        if not isinstance(child_id, list):
3339            child_id = [child_id]
3340        deleted = []
3341        for id in child_id:
[6940]3342            # Students are not allowed to remove core tickets
[9700]3343            if id in self.context and \
3344                self.context[id].removable_by_student:
[7723]3345                del self.context[id]
3346                deleted.append(id)
[6808]3347        if len(deleted):
[7723]3348            self.flash(_('Successfully removed: ${a}',
3349                mapping = {'a':', '.join(deleted)}))
[9332]3350            self.context.writeLogMessage(
[9924]3351                self,'removed: %s at %s' %
3352                (', '.join(deleted), self.context.level))
[6808]3353        self.redirect(self.url(self.context, u'@@edit'))
3354        return
3355
[9280]3356    @jsaction(_('Remove selected tickets'))
3357    def delCourseTicket(self, **data):
3358        self._delCourseTicket(**data)
3359        return
3360
[14684]3361    def _updateTickets(self, **data):
3362        cat = queryUtility(ICatalog, name='courses_catalog')
3363        invalidated = list()
3364        for value in self.context.values():
3365            result = cat.searchResults(code=(value.code, value.code))
3366            if len(result) != 1:
3367                course = None
3368            else:
3369                course = list(result)[0]
3370            invalid = self.context.updateCourseTicket(value, course)
3371            if invalid:
3372                invalidated.append(invalid)
3373        if invalidated:
3374            invalidated_string = ', '.join(invalidated)
3375            self.context.writeLogMessage(
3376                self, 'course tickets invalidated: %s' % invalidated_string)
3377        self.flash(_('All course tickets updated.'))
3378        return
3379
3380    @action(_('Update all tickets'),
3381        tooltip=_('Update all course parameters including course titles.'))
3382    def updateTickets(self, **data):
3383        self._updateTickets(**data)
3384        return
3385
[9280]3386    def _registerCourses(self, **data):
[10155]3387        if self.context.student.is_postgrad and \
3388            not self.context.student.is_special_postgrad:
[9252]3389            self.flash(_(
3390                "You are a postgraduate student, "
[11254]3391                "your course list can't bee registered."), type="warning")
[9252]3392            self.redirect(self.url(self.context))
3393            return
[9830]3394        students_utils = getUtility(IStudentsUtils)
[14584]3395        warning = students_utils.warnCreditsOOR(self.context)
3396        if warning:
3397            self.flash(warning, type="warning")
[8642]3398            return
[14247]3399        msg = self.context.course_registration_forbidden
3400        if msg:
3401            self.flash(msg, type="warning")
[13031]3402            return
[8736]3403        IWorkflowInfo(self.context.student).fireTransition(
[7642]3404            'register_courses')
[7723]3405        self.flash(_('Course list has been registered.'))
[6810]3406        self.redirect(self.url(self.context))
3407        return
3408
[12474]3409    @action(_('Register course list'), style='primary',
3410        warning=_('You can not edit your course list after registration.'
3411            ' You really want to register?'))
[9280]3412    def registerCourses(self, **data):
3413        self._registerCourses(**data)
3414        return
3415
[6808]3416class CourseTicketAddFormPage2(CourseTicketAddFormPage):
3417    """Add a course ticket by student.
3418    """
3419    grok.name('ctadd')
3420    grok.require('waeup.handleStudent')
[9420]3421    form_fields = grok.AutoFields(ICourseTicketAdd)
[6808]3422
[7539]3423    def update(self):
[9257]3424        if self.context.student.state != PAID or \
3425            not self.context.is_current_level:
[7539]3426            emit_lock_message(self)
3427            return
3428        super(CourseTicketAddFormPage2, self).update()
3429        return
3430
[7723]3431    @action(_('Add course ticket'))
[6808]3432    def addCourseTicket(self, **data):
[7642]3433        # Safety belt
[8736]3434        if self.context.student.state != PAID:
[7539]3435            return
[6808]3436        course = data['course']
[15970]3437        if course.former_course:
3438            self.flash(_('Former courses can\'t be added.'), type="warning")
3439            return
[9895]3440        success = addCourseTicket(self, course)
3441        if success:
3442            self.redirect(self.url(self.context, u'@@edit'))
[6808]3443        return
[7369]3444
[7819]3445class SetPasswordPage(KofaPage):
3446    grok.context(IKofaObject)
[7660]3447    grok.name('setpassword')
3448    grok.require('waeup.Anonymous')
3449    grok.template('setpassword')
[7723]3450    label = _('Set password for first-time login')
[7660]3451    ac_prefix = 'PWD'
3452    pnav = 0
[7738]3453    set_button = _('Set')
[7660]3454
3455    def update(self, SUBMIT=None):
3456        self.reg_number = self.request.form.get('reg_number', None)
3457        self.ac_series = self.request.form.get('ac_series', None)
3458        self.ac_number = self.request.form.get('ac_number', None)
3459
3460        if SUBMIT is None:
3461            return
3462        hitlist = search(query=self.reg_number,
3463            searchtype='reg_number', view=self)
3464        if not hitlist:
[11254]3465            self.flash(_('No student found.'), type="warning")
[7660]3466            return
3467        if len(hitlist) != 1:   # Cannot happen but anyway
[11254]3468            self.flash(_('More than one student found.'), type="warning")
[7660]3469            return
3470        student = hitlist[0].context
3471        self.student_id = student.student_id
3472        student_pw = student.password
3473        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3474        code = get_access_code(pin)
3475        if not code:
[11254]3476            self.flash(_('Access code is invalid.'), type="warning")
[7660]3477            return
3478        if student_pw and pin == student.adm_code:
[7723]3479            self.flash(_(
3480                'Password has already been set. Your Student Id is ${a}',
3481                mapping = {'a':self.student_id}))
[7660]3482            return
3483        elif student_pw:
3484            self.flash(
[7723]3485                _('Password has already been set. You are using the ' +
[11254]3486                'wrong Access Code.'), type="warning")
[7660]3487            return
3488        # Mark pin as used (this also fires a pin related transition)
3489        # and set student password
3490        if code.state == USED:
[11254]3491            self.flash(_('Access code has already been used.'), type="warning")
[7660]3492            return
3493        else:
[7723]3494            comment = _(u"invalidated")
[7660]3495            # Here we know that the ac is in state initialized so we do not
3496            # expect an exception
3497            invalidate_accesscode(pin,comment)
3498            IUserAccount(student).setPassword(self.ac_number)
3499            student.adm_code = pin
[7723]3500        self.flash(_('Password has been set. Your Student Id is ${a}',
3501            mapping = {'a':self.student_id}))
[7811]3502        return
[8779]3503
3504class StudentRequestPasswordPage(KofaAddFormPage):
[13047]3505    """Captcha'd request password page for students.
[8779]3506    """
3507    grok.name('requestpw')
3508    grok.require('waeup.Anonymous')
3509    grok.template('requestpw')
3510    form_fields = grok.AutoFields(IStudentRequestPW).select(
[13344]3511        'lastname','number','email')
[8779]3512    label = _('Request password for first-time login')
3513
3514    def update(self):
[13396]3515        blocker = grok.getSite()['configuration'].maintmode_enabled_by
3516        if blocker:
3517            self.flash(_('The portal is in maintenance mode. '
3518                        'Password request forms are temporarily disabled.'),
3519                       type='warning')
3520            self.redirect(self.url(self.context))
3521            return
[8779]3522        # Handle captcha
3523        self.captcha = getUtility(ICaptchaManager).getCaptcha()
3524        self.captcha_result = self.captcha.verify(self.request)
3525        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
3526        return
3527
3528    def _redirect(self, email, password, student_id):
3529        # Forward only email to landing page in base package.
3530        self.redirect(self.url(self.context, 'requestpw_complete',
3531            data = dict(email=email)))
3532        return
3533
[14305]3534    def _redirect_no_student(self):
3535        # No record found, this is the truth. We do not redirect here.
3536        # We are using this method in custom packages
3537        # for redirecting alumni to the application section.
3538        self.flash(_('No student record found.'), type="warning")
3539        return
3540
[8779]3541    def _pw_used(self):
[8780]3542        # XXX: False if password has not been used. We need an extra
3543        #      attribute which remembers if student logged in.
[8779]3544        return True
3545
[8854]3546    @action(_('Send login credentials to email address'), style='primary')
[8779]3547    def get_credentials(self, **data):
3548        if not self.captcha_result.is_valid:
3549            # Captcha will display error messages automatically.
3550            # No need to flash something.
3551            return
[8854]3552        number = data.get('number','')
[13344]3553        lastname = data.get('lastname','')
[8779]3554        cat = getUtility(ICatalog, name='students_catalog')
3555        results = list(
[8854]3556            cat.searchResults(reg_number=(number, number)))
3557        if not results:
3558            results = list(
3559                cat.searchResults(matric_number=(number, number)))
[8779]3560        if results:
3561            student = results[0]
[13344]3562            if getattr(student,'lastname',None) is None:
[11254]3563                self.flash(_('An error occurred.'), type="danger")
[8779]3564                return
[13344]3565            elif student.lastname.lower() != lastname.lower():
[8779]3566                # Don't tell the truth here. Anonymous must not
[13344]3567                # know that a record was found and only the lastname
[8779]3568                # verification failed.
[11254]3569                self.flash(_('No student record found.'), type="warning")
[8779]3570                return
3571            elif student.password is not None and self._pw_used:
3572                self.flash(_('Your password has already been set and used. '
[11254]3573                             'Please proceed to the login page.'),
3574                           type="warning")
[8779]3575                return
3576            # Store email address but nothing else.
3577            student.email = data['email']
3578            notify(grok.ObjectModifiedEvent(student))
3579        else:
[14305]3580            self._redirect_no_student()
[8779]3581            return
3582
3583        kofa_utils = getUtility(IKofaUtils)
3584        password = kofa_utils.genPassword()
[8857]3585        mandate = PasswordMandate()
[8853]3586        mandate.params['password'] = password
[8858]3587        mandate.params['user'] = student
[8853]3588        site = grok.getSite()
3589        site['mandates'].addMandate(mandate)
[8779]3590        # Send email with credentials
[8853]3591        args = {'mandate_id':mandate.mandate_id}
3592        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3593        url_info = u'Confirmation link: %s' % mandate_url
[8779]3594        msg = _('You have successfully requested a password for the')
3595        if kofa_utils.sendCredentials(IUserAccount(student),
[8853]3596            password, url_info, msg):
[8779]3597            email_sent = student.email
3598        else:
3599            email_sent = None
3600        self._redirect(email=email_sent, password=password,
3601            student_id=student.student_id)
[8856]3602        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3603        self.context.logger.info(
3604            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
[8779]3605        return
3606
[15609]3607class ParentsUser:
3608    pass
3609
3610class RequestParentsPasswordPage(StudentRequestPasswordPage):
3611    """Captcha'd request password page for parents.
3612    """
3613    grok.name('requestppw')
3614    grok.template('requestppw')
3615    label = _('Request password for parents access')
3616
3617    def update(self):
3618        super(RequestParentsPasswordPage, self).update()
3619        kofa_utils = getUtility(IKofaUtils)
3620        self.temp_password_minutes = kofa_utils.TEMP_PASSWORD_MINUTES
3621        return
3622
3623    @action(_('Send temporary login credentials to email address'), style='primary')
3624    def get_credentials(self, **data):
3625        if not self.captcha_result.is_valid:
3626            # Captcha will display error messages automatically.
3627            # No need to flash something.
3628            return
3629        number = data.get('number','')
3630        lastname = data.get('lastname','')
3631        email = data['email']
3632        cat = getUtility(ICatalog, name='students_catalog')
3633        results = list(
3634            cat.searchResults(reg_number=(number, number)))
3635        if not results:
3636            results = list(
3637                cat.searchResults(matric_number=(number, number)))
3638        if results:
3639            student = results[0]
3640            if getattr(student,'lastname',None) is None:
3641                self.flash(_('An error occurred.'), type="danger")
3642                return
3643            elif student.lastname.lower() != lastname.lower():
3644                # Don't tell the truth here. Anonymous must not
3645                # know that a record was found and only the lastname
3646                # verification failed.
3647                self.flash(_('No student record found.'), type="warning")
3648                return
3649            elif email != student.parents_email:
3650                self.flash(_('Wrong email address.'), type="warning")
3651                return
3652        else:
3653            self._redirect_no_student()
3654            return
3655        kofa_utils = getUtility(IKofaUtils)
3656        password = kofa_utils.genPassword()
3657        mandate = ParentsPasswordMandate()
3658        mandate.params['password'] = password
3659        mandate.params['student'] = student
3660        site = grok.getSite()
3661        site['mandates'].addMandate(mandate)
3662        # Send email with credentials
3663        args = {'mandate_id':mandate.mandate_id}
3664        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3665        url_info = u'Confirmation link: %s' % mandate_url
3666        msg = _('You have successfully requested a parents password for the')
3667        # Create a fake user
3668        user = ParentsUser()
3669        user.name = student.student_id
3670        user.title = "Parents of %s" % student.display_fullname
3671        user.email = student.parents_email
3672        if kofa_utils.sendCredentials(user, password, url_info, msg):
3673            email_sent = user.email
3674        else:
3675            email_sent = None
3676        self._redirect(email=email_sent, password=password,
3677            student_id=student.student_id)
3678        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3679        self.context.logger.info(
3680            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
3681        return
3682
[8779]3683class StudentRequestPasswordEmailSent(KofaPage):
3684    """Landing page after successful password request.
3685
3686    """
3687    grok.name('requestpw_complete')
3688    grok.require('waeup.Public')
3689    grok.template('requestpwmailsent')
3690    label = _('Your password request was successful.')
3691
3692    def update(self, email=None, student_id=None, password=None):
3693        self.email = email
3694        self.password = password
3695        self.student_id = student_id
[8974]3696        return
[9797]3697
[9806]3698class FilterStudentsInDepartmentPage(KofaPage):
3699    """Page that filters and lists students.
3700    """
3701    grok.context(IDepartment)
3702    grok.require('waeup.showStudents')
3703    grok.name('students')
3704    grok.template('filterstudentspage')
3705    pnav = 1
[9819]3706    session_label = _('Current Session')
3707    level_label = _('Current Level')
[9806]3708
3709    def label(self):
[10650]3710        return 'Students in %s' % self.context.longtitle
[9806]3711
3712    def _set_session_values(self):
3713        vocab_terms = academic_sessions_vocab.by_value.values()
3714        self.sessions = sorted(
3715            [(x.title, x.token) for x in vocab_terms], reverse=True)
3716        self.sessions += [('All Sessions', 'all')]
3717        return
3718
3719    def _set_level_values(self):
3720        vocab_terms = course_levels.by_value.values()
3721        self.levels = sorted(
3722            [(x.title, x.token) for x in vocab_terms])
3723        self.levels += [('All Levels', 'all')]
3724        return
3725
3726    def _searchCatalog(self, session, level):
[16812]3727        if level not in (10, 999, 1000, None):
[9806]3728            start_level = 100 * (level // 100)
3729            end_level = start_level + 90
3730        else:
3731            start_level = end_level = level
3732        cat = queryUtility(ICatalog, name='students_catalog')
3733        students = cat.searchResults(
3734            current_session=(session, session),
3735            current_level=(start_level, end_level),
3736            depcode=(self.context.code, self.context.code)
3737            )
3738        hitlist = []
3739        for student in students:
3740            hitlist.append(StudentQueryResultItem(student, view=self))
3741        return hitlist
3742
3743    def update(self, SHOW=None, session=None, level=None):
3744        self.parent_url = self.url(self.context.__parent__)
3745        self._set_session_values()
3746        self._set_level_values()
3747        self.hitlist = []
3748        self.session_default = session
3749        self.level_default = level
3750        if SHOW is not None:
3751            if session != 'all':
3752                self.session = int(session)
3753                self.session_string = '%s %s/%s' % (
3754                    self.session_label, self.session, self.session+1)
3755            else:
3756                self.session = None
3757                self.session_string = _('in any session')
3758            if level != 'all':
3759                self.level = int(level)
3760                self.level_string = '%s %s' % (self.level_label, self.level)
3761            else:
3762                self.level = None
3763                self.level_string = _('at any level')
3764            self.hitlist = self._searchCatalog(self.session, self.level)
3765            if not self.hitlist:
[11254]3766                self.flash(_('No student found.'), type="warning")
[9806]3767        return
3768
3769class FilterStudentsInCertificatePage(FilterStudentsInDepartmentPage):
3770    """Page that filters and lists students.
3771    """
3772    grok.context(ICertificate)
3773
3774    def label(self):
[10650]3775        return 'Students studying %s' % self.context.longtitle
[9806]3776
3777    def _searchCatalog(self, session, level):
[16812]3778        if level not in (10, 999, 1000, None):
[9806]3779            start_level = 100 * (level // 100)
3780            end_level = start_level + 90
3781        else:
3782            start_level = end_level = level
3783        cat = queryUtility(ICatalog, name='students_catalog')
3784        students = cat.searchResults(
3785            current_session=(session, session),
3786            current_level=(start_level, end_level),
3787            certcode=(self.context.code, self.context.code)
3788            )
3789        hitlist = []
3790        for student in students:
3791            hitlist.append(StudentQueryResultItem(student, view=self))
3792        return hitlist
3793
3794class FilterStudentsInCoursePage(FilterStudentsInDepartmentPage):
3795    """Page that filters and lists students.
3796    """
3797    grok.context(ICourse)
[13764]3798    grok.require('waeup.viewStudent')
[9806]3799
[10024]3800    session_label = _('Session')
3801    level_label = _('Level')
3802
[9806]3803    def label(self):
[10650]3804        return 'Students registered for %s' % self.context.longtitle
[9806]3805
3806    def _searchCatalog(self, session, level):
[16812]3807        if level not in (10, 999, 1000, None):
[9806]3808            start_level = 100 * (level // 100)
3809            end_level = start_level + 90
3810        else:
3811            start_level = end_level = level
3812        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3813        coursetickets = cat.searchResults(
3814            session=(session, session),
3815            level=(start_level, end_level),
3816            code=(self.context.code, self.context.code)
3817            )
3818        hitlist = []
3819        for ticket in coursetickets:
3820            hitlist.append(StudentQueryResultItem(ticket.student, view=self))
[10039]3821        return list(set(hitlist))
[9806]3822
[13055]3823class ClearAllStudentsInDepartmentView(UtilityView, grok.View):
[11862]3824    """ Clear all students of a department in state 'clearance requested'.
3825    """
3826    grok.context(IDepartment)
3827    grok.name('clearallstudents')
3828    grok.require('waeup.clearAllStudents')
3829
3830    def update(self):
3831        cat = queryUtility(ICatalog, name='students_catalog')
3832        students = cat.searchResults(
3833            depcode=(self.context.code, self.context.code),
3834            state=(REQUESTED, REQUESTED)
3835            )
3836        num = 0
3837        for student in students:
3838            if getUtility(IStudentsUtils).clearance_disabled_message(student):
3839                continue
3840            IWorkflowInfo(student).fireTransition('clear')
3841            num += 1
3842        self.flash(_('%d students have been cleared.' % num))
3843        self.redirect(self.url(self.context))
3844        return
3845
3846    def render(self):
3847        return
3848
[16465]3849#class RemoveFlashNoticeAllStudentsInDepartmentView(UtilityView, grok.View):
3850#    """ Remove flash notices of all students in a department.
3851#    """
3852#    grok.context(IDepartment)
3853#    grok.name('removeflash')
3854#    grok.require('waeup.manageStudent')
3855
3856#    def update(self):
3857#        cat = queryUtility(ICatalog, name='students_catalog')
3858#        students = cat.searchResults(
3859#            depcode=(self.context.code, self.context.code),
3860#            )
3861#        num = 0
3862#        for student in students:
3863#            student.flash_notice = u''
3864#            num += 1
3865#        self.flash(_('%d flash notices have been removed.' % num))
3866#        self.redirect(self.url(self.context))
3867#        return
3868
3869#    def render(self):
3870#        return
3871
3872class EditFlashNoticesFormPage(KofaFormPage):
3873    """Edit all flash notices of students in a department.
[16459]3874    """
3875    grok.context(IDepartment)
[16465]3876    grok.name('edit_flash_notices')
3877    grok.template('editflashnotices')
[16459]3878    grok.require('waeup.manageStudent')
[16465]3879    form_fields = grok.AutoFields(IFlashNotice)
3880    pnav = 0
[16459]3881
[16465]3882    def label(self):
3883        return _(u'Set flash notices for all students in ${a}',
3884            mapping = {'a':self.context.longtitle})
3885
3886    @action('Save flash notices', style='primary')
3887    def save(self, *args, **data):
[16459]3888        cat = queryUtility(ICatalog, name='students_catalog')
3889        students = cat.searchResults(
3890            depcode=(self.context.code, self.context.code),
3891            )
3892        num = 0
3893        for student in students:
[16465]3894            student.flash_notice = data['flash_notice']
[16459]3895            num += 1
[16465]3896        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3897        grok.getSite().logger.info(
3898            '%s - %s - saved flash notice: %s'
3899            % (ob_class, self.context.__name__, data['flash_notice']))
3900        self.flash(_('%d flash notices have been edited.' % num))
[16459]3901        self.redirect(self.url(self.context))
3902        return
3903
[16465]3904    @action(_('Cancel'), validator=NullValidator)
3905    def cancel(self, **data):
3906        self.redirect(self.url(self.context))
[16459]3907
[10627]3908class EditScoresPage(KofaPage):
[13894]3909    """Page that allows to edit batches of scores.
[10627]3910    """
3911    grok.context(ICourse)
[10632]3912    grok.require('waeup.editScores')
[10627]3913    grok.name('edit_scores')
3914    grok.template('editscorespage')
3915    pnav = 1
[13936]3916    doclink = DOCLINK + '/students/browser.html#batch-editing-scores-by-lecturers'
[10627]3917
3918    def label(self):
[10631]3919        return '%s tickets in academic session %s' % (
[13938]3920            self.context.code, self.session_title)
[10627]3921
3922    def _searchCatalog(self, session):
3923        cat = queryUtility(ICatalog, name='coursetickets_catalog')
[15243]3924        # Attention: Also tickets of previous studycourses are found
[10627]3925        coursetickets = cat.searchResults(
3926            session=(session, session),
3927            code=(self.context.code, self.context.code)
3928            )
3929        return list(coursetickets)
3930
[13935]3931    def _extract_uploadfile(self, uploadfile):
3932        """Get a mapping of student-ids to scores.
3933
3934        The mapping is constructed by reading contents from `uploadfile`.
3935
3936        We expect uploadfile to be a regular CSV file with columns
3937        ``student_id`` and ``score`` (other cols are ignored).
3938        """
3939        result = dict()
3940        data = StringIO(uploadfile.read())  # ensure we have something seekable
3941        reader = csv.DictReader(data)
3942        for row in reader:
3943            if not 'student_id' in row or not 'score' in row:
3944                continue
3945            result[row['student_id']] = row['score']
3946        return result
3947
[14285]3948    def _update_scores(self, form):
[13935]3949        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3950        error = ''
[13936]3951        if 'UPDATE_FILE' in form:
3952            if form['uploadfile']:
3953                try:
3954                    formvals = self._extract_uploadfile(form['uploadfile'])
3955                except:
3956                    self.flash(
3957                        _('Uploaded file contains illegal data. Ignored'),
3958                        type="danger")
[14283]3959                    return False
[13936]3960            else:
[13935]3961                self.flash(
[13936]3962                    _('No file provided.'), type="danger")
[14283]3963                return False
[13936]3964        else:
3965            formvals = dict(zip(form['sids'], form['scores']))
[14285]3966        for ticket in self.editable_tickets:
[13935]3967            score = ticket.score
3968            sid = ticket.student.student_id
3969            if sid not in formvals:
3970                continue
3971            if formvals[sid] == '':
3972                score = None
3973            else:
3974                try:
3975                    score = int(formvals[sid])
3976                except ValueError:
3977                    error += '%s, ' % ticket.student.display_fullname
3978            if ticket.score != score:
3979                ticket.score = score
3980                ticket.student.__parent__.logger.info(
3981                    '%s - %s %s/%s score updated (%s)' % (
3982                        ob_class, ticket.student.student_id,
3983                        ticket.level, ticket.code, score)
3984                    )
3985        if error:
3986            self.flash(
3987                _('Error: Score(s) of following students have not been '
3988                    'updated (only integers are allowed): %s.' % error.strip(', ')),
3989                type="danger")
[14283]3990        return True
3991
[15422]3992    def _validate_results(self, form):
3993        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3994        user = get_current_principal()
3995        if user is None:
3996            usertitle = 'system'
3997        else:
3998            usertitle = getattr(user, 'public_name', None)
3999            if not usertitle:
4000                usertitle = user.title
4001        self.context.results_validated_by = usertitle
4002        self.context.results_validation_date = datetime.utcnow()
4003        self.context.results_validation_session = self.current_academic_session
4004        return
4005
4006    def _results_editable(self, results_validation_session,
4007                         current_academic_session):
4008        user = get_current_principal()
4009        prm = IPrincipalRoleManager(self.context)
4010        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
4011        if 'waeup.local.LocalStudentsManager' in roles:
4012            return True
4013        if results_validation_session \
4014            and results_validation_session >= current_academic_session:
4015            return False
4016        return True
4017
[14283]4018    def update(self,  *args, **kw):
4019        form = self.request.form
4020        self.current_academic_session = grok.getSite()[
4021            'configuration'].current_academic_session
[15629]4022        if self.context.__parent__.__parent__.score_editing_disabled \
4023            or self.context.score_editing_disabled:
[14283]4024            self.flash(_('Score editing disabled.'), type="warning")
4025            self.redirect(self.url(self.context))
[13938]4026            return
[14283]4027        if not self.current_academic_session:
4028            self.flash(_('Current academic session not set.'), type="warning")
4029            self.redirect(self.url(self.context))
4030            return
[15422]4031        vs = self.context.results_validation_session
4032        if not self._results_editable(vs, self.current_academic_session):
4033            self.flash(
4034                _('Course results have already been '
4035                  'validated and can no longer be changed.'),
4036                type="danger")
4037            self.redirect(self.url(self.context))
4038            return
[14283]4039        self.session_title = academic_sessions_vocab.getTerm(
4040            self.current_academic_session).title
4041        self.tickets = self._searchCatalog(self.current_academic_session)
4042        if not self.tickets:
4043            self.flash(_('No student found.'), type="warning")
4044            self.redirect(self.url(self.context))
4045            return
[14286]4046        self.editable_tickets = [
4047            ticket for ticket in self.tickets if ticket.editable_by_lecturer]
[15422]4048        if not 'UPDATE_TABLE' in form and not 'UPDATE_FILE' in form\
4049            and not 'VALIDATE_RESULTS' in form:
[14283]4050            return
[15422]4051        if 'VALIDATE_RESULTS' in form:
4052            if vs and vs >= self.current_academic_session:
4053                self.flash(
4054                    _('Course results have already been validated.'),
4055                    type="danger")
[16007]4056            for ticket in self.tickets:
4057                if ticket.total_score is not None:
4058                    break
4059                self.flash(
4060                    _('No score has been entered.'),
4061                    type="danger")
[15422]4062                return
4063            self._validate_results(form)
4064            self.flash(_('You successfully validated the course results.'))
4065            self.redirect(self.url(self.context))
4066            return
[14284]4067        if not self.editable_tickets:
[14283]4068            return
[14285]4069        success = self._update_scores(form)
[14283]4070        if success:
4071            self.flash(_('You successfully updated course results.'))
[10627]4072        return
4073
[13894]4074class DownloadScoresView(UtilityView, grok.View):
4075    """View that exports scores.
4076    """
4077    grok.context(ICourse)
4078    grok.require('waeup.editScores')
4079    grok.name('download_scores')
4080
[15422]4081    def _results_editable(self, results_validation_session,
4082                         current_academic_session):
4083        user = get_current_principal()
4084        prm = IPrincipalRoleManager(self.context)
4085        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
4086        if 'waeup.local.LocalStudentsManager' in roles:
4087            return True
4088        if results_validation_session \
4089            and results_validation_session >= current_academic_session:
4090            return False
4091        return True
4092
[13894]4093    def update(self):
4094        self.current_academic_session = grok.getSite()[
4095            'configuration'].current_academic_session
[15629]4096        if self.context.__parent__.__parent__.score_editing_disabled \
4097            or self.context.score_editing_disabled:
[13894]4098            self.flash(_('Score editing disabled.'), type="warning")
4099            self.redirect(self.url(self.context))
4100            return
4101        if not self.current_academic_session:
4102            self.flash(_('Current academic session not set.'), type="warning")
4103            self.redirect(self.url(self.context))
4104            return
[15422]4105        vs = self.context.results_validation_session
4106        if not self._results_editable(vs, self.current_academic_session):
4107            self.flash(
4108                _('Course results have already been '
4109                  'validated and can no longer be changed.'),
4110                type="danger")
4111            self.redirect(self.url(self.context))
4112            return
[13894]4113        site = grok.getSite()
4114        exporter = getUtility(ICSVExporter, name='lecturer')
4115        self.csv = exporter.export_filtered(site, filepath=None,
4116                                 catalog='coursetickets',
4117                                 session=self.current_academic_session,
4118                                 level=None,
4119                                 code=self.context.code)
4120        return
4121
4122    def render(self):
4123        filename = 'results_%s_%s.csv' % (
4124            self.context.code, self.current_academic_session)
4125        self.response.setHeader(
4126            'Content-Type', 'text/csv; charset=UTF-8')
4127        self.response.setHeader(
4128            'Content-Disposition:', 'attachment; filename="%s' % filename)
4129        return self.csv
4130
[13898]4131class ExportPDFScoresSlip(UtilityView, grok.View,
4132    LocalRoleAssignmentUtilityView):
4133    """Deliver a PDF slip of course tickets for a lecturer.
4134    """
4135    grok.context(ICourse)
4136    grok.name('coursetickets.pdf')
[15422]4137    grok.require('waeup.showStudents')
[13898]4138
[15426]4139    def update(self):
4140        self.current_academic_session = grok.getSite()[
4141            'configuration'].current_academic_session
4142        if not self.current_academic_session:
4143            self.flash(_('Current academic session not set.'), type="danger")
4144            self.redirect(self.url(self.context))
4145            return
4146
[15246]4147    @property
4148    def note(self):
4149        return
4150
[14314]4151    def data(self, session):
[13898]4152        cat = queryUtility(ICatalog, name='coursetickets_catalog')
[15243]4153        # Attention: Also tickets of previous studycourses are found
[13898]4154        coursetickets = cat.searchResults(
4155            session=(session, session),
4156            code=(self.context.code, self.context.code)
4157            )
[16518]4158        header = [[_('S/N'),
4159                   _('Matric No.'),
[13898]4160                   _('Reg. No.'),
4161                   _('Fullname'),
4162                   _('Status'),
4163                   _('Course of Studies'),
4164                   _('Level'),
4165                   _('Score') ],]
[13908]4166        tickets = []
[13898]4167        for ticket in list(coursetickets):
[16520]4168            row = [ticket.student.matric_number,
[13898]4169                  ticket.student.reg_number,
4170                  ticket.student.display_fullname,
4171                  ticket.student.translated_state,
4172                  ticket.student.certcode,
4173                  ticket.level,
[16505]4174                  ticket.score,
4175                  ticket.student.lastname # for sorting only
4176                  ]
[13908]4177            tickets.append(row)
[16520]4178        data = sorted(tickets, key=lambda value: value[7])
4179        sn = 1
4180        for d in data:
4181            d.pop(7)
4182            d.insert(0, sn)
[16518]4183            sn += 1
[16505]4184        return header + data, None
[13898]4185
4186    def render(self):
4187        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
4188                     if i['local_role'] == 'waeup.local.Lecturer']
[15865]4189        lecturers = sorted(lecturers)
[13898]4190        lecturers =  ', '.join(lecturers)
4191        students_utils = getUtility(IStudentsUtils)
4192        return students_utils.renderPDFCourseticketsOverview(
[15426]4193            self, 'coursetickets', self.current_academic_session,
4194            self.data(self.current_academic_session), lecturers,
[15423]4195            'landscape', 90, self.note)
[13898]4196
[15423]4197class ExportAttendanceSlip(UtilityView, grok.View,
4198    LocalRoleAssignmentUtilityView):
4199    """Deliver a PDF slip of course tickets in attendance sheet format.
4200    """
4201    grok.context(ICourse)
4202    grok.name('attendance.pdf')
4203    grok.require('waeup.showStudents')
4204
[15426]4205    def update(self):
4206        self.current_academic_session = grok.getSite()[
4207            'configuration'].current_academic_session
4208        if not self.current_academic_session:
4209            self.flash(_('Current academic session not set.'), type="danger")
4210            self.redirect(self.url(self.context))
4211            return
4212
[15423]4213    @property
4214    def note(self):
4215        return
4216
4217    def data(self, session):
4218        cat = queryUtility(ICatalog, name='coursetickets_catalog')
4219        # Attention: Also tickets of previous studycourses are found
4220        coursetickets = cat.searchResults(
4221            session=(session, session),
4222            code=(self.context.code, self.context.code)
4223            )
[15526]4224        header = [[_('S/N'),
[15541]4225                   _('Matric No.'),
[15538]4226                   _('Name'),
[15423]4227                   _('Level'),
[15542]4228                   _('Course of\nStudies'),
[15423]4229                   _('Booklet No.'),
4230                   _('Signature'),
4231                   ],]
4232        tickets = []
[15526]4233        sn = 1
4234        ctlist = sorted(list(coursetickets),
[16518]4235                        key=lambda value: str(value.student.faccode) +
4236                                          str(value.student.depcode) +
4237                                          str(value.student.certcode) +
[15535]4238                                          str(value.student.matric_number))
[15642]4239        # In AAUE only editable appear on the attendance sheet. Hopefully
4240        # this holds for other universities too.
4241        editable_tickets = [ticket for ticket in ctlist
4242            if ticket.editable_by_lecturer]
4243        for ticket in editable_tickets:
[15626]4244            name = textwrap.fill(ticket.student.display_fullname, 20)
[15526]4245            row = [sn,
[15423]4246                  ticket.student.matric_number,
[15624]4247                  name,
[15423]4248                  ticket.level,
4249                  ticket.student.certcode,
[15624]4250                  20 * ' ',
[15544]4251                  27 * ' ',
[15423]4252                  ]
4253            tickets.append(row)
[15526]4254            sn += 1
4255        return header + tickets, None
[15423]4256
4257    def render(self):
4258        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
4259                     if i['local_role'] == 'waeup.local.Lecturer']
4260        lecturers =  ', '.join(lecturers)
4261        students_utils = getUtility(IStudentsUtils)
4262        return students_utils.renderPDFCourseticketsOverview(
[15426]4263            self, 'attendance', self.current_academic_session,
4264            self.data(self.current_academic_session),
[15526]4265            lecturers, '', 65, self.note)
[15423]4266
[9813]4267class ExportJobContainerOverview(KofaPage):
[9835]4268    """Page that lists active student data export jobs and provides links
4269    to discard or download CSV files.
4270
[9797]4271    """
[9813]4272    grok.context(VirtualExportJobContainer)
[9797]4273    grok.require('waeup.showStudents')
4274    grok.name('index.html')
4275    grok.template('exportjobsindex')
[9813]4276    label = _('Student Data Exports')
[9797]4277    pnav = 1
[12910]4278    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
[9797]4279
[15545]4280    def update(self, CREATE1=None, CREATE2=None, DISCARD=None, job_id=None):
4281        if CREATE1:
[9836]4282            self.redirect(self.url('@@exportconfig'))
[9797]4283            return
[15545]4284        if CREATE2:
4285            self.redirect(self.url('@@exportselected'))
4286            return
[9797]4287        if DISCARD and job_id:
4288            entry = self.context.entry_from_job_id(job_id)
4289            self.context.delete_export_entry(entry)
[9836]4290            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4291            self.context.logger.info(
4292                '%s - discarded: job_id=%s' % (ob_class, job_id))
[9819]4293            self.flash(_('Discarded export') + ' %s' % job_id)
[9822]4294        self.entries = doll_up(self, user=self.request.principal.id)
[9797]4295        return
4296
[9833]4297class ExportJobContainerJobConfig(KofaPage):
[9797]4298    """Page that configures a students export job.
[9833]4299
4300    This is a baseclass.
[9797]4301    """
[9833]4302    grok.baseclass()
[9797]4303    grok.require('waeup.showStudents')
[9836]4304    grok.template('exportconfig')
[9833]4305    label = _('Configure student data export')
[9797]4306    pnav = 1
[9835]4307    redirect_target = ''
[12901]4308    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
[9797]4309
4310    def _set_session_values(self):
4311        vocab_terms = academic_sessions_vocab.by_value.values()
[15042]4312        self.sessions = [(_('All Sessions'), 'all')]
4313        self.sessions += sorted(
[9797]4314            [(x.title, x.token) for x in vocab_terms], reverse=True)
4315        return
4316
4317    def _set_level_values(self):
4318        vocab_terms = course_levels.by_value.values()
[15042]4319        self.levels = [(_('All Levels'), 'all')]
4320        self.levels += sorted(
[9797]4321            [(x.title, x.token) for x in vocab_terms])
4322        return
4323
[15546]4324    def _set_semesters_values(self):
4325        utils = getUtility(IKofaUtils)
4326        self.semesters =[(_('All Semesters'), 'all')]
4327        self.semesters += sorted([(value, key) for key, value in
4328                      utils.SEMESTER_DICT.items()])
4329        return
4330
[9803]4331    def _set_mode_values(self):
4332        utils = getUtility(IKofaUtils)
[15042]4333        self.modes =[(_('All Modes'), 'all')]
4334        self.modes += sorted([(value, key) for key, value in
[9838]4335                      utils.STUDY_MODES_DICT.items()])
[9803]4336        return
4337
[15042]4338    def _set_paycat_values(self):
4339        utils = getUtility(IKofaUtils)
4340        self.paycats =[(_('All Payment Categories'), 'all')]
4341        self.paycats += sorted([(value, key) for key, value in
4342                      utils.PAYMENT_CATEGORIES.items()])
4343        return
4344
[9804]4345    def _set_exporter_values(self):
[17823]4346        kofa_utils = getUtility(IKofaUtils)
4347        exporters = kofa_utils.collect_exporters(self.context)
4348        if exporters:
[10279]4349            self.exporters = exporters
[10248]4350            return
[17823]4351        exporters = []
[12104]4352        STUDENT_EXPORTER_NAMES = getUtility(
4353            IStudentsUtils).STUDENT_EXPORTER_NAMES
4354        for name in STUDENT_EXPORTER_NAMES:
[9804]4355            util = getUtility(ICSVExporter, name=name)
4356            exporters.append((util.title, name),)
4357        self.exporters = exporters
[10247]4358        return
[9804]4359
[9833]4360    @property
[12632]4361    def faccode(self):
4362        return None
4363
4364    @property
[9833]4365    def depcode(self):
4366        return None
4367
[9842]4368    @property
4369    def certcode(self):
4370        return None
4371
[9804]4372    def update(self, START=None, session=None, level=None, mode=None,
[15042]4373               payments_start=None, payments_end=None, ct_level=None,
[15546]4374               ct_session=None, ct_semester=None, paycat=None,
[15918]4375               paysession=None, level_session=None, exporter=None):
[9797]4376        self._set_session_values()
4377        self._set_level_values()
[9803]4378        self._set_mode_values()
[15042]4379        self._set_paycat_values()
[9804]4380        self._set_exporter_values()
[15546]4381        self._set_semesters_values()
[9797]4382        if START is None:
4383            return
[13201]4384        ena = exports_not_allowed(self)
4385        if ena:
4386            self.flash(ena, type='danger')
[13198]4387            return
[11730]4388        if payments_start or payments_end:
4389            date_format = '%d/%m/%Y'
4390            try:
[13935]4391                datetime.strptime(payments_start, date_format)
4392                datetime.strptime(payments_end, date_format)
[11730]4393            except ValueError:
4394                self.flash(_('Payment dates do not match format d/m/Y.'),
4395                           type="danger")
4396                return
[9797]4397        if session == 'all':
4398            session=None
4399        if level == 'all':
4400            level = None
[9803]4401        if mode == 'all':
4402            mode = None
[12632]4403        if (mode,
4404            level,
4405            session,
4406            self.faccode,
4407            self.depcode,
4408            self.certcode) == (None, None, None, None, None, None):
[9933]4409            # Export all students including those without certificate
[15042]4410            job_id = self.context.start_export_job(exporter,
4411                                          self.request.principal.id,
4412                                          payments_start = payments_start,
4413                                          payments_end = payments_end,
4414                                          paycat=paycat,
[15055]4415                                          paysession=paysession,
[15042]4416                                          ct_level = ct_level,
4417                                          ct_session = ct_session,
[15546]4418                                          ct_semester = ct_semester,
[15918]4419                                          level_session=level_session,
[15042]4420                                          )
[9933]4421        else:
[15042]4422            job_id = self.context.start_export_job(exporter,
4423                                          self.request.principal.id,
4424                                          current_session=session,
4425                                          current_level=level,
4426                                          current_mode=mode,
4427                                          faccode=self.faccode,
4428                                          depcode=self.depcode,
4429                                          certcode=self.certcode,
4430                                          payments_start = payments_start,
4431                                          payments_end = payments_end,
4432                                          paycat=paycat,
[15055]4433                                          paysession=paysession,
[15042]4434                                          ct_level = ct_level,
[15546]4435                                          ct_session = ct_session,
[15918]4436                                          ct_semester = ct_semester,
4437                                          level_session=level_session,)
[9836]4438        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4439        self.context.logger.info(
[15918]4440            '%s - exported: %s (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s), job_id=%s'
[12632]4441            % (ob_class, exporter, session, level, mode, self.faccode,
[15042]4442            self.depcode, self.certcode, payments_start, payments_end,
[15918]4443            ct_level, ct_session, paycat, paysession, level_session, job_id))
[9833]4444        self.flash(_('Export started for students with') +
4445                   ' current_session=%s, current_level=%s, study_mode=%s' % (
4446                   session, level, mode))
[9835]4447        self.redirect(self.url(self.redirect_target))
[9797]4448        return
4449
[9822]4450class ExportJobContainerDownload(ExportCSVView):
[9835]4451    """Page that downloads a students export csv file.
4452
[9797]4453    """
[9813]4454    grok.context(VirtualExportJobContainer)
[9797]4455    grok.require('waeup.showStudents')
[9833]4456
4457class DatacenterExportJobContainerJobConfig(ExportJobContainerJobConfig):
4458    """Page that configures a students export job in datacenter.
4459
4460    """
[15545]4461    grok.name('exportconfig')
[9833]4462    grok.context(IDataCenter)
[9835]4463    redirect_target = '@@export'
[9833]4464
[12518]4465class DatacenterExportJobContainerSelectStudents(ExportJobContainerJobConfig):
4466    """Page that configures a students export job in datacenter.
4467
4468    """
4469    grok.name('exportselected')
4470    grok.context(IDataCenter)
4471    redirect_target = '@@export'
4472    grok.template('exportselected')
4473
4474    def update(self, START=None, students=None, exporter=None):
4475        self._set_exporter_values()
4476        if START is None:
4477            return
[13201]4478        ena = exports_not_allowed(self)
4479        if ena:
4480            self.flash(ena, type='danger')
[13200]4481            return
[12518]4482        try:
4483            ids = students.replace(',', ' ').split()
4484        except:
4485            self.flash(sys.exc_info()[1])
4486            self.redirect(self.url(self.redirect_target))
4487            return
4488        job_id = self.context.start_export_job(
4489            exporter, self.request.principal.id, selected=ids)
4490        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4491        self.context.logger.info(
4492            '%s - selected students exported: %s, job_id=%s' %
4493            (ob_class, exporter, job_id))
4494        self.flash(_('Export of selected students started.'))
4495        self.redirect(self.url(self.redirect_target))
4496        return
4497
[15545]4498class FacultiesExportJobContainerJobConfig(
4499    DatacenterExportJobContainerJobConfig):
[10247]4500    """Page that configures a students export job in facultiescontainer.
4501
4502    """
4503    grok.context(VirtualFacultiesExportJobContainer)
[15545]4504    redirect_target = ''
[10247]4505
[15545]4506class FacultiesExportJobContainerSelectStudents(
4507    DatacenterExportJobContainerSelectStudents):
4508    """Page that configures a students export job in facultiescontainer.
[12632]4509
[15545]4510    """
4511    grok.context(VirtualFacultiesExportJobContainer)
4512    redirect_target = ''
4513
4514class FacultyExportJobContainerJobConfig(DatacenterExportJobContainerJobConfig):
[12632]4515    """Page that configures a students export job in faculties.
4516
4517    """
4518    grok.context(VirtualFacultyExportJobContainer)
[15545]4519    redirect_target = ''
[12632]4520
4521    @property
4522    def faccode(self):
4523        return self.context.__parent__.code
4524
[15545]4525class DepartmentExportJobContainerJobConfig(
4526    DatacenterExportJobContainerJobConfig):
[9833]4527    """Page that configures a students export job in departments.
4528
4529    """
4530    grok.context(VirtualDepartmentExportJobContainer)
[15545]4531    redirect_target = ''
[9833]4532
4533    @property
4534    def depcode(self):
[9835]4535        return self.context.__parent__.code
[9842]4536
[15545]4537class CertificateExportJobContainerJobConfig(
4538    DatacenterExportJobContainerJobConfig):
[9842]4539    """Page that configures a students export job for certificates.
4540
4541    """
4542    grok.context(VirtualCertificateExportJobContainer)
[9843]4543    grok.template('exportconfig_certificate')
[15545]4544    redirect_target = ''
[9842]4545
4546    @property
4547    def certcode(self):
4548        return self.context.__parent__.code
[9843]4549
[15545]4550class CourseExportJobContainerJobConfig(
4551    DatacenterExportJobContainerJobConfig):
[9843]4552    """Page that configures a students export job for courses.
4553
4554    In contrast to department or certificate student data exports the
4555    coursetickets_catalog is searched here. Therefore the update
4556    method from the base class is customized.
4557    """
4558    grok.context(VirtualCourseExportJobContainer)
4559    grok.template('exportconfig_course')
[15545]4560    redirect_target = ''
[9843]4561
4562    def _set_exporter_values(self):
[13894]4563        # We provide only the 'coursetickets' and 'lecturer' exporter
4564        # but can add more.
[9843]4565        exporters = []
[13894]4566        for name in ('coursetickets', 'lecturer'):
[9843]4567            util = getUtility(ICSVExporter, name=name)
4568            exporters.append((util.title, name),)
4569        self.exporters = exporters
[15545]4570        return
[9843]4571
[16412]4572    # Disabled on 10/03/21
4573    #def _set_session_values(self):
4574    #    # We allow only current academic session
4575    #    academic_session = grok.getSite()['configuration'].current_academic_session
4576    #    if not academic_session:
4577    #        self.sessions = []
4578    #        return
4579    #    x = academic_sessions_vocab.getTerm(academic_session)
4580    #    self.sessions = [(x.title, x.token)]
4581    #    return
4582
[13766]4583    def _set_session_values(self):
[16412]4584        vocab_terms = academic_sessions_vocab.by_value.values()
4585        self.sessions = sorted(
4586            [(x.title, x.token) for x in vocab_terms], reverse=True)
4587        self.sessions += [('All Sessions', 'all')]
[13766]4588        return
4589
[9843]4590    def update(self, START=None, session=None, level=None, mode=None,
4591               exporter=None):
[15545]4592        if not checkPermission('waeup.exportData', self.context):
4593            self.flash(_('Not permitted.'), type='danger')
4594            self.redirect(self.url(self.context))
4595            return
[9843]4596        self._set_session_values()
4597        self._set_level_values()
4598        self._set_mode_values()
4599        self._set_exporter_values()
[16412]4600        # Disabled on 10/03/21
4601        #if not self.sessions:
4602        #    self.flash(
4603        #        _('Academic session not set. '
4604        #          'Please contact the administrator.'),
4605        #        type='danger')
4606        #    self.redirect(self.url(self.context))
4607        #    return
[9843]4608        if START is None:
4609            return
[13201]4610        ena = exports_not_allowed(self)
4611        if ena:
4612            self.flash(ena, type='danger')
[13200]4613            return
[9843]4614        if session == 'all':
[10016]4615            session = None
[9843]4616        if level == 'all':
4617            level = None
4618        job_id = self.context.start_export_job(exporter,
4619                                      self.request.principal.id,
4620                                      # Use a different catalog and
4621                                      # pass different keywords than
4622                                      # for the (default) students_catalog
[9845]4623                                      catalog='coursetickets',
[9843]4624                                      session=session,
4625                                      level=level,
4626                                      code=self.context.__parent__.code)
4627        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4628        self.context.logger.info(
4629            '%s - exported: %s (%s, %s, %s), job_id=%s'
4630            % (ob_class, exporter, session, level,
4631            self.context.__parent__.code, job_id))
4632        self.flash(_('Export started for course tickets with') +
4633                   ' level_session=%s, level=%s' % (
4634                   session, level))
4635        self.redirect(self.url(self.redirect_target))
[13935]4636        return
Note: See TracBrowser for help on using the repository browser.