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

Last change on this file since 13147 was 13129, checked in by Henrik Bettermann, 10 years ago

Change misleading attribute name.

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