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

Last change on this file since 13606 was 13429, checked in by Henrik Bettermann, 9 years ago

... also if record was found.

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