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

Last change on this file since 16976 was 16976, checked in by Henrik Bettermann, 2 years ago

Send email after final submission of application form.

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