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

Last change on this file since 9168 was 9161, checked in by Henrik Bettermann, 12 years ago

In contrast to the comment of the last revision: We need to store validation_date and validated_by also in Kofa. They have to be set by the workflow transition events. They must not be editable (but importable and exportable).

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