source: main/waeup.sirp/trunk/src/waeup/sirp/students/browser.py @ 7633

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

Add payment session column. Remove unused pagetemplate.

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