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

Last change on this file since 15344 was 15334, checked in by Henrik Bettermann, 6 years ago

Add tests and adjust the documentation.

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