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

Last change on this file since 10389 was 10358, checked in by Henrik Bettermann, 12 years ago

For imostate we have to customize the workflow. Applicants do not pay.

  • Property svn:keywords set to Id
File size: 41.7 KB
RevLine 
[5273]1## $Id: browser.py 10358 2013-06-23 06:03:07Z 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
[7392]25from zope.component import getUtility, 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,
[8037]34    IApplicantRegisterUpdate
[7363]35    )
[9900]36from waeup.kofa.applicants.container import ApplicantsContainer
[8404]37from waeup.kofa.applicants.applicant import search
[8636]38from waeup.kofa.applicants.workflow import (
39    INITIALIZED, STARTED, PAID, SUBMITTED, ADMITTED)
[7811]40from waeup.kofa.browser import (
[9217]41#    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
[7363]42    DEFAULT_PASSPORT_IMAGE_PATH)
[9217]43from waeup.kofa.browser.layout import (
44    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage)
[7811]45from waeup.kofa.browser.interfaces import ICaptchaManager
46from waeup.kofa.browser.breadcrumbs import Breadcrumb
[8314]47from waeup.kofa.browser.resources import toggleall
[7811]48from waeup.kofa.browser.layout import (
[8550]49    NullValidator, jsaction, action, UtilityView, JSAction)
[7811]50from waeup.kofa.browser.pages import add_local_role, del_local_roles
51from waeup.kofa.browser.resources import datepicker, tabs, datatable, warning
52from waeup.kofa.interfaces import (
[7819]53    IKofaObject, ILocalRolesAssignable, IExtFileStore, IPDF,
54    IFileStoreNameChooser, IPasswordValidator, IUserAccount, IKofaUtils)
[7811]55from waeup.kofa.interfaces import MessageFactory as _
56from waeup.kofa.permissions import get_users_with_local_roles
57from waeup.kofa.students.interfaces import IStudentsUtils
[8186]58from waeup.kofa.utils.helpers import string_from_bytes, file_size, now
[8170]59from waeup.kofa.widgets.datewidget import (
60    FriendlyDateDisplayWidget, FriendlyDateDisplayWidget,
61    FriendlyDatetimeDisplayWidget)
[8365]62from waeup.kofa.widgets.htmlwidget import HTMLDisplayWidget
[5320]63
[7819]64grok.context(IKofaObject) # Make IKofaObject the default context
[5273]65
[8550]66class SubmitJSAction(JSAction):
67
68    msg = _('\'You can not edit your application records after final submission.'
69            ' You really want to submit?\'')
70
71class submitaction(grok.action):
72
73    def __call__(self, success):
74        action = SubmitJSAction(self.label, success=success, **self.options)
75        self.actions.append(action)
76        return action
77
[8388]78class ApplicantsRootPage(KofaDisplayFormPage):
[5822]79    grok.context(IApplicantsRoot)
80    grok.name('index')
[6153]81    grok.require('waeup.Public')
[8388]82    form_fields = grok.AutoFields(IApplicantsRoot)
83    form_fields['description'].custom_widget = HTMLDisplayWidget
[7710]84    label = _('Application Section')
[8404]85    search_button = _('Search')
[5843]86    pnav = 3
[6012]87
88    def update(self):
[6067]89        super(ApplicantsRootPage, self).update()
[6012]90        return
91
[8388]92    @property
93    def introduction(self):
94        # Here we know that the cookie has been set
95        lang = self.request.cookies.get('kofa.language')
96        html = self.context.description_dict.get(lang,'')
97        if html == '':
98            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
99            html = self.context.description_dict.get(portal_language,'')
100        return html
101
[10097]102    @property
103    def containers(self):
[10098]104        if self.layout.isAuthenticated():
105            return self.context.values()
[10097]106        return [value for value in self.context.values() if not value.hidden]
107
[8404]108class ApplicantsSearchPage(KofaPage):
109    grok.context(IApplicantsRoot)
110    grok.name('search')
111    grok.require('waeup.viewApplication')
112    label = _('Search applicants')
113    search_button = _('Search')
114    pnav = 3
115
116    def update(self, *args, **kw):
117        datatable.need()
118        form = self.request.form
119        self.results = []
120        if 'searchterm' in form and form['searchterm']:
121            self.searchterm = form['searchterm']
122            self.searchtype = form['searchtype']
123        elif 'old_searchterm' in form:
124            self.searchterm = form['old_searchterm']
125            self.searchtype = form['old_searchtype']
126        else:
127            if 'search' in form:
128                self.flash(_('Empty search string'))
129            return
130        self.results = search(query=self.searchterm,
131            searchtype=self.searchtype, view=self)
132        if not self.results:
133            self.flash(_('No applicant found.'))
134        return
135
[7819]136class ApplicantsRootManageFormPage(KofaEditFormPage):
[5828]137    grok.context(IApplicantsRoot)
138    grok.name('manage')
[6107]139    grok.template('applicantsrootmanagepage')
[8388]140    form_fields = grok.AutoFields(IApplicantsRoot)
[7710]141    label = _('Manage application section')
[5843]142    pnav = 3
[7136]143    grok.require('waeup.manageApplication')
[8388]144    taboneactions = [_('Save')]
145    tabtwoactions = [_('Add applicants container'), _('Remove selected')]
146    tabthreeactions1 = [_('Remove selected local roles')]
147    tabthreeactions2 = [_('Add local role')]
[7710]148    subunits = _('Applicants Containers')
[6078]149
[6069]150    def update(self):
151        tabs.need()
[6108]152        datatable.need()
[7330]153        warning.need()
[8388]154        self.tab1 = self.tab2 = self.tab3 = ''
155        qs = self.request.get('QUERY_STRING', '')
156        if not qs:
157            qs = 'tab1'
158        setattr(self, qs, 'active')
[6069]159        return super(ApplicantsRootManageFormPage, self).update()
[5828]160
[6184]161    def getLocalRoles(self):
162        roles = ILocalRolesAssignable(self.context)
163        return roles()
164
165    def getUsers(self):
166        """Get a list of all users.
167        """
168        for key, val in grok.getSite()['users'].items():
169            url = self.url(val)
170            yield(dict(url=url, name=key, val=val))
171
172    def getUsersWithLocalRoles(self):
173        return get_users_with_local_roles(self.context)
174
[7710]175    @jsaction(_('Remove selected'))
[6069]176    def delApplicantsContainers(self, **data):
177        form = self.request.form
[9701]178        if 'val_id' in form:
[8388]179            child_id = form['val_id']
180        else:
181            self.flash(_('No container selected!'))
182            self.redirect(self.url(self.context, '@@manage')+'?tab2')
183            return
[6069]184        if not isinstance(child_id, list):
185            child_id = [child_id]
186        deleted = []
187        for id in child_id:
188            try:
189                del self.context[id]
190                deleted.append(id)
191            except:
[7710]192                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[6069]193                        id, sys.exc_info()[0], sys.exc_info()[1]))
194        if len(deleted):
[7738]195            self.flash(_('Successfully removed: ${a}',
196                mapping = {'a':', '.join(deleted)}))
[8388]197        self.redirect(self.url(self.context, '@@manage')+'?tab2')
[6078]198        return
[5828]199
[7710]200    @action(_('Add applicants container'), validator=NullValidator)
[6069]201    def addApplicantsContainer(self, **data):
202        self.redirect(self.url(self.context, '@@add'))
[6078]203        return
204
[7710]205    @action(_('Add local role'), validator=NullValidator)
[6184]206    def addLocalRole(self, **data):
[7484]207        return add_local_role(self,3, **data)
[6184]208
[7710]209    @action(_('Remove selected local roles'))
[6184]210    def delLocalRoles(self, **data):
[7484]211        return del_local_roles(self,3,**data)
[6184]212
[8388]213    def _description(self):
214        view = ApplicantsRootPage(
215            self.context,self.request)
216        view.setUpWidgets()
217        return view.widgets['description']()
218
219    @action(_('Save'), style='primary')
220    def save(self, **data):
221        self.applyData(self.context, **data)
222        self.context.description_dict = self._description()
[8390]223        self.flash(_('Form has been saved.'))
[8388]224        return
225
[7819]226class ApplicantsContainerAddFormPage(KofaAddFormPage):
[5822]227    grok.context(IApplicantsRoot)
[7136]228    grok.require('waeup.manageApplication')
[5822]229    grok.name('add')
[6107]230    grok.template('applicantscontaineraddpage')
[7710]231    label = _('Add applicants container')
[5843]232    pnav = 3
[6078]233
[6103]234    form_fields = grok.AutoFields(
[7903]235        IApplicantsContainerAdd).omit('code').omit('title')
[6078]236
[6083]237    def update(self):
238        datepicker.need() # Enable jQuery datepicker in date fields.
239        return super(ApplicantsContainerAddFormPage, self).update()
240
[7710]241    @action(_('Add applicants container'))
[6069]242    def addApplicantsContainer(self, **data):
[6103]243        year = data['year']
244        code = u'%s%s' % (data['prefix'], year)
[9529]245        apptypes_dict = getUtility(IApplicantsUtils).APP_TYPES_DICT
246        title = apptypes_dict[data['prefix']][0]
[7685]247        title = u'%s %s/%s' % (title, year, year + 1)
[6087]248        if code in self.context.keys():
[6105]249            self.flash(
[7710]250                _('An applicants container for the same application type and entrance year exists already in the database.'))
[5822]251            return
252        # Add new applicants container...
[8009]253        container = createObject(u'waeup.ApplicantsContainer')
[6069]254        self.applyData(container, **data)
[6087]255        container.code = code
256        container.title = title
257        self.context[code] = container
[7710]258        self.flash(_('Added:') + ' "%s".' % code)
[7484]259        self.redirect(self.url(self.context, u'@@manage'))
[5822]260        return
[6078]261
[7710]262    @action(_('Cancel'), validator=NullValidator)
[6069]263    def cancel(self, **data):
[7484]264        self.redirect(self.url(self.context, '@@manage'))
[6078]265
[5845]266class ApplicantsRootBreadcrumb(Breadcrumb):
267    """A breadcrumb for applicantsroot.
268    """
269    grok.context(IApplicantsRoot)
[7710]270    title = _(u'Applicants')
[6078]271
[5845]272class ApplicantsContainerBreadcrumb(Breadcrumb):
273    """A breadcrumb for applicantscontainers.
274    """
275    grok.context(IApplicantsContainer)
[6319]276
[6153]277class ApplicantBreadcrumb(Breadcrumb):
278    """A breadcrumb for applicants.
279    """
280    grok.context(IApplicant)
[6319]281
[6153]282    @property
283    def title(self):
284        """Get a title for a context.
285        """
[7240]286        return self.context.application_number
[5828]287
[7250]288class OnlinePaymentBreadcrumb(Breadcrumb):
289    """A breadcrumb for payments.
290    """
291    grok.context(IApplicantOnlinePayment)
292
293    @property
294    def title(self):
295        return self.context.p_id
296
[8563]297class ApplicantsStatisticsPage(KofaDisplayFormPage):
298    """Some statistics about applicants in a container.
299    """
300    grok.context(IApplicantsContainer)
301    grok.name('statistics')
[8565]302    grok.require('waeup.viewApplicationStatistics')
[8563]303    grok.template('applicantcontainerstatistics')
304
305    @property
306    def label(self):
307        return "%s" % self.context.title
308
[7819]309class ApplicantsContainerPage(KofaDisplayFormPage):
[5830]310    """The standard view for regular applicant containers.
311    """
312    grok.context(IApplicantsContainer)
313    grok.name('index')
[6153]314    grok.require('waeup.Public')
[6029]315    grok.template('applicantscontainerpage')
[5850]316    pnav = 3
[6053]317
[9078]318    @property
319    def form_fields(self):
320        form_fields = grok.AutoFields(IApplicantsContainer).omit('title')
321        form_fields['description'].custom_widget = HTMLDisplayWidget
322        form_fields[
323            'startdate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
324        form_fields[
325            'enddate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
326        if self.request.principal.id == 'zope.anybody':
327            form_fields = form_fields.omit(
[10101]328                'code', 'prefix', 'year', 'mode', 'hidden',
[9078]329                'strict_deadline', 'application_category')
330        return form_fields
[6053]331
[5837]332    @property
[7708]333    def introduction(self):
[7833]334        # Here we know that the cookie has been set
335        lang = self.request.cookies.get('kofa.language')
[7708]336        html = self.context.description_dict.get(lang,'')
[8388]337        if html == '':
[7833]338            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7708]339            html = self.context.description_dict.get(portal_language,'')
[8388]340        return html
[7708]341
342    @property
[7467]343    def label(self):
[7493]344        return "%s" % self.context.title
[5837]345
[7819]346class ApplicantsContainerManageFormPage(KofaEditFormPage):
[5837]347    grok.context(IApplicantsContainer)
[5850]348    grok.name('manage')
[6107]349    grok.template('applicantscontainermanagepage')
[7903]350    form_fields = grok.AutoFields(IApplicantsContainer).omit('title')
[7710]351    taboneactions = [_('Save'),_('Cancel')]
[8684]352    tabtwoactions = [_('Remove selected'),_('Cancel'),
[8314]353        _('Create students from selected')]
[7710]354    tabthreeactions1 = [_('Remove selected local roles')]
355    tabthreeactions2 = [_('Add local role')]
[5844]356    # Use friendlier date widget...
[7136]357    grok.require('waeup.manageApplication')
[5850]358
359    @property
360    def label(self):
[7710]361        return _('Manage applicants container')
[5850]362
[5845]363    pnav = 3
[5837]364
[8547]365    @property
366    def showApplicants(self):
367        if len(self.context) < 5000:
368            return True
369        return False
370
[5837]371    def update(self):
[5850]372        datepicker.need() # Enable jQuery datepicker in date fields.
[5982]373        tabs.need()
[8314]374        toggleall.need()
[7484]375        self.tab1 = self.tab2 = self.tab3 = ''
376        qs = self.request.get('QUERY_STRING', '')
377        if not qs:
378            qs = 'tab1'
379        setattr(self, qs, 'active')
[7330]380        warning.need()
[6015]381        datatable.need()  # Enable jQurey datatables for contents listing
[6107]382        return super(ApplicantsContainerManageFormPage, self).update()
[5837]383
[6184]384    def getLocalRoles(self):
385        roles = ILocalRolesAssignable(self.context)
386        return roles()
387
388    def getUsers(self):
389        """Get a list of all users.
390        """
391        for key, val in grok.getSite()['users'].items():
392            url = self.url(val)
393            yield(dict(url=url, name=key, val=val))
394
395    def getUsersWithLocalRoles(self):
396        return get_users_with_local_roles(self.context)
397
[7708]398    def _description(self):
399        view = ApplicantsContainerPage(
400            self.context,self.request)
401        view.setUpWidgets()
402        return view.widgets['description']()
403
[7714]404    @action(_('Save'), style='primary')
[7489]405    def save(self, **data):
[9531]406        changed_fields = self.applyData(self.context, **data)
407        if changed_fields:
408            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
409        else:
410            changed_fields = []
[7708]411        self.context.description_dict = self._description()
[8562]412        # Always refresh title. So we can change titles
413        # if APP_TYPES_DICT has been edited.
[9529]414        apptypes_dict = getUtility(IApplicantsUtils).APP_TYPES_DICT
415        title = apptypes_dict[self.context.prefix][0]
[8562]416        self.context.title = u'%s %s/%s' % (
417            title, self.context.year, self.context.year + 1)
[7710]418        self.flash(_('Form has been saved.'))
[9531]419        fields_string = ' + '.join(changed_fields)
420        self.context.writeLogMessage(self, 'saved: % s' % fields_string)
[5837]421        return
[6078]422
[7710]423    @jsaction(_('Remove selected'))
[6105]424    def delApplicant(self, **data):
[6189]425        form = self.request.form
[9701]426        if 'val_id' in form:
[6189]427            child_id = form['val_id']
428        else:
[7710]429            self.flash(_('No applicant selected!'))
[7484]430            self.redirect(self.url(self.context, '@@manage')+'?tab2')
[6189]431            return
432        if not isinstance(child_id, list):
433            child_id = [child_id]
434        deleted = []
435        for id in child_id:
436            try:
437                del self.context[id]
438                deleted.append(id)
439            except:
[7710]440                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[6189]441                        id, sys.exc_info()[0], sys.exc_info()[1]))
442        if len(deleted):
[7741]443            self.flash(_('Successfully removed: ${a}',
[7738]444                mapping = {'a':', '.join(deleted)}))
[7484]445        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6189]446        return
[6105]447
[8314]448    @action(_('Create students from selected'))
449    def createStudents(self, **data):
450        form = self.request.form
[9701]451        if 'val_id' in form:
[8314]452            child_id = form['val_id']
453        else:
454            self.flash(_('No applicant selected!'))
455            self.redirect(self.url(self.context, '@@manage')+'?tab2')
456            return
457        if not isinstance(child_id, list):
458            child_id = [child_id]
459        created = []
460        for id in child_id:
461            success, msg = self.context[id].createStudent(view=self)
462            if success:
463                created.append(id)
464        if len(created):
465            self.flash(_('${a} students successfully created.',
466                mapping = {'a': len(created)}))
467        else:
468            self.flash(_('No student could be created.'))
469        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
470        return
471
[7710]472    @action(_('Cancel'), validator=NullValidator)
[5837]473    def cancel(self, **data):
474        self.redirect(self.url(self.context))
475        return
[5886]476
[7710]477    @action(_('Add local role'), validator=NullValidator)
[6184]478    def addLocalRole(self, **data):
479        return add_local_role(self,3, **data)
[6105]480
[7710]481    @action(_('Remove selected local roles'))
[6184]482    def delLocalRoles(self, **data):
483        return del_local_roles(self,3,**data)
484
[7819]485class ApplicantAddFormPage(KofaAddFormPage):
[6622]486    """Add-form to add an applicant.
[6327]487    """
488    grok.context(IApplicantsContainer)
[7136]489    grok.require('waeup.manageApplication')
[6327]490    grok.name('addapplicant')
[7240]491    #grok.template('applicantaddpage')
492    form_fields = grok.AutoFields(IApplicant).select(
[7356]493        'firstname', 'middlename', 'lastname',
[7240]494        'email', 'phone')
[7714]495    label = _('Add applicant')
[6327]496    pnav = 3
497
[7714]498    @action(_('Create application record'))
[6327]499    def addApplicant(self, **data):
[8008]500        applicant = createObject(u'waeup.Applicant')
[7240]501        self.applyData(applicant, **data)
502        self.context.addApplicant(applicant)
[7714]503        self.flash(_('Applicant record created.'))
[7363]504        self.redirect(
505            self.url(self.context[applicant.application_number], 'index'))
[6327]506        return
507
[7819]508class ApplicantDisplayFormPage(KofaDisplayFormPage):
[8014]509    """A display view for applicant data.
510    """
[5273]511    grok.context(IApplicant)
512    grok.name('index')
[7113]513    grok.require('waeup.viewApplication')
[7200]514    grok.template('applicantdisplaypage')
[6320]515    form_fields = grok.AutoFields(IApplicant).omit(
[8983]516        'locked', 'course_admitted', 'password', 'suspended')
[7714]517    label = _('Applicant')
[5843]518    pnav = 3
[8922]519    hide_hint = False
[5273]520
[8046]521    @property
[10221]522    def target(self):
523        return getattr(self.context.__parent__, 'prefix', None)
524
525    @property
[8046]526    def separators(self):
527        return getUtility(IApplicantsUtils).SEPARATORS_DICT
528
[7063]529    def update(self):
530        self.passport_url = self.url(self.context, 'passport.jpg')
[7240]531        # Mark application as started if applicant logs in for the first time
[7272]532        usertype = getattr(self.request.principal, 'user_type', None)
533        if usertype == 'applicant' and \
534            IWorkflowState(self.context).getState() == INITIALIZED:
[7240]535            IWorkflowInfo(self.context).fireTransition('start')
[7063]536        return
537
[6196]538    @property
[7240]539    def hasPassword(self):
540        if self.context.password:
[7714]541            return _('set')
542        return _('unset')
[7240]543
544    @property
[6196]545    def label(self):
546        container_title = self.context.__parent__.title
[8096]547        return _('${a} <br /> Application Record ${b}', mapping = {
[7714]548            'a':container_title, 'b':self.context.application_number})
[6196]549
[7347]550    def getCourseAdmitted(self):
551        """Return link, title and code in html format to the certificate
552           admitted.
553        """
554        course_admitted = self.context.course_admitted
[7351]555        if getattr(course_admitted, '__parent__',None):
[7347]556            url = self.url(course_admitted)
557            title = course_admitted.title
558            code = course_admitted.code
559            return '<a href="%s">%s - %s</a>' %(url,code,title)
560        return ''
[6254]561
[7259]562class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
563    grok.context(IApplicant)
564    grok.name('base')
565    form_fields = grok.AutoFields(IApplicant).select(
[9141]566        'applicant_id','email', 'course1')
[7259]567
[7459]568class CreateStudentPage(UtilityView, grok.View):
[8636]569    """Create a student object from applicant data.
[7341]570    """
571    grok.context(IApplicant)
572    grok.name('createstudent')
573    grok.require('waeup.manageStudent')
574
575    def update(self):
[8314]576        msg = self.context.createStudent(view=self)[1]
[7341]577        self.flash(msg)
578        self.redirect(self.url(self.context))
579        return
580
581    def render(self):
582        return
583
[8636]584class CreateAllStudentsPage(UtilityView, grok.View):
585    """Create all student objects from applicant data
586    in a container.
587
588    This is a hidden page, no link or button will
589    be provided and only PortalManagers can do this.
590    """
[9900]591    #grok.context(IApplicantsContainer)
[8636]592    grok.name('createallstudents')
593    grok.require('waeup.managePortal')
594
595    def update(self):
596        cat = getUtility(ICatalog, name='applicants_catalog')
597        results = list(cat.searchResults(state=(ADMITTED, ADMITTED)))
598        created = []
[9900]599        container_only = False
600        applicants_root = grok.getSite()['applicants']
601        if isinstance(self.context, ApplicantsContainer):
602            container_only = True
[8636]603        for result in results:
[9900]604            if container_only and result.__parent__ is not self.context:
[8636]605                continue
606            success, msg = result.createStudent(view=self)
607            if success:
608                created.append(result.applicant_id)
609            else:
610                ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
[9900]611                applicants_root.logger.info(
[8742]612                    '%s - %s - %s' % (ob_class, result.applicant_id, msg))
[8636]613        if len(created):
614            self.flash(_('${a} students successfully created.',
615                mapping = {'a': len(created)}))
616        else:
617            self.flash(_('No student could be created.'))
[9900]618        self.redirect(self.url(self.context))
[8636]619        return
620
621    def render(self):
622        return
623
[8260]624class ApplicationFeePaymentAddPage(UtilityView, grok.View):
[7250]625    """ Page to add an online payment ticket
626    """
627    grok.context(IApplicant)
628    grok.name('addafp')
629    grok.require('waeup.payApplicant')
[8243]630    factory = u'waeup.ApplicantOnlinePayment'
[7250]631
632    def update(self):
633        for key in self.context.keys():
634            ticket = self.context[key]
635            if ticket.p_state == 'paid':
636                  self.flash(
[7714]637                      _('This type of payment has already been made.'))
[7250]638                  self.redirect(self.url(self.context))
639                  return
[8524]640        applicants_utils = getUtility(IApplicantsUtils)
641        container = self.context.__parent__
[8243]642        payment = createObject(self.factory)
[8524]643        error = applicants_utils.setPaymentDetails(container, payment)
644        if error is not None:
645            self.flash(error)
646            self.redirect(self.url(self.context))
647            return
[7250]648        self.context[payment.p_id] = payment
[7714]649        self.flash(_('Payment ticket created.'))
[8280]650        self.redirect(self.url(payment))
[7250]651        return
652
653    def render(self):
654        return
655
656
[7819]657class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[7250]658    """ Page to view an online payment ticket
659    """
660    grok.context(IApplicantOnlinePayment)
661    grok.name('index')
662    grok.require('waeup.viewApplication')
[9984]663    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8170]664    form_fields[
665        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
666    form_fields[
667        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]668    pnav = 3
669
670    @property
671    def label(self):
[7714]672        return _('${a}: Online Payment Ticket ${b}', mapping = {
[8170]673            'a':self.context.__parent__.display_fullname,
674            'b':self.context.p_id})
[7250]675
[8420]676class OnlinePaymentApprovePage(UtilityView, grok.View):
677    """ Approval view
[7250]678    """
679    grok.context(IApplicantOnlinePayment)
[8420]680    grok.name('approve')
681    grok.require('waeup.managePortal')
[7250]682
683    def update(self):
[8428]684        success, msg, log = self.context.approveApplicantPayment()
685        if log is not None:
[9771]686            applicant = self.context.__parent__
687            # Add log message to applicants.log
688            applicant.writeLogMessage(self, log)
689            # Add log message to payments.log
690            self.context.logger.info(
[9795]691                '%s,%s,%s,%s,%s,,,,,,' % (
[9771]692                applicant.applicant_id,
693                self.context.p_id, self.context.p_category,
694                self.context.amount_auth, self.context.r_code))
[8422]695        self.flash(msg)
[7250]696        return
697
698    def render(self):
699        self.redirect(self.url(self.context, '@@index'))
700        return
701
[7459]702class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7250]703    """Deliver a PDF slip of the context.
704    """
705    grok.context(IApplicantOnlinePayment)
[8262]706    grok.name('payment_slip.pdf')
[7250]707    grok.require('waeup.viewApplication')
[9984]708    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8173]709    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
710    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]711    prefix = 'form'
[8258]712    note = None
[7250]713
714    @property
[7714]715    def title(self):
[7819]716        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]717        return translate(_('Payment Data'), 'waeup.kofa',
[7714]718            target_language=portal_language)
719
720    @property
[7250]721    def label(self):
[7819]722        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[8262]723        return translate(_('Online Payment Slip'),
[7811]724            'waeup.kofa', target_language=portal_language) \
[7714]725            + ' %s' % self.context.p_id
[7250]726
727    def render(self):
[8262]728        #if self.context.p_state != 'paid':
729        #    self.flash(_('Ticket not yet paid.'))
730        #    self.redirect(self.url(self.context))
731        #    return
[7259]732        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
[7250]733            self.request)
734        students_utils = getUtility(IStudentsUtils)
[8262]735        return students_utils.renderPDF(self,'payment_slip.pdf',
[8258]736            self.context.__parent__, applicantview, note=self.note)
[7250]737
[7459]738class ExportPDFPage(UtilityView, grok.View):
[6358]739    """Deliver a PDF slip of the context.
740    """
741    grok.context(IApplicant)
742    grok.name('application_slip.pdf')
[7136]743    grok.require('waeup.viewApplication')
[6358]744    prefix = 'form'
745
[8666]746    def update(self):
[9051]747        if self.context.state in ('initialized', 'started', 'paid'):
[8666]748            self.flash(
[9051]749                _('Please pay and submit before trying to download the application slip.'))
[8666]750            return self.redirect(self.url(self.context))
751        return
752
[6358]753    def render(self):
[7392]754        pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
755            view=self)
[6358]756        self.response.setHeader(
757            'Content-Type', 'application/pdf')
[7392]758        return pdfstream
[6358]759
[7081]760def handle_img_upload(upload, context, view):
[7063]761    """Handle upload of applicant image.
[7081]762
763    Returns `True` in case of success or `False`.
764
765    Please note that file pointer passed in (`upload`) most probably
766    points to end of file when leaving this function.
[7063]767    """
[7081]768    size = file_size(upload)
769    if size > MAX_UPLOAD_SIZE:
[7714]770        view.flash(_('Uploaded image is too big!'))
[7081]771        return False
[7247]772    dummy, ext = os.path.splitext(upload.filename)
773    ext.lower()
774    if ext != '.jpg':
[7714]775        view.flash(_('jpg file extension expected.'))
[7247]776        return False
[7081]777    upload.seek(0) # file pointer moved when determining size
[7063]778    store = getUtility(IExtFileStore)
779    file_id = IFileStoreNameChooser(context).chooseName()
780    store.createFile(file_id, upload)
[7081]781    return True
[7063]782
[7819]783class ApplicantManageFormPage(KofaEditFormPage):
[6196]784    """A full edit view for applicant data.
785    """
786    grok.context(IApplicant)
[7200]787    grok.name('manage')
[7136]788    grok.require('waeup.manageApplication')
[6476]789    form_fields = grok.AutoFields(IApplicant)
[7351]790    form_fields['student_id'].for_display = True
[7378]791    form_fields['applicant_id'].for_display = True
[7200]792    grok.template('applicanteditpage')
[6322]793    manage_applications = True
[6196]794    pnav = 3
[7714]795    display_actions = [[_('Save'), _('Final Submit')],
796        [_('Add online payment ticket'),_('Remove selected tickets')]]
[6196]797
[8046]798    @property
[10221]799    def target(self):
800        return getattr(self.context.__parent__, 'prefix', None)
801
802    @property
[8046]803    def separators(self):
804        return getUtility(IApplicantsUtils).SEPARATORS_DICT
805
[6196]806    def update(self):
807        datepicker.need() # Enable jQuery datepicker in date fields.
[7330]808        warning.need()
[7200]809        super(ApplicantManageFormPage, self).update()
[6353]810        self.wf_info = IWorkflowInfo(self.context)
[7081]811        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
[10090]812        self.upload_success = None
[6598]813        upload = self.request.form.get('form.passport', None)
814        if upload:
[10090]815            # We got a fresh upload, upload_success is
816            # either True or False
817            self.upload_success = handle_img_upload(
[7084]818                upload, self.context, self)
[10090]819            if self.upload_success:
[10095]820                self.context.writeLogMessage(self, 'saved: passport')
[6196]821        return
822
823    @property
824    def label(self):
825        container_title = self.context.__parent__.title
[8096]826        return _('${a} <br /> Application Form ${b}', mapping = {
[7714]827            'a':container_title, 'b':self.context.application_number})
[6196]828
[6303]829    def getTransitions(self):
[6351]830        """Return a list of dicts of allowed transition ids and titles.
[6353]831
832        Each list entry provides keys ``name`` and ``title`` for
833        internal name and (human readable) title of a single
834        transition.
[6349]835        """
[8434]836        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
837            if not t[0] == 'pay']
[7687]838        return [dict(name='', title=_('No transition'))] +[
[6355]839            dict(name=x, title=y) for x, y in allowed_transitions]
[6303]840
[7714]841    @action(_('Save'), style='primary')
[6196]842    def save(self, **data):
[7240]843        form = self.request.form
844        password = form.get('password', None)
845        password_ctl = form.get('control_password', None)
846        if password:
847            validator = getUtility(IPasswordValidator)
848            errors = validator.validate_password(password, password_ctl)
849            if errors:
850                self.flash( ' '.join(errors))
851                return
[10090]852        if self.upload_success is False:  # False is not None!
853            # Error during image upload. Ignore other values.
854            return
[6475]855        changed_fields = self.applyData(self.context, **data)
[7199]856        # Turn list of lists into single list
857        if changed_fields:
858            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7240]859        else:
860            changed_fields = []
861        if password:
862            # Now we know that the form has no errors and can set password ...
863            IUserAccount(self.context).setPassword(password)
864            changed_fields.append('password')
[7199]865        fields_string = ' + '.join(changed_fields)
[7085]866        trans_id = form.get('transition', None)
867        if trans_id:
868            self.wf_info.fireTransition(trans_id)
[7714]869        self.flash(_('Form has been saved.'))
[6644]870        if fields_string:
[8742]871            self.context.writeLogMessage(self, 'saved: % s' % fields_string)
[6196]872        return
873
[7250]874    def unremovable(self, ticket):
[7330]875        return False
[7250]876
877    # This method is also used by the ApplicantEditFormPage
878    def delPaymentTickets(self, **data):
879        form = self.request.form
[9701]880        if 'val_id' in form:
[7250]881            child_id = form['val_id']
882        else:
[7714]883            self.flash(_('No payment selected.'))
[7250]884            self.redirect(self.url(self.context))
885            return
886        if not isinstance(child_id, list):
887            child_id = [child_id]
888        deleted = []
889        for id in child_id:
890            # Applicants are not allowed to remove used payment tickets
891            if not self.unremovable(self.context[id]):
892                try:
893                    del self.context[id]
894                    deleted.append(id)
895                except:
[7714]896                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[7250]897                            id, sys.exc_info()[0], sys.exc_info()[1]))
898        if len(deleted):
[7741]899            self.flash(_('Successfully removed: ${a}',
[7738]900                mapping = {'a':', '.join(deleted)}))
[8742]901            self.context.writeLogMessage(
902                self, 'removed: % s' % ', '.join(deleted))
[7250]903        return
904
[7252]905    # We explicitely want the forms to be validated before payment tickets
906    # can be created. If no validation is requested, use
[7459]907    # 'validator=NullValidator' in the action directive
[7714]908    @action(_('Add online payment ticket'))
[7250]909    def addPaymentTicket(self, **data):
910        self.redirect(self.url(self.context, '@@addafp'))
[7252]911        return
[7250]912
[7714]913    @jsaction(_('Remove selected tickets'))
[7250]914    def removePaymentTickets(self, **data):
915        self.delPaymentTickets(**data)
916        self.redirect(self.url(self.context) + '/@@manage')
917        return
918
[10094]919    # Not used in base package
920    def file_exists(self, attr):
921        file = getUtility(IExtFileStore).getFileByContext(
922            self.context, attr=attr)
923        if file:
924            return True
925        else:
926            return False
927
[7200]928class ApplicantEditFormPage(ApplicantManageFormPage):
[5982]929    """An applicant-centered edit view for applicant data.
930    """
[6196]931    grok.context(IApplicantEdit)
[5273]932    grok.name('edit')
[6198]933    grok.require('waeup.handleApplication')
[6459]934    form_fields = grok.AutoFields(IApplicantEdit).omit(
[6476]935        'locked', 'course_admitted', 'student_id',
[9047]936        'suspended'
[6459]937        )
[7459]938    form_fields['applicant_id'].for_display = True
[8039]939    form_fields['reg_number'].for_display = True
[7200]940    grok.template('applicanteditpage')
[6322]941    manage_applications = False
[10358]942    submit_state = PAID
[5484]943
[7250]944    @property
945    def display_actions(self):
[8286]946        state = IWorkflowState(self.context).getState()
[10358]947        actions = [[],[]]
948        if state == STARTED:
[7714]949            actions = [[_('Save')],
950                [_('Add online payment ticket'),_('Remove selected tickets')]]
[8286]951        elif state == PAID:
[7714]952            actions = [[_('Save'), _('Final Submit')],
953                [_('Remove selected tickets')]]
[7250]954        return actions
955
[7330]956    def unremovable(self, ticket):
[8286]957        state = IWorkflowState(self.context).getState()
958        return ticket.r_code or state in (INITIALIZED, SUBMITTED)
[7330]959
[7145]960    def emit_lock_message(self):
[7714]961        self.flash(_('The requested form is locked (read-only).'))
[5941]962        self.redirect(self.url(self.context))
963        return
[6078]964
[5686]965    def update(self):
[8665]966        if self.context.locked or (
967            self.context.__parent__.expired and
968            self.context.__parent__.strict_deadline):
[7145]969            self.emit_lock_message()
[5941]970            return
[7200]971        super(ApplicantEditFormPage, self).update()
[5686]972        return
[5952]973
[6196]974    def dataNotComplete(self):
[7252]975        store = getUtility(IExtFileStore)
976        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
[7714]977            return _('No passport picture uploaded.')
[6322]978        if not self.request.form.get('confirm_passport', False):
[7714]979            return _('Passport picture confirmation box not ticked.')
[6196]980        return False
[5952]981
[7252]982    # We explicitely want the forms to be validated before payment tickets
983    # can be created. If no validation is requested, use
[7459]984    # 'validator=NullValidator' in the action directive
[7714]985    @action(_('Add online payment ticket'))
[7250]986    def addPaymentTicket(self, **data):
987        self.redirect(self.url(self.context, '@@addafp'))
[7252]988        return
[7250]989
[7714]990    @jsaction(_('Remove selected tickets'))
[7250]991    def removePaymentTickets(self, **data):
992        self.delPaymentTickets(**data)
993        self.redirect(self.url(self.context) + '/@@edit')
994        return
995
[7996]996    @action(_('Save'), style='primary')
[5273]997    def save(self, **data):
[10090]998        if self.upload_success is False:  # False is not None!
999            # Error during image upload. Ignore other values.
1000            return
[10219]1001        if data.get('course1', 1) == data.get('course2', 2):
[10210]1002            self.flash(_('1st and 2nd choice must be different.'))
1003            return
[5273]1004        self.applyData(self.context, **data)
[10210]1005        self.flash(_('Form has been saved.'))
[5273]1006        return
1007
[8550]1008    @submitaction(_('Final Submit'))
[5484]1009    def finalsubmit(self, **data):
[10090]1010        if self.upload_success is False:  # False is not None!
[7084]1011            return # error during image upload. Ignore other values
[6196]1012        if self.dataNotComplete():
1013            self.flash(self.dataNotComplete())
[5941]1014            return
[7252]1015        self.applyData(self.context, **data)
[8286]1016        state = IWorkflowState(self.context).getState()
[6322]1017        # This shouldn't happen, but the application officer
1018        # might have forgotten to lock the form after changing the state
[10358]1019        if state != self.submit_state:
[8589]1020            self.flash(_('The form cannot be submitted. Wrong state!'))
[6303]1021            return
1022        IWorkflowInfo(self.context).fireTransition('submit')
[8589]1023        # application_date is used in export files for sorting.
1024        # We can thus store utc.
[8194]1025        self.context.application_date = datetime.utcnow()
[7714]1026        self.flash(_('Form has been submitted.'))
[6196]1027        self.redirect(self.url(self.context))
[5273]1028        return
[5941]1029
[7063]1030class PassportImage(grok.View):
1031    """Renders the passport image for applicants.
1032    """
1033    grok.name('passport.jpg')
1034    grok.context(IApplicant)
[7113]1035    grok.require('waeup.viewApplication')
[7063]1036
1037    def render(self):
1038        # A filename chooser turns a context into a filename suitable
1039        # for file storage.
1040        image = getUtility(IExtFileStore).getFileByContext(self.context)
1041        self.response.setHeader(
1042            'Content-Type', 'image/jpeg')
1043        if image is None:
1044            # show placeholder image
[7089]1045            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
[7063]1046        return image
[7363]1047
[7819]1048class ApplicantRegistrationPage(KofaAddFormPage):
[7363]1049    """Captcha'd registration page for applicants.
1050    """
1051    grok.context(IApplicantsContainer)
1052    grok.name('register')
[7373]1053    grok.require('waeup.Anonymous')
[7363]1054    grok.template('applicantregister')
1055
[7368]1056    @property
[8033]1057    def form_fields(self):
1058        form_fields = None
[8128]1059        if self.context.mode == 'update':
1060            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
1061                'firstname','reg_number','email')
1062        else: #if self.context.mode == 'create':
[8033]1063            form_fields = grok.AutoFields(IApplicantEdit).select(
1064                'firstname', 'middlename', 'lastname', 'email', 'phone')
1065        return form_fields
1066
1067    @property
[7368]1068    def label(self):
[8078]1069        return _('Apply for ${a}',
[7714]1070            mapping = {'a':self.context.title})
[7368]1071
[7363]1072    def update(self):
[8665]1073        if self.context.expired:
1074            self.flash(_('Outside application period.'))
[7368]1075            self.redirect(self.url(self.context))
1076            return
1077        # Handle captcha
[7363]1078        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1079        self.captcha_result = self.captcha.verify(self.request)
1080        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1081        return
1082
[8629]1083    def _redirect(self, email, password, applicant_id):
1084        # Forward only email to landing page in base package.
1085        self.redirect(self.url(self.context, 'registration_complete',
1086            data = dict(email=email)))
1087        return
1088
[9178]1089    @action(_('Send login credentials to email address'), style='primary')
[7363]1090    def register(self, **data):
1091        if not self.captcha_result.is_valid:
[8037]1092            # Captcha will display error messages automatically.
[7363]1093            # No need to flash something.
1094            return
[8033]1095        if self.context.mode == 'create':
1096            # Add applicant
1097            applicant = createObject(u'waeup.Applicant')
1098            self.applyData(applicant, **data)
1099            self.context.addApplicant(applicant)
[8042]1100            applicant.reg_number = applicant.applicant_id
1101            notify(grok.ObjectModifiedEvent(applicant))
[8033]1102        elif self.context.mode == 'update':
1103            # Update applicant
[8037]1104            reg_number = data.get('reg_number','')
1105            firstname = data.get('firstname','')
[8033]1106            cat = getUtility(ICatalog, name='applicants_catalog')
1107            results = list(
1108                cat.searchResults(reg_number=(reg_number, reg_number)))
1109            if results:
1110                applicant = results[0]
[8042]1111                if getattr(applicant,'firstname',None) is None:
[8037]1112                    self.flash(_('An error occurred.'))
1113                    return
1114                elif applicant.firstname.lower() != firstname.lower():
[8042]1115                    # Don't tell the truth here. Anonymous must not
1116                    # know that a record was found and only the firstname
1117                    # verification failed.
[8037]1118                    self.flash(_('No application record found.'))
1119                    return
[8627]1120                elif applicant.password is not None and \
1121                    applicant.state != INITIALIZED:
1122                    self.flash(_('Your password has already been set and used. '
[8042]1123                                 'Please proceed to the login page.'))
1124                    return
1125                # Store email address but nothing else.
[8033]1126                applicant.email = data['email']
[8042]1127                notify(grok.ObjectModifiedEvent(applicant))
[8033]1128            else:
[8042]1129                # No record found, this is the truth.
[8033]1130                self.flash(_('No application record found.'))
1131                return
1132        else:
[8042]1133            # Does not happen but anyway ...
[8033]1134            return
[7819]1135        kofa_utils = getUtility(IKofaUtils)
[7811]1136        password = kofa_utils.genPassword()
[7380]1137        IUserAccount(applicant).setPassword(password)
[7365]1138        # Send email with credentials
[7399]1139        login_url = self.url(grok.getSite(), 'login')
[8853]1140        url_info = u'Login: %s' % login_url
[7714]1141        msg = _('You have successfully been registered for the')
[7811]1142        if kofa_utils.sendCredentials(IUserAccount(applicant),
[8853]1143            password, url_info, msg):
[8629]1144            email_sent = applicant.email
[7380]1145        else:
[8629]1146            email_sent = None
1147        self._redirect(email=email_sent, password=password,
1148            applicant_id=applicant.applicant_id)
[7380]1149        return
1150
[7819]1151class ApplicantRegistrationEmailSent(KofaPage):
[7380]1152    """Landing page after successful registration.
[8629]1153
[7380]1154    """
1155    grok.name('registration_complete')
1156    grok.require('waeup.Public')
1157    grok.template('applicantregemailsent')
[7714]1158    label = _('Your registration was successful.')
[7380]1159
[8629]1160    def update(self, email=None, applicant_id=None, password=None):
[7380]1161        self.email = email
[8629]1162        self.password = password
1163        self.applicant_id = applicant_id
[7380]1164        return
Note: See TracBrowser for help on using the repository browser.