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

Last change on this file since 13894 was 13894, checked in by Henrik Bettermann, 8 years ago

Add DownloadScoresView which is for lecturers only. Remove
waeup.showStudents from Lecturer role. Adjust
DataForLecturerExporter. Only editable course tickets are being
exported.

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