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

Last change on this file since 15622 was 15622, checked in by Henrik Bettermann, 5 years ago

Next try.

  • Property svn:keywords set to Id
File size: 156.0 KB
Line 
1## $Id: browser.py 15622 2019-09-30 07:03:21Z henrik $
2##
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"""
20import csv
21import grok
22import pytz
23import sys
24from cStringIO import StringIO
25from datetime import datetime
26from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
27from urllib import urlencode
28from reportlab.platypus import Paragraph
29from zope.catalog.interfaces import ICatalog
30from zope.component import queryUtility, getUtility, createObject
31from zope.event import notify
32from zope.formlib.textwidgets import BytesDisplayWidget
33from zope.i18n import translate
34from zope.schema.interfaces import ConstraintNotSatisfied, RequiredMissing
35from zope.security import checkPermission
36from zope.securitypolicy.interfaces import IPrincipalRoleManager
37from waeup.kofa.accesscodes import invalidate_accesscode, get_access_code
38from waeup.kofa.accesscodes.workflow import USED
39from waeup.kofa.browser.pdf import ENTRY1_STYLE
40from waeup.kofa.browser.breadcrumbs import Breadcrumb
41from waeup.kofa.browser.interfaces import ICaptchaManager
42from waeup.kofa.browser.layout import (
43    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
44    NullValidator, jsaction, action, UtilityView)
45from waeup.kofa.browser.pages import (
46    ContactAdminFormPage, ExportCSVView, doll_up, exports_not_allowed,
47    LocalRoleAssignmentUtilityView)
48from waeup.kofa.hostels.hostel import NOT_OCCUPIED
49from waeup.kofa.interfaces import (
50    IKofaObject, IUserAccount, IExtFileStore, IPasswordValidator, IContactForm,
51    IKofaUtils, IObjectHistory, academic_sessions, ICSVExporter,
52    academic_sessions_vocab, IDataCenter, DOCLINK)
53from waeup.kofa.interfaces import MessageFactory as _
54from waeup.kofa.mandates.mandate import PasswordMandate, ParentsPasswordMandate
55from waeup.kofa.university.interfaces import (
56    IDepartment, ICertificate, ICourse)
57from waeup.kofa.university.certificate import (
58    VirtualCertificateExportJobContainer)
59from waeup.kofa.university.department import (
60    VirtualDepartmentExportJobContainer)
61from waeup.kofa.university.faculty import VirtualFacultyExportJobContainer
62from waeup.kofa.university.facultiescontainer import (
63    VirtualFacultiesExportJobContainer)
64from waeup.kofa.university.course import (
65    VirtualCourseExportJobContainer,)
66from waeup.kofa.university.vocabularies import course_levels
67from waeup.kofa.utils.batching import VirtualExportJobContainer
68from waeup.kofa.utils.helpers import get_current_principal, now
69from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
70from waeup.kofa.students.interfaces import (
71    IStudentsContainer, IStudent, IUGStudentClearance, IPGStudentClearance,
72    IStudentPersonal, IStudentPersonalEdit, IStudentBase, IStudentStudyCourse,
73    IStudentStudyCourseTransfer,
74    IStudentAccommodation, IStudentStudyLevel, ICourseTicket, ICourseTicketAdd,
75    IStudentPaymentsContainer, IStudentOnlinePayment, IStudentPreviousPayment,
76    IStudentBalancePayment, IBedTicket, IStudentsUtils, IStudentRequestPW,
77    )
78from waeup.kofa.students.catalog import search, StudentQueryResultItem
79from waeup.kofa.students.vocabularies import StudyLevelSource
80from waeup.kofa.students.workflow import (
81    ADMITTED, PAID, CLEARANCE, REQUESTED, RETURNING, CLEARED, REGISTERED,
82    VALIDATED, GRADUATED, TRANSREQ, TRANSVAL, TRANSREL, FORBIDDEN_POSTGRAD_TRANS
83    )
84
85
86grok.context(IKofaObject)  # Make IKofaObject the default context
87
88
89class TicketError(Exception):
90    """A course ticket could not be added
91    """
92    pass
93
94# Save function used for save methods in pages
95def msave(view, **data):
96    changed_fields = view.applyData(view.context, **data)
97    # Turn list of lists into single list
98    if changed_fields:
99        changed_fields = reduce(lambda x, y: x+y, changed_fields.values())
100    # Inform catalog if certificate has changed
101    # (applyData does this only for the context)
102    if 'certificate' in changed_fields:
103        notify(grok.ObjectModifiedEvent(view.context.student))
104    fields_string = ' + '.join(changed_fields)
105    view.flash(_('Form has been saved.'))
106    if fields_string:
107        view.context.writeLogMessage(view, 'saved: %s' % fields_string)
108    return
109
110def emit_lock_message(view):
111    """Flash a lock message.
112    """
113    view.flash(_('The requested form is locked (read-only).'), type="warning")
114    view.redirect(view.url(view.context))
115    return
116
117def translated_values(view):
118    """Translate course ticket attribute values to be displayed on
119    studylevel pages.
120    """
121    lang = view.request.cookies.get('kofa.language')
122    for value in view.context.values():
123        # We have to unghostify (according to Tres Seaver) the __dict__
124        # by activating the object, otherwise value_dict will be empty
125        # when calling the first time.
126        value._p_activate()
127        value_dict = dict([i for i in value.__dict__.items()])
128        value_dict['url'] = view.url(value)
129        value_dict['removable_by_student'] = value.removable_by_student
130        value_dict['mandatory'] = translate(str(value.mandatory), 'zope',
131            target_language=lang)
132        value_dict['carry_over'] = translate(str(value.carry_over), 'zope',
133            target_language=lang)
134        value_dict['outstanding'] = translate(str(value.outstanding), 'zope',
135            target_language=lang)
136        value_dict['automatic'] = translate(str(value.automatic), 'zope',
137            target_language=lang)
138        value_dict['grade'] = value.grade
139        value_dict['weight'] = value.weight
140        value_dict['course_category'] = value.course_category
141        value_dict['total_score'] = value.total_score
142        semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
143        value_dict['semester'] = semester_dict[
144            value.semester].replace('mester', 'm.')
145        yield value_dict
146
147def addCourseTicket(view, course=None):
148    students_utils = getUtility(IStudentsUtils)
149    ticket = createObject(u'waeup.CourseTicket')
150    ticket.automatic = False
151    ticket.carry_over = False
152    warning = students_utils.warnCreditsOOR(view.context, course)
153    if warning:
154        view.flash(warning, type="warning")
155        return False
156    try:
157        view.context.addCourseTicket(ticket, course)
158    except KeyError:
159        view.flash(_('The ticket exists.'), type="warning")
160        return False
161    except TicketError, error:
162        # Ticket errors are not being raised in the base package.
163        view.flash(error, type="warning")
164        return False
165    view.flash(_('Successfully added ${a}.',
166        mapping = {'a':ticket.code}))
167    view.context.writeLogMessage(
168        view,'added: %s|%s|%s' % (
169        ticket.code, ticket.level, ticket.level_session))
170    return True
171
172def level_dict(studycourse):
173    portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
174    level_dict = {}
175    studylevelsource = StudyLevelSource().factory
176    for code in studylevelsource.getValues(studycourse):
177        title = translate(studylevelsource.getTitle(studycourse, code),
178            'waeup.kofa', target_language=portal_language)
179        level_dict[code] = title
180    return level_dict
181
182class StudentsBreadcrumb(Breadcrumb):
183    """A breadcrumb for the students container.
184    """
185    grok.context(IStudentsContainer)
186    title = _('Students')
187
188    @property
189    def target(self):
190        user = get_current_principal()
191        if getattr(user, 'user_type', None) == 'student':
192            return None
193        return self.viewname
194
195class StudentBreadcrumb(Breadcrumb):
196    """A breadcrumb for the student container.
197    """
198    grok.context(IStudent)
199
200    def title(self):
201        return self.context.display_fullname
202
203class SudyCourseBreadcrumb(Breadcrumb):
204    """A breadcrumb for the student study course.
205    """
206    grok.context(IStudentStudyCourse)
207
208    def title(self):
209        if self.context.is_current:
210            return _('Study Course')
211        else:
212            return _('Previous Study Course')
213
214class PaymentsBreadcrumb(Breadcrumb):
215    """A breadcrumb for the student payments folder.
216    """
217    grok.context(IStudentPaymentsContainer)
218    title = _('Payments')
219
220class OnlinePaymentBreadcrumb(Breadcrumb):
221    """A breadcrumb for payments.
222    """
223    grok.context(IStudentOnlinePayment)
224
225    @property
226    def title(self):
227        return self.context.p_id
228
229class AccommodationBreadcrumb(Breadcrumb):
230    """A breadcrumb for the student accommodation folder.
231    """
232    grok.context(IStudentAccommodation)
233    title = _('Accommodation')
234
235class BedTicketBreadcrumb(Breadcrumb):
236    """A breadcrumb for bed tickets.
237    """
238    grok.context(IBedTicket)
239
240    @property
241    def title(self):
242        return _('Bed Ticket ${a}',
243            mapping = {'a':self.context.getSessionString()})
244
245class StudyLevelBreadcrumb(Breadcrumb):
246    """A breadcrumb for course lists.
247    """
248    grok.context(IStudentStudyLevel)
249
250    @property
251    def title(self):
252        return self.context.level_title
253
254class StudentsContainerPage(KofaPage):
255    """The standard view for student containers.
256    """
257    grok.context(IStudentsContainer)
258    grok.name('index')
259    grok.require('waeup.viewStudentsContainer')
260    grok.template('containerpage')
261    label = _('Find students')
262    search_button = _('Find student(s)')
263    pnav = 4
264
265    def update(self, *args, **kw):
266        form = self.request.form
267        self.hitlist = []
268        if form.get('searchtype', None) in (
269            'suspended', TRANSREQ, TRANSVAL, GRADUATED):
270            self.searchtype = form['searchtype']
271            self.searchterm = None
272        elif 'searchterm' in form and form['searchterm']:
273            self.searchterm = form['searchterm']
274            self.searchtype = form['searchtype']
275        elif 'old_searchterm' in form:
276            self.searchterm = form['old_searchterm']
277            self.searchtype = form['old_searchtype']
278        else:
279            if 'search' in form:
280                self.flash(_('Empty search string'), type="warning")
281            return
282        if self.searchtype == 'current_session':
283            try:
284                self.searchterm = int(self.searchterm)
285            except ValueError:
286                self.flash(_('Only year dates allowed (e.g. 2011).'),
287                           type="danger")
288                return
289        self.hitlist = search(query=self.searchterm,
290            searchtype=self.searchtype, view=self)
291        if not self.hitlist:
292            self.flash(_('No student found.'), type="warning")
293        return
294
295class StudentsContainerManagePage(KofaPage):
296    """The manage page for student containers.
297    """
298    grok.context(IStudentsContainer)
299    grok.name('manage')
300    grok.require('waeup.manageStudent')
301    grok.template('containermanagepage')
302    pnav = 4
303    label = _('Manage students section')
304    search_button = _('Find student(s)')
305    remove_button = _('Remove selected')
306    doclink = DOCLINK + '/students.html'
307
308    def update(self, *args, **kw):
309        form = self.request.form
310        self.hitlist = []
311        if form.get('searchtype', None) in (
312            'suspended', TRANSREQ, TRANSVAL, GRADUATED):
313            self.searchtype = form['searchtype']
314            self.searchterm = None
315        elif 'searchterm' in form and form['searchterm']:
316            self.searchterm = form['searchterm']
317            self.searchtype = form['searchtype']
318        elif 'old_searchterm' in form:
319            self.searchterm = form['old_searchterm']
320            self.searchtype = form['old_searchtype']
321        else:
322            if 'search' in form:
323                self.flash(_('Empty search string'), type="warning")
324            return
325        if self.searchtype == 'current_session':
326            try:
327                self.searchterm = int(self.searchterm)
328            except ValueError:
329                self.flash(_('Only year dates allowed (e.g. 2011).'),
330                           type="danger")
331                return
332        if not 'entries' in form:
333            self.hitlist = search(query=self.searchterm,
334                searchtype=self.searchtype, view=self)
335            if not self.hitlist:
336                self.flash(_('No student found.'), type="warning")
337            if 'remove' in form:
338                self.flash(_('No item selected.'), type="warning")
339            return
340        entries = form['entries']
341        if isinstance(entries, basestring):
342            entries = [entries]
343        deleted = []
344        for entry in entries:
345            if 'remove' in form:
346                del self.context[entry]
347                deleted.append(entry)
348        self.hitlist = search(query=self.searchterm,
349            searchtype=self.searchtype, view=self)
350        if len(deleted):
351            self.flash(_('Successfully removed: ${a}',
352                mapping = {'a':', '.join(deleted)}))
353        return
354
355class StudentAddFormPage(KofaAddFormPage):
356    """Add-form to add a student.
357    """
358    grok.context(IStudentsContainer)
359    grok.require('waeup.manageStudent')
360    grok.name('addstudent')
361    form_fields = grok.AutoFields(IStudent).select(
362        'firstname', 'middlename', 'lastname', 'reg_number')
363    label = _('Add student')
364    pnav = 4
365
366    @action(_('Create student'), style='primary')
367    def addStudent(self, **data):
368        student = createObject(u'waeup.Student')
369        self.applyData(student, **data)
370        self.context.addStudent(student)
371        self.flash(_('Student record created.'))
372        self.redirect(self.url(self.context[student.student_id], 'index'))
373        return
374
375    @action(_('Create graduated student'), style='primary')
376    def addGraduatedStudent(self, **data):
377        student = createObject(u'waeup.Student')
378        self.applyData(student, **data)
379        self.context.addStudent(student)
380        IWorkflowState(student).setState(GRADUATED)
381        notify(grok.ObjectModifiedEvent(student))
382        history = IObjectHistory(student)
383        history.addMessage("State 'graduated' set")
384        self.flash(_('Graduated student record created.'))
385        self.redirect(self.url(self.context[student.student_id], 'index'))
386        return
387
388class LoginAsStudentStep1(KofaEditFormPage):
389    """ View to temporarily set a student password.
390    """
391    grok.context(IStudent)
392    grok.name('loginasstep1')
393    grok.require('waeup.loginAsStudent')
394    grok.template('loginasstep1')
395    pnav = 4
396
397    def update(self):
398        super(LoginAsStudentStep1, self).update()
399        kofa_utils = getUtility(IKofaUtils)
400        self.temp_password_minutes = kofa_utils.TEMP_PASSWORD_MINUTES
401        return
402
403    def label(self):
404        return _(u'Set temporary password for ${a}',
405            mapping = {'a':self.context.display_fullname})
406
407    @action('Set password now', style='primary')
408    def setPassword(self, *args, **data):
409        kofa_utils = getUtility(IKofaUtils)
410        password = kofa_utils.genPassword()
411        self.context.setTempPassword(self.request.principal.id, password)
412        self.context.writeLogMessage(
413            self, 'temp_password generated: %s' % password)
414        args = {'password':password}
415        self.redirect(self.url(self.context) +
416            '/loginasstep2?%s' % urlencode(args))
417        return
418
419class LoginAsStudentStep2(KofaPage):
420    """ View to temporarily login as student with a temporary password.
421    """
422    grok.context(IStudent)
423    grok.name('loginasstep2')
424    grok.require('waeup.Public')
425    grok.template('loginasstep2')
426    login_button = _('Login now')
427    pnav = 4
428
429    def label(self):
430        return _(u'Login as ${a}',
431            mapping = {'a':self.context.student_id})
432
433    def update(self, SUBMIT=None, password=None):
434        self.password = password
435        if SUBMIT is not None:
436            self.flash(_('You successfully logged in as student.'))
437            self.redirect(self.url(self.context))
438        return
439
440class StudentBaseDisplayFormPage(KofaDisplayFormPage):
441    """ Page to display student base data
442    """
443    grok.context(IStudent)
444    grok.name('index')
445    grok.require('waeup.viewStudent')
446    grok.template('basepage')
447    form_fields = grok.AutoFields(IStudentBase).omit(
448        'password', 'suspended', 'suspended_comment', 'flash_notice')
449    pnav = 4
450
451    @property
452    def label(self):
453        if self.context.suspended:
454            return _('${a}: Base Data (account deactivated)',
455                mapping = {'a':self.context.display_fullname})
456        return  _('${a}: Base Data',
457            mapping = {'a':self.context.display_fullname})
458
459    @property
460    def hasPassword(self):
461        if self.context.password:
462            return _('set')
463        return _('unset')
464
465    def update(self):
466        if self.context.flash_notice:
467            self.flash(self.context.flash_notice, type="warning")
468        super(StudentBaseDisplayFormPage, self).update()
469        return
470
471class StudentBasePDFFormPage(KofaDisplayFormPage):
472    """ Page to display student base data in pdf files.
473    """
474
475    def __init__(self, context, request, omit_fields=()):
476        self.omit_fields = omit_fields
477        super(StudentBasePDFFormPage, self).__init__(context, request)
478
479    @property
480    def form_fields(self):
481        form_fields = grok.AutoFields(IStudentBase)
482        for field in self.omit_fields:
483            form_fields = form_fields.omit(field)
484        return form_fields
485
486class ContactStudentFormPage(ContactAdminFormPage):
487    grok.context(IStudent)
488    grok.name('contactstudent')
489    grok.require('waeup.viewStudent')
490    pnav = 4
491    form_fields = grok.AutoFields(IContactForm).select('subject', 'body')
492
493    def update(self, subject=u'', body=u''):
494        super(ContactStudentFormPage, self).update()
495        self.form_fields.get('subject').field.default = subject
496        self.form_fields.get('body').field.default = body
497        return
498
499    def label(self):
500        return _(u'Send message to ${a}',
501            mapping = {'a':self.context.display_fullname})
502
503    @action('Send message now', style='primary')
504    def send(self, *args, **data):
505        try:
506            email = self.request.principal.email
507        except AttributeError:
508            email = self.config.email_admin
509        usertype = getattr(self.request.principal,
510                           'user_type', 'system').title()
511        kofa_utils = getUtility(IKofaUtils)
512        success = kofa_utils.sendContactForm(
513                self.request.principal.title,email,
514                self.context.display_fullname,self.context.email,
515                self.request.principal.id,usertype,
516                self.config.name,
517                data['body'],data['subject'])
518        if success:
519            self.flash(_('Your message has been sent.'))
520        else:
521            self.flash(_('An smtp server error occurred.'), type="danger")
522        return
523
524class ExportPDFAdmissionSlip(UtilityView, grok.View):
525    """Deliver a PDF Admission slip.
526    """
527    grok.context(IStudent)
528    grok.name('admission_slip.pdf')
529    grok.require('waeup.viewStudent')
530    prefix = 'form'
531
532    omit_fields = ('date_of_birth', 'current_level', 'flash_notice')
533
534    form_fields = grok.AutoFields(IStudentBase).select('student_id', 'reg_number')
535
536    @property
537    def label(self):
538        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
539        return translate(_('Admission Letter of'),
540            'waeup.kofa', target_language=portal_language) \
541            + ' %s' % self.context.display_fullname
542
543    def render(self):
544        students_utils = getUtility(IStudentsUtils)
545        return students_utils.renderPDFAdmissionLetter(self,
546            self.context.student, omit_fields=self.omit_fields)
547
548class StudentBaseManageFormPage(KofaEditFormPage):
549    """ View to manage student base data
550    """
551    grok.context(IStudent)
552    grok.name('manage_base')
553    grok.require('waeup.manageStudent')
554    form_fields = grok.AutoFields(IStudentBase).omit(
555        'student_id', 'adm_code', 'suspended')
556    grok.template('basemanagepage')
557    label = _('Manage base data')
558    pnav = 4
559
560    def update(self):
561        super(StudentBaseManageFormPage, self).update()
562        self.wf_info = IWorkflowInfo(self.context)
563        return
564
565    @action(_('Save'), style='primary')
566    def save(self, **data):
567        form = self.request.form
568        password = form.get('password', None)
569        password_ctl = form.get('control_password', None)
570        if password:
571            validator = getUtility(IPasswordValidator)
572            errors = validator.validate_password(password, password_ctl)
573            if errors:
574                self.flash( ' '.join(errors), type="danger")
575                return
576        changed_fields = self.applyData(self.context, **data)
577        # Turn list of lists into single list
578        if changed_fields:
579            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
580        else:
581            changed_fields = []
582        if password:
583            # Now we know that the form has no errors and can set password
584            IUserAccount(self.context).setPassword(password)
585            changed_fields.append('password')
586        fields_string = ' + '.join(changed_fields)
587        self.flash(_('Form has been saved.'))
588        if fields_string:
589            self.context.writeLogMessage(self, 'saved: % s' % fields_string)
590        return
591
592class StudentTriggerTransitionFormPage(KofaEditFormPage):
593    """ View to trigger student workflow transitions
594    """
595    grok.context(IStudent)
596    grok.name('trigtrans')
597    grok.require('waeup.triggerTransition')
598    grok.template('trigtrans')
599    label = _('Trigger registration transition')
600    pnav = 4
601
602    def getTransitions(self):
603        """Return a list of dicts of allowed transition ids and titles.
604
605        Each list entry provides keys ``name`` and ``title`` for
606        internal name and (human readable) title of a single
607        transition.
608        """
609        wf_info = IWorkflowInfo(self.context)
610        allowed_transitions = [t for t in wf_info.getManualTransitions()
611            if not t[0].startswith('pay')]
612        if self.context.is_postgrad and not self.context.is_special_postgrad:
613            allowed_transitions = [t for t in allowed_transitions
614                if not t[0] in FORBIDDEN_POSTGRAD_TRANS]
615        return [dict(name='', title=_('No transition'))] +[
616            dict(name=x, title=y) for x, y in allowed_transitions]
617
618    @action(_('Save'), style='primary')
619    def save(self, **data):
620        form = self.request.form
621        if 'transition' in form and form['transition']:
622            transition_id = form['transition']
623            wf_info = IWorkflowInfo(self.context)
624            wf_info.fireTransition(transition_id)
625        return
626
627class StudentActivateView(UtilityView, grok.View):
628    """ Activate student account
629    """
630    grok.context(IStudent)
631    grok.name('activate')
632    grok.require('waeup.manageStudent')
633
634    def update(self):
635        self.context.suspended = False
636        self.context.writeLogMessage(self, 'account activated')
637        history = IObjectHistory(self.context)
638        history.addMessage('Student account activated')
639        self.flash(_('Student account has been activated.'))
640        self.redirect(self.url(self.context))
641        return
642
643    def render(self):
644        return
645
646class StudentDeactivateView(UtilityView, grok.View):
647    """ Deactivate student account
648    """
649    grok.context(IStudent)
650    grok.name('deactivate')
651    grok.require('waeup.manageStudent')
652
653    def update(self):
654        self.context.suspended = True
655        self.context.writeLogMessage(self, 'account deactivated')
656        history = IObjectHistory(self.context)
657        history.addMessage('Student account deactivated')
658        self.flash(_('Student account has been deactivated.'))
659        self.redirect(self.url(self.context))
660        return
661
662    def render(self):
663        return
664
665class StudentClearanceDisplayFormPage(KofaDisplayFormPage):
666    """ Page to display student clearance data
667    """
668    grok.context(IStudent)
669    grok.name('view_clearance')
670    grok.require('waeup.viewStudent')
671    pnav = 4
672
673    @property
674    def separators(self):
675        return getUtility(IStudentsUtils).SEPARATORS_DICT
676
677    @property
678    def form_fields(self):
679        if self.context.is_postgrad:
680            form_fields = grok.AutoFields(IPGStudentClearance)
681        else:
682            form_fields = grok.AutoFields(IUGStudentClearance)
683        if not getattr(self.context, 'officer_comment'):
684            form_fields = form_fields.omit('officer_comment')
685        else:
686            form_fields['officer_comment'].custom_widget = BytesDisplayWidget
687        return form_fields
688
689    @property
690    def label(self):
691        return _('${a}: Clearance Data',
692            mapping = {'a':self.context.display_fullname})
693
694class ExportPDFClearanceSlip(grok.View):
695    """Deliver a PDF slip of the context.
696    """
697    grok.context(IStudent)
698    grok.name('clearance_slip.pdf')
699    grok.require('waeup.viewStudent')
700    prefix = 'form'
701    omit_fields = (
702        'suspended', 'phone',
703        'adm_code', 'suspended_comment',
704        'date_of_birth', 'current_level',
705        'flash_notice')
706
707    @property
708    def form_fields(self):
709        if self.context.is_postgrad:
710            form_fields = grok.AutoFields(IPGStudentClearance)
711        else:
712            form_fields = grok.AutoFields(IUGStudentClearance)
713        if not getattr(self.context, 'officer_comment'):
714            form_fields = form_fields.omit('officer_comment')
715        return form_fields
716
717    @property
718    def title(self):
719        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
720        return translate(_('Clearance Data'), 'waeup.kofa',
721            target_language=portal_language)
722
723    @property
724    def label(self):
725        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
726        return translate(_('Clearance Slip of'),
727            'waeup.kofa', target_language=portal_language) \
728            + ' %s' % self.context.display_fullname
729
730    # XXX: not used in waeup.kofa and thus not tested
731    def _signatures(self):
732        isStudent = getattr(
733            self.request.principal, 'user_type', None) == 'student'
734        if not isStudent and self.context.state in (CLEARED, ):
735            return ([_('Student Signature')],
736                    [_('Clearance Officer Signature')])
737        return
738
739    def _sigsInFooter(self):
740        isStudent = getattr(
741            self.request.principal, 'user_type', None) == 'student'
742        if not isStudent and self.context.state in (CLEARED, ):
743            return (_('Date, Student Signature'),
744                    _('Date, Clearance Officer Signature'),
745                    )
746        return ()
747
748    def render(self):
749        studentview = StudentBasePDFFormPage(self.context.student,
750            self.request, self.omit_fields)
751        students_utils = getUtility(IStudentsUtils)
752        return students_utils.renderPDF(
753            self, 'clearance_slip.pdf',
754            self.context.student, studentview, signatures=self._signatures(),
755            sigs_in_footer=self._sigsInFooter(),
756            omit_fields=self.omit_fields)
757
758class StudentClearanceManageFormPage(KofaEditFormPage):
759    """ Page to manage student clearance data
760    """
761    grok.context(IStudent)
762    grok.name('manage_clearance')
763    grok.require('waeup.manageStudent')
764    grok.template('clearanceeditpage')
765    label = _('Manage clearance data')
766    deletion_warning = _('Are you sure?')
767    pnav = 4
768
769    @property
770    def separators(self):
771        return getUtility(IStudentsUtils).SEPARATORS_DICT
772
773    @property
774    def form_fields(self):
775        if self.context.is_postgrad:
776            form_fields = grok.AutoFields(IPGStudentClearance).omit('clr_code')
777        else:
778            form_fields = grok.AutoFields(IUGStudentClearance).omit('clr_code')
779        return form_fields
780
781    @action(_('Save'), style='primary')
782    def save(self, **data):
783        msave(self, **data)
784        return
785
786class StudentClearView(UtilityView, grok.View):
787    """ Clear student by clearance officer
788    """
789    grok.context(IStudent)
790    grok.name('clear')
791    grok.require('waeup.clearStudent')
792
793    def update(self):
794        cdm = getUtility(IStudentsUtils).clearance_disabled_message(
795            self.context)
796        if cdm:
797            self.flash(cdm)
798            self.redirect(self.url(self.context,'view_clearance'))
799            return
800        if self.context.state == REQUESTED:
801            IWorkflowInfo(self.context).fireTransition('clear')
802            self.flash(_('Student has been cleared.'))
803        else:
804            self.flash(_('Student is in wrong state.'), type="warning")
805        self.redirect(self.url(self.context,'view_clearance'))
806        return
807
808    def render(self):
809        return
810
811class StudentRejectClearancePage(KofaEditFormPage):
812    """ Reject clearance by clearance officers.
813    """
814    grok.context(IStudent)
815    grok.name('reject_clearance')
816    label = _('Reject clearance')
817    grok.require('waeup.clearStudent')
818    form_fields = grok.AutoFields(
819        IUGStudentClearance).select('officer_comment')
820
821    def update(self):
822        cdm = getUtility(IStudentsUtils).clearance_disabled_message(
823            self.context)
824        if cdm:
825            self.flash(cdm, type="warning")
826            self.redirect(self.url(self.context,'view_clearance'))
827            return
828        return super(StudentRejectClearancePage, self).update()
829
830    @action(_('Save comment and reject clearance now'), style='primary')
831    def reject(self, **data):
832        if self.context.state == CLEARED:
833            IWorkflowInfo(self.context).fireTransition('reset4')
834            message = _('Clearance has been annulled.')
835            self.flash(message, type="warning")
836        elif self.context.state == REQUESTED:
837            IWorkflowInfo(self.context).fireTransition('reset3')
838            message = _('Clearance request has been rejected.')
839            self.flash(message, type="warning")
840        else:
841            self.flash(_('Student is in wrong state.'), type="warning")
842            self.redirect(self.url(self.context,'view_clearance'))
843            return
844        self.applyData(self.context, **data)
845        comment = data['officer_comment']
846        if comment:
847            self.context.writeLogMessage(
848                self, 'comment: %s' % comment.replace('\n', '<br>'))
849            args = {'subject':message, 'body':comment}
850        else:
851            args = {'subject':message,}
852        self.redirect(self.url(self.context) +
853            '/contactstudent?%s' % urlencode(args))
854        return
855
856
857class StudentPersonalDisplayFormPage(KofaDisplayFormPage):
858    """ Page to display student personal data
859    """
860    grok.context(IStudent)
861    grok.name('view_personal')
862    grok.require('waeup.viewStudent')
863    form_fields = grok.AutoFields(IStudentPersonal)
864    form_fields['perm_address'].custom_widget = BytesDisplayWidget
865    form_fields[
866        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
867    pnav = 4
868
869    @property
870    def label(self):
871        return _('${a}: Personal Data',
872            mapping = {'a':self.context.display_fullname})
873
874class StudentPersonalManageFormPage(KofaEditFormPage):
875    """ Page to manage personal data
876    """
877    grok.context(IStudent)
878    grok.name('manage_personal')
879    grok.require('waeup.manageStudent')
880    form_fields = grok.AutoFields(IStudentPersonal)
881    form_fields['personal_updated'].for_display = True
882    form_fields[
883        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
884    label = _('Manage personal data')
885    pnav = 4
886
887    @action(_('Save'), style='primary')
888    def save(self, **data):
889        msave(self, **data)
890        return
891
892class StudentPersonalEditFormPage(KofaEditFormPage):
893    """ Page to edit personal data
894    """
895    grok.context(IStudent)
896    grok.name('edit_personal')
897    grok.require('waeup.handleStudent')
898    form_fields = grok.AutoFields(IStudentPersonalEdit).omit('personal_updated')
899    label = _('Edit personal data')
900    pnav = 4
901
902    @action(_('Save/Confirm'), style='primary')
903    def save(self, **data):
904        msave(self, **data)
905        self.context.personal_updated = datetime.utcnow()
906        return
907
908class StudyCourseDisplayFormPage(KofaDisplayFormPage):
909    """ Page to display the student study course data
910    """
911    grok.context(IStudentStudyCourse)
912    grok.name('index')
913    grok.require('waeup.viewStudent')
914    grok.template('studycoursepage')
915    pnav = 4
916
917    @property
918    def form_fields(self):
919        if self.context.is_postgrad:
920            form_fields = grok.AutoFields(IStudentStudyCourse).omit(
921                'previous_verdict')
922        else:
923            form_fields = grok.AutoFields(IStudentStudyCourse)
924        return form_fields
925
926    @property
927    def label(self):
928        if self.context.is_current:
929            return _('${a}: Study Course',
930                mapping = {'a':self.context.__parent__.display_fullname})
931        else:
932            return _('${a}: Previous Study Course',
933                mapping = {'a':self.context.__parent__.display_fullname})
934
935    @property
936    def current_mode(self):
937        if self.context.certificate is not None:
938            studymodes_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
939            return studymodes_dict[self.context.certificate.study_mode]
940        return
941
942    @property
943    def department(self):
944        try:
945            if self.context.certificate is not None:
946                return self.context.certificate.__parent__.__parent__
947        except AttributeError:
948            # handle_certificate_removed does only clear
949            # studycourses with certificate code 'studycourse' but not
950            # 'studycourse_1' or 'studycourse_2'. These certificates do
951            # still exist but have no parents.
952            pass
953        return
954
955    @property
956    def faculty(self):
957        try:
958            if self.context.certificate is not None:
959                return self.context.certificate.__parent__.__parent__.__parent__
960        except AttributeError:
961            # handle_certificate_removed does only clear
962            # studycourses with certificate code 'studycourse' but not
963            # 'studycourse_1' or 'studycourse_2'. These certificates do
964            # still exist but have no parents.
965            pass
966        return
967
968    @property
969    def prev_studycourses(self):
970        if self.context.is_current:
971            if self.context.__parent__.get('studycourse_2', None) is not None:
972                return (
973                        {'href':self.url(self.context.student) + '/studycourse_1',
974                        'title':_('First Study Course, ')},
975                        {'href':self.url(self.context.student) + '/studycourse_2',
976                        'title':_('Second Study Course')}
977                        )
978            if self.context.__parent__.get('studycourse_1', None) is not None:
979                return (
980                        {'href':self.url(self.context.student) + '/studycourse_1',
981                        'title':_('First Study Course')},
982                        )
983        return
984
985class StudyCourseManageFormPage(KofaEditFormPage):
986    """ Page to edit the student study course data
987    """
988    grok.context(IStudentStudyCourse)
989    grok.name('manage')
990    grok.require('waeup.manageStudent')
991    grok.template('studycoursemanagepage')
992    label = _('Manage study course')
993    pnav = 4
994    taboneactions = [_('Save'),_('Cancel')]
995    tabtwoactions = [_('Remove selected levels'),_('Cancel')]
996    tabthreeactions = [_('Add study level')]
997
998    @property
999    def form_fields(self):
1000        if self.context.is_postgrad:
1001            form_fields = grok.AutoFields(IStudentStudyCourse).omit(
1002                'previous_verdict')
1003        else:
1004            form_fields = grok.AutoFields(IStudentStudyCourse)
1005        return form_fields
1006
1007    def update(self):
1008        if not self.context.is_current \
1009            or self.context.student.studycourse_locked:
1010            emit_lock_message(self)
1011            return
1012        super(StudyCourseManageFormPage, self).update()
1013        return
1014
1015    @action(_('Save'), style='primary')
1016    def save(self, **data):
1017        try:
1018            msave(self, **data)
1019        except ConstraintNotSatisfied:
1020            # The selected level might not exist in certificate
1021            self.flash(_('Current level not available for certificate.'),
1022                       type="warning")
1023            return
1024        notify(grok.ObjectModifiedEvent(self.context.__parent__))
1025        return
1026
1027    @property
1028    def level_dicts(self):
1029        studylevelsource = StudyLevelSource().factory
1030        for code in studylevelsource.getValues(self.context):
1031            title = studylevelsource.getTitle(self.context, code)
1032            yield(dict(code=code, title=title))
1033
1034    @property
1035    def session_dicts(self):
1036        yield(dict(code='', title='--'))
1037        for item in academic_sessions():
1038            code = item[1]
1039            title = item[0]
1040            yield(dict(code=code, title=title))
1041
1042    @action(_('Add study level'), style='primary')
1043    def addStudyLevel(self, **data):
1044        level_code = self.request.form.get('addlevel', None)
1045        level_session = self.request.form.get('level_session', None)
1046        if not level_session and not level_code == '0':
1047            self.flash(_('You must select a session for the level.'),
1048                       type="warning")
1049            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1050            return
1051        if level_session and level_code == '0':
1052            self.flash(_('Level zero must not be assigned a session.'),
1053                       type="warning")
1054            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1055            return
1056        studylevel = createObject(u'waeup.StudentStudyLevel')
1057        studylevel.level = int(level_code)
1058        if level_code != '0':
1059            studylevel.level_session = int(level_session)
1060        try:
1061            self.context.addStudentStudyLevel(
1062                self.context.certificate,studylevel)
1063            self.flash(_('Study level has been added.'))
1064        except KeyError:
1065            self.flash(_('This level exists.'), type="warning")
1066        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1067        return
1068
1069    @jsaction(_('Remove selected levels'))
1070    def delStudyLevels(self, **data):
1071        form = self.request.form
1072        if 'val_id' in form:
1073            child_id = form['val_id']
1074        else:
1075            self.flash(_('No study level selected.'), type="warning")
1076            self.redirect(self.url(self.context, '@@manage')+'#tab2')
1077            return
1078        if not isinstance(child_id, list):
1079            child_id = [child_id]
1080        deleted = []
1081        for id in child_id:
1082            del self.context[id]
1083            deleted.append(id)
1084        if len(deleted):
1085            self.flash(_('Successfully removed: ${a}',
1086                mapping = {'a':', '.join(deleted)}))
1087            self.context.writeLogMessage(
1088                self,'removed: %s' % ', '.join(deleted))
1089        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1090        return
1091
1092class StudentTranscriptRequestPage(KofaPage):
1093    """ Page to request transcript by student
1094    """
1095    grok.context(IStudent)
1096    grok.name('request_transcript')
1097    grok.require('waeup.handleStudent')
1098    grok.template('transcriptrequest')
1099    label = _('Request transcript')
1100    ac_prefix = 'TSC'
1101    notice = ''
1102    pnav = 4
1103    buttonname = _('Submit')
1104    with_ac = True
1105
1106    def update(self, SUBMIT=None):
1107        super(StudentTranscriptRequestPage, self).update()
1108        if not self.context.state == GRADUATED:
1109            self.flash(_("Wrong state"), type="danger")
1110            self.redirect(self.url(self.context))
1111            return
1112        if self.with_ac:
1113            self.ac_series = self.request.form.get('ac_series', None)
1114            self.ac_number = self.request.form.get('ac_number', None)
1115        if getattr(
1116            self.context['studycourse'], 'transcript_comment', None) is not None:
1117            self.correspondence = self.context[
1118                'studycourse'].transcript_comment.replace(
1119                    '\n', '<br>')
1120        else:
1121            self.correspondence = ''
1122        if SUBMIT is None:
1123            return
1124        if self.with_ac:
1125            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
1126            code = get_access_code(pin)
1127            if not code:
1128                self.flash(_('Activation code is invalid.'), type="warning")
1129                return
1130            if code.state == USED:
1131                self.flash(_('Activation code has already been used.'),
1132                           type="warning")
1133                return
1134            # Mark pin as used (this also fires a pin related transition)
1135            # and fire transition request_transcript
1136            comment = _(u"invalidated")
1137            # Here we know that the ac is in state initialized so we do not
1138            # expect an exception, but the owner might be different
1139            if not invalidate_accesscode(pin, comment, self.context.student_id):
1140                self.flash(_('You are not the owner of this access code.'),
1141                           type="warning")
1142                return
1143            self.context.clr_code = pin
1144        IWorkflowInfo(self.context).fireTransition('request_transcript')
1145        comment = self.request.form.get('comment', '').replace('\r', '')
1146        address = self.request.form.get('address', '').replace('\r', '')
1147        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1148        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1149        old_transcript_comment = getattr(
1150            self.context['studycourse'], 'transcript_comment', None)
1151        if old_transcript_comment == None:
1152            old_transcript_comment = ''
1153        self.context['studycourse'].transcript_comment = '''On %s %s wrote:
1154
1155%s
1156
1157Dispatch Address:
1158%s
1159
1160%s''' % (today, self.request.principal.id, comment, address,
1161         old_transcript_comment)
1162        self.context.writeLogMessage(
1163            self, 'comment: %s' % comment.replace('\n', '<br>'))
1164        self.flash(_('Transcript processing has been started.'))
1165        self.redirect(self.url(self.context))
1166        return
1167
1168class StudentTranscriptSignView(UtilityView, grok.View):
1169    """ View to sign transcript
1170    """
1171    grok.context(IStudentStudyCourse)
1172    grok.name('sign_transcript')
1173    grok.require('waeup.signTranscript')
1174
1175    def update(self, SUBMIT=None):
1176        if self.context.student.state != TRANSVAL:
1177            self.flash(_('Student is in wrong state.'), type="warning")
1178            self.redirect(self.url(self.context))
1179            return
1180        prev_transcript_signees = getattr(
1181            self.context, 'transcript_signees', None)
1182        if prev_transcript_signees \
1183            and '(%s)' % self.request.principal.id in prev_transcript_signees:
1184            self.flash(_('You have already signed this transcript.'),
1185                type="warning")
1186            self.redirect(self.url(self.context) + '/transcript')
1187            return
1188        self.flash(_('Transcript signed.'))
1189        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1190        self.context.student.__parent__.logger.info(
1191            '%s - %s - Transcript signed'
1192            % (ob_class, self.context.student.student_id))
1193        self.context.student.history.addMessage('Transcript signed')
1194        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1195        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1196        if prev_transcript_signees == None:
1197            prev_transcript_signees = ''
1198        self.context.transcript_signees = (
1199            u"Electronically signed by %s (%s) on %s\n%s"
1200            % (self.request.principal.title, self.request.principal.id, today,
1201            prev_transcript_signees))
1202        self.redirect(self.url(self.context) + '/transcript')
1203        return
1204
1205    def render(self):
1206        return
1207
1208class StudentTranscriptValidateFormPage(KofaEditFormPage):
1209    """ Page to validate transcript
1210    """
1211    grok.context(IStudentStudyCourse)
1212    grok.name('validate_transcript')
1213    grok.require('waeup.processTranscript')
1214    grok.template('transcriptprocess')
1215    label = _('Validate transcript')
1216    buttonname = _('Save comment and validate transcript')
1217    pnav = 4
1218
1219    @property
1220    def remarks(self):
1221        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1222        levelremarks = ''
1223        studylevelsource = StudyLevelSource().factory
1224        for studylevel in self.context.values():
1225            leveltitle = studylevelsource.getTitle(
1226                self.context, studylevel.level)
1227            url = self.url(self.context) + '/%s/remark' % studylevel.level
1228            button_title = translate(
1229                _('Edit'), 'waeup.kofa', target_language=portal_language)
1230            levelremarks += (
1231                '<tr>'
1232                '<td>%s:</td>'
1233                '<td>%s</td> '
1234                '<td><a class="btn btn-primary btn-xs" href="%s">%s</a></td>'
1235                '</tr>'
1236                ) % (
1237                leveltitle, studylevel.transcript_remark, url, button_title)
1238        return levelremarks
1239
1240    def update(self, SUBMIT=None):
1241        super(StudentTranscriptValidateFormPage, self).update()
1242        if self.context.student.state != TRANSREQ:
1243            self.flash(_('Student is in wrong state.'), type="warning")
1244            self.redirect(self.url(self.context))
1245            return
1246        if getattr(self.context, 'transcript_comment', None) is not None:
1247            self.correspondence = self.context.transcript_comment.replace(
1248                '\n', '<br>')
1249        else:
1250            self.correspondence = ''
1251        if getattr(self.context, 'transcript_signees', None) is not None:
1252            self.signees = self.context.transcript_signees.replace(
1253                '\n', '<br><br>')
1254        else:
1255            self.signees = ''
1256        if SUBMIT is None:
1257            return
1258        # Fire transition
1259        IWorkflowInfo(self.context.student).fireTransition('validate_transcript')
1260        self.flash(_('Transcript validated.'))
1261        comment = self.request.form.get('comment', '').replace('\r', '')
1262        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1263        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1264        old_transcript_comment = getattr(
1265            self.context, 'transcript_comment', None)
1266        if old_transcript_comment == None:
1267            old_transcript_comment = ''
1268        self.context.transcript_comment = '''On %s %s wrote:
1269
1270%s
1271
1272%s''' % (today, self.request.principal.id, comment,
1273         old_transcript_comment)
1274        self.context.writeLogMessage(
1275            self, 'comment: %s' % comment.replace('\n', '<br>'))
1276        self.redirect(self.url(self.context) + '/transcript')
1277        return
1278
1279class StudentTranscriptReleaseFormPage(KofaEditFormPage):
1280    """ Page to release transcript
1281    """
1282    grok.context(IStudentStudyCourse)
1283    grok.name('release_transcript')
1284    grok.require('waeup.processTranscript')
1285    grok.template('transcriptprocess')
1286    label = _('Release transcript')
1287    buttonname = _('Save comment and release transcript')
1288    pnav = 4
1289
1290    @property
1291    def remarks(self):
1292        levelremarks = ''
1293        studylevelsource = StudyLevelSource().factory
1294        for studylevel in self.context.values():
1295            leveltitle = studylevelsource.getTitle(
1296                self.context, studylevel.level)
1297            levelremarks += "%s: %s <br><br>" % (
1298                leveltitle, studylevel.transcript_remark)
1299        return levelremarks
1300
1301    def update(self, SUBMIT=None):
1302        super(StudentTranscriptReleaseFormPage, self).update()
1303        if self.context.student.state != TRANSVAL:
1304            self.flash(_('Student is in wrong state.'), type="warning")
1305            self.redirect(self.url(self.context))
1306            return
1307        if getattr(self.context, 'transcript_comment', None) is not None:
1308            self.correspondence = self.context.transcript_comment.replace(
1309                '\n', '<br>')
1310        else:
1311            self.correspondence = ''
1312        if getattr(self.context, 'transcript_signees', None) is not None:
1313            self.signees = self.context.transcript_signees.replace(
1314                '\n', '<br><br>')
1315        else:
1316            self.signees = ''
1317        if SUBMIT is None:
1318            return
1319        # Fire transition
1320        IWorkflowInfo(self.context.student).fireTransition('release_transcript')
1321        self.flash(_('Transcript released and final transcript file saved.'))
1322        comment = self.request.form.get('comment', '').replace('\r', '')
1323        tz = getattr(queryUtility(IKofaUtils), 'tzinfo', pytz.utc)
1324        today = now(tz).strftime('%d/%m/%Y %H:%M:%S %Z')
1325        old_transcript_comment = getattr(
1326            self.context, 'transcript_comment', None)
1327        if old_transcript_comment == None:
1328            old_transcript_comment = ''
1329        self.context.transcript_comment = '''On %s %s wrote:
1330
1331%s
1332
1333%s''' % (today, self.request.principal.id, comment,
1334         old_transcript_comment)
1335        self.context.writeLogMessage(
1336            self, 'comment: %s' % comment.replace('\n', '<br>'))
1337        # Produce transcript file
1338        self.redirect(self.url(self.context) + '/transcript.pdf')
1339        return
1340
1341class StudyCourseTranscriptPage(KofaDisplayFormPage):
1342    """ Page to display the student's transcript.
1343    """
1344    grok.context(IStudentStudyCourse)
1345    grok.name('transcript')
1346    grok.require('waeup.viewTranscript')
1347    grok.template('transcript')
1348    pnav = 4
1349
1350    def update(self):
1351        final_slip = getUtility(IExtFileStore).getFileByContext(
1352            self.context.student, attr='final_transcript')
1353        if not self.context.student.transcript_enabled or final_slip:
1354            self.flash(_('Forbidden!'), type="warning")
1355            self.redirect(self.url(self.context))
1356            return
1357        super(StudyCourseTranscriptPage, self).update()
1358        self.semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
1359        self.level_dict = level_dict(self.context)
1360        self.session_dict = dict([(None, 'None'),] +
1361            [(item[1], item[0]) for item in academic_sessions()])
1362        self.studymode_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
1363        return
1364
1365    @property
1366    def label(self):
1367        # Here we know that the cookie has been set
1368        return _('${a}: Transcript Data', mapping = {
1369            'a':self.context.student.display_fullname})
1370
1371class ExportPDFTranscriptSlip(UtilityView, grok.View):
1372    """Deliver a PDF slip of the context.
1373    """
1374    grok.context(IStudentStudyCourse)
1375    grok.name('transcript.pdf')
1376    grok.require('waeup.viewTranscript')
1377    prefix = 'form'
1378    omit_fields = (
1379        'department', 'faculty', 'current_mode', 'entry_session', 'certificate',
1380        'password', 'suspended', 'phone', 'email',
1381        'adm_code', 'suspended_comment', 'current_level', 'flash_notice')
1382
1383    def update(self):
1384        final_slip = getUtility(IExtFileStore).getFileByContext(
1385            self.context.student, attr='final_transcript')
1386        if not self.context.student.transcript_enabled \
1387            or final_slip:
1388            self.flash(_('Forbidden!'), type="warning")
1389            self.redirect(self.url(self.context))
1390            return
1391        super(ExportPDFTranscriptSlip, self).update()
1392        self.semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
1393        self.level_dict = level_dict(self.context)
1394        self.session_dict = dict([(None, 'None'),] +
1395            [(item[1], item[0]) for item in academic_sessions()])
1396        self.studymode_dict = getUtility(IKofaUtils).STUDY_MODES_DICT
1397        return
1398
1399    @property
1400    def label(self):
1401        # Here we know that the cookie has been set
1402        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1403        return translate(_('Academic Transcript'),
1404            'waeup.kofa', target_language=portal_language)
1405
1406    def _sigsInFooter(self):
1407        if getattr(
1408            self.context.student['studycourse'], 'transcript_signees', None):
1409            return ()
1410        return (_('CERTIFIED TRUE COPY'),)
1411
1412    def _signatures(self):
1413        return ()
1414
1415    def _digital_sigs(self):
1416        if getattr(
1417            self.context.student['studycourse'], 'transcript_signees', None):
1418            return self.context.student['studycourse'].transcript_signees
1419        return ()
1420
1421    def _save_file(self):
1422        if self.context.student.state == TRANSREL:
1423            return True
1424        return False
1425
1426    def render(self):
1427        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1428        Term = translate(_('Term'), 'waeup.kofa', target_language=portal_language)
1429        Code = translate(_('Code'), 'waeup.kofa', target_language=portal_language)
1430        Title = translate(_('Title'), 'waeup.kofa', target_language=portal_language)
1431        Cred = translate(_('Credits'), 'waeup.kofa', target_language=portal_language)
1432        Score = translate(_('Score'), 'waeup.kofa', target_language=portal_language)
1433        Grade = translate(_('Grade'), 'waeup.kofa', target_language=portal_language)
1434        studentview = StudentBasePDFFormPage(self.context.student,
1435            self.request, self.omit_fields)
1436        students_utils = getUtility(IStudentsUtils)
1437
1438        tableheader = [(Code,'code', 2.5),
1439                         (Title,'title', 7),
1440                         (Term, 'semester', 1.5),
1441                         (Cred, 'credits', 1.5),
1442                         (Score, 'total_score', 1.5),
1443                         (Grade, 'grade', 1.5),
1444                         ]
1445
1446        pdfstream = students_utils.renderPDFTranscript(
1447            self, 'transcript.pdf',
1448            self.context.student, studentview,
1449            omit_fields=self.omit_fields,
1450            tableheader=tableheader,
1451            signatures=self._signatures(),
1452            sigs_in_footer=self._sigsInFooter(),
1453            digital_sigs=self._digital_sigs(),
1454            save_file=self._save_file(),
1455            )
1456        if not pdfstream:
1457            self.redirect(self.url(self.context.student))
1458            return
1459        return pdfstream
1460
1461class StudentTransferFormPage(KofaAddFormPage):
1462    """Page to transfer the student.
1463    """
1464    grok.context(IStudent)
1465    grok.name('transfer')
1466    grok.require('waeup.manageStudent')
1467    label = _('Transfer student')
1468    form_fields = grok.AutoFields(IStudentStudyCourseTransfer).omit(
1469        'entry_mode', 'entry_session')
1470    pnav = 4
1471
1472    @jsaction(_('Transfer'))
1473    def transferStudent(self, **data):
1474        error = self.context.transfer(**data)
1475        if error == -1:
1476            self.flash(_('Current level does not match certificate levels.'),
1477                       type="warning")
1478        elif error == -2:
1479            self.flash(_('Former study course record incomplete.'),
1480                       type="warning")
1481        elif error == -3:
1482            self.flash(_('Maximum number of transfers exceeded.'),
1483                       type="warning")
1484        else:
1485            self.flash(_('Successfully transferred.'))
1486        return
1487
1488class RevertTransferFormPage(KofaEditFormPage):
1489    """View that reverts the previous transfer.
1490    """
1491    grok.context(IStudent)
1492    grok.name('revert_transfer')
1493    grok.require('waeup.manageStudent')
1494    grok.template('reverttransfer')
1495    label = _('Revert previous transfer')
1496
1497    def update(self):
1498        if not self.context.has_key('studycourse_1'):
1499            self.flash(_('No previous transfer.'), type="warning")
1500            self.redirect(self.url(self.context))
1501            return
1502        return
1503
1504    @jsaction(_('Revert now'))
1505    def transferStudent(self, **data):
1506        self.context.revert_transfer()
1507        self.flash(_('Previous transfer reverted.'))
1508        self.redirect(self.url(self.context, 'studycourse'))
1509        return
1510
1511class StudyLevelDisplayFormPage(KofaDisplayFormPage):
1512    """ Page to display student study levels
1513    """
1514    grok.context(IStudentStudyLevel)
1515    grok.name('index')
1516    grok.require('waeup.viewStudent')
1517    form_fields = grok.AutoFields(IStudentStudyLevel).omit('level')
1518    form_fields[
1519        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
1520    grok.template('studylevelpage')
1521    pnav = 4
1522
1523    def update(self):
1524        super(StudyLevelDisplayFormPage, self).update()
1525        if self.context.level == 0:
1526            self.form_fields = self.form_fields.omit('gpa')
1527        return
1528
1529    @property
1530    def translated_values(self):
1531        return translated_values(self)
1532
1533    @property
1534    def label(self):
1535        # Here we know that the cookie has been set
1536        lang = self.request.cookies.get('kofa.language')
1537        level_title = translate(self.context.level_title, 'waeup.kofa',
1538            target_language=lang)
1539        return _('${a}: ${b}', mapping = {
1540            'a':self.context.student.display_fullname,
1541            'b':level_title})
1542
1543class ExportPDFCourseRegistrationSlip(UtilityView, grok.View):
1544    """Deliver a PDF slip of the context.
1545    """
1546    grok.context(IStudentStudyLevel)
1547    grok.name('course_registration_slip.pdf')
1548    grok.require('waeup.viewStudent')
1549    form_fields = grok.AutoFields(IStudentStudyLevel).omit(
1550        'level', 'gpa', 'transcript_remark')
1551    form_fields[
1552        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
1553    prefix = 'form'
1554    omit_fields = (
1555        'password', 'suspended', 'phone', 'date_of_birth',
1556        'adm_code', 'sex', 'suspended_comment', 'current_level',
1557        'flash_notice')
1558
1559    @property
1560    def title(self):
1561        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1562        return translate(_('Level Data'), 'waeup.kofa',
1563            target_language=portal_language)
1564
1565    @property
1566    def label(self):
1567        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1568        lang = self.request.cookies.get('kofa.language', portal_language)
1569        level_title = translate(self.context.level_title, 'waeup.kofa',
1570            target_language=lang)
1571        return translate(_('Course Registration Slip'),
1572            'waeup.kofa', target_language=portal_language) \
1573            + ' %s' % level_title
1574
1575    @property
1576    def tabletitle(self):
1577        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1578        tabletitle = []
1579        tabletitle.append(translate(_('1st Semester Courses'), 'waeup.kofa',
1580            target_language=portal_language))
1581        tabletitle.append(translate(_('2nd Semester Courses'), 'waeup.kofa',
1582            target_language=portal_language))
1583        tabletitle.append(translate(_('Level Courses'), 'waeup.kofa',
1584            target_language=portal_language))
1585        return tabletitle
1586
1587    def render(self):
1588        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1589        Code = translate(_('Code'), 'waeup.kofa', target_language=portal_language)
1590        Title = translate(_('Title'), 'waeup.kofa', target_language=portal_language)
1591        Dept = translate(_('Dept.'), 'waeup.kofa', target_language=portal_language)
1592        Faculty = translate(_('Faculty'), 'waeup.kofa', target_language=portal_language)
1593        Cred = translate(_('Cred.'), 'waeup.kofa', target_language=portal_language)
1594        #Mand = translate(_('Requ.'), 'waeup.kofa', target_language=portal_language)
1595        Score = translate(_('Score'), 'waeup.kofa', target_language=portal_language)
1596        Grade = translate(_('Grade'), 'waeup.kofa', target_language=portal_language)
1597        studentview = StudentBasePDFFormPage(self.context.student,
1598            self.request, self.omit_fields)
1599        students_utils = getUtility(IStudentsUtils)
1600
1601        tabledata = []
1602        tableheader = []
1603        for i in range(1,7):
1604            tabledata.append(sorted(
1605                [value for value in self.context.values() if value.semester == i],
1606                key=lambda value: str(value.semester) + value.code))
1607            tableheader.append([(Code,'code', 2.5),
1608                             (Title,'title', 5),
1609                             (Dept,'dcode', 1.5), (Faculty,'fcode', 1.5),
1610                             (Cred, 'credits', 1.5),
1611                             #(Mand, 'mandatory', 1.5),
1612                             (Score, 'score', 1.5),
1613                             (Grade, 'grade', 1.5),
1614                             #('Auto', 'automatic', 1.5)
1615                             ])
1616        return students_utils.renderPDF(
1617            self, 'course_registration_slip.pdf',
1618            self.context.student, studentview,
1619            tableheader=tableheader,
1620            tabledata=tabledata,
1621            omit_fields=self.omit_fields
1622            )
1623
1624class StudyLevelManageFormPage(KofaEditFormPage):
1625    """ Page to edit the student study level data
1626    """
1627    grok.context(IStudentStudyLevel)
1628    grok.name('manage')
1629    grok.require('waeup.manageStudent')
1630    grok.template('studylevelmanagepage')
1631    form_fields = grok.AutoFields(IStudentStudyLevel).omit(
1632        'validation_date', 'validated_by', 'total_credits', 'gpa', 'level')
1633    pnav = 4
1634    taboneactions = [_('Save'),_('Cancel')]
1635    tabtwoactions = [_('Add course ticket'),
1636        _('Remove selected tickets'),_('Cancel')]
1637    placeholder = _('Enter valid course code')
1638
1639    def update(self, ADD=None, course=None):
1640        if not self.context.__parent__.is_current \
1641            or self.context.student.studycourse_locked:
1642            emit_lock_message(self)
1643            return
1644        super(StudyLevelManageFormPage, self).update()
1645        if ADD is not None:
1646            if not course:
1647                self.flash(_('No valid course code entered.'), type="warning")
1648                self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1649                return
1650            cat = queryUtility(ICatalog, name='courses_catalog')
1651            result = cat.searchResults(code=(course, course))
1652            if len(result) != 1:
1653                self.flash(_('Course not found.'), type="warning")
1654            else:
1655                course = list(result)[0]
1656                addCourseTicket(self, course)
1657            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1658        return
1659
1660    @property
1661    def translated_values(self):
1662        return translated_values(self)
1663
1664    @property
1665    def label(self):
1666        # Here we know that the cookie has been set
1667        lang = self.request.cookies.get('kofa.language')
1668        level_title = translate(self.context.level_title, 'waeup.kofa',
1669            target_language=lang)
1670        return _('Manage ${a}',
1671            mapping = {'a':level_title})
1672
1673    @action(_('Save'), style='primary')
1674    def save(self, **data):
1675        msave(self, **data)
1676        return
1677
1678    @jsaction(_('Remove selected tickets'))
1679    def delCourseTicket(self, **data):
1680        form = self.request.form
1681        if 'val_id' in form:
1682            child_id = form['val_id']
1683        else:
1684            self.flash(_('No ticket selected.'), type="warning")
1685            self.redirect(self.url(self.context, '@@manage')+'#tab2')
1686            return
1687        if not isinstance(child_id, list):
1688            child_id = [child_id]
1689        deleted = []
1690        for id in child_id:
1691            del self.context[id]
1692            deleted.append(id)
1693        if len(deleted):
1694            self.flash(_('Successfully removed: ${a}',
1695                mapping = {'a':', '.join(deleted)}))
1696            self.context.writeLogMessage(
1697                self,'removed: %s at %s' %
1698                (', '.join(deleted), self.context.level))
1699        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1700        return
1701
1702class StudyLevelRemarkFormPage(KofaEditFormPage):
1703    """ Page to edit the student study level transcript remark only
1704    """
1705    grok.context(IStudentStudyLevel)
1706    grok.name('remark')
1707    grok.require('waeup.processTranscript')
1708    grok.template('studylevelremarkpage')
1709    form_fields = grok.AutoFields(IStudentStudyLevel).omit('level')
1710    form_fields['level_session'].for_display = True
1711    form_fields['level_verdict'].for_display = True
1712    form_fields['validation_date'].for_display = True
1713    form_fields['validated_by'].for_display = True
1714
1715    def update(self, ADD=None, course=None):
1716        if self.context.student.studycourse_locked:
1717            emit_lock_message(self)
1718            return
1719        super(StudyLevelRemarkFormPage, self).update()
1720
1721    @property
1722    def label(self):
1723        lang = self.request.cookies.get('kofa.language')
1724        level_title = translate(self.context.level_title, 'waeup.kofa',
1725            target_language=lang)
1726        return _(
1727            'Edit transcript remark of level ${a}', mapping = {'a':level_title})
1728
1729    @property
1730    def translated_values(self):
1731        return translated_values(self)
1732
1733    @action(_('Save remark and go and back to transcript validation page'),
1734        style='primary')
1735    def save(self, **data):
1736        msave(self, **data)
1737        self.redirect(self.url(self.context.student)
1738            + '/studycourse/validate_transcript#tab4')
1739        return
1740
1741class ValidateCoursesView(UtilityView, grok.View):
1742    """ Validate course list by course adviser
1743    """
1744    grok.context(IStudentStudyLevel)
1745    grok.name('validate_courses')
1746    grok.require('waeup.validateStudent')
1747
1748    def update(self):
1749        if not self.context.__parent__.is_current:
1750            emit_lock_message(self)
1751            return
1752        if str(self.context.student.current_level) != self.context.__name__:
1753            self.flash(_('This is not the student\'s current level.'),
1754                       type="danger")
1755        elif self.context.student.state == REGISTERED:
1756            IWorkflowInfo(self.context.student).fireTransition(
1757                'validate_courses')
1758            self.flash(_('Course list has been validated.'))
1759        else:
1760            self.flash(_('Student is in the wrong state.'), type="warning")
1761        self.redirect(self.url(self.context))
1762        return
1763
1764    def render(self):
1765        return
1766
1767class RejectCoursesView(UtilityView, grok.View):
1768    """ Reject course list by course adviser
1769    """
1770    grok.context(IStudentStudyLevel)
1771    grok.name('reject_courses')
1772    grok.require('waeup.validateStudent')
1773
1774    def update(self):
1775        if not self.context.__parent__.is_current:
1776            emit_lock_message(self)
1777            return
1778        if str(self.context.__parent__.current_level) != self.context.__name__:
1779            self.flash(_('This is not the student\'s current level.'),
1780                       type="danger")
1781            self.redirect(self.url(self.context))
1782            return
1783        elif self.context.student.state == VALIDATED:
1784            IWorkflowInfo(self.context.student).fireTransition('reset8')
1785            message = _('Course list request has been annulled.')
1786            self.flash(message)
1787        elif self.context.student.state == REGISTERED:
1788            IWorkflowInfo(self.context.student).fireTransition('reset7')
1789            message = _('Course list has been unregistered.')
1790            self.flash(message)
1791        else:
1792            self.flash(_('Student is in the wrong state.'), type="warning")
1793            self.redirect(self.url(self.context))
1794            return
1795        args = {'subject':message}
1796        self.redirect(self.url(self.context.student) +
1797            '/contactstudent?%s' % urlencode(args))
1798        return
1799
1800    def render(self):
1801        return
1802
1803class UnregisterCoursesView(UtilityView, grok.View):
1804    """Unregister course list by student
1805    """
1806    grok.context(IStudentStudyLevel)
1807    grok.name('unregister_courses')
1808    grok.require('waeup.handleStudent')
1809
1810    def update(self):
1811        if not self.context.__parent__.is_current:
1812            emit_lock_message(self)
1813            return
1814        try:
1815            deadline = grok.getSite()['configuration'][
1816                str(self.context.level_session)].coursereg_deadline
1817        except (TypeError, KeyError):
1818            deadline = None
1819        if deadline and deadline < datetime.now(pytz.utc):
1820            self.flash(_(
1821                "Course registration has ended. "
1822                "Unregistration is disabled."), type="warning")
1823        elif str(self.context.__parent__.current_level) != self.context.__name__:
1824            self.flash(_('This is not your current level.'), type="danger")
1825        elif self.context.student.state == REGISTERED:
1826            IWorkflowInfo(self.context.student).fireTransition('reset7')
1827            message = _('Course list has been unregistered.')
1828            self.flash(message)
1829        else:
1830            self.flash(_('You are in the wrong state.'), type="warning")
1831        self.redirect(self.url(self.context))
1832        return
1833
1834    def render(self):
1835        return
1836
1837class CourseTicketAddFormPage(KofaAddFormPage):
1838    """Add a course ticket.
1839    """
1840    grok.context(IStudentStudyLevel)
1841    grok.name('add')
1842    grok.require('waeup.manageStudent')
1843    label = _('Add course ticket')
1844    form_fields = grok.AutoFields(ICourseTicketAdd)
1845    pnav = 4
1846
1847    def update(self):
1848        if not self.context.__parent__.is_current \
1849            or self.context.student.studycourse_locked:
1850            emit_lock_message(self)
1851            return
1852        super(CourseTicketAddFormPage, self).update()
1853        return
1854
1855    @action(_('Add course ticket'), style='primary')
1856    def addCourseTicket(self, **data):
1857        course = data['course']
1858        success = addCourseTicket(self, course)
1859        if success:
1860            self.redirect(self.url(self.context, u'@@manage')+'#tab2')
1861        return
1862
1863    @action(_('Cancel'), validator=NullValidator)
1864    def cancel(self, **data):
1865        self.redirect(self.url(self.context))
1866
1867class CourseTicketDisplayFormPage(KofaDisplayFormPage):
1868    """ Page to display course tickets
1869    """
1870    grok.context(ICourseTicket)
1871    grok.name('index')
1872    grok.require('waeup.viewStudent')
1873    form_fields = grok.AutoFields(ICourseTicket).omit('course_category',
1874        'ticket_session')
1875    grok.template('courseticketpage')
1876    pnav = 4
1877
1878    @property
1879    def label(self):
1880        return _('${a}: Course Ticket ${b}', mapping = {
1881            'a':self.context.student.display_fullname,
1882            'b':self.context.code})
1883
1884class CourseTicketManageFormPage(KofaEditFormPage):
1885    """ Page to manage course tickets
1886    """
1887    grok.context(ICourseTicket)
1888    grok.name('manage')
1889    grok.require('waeup.manageStudent')
1890    form_fields = grok.AutoFields(ICourseTicket).omit('course_category')
1891    form_fields['title'].for_display = True
1892    form_fields['fcode'].for_display = True
1893    form_fields['dcode'].for_display = True
1894    form_fields['semester'].for_display = True
1895    form_fields['passmark'].for_display = True
1896    form_fields['credits'].for_display = True
1897    form_fields['mandatory'].for_display = False
1898    form_fields['automatic'].for_display = True
1899    form_fields['carry_over'].for_display = True
1900    form_fields['ticket_session'].for_display = True
1901    pnav = 4
1902    grok.template('courseticketmanagepage')
1903
1904    def update(self):
1905        if not self.context.__parent__.__parent__.is_current \
1906            or self.context.student.studycourse_locked:
1907            emit_lock_message(self)
1908            return
1909        super(CourseTicketManageFormPage, self).update()
1910        return
1911
1912    @property
1913    def label(self):
1914        return _('Manage course ticket ${a}', mapping = {'a':self.context.code})
1915
1916    @action('Save', style='primary')
1917    def save(self, **data):
1918        msave(self, **data)
1919        return
1920
1921class PaymentsManageFormPage(KofaEditFormPage):
1922    """ Page to manage the student payments
1923
1924    This manage form page is for both students and students officers.
1925    """
1926    grok.context(IStudentPaymentsContainer)
1927    grok.name('index')
1928    grok.require('waeup.viewStudent')
1929    form_fields = grok.AutoFields(IStudentPaymentsContainer)
1930    grok.template('paymentsmanagepage')
1931    pnav = 4
1932
1933    @property
1934    def manage_payments_allowed(self):
1935        return checkPermission('waeup.payStudent', self.context)
1936
1937    def unremovable(self, ticket):
1938        usertype = getattr(self.request.principal, 'user_type', None)
1939        if not usertype:
1940            return False
1941        if not self.manage_payments_allowed:
1942            return True
1943        return (self.request.principal.user_type == 'student' and ticket.r_code)
1944
1945    @property
1946    def label(self):
1947        return _('${a}: Payments',
1948            mapping = {'a':self.context.__parent__.display_fullname})
1949
1950    @jsaction(_('Remove selected tickets'))
1951    def delPaymentTicket(self, **data):
1952        form = self.request.form
1953        if 'val_id' in form:
1954            child_id = form['val_id']
1955        else:
1956            self.flash(_('No payment selected.'), type="warning")
1957            self.redirect(self.url(self.context))
1958            return
1959        if not isinstance(child_id, list):
1960            child_id = [child_id]
1961        deleted = []
1962        for id in child_id:
1963            # Students are not allowed to remove used payment tickets
1964            ticket = self.context.get(id, None)
1965            if ticket is not None and not self.unremovable(ticket):
1966                del self.context[id]
1967                deleted.append(id)
1968        if len(deleted):
1969            self.flash(_('Successfully removed: ${a}',
1970                mapping = {'a': ', '.join(deleted)}))
1971            self.context.writeLogMessage(
1972                self,'removed: %s' % ', '.join(deleted))
1973        self.redirect(self.url(self.context))
1974        return
1975
1976    #@action(_('Add online payment ticket'))
1977    #def addPaymentTicket(self, **data):
1978    #    self.redirect(self.url(self.context, '@@addop'))
1979
1980class OnlinePaymentAddFormPage(KofaAddFormPage):
1981    """ Page to add an online payment ticket
1982    """
1983    grok.context(IStudentPaymentsContainer)
1984    grok.name('addop')
1985    grok.template('onlinepaymentaddform')
1986    grok.require('waeup.payStudent')
1987    form_fields = grok.AutoFields(IStudentOnlinePayment).select(
1988        'p_category')
1989    label = _('Add online payment')
1990    pnav = 4
1991
1992    @property
1993    def selectable_categories(self):
1994        student = self.context.__parent__
1995        categories = getUtility(
1996            IKofaUtils).selectable_payment_categories(student)
1997        return sorted(categories.items(), key=lambda value: value[1])
1998
1999    @action(_('Create ticket'), style='primary')
2000    def createTicket(self, **data):
2001        p_category = data['p_category']
2002        previous_session = data.get('p_session', None)
2003        previous_level = data.get('p_level', None)
2004        student = self.context.__parent__
2005        # The hostel_application payment category is temporarily used
2006        # by Uniben.
2007        if p_category in ('bed_allocation', 'hostel_application') and student[
2008            'studycourse'].current_session != grok.getSite()[
2009            'hostels'].accommodation_session:
2010                self.flash(
2011                    _('Your current session does not match ' + \
2012                    'accommodation session.'), type="danger")
2013                return
2014        if 'maintenance' in p_category:
2015            current_session = str(student['studycourse'].current_session)
2016            if not current_session in student['accommodation']:
2017                self.flash(_('You have not yet booked accommodation.'),
2018                           type="warning")
2019                return
2020        students_utils = getUtility(IStudentsUtils)
2021        error, payment = students_utils.setPaymentDetails(
2022            p_category, student, previous_session, previous_level)
2023        if error is not None:
2024            self.flash(error, type="danger")
2025            return
2026        if p_category == 'transfer':
2027            payment.p_item = self.request.form['new_programme']
2028        self.context[payment.p_id] = payment
2029        self.flash(_('Payment ticket created.'))
2030        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
2031        self.redirect(self.url(self.context))
2032        return
2033
2034    @action(_('Cancel'), validator=NullValidator)
2035    def cancel(self, **data):
2036        self.redirect(self.url(self.context))
2037
2038class PreviousPaymentAddFormPage(KofaAddFormPage):
2039    """ Page to add an online payment ticket for previous sessions.
2040    """
2041    grok.context(IStudentPaymentsContainer)
2042    grok.name('addpp')
2043    grok.require('waeup.payStudent')
2044    form_fields = grok.AutoFields(IStudentPreviousPayment)
2045    label = _('Add previous session online payment')
2046    pnav = 4
2047
2048    def update(self):
2049        if self.context.student.before_payment:
2050            self.flash(_("No previous payment to be made."), type="warning")
2051            self.redirect(self.url(self.context))
2052        super(PreviousPaymentAddFormPage, self).update()
2053        return
2054
2055    @action(_('Create ticket'), style='primary')
2056    def createTicket(self, **data):
2057        p_category = data['p_category']
2058        previous_session = data.get('p_session', None)
2059        previous_level = data.get('p_level', None)
2060        student = self.context.__parent__
2061        students_utils = getUtility(IStudentsUtils)
2062        error, payment = students_utils.setPaymentDetails(
2063            p_category, student, previous_session, previous_level)
2064        if error is not None:
2065            self.flash(error, type="danger")
2066            return
2067        self.context[payment.p_id] = payment
2068        self.flash(_('Payment ticket created.'))
2069        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
2070        self.redirect(self.url(self.context))
2071        return
2072
2073    @action(_('Cancel'), validator=NullValidator)
2074    def cancel(self, **data):
2075        self.redirect(self.url(self.context))
2076
2077class BalancePaymentAddFormPage(KofaAddFormPage):
2078    """ Page to add an online payment which can balance s previous session
2079    payment.
2080    """
2081    grok.context(IStudentPaymentsContainer)
2082    grok.name('addbp')
2083    grok.require('waeup.manageStudent')
2084    form_fields = grok.AutoFields(IStudentBalancePayment)
2085    label = _('Add balance')
2086    pnav = 4
2087
2088    @action(_('Create ticket'), style='primary')
2089    def createTicket(self, **data):
2090        p_category = data['p_category']
2091        balance_session = data.get('balance_session', None)
2092        balance_level = data.get('balance_level', None)
2093        balance_amount = data.get('balance_amount', None)
2094        student = self.context.__parent__
2095        students_utils = getUtility(IStudentsUtils)
2096        error, payment = students_utils.setBalanceDetails(
2097            p_category, student, balance_session,
2098            balance_level, balance_amount)
2099        if error is not None:
2100            self.flash(error, type="danger")
2101            return
2102        self.context[payment.p_id] = payment
2103        self.flash(_('Payment ticket created.'))
2104        self.context.writeLogMessage(self,'added: %s' % payment.p_id)
2105        self.redirect(self.url(self.context))
2106        return
2107
2108    @action(_('Cancel'), validator=NullValidator)
2109    def cancel(self, **data):
2110        self.redirect(self.url(self.context))
2111
2112class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
2113    """ Page to view an online payment ticket
2114    """
2115    grok.context(IStudentOnlinePayment)
2116    grok.name('index')
2117    grok.require('waeup.viewStudent')
2118    form_fields = grok.AutoFields(IStudentOnlinePayment).omit('p_item')
2119    form_fields[
2120        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2121    form_fields[
2122        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2123    pnav = 4
2124
2125    @property
2126    def label(self):
2127        return _('${a}: Online Payment Ticket ${b}', mapping = {
2128            'a':self.context.student.display_fullname,
2129            'b':self.context.p_id})
2130
2131class OnlinePaymentApproveView(UtilityView, grok.View):
2132    """ Callback view
2133    """
2134    grok.context(IStudentOnlinePayment)
2135    grok.name('approve')
2136    grok.require('waeup.managePortal')
2137
2138    def update(self):
2139        flashtype, msg, log = self.context.approveStudentPayment()
2140        if log is not None:
2141            # Add log message to students.log
2142            self.context.writeLogMessage(self,log)
2143            # Add log message to payments.log
2144            self.context.logger.info(
2145                '%s,%s,%s,%s,%s,,,,,,' % (
2146                self.context.student.student_id,
2147                self.context.p_id, self.context.p_category,
2148                self.context.amount_auth, self.context.r_code))
2149        self.flash(msg, type=flashtype)
2150        return
2151
2152    def render(self):
2153        self.redirect(self.url(self.context, '@@index'))
2154        return
2155
2156class OnlinePaymentFakeApproveView(OnlinePaymentApproveView):
2157    """ Approval view for students.
2158
2159    This view is used for browser tests only and
2160    must be neutralized in custom pages!
2161    """
2162    grok.name('fake_approve')
2163    grok.require('waeup.payStudent')
2164
2165class ExportPDFPaymentSlip(UtilityView, grok.View):
2166    """Deliver a PDF slip of the context.
2167    """
2168    grok.context(IStudentOnlinePayment)
2169    grok.name('payment_slip.pdf')
2170    grok.require('waeup.viewStudent')
2171    form_fields = grok.AutoFields(IStudentOnlinePayment).omit('p_item')
2172    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2173    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2174    prefix = 'form'
2175    note = None
2176    omit_fields = (
2177        'password', 'suspended', 'phone', 'date_of_birth',
2178        'adm_code', 'sex', 'suspended_comment', 'current_level',
2179        'flash_notice')
2180
2181    @property
2182    def title(self):
2183        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2184        return translate(_('Payment Data'), 'waeup.kofa',
2185            target_language=portal_language)
2186
2187    @property
2188    def label(self):
2189        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2190        return translate(_('Online Payment Slip'),
2191            'waeup.kofa', target_language=portal_language) \
2192            + ' %s' % self.context.p_id
2193
2194    def render(self):
2195        #if self.context.p_state != 'paid':
2196        #    self.flash('Ticket not yet paid.')
2197        #    self.redirect(self.url(self.context))
2198        #    return
2199        studentview = StudentBasePDFFormPage(self.context.student,
2200            self.request, self.omit_fields)
2201        students_utils = getUtility(IStudentsUtils)
2202        return students_utils.renderPDF(self, 'payment_slip.pdf',
2203            self.context.student, studentview, note=self.note,
2204            omit_fields=self.omit_fields)
2205
2206
2207class AccommodationManageFormPage(KofaEditFormPage):
2208    """ Page to manage bed tickets.
2209
2210    This manage form page is for both students and students officers.
2211    """
2212    grok.context(IStudentAccommodation)
2213    grok.name('index')
2214    grok.require('waeup.handleAccommodation')
2215    form_fields = grok.AutoFields(IStudentAccommodation)
2216    grok.template('accommodationmanagepage')
2217    pnav = 4
2218    with_hostel_selection = True
2219
2220    @property
2221    def booking_allowed(self):
2222        students_utils = getUtility(IStudentsUtils)
2223        acc_details  = students_utils.getAccommodationDetails(self.context.student)
2224        error_message = students_utils.checkAccommodationRequirements(
2225            self.context.student, acc_details)
2226        if error_message:
2227            return False
2228        return True
2229
2230    @property
2231    def actionsgroup1(self):
2232        if not self.booking_allowed:
2233            return []
2234        if not self.with_hostel_selection:
2235            return []
2236        return [_('Save')]
2237
2238    @property
2239    def actionsgroup2(self):
2240        if getattr(self.request.principal, 'user_type', None) == 'student':
2241            ## Book button can be disabled in custom packages by
2242            ## uncommenting the following lines.
2243            #if not self.booking_allowed:
2244            #    return []
2245            return [_('Book accommodation')]
2246        return [_('Book accommodation'), _('Remove selected')]
2247
2248    @property
2249    def label(self):
2250        return _('${a}: Accommodation',
2251            mapping = {'a':self.context.__parent__.display_fullname})
2252
2253    @property
2254    def desired_hostel(self):
2255        if self.context.desired_hostel == 'no':
2256            return _('No favoured hostel')
2257        if self.context.desired_hostel:
2258            hostel = grok.getSite()['hostels'].get(self.context.desired_hostel)
2259            if hostel is not None:
2260                return hostel.hostel_name
2261        return
2262
2263    def getHostels(self):
2264        """Get a list of all stored hostels.
2265        """
2266        yield(dict(name=None, title='--', selected=''))
2267        selected = ''
2268        if self.context.desired_hostel == 'no':
2269          selected = 'selected'
2270        yield(dict(name='no', title=_('No favoured hostel'), selected=selected))
2271        for val in grok.getSite()['hostels'].values():
2272            selected = ''
2273            if val.hostel_id == self.context.desired_hostel:
2274                selected = 'selected'
2275            yield(dict(name=val.hostel_id, title=val.hostel_name,
2276                       selected=selected))
2277
2278    @action(_('Save'), style='primary')
2279    def save(self):
2280        hostel = self.request.form.get('hostel', None)
2281        self.context.desired_hostel = hostel
2282        self.flash(_('Your selection has been saved.'))
2283        return
2284
2285    @action(_('Book accommodation'), style='primary')
2286    def bookAccommodation(self, **data):
2287        self.redirect(self.url(self.context, 'add'))
2288        return
2289
2290    @jsaction(_('Remove selected'))
2291    def delBedTickets(self, **data):
2292        if getattr(self.request.principal, 'user_type', None) == 'student':
2293            self.flash(_('You are not allowed to remove bed tickets.'),
2294                       type="warning")
2295            self.redirect(self.url(self.context))
2296            return
2297        form = self.request.form
2298        if 'val_id' in form:
2299            child_id = form['val_id']
2300        else:
2301            self.flash(_('No bed ticket selected.'), type="warning")
2302            self.redirect(self.url(self.context))
2303            return
2304        if not isinstance(child_id, list):
2305            child_id = [child_id]
2306        deleted = []
2307        for id in child_id:
2308            del self.context[id]
2309            deleted.append(id)
2310        if len(deleted):
2311            self.flash(_('Successfully removed: ${a}',
2312                mapping = {'a':', '.join(deleted)}))
2313            self.context.writeLogMessage(
2314                self,'removed: % s' % ', '.join(deleted))
2315        self.redirect(self.url(self.context))
2316        return
2317
2318class BedTicketAddPage(KofaPage):
2319    """ Page to add a bed ticket
2320    """
2321    grok.context(IStudentAccommodation)
2322    grok.name('add')
2323    grok.require('waeup.handleAccommodation')
2324    grok.template('enterpin')
2325    ac_prefix = 'HOS'
2326    label = _('Add bed ticket')
2327    pnav = 4
2328    buttonname = _('Create bed ticket')
2329    notice = ''
2330    with_ac = True
2331
2332    def update(self, SUBMIT=None):
2333        student = self.context.student
2334        students_utils = getUtility(IStudentsUtils)
2335        acc_details  = students_utils.getAccommodationDetails(student)
2336        error_message = students_utils.checkAccommodationRequirements(
2337            student, acc_details)
2338        if error_message:
2339            self.flash(error_message, type="warning")
2340            self.redirect(self.url(self.context))
2341            return
2342        if self.with_ac:
2343            self.ac_series = self.request.form.get('ac_series', None)
2344            self.ac_number = self.request.form.get('ac_number', None)
2345        if SUBMIT is None:
2346            return
2347        if self.with_ac:
2348            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2349            code = get_access_code(pin)
2350            if not code:
2351                self.flash(_('Activation code is invalid.'), type="warning")
2352                return
2353        # Search and book bed
2354        cat = queryUtility(ICatalog, name='beds_catalog', default=None)
2355        entries = cat.searchResults(
2356            owner=(student.student_id,student.student_id))
2357        if len(entries):
2358            # If bed space has been manually allocated use this bed
2359            manual = True
2360            bed = [entry for entry in entries][0]
2361            # Safety belt for paranoids: Does this bed really exist on portal?
2362            # XXX: Can be remove if nobody complains.
2363            if bed.__parent__.__parent__ is None:
2364                self.flash(_('System error: Please contact the adminsitrator.'),
2365                           type="danger")
2366                self.context.writeLogMessage(
2367                    self, 'fatal error: %s' % bed.bed_id)
2368                return
2369        else:
2370            # else search for other available beds
2371            manual = False
2372            entries = cat.searchResults(
2373                bed_type=(acc_details['bt'],acc_details['bt']))
2374            available_beds = [
2375                entry for entry in entries if entry.owner == NOT_OCCUPIED]
2376            if available_beds:
2377                students_utils = getUtility(IStudentsUtils)
2378                bed = students_utils.selectBed(
2379                    available_beds, self.context.desired_hostel)
2380                if bed is None:
2381                    self.flash(_(
2382                        'There is no free bed in your desired hostel. '
2383                        'Please try another hostel.'),
2384                        type="warning")
2385                    self.redirect(self.url(self.context))
2386                    return
2387                # Safety belt for paranoids: Does this bed really exist
2388                # in portal?
2389                # XXX: Can be remove if nobody complains.
2390                if bed.__parent__.__parent__ is None:
2391                    self.flash(_(
2392                        'System error: Please contact the administrator.'),
2393                        type="warning")
2394                    self.context.writeLogMessage(
2395                        self, 'fatal error: %s' % bed.bed_id)
2396                    return
2397                bed.bookBed(student.student_id)
2398            else:
2399                self.flash(_('There is no free bed in your category ${a}.',
2400                    mapping = {'a':acc_details['bt']}), type="warning")
2401                self.redirect(self.url(self.context))
2402                return
2403        if self.with_ac:
2404            # Mark pin as used (this also fires a pin related transition)
2405            if code.state == USED:
2406                self.flash(_('Activation code has already been used.'),
2407                           type="warning")
2408                if not manual:
2409                    # Release the previously booked bed
2410                    bed.owner = NOT_OCCUPIED
2411                    # Catalog must be informed
2412                    notify(grok.ObjectModifiedEvent(bed))
2413                return
2414            else:
2415                comment = _(u'invalidated')
2416                # Here we know that the ac is in state initialized so we do not
2417                # expect an exception, but the owner might be different
2418                success = invalidate_accesscode(
2419                    pin, comment, self.context.student.student_id)
2420                if not success:
2421                    self.flash(_('You are not the owner of this access code.'),
2422                               type="warning")
2423                    if not manual:
2424                        # Release the previously booked bed
2425                        bed.owner = NOT_OCCUPIED
2426                        # Catalog must be informed
2427                        notify(grok.ObjectModifiedEvent(bed))
2428                    return
2429        # Create bed ticket
2430        bedticket = createObject(u'waeup.BedTicket')
2431        if self.with_ac:
2432            bedticket.booking_code = pin
2433        bedticket.booking_session = acc_details['booking_session']
2434        bedticket.bed_type = acc_details['bt']
2435        bedticket.bed = bed
2436        hall_title = bed.__parent__.hostel_name
2437        coordinates = bed.coordinates[1:]
2438        block, room_nr, bed_nr = coordinates
2439        bc = _('${a}, Block ${b}, Room ${c}, Bed ${d} (${e})', mapping = {
2440            'a':hall_title, 'b':block,
2441            'c':room_nr, 'd':bed_nr,
2442            'e':bed.bed_type})
2443        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2444        bedticket.bed_coordinates = translate(
2445            bc, 'waeup.kofa',target_language=portal_language)
2446        self.context.addBedTicket(bedticket)
2447        self.context.writeLogMessage(self, 'booked: %s' % bed.bed_id)
2448        self.flash(_('Bed ticket created and bed booked: ${a}',
2449            mapping = {'a':bedticket.display_coordinates}))
2450        self.redirect(self.url(self.context))
2451        return
2452
2453class BedTicketDisplayFormPage(KofaDisplayFormPage):
2454    """ Page to display bed tickets
2455    """
2456    grok.context(IBedTicket)
2457    grok.name('index')
2458    grok.require('waeup.handleAccommodation')
2459    form_fields = grok.AutoFields(IBedTicket).omit('bed_coordinates')
2460    form_fields['booking_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2461    pnav = 4
2462
2463    @property
2464    def label(self):
2465        return _('Bed Ticket for Session ${a}',
2466            mapping = {'a':self.context.getSessionString()})
2467
2468class ExportPDFBedTicketSlip(UtilityView, grok.View):
2469    """Deliver a PDF slip of the context.
2470    """
2471    grok.context(IBedTicket)
2472    grok.name('bed_allocation_slip.pdf')
2473    grok.require('waeup.handleAccommodation')
2474    form_fields = grok.AutoFields(IBedTicket).omit('bed_coordinates')
2475    form_fields['booking_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2476    prefix = 'form'
2477    omit_fields = (
2478        'password', 'suspended', 'phone', 'adm_code',
2479        'suspended_comment', 'date_of_birth', 'current_level',
2480        'flash_notice')
2481
2482    @property
2483    def title(self):
2484        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2485        return translate(_('Bed Allocation Data'), 'waeup.kofa',
2486            target_language=portal_language)
2487
2488    @property
2489    def label(self):
2490        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2491        #return translate(_('Bed Allocation: '),
2492        #    'waeup.kofa', target_language=portal_language) \
2493        #    + ' %s' % self.context.bed_coordinates
2494        return translate(_('Bed Allocation Slip'),
2495            'waeup.kofa', target_language=portal_language) \
2496            + ' %s' % self.context.getSessionString()
2497
2498    def render(self):
2499        studentview = StudentBasePDFFormPage(self.context.student,
2500            self.request, self.omit_fields)
2501        students_utils = getUtility(IStudentsUtils)
2502        note = None
2503        n = grok.getSite()['hostels'].allocation_expiration
2504        if n:
2505            note = _("""
2506<br /><br /><br /><br /><br /><font size="12">
2507Please endeavour to pay your hostel maintenance charge within ${a} days
2508 of being allocated a space or else you are deemed to have
2509 voluntarily forfeited it and it goes back into circulation to be
2510 available for booking afresh!</font>)
2511""")
2512            note = _(note, mapping={'a': n})
2513            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2514            note = translate(
2515                note, 'waeup.kofa', target_language=portal_language)
2516        return students_utils.renderPDF(
2517            self, 'bed_allocation_slip.pdf',
2518            self.context.student, studentview,
2519            omit_fields=self.omit_fields,
2520            note=note)
2521
2522class BedTicketRelocationView(UtilityView, grok.View):
2523    """ Callback view
2524    """
2525    grok.context(IBedTicket)
2526    grok.name('relocate')
2527    grok.require('waeup.manageHostels')
2528
2529    # Relocate student if student parameters have changed or the bed_type
2530    # of the bed has changed
2531    def update(self):
2532        success, msg = self.context.relocateStudent()
2533        if not success:
2534            self.flash(msg, type="warning")
2535        else:
2536            self.flash(msg)
2537        self.redirect(self.url(self.context))
2538        return
2539
2540    def render(self):
2541        return
2542
2543class StudentHistoryPage(KofaPage):
2544    """ Page to display student history
2545    """
2546    grok.context(IStudent)
2547    grok.name('history')
2548    grok.require('waeup.viewStudent')
2549    grok.template('studenthistory')
2550    pnav = 4
2551
2552    @property
2553    def label(self):
2554        return _('${a}: History', mapping = {'a':self.context.display_fullname})
2555
2556# Pages for students only
2557
2558class StudentBaseEditFormPage(KofaEditFormPage):
2559    """ View to edit student base data
2560    """
2561    grok.context(IStudent)
2562    grok.name('edit_base')
2563    grok.require('waeup.handleStudent')
2564    form_fields = grok.AutoFields(IStudentBase).select(
2565        'email', 'phone', 'parents_email')
2566    label = _('Edit base data')
2567    pnav = 4
2568
2569    @action(_('Save'), style='primary')
2570    def save(self, **data):
2571        msave(self, **data)
2572        return
2573
2574class StudentChangePasswordPage(KofaEditFormPage):
2575    """ View to edit student passwords
2576    """
2577    grok.context(IStudent)
2578    grok.name('change_password')
2579    grok.require('waeup.handleStudent')
2580    grok.template('change_password')
2581    label = _('Change password')
2582    pnav = 4
2583
2584    @action(_('Save'), style='primary')
2585    def save(self, **data):
2586        form = self.request.form
2587        password = form.get('change_password', None)
2588        password_ctl = form.get('change_password_repeat', None)
2589        if password:
2590            validator = getUtility(IPasswordValidator)
2591            errors = validator.validate_password(password, password_ctl)
2592            if not errors:
2593                IUserAccount(self.context).setPassword(password)
2594                # Unset temporary password
2595                self.context.temp_password = None
2596                self.context.writeLogMessage(self, 'saved: password')
2597                self.flash(_('Password changed.'))
2598            else:
2599                self.flash( ' '.join(errors), type="warning")
2600        return
2601
2602class StudentFilesUploadPage(KofaPage):
2603    """ View to upload files by student
2604    """
2605    grok.context(IStudent)
2606    grok.name('change_portrait')
2607    grok.require('waeup.uploadStudentFile')
2608    grok.template('filesuploadpage')
2609    label = _('Upload portrait')
2610    pnav = 4
2611
2612    def update(self):
2613        PORTRAIT_CHANGE_STATES = getUtility(IStudentsUtils).PORTRAIT_CHANGE_STATES
2614        if self.context.student.state not in PORTRAIT_CHANGE_STATES:
2615            emit_lock_message(self)
2616            return
2617        super(StudentFilesUploadPage, self).update()
2618        return
2619
2620class StartClearancePage(KofaPage):
2621    grok.context(IStudent)
2622    grok.name('start_clearance')
2623    grok.require('waeup.handleStudent')
2624    grok.template('enterpin')
2625    label = _('Start clearance')
2626    ac_prefix = 'CLR'
2627    notice = ''
2628    pnav = 4
2629    buttonname = _('Start clearance now')
2630    with_ac = True
2631
2632    @property
2633    def all_required_fields_filled(self):
2634        if not self.context.email:
2635            return _("Email address is missing."), 'edit_base'
2636        if not self.context.phone:
2637            return _("Phone number is missing."), 'edit_base'
2638        return
2639
2640    @property
2641    def portrait_uploaded(self):
2642        store = getUtility(IExtFileStore)
2643        if store.getFileByContext(self.context, attr=u'passport.jpg'):
2644            return True
2645        return False
2646
2647    def update(self, SUBMIT=None):
2648        if not self.context.state == ADMITTED:
2649            self.flash(_("Wrong state"), type="warning")
2650            self.redirect(self.url(self.context))
2651            return
2652        if not self.portrait_uploaded:
2653            self.flash(_("No portrait uploaded."), type="warning")
2654            self.redirect(self.url(self.context, 'change_portrait'))
2655            return
2656        if self.all_required_fields_filled:
2657            arf_warning = self.all_required_fields_filled[0]
2658            arf_redirect = self.all_required_fields_filled[1]
2659            self.flash(arf_warning, type="warning")
2660            self.redirect(self.url(self.context, arf_redirect))
2661            return
2662        if self.with_ac:
2663            self.ac_series = self.request.form.get('ac_series', None)
2664            self.ac_number = self.request.form.get('ac_number', None)
2665        if SUBMIT is None:
2666            return
2667        if self.with_ac:
2668            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2669            code = get_access_code(pin)
2670            if not code:
2671                self.flash(_('Activation code is invalid.'), type="warning")
2672                return
2673            if code.state == USED:
2674                self.flash(_('Activation code has already been used.'),
2675                           type="warning")
2676                return
2677            # Mark pin as used (this also fires a pin related transition)
2678            # and fire transition start_clearance
2679            comment = _(u"invalidated")
2680            # Here we know that the ac is in state initialized so we do not
2681            # expect an exception, but the owner might be different
2682            if not invalidate_accesscode(pin, comment, self.context.student_id):
2683                self.flash(_('You are not the owner of this access code.'),
2684                           type="warning")
2685                return
2686            self.context.clr_code = pin
2687        IWorkflowInfo(self.context).fireTransition('start_clearance')
2688        self.flash(_('Clearance process has been started.'))
2689        self.redirect(self.url(self.context,'cedit'))
2690        return
2691
2692class StudentClearanceEditFormPage(StudentClearanceManageFormPage):
2693    """ View to edit student clearance data by student
2694    """
2695    grok.context(IStudent)
2696    grok.name('cedit')
2697    grok.require('waeup.handleStudent')
2698    label = _('Edit clearance data')
2699
2700    @property
2701    def form_fields(self):
2702        if self.context.is_postgrad:
2703            form_fields = grok.AutoFields(IPGStudentClearance).omit(
2704                'clr_code', 'officer_comment')
2705        else:
2706            form_fields = grok.AutoFields(IUGStudentClearance).omit(
2707                'clr_code', 'officer_comment')
2708        return form_fields
2709
2710    def update(self):
2711        if self.context.clearance_locked:
2712            emit_lock_message(self)
2713            return
2714        return super(StudentClearanceEditFormPage, self).update()
2715
2716    @action(_('Save'), style='primary')
2717    def save(self, **data):
2718        self.applyData(self.context, **data)
2719        self.flash(_('Clearance form has been saved.'))
2720        return
2721
2722    def dataNotComplete(self):
2723        """To be implemented in the customization package.
2724        """
2725        return False
2726
2727    @action(_('Save and request clearance'), style='primary',
2728            warning=_('You can not edit your data after '
2729            'requesting clearance. You really want to request clearance now?'))
2730    def requestClearance(self, **data):
2731        self.applyData(self.context, **data)
2732        if self.dataNotComplete():
2733            self.flash(self.dataNotComplete(), type="warning")
2734            return
2735        self.flash(_('Clearance form has been saved.'))
2736        if self.context.clr_code:
2737            self.redirect(self.url(self.context, 'request_clearance'))
2738        else:
2739            # We bypass the request_clearance page if student
2740            # has been imported in state 'clearance started' and
2741            # no clr_code was entered before.
2742            state = IWorkflowState(self.context).getState()
2743            if state != CLEARANCE:
2744                # This shouldn't happen, but the application officer
2745                # might have forgotten to lock the form after changing the state
2746                self.flash(_('This form cannot be submitted. Wrong state!'),
2747                           type="danger")
2748                return
2749            IWorkflowInfo(self.context).fireTransition('request_clearance')
2750            self.flash(_('Clearance has been requested.'))
2751            self.redirect(self.url(self.context))
2752        return
2753
2754class RequestClearancePage(KofaPage):
2755    grok.context(IStudent)
2756    grok.name('request_clearance')
2757    grok.require('waeup.handleStudent')
2758    grok.template('enterpin')
2759    label = _('Request clearance')
2760    notice = _('Enter the CLR access code used for starting clearance.')
2761    ac_prefix = 'CLR'
2762    pnav = 4
2763    buttonname = _('Request clearance now')
2764    with_ac = True
2765
2766    def update(self, SUBMIT=None):
2767        if self.with_ac:
2768            self.ac_series = self.request.form.get('ac_series', None)
2769            self.ac_number = self.request.form.get('ac_number', None)
2770        if SUBMIT is None:
2771            return
2772        if self.with_ac:
2773            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2774            if self.context.clr_code and self.context.clr_code != pin:
2775                self.flash(_("This isn't your CLR access code."), type="danger")
2776                return
2777        state = IWorkflowState(self.context).getState()
2778        if state != CLEARANCE:
2779            # This shouldn't happen, but the application officer
2780            # might have forgotten to lock the form after changing the state
2781            self.flash(_('This form cannot be submitted. Wrong state!'),
2782                       type="danger")
2783            return
2784        IWorkflowInfo(self.context).fireTransition('request_clearance')
2785        self.flash(_('Clearance has been requested.'))
2786        self.redirect(self.url(self.context))
2787        return
2788
2789class StartSessionPage(KofaPage):
2790    grok.context(IStudentStudyCourse)
2791    grok.name('start_session')
2792    grok.require('waeup.handleStudent')
2793    grok.template('enterpin')
2794    label = _('Start session')
2795    ac_prefix = 'SFE'
2796    notice = ''
2797    pnav = 4
2798    buttonname = _('Start now')
2799    with_ac = True
2800
2801    def update(self, SUBMIT=None):
2802        if not self.context.is_current:
2803            emit_lock_message(self)
2804            return
2805        super(StartSessionPage, self).update()
2806        if not self.context.next_session_allowed:
2807            self.flash(_("You are not entitled to start session."),
2808                       type="warning")
2809            self.redirect(self.url(self.context))
2810            return
2811        if self.with_ac:
2812            self.ac_series = self.request.form.get('ac_series', None)
2813            self.ac_number = self.request.form.get('ac_number', None)
2814        if SUBMIT is None:
2815            return
2816        if self.with_ac:
2817            pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
2818            code = get_access_code(pin)
2819            if not code:
2820                self.flash(_('Activation code is invalid.'), type="warning")
2821                return
2822            # Mark pin as used (this also fires a pin related transition)
2823            if code.state == USED:
2824                self.flash(_('Activation code has already been used.'),
2825                           type="warning")
2826                return
2827            else:
2828                comment = _(u"invalidated")
2829                # Here we know that the ac is in state initialized so we do not
2830                # expect an error, but the owner might be different
2831                if not invalidate_accesscode(
2832                    pin,comment,self.context.student.student_id):
2833                    self.flash(_('You are not the owner of this access code.'),
2834                               type="warning")
2835                    return
2836        try:
2837            if self.context.student.state == CLEARED:
2838                IWorkflowInfo(self.context.student).fireTransition(
2839                    'pay_first_school_fee')
2840            elif self.context.student.state == RETURNING:
2841                IWorkflowInfo(self.context.student).fireTransition(
2842                    'pay_school_fee')
2843            elif self.context.student.state == PAID:
2844                IWorkflowInfo(self.context.student).fireTransition(
2845                    'pay_pg_fee')
2846        except ConstraintNotSatisfied:
2847            self.flash(_('An error occurred, please contact the system administrator.'),
2848                       type="danger")
2849            return
2850        self.flash(_('Session started.'))
2851        self.redirect(self.url(self.context))
2852        return
2853
2854class AddStudyLevelFormPage(KofaEditFormPage):
2855    """ Page for students to add current study levels
2856    """
2857    grok.context(IStudentStudyCourse)
2858    grok.name('add')
2859    grok.require('waeup.handleStudent')
2860    grok.template('studyleveladdpage')
2861    form_fields = grok.AutoFields(IStudentStudyCourse)
2862    pnav = 4
2863
2864    @property
2865    def label(self):
2866        studylevelsource = StudyLevelSource().factory
2867        code = self.context.current_level
2868        title = studylevelsource.getTitle(self.context, code)
2869        return _('Add current level ${a}', mapping = {'a':title})
2870
2871    def update(self):
2872        if not self.context.is_current \
2873            or self.context.student.studycourse_locked:
2874            emit_lock_message(self)
2875            return
2876        if self.context.student.state != PAID:
2877            emit_lock_message(self)
2878            return
2879        code = self.context.current_level
2880        if code is None:
2881            self.flash(_('Your data are incomplete'), type="danger")
2882            self.redirect(self.url(self.context))
2883            return
2884        super(AddStudyLevelFormPage, self).update()
2885        return
2886
2887    @action(_('Create course list now'), style='primary')
2888    def addStudyLevel(self, **data):
2889        studylevel = createObject(u'waeup.StudentStudyLevel')
2890        studylevel.level = self.context.current_level
2891        studylevel.level_session = self.context.current_session
2892        try:
2893            self.context.addStudentStudyLevel(
2894                self.context.certificate,studylevel)
2895        except KeyError:
2896            self.flash(_('This level exists.'), type="warning")
2897            self.redirect(self.url(self.context))
2898            return
2899        except RequiredMissing:
2900            self.flash(_('Your data are incomplete.'), type="danger")
2901            self.redirect(self.url(self.context))
2902            return
2903        self.flash(_('You successfully created a new course list.'))
2904        self.redirect(self.url(self.context, str(studylevel.level)))
2905        return
2906
2907class StudyLevelEditFormPage(KofaEditFormPage):
2908    """ Page to edit the student study level data by students
2909    """
2910    grok.context(IStudentStudyLevel)
2911    grok.name('edit')
2912    grok.require('waeup.editStudyLevel')
2913    grok.template('studyleveleditpage')
2914    pnav = 4
2915    placeholder = _('Enter valid course code')
2916
2917    def update(self, ADD=None, course=None):
2918        if not self.context.__parent__.is_current:
2919            emit_lock_message(self)
2920            return
2921        if self.context.student.state != PAID or \
2922            not self.context.is_current_level:
2923            emit_lock_message(self)
2924            return
2925        super(StudyLevelEditFormPage, self).update()
2926        if ADD is not None:
2927            if not course:
2928                self.flash(_('No valid course code entered.'), type="warning")
2929                return
2930            cat = queryUtility(ICatalog, name='courses_catalog')
2931            result = cat.searchResults(code=(course, course))
2932            if len(result) != 1:
2933                self.flash(_('Course not found.'), type="warning")
2934                return
2935            course = list(result)[0]
2936            addCourseTicket(self, course)
2937        return
2938
2939    @property
2940    def label(self):
2941        # Here we know that the cookie has been set
2942        lang = self.request.cookies.get('kofa.language')
2943        level_title = translate(self.context.level_title, 'waeup.kofa',
2944            target_language=lang)
2945        return _('Edit course list of ${a}',
2946            mapping = {'a':level_title})
2947
2948    @property
2949    def translated_values(self):
2950        return translated_values(self)
2951
2952    def _delCourseTicket(self, **data):
2953        form = self.request.form
2954        if 'val_id' in form:
2955            child_id = form['val_id']
2956        else:
2957            self.flash(_('No ticket selected.'), type="warning")
2958            self.redirect(self.url(self.context, '@@edit'))
2959            return
2960        if not isinstance(child_id, list):
2961            child_id = [child_id]
2962        deleted = []
2963        for id in child_id:
2964            # Students are not allowed to remove core tickets
2965            if id in self.context and \
2966                self.context[id].removable_by_student:
2967                del self.context[id]
2968                deleted.append(id)
2969        if len(deleted):
2970            self.flash(_('Successfully removed: ${a}',
2971                mapping = {'a':', '.join(deleted)}))
2972            self.context.writeLogMessage(
2973                self,'removed: %s at %s' %
2974                (', '.join(deleted), self.context.level))
2975        self.redirect(self.url(self.context, u'@@edit'))
2976        return
2977
2978    @jsaction(_('Remove selected tickets'))
2979    def delCourseTicket(self, **data):
2980        self._delCourseTicket(**data)
2981        return
2982
2983    def _updateTickets(self, **data):
2984        cat = queryUtility(ICatalog, name='courses_catalog')
2985        invalidated = list()
2986        for value in self.context.values():
2987            result = cat.searchResults(code=(value.code, value.code))
2988            if len(result) != 1:
2989                course = None
2990            else:
2991                course = list(result)[0]
2992            invalid = self.context.updateCourseTicket(value, course)
2993            if invalid:
2994                invalidated.append(invalid)
2995        if invalidated:
2996            invalidated_string = ', '.join(invalidated)
2997            self.context.writeLogMessage(
2998                self, 'course tickets invalidated: %s' % invalidated_string)
2999        self.flash(_('All course tickets updated.'))
3000        return
3001
3002    @action(_('Update all tickets'),
3003        tooltip=_('Update all course parameters including course titles.'))
3004    def updateTickets(self, **data):
3005        self._updateTickets(**data)
3006        return
3007
3008    def _registerCourses(self, **data):
3009        if self.context.student.is_postgrad and \
3010            not self.context.student.is_special_postgrad:
3011            self.flash(_(
3012                "You are a postgraduate student, "
3013                "your course list can't bee registered."), type="warning")
3014            self.redirect(self.url(self.context))
3015            return
3016        students_utils = getUtility(IStudentsUtils)
3017        warning = students_utils.warnCreditsOOR(self.context)
3018        if warning:
3019            self.flash(warning, type="warning")
3020            return
3021        msg = self.context.course_registration_forbidden
3022        if msg:
3023            self.flash(msg, type="warning")
3024            return
3025        IWorkflowInfo(self.context.student).fireTransition(
3026            'register_courses')
3027        self.flash(_('Course list has been registered.'))
3028        self.redirect(self.url(self.context))
3029        return
3030
3031    @action(_('Register course list'), style='primary',
3032        warning=_('You can not edit your course list after registration.'
3033            ' You really want to register?'))
3034    def registerCourses(self, **data):
3035        self._registerCourses(**data)
3036        return
3037
3038class CourseTicketAddFormPage2(CourseTicketAddFormPage):
3039    """Add a course ticket by student.
3040    """
3041    grok.name('ctadd')
3042    grok.require('waeup.handleStudent')
3043    form_fields = grok.AutoFields(ICourseTicketAdd)
3044
3045    def update(self):
3046        if self.context.student.state != PAID or \
3047            not self.context.is_current_level:
3048            emit_lock_message(self)
3049            return
3050        super(CourseTicketAddFormPage2, self).update()
3051        return
3052
3053    @action(_('Add course ticket'))
3054    def addCourseTicket(self, **data):
3055        # Safety belt
3056        if self.context.student.state != PAID:
3057            return
3058        course = data['course']
3059        success = addCourseTicket(self, course)
3060        if success:
3061            self.redirect(self.url(self.context, u'@@edit'))
3062        return
3063
3064class SetPasswordPage(KofaPage):
3065    grok.context(IKofaObject)
3066    grok.name('setpassword')
3067    grok.require('waeup.Anonymous')
3068    grok.template('setpassword')
3069    label = _('Set password for first-time login')
3070    ac_prefix = 'PWD'
3071    pnav = 0
3072    set_button = _('Set')
3073
3074    def update(self, SUBMIT=None):
3075        self.reg_number = self.request.form.get('reg_number', None)
3076        self.ac_series = self.request.form.get('ac_series', None)
3077        self.ac_number = self.request.form.get('ac_number', None)
3078
3079        if SUBMIT is None:
3080            return
3081        hitlist = search(query=self.reg_number,
3082            searchtype='reg_number', view=self)
3083        if not hitlist:
3084            self.flash(_('No student found.'), type="warning")
3085            return
3086        if len(hitlist) != 1:   # Cannot happen but anyway
3087            self.flash(_('More than one student found.'), type="warning")
3088            return
3089        student = hitlist[0].context
3090        self.student_id = student.student_id
3091        student_pw = student.password
3092        pin = '%s-%s-%s' % (self.ac_prefix, self.ac_series, self.ac_number)
3093        code = get_access_code(pin)
3094        if not code:
3095            self.flash(_('Access code is invalid.'), type="warning")
3096            return
3097        if student_pw and pin == student.adm_code:
3098            self.flash(_(
3099                'Password has already been set. Your Student Id is ${a}',
3100                mapping = {'a':self.student_id}))
3101            return
3102        elif student_pw:
3103            self.flash(
3104                _('Password has already been set. You are using the ' +
3105                'wrong Access Code.'), type="warning")
3106            return
3107        # Mark pin as used (this also fires a pin related transition)
3108        # and set student password
3109        if code.state == USED:
3110            self.flash(_('Access code has already been used.'), type="warning")
3111            return
3112        else:
3113            comment = _(u"invalidated")
3114            # Here we know that the ac is in state initialized so we do not
3115            # expect an exception
3116            invalidate_accesscode(pin,comment)
3117            IUserAccount(student).setPassword(self.ac_number)
3118            student.adm_code = pin
3119        self.flash(_('Password has been set. Your Student Id is ${a}',
3120            mapping = {'a':self.student_id}))
3121        return
3122
3123class StudentRequestPasswordPage(KofaAddFormPage):
3124    """Captcha'd request password page for students.
3125    """
3126    grok.name('requestpw')
3127    grok.require('waeup.Anonymous')
3128    grok.template('requestpw')
3129    form_fields = grok.AutoFields(IStudentRequestPW).select(
3130        'lastname','number','email')
3131    label = _('Request password for first-time login')
3132
3133    def update(self):
3134        blocker = grok.getSite()['configuration'].maintmode_enabled_by
3135        if blocker:
3136            self.flash(_('The portal is in maintenance mode. '
3137                        'Password request forms are temporarily disabled.'),
3138                       type='warning')
3139            self.redirect(self.url(self.context))
3140            return
3141        # Handle captcha
3142        self.captcha = getUtility(ICaptchaManager).getCaptcha()
3143        self.captcha_result = self.captcha.verify(self.request)
3144        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
3145        return
3146
3147    def _redirect(self, email, password, student_id):
3148        # Forward only email to landing page in base package.
3149        self.redirect(self.url(self.context, 'requestpw_complete',
3150            data = dict(email=email)))
3151        return
3152
3153    def _redirect_no_student(self):
3154        # No record found, this is the truth. We do not redirect here.
3155        # We are using this method in custom packages
3156        # for redirecting alumni to the application section.
3157        self.flash(_('No student record found.'), type="warning")
3158        return
3159
3160    def _pw_used(self):
3161        # XXX: False if password has not been used. We need an extra
3162        #      attribute which remembers if student logged in.
3163        return True
3164
3165    @action(_('Send login credentials to email address'), style='primary')
3166    def get_credentials(self, **data):
3167        if not self.captcha_result.is_valid:
3168            # Captcha will display error messages automatically.
3169            # No need to flash something.
3170            return
3171        number = data.get('number','')
3172        lastname = data.get('lastname','')
3173        cat = getUtility(ICatalog, name='students_catalog')
3174        results = list(
3175            cat.searchResults(reg_number=(number, number)))
3176        if not results:
3177            results = list(
3178                cat.searchResults(matric_number=(number, number)))
3179        if results:
3180            student = results[0]
3181            if getattr(student,'lastname',None) is None:
3182                self.flash(_('An error occurred.'), type="danger")
3183                return
3184            elif student.lastname.lower() != lastname.lower():
3185                # Don't tell the truth here. Anonymous must not
3186                # know that a record was found and only the lastname
3187                # verification failed.
3188                self.flash(_('No student record found.'), type="warning")
3189                return
3190            elif student.password is not None and self._pw_used:
3191                self.flash(_('Your password has already been set and used. '
3192                             'Please proceed to the login page.'),
3193                           type="warning")
3194                return
3195            # Store email address but nothing else.
3196            student.email = data['email']
3197            notify(grok.ObjectModifiedEvent(student))
3198        else:
3199            self._redirect_no_student()
3200            return
3201
3202        kofa_utils = getUtility(IKofaUtils)
3203        password = kofa_utils.genPassword()
3204        mandate = PasswordMandate()
3205        mandate.params['password'] = password
3206        mandate.params['user'] = student
3207        site = grok.getSite()
3208        site['mandates'].addMandate(mandate)
3209        # Send email with credentials
3210        args = {'mandate_id':mandate.mandate_id}
3211        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3212        url_info = u'Confirmation link: %s' % mandate_url
3213        msg = _('You have successfully requested a password for the')
3214        if kofa_utils.sendCredentials(IUserAccount(student),
3215            password, url_info, msg):
3216            email_sent = student.email
3217        else:
3218            email_sent = None
3219        self._redirect(email=email_sent, password=password,
3220            student_id=student.student_id)
3221        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3222        self.context.logger.info(
3223            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
3224        return
3225
3226class ParentsUser:
3227    pass
3228
3229class RequestParentsPasswordPage(StudentRequestPasswordPage):
3230    """Captcha'd request password page for parents.
3231    """
3232    grok.name('requestppw')
3233    grok.template('requestppw')
3234    label = _('Request password for parents access')
3235
3236    def update(self):
3237        super(RequestParentsPasswordPage, self).update()
3238        kofa_utils = getUtility(IKofaUtils)
3239        self.temp_password_minutes = kofa_utils.TEMP_PASSWORD_MINUTES
3240        return
3241
3242    @action(_('Send temporary login credentials to email address'), style='primary')
3243    def get_credentials(self, **data):
3244        if not self.captcha_result.is_valid:
3245            # Captcha will display error messages automatically.
3246            # No need to flash something.
3247            return
3248        number = data.get('number','')
3249        lastname = data.get('lastname','')
3250        email = data['email']
3251        cat = getUtility(ICatalog, name='students_catalog')
3252        results = list(
3253            cat.searchResults(reg_number=(number, number)))
3254        if not results:
3255            results = list(
3256                cat.searchResults(matric_number=(number, number)))
3257        if results:
3258            student = results[0]
3259            if getattr(student,'lastname',None) is None:
3260                self.flash(_('An error occurred.'), type="danger")
3261                return
3262            elif student.lastname.lower() != lastname.lower():
3263                # Don't tell the truth here. Anonymous must not
3264                # know that a record was found and only the lastname
3265                # verification failed.
3266                self.flash(_('No student record found.'), type="warning")
3267                return
3268            elif email != student.parents_email:
3269                self.flash(_('Wrong email address.'), type="warning")
3270                return
3271        else:
3272            self._redirect_no_student()
3273            return
3274        kofa_utils = getUtility(IKofaUtils)
3275        password = kofa_utils.genPassword()
3276        mandate = ParentsPasswordMandate()
3277        mandate.params['password'] = password
3278        mandate.params['student'] = student
3279        site = grok.getSite()
3280        site['mandates'].addMandate(mandate)
3281        # Send email with credentials
3282        args = {'mandate_id':mandate.mandate_id}
3283        mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
3284        url_info = u'Confirmation link: %s' % mandate_url
3285        msg = _('You have successfully requested a parents password for the')
3286        # Create a fake user
3287        user = ParentsUser()
3288        user.name = student.student_id
3289        user.title = "Parents of %s" % student.display_fullname
3290        user.email = student.parents_email
3291        if kofa_utils.sendCredentials(user, password, url_info, msg):
3292            email_sent = user.email
3293        else:
3294            email_sent = None
3295        self._redirect(email=email_sent, password=password,
3296            student_id=student.student_id)
3297        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3298        self.context.logger.info(
3299            '%s - %s (%s) - %s' % (ob_class, number, student.student_id, email_sent))
3300        return
3301
3302class StudentRequestPasswordEmailSent(KofaPage):
3303    """Landing page after successful password request.
3304
3305    """
3306    grok.name('requestpw_complete')
3307    grok.require('waeup.Public')
3308    grok.template('requestpwmailsent')
3309    label = _('Your password request was successful.')
3310
3311    def update(self, email=None, student_id=None, password=None):
3312        self.email = email
3313        self.password = password
3314        self.student_id = student_id
3315        return
3316
3317class FilterStudentsInDepartmentPage(KofaPage):
3318    """Page that filters and lists students.
3319    """
3320    grok.context(IDepartment)
3321    grok.require('waeup.showStudents')
3322    grok.name('students')
3323    grok.template('filterstudentspage')
3324    pnav = 1
3325    session_label = _('Current Session')
3326    level_label = _('Current Level')
3327
3328    def label(self):
3329        return 'Students in %s' % self.context.longtitle
3330
3331    def _set_session_values(self):
3332        vocab_terms = academic_sessions_vocab.by_value.values()
3333        self.sessions = sorted(
3334            [(x.title, x.token) for x in vocab_terms], reverse=True)
3335        self.sessions += [('All Sessions', 'all')]
3336        return
3337
3338    def _set_level_values(self):
3339        vocab_terms = course_levels.by_value.values()
3340        self.levels = sorted(
3341            [(x.title, x.token) for x in vocab_terms])
3342        self.levels += [('All Levels', 'all')]
3343        return
3344
3345    def _searchCatalog(self, session, level):
3346        if level not in (10, 999, None):
3347            start_level = 100 * (level // 100)
3348            end_level = start_level + 90
3349        else:
3350            start_level = end_level = level
3351        cat = queryUtility(ICatalog, name='students_catalog')
3352        students = cat.searchResults(
3353            current_session=(session, session),
3354            current_level=(start_level, end_level),
3355            depcode=(self.context.code, self.context.code)
3356            )
3357        hitlist = []
3358        for student in students:
3359            hitlist.append(StudentQueryResultItem(student, view=self))
3360        return hitlist
3361
3362    def update(self, SHOW=None, session=None, level=None):
3363        self.parent_url = self.url(self.context.__parent__)
3364        self._set_session_values()
3365        self._set_level_values()
3366        self.hitlist = []
3367        self.session_default = session
3368        self.level_default = level
3369        if SHOW is not None:
3370            if session != 'all':
3371                self.session = int(session)
3372                self.session_string = '%s %s/%s' % (
3373                    self.session_label, self.session, self.session+1)
3374            else:
3375                self.session = None
3376                self.session_string = _('in any session')
3377            if level != 'all':
3378                self.level = int(level)
3379                self.level_string = '%s %s' % (self.level_label, self.level)
3380            else:
3381                self.level = None
3382                self.level_string = _('at any level')
3383            self.hitlist = self._searchCatalog(self.session, self.level)
3384            if not self.hitlist:
3385                self.flash(_('No student found.'), type="warning")
3386        return
3387
3388class FilterStudentsInCertificatePage(FilterStudentsInDepartmentPage):
3389    """Page that filters and lists students.
3390    """
3391    grok.context(ICertificate)
3392
3393    def label(self):
3394        return 'Students studying %s' % self.context.longtitle
3395
3396    def _searchCatalog(self, session, level):
3397        if level not in (10, 999, None):
3398            start_level = 100 * (level // 100)
3399            end_level = start_level + 90
3400        else:
3401            start_level = end_level = level
3402        cat = queryUtility(ICatalog, name='students_catalog')
3403        students = cat.searchResults(
3404            current_session=(session, session),
3405            current_level=(start_level, end_level),
3406            certcode=(self.context.code, self.context.code)
3407            )
3408        hitlist = []
3409        for student in students:
3410            hitlist.append(StudentQueryResultItem(student, view=self))
3411        return hitlist
3412
3413class FilterStudentsInCoursePage(FilterStudentsInDepartmentPage):
3414    """Page that filters and lists students.
3415    """
3416    grok.context(ICourse)
3417    grok.require('waeup.viewStudent')
3418
3419    session_label = _('Session')
3420    level_label = _('Level')
3421
3422    def label(self):
3423        return 'Students registered for %s' % self.context.longtitle
3424
3425    def _searchCatalog(self, session, level):
3426        if level not in (10, 999, None):
3427            start_level = 100 * (level // 100)
3428            end_level = start_level + 90
3429        else:
3430            start_level = end_level = level
3431        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3432        coursetickets = cat.searchResults(
3433            session=(session, session),
3434            level=(start_level, end_level),
3435            code=(self.context.code, self.context.code)
3436            )
3437        hitlist = []
3438        for ticket in coursetickets:
3439            hitlist.append(StudentQueryResultItem(ticket.student, view=self))
3440        return list(set(hitlist))
3441
3442class ClearAllStudentsInDepartmentView(UtilityView, grok.View):
3443    """ Clear all students of a department in state 'clearance requested'.
3444    """
3445    grok.context(IDepartment)
3446    grok.name('clearallstudents')
3447    grok.require('waeup.clearAllStudents')
3448
3449    def update(self):
3450        cat = queryUtility(ICatalog, name='students_catalog')
3451        students = cat.searchResults(
3452            depcode=(self.context.code, self.context.code),
3453            state=(REQUESTED, REQUESTED)
3454            )
3455        num = 0
3456        for student in students:
3457            if getUtility(IStudentsUtils).clearance_disabled_message(student):
3458                continue
3459            IWorkflowInfo(student).fireTransition('clear')
3460            num += 1
3461        self.flash(_('%d students have been cleared.' % num))
3462        self.redirect(self.url(self.context))
3463        return
3464
3465    def render(self):
3466        return
3467
3468class EditScoresPage(KofaPage):
3469    """Page that allows to edit batches of scores.
3470    """
3471    grok.context(ICourse)
3472    grok.require('waeup.editScores')
3473    grok.name('edit_scores')
3474    grok.template('editscorespage')
3475    pnav = 1
3476    doclink = DOCLINK + '/students/browser.html#batch-editing-scores-by-lecturers'
3477
3478    def label(self):
3479        return '%s tickets in academic session %s' % (
3480            self.context.code, self.session_title)
3481
3482    def _searchCatalog(self, session):
3483        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3484        # Attention: Also tickets of previous studycourses are found
3485        coursetickets = cat.searchResults(
3486            session=(session, session),
3487            code=(self.context.code, self.context.code)
3488            )
3489        return list(coursetickets)
3490
3491    def _extract_uploadfile(self, uploadfile):
3492        """Get a mapping of student-ids to scores.
3493
3494        The mapping is constructed by reading contents from `uploadfile`.
3495
3496        We expect uploadfile to be a regular CSV file with columns
3497        ``student_id`` and ``score`` (other cols are ignored).
3498        """
3499        result = dict()
3500        data = StringIO(uploadfile.read())  # ensure we have something seekable
3501        reader = csv.DictReader(data)
3502        for row in reader:
3503            if not 'student_id' in row or not 'score' in row:
3504                continue
3505            result[row['student_id']] = row['score']
3506        return result
3507
3508    def _update_scores(self, form):
3509        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3510        error = ''
3511        if 'UPDATE_FILE' in form:
3512            if form['uploadfile']:
3513                try:
3514                    formvals = self._extract_uploadfile(form['uploadfile'])
3515                except:
3516                    self.flash(
3517                        _('Uploaded file contains illegal data. Ignored'),
3518                        type="danger")
3519                    return False
3520            else:
3521                self.flash(
3522                    _('No file provided.'), type="danger")
3523                return False
3524        else:
3525            formvals = dict(zip(form['sids'], form['scores']))
3526        for ticket in self.editable_tickets:
3527            score = ticket.score
3528            sid = ticket.student.student_id
3529            if sid not in formvals:
3530                continue
3531            if formvals[sid] == '':
3532                score = None
3533            else:
3534                try:
3535                    score = int(formvals[sid])
3536                except ValueError:
3537                    error += '%s, ' % ticket.student.display_fullname
3538            if ticket.score != score:
3539                ticket.score = score
3540                ticket.student.__parent__.logger.info(
3541                    '%s - %s %s/%s score updated (%s)' % (
3542                        ob_class, ticket.student.student_id,
3543                        ticket.level, ticket.code, score)
3544                    )
3545        if error:
3546            self.flash(
3547                _('Error: Score(s) of following students have not been '
3548                    'updated (only integers are allowed): %s.' % error.strip(', ')),
3549                type="danger")
3550        return True
3551
3552    def _validate_results(self, form):
3553        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
3554        user = get_current_principal()
3555        if user is None:
3556            usertitle = 'system'
3557        else:
3558            usertitle = getattr(user, 'public_name', None)
3559            if not usertitle:
3560                usertitle = user.title
3561        self.context.results_validated_by = usertitle
3562        self.context.results_validation_date = datetime.utcnow()
3563        self.context.results_validation_session = self.current_academic_session
3564        return
3565
3566    def _results_editable(self, results_validation_session,
3567                         current_academic_session):
3568        user = get_current_principal()
3569        prm = IPrincipalRoleManager(self.context)
3570        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
3571        if 'waeup.local.LocalStudentsManager' in roles:
3572            return True
3573        if results_validation_session \
3574            and results_validation_session >= current_academic_session:
3575            return False
3576        return True
3577
3578    def update(self,  *args, **kw):
3579        form = self.request.form
3580        self.current_academic_session = grok.getSite()[
3581            'configuration'].current_academic_session
3582        if self.context.__parent__.__parent__.score_editing_disabled:
3583            self.flash(_('Score editing disabled.'), type="warning")
3584            self.redirect(self.url(self.context))
3585            return
3586        if not self.current_academic_session:
3587            self.flash(_('Current academic session not set.'), type="warning")
3588            self.redirect(self.url(self.context))
3589            return
3590        vs = self.context.results_validation_session
3591        if not self._results_editable(vs, self.current_academic_session):
3592            self.flash(
3593                _('Course results have already been '
3594                  'validated and can no longer be changed.'),
3595                type="danger")
3596            self.redirect(self.url(self.context))
3597            return
3598        self.session_title = academic_sessions_vocab.getTerm(
3599            self.current_academic_session).title
3600        self.tickets = self._searchCatalog(self.current_academic_session)
3601        if not self.tickets:
3602            self.flash(_('No student found.'), type="warning")
3603            self.redirect(self.url(self.context))
3604            return
3605        self.editable_tickets = [
3606            ticket for ticket in self.tickets if ticket.editable_by_lecturer]
3607        if not 'UPDATE_TABLE' in form and not 'UPDATE_FILE' in form\
3608            and not 'VALIDATE_RESULTS' in form:
3609            return
3610        if 'VALIDATE_RESULTS' in form:
3611            if vs and vs >= self.current_academic_session:
3612                self.flash(
3613                    _('Course results have already been validated.'),
3614                    type="danger")
3615                return
3616            self._validate_results(form)
3617            self.flash(_('You successfully validated the course results.'))
3618            self.redirect(self.url(self.context))
3619            return
3620        if not self.editable_tickets:
3621            return
3622        success = self._update_scores(form)
3623        if success:
3624            self.flash(_('You successfully updated course results.'))
3625        return
3626
3627class DownloadScoresView(UtilityView, grok.View):
3628    """View that exports scores.
3629    """
3630    grok.context(ICourse)
3631    grok.require('waeup.editScores')
3632    grok.name('download_scores')
3633
3634    def _results_editable(self, results_validation_session,
3635                         current_academic_session):
3636        user = get_current_principal()
3637        prm = IPrincipalRoleManager(self.context)
3638        roles = [x[0] for x in prm.getRolesForPrincipal(user.id)]
3639        if 'waeup.local.LocalStudentsManager' in roles:
3640            return True
3641        if results_validation_session \
3642            and results_validation_session >= current_academic_session:
3643            return False
3644        return True
3645
3646    def update(self):
3647        self.current_academic_session = grok.getSite()[
3648            'configuration'].current_academic_session
3649        if self.context.__parent__.__parent__.score_editing_disabled:
3650            self.flash(_('Score editing disabled.'), type="warning")
3651            self.redirect(self.url(self.context))
3652            return
3653        if not self.current_academic_session:
3654            self.flash(_('Current academic session not set.'), type="warning")
3655            self.redirect(self.url(self.context))
3656            return
3657        vs = self.context.results_validation_session
3658        if not self._results_editable(vs, self.current_academic_session):
3659            self.flash(
3660                _('Course results have already been '
3661                  'validated and can no longer be changed.'),
3662                type="danger")
3663            self.redirect(self.url(self.context))
3664            return
3665        site = grok.getSite()
3666        exporter = getUtility(ICSVExporter, name='lecturer')
3667        self.csv = exporter.export_filtered(site, filepath=None,
3668                                 catalog='coursetickets',
3669                                 session=self.current_academic_session,
3670                                 level=None,
3671                                 code=self.context.code)
3672        return
3673
3674    def render(self):
3675        filename = 'results_%s_%s.csv' % (
3676            self.context.code, self.current_academic_session)
3677        self.response.setHeader(
3678            'Content-Type', 'text/csv; charset=UTF-8')
3679        self.response.setHeader(
3680            'Content-Disposition:', 'attachment; filename="%s' % filename)
3681        return self.csv
3682
3683class ExportPDFScoresSlip(UtilityView, grok.View,
3684    LocalRoleAssignmentUtilityView):
3685    """Deliver a PDF slip of course tickets for a lecturer.
3686    """
3687    grok.context(ICourse)
3688    grok.name('coursetickets.pdf')
3689    grok.require('waeup.showStudents')
3690
3691    def update(self):
3692        self.current_academic_session = grok.getSite()[
3693            'configuration'].current_academic_session
3694        if not self.current_academic_session:
3695            self.flash(_('Current academic session not set.'), type="danger")
3696            self.redirect(self.url(self.context))
3697            return
3698
3699    @property
3700    def note(self):
3701        return
3702
3703    def data(self, session):
3704        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3705        # Attention: Also tickets of previous studycourses are found
3706        coursetickets = cat.searchResults(
3707            session=(session, session),
3708            code=(self.context.code, self.context.code)
3709            )
3710        header = [[_('Matric No.'),
3711                   _('Reg. No.'),
3712                   _('Fullname'),
3713                   _('Status'),
3714                   _('Course of Studies'),
3715                   _('Level'),
3716                   _('Score') ],]
3717        tickets = []
3718        for ticket in list(coursetickets):
3719            row = [ticket.student.matric_number,
3720                  ticket.student.reg_number,
3721                  ticket.student.display_fullname,
3722                  ticket.student.translated_state,
3723                  ticket.student.certcode,
3724                  ticket.level,
3725                  ticket.score]
3726            tickets.append(row)
3727        return header + sorted(tickets, key=lambda value: value[0]), None
3728
3729    def render(self):
3730        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
3731                     if i['local_role'] == 'waeup.local.Lecturer']
3732        lecturers =  ', '.join(lecturers)
3733        students_utils = getUtility(IStudentsUtils)
3734        return students_utils.renderPDFCourseticketsOverview(
3735            self, 'coursetickets', self.current_academic_session,
3736            self.data(self.current_academic_session), lecturers,
3737            'landscape', 90, self.note)
3738
3739class ExportAttendanceSlip(UtilityView, grok.View,
3740    LocalRoleAssignmentUtilityView):
3741    """Deliver a PDF slip of course tickets in attendance sheet format.
3742    """
3743    grok.context(ICourse)
3744    grok.name('attendance.pdf')
3745    grok.require('waeup.showStudents')
3746
3747    def update(self):
3748        self.current_academic_session = grok.getSite()[
3749            'configuration'].current_academic_session
3750        if not self.current_academic_session:
3751            self.flash(_('Current academic session not set.'), type="danger")
3752            self.redirect(self.url(self.context))
3753            return
3754
3755    @property
3756    def note(self):
3757        return
3758
3759    def data(self, session):
3760        cat = queryUtility(ICatalog, name='coursetickets_catalog')
3761        # Attention: Also tickets of previous studycourses are found
3762        coursetickets = cat.searchResults(
3763            session=(session, session),
3764            code=(self.context.code, self.context.code)
3765            )
3766        header = [[_('S/N'),
3767                   _('Matric No.'),
3768                   _('Name'),
3769                   _('Level'),
3770                   _('Course of\nStudies'),
3771                   _('Booklet No.'),
3772                   _('Signature'),
3773                   ],]
3774        tickets = []
3775        sn = 1
3776        ctlist = sorted(list(coursetickets),
3777                        key=lambda value: str(value.student.certcode) +
3778                                          str(value.student.matric_number))
3779        for ticket in ctlist:
3780            name = Paragraph(ticket.student.display_fullname, ENTRY1_STYLE)
3781            row = [sn,
3782                  ticket.student.matric_number,
3783                  name,
3784                  ticket.level,
3785                  ticket.student.certcode,
3786                  20 * ' ',
3787                  27 * ' ',
3788                  ]
3789            tickets.append(row)
3790            sn += 1
3791        return header + tickets, None
3792
3793    def render(self):
3794        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
3795                     if i['local_role'] == 'waeup.local.Lecturer']
3796        lecturers =  ', '.join(lecturers)
3797        students_utils = getUtility(IStudentsUtils)
3798        return students_utils.renderPDFCourseticketsOverview(
3799            self, 'attendance', self.current_academic_session,
3800            self.data(self.current_academic_session),
3801            lecturers, '', 65, self.note)
3802
3803class ExportJobContainerOverview(KofaPage):
3804    """Page that lists active student data export jobs and provides links
3805    to discard or download CSV files.
3806
3807    """
3808    grok.context(VirtualExportJobContainer)
3809    grok.require('waeup.showStudents')
3810    grok.name('index.html')
3811    grok.template('exportjobsindex')
3812    label = _('Student Data Exports')
3813    pnav = 1
3814    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
3815
3816    def update(self, CREATE1=None, CREATE2=None, DISCARD=None, job_id=None):
3817        if CREATE1:
3818            self.redirect(self.url('@@exportconfig'))
3819            return
3820        if CREATE2:
3821            self.redirect(self.url('@@exportselected'))
3822            return
3823        if DISCARD and job_id:
3824            entry = self.context.entry_from_job_id(job_id)
3825            self.context.delete_export_entry(entry)
3826            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3827            self.context.logger.info(
3828                '%s - discarded: job_id=%s' % (ob_class, job_id))
3829            self.flash(_('Discarded export') + ' %s' % job_id)
3830        self.entries = doll_up(self, user=self.request.principal.id)
3831        return
3832
3833class ExportJobContainerJobConfig(KofaPage):
3834    """Page that configures a students export job.
3835
3836    This is a baseclass.
3837    """
3838    grok.baseclass()
3839    grok.require('waeup.showStudents')
3840    grok.template('exportconfig')
3841    label = _('Configure student data export')
3842    pnav = 1
3843    redirect_target = ''
3844    doclink = DOCLINK + '/datacenter/export.html#student-data-exporters'
3845
3846    def _set_session_values(self):
3847        vocab_terms = academic_sessions_vocab.by_value.values()
3848        self.sessions = [(_('All Sessions'), 'all')]
3849        self.sessions += sorted(
3850            [(x.title, x.token) for x in vocab_terms], reverse=True)
3851        return
3852
3853    def _set_level_values(self):
3854        vocab_terms = course_levels.by_value.values()
3855        self.levels = [(_('All Levels'), 'all')]
3856        self.levels += sorted(
3857            [(x.title, x.token) for x in vocab_terms])
3858        return
3859
3860    def _set_semesters_values(self):
3861        utils = getUtility(IKofaUtils)
3862        self.semesters =[(_('All Semesters'), 'all')]
3863        self.semesters += sorted([(value, key) for key, value in
3864                      utils.SEMESTER_DICT.items()])
3865        return
3866
3867    def _set_mode_values(self):
3868        utils = getUtility(IKofaUtils)
3869        self.modes =[(_('All Modes'), 'all')]
3870        self.modes += sorted([(value, key) for key, value in
3871                      utils.STUDY_MODES_DICT.items()])
3872        return
3873
3874    def _set_paycat_values(self):
3875        utils = getUtility(IKofaUtils)
3876        self.paycats =[(_('All Payment Categories'), 'all')]
3877        self.paycats += sorted([(value, key) for key, value in
3878                      utils.PAYMENT_CATEGORIES.items()])
3879        return
3880
3881    def _set_exporter_values(self):
3882        # We provide all student exporters, nothing else, yet.
3883        # Bursary, Department or Accommodation Officers don't
3884        # have the general exportData
3885        # permission and are only allowed to export bursary, payments
3886        # overview or accommodation data respectively.
3887        # This is the only place where waeup.exportAccommodationData,
3888        # waeup.exportBursaryData and waeup.exportPaymentsOverview
3889        # are used.
3890        exporters = []
3891        if not checkPermission('waeup.exportData', self.context):
3892            if checkPermission('waeup.exportBursaryData', self.context):
3893                exporters += [('Bursary Data', 'bursary')]
3894            if checkPermission('waeup.exportPaymentsOverview', self.context):
3895                exporters += [('School Fee Payments Overview',
3896                               'sfpaymentsoverview'),
3897                              ('Session Payments Overview',
3898                               'sessionpaymentsoverview')]
3899            if checkPermission('waeup.exportAccommodationData', self.context):
3900                exporters += [('Bed Tickets', 'bedtickets'),
3901                              ('Accommodation Payments',
3902                               'accommodationpayments')]
3903            self.exporters = exporters
3904            return
3905        STUDENT_EXPORTER_NAMES = getUtility(
3906            IStudentsUtils).STUDENT_EXPORTER_NAMES
3907        for name in STUDENT_EXPORTER_NAMES:
3908            util = getUtility(ICSVExporter, name=name)
3909            exporters.append((util.title, name),)
3910        self.exporters = exporters
3911        return
3912
3913    @property
3914    def faccode(self):
3915        return None
3916
3917    @property
3918    def depcode(self):
3919        return None
3920
3921    @property
3922    def certcode(self):
3923        return None
3924
3925    def update(self, START=None, session=None, level=None, mode=None,
3926               payments_start=None, payments_end=None, ct_level=None,
3927               ct_session=None, ct_semester=None, paycat=None,
3928               paysession=None, exporter=None):
3929        self._set_session_values()
3930        self._set_level_values()
3931        self._set_mode_values()
3932        self._set_paycat_values()
3933        self._set_exporter_values()
3934        self._set_semesters_values()
3935        if START is None:
3936            return
3937        ena = exports_not_allowed(self)
3938        if ena:
3939            self.flash(ena, type='danger')
3940            return
3941        if payments_start or payments_end:
3942            date_format = '%d/%m/%Y'
3943            try:
3944                datetime.strptime(payments_start, date_format)
3945                datetime.strptime(payments_end, date_format)
3946            except ValueError:
3947                self.flash(_('Payment dates do not match format d/m/Y.'),
3948                           type="danger")
3949                return
3950        if session == 'all':
3951            session=None
3952        if level == 'all':
3953            level = None
3954        if mode == 'all':
3955            mode = None
3956        if (mode,
3957            level,
3958            session,
3959            self.faccode,
3960            self.depcode,
3961            self.certcode) == (None, None, None, None, None, None):
3962            # Export all students including those without certificate
3963            job_id = self.context.start_export_job(exporter,
3964                                          self.request.principal.id,
3965                                          payments_start = payments_start,
3966                                          payments_end = payments_end,
3967                                          paycat=paycat,
3968                                          paysession=paysession,
3969                                          ct_level = ct_level,
3970                                          ct_session = ct_session,
3971                                          ct_semester = ct_semester,
3972                                          )
3973        else:
3974            job_id = self.context.start_export_job(exporter,
3975                                          self.request.principal.id,
3976                                          current_session=session,
3977                                          current_level=level,
3978                                          current_mode=mode,
3979                                          faccode=self.faccode,
3980                                          depcode=self.depcode,
3981                                          certcode=self.certcode,
3982                                          payments_start = payments_start,
3983                                          payments_end = payments_end,
3984                                          paycat=paycat,
3985                                          paysession=paysession,
3986                                          ct_level = ct_level,
3987                                          ct_session = ct_session,
3988                                          ct_semester = ct_semester,)
3989        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
3990        self.context.logger.info(
3991            '%s - exported: %s (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s), job_id=%s'
3992            % (ob_class, exporter, session, level, mode, self.faccode,
3993            self.depcode, self.certcode, payments_start, payments_end,
3994            ct_level, ct_session, paycat, paysession, job_id))
3995        self.flash(_('Export started for students with') +
3996                   ' current_session=%s, current_level=%s, study_mode=%s' % (
3997                   session, level, mode))
3998        self.redirect(self.url(self.redirect_target))
3999        return
4000
4001class ExportJobContainerDownload(ExportCSVView):
4002    """Page that downloads a students export csv file.
4003
4004    """
4005    grok.context(VirtualExportJobContainer)
4006    grok.require('waeup.showStudents')
4007
4008class DatacenterExportJobContainerJobConfig(ExportJobContainerJobConfig):
4009    """Page that configures a students export job in datacenter.
4010
4011    """
4012    grok.name('exportconfig')
4013    grok.context(IDataCenter)
4014    redirect_target = '@@export'
4015
4016class DatacenterExportJobContainerSelectStudents(ExportJobContainerJobConfig):
4017    """Page that configures a students export job in datacenter.
4018
4019    """
4020    grok.name('exportselected')
4021    grok.context(IDataCenter)
4022    redirect_target = '@@export'
4023    grok.template('exportselected')
4024
4025    def update(self, START=None, students=None, exporter=None):
4026        self._set_exporter_values()
4027        if START is None:
4028            return
4029        ena = exports_not_allowed(self)
4030        if ena:
4031            self.flash(ena, type='danger')
4032            return
4033        try:
4034            ids = students.replace(',', ' ').split()
4035        except:
4036            self.flash(sys.exc_info()[1])
4037            self.redirect(self.url(self.redirect_target))
4038            return
4039        job_id = self.context.start_export_job(
4040            exporter, self.request.principal.id, selected=ids)
4041        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4042        self.context.logger.info(
4043            '%s - selected students exported: %s, job_id=%s' %
4044            (ob_class, exporter, job_id))
4045        self.flash(_('Export of selected students started.'))
4046        self.redirect(self.url(self.redirect_target))
4047        return
4048
4049class FacultiesExportJobContainerJobConfig(
4050    DatacenterExportJobContainerJobConfig):
4051    """Page that configures a students export job in facultiescontainer.
4052
4053    """
4054    grok.context(VirtualFacultiesExportJobContainer)
4055    redirect_target = ''
4056
4057class FacultiesExportJobContainerSelectStudents(
4058    DatacenterExportJobContainerSelectStudents):
4059    """Page that configures a students export job in facultiescontainer.
4060
4061    """
4062    grok.context(VirtualFacultiesExportJobContainer)
4063    redirect_target = ''
4064
4065class FacultyExportJobContainerJobConfig(DatacenterExportJobContainerJobConfig):
4066    """Page that configures a students export job in faculties.
4067
4068    """
4069    grok.context(VirtualFacultyExportJobContainer)
4070    redirect_target = ''
4071
4072    @property
4073    def faccode(self):
4074        return self.context.__parent__.code
4075
4076class DepartmentExportJobContainerJobConfig(
4077    DatacenterExportJobContainerJobConfig):
4078    """Page that configures a students export job in departments.
4079
4080    """
4081    grok.context(VirtualDepartmentExportJobContainer)
4082    redirect_target = ''
4083
4084    @property
4085    def depcode(self):
4086        return self.context.__parent__.code
4087
4088class CertificateExportJobContainerJobConfig(
4089    DatacenterExportJobContainerJobConfig):
4090    """Page that configures a students export job for certificates.
4091
4092    """
4093    grok.context(VirtualCertificateExportJobContainer)
4094    grok.template('exportconfig_certificate')
4095    redirect_target = ''
4096
4097    @property
4098    def certcode(self):
4099        return self.context.__parent__.code
4100
4101class CourseExportJobContainerJobConfig(
4102    DatacenterExportJobContainerJobConfig):
4103    """Page that configures a students export job for courses.
4104
4105    In contrast to department or certificate student data exports the
4106    coursetickets_catalog is searched here. Therefore the update
4107    method from the base class is customized.
4108    """
4109    grok.context(VirtualCourseExportJobContainer)
4110    grok.template('exportconfig_course')
4111    redirect_target = ''
4112
4113    def _set_exporter_values(self):
4114        # We provide only the 'coursetickets' and 'lecturer' exporter
4115        # but can add more.
4116        exporters = []
4117        for name in ('coursetickets', 'lecturer'):
4118            util = getUtility(ICSVExporter, name=name)
4119            exporters.append((util.title, name),)
4120        self.exporters = exporters
4121        return
4122
4123    def _set_session_values(self):
4124        # We allow only current academic session
4125        academic_session = grok.getSite()['configuration'].current_academic_session
4126        if not academic_session:
4127            self.sessions = []
4128            return
4129        x = academic_sessions_vocab.getTerm(academic_session)
4130        self.sessions = [(x.title, x.token)]
4131        return
4132
4133    def update(self, START=None, session=None, level=None, mode=None,
4134               exporter=None):
4135        if not checkPermission('waeup.exportData', self.context):
4136            self.flash(_('Not permitted.'), type='danger')
4137            self.redirect(self.url(self.context))
4138            return
4139        self._set_session_values()
4140        self._set_level_values()
4141        self._set_mode_values()
4142        self._set_exporter_values()
4143        if not self.sessions:
4144            self.flash(
4145                _('Academic session not set. '
4146                  'Please contact the administrator.'),
4147                type='danger')
4148            self.redirect(self.url(self.context))
4149            return
4150        if START is None:
4151            return
4152        ena = exports_not_allowed(self)
4153        if ena:
4154            self.flash(ena, type='danger')
4155            return
4156        if session == 'all':
4157            session = None
4158        if level == 'all':
4159            level = None
4160        job_id = self.context.start_export_job(exporter,
4161                                      self.request.principal.id,
4162                                      # Use a different catalog and
4163                                      # pass different keywords than
4164                                      # for the (default) students_catalog
4165                                      catalog='coursetickets',
4166                                      session=session,
4167                                      level=level,
4168                                      code=self.context.__parent__.code)
4169        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
4170        self.context.logger.info(
4171            '%s - exported: %s (%s, %s, %s), job_id=%s'
4172            % (ob_class, exporter, session, level,
4173            self.context.__parent__.code, job_id))
4174        self.flash(_('Export started for course tickets with') +
4175                   ' level_session=%s, level=%s' % (
4176                   session, level))
4177        self.redirect(self.url(self.redirect_target))
4178        return
Note: See TracBrowser for help on using the repository browser.