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

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

This is the correct way to hide the hidden attribute.

  • Property svn:keywords set to Id
File size: 41.4 KB
RevLine 
[5273]1## $Id: browser.py 10101 2013-04-24 12:09:47Z 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
522    def separators(self):
523        return getUtility(IApplicantsUtils).SEPARATORS_DICT
524
[7063]525    def update(self):
526        self.passport_url = self.url(self.context, 'passport.jpg')
[7240]527        # Mark application as started if applicant logs in for the first time
[7272]528        usertype = getattr(self.request.principal, 'user_type', None)
529        if usertype == 'applicant' and \
530            IWorkflowState(self.context).getState() == INITIALIZED:
[7240]531            IWorkflowInfo(self.context).fireTransition('start')
[7063]532        return
533
[6196]534    @property
[7240]535    def hasPassword(self):
536        if self.context.password:
[7714]537            return _('set')
538        return _('unset')
[7240]539
540    @property
[6196]541    def label(self):
542        container_title = self.context.__parent__.title
[8096]543        return _('${a} <br /> Application Record ${b}', mapping = {
[7714]544            'a':container_title, 'b':self.context.application_number})
[6196]545
[7347]546    def getCourseAdmitted(self):
547        """Return link, title and code in html format to the certificate
548           admitted.
549        """
550        course_admitted = self.context.course_admitted
[7351]551        if getattr(course_admitted, '__parent__',None):
[7347]552            url = self.url(course_admitted)
553            title = course_admitted.title
554            code = course_admitted.code
555            return '<a href="%s">%s - %s</a>' %(url,code,title)
556        return ''
[6254]557
[7259]558class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
559    grok.context(IApplicant)
560    grok.name('base')
561    form_fields = grok.AutoFields(IApplicant).select(
[9141]562        'applicant_id','email', 'course1')
[7259]563
[7459]564class CreateStudentPage(UtilityView, grok.View):
[8636]565    """Create a student object from applicant data.
[7341]566    """
567    grok.context(IApplicant)
568    grok.name('createstudent')
569    grok.require('waeup.manageStudent')
570
571    def update(self):
[8314]572        msg = self.context.createStudent(view=self)[1]
[7341]573        self.flash(msg)
574        self.redirect(self.url(self.context))
575        return
576
577    def render(self):
578        return
579
[8636]580class CreateAllStudentsPage(UtilityView, grok.View):
581    """Create all student objects from applicant data
582    in a container.
583
584    This is a hidden page, no link or button will
585    be provided and only PortalManagers can do this.
586    """
[9900]587    #grok.context(IApplicantsContainer)
[8636]588    grok.name('createallstudents')
589    grok.require('waeup.managePortal')
590
591    def update(self):
592        cat = getUtility(ICatalog, name='applicants_catalog')
593        results = list(cat.searchResults(state=(ADMITTED, ADMITTED)))
594        created = []
[9900]595        container_only = False
596        applicants_root = grok.getSite()['applicants']
597        if isinstance(self.context, ApplicantsContainer):
598            container_only = True
[8636]599        for result in results:
[9900]600            if container_only and result.__parent__ is not self.context:
[8636]601                continue
602            success, msg = result.createStudent(view=self)
603            if success:
604                created.append(result.applicant_id)
605            else:
606                ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
[9900]607                applicants_root.logger.info(
[8742]608                    '%s - %s - %s' % (ob_class, result.applicant_id, msg))
[8636]609        if len(created):
610            self.flash(_('${a} students successfully created.',
611                mapping = {'a': len(created)}))
612        else:
613            self.flash(_('No student could be created.'))
[9900]614        self.redirect(self.url(self.context))
[8636]615        return
616
617    def render(self):
618        return
619
[8260]620class ApplicationFeePaymentAddPage(UtilityView, grok.View):
[7250]621    """ Page to add an online payment ticket
622    """
623    grok.context(IApplicant)
624    grok.name('addafp')
625    grok.require('waeup.payApplicant')
[8243]626    factory = u'waeup.ApplicantOnlinePayment'
[7250]627
628    def update(self):
629        for key in self.context.keys():
630            ticket = self.context[key]
631            if ticket.p_state == 'paid':
632                  self.flash(
[7714]633                      _('This type of payment has already been made.'))
[7250]634                  self.redirect(self.url(self.context))
635                  return
[8524]636        applicants_utils = getUtility(IApplicantsUtils)
637        container = self.context.__parent__
[8243]638        payment = createObject(self.factory)
[8524]639        error = applicants_utils.setPaymentDetails(container, payment)
640        if error is not None:
641            self.flash(error)
642            self.redirect(self.url(self.context))
643            return
[7250]644        self.context[payment.p_id] = payment
[7714]645        self.flash(_('Payment ticket created.'))
[8280]646        self.redirect(self.url(payment))
[7250]647        return
648
649    def render(self):
650        return
651
652
[7819]653class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
[7250]654    """ Page to view an online payment ticket
655    """
656    grok.context(IApplicantOnlinePayment)
657    grok.name('index')
658    grok.require('waeup.viewApplication')
[9984]659    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8170]660    form_fields[
661        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
662    form_fields[
663        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]664    pnav = 3
665
666    @property
667    def label(self):
[7714]668        return _('${a}: Online Payment Ticket ${b}', mapping = {
[8170]669            'a':self.context.__parent__.display_fullname,
670            'b':self.context.p_id})
[7250]671
[8420]672class OnlinePaymentApprovePage(UtilityView, grok.View):
673    """ Approval view
[7250]674    """
675    grok.context(IApplicantOnlinePayment)
[8420]676    grok.name('approve')
677    grok.require('waeup.managePortal')
[7250]678
679    def update(self):
[8428]680        success, msg, log = self.context.approveApplicantPayment()
681        if log is not None:
[9771]682            applicant = self.context.__parent__
683            # Add log message to applicants.log
684            applicant.writeLogMessage(self, log)
685            # Add log message to payments.log
686            self.context.logger.info(
[9795]687                '%s,%s,%s,%s,%s,,,,,,' % (
[9771]688                applicant.applicant_id,
689                self.context.p_id, self.context.p_category,
690                self.context.amount_auth, self.context.r_code))
[8422]691        self.flash(msg)
[7250]692        return
693
694    def render(self):
695        self.redirect(self.url(self.context, '@@index'))
696        return
697
[7459]698class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7250]699    """Deliver a PDF slip of the context.
700    """
701    grok.context(IApplicantOnlinePayment)
[8262]702    grok.name('payment_slip.pdf')
[7250]703    grok.require('waeup.viewApplication')
[9984]704    form_fields = grok.AutoFields(IApplicantOnlinePayment).omit('p_item')
[8173]705    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
706    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]707    prefix = 'form'
[8258]708    note = None
[7250]709
710    @property
[7714]711    def title(self):
[7819]712        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[7811]713        return translate(_('Payment Data'), 'waeup.kofa',
[7714]714            target_language=portal_language)
715
716    @property
[7250]717    def label(self):
[7819]718        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[8262]719        return translate(_('Online Payment Slip'),
[7811]720            'waeup.kofa', target_language=portal_language) \
[7714]721            + ' %s' % self.context.p_id
[7250]722
723    def render(self):
[8262]724        #if self.context.p_state != 'paid':
725        #    self.flash(_('Ticket not yet paid.'))
726        #    self.redirect(self.url(self.context))
727        #    return
[7259]728        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
[7250]729            self.request)
730        students_utils = getUtility(IStudentsUtils)
[8262]731        return students_utils.renderPDF(self,'payment_slip.pdf',
[8258]732            self.context.__parent__, applicantview, note=self.note)
[7250]733
[7459]734class ExportPDFPage(UtilityView, grok.View):
[6358]735    """Deliver a PDF slip of the context.
736    """
737    grok.context(IApplicant)
738    grok.name('application_slip.pdf')
[7136]739    grok.require('waeup.viewApplication')
[6358]740    prefix = 'form'
741
[8666]742    def update(self):
[9051]743        if self.context.state in ('initialized', 'started', 'paid'):
[8666]744            self.flash(
[9051]745                _('Please pay and submit before trying to download the application slip.'))
[8666]746            return self.redirect(self.url(self.context))
747        return
748
[6358]749    def render(self):
[7392]750        pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
751            view=self)
[6358]752        self.response.setHeader(
753            'Content-Type', 'application/pdf')
[7392]754        return pdfstream
[6358]755
[7081]756def handle_img_upload(upload, context, view):
[7063]757    """Handle upload of applicant image.
[7081]758
759    Returns `True` in case of success or `False`.
760
761    Please note that file pointer passed in (`upload`) most probably
762    points to end of file when leaving this function.
[7063]763    """
[7081]764    size = file_size(upload)
765    if size > MAX_UPLOAD_SIZE:
[7714]766        view.flash(_('Uploaded image is too big!'))
[7081]767        return False
[7247]768    dummy, ext = os.path.splitext(upload.filename)
769    ext.lower()
770    if ext != '.jpg':
[7714]771        view.flash(_('jpg file extension expected.'))
[7247]772        return False
[7081]773    upload.seek(0) # file pointer moved when determining size
[7063]774    store = getUtility(IExtFileStore)
775    file_id = IFileStoreNameChooser(context).chooseName()
776    store.createFile(file_id, upload)
[7081]777    return True
[7063]778
[7819]779class ApplicantManageFormPage(KofaEditFormPage):
[6196]780    """A full edit view for applicant data.
781    """
782    grok.context(IApplicant)
[7200]783    grok.name('manage')
[7136]784    grok.require('waeup.manageApplication')
[6476]785    form_fields = grok.AutoFields(IApplicant)
[7351]786    form_fields['student_id'].for_display = True
[7378]787    form_fields['applicant_id'].for_display = True
[7200]788    grok.template('applicanteditpage')
[6322]789    manage_applications = True
[6196]790    pnav = 3
[7714]791    display_actions = [[_('Save'), _('Final Submit')],
792        [_('Add online payment ticket'),_('Remove selected tickets')]]
[6196]793
[8046]794    @property
795    def separators(self):
796        return getUtility(IApplicantsUtils).SEPARATORS_DICT
797
[6196]798    def update(self):
799        datepicker.need() # Enable jQuery datepicker in date fields.
[7330]800        warning.need()
[7200]801        super(ApplicantManageFormPage, self).update()
[6353]802        self.wf_info = IWorkflowInfo(self.context)
[7081]803        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
[10090]804        self.upload_success = None
[6598]805        upload = self.request.form.get('form.passport', None)
806        if upload:
[10090]807            # We got a fresh upload, upload_success is
808            # either True or False
809            self.upload_success = handle_img_upload(
[7084]810                upload, self.context, self)
[10090]811            if self.upload_success:
[10095]812                self.context.writeLogMessage(self, 'saved: passport')
[6196]813        return
814
815    @property
816    def label(self):
817        container_title = self.context.__parent__.title
[8096]818        return _('${a} <br /> Application Form ${b}', mapping = {
[7714]819            'a':container_title, 'b':self.context.application_number})
[6196]820
[6303]821    def getTransitions(self):
[6351]822        """Return a list of dicts of allowed transition ids and titles.
[6353]823
824        Each list entry provides keys ``name`` and ``title`` for
825        internal name and (human readable) title of a single
826        transition.
[6349]827        """
[8434]828        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
829            if not t[0] == 'pay']
[7687]830        return [dict(name='', title=_('No transition'))] +[
[6355]831            dict(name=x, title=y) for x, y in allowed_transitions]
[6303]832
[7714]833    @action(_('Save'), style='primary')
[6196]834    def save(self, **data):
[7240]835        form = self.request.form
836        password = form.get('password', None)
837        password_ctl = form.get('control_password', None)
838        if password:
839            validator = getUtility(IPasswordValidator)
840            errors = validator.validate_password(password, password_ctl)
841            if errors:
842                self.flash( ' '.join(errors))
843                return
[10090]844        if self.upload_success is False:  # False is not None!
845            # Error during image upload. Ignore other values.
846            return
[6475]847        changed_fields = self.applyData(self.context, **data)
[7199]848        # Turn list of lists into single list
849        if changed_fields:
850            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7240]851        else:
852            changed_fields = []
853        if password:
854            # Now we know that the form has no errors and can set password ...
855            IUserAccount(self.context).setPassword(password)
856            changed_fields.append('password')
[7199]857        fields_string = ' + '.join(changed_fields)
[7085]858        trans_id = form.get('transition', None)
859        if trans_id:
860            self.wf_info.fireTransition(trans_id)
[7714]861        self.flash(_('Form has been saved.'))
[6644]862        if fields_string:
[8742]863            self.context.writeLogMessage(self, 'saved: % s' % fields_string)
[6196]864        return
865
[7250]866    def unremovable(self, ticket):
[7330]867        return False
[7250]868
869    # This method is also used by the ApplicantEditFormPage
870    def delPaymentTickets(self, **data):
871        form = self.request.form
[9701]872        if 'val_id' in form:
[7250]873            child_id = form['val_id']
874        else:
[7714]875            self.flash(_('No payment selected.'))
[7250]876            self.redirect(self.url(self.context))
877            return
878        if not isinstance(child_id, list):
879            child_id = [child_id]
880        deleted = []
881        for id in child_id:
882            # Applicants are not allowed to remove used payment tickets
883            if not self.unremovable(self.context[id]):
884                try:
885                    del self.context[id]
886                    deleted.append(id)
887                except:
[7714]888                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[7250]889                            id, sys.exc_info()[0], sys.exc_info()[1]))
890        if len(deleted):
[7741]891            self.flash(_('Successfully removed: ${a}',
[7738]892                mapping = {'a':', '.join(deleted)}))
[8742]893            self.context.writeLogMessage(
894                self, 'removed: % s' % ', '.join(deleted))
[7250]895        return
896
[7252]897    # We explicitely want the forms to be validated before payment tickets
898    # can be created. If no validation is requested, use
[7459]899    # 'validator=NullValidator' in the action directive
[7714]900    @action(_('Add online payment ticket'))
[7250]901    def addPaymentTicket(self, **data):
902        self.redirect(self.url(self.context, '@@addafp'))
[7252]903        return
[7250]904
[7714]905    @jsaction(_('Remove selected tickets'))
[7250]906    def removePaymentTickets(self, **data):
907        self.delPaymentTickets(**data)
908        self.redirect(self.url(self.context) + '/@@manage')
909        return
910
[10094]911    # Not used in base package
912    def file_exists(self, attr):
913        file = getUtility(IExtFileStore).getFileByContext(
914            self.context, attr=attr)
915        if file:
916            return True
917        else:
918            return False
919
[7200]920class ApplicantEditFormPage(ApplicantManageFormPage):
[5982]921    """An applicant-centered edit view for applicant data.
922    """
[6196]923    grok.context(IApplicantEdit)
[5273]924    grok.name('edit')
[6198]925    grok.require('waeup.handleApplication')
[6459]926    form_fields = grok.AutoFields(IApplicantEdit).omit(
[6476]927        'locked', 'course_admitted', 'student_id',
[9047]928        'suspended'
[6459]929        )
[7459]930    form_fields['applicant_id'].for_display = True
[8039]931    form_fields['reg_number'].for_display = True
[7200]932    grok.template('applicanteditpage')
[6322]933    manage_applications = False
[5484]934
[7250]935    @property
936    def display_actions(self):
[8286]937        state = IWorkflowState(self.context).getState()
938        if state == INITIALIZED:
[7250]939            actions = [[],[]]
[8286]940        elif state == STARTED:
[7714]941            actions = [[_('Save')],
942                [_('Add online payment ticket'),_('Remove selected tickets')]]
[8286]943        elif state == PAID:
[7714]944            actions = [[_('Save'), _('Final Submit')],
945                [_('Remove selected tickets')]]
[7351]946        else:
[7250]947            actions = [[],[]]
948        return actions
949
[7330]950    def unremovable(self, ticket):
[8286]951        state = IWorkflowState(self.context).getState()
952        return ticket.r_code or state in (INITIALIZED, SUBMITTED)
[7330]953
[7145]954    def emit_lock_message(self):
[7714]955        self.flash(_('The requested form is locked (read-only).'))
[5941]956        self.redirect(self.url(self.context))
957        return
[6078]958
[5686]959    def update(self):
[8665]960        if self.context.locked or (
961            self.context.__parent__.expired and
962            self.context.__parent__.strict_deadline):
[7145]963            self.emit_lock_message()
[5941]964            return
[7200]965        super(ApplicantEditFormPage, self).update()
[5686]966        return
[5952]967
[6196]968    def dataNotComplete(self):
[7252]969        store = getUtility(IExtFileStore)
970        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
[7714]971            return _('No passport picture uploaded.')
[6322]972        if not self.request.form.get('confirm_passport', False):
[7714]973            return _('Passport picture confirmation box not ticked.')
[6196]974        return False
[5952]975
[7252]976    # We explicitely want the forms to be validated before payment tickets
977    # can be created. If no validation is requested, use
[7459]978    # 'validator=NullValidator' in the action directive
[7714]979    @action(_('Add online payment ticket'))
[7250]980    def addPaymentTicket(self, **data):
981        self.redirect(self.url(self.context, '@@addafp'))
[7252]982        return
[7250]983
[7714]984    @jsaction(_('Remove selected tickets'))
[7250]985    def removePaymentTickets(self, **data):
986        self.delPaymentTickets(**data)
987        self.redirect(self.url(self.context) + '/@@edit')
988        return
989
[7996]990    @action(_('Save'), style='primary')
[5273]991    def save(self, **data):
[10090]992        if self.upload_success is False:  # False is not None!
993            # Error during image upload. Ignore other values.
994            return
[5273]995        self.applyData(self.context, **data)
[6196]996        self.flash('Form has been saved.')
[5273]997        return
998
[8550]999    @submitaction(_('Final Submit'))
[5484]1000    def finalsubmit(self, **data):
[10090]1001        if self.upload_success is False:  # False is not None!
[7084]1002            return # error during image upload. Ignore other values
[6196]1003        if self.dataNotComplete():
1004            self.flash(self.dataNotComplete())
[5941]1005            return
[7252]1006        self.applyData(self.context, **data)
[8286]1007        state = IWorkflowState(self.context).getState()
[6322]1008        # This shouldn't happen, but the application officer
1009        # might have forgotten to lock the form after changing the state
[8286]1010        if state != PAID:
[8589]1011            self.flash(_('The form cannot be submitted. Wrong state!'))
[6303]1012            return
1013        IWorkflowInfo(self.context).fireTransition('submit')
[8589]1014        # application_date is used in export files for sorting.
1015        # We can thus store utc.
[8194]1016        self.context.application_date = datetime.utcnow()
[7714]1017        self.flash(_('Form has been submitted.'))
[6196]1018        self.redirect(self.url(self.context))
[5273]1019        return
[5941]1020
[7063]1021class PassportImage(grok.View):
1022    """Renders the passport image for applicants.
1023    """
1024    grok.name('passport.jpg')
1025    grok.context(IApplicant)
[7113]1026    grok.require('waeup.viewApplication')
[7063]1027
1028    def render(self):
1029        # A filename chooser turns a context into a filename suitable
1030        # for file storage.
1031        image = getUtility(IExtFileStore).getFileByContext(self.context)
1032        self.response.setHeader(
1033            'Content-Type', 'image/jpeg')
1034        if image is None:
1035            # show placeholder image
[7089]1036            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
[7063]1037        return image
[7363]1038
[7819]1039class ApplicantRegistrationPage(KofaAddFormPage):
[7363]1040    """Captcha'd registration page for applicants.
1041    """
1042    grok.context(IApplicantsContainer)
1043    grok.name('register')
[7373]1044    grok.require('waeup.Anonymous')
[7363]1045    grok.template('applicantregister')
1046
[7368]1047    @property
[8033]1048    def form_fields(self):
1049        form_fields = None
[8128]1050        if self.context.mode == 'update':
1051            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
1052                'firstname','reg_number','email')
1053        else: #if self.context.mode == 'create':
[8033]1054            form_fields = grok.AutoFields(IApplicantEdit).select(
1055                'firstname', 'middlename', 'lastname', 'email', 'phone')
1056        return form_fields
1057
1058    @property
[7368]1059    def label(self):
[8078]1060        return _('Apply for ${a}',
[7714]1061            mapping = {'a':self.context.title})
[7368]1062
[7363]1063    def update(self):
[8665]1064        if self.context.expired:
1065            self.flash(_('Outside application period.'))
[7368]1066            self.redirect(self.url(self.context))
1067            return
1068        # Handle captcha
[7363]1069        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1070        self.captcha_result = self.captcha.verify(self.request)
1071        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1072        return
1073
[8629]1074    def _redirect(self, email, password, applicant_id):
1075        # Forward only email to landing page in base package.
1076        self.redirect(self.url(self.context, 'registration_complete',
1077            data = dict(email=email)))
1078        return
1079
[9178]1080    @action(_('Send login credentials to email address'), style='primary')
[7363]1081    def register(self, **data):
1082        if not self.captcha_result.is_valid:
[8037]1083            # Captcha will display error messages automatically.
[7363]1084            # No need to flash something.
1085            return
[8033]1086        if self.context.mode == 'create':
1087            # Add applicant
1088            applicant = createObject(u'waeup.Applicant')
1089            self.applyData(applicant, **data)
1090            self.context.addApplicant(applicant)
[8042]1091            applicant.reg_number = applicant.applicant_id
1092            notify(grok.ObjectModifiedEvent(applicant))
[8033]1093        elif self.context.mode == 'update':
1094            # Update applicant
[8037]1095            reg_number = data.get('reg_number','')
1096            firstname = data.get('firstname','')
[8033]1097            cat = getUtility(ICatalog, name='applicants_catalog')
1098            results = list(
1099                cat.searchResults(reg_number=(reg_number, reg_number)))
1100            if results:
1101                applicant = results[0]
[8042]1102                if getattr(applicant,'firstname',None) is None:
[8037]1103                    self.flash(_('An error occurred.'))
1104                    return
1105                elif applicant.firstname.lower() != firstname.lower():
[8042]1106                    # Don't tell the truth here. Anonymous must not
1107                    # know that a record was found and only the firstname
1108                    # verification failed.
[8037]1109                    self.flash(_('No application record found.'))
1110                    return
[8627]1111                elif applicant.password is not None and \
1112                    applicant.state != INITIALIZED:
1113                    self.flash(_('Your password has already been set and used. '
[8042]1114                                 'Please proceed to the login page.'))
1115                    return
1116                # Store email address but nothing else.
[8033]1117                applicant.email = data['email']
[8042]1118                notify(grok.ObjectModifiedEvent(applicant))
[8033]1119            else:
[8042]1120                # No record found, this is the truth.
[8033]1121                self.flash(_('No application record found.'))
1122                return
1123        else:
[8042]1124            # Does not happen but anyway ...
[8033]1125            return
[7819]1126        kofa_utils = getUtility(IKofaUtils)
[7811]1127        password = kofa_utils.genPassword()
[7380]1128        IUserAccount(applicant).setPassword(password)
[7365]1129        # Send email with credentials
[7399]1130        login_url = self.url(grok.getSite(), 'login')
[8853]1131        url_info = u'Login: %s' % login_url
[7714]1132        msg = _('You have successfully been registered for the')
[7811]1133        if kofa_utils.sendCredentials(IUserAccount(applicant),
[8853]1134            password, url_info, msg):
[8629]1135            email_sent = applicant.email
[7380]1136        else:
[8629]1137            email_sent = None
1138        self._redirect(email=email_sent, password=password,
1139            applicant_id=applicant.applicant_id)
[7380]1140        return
1141
[7819]1142class ApplicantRegistrationEmailSent(KofaPage):
[7380]1143    """Landing page after successful registration.
[8629]1144
[7380]1145    """
1146    grok.name('registration_complete')
1147    grok.require('waeup.Public')
1148    grok.template('applicantregemailsent')
[7714]1149    label = _('Your registration was successful.')
[7380]1150
[8629]1151    def update(self, email=None, applicant_id=None, password=None):
[7380]1152        self.email = email
[8629]1153        self.password = password
1154        self.applicant_id = applicant_id
[7380]1155        return
Note: See TracBrowser for help on using the repository browser.