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

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

Insert serial number after sorting.

  • Property svn:keywords set to Id
File size: 171.3 KB
RevLine 
[7191]1## $Id: browser.py 16520 2021-06-29 07:35:39Z 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):
[7114]2926    """ View to upload files by student
2927    """
2928    grok.context(IStudent)
2929    grok.name('change_portrait')
[7127]2930    grok.require('waeup.uploadStudentFile')
[7114]2931    grok.template('filesuploadpage')
[7723]2932    label = _('Upload portrait')
[7114]2933    pnav = 4
2934
[7133]2935    def update(self):
[13129]2936        PORTRAIT_CHANGE_STATES = getUtility(IStudentsUtils).PORTRAIT_CHANGE_STATES
2937        if self.context.student.state not in PORTRAIT_CHANGE_STATES:
[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
[7819]2944class StartClearancePage(KofaPage):
[6770]2945    grok.context(IStudent)
2946    grok.name('start_clearance')
2947    grok.require('waeup.handleStudent')
2948    grok.template('enterpin')
[7723]2949    label = _('Start clearance')
[6770]2950    ac_prefix = 'CLR'
2951    notice = ''
2952    pnav = 4
[7723]2953    buttonname = _('Start clearance now')
[9952]2954    with_ac = True
[6770]2955
[7133]2956    @property
2957    def all_required_fields_filled(self):
[13349]2958        if not self.context.email:
[13350]2959            return _("Email address is missing."), 'edit_base'
[13349]2960        if not self.context.phone:
[13350]2961            return _("Phone number is missing."), 'edit_base'
[13349]2962        return
[7133]2963
2964    @property
2965    def portrait_uploaded(self):
2966        store = getUtility(IExtFileStore)
2967        if store.getFileByContext(self.context, attr=u'passport.jpg'):
2968            return True
2969        return False
2970
[6770]2971    def update(self, SUBMIT=None):
[7671]2972        if not self.context.state == ADMITTED:
[11254]2973            self.flash(_("Wrong state"), type="warning")
[6936]2974            self.redirect(self.url(self.context))
2975            return
[7133]2976        if not self.portrait_uploaded:
[11254]2977            self.flash(_("No portrait uploaded."), type="warning")
[7133]2978            self.redirect(self.url(self.context, 'change_portrait'))
2979            return
[13350]2980        if self.all_required_fields_filled:
2981            arf_warning = self.all_required_fields_filled[0]
2982            arf_redirect = self.all_required_fields_filled[1]
[13349]2983            self.flash(arf_warning, type="warning")
[13350]2984            self.redirect(self.url(self.context, arf_redirect))
[7133]2985            return
[9952]2986        if self.with_ac:
2987            self.ac_series = self.request.form.get('ac_series', None)
2988            self.ac_number = self.request.form.get('ac_number', None)
[6770]2989        if SUBMIT is None:
2990            return
[9952]2991        if self.with_ac:
2992            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2993            code = get_access_code(pin)
2994            if not code:
[11254]2995                self.flash(_('Activation code is invalid.'), type="warning")
[9952]2996                return
2997            if code.state == USED:
[11254]2998                self.flash(_('Activation code has already been used.'),
2999                           type="warning")
[9952]3000                return
3001            # Mark pin as used (this also fires a pin related transition)
3002            # and fire transition start_clearance
3003            comment = _(u"invalidated")
3004            # Here we know that the ac is in state initialized so we do not
3005            # expect an exception, but the owner might be different
3006            if not invalidate_accesscode(pin, comment, self.context.student_id):
[11254]3007                self.flash(_('You are not the owner of this access code.'),
3008                           type="warning")
[9952]3009                return
3010            self.context.clr_code = pin
[6770]3011        IWorkflowInfo(self.context).fireTransition('start_clearance')
[7723]3012        self.flash(_('Clearance process has been started.'))
[6770]3013        self.redirect(self.url(self.context,'cedit'))
3014        return
3015
[6695]3016class StudentClearanceEditFormPage(StudentClearanceManageFormPage):
3017    """ View to edit student clearance data by student
3018    """
3019    grok.context(IStudent)
3020    grok.name('cedit')
3021    grok.require('waeup.handleStudent')
[7723]3022    label = _('Edit clearance data')
[6718]3023
[7993]3024    @property
3025    def form_fields(self):
[8472]3026        if self.context.is_postgrad:
[8974]3027            form_fields = grok.AutoFields(IPGStudentClearance).omit(
[13103]3028                'clr_code', 'officer_comment')
[7993]3029        else:
[8974]3030            form_fields = grok.AutoFields(IUGStudentClearance).omit(
[13103]3031                'clr_code', 'officer_comment')
[7993]3032        return form_fields
3033
[6718]3034    def update(self):
3035        if self.context.clearance_locked:
[7145]3036            emit_lock_message(self)
[6718]3037            return
3038        return super(StudentClearanceEditFormPage, self).update()
[6719]3039
[7723]3040    @action(_('Save'), style='primary')
[6722]3041    def save(self, **data):
3042        self.applyData(self.context, **data)
[7723]3043        self.flash(_('Clearance form has been saved.'))
[6722]3044        return
3045
[7253]3046    def dataNotComplete(self):
[7642]3047        """To be implemented in the customization package.
3048        """
[7253]3049        return False
3050
[14102]3051    @action(_('Save and request clearance'), style='primary',
3052            warning=_('You can not edit your data after '
3053            'requesting clearance. You really want to request clearance now?'))
[7186]3054    def requestClearance(self, **data):
[6722]3055        self.applyData(self.context, **data)
[7253]3056        if self.dataNotComplete():
[11254]3057            self.flash(self.dataNotComplete(), type="warning")
[7253]3058            return
[7723]3059        self.flash(_('Clearance form has been saved.'))
[9021]3060        if self.context.clr_code:
3061            self.redirect(self.url(self.context, 'request_clearance'))
3062        else:
3063            # We bypass the request_clearance page if student
3064            # has been imported in state 'clearance started' and
3065            # no clr_code was entered before.
3066            state = IWorkflowState(self.context).getState()
3067            if state != CLEARANCE:
3068                # This shouldn't happen, but the application officer
3069                # might have forgotten to lock the form after changing the state
[11254]3070                self.flash(_('This form cannot be submitted. Wrong state!'),
3071                           type="danger")
[9021]3072                return
3073            IWorkflowInfo(self.context).fireTransition('request_clearance')
3074            self.flash(_('Clearance has been requested.'))
3075            self.redirect(self.url(self.context))
[6722]3076        return
3077
[7819]3078class RequestClearancePage(KofaPage):
[6769]3079    grok.context(IStudent)
3080    grok.name('request_clearance')
3081    grok.require('waeup.handleStudent')
3082    grok.template('enterpin')
[7723]3083    label = _('Request clearance')
3084    notice = _('Enter the CLR access code used for starting clearance.')
[6769]3085    ac_prefix = 'CLR'
3086    pnav = 4
[7723]3087    buttonname = _('Request clearance now')
[9952]3088    with_ac = True
[6769]3089
3090    def update(self, SUBMIT=None):
[9952]3091        if self.with_ac:
3092            self.ac_series = self.request.form.get('ac_series', None)
3093            self.ac_number = self.request.form.get('ac_number', None)
[6769]3094        if SUBMIT is None:
3095            return
[9952]3096        if self.with_ac:
3097            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3098            if self.context.clr_code and self.context.clr_code != pin:
[11254]3099                self.flash(_("This isn't your CLR access code."), type="danger")
[9952]3100                return
[6769]3101        state = IWorkflowState(self.context).getState()
3102        if state != CLEARANCE:
[9021]3103            # This shouldn't happen, but the application officer
3104            # might have forgotten to lock the form after changing the state
[11254]3105            self.flash(_('This form cannot be submitted. Wrong state!'),
3106                       type="danger")
[6769]3107            return
3108        IWorkflowInfo(self.context).fireTransition('request_clearance')
[7723]3109        self.flash(_('Clearance has been requested.'))
[6769]3110        self.redirect(self.url(self.context))
[6789]3111        return
[6806]3112
[8471]3113class StartSessionPage(KofaPage):
[6944]3114    grok.context(IStudentStudyCourse)
[8471]3115    grok.name('start_session')
[6944]3116    grok.require('waeup.handleStudent')
3117    grok.template('enterpin')
[8471]3118    label = _('Start session')
[6944]3119    ac_prefix = 'SFE'
3120    notice = ''
3121    pnav = 4
[8471]3122    buttonname = _('Start now')
[9952]3123    with_ac = True
[6944]3124
3125    def update(self, SUBMIT=None):
[9139]3126        if not self.context.is_current:
3127            emit_lock_message(self)
3128            return
3129        super(StartSessionPage, self).update()
[8471]3130        if not self.context.next_session_allowed:
[11254]3131            self.flash(_("You are not entitled to start session."),
3132                       type="warning")
[6944]3133            self.redirect(self.url(self.context))
3134            return
[9952]3135        if self.with_ac:
3136            self.ac_series = self.request.form.get('ac_series', None)
3137            self.ac_number = self.request.form.get('ac_number', None)
[6944]3138        if SUBMIT is None:
3139            return
[9952]3140        if self.with_ac:
3141            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3142            code = get_access_code(pin)
3143            if not code:
[11254]3144                self.flash(_('Activation code is invalid.'), type="warning")
[6944]3145                return
[9952]3146            # Mark pin as used (this also fires a pin related transition)
3147            if code.state == USED:
[11254]3148                self.flash(_('Activation code has already been used.'),
3149                           type="warning")
[9952]3150                return
3151            else:
3152                comment = _(u"invalidated")
3153                # Here we know that the ac is in state initialized so we do not
3154                # expect an error, but the owner might be different
3155                if not invalidate_accesscode(
3156                    pin,comment,self.context.student.student_id):
[11254]3157                    self.flash(_('You are not the owner of this access code.'),
3158                               type="warning")
[9952]3159                    return
[9637]3160        try:
3161            if self.context.student.state == CLEARED:
3162                IWorkflowInfo(self.context.student).fireTransition(
3163                    'pay_first_school_fee')
3164            elif self.context.student.state == RETURNING:
3165                IWorkflowInfo(self.context.student).fireTransition(
3166                    'pay_school_fee')
3167            elif self.context.student.state == PAID:
3168                IWorkflowInfo(self.context.student).fireTransition(
3169                    'pay_pg_fee')
3170        except ConstraintNotSatisfied:
[11254]3171            self.flash(_('An error occurred, please contact the system administrator.'),
3172                       type="danger")
[9637]3173            return
[8471]3174        self.flash(_('Session started.'))
[6944]3175        self.redirect(self.url(self.context))
3176        return
3177
[7819]3178class AddStudyLevelFormPage(KofaEditFormPage):
[6806]3179    """ Page for students to add current study levels
3180    """
3181    grok.context(IStudentStudyCourse)
3182    grok.name('add')
3183    grok.require('waeup.handleStudent')
3184    grok.template('studyleveladdpage')
3185    form_fields = grok.AutoFields(IStudentStudyCourse)
3186    pnav = 4
3187
3188    @property
3189    def label(self):
3190        studylevelsource = StudyLevelSource().factory
3191        code = self.context.current_level
3192        title = studylevelsource.getTitle(self.context, code)
[7723]3193        return _('Add current level ${a}', mapping = {'a':title})
[6806]3194
3195    def update(self):
[15163]3196        if not self.context.is_current \
3197            or self.context.student.studycourse_locked:
[9139]3198            emit_lock_message(self)
3199            return
[8736]3200        if self.context.student.state != PAID:
[7145]3201            emit_lock_message(self)
[6806]3202            return
[11254]3203        code = self.context.current_level
3204        if code is None:
3205            self.flash(_('Your data are incomplete'), type="danger")
3206            self.redirect(self.url(self.context))
3207            return
[6806]3208        super(AddStudyLevelFormPage, self).update()
3209        return
3210
[7723]3211    @action(_('Create course list now'), style='primary')
[6806]3212    def addStudyLevel(self, **data):
[8323]3213        studylevel = createObject(u'waeup.StudentStudyLevel')
[6806]3214        studylevel.level = self.context.current_level
3215        studylevel.level_session = self.context.current_session
3216        try:
3217            self.context.addStudentStudyLevel(
3218                self.context.certificate,studylevel)
3219        except KeyError:
[11254]3220            self.flash(_('This level exists.'), type="warning")
[13773]3221            self.redirect(self.url(self.context))
3222            return
[9467]3223        except RequiredMissing:
[13773]3224            self.flash(_('Your data are incomplete.'), type="danger")
3225            self.redirect(self.url(self.context))
3226            return
3227        self.flash(_('You successfully created a new course list.'))
3228        self.redirect(self.url(self.context, str(studylevel.level)))
[6806]3229        return
[6808]3230
[7819]3231class StudyLevelEditFormPage(KofaEditFormPage):
[6808]3232    """ Page to edit the student study level data by students
3233    """
3234    grok.context(IStudentStudyLevel)
3235    grok.name('edit')
[9924]3236    grok.require('waeup.editStudyLevel')
[6808]3237    grok.template('studyleveleditpage')
3238    pnav = 4
[12473]3239    placeholder = _('Enter valid course code')
[6808]3240
[9895]3241    def update(self, ADD=None, course=None):
[9139]3242        if not self.context.__parent__.is_current:
3243            emit_lock_message(self)
3244            return
[9257]3245        if self.context.student.state != PAID or \
3246            not self.context.is_current_level:
[7539]3247            emit_lock_message(self)
3248            return
[6808]3249        super(StudyLevelEditFormPage, self).update()
[9895]3250        if ADD is not None:
3251            if not course:
[11254]3252                self.flash(_('No valid course code entered.'), type="warning")
[9895]3253                return
3254            cat = queryUtility(ICatalog, name='courses_catalog')
3255            result = cat.searchResults(code=(course, course))
3256            if len(result) != 1:
[11254]3257                self.flash(_('Course not found.'), type="warning")
[9895]3258                return
3259            course = list(result)[0]
[15970]3260            if course.former_course:
3261                self.flash(_('Former courses can\'t be added.'), type="warning")
3262                return
[9895]3263            addCourseTicket(self, course)
[6808]3264        return
3265
3266    @property
3267    def label(self):
[7833]3268        # Here we know that the cookie has been set
3269        lang = self.request.cookies.get('kofa.language')
[7811]3270        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]3271            target_language=lang)
[8920]3272        return _('Edit course list of ${a}',
[7723]3273            mapping = {'a':level_title})
[6808]3274
3275    @property
[8921]3276    def translated_values(self):
3277        return translated_values(self)
3278
[9280]3279    def _delCourseTicket(self, **data):
[6808]3280        form = self.request.form
[9701]3281        if 'val_id' in form:
[6808]3282            child_id = form['val_id']
3283        else:
[11254]3284            self.flash(_('No ticket selected.'), type="warning")
[6808]3285            self.redirect(self.url(self.context, '@@edit'))
3286            return
3287        if not isinstance(child_id, list):
3288            child_id = [child_id]
3289        deleted = []
3290        for id in child_id:
[6940]3291            # Students are not allowed to remove core tickets
[9700]3292            if id in self.context and \
3293                self.context[id].removable_by_student:
[7723]3294                del self.context[id]
3295                deleted.append(id)
[6808]3296        if len(deleted):
[7723]3297            self.flash(_('Successfully removed: ${a}',
3298                mapping = {'a':', '.join(deleted)}))
[9332]3299            self.context.writeLogMessage(
[9924]3300                self,'removed: %s at %s' %
3301                (', '.join(deleted), self.context.level))
[6808]3302        self.redirect(self.url(self.context, u'@@edit'))
3303        return
3304
[9280]3305    @jsaction(_('Remove selected tickets'))
3306    def delCourseTicket(self, **data):
3307        self._delCourseTicket(**data)
3308        return
3309
[14684]3310    def _updateTickets(self, **data):
3311        cat = queryUtility(ICatalog, name='courses_catalog')
3312        invalidated = list()
3313        for value in self.context.values():
3314            result = cat.searchResults(code=(value.code, value.code))
3315            if len(result) != 1:
3316                course = None
3317            else:
3318                course = list(result)[0]
3319            invalid = self.context.updateCourseTicket(value, course)
3320            if invalid:
3321                invalidated.append(invalid)
3322        if invalidated:
3323            invalidated_string = ', '.join(invalidated)
3324            self.context.writeLogMessage(
3325                self, 'course tickets invalidated: %s' % invalidated_string)
3326        self.flash(_('All course tickets updated.'))
3327        return
3328
3329    @action(_('Update all tickets'),
3330        tooltip=_('Update all course parameters including course titles.'))
3331    def updateTickets(self, **data):
3332        self._updateTickets(**data)
3333        return
3334
[9280]3335    def _registerCourses(self, **data):
[10155]3336        if self.context.student.is_postgrad and \
3337            not self.context.student.is_special_postgrad:
[9252]3338            self.flash(_(
3339                "You are a postgraduate student, "
[11254]3340                "your course list can't bee registered."), type="warning")
[9252]3341            self.redirect(self.url(self.context))
3342            return
[9830]3343        students_utils = getUtility(IStudentsUtils)
[14584]3344        warning = students_utils.warnCreditsOOR(self.context)
3345        if warning:
3346            self.flash(warning, type="warning")
[8642]3347            return
[14247]3348        msg = self.context.course_registration_forbidden
3349        if msg:
3350            self.flash(msg, type="warning")
[13031]3351            return
[8736]3352        IWorkflowInfo(self.context.student).fireTransition(
[7642]3353            'register_courses')
[7723]3354        self.flash(_('Course list has been registered.'))
[6810]3355        self.redirect(self.url(self.context))
3356        return
3357
[12474]3358    @action(_('Register course list'), style='primary',
3359        warning=_('You can not edit your course list after registration.'
3360            ' You really want to register?'))
[9280]3361    def registerCourses(self, **data):
3362        self._registerCourses(**data)
3363        return
3364
[6808]3365class CourseTicketAddFormPage2(CourseTicketAddFormPage):
3366    """Add a course ticket by student.
3367    """
3368    grok.name('ctadd')
3369    grok.require('waeup.handleStudent')
[9420]3370    form_fields = grok.AutoFields(ICourseTicketAdd)
[6808]3371
[7539]3372    def update(self):
[9257]3373        if self.context.student.state != PAID or \
3374            not self.context.is_current_level:
[7539]3375            emit_lock_message(self)
3376            return
3377        super(CourseTicketAddFormPage2, self).update()
3378        return
3379
[7723]3380    @action(_('Add course ticket'))
[6808]3381    def addCourseTicket(self, **data):
[7642]3382        # Safety belt
[8736]3383        if self.context.student.state != PAID:
[7539]3384            return
[6808]3385        course = data['course']
[15970]3386        if course.former_course:
3387            self.flash(_('Former courses can\'t be added.'), type="warning")
3388            return
[9895]3389        success = addCourseTicket(self, course)
3390        if success:
3391            self.redirect(self.url(self.context, u'@@edit'))
[6808]3392        return
[7369]3393
[7819]3394class SetPasswordPage(KofaPage):
3395    grok.context(IKofaObject)
[7660]3396    grok.name('setpassword')
3397    grok.require('waeup.Anonymous')
3398    grok.template('setpassword')
[7723]3399    label = _('Set password for first-time login')
[7660]3400    ac_prefix = 'PWD'
3401    pnav = 0
[7738]3402    set_button = _('Set')
[7660]3403
3404    def update(self, SUBMIT=None):
3405        self.reg_number = self.request.form.get('reg_number', None)
3406        self.ac_series = self.request.form.get('ac_series', None)
3407        self.ac_number = self.request.form.get('ac_number', None)
3408
3409        if SUBMIT is None:
3410            return
3411        hitlist = search(query=self.reg_number,
3412            searchtype='reg_number', view=self)
3413        if not hitlist:
[11254]3414            self.flash(_('No student found.'), type="warning")
[7660]3415            return
3416        if len(hitlist) != 1:   # Cannot happen but anyway
[11254]3417            self.flash(_('More than one student found.'), type="warning")
[7660]3418            return
3419        student = hitlist[0].context
3420        self.student_id = student.student_id
3421        student_pw = student.password
3422        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3423        code = get_access_code(pin)
3424        if not code:
[11254]3425            self.flash(_('Access code is invalid.'), type="warning")
[7660]3426            return
3427        if student_pw and pin == student.adm_code:
[7723]3428            self.flash(_(
3429                'Password has already been set. Your Student Id is ${a}',
3430                mapping = {'a':self.student_id}))
[7660]3431            return
3432        elif student_pw:
3433            self.flash(
[7723]3434                _('Password has already been set. You are using the ' +
[11254]3435                'wrong Access Code.'), type="warning")
[7660]3436            return
3437        # Mark pin as used (this also fires a pin related transition)
3438        # and set student password
3439        if code.state == USED:
[11254]3440            self.flash(_('Access code has already been used.'), type="warning")
[7660]3441            return
3442        else:
[7723]3443            comment = _(u"invalidated")
[7660]3444            # Here we know that the ac is in state initialized so we do not
3445            # expect an exception
3446            invalidate_accesscode(pin,comment)
3447            IUserAccount(student).setPassword(self.ac_number)
3448            student.adm_code = pin
[7723]3449        self.flash(_('Password has been set. Your Student Id is ${a}',
3450            mapping = {'a':self.student_id}))
[7811]3451        return
[8779]3452
3453class StudentRequestPasswordPage(KofaAddFormPage):
[13047]3454    """Captcha'd request password page for students.
[8779]3455    """
3456    grok.name('requestpw')
3457    grok.require('waeup.Anonymous')
3458    grok.template('requestpw')
3459    form_fields = grok.AutoFields(IStudentRequestPW).select(
[13344]3460        'lastname','number','email')
[8779]3461    label = _('Request password for first-time login')
3462
3463    def update(self):
[13396]3464        blocker = grok.getSite()['configuration'].maintmode_enabled_by
3465        if blocker:
3466            self.flash(_('The portal is in maintenance mode. '
3467                        'Password request forms are temporarily disabled.'),
3468                       type='warning')
3469            self.redirect(self.url(self.context))
3470            return
[8779]3471        # Handle captcha
3472        self.captcha = getUtility(ICaptchaManager).getCaptcha()
3473        self.captcha_result = self.captcha.verify(self.request)
3474        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
3475        return
3476
3477    def _redirect(self, email, password, student_id):
3478        # Forward only email to landing page in base package.
3479        self.redirect(self.url(self.context, 'requestpw_complete',
3480            data = dict(email=email)))
3481        return
3482
[14305]3483    def _redirect_no_student(self):
3484        # No record found, this is the truth. We do not redirect here.
3485        # We are using this method in custom packages
3486        # for redirecting alumni to the application section.
3487        self.flash(_('No student record found.'), type="warning")
3488        return
3489
[8779]3490    def _pw_used(self):
[8780]3491        # XXX: False if password has not been used. We need an extra
3492        #      attribute which remembers if student logged in.
[8779]3493        return True
3494
[8854]3495    @action(_('Send login credentials to email address'), style='primary')
[8779]3496    def get_credentials(self, **data):
3497        if not self.captcha_result.is_valid:
3498            # Captcha will display error messages automatically.
3499            # No need to flash something.
3500            return
[8854]3501        number = data.get('number','')
[13344]3502        lastname = data.get('lastname','')
[8779]3503        cat = getUtility(ICatalog, name='students_catalog')
3504        results = list(
[8854]3505            cat.searchResults(reg_number=(number, number)))
3506        if not results:
3507            results = list(
3508                cat.searchResults(matric_number=(number, number)))
[8779]3509        if results:
3510            student = results[0]
[13344]3511            if getattr(student,'lastname',None) is None:
[11254]3512                self.flash(_('An error occurred.'), type="danger")
[8779]3513                return
[13344]3514            elif student.lastname.lower() != lastname.lower():
[8779]3515                # Don't tell the truth here. Anonymous must not
[13344]3516                # know that a record was found and only the lastname
[8779]3517                # verification failed.
[11254]3518                self.flash(_('No student record found.'), type="warning")
[8779]3519                return
3520            elif student.password is not None and self._pw_used:
3521                self.flash(_('Your password has already been set and used. '
[11254]3522                             'Please proceed to the login page.'),
3523                           type="warning")
[8779]3524                return
3525            # Store email address but nothing else.
3526            student.email = data['email']
3527            notify(grok.ObjectModifiedEvent(student))
3528        else:
[14305]3529            self._redirect_no_student()
[8779]3530            return
3531
3532        kofa_utils = getUtility(IKofaUtils)
3533        password = kofa_utils.genPassword()
[8857]3534        mandate = PasswordMandate()
[8853]3535        mandate.params['password'] = password
[8858]3536        mandate.params['user'] = student
[8853]3537        site = grok.getSite()
3538        site['mandates'].addMandate(mandate)
[8779]3539        # Send email with credentials
[8853]3540        args = {'mandate_id':mandate.mandate_id}
3541        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3542        url_info = u'Confirmation link: %s' % mandate_url
[8779]3543        msg = _('You have successfully requested a password for the')
3544        if kofa_utils.sendCredentials(IUserAccount(student),
[8853]3545            password, url_info, msg):
[8779]3546            email_sent = student.email
3547        else:
3548            email_sent = None
3549        self._redirect(email=email_sent, password=password,
3550            student_id=student.student_id)
[8856]3551        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3552        self.context.logger.info(
3553            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
[8779]3554        return
3555
[15609]3556class ParentsUser:
3557    pass
3558
3559class RequestParentsPasswordPage(StudentRequestPasswordPage):
3560    """Captcha'd request password page for parents.
3561    """
3562    grok.name('requestppw')
3563    grok.template('requestppw')
3564    label = _('Request password for parents access')
3565
3566    def update(self):
3567        super(RequestParentsPasswordPage, self).update()
3568        kofa_utils = getUtility(IKofaUtils)
3569        self.temp_password_minutes = kofa_utils.TEMP_PASSWORD_MINUTES
3570        return
3571
3572    @action(_('Send temporary login credentials to email address'), style='primary')
3573    def get_credentials(self, **data):
3574        if not self.captcha_result.is_valid:
3575            # Captcha will display error messages automatically.
3576            # No need to flash something.
3577            return
3578        number = data.get('number','')
3579        lastname = data.get('lastname','')
3580        email = data['email']
3581        cat = getUtility(ICatalog, name='students_catalog')
3582        results = list(
3583            cat.searchResults(reg_number=(number, number)))
3584        if not results:
3585            results = list(
3586                cat.searchResults(matric_number=(number, number)))
3587        if results:
3588            student = results[0]
3589            if getattr(student,'lastname',None) is None:
3590                self.flash(_('An error occurred.'), type="danger")
3591                return
3592            elif student.lastname.lower() != lastname.lower():
3593                # Don't tell the truth here. Anonymous must not
3594                # know that a record was found and only the lastname
3595                # verification failed.
3596                self.flash(_('No student record found.'), type="warning")
3597                return
3598            elif email != student.parents_email:
3599                self.flash(_('Wrong email address.'), type="warning")
3600                return
3601        else:
3602            self._redirect_no_student()
3603            return
3604        kofa_utils = getUtility(IKofaUtils)
3605        password = kofa_utils.genPassword()
3606        mandate = ParentsPasswordMandate()
3607        mandate.params['password'] = password
3608        mandate.params['student'] = student
3609        site = grok.getSite()
3610        site['mandates'].addMandate(mandate)
3611        # Send email with credentials
3612        args = {'mandate_id':mandate.mandate_id}
3613        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3614        url_info = u'Confirmation link: %s' % mandate_url
3615        msg = _('You have successfully requested a parents password for the')
3616        # Create a fake user
3617        user = ParentsUser()
3618        user.name = student.student_id
3619        user.title = "Parents of %s" % student.display_fullname
3620        user.email = student.parents_email
3621        if kofa_utils.sendCredentials(user, password, url_info, msg):
3622            email_sent = user.email
3623        else:
3624            email_sent = None
3625        self._redirect(email=email_sent, password=password,
3626            student_id=student.student_id)
3627        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3628        self.context.logger.info(
3629            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
3630        return
3631
[8779]3632class StudentRequestPasswordEmailSent(KofaPage):
3633    """Landing page after successful password request.
3634
3635    """
3636    grok.name('requestpw_complete')
3637    grok.require('waeup.Public')
3638    grok.template('requestpwmailsent')
3639    label = _('Your password request was successful.')
3640
3641    def update(self, email=None, student_id=None, password=None):
3642        self.email = email
3643        self.password = password
3644        self.student_id = student_id
[8974]3645        return
[9797]3646
[9806]3647class FilterStudentsInDepartmentPage(KofaPage):
3648    """Page that filters and lists students.
3649    """
3650    grok.context(IDepartment)
3651    grok.require('waeup.showStudents')
3652    grok.name('students')
3653    grok.template('filterstudentspage')
3654    pnav = 1
[9819]3655    session_label = _('Current Session')
3656    level_label = _('Current Level')
[9806]3657
3658    def label(self):
[10650]3659        return 'Students in %s' % self.context.longtitle
[9806]3660
3661    def _set_session_values(self):
3662        vocab_terms = academic_sessions_vocab.by_value.values()
3663        self.sessions = sorted(
3664            [(x.title, x.token) for x in vocab_terms], reverse=True)
3665        self.sessions += [('All Sessions', 'all')]
3666        return
3667
3668    def _set_level_values(self):
3669        vocab_terms = course_levels.by_value.values()
3670        self.levels = sorted(
3671            [(x.title, x.token) for x in vocab_terms])
3672        self.levels += [('All Levels', 'all')]
3673        return
3674
3675    def _searchCatalog(self, session, level):
3676        if level not in (10, 999, None):
3677            start_level = 100 * (level // 100)
3678            end_level = start_level + 90
3679        else:
3680            start_level = end_level = level
3681        cat = queryUtility(ICatalog, name='students_catalog')
3682        students = cat.searchResults(
3683            current_session=(session, session),
3684            current_level=(start_level, end_level),
3685            depcode=(self.context.code, self.context.code)
3686            )
3687        hitlist = []
3688        for student in students:
3689            hitlist.append(StudentQueryResultItem(student, view=self))
3690        return hitlist
3691
3692    def update(self, SHOW=None, session=None, level=None):
3693        self.parent_url = self.url(self.context.__parent__)
3694        self._set_session_values()
3695        self._set_level_values()
3696        self.hitlist = []
3697        self.session_default = session
3698        self.level_default = level
3699        if SHOW is not None:
3700            if session != 'all':
3701                self.session = int(session)
3702                self.session_string = '%s %s/%s' % (
3703                    self.session_label, self.session, self.session+1)
3704            else:
3705                self.session = None
3706                self.session_string = _('in any session')
3707            if level != 'all':
3708                self.level = int(level)
3709                self.level_string = '%s %s' % (self.level_label, self.level)
3710            else:
3711                self.level = None
3712                self.level_string = _('at any level')
3713            self.hitlist = self._searchCatalog(self.session, self.level)
3714            if not self.hitlist:
[11254]3715                self.flash(_('No student found.'), type="warning")
[9806]3716        return
3717
3718class FilterStudentsInCertificatePage(FilterStudentsInDepartmentPage):
3719    """Page that filters and lists students.
3720    """
3721    grok.context(ICertificate)
3722
3723    def label(self):
[10650]3724        return 'Students studying %s' % self.context.longtitle
[9806]3725
3726    def _searchCatalog(self, session, level):
3727        if level not in (10, 999, None):
3728            start_level = 100 * (level // 100)
3729            end_level = start_level + 90
3730        else:
3731            start_level = end_level = level
3732        cat = queryUtility(ICatalog, name='students_catalog')
3733        students = cat.searchResults(
3734            current_session=(session, session),
3735            current_level=(start_level, end_level),
3736            certcode=(self.context.code, self.context.code)
3737            )
3738        hitlist = []
3739        for student in students:
3740            hitlist.append(StudentQueryResultItem(student, view=self))
3741        return hitlist
3742
3743class FilterStudentsInCoursePage(FilterStudentsInDepartmentPage):
3744    """Page that filters and lists students.
3745    """
3746    grok.context(ICourse)
[13764]3747    grok.require('waeup.viewStudent')
[9806]3748
[10024]3749    session_label = _('Session')
3750    level_label = _('Level')
3751
[9806]3752    def label(self):
[10650]3753        return 'Students registered for %s' % self.context.longtitle
[9806]3754
3755    def _searchCatalog(self, session, level):
3756        if level not in (10, 999, None):
3757            start_level = 100 * (level // 100)
3758            end_level = start_level + 90
3759        else:
3760            start_level = end_level = level
3761        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3762        coursetickets = cat.searchResults(
3763            session=(session, session),
3764            level=(start_level, end_level),
3765            code=(self.context.code, self.context.code)
3766            )
3767        hitlist = []
3768        for ticket in coursetickets:
3769            hitlist.append(StudentQueryResultItem(ticket.student, view=self))
[10039]3770        return list(set(hitlist))
[9806]3771
[13055]3772class ClearAllStudentsInDepartmentView(UtilityView, grok.View):
[11862]3773    """ Clear all students of a department in state 'clearance requested'.
3774    """
3775    grok.context(IDepartment)
3776    grok.name('clearallstudents')
3777    grok.require('waeup.clearAllStudents')
3778
3779    def update(self):
3780        cat = queryUtility(ICatalog, name='students_catalog')
3781        students = cat.searchResults(
3782            depcode=(self.context.code, self.context.code),
3783            state=(REQUESTED, REQUESTED)
3784            )
3785        num = 0
3786        for student in students:
3787            if getUtility(IStudentsUtils).clearance_disabled_message(student):
3788                continue
3789            IWorkflowInfo(student).fireTransition('clear')
3790            num += 1
3791        self.flash(_('%d students have been cleared.' % num))
3792        self.redirect(self.url(self.context))
3793        return
3794
3795    def render(self):
3796        return
3797
[16465]3798#class RemoveFlashNoticeAllStudentsInDepartmentView(UtilityView, grok.View):
3799#    """ Remove flash notices of all students in a department.
3800#    """
3801#    grok.context(IDepartment)
3802#    grok.name('removeflash')
3803#    grok.require('waeup.manageStudent')
3804
3805#    def update(self):
3806#        cat = queryUtility(ICatalog, name='students_catalog')
3807#        students = cat.searchResults(
3808#            depcode=(self.context.code, self.context.code),
3809#            )
3810#        num = 0
3811#        for student in students:
3812#            student.flash_notice = u''
3813#            num += 1
3814#        self.flash(_('%d flash notices have been removed.' % num))
3815#        self.redirect(self.url(self.context))
3816#        return
3817
3818#    def render(self):
3819#        return
3820
3821class EditFlashNoticesFormPage(KofaFormPage):
3822    """Edit all flash notices of students in a department.
[16459]3823    """
3824    grok.context(IDepartment)
[16465]3825    grok.name('edit_flash_notices')
3826    grok.template('editflashnotices')
[16459]3827    grok.require('waeup.manageStudent')
[16465]3828    form_fields = grok.AutoFields(IFlashNotice)
3829    pnav = 0
[16459]3830
[16465]3831    def label(self):
3832        return _(u'Set flash notices for all students in ${a}',
3833            mapping = {'a':self.context.longtitle})
3834
3835    @action('Save flash notices', style='primary')
3836    def save(self, *args, **data):
[16459]3837        cat = queryUtility(ICatalog, name='students_catalog')
3838        students = cat.searchResults(
3839            depcode=(self.context.code, self.context.code),
3840            )
3841        num = 0
3842        for student in students:
[16465]3843            student.flash_notice = data['flash_notice']
[16459]3844            num += 1
[16465]3845        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3846        grok.getSite().logger.info(
3847            '%s - %s - saved flash notice: %s'
3848            % (ob_class, self.context.__name__, data['flash_notice']))
3849        self.flash(_('%d flash notices have been edited.' % num))
[16459]3850        self.redirect(self.url(self.context))
3851        return
3852
[16465]3853    @action(_('Cancel'), validator=NullValidator)
3854    def cancel(self, **data):
3855        self.redirect(self.url(self.context))
[16459]3856
[10627]3857class EditScoresPage(KofaPage):
[13894]3858    """Page that allows to edit batches of scores.
[10627]3859    """
3860    grok.context(ICourse)
[10632]3861    grok.require('waeup.editScores')
[10627]3862    grok.name('edit_scores')
3863    grok.template('editscorespage')
3864    pnav = 1
[13936]3865    doclink = DOCLINK + '/students/browser.html#batch-editing-scores-by-lecturers'
[10627]3866
3867    def label(self):
[10631]3868        return '%s tickets in academic session %s' % (
[13938]3869            self.context.code, self.session_title)
[10627]3870
3871    def _searchCatalog(self, session):
3872        cat = queryUtility(ICatalog, name='coursetickets_catalog')
[15243]3873        # Attention: Also tickets of previous studycourses are found
[10627]3874        coursetickets = cat.searchResults(
3875            session=(session, session),
3876            code=(self.context.code, self.context.code)
3877            )
3878        return list(coursetickets)
3879
[13935]3880    def _extract_uploadfile(self, uploadfile):
3881        """Get a mapping of student-ids to scores.
3882
3883        The mapping is constructed by reading contents from `uploadfile`.
3884
3885        We expect uploadfile to be a regular CSV file with columns
3886        ``student_id`` and ``score`` (other cols are ignored).
3887        """
3888        result = dict()
3889        data = StringIO(uploadfile.read())  # ensure we have something seekable
3890        reader = csv.DictReader(data)
3891        for row in reader:
3892            if not 'student_id' in row or not 'score' in row:
3893                continue
3894            result[row['student_id']] = row['score']
3895        return result
3896
[14285]3897    def _update_scores(self, form):
[13935]3898        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3899        error = ''
[13936]3900        if 'UPDATE_FILE' in form:
3901            if form['uploadfile']:
3902                try:
3903                    formvals = self._extract_uploadfile(form['uploadfile'])
3904                except:
3905                    self.flash(
3906                        _('Uploaded file contains illegal data. Ignored'),
3907                        type="danger")
[14283]3908                    return False
[13936]3909            else:
[13935]3910                self.flash(
[13936]3911                    _('No file provided.'), type="danger")
[14283]3912                return False
[13936]3913        else:
3914            formvals = dict(zip(form['sids'], form['scores']))
[14285]3915        for ticket in self.editable_tickets:
[13935]3916            score = ticket.score
3917            sid = ticket.student.student_id
3918            if sid not in formvals:
3919                continue
3920            if formvals[sid] == '':
3921                score = None
3922            else:
3923                try:
3924                    score = int(formvals[sid])
3925                except ValueError:
3926                    error += '%s, ' % ticket.student.display_fullname
3927            if ticket.score != score:
3928                ticket.score = score
3929                ticket.student.__parent__.logger.info(
3930                    '%s - %s %s/%s score updated (%s)' % (
3931                        ob_class, ticket.student.student_id,
3932                        ticket.level, ticket.code, score)
3933                    )
3934        if error:
3935            self.flash(
3936                _('Error: Score(s) of following students have not been '
3937                    'updated (only integers are allowed): %s.' % error.strip(', ')),
3938                type="danger")
[14283]3939        return True
3940
[15422]3941    def _validate_results(self, form):
3942        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3943        user = get_current_principal()
3944        if user is None:
3945            usertitle = 'system'
3946        else:
3947            usertitle = getattr(user, 'public_name', None)
3948            if not usertitle:
3949                usertitle = user.title
3950        self.context.results_validated_by = usertitle
3951        self.context.results_validation_date = datetime.utcnow()
3952        self.context.results_validation_session = self.current_academic_session
3953        return
3954
3955    def _results_editable(self, results_validation_session,
3956                         current_academic_session):
3957        user = get_current_principal()
3958        prm = IPrincipalRoleManager(self.context)
3959        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
3960        if 'waeup.local.LocalStudentsManager' in roles:
3961            return True
3962        if results_validation_session \
3963            and results_validation_session >= current_academic_session:
3964            return False
3965        return True
3966
[14283]3967    def update(self,  *args, **kw):
3968        form = self.request.form
3969        self.current_academic_session = grok.getSite()[
3970            'configuration'].current_academic_session
[15629]3971        if self.context.__parent__.__parent__.score_editing_disabled \
3972            or self.context.score_editing_disabled:
[14283]3973            self.flash(_('Score editing disabled.'), type="warning")
3974            self.redirect(self.url(self.context))
[13938]3975            return
[14283]3976        if not self.current_academic_session:
3977            self.flash(_('Current academic session not set.'), type="warning")
3978            self.redirect(self.url(self.context))
3979            return
[15422]3980        vs = self.context.results_validation_session
3981        if not self._results_editable(vs, self.current_academic_session):
3982            self.flash(
3983                _('Course results have already been '
3984                  'validated and can no longer be changed.'),
3985                type="danger")
3986            self.redirect(self.url(self.context))
3987            return
[14283]3988        self.session_title = academic_sessions_vocab.getTerm(
3989            self.current_academic_session).title
3990        self.tickets = self._searchCatalog(self.current_academic_session)
3991        if not self.tickets:
3992            self.flash(_('No student found.'), type="warning")
3993            self.redirect(self.url(self.context))
3994            return
[14286]3995        self.editable_tickets = [
3996            ticket for ticket in self.tickets if ticket.editable_by_lecturer]
[15422]3997        if not 'UPDATE_TABLE' in form and not 'UPDATE_FILE' in form\
3998            and not 'VALIDATE_RESULTS' in form:
[14283]3999            return
[15422]4000        if 'VALIDATE_RESULTS' in form:
4001            if vs and vs >= self.current_academic_session:
4002                self.flash(
4003                    _('Course results have already been validated.'),
4004                    type="danger")
[16007]4005            for ticket in self.tickets:
4006                if ticket.total_score is not None:
4007                    break
4008                self.flash(
4009                    _('No score has been entered.'),
4010                    type="danger")
[15422]4011                return
4012            self._validate_results(form)
4013            self.flash(_('You successfully validated the course results.'))
4014            self.redirect(self.url(self.context))
4015            return
[14284]4016        if not self.editable_tickets:
[14283]4017            return
[14285]4018        success = self._update_scores(form)
[14283]4019        if success:
4020            self.flash(_('You successfully updated course results.'))
[10627]4021        return
4022
[13894]4023class DownloadScoresView(UtilityView, grok.View):
4024    """View that exports scores.
4025    """
4026    grok.context(ICourse)
4027    grok.require('waeup.editScores')
4028    grok.name('download_scores')
4029
[15422]4030    def _results_editable(self, results_validation_session,
4031                         current_academic_session):
4032        user = get_current_principal()
4033        prm = IPrincipalRoleManager(self.context)
4034        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
4035        if 'waeup.local.LocalStudentsManager' in roles:
4036            return True
4037        if results_validation_session \
4038            and results_validation_session >= current_academic_session:
4039            return False
4040        return True
4041
[13894]4042    def update(self):
4043        self.current_academic_session = grok.getSite()[
4044            'configuration'].current_academic_session
[15629]4045        if self.context.__parent__.__parent__.score_editing_disabled \
4046            or self.context.score_editing_disabled:
[13894]4047            self.flash(_('Score editing disabled.'), type="warning")
4048            self.redirect(self.url(self.context))
4049            return
4050        if not self.current_academic_session:
4051            self.flash(_('Current academic session not set.'), type="warning")
4052            self.redirect(self.url(self.context))
4053            return
[15422]4054        vs = self.context.results_validation_session
4055        if not self._results_editable(vs, self.current_academic_session):
4056            self.flash(
4057                _('Course results have already been '
4058                  'validated and can no longer be changed.'),
4059                type="danger")
4060            self.redirect(self.url(self.context))
4061            return
[13894]4062        site = grok.getSite()
4063        exporter = getUtility(ICSVExporter, name='lecturer')
4064        self.csv = exporter.export_filtered(site, filepath=None,
4065                                 catalog='coursetickets',
4066                                 session=self.current_academic_session,
4067                                 level=None,
4068                                 code=self.context.code)
4069        return
4070
4071    def render(self):
4072        filename = 'results_%s_%s.csv' % (
4073            self.context.code, self.current_academic_session)
4074        self.response.setHeader(
4075            'Content-Type', 'text/csv; charset=UTF-8')
4076        self.response.setHeader(
4077            'Content-Disposition:', 'attachment; filename="%s' % filename)
4078        return self.csv
4079
[13898]4080class ExportPDFScoresSlip(UtilityView, grok.View,
4081    LocalRoleAssignmentUtilityView):
4082    """Deliver a PDF slip of course tickets for a lecturer.
4083    """
4084    grok.context(ICourse)
4085    grok.name('coursetickets.pdf')
[15422]4086    grok.require('waeup.showStudents')
[13898]4087
[15426]4088    def update(self):
4089        self.current_academic_session = grok.getSite()[
4090            'configuration'].current_academic_session
4091        if not self.current_academic_session:
4092            self.flash(_('Current academic session not set.'), type="danger")
4093            self.redirect(self.url(self.context))
4094            return
4095
[15246]4096    @property
4097    def note(self):
4098        return
4099
[14314]4100    def data(self, session):
[13898]4101        cat = queryUtility(ICatalog, name='coursetickets_catalog')
[15243]4102        # Attention: Also tickets of previous studycourses are found
[13898]4103        coursetickets = cat.searchResults(
4104            session=(session, session),
4105            code=(self.context.code, self.context.code)
4106            )
[16518]4107        header = [[_('S/N'),
4108                   _('Matric No.'),
[13898]4109                   _('Reg. No.'),
4110                   _('Fullname'),
4111                   _('Status'),
4112                   _('Course of Studies'),
4113                   _('Level'),
4114                   _('Score') ],]
[13908]4115        tickets = []
[13898]4116        for ticket in list(coursetickets):
[16520]4117            row = [ticket.student.matric_number,
[13898]4118                  ticket.student.reg_number,
4119                  ticket.student.display_fullname,
4120                  ticket.student.translated_state,
4121                  ticket.student.certcode,
4122                  ticket.level,
[16505]4123                  ticket.score,
4124                  ticket.student.lastname # for sorting only
4125                  ]
[13908]4126            tickets.append(row)
[16520]4127        data = sorted(tickets, key=lambda value: value[7])
4128        sn = 1
4129        for d in data:
4130            d.pop(7)
4131            d.insert(0, sn)
[16518]4132            sn += 1
[16505]4133        return header + data, None
[13898]4134
4135    def render(self):
4136        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
4137                     if i['local_role'] == 'waeup.local.Lecturer']
[15865]4138        lecturers = sorted(lecturers)
[13898]4139        lecturers =  ', '.join(lecturers)
4140        students_utils = getUtility(IStudentsUtils)
4141        return students_utils.renderPDFCourseticketsOverview(
[15426]4142            self, 'coursetickets', self.current_academic_session,
4143            self.data(self.current_academic_session), lecturers,
[15423]4144            'landscape', 90, self.note)
[13898]4145
[15423]4146class ExportAttendanceSlip(UtilityView, grok.View,
4147    LocalRoleAssignmentUtilityView):
4148    """Deliver a PDF slip of course tickets in attendance sheet format.
4149    """
4150    grok.context(ICourse)
4151    grok.name('attendance.pdf')
4152    grok.require('waeup.showStudents')
4153
[15426]4154    def update(self):
4155        self.current_academic_session = grok.getSite()[
4156            'configuration'].current_academic_session
4157        if not self.current_academic_session:
4158            self.flash(_('Current academic session not set.'), type="danger")
4159            self.redirect(self.url(self.context))
4160            return
4161
[15423]4162    @property
4163    def note(self):
4164        return
4165
4166    def data(self, session):
4167        cat = queryUtility(ICatalog, name='coursetickets_catalog')
4168        # Attention: Also tickets of previous studycourses are found
4169        coursetickets = cat.searchResults(
4170            session=(session, session),
4171            code=(self.context.code, self.context.code)
4172            )
[15526]4173        header = [[_('S/N'),
[15541]4174                   _('Matric No.'),
[15538]4175                   _('Name'),
[15423]4176                   _('Level'),
[15542]4177                   _('Course of\nStudies'),
[15423]4178                   _('Booklet No.'),
4179                   _('Signature'),
4180                   ],]
4181        tickets = []
[15526]4182        sn = 1
4183        ctlist = sorted(list(coursetickets),
[16518]4184                        key=lambda value: str(value.student.faccode) +
4185                                          str(value.student.depcode) +
4186                                          str(value.student.certcode) +
[15535]4187                                          str(value.student.matric_number))
[15642]4188        # In AAUE only editable appear on the attendance sheet. Hopefully
4189        # this holds for other universities too.
4190        editable_tickets = [ticket for ticket in ctlist
4191            if ticket.editable_by_lecturer]
4192        for ticket in editable_tickets:
[15626]4193            name = textwrap.fill(ticket.student.display_fullname, 20)
[15526]4194            row = [sn,
[15423]4195                  ticket.student.matric_number,
[15624]4196                  name,
[15423]4197                  ticket.level,
4198                  ticket.student.certcode,
[15624]4199                  20 * ' ',
[15544]4200                  27 * ' ',
[15423]4201                  ]
4202            tickets.append(row)
[15526]4203            sn += 1
4204        return header + tickets, None
[15423]4205
4206    def render(self):
4207        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
4208                     if i['local_role'] == 'waeup.local.Lecturer']
4209        lecturers =  ', '.join(lecturers)
4210        students_utils = getUtility(IStudentsUtils)
4211        return students_utils.renderPDFCourseticketsOverview(
[15426]4212            self, 'attendance', self.current_academic_session,
4213            self.data(self.current_academic_session),
[15526]4214            lecturers, '', 65, self.note)
[15423]4215
[9813]4216class ExportJobContainerOverview(KofaPage):
[9835]4217    """Page that lists active student data export jobs and provides links
4218    to discard or download CSV files.
4219
[9797]4220    """
[9813]4221    grok.context(VirtualExportJobContainer)
[9797]4222    grok.require('waeup.showStudents')
4223    grok.name('index.html')
4224    grok.template('exportjobsindex')
[9813]4225    label = _('Student Data Exports')
[9797]4226    pnav = 1
[12910]4227    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
[9797]4228
[15545]4229    def update(self, CREATE1=None, CREATE2=None, DISCARD=None, job_id=None):
4230        if CREATE1:
[9836]4231            self.redirect(self.url('@@exportconfig'))
[9797]4232            return
[15545]4233        if CREATE2:
4234            self.redirect(self.url('@@exportselected'))
4235            return
[9797]4236        if DISCARD and job_id:
4237            entry = self.context.entry_from_job_id(job_id)
4238            self.context.delete_export_entry(entry)
[9836]4239            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4240            self.context.logger.info(
4241                '%s - discarded: job_id=%s' % (ob_class, job_id))
[9819]4242            self.flash(_('Discarded export') + ' %s' % job_id)
[9822]4243        self.entries = doll_up(self, user=self.request.principal.id)
[9797]4244        return
4245
[9833]4246class ExportJobContainerJobConfig(KofaPage):
[9797]4247    """Page that configures a students export job.
[9833]4248
4249    This is a baseclass.
[9797]4250    """
[9833]4251    grok.baseclass()
[9797]4252    grok.require('waeup.showStudents')
[9836]4253    grok.template('exportconfig')
[9833]4254    label = _('Configure student data export')
[9797]4255    pnav = 1
[9835]4256    redirect_target = ''
[12901]4257    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
[9797]4258
4259    def _set_session_values(self):
4260        vocab_terms = academic_sessions_vocab.by_value.values()
[15042]4261        self.sessions = [(_('All Sessions'), 'all')]
4262        self.sessions += sorted(
[9797]4263            [(x.title, x.token) for x in vocab_terms], reverse=True)
4264        return
4265
4266    def _set_level_values(self):
4267        vocab_terms = course_levels.by_value.values()
[15042]4268        self.levels = [(_('All Levels'), 'all')]
4269        self.levels += sorted(
[9797]4270            [(x.title, x.token) for x in vocab_terms])
4271        return
4272
[15546]4273    def _set_semesters_values(self):
4274        utils = getUtility(IKofaUtils)
4275        self.semesters =[(_('All Semesters'), 'all')]
4276        self.semesters += sorted([(value, key) for key, value in
4277                      utils.SEMESTER_DICT.items()])
4278        return
4279
[9803]4280    def _set_mode_values(self):
4281        utils = getUtility(IKofaUtils)
[15042]4282        self.modes =[(_('All Modes'), 'all')]
4283        self.modes += sorted([(value, key) for key, value in
[9838]4284                      utils.STUDY_MODES_DICT.items()])
[9803]4285        return
4286
[15042]4287    def _set_paycat_values(self):
4288        utils = getUtility(IKofaUtils)
4289        self.paycats =[(_('All Payment Categories'), 'all')]
4290        self.paycats += sorted([(value, key) for key, value in
4291                      utils.PAYMENT_CATEGORIES.items()])
4292        return
4293
[9804]4294    def _set_exporter_values(self):
4295        # We provide all student exporters, nothing else, yet.
[15277]4296        # Bursary, Department or Accommodation Officers don't
4297        # have the general exportData
4298        # permission and are only allowed to export bursary, payments
4299        # overview or accommodation data respectively.
4300        # This is the only place where waeup.exportAccommodationData,
[10279]4301        # waeup.exportBursaryData and waeup.exportPaymentsOverview
4302        # are used.
4303        exporters = []
[10248]4304        if not checkPermission('waeup.exportData', self.context):
[10279]4305            if checkPermission('waeup.exportBursaryData', self.context):
4306                exporters += [('Bursary Data', 'bursary')]
4307            if checkPermission('waeup.exportPaymentsOverview', self.context):
[15051]4308                exporters += [('School Fee Payments Overview',
4309                               'sfpaymentsoverview'),
4310                              ('Session Payments Overview',
4311                               'sessionpaymentsoverview')]
[15277]4312            if checkPermission('waeup.exportAccommodationData', self.context):
4313                exporters += [('Bed Tickets', 'bedtickets'),
4314                              ('Accommodation Payments',
4315                               'accommodationpayments')]
[10279]4316            self.exporters = exporters
[10248]4317            return
[12104]4318        STUDENT_EXPORTER_NAMES = getUtility(
4319            IStudentsUtils).STUDENT_EXPORTER_NAMES
4320        for name in STUDENT_EXPORTER_NAMES:
[9804]4321            util = getUtility(ICSVExporter, name=name)
4322            exporters.append((util.title, name),)
4323        self.exporters = exporters
[10247]4324        return
[9804]4325
[9833]4326    @property
[12632]4327    def faccode(self):
4328        return None
4329
4330    @property
[9833]4331    def depcode(self):
4332        return None
4333
[9842]4334    @property
4335    def certcode(self):
4336        return None
4337
[9804]4338    def update(self, START=None, session=None, level=None, mode=None,
[15042]4339               payments_start=None, payments_end=None, ct_level=None,
[15546]4340               ct_session=None, ct_semester=None, paycat=None,
[15918]4341               paysession=None, level_session=None, exporter=None):
[9797]4342        self._set_session_values()
4343        self._set_level_values()
[9803]4344        self._set_mode_values()
[15042]4345        self._set_paycat_values()
[9804]4346        self._set_exporter_values()
[15546]4347        self._set_semesters_values()
[9797]4348        if START is None:
4349            return
[13201]4350        ena = exports_not_allowed(self)
4351        if ena:
4352            self.flash(ena, type='danger')
[13198]4353            return
[11730]4354        if payments_start or payments_end:
4355            date_format = '%d/%m/%Y'
4356            try:
[13935]4357                datetime.strptime(payments_start, date_format)
4358                datetime.strptime(payments_end, date_format)
[11730]4359            except ValueError:
4360                self.flash(_('Payment dates do not match format d/m/Y.'),
4361                           type="danger")
4362                return
[9797]4363        if session == 'all':
4364            session=None
4365        if level == 'all':
4366            level = None
[9803]4367        if mode == 'all':
4368            mode = None
[12632]4369        if (mode,
4370            level,
4371            session,
4372            self.faccode,
4373            self.depcode,
4374            self.certcode) == (None, None, None, None, None, None):
[9933]4375            # Export all students including those without certificate
[15042]4376            job_id = self.context.start_export_job(exporter,
4377                                          self.request.principal.id,
4378                                          payments_start = payments_start,
4379                                          payments_end = payments_end,
4380                                          paycat=paycat,
[15055]4381                                          paysession=paysession,
[15042]4382                                          ct_level = ct_level,
4383                                          ct_session = ct_session,
[15546]4384                                          ct_semester = ct_semester,
[15918]4385                                          level_session=level_session,
[15042]4386                                          )
[9933]4387        else:
[15042]4388            job_id = self.context.start_export_job(exporter,
4389                                          self.request.principal.id,
4390                                          current_session=session,
4391                                          current_level=level,
4392                                          current_mode=mode,
4393                                          faccode=self.faccode,
4394                                          depcode=self.depcode,
4395                                          certcode=self.certcode,
4396                                          payments_start = payments_start,
4397                                          payments_end = payments_end,
4398                                          paycat=paycat,
[15055]4399                                          paysession=paysession,
[15042]4400                                          ct_level = ct_level,
[15546]4401                                          ct_session = ct_session,
[15918]4402                                          ct_semester = ct_semester,
4403                                          level_session=level_session,)
[9836]4404        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4405        self.context.logger.info(
[15918]4406            '%s - exported: %s (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s), job_id=%s'
[12632]4407            % (ob_class, exporter, session, level, mode, self.faccode,
[15042]4408            self.depcode, self.certcode, payments_start, payments_end,
[15918]4409            ct_level, ct_session, paycat, paysession, level_session, job_id))
[9833]4410        self.flash(_('Export started for students with') +
4411                   ' current_session=%s, current_level=%s, study_mode=%s' % (
4412                   session, level, mode))
[9835]4413        self.redirect(self.url(self.redirect_target))
[9797]4414        return
4415
[9822]4416class ExportJobContainerDownload(ExportCSVView):
[9835]4417    """Page that downloads a students export csv file.
4418
[9797]4419    """
[9813]4420    grok.context(VirtualExportJobContainer)
[9797]4421    grok.require('waeup.showStudents')
[9833]4422
4423class DatacenterExportJobContainerJobConfig(ExportJobContainerJobConfig):
4424    """Page that configures a students export job in datacenter.
4425
4426    """
[15545]4427    grok.name('exportconfig')
[9833]4428    grok.context(IDataCenter)
[9835]4429    redirect_target = '@@export'
[9833]4430
[12518]4431class DatacenterExportJobContainerSelectStudents(ExportJobContainerJobConfig):
4432    """Page that configures a students export job in datacenter.
4433
4434    """
4435    grok.name('exportselected')
4436    grok.context(IDataCenter)
4437    redirect_target = '@@export'
4438    grok.template('exportselected')
4439
4440    def update(self, START=None, students=None, exporter=None):
4441        self._set_exporter_values()
4442        if START is None:
4443            return
[13201]4444        ena = exports_not_allowed(self)
4445        if ena:
4446            self.flash(ena, type='danger')
[13200]4447            return
[12518]4448        try:
4449            ids = students.replace(',', ' ').split()
4450        except:
4451            self.flash(sys.exc_info()[1])
4452            self.redirect(self.url(self.redirect_target))
4453            return
4454        job_id = self.context.start_export_job(
4455            exporter, self.request.principal.id, selected=ids)
4456        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4457        self.context.logger.info(
4458            '%s - selected students exported: %s, job_id=%s' %
4459            (ob_class, exporter, job_id))
4460        self.flash(_('Export of selected students started.'))
4461        self.redirect(self.url(self.redirect_target))
4462        return
4463
[15545]4464class FacultiesExportJobContainerJobConfig(
4465    DatacenterExportJobContainerJobConfig):
[10247]4466    """Page that configures a students export job in facultiescontainer.
4467
4468    """
4469    grok.context(VirtualFacultiesExportJobContainer)
[15545]4470    redirect_target = ''
[10247]4471
[15545]4472class FacultiesExportJobContainerSelectStudents(
4473    DatacenterExportJobContainerSelectStudents):
4474    """Page that configures a students export job in facultiescontainer.
[12632]4475
[15545]4476    """
4477    grok.context(VirtualFacultiesExportJobContainer)
4478    redirect_target = ''
4479
4480class FacultyExportJobContainerJobConfig(DatacenterExportJobContainerJobConfig):
[12632]4481    """Page that configures a students export job in faculties.
4482
4483    """
4484    grok.context(VirtualFacultyExportJobContainer)
[15545]4485    redirect_target = ''
[12632]4486
4487    @property
4488    def faccode(self):
4489        return self.context.__parent__.code
4490
[15545]4491class DepartmentExportJobContainerJobConfig(
4492    DatacenterExportJobContainerJobConfig):
[9833]4493    """Page that configures a students export job in departments.
4494
4495    """
4496    grok.context(VirtualDepartmentExportJobContainer)
[15545]4497    redirect_target = ''
[9833]4498
4499    @property
4500    def depcode(self):
[9835]4501        return self.context.__parent__.code
[9842]4502
[15545]4503class CertificateExportJobContainerJobConfig(
4504    DatacenterExportJobContainerJobConfig):
[9842]4505    """Page that configures a students export job for certificates.
4506
4507    """
4508    grok.context(VirtualCertificateExportJobContainer)
[9843]4509    grok.template('exportconfig_certificate')
[15545]4510    redirect_target = ''
[9842]4511
4512    @property
4513    def certcode(self):
4514        return self.context.__parent__.code
[9843]4515
[15545]4516class CourseExportJobContainerJobConfig(
4517    DatacenterExportJobContainerJobConfig):
[9843]4518    """Page that configures a students export job for courses.
4519
4520    In contrast to department or certificate student data exports the
4521    coursetickets_catalog is searched here. Therefore the update
4522    method from the base class is customized.
4523    """
4524    grok.context(VirtualCourseExportJobContainer)
4525    grok.template('exportconfig_course')
[15545]4526    redirect_target = ''
[9843]4527
4528    def _set_exporter_values(self):
[13894]4529        # We provide only the 'coursetickets' and 'lecturer' exporter
4530        # but can add more.
[9843]4531        exporters = []
[13894]4532        for name in ('coursetickets', 'lecturer'):
[9843]4533            util = getUtility(ICSVExporter, name=name)
4534            exporters.append((util.title, name),)
4535        self.exporters = exporters
[15545]4536        return
[9843]4537
[16412]4538    # Disabled on 10/03/21
4539    #def _set_session_values(self):
4540    #    # We allow only current academic session
4541    #    academic_session = grok.getSite()['configuration'].current_academic_session
4542    #    if not academic_session:
4543    #        self.sessions = []
4544    #        return
4545    #    x = academic_sessions_vocab.getTerm(academic_session)
4546    #    self.sessions = [(x.title, x.token)]
4547    #    return
4548
[13766]4549    def _set_session_values(self):
[16412]4550        vocab_terms = academic_sessions_vocab.by_value.values()
4551        self.sessions = sorted(
4552            [(x.title, x.token) for x in vocab_terms], reverse=True)
4553        self.sessions += [('All Sessions', 'all')]
[13766]4554        return
4555
[9843]4556    def update(self, START=None, session=None, level=None, mode=None,
4557               exporter=None):
[15545]4558        if not checkPermission('waeup.exportData', self.context):
4559            self.flash(_('Not permitted.'), type='danger')
4560            self.redirect(self.url(self.context))
4561            return
[9843]4562        self._set_session_values()
4563        self._set_level_values()
4564        self._set_mode_values()
4565        self._set_exporter_values()
[16412]4566        # Disabled on 10/03/21
4567        #if not self.sessions:
4568        #    self.flash(
4569        #        _('Academic session not set. '
4570        #          'Please contact the administrator.'),
4571        #        type='danger')
4572        #    self.redirect(self.url(self.context))
4573        #    return
[9843]4574        if START is None:
4575            return
[13201]4576        ena = exports_not_allowed(self)
4577        if ena:
4578            self.flash(ena, type='danger')
[13200]4579            return
[9843]4580        if session == 'all':
[10016]4581            session = None
[9843]4582        if level == 'all':
4583            level = None
4584        job_id = self.context.start_export_job(exporter,
4585                                      self.request.principal.id,
4586                                      # Use a different catalog and
4587                                      # pass different keywords than
4588                                      # for the (default) students_catalog
[9845]4589                                      catalog='coursetickets',
[9843]4590                                      session=session,
4591                                      level=level,
4592                                      code=self.context.__parent__.code)
4593        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4594        self.context.logger.info(
4595            '%s - exported: %s (%s, %s, %s), job_id=%s'
4596            % (ob_class, exporter, session, level,
4597            self.context.__parent__.code, job_id))
4598        self.flash(_('Export started for course tickets with') +
4599                   ' level_session=%s, level=%s' % (
4600                   session, level))
4601        self.redirect(self.url(self.redirect_target))
[13935]4602        return
Note: See TracBrowser for help on using the repository browser.