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

Last change on this file since 9819 was 9795, checked in by Henrik Bettermann, 12 years ago

Add suspended students search.

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