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

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

Use HTMLDisplayWidget for description of ApplicantsContainers?.

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