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

Last change on this file since 8974 was 8974, checked in by uli, 12 years ago

Tiny code cleanup.

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