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

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

Add study level breadcrumb.

  • Property svn:keywords set to Id
File size: 27.0 KB
Line 
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"""
18import grok
19
20from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
21from zope.component import createObject
22from waeup.sirp.accesscodes import invalidate_accesscode, get_access_code
23from waeup.sirp.accesscodes.workflow import USED
24from waeup.sirp.browser import (
25    WAeUPPage, WAeUPEditFormPage, WAeUPAddFormPage, WAeUPDisplayFormPage)
26from waeup.sirp.browser.breadcrumbs import Breadcrumb
27from waeup.sirp.browser.resources import datepicker, datatable, tabs
28from waeup.sirp.browser.viewlets import (
29    ManageActionButton, PrimaryNavTab, AddActionButton)
30from waeup.sirp.interfaces import IWAeUPObject, IUserAccount
31from waeup.sirp.widgets.datewidget import (
32    FriendlyDateWidget, FriendlyDateDisplayWidget)
33from waeup.sirp.students.interfaces import (
34    IStudentsContainer, IStudent, IStudentClearance, IStudentPasswordSetting,
35    IStudentPersonal, IStudentBase, IStudentStudyCourse, IStudentPayments,
36    IStudentAccommodation, IStudentClearanceEdit, IStudentStudyLevel,
37    )
38from waeup.sirp.students.catalog import search
39from waeup.sirp.students.workflow import CLEARANCE
40from waeup.sirp.students.studylevel import StudentStudyLevel
41from waeup.sirp.students.vocabularies import StudyLevelSource
42
43# Save function used for save methods in manager pages
44def msave(view, **data):
45    form = view.request.form
46    ob_class = view.__implemented__.__name__.replace('waeup.sirp.','')
47    changed_fields = view.applyData(view.context, **data)
48    # Turn list of lists into single list
49    if changed_fields:
50        changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
51    fields_string = ' + '.join(changed_fields)
52    view.context._p_changed = True
53    view.flash('Form has been saved.')
54    if fields_string:
55        try:
56            view.context.loggerInfo(ob_class, 'saved: % s' % fields_string)
57        except AttributeError:
58            view.context.__parent__.loggerInfo(ob_class, 'saved: % s' % fields_string)
59    return
60
61class StudentsTab(PrimaryNavTab):
62    """Students tab in primary navigation.
63    """
64
65    grok.context(IWAeUPObject)
66    grok.order(3)
67    grok.require('waeup.viewStudent')
68    grok.template('primarynavtab')
69
70    pnav = 4
71    tab_title = u'Students'
72
73    @property
74    def link_target(self):
75        return self.view.application_url('students')
76
77class StudentsBreadcrumb(Breadcrumb):
78    """A breadcrumb for the students container.
79    """
80    grok.context(IStudentsContainer)
81    title = u'Students'
82
83class SudyCourseBreadcrumb(Breadcrumb):
84    """A breadcrumb for the student study course.
85    """
86    grok.context(IStudentStudyCourse)
87    title = u'Study Course'
88
89class PaymentsBreadcrumb(Breadcrumb):
90    """A breadcrumb for the student payments folder.
91    """
92    grok.context(IStudentPayments)
93    title = u'Payments'
94
95class AccommodationBreadcrumb(Breadcrumb):
96    """A breadcrumb for the student accommodation folder.
97    """
98    grok.context(IStudentAccommodation)
99    title = u'Accommodation'
100
101class StudyLevelBreadcrumb(Breadcrumb):
102    """A breadcrumb for course lists.
103    """
104    grok.context(IStudentStudyLevel)
105
106    @property
107    def title(self):
108        return self.context.level_title
109
110class StudentsContainerPage(WAeUPPage):
111    """The standard view for student containers.
112    """
113    grok.context(IStudentsContainer)
114    grok.name('index')
115    grok.require('waeup.viewStudent')
116    grok.template('containerpage')
117    label = 'Student Section'
118    title = 'Students'
119    pnav = 4
120
121    def update(self, *args, **kw):
122        datatable.need()
123        form = self.request.form
124        self.hitlist = []
125        if 'searchterm' in form and form['searchterm']:
126            self.searchterm = form['searchterm']
127            self.searchtype = form['searchtype']
128        elif 'old_searchterm' in form:
129            self.searchterm = form['old_searchterm']
130            self.searchtype = form['old_searchtype']
131        else:
132            if 'search' in form:
133                self.flash('Empty search string.')
134            return
135        self.hitlist = search(query=self.searchterm,
136            searchtype=self.searchtype, view=self)
137        if not self.hitlist:
138            self.flash('No student found.')
139        return
140
141class SetPasswordPage(WAeUPPage):
142    grok.context(IWAeUPObject)
143    grok.name('setpassword')
144    grok.require('waeup.Public')
145    grok.template('setpassword')
146    title = ''
147    label = 'Set password for first-time login'
148    ac_prefix = 'PWD'
149    pnav = 0
150
151    def update(self, SUBMIT=None):
152        self.reg_number = self.request.form.get('reg_number', None)
153        self.ac_series = self.request.form.get('ac_series', None)
154        self.ac_number = self.request.form.get('ac_number', None)
155
156        if SUBMIT is None:
157            return
158        hitlist = search(query=self.reg_number,
159            searchtype='reg_number', view=self)
160        if not hitlist:
161            self.flash('No student found.')
162            return
163        if len(hitlist) != 1:   # Cannot happen but anyway
164            self.flash('More than one student found.')
165            return
166        student = hitlist[0].context
167        self.student_id = student.student_id
168        student_pw = student.password
169        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
170        code = get_access_code(pin)
171        if not code:
172            self.flash('Access code is invalid.')
173            return
174        if student_pw and pin == student.adm_code:
175            self.flash('Password has already been set. Your Student Id is %s'
176                % self.student_id)
177            return
178        elif student_pw:
179            self.flash('Password has already been set.')
180            return
181        # Mark pin as used (this also fires a pin related transition)
182        # and set student password
183        if code.state == USED:
184            self.flash('Access code has already been used.')
185            return
186        else:
187            comment = u"AC invalidated for %s" % self.student_id
188            # Here we know that the ac is in state initialized so we do not
189            # expect an exception
190            #import pdb; pdb.set_trace()
191            invalidate_accesscode(pin,comment)
192            IUserAccount(student).setPassword(self.ac_number)
193            student.adm_code = pin
194        self.flash('Password has been set. Your Student Id is %s'
195            % self.student_id)
196        return
197
198class StudentsContainerManageActionButton(ManageActionButton):
199    grok.order(1)
200    grok.context(IStudentsContainer)
201    grok.view(StudentsContainerPage)
202    grok.require('waeup.manageStudents')
203    text = 'Manage student section'
204
205
206class StudentsContainerManagePage(WAeUPPage):
207    """The manage page for student containers.
208    """
209    grok.context(IStudentsContainer)
210    grok.name('manage')
211    grok.require('waeup.manageStudents')
212    grok.template('containermanagepage')
213    pnav = 4
214    title = 'Manage student section'
215
216    @property
217    def label(self):
218        return self.title
219
220    def update(self, *args, **kw):
221        datatable.need()
222        form = self.request.form
223        self.hitlist = []
224        if 'searchterm' in form and form['searchterm']:
225            self.searchterm = form['searchterm']
226            self.searchtype = form['searchtype']
227        elif 'old_searchterm' in form:
228            self.searchterm = form['old_searchterm']
229            self.searchtype = form['old_searchtype']
230        else:
231            if 'search' in form:
232                self.flash('Empty search string.')
233            return
234        if not 'entries' in form:
235            self.hitlist = search(query=self.searchterm,
236                searchtype=self.searchtype, view=self)
237            if not self.hitlist:
238                self.flash('No student found.')
239            return
240        entries = form['entries']
241        if isinstance(entries, basestring):
242            entries = [entries]
243        deleted = []
244        for entry in entries:
245            if 'remove' in form:
246                del self.context[entry]
247                deleted.append(entry)
248        self.hitlist = search(query=self.searchterm,
249            searchtype=self.searchtype, view=self)
250        if len(deleted):
251            self.flash('Successfully removed: %s' % ', '.join(deleted))
252        return
253
254class StudentsContainerAddActionButton(AddActionButton):
255    grok.order(1)
256    grok.context(IStudentsContainer)
257    grok.view(StudentsContainerManagePage)
258    grok.require('waeup.manageStudents')
259    text = 'Add student'
260    target = 'addstudent'
261
262class StudentAddFormPage(WAeUPAddFormPage):
263    """Add-form to add a student.
264    """
265    grok.context(IStudentsContainer)
266    grok.require('waeup.manageStudents')
267    grok.name('addstudent')
268    grok.template('studentaddpage')
269    form_fields = grok.AutoFields(IStudent)
270    title = 'Students'
271    label = 'Add student'
272    pnav = 4
273
274    @grok.action('Create student record')
275    def addStudent(self, **data):
276        student = createObject(u'waeup.Student')
277        self.applyData(student, **data)
278        self.context.addStudent(student)
279        self.flash('Student record created.')
280        self.redirect(self.url(self.context[student.student_id], 'index'))
281        return
282
283class StudentBaseDisplayFormPage(WAeUPDisplayFormPage):
284    """ Page to display student base data
285    """
286    grok.context(IStudent)
287    grok.name('index')
288    grok.require('waeup.viewStudent')
289    grok.template('basepage')
290    form_fields = grok.AutoFields(IStudentBase).omit('password')
291    pnav = 4
292    title = 'Base Data'
293
294    @property
295    def label(self):
296        return '%s: Base Data' % self.context.name
297
298    @property
299    def hasPassword(self):
300        if self.context.password:
301            return 'set'
302        return 'unset'
303
304class StudentBaseManageActionButton(ManageActionButton):
305    grok.order(1)
306    grok.context(IStudent)
307    grok.view(StudentBaseDisplayFormPage)
308    grok.require('waeup.manageStudents')
309    text = 'Manage'
310    target = 'edit_base'
311
312class StudentBaseManageFormPage(WAeUPEditFormPage):
313    """ View to edit student base data
314    """
315    grok.context(IStudent)
316    grok.name('edit_base')
317    grok.require('waeup.manageStudents')
318    form_fields = grok.AutoFields(IStudentBase).omit('student_id')
319    grok.template('basemanagepage')
320    label = 'Manage base data'
321    title = 'Base Data'
322    pnav = 4
323
324    def update(self):
325        datepicker.need() # Enable jQuery datepicker in date fields.
326        super(StudentBaseManageFormPage, self).update()
327        self.wf_info = IWorkflowInfo(self.context)
328        return
329
330    def getTransitions(self):
331        """Return a list of dicts of allowed transition ids and titles.
332
333        Each list entry provides keys ``name`` and ``title`` for
334        internal name and (human readable) title of a single
335        transition.
336        """
337        allowed_transitions = self.wf_info.getManualTransitions()
338        return [dict(name='', title='No transition')] +[
339            dict(name=x, title=y) for x, y in allowed_transitions]
340
341    @grok.action('Save')
342    def save(self, **data):
343        form = self.request.form
344        ob_class = self.__implemented__.__name__.replace('waeup.sirp.','')
345        if form.has_key('password') and form['password']:
346            if form['password'] != form['control_password']:
347                self.flash('Passwords do not match.')
348                return
349            IUserAccount(self.context).setPassword(form['password'])
350            self.context.loggerInfo(ob_class, 'password changed')
351        # Turn list of lists into single list
352        changed_fields = self.applyData(self.context, **data)
353        if changed_fields:
354            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
355            changed_fields = [x for x in changed_fields
356                              if not x.startswith('password')]
357        fields_string = ' + '.join(changed_fields)
358        self.context._p_changed = True
359        if form.has_key('transition') and form['transition']:
360            transition_id = form['transition']
361            self.wf_info.fireTransition(transition_id)
362        self.flash('Form has been saved.')
363        if fields_string:
364            self.context.loggerInfo(ob_class, 'saved: % s' % fields_string)
365        return
366
367class StudentClearanceDisplayFormPage(WAeUPDisplayFormPage):
368    """ Page to display student clearance data
369    """
370    grok.context(IStudent)
371    grok.name('view_clearance')
372    grok.require('waeup.viewStudent')
373    form_fields = grok.AutoFields(IStudentClearance).omit('clearance_locked')
374    form_fields['date_of_birth'].custom_widget = FriendlyDateDisplayWidget('le')
375    title = 'Clearance Data'
376    pnav = 4
377
378    @property
379    def label(self):
380        return '%s: Clearance Data' % self.context.name
381
382class StudentClearanceManageActionButton(ManageActionButton):
383    grok.order(1)
384    grok.context(IStudent)
385    grok.view(StudentClearanceDisplayFormPage)
386    grok.require('waeup.manageStudents')
387    text = 'Manage'
388    target = 'edit_clearance'
389
390class StudentClearanceManageFormPage(WAeUPEditFormPage):
391    """ Page to edit student clearance data
392    """
393    grok.context(IStudent)
394    grok.name('edit_clearance')
395    grok.require('waeup.manageStudents')
396    form_fields = grok.AutoFields(IStudentClearance)
397    label = 'Manage clearance data'
398    title = 'Clearance Data'
399    pnav = 4
400
401    form_fields['date_of_birth'].custom_widget = FriendlyDateWidget('le-year')
402
403    def update(self):
404        datepicker.need() # Enable jQuery datepicker in date fields.
405        return super(StudentClearanceManageFormPage, self).update()
406
407    @grok.action('Save')
408    def save(self, **data):
409        msave(self, **data)
410        return
411
412class StudentPersonalDisplayFormPage(WAeUPDisplayFormPage):
413    """ Page to display student personal data
414    """
415    grok.context(IStudent)
416    grok.name('view_personal')
417    grok.require('waeup.viewStudent')
418    form_fields = grok.AutoFields(IStudentPersonal)
419    title = 'Personal Data'
420    pnav = 4
421
422    @property
423    def label(self):
424        return '%s: Personal Data' % self.context.name
425
426class StudentPersonalManageActionButton(ManageActionButton):
427    grok.order(1)
428    grok.context(IStudent)
429    grok.view(StudentPersonalDisplayFormPage)
430    grok.require('waeup.manageStudents')
431    text = 'Manage'
432    target = 'edit_personal'
433
434class StudentPersonalManageFormPage(WAeUPEditFormPage):
435    """ Page to edit student clearance data
436    """
437    grok.context(IStudent)
438    grok.name('edit_personal')
439    grok.require('waeup.viewStudent')
440    form_fields = grok.AutoFields(IStudentPersonal)
441    label = 'Manage personal data'
442    title = 'Personal Data'
443    pnav = 4
444
445    @grok.action('Save')
446    def save(self, **data):
447        msave(self, **data)
448        return
449
450class StudyCourseDisplayFormPage(WAeUPDisplayFormPage):
451    """ Page to display the student study course data
452    """
453    grok.context(IStudentStudyCourse)
454    grok.name('index')
455    grok.require('waeup.viewStudent')
456    form_fields = grok.AutoFields(IStudentStudyCourse)
457    grok.template('studycoursepage')
458    title = 'Study Course'
459    pnav = 4
460
461    @property
462    def label(self):
463        return '%s: Study Course' % self.context.__parent__.name
464
465class StudyCourseManageActionButton(ManageActionButton):
466    grok.order(1)
467    grok.context(IStudentStudyCourse)
468    grok.view(StudyCourseDisplayFormPage)
469    grok.require('waeup.manageStudents')
470    text = 'Manage'
471    target = 'manage'
472
473class StudyCourseManageFormPage(WAeUPEditFormPage):
474    """ Page to edit the student study course data
475    """
476    grok.context(IStudentStudyCourse)
477    grok.name('manage')
478    grok.require('waeup.manageStudents')
479    grok.template('studycoursemanagepage')
480    form_fields = grok.AutoFields(IStudentStudyCourse)
481    title = 'Study Course'
482    label = 'Manage study course'
483    pnav = 4
484    taboneactions = ['Save','Cancel']
485    tabtwoactions = ['Remove selected levels','Cancel']
486    tabthreeactions = ['Add study level']
487
488    def update(self):
489        super(StudyCourseManageFormPage, self).update()
490        tabs.need()
491        datatable.need()
492        return
493
494    @grok.action('Save')
495    def save(self, **data):
496        msave(self, **data)
497        return
498
499    @property
500    def level_dict(self):
501        studylevelsource = StudyLevelSource().factory
502        for code in studylevelsource.getValues(self.context):
503            title = studylevelsource.getTitle(self.context, code)
504            yield(dict(code=code, title=title))
505
506    @grok.action('Add study level')
507    def addStudyLevel(self, **data):
508        level_code = self.request.form.get('addlevel', None)
509        studylevel = StudentStudyLevel()
510        studylevel.level = int(level_code)
511        try:
512            self.context.addStudentStudyLevel(studylevel)
513        except KeyError:
514            self.flash('This level exists.')
515        self.redirect(self.url(self.context, u'@@manage')+'#tab-2')
516        return
517
518    @grok.action('Remove selected levels')
519    def delStudyLevels(self, **data):
520        form = self.request.form
521        if form.has_key('val_id'):
522            child_id = form['val_id']
523        else:
524            self.flash('No study level selected.')
525            self.redirect(self.url(self.context, '@@manage')+'#tab-2')
526            return
527        if not isinstance(child_id, list):
528            child_id = [child_id]
529        deleted = []
530        for id in child_id:
531            try:
532                del self.context[id]
533                deleted.append(id)
534            except:
535                self.flash('Could not delete %s: %s: %s' % (
536                        id, sys.exc_info()[0], sys.exc_info()[1]))
537        if len(deleted):
538            self.flash('Successfully removed: %s' % ', '.join(deleted))
539        self.redirect(self.url(self.context, u'@@manage')+'#tab-2')
540        return
541
542class StudyLevelDisplayFormPage(WAeUPDisplayFormPage):
543    """ Page to display student study levels
544    """
545    grok.context(IStudentStudyLevel)
546    grok.name('index')
547    grok.require('waeup.viewStudent')
548    form_fields = grok.AutoFields(IStudentStudyLevel)
549    #grok.template('studylevelpage')
550    title = 'Study Level'
551    pnav = 4
552
553    @property
554    def label(self):
555        return '%s: Study Level %s' % (
556            self.context.getStudent().name,self.context.level_title)
557
558class PaymentsDisplayFormPage(WAeUPDisplayFormPage):
559    """ Page to display the student payments
560    """
561    grok.context(IStudentPayments)
562    grok.name('index')
563    grok.require('waeup.viewStudent')
564    form_fields = grok.AutoFields(IStudentPayments)
565    #grok.template('paymentspage')
566    title = 'Payments'
567    pnav = 4
568
569    @property
570    def label(self):
571        return '%s: Payments' % self.context.__parent__.name
572
573class AccommodationDisplayFormPage(WAeUPDisplayFormPage):
574    """ Page to display the student accommodation data
575    """
576    grok.context(IStudentAccommodation)
577    grok.name('index')
578    grok.require('waeup.viewStudent')
579    form_fields = grok.AutoFields(IStudentAccommodation)
580    #grok.template('accommodationpage')
581    title = 'Accommodation'
582    pnav = 4
583
584    @property
585    def label(self):
586        return '%s: Accommodation Data' % self.context.__parent__.name
587
588class StudentHistoryPage(WAeUPPage):
589    """ Page to display student clearance data
590    """
591    grok.context(IStudent)
592    grok.name('history')
593    grok.require('waeup.viewStudent')
594    grok.template('studenthistory')
595    title = 'History'
596    pnav = 4
597
598    @property
599    def label(self):
600        return '%s: History' % self.context.name
601
602# Pages for students only
603
604class StudentBaseEditActionButton(ManageActionButton):
605    grok.order(1)
606    grok.context(IStudent)
607    grok.view(StudentBaseDisplayFormPage)
608    grok.require('waeup.handleStudent')
609    text = 'Change password'
610    target = 'bedit'
611
612class StudentPasswordSetting(grok.Adapter):
613    """Adapt IStudent to data needed for password settings.
614
615    We provide password getters/setters for the attached context (an
616    IStudent object) that cooperate seamless with the usual
617    formlib/form techniques.
618    """
619    grok.context(IStudent)
620    grok.provides(IStudentPasswordSetting)
621
622    def __init__(self, context):
623        self.name = context.name
624        self.password_repeat = context.password
625        self.context = context
626        return
627
628    def getPassword(self):
629        return self.context.password
630
631    def setPassword(self, password):
632        IUserAccount(self.context).setPassword(password)
633        return
634
635    password = property(getPassword, setPassword)
636
637class StudentBaseEditFormPage(WAeUPEditFormPage):
638    """ View to edit student base data by student
639    """
640    grok.context(IStudent)
641    grok.name('bedit')
642    grok.require('waeup.handleStudent')
643    #form_fields = grok.AutoFields(IStudentBaseEdit).omit(
644    #    'student_id', 'reg_number', 'matric_number')
645    form_fields = grok.AutoFields(IStudentPasswordSetting)
646    grok.template('baseeditpage')
647    label = 'Change password'
648    title = 'Base Data'
649    pnav = 4
650
651    def update(self):
652        super(StudentBaseEditFormPage, self).update()
653        self.wf_info = IWorkflowInfo(self.context)
654        return
655
656    def onFailure(self, action, data, errors):
657        new_status = []
658        other_errors = False
659        for error in errors:
660            msg = getattr(error, 'message', '')
661            if isinstance(msg, basestring) and msg != '':
662                new_status.append(msg)
663            else:
664                other_errors = True
665        if other_errors:
666            if new_status:
667                new_status.append('see below for further errors')
668            else:
669                new_status.append('See below for details.')
670        if new_status:
671            self.status = u'There were errors: %s' % ', '.join(new_status)
672        return
673
674    @grok.action('Save', failure=onFailure)
675    def save(self, **data):
676        self.applyData(self.context, **data)
677        self.flash('Form has been saved.')
678        return
679
680class StudentClearanceStartActionButton(ManageActionButton):
681    grok.order(1)
682    grok.context(IStudent)
683    grok.view(StudentClearanceDisplayFormPage)
684    grok.require('waeup.handleStudent')
685    icon = 'actionicon_start.png'
686    text = 'Start clearance'
687    target = 'start_clearance'
688
689    @property
690    def target_url(self):
691        if self.context.state != 'admitted':
692            return ''
693        return self.view.url(self.view.context, self.target)
694
695class StartClearancePage(WAeUPPage):
696    grok.context(IStudent)
697    grok.name('start_clearance')
698    grok.require('waeup.handleStudent')
699    grok.template('enterpin')
700    title = 'Start clearance'
701    label = 'Start clearance'
702    ac_prefix = 'CLR'
703    notice = ''
704    pnav = 4
705    buttonname = 'Start clearance now'
706
707    def update(self, SUBMIT=None):
708        self.ac_series = self.request.form.get('ac_series', None)
709        self.ac_number = self.request.form.get('ac_number', None)
710
711        if SUBMIT is None:
712            return
713        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
714        code = get_access_code(pin)
715        if not code:
716            self.flash('Access code is invalid.')
717            return
718        # Mark pin as used (this also fires a pin related transition)
719        # and fire transition start_clearance
720        if code.state == USED:
721            self.flash('Access code has already been used.')
722            return
723        else:
724            comment = u"AC invalidated for %s" % self.context.student_id
725            # Here we know that the ac is in state initialized so we do not
726            # expect an exception
727            invalidate_accesscode(pin,comment)
728            self.context.clr_code = pin
729        IWorkflowInfo(self.context).fireTransition('start_clearance')
730        self.flash('Clearance process has been started.')
731        self.redirect(self.url(self.context,'cedit'))
732        return
733
734class StudentClearanceEditActionButton(ManageActionButton):
735    grok.order(1)
736    grok.context(IStudent)
737    grok.view(StudentClearanceDisplayFormPage)
738    grok.require('waeup.handleStudent')
739    text = 'Edit'
740    target = 'cedit'
741
742    @property
743    def target_url(self):
744        if self.context.clearance_locked:
745            return ''
746        return self.view.url(self.view.context, self.target)
747
748class StudentClearanceEditFormPage(StudentClearanceManageFormPage):
749    """ View to edit student clearance data by student
750    """
751    grok.context(IStudent)
752    grok.name('cedit')
753    grok.require('waeup.handleStudent')
754    form_fields = grok.AutoFields(
755        IStudentClearanceEdit).omit('clearance_locked')
756    label = 'Edit clearance data'
757    title = 'Clearance Data'
758    pnav = 4
759    form_fields['date_of_birth'].custom_widget = FriendlyDateWidget('le-year')
760
761    def emitLockMessage(self):
762        self.flash('The requested form is locked (read-only).')
763        self.redirect(self.url(self.context))
764        return
765
766    def update(self):
767        if self.context.clearance_locked:
768            self.emitLockMessage()
769            return
770        datepicker.need()
771        return super(StudentClearanceEditFormPage, self).update()
772
773    @grok.action('Save')
774    def save(self, **data):
775        self.applyData(self.context, **data)
776        self.flash('Clearance form has been saved.')
777        return
778
779    @grok.action('Save and request clearance')
780    def requestclearance(self, **data):
781        self.applyData(self.context, **data)
782        self.context._p_changed = True
783        #if self.dataNotComplete():
784        #    self.flash(self.dataNotComplete())
785        #    return
786        self.flash('Clearance form has been saved.')
787        self.redirect(self.url(self.context,'request_clearance'))
788        return
789
790class RequestClearancePage(WAeUPPage):
791    grok.context(IStudent)
792    grok.name('request_clearance')
793    grok.require('waeup.handleStudent')
794    grok.template('enterpin')
795    title = 'Request clearance'
796    label = 'Request clearance'
797    notice = 'Enter the CLR access code used for starting clearance.'
798    ac_prefix = 'CLR'
799    pnav = 4
800    buttonname = 'Request clearance now'
801
802    def update(self, SUBMIT=None):
803        self.ac_series = self.request.form.get('ac_series', None)
804        self.ac_number = self.request.form.get('ac_number', None)
805        if SUBMIT is None:
806            return
807        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
808        if self.context.clr_code != pin:
809            self.flash("This isn't your CLR access code.")
810            return
811        state = IWorkflowState(self.context).getState()
812        # This shouldn't happen, but the application officer
813        # might have forgotten to lock the form after changing the state
814        if state != CLEARANCE:
815            self.flash('This form cannot be submitted. Wrong state!')
816            return
817        IWorkflowInfo(self.context).fireTransition('request_clearance')
818        self.flash('Clearance has been requested.')
819        self.redirect(self.url(self.context))
820        return
Note: See TracBrowser for help on using the repository browser.