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

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

Implement CreateAllStudentsPage? which creates students from all admitted students in a container.

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