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

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

Add 'Modules Level'.

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