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

Last change on this file since 8552 was 8550, checked in by Henrik Bettermann, 13 years ago

Extend warning message before submitting the application form.

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