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

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

Remove trash.

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