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

Last change on this file since 8558 was 8558, checked in by Henrik Bettermann, 13 years ago

Workaround to avoid RuntimeErrors?.

  • Property svn:keywords set to Id
File size: 68.3 KB
RevLine 
[7191]1## $Id: browser.py 8558 2012-05-30 08:54:38Z henrik $
2##
[6621]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""UI components for students and related components.
19"""
[7006]20import sys
[6621]21import grok
[7275]22from urllib import urlencode
[6869]23from time import time
[7256]24from datetime import datetime
[8143]25from copy import deepcopy
[7015]26from zope.event import notify
[7723]27from zope.i18n import translate
[6996]28from zope.catalog.interfaces import ICatalog
[7386]29from zope.component import queryUtility, getUtility, createObject
[8099]30from zope.schema.interfaces import ConstraintNotSatisfied
[7386]31from zope.formlib.textwidgets import BytesDisplayWidget
[6621]32from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
[7811]33from waeup.kofa.accesscodes import (
[8420]34    invalidate_accesscode, get_access_code)
[7811]35from waeup.kofa.accesscodes.workflow import USED
36from waeup.kofa.browser import (
[7819]37    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
[7834]38    ContactAdminForm, KofaForm, NullValidator)
[7811]39from waeup.kofa.browser.breadcrumbs import Breadcrumb
40from waeup.kofa.browser.resources import datepicker, datatable, tabs, warning
41from waeup.kofa.browser.layout import jsaction, action, UtilityView
42from waeup.kofa.interfaces import (
[7819]43    IKofaObject, IUserAccount, IExtFileStore, IPasswordValidator, IContactForm,
44    IKofaUtils, IUniversity)
[7811]45from waeup.kofa.interfaces import MessageFactory as _
[8170]46from waeup.kofa.widgets.datewidget import (
47    FriendlyDateWidget, FriendlyDateDisplayWidget,
48    FriendlyDatetimeDisplayWidget)
[7868]49from waeup.kofa.widgets.restwidget import ReSTDisplayWidget
[7811]50from waeup.kofa.students.interfaces import (
[7993]51    IStudentsContainer, IStudent,
52    IUGStudentClearance,IPGStudentClearance,
[6859]53    IStudentPersonal, IStudentBase, IStudentStudyCourse,
[7538]54    IStudentAccommodation, IStudentStudyLevel,
[6877]55    ICourseTicket, ICourseTicketAdd, IStudentPaymentsContainer,
[8346]56    IStudentOnlinePayment, IBedTicket, IStudentsUtils
[6621]57    )
[7811]58from waeup.kofa.students.catalog import search
59from waeup.kofa.students.workflow import (ADMITTED, PAID,
[7158]60    CLEARANCE, REQUESTED, RETURNING, CLEARED, REGISTERED, VALIDATED)
[7811]61from waeup.kofa.students.studylevel import StudentStudyLevel, CourseTicket
62from waeup.kofa.students.vocabularies import StudyLevelSource
63from waeup.kofa.browser.resources import toggleall
64from waeup.kofa.hostels.hostel import NOT_OCCUPIED
65from waeup.kofa.utils.helpers import get_current_principal
[6621]66
[6943]67def write_log_message(view, message):
[7811]68    ob_class = view.__implemented__.__name__.replace('waeup.kofa.','')
[6943]69    view.context.getStudent().loggerInfo(ob_class, message)
70    return
71
[7133]72# Save function used for save methods in pages
[6762]73def msave(view, **data):
74    changed_fields = view.applyData(view.context, **data)
[6771]75    # Turn list of lists into single list
76    if changed_fields:
77        changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7205]78    # Inform catalog if certificate has changed
79    # (applyData does this only for the context)
80    if 'certificate' in changed_fields:
81        notify(grok.ObjectModifiedEvent(view.context.getStudent()))
[6771]82    fields_string = ' + '.join(changed_fields)
[7723]83    view.flash(_('Form has been saved.'))
[6762]84    if fields_string:
[7108]85        write_log_message(view, 'saved: %s' % fields_string)
[6762]86    return
87
[7145]88def emit_lock_message(view):
[7642]89    """Flash a lock message.
90    """
[7723]91    view.flash(_('The requested form is locked (read-only).'))
[7133]92    view.redirect(view.url(view.context))
93    return
94
[6629]95class StudentsBreadcrumb(Breadcrumb):
96    """A breadcrumb for the students container.
97    """
98    grok.context(IStudentsContainer)
[7723]99    title = _('Students')
[6629]100
[7459]101    @property
102    def target(self):
103        user = get_current_principal()
104        if getattr(user, 'user_type', None) == 'student':
105            return None
106        return self.viewname
107
[6818]108class StudentBreadcrumb(Breadcrumb):
109    """A breadcrumb for the student container.
110    """
111    grok.context(IStudent)
112
113    def title(self):
[7364]114        return self.context.display_fullname
[6818]115
[6635]116class SudyCourseBreadcrumb(Breadcrumb):
117    """A breadcrumb for the student study course.
118    """
119    grok.context(IStudentStudyCourse)
[7723]120    title = _('Study Course')
[6635]121
122class PaymentsBreadcrumb(Breadcrumb):
123    """A breadcrumb for the student payments folder.
124    """
[6859]125    grok.context(IStudentPaymentsContainer)
[7723]126    title = _('Payments')
[6635]127
[6870]128class OnlinePaymentBreadcrumb(Breadcrumb):
[7251]129    """A breadcrumb for payments.
[6870]130    """
[6877]131    grok.context(IStudentOnlinePayment)
[6870]132
133    @property
134    def title(self):
135        return self.context.p_id
136
[6635]137class AccommodationBreadcrumb(Breadcrumb):
138    """A breadcrumb for the student accommodation folder.
139    """
140    grok.context(IStudentAccommodation)
[7723]141    title = _('Accommodation')
[6635]142
[6994]143class BedTicketBreadcrumb(Breadcrumb):
144    """A breadcrumb for bed tickets.
145    """
146    grok.context(IBedTicket)
[7009]147
[6994]148    @property
149    def title(self):
[7723]150        return _('Bed Ticket ${a}',
151            mapping = {'a':self.context.getSessionString()})
[6994]152
[6776]153class StudyLevelBreadcrumb(Breadcrumb):
154    """A breadcrumb for course lists.
155    """
156    grok.context(IStudentStudyLevel)
157
158    @property
159    def title(self):
[7834]160        return self.context.level_title
[6776]161
[7819]162class StudentsContainerPage(KofaPage):
[6626]163    """The standard view for student containers.
[6621]164    """
165    grok.context(IStudentsContainer)
166    grok.name('index')
[7240]167    grok.require('waeup.viewStudentsContainer')
[6695]168    grok.template('containerpage')
[7723]169    label = _('Student Section')
[7735]170    search_button = _('Search')
[6642]171    pnav = 4
[6621]172
[6626]173    def update(self, *args, **kw):
174        datatable.need()
175        form = self.request.form
176        self.hitlist = []
177        if 'searchterm' in form and form['searchterm']:
178            self.searchterm = form['searchterm']
179            self.searchtype = form['searchtype']
180        elif 'old_searchterm' in form:
181            self.searchterm = form['old_searchterm']
182            self.searchtype = form['old_searchtype']
183        else:
184            if 'search' in form:
[7745]185                self.flash(_('Empty search string'))
[6626]186            return
[7068]187        if self.searchtype == 'current_session':
[8081]188            try:
189                self.searchterm = int(self.searchterm)
190            except ValueError:
[8404]191                self.flash(_('Only year dates allowed (e.g. 2011).'))
[8081]192                return
[6626]193        self.hitlist = search(query=self.searchterm,
194            searchtype=self.searchtype, view=self)
195        if not self.hitlist:
[8404]196            self.flash(_('No student found.'))
[6626]197        return
198
[7819]199class StudentsContainerManagePage(KofaPage):
[6626]200    """The manage page for student containers.
[6622]201    """
202    grok.context(IStudentsContainer)
203    grok.name('manage')
[7136]204    grok.require('waeup.manageStudent')
[6695]205    grok.template('containermanagepage')
[6642]206    pnav = 4
[7723]207    label = _('Manage student section')
[7735]208    search_button = _('Search')
209    remove_button = _('Remove selected')
[6622]210
[6626]211    def update(self, *args, **kw):
212        datatable.need()
[6820]213        toggleall.need()
[7329]214        warning.need()
[6626]215        form = self.request.form
216        self.hitlist = []
217        if 'searchterm' in form and form['searchterm']:
218            self.searchterm = form['searchterm']
219            self.searchtype = form['searchtype']
220        elif 'old_searchterm' in form:
221            self.searchterm = form['old_searchterm']
222            self.searchtype = form['old_searchtype']
223        else:
224            if 'search' in form:
[7745]225                self.flash(_('Empty search string'))
[6626]226            return
[8082]227        if self.searchtype == 'current_session':
228            try:
229                self.searchterm = int(self.searchterm)
230            except ValueError:
231                self.flash('Only year dates allowed (e.g. 2011).')
232                return
[6626]233        if not 'entries' in form:
234            self.hitlist = search(query=self.searchterm,
235                searchtype=self.searchtype, view=self)
236            if not self.hitlist:
[7723]237                self.flash(_('No student found.'))
[7459]238            if 'remove' in form:
[7723]239                self.flash(_('No item selected.'))
[6626]240            return
241        entries = form['entries']
242        if isinstance(entries, basestring):
243            entries = [entries]
244        deleted = []
245        for entry in entries:
246            if 'remove' in form:
247                del self.context[entry]
248                deleted.append(entry)
249        self.hitlist = search(query=self.searchterm,
250            searchtype=self.searchtype, view=self)
251        if len(deleted):
[7723]252            self.flash(_('Successfully removed: ${a}',
253                mapping = {'a':', '.join(deleted)}))
[6622]254        return
255
[7819]256class StudentAddFormPage(KofaAddFormPage):
[6622]257    """Add-form to add a student.
258    """
259    grok.context(IStudentsContainer)
[7136]260    grok.require('waeup.manageStudent')
[6622]261    grok.name('addstudent')
[7357]262    form_fields = grok.AutoFields(IStudent).select(
[7520]263        'firstname', 'middlename', 'lastname', 'reg_number')
[7723]264    label = _('Add student')
[6642]265    pnav = 4
[6622]266
[7723]267    @action(_('Create student record'), style='primary')
[6622]268    def addStudent(self, **data):
269        student = createObject(u'waeup.Student')
270        self.applyData(student, **data)
[6652]271        self.context.addStudent(student)
[7723]272        self.flash(_('Student record created.'))
[6651]273        self.redirect(self.url(self.context[student.student_id], 'index'))
[6622]274        return
275
[7819]276class StudentBaseDisplayFormPage(KofaDisplayFormPage):
[6631]277    """ Page to display student base data
278    """
[6622]279    grok.context(IStudent)
280    grok.name('index')
[6660]281    grok.require('waeup.viewStudent')
[6695]282    grok.template('basepage')
[6756]283    form_fields = grok.AutoFields(IStudentBase).omit('password')
[6642]284    pnav = 4
[6622]285
286    @property
287    def label(self):
[7723]288        return _('${a}: Base Data',
289            mapping = {'a':self.context.display_fullname})
[6631]290
[6699]291    @property
292    def hasPassword(self):
293        if self.context.password:
[7723]294            return _('set')
295        return _('unset')
[6699]296
[7229]297class ContactStudentForm(ContactAdminForm):
298    grok.context(IStudent)
[7230]299    grok.name('contactstudent')
[7275]300    grok.require('waeup.viewStudent')
[7229]301    pnav = 4
302    form_fields = grok.AutoFields(IContactForm).select('subject', 'body')
303
[7275]304    def update(self, subject=u''):
305        self.form_fields.get('subject').field.default = subject
306        self.subject = subject
307        return
308
[7229]309    def label(self):
[7723]310        return _(u'Send message to ${a}',
311            mapping = {'a':self.context.display_fullname})
[7229]312
[7459]313    @action('Send message now', style='primary')
[7229]314    def send(self, *args, **data):
[7234]315        try:
[7403]316            email = self.request.principal.email
[7234]317        except AttributeError:
[7403]318            email = self.config.email_admin
319        usertype = getattr(self.request.principal,
320                           'user_type', 'system').title()
[7819]321        kofa_utils = getUtility(IKofaUtils)
[7811]322        success = kofa_utils.sendContactForm(
[7403]323                self.request.principal.title,email,
324                self.context.display_fullname,self.context.email,
325                self.request.principal.id,usertype,
326                self.config.name,
327                data['body'],data['subject'])
[7229]328        if success:
[7723]329            self.flash(_('Your message has been sent.'))
[7229]330        else:
[7723]331            self.flash(_('An smtp server error occurred.'))
[7229]332        return
333
[7819]334class StudentBaseManageFormPage(KofaEditFormPage):
[7133]335    """ View to manage student base data
[6631]336    """
337    grok.context(IStudent)
[7133]338    grok.name('manage_base')
[7136]339    grok.require('waeup.manageStudent')
[6631]340    form_fields = grok.AutoFields(IStudentBase).omit('student_id')
[6695]341    grok.template('basemanagepage')
[7723]342    label = _('Manage base data')
[6642]343    pnav = 4
[6631]344
[6638]345    def update(self):
346        datepicker.need() # Enable jQuery datepicker in date fields.
[7134]347        tabs.need()
[7490]348        self.tab1 = self.tab2 = ''
349        qs = self.request.get('QUERY_STRING', '')
350        if not qs:
351            qs = 'tab1'
352        setattr(self, qs, 'active')
[6638]353        super(StudentBaseManageFormPage, self).update()
354        self.wf_info = IWorkflowInfo(self.context)
355        return
356
357    def getTransitions(self):
358        """Return a list of dicts of allowed transition ids and titles.
359
360        Each list entry provides keys ``name`` and ``title`` for
361        internal name and (human readable) title of a single
362        transition.
363        """
[8434]364        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
365            if not t[0].startswith('pay')]
[7687]366        return [dict(name='', title=_('No transition'))] +[
[6638]367            dict(name=x, title=y) for x, y in allowed_transitions]
368
[7723]369    @action(_('Save'), style='primary')
[6638]370    def save(self, **data):
[6701]371        form = self.request.form
[6790]372        password = form.get('password', None)
373        password_ctl = form.get('control_password', None)
374        if password:
[7147]375            validator = getUtility(IPasswordValidator)
376            errors = validator.validate_password(password, password_ctl)
377            if errors:
378                self.flash( ' '.join(errors))
379                return
380        changed_fields = self.applyData(self.context, **data)
[6771]381        # Turn list of lists into single list
382        if changed_fields:
383            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7147]384        else:
385            changed_fields = []
386        if password:
387            # Now we know that the form has no errors and can set password ...
388            IUserAccount(self.context).setPassword(password)
389            changed_fields.append('password')
390        # ... and execute transition
[6638]391        if form.has_key('transition') and form['transition']:
392            transition_id = form['transition']
393            self.wf_info.fireTransition(transition_id)
[7147]394        fields_string = ' + '.join(changed_fields)
[7723]395        self.flash(_('Form has been saved.'))
[6644]396        if fields_string:
[6943]397            write_log_message(self, 'saved: % s' % fields_string)
[6638]398        return
399
[7819]400class StudentClearanceDisplayFormPage(KofaDisplayFormPage):
[6631]401    """ Page to display student clearance data
402    """
403    grok.context(IStudent)
404    grok.name('view_clearance')
[6660]405    grok.require('waeup.viewStudent')
[6642]406    pnav = 4
[6631]407
408    @property
[8099]409    def separators(self):
410        return getUtility(IStudentsUtils).SEPARATORS_DICT
411
412    @property
[7993]413    def form_fields(self):
[8472]414        if self.context.is_postgrad:
[7993]415            form_fields = grok.AutoFields(IPGStudentClearance).omit('clearance_locked')
416        else:
417            form_fields = grok.AutoFields(IUGStudentClearance).omit('clearance_locked')
418        return form_fields
419
420    @property
[6631]421    def label(self):
[7723]422        return _('${a}: Clearance Data',
423            mapping = {'a':self.context.display_fullname})
[6631]424
[7277]425class ExportPDFClearanceSlipPage(grok.View):
426    """Deliver a PDF slip of the context.
427    """
428    grok.context(IStudent)
429    grok.name('clearance.pdf')
430    grok.require('waeup.viewStudent')
431    prefix = 'form'
432
433    @property
[7993]434    def form_fields(self):
[8472]435        if self.context.is_postgrad:
[7993]436            form_fields = grok.AutoFields(IPGStudentClearance).omit('clearance_locked')
437        else:
438            form_fields = grok.AutoFields(IUGStudentClearance).omit('clearance_locked')
439        return form_fields
440
441    @property
[7723]442    def title(self):
[7819]443        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]444        return translate(_('Clearance Data'), 'waeup.kofa',
[7723]445            target_language=portal_language)
446
447    @property
[7277]448    def label(self):
[7819]449        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7723]450        return translate(_('Clearance Slip of '),
[7811]451            'waeup.kofa', target_language=portal_language) \
[7723]452            + ' %s' % self.context.display_fullname
[7277]453
454    def render(self):
455        studentview = StudentBaseDisplayFormPage(self.context.getStudent(),
456            self.request)
457        students_utils = getUtility(IStudentsUtils)
458        return students_utils.renderPDF(
[7318]459            self, 'clearance.pdf',
[7310]460            self.context.getStudent(), studentview)
[7277]461
[7819]462class StudentClearanceManageFormPage(KofaEditFormPage):
[8120]463    """ Page to manage student clearance data
[6631]464    """
465    grok.context(IStudent)
[8119]466    grok.name('manage_clearance')
[7136]467    grok.require('waeup.manageStudent')
[7134]468    grok.template('clearanceeditpage')
[7723]469    label = _('Manage clearance data')
[6642]470    pnav = 4
[6650]471
[7993]472    @property
[8099]473    def separators(self):
474        return getUtility(IStudentsUtils).SEPARATORS_DICT
475
476    @property
[7993]477    def form_fields(self):
[8472]478        if self.context.is_postgrad:
[7993]479            form_fields = grok.AutoFields(IPGStudentClearance)
480        else:
481            form_fields = grok.AutoFields(IUGStudentClearance)
482        return form_fields
483
[6650]484    def update(self):
485        datepicker.need() # Enable jQuery datepicker in date fields.
[7134]486        tabs.need()
[7490]487        self.tab1 = self.tab2 = ''
488        qs = self.request.get('QUERY_STRING', '')
489        if not qs:
490            qs = 'tab1'
491        setattr(self, qs, 'active')
[6650]492        return super(StudentClearanceManageFormPage, self).update()
493
[7723]494    @action(_('Save'), style='primary')
[6695]495    def save(self, **data):
[6762]496        msave(self, **data)
[6695]497        return
498
[7459]499class StudentClearPage(UtilityView, grok.View):
[7158]500    """ Clear student by clearance officer
501    """
502    grok.context(IStudent)
503    grok.name('clear')
504    grok.require('waeup.clearStudent')
505
506    def update(self):
507        if self.context.state == REQUESTED:
508            IWorkflowInfo(self.context).fireTransition('clear')
[7723]509            self.flash(_('Student has been cleared.'))
[7158]510        else:
[7723]511            self.flash(_('Student is in wrong state.'))
[7158]512        self.redirect(self.url(self.context,'view_clearance'))
513        return
514
515    def render(self):
516        return
517
[7459]518class StudentRejectClearancePage(UtilityView, grok.View):
[7158]519    """ Reject clearance by clearance officers
520    """
521    grok.context(IStudent)
522    grok.name('reject_clearance')
523    grok.require('waeup.clearStudent')
524
525    def update(self):
526        if self.context.state == CLEARED:
527            IWorkflowInfo(self.context).fireTransition('reset4')
[7723]528            message = _('Clearance has been annulled.')
[7275]529            self.flash(message)
[7158]530        elif self.context.state == REQUESTED:
531            IWorkflowInfo(self.context).fireTransition('reset3')
[7723]532            message = _('Clearance request has been rejected.')
[7275]533            self.flash(message)
[7158]534        else:
[7723]535            self.flash(_('Student is in wrong state.'))
[7334]536            self.redirect(self.url(self.context,'view_clearance'))
[7275]537            return
538        args = {'subject':message}
539        self.redirect(self.url(self.context) +
540            '/contactstudent?%s' % urlencode(args))
[7158]541        return
542
543    def render(self):
544        return
545
[7819]546class StudentPersonalDisplayFormPage(KofaDisplayFormPage):
[6631]547    """ Page to display student personal data
548    """
549    grok.context(IStudent)
550    grok.name('view_personal')
[6660]551    grok.require('waeup.viewStudent')
[6631]552    form_fields = grok.AutoFields(IStudentPersonal)
[7386]553    form_fields['perm_address'].custom_widget = BytesDisplayWidget
[6642]554    pnav = 4
[6631]555
556    @property
557    def label(self):
[7723]558        return _('${a}: Personal Data',
559            mapping = {'a':self.context.display_fullname})
[6631]560
[8119]561class StudentPersonalEditFormPage(KofaEditFormPage):
[8120]562    """ Page to edit personal data
[6631]563    """
564    grok.context(IStudent)
565    grok.name('edit_personal')
[8119]566    grok.require('waeup.handleStudent')
[6631]567    form_fields = grok.AutoFields(IStudentPersonal)
[8119]568    label = _('Edit personal data')
[6642]569    pnav = 4
[6631]570
[7723]571    @action(_('Save'), style='primary')
[6762]572    def save(self, **data):
573        msave(self, **data)
574        return
575
[7819]576class StudyCourseDisplayFormPage(KofaDisplayFormPage):
[6635]577    """ Page to display the student study course data
578    """
579    grok.context(IStudentStudyCourse)
580    grok.name('index')
[6660]581    grok.require('waeup.viewStudent')
[6635]582    form_fields = grok.AutoFields(IStudentStudyCourse)
[6775]583    grok.template('studycoursepage')
[6642]584    pnav = 4
[6635]585
586    @property
587    def label(self):
[7723]588        return _('${a}: Study Course',
589            mapping = {'a':self.context.__parent__.display_fullname})
[6635]590
[6912]591    @property
592    def current_mode(self):
[7641]593        if self.context.certificate is not None:
[7841]594            studymodes_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
[7681]595            return studymodes_dict[self.context.certificate.study_mode]
[7171]596        return
[7642]597
[7171]598    @property
599    def department(self):
[7205]600        if self.context.certificate is not None:
[7171]601            return self.context.certificate.__parent__.__parent__
602        return
[6912]603
[7171]604    @property
605    def faculty(self):
[7205]606        if self.context.certificate is not None:
[7171]607            return self.context.certificate.__parent__.__parent__.__parent__
608        return
609
[7819]610class StudyCourseManageFormPage(KofaEditFormPage):
[6649]611    """ Page to edit the student study course data
612    """
613    grok.context(IStudentStudyCourse)
[6775]614    grok.name('manage')
[7136]615    grok.require('waeup.manageStudent')
[6775]616    grok.template('studycoursemanagepage')
[6649]617    form_fields = grok.AutoFields(IStudentStudyCourse)
[7723]618    label = _('Manage study course')
[6649]619    pnav = 4
[7723]620    taboneactions = [_('Save'),_('Cancel')]
621    tabtwoactions = [_('Remove selected levels'),_('Cancel')]
622    tabthreeactions = [_('Add study level')]
[6649]623
[6775]624    def update(self):
625        super(StudyCourseManageFormPage, self).update()
626        tabs.need()
[7484]627        self.tab1 = self.tab2 = ''
628        qs = self.request.get('QUERY_STRING', '')
629        if not qs:
630            qs = 'tab1'
631        setattr(self, qs, 'active')
[7490]632        warning.need()
633        datatable.need()
634        return
[6775]635
[7723]636    @action(_('Save'), style='primary')
[6761]637    def save(self, **data):
[8099]638        try:
639            msave(self, **data)
640        except ConstraintNotSatisfied:
641            # The selected level might not exist in certificate
642            self.flash(_('Current level not available for certificate.'))
643            return
[8081]644        notify(grok.ObjectModifiedEvent(self.context.__parent__))
[6761]645        return
646
[6775]647    @property
648    def level_dict(self):
649        studylevelsource = StudyLevelSource().factory
650        for code in studylevelsource.getValues(self.context):
651            title = studylevelsource.getTitle(self.context, code)
652            yield(dict(code=code, title=title))
653
[7723]654    @action(_('Add study level'))
[6774]655    def addStudyLevel(self, **data):
[6775]656        level_code = self.request.form.get('addlevel', None)
[8323]657        studylevel = createObject(u'waeup.StudentStudyLevel')
[6775]658        studylevel.level = int(level_code)
659        try:
[6782]660            self.context.addStudentStudyLevel(
661                self.context.certificate,studylevel)
[7723]662            self.flash(_('Study level has been added.'))
[6775]663        except KeyError:
[7723]664            self.flash(_('This level exists.'))
[7484]665        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6774]666        return
667
[7723]668    @jsaction(_('Remove selected levels'))
[6775]669    def delStudyLevels(self, **data):
670        form = self.request.form
671        if form.has_key('val_id'):
672            child_id = form['val_id']
673        else:
[7723]674            self.flash(_('No study level selected.'))
[7484]675            self.redirect(self.url(self.context, '@@manage')+'?tab2')
[6775]676            return
677        if not isinstance(child_id, list):
678            child_id = [child_id]
679        deleted = []
680        for id in child_id:
[7723]681            del self.context[id]
682            deleted.append(id)
[6775]683        if len(deleted):
[7723]684            self.flash(_('Successfully removed: ${a}',
685                mapping = {'a':', '.join(deleted)}))
[7484]686        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6775]687        return
[6774]688
[7819]689class StudyLevelDisplayFormPage(KofaDisplayFormPage):
[6774]690    """ Page to display student study levels
691    """
692    grok.context(IStudentStudyLevel)
693    grok.name('index')
694    grok.require('waeup.viewStudent')
[6775]695    form_fields = grok.AutoFields(IStudentStudyLevel)
[6783]696    grok.template('studylevelpage')
[6774]697    pnav = 4
698
[7310]699    def update(self):
700        super(StudyLevelDisplayFormPage, self).update()
701        datatable.need()
702        return
703
[6774]704    @property
[8141]705    def translated_values(self):
706        lang = self.request.cookies.get('kofa.language')
707        for value in self.context.values():
[8558]708            value_dict = dict([i for i in value.__dict__.items()])
[8141]709            value_dict['mandatory'] = translate(str(value.mandatory), 'zope',
710                target_language=lang)
711            value_dict['carry_over'] = translate(str(value.carry_over), 'zope',
712                target_language=lang)
713            value_dict['automatic'] = translate(str(value.automatic), 'zope',
714                target_language=lang)
715            yield value_dict
716
717    @property
[6774]718    def label(self):
[7833]719        # Here we know that the cookie has been set
720        lang = self.request.cookies.get('kofa.language')
[7811]721        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]722            target_language=lang)
723        return _('${a}: Study Level ${b}', mapping = {
724            'a':self.context.getStudent().display_fullname,
725            'b':level_title})
[6774]726
[6803]727    @property
728    def total_credits(self):
729        total_credits = 0
730        for key, val in self.context.items():
731            total_credits += val.credits
732        return total_credits
733
[7459]734class ExportPDFCourseRegistrationSlipPage(UtilityView, grok.View):
[7028]735    """Deliver a PDF slip of the context.
736    """
737    grok.context(IStudentStudyLevel)
738    grok.name('course_registration.pdf')
739    grok.require('waeup.viewStudent')
740    form_fields = grok.AutoFields(IStudentStudyLevel)
741    prefix = 'form'
742
743    @property
[7723]744    def title(self):
[7819]745        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]746        return translate(_('Level Data'), 'waeup.kofa',
[7723]747            target_language=portal_language)
748
749    @property
750    def content_title(self):
[7819]751        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]752        return translate(_('Course List'), 'waeup.kofa',
[7723]753            target_language=portal_language)
754
755    @property
[7028]756    def label(self):
[7819]757        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]758        lang = self.request.cookies.get('kofa.language', portal_language)
759        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]760            target_language=lang)
[8141]761        return translate(_('Course Registration Slip'),
[7811]762            'waeup.kofa', target_language=portal_language) \
[7723]763            + ' %s' % level_title
[7028]764
765    def render(self):
[7819]766        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]767        Sem = translate(_('Sem.'), 'waeup.kofa', target_language=portal_language)
768        Code = translate(_('Code'), 'waeup.kofa', target_language=portal_language)
769        Title = translate(_('Title'), 'waeup.kofa', target_language=portal_language)
770        Dept = translate(_('Dept.'), 'waeup.kofa', target_language=portal_language)
771        Faculty = translate(_('Faculty'), 'waeup.kofa', target_language=portal_language)
772        Cred = translate(_('Cred.'), 'waeup.kofa', target_language=portal_language)
773        Mand = translate(_('Mand.'), 'waeup.kofa', target_language=portal_language)
774        Score = translate(_('Score'), 'waeup.kofa', target_language=portal_language)
[7028]775        studentview = StudentBaseDisplayFormPage(self.context.getStudent(),
776            self.request)
[7150]777        students_utils = getUtility(IStudentsUtils)
[7318]778        tabledata = sorted(self.context.values(),
779            key=lambda value: str(value.semester) + value.code)
[7186]780        return students_utils.renderPDF(
[7318]781            self, 'course_registration.pdf',
[7310]782            self.context.getStudent(), studentview,
[7723]783            tableheader=[(Sem,'semester', 1.5),(Code,'code', 2.5),
784                         (Title,'title', 5),
785                         (Dept,'dcode', 1.5), (Faculty,'fcode', 1.5),
786                         (Cred, 'credits', 1.5),
787                         (Mand, 'mandatory', 1.5),
[8141]788                         (Score, 'score', 1.5),
789                         #('Auto', 'automatic', 1.5)
[7304]790                         ],
[7318]791            tabledata=tabledata)
[7028]792
[7819]793class StudyLevelManageFormPage(KofaEditFormPage):
[6792]794    """ Page to edit the student study level data
795    """
796    grok.context(IStudentStudyLevel)
797    grok.name('manage')
[7136]798    grok.require('waeup.manageStudent')
[6792]799    grok.template('studylevelmanagepage')
800    form_fields = grok.AutoFields(IStudentStudyLevel)
801    pnav = 4
[7723]802    taboneactions = [_('Save'),_('Cancel')]
803    tabtwoactions = [_('Add course ticket'),
804        _('Remove selected tickets'),_('Cancel')]
[6792]805
806    def update(self):
807        super(StudyLevelManageFormPage, self).update()
808        tabs.need()
[7484]809        self.tab1 = self.tab2 = ''
810        qs = self.request.get('QUERY_STRING', '')
811        if not qs:
812            qs = 'tab1'
813        setattr(self, qs, 'active')
[7490]814        warning.need()
815        datatable.need()
[6792]816        return
817
818    @property
819    def label(self):
[7833]820        # Here we know that the cookie has been set
821        lang = self.request.cookies.get('kofa.language')
[7811]822        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]823            target_language=lang)
824        return _('Manage study level ${a}',
825            mapping = {'a':level_title})
[6792]826
[7723]827    @action(_('Save'), style='primary')
[6792]828    def save(self, **data):
829        msave(self, **data)
830        return
831
[7723]832    @action(_('Add course ticket'))
[6795]833    def addCourseTicket(self, **data):
834        self.redirect(self.url(self.context, '@@add'))
[6792]835
[7723]836    @jsaction(_('Remove selected tickets'))
[6792]837    def delCourseTicket(self, **data):
838        form = self.request.form
839        if form.has_key('val_id'):
840            child_id = form['val_id']
841        else:
[7723]842            self.flash(_('No ticket selected.'))
[7484]843            self.redirect(self.url(self.context, '@@manage')+'?tab2')
[6792]844            return
845        if not isinstance(child_id, list):
846            child_id = [child_id]
847        deleted = []
848        for id in child_id:
[7723]849            del self.context[id]
850            deleted.append(id)
[6792]851        if len(deleted):
[7723]852            self.flash(_('Successfully removed: ${a}',
853                mapping = {'a':', '.join(deleted)}))
[7484]854        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6792]855        return
856
[7459]857class ValidateCoursesPage(UtilityView, grok.View):
[7334]858    """ Validate course list by course adviser
859    """
860    grok.context(IStudentStudyLevel)
861    grok.name('validate_courses')
862    grok.require('waeup.validateStudent')
863
864    def update(self):
865        if str(self.context.__parent__.current_level) != self.context.__name__:
[7723]866            self.flash(_('This level does not correspond current level.'))
[7334]867        elif self.context.getStudent().state == REGISTERED:
[7642]868            IWorkflowInfo(self.context.getStudent()).fireTransition(
869                'validate_courses')
[7723]870            self.flash(_('Course list has been validated.'))
[7334]871        else:
[7723]872            self.flash(_('Student is in the wrong state.'))
[7334]873        self.redirect(self.url(self.context))
874        return
875
876    def render(self):
877        return
878
[7459]879class RejectCoursesPage(UtilityView, grok.View):
[7334]880    """ Reject course list by course adviser
881    """
882    grok.context(IStudentStudyLevel)
883    grok.name('reject_courses')
884    grok.require('waeup.validateStudent')
885
886    def update(self):
887        if str(self.context.__parent__.current_level) != self.context.__name__:
[7723]888            self.flash(_('This level does not correspond current level.'))
[7334]889            self.redirect(self.url(self.context))
890            return
891        elif self.context.getStudent().state == VALIDATED:
892            IWorkflowInfo(self.context.getStudent()).fireTransition('reset8')
[7723]893            message = _('Course list request has been annulled.')
[7334]894            self.flash(message)
895        elif self.context.getStudent().state == REGISTERED:
896            IWorkflowInfo(self.context.getStudent()).fireTransition('reset7')
[7723]897            message = _('Course list request has been rejected:')
[7334]898            self.flash(message)
899        else:
[7723]900            self.flash(_('Student is in the wrong state.'))
[7334]901            self.redirect(self.url(self.context))
902            return
903        args = {'subject':message}
904        self.redirect(self.url(self.context.getStudent()) +
905            '/contactstudent?%s' % urlencode(args))
906        return
907
908    def render(self):
909        return
910
[7819]911class CourseTicketAddFormPage(KofaAddFormPage):
[6808]912    """Add a course ticket.
[6795]913    """
914    grok.context(IStudentStudyLevel)
915    grok.name('add')
[7136]916    grok.require('waeup.manageStudent')
[7723]917    label = _('Add course ticket')
[6808]918    form_fields = grok.AutoFields(ICourseTicketAdd).omit(
[8141]919        'score', 'automatic', 'carry_over')
[6795]920    pnav = 4
921
[7723]922    @action(_('Add course ticket'))
[6795]923    def addCourseTicket(self, **data):
[8325]924        ticket = createObject(u'waeup.CourseTicket')
[6795]925        course = data['course']
[6802]926        ticket.automatic = False
[8141]927        ticket.carry_over = False
[6795]928        ticket.code = course.code
929        ticket.title = course.title
[7304]930        ticket.fcode = course.__parent__.__parent__.__parent__.code
931        ticket.dcode = course.__parent__.__parent__.code
[6795]932        ticket.credits = course.credits
933        ticket.passmark = course.passmark
934        ticket.semester = course.semester
935        try:
936            self.context.addCourseTicket(ticket)
937        except KeyError:
[7723]938            self.flash(_('The ticket exists.'))
[6795]939            return
[7723]940        self.flash(_('Successfully added ${a}.',
941            mapping = {'a':ticket.code}))
[7484]942        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6795]943        return
944
[7834]945    @action(_('Cancel'), validator=NullValidator)
[6795]946    def cancel(self, **data):
947        self.redirect(self.url(self.context))
948
[7819]949class CourseTicketDisplayFormPage(KofaDisplayFormPage):
[6796]950    """ Page to display course tickets
951    """
952    grok.context(ICourseTicket)
953    grok.name('index')
954    grok.require('waeup.viewStudent')
955    form_fields = grok.AutoFields(ICourseTicket)
956    grok.template('courseticketpage')
957    pnav = 4
958
959    @property
960    def label(self):
[7723]961        return _('${a}: Course Ticket ${b}', mapping = {
962            'a':self.context.getStudent().display_fullname,
963            'b':self.context.code})
[6796]964
[7819]965class CourseTicketManageFormPage(KofaEditFormPage):
[6796]966    """ Page to manage course tickets
967    """
968    grok.context(ICourseTicket)
969    grok.name('manage')
[7136]970    grok.require('waeup.manageStudent')
[6796]971    form_fields = grok.AutoFields(ICourseTicket)
972    grok.template('courseticketmanagepage')
973    pnav = 4
974
975    @property
976    def label(self):
[7723]977        return _('Manage course ticket ${a}', mapping = {'a':self.context.code})
[6796]978
[7459]979    @action('Save', style='primary')
[6796]980    def save(self, **data):
981        msave(self, **data)
982        return
983
[7819]984class PaymentsManageFormPage(KofaEditFormPage):
[6869]985    """ Page to manage the student payments
[7642]986
987    This manage form page is for both students and students officers.
[6869]988    """
989    grok.context(IStudentPaymentsContainer)
[6940]990    grok.name('index')
[7181]991    grok.require('waeup.payStudent')
[6869]992    form_fields = grok.AutoFields(IStudentPaymentsContainer)
993    grok.template('paymentsmanagepage')
994    pnav = 4
995
[6940]996    def unremovable(self, ticket):
[7251]997        usertype = getattr(self.request.principal, 'user_type', None)
998        if not usertype:
999            return False
1000        return (self.request.principal.user_type == 'student' and ticket.r_code)
[6940]1001
[6869]1002    @property
1003    def label(self):
[7723]1004        return _('${a}: Payments',
1005            mapping = {'a':self.context.__parent__.display_fullname})
[6869]1006
1007    def update(self):
1008        super(PaymentsManageFormPage, self).update()
1009        datatable.need()
[7329]1010        warning.need()
[6869]1011        return
1012
[7723]1013    @jsaction(_('Remove selected tickets'))
[6869]1014    def delPaymentTicket(self, **data):
1015        form = self.request.form
1016        if form.has_key('val_id'):
1017            child_id = form['val_id']
1018        else:
[7723]1019            self.flash(_('No payment selected.'))
[6940]1020            self.redirect(self.url(self.context))
[6869]1021            return
1022        if not isinstance(child_id, list):
1023            child_id = [child_id]
1024        deleted = []
1025        for id in child_id:
[6992]1026            # Students are not allowed to remove used payment tickets
[6940]1027            if not self.unremovable(self.context[id]):
[7723]1028                del self.context[id]
1029                deleted.append(id)
[6869]1030        if len(deleted):
[7723]1031            self.flash(_('Successfully removed: ${a}',
1032                mapping = {'a': ', '.join(deleted)}))
[6943]1033            write_log_message(self,'removed: % s' % ', '.join(deleted))
[6940]1034        self.redirect(self.url(self.context))
[6869]1035        return
1036
[7723]1037    @action(_('Add online payment ticket'))
[6869]1038    def addPaymentTicket(self, **data):
1039        self.redirect(self.url(self.context, '@@addop'))
1040
[7819]1041class OnlinePaymentAddFormPage(KofaAddFormPage):
[6869]1042    """ Page to add an online payment ticket
1043    """
1044    grok.context(IStudentPaymentsContainer)
1045    grok.name('addop')
[7181]1046    grok.require('waeup.payStudent')
[6877]1047    form_fields = grok.AutoFields(IStudentOnlinePayment).select(
[6869]1048        'p_category')
[7723]1049    label = _('Add online payment')
[6869]1050    pnav = 4
[8245]1051    factory = u'waeup.StudentOnlinePayment'
[7642]1052
[8245]1053    def _fillCustomFields(self, payment, pay_details):
1054        """No custom fields in the base package
1055        """
[8246]1056        return payment
[8245]1057
[7723]1058    @action(_('Create ticket'), style='primary')
[6869]1059    def createTicket(self, **data):
[7024]1060        p_category = data['p_category']
1061        student = self.context.__parent__
1062        if p_category == 'bed_allocation' and student[
1063            'studycourse'].current_session != grok.getSite()[
1064            'configuration'].accommodation_session:
1065                self.flash(
[7723]1066                    _('Your current session does not match ' + \
1067                    'accommodation session.'))
[7024]1068                self.redirect(self.url(self.context))
1069                return
[7150]1070        students_utils = getUtility(IStudentsUtils)
[8081]1071        try:
1072            pay_details  = students_utils.getPaymentDetails(
1073                p_category,student)
[8268]1074        except (AttributeError, TypeError):
[8081]1075            self.flash(
1076                _('Study course data are incomplete.'))
1077            self.redirect(self.url(self.context))
1078            return
[6994]1079        if pay_details['error']:
1080            self.flash(pay_details['error'])
[6940]1081            self.redirect(self.url(self.context))
[6920]1082            return
[7025]1083        p_item = pay_details['p_item']
1084        p_session = pay_details['p_session']
1085        for key in self.context.keys():
1086            ticket = self.context[key]
[7248]1087            if ticket.p_state == 'paid' and\
1088               ticket.p_category == p_category and \
[7025]1089               ticket.p_item == p_item and \
1090               ticket.p_session == p_session:
1091                  self.flash(
[7723]1092                      _('This type of payment has already been made.'))
[7025]1093                  self.redirect(self.url(self.context))
1094                  return
[8245]1095        payment = createObject(self.factory)
[7025]1096        self.applyData(payment, **data)
1097        timestamp = "%d" % int(time()*1000)
1098        payment.p_id = "p%s" % timestamp
1099        payment.p_item = p_item
1100        payment.p_session = p_session
[8268]1101        payment.p_level = pay_details['p_level']
[6994]1102        payment.amount_auth = pay_details['amount']
[8245]1103        payment = self._fillCustomFields(payment, pay_details)
[6869]1104        self.context[payment.p_id] = payment
[7723]1105        self.flash(_('Payment ticket created.'))
[6940]1106        self.redirect(self.url(self.context))
[6869]1107        return
1108
[7819]1109class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[6869]1110    """ Page to view an online payment ticket
1111    """
[6877]1112    grok.context(IStudentOnlinePayment)
[6869]1113    grok.name('index')
1114    grok.require('waeup.viewStudent')
[6877]1115    form_fields = grok.AutoFields(IStudentOnlinePayment)
[8170]1116    form_fields[
1117        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
1118    form_fields[
1119        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[6869]1120    pnav = 4
1121
1122    @property
1123    def label(self):
[7723]1124        return _('${a}: Online Payment Ticket ${b}', mapping = {
1125            'a':self.context.getStudent().display_fullname,
1126            'b':self.context.p_id})
[6869]1127
[8420]1128class OnlinePaymentApprovePage(UtilityView, grok.View):
[6930]1129    """ Callback view
1130    """
1131    grok.context(IStudentOnlinePayment)
[8420]1132    grok.name('approve')
1133    grok.require('waeup.managePortal')
[6930]1134
1135    def update(self):
[8428]1136        success, msg, log = self.context.approveStudentPayment()
1137        if log is not None:
1138            write_log_message(self,log)
[8420]1139        self.flash(msg)
[6940]1140        return
[6930]1141
1142    def render(self):
[6940]1143        self.redirect(self.url(self.context, '@@index'))
[6930]1144        return
1145
[8420]1146class OnlinePaymentFakeApprovePage(OnlinePaymentApprovePage):
1147    """ Approval view for students.
1148
1149    This view is used for browser tests only and
1150    must be neutralized in custom pages!
1151    """
1152
1153    grok.name('fake_approve')
1154    grok.require('waeup.payStudent')
1155
[7459]1156class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7019]1157    """Deliver a PDF slip of the context.
1158    """
1159    grok.context(IStudentOnlinePayment)
[8262]1160    grok.name('payment_slip.pdf')
[7019]1161    grok.require('waeup.viewStudent')
1162    form_fields = grok.AutoFields(IStudentOnlinePayment)
[8173]1163    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
1164    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7019]1165    prefix = 'form'
[8258]1166    note = None
[7019]1167
1168    @property
[8262]1169    def title(self):
1170        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1171        return translate(_('Payment Data'), 'waeup.kofa',
1172            target_language=portal_language)
1173
1174    @property
[7019]1175    def label(self):
[8262]1176        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1177        return translate(_('Online Payment Slip'),
1178            'waeup.kofa', target_language=portal_language) \
1179            + ' %s' % self.context.p_id
[7019]1180
1181    def render(self):
[8262]1182        #if self.context.p_state != 'paid':
1183        #    self.flash('Ticket not yet paid.')
1184        #    self.redirect(self.url(self.context))
1185        #    return
[7019]1186        studentview = StudentBaseDisplayFormPage(self.context.getStudent(),
1187            self.request)
[7150]1188        students_utils = getUtility(IStudentsUtils)
[8262]1189        return students_utils.renderPDF(self, 'payment_slip.pdf',
[8258]1190            self.context.getStudent(), studentview, note=self.note)
[7019]1191
[6992]1192
[7819]1193class AccommodationManageFormPage(KofaEditFormPage):
[7009]1194    """ Page to manage bed tickets.
[7642]1195
1196    This manage form page is for both students and students officers.
[6635]1197    """
1198    grok.context(IStudentAccommodation)
1199    grok.name('index')
[7181]1200    grok.require('waeup.handleAccommodation')
[6635]1201    form_fields = grok.AutoFields(IStudentAccommodation)
[6992]1202    grok.template('accommodationmanagepage')
[6642]1203    pnav = 4
[7723]1204    officers_only_actions = [_('Remove selected')]
[6635]1205
1206    @property
1207    def label(self):
[7723]1208        return _('${a}: Accommodation',
1209            mapping = {'a':self.context.__parent__.display_fullname})
[6637]1210
[6992]1211    def update(self):
1212        super(AccommodationManageFormPage, self).update()
1213        datatable.need()
[7329]1214        warning.need()
[6992]1215        return
1216
[7723]1217    @jsaction(_('Remove selected'))
[7009]1218    def delBedTickets(self, **data):
[7240]1219        if getattr(self.request.principal, 'user_type', None) == 'student':
[7723]1220            self.flash(_('You are not allowed to remove bed tickets.'))
[7017]1221            self.redirect(self.url(self.context))
1222            return
[6992]1223        form = self.request.form
1224        if form.has_key('val_id'):
1225            child_id = form['val_id']
1226        else:
[7723]1227            self.flash(_('No bed ticket selected.'))
[6992]1228            self.redirect(self.url(self.context))
1229            return
1230        if not isinstance(child_id, list):
1231            child_id = [child_id]
1232        deleted = []
1233        for id in child_id:
[7068]1234            del self.context[id]
1235            deleted.append(id)
[6992]1236        if len(deleted):
[7723]1237            self.flash(_('Successfully removed: ${a}',
1238                mapping = {'a':', '.join(deleted)}))
[6992]1239            write_log_message(self,'removed: % s' % ', '.join(deleted))
1240        self.redirect(self.url(self.context))
1241        return
1242
[7009]1243    @property
1244    def selected_actions(self):
[7240]1245        if getattr(self.request.principal, 'user_type', None) == 'student':
[7642]1246            return [action for action in self.actions
1247                    if not action.label in self.officers_only_actions]
1248        return self.actions
[7009]1249
[7819]1250class BedTicketAddPage(KofaPage):
[6992]1251    """ Page to add an online payment ticket
1252    """
1253    grok.context(IStudentAccommodation)
1254    grok.name('add')
[7181]1255    grok.require('waeup.handleAccommodation')
[6992]1256    grok.template('enterpin')
[6993]1257    ac_prefix = 'HOS'
[7723]1258    label = _('Add bed ticket')
[6992]1259    pnav = 4
[7723]1260    buttonname = _('Create bed ticket')
[6993]1261    notice = ''
[6992]1262
1263    def update(self, SUBMIT=None):
[6996]1264        student = self.context.getStudent()
[7150]1265        students_utils = getUtility(IStudentsUtils)
[7186]1266        acc_details  = students_utils.getAccommodationDetails(student)
[7369]1267        if not acc_details:
[7723]1268            self.flash(_("Your data are incomplete."))
[7369]1269            self.redirect(self.url(self.context))
1270            return
[6996]1271        if not student.state in acc_details['allowed_states']:
[7723]1272            self.flash(_("You are in the wrong registration state."))
[6992]1273            self.redirect(self.url(self.context))
1274            return
[7642]1275        if student['studycourse'].current_session != acc_details[
1276            'booking_session']:
[7061]1277            self.flash(
[7723]1278                _('Your current session does not match accommodation session.'))
[7061]1279            self.redirect(self.url(self.context))
1280            return
1281        if str(acc_details['booking_session']) in self.context.keys():
[7642]1282            self.flash(
[7723]1283                _('You already booked a bed space in current ' \
1284                    + 'accommodation session.'))
[7004]1285            self.redirect(self.url(self.context))
1286            return
[6992]1287        self.ac_series = self.request.form.get('ac_series', None)
1288        self.ac_number = self.request.form.get('ac_number', None)
1289        if SUBMIT is None:
1290            return
1291        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1292        code = get_access_code(pin)
1293        if not code:
[7723]1294            self.flash(_('Activation code is invalid.'))
[6992]1295            return
[7060]1296        # Search and book bed
[6997]1297        cat = queryUtility(ICatalog, name='beds_catalog', default=None)
1298        entries = cat.searchResults(
[7003]1299            owner=(student.student_id,student.student_id))
1300        if len(entries):
[7060]1301            # If bed space has bee manually allocated use this bed
[7003]1302            bed = [entry for entry in entries][0]
[7060]1303        else:
1304            # else search for other available beds
1305            entries = cat.searchResults(
1306                bed_type=(acc_details['bt'],acc_details['bt']))
1307            available_beds = [
1308                entry for entry in entries if entry.owner == NOT_OCCUPIED]
1309            if available_beds:
[7150]1310                students_utils = getUtility(IStudentsUtils)
[7186]1311                bed = students_utils.selectBed(available_beds)
[7060]1312                bed.bookBed(student.student_id)
1313            else:
[7723]1314                self.flash(_('There is no free bed in your category ${a}.',
1315                    mapping = {'a':acc_details['bt']}))
[7060]1316                return
[6992]1317        # Mark pin as used (this also fires a pin related transition)
1318        if code.state == USED:
[7723]1319            self.flash(_('Activation code has already been used.'))
[6992]1320            return
1321        else:
[7723]1322            comment = _(u'invalidated')
[6992]1323            # Here we know that the ac is in state initialized so we do not
1324            # expect an exception, but the owner might be different
1325            if not invalidate_accesscode(
1326                pin,comment,self.context.getStudent().student_id):
[7723]1327                self.flash(_('You are not the owner of this access code.'))
[6992]1328                return
[7060]1329        # Create bed ticket
[6992]1330        bedticket = createObject(u'waeup.BedTicket')
1331        bedticket.booking_code = pin
[6994]1332        bedticket.booking_session = acc_details['booking_session']
[6996]1333        bedticket.bed_type = acc_details['bt']
[7006]1334        bedticket.bed = bed
[6996]1335        hall_title = bed.__parent__.hostel_name
1336        coordinates = bed.getBedCoordinates()[1:]
1337        block, room_nr, bed_nr = coordinates
[7723]1338        bc = _('${a}, Block ${b}, Room ${c}, Bed ${d} (${e})', mapping = {
1339            'a':hall_title, 'b':block,
1340            'c':room_nr, 'd':bed_nr,
1341            'e':bed.bed_type})
[7819]1342        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7723]1343        bedticket.bed_coordinates = translate(
[7811]1344            bc, 'waeup.kofa',target_language=portal_language)
[6996]1345        key = str(acc_details['booking_session'])
1346        self.context[key] = bedticket
[7723]1347        self.flash(_('Bed ticket created and bed booked: ${a}',
1348            mapping = {'a':bedticket.bed_coordinates}))
[6992]1349        self.redirect(self.url(self.context))
1350        return
1351
[7819]1352class BedTicketDisplayFormPage(KofaDisplayFormPage):
[6994]1353    """ Page to display bed tickets
1354    """
1355    grok.context(IBedTicket)
1356    grok.name('index')
[7181]1357    grok.require('waeup.handleAccommodation')
[6994]1358    form_fields = grok.AutoFields(IBedTicket)
1359    pnav = 4
1360
1361    @property
1362    def label(self):
[7723]1363        return _('Bed Ticket for Session ${a}',
1364            mapping = {'a':self.context.getSessionString()})
[6994]1365
[7459]1366class ExportPDFBedTicketSlipPage(UtilityView, grok.View):
[7027]1367    """Deliver a PDF slip of the context.
1368    """
1369    grok.context(IBedTicket)
1370    grok.name('bed_allocation.pdf')
[7181]1371    grok.require('waeup.handleAccommodation')
[7027]1372    form_fields = grok.AutoFields(IBedTicket)
[8173]1373    form_fields['booking_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7027]1374    prefix = 'form'
1375
1376    @property
[7723]1377    def title(self):
[7819]1378        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]1379        return translate(_('Bed Allocation Data'), 'waeup.kofa',
[7723]1380            target_language=portal_language)
1381
1382    @property
[7027]1383    def label(self):
[7819]1384        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7723]1385        return translate(_('Bed Allocation: '),
[7811]1386            'waeup.kofa', target_language=portal_language) \
[7723]1387            + ' %s' % self.context.bed_coordinates
[7027]1388
1389    def render(self):
1390        studentview = StudentBaseDisplayFormPage(self.context.getStudent(),
1391            self.request)
[7150]1392        students_utils = getUtility(IStudentsUtils)
[7186]1393        return students_utils.renderPDF(
[7318]1394            self, 'bed_allocation.pdf',
[7310]1395            self.context.getStudent(), studentview)
[7027]1396
[7459]1397class BedTicketRelocationPage(UtilityView, grok.View):
[7015]1398    """ Callback view
1399    """
1400    grok.context(IBedTicket)
1401    grok.name('relocate')
1402    grok.require('waeup.manageHostels')
1403
[7059]1404    # Relocate student if student parameters have changed or the bed_type
1405    # of the bed has changed
[7015]1406    def update(self):
1407        student = self.context.getStudent()
[7150]1408        students_utils = getUtility(IStudentsUtils)
[7186]1409        acc_details  = students_utils.getAccommodationDetails(student)
[7068]1410        if self.context.bed != None and \
1411              'reserved' in self.context.bed.bed_type:
[7723]1412            self.flash(_("Students in reserved beds can't be relocated."))
[7068]1413            self.redirect(self.url(self.context))
1414            return
[7059]1415        if acc_details['bt'] == self.context.bed_type and \
[7068]1416                self.context.bed != None and \
[7059]1417                self.context.bed.bed_type == self.context.bed_type:
[7723]1418            self.flash(_("Student can't be relocated."))
[7068]1419            self.redirect(self.url(self.context))
[7015]1420            return
[7068]1421        # Search a bed
[7015]1422        cat = queryUtility(ICatalog, name='beds_catalog', default=None)
1423        entries = cat.searchResults(
[7068]1424            owner=(student.student_id,student.student_id))
1425        if len(entries) and self.context.bed == None:
1426            # If booking has been cancelled but other bed space has been
1427            # manually allocated after cancellation use this bed
1428            new_bed = [entry for entry in entries][0]
1429        else:
1430            # Search for other available beds
1431            entries = cat.searchResults(
1432                bed_type=(acc_details['bt'],acc_details['bt']))
1433            available_beds = [
1434                entry for entry in entries if entry.owner == NOT_OCCUPIED]
1435            if available_beds:
[7150]1436                students_utils = getUtility(IStudentsUtils)
[7186]1437                new_bed = students_utils.selectBed(available_beds)
[7068]1438                new_bed.bookBed(student.student_id)
1439            else:
[7723]1440                self.flash(_('There is no free bed in your category ${a}.',
1441                    mapping = {'a':acc_details['bt']}))
[7068]1442                self.redirect(self.url(self.context))
1443                return
[7642]1444        # Release old bed if exists
[7068]1445        if self.context.bed != None:
1446            self.context.bed.owner = NOT_OCCUPIED
1447            notify(grok.ObjectModifiedEvent(self.context.bed))
[7015]1448        # Alocate new bed
1449        self.context.bed_type = acc_details['bt']
[7068]1450        self.context.bed = new_bed
1451        hall_title = new_bed.__parent__.hostel_name
1452        coordinates = new_bed.getBedCoordinates()[1:]
[7015]1453        block, room_nr, bed_nr = coordinates
[7723]1454        bc = _('${a}, Block ${b}, Room ${c}, Bed ${d} (${e})', mapping = {
1455            'a':hall_title, 'b':block,
1456            'c':room_nr, 'd':bed_nr,
1457            'e':new_bed.bed_type})
[7819]1458        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7723]1459        self.context.bed_coordinates = translate(
[7811]1460            bc, 'waeup.kofa',target_language=portal_language)
[7723]1461        self.flash(_('Student relocated: ${a}',
1462            mapping = {'a':self.context.bed_coordinates}))
[7015]1463        self.redirect(self.url(self.context))
1464        return
1465
1466    def render(self):
1467        return
1468
[7819]1469class StudentHistoryPage(KofaPage):
[6637]1470    """ Page to display student clearance data
1471    """
1472    grok.context(IStudent)
1473    grok.name('history')
[6660]1474    grok.require('waeup.viewStudent')
[6637]1475    grok.template('studenthistory')
[6642]1476    pnav = 4
[6637]1477
1478    @property
1479    def label(self):
[7723]1480        return _('${a}: History', mapping = {'a':self.context.display_fullname})
[6694]1481
1482# Pages for students only
1483
[7819]1484class StudentBaseEditFormPage(KofaEditFormPage):
[7133]1485    """ View to edit student base data
1486    """
1487    grok.context(IStudent)
1488    grok.name('edit_base')
1489    grok.require('waeup.handleStudent')
1490    form_fields = grok.AutoFields(IStudentBase).select(
1491        'email', 'phone')
[7723]1492    label = _('Edit base data')
[7133]1493    pnav = 4
1494
[7723]1495    @action(_('Save'), style='primary')
[7133]1496    def save(self, **data):
1497        msave(self, **data)
1498        return
1499
[7819]1500class StudentChangePasswordPage(KofaEditFormPage):
[7144]1501    """ View to manage student base data
[6756]1502    """
1503    grok.context(IStudent)
[7114]1504    grok.name('change_password')
[6694]1505    grok.require('waeup.handleStudent')
[7144]1506    grok.template('change_password')
[7723]1507    label = _('Change password')
[6694]1508    pnav = 4
1509
[7723]1510    @action(_('Save'), style='primary')
[7144]1511    def save(self, **data):
1512        form = self.request.form
1513        password = form.get('change_password', None)
1514        password_ctl = form.get('change_password_repeat', None)
1515        if password:
[7147]1516            validator = getUtility(IPasswordValidator)
1517            errors = validator.validate_password(password, password_ctl)
1518            if not errors:
1519                IUserAccount(self.context).setPassword(password)
1520                write_log_message(self, 'saved: password')
[7723]1521                self.flash(_('Password changed.'))
[6756]1522            else:
[7147]1523                self.flash( ' '.join(errors))
[6756]1524        return
1525
[7819]1526class StudentFilesUploadPage(KofaPage):
[7114]1527    """ View to upload files by student
1528    """
1529    grok.context(IStudent)
1530    grok.name('change_portrait')
[7127]1531    grok.require('waeup.uploadStudentFile')
[7114]1532    grok.template('filesuploadpage')
[7723]1533    label = _('Upload portrait')
[7114]1534    pnav = 4
1535
[7133]1536    def update(self):
[7539]1537        if self.context.getStudent().state != ADMITTED:
[7145]1538            emit_lock_message(self)
[7133]1539            return
1540        super(StudentFilesUploadPage, self).update()
1541        return
1542
[7819]1543class StartClearancePage(KofaPage):
[6770]1544    grok.context(IStudent)
1545    grok.name('start_clearance')
1546    grok.require('waeup.handleStudent')
1547    grok.template('enterpin')
[7723]1548    label = _('Start clearance')
[6770]1549    ac_prefix = 'CLR'
1550    notice = ''
1551    pnav = 4
[7723]1552    buttonname = _('Start clearance now')
[6770]1553
[7133]1554    @property
1555    def all_required_fields_filled(self):
1556        if self.context.email and self.context.phone:
1557            return True
1558        return False
1559
1560    @property
1561    def portrait_uploaded(self):
1562        store = getUtility(IExtFileStore)
1563        if store.getFileByContext(self.context, attr=u'passport.jpg'):
1564            return True
1565        return False
1566
[6770]1567    def update(self, SUBMIT=None):
[7671]1568        if not self.context.state == ADMITTED:
[7745]1569            self.flash(_("Wrong state"))
[6936]1570            self.redirect(self.url(self.context))
1571            return
[7133]1572        if not self.portrait_uploaded:
[7723]1573            self.flash(_("No portrait uploaded."))
[7133]1574            self.redirect(self.url(self.context, 'change_portrait'))
1575            return
1576        if not self.all_required_fields_filled:
[7723]1577            self.flash(_("Not all required fields filled."))
[7133]1578            self.redirect(self.url(self.context, 'edit_base'))
1579            return
[6770]1580        self.ac_series = self.request.form.get('ac_series', None)
1581        self.ac_number = self.request.form.get('ac_number', None)
1582
1583        if SUBMIT is None:
1584            return
1585        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1586        code = get_access_code(pin)
1587        if not code:
[7723]1588            self.flash(_('Activation code is invalid.'))
[6770]1589            return
1590        # Mark pin as used (this also fires a pin related transition)
1591        # and fire transition start_clearance
1592        if code.state == USED:
[7723]1593            self.flash(_('Activation code has already been used.'))
[6770]1594            return
1595        else:
[7723]1596            comment = _(u"invalidated")
[6770]1597            # Here we know that the ac is in state initialized so we do not
[6927]1598            # expect an exception, but the owner might be different
1599            if not invalidate_accesscode(pin,comment,self.context.student_id):
[7723]1600                self.flash(_('You are not the owner of this access code.'))
[6927]1601                return
[6770]1602            self.context.clr_code = pin
1603        IWorkflowInfo(self.context).fireTransition('start_clearance')
[7723]1604        self.flash(_('Clearance process has been started.'))
[6770]1605        self.redirect(self.url(self.context,'cedit'))
1606        return
1607
[6695]1608class StudentClearanceEditFormPage(StudentClearanceManageFormPage):
1609    """ View to edit student clearance data by student
1610    """
1611    grok.context(IStudent)
1612    grok.name('cedit')
1613    grok.require('waeup.handleStudent')
[7723]1614    label = _('Edit clearance data')
[6718]1615
[7993]1616    @property
1617    def form_fields(self):
[8472]1618        if self.context.is_postgrad:
[7993]1619            form_fields = grok.AutoFields(IPGStudentClearance).omit('clearance_locked')
1620        else:
1621            form_fields = grok.AutoFields(IUGStudentClearance).omit('clearance_locked')
1622        return form_fields
1623
[6718]1624    def update(self):
1625        if self.context.clearance_locked:
[7145]1626            emit_lock_message(self)
[6718]1627            return
1628        return super(StudentClearanceEditFormPage, self).update()
[6719]1629
[7723]1630    @action(_('Save'), style='primary')
[6722]1631    def save(self, **data):
1632        self.applyData(self.context, **data)
[7723]1633        self.flash(_('Clearance form has been saved.'))
[6722]1634        return
1635
[7253]1636    def dataNotComplete(self):
[7642]1637        """To be implemented in the customization package.
1638        """
[7253]1639        return False
1640
[7723]1641    @action(_('Save and request clearance'), style='primary')
[7186]1642    def requestClearance(self, **data):
[6722]1643        self.applyData(self.context, **data)
[7253]1644        if self.dataNotComplete():
1645            self.flash(self.dataNotComplete())
1646            return
[7723]1647        self.flash(_('Clearance form has been saved.'))
[6769]1648        self.redirect(self.url(self.context,'request_clearance'))
[6722]1649        return
1650
[7819]1651class RequestClearancePage(KofaPage):
[6769]1652    grok.context(IStudent)
1653    grok.name('request_clearance')
1654    grok.require('waeup.handleStudent')
1655    grok.template('enterpin')
[7723]1656    label = _('Request clearance')
1657    notice = _('Enter the CLR access code used for starting clearance.')
[6769]1658    ac_prefix = 'CLR'
1659    pnav = 4
[7723]1660    buttonname = _('Request clearance now')
[6769]1661
1662    def update(self, SUBMIT=None):
1663        self.ac_series = self.request.form.get('ac_series', None)
1664        self.ac_number = self.request.form.get('ac_number', None)
1665        if SUBMIT is None:
1666            return
1667        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1668        if self.context.clr_code != pin:
[7723]1669            self.flash(_("This isn't your CLR access code."))
[6769]1670            return
1671        state = IWorkflowState(self.context).getState()
1672        # This shouldn't happen, but the application officer
1673        # might have forgotten to lock the form after changing the state
1674        if state != CLEARANCE:
[7723]1675            self.flash(_('This form cannot be submitted. Wrong state!'))
[6769]1676            return
1677        IWorkflowInfo(self.context).fireTransition('request_clearance')
[7723]1678        self.flash(_('Clearance has been requested.'))
[6769]1679        self.redirect(self.url(self.context))
[6789]1680        return
[6806]1681
[8471]1682class StartSessionPage(KofaPage):
[6944]1683    grok.context(IStudentStudyCourse)
[8471]1684    grok.name('start_session')
[6944]1685    grok.require('waeup.handleStudent')
1686    grok.template('enterpin')
[8471]1687    label = _('Start session')
[6944]1688    ac_prefix = 'SFE'
1689    notice = ''
1690    pnav = 4
[8471]1691    buttonname = _('Start now')
[6944]1692
1693    def update(self, SUBMIT=None):
[8471]1694        if not self.context.next_session_allowed:
1695            self.flash(_("You are not entitled to start session."))
[6944]1696            self.redirect(self.url(self.context))
1697            return
1698        self.ac_series = self.request.form.get('ac_series', None)
1699        self.ac_number = self.request.form.get('ac_number', None)
1700
1701        if SUBMIT is None:
1702            return
1703        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1704        code = get_access_code(pin)
1705        if not code:
[7723]1706            self.flash(_('Activation code is invalid.'))
[6944]1707            return
1708        # Mark pin as used (this also fires a pin related transition)
1709        if code.state == USED:
[7723]1710            self.flash(_('Activation code has already been used.'))
[6944]1711            return
1712        else:
[7723]1713            comment = _(u"invalidated")
[6944]1714            # Here we know that the ac is in state initialized so we do not
[8471]1715            # expect an error, but the owner might be different
[6944]1716            if not invalidate_accesscode(
1717                pin,comment,self.context.getStudent().student_id):
[7723]1718                self.flash(_('You are not the owner of this access code.'))
[6944]1719                return
1720        if self.context.getStudent().state == CLEARED:
1721            IWorkflowInfo(self.context.getStudent()).fireTransition(
1722                'pay_first_school_fee')
1723        elif self.context.getStudent().state == RETURNING:
1724            IWorkflowInfo(self.context.getStudent()).fireTransition(
1725                'pay_school_fee')
[8471]1726        elif self.context.getStudent().state == PAID:
1727            IWorkflowInfo(self.context.getStudent()).fireTransition(
1728                'pay_pg_fee')
1729        self.flash(_('Session started.'))
[6944]1730        self.redirect(self.url(self.context))
1731        return
1732
[7819]1733class AddStudyLevelFormPage(KofaEditFormPage):
[6806]1734    """ Page for students to add current study levels
1735    """
1736    grok.context(IStudentStudyCourse)
1737    grok.name('add')
1738    grok.require('waeup.handleStudent')
1739    grok.template('studyleveladdpage')
1740    form_fields = grok.AutoFields(IStudentStudyCourse)
1741    pnav = 4
1742
1743    @property
1744    def label(self):
1745        studylevelsource = StudyLevelSource().factory
1746        code = self.context.current_level
1747        title = studylevelsource.getTitle(self.context, code)
[7723]1748        return _('Add current level ${a}', mapping = {'a':title})
[6806]1749
1750    def update(self):
[7539]1751        if self.context.getStudent().state != PAID:
[7145]1752            emit_lock_message(self)
[6806]1753            return
1754        super(AddStudyLevelFormPage, self).update()
1755        return
1756
[7723]1757    @action(_('Create course list now'), style='primary')
[6806]1758    def addStudyLevel(self, **data):
[8323]1759        studylevel = createObject(u'waeup.StudentStudyLevel')
[6806]1760        studylevel.level = self.context.current_level
1761        studylevel.level_session = self.context.current_session
1762        try:
1763            self.context.addStudentStudyLevel(
1764                self.context.certificate,studylevel)
1765        except KeyError:
[7723]1766            self.flash(_('This level exists.'))
[6806]1767        self.redirect(self.url(self.context))
1768        return
[6808]1769
[7819]1770class StudyLevelEditFormPage(KofaEditFormPage):
[6808]1771    """ Page to edit the student study level data by students
1772    """
1773    grok.context(IStudentStudyLevel)
1774    grok.name('edit')
1775    grok.require('waeup.handleStudent')
1776    grok.template('studyleveleditpage')
1777    form_fields = grok.AutoFields(IStudentStudyLevel).omit(
1778        'level_session', 'level_verdict')
1779    pnav = 4
1780
1781    def update(self):
[7539]1782        if self.context.getStudent().state != PAID:
1783            emit_lock_message(self)
1784            return
[6808]1785        super(StudyLevelEditFormPage, self).update()
1786        datatable.need()
[7329]1787        warning.need()
[6808]1788        return
1789
1790    @property
1791    def label(self):
[7833]1792        # Here we know that the cookie has been set
1793        lang = self.request.cookies.get('kofa.language')
[7811]1794        level_title = translate(self.context.level_title, 'waeup.kofa',
[7723]1795            target_language=lang)
1796        return _('Add and remove course tickets of study level ${a}',
1797            mapping = {'a':level_title})
[6808]1798
1799    @property
1800    def total_credits(self):
1801        total_credits = 0
1802        for key, val in self.context.items():
1803            total_credits += val.credits
1804        return total_credits
1805
[7723]1806    @action(_('Add course ticket'))
[6808]1807    def addCourseTicket(self, **data):
1808        self.redirect(self.url(self.context, 'ctadd'))
1809
[7723]1810    @jsaction(_('Remove selected tickets'))
[6808]1811    def delCourseTicket(self, **data):
1812        form = self.request.form
1813        if form.has_key('val_id'):
1814            child_id = form['val_id']
1815        else:
[7723]1816            self.flash(_('No ticket selected.'))
[6808]1817            self.redirect(self.url(self.context, '@@edit'))
1818            return
1819        if not isinstance(child_id, list):
1820            child_id = [child_id]
1821        deleted = []
1822        for id in child_id:
[6940]1823            # Students are not allowed to remove core tickets
[7665]1824            if not self.context[id].mandatory:
[7723]1825                del self.context[id]
1826                deleted.append(id)
[6808]1827        if len(deleted):
[7723]1828            self.flash(_('Successfully removed: ${a}',
1829                mapping = {'a':', '.join(deleted)}))
[6808]1830        self.redirect(self.url(self.context, u'@@edit'))
1831        return
1832
[7723]1833    @action(_('Register course list'), style='primary')
[8481]1834    def registerCourses(self, **data):
[7642]1835        IWorkflowInfo(self.context.getStudent()).fireTransition(
1836            'register_courses')
[7723]1837        self.flash(_('Course list has been registered.'))
[6810]1838        self.redirect(self.url(self.context))
1839        return
1840
[6808]1841class CourseTicketAddFormPage2(CourseTicketAddFormPage):
1842    """Add a course ticket by student.
1843    """
1844    grok.name('ctadd')
1845    grok.require('waeup.handleStudent')
1846    form_fields = grok.AutoFields(ICourseTicketAdd).omit(
[8141]1847        'score', 'mandatory', 'automatic', 'carry_over')
[6808]1848
[7539]1849    def update(self):
1850        if self.context.getStudent().state != PAID:
1851            emit_lock_message(self)
1852            return
1853        super(CourseTicketAddFormPage2, self).update()
1854        return
1855
[7723]1856    @action(_('Add course ticket'))
[6808]1857    def addCourseTicket(self, **data):
[7642]1858        # Safety belt
[7539]1859        if self.context.getStudent().state != PAID:
1860            return
[8325]1861        ticket = createObject(u'waeup.CourseTicket')
[6808]1862        course = data['course']
[7642]1863        for name in ['code', 'title', 'credits', 'passmark', 'semester']:
1864            setattr(ticket, name, getattr(course, name))
[6808]1865        ticket.automatic = False
1866        try:
1867            self.context.addCourseTicket(ticket)
1868        except KeyError:
[7723]1869            self.flash(_('The ticket exists.'))
[6808]1870            return
[7723]1871        self.flash(_('Successfully added ${a}.',
1872            mapping = {'a':ticket.code}))
[6808]1873        self.redirect(self.url(self.context, u'@@edit'))
1874        return
[7369]1875
1876
[7819]1877class SetPasswordPage(KofaPage):
1878    grok.context(IKofaObject)
[7660]1879    grok.name('setpassword')
1880    grok.require('waeup.Anonymous')
1881    grok.template('setpassword')
[7723]1882    label = _('Set password for first-time login')
[7660]1883    ac_prefix = 'PWD'
1884    pnav = 0
[7738]1885    set_button = _('Set')
[7660]1886
1887    def update(self, SUBMIT=None):
1888        self.reg_number = self.request.form.get('reg_number', None)
1889        self.ac_series = self.request.form.get('ac_series', None)
1890        self.ac_number = self.request.form.get('ac_number', None)
1891
1892        if SUBMIT is None:
1893            return
1894        hitlist = search(query=self.reg_number,
1895            searchtype='reg_number', view=self)
1896        if not hitlist:
[7723]1897            self.flash(_('No student found.'))
[7660]1898            return
1899        if len(hitlist) != 1:   # Cannot happen but anyway
[7723]1900            self.flash(_('More than one student found.'))
[7660]1901            return
1902        student = hitlist[0].context
1903        self.student_id = student.student_id
1904        student_pw = student.password
1905        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1906        code = get_access_code(pin)
1907        if not code:
[7723]1908            self.flash(_('Access code is invalid.'))
[7660]1909            return
1910        if student_pw and pin == student.adm_code:
[7723]1911            self.flash(_(
1912                'Password has already been set. Your Student Id is ${a}',
1913                mapping = {'a':self.student_id}))
[7660]1914            return
1915        elif student_pw:
1916            self.flash(
[7723]1917                _('Password has already been set. You are using the ' +
1918                'wrong Access Code.'))
[7660]1919            return
1920        # Mark pin as used (this also fires a pin related transition)
1921        # and set student password
1922        if code.state == USED:
[7723]1923            self.flash(_('Access code has already been used.'))
[7660]1924            return
1925        else:
[7723]1926            comment = _(u"invalidated")
[7660]1927            # Here we know that the ac is in state initialized so we do not
1928            # expect an exception
1929            invalidate_accesscode(pin,comment)
1930            IUserAccount(student).setPassword(self.ac_number)
1931            student.adm_code = pin
[7723]1932        self.flash(_('Password has been set. Your Student Id is ${a}',
1933            mapping = {'a':self.student_id}))
[7811]1934        return
Note: See TracBrowser for help on using the repository browser.