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

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

StudentRequestPasswordPage?: Create mandate and send link by email instead of setting password directly.

Show link to StudentRequestPasswordPage? on login page.

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