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

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

Also relocate student if bed_type of bed has changed.

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