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

Last change on this file since 16303 was 16302, checked in by Henrik Bettermann, 4 years ago

Set maximum number of bulk emails.

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