source: main/waeup.sirp/branches/henrik-bootstrap/src/waeup/sirp/students/browser.py @ 7786

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

Add breadcrumbs to student site layout. Omit the Students breadcrumb if principal is a student.

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