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

Last change on this file since 11657 was 11580, checked in by Henrik Bettermann, 11 years ago

Show correct flash message color after payment.

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