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

Last change on this file since 13010 was 13005, checked in by Henrik Bettermann, 9 years ago

Add Payment class attribute created_online to mark payment tickets
which are added online and not by import. This attribute is needed in
custom packages when sending data to payment gateways.

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