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

Last change on this file since 18277 was 18277, checked in by Henrik Bettermann, 5 months ago

Allow registration if the container's enddate is None.

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