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

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

Translate boolean values also in edit and manage pages.

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