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

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

Do not allow submission when application period has expired.

  • Property svn:keywords set to Id
File size: 38.6 KB
Line 
1## $Id: browser.py 8589 2012-06-01 06:21:18Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
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.
8##
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.
13##
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##
18"""UI components for basic applicants and related components.
19"""
20import os
21import pytz
22import sys
23import grok
24from datetime import datetime, date
25from zope.event import notify
26from zope.component import getUtility, createObject, getAdapter
27from zope.catalog.interfaces import ICatalog
28from zope.i18n import translate
29from hurry.workflow.interfaces import (
30    IWorkflowInfo, IWorkflowState, InvalidTransitionError)
31from waeup.kofa.applicants.interfaces import (
32    IApplicant, IApplicantEdit, IApplicantsRoot,
33    IApplicantsContainer, IApplicantsContainerAdd,
34    MAX_UPLOAD_SIZE, IApplicantOnlinePayment, IApplicantsUtils,
35    IApplicantRegisterUpdate
36    )
37from waeup.kofa.applicants.applicant import search
38from waeup.kofa.applicants.workflow import INITIALIZED, STARTED, PAID, SUBMITTED
39from waeup.kofa.browser import (
40    KofaPage, KofaEditFormPage, KofaAddFormPage, KofaDisplayFormPage,
41    DEFAULT_PASSPORT_IMAGE_PATH)
42from waeup.kofa.browser.interfaces import ICaptchaManager
43from waeup.kofa.browser.breadcrumbs import Breadcrumb
44from waeup.kofa.browser.resources import toggleall
45from waeup.kofa.browser.layout import (
46    NullValidator, jsaction, action, UtilityView, JSAction)
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 (
50    IKofaObject, ILocalRolesAssignable, IExtFileStore, IPDF,
51    IFileStoreNameChooser, IPasswordValidator, IUserAccount, IKofaUtils)
52from waeup.kofa.interfaces import MessageFactory as _
53from waeup.kofa.permissions import get_users_with_local_roles
54from waeup.kofa.students.interfaces import IStudentsUtils
55from waeup.kofa.utils.helpers import string_from_bytes, file_size, now
56from waeup.kofa.widgets.datewidget import (
57    FriendlyDateDisplayWidget, FriendlyDateDisplayWidget,
58    FriendlyDatetimeDisplayWidget)
59from waeup.kofa.widgets.htmlwidget import HTMLDisplayWidget
60
61grok.context(IKofaObject) # Make IKofaObject the default context
62
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
75class ApplicantsRootPage(KofaDisplayFormPage):
76    grok.context(IApplicantsRoot)
77    grok.name('index')
78    grok.require('waeup.Public')
79    form_fields = grok.AutoFields(IApplicantsRoot)
80    form_fields['description'].custom_widget = HTMLDisplayWidget
81    label = _('Application Section')
82    search_button = _('Search')
83    pnav = 3
84
85    def update(self):
86        super(ApplicantsRootPage, self).update()
87        return
88
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
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
127class ApplicantsRootManageFormPage(KofaEditFormPage):
128    grok.context(IApplicantsRoot)
129    grok.name('manage')
130    grok.template('applicantsrootmanagepage')
131    form_fields = grok.AutoFields(IApplicantsRoot)
132    label = _('Manage application section')
133    pnav = 3
134    grok.require('waeup.manageApplication')
135    taboneactions = [_('Save')]
136    tabtwoactions = [_('Add applicants container'), _('Remove selected')]
137    tabthreeactions1 = [_('Remove selected local roles')]
138    tabthreeactions2 = [_('Add local role')]
139    subunits = _('Applicants Containers')
140
141    def update(self):
142        tabs.need()
143        datatable.need()
144        warning.need()
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')
150        return super(ApplicantsRootManageFormPage, self).update()
151
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
166    @jsaction(_('Remove selected'))
167    def delApplicantsContainers(self, **data):
168        form = self.request.form
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
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:
183                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
184                        id, sys.exc_info()[0], sys.exc_info()[1]))
185        if len(deleted):
186            self.flash(_('Successfully removed: ${a}',
187                mapping = {'a':', '.join(deleted)}))
188        self.redirect(self.url(self.context, '@@manage')+'?tab2')
189        return
190
191    @action(_('Add applicants container'), validator=NullValidator)
192    def addApplicantsContainer(self, **data):
193        self.redirect(self.url(self.context, '@@add'))
194        return
195
196    @action(_('Add local role'), validator=NullValidator)
197    def addLocalRole(self, **data):
198        return add_local_role(self,3, **data)
199
200    @action(_('Remove selected local roles'))
201    def delLocalRoles(self, **data):
202        return del_local_roles(self,3,**data)
203
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()
214        self.flash(_('Form has been saved.'))
215        return
216
217class ApplicantsContainerAddFormPage(KofaAddFormPage):
218    grok.context(IApplicantsRoot)
219    grok.require('waeup.manageApplication')
220    grok.name('add')
221    grok.template('applicantscontaineraddpage')
222    label = _('Add applicants container')
223    pnav = 3
224
225    form_fields = grok.AutoFields(
226        IApplicantsContainerAdd).omit('code').omit('title')
227
228    def update(self):
229        datepicker.need() # Enable jQuery datepicker in date fields.
230        return super(ApplicantsContainerAddFormPage, self).update()
231
232    @action(_('Add applicants container'))
233    def addApplicantsContainer(self, **data):
234        year = data['year']
235        code = u'%s%s' % (data['prefix'], year)
236        appcats_dict = getUtility(IApplicantsUtils).APP_TYPES_DICT
237        title = appcats_dict[data['prefix']][0]
238        title = u'%s %s/%s' % (title, year, year + 1)
239        if code in self.context.keys():
240            self.flash(
241                _('An applicants container for the same application type and entrance year exists already in the database.'))
242            return
243        # Add new applicants container...
244        container = createObject(u'waeup.ApplicantsContainer')
245        self.applyData(container, **data)
246        container.code = code
247        container.title = title
248        self.context[code] = container
249        self.flash(_('Added:') + ' "%s".' % code)
250        self.redirect(self.url(self.context, u'@@manage'))
251        return
252
253    @action(_('Cancel'), validator=NullValidator)
254    def cancel(self, **data):
255        self.redirect(self.url(self.context, '@@manage'))
256
257class ApplicantsRootBreadcrumb(Breadcrumb):
258    """A breadcrumb for applicantsroot.
259    """
260    grok.context(IApplicantsRoot)
261    title = _(u'Applicants')
262
263class ApplicantsContainerBreadcrumb(Breadcrumb):
264    """A breadcrumb for applicantscontainers.
265    """
266    grok.context(IApplicantsContainer)
267
268class ApplicantBreadcrumb(Breadcrumb):
269    """A breadcrumb for applicants.
270    """
271    grok.context(IApplicant)
272
273    @property
274    def title(self):
275        """Get a title for a context.
276        """
277        return self.context.application_number
278
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
288class ApplicantsStatisticsPage(KofaDisplayFormPage):
289    """Some statistics about applicants in a container.
290    """
291    grok.context(IApplicantsContainer)
292    grok.name('statistics')
293    grok.require('waeup.viewApplicationStatistics')
294    grok.template('applicantcontainerstatistics')
295
296    @property
297    def label(self):
298        return "%s" % self.context.title
299
300class ApplicantsContainerPage(KofaDisplayFormPage):
301    """The standard view for regular applicant containers.
302    """
303    grok.context(IApplicantsContainer)
304    grok.name('index')
305    grok.require('waeup.Public')
306    grok.template('applicantscontainerpage')
307    pnav = 3
308
309    form_fields = grok.AutoFields(IApplicantsContainer).omit('title')
310    form_fields['description'].custom_widget = HTMLDisplayWidget
311    form_fields[
312        'startdate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
313    form_fields[
314        'enddate'].custom_widget = FriendlyDatetimeDisplayWidget('le')
315
316    @property
317    def introduction(self):
318        # Here we know that the cookie has been set
319        lang = self.request.cookies.get('kofa.language')
320        html = self.context.description_dict.get(lang,'')
321        if html == '':
322            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
323            html = self.context.description_dict.get(portal_language,'')
324        return html
325
326    @property
327    def label(self):
328        return "%s" % self.context.title
329
330class ApplicantsContainerManageFormPage(KofaEditFormPage):
331    grok.context(IApplicantsContainer)
332    grok.name('manage')
333    grok.template('applicantscontainermanagepage')
334    form_fields = grok.AutoFields(IApplicantsContainer).omit('title')
335    taboneactions = [_('Save'),_('Cancel')]
336    tabtwoactions = [_('Add applicant'), _('Remove selected'),_('Cancel'),
337        _('Create students from selected')]
338    tabthreeactions1 = [_('Remove selected local roles')]
339    tabthreeactions2 = [_('Add local role')]
340    # Use friendlier date widget...
341    grok.require('waeup.manageApplication')
342
343    @property
344    def label(self):
345        return _('Manage applicants container')
346
347    pnav = 3
348
349    @property
350    def showApplicants(self):
351        if len(self.context) < 5000:
352            return True
353        return False
354
355    def update(self):
356        datepicker.need() # Enable jQuery datepicker in date fields.
357        tabs.need()
358        toggleall.need()
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')
364        warning.need()
365        datatable.need()  # Enable jQurey datatables for contents listing
366        return super(ApplicantsContainerManageFormPage, self).update()
367
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
382    def _description(self):
383        view = ApplicantsContainerPage(
384            self.context,self.request)
385        view.setUpWidgets()
386        return view.widgets['description']()
387
388    @action(_('Save'), style='primary')
389    def save(self, **data):
390        self.applyData(self.context, **data)
391        self.context.description_dict = self._description()
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)
398        self.flash(_('Form has been saved.'))
399        return
400
401    @jsaction(_('Remove selected'))
402    def delApplicant(self, **data):
403        form = self.request.form
404        if form.has_key('val_id'):
405            child_id = form['val_id']
406        else:
407            self.flash(_('No applicant selected!'))
408            self.redirect(self.url(self.context, '@@manage')+'?tab2')
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:
418                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
419                        id, sys.exc_info()[0], sys.exc_info()[1]))
420        if len(deleted):
421            self.flash(_('Successfully removed: ${a}',
422                mapping = {'a':', '.join(deleted)}))
423        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
424        return
425
426    @action(_('Add applicant'), validator=NullValidator)
427    def addApplicant(self, **data):
428        self.redirect(self.url(self.context, 'addapplicant'))
429        return
430
431    @action(_('Create students from selected'))
432    def createStudents(self, **data):
433        form = self.request.form
434        if form.has_key('val_id'):
435            child_id = form['val_id']
436        else:
437            self.flash(_('No applicant selected!'))
438            self.redirect(self.url(self.context, '@@manage')+'?tab2')
439            return
440        if not isinstance(child_id, list):
441            child_id = [child_id]
442        created = []
443        for id in child_id:
444            success, msg = self.context[id].createStudent(view=self)
445            if success:
446                created.append(id)
447        if len(created):
448            self.flash(_('${a} students successfully created.',
449                mapping = {'a': len(created)}))
450        else:
451            self.flash(_('No student could be created.'))
452        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
453        return
454
455    @action(_('Cancel'), validator=NullValidator)
456    def cancel(self, **data):
457        self.redirect(self.url(self.context))
458        return
459
460    @action(_('Add local role'), validator=NullValidator)
461    def addLocalRole(self, **data):
462        return add_local_role(self,3, **data)
463
464    @action(_('Remove selected local roles'))
465    def delLocalRoles(self, **data):
466        return del_local_roles(self,3,**data)
467
468class ApplicantAddFormPage(KofaAddFormPage):
469    """Add-form to add an applicant.
470    """
471    grok.context(IApplicantsContainer)
472    grok.require('waeup.manageApplication')
473    grok.name('addapplicant')
474    #grok.template('applicantaddpage')
475    form_fields = grok.AutoFields(IApplicant).select(
476        'firstname', 'middlename', 'lastname',
477        'email', 'phone')
478    label = _('Add applicant')
479    pnav = 3
480
481    @action(_('Create application record'))
482    def addApplicant(self, **data):
483        applicant = createObject(u'waeup.Applicant')
484        self.applyData(applicant, **data)
485        self.context.addApplicant(applicant)
486        self.flash(_('Applicant record created.'))
487        self.redirect(
488            self.url(self.context[applicant.application_number], 'index'))
489        return
490
491class ApplicantDisplayFormPage(KofaDisplayFormPage):
492    """A display view for applicant data.
493    """
494    grok.context(IApplicant)
495    grok.name('index')
496    grok.require('waeup.viewApplication')
497    grok.template('applicantdisplaypage')
498    form_fields = grok.AutoFields(IApplicant).omit(
499        'locked', 'course_admitted', 'password')
500    label = _('Applicant')
501    pnav = 3
502
503    @property
504    def separators(self):
505        return getUtility(IApplicantsUtils).SEPARATORS_DICT
506
507    def update(self):
508        self.passport_url = self.url(self.context, 'passport.jpg')
509        # Mark application as started if applicant logs in for the first time
510        usertype = getattr(self.request.principal, 'user_type', None)
511        if usertype == 'applicant' and \
512            IWorkflowState(self.context).getState() == INITIALIZED:
513            IWorkflowInfo(self.context).fireTransition('start')
514        return
515
516    @property
517    def hasPassword(self):
518        if self.context.password:
519            return _('set')
520        return _('unset')
521
522    @property
523    def label(self):
524        container_title = self.context.__parent__.title
525        return _('${a} <br /> Application Record ${b}', mapping = {
526            'a':container_title, 'b':self.context.application_number})
527
528    def getCourseAdmitted(self):
529        """Return link, title and code in html format to the certificate
530           admitted.
531        """
532        course_admitted = self.context.course_admitted
533        if getattr(course_admitted, '__parent__',None):
534            url = self.url(course_admitted)
535            title = course_admitted.title
536            code = course_admitted.code
537            return '<a href="%s">%s - %s</a>' %(url,code,title)
538        return ''
539
540class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
541    grok.context(IApplicant)
542    grok.name('base')
543    form_fields = grok.AutoFields(IApplicant).select(
544        'applicant_id', 'firstname', 'lastname','email', 'course1')
545
546class CreateStudentPage(UtilityView, grok.View):
547    """Create a student object from applicatnt data
548    and copy applicant object.
549    """
550    grok.context(IApplicant)
551    grok.name('createstudent')
552    grok.require('waeup.manageStudent')
553
554    def update(self):
555        msg = self.context.createStudent(view=self)[1]
556        self.flash(msg)
557        self.redirect(self.url(self.context))
558        return
559
560    def render(self):
561        return
562
563class ApplicationFeePaymentAddPage(UtilityView, grok.View):
564    """ Page to add an online payment ticket
565    """
566    grok.context(IApplicant)
567    grok.name('addafp')
568    grok.require('waeup.payApplicant')
569    factory = u'waeup.ApplicantOnlinePayment'
570
571    def update(self):
572        for key in self.context.keys():
573            ticket = self.context[key]
574            if ticket.p_state == 'paid':
575                  self.flash(
576                      _('This type of payment has already been made.'))
577                  self.redirect(self.url(self.context))
578                  return
579        applicants_utils = getUtility(IApplicantsUtils)
580        container = self.context.__parent__
581        payment = createObject(self.factory)
582        error = applicants_utils.setPaymentDetails(container, payment)
583        if error is not None:
584            self.flash(error)
585            self.redirect(self.url(self.context))
586            return
587        self.context[payment.p_id] = payment
588        self.flash(_('Payment ticket created.'))
589        self.redirect(self.url(payment))
590        return
591
592    def render(self):
593        return
594
595
596class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
597    """ Page to view an online payment ticket
598    """
599    grok.context(IApplicantOnlinePayment)
600    grok.name('index')
601    grok.require('waeup.viewApplication')
602    form_fields = grok.AutoFields(IApplicantOnlinePayment)
603    form_fields[
604        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
605    form_fields[
606        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
607    pnav = 3
608
609    @property
610    def label(self):
611        return _('${a}: Online Payment Ticket ${b}', mapping = {
612            'a':self.context.__parent__.display_fullname,
613            'b':self.context.p_id})
614
615class OnlinePaymentApprovePage(UtilityView, grok.View):
616    """ Approval view
617    """
618    grok.context(IApplicantOnlinePayment)
619    grok.name('approve')
620    grok.require('waeup.managePortal')
621
622    def update(self):
623        success, msg, log = self.context.approveApplicantPayment()
624        if log is not None:
625            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
626            self.context.__parent__.loggerInfo(ob_class, log)
627        self.flash(msg)
628        return
629
630    def render(self):
631        self.redirect(self.url(self.context, '@@index'))
632        return
633
634class ExportPDFPaymentSlipPage(UtilityView, grok.View):
635    """Deliver a PDF slip of the context.
636    """
637    grok.context(IApplicantOnlinePayment)
638    grok.name('payment_slip.pdf')
639    grok.require('waeup.viewApplication')
640    form_fields = grok.AutoFields(IApplicantOnlinePayment)
641    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
642    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
643    prefix = 'form'
644    note = None
645
646    @property
647    def title(self):
648        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
649        return translate(_('Payment Data'), 'waeup.kofa',
650            target_language=portal_language)
651
652    @property
653    def label(self):
654        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
655        return translate(_('Online Payment Slip'),
656            'waeup.kofa', target_language=portal_language) \
657            + ' %s' % self.context.p_id
658
659    def render(self):
660        #if self.context.p_state != 'paid':
661        #    self.flash(_('Ticket not yet paid.'))
662        #    self.redirect(self.url(self.context))
663        #    return
664        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
665            self.request)
666        students_utils = getUtility(IStudentsUtils)
667        return students_utils.renderPDF(self,'payment_slip.pdf',
668            self.context.__parent__, applicantview, note=self.note)
669
670class ExportPDFPage(UtilityView, grok.View):
671    """Deliver a PDF slip of the context.
672    """
673    grok.context(IApplicant)
674    grok.name('application_slip.pdf')
675    grok.require('waeup.viewApplication')
676    prefix = 'form'
677
678    def render(self):
679        pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
680            view=self)
681        self.response.setHeader(
682            'Content-Type', 'application/pdf')
683        return pdfstream
684
685def handle_img_upload(upload, context, view):
686    """Handle upload of applicant image.
687
688    Returns `True` in case of success or `False`.
689
690    Please note that file pointer passed in (`upload`) most probably
691    points to end of file when leaving this function.
692    """
693    size = file_size(upload)
694    if size > MAX_UPLOAD_SIZE:
695        view.flash(_('Uploaded image is too big!'))
696        return False
697    dummy, ext = os.path.splitext(upload.filename)
698    ext.lower()
699    if ext != '.jpg':
700        view.flash(_('jpg file extension expected.'))
701        return False
702    upload.seek(0) # file pointer moved when determining size
703    store = getUtility(IExtFileStore)
704    file_id = IFileStoreNameChooser(context).chooseName()
705    store.createFile(file_id, upload)
706    return True
707
708class ApplicantManageFormPage(KofaEditFormPage):
709    """A full edit view for applicant data.
710    """
711    grok.context(IApplicant)
712    grok.name('manage')
713    grok.require('waeup.manageApplication')
714    form_fields = grok.AutoFields(IApplicant)
715    form_fields['student_id'].for_display = True
716    form_fields['applicant_id'].for_display = True
717    grok.template('applicanteditpage')
718    manage_applications = True
719    pnav = 3
720    display_actions = [[_('Save'), _('Final Submit')],
721        [_('Add online payment ticket'),_('Remove selected tickets')]]
722
723    @property
724    def separators(self):
725        return getUtility(IApplicantsUtils).SEPARATORS_DICT
726
727    def update(self):
728        datepicker.need() # Enable jQuery datepicker in date fields.
729        warning.need()
730        super(ApplicantManageFormPage, self).update()
731        self.wf_info = IWorkflowInfo(self.context)
732        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
733        self.passport_changed = None
734        upload = self.request.form.get('form.passport', None)
735        if upload:
736            # We got a fresh upload
737            self.passport_changed = handle_img_upload(
738                upload, self.context, self)
739        return
740
741    @property
742    def label(self):
743        container_title = self.context.__parent__.title
744        return _('${a} <br /> Application Form ${b}', mapping = {
745            'a':container_title, 'b':self.context.application_number})
746
747    def getTransitions(self):
748        """Return a list of dicts of allowed transition ids and titles.
749
750        Each list entry provides keys ``name`` and ``title`` for
751        internal name and (human readable) title of a single
752        transition.
753        """
754        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
755            if not t[0] == 'pay']
756        return [dict(name='', title=_('No transition'))] +[
757            dict(name=x, title=y) for x, y in allowed_transitions]
758
759    @action(_('Save'), style='primary')
760    def save(self, **data):
761        form = self.request.form
762        password = form.get('password', None)
763        password_ctl = form.get('control_password', None)
764        if password:
765            validator = getUtility(IPasswordValidator)
766            errors = validator.validate_password(password, password_ctl)
767            if errors:
768                self.flash( ' '.join(errors))
769                return
770        if self.passport_changed is False:  # False is not None!
771            return # error during image upload. Ignore other values
772        changed_fields = self.applyData(self.context, **data)
773        # Turn list of lists into single list
774        if changed_fields:
775            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
776        else:
777            changed_fields = []
778        if self.passport_changed:
779            changed_fields.append('passport')
780        if password:
781            # Now we know that the form has no errors and can set password ...
782            IUserAccount(self.context).setPassword(password)
783            changed_fields.append('password')
784        fields_string = ' + '.join(changed_fields)
785        trans_id = form.get('transition', None)
786        if trans_id:
787            self.wf_info.fireTransition(trans_id)
788        self.flash(_('Form has been saved.'))
789        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
790        if fields_string:
791            self.context.loggerInfo(ob_class, 'saved: % s' % fields_string)
792        return
793
794    def unremovable(self, ticket):
795        return False
796
797    # This method is also used by the ApplicantEditFormPage
798    def delPaymentTickets(self, **data):
799        form = self.request.form
800        if form.has_key('val_id'):
801            child_id = form['val_id']
802        else:
803            self.flash(_('No payment selected.'))
804            self.redirect(self.url(self.context))
805            return
806        if not isinstance(child_id, list):
807            child_id = [child_id]
808        deleted = []
809        for id in child_id:
810            # Applicants are not allowed to remove used payment tickets
811            if not self.unremovable(self.context[id]):
812                try:
813                    del self.context[id]
814                    deleted.append(id)
815                except:
816                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
817                            id, sys.exc_info()[0], sys.exc_info()[1]))
818        if len(deleted):
819            self.flash(_('Successfully removed: ${a}',
820                mapping = {'a':', '.join(deleted)}))
821            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
822            self.context.loggerInfo(
823                ob_class, 'removed: % s' % ', '.join(deleted))
824        return
825
826    # We explicitely want the forms to be validated before payment tickets
827    # can be created. If no validation is requested, use
828    # 'validator=NullValidator' in the action directive
829    @action(_('Add online payment ticket'))
830    def addPaymentTicket(self, **data):
831        self.redirect(self.url(self.context, '@@addafp'))
832        return
833
834    @jsaction(_('Remove selected tickets'))
835    def removePaymentTickets(self, **data):
836        self.delPaymentTickets(**data)
837        self.redirect(self.url(self.context) + '/@@manage')
838        return
839
840class ApplicantEditFormPage(ApplicantManageFormPage):
841    """An applicant-centered edit view for applicant data.
842    """
843    grok.context(IApplicantEdit)
844    grok.name('edit')
845    grok.require('waeup.handleApplication')
846    form_fields = grok.AutoFields(IApplicantEdit).omit(
847        'locked', 'course_admitted', 'student_id',
848        'screening_score',
849        )
850    form_fields['applicant_id'].for_display = True
851    form_fields['reg_number'].for_display = True
852    grok.template('applicanteditpage')
853    manage_applications = False
854
855    @property
856    def display_actions(self):
857        state = IWorkflowState(self.context).getState()
858        if state == INITIALIZED:
859            actions = [[],[]]
860        elif state == STARTED:
861            actions = [[_('Save')],
862                [_('Add online payment ticket'),_('Remove selected tickets')]]
863        elif state == PAID:
864            actions = [[_('Save'), _('Final Submit')],
865                [_('Remove selected tickets')]]
866        else:
867            actions = [[],[]]
868        return actions
869
870    def unremovable(self, ticket):
871        state = IWorkflowState(self.context).getState()
872        return ticket.r_code or state in (INITIALIZED, SUBMITTED)
873
874    def emit_lock_message(self):
875        self.flash(_('The requested form is locked (read-only).'))
876        self.redirect(self.url(self.context))
877        return
878
879    def update(self):
880        if self.context.locked:
881            self.emit_lock_message()
882            return
883        super(ApplicantEditFormPage, self).update()
884        return
885
886    def dataNotComplete(self):
887        store = getUtility(IExtFileStore)
888        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
889            return _('No passport picture uploaded.')
890        if not self.request.form.get('confirm_passport', False):
891            return _('Passport picture confirmation box not ticked.')
892        return False
893
894    # We explicitely want the forms to be validated before payment tickets
895    # can be created. If no validation is requested, use
896    # 'validator=NullValidator' in the action directive
897    @action(_('Add online payment ticket'))
898    def addPaymentTicket(self, **data):
899        self.redirect(self.url(self.context, '@@addafp'))
900        return
901
902    @jsaction(_('Remove selected tickets'))
903    def removePaymentTickets(self, **data):
904        self.delPaymentTickets(**data)
905        self.redirect(self.url(self.context) + '/@@edit')
906        return
907
908    @action(_('Save'), style='primary')
909    def save(self, **data):
910        if self.passport_changed is False:  # False is not None!
911            return # error during image upload. Ignore other values
912        self.applyData(self.context, **data)
913        self.flash('Form has been saved.')
914        return
915
916    @submitaction(_('Final Submit'))
917    def finalsubmit(self, **data):
918        if self.passport_changed is False:  # False is not None!
919            return # error during image upload. Ignore other values
920        if self.dataNotComplete():
921            self.flash(self.dataNotComplete())
922            return
923        self.applyData(self.context, **data)
924        state = IWorkflowState(self.context).getState()
925        # This shouldn't happen, but the application officer
926        # might have forgotten to lock the form after changing the state
927        if state != PAID:
928            self.flash(_('The form cannot be submitted. Wrong state!'))
929            return
930        if not self.context.__parent__.enddate or (
931            self.context.__parent__.enddate < datetime.now(pytz.utc)):
932            self.flash(
933                _('The form cannot be submitted. Application period has expired!'))
934            return
935        IWorkflowInfo(self.context).fireTransition('submit')
936        # application_date is used in export files for sorting.
937        # We can thus store utc.
938        self.context.application_date = datetime.utcnow()
939        self.context.locked = True
940        self.flash(_('Form has been submitted.'))
941        self.redirect(self.url(self.context))
942        return
943
944class PassportImage(grok.View):
945    """Renders the passport image for applicants.
946    """
947    grok.name('passport.jpg')
948    grok.context(IApplicant)
949    grok.require('waeup.viewApplication')
950
951    def render(self):
952        # A filename chooser turns a context into a filename suitable
953        # for file storage.
954        image = getUtility(IExtFileStore).getFileByContext(self.context)
955        self.response.setHeader(
956            'Content-Type', 'image/jpeg')
957        if image is None:
958            # show placeholder image
959            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
960        return image
961
962class ApplicantRegistrationPage(KofaAddFormPage):
963    """Captcha'd registration page for applicants.
964    """
965    grok.context(IApplicantsContainer)
966    grok.name('register')
967    grok.require('waeup.Anonymous')
968    grok.template('applicantregister')
969
970    @property
971    def form_fields(self):
972        form_fields = None
973        if self.context.mode == 'update':
974            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
975                'firstname','reg_number','email')
976        else: #if self.context.mode == 'create':
977            form_fields = grok.AutoFields(IApplicantEdit).select(
978                'firstname', 'middlename', 'lastname', 'email', 'phone')
979        return form_fields
980
981    @property
982    def label(self):
983        return _('Apply for ${a}',
984            mapping = {'a':self.context.title})
985
986    def update(self):
987        # Check if application has started ...
988        if not self.context.startdate or (
989            self.context.startdate > datetime.now(pytz.utc)):
990            self.flash(_('Application has not yet started.'))
991            self.redirect(self.url(self.context))
992            return
993        # ... or ended
994        if not self.context.enddate or (
995            self.context.enddate < datetime.now(pytz.utc)):
996            self.flash(_('Application has ended.'))
997            self.redirect(self.url(self.context))
998            return
999        # Handle captcha
1000        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1001        self.captcha_result = self.captcha.verify(self.request)
1002        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1003        return
1004
1005    @action(_('Get login credentials'), style='primary')
1006    def register(self, **data):
1007        if not self.captcha_result.is_valid:
1008            # Captcha will display error messages automatically.
1009            # No need to flash something.
1010            return
1011        if self.context.mode == 'create':
1012            # Add applicant
1013            applicant = createObject(u'waeup.Applicant')
1014            self.applyData(applicant, **data)
1015            self.context.addApplicant(applicant)
1016            applicant.reg_number = applicant.applicant_id
1017            notify(grok.ObjectModifiedEvent(applicant))
1018        elif self.context.mode == 'update':
1019            # Update applicant
1020            reg_number = data.get('reg_number','')
1021            firstname = data.get('firstname','')
1022            cat = getUtility(ICatalog, name='applicants_catalog')
1023            results = list(
1024                cat.searchResults(reg_number=(reg_number, reg_number)))
1025            if results:
1026                applicant = results[0]
1027                if getattr(applicant,'firstname',None) is None:
1028                    self.flash(_('An error occurred.'))
1029                    return
1030                elif applicant.firstname.lower() != firstname.lower():
1031                    # Don't tell the truth here. Anonymous must not
1032                    # know that a record was found and only the firstname
1033                    # verification failed.
1034                    self.flash(_('No application record found.'))
1035                    return
1036                elif applicant.password is not None:
1037                    self.flash(_('Your password has already been set. '
1038                                 'Please proceed to the login page.'))
1039                    return
1040                # Store email address but nothing else.
1041                applicant.email = data['email']
1042                notify(grok.ObjectModifiedEvent(applicant))
1043            else:
1044                # No record found, this is the truth.
1045                self.flash(_('No application record found.'))
1046                return
1047        else:
1048            # Does not happen but anyway ...
1049            return
1050        kofa_utils = getUtility(IKofaUtils)
1051        password = kofa_utils.genPassword()
1052        IUserAccount(applicant).setPassword(password)
1053        # Send email with credentials
1054        login_url = self.url(grok.getSite(), 'login')
1055        msg = _('You have successfully been registered for the')
1056        if kofa_utils.sendCredentials(IUserAccount(applicant),
1057            password, login_url, msg):
1058            self.redirect(self.url(self.context, 'registration_complete',
1059                                   data = dict(email=applicant.email)))
1060            return
1061        else:
1062            self.flash(_('Email could not been sent. Please retry later.'))
1063        return
1064
1065class ApplicantRegistrationEmailSent(KofaPage):
1066    """Landing page after successful registration.
1067    """
1068    grok.name('registration_complete')
1069    grok.require('waeup.Public')
1070    grok.template('applicantregemailsent')
1071    label = _('Your registration was successful.')
1072
1073    def update(self, email=None):
1074        self.email = email
1075        return
Note: See TracBrowser for help on using the repository browser.