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

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

Add 'Add applicant' action button.

  • Property svn:keywords set to Id
File size: 39.8 KB
Line 
1## $Id: browser.py 8684 2012-06-12 05:22:54Z 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 sys
22import grok
23from datetime import datetime, date
24from zope.event import notify
25from zope.component import getUtility, createObject, getAdapter
26from zope.catalog.interfaces import ICatalog
27from zope.i18n import translate
28from hurry.workflow.interfaces import (
29    IWorkflowInfo, IWorkflowState, InvalidTransitionError)
30from waeup.kofa.applicants.interfaces import (
31    IApplicant, IApplicantEdit, IApplicantsRoot,
32    IApplicantsContainer, IApplicantsContainerAdd,
33    MAX_UPLOAD_SIZE, IApplicantOnlinePayment, IApplicantsUtils,
34    IApplicantRegisterUpdate
35    )
36from waeup.kofa.applicants.applicant import search
37from waeup.kofa.applicants.workflow import (
38    INITIALIZED, STARTED, PAID, SUBMITTED, ADMITTED)
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 = [_('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(_('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
450    @action(_('Cancel'), validator=NullValidator)
451    def cancel(self, **data):
452        self.redirect(self.url(self.context))
453        return
454
455    @action(_('Add local role'), validator=NullValidator)
456    def addLocalRole(self, **data):
457        return add_local_role(self,3, **data)
458
459    @action(_('Remove selected local roles'))
460    def delLocalRoles(self, **data):
461        return del_local_roles(self,3,**data)
462
463class ApplicantAddFormPage(KofaAddFormPage):
464    """Add-form to add an applicant.
465    """
466    grok.context(IApplicantsContainer)
467    grok.require('waeup.manageApplication')
468    grok.name('addapplicant')
469    #grok.template('applicantaddpage')
470    form_fields = grok.AutoFields(IApplicant).select(
471        'firstname', 'middlename', 'lastname',
472        'email', 'phone')
473    label = _('Add applicant')
474    pnav = 3
475
476    @action(_('Create application record'))
477    def addApplicant(self, **data):
478        applicant = createObject(u'waeup.Applicant')
479        self.applyData(applicant, **data)
480        self.context.addApplicant(applicant)
481        self.flash(_('Applicant record created.'))
482        self.redirect(
483            self.url(self.context[applicant.application_number], 'index'))
484        return
485
486class ApplicantDisplayFormPage(KofaDisplayFormPage):
487    """A display view for applicant data.
488    """
489    grok.context(IApplicant)
490    grok.name('index')
491    grok.require('waeup.viewApplication')
492    grok.template('applicantdisplaypage')
493    form_fields = grok.AutoFields(IApplicant).omit(
494        'locked', 'course_admitted', 'password')
495    label = _('Applicant')
496    pnav = 3
497
498    @property
499    def separators(self):
500        return getUtility(IApplicantsUtils).SEPARATORS_DICT
501
502    def update(self):
503        self.passport_url = self.url(self.context, 'passport.jpg')
504        # Mark application as started if applicant logs in for the first time
505        usertype = getattr(self.request.principal, 'user_type', None)
506        if usertype == 'applicant' and \
507            IWorkflowState(self.context).getState() == INITIALIZED:
508            IWorkflowInfo(self.context).fireTransition('start')
509        return
510
511    @property
512    def hasPassword(self):
513        if self.context.password:
514            return _('set')
515        return _('unset')
516
517    @property
518    def label(self):
519        container_title = self.context.__parent__.title
520        return _('${a} <br /> Application Record ${b}', mapping = {
521            'a':container_title, 'b':self.context.application_number})
522
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
528        if getattr(course_admitted, '__parent__',None):
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 ''
534
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
541class CreateStudentPage(UtilityView, grok.View):
542    """Create a student object from applicant data.
543    """
544    grok.context(IApplicant)
545    grok.name('createstudent')
546    grok.require('waeup.manageStudent')
547
548    def update(self):
549        msg = self.context.createStudent(view=self)[1]
550        self.flash(msg)
551        self.redirect(self.url(self.context))
552        return
553
554    def render(self):
555        return
556
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.','')
580                self.context.__parent__.logger_info(
581                    ob_class,result.applicant_id,msg)
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
593class ApplicationFeePaymentAddPage(UtilityView, grok.View):
594    """ Page to add an online payment ticket
595    """
596    grok.context(IApplicant)
597    grok.name('addafp')
598    grok.require('waeup.payApplicant')
599    factory = u'waeup.ApplicantOnlinePayment'
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(
606                      _('This type of payment has already been made.'))
607                  self.redirect(self.url(self.context))
608                  return
609        applicants_utils = getUtility(IApplicantsUtils)
610        container = self.context.__parent__
611        payment = createObject(self.factory)
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
617        self.context[payment.p_id] = payment
618        self.flash(_('Payment ticket created.'))
619        self.redirect(self.url(payment))
620        return
621
622    def render(self):
623        return
624
625
626class OnlinePaymentDisplayFormPage(KofaDisplayFormPage):
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)
633    form_fields[
634        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
635    form_fields[
636        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
637    pnav = 3
638
639    @property
640    def label(self):
641        return _('${a}: Online Payment Ticket ${b}', mapping = {
642            'a':self.context.__parent__.display_fullname,
643            'b':self.context.p_id})
644
645class OnlinePaymentApprovePage(UtilityView, grok.View):
646    """ Approval view
647    """
648    grok.context(IApplicantOnlinePayment)
649    grok.name('approve')
650    grok.require('waeup.managePortal')
651
652    def update(self):
653        success, msg, log = self.context.approveApplicantPayment()
654        if log is not None:
655            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
656            self.context.__parent__.loggerInfo(ob_class, log)
657        self.flash(msg)
658        return
659
660    def render(self):
661        self.redirect(self.url(self.context, '@@index'))
662        return
663
664class ExportPDFPaymentSlipPage(UtilityView, grok.View):
665    """Deliver a PDF slip of the context.
666    """
667    grok.context(IApplicantOnlinePayment)
668    grok.name('payment_slip.pdf')
669    grok.require('waeup.viewApplication')
670    form_fields = grok.AutoFields(IApplicantOnlinePayment)
671    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
672    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
673    prefix = 'form'
674    note = None
675
676    @property
677    def title(self):
678        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
679        return translate(_('Payment Data'), 'waeup.kofa',
680            target_language=portal_language)
681
682    @property
683    def label(self):
684        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
685        return translate(_('Online Payment Slip'),
686            'waeup.kofa', target_language=portal_language) \
687            + ' %s' % self.context.p_id
688
689    def render(self):
690        #if self.context.p_state != 'paid':
691        #    self.flash(_('Ticket not yet paid.'))
692        #    self.redirect(self.url(self.context))
693        #    return
694        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
695            self.request)
696        students_utils = getUtility(IStudentsUtils)
697        return students_utils.renderPDF(self,'payment_slip.pdf',
698            self.context.__parent__, applicantview, note=self.note)
699
700class ExportPDFPage(UtilityView, grok.View):
701    """Deliver a PDF slip of the context.
702    """
703    grok.context(IApplicant)
704    grok.name('application_slip.pdf')
705    grok.require('waeup.viewApplication')
706    prefix = 'form'
707
708    def update(self):
709        if self.context.state in ('initialized', 'started'):
710            self.flash(
711                _('Please pay before trying to download the application slip.'))
712            return self.redirect(self.url(self.context))
713        return
714
715    def render(self):
716        pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
717            view=self)
718        self.response.setHeader(
719            'Content-Type', 'application/pdf')
720        return pdfstream
721
722def handle_img_upload(upload, context, view):
723    """Handle upload of applicant image.
724
725    Returns `True` in case of success or `False`.
726
727    Please note that file pointer passed in (`upload`) most probably
728    points to end of file when leaving this function.
729    """
730    size = file_size(upload)
731    if size > MAX_UPLOAD_SIZE:
732        view.flash(_('Uploaded image is too big!'))
733        return False
734    dummy, ext = os.path.splitext(upload.filename)
735    ext.lower()
736    if ext != '.jpg':
737        view.flash(_('jpg file extension expected.'))
738        return False
739    upload.seek(0) # file pointer moved when determining size
740    store = getUtility(IExtFileStore)
741    file_id = IFileStoreNameChooser(context).chooseName()
742    store.createFile(file_id, upload)
743    return True
744
745class ApplicantManageFormPage(KofaEditFormPage):
746    """A full edit view for applicant data.
747    """
748    grok.context(IApplicant)
749    grok.name('manage')
750    grok.require('waeup.manageApplication')
751    form_fields = grok.AutoFields(IApplicant)
752    form_fields['student_id'].for_display = True
753    form_fields['applicant_id'].for_display = True
754    grok.template('applicanteditpage')
755    manage_applications = True
756    pnav = 3
757    display_actions = [[_('Save'), _('Final Submit')],
758        [_('Add online payment ticket'),_('Remove selected tickets')]]
759
760    @property
761    def separators(self):
762        return getUtility(IApplicantsUtils).SEPARATORS_DICT
763
764    def update(self):
765        datepicker.need() # Enable jQuery datepicker in date fields.
766        warning.need()
767        super(ApplicantManageFormPage, self).update()
768        self.wf_info = IWorkflowInfo(self.context)
769        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
770        self.passport_changed = None
771        upload = self.request.form.get('form.passport', None)
772        if upload:
773            # We got a fresh upload
774            self.passport_changed = handle_img_upload(
775                upload, self.context, self)
776        return
777
778    @property
779    def label(self):
780        container_title = self.context.__parent__.title
781        return _('${a} <br /> Application Form ${b}', mapping = {
782            'a':container_title, 'b':self.context.application_number})
783
784    def getTransitions(self):
785        """Return a list of dicts of allowed transition ids and titles.
786
787        Each list entry provides keys ``name`` and ``title`` for
788        internal name and (human readable) title of a single
789        transition.
790        """
791        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
792            if not t[0] == 'pay']
793        return [dict(name='', title=_('No transition'))] +[
794            dict(name=x, title=y) for x, y in allowed_transitions]
795
796    @action(_('Save'), style='primary')
797    def save(self, **data):
798        form = self.request.form
799        password = form.get('password', None)
800        password_ctl = form.get('control_password', None)
801        if password:
802            validator = getUtility(IPasswordValidator)
803            errors = validator.validate_password(password, password_ctl)
804            if errors:
805                self.flash( ' '.join(errors))
806                return
807        if self.passport_changed is False:  # False is not None!
808            return # error during image upload. Ignore other values
809        changed_fields = self.applyData(self.context, **data)
810        # Turn list of lists into single list
811        if changed_fields:
812            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
813        else:
814            changed_fields = []
815        if self.passport_changed:
816            changed_fields.append('passport')
817        if password:
818            # Now we know that the form has no errors and can set password ...
819            IUserAccount(self.context).setPassword(password)
820            changed_fields.append('password')
821        fields_string = ' + '.join(changed_fields)
822        trans_id = form.get('transition', None)
823        if trans_id:
824            self.wf_info.fireTransition(trans_id)
825        self.flash(_('Form has been saved.'))
826        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
827        if fields_string:
828            self.context.loggerInfo(ob_class, 'saved: % s' % fields_string)
829        return
830
831    def unremovable(self, ticket):
832        return False
833
834    # This method is also used by the ApplicantEditFormPage
835    def delPaymentTickets(self, **data):
836        form = self.request.form
837        if form.has_key('val_id'):
838            child_id = form['val_id']
839        else:
840            self.flash(_('No payment selected.'))
841            self.redirect(self.url(self.context))
842            return
843        if not isinstance(child_id, list):
844            child_id = [child_id]
845        deleted = []
846        for id in child_id:
847            # Applicants are not allowed to remove used payment tickets
848            if not self.unremovable(self.context[id]):
849                try:
850                    del self.context[id]
851                    deleted.append(id)
852                except:
853                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
854                            id, sys.exc_info()[0], sys.exc_info()[1]))
855        if len(deleted):
856            self.flash(_('Successfully removed: ${a}',
857                mapping = {'a':', '.join(deleted)}))
858            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
859            self.context.loggerInfo(
860                ob_class, 'removed: % s' % ', '.join(deleted))
861        return
862
863    # We explicitely want the forms to be validated before payment tickets
864    # can be created. If no validation is requested, use
865    # 'validator=NullValidator' in the action directive
866    @action(_('Add online payment ticket'))
867    def addPaymentTicket(self, **data):
868        self.redirect(self.url(self.context, '@@addafp'))
869        return
870
871    @jsaction(_('Remove selected tickets'))
872    def removePaymentTickets(self, **data):
873        self.delPaymentTickets(**data)
874        self.redirect(self.url(self.context) + '/@@manage')
875        return
876
877class ApplicantEditFormPage(ApplicantManageFormPage):
878    """An applicant-centered edit view for applicant data.
879    """
880    grok.context(IApplicantEdit)
881    grok.name('edit')
882    grok.require('waeup.handleApplication')
883    form_fields = grok.AutoFields(IApplicantEdit).omit(
884        'locked', 'course_admitted', 'student_id',
885        'screening_score',
886        )
887    form_fields['applicant_id'].for_display = True
888    form_fields['reg_number'].for_display = True
889    grok.template('applicanteditpage')
890    manage_applications = False
891
892    @property
893    def display_actions(self):
894        state = IWorkflowState(self.context).getState()
895        if state == INITIALIZED:
896            actions = [[],[]]
897        elif state == STARTED:
898            actions = [[_('Save')],
899                [_('Add online payment ticket'),_('Remove selected tickets')]]
900        elif state == PAID:
901            actions = [[_('Save'), _('Final Submit')],
902                [_('Remove selected tickets')]]
903        else:
904            actions = [[],[]]
905        return actions
906
907    def unremovable(self, ticket):
908        state = IWorkflowState(self.context).getState()
909        return ticket.r_code or state in (INITIALIZED, SUBMITTED)
910
911    def emit_lock_message(self):
912        self.flash(_('The requested form is locked (read-only).'))
913        self.redirect(self.url(self.context))
914        return
915
916    def update(self):
917        if self.context.locked or (
918            self.context.__parent__.expired and
919            self.context.__parent__.strict_deadline):
920            self.emit_lock_message()
921            return
922        super(ApplicantEditFormPage, self).update()
923        return
924
925    def dataNotComplete(self):
926        store = getUtility(IExtFileStore)
927        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
928            return _('No passport picture uploaded.')
929        if not self.request.form.get('confirm_passport', False):
930            return _('Passport picture confirmation box not ticked.')
931        return False
932
933    # We explicitely want the forms to be validated before payment tickets
934    # can be created. If no validation is requested, use
935    # 'validator=NullValidator' in the action directive
936    @action(_('Add online payment ticket'))
937    def addPaymentTicket(self, **data):
938        self.redirect(self.url(self.context, '@@addafp'))
939        return
940
941    @jsaction(_('Remove selected tickets'))
942    def removePaymentTickets(self, **data):
943        self.delPaymentTickets(**data)
944        self.redirect(self.url(self.context) + '/@@edit')
945        return
946
947    @action(_('Save'), style='primary')
948    def save(self, **data):
949        if self.passport_changed is False:  # False is not None!
950            return # error during image upload. Ignore other values
951        self.applyData(self.context, **data)
952        self.flash('Form has been saved.')
953        return
954
955    @submitaction(_('Final Submit'))
956    def finalsubmit(self, **data):
957        if self.passport_changed is False:  # False is not None!
958            return # error during image upload. Ignore other values
959        if self.dataNotComplete():
960            self.flash(self.dataNotComplete())
961            return
962        self.applyData(self.context, **data)
963        state = IWorkflowState(self.context).getState()
964        # This shouldn't happen, but the application officer
965        # might have forgotten to lock the form after changing the state
966        if state != PAID:
967            self.flash(_('The form cannot be submitted. Wrong state!'))
968            return
969        IWorkflowInfo(self.context).fireTransition('submit')
970        # application_date is used in export files for sorting.
971        # We can thus store utc.
972        self.context.application_date = datetime.utcnow()
973        self.context.locked = True
974        self.flash(_('Form has been submitted.'))
975        self.redirect(self.url(self.context))
976        return
977
978class PassportImage(grok.View):
979    """Renders the passport image for applicants.
980    """
981    grok.name('passport.jpg')
982    grok.context(IApplicant)
983    grok.require('waeup.viewApplication')
984
985    def render(self):
986        # A filename chooser turns a context into a filename suitable
987        # for file storage.
988        image = getUtility(IExtFileStore).getFileByContext(self.context)
989        self.response.setHeader(
990            'Content-Type', 'image/jpeg')
991        if image is None:
992            # show placeholder image
993            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
994        return image
995
996class ApplicantRegistrationPage(KofaAddFormPage):
997    """Captcha'd registration page for applicants.
998    """
999    grok.context(IApplicantsContainer)
1000    grok.name('register')
1001    grok.require('waeup.Anonymous')
1002    grok.template('applicantregister')
1003
1004    @property
1005    def form_fields(self):
1006        form_fields = None
1007        if self.context.mode == 'update':
1008            form_fields = grok.AutoFields(IApplicantRegisterUpdate).select(
1009                'firstname','reg_number','email')
1010        else: #if self.context.mode == 'create':
1011            form_fields = grok.AutoFields(IApplicantEdit).select(
1012                'firstname', 'middlename', 'lastname', 'email', 'phone')
1013        return form_fields
1014
1015    @property
1016    def label(self):
1017        return _('Apply for ${a}',
1018            mapping = {'a':self.context.title})
1019
1020    def update(self):
1021        if self.context.expired:
1022            self.flash(_('Outside application period.'))
1023            self.redirect(self.url(self.context))
1024            return
1025        # Handle captcha
1026        self.captcha = getUtility(ICaptchaManager).getCaptcha()
1027        self.captcha_result = self.captcha.verify(self.request)
1028        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
1029        return
1030
1031    def _redirect(self, email, password, applicant_id):
1032        # Forward only email to landing page in base package.
1033        self.redirect(self.url(self.context, 'registration_complete',
1034            data = dict(email=email)))
1035        return
1036
1037    @action(_('Get login credentials'), style='primary')
1038    def register(self, **data):
1039        if not self.captcha_result.is_valid:
1040            # Captcha will display error messages automatically.
1041            # No need to flash something.
1042            return
1043        if self.context.mode == 'create':
1044            # Add applicant
1045            applicant = createObject(u'waeup.Applicant')
1046            self.applyData(applicant, **data)
1047            self.context.addApplicant(applicant)
1048            applicant.reg_number = applicant.applicant_id
1049            notify(grok.ObjectModifiedEvent(applicant))
1050        elif self.context.mode == 'update':
1051            # Update applicant
1052            reg_number = data.get('reg_number','')
1053            firstname = data.get('firstname','')
1054            cat = getUtility(ICatalog, name='applicants_catalog')
1055            results = list(
1056                cat.searchResults(reg_number=(reg_number, reg_number)))
1057            if results:
1058                applicant = results[0]
1059                if getattr(applicant,'firstname',None) is None:
1060                    self.flash(_('An error occurred.'))
1061                    return
1062                elif applicant.firstname.lower() != firstname.lower():
1063                    # Don't tell the truth here. Anonymous must not
1064                    # know that a record was found and only the firstname
1065                    # verification failed.
1066                    self.flash(_('No application record found.'))
1067                    return
1068                elif applicant.password is not None and \
1069                    applicant.state != INITIALIZED:
1070                    self.flash(_('Your password has already been set and used. '
1071                                 'Please proceed to the login page.'))
1072                    return
1073                # Store email address but nothing else.
1074                applicant.email = data['email']
1075                notify(grok.ObjectModifiedEvent(applicant))
1076            else:
1077                # No record found, this is the truth.
1078                self.flash(_('No application record found.'))
1079                return
1080        else:
1081            # Does not happen but anyway ...
1082            return
1083        kofa_utils = getUtility(IKofaUtils)
1084        password = kofa_utils.genPassword()
1085        IUserAccount(applicant).setPassword(password)
1086        # Send email with credentials
1087        login_url = self.url(grok.getSite(), 'login')
1088        msg = _('You have successfully been registered for the')
1089        if kofa_utils.sendCredentials(IUserAccount(applicant),
1090            password, login_url, msg):
1091            email_sent = applicant.email
1092        else:
1093            email_sent = None
1094        self._redirect(email=email_sent, password=password,
1095            applicant_id=applicant.applicant_id)
1096        return
1097
1098class ApplicantRegistrationEmailSent(KofaPage):
1099    """Landing page after successful registration.
1100
1101    """
1102    grok.name('registration_complete')
1103    grok.require('waeup.Public')
1104    grok.template('applicantregemailsent')
1105    label = _('Your registration was successful.')
1106
1107    def update(self, email=None, applicant_id=None, password=None):
1108        self.email = email
1109        self.password = password
1110        self.applicant_id = applicant_id
1111        return
Note: See TracBrowser for help on using the repository browser.