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

Last change on this file since 13244 was 13232, checked in by Henrik Bettermann, 10 years ago

Officers must be aware of what they are doing when puring containers.

  • Property svn:keywords set to Id
File size: 50.2 KB
RevLine 
[5273]1## $Id: browser.py 13232 2015-08-27 06:09:58Z henrik $
[6078]2##
[7192]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
[5273]4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
[6078]8##
[5273]9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
[6078]13##
[5273]14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
[5824]18"""UI components for basic applicants and related components.
[5273]19"""
[7063]20import os
[6082]21import sys
[5273]22import grok
[7370]23from datetime import datetime, date
[8042]24from zope.event import notify
[13152]25from zope.component import getUtility, queryUtility, createObject, getAdapter
[8033]26from zope.catalog.interfaces import ICatalog
[7714]27from zope.i18n import translate
[7322]28from hurry.workflow.interfaces import (
29    IWorkflowInfo, IWorkflowState, InvalidTransitionError)
[7811]30from waeup.kofa.applicants.interfaces import (
[7363]31    IApplicant, IApplicantEdit, IApplicantsRoot,
[7683]32    IApplicantsContainer, IApplicantsContainerAdd,
[8033]33    MAX_UPLOAD_SIZE, IApplicantOnlinePayment, IApplicantsUtils,
[10845]34    IApplicantRegisterUpdate, ISpecialApplicant
[7363]35    )
[12247]36from waeup.kofa.utils.helpers import html2dict
[10655]37from waeup.kofa.applicants.container import (
38    ApplicantsContainer, VirtualApplicantsExportJobContainer)
[8404]39from waeup.kofa.applicants.applicant import search
[8636]40from waeup.kofa.applicants.workflow import (
41    INITIALIZED, STARTED, PAID, SUBMITTED, ADMITTED)
[7811]42from waeup.kofa.browser import (
[9217]43#    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
[7363]44    DEFAULT_PASSPORT_IMAGE_PATH)
[9217]45from waeup.kofa.browser.layout import (
46    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage)
[7811]47from waeup.kofa.browser.interfaces import ICaptchaManager
48from waeup.kofa.browser.breadcrumbs import Breadcrumb
49from waeup.kofa.browser.layout import (
[11437]50    NullValidator, jsaction, action, UtilityView)
[10655]51from waeup.kofa.browser.pages import (
52    add_local_role, del_local_roles, doll_up, ExportCSVView)
[7811]53from waeup.kofa.interfaces import (
[13177]54    IKofaObject, ILocalRolesAssignable, IExtFileStore, IPDF, DOCLINK,
[7819]55    IFileStoreNameChooser, IPasswordValidator, IUserAccount, IKofaUtils)
[7811]56from waeup.kofa.interfaces import MessageFactory as _
57from waeup.kofa.permissions import get_users_with_local_roles
58from waeup.kofa.students.interfaces import IStudentsUtils
[8186]59from waeup.kofa.utils.helpers import string_from_bytes, file_size, now
[8170]60from waeup.kofa.widgets.datewidget import (
[10831]61    FriendlyDateDisplayWidget,
[8170]62    FriendlyDatetimeDisplayWidget)
[5320]63
[7819]64grok.context(IKofaObject) # Make IKofaObject the default context
[5273]65
[11437]66WARNING = _('You can not edit your application records after final submission.'
67            ' You really want to submit?')
[8550]68
[8388]69class ApplicantsRootPage(KofaDisplayFormPage):
[5822]70    grok.context(IApplicantsRoot)
71    grok.name('index')
[6153]72    grok.require('waeup.Public')
[8388]73    form_fields = grok.AutoFields(IApplicantsRoot)
[13076]74    label = _('Applicants Section')
[5843]75    pnav = 3
[6012]76
77    def update(self):
[6067]78        super(ApplicantsRootPage, self).update()
[6012]79        return
80
[8388]81    @property
82    def introduction(self):
83        # Here we know that the cookie has been set
84        lang = self.request.cookies.get('kofa.language')
85        html = self.context.description_dict.get(lang,'')
86        if html == '':
87            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
88            html = self.context.description_dict.get(portal_language,'')
89        return html
90
[10097]91    @property
92    def containers(self):
[10098]93        if self.layout.isAuthenticated():
[13217]94            values = sorted([container for container in self.context.values()],
[13222]95                            key=lambda value: value.enddate, reverse=True)
[13217]96            return values
97        values = sorted([container for container in self.context.values()
98                         if not container.hidden],
[13222]99                        key=lambda value: value.enddate, reverse=True)
[13217]100        return values
[10097]101
[8404]102class ApplicantsSearchPage(KofaPage):
103    grok.context(IApplicantsRoot)
104    grok.name('search')
105    grok.require('waeup.viewApplication')
[10644]106    label = _('Find applicants')
[10645]107    search_button = _('Find applicant')
[8404]108    pnav = 3
109
110    def update(self, *args, **kw):
111        form = self.request.form
112        self.results = []
113        if 'searchterm' in form and form['searchterm']:
114            self.searchterm = form['searchterm']
115            self.searchtype = form['searchtype']
116        elif 'old_searchterm' in form:
117            self.searchterm = form['old_searchterm']
118            self.searchtype = form['old_searchtype']
119        else:
120            if 'search' in form:
[11254]121                self.flash(_('Empty search string'), type='warning')
[8404]122            return
123        self.results = search(query=self.searchterm,
124            searchtype=self.searchtype, view=self)
125        if not self.results:
[11254]126            self.flash(_('No applicant found.'), type='warning')
[8404]127        return
128
[7819]129class ApplicantsRootManageFormPage(KofaEditFormPage):
[5828]130    grok.context(IApplicantsRoot)
131    grok.name('manage')
[6107]132    grok.template('applicantsrootmanagepage')
[8388]133    form_fields = grok.AutoFields(IApplicantsRoot)
[13076]134    label = _('Manage applicants section')
[5843]135    pnav = 3
[7136]136    grok.require('waeup.manageApplication')
[8388]137    taboneactions = [_('Save')]
138    tabtwoactions = [_('Add applicants container'), _('Remove selected')]
139    tabthreeactions1 = [_('Remove selected local roles')]
140    tabthreeactions2 = [_('Add local role')]
[7710]141    subunits = _('Applicants Containers')
[13177]142    doclink = DOCLINK + '/applicants.html'
[6078]143
[6184]144    def getLocalRoles(self):
145        roles = ILocalRolesAssignable(self.context)
146        return roles()
147
148    def getUsers(self):
149        """Get a list of all users.
150        """
151        for key, val in grok.getSite()['users'].items():
152            url = self.url(val)
153            yield(dict(url=url, name=key, val=val))
154
155    def getUsersWithLocalRoles(self):
156        return get_users_with_local_roles(self.context)
157
[7710]158    @jsaction(_('Remove selected'))
[6069]159    def delApplicantsContainers(self, **data):
160        form = self.request.form
[9701]161        if 'val_id' in form:
[8388]162            child_id = form['val_id']
163        else:
[11254]164            self.flash(_('No container selected!'), type='warning')
165            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[8388]166            return
[6069]167        if not isinstance(child_id, list):
168            child_id = [child_id]
169        deleted = []
170        for id in child_id:
171            try:
172                del self.context[id]
173                deleted.append(id)
174            except:
[7710]175                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]176                    id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[6069]177        if len(deleted):
[7738]178            self.flash(_('Successfully removed: ${a}',
179                mapping = {'a':', '.join(deleted)}))
[12892]180        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
181        self.context.logger.info(
182            '%s - removed: %s' % (ob_class, ', '.join(deleted)))
[11254]183        self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6078]184        return
[5828]185
[7710]186    @action(_('Add applicants container'), validator=NullValidator)
[6069]187    def addApplicantsContainer(self, **data):
188        self.redirect(self.url(self.context, '@@add'))
[6078]189        return
190
[7710]191    @action(_('Add local role'), validator=NullValidator)
[6184]192    def addLocalRole(self, **data):
[7484]193        return add_local_role(self,3, **data)
[6184]194
[7710]195    @action(_('Remove selected local roles'))
[6184]196    def delLocalRoles(self, **data):
[7484]197        return del_local_roles(self,3,**data)
[6184]198
[8388]199    @action(_('Save'), style='primary')
200    def save(self, **data):
201        self.applyData(self.context, **data)
[12247]202        description = getattr(self.context, 'description', None)
203        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
204        self.context.description_dict = html2dict(description, portal_language)
[8390]205        self.flash(_('Form has been saved.'))
[8388]206        return
207
[7819]208class ApplicantsContainerAddFormPage(KofaAddFormPage):
[5822]209    grok.context(IApplicantsRoot)
[7136]210    grok.require('waeup.manageApplication')
[5822]211    grok.name('add')
[6107]212    grok.template('applicantscontaineraddpage')
[7710]213    label = _('Add applicants container')
[5843]214    pnav = 3
[6078]215
[6103]216    form_fields = grok.AutoFields(
[7903]217        IApplicantsContainerAdd).omit('code').omit('title')
[6078]218
[7710]219    @action(_('Add applicants container'))
[6069]220    def addApplicantsContainer(self, **data):
[6103]221        year = data['year']
222        code = u'%s%s' % (data['prefix'], year)
[9529]223        apptypes_dict = getUtility(IApplicantsUtils).APP_TYPES_DICT
224        title = apptypes_dict[data['prefix']][0]
[7685]225        title = u'%s %s/%s' % (title, year, year + 1)
[6087]226        if code in self.context.keys():
[6105]227            self.flash(
[11254]228              _('An applicants container for the same application '
229                'type and entrance year exists already in the database.'),
230                type='warning')
[5822]231            return
232        # Add new applicants container...
[8009]233        container = createObject(u'waeup.ApplicantsContainer')
[6069]234        self.applyData(container, **data)
[6087]235        container.code = code
236        container.title = title
237        self.context[code] = container
[7710]238        self.flash(_('Added:') + ' "%s".' % code)
[12892]239        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
240        self.context.logger.info('%s - added: %s' % (ob_class, code))
[7484]241        self.redirect(self.url(self.context, u'@@manage'))
[5822]242        return
[6078]243
[7710]244    @action(_('Cancel'), validator=NullValidator)
[6069]245    def cancel(self, **data):
[7484]246        self.redirect(self.url(self.context, '@@manage'))
[6078]247
[5845]248class ApplicantsRootBreadcrumb(Breadcrumb):
249    """A breadcrumb for applicantsroot.
250    """
251    grok.context(IApplicantsRoot)
[7710]252    title = _(u'Applicants')
[6078]253
[5845]254class ApplicantsContainerBreadcrumb(Breadcrumb):
255    """A breadcrumb for applicantscontainers.
256    """
257    grok.context(IApplicantsContainer)
[6319]258
[10655]259
260class ApplicantsExportsBreadcrumb(Breadcrumb):
261    """A breadcrumb for exports.
262    """
263    grok.context(VirtualApplicantsExportJobContainer)
264    title = _(u'Applicant Data Exports')
265    target = None
266
[6153]267class ApplicantBreadcrumb(Breadcrumb):
268    """A breadcrumb for applicants.
269    """
270    grok.context(IApplicant)
[6319]271
[6153]272    @property
273    def title(self):
274        """Get a title for a context.
275        """
[7240]276        return self.context.application_number
[5828]277
[7250]278class OnlinePaymentBreadcrumb(Breadcrumb):
279    """A breadcrumb for payments.
280    """
281    grok.context(IApplicantOnlinePayment)
282
283    @property
284    def title(self):
285        return self.context.p_id
286
[8563]287class ApplicantsStatisticsPage(KofaDisplayFormPage):
288    """Some statistics about applicants in a container.
289    """
290    grok.context(IApplicantsContainer)
291    grok.name('statistics')
[8565]292    grok.require('waeup.viewApplicationStatistics')
[8563]293    grok.template('applicantcontainerstatistics')
294
295    @property
296    def label(self):
297        return "%s" % self.context.title
298
[7819]299class ApplicantsContainerPage(KofaDisplayFormPage):
[5830]300    """The standard view for regular applicant containers.
301    """
302    grok.context(IApplicantsContainer)
303    grok.name('index')
[6153]304    grok.require('waeup.Public')
[6029]305    grok.template('applicantscontainerpage')
[5850]306    pnav = 3
[6053]307
[9078]308    @property
309    def form_fields(self):
[12247]310        form_fields = grok.AutoFields(IApplicantsContainer).omit(
311            'title', 'description')
[9078]312        form_fields[
313            'startdate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
314        form_fields[
315            'enddate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
316        if self.request.principal.id == 'zope.anybody':
317            form_fields = form_fields.omit(
[10101]318                'code', 'prefix', 'year', 'mode', 'hidden',
[11870]319                'strict_deadline', 'application_category',
320                'application_slip_notice')
[9078]321        return form_fields
[6053]322
[5837]323    @property
[7708]324    def introduction(self):
[7833]325        # Here we know that the cookie has been set
326        lang = self.request.cookies.get('kofa.language')
[7708]327        html = self.context.description_dict.get(lang,'')
[8388]328        if html == '':
[7833]329            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7708]330            html = self.context.description_dict.get(portal_language,'')
[8388]331        return html
[7708]332
333    @property
[7467]334    def label(self):
[7493]335        return "%s" % self.context.title
[5837]336
[7819]337class ApplicantsContainerManageFormPage(KofaEditFormPage):
[5837]338    grok.context(IApplicantsContainer)
[5850]339    grok.name('manage')
[6107]340    grok.template('applicantscontainermanagepage')
[10625]341    form_fields = grok.AutoFields(IApplicantsContainer)
[7710]342    taboneactions = [_('Save'),_('Cancel')]
[8684]343    tabtwoactions = [_('Remove selected'),_('Cancel'),
[8314]344        _('Create students from selected')]
[7710]345    tabthreeactions1 = [_('Remove selected local roles')]
346    tabthreeactions2 = [_('Add local role')]
[5844]347    # Use friendlier date widget...
[7136]348    grok.require('waeup.manageApplication')
[13177]349    doclink = DOCLINK + '/applicants.html'
[5850]350
351    @property
352    def label(self):
[7710]353        return _('Manage applicants container')
[5850]354
[5845]355    pnav = 3
[5837]356
[8547]357    @property
358    def showApplicants(self):
[13217]359        if self.context.counts[1] < 1000:
[8547]360            return True
361        return False
362
[6184]363    def getLocalRoles(self):
364        roles = ILocalRolesAssignable(self.context)
365        return roles()
366
367    def getUsers(self):
368        """Get a list of all users.
369        """
370        for key, val in grok.getSite()['users'].items():
371            url = self.url(val)
372            yield(dict(url=url, name=key, val=val))
373
374    def getUsersWithLocalRoles(self):
375        return get_users_with_local_roles(self.context)
376
[7714]377    @action(_('Save'), style='primary')
[7489]378    def save(self, **data):
[9531]379        changed_fields = self.applyData(self.context, **data)
380        if changed_fields:
381            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
382        else:
383            changed_fields = []
[12247]384        description = getattr(self.context, 'description', None)
385        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
386        self.context.description_dict = html2dict(description, portal_language)
[7710]387        self.flash(_('Form has been saved.'))
[9531]388        fields_string = ' + '.join(changed_fields)
[12892]389        self.context.writeLogMessage(self, 'saved: %s' % fields_string)
[5837]390        return
[6078]391
[7710]392    @jsaction(_('Remove selected'))
[6105]393    def delApplicant(self, **data):
[6189]394        form = self.request.form
[9701]395        if 'val_id' in form:
[6189]396            child_id = form['val_id']
397        else:
[11254]398            self.flash(_('No applicant selected!'), type='warning')
399            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[6189]400            return
401        if not isinstance(child_id, list):
402            child_id = [child_id]
403        deleted = []
404        for id in child_id:
405            try:
406                del self.context[id]
407                deleted.append(id)
408            except:
[7710]409                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]410                    id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[6189]411        if len(deleted):
[7741]412            self.flash(_('Successfully removed: ${a}',
[7738]413                mapping = {'a':', '.join(deleted)}))
[11254]414        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[6189]415        return
[6105]416
[8314]417    @action(_('Create students from selected'))
418    def createStudents(self, **data):
419        form = self.request.form
[9701]420        if 'val_id' in form:
[8314]421            child_id = form['val_id']
422        else:
[11254]423            self.flash(_('No applicant selected!'), type='warning')
424            self.redirect(self.url(self.context, '@@manage')+'#tab2')
[8314]425            return
426        if not isinstance(child_id, list):
427            child_id = [child_id]
428        created = []
429        for id in child_id:
430            success, msg = self.context[id].createStudent(view=self)
431            if success:
432                created.append(id)
433        if len(created):
434            self.flash(_('${a} students successfully created.',
435                mapping = {'a': len(created)}))
436        else:
[11254]437            self.flash(_('No student could be created.'), type='warning')
438        self.redirect(self.url(self.context, u'@@manage')+'#tab2')
[8314]439        return
440
[7710]441    @action(_('Cancel'), validator=NullValidator)
[5837]442    def cancel(self, **data):
443        self.redirect(self.url(self.context))
444        return
[5886]445
[7710]446    @action(_('Add local role'), validator=NullValidator)
[6184]447    def addLocalRole(self, **data):
448        return add_local_role(self,3, **data)
[6105]449
[7710]450    @action(_('Remove selected local roles'))
[6184]451    def delLocalRoles(self, **data):
452        return del_local_roles(self,3,**data)
453
[7819]454class ApplicantAddFormPage(KofaAddFormPage):
[6622]455    """Add-form to add an applicant.
[6327]456    """
457    grok.context(IApplicantsContainer)
[7136]458    grok.require('waeup.manageApplication')
[6327]459    grok.name('addapplicant')
[7240]460    #grok.template('applicantaddpage')
461    form_fields = grok.AutoFields(IApplicant).select(
[7356]462        'firstname', 'middlename', 'lastname',
[7240]463        'email', 'phone')
[7714]464    label = _('Add applicant')
[6327]465    pnav = 3
[13177]466    doclink = DOCLINK + '/applicants.html'
[6327]467
[7714]468    @action(_('Create application record'))
[6327]469    def addApplicant(self, **data):
[8008]470        applicant = createObject(u'waeup.Applicant')
[7240]471        self.applyData(applicant, **data)
472        self.context.addApplicant(applicant)
[13073]473        self.flash(_('Application record created.'))
[7363]474        self.redirect(
475            self.url(self.context[applicant.application_number], 'index'))
[6327]476        return
477
[13217]478class ApplicantsContainerPrefillFormPage(KofaAddFormPage):
[13218]479    """Form to pre-fill applicants containers.
[13217]480    """
481    grok.context(IApplicantsContainer)
482    grok.require('waeup.manageApplication')
483    grok.name('prefill')
[13218]484    grok.template('prefillcontainer')
[13217]485    label = _('Pre-fill container')
486    pnav = 3
[13232]487    doclink = DOCLINK + '/applicants/browser.html#preparation-and-maintenance-of-applicants-containers'
[13217]488
489    def update(self):
490        if self.context.mode == 'update':
491            self.flash(_('Container must be in create mode to be pre-filled.'),
492                type='danger')
493            self.redirect(self.url(self.context))
494            return
495        super(ApplicantsContainerPrefillFormPage, self).update()
496        return
497
498    @action(_('Pre-fill now'), style='primary')
[13218]499    def addApplicants(self):
[13217]500        form = self.request.form
501        if 'number' in form and form['number']:
502            number = int(form['number'])
503        for i in range(number):
504            applicant = createObject(u'waeup.Applicant')
505            self.context.addApplicant(applicant)
506        self.flash(_('%s application records created.' % number))
507        self.context.writeLogMessage(self, '%s applicants created' % (number))
508        self.redirect(self.url(self.context, 'index'))
509        return
510
511    @action(_('Cancel'), validator=NullValidator)
512    def cancel(self, **data):
513        self.redirect(self.url(self.context))
514        return
515
[13218]516class ApplicantsContainerPurgeFormPage(KofaEditFormPage):
517    """Form to pre-fill applicants containers.
518    """
519    grok.context(IApplicantsContainer)
520    grok.require('waeup.manageApplication')
521    grok.name('purge')
522    grok.template('purgecontainer')
523    label = _('Purge container')
524    pnav = 3
[13232]525    doclink = DOCLINK + '/applicants/browser.html#preparation-and-maintenance-of-applicants-containers'
[13218]526
[13232]527    @action(_('Remove initialized records'),
528              tooltip=_('Don\'t use if application is in progress!'),
529              warning=_('Are you really sure?'),
530              style='primary')
[13218]531    def purgeInitialized(self):
532        form = self.request.form
533        purged = 0
534        keys = [key for key in self.context.keys()]
535        for key in keys:
536            if self.context[key].state == 'initialized':
537                del self.context[key]
538                purged += 1
539        self.flash(_('%s application records purged.' % purged))
540        self.context.writeLogMessage(self, '%s applicants purged' % (purged))
541        self.redirect(self.url(self.context, 'index'))
542        return
543
544    @action(_('Cancel'), validator=NullValidator)
545    def cancel(self, **data):
546        self.redirect(self.url(self.context))
547        return
548
[7819]549class ApplicantDisplayFormPage(KofaDisplayFormPage):
[8014]550    """A display view for applicant data.
551    """
[5273]552    grok.context(IApplicant)
553    grok.name('index')
[7113]554    grok.require('waeup.viewApplication')
[7200]555    grok.template('applicantdisplaypage')
[7714]556    label = _('Applicant')
[5843]557    pnav = 3
[8922]558    hide_hint = False
[5273]559
[8046]560    @property
[10831]561    def form_fields(self):
562        if self.context.special:
[11599]563            form_fields = grok.AutoFields(ISpecialApplicant).omit('locked')
[10831]564        else:
565            form_fields = grok.AutoFields(IApplicant).omit(
[10845]566                'locked', 'course_admitted', 'password', 'suspended')
[10831]567        return form_fields
568
569    @property
[10534]570    def target(self):
571        return getattr(self.context.__parent__, 'prefix', None)
572
573    @property
[8046]574    def separators(self):
575        return getUtility(IApplicantsUtils).SEPARATORS_DICT
576
[7063]577    def update(self):
578        self.passport_url = self.url(self.context, 'passport.jpg')
[7240]579        # Mark application as started if applicant logs in for the first time
[7272]580        usertype = getattr(self.request.principal, 'user_type', None)
581        if usertype == 'applicant' and \
582            IWorkflowState(self.context).getState() == INITIALIZED:
[7240]583            IWorkflowInfo(self.context).fireTransition('start')
[10895]584        if usertype == 'applicant' and self.context.state == 'created':
[10908]585            session = '%s/%s' % (self.context.__parent__.year,
586                                 self.context.__parent__.year+1)
587            title = getattr(grok.getSite()['configuration'], 'name', u'Sample University')
[10895]588            msg = _(
589                '\n <strong>Congratulations!</strong>' +
[10933]590                ' You have been offered provisional admission into the' +
[10908]591                ' ${c} Academic Session of ${d}.'
592                ' Your student record has been created for you.' +
593                ' Please, logout again and proceed to the' +
594                ' login page of the portal.'
[10895]595                ' Then enter your new student credentials:' +
596                ' user name= ${a}, password = ${b}.' +
597                ' Change your password when you have logged in.',
598                mapping = {
599                    'a':self.context.student_id,
[10908]600                    'b':self.context.application_number,
601                    'c':session,
602                    'd':title}
[10895]603                )
604            self.flash(msg)
[7063]605        return
606
[6196]607    @property
[7240]608    def hasPassword(self):
609        if self.context.password:
[7714]610            return _('set')
611        return _('unset')
[7240]612
613    @property
[6196]614    def label(self):
615        container_title = self.context.__parent__.title
[8096]616        return _('${a} <br /> Application Record ${b}', mapping = {
[7714]617            'a':container_title, 'b':self.context.application_number})
[6196]618
[7347]619    def getCourseAdmitted(self):
620        """Return link, title and code in html format to the certificate
621           admitted.
622        """
623        course_admitted = self.context.course_admitted
[7351]624        if getattr(course_admitted, '__parent__',None):
[7347]625            url = self.url(course_admitted)
626            title = course_admitted.title
627            code = course_admitted.code
628            return '<a href="%s">%s - %s</a>' %(url,code,title)
629        return ''
[6254]630
[7259]631class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
632    grok.context(IApplicant)
633    grok.name('base')
634    form_fields = grok.AutoFields(IApplicant).select(
[9141]635        'applicant_id','email', 'course1')
[7259]636
[7459]637class CreateStudentPage(UtilityView, grok.View):
[8636]638    """Create a student object from applicant data.
[7341]639    """
640    grok.context(IApplicant)
641    grok.name('createstudent')
642    grok.require('waeup.manageStudent')
643
644    def update(self):
[8314]645        msg = self.context.createStudent(view=self)[1]
[11254]646        self.flash(msg, type='warning')
[7341]647        self.redirect(self.url(self.context))
648        return
649
650    def render(self):
651        return
652
[8636]653class CreateAllStudentsPage(UtilityView, grok.View):
654    """Create all student objects from applicant data
[11874]655    in the root container or in a specific  applicants container only.
[11826]656    Only PortalManagers can do this.
[8636]657    """
[9900]658    #grok.context(IApplicantsContainer)
[8636]659    grok.name('createallstudents')
660    grok.require('waeup.managePortal')
661
662    def update(self):
663        cat = getUtility(ICatalog, name='applicants_catalog')
664        results = list(cat.searchResults(state=(ADMITTED, ADMITTED)))
665        created = []
[9900]666        container_only = False
667        applicants_root = grok.getSite()['applicants']
668        if isinstance(self.context, ApplicantsContainer):
669            container_only = True
[8636]670        for result in results:
[9900]671            if container_only and result.__parent__ is not self.context:
[8636]672                continue
673            success, msg = result.createStudent(view=self)
674            if success:
675                created.append(result.applicant_id)
676            else:
[12893]677                ob_class = self.__implemented__.__name__.replace(
678                    'waeup.kofa.','')
[9900]679                applicants_root.logger.info(
[8742]680                    '%s - %s - %s' % (ob_class, result.applicant_id, msg))
[8636]681        if len(created):
682            self.flash(_('${a} students successfully created.',
683                mapping = {'a': len(created)}))
684        else:
[11254]685            self.flash(_('No student could be created.'), type='warning')
[9900]686        self.redirect(self.url(self.context))
[8636]687        return
688
689    def render(self):
690        return
691
[8260]692class ApplicationFeePaymentAddPage(UtilityView, grok.View):
[7250]693    """ Page to add an online payment ticket
694    """
695    grok.context(IApplicant)
696    grok.name('addafp')
697    grok.require('waeup.payApplicant')
[8243]698    factory = u'waeup.ApplicantOnlinePayment'
[7250]699
[11726]700    @property
701    def custom_requirements(self):
702        return ''
703
[7250]704    def update(self):
[11726]705        # Additional requirements in custom packages.
706        if self.custom_requirements:
707            self.flash(
708                self.custom_requirements,
709                type='danger')
710            self.redirect(self.url(self.context))
[11727]711            return
[11575]712        if not self.context.special:
713            for key in self.context.keys():
714                ticket = self.context[key]
715                if ticket.p_state == 'paid':
716                      self.flash(
717                          _('This type of payment has already been made.'),
718                          type='warning')
719                      self.redirect(self.url(self.context))
720                      return
[8524]721        applicants_utils = getUtility(IApplicantsUtils)
722        container = self.context.__parent__
[8243]723        payment = createObject(self.factory)
[11254]724        failure = applicants_utils.setPaymentDetails(
[10831]725            container, payment, self.context)
[11254]726        if failure is not None:
[13123]727            self.flash(failure, type='danger')
[8524]728            self.redirect(self.url(self.context))
729            return
[7250]730        self.context[payment.p_id] = payment
[12893]731        self.context.writeLogMessage(self, 'added: %s' % payment.p_id)
[7714]732        self.flash(_('Payment ticket created.'))
[8280]733        self.redirect(self.url(payment))
[7250]734        return
735
736    def render(self):
737        return
738
739
[7819]740class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[7250]741    """ Page to view an online payment ticket
742    """
743    grok.context(IApplicantOnlinePayment)
744    grok.name('index')
745    grok.require('waeup.viewApplication')
[9984]746    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8170]747    form_fields[
748        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
749    form_fields[
750        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]751    pnav = 3
752
753    @property
754    def label(self):
[7714]755        return _('${a}: Online Payment Ticket ${b}', mapping = {
[8170]756            'a':self.context.__parent__.display_fullname,
757            'b':self.context.p_id})
[7250]758
[8420]759class OnlinePaymentApprovePage(UtilityView, grok.View):
760    """ Approval view
[7250]761    """
762    grok.context(IApplicantOnlinePayment)
[8420]763    grok.name('approve')
764    grok.require('waeup.managePortal')
[7250]765
766    def update(self):
[11580]767        flashtype, msg, log = self.context.approveApplicantPayment()
[8428]768        if log is not None:
[9771]769            applicant = self.context.__parent__
770            # Add log message to applicants.log
771            applicant.writeLogMessage(self, log)
772            # Add log message to payments.log
773            self.context.logger.info(
[9795]774                '%s,%s,%s,%s,%s,,,,,,' % (
[9771]775                applicant.applicant_id,
776                self.context.p_id, self.context.p_category,
777                self.context.amount_auth, self.context.r_code))
[11580]778        self.flash(msg, type=flashtype)
[7250]779        return
780
781    def render(self):
782        self.redirect(self.url(self.context, '@@index'))
783        return
784
[7459]785class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7250]786    """Deliver a PDF slip of the context.
787    """
788    grok.context(IApplicantOnlinePayment)
[8262]789    grok.name('payment_slip.pdf')
[7250]790    grok.require('waeup.viewApplication')
[9984]791    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8173]792    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
793    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]794    prefix = 'form'
[8258]795    note = None
[7250]796
797    @property
[7714]798    def title(self):
[7819]799        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]800        return translate(_('Payment Data'), 'waeup.kofa',
[7714]801            target_language=portal_language)
802
803    @property
[7250]804    def label(self):
[7819]805        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[8262]806        return translate(_('Online Payment Slip'),
[7811]807            'waeup.kofa', target_language=portal_language) \
[7714]808            + ' %s' % self.context.p_id
[7250]809
[11754]810    @property
811    def payment_slip_download_warning(self):
812        if self.context.__parent__.state != SUBMITTED:
813            return _('Please submit the application form before '
814                     'trying to download payment slips.')
815        return ''
816
[7250]817    def render(self):
[11754]818        if self.payment_slip_download_warning:
819            self.flash(self.payment_slip_download_warning, type='danger')
[11599]820            self.redirect(self.url(self.context))
821            return
[7259]822        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
[7250]823            self.request)
824        students_utils = getUtility(IStudentsUtils)
[8262]825        return students_utils.renderPDF(self,'payment_slip.pdf',
[8258]826            self.context.__parent__, applicantview, note=self.note)
[7250]827
[10571]828class ExportPDFPageApplicationSlip(UtilityView, grok.View):
[6358]829    """Deliver a PDF slip of the context.
830    """
831    grok.context(IApplicant)
832    grok.name('application_slip.pdf')
[7136]833    grok.require('waeup.viewApplication')
[6358]834    prefix = 'form'
835
[8666]836    def update(self):
[9051]837        if self.context.state in ('initialized', 'started', 'paid'):
[8666]838            self.flash(
[11254]839                _('Please pay and submit before trying to download '
840                  'the application slip.'), type='warning')
[8666]841            return self.redirect(self.url(self.context))
842        return
843
[6358]844    def render(self):
[12395]845        try:
846            pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
847                view=self)
848        except IOError:
849            self.flash(
850                _('Your image file is corrupted. '
851                  'Please replace.'), type='danger')
852            return self.redirect(self.url(self.context))
[6358]853        self.response.setHeader(
854            'Content-Type', 'application/pdf')
[7392]855        return pdfstream
[6358]856
[7081]857def handle_img_upload(upload, context, view):
[7063]858    """Handle upload of applicant image.
[7081]859
860    Returns `True` in case of success or `False`.
861
862    Please note that file pointer passed in (`upload`) most probably
863    points to end of file when leaving this function.
[7063]864    """
[7081]865    size = file_size(upload)
866    if size > MAX_UPLOAD_SIZE:
[11254]867        view.flash(_('Uploaded image is too big!'), type='danger')
[7081]868        return False
[7247]869    dummy, ext = os.path.splitext(upload.filename)
870    ext.lower()
871    if ext != '.jpg':
[11254]872        view.flash(_('jpg file extension expected.'), type='danger')
[7247]873        return False
[7081]874    upload.seek(0) # file pointer moved when determining size
[7063]875    store = getUtility(IExtFileStore)
876    file_id = IFileStoreNameChooser(context).chooseName()
877    store.createFile(file_id, upload)
[7081]878    return True
[7063]879
[7819]880class ApplicantManageFormPage(KofaEditFormPage):
[6196]881    """A full edit view for applicant data.
882    """
883    grok.context(IApplicant)
[7200]884    grok.name('manage')
[7136]885    grok.require('waeup.manageApplication')
[7200]886    grok.template('applicanteditpage')
[6322]887    manage_applications = True
[6196]888    pnav = 3
[12664]889    display_actions = [[_('Save'), _('Finally Submit')],
[7714]890        [_('Add online payment ticket'),_('Remove selected tickets')]]
[6196]891
[8046]892    @property
[10831]893    def form_fields(self):
894        if self.context.special:
[10845]895            form_fields = grok.AutoFields(ISpecialApplicant)
896            form_fields['applicant_id'].for_display = True
[10831]897        else:
898            form_fields = grok.AutoFields(IApplicant)
899            form_fields['student_id'].for_display = True
900            form_fields['applicant_id'].for_display = True
901        return form_fields
902
903    @property
[10534]904    def target(self):
905        return getattr(self.context.__parent__, 'prefix', None)
906
907    @property
[8046]908    def separators(self):
909        return getUtility(IApplicantsUtils).SEPARATORS_DICT
910
[11733]911    @property
912    def custom_upload_requirements(self):
913        return ''
914
[6196]915    def update(self):
[7200]916        super(ApplicantManageFormPage, self).update()
[6353]917        self.wf_info = IWorkflowInfo(self.context)
[7081]918        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
[10090]919        self.upload_success = None
[6598]920        upload = self.request.form.get('form.passport', None)
921        if upload:
[11733]922            if self.custom_upload_requirements:
923                self.flash(
924                    self.custom_upload_requirements,
925                    type='danger')
926                self.redirect(self.url(self.context))
927                return
[10090]928            # We got a fresh upload, upload_success is
929            # either True or False
930            self.upload_success = handle_img_upload(
[7084]931                upload, self.context, self)
[10090]932            if self.upload_success:
[10095]933                self.context.writeLogMessage(self, 'saved: passport')
[6196]934        return
935
936    @property
937    def label(self):
938        container_title = self.context.__parent__.title
[8096]939        return _('${a} <br /> Application Form ${b}', mapping = {
[7714]940            'a':container_title, 'b':self.context.application_number})
[6196]941
[6303]942    def getTransitions(self):
[6351]943        """Return a list of dicts of allowed transition ids and titles.
[6353]944
945        Each list entry provides keys ``name`` and ``title`` for
946        internal name and (human readable) title of a single
947        transition.
[6349]948        """
[8434]949        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
[11482]950            if not t[0] in ('pay', 'create')]
[7687]951        return [dict(name='', title=_('No transition'))] +[
[6355]952            dict(name=x, title=y) for x, y in allowed_transitions]
[6303]953
[7714]954    @action(_('Save'), style='primary')
[6196]955    def save(self, **data):
[7240]956        form = self.request.form
957        password = form.get('password', None)
958        password_ctl = form.get('control_password', None)
959        if password:
960            validator = getUtility(IPasswordValidator)
961            errors = validator.validate_password(password, password_ctl)
962            if errors:
[11254]963                self.flash( ' '.join(errors), type='danger')
[7240]964                return
[10090]965        if self.upload_success is False:  # False is not None!
966            # Error during image upload. Ignore other values.
967            return
[6475]968        changed_fields = self.applyData(self.context, **data)
[7199]969        # Turn list of lists into single list
970        if changed_fields:
971            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7240]972        else:
973            changed_fields = []
974        if password:
975            # Now we know that the form has no errors and can set password ...
976            IUserAccount(self.context).setPassword(password)
977            changed_fields.append('password')
[7199]978        fields_string = ' + '.join(changed_fields)
[7085]979        trans_id = form.get('transition', None)
980        if trans_id:
981            self.wf_info.fireTransition(trans_id)
[7714]982        self.flash(_('Form has been saved.'))
[6644]983        if fields_string:
[12892]984            self.context.writeLogMessage(self, 'saved: %s' % fields_string)
[6196]985        return
986
[7250]987    def unremovable(self, ticket):
[7330]988        return False
[7250]989
990    # This method is also used by the ApplicantEditFormPage
991    def delPaymentTickets(self, **data):
992        form = self.request.form
[9701]993        if 'val_id' in form:
[7250]994            child_id = form['val_id']
995        else:
[11254]996            self.flash(_('No payment selected.'), type='warning')
[7250]997            self.redirect(self.url(self.context))
998            return
999        if not isinstance(child_id, list):
1000            child_id = [child_id]
1001        deleted = []
1002        for id in child_id:
1003            # Applicants are not allowed to remove used payment tickets
1004            if not self.unremovable(self.context[id]):
1005                try:
1006                    del self.context[id]
1007                    deleted.append(id)
1008                except:
[7714]1009                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[11254]1010                      id, sys.exc_info()[0], sys.exc_info()[1]), type='danger')
[7250]1011        if len(deleted):
[7741]1012            self.flash(_('Successfully removed: ${a}',
[7738]1013                mapping = {'a':', '.join(deleted)}))
[8742]1014            self.context.writeLogMessage(
1015                self, 'removed: % s' % ', '.join(deleted))
[7250]1016        return
1017
[7252]1018    # We explicitely want the forms to be validated before payment tickets
1019    # can be created. If no validation is requested, use
[7459]1020    # 'validator=NullValidator' in the action directive
[11578]1021    @action(_('Add online payment ticket'), style='primary')
[7250]1022    def addPaymentTicket(self, **data):
1023        self.redirect(self.url(self.context, '@@addafp'))
[7252]1024        return
[7250]1025
[7714]1026    @jsaction(_('Remove selected tickets'))
[7250]1027    def removePaymentTickets(self, **data):
1028        self.delPaymentTickets(**data)
1029        self.redirect(self.url(self.context) + '/@@manage')
1030        return
1031
[10094]1032    # Not used in base package
1033    def file_exists(self, attr):
1034        file = getUtility(IExtFileStore).getFileByContext(
1035            self.context, attr=attr)
1036        if file:
1037            return True
1038        else:
1039            return False
1040
[7200]1041class ApplicantEditFormPage(ApplicantManageFormPage):
[5982]1042    """An applicant-centered edit view for applicant data.
1043    """
[6196]1044    grok.context(IApplicantEdit)
[5273]1045    grok.name('edit')
[6198]1046    grok.require('waeup.handleApplication')
[7200]1047    grok.template('applicanteditpage')
[6322]1048    manage_applications = False
[10358]1049    submit_state = PAID
[5484]1050
[7250]1051    @property
[10831]1052    def form_fields(self):
1053        if self.context.special:
[11657]1054            form_fields = grok.AutoFields(ISpecialApplicant).omit(
1055                'locked', 'suspended')
[10845]1056            form_fields['applicant_id'].for_display = True
[10831]1057        else:
1058            form_fields = grok.AutoFields(IApplicantEdit).omit(
1059                'locked', 'course_admitted', 'student_id',
[10845]1060                'suspended'
[10831]1061                )
1062            form_fields['applicant_id'].for_display = True
1063            form_fields['reg_number'].for_display = True
1064        return form_fields
1065
1066    @property
[7250]1067    def display_actions(self):
[8286]1068        state = IWorkflowState(self.context).getState()
[13100]1069        # If the form is unlocked, applicants are allowed to save the form
1070        # and remove unused tickets.
1071        actions = [[_('Save')], [_('Remove selected tickets')]]
1072        # Only in state started they can also add tickets.
[10358]1073        if state == STARTED:
[7714]1074            actions = [[_('Save')],
1075                [_('Add online payment ticket'),_('Remove selected tickets')]]
[13100]1076        # In state paid, they can submit the data and further add tickets
1077        # if the application is special.
[11599]1078        elif self.context.special and state == PAID:
[12664]1079            actions = [[_('Save'), _('Finally Submit')],
[11599]1080                [_('Add online payment ticket'),_('Remove selected tickets')]]
[8286]1081        elif state == PAID:
[12664]1082            actions = [[_('Save'), _('Finally Submit')],
[7714]1083                [_('Remove selected tickets')]]
[7250]1084        return actions
1085
[7330]1086    def unremovable(self, ticket):
[13100]1087        return ticket.r_code
[7330]1088
[7145]1089    def emit_lock_message(self):
[11254]1090        self.flash(_('The requested form is locked (read-only).'),
1091                   type='warning')
[5941]1092        self.redirect(self.url(self.context))
1093        return
[6078]1094
[5686]1095    def update(self):
[8665]1096        if self.context.locked or (
1097            self.context.__parent__.expired and
1098            self.context.__parent__.strict_deadline):
[7145]1099            self.emit_lock_message()
[5941]1100            return
[7200]1101        super(ApplicantEditFormPage, self).update()
[5686]1102        return
[5952]1103
[6196]1104    def dataNotComplete(self):
[7252]1105        store = getUtility(IExtFileStore)
1106        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
[7714]1107            return _('No passport picture uploaded.')
[6322]1108        if not self.request.form.get('confirm_passport', False):
[7714]1109            return _('Passport picture confirmation box not ticked.')
[6196]1110        return False
[5952]1111
[7252]1112    # We explicitely want the forms to be validated before payment tickets
1113    # can be created. If no validation is requested, use
[7459]1114    # 'validator=NullValidator' in the action directive
[11578]1115    @action(_('Add online payment ticket'), style='primary')
[7250]1116    def addPaymentTicket(self, **data):
1117        self.redirect(self.url(self.context, '@@addafp'))
[7252]1118        return
[7250]1119
[7714]1120    @jsaction(_('Remove selected tickets'))
[7250]1121    def removePaymentTickets(self, **data):
1122        self.delPaymentTickets(**data)
1123        self.redirect(self.url(self.context) + '/@@edit')
1124        return
1125
[7996]1126    @action(_('Save'), style='primary')
[5273]1127    def save(self, **data):
[10090]1128        if self.upload_success is False:  # False is not None!
1129            # Error during image upload. Ignore other values.
1130            return
[10219]1131        if data.get('course1', 1) == data.get('course2', 2):
[11254]1132            self.flash(_('1st and 2nd choice must be different.'),
1133                       type='warning')
[10210]1134            return
[5273]1135        self.applyData(self.context, **data)
[10210]1136        self.flash(_('Form has been saved.'))
[5273]1137        return
1138
[12664]1139    @action(_('Finally Submit'), warning=WARNING)
[5484]1140    def finalsubmit(self, **data):
[10090]1141        if self.upload_success is False:  # False is not None!
[7084]1142            return # error during image upload. Ignore other values
[6196]1143        if self.dataNotComplete():
[11254]1144            self.flash(self.dataNotComplete(), type='danger')
[5941]1145            return
[7252]1146        self.applyData(self.context, **data)
[8286]1147        state = IWorkflowState(self.context).getState()
[6322]1148        # This shouldn't happen, but the application officer
1149        # might have forgotten to lock the form after changing the state
[10358]1150        if state != self.submit_state:
[11254]1151            self.flash(_('The form cannot be submitted. Wrong state!'),
1152                       type='danger')
[6303]1153            return
1154        IWorkflowInfo(self.context).fireTransition('submit')
[8589]1155        # application_date is used in export files for sorting.
1156        # We can thus store utc.
[8194]1157        self.context.application_date = datetime.utcnow()
[7714]1158        self.flash(_('Form has been submitted.'))
[6196]1159        self.redirect(self.url(self.context))
[5273]1160        return
[5941]1161
[7063]1162class PassportImage(grok.View):
1163    """Renders the passport image for applicants.
1164    """
1165    grok.name('passport.jpg')
1166    grok.context(IApplicant)
[7113]1167    grok.require('waeup.viewApplication')
[7063]1168
1169    def render(self):
1170        # A filename chooser turns a context into a filename suitable
1171        # for file storage.
1172        image = getUtility(IExtFileStore).getFileByContext(self.context)
1173        self.response.setHeader(
1174            'Content-Type', 'image/jpeg')
1175        if image is None:
1176            # show placeholder image
[7089]1177            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
[7063]1178        return image
[7363]1179
[7819]1180class ApplicantRegistrationPage(KofaAddFormPage):
[7363]1181    """Captcha'd registration page for applicants.
1182    """
1183    grok.context(IApplicantsContainer)
1184    grok.name('register')
[7373]1185    grok.require('waeup.Anonymous')
[7363]1186    grok.template('applicantregister')
1187
[7368]1188    @property
[8033]1189    def form_fields(self):
1190        form_fields = None
[8128]1191        if self.context.mode == 'update':
1192            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
[11738]1193                'lastname','reg_number','email')
[8128]1194        else: #if self.context.mode == 'create':
[8033]1195            form_fields = grok.AutoFields(IApplicantEdit).select(
1196                'firstname', 'middlename', 'lastname', 'email', 'phone')
1197        return form_fields
1198
1199    @property
[7368]1200    def label(self):
[8078]1201        return _('Apply for ${a}',
[7714]1202            mapping = {'a':self.context.title})
[7368]1203
[7363]1204    def update(self):
[8665]1205        if self.context.expired:
[11254]1206            self.flash(_('Outside application period.'), type='warning')
[7368]1207            self.redirect(self.url(self.context))
1208            return
1209        # Handle captcha
[7363]1210        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1211        self.captcha_result = self.captcha.verify(self.request)
1212        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1213        return
1214
[8629]1215    def _redirect(self, email, password, applicant_id):
1216        # Forward only email to landing page in base package.
1217        self.redirect(self.url(self.context, 'registration_complete',
1218            data = dict(email=email)))
1219        return
1220
[9178]1221    @action(_('Send login credentials to email address'), style='primary')
[7363]1222    def register(self, **data):
1223        if not self.captcha_result.is_valid:
[8037]1224            # Captcha will display error messages automatically.
[7363]1225            # No need to flash something.
1226            return
[8033]1227        if self.context.mode == 'create':
[13217]1228            # Check if there are unused records in this container which
1229            # can be taken
1230            applicant = self.context.first_unused
1231            if applicant is None:
[13215]1232                # Add applicant
1233                applicant = createObject(u'waeup.Applicant')
1234                self.context.addApplicant(applicant)
[8033]1235            self.applyData(applicant, **data)
[8042]1236            applicant.reg_number = applicant.applicant_id
1237            notify(grok.ObjectModifiedEvent(applicant))
[8033]1238        elif self.context.mode == 'update':
1239            # Update applicant
[8037]1240            reg_number = data.get('reg_number','')
[11738]1241            lastname = data.get('lastname','')
[8033]1242            cat = getUtility(ICatalog, name='applicants_catalog')
1243            results = list(
1244                cat.searchResults(reg_number=(reg_number, reg_number)))
1245            if results:
1246                applicant = results[0]
[11738]1247                if getattr(applicant,'lastname',None) is None:
[11254]1248                    self.flash(_('An error occurred.'), type='danger')
[8037]1249                    return
[11738]1250                elif applicant.lastname.lower() != lastname.lower():
[8042]1251                    # Don't tell the truth here. Anonymous must not
[11738]1252                    # know that a record was found and only the lastname
[8042]1253                    # verification failed.
[13099]1254                    self.flash(
1255                        _('No application record found.'), type='warning')
[8037]1256                    return
[8627]1257                elif applicant.password is not None and \
1258                    applicant.state != INITIALIZED:
1259                    self.flash(_('Your password has already been set and used. '
[11254]1260                                 'Please proceed to the login page.'),
1261                               type='warning')
[8042]1262                    return
1263                # Store email address but nothing else.
[8033]1264                applicant.email = data['email']
[8042]1265                notify(grok.ObjectModifiedEvent(applicant))
[8033]1266            else:
[8042]1267                # No record found, this is the truth.
[11254]1268                self.flash(_('No application record found.'), type='warning')
[8033]1269                return
1270        else:
[8042]1271            # Does not happen but anyway ...
[8033]1272            return
[7819]1273        kofa_utils = getUtility(IKofaUtils)
[7811]1274        password = kofa_utils.genPassword()
[7380]1275        IUserAccount(applicant).setPassword(password)
[7365]1276        # Send email with credentials
[7399]1277        login_url = self.url(grok.getSite(), 'login')
[8853]1278        url_info = u'Login: %s' % login_url
[7714]1279        msg = _('You have successfully been registered for the')
[7811]1280        if kofa_utils.sendCredentials(IUserAccount(applicant),
[8853]1281            password, url_info, msg):
[8629]1282            email_sent = applicant.email
[7380]1283        else:
[8629]1284            email_sent = None
1285        self._redirect(email=email_sent, password=password,
1286            applicant_id=applicant.applicant_id)
[7380]1287        return
1288
[7819]1289class ApplicantRegistrationEmailSent(KofaPage):
[7380]1290    """Landing page after successful registration.
[8629]1291
[7380]1292    """
1293    grok.name('registration_complete')
1294    grok.require('waeup.Public')
1295    grok.template('applicantregemailsent')
[7714]1296    label = _('Your registration was successful.')
[7380]1297
[8629]1298    def update(self, email=None, applicant_id=None, password=None):
[7380]1299        self.email = email
[8629]1300        self.password = password
1301        self.applicant_id = applicant_id
[7380]1302        return
[10655]1303
1304class ExportJobContainerOverview(KofaPage):
1305    """Page that lists active applicant data export jobs and provides links
1306    to discard or download CSV files.
1307
1308    """
1309    grok.context(VirtualApplicantsExportJobContainer)
1310    grok.require('waeup.manageApplication')
1311    grok.name('index.html')
1312    grok.template('exportjobsindex')
[11254]1313    label = _('Data Exports')
[10655]1314    pnav = 3
1315
1316    def update(self, CREATE=None, DISCARD=None, job_id=None):
1317        if CREATE:
1318            self.redirect(self.url('@@start_export'))
1319            return
1320        if DISCARD and job_id:
1321            entry = self.context.entry_from_job_id(job_id)
1322            self.context.delete_export_entry(entry)
1323            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1324            self.context.logger.info(
1325                '%s - discarded: job_id=%s' % (ob_class, job_id))
1326            self.flash(_('Discarded export') + ' %s' % job_id)
1327        self.entries = doll_up(self, user=self.request.principal.id)
1328        return
1329
1330class ExportJobContainerJobStart(KofaPage):
1331    """Page that starts an applicants export job.
1332
1333    """
1334    grok.context(VirtualApplicantsExportJobContainer)
1335    grok.require('waeup.manageApplication')
1336    grok.name('start_export')
1337
1338    def update(self):
[13152]1339        utils = queryUtility(IKofaUtils)
1340        if not utils.expensive_actions_allowed():
1341            self.flash(_(
1342                "Currently, exporters cannot be started due to high "
1343                "system load. Please try again later."), type='danger')
1344            self.entries = doll_up(self, user=None)
1345            return
[10655]1346        exporter = 'applicants'
1347        container_code = self.context.__parent__.code
1348        job_id = self.context.start_export_job(exporter,
1349                                      self.request.principal.id,
1350                                      container=container_code)
1351
1352        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
1353        self.context.logger.info(
1354            '%s - exported: %s (%s), job_id=%s'
1355            % (ob_class, exporter, container_code, job_id))
1356        self.flash(_('Export started.'))
1357        self.redirect(self.url(self.context))
1358        return
1359
1360    def render(self):
1361        return
1362
1363class ExportJobContainerDownload(ExportCSVView):
1364    """Page that downloads a students export csv file.
1365
1366    """
1367    grok.context(VirtualApplicantsExportJobContainer)
[11253]1368    grok.require('waeup.manageApplication')
Note: See TracBrowser for help on using the repository browser.