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

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

Surcharge 1 is portal provider fee.

Show data on goto_interswitch page.

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