source: main/waeup.kofa/trunk/src/waeup/kofa/applicants/browser.py @ 16549

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

Enable applicants to upload also additional jpg files.

  • Property svn:keywords set to Id
File size: 79.0 KB
RevLine 
[5273]1## $Id: browser.py 16545 2021-07-13 14:08:06Z henrik $
[6078]2##
[7192]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
[5273]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.
[6078]8##
[5273]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.
[6078]13##
[5273]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##
[5824]18"""UI components for basic applicants and related components.
[5273]19"""
[7063]20import os
[6082]21import sys
[5273]22import grok
[13950]23import transaction
[15584]24from cgi import escape
[14014]25from urllib import urlencode
[7370]26from datetime import datetime, date
[14934]27from time import time, sleep
[16116]28import xmlrpclib
[8042]29from zope.event import notify
[13152]30from zope.component import getUtility, queryUtility, createObject, getAdapter
[8033]31from zope.catalog.interfaces import ICatalog
[7714]32from zope.i18n import translate
[14949]33from zope.security import checkPermission
[7322]34from hurry.workflow.interfaces import (
35    IWorkflowInfo, IWorkflowState, InvalidTransitionError)
[14256]36from reportlab.platypus.doctemplate import LayoutError
[14014]37from waeup.kofa.mandates.mandate import RefereeReportMandate
[7811]38from waeup.kofa.applicants.interfaces import (
[7363]39    IApplicant, IApplicantEdit, IApplicantsRoot,
[7683]40    IApplicantsContainer, IApplicantsContainerAdd,
[15833]41    IApplicantOnlinePayment, IApplicantsUtils,
[13976]42    IApplicantRegisterUpdate, ISpecialApplicant,
43    IApplicantRefereeReport
[7363]44    )
[16545]45from waeup.kofa.utils.helpers import (html2dict,
46    string_from_bytes, file_size, get_fileformat)
[10655]47from waeup.kofa.applicants.container import (
48    ApplicantsContainer, VirtualApplicantsExportJobContainer)
[8404]49from waeup.kofa.applicants.applicant import search
[8636]50from waeup.kofa.applicants.workflow import (
[13254]51    INITIALIZED, STARTED, PAID, SUBMITTED, ADMITTED, NOT_ADMITTED, CREATED)
[7811]52from waeup.kofa.browser import (
[9217]53#    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
[7363]54    DEFAULT_PASSPORT_IMAGE_PATH)
[9217]55from waeup.kofa.browser.layout import (
56    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage)
[7811]57from waeup.kofa.browser.interfaces import ICaptchaManager
58from waeup.kofa.browser.breadcrumbs import Breadcrumb
59from waeup.kofa.browser.layout import (
[11437]60    NullValidator, jsaction, action, UtilityView)
[10655]61from waeup.kofa.browser.pages import (
62    add_local_role, del_local_roles, doll_up, ExportCSVView)
[7811]63from waeup.kofa.interfaces import (
[13177]64    IKofaObject, ILocalRolesAssignable, IExtFileStore, IPDF, DOCLINK,
[7819]65    IFileStoreNameChooser, IPasswordValidator, IUserAccount, IKofaUtils)
[7811]66from waeup.kofa.interfaces import MessageFactory as _
67from waeup.kofa.permissions import get_users_with_local_roles
68from waeup.kofa.students.interfaces import IStudentsUtils
[16231]69from waeup.kofa.students.browser import ContactStudentFormPage
[8186]70from waeup.kofa.utils.helpers import string_from_bytes, file_size, now
[8170]71from waeup.kofa.widgets.datewidget import (
[10831]72    FriendlyDateDisplayWidget,
[8170]73    FriendlyDatetimeDisplayWidget)
[5320]74
[7819]75grok.context(IKofaObject) # Make IKofaObject the default context
[5273]76
[14025]77WARNING = _('You can not edit your application records after final submission.'
78            ' You really want to submit?')
79
[8388]80class ApplicantsRootPage(KofaDisplayFormPage):
[5822]81    grok.context(IApplicantsRoot)
82    grok.name('index')
[6153]83    grok.require('waeup.Public')
[8388]84    form_fields = grok.AutoFields(IApplicantsRoot)
[13076]85    label = _('Applicants Section')
[5843]86    pnav = 3
[6012]87
88    def update(self):
[6067]89        super(ApplicantsRootPage, self).update()
[6012]90        return
91
[8388]92    @property
93    def introduction(self):
94        # Here we know that the cookie has been set
95        lang = self.request.cookies.get('kofa.language')
96        html = self.context.description_dict.get(lang,'')
97        if html == '':
98            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
99            html = self.context.description_dict.get(portal_language,'')
100        return html
101
[10097]102    @property
103    def containers(self):
[10098]104        if self.layout.isAuthenticated():
[13249]105            return self.context.values()
[13217]106        values = sorted([container for container in self.context.values()
[13249]107                         if not container.hidden and container.enddate],
[13222]108                        key=lambda value: value.enddate, reverse=True)
[13217]109        return values
[10097]110
[8404]111class ApplicantsSearchPage(KofaPage):
112    grok.context(IApplicantsRoot)
113    grok.name('search')
114    grok.require('waeup.viewApplication')
[10644]115    label = _('Find applicants')
[10645]116    search_button = _('Find applicant')
[8404]117    pnav = 3
118
119    def update(self, *args, **kw):
120        form = self.request.form
121        self.results = []
122        if 'searchterm' in form and form['searchterm']:
123            self.searchterm = form['searchterm']
124            self.searchtype = form['searchtype']
125        elif 'old_searchterm' in form:
126            self.searchterm = form['old_searchterm']
127            self.searchtype = form['old_searchtype']
128        else:
129            if 'search' in form:
[11254]130                self.flash(_('Empty search string'), type='warning')
[8404]131            return
132        self.results = search(query=self.searchterm,
133            searchtype=self.searchtype, view=self)
134        if not self.results:
[11254]135            self.flash(_('No applicant found.'), type='warning')
[8404]136        return
137
[7819]138class ApplicantsRootManageFormPage(KofaEditFormPage):
[5828]139    grok.context(IApplicantsRoot)
140    grok.name('manage')
[6107]141    grok.template('applicantsrootmanagepage')
[8388]142    form_fields = grok.AutoFields(IApplicantsRoot)
[13076]143    label = _('Manage applicants section')
[5843]144    pnav = 3
[7136]145    grok.require('waeup.manageApplication')
[8388]146    taboneactions = [_('Save')]
147    tabtwoactions = [_('Add applicants container'), _('Remove selected')]
148    tabthreeactions1 = [_('Remove selected local roles')]
149    tabthreeactions2 = [_('Add local role')]
[7710]150    subunits = _('Applicants Containers')
[13177]151    doclink = DOCLINK + '/applicants.html'
[6078]152
[6184]153    def getLocalRoles(self):
154        roles = ILocalRolesAssignable(self.context)
155        return roles()
156
157    def getUsers(self):
[15964]158        return getUtility(IKofaUtils).getUsers()
[6184]159
[15964]160    #def getUsers(self):
161    #    """Get a list of all users.
162    #    """
163    #    for key, val in grok.getSite()['users'].items():
164    #        url = self.url(val)
165    #        yield(dict(url=url, name=key, val=val))
166
[6184]167    def getUsersWithLocalRoles(self):
168        return get_users_with_local_roles(self.context)
169
[7710]170    @jsaction(_('Remove selected'))
[6069]171    def delApplicantsContainers(self, **data):
172        form = self.request.form
[9701]173        if 'val_id' in form:
[8388]174            child_id = form['val_id']
175        else:
[11254]176            self.flash(_('No container selected!'), type='warning')
177            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[8388]178            return
[6069]179        if not isinstance(child_id, list):
180            child_id = [child_id]
181        deleted = []
182        for id in child_id:
183            try:
184                del self.context[id]
185                deleted.append(id)
186            except:
[7710]187                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]188                    id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[6069]189        if len(deleted):
[7738]190            self.flash(_('Successfully removed: ${a}',
191                mapping = {'a':', '.join(deleted)}))
[12892]192        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
193        self.context.logger.info(
194            '%s - removed: %s' % (ob_class, ', '.join(deleted)))
[11254]195        self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6078]196        return
[5828]197
[7710]198    @action(_('Add applicants container'), validator=NullValidator)
[6069]199    def addApplicantsContainer(self, **data):
200        self.redirect(self.url(self.context, '@@add'))
[6078]201        return
202
[7710]203    @action(_('Add local role'), validator=NullValidator)
[6184]204    def addLocalRole(self, **data):
[7484]205        return add_local_role(self,3, **data)
[6184]206
[7710]207    @action(_('Remove selected local roles'))
[6184]208    def delLocalRoles(self, **data):
[7484]209        return del_local_roles(self,3,**data)
[6184]210
[8388]211    @action(_('Save'), style='primary')
212    def save(self, **data):
213        self.applyData(self.context, **data)
[12247]214        description = getattr(self.context, 'description', None)
215        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
216        self.context.description_dict = html2dict(description, portal_language)
[8390]217        self.flash(_('Form has been saved.'))
[8388]218        return
219
[7819]220class ApplicantsContainerAddFormPage(KofaAddFormPage):
[5822]221    grok.context(IApplicantsRoot)
[7136]222    grok.require('waeup.manageApplication')
[5822]223    grok.name('add')
[6107]224    grok.template('applicantscontaineraddpage')
[7710]225    label = _('Add applicants container')
[5843]226    pnav = 3
[6078]227
[6103]228    form_fields = grok.AutoFields(
[7903]229        IApplicantsContainerAdd).omit('code').omit('title')
[6078]230
[7710]231    @action(_('Add applicants container'))
[6069]232    def addApplicantsContainer(self, **data):
[6103]233        year = data['year']
[16190]234        if not data['container_number'] and not data['year']:
235            self.flash(
236              _('You must select either Year of Entrance or Container Number.'),
237                type='warning')
238            return
[15548]239        if not data['container_number']:
240            code = u'%s%s' % (data['prefix'], year)
241        else:
242            code = u'%s%s' % (data['prefix'], data['container_number'])
[9529]243        apptypes_dict = getUtility(IApplicantsUtils).APP_TYPES_DICT
[16190]244        title = u'%s' % apptypes_dict[data['prefix']][0]
245        if year:
246            title = u'%s %s/%s' % (title, year, year + 1)
[6087]247        if code in self.context.keys():
[6105]248            self.flash(
[11254]249              _('An applicants container for the same application '
[16190]250                'type and entrance year or container number '
251                'already exists in the database.'),
[11254]252                type='warning')
[5822]253            return
254        # Add new applicants container...
[8009]255        container = createObject(u'waeup.ApplicantsContainer')
[6069]256        self.applyData(container, **data)
[6087]257        container.code = code
258        container.title = title
259        self.context[code] = container
[7710]260        self.flash(_('Added:') + ' "%s".' % code)
[12892]261        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
262        self.context.logger.info('%s - added: %s' % (ob_class, code))
[7484]263        self.redirect(self.url(self.context, u'@@manage'))
[5822]264        return
[6078]265
[7710]266    @action(_('Cancel'), validator=NullValidator)
[6069]267    def cancel(self, **data):
[7484]268        self.redirect(self.url(self.context, '@@manage'))
[6078]269
[5845]270class ApplicantsRootBreadcrumb(Breadcrumb):
271    """A breadcrumb for applicantsroot.
272    """
273    grok.context(IApplicantsRoot)
[7710]274    title = _(u'Applicants')
[6078]275
[5845]276class ApplicantsContainerBreadcrumb(Breadcrumb):
277    """A breadcrumb for applicantscontainers.
278    """
279    grok.context(IApplicantsContainer)
[6319]280
[10655]281
282class ApplicantsExportsBreadcrumb(Breadcrumb):
283    """A breadcrumb for exports.
284    """
285    grok.context(VirtualApplicantsExportJobContainer)
286    title = _(u'Applicant Data Exports')
287    target = None
288
[6153]289class ApplicantBreadcrumb(Breadcrumb):
290    """A breadcrumb for applicants.
291    """
292    grok.context(IApplicant)
[6319]293
[6153]294    @property
295    def title(self):
296        """Get a title for a context.
297        """
[7240]298        return self.context.application_number
[5828]299
[7250]300class OnlinePaymentBreadcrumb(Breadcrumb):
301    """A breadcrumb for payments.
302    """
303    grok.context(IApplicantOnlinePayment)
304
305    @property
306    def title(self):
307        return self.context.p_id
308
[13976]309class RefereeReportBreadcrumb(Breadcrumb):
310    """A breadcrumb for referee reports.
311    """
312    grok.context(IApplicantRefereeReport)
313
314    @property
315    def title(self):
316        return self.context.r_id
317
[8563]318class ApplicantsStatisticsPage(KofaDisplayFormPage):
319    """Some statistics about applicants in a container.
320    """
321    grok.context(IApplicantsContainer)
322    grok.name('statistics')
[8565]323    grok.require('waeup.viewApplicationStatistics')
[8563]324    grok.template('applicantcontainerstatistics')
325
326    @property
327    def label(self):
328        return "%s" % self.context.title
329
[7819]330class ApplicantsContainerPage(KofaDisplayFormPage):
[5830]331    """The standard view for regular applicant containers.
332    """
333    grok.context(IApplicantsContainer)
334    grok.name('index')
[6153]335    grok.require('waeup.Public')
[6029]336    grok.template('applicantscontainerpage')
[5850]337    pnav = 3
[6053]338
[9078]339    @property
340    def form_fields(self):
[12247]341        form_fields = grok.AutoFields(IApplicantsContainer).omit(
342            'title', 'description')
[9078]343        form_fields[
344            'startdate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
345        form_fields[
346            'enddate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
347        if self.request.principal.id == 'zope.anybody':
348            form_fields = form_fields.omit(
[10101]349                'code', 'prefix', 'year', 'mode', 'hidden',
[11870]350                'strict_deadline', 'application_category',
[15819]351                'application_slip_notice', 'with_picture')
[9078]352        return form_fields
[6053]353
[5837]354    @property
[7708]355    def introduction(self):
[7833]356        # Here we know that the cookie has been set
357        lang = self.request.cookies.get('kofa.language')
[7708]358        html = self.context.description_dict.get(lang,'')
[8388]359        if html == '':
[7833]360            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7708]361            html = self.context.description_dict.get(portal_language,'')
[8388]362        return html
[7708]363
364    @property
[7467]365    def label(self):
[7493]366        return "%s" % self.context.title
[5837]367
[7819]368class ApplicantsContainerManageFormPage(KofaEditFormPage):
[5837]369    grok.context(IApplicantsContainer)
[5850]370    grok.name('manage')
[6107]371    grok.template('applicantscontainermanagepage')
[10625]372    form_fields = grok.AutoFields(IApplicantsContainer)
[7710]373    taboneactions = [_('Save'),_('Cancel')]
[8684]374    tabtwoactions = [_('Remove selected'),_('Cancel'),
[8314]375        _('Create students from selected')]
[7710]376    tabthreeactions1 = [_('Remove selected local roles')]
377    tabthreeactions2 = [_('Add local role')]
[5844]378    # Use friendlier date widget...
[7136]379    grok.require('waeup.manageApplication')
[13177]380    doclink = DOCLINK + '/applicants.html'
[16327]381    max_applicants = 2000
[5850]382
383    @property
384    def label(self):
[7710]385        return _('Manage applicants container')
[5850]386
[5845]387    pnav = 3
[5837]388
[8547]389    @property
390    def showApplicants(self):
[16327]391        if self.context.counts[1] < self.max_applicants:
[8547]392            return True
393        return False
394
[6184]395    def getLocalRoles(self):
396        roles = ILocalRolesAssignable(self.context)
397        return roles()
398
[15964]399    #def getUsers(self):
400    #    """Get a list of all users.
401    #    """
402    #    for key, val in grok.getSite()['users'].items():
403    #        url = self.url(val)
404    #        yield(dict(url=url, name=key, val=val))
405
[6184]406    def getUsers(self):
[15964]407        return getUtility(IKofaUtils).getUsers()
[6184]408
409    def getUsersWithLocalRoles(self):
410        return get_users_with_local_roles(self.context)
411
[7714]412    @action(_('Save'), style='primary')
[7489]413    def save(self, **data):
[9531]414        changed_fields = self.applyData(self.context, **data)
415        if changed_fields:
416            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
417        else:
418            changed_fields = []
[12247]419        description = getattr(self.context, 'description', None)
420        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
421        self.context.description_dict = html2dict(description, portal_language)
[7710]422        self.flash(_('Form has been saved.'))
[9531]423        fields_string = ' + '.join(changed_fields)
[12892]424        self.context.writeLogMessage(self, 'saved: %s' % fields_string)
[5837]425        return
[6078]426
[7710]427    @jsaction(_('Remove selected'))
[6105]428    def delApplicant(self, **data):
[6189]429        form = self.request.form
[9701]430        if 'val_id' in form:
[6189]431            child_id = form['val_id']
432        else:
[11254]433            self.flash(_('No applicant selected!'), type='warning')
434            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6189]435            return
436        if not isinstance(child_id, list):
437            child_id = [child_id]
438        deleted = []
439        for id in child_id:
440            try:
441                del self.context[id]
442                deleted.append(id)
443            except:
[7710]444                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]445                    id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[6189]446        if len(deleted):
[7741]447            self.flash(_('Successfully removed: ${a}',
[7738]448                mapping = {'a':', '.join(deleted)}))
[11254]449        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6189]450        return
[6105]451
[8314]452    @action(_('Create students from selected'))
453    def createStudents(self, **data):
[14949]454        if not checkPermission('waeup.createStudents', self.context):
455            self.flash(
456                _('You don\'t have permission to create student records.'),
457                type='warning')
458            self.redirect(self.url(self.context, '@@manage')+'#tab2')
459            return
[8314]460        form = self.request.form
[9701]461        if 'val_id' in form:
[8314]462            child_id = form['val_id']
463        else:
[11254]464            self.flash(_('No applicant selected!'), type='warning')
465            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[8314]466            return
467        if not isinstance(child_id, list):
468            child_id = [child_id]
469        created = []
[14682]470        if len(child_id) > 10 and self.request.principal.id != 'admin':
471            self.flash(_('A maximum of 10 applicants can be selected!'),
472                       type='warning')
473            self.redirect(self.url(self.context, '@@manage')+'#tab2')
474            return
[8314]475        for id in child_id:
476            success, msg = self.context[id].createStudent(view=self)
477            if success:
478                created.append(id)
479        if len(created):
480            self.flash(_('${a} students successfully created.',
481                mapping = {'a': len(created)}))
482        else:
[11254]483            self.flash(_('No student could be created.'), type='warning')
484        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[8314]485        return
486
[7710]487    @action(_('Cancel'), validator=NullValidator)
[5837]488    def cancel(self, **data):
489        self.redirect(self.url(self.context))
490        return
[5886]491
[7710]492    @action(_('Add local role'), validator=NullValidator)
[6184]493    def addLocalRole(self, **data):
494        return add_local_role(self,3, **data)
[6105]495
[7710]496    @action(_('Remove selected local roles'))
[6184]497    def delLocalRoles(self, **data):
498        return del_local_roles(self,3,**data)
499
[7819]500class ApplicantAddFormPage(KofaAddFormPage):
[6622]501    """Add-form to add an applicant.
[6327]502    """
503    grok.context(IApplicantsContainer)
[7136]504    grok.require('waeup.manageApplication')
[6327]505    grok.name('addapplicant')
[7240]506    #grok.template('applicantaddpage')
507    form_fields = grok.AutoFields(IApplicant).select(
[7356]508        'firstname', 'middlename', 'lastname',
[7240]509        'email', 'phone')
[7714]510    label = _('Add applicant')
[6327]511    pnav = 3
[13177]512    doclink = DOCLINK + '/applicants.html'
[6327]513
[7714]514    @action(_('Create application record'))
[6327]515    def addApplicant(self, **data):
[8008]516        applicant = createObject(u'waeup.Applicant')
[7240]517        self.applyData(applicant, **data)
518        self.context.addApplicant(applicant)
[13073]519        self.flash(_('Application record created.'))
[7363]520        self.redirect(
521            self.url(self.context[applicant.application_number], 'index'))
[6327]522        return
523
[13217]524class ApplicantsContainerPrefillFormPage(KofaAddFormPage):
[13218]525    """Form to pre-fill applicants containers.
[13217]526    """
527    grok.context(IApplicantsContainer)
528    grok.require('waeup.manageApplication')
529    grok.name('prefill')
[13218]530    grok.template('prefillcontainer')
[13217]531    label = _('Pre-fill container')
532    pnav = 3
[13232]533    doclink = DOCLINK + '/applicants/browser.html#preparation-and-maintenance-of-applicants-containers'
[13217]534
535    def update(self):
536        if self.context.mode == 'update':
537            self.flash(_('Container must be in create mode to be pre-filled.'),
538                type='danger')
539            self.redirect(self.url(self.context))
540            return
541        super(ApplicantsContainerPrefillFormPage, self).update()
542        return
543
544    @action(_('Pre-fill now'), style='primary')
[13218]545    def addApplicants(self):
[13217]546        form = self.request.form
547        if 'number' in form and form['number']:
548            number = int(form['number'])
549        for i in range(number):
550            applicant = createObject(u'waeup.Applicant')
551            self.context.addApplicant(applicant)
552        self.flash(_('%s application records created.' % number))
553        self.context.writeLogMessage(self, '%s applicants created' % (number))
554        self.redirect(self.url(self.context, 'index'))
555        return
556
557    @action(_('Cancel'), validator=NullValidator)
558    def cancel(self, **data):
559        self.redirect(self.url(self.context))
560        return
561
[13218]562class ApplicantsContainerPurgeFormPage(KofaEditFormPage):
[14109]563    """Form to purge applicants containers.
[13218]564    """
565    grok.context(IApplicantsContainer)
566    grok.require('waeup.manageApplication')
567    grok.name('purge')
568    grok.template('purgecontainer')
569    label = _('Purge container')
570    pnav = 3
[13232]571    doclink = DOCLINK + '/applicants/browser.html#preparation-and-maintenance-of-applicants-containers'
[13218]572
[13232]573    @action(_('Remove initialized records'),
574              tooltip=_('Don\'t use if application is in progress!'),
575              warning=_('Are you really sure?'),
576              style='primary')
[13218]577    def purgeInitialized(self):
578        form = self.request.form
579        purged = 0
580        keys = [key for key in self.context.keys()]
581        for key in keys:
582            if self.context[key].state == 'initialized':
583                del self.context[key]
584                purged += 1
585        self.flash(_('%s application records purged.' % purged))
586        self.context.writeLogMessage(self, '%s applicants purged' % (purged))
587        self.redirect(self.url(self.context, 'index'))
588        return
589
590    @action(_('Cancel'), validator=NullValidator)
591    def cancel(self, **data):
592        self.redirect(self.url(self.context))
593        return
594
[7819]595class ApplicantDisplayFormPage(KofaDisplayFormPage):
[8014]596    """A display view for applicant data.
597    """
[5273]598    grok.context(IApplicant)
599    grok.name('index')
[7113]600    grok.require('waeup.viewApplication')
[7200]601    grok.template('applicantdisplaypage')
[7714]602    label = _('Applicant')
[5843]603    pnav = 3
[8922]604    hide_hint = False
[5273]605
[8046]606    @property
[16059]607    def display_refereereports(self):
608        if self.context.refereereports:
609            return True
610        return False
611
612    @property
[15943]613    def file_links(self):
614        html = ''
615        file_store = getUtility(IExtFileStore)
616        additional_files = getUtility(IApplicantsUtils).ADDITIONAL_FILES
617        for filename in additional_files:
618            pdf = getUtility(IExtFileStore).getFileByContext(
619                self.context, attr=filename[1])
620            if pdf:
621                html += '<a href="%s">%s</a>, ' % (self.url(
622                    self.context, filename[1]), filename[0])
623        html = html.strip(', ')
624        return html
625
626    @property
[13886]627    def display_payments(self):
[15122]628        if self.context.payments:
629            return True
[13886]630        if self.context.special:
631            return True
632        return getattr(self.context.__parent__, 'application_fee', None)
633
634    @property
[10831]635    def form_fields(self):
636        if self.context.special:
[11599]637            form_fields = grok.AutoFields(ISpecialApplicant).omit('locked')
[10831]638        else:
639            form_fields = grok.AutoFields(IApplicant).omit(
[10845]640                'locked', 'course_admitted', 'password', 'suspended')
[10831]641        return form_fields
642
643    @property
[10534]644    def target(self):
645        return getattr(self.context.__parent__, 'prefix', None)
646
647    @property
[8046]648    def separators(self):
649        return getUtility(IApplicantsUtils).SEPARATORS_DICT
650
[7063]651    def update(self):
652        self.passport_url = self.url(self.context, 'passport.jpg')
[7240]653        # Mark application as started if applicant logs in for the first time
[7272]654        usertype = getattr(self.request.principal, 'user_type', None)
655        if usertype == 'applicant' and \
656            IWorkflowState(self.context).getState() == INITIALIZED:
[7240]657            IWorkflowInfo(self.context).fireTransition('start')
[10895]658        if usertype == 'applicant' and self.context.state == 'created':
[10908]659            session = '%s/%s' % (self.context.__parent__.year,
660                                 self.context.__parent__.year+1)
661            title = getattr(grok.getSite()['configuration'], 'name', u'Sample University')
[10895]662            msg = _(
663                '\n <strong>Congratulations!</strong>' +
[10933]664                ' You have been offered provisional admission into the' +
[10908]665                ' ${c} Academic Session of ${d}.'
666                ' Your student record has been created for you.' +
667                ' Please, logout again and proceed to the' +
668                ' login page of the portal.'
[10895]669                ' Then enter your new student credentials:' +
670                ' user name= ${a}, password = ${b}.' +
671                ' Change your password when you have logged in.',
672                mapping = {
673                    'a':self.context.student_id,
[10908]674                    'b':self.context.application_number,
675                    'c':session,
676                    'd':title}
[10895]677                )
678            self.flash(msg)
[7063]679        return
680
[6196]681    @property
[7240]682    def hasPassword(self):
683        if self.context.password:
[7714]684            return _('set')
685        return _('unset')
[7240]686
687    @property
[6196]688    def label(self):
689        container_title = self.context.__parent__.title
[8096]690        return _('${a} <br /> Application Record ${b}', mapping = {
[7714]691            'a':container_title, 'b':self.context.application_number})
[6196]692
[7347]693    def getCourseAdmitted(self):
694        """Return link, title and code in html format to the certificate
695           admitted.
696        """
697        course_admitted = self.context.course_admitted
[7351]698        if getattr(course_admitted, '__parent__',None):
[7347]699            url = self.url(course_admitted)
700            title = course_admitted.title
701            code = course_admitted.code
702            return '<a href="%s">%s - %s</a>' %(url,code,title)
703        return ''
[6254]704
[7259]705class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
706    grok.context(IApplicant)
707    grok.name('base')
[16006]708
[15581]709    @property
710    def form_fields(self):
711        form_fields = grok.AutoFields(IApplicant).select(
712            'applicant_id', 'reg_number', 'email', 'course1')
713        if self.context.__parent__.prefix in ('special',):
714            form_fields['reg_number'].field.title = u'Identification Number'
715            return form_fields
716        return form_fields
[7259]717
[16231]718class ContactApplicantFormPage(ContactStudentFormPage):
719    grok.context(IApplicant)
720    grok.name('contactapplicant')
721    grok.require('waeup.viewApplication')
722    pnav = 3
723
[7459]724class CreateStudentPage(UtilityView, grok.View):
[8636]725    """Create a student object from applicant data.
[7341]726    """
727    grok.context(IApplicant)
728    grok.name('createstudent')
[14948]729    grok.require('waeup.createStudents')
[7341]730
731    def update(self):
[14346]732        success, msg = self.context.createStudent(view=self)
733        if success:
734            self.flash(msg)
735        else:
736            self.flash(msg, type='warning')
[7341]737        self.redirect(self.url(self.context))
738        return
739
740    def render(self):
741        return
742
[14951]743class CreateAllStudentsPage(KofaPage):
[8636]744    """Create all student objects from applicant data
[14934]745    in the root container or in a specific applicants container only.
[15932]746    Only PortalManagers or StudentCreators can do this.
[8636]747    """
[9900]748    #grok.context(IApplicantsContainer)
[8636]749    grok.name('createallstudents')
[14948]750    grok.require('waeup.createStudents')
[14951]751    label = _('Student Record Creation Report')
[8636]752
753    def update(self):
[14934]754        grok.getSite()['configuration'].maintmode_enabled_by = u'admin'
755        transaction.commit()
756        # Wait 10 seconds for all transactions to be finished.
757        # Do not wait in tests.
758        if not self.request.principal.id == 'zope.mgr':
759            sleep(10)
[8636]760        cat = getUtility(ICatalog, name='applicants_catalog')
761        results = list(cat.searchResults(state=(ADMITTED, ADMITTED)))
762        created = []
[14949]763        failed = []
[9900]764        container_only = False
765        applicants_root = grok.getSite()['applicants']
766        if isinstance(self.context, ApplicantsContainer):
767            container_only = True
[8636]768        for result in results:
[9900]769            if container_only and result.__parent__ is not self.context:
[8636]770                continue
771            success, msg = result.createStudent(view=self)
772            if success:
773                created.append(result.applicant_id)
774            else:
[14951]775                failed.append(
776                    (result.applicant_id, self.url(result, 'manage'), msg))
[12893]777                ob_class = self.__implemented__.__name__.replace(
778                    'waeup.kofa.','')
[14934]779        grok.getSite()['configuration'].maintmode_enabled_by = None
[14951]780        self.successful = ', '.join(created)
781        self.failed = failed
[8636]782        return
783
784
[8260]785class ApplicationFeePaymentAddPage(UtilityView, grok.View):
[7250]786    """ Page to add an online payment ticket
787    """
788    grok.context(IApplicant)
789    grok.name('addafp')
790    grok.require('waeup.payApplicant')
[8243]791    factory = u'waeup.ApplicantOnlinePayment'
[7250]792
[11726]793    @property
794    def custom_requirements(self):
795        return ''
796
[7250]797    def update(self):
[11726]798        # Additional requirements in custom packages.
799        if self.custom_requirements:
800            self.flash(
801                self.custom_requirements,
802                type='danger')
803            self.redirect(self.url(self.context))
[11727]804            return
[11575]805        if not self.context.special:
[16072]806            for ticket in self.context.payments:
[11575]807                if ticket.p_state == 'paid':
808                      self.flash(
809                          _('This type of payment has already been made.'),
810                          type='warning')
811                      self.redirect(self.url(self.context))
812                      return
[8524]813        applicants_utils = getUtility(IApplicantsUtils)
814        container = self.context.__parent__
[8243]815        payment = createObject(self.factory)
[11254]816        failure = applicants_utils.setPaymentDetails(
[10831]817            container, payment, self.context)
[11254]818        if failure is not None:
[13123]819            self.flash(failure, type='danger')
[8524]820            self.redirect(self.url(self.context))
821            return
[16431]822        if getattr(self.context, 'p_option', None):
823            payment.p_option = self.context.p_option
[7250]824        self.context[payment.p_id] = payment
[12893]825        self.context.writeLogMessage(self, 'added: %s' % payment.p_id)
[7714]826        self.flash(_('Payment ticket created.'))
[8280]827        self.redirect(self.url(payment))
[7250]828        return
829
830    def render(self):
831        return
832
833
[7819]834class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[7250]835    """ Page to view an online payment ticket
836    """
837    grok.context(IApplicantOnlinePayment)
838    grok.name('index')
839    grok.require('waeup.viewApplication')
[9984]840    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8170]841    form_fields[
842        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
843    form_fields[
844        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]845    pnav = 3
846
847    @property
848    def label(self):
[7714]849        return _('${a}: Online Payment Ticket ${b}', mapping = {
[8170]850            'a':self.context.__parent__.display_fullname,
851            'b':self.context.p_id})
[7250]852
[8420]853class OnlinePaymentApprovePage(UtilityView, grok.View):
854    """ Approval view
[7250]855    """
856    grok.context(IApplicantOnlinePayment)
[8420]857    grok.name('approve')
858    grok.require('waeup.managePortal')
[7250]859
860    def update(self):
[11580]861        flashtype, msg, log = self.context.approveApplicantPayment()
[8428]862        if log is not None:
[9771]863            applicant = self.context.__parent__
864            # Add log message to applicants.log
865            applicant.writeLogMessage(self, log)
866            # Add log message to payments.log
867            self.context.logger.info(
[9795]868                '%s,%s,%s,%s,%s,,,,,,' % (
[9771]869                applicant.applicant_id,
870                self.context.p_id, self.context.p_category,
871                self.context.amount_auth, self.context.r_code))
[11580]872        self.flash(msg, type=flashtype)
[7250]873        return
874
875    def render(self):
876        self.redirect(self.url(self.context, '@@index'))
877        return
878
[7459]879class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7250]880    """Deliver a PDF slip of the context.
881    """
882    grok.context(IApplicantOnlinePayment)
[8262]883    grok.name('payment_slip.pdf')
[7250]884    grok.require('waeup.viewApplication')
[9984]885    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8173]886    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
887    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[16058]888    #prefix = 'form'
[8258]889    note = None
[7250]890
891    @property
[7714]892    def title(self):
[7819]893        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]894        return translate(_('Payment Data'), 'waeup.kofa',
[7714]895            target_language=portal_language)
896
897    @property
[7250]898    def label(self):
[7819]899        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[8262]900        return translate(_('Online Payment Slip'),
[7811]901            'waeup.kofa', target_language=portal_language) \
[7714]902            + ' %s' % self.context.p_id
[7250]903
[11754]904    @property
905    def payment_slip_download_warning(self):
[14567]906        if self.context.__parent__.state not in (
907            SUBMITTED, ADMITTED, NOT_ADMITTED, CREATED):
[11754]908            return _('Please submit the application form before '
909                     'trying to download payment slips.')
910        return ''
911
[7250]912    def render(self):
[11754]913        if self.payment_slip_download_warning:
914            self.flash(self.payment_slip_download_warning, type='danger')
[11599]915            self.redirect(self.url(self.context))
916            return
[7259]917        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
[7250]918            self.request)
919        students_utils = getUtility(IStudentsUtils)
[8262]920        return students_utils.renderPDF(self,'payment_slip.pdf',
[8258]921            self.context.__parent__, applicantview, note=self.note)
[7250]922
[10571]923class ExportPDFPageApplicationSlip(UtilityView, grok.View):
[6358]924    """Deliver a PDF slip of the context.
925    """
926    grok.context(IApplicant)
927    grok.name('application_slip.pdf')
[7136]928    grok.require('waeup.viewApplication')
[16058]929    #prefix = 'form'
[6358]930
[8666]931    def update(self):
[9051]932        if self.context.state in ('initialized', 'started', 'paid'):
[8666]933            self.flash(
[11254]934                _('Please pay and submit before trying to download '
935                  'the application slip.'), type='warning')
[8666]936            return self.redirect(self.url(self.context))
937        return
938
[6358]939    def render(self):
[12395]940        try:
941            pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
942                view=self)
943        except IOError:
944            self.flash(
945                _('Your image file is corrupted. '
946                  'Please replace.'), type='danger')
947            return self.redirect(self.url(self.context))
[14256]948        except LayoutError, err:
[15583]949            self.flash(
[14256]950                'PDF file could not be created. Reportlab error message: %s'
951                % escape(err.message),
952                type="danger")
953            return self.redirect(self.url(self.context))
[6358]954        self.response.setHeader(
955            'Content-Type', 'application/pdf')
[7392]956        return pdfstream
[6358]957
[7081]958def handle_img_upload(upload, context, view):
[7063]959    """Handle upload of applicant image.
[7081]960
961    Returns `True` in case of success or `False`.
962
963    Please note that file pointer passed in (`upload`) most probably
964    points to end of file when leaving this function.
[7063]965    """
[15833]966    max_upload_size = getUtility(IKofaUtils).MAX_PASSPORT_SIZE
[7081]967    size = file_size(upload)
[15833]968    if size > max_upload_size:
[11254]969        view.flash(_('Uploaded image is too big!'), type='danger')
[7081]970        return False
[7247]971    dummy, ext = os.path.splitext(upload.filename)
972    ext.lower()
973    if ext != '.jpg':
[11254]974        view.flash(_('jpg file extension expected.'), type='danger')
[7247]975        return False
[7081]976    upload.seek(0) # file pointer moved when determining size
[7063]977    store = getUtility(IExtFileStore)
978    file_id = IFileStoreNameChooser(context).chooseName()
[14001]979    try:
980        store.createFile(file_id, upload)
981    except IOError:
982        view.flash(_('Image file cannot be changed.'), type='danger')
983        return False
[7081]984    return True
[7063]985
[15943]986def handle_file_upload(upload, context, view, attr=None):
987    """Handle upload of applicant files.
988
989    Returns `True` in case of success or `False`.
990
991    Please note that file pointer passed in (`upload`) most probably
992    points to end of file when leaving this function.
993    """
994    size = file_size(upload)
995    max_upload_size = 1024 * getUtility(IStudentsUtils).MAX_KB
996    if size > max_upload_size:
997        view.flash(_('Uploaded file is too big!'))
998        return False
[16545]999    upload.seek(0)  # file pointer moved when determining size
1000    dummy,ext = os.path.splitext(upload.filename)
1001    file_format = get_fileformat(None, upload.read(512))
1002    upload.seek(0)  # same here
1003    if file_format is None:
1004        view.flash(_('Could not determine file type.'), type="danger")
1005        return False
[15943]1006    ext.lower()
[16545]1007    if ext not in ('.pdf', '.jpg'):
1008        view.flash(_('pdf or jpg file extension expected.'), type='danger')
[15943]1009        return False
[16545]1010    download_name = attr + '.' + file_format
[15943]1011    store = getUtility(IExtFileStore)
[16545]1012    file_id = IFileStoreNameChooser(context).chooseName(attr=download_name)
[15943]1013    store.createFile(file_id, upload)
1014    return True
1015
[7819]1016class ApplicantManageFormPage(KofaEditFormPage):
[6196]1017    """A full edit view for applicant data.
1018    """
1019    grok.context(IApplicant)
[7200]1020    grok.name('manage')
[7136]1021    grok.require('waeup.manageApplication')
[7200]1022    grok.template('applicanteditpage')
[6322]1023    manage_applications = True
[6196]1024    pnav = 3
[12664]1025    display_actions = [[_('Save'), _('Finally Submit')],
[7714]1026        [_('Add online payment ticket'),_('Remove selected tickets')]]
[6196]1027
[8046]1028    @property
[13886]1029    def display_payments(self):
[15122]1030        if self.context.payments:
1031            return True
[13886]1032        if self.context.special:
1033            return True
1034        return getattr(self.context.__parent__, 'application_fee', None)
1035
1036    @property
[13976]1037    def display_refereereports(self):
1038        if self.context.refereereports:
1039            return True
1040        return False
1041
[15946]1042    def display_fileupload(self, filename):
1043        """This method can be used in custom packages to avoid unneccessary
1044        file uploads.
1045        """
1046        return True
1047
[13976]1048    @property
[10831]1049    def form_fields(self):
1050        if self.context.special:
[10845]1051            form_fields = grok.AutoFields(ISpecialApplicant)
1052            form_fields['applicant_id'].for_display = True
[10831]1053        else:
1054            form_fields = grok.AutoFields(IApplicant)
1055            form_fields['student_id'].for_display = True
1056            form_fields['applicant_id'].for_display = True
1057        return form_fields
1058
1059    @property
[10534]1060    def target(self):
1061        return getattr(self.context.__parent__, 'prefix', None)
1062
1063    @property
[8046]1064    def separators(self):
1065        return getUtility(IApplicantsUtils).SEPARATORS_DICT
1066
[11733]1067    @property
1068    def custom_upload_requirements(self):
1069        return ''
1070
[6196]1071    def update(self):
[7200]1072        super(ApplicantManageFormPage, self).update()
[15833]1073        max_upload_size = getUtility(IKofaUtils).MAX_PASSPORT_SIZE
[6353]1074        self.wf_info = IWorkflowInfo(self.context)
[15833]1075        self.max_upload_size = string_from_bytes(max_upload_size)
[10090]1076        self.upload_success = None
[6598]1077        upload = self.request.form.get('form.passport', None)
1078        if upload:
[11733]1079            if self.custom_upload_requirements:
1080                self.flash(
1081                    self.custom_upload_requirements,
1082                    type='danger')
1083                self.redirect(self.url(self.context))
1084                return
[10090]1085            # We got a fresh upload, upload_success is
1086            # either True or False
1087            self.upload_success = handle_img_upload(
[7084]1088                upload, self.context, self)
[10090]1089            if self.upload_success:
[10095]1090                self.context.writeLogMessage(self, 'saved: passport')
[15943]1091        file_store = getUtility(IExtFileStore)
1092        self.additional_files = getUtility(IApplicantsUtils).ADDITIONAL_FILES
1093        for filename in self.additional_files:
1094            upload = self.request.form.get(filename[1], None)
1095            if upload:
1096                # We got a fresh file upload
1097                success = handle_file_upload(
1098                    upload, self.context, self, attr=filename[1])
1099                if success:
1100                    self.context.writeLogMessage(
1101                        self, 'saved: %s' % filename[1])
1102                else:
1103                    self.upload_success = False
[15946]1104        self.max_file_upload_size = string_from_bytes(
1105            1024*getUtility(IStudentsUtils).MAX_KB)
[6196]1106        return
1107
1108    @property
1109    def label(self):
1110        container_title = self.context.__parent__.title
[8096]1111        return _('${a} <br /> Application Form ${b}', mapping = {
[7714]1112            'a':container_title, 'b':self.context.application_number})
[6196]1113
[6303]1114    def getTransitions(self):
[6351]1115        """Return a list of dicts of allowed transition ids and titles.
[6353]1116
1117        Each list entry provides keys ``name`` and ``title`` for
1118        internal name and (human readable) title of a single
1119        transition.
[6349]1120        """
[8434]1121        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
[11482]1122            if not t[0] in ('pay', 'create')]
[7687]1123        return [dict(name='', title=_('No transition'))] +[
[6355]1124            dict(name=x, title=y) for x, y in allowed_transitions]
[6303]1125
[16218]1126    def saveCourses(self):
[16074]1127        """In custom packages we needed to customize the certificate
1128        select widget. We just save course1 and course2 if these customized
1129        fields appear in the form.
1130        """
[16218]1131        return None, []
[16074]1132
[7714]1133    @action(_('Save'), style='primary')
[6196]1134    def save(self, **data):
[16219]1135        error, changed_courses = self.saveCourses()
1136        if error:
1137            self.flash(error, type='danger')
1138            return
[7240]1139        form = self.request.form
1140        password = form.get('password', None)
1141        password_ctl = form.get('control_password', None)
1142        if password:
1143            validator = getUtility(IPasswordValidator)
1144            errors = validator.validate_password(password, password_ctl)
1145            if errors:
[11254]1146                self.flash( ' '.join(errors), type='danger')
[7240]1147                return
[10090]1148        if self.upload_success is False:  # False is not None!
1149            # Error during image upload. Ignore other values.
1150            return
[6475]1151        changed_fields = self.applyData(self.context, **data)
[7199]1152        # Turn list of lists into single list
1153        if changed_fields:
1154            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7240]1155        else:
1156            changed_fields = []
[16218]1157        changed_fields += changed_courses
[7240]1158        if password:
1159            # Now we know that the form has no errors and can set password ...
1160            IUserAccount(self.context).setPassword(password)
1161            changed_fields.append('password')
[7199]1162        fields_string = ' + '.join(changed_fields)
[7085]1163        trans_id = form.get('transition', None)
1164        if trans_id:
1165            self.wf_info.fireTransition(trans_id)
[7714]1166        self.flash(_('Form has been saved.'))
[6644]1167        if fields_string:
[12892]1168            self.context.writeLogMessage(self, 'saved: %s' % fields_string)
[6196]1169        return
1170
[7250]1171    def unremovable(self, ticket):
[7330]1172        return False
[7250]1173
1174    # This method is also used by the ApplicantEditFormPage
1175    def delPaymentTickets(self, **data):
1176        form = self.request.form
[9701]1177        if 'val_id' in form:
[7250]1178            child_id = form['val_id']
1179        else:
[11254]1180            self.flash(_('No payment selected.'), type='warning')
[7250]1181            self.redirect(self.url(self.context))
1182            return
1183        if not isinstance(child_id, list):
1184            child_id = [child_id]
1185        deleted = []
1186        for id in child_id:
1187            # Applicants are not allowed to remove used payment tickets
1188            if not self.unremovable(self.context[id]):
1189                try:
1190                    del self.context[id]
1191                    deleted.append(id)
1192                except:
[7714]1193                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]1194                      id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[7250]1195        if len(deleted):
[7741]1196            self.flash(_('Successfully removed: ${a}',
[7738]1197                mapping = {'a':', '.join(deleted)}))
[8742]1198            self.context.writeLogMessage(
1199                self, 'removed: % s' % ', '.join(deleted))
[7250]1200        return
1201
[7252]1202    # We explicitely want the forms to be validated before payment tickets
1203    # can be created. If no validation is requested, use
[7459]1204    # 'validator=NullValidator' in the action directive
[11578]1205    @action(_('Add online payment ticket'), style='primary')
[7250]1206    def addPaymentTicket(self, **data):
1207        self.redirect(self.url(self.context, '@@addafp'))
[7252]1208        return
[7250]1209
[7714]1210    @jsaction(_('Remove selected tickets'))
[7250]1211    def removePaymentTickets(self, **data):
1212        self.delPaymentTickets(**data)
1213        self.redirect(self.url(self.context) + '/@@manage')
1214        return
1215
[10094]1216    # Not used in base package
1217    def file_exists(self, attr):
1218        file = getUtility(IExtFileStore).getFileByContext(
1219            self.context, attr=attr)
1220        if file:
1221            return True
1222        else:
1223            return False
1224
[7200]1225class ApplicantEditFormPage(ApplicantManageFormPage):
[5982]1226    """An applicant-centered edit view for applicant data.
1227    """
[6196]1228    grok.context(IApplicantEdit)
[5273]1229    grok.name('edit')
[6198]1230    grok.require('waeup.handleApplication')
[7200]1231    grok.template('applicanteditpage')
[6322]1232    manage_applications = False
[10358]1233    submit_state = PAID
[16207]1234    mandate_days = 31
[5484]1235
[7250]1236    @property
[13976]1237    def display_refereereports(self):
1238        return False
1239
1240    @property
[10831]1241    def form_fields(self):
1242        if self.context.special:
[11657]1243            form_fields = grok.AutoFields(ISpecialApplicant).omit(
1244                'locked', 'suspended')
[10845]1245            form_fields['applicant_id'].for_display = True
[10831]1246        else:
1247            form_fields = grok.AutoFields(IApplicantEdit).omit(
1248                'locked', 'course_admitted', 'student_id',
[10845]1249                'suspended'
[10831]1250                )
1251            form_fields['applicant_id'].for_display = True
1252            form_fields['reg_number'].for_display = True
1253        return form_fields
1254
1255    @property
[7250]1256    def display_actions(self):
[8286]1257        state = IWorkflowState(self.context).getState()
[13100]1258        # If the form is unlocked, applicants are allowed to save the form
1259        # and remove unused tickets.
1260        actions = [[_('Save')], [_('Remove selected tickets')]]
1261        # Only in state started they can also add tickets.
[10358]1262        if state == STARTED:
[7714]1263            actions = [[_('Save')],
1264                [_('Add online payment ticket'),_('Remove selected tickets')]]
[13100]1265        # In state paid, they can submit the data and further add tickets
1266        # if the application is special.
[11599]1267        elif self.context.special and state == PAID:
[12664]1268            actions = [[_('Save'), _('Finally Submit')],
[11599]1269                [_('Add online payment ticket'),_('Remove selected tickets')]]
[8286]1270        elif state == PAID:
[12664]1271            actions = [[_('Save'), _('Finally Submit')],
[7714]1272                [_('Remove selected tickets')]]
[7250]1273        return actions
1274
[7330]1275    def unremovable(self, ticket):
[13100]1276        return ticket.r_code
[7330]1277
[7145]1278    def emit_lock_message(self):
[11254]1279        self.flash(_('The requested form is locked (read-only).'),
1280                   type='warning')
[5941]1281        self.redirect(self.url(self.context))
1282        return
[6078]1283
[5686]1284    def update(self):
[8665]1285        if self.context.locked or (
1286            self.context.__parent__.expired and
1287            self.context.__parent__.strict_deadline):
[7145]1288            self.emit_lock_message()
[5941]1289            return
[7200]1290        super(ApplicantEditFormPage, self).update()
[5686]1291        return
[5952]1292
[15634]1293    def dataNotComplete(self, data):
[15502]1294        if self.context.__parent__.with_picture:
1295            store = getUtility(IExtFileStore)
1296            if not store.getFileByContext(self.context, attr=u'passport.jpg'):
1297                return _('No passport picture uploaded.')
1298            if not self.request.form.get('confirm_passport', False):
1299                return _('Passport picture confirmation box not ticked.')
[6196]1300        return False
[5952]1301
[7252]1302    # We explicitely want the forms to be validated before payment tickets
1303    # can be created. If no validation is requested, use
[7459]1304    # 'validator=NullValidator' in the action directive
[11578]1305    @action(_('Add online payment ticket'), style='primary')
[7250]1306    def addPaymentTicket(self, **data):
1307        self.redirect(self.url(self.context, '@@addafp'))
[7252]1308        return
[7250]1309
[7714]1310    @jsaction(_('Remove selected tickets'))
[7250]1311    def removePaymentTickets(self, **data):
1312        self.delPaymentTickets(**data)
1313        self.redirect(self.url(self.context) + '/@@edit')
1314        return
1315
[7996]1316    @action(_('Save'), style='primary')
[5273]1317    def save(self, **data):
[10090]1318        if self.upload_success is False:  # False is not None!
1319            # Error during image upload. Ignore other values.
1320            return
[5273]1321        self.applyData(self.context, **data)
[16218]1322        error, dummy = self.saveCourses()
[16217]1323        if error:
[16218]1324            self.flash(error, type='danger')
[16217]1325            return
[10210]1326        self.flash(_('Form has been saved.'))
[5273]1327        return
1328
[14014]1329    def informReferees(self):
1330        site = grok.getSite()
1331        kofa_utils = getUtility(IKofaUtils)
1332        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1333        failed = ''
[14016]1334        emails_sent = 0
[14014]1335        for referee in self.context.referees:
1336            if referee.email_sent:
1337                continue
[16059]1338            mandate = RefereeReportMandate(days=self.mandate_days)
[14014]1339            mandate.params['name'] = referee.name
1340            mandate.params['email'] = referee.email
1341            mandate.params[
1342                'redirect_path'] = '/applicants/%s/%s/addrefereereport' % (
1343                    self.context.__parent__.code,
1344                    self.context.application_number)
[16059]1345            mandate.params['redirect_path2'] = ''
1346            mandate.params['applicant_id'] = self.context.applicant_id
[14014]1347            site['mandates'].addMandate(mandate)
1348            # Send invitation email
1349            args = {'mandate_id':mandate.mandate_id}
1350            mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
1351            url_info = u'Report link: %s' % mandate_url
1352            success = kofa_utils.inviteReferee(referee, self.context, url_info)
1353            if success:
[14016]1354                emails_sent += 1
[14014]1355                self.context.writeLogMessage(
1356                    self, 'email sent: %s' % referee.email)
1357                referee.email_sent = True
1358            else:
1359                failed += '%s ' % referee.email
[14016]1360        return failed, emails_sent
[14014]1361
[14025]1362    @action(_('Finally Submit'), warning=WARNING)
[5484]1363    def finalsubmit(self, **data):
[10090]1364        if self.upload_success is False:  # False is not None!
[7084]1365            return # error during image upload. Ignore other values
[15636]1366        dnt = self.dataNotComplete(data)
1367        if dnt:
1368            self.flash(dnt, type='danger')
[5941]1369            return
[7252]1370        self.applyData(self.context, **data)
[16218]1371        error, dummy = self.saveCourses()
1372        if error:
1373            self.flash(error, type='danger')
1374            return
[8286]1375        state = IWorkflowState(self.context).getState()
[6322]1376        # This shouldn't happen, but the application officer
1377        # might have forgotten to lock the form after changing the state
[10358]1378        if state != self.submit_state:
[11254]1379            self.flash(_('The form cannot be submitted. Wrong state!'),
1380                       type='danger')
[6303]1381            return
[14014]1382        msg = _('Form has been submitted.')
1383        # Create mandates and send emails to referees
1384        if getattr(self.context, 'referees', None):
[14016]1385            failed, emails_sent = self.informReferees()
[14014]1386            if failed:
1387                self.flash(
1388                    _('Some invitation emails could not be sent:') + failed,
1389                    type='danger')
1390                return
1391            msg = _('Form has been successfully submitted and '
[14016]1392                    '${a} invitation emails were sent.',
1393                    mapping = {'a':  emails_sent})
[6303]1394        IWorkflowInfo(self.context).fireTransition('submit')
[8589]1395        # application_date is used in export files for sorting.
1396        # We can thus store utc.
[8194]1397        self.context.application_date = datetime.utcnow()
[14014]1398        self.flash(msg)
[6196]1399        self.redirect(self.url(self.context))
[5273]1400        return
[5941]1401
[7063]1402class PassportImage(grok.View):
1403    """Renders the passport image for applicants.
1404    """
1405    grok.name('passport.jpg')
1406    grok.context(IApplicant)
[7113]1407    grok.require('waeup.viewApplication')
[7063]1408
1409    def render(self):
1410        # A filename chooser turns a context into a filename suitable
1411        # for file storage.
1412        image = getUtility(IExtFileStore).getFileByContext(self.context)
[16059]1413        self.response.setHeader('Content-Type', 'image/jpeg')
[7063]1414        if image is None:
1415            # show placeholder image
[7089]1416            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
[7063]1417        return image
[7363]1418
[16059]1419class PassportImageForReport(PassportImage):
1420    """Renders the passport image for applicants for referee reports.
1421    """
1422    grok.name('passport_for_report.jpg')
1423    grok.context(IApplicant)
1424    grok.require('waeup.Public')
1425
1426    def render(self):
1427        # Check mandate
1428        form = self.request.form
1429        self.mandate_id = form.get('mandate_id', None)
1430        self.mandates = grok.getSite()['mandates']
1431        mandate = self.mandates.get(self.mandate_id, None)
1432        if mandate is None:
1433            self.flash(_('No mandate.'), type='warning')
1434            self.redirect(self.application_url())
1435            return
1436        if mandate:
1437            # Check the mandate expiration date after redirect again
1438            if mandate.expires < datetime.utcnow():
1439                self.flash(_('Mandate expired.'),
1440                           type='warning')
1441                self.redirect(self.application_url())
1442                return
1443            # Check if mandate allows access
1444            if mandate.params.get('applicant_id') != self.context.applicant_id:
1445                self.flash(_('Wrong mandate.'),
1446                           type='warning')
1447                self.redirect(self.application_url())
1448                return
1449            return super(PassportImageForReport, self).render()
1450        return
1451
[7819]1452class ApplicantRegistrationPage(KofaAddFormPage):
[7363]1453    """Captcha'd registration page for applicants.
1454    """
1455    grok.context(IApplicantsContainer)
1456    grok.name('register')
[7373]1457    grok.require('waeup.Anonymous')
[7363]1458    grok.template('applicantregister')
1459
[7368]1460    @property
[8033]1461    def form_fields(self):
1462        form_fields = None
[8128]1463        if self.context.mode == 'update':
1464            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
[11738]1465                'lastname','reg_number','email')
[8128]1466        else: #if self.context.mode == 'create':
[8033]1467            form_fields = grok.AutoFields(IApplicantEdit).select(
1468                'firstname', 'middlename', 'lastname', 'email', 'phone')
1469        return form_fields
1470
1471    @property
[7368]1472    def label(self):
[8078]1473        return _('Apply for ${a}',
[7714]1474            mapping = {'a':self.context.title})
[7368]1475
[7363]1476    def update(self):
[8665]1477        if self.context.expired:
[11254]1478            self.flash(_('Outside application period.'), type='warning')
[7368]1479            self.redirect(self.url(self.context))
1480            return
[13394]1481        blocker = grok.getSite()['configuration'].maintmode_enabled_by
1482        if blocker:
1483            self.flash(_('The portal is in maintenance mode '
1484                        'and registration temporarily disabled.'),
1485                       type='warning')
1486            self.redirect(self.url(self.context))
1487            return
[7368]1488        # Handle captcha
[7363]1489        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1490        self.captcha_result = self.captcha.verify(self.request)
1491        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1492        return
1493
[8629]1494    def _redirect(self, email, password, applicant_id):
1495        # Forward only email to landing page in base package.
1496        self.redirect(self.url(self.context, 'registration_complete',
1497            data = dict(email=email)))
1498        return
1499
[14578]1500    @property
1501    def _postfix(self):
1502        """In customized packages we can add a container dependent string if
1503        applicants have been imported into several containers.
1504        """
1505        return ''
1506
[9178]1507    @action(_('Send login credentials to email address'), style='primary')
[7363]1508    def register(self, **data):
1509        if not self.captcha_result.is_valid:
[8037]1510            # Captcha will display error messages automatically.
[7363]1511            # No need to flash something.
1512            return
[8033]1513        if self.context.mode == 'create':
[13217]1514            # Check if there are unused records in this container which
1515            # can be taken
1516            applicant = self.context.first_unused
1517            if applicant is None:
[13215]1518                # Add applicant
1519                applicant = createObject(u'waeup.Applicant')
1520                self.context.addApplicant(applicant)
[14110]1521            else:
1522                applicants_root = grok.getSite()['applicants']
1523                ob_class = self.__implemented__.__name__.replace(
1524                    'waeup.kofa.','')
1525                applicants_root.logger.info('%s - used: %s' % (
1526                    ob_class, applicant.applicant_id))
[8033]1527            self.applyData(applicant, **data)
[15578]1528            # applicant.reg_number = applicant.applicant_id
[8042]1529            notify(grok.ObjectModifiedEvent(applicant))
[8033]1530        elif self.context.mode == 'update':
1531            # Update applicant
[8037]1532            reg_number = data.get('reg_number','')
[11738]1533            lastname = data.get('lastname','')
[8033]1534            cat = getUtility(ICatalog, name='applicants_catalog')
[14578]1535            searchstr = reg_number + self._postfix
[8033]1536            results = list(
[14578]1537                cat.searchResults(reg_number=(searchstr, searchstr)))
[8033]1538            if results:
1539                applicant = results[0]
[11738]1540                if getattr(applicant,'lastname',None) is None:
[11254]1541                    self.flash(_('An error occurred.'), type='danger')
[8037]1542                    return
[11738]1543                elif applicant.lastname.lower() != lastname.lower():
[8042]1544                    # Don't tell the truth here. Anonymous must not
[11738]1545                    # know that a record was found and only the lastname
[8042]1546                    # verification failed.
[13099]1547                    self.flash(
1548                        _('No application record found.'), type='warning')
[8037]1549                    return
[8627]1550                elif applicant.password is not None and \
1551                    applicant.state != INITIALIZED:
1552                    self.flash(_('Your password has already been set and used. '
[11254]1553                                 'Please proceed to the login page.'),
1554                               type='warning')
[8042]1555                    return
1556                # Store email address but nothing else.
[8033]1557                applicant.email = data['email']
[8042]1558                notify(grok.ObjectModifiedEvent(applicant))
[8033]1559            else:
[8042]1560                # No record found, this is the truth.
[11254]1561                self.flash(_('No application record found.'), type='warning')
[8033]1562                return
1563        else:
[8042]1564            # Does not happen but anyway ...
[8033]1565            return
[7819]1566        kofa_utils = getUtility(IKofaUtils)
[7811]1567        password = kofa_utils.genPassword()
[7380]1568        IUserAccount(applicant).setPassword(password)
[7365]1569        # Send email with credentials
[16538]1570        args = {'login':applicant.applicant_id, 'password':password}
[16539]1571        login_url = self.url(grok.getSite()) + '/login?%s' % urlencode(args)
[8853]1572        url_info = u'Login: %s' % login_url
[7714]1573        msg = _('You have successfully been registered for the')
[7811]1574        if kofa_utils.sendCredentials(IUserAccount(applicant),
[8853]1575            password, url_info, msg):
[8629]1576            email_sent = applicant.email
[7380]1577        else:
[8629]1578            email_sent = None
1579        self._redirect(email=email_sent, password=password,
1580            applicant_id=applicant.applicant_id)
[7380]1581        return
1582
[7819]1583class ApplicantRegistrationEmailSent(KofaPage):
[7380]1584    """Landing page after successful registration.
[8629]1585
[7380]1586    """
1587    grok.name('registration_complete')
1588    grok.require('waeup.Public')
1589    grok.template('applicantregemailsent')
[7714]1590    label = _('Your registration was successful.')
[7380]1591
[8629]1592    def update(self, email=None, applicant_id=None, password=None):
[7380]1593        self.email = email
[8629]1594        self.password = password
1595        self.applicant_id = applicant_id
[7380]1596        return
[10655]1597
[13254]1598class ApplicantCheckStatusPage(KofaPage):
1599    """Captcha'd status checking page for applicants.
1600    """
1601    grok.context(IApplicantsRoot)
1602    grok.name('checkstatus')
1603    grok.require('waeup.Anonymous')
1604    grok.template('applicantcheckstatus')
1605    buttonname = _('Submit')
[16097]1606    pnav = 7
[13254]1607
1608    def label(self):
1609        if self.result:
[13429]1610            return _('Admission status of ${a}',
[13254]1611                     mapping = {'a':self.applicant.applicant_id})
[13428]1612        return _('Check your admission status')
[13254]1613
1614    def update(self, SUBMIT=None):
1615        form = self.request.form
1616        self.result = False
1617        # Handle captcha
1618        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1619        self.captcha_result = self.captcha.verify(self.request)
1620        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1621        if SUBMIT:
1622            if not self.captcha_result.is_valid:
1623                # Captcha will display error messages automatically.
1624                # No need to flash something.
1625                return
[13363]1626            unique_id = form.get('unique_id', None)
[13254]1627            lastname = form.get('lastname', None)
[13363]1628            if not unique_id or not lastname:
[13254]1629                self.flash(
1630                    _('Required input missing.'), type='warning')
1631                return
1632            cat = getUtility(ICatalog, name='applicants_catalog')
1633            results = list(
[13363]1634                cat.searchResults(applicant_id=(unique_id, unique_id)))
1635            if not results:
1636                results = list(
1637                    cat.searchResults(reg_number=(unique_id, unique_id)))
[13254]1638            if results:
1639                applicant = results[0]
[13282]1640                if applicant.lastname.lower().strip() != lastname.lower():
[13254]1641                    # Don't tell the truth here. Anonymous must not
1642                    # know that a record was found and only the lastname
1643                    # verification failed.
1644                    self.flash(
1645                        _('No application record found.'), type='warning')
1646                    return
1647            else:
1648                self.flash(_('No application record found.'), type='warning')
1649                return
1650            self.applicant = applicant
1651            self.entry_session = "%s/%s" % (
1652                applicant.__parent__.year,
1653                applicant.__parent__.year+1)
1654            course_admitted = getattr(applicant, 'course_admitted', None)
1655            self.course_admitted = False
1656            if course_admitted is not None:
[14394]1657                try:
1658                    self.course_admitted = True
1659                    self.longtitle = course_admitted.longtitle
1660                    self.department = course_admitted.__parent__.__parent__.longtitle
1661                    self.faculty = course_admitted.__parent__.__parent__.__parent__.longtitle
1662                except AttributeError:
1663                    self.flash(_('Application record invalid.'), type='warning')
1664                    return
[13254]1665            self.result = True
1666            self.admitted = False
1667            self.not_admitted = False
1668            self.submitted = False
1669            self.not_submitted = False
[13356]1670            self.created = False
[13254]1671            if applicant.state in (ADMITTED, CREATED):
1672                self.admitted = True
[13356]1673            if applicant.state in (CREATED):
1674                self.created = True
[13365]1675                self.student_id = applicant.student_id
1676                self.password = applicant.application_number
[13254]1677            if applicant.state in (NOT_ADMITTED,):
1678                self.not_admitted = True
1679            if applicant.state in (SUBMITTED,):
1680                self.submitted = True
1681            if applicant.state in (INITIALIZED, STARTED, PAID):
1682                self.not_submitted = True
1683        return
1684
[16116]1685class CheckTranscriptStatus(KofaPage):
1686    """A display page for checking transcript processing status.
1687    """
1688    grok.context(IApplicantsRoot)
1689    grok.name('checktranscript')
1690    grok.require('waeup.Public')
1691    label = _('Check transcript status')
1692    buttonname = _('Check status now')
1693    pnav = 8
[16120]1694    websites = (('DemoPortal', 'https://kofa-demo.waeup.org/'),)
[16129]1695    #websites = (('DemoPortal', 'http://localhost:8080/app/'),)
[16120]1696    appl_url1 = 'https://kofa-demo.waeup.org/applicants'
1697    appl_url2 = 'https://kofa-demo.waeup.org/applicants'
[16116]1698
1699    def update(self, SUBMIT=None):
1700        form = self.request.form
1701        self.button = False
1702        # Handle captcha
1703        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1704        self.captcha_result = self.captcha.verify(self.request)
1705        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1706        if SUBMIT:
1707            self.results = []
1708            if not self.captcha_result.is_valid:
1709                # Captcha will display error messages automatically.
1710                # No need to flash something.
1711                return
1712            unique_id = form.get('unique_id', None)
1713            email = form.get('email', None)
1714            if not unique_id or not email:
1715                self.flash(
1716                    _('Required input missing.'), type='warning')
1717                return
1718            self.button = True
1719            # Call webservice of all websites
1720            for website in self.websites:
1721                server = xmlrpclib.ServerProxy(website[1])
1722                result = server.get_grad_student(unique_id, email)
1723                if not result:
1724                    continue
1725                self.results.append((result, website))
1726        return
1727
[10655]1728class ExportJobContainerOverview(KofaPage):
1729    """Page that lists active applicant data export jobs and provides links
1730    to discard or download CSV files.
1731
1732    """
1733    grok.context(VirtualApplicantsExportJobContainer)
1734    grok.require('waeup.manageApplication')
1735    grok.name('index.html')
1736    grok.template('exportjobsindex')
[11254]1737    label = _('Data Exports')
[10655]1738    pnav = 3
1739
1740    def update(self, CREATE=None, DISCARD=None, job_id=None):
1741        if CREATE:
1742            self.redirect(self.url('@@start_export'))
1743            return
1744        if DISCARD and job_id:
1745            entry = self.context.entry_from_job_id(job_id)
1746            self.context.delete_export_entry(entry)
1747            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1748            self.context.logger.info(
1749                '%s - discarded: job_id=%s' % (ob_class, job_id))
1750            self.flash(_('Discarded export') + ' %s' % job_id)
1751        self.entries = doll_up(self, user=self.request.principal.id)
1752        return
1753
[13950]1754class ExportJobContainerJobStart(UtilityView, grok.View):
[16064]1755    """View that starts three export jobs, one for applicants, a second
1756    one for applicant payments and a third for referee reports.
[10655]1757    """
1758    grok.context(VirtualApplicantsExportJobContainer)
1759    grok.require('waeup.manageApplication')
1760    grok.name('start_export')
1761
1762    def update(self):
[13152]1763        utils = queryUtility(IKofaUtils)
1764        if not utils.expensive_actions_allowed():
1765            self.flash(_(
1766                "Currently, exporters cannot be started due to high "
1767                "system load. Please try again later."), type='danger')
1768            self.entries = doll_up(self, user=None)
1769            return
[13950]1770
1771        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1772        container_code = self.context.__parent__.code
1773        # Start first exporter
[16064]1774        for exporter in ('applicants',
1775                         'applicantpayments',
1776                         'applicantrefereereports'):
1777            job_id = self.context.start_export_job(exporter,
1778                                          self.request.principal.id,
1779                                          container=container_code)
1780            self.context.logger.info(
1781                '%s - exported: %s (%s), job_id=%s'
1782                % (ob_class, exporter, container_code, job_id))
1783            # Commit transaction so that job is stored in the ZODB
1784            transaction.commit()
[13950]1785        self.flash(_('Exports started.'))
[10655]1786        self.redirect(self.url(self.context))
1787        return
1788
1789    def render(self):
1790        return
1791
1792class ExportJobContainerDownload(ExportCSVView):
1793    """Page that downloads a students export csv file.
1794
1795    """
1796    grok.context(VirtualApplicantsExportJobContainer)
[11253]1797    grok.require('waeup.manageApplication')
[13976]1798
[16214]1799class RefereesRemindPage(UtilityView, grok.View):
1800    """A display view for referee reports.
1801    """
1802    grok.context(IApplicant)
1803    grok.name('remind_referees')
1804    grok.require('waeup.manageApplication')
1805
1806    mandate_days = 31
1807
1808    def remindReferees(self):
1809        site = grok.getSite()
1810        kofa_utils = getUtility(IKofaUtils)
1811        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1812        failed = ''
1813        emails_sent = 0
1814        for referee in self.context.referees:
[16221]1815            #if not referee.email_sent:
1816            #    continue
[16214]1817            # Check if referee has already created a report
1818            report_exists = False
1819            for report in self.context.refereereports:
[16215]1820                if report.email == referee.email:
[16214]1821                    report_exists = True
1822            if report_exists:
1823                continue
1824            # If not, create new mandate
1825            mandate = RefereeReportMandate(days=self.mandate_days)
1826            mandate.params['name'] = referee.name
1827            mandate.params['email'] = referee.email
1828            mandate.params[
1829                'redirect_path'] = '/applicants/%s/%s/addrefereereport' % (
1830                    self.context.__parent__.code,
1831                    self.context.application_number)
1832            mandate.params['redirect_path2'] = ''
1833            mandate.params['applicant_id'] = self.context.applicant_id
1834            site['mandates'].addMandate(mandate)
1835            # Send invitation email
1836            args = {'mandate_id':mandate.mandate_id}
1837            mandate_url = self.url(site) + '/mandate?%s' % urlencode(args)
1838            url_info = u'Report link: %s' % mandate_url
1839            success = kofa_utils.inviteReferee(referee, self.context, url_info)
1840            if success:
1841                emails_sent += 1
1842                self.context.writeLogMessage(
1843                    self, 'email sent: %s' % referee.email)
1844                referee.email_sent = True
1845            else:
1846                failed += '%s ' % referee.email
1847        return failed, emails_sent
1848
1849    def update(self):
1850        if self.context.state != 'submitted':
1851            self.flash(
1852                _('Not allowed!'), type='danger')
1853            return self.redirect(self.url(self.context))
1854        failed, emails_sent = self.remindReferees()
1855        msg = _('${a} referee(s) have been reminded by email.',
1856                mapping = {'a':  emails_sent})
1857        self.flash(msg)
1858        return self.redirect(self.url(self.context))
1859
1860    def render(self):
1861        return
1862
[13976]1863class RefereeReportDisplayFormPage(KofaDisplayFormPage):
1864    """A display view for referee reports.
1865    """
1866    grok.context(IApplicantRefereeReport)
1867    grok.name('index')
1868    grok.require('waeup.manageApplication')
1869    label = _('Referee Report')
1870    pnav = 3
[16058]1871    form_fields = grok.AutoFields(IApplicantRefereeReport)
1872    form_fields[
1873        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[13976]1874
[16243]1875class RefereeReportManageFormPage(KofaEditFormPage):
1876    """A displaymanage for referee reports.
1877    """
1878    grok.context(IApplicantRefereeReport)
1879    grok.name('manage')
1880    grok.require('waeup.managePortal')
1881    label = _('Manage Referee Report')
1882    pnav = 3
1883    form_fields = grok.AutoFields(IApplicantRefereeReport).omit('creation_date')
1884
1885    @action(_('Save'), style='primary')
1886    def save(self, **data):
1887        changed_fields = self.applyData(self.context, **data)
1888        # Turn list of lists into single list
1889        if changed_fields:
1890            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
1891        else:
1892            changed_fields = []
1893        fields_string = ' + '.join(changed_fields)
1894        self.flash(_('Form has been saved.'))
1895        if fields_string:
1896            self.context.__parent__.writeLogMessage(
1897                self, '%s - saved: %s' % (self.context.r_id, fields_string))
1898        return
1899
[16059]1900class RemoveRefereeReportPage(UtilityView, grok.View):
1901    """
1902    """
1903    grok.context(IApplicantRefereeReport)
1904    grok.name('remove')
1905    grok.require('waeup.manageApplication')
1906
1907    def update(self):
1908        redirect_url = self.url(self.context.__parent__)
1909        self.context.__parent__.writeLogMessage(
1910            self, 'removed: %s' % self.context.r_id)
1911        del self.context.__parent__[self.context.r_id]
1912        self.flash(_('Referee report removed.'))
1913        self.redirect(redirect_url)
1914        return
1915
1916    def render(self):
1917        return
1918
[13976]1919class RefereeReportAddFormPage(KofaAddFormPage):
1920    """Add-form to add an referee report. This form
[13992]1921    is protected by a mandate.
[13976]1922    """
1923    grok.context(IApplicant)
[13991]1924    grok.require('waeup.Public')
[13976]1925    grok.name('addrefereereport')
1926    form_fields = grok.AutoFields(
1927        IApplicantRefereeReport).omit('creation_date')
[13992]1928    grok.template('refereereportpage')
[16059]1929    label = _('Referee Report Form')
[13976]1930    pnav = 3
1931    #doclink = DOCLINK + '/refereereports.html'
1932
1933    def update(self):
[13991]1934        blocker = grok.getSite()['configuration'].maintmode_enabled_by
1935        if blocker:
1936            self.flash(_('The portal is in maintenance mode. '
1937                        'Referee report forms are temporarily disabled.'),
1938                       type='warning')
1939            self.redirect(self.application_url())
1940            return
1941        # Check mandate
1942        form = self.request.form
[13992]1943        self.mandate_id = form.get('mandate_id', None)
1944        self.mandates = grok.getSite()['mandates']
1945        mandate = self.mandates.get(self.mandate_id, None)
[13991]1946        if mandate is None and not self.request.form.get('form.actions.submit'):
1947            self.flash(_('No mandate.'), type='warning')
1948            self.redirect(self.application_url())
1949            return
1950        if mandate:
[16058]1951            # Check the mandate expiration date after redirect again
1952            if mandate.expires < datetime.utcnow():
1953                self.flash(_('Mandate expired.'),
1954                           type='warning')
1955                self.redirect(self.application_url())
1956                return
[16059]1957            args = {'mandate_id':mandate.mandate_id}
1958            # Check if report exists.
[16214]1959            # (1) If mandate has been used to create a report,
1960            # redirect to the pdf file.
[16059]1961            if mandate.params.get('redirect_path2'):
1962                self.redirect(
1963                    self.application_url() +
1964                    mandate.params.get('redirect_path2') +
1965                    '?%s' % urlencode(args))
1966                return
[16214]1967            # (2) Report exists but was created with another mandate.
1968            for report in self.context.refereereports:
[16215]1969                if report.email == mandate.params.get('email'):
[16214]1970                    self.flash(_('You have already created a '
1971                                 'report with another mandate.'),
1972                               type='warning')
1973                    self.redirect(self.application_url())
1974                    return
[13991]1975            # Prefill form with mandate params
1976            self.form_fields.get(
1977                'name').field.default = mandate.params['name']
1978            self.form_fields.get(
[16243]1979                'email_pref').field.default = mandate.params['email']
[16059]1980            self.passport_url = self.url(
1981                self.context, 'passport_for_report.jpg') + '?%s' % urlencode(args)
[13976]1982        super(RefereeReportAddFormPage, self).update()
1983        return
1984
1985    @action(_('Submit'),
1986              warning=_('Are you really sure? '
1987                        'Reports can neither be modified or added '
1988                        'after submission.'),
1989              style='primary')
1990    def addRefereeReport(self, **data):
1991        report = createObject(u'waeup.ApplicantRefereeReport')
1992        timestamp = ("%d" % int(time()*10000))[1:]
1993        report.r_id = "r%s" % timestamp
[16243]1994        report.email = self.mandates[self.mandate_id].params['email']
[13976]1995        self.applyData(report, **data)
1996        self.context[report.r_id] = report
[16059]1997        # self.flash(_('Referee report has been saved. Thank you!'))
[13976]1998        self.context.writeLogMessage(self, 'added: %s' % report.r_id)
[16059]1999        # Changed on 19/04/20: We do no longer delete the mandate
2000        # but set path to redirect to the pdf file
2001        self.mandates[self.mandate_id].params[
2002            'redirect_path2'] = '/applicants/%s/%s/%s/referee_report.pdf' % (
2003                self.context.__parent__.code,
2004                self.context.application_number,
2005                report.r_id)
2006        notify(grok.ObjectModifiedEvent(self.mandates[self.mandate_id]))
2007        args = {'mandate_id':self.mandate_id}
[16214]2008        self.flash(_('Your report has been successfully submitted. '
2009                     'Please use the report link in the email again to download '
2010                     'a pdf slip of your report.'))
2011        #self.redirect(self.url(report, 'referee_report.pdf')
2012        #              + '?%s' % urlencode(args))
2013        self.redirect(self.application_url())
[15943]2014        return
2015
[16058]2016class ExportPDFReportSlipPage(UtilityView, grok.View):
2017    """Deliver a PDF slip of the context.
2018    """
2019    grok.context(IApplicantRefereeReport)
2020    grok.name('referee_report_slip.pdf')
2021    grok.require('waeup.manageApplication')
2022    form_fields = grok.AutoFields(IApplicantRefereeReport)
2023    form_fields[
2024        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
2025    #prefix = 'form'
2026    note = None
2027
2028    @property
2029    def title(self):
2030        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2031        return translate(_('Referee Report'), 'waeup.kofa',
2032            target_language=portal_language)
2033
2034    @property
2035    def label(self):
2036        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
2037        return translate(_('Referee Report Slip'),
2038            'waeup.kofa', target_language=portal_language) \
2039            + ' %s' % self.context.r_id
2040
2041    def render(self):
2042        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
2043            self.request)
2044        students_utils = getUtility(IStudentsUtils)
2045        return students_utils.renderPDF(self,'referee_report_slip.pdf',
2046            self.context.__parent__, applicantview, note=self.note)
2047
[16059]2048class ExportPDFReportSlipPage2(ExportPDFReportSlipPage):
2049    """Deliver a PDF slip of the context to referees.
2050    """
2051    grok.name('referee_report.pdf')
2052    grok.require('waeup.Public')
2053
2054    def update(self):
2055        # Check mandate
2056        form = self.request.form
2057        self.mandate_id = form.get('mandate_id', None)
2058        self.mandates = grok.getSite()['mandates']
2059        mandate = self.mandates.get(self.mandate_id, None)
2060        if mandate is None:
2061            self.flash(_('No mandate.'), type='warning')
2062            self.redirect(self.application_url())
2063            return
2064        if mandate:
2065            # Check the mandate expiration date after redirect again
2066            if mandate.expires < datetime.utcnow():
2067                self.flash(_('Mandate expired.'),
2068                           type='warning')
2069                self.redirect(self.application_url())
2070                return
2071            # Check if form has really been submitted
2072            if not mandate.params.get('redirect_path2') \
2073                or mandate.params.get(
2074                    'applicant_id') != self.context.__parent__.applicant_id:
2075                self.flash(_('Wrong mandate.'),
2076                           type='warning')
2077                self.redirect(self.application_url())
2078                return
2079            super(ExportPDFReportSlipPage2, self).update()
2080        return
2081
[15943]2082class AdditionalFile(grok.View):
[16545]2083    """Renders additional files for applicants.
[15943]2084    This is a baseclass.
2085    """
2086    grok.baseclass()
2087    grok.context(IApplicant)
2088    grok.require('waeup.viewApplication')
2089
2090    def render(self):
[16545]2091        #image = getUtility(IExtFileStore).getFileByContext(
2092        #    self.context, attr=self.download_name)
2093        file = getUtility(IExtFileStore).getFileByContext(
[15943]2094            self.context, attr=self.__name__)
[16545]2095        dummy,ext = os.path.splitext(file.name)
2096        if ext == '.jpg':
2097            self.response.setHeader('Content-Type', 'image/jpeg')
2098        elif ext == '.pdf':
2099            self.response.setHeader('Content-Type', 'application/pdf')
2100        return file
[15943]2101
2102class TestFile(AdditionalFile):
[16545]2103    """Renders testfile.
[15943]2104    """
[16545]2105    grok.name('testfile')
Note: See TracBrowser for help on using the repository browser.