source: main/waeup.sirp/trunk/src/waeup/sirp/applicants/browser.py @ 7721

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

Continue internat. of applicants package including pdf exports.

  • Property svn:keywords set to Id
File size: 34.6 KB
RevLine 
[5273]1## $Id: browser.py 7714 2012-02-28 10:34:16Z 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
[7250]23from time import time
[7370]24from datetime import datetime, date
[7392]25from zope.component import getUtility, createObject, getAdapter
[6358]26from zope.formlib.form import setUpEditWidgets
[7714]27from zope.i18n import translate
[7322]28from hurry.workflow.interfaces import (
29    IWorkflowInfo, IWorkflowState, InvalidTransitionError)
[7363]30from waeup.sirp.applicants.interfaces import (
31    IApplicant, IApplicantEdit, IApplicantsRoot,
[7683]32    IApplicantsContainer, IApplicantsContainerAdd,
33    MAX_UPLOAD_SIZE, IApplicantOnlinePayment, IApplicantsUtils
[7363]34    )
35from waeup.sirp.applicants.workflow import INITIALIZED, STARTED, PAID, SUBMITTED
[5273]36from waeup.sirp.browser import (
[7363]37    SIRPPage, SIRPEditFormPage, SIRPAddFormPage, SIRPDisplayFormPage,
38    DEFAULT_PASSPORT_IMAGE_PATH)
39from waeup.sirp.browser.interfaces import ICaptchaManager
[6081]40from waeup.sirp.browser.breadcrumbs import Breadcrumb
[7459]41from waeup.sirp.browser.layout import (
42    NullValidator, jsaction, action, UtilityView)
[6321]43from waeup.sirp.browser.pages import add_local_role, del_local_roles
[7330]44from waeup.sirp.browser.resources import datepicker, tabs, datatable, warning
[7063]45from waeup.sirp.interfaces import (
[7392]46    ISIRPObject, ILocalRolesAssignable, IExtFileStore, IPDF,
[7365]47    IFileStoreNameChooser, IPasswordValidator, IUserAccount, ISIRPUtils)
[7687]48from waeup.sirp.interfaces import MessageFactory as _
[6321]49from waeup.sirp.permissions import get_users_with_local_roles
[7363]50from waeup.sirp.students.interfaces import IStudentsUtils
[7081]51from waeup.sirp.utils.helpers import string_from_bytes, file_size
[6054]52from waeup.sirp.widgets.datewidget import (
[7250]53    FriendlyDateWidget, FriendlyDateDisplayWidget,
54    FriendlyDatetimeDisplayWidget)
[7363]55from waeup.sirp.widgets.phonewidget import PhoneWidget
[6084]56from waeup.sirp.widgets.restwidget import ReSTDisplayWidget
[5320]57
[7321]58grok.context(ISIRPObject) # Make ISIRPObject the default context
[5273]59
[7321]60class ApplicantsRootPage(SIRPPage):
[5822]61    grok.context(IApplicantsRoot)
62    grok.name('index')
[6153]63    grok.require('waeup.Public')
[7710]64    label = _('Application Section')
[5843]65    pnav = 3
[6012]66
67    def update(self):
[6067]68        super(ApplicantsRootPage, self).update()
[7493]69        #datatable.need()
[6012]70        return
71
[7321]72class ApplicantsRootManageFormPage(SIRPEditFormPage):
[5828]73    grok.context(IApplicantsRoot)
74    grok.name('manage')
[6107]75    grok.template('applicantsrootmanagepage')
[7710]76    label = _('Manage application section')
[5843]77    pnav = 3
[7136]78    grok.require('waeup.manageApplication')
[7710]79    taboneactions = [_('Add applicants container'), _('Remove selected'),
80        _('Cancel')]
81    tabtwoactions1 = [_('Remove selected local roles')]
82    tabtwoactions2 = [_('Add local role')]
83    subunits = _('Applicants Containers')
[6078]84
[6069]85    def update(self):
86        tabs.need()
[6108]87        datatable.need()
[7330]88        warning.need()
[6069]89        return super(ApplicantsRootManageFormPage, self).update()
[5828]90
[6184]91    def getLocalRoles(self):
92        roles = ILocalRolesAssignable(self.context)
93        return roles()
94
95    def getUsers(self):
96        """Get a list of all users.
97        """
98        for key, val in grok.getSite()['users'].items():
99            url = self.url(val)
100            yield(dict(url=url, name=key, val=val))
101
102    def getUsersWithLocalRoles(self):
103        return get_users_with_local_roles(self.context)
104
[7710]105    @jsaction(_('Remove selected'))
[6069]106    def delApplicantsContainers(self, **data):
107        form = self.request.form
108        child_id = form['val_id']
109        if not isinstance(child_id, list):
110            child_id = [child_id]
111        deleted = []
112        for id in child_id:
113            try:
114                del self.context[id]
115                deleted.append(id)
116            except:
[7710]117                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[6069]118                        id, sys.exc_info()[0], sys.exc_info()[1]))
119        if len(deleted):
[7710]120            self.flash(_('Successfully removed:') + ' %s' % ', '.join(deleted))
[7484]121        self.redirect(self.url(self.context, '@@manage'))
[6078]122        return
[5828]123
[7710]124    @action(_('Add applicants container'), validator=NullValidator)
[6069]125    def addApplicantsContainer(self, **data):
126        self.redirect(self.url(self.context, '@@add'))
[6078]127        return
128
[7710]129    @action(_('Cancel'), validator=NullValidator)
[6069]130    def cancel(self, **data):
131        self.redirect(self.url(self.context))
[6078]132        return
133
[7710]134    @action(_('Add local role'), validator=NullValidator)
[6184]135    def addLocalRole(self, **data):
[7484]136        return add_local_role(self,3, **data)
[6184]137
[7710]138    @action(_('Remove selected local roles'))
[6184]139    def delLocalRoles(self, **data):
[7484]140        return del_local_roles(self,3,**data)
[6184]141
[7321]142class ApplicantsContainerAddFormPage(SIRPAddFormPage):
[5822]143    grok.context(IApplicantsRoot)
[7136]144    grok.require('waeup.manageApplication')
[5822]145    grok.name('add')
[6107]146    grok.template('applicantscontaineraddpage')
[7710]147    label = _('Add applicants container')
[5843]148    pnav = 3
[6078]149
[6103]150    form_fields = grok.AutoFields(
[7708]151        IApplicantsContainerAdd).omit('code').omit('title', 'description_dict')
[6083]152    form_fields['startdate'].custom_widget = FriendlyDateWidget('le')
153    form_fields['enddate'].custom_widget = FriendlyDateWidget('le')
[6078]154
[6083]155    def update(self):
156        datepicker.need() # Enable jQuery datepicker in date fields.
157        return super(ApplicantsContainerAddFormPage, self).update()
158
[7710]159    @action(_('Add applicants container'))
[6069]160    def addApplicantsContainer(self, **data):
[6103]161        year = data['year']
162        code = u'%s%s' % (data['prefix'], year)
[7683]163        appcats_dict = getUtility(IApplicantsUtils).getApplicationTypeDict()
[7685]164        title = appcats_dict[data['prefix']][0]
165        title = u'%s %s/%s' % (title, year, year + 1)
[6087]166        if code in self.context.keys():
[6105]167            self.flash(
[7710]168                _('An applicants container for the same application type and entrance year exists already in the database.'))
[5822]169            return
170        # Add new applicants container...
[6083]171        provider = data['provider'][1]
[5822]172        container = provider.factory()
[6069]173        self.applyData(container, **data)
[6087]174        container.code = code
175        container.title = title
176        self.context[code] = container
[7710]177        self.flash(_('Added:') + ' "%s".' % code)
[7484]178        self.redirect(self.url(self.context, u'@@manage'))
[5822]179        return
[6078]180
[7710]181    @action(_('Cancel'), validator=NullValidator)
[6069]182    def cancel(self, **data):
[7484]183        self.redirect(self.url(self.context, '@@manage'))
[6078]184
[5845]185class ApplicantsRootBreadcrumb(Breadcrumb):
186    """A breadcrumb for applicantsroot.
187    """
188    grok.context(IApplicantsRoot)
[7710]189    title = _(u'Applicants')
[6078]190
[5845]191class ApplicantsContainerBreadcrumb(Breadcrumb):
192    """A breadcrumb for applicantscontainers.
193    """
194    grok.context(IApplicantsContainer)
[6319]195
[6153]196class ApplicantBreadcrumb(Breadcrumb):
197    """A breadcrumb for applicants.
198    """
199    grok.context(IApplicant)
[6319]200
[6153]201    @property
202    def title(self):
203        """Get a title for a context.
204        """
[7240]205        return self.context.application_number
[5828]206
[7250]207class OnlinePaymentBreadcrumb(Breadcrumb):
208    """A breadcrumb for payments.
209    """
210    grok.context(IApplicantOnlinePayment)
211
212    @property
213    def title(self):
214        return self.context.p_id
215
[7321]216class ApplicantsContainerPage(SIRPDisplayFormPage):
[5830]217    """The standard view for regular applicant containers.
218    """
219    grok.context(IApplicantsContainer)
220    grok.name('index')
[6153]221    grok.require('waeup.Public')
[6029]222    grok.template('applicantscontainerpage')
[5850]223    pnav = 3
[6053]224
[7708]225    form_fields = grok.AutoFields(IApplicantsContainer).omit(
226        'title', 'description_dict')
[6054]227    form_fields['startdate'].custom_widget = FriendlyDateDisplayWidget('le')
228    form_fields['enddate'].custom_widget = FriendlyDateDisplayWidget('le')
[6084]229    form_fields['description'].custom_widget = ReSTDisplayWidget
[6053]230
[5837]231    @property
[7708]232    def introduction(self):
233        portal_language = getUtility(ISIRPUtils).PORTAL_LANGUAGE
234        lang = self.request.cookies.get('sirp.language', portal_language)
235        html = self.context.description_dict.get(lang,'')
236        if html =='':
237            html = self.context.description_dict.get(portal_language,'')
238        if html =='':
239            return ''
240        else:
241            return html
242
243    @property
[7467]244    def label(self):
[7493]245        return "%s" % self.context.title
[5837]246
[7321]247class ApplicantsContainerManageFormPage(SIRPEditFormPage):
[5837]248    grok.context(IApplicantsContainer)
[5850]249    grok.name('manage')
[6107]250    grok.template('applicantscontainermanagepage')
[7708]251    form_fields = grok.AutoFields(IApplicantsContainer).omit(
252        'title', 'description_dict')
[7710]253    taboneactions = [_('Save'),_('Cancel')]
254    tabtwoactions = [_('Add applicant'), _('Remove selected'),_('Cancel')]
255    tabthreeactions1 = [_('Remove selected local roles')]
256    tabthreeactions2 = [_('Add local role')]
[5844]257    # Use friendlier date widget...
[6054]258    form_fields['startdate'].custom_widget = FriendlyDateWidget('le')
259    form_fields['enddate'].custom_widget = FriendlyDateWidget('le')
[7136]260    grok.require('waeup.manageApplication')
[5850]261
262    @property
263    def label(self):
[7710]264        return _('Manage applicants container')
[5850]265
[5845]266    pnav = 3
[5837]267
268    def update(self):
[5850]269        datepicker.need() # Enable jQuery datepicker in date fields.
[5982]270        tabs.need()
[7484]271        self.tab1 = self.tab2 = self.tab3 = ''
272        qs = self.request.get('QUERY_STRING', '')
273        if not qs:
274            qs = 'tab1'
275        setattr(self, qs, 'active')
[7330]276        warning.need()
[6015]277        datatable.need()  # Enable jQurey datatables for contents listing
[6107]278        return super(ApplicantsContainerManageFormPage, self).update()
[5837]279
[6184]280    def getLocalRoles(self):
281        roles = ILocalRolesAssignable(self.context)
282        return roles()
283
284    def getUsers(self):
285        """Get a list of all users.
286        """
287        for key, val in grok.getSite()['users'].items():
288            url = self.url(val)
289            yield(dict(url=url, name=key, val=val))
290
291    def getUsersWithLocalRoles(self):
292        return get_users_with_local_roles(self.context)
293
[7708]294    def _description(self):
295        view = ApplicantsContainerPage(
296            self.context,self.request)
297        view.setUpWidgets()
298        return view.widgets['description']()
299
[7714]300    @action(_('Save'), style='primary')
[7489]301    def save(self, **data):
[5837]302        self.applyData(self.context, **data)
[7708]303        self.context.description_dict = self._description()
[7710]304        self.flash(_('Form has been saved.'))
[5837]305        return
[6078]306
[7710]307    @jsaction(_('Remove selected'))
[6105]308    def delApplicant(self, **data):
[6189]309        form = self.request.form
310        if form.has_key('val_id'):
311            child_id = form['val_id']
312        else:
[7710]313            self.flash(_('No applicant selected!'))
[7484]314            self.redirect(self.url(self.context, '@@manage')+'?tab2')
[6189]315            return
316        if not isinstance(child_id, list):
317            child_id = [child_id]
318        deleted = []
319        for id in child_id:
320            try:
321                del self.context[id]
322                deleted.append(id)
323            except:
[7710]324                self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[6189]325                        id, sys.exc_info()[0], sys.exc_info()[1]))
326        if len(deleted):
[7710]327            self.flash(_('Successfully removed:') + ' %s' % ', '.join(deleted))
[7484]328        self.redirect(self.url(self.context, u'@@manage')+'?tab2')
[6189]329        return
[6105]330
[7710]331    @action(_('Add applicant'), validator=NullValidator)
[6105]332    def addApplicant(self, **data):
[6327]333        self.redirect(self.url(self.context, 'addapplicant'))
334        return
[6105]335
[7710]336    @action(_('Cancel'), validator=NullValidator)
[5837]337    def cancel(self, **data):
338        self.redirect(self.url(self.context))
339        return
[5886]340
[7710]341    @action(_('Add local role'), validator=NullValidator)
[6184]342    def addLocalRole(self, **data):
343        return add_local_role(self,3, **data)
[6105]344
[7710]345    @action(_('Remove selected local roles'))
[6184]346    def delLocalRoles(self, **data):
347        return del_local_roles(self,3,**data)
348
[7321]349class ApplicantAddFormPage(SIRPAddFormPage):
[6622]350    """Add-form to add an applicant.
[6327]351    """
352    grok.context(IApplicantsContainer)
[7136]353    grok.require('waeup.manageApplication')
[6327]354    grok.name('addapplicant')
[7240]355    #grok.template('applicantaddpage')
356    form_fields = grok.AutoFields(IApplicant).select(
[7356]357        'firstname', 'middlename', 'lastname',
[7240]358        'email', 'phone')
[7714]359    label = _('Add applicant')
[6327]360    pnav = 3
361
[7714]362    @action(_('Create application record'))
[6327]363    def addApplicant(self, **data):
[7260]364        applicant = createObject(u'waeup.Applicant')
[7240]365        self.applyData(applicant, **data)
366        self.context.addApplicant(applicant)
[7714]367        self.flash(_('Applicant record created.'))
[7363]368        self.redirect(
369            self.url(self.context[applicant.application_number], 'index'))
[6327]370        return
371
[7321]372class ApplicantDisplayFormPage(SIRPDisplayFormPage):
[5273]373    grok.context(IApplicant)
374    grok.name('index')
[7113]375    grok.require('waeup.viewApplication')
[7200]376    grok.template('applicantdisplaypage')
[6320]377    form_fields = grok.AutoFields(IApplicant).omit(
[7347]378        'locked', 'course_admitted', 'password')
[6054]379    form_fields['date_of_birth'].custom_widget = FriendlyDateDisplayWidget('le')
[7714]380    label = _('Applicant')
[5843]381    pnav = 3
[5273]382
[7063]383    def update(self):
384        self.passport_url = self.url(self.context, 'passport.jpg')
[7240]385        # Mark application as started if applicant logs in for the first time
[7272]386        usertype = getattr(self.request.principal, 'user_type', None)
387        if usertype == 'applicant' and \
388            IWorkflowState(self.context).getState() == INITIALIZED:
[7240]389            IWorkflowInfo(self.context).fireTransition('start')
[7063]390        return
391
[6196]392    @property
[7240]393    def hasPassword(self):
394        if self.context.password:
[7714]395            return _('set')
396        return _('unset')
[7240]397
398    @property
[6196]399    def label(self):
400        container_title = self.context.__parent__.title
[7714]401        return _('${a} Application Record ${b}', mapping = {
402            'a':container_title, 'b':self.context.application_number})
[6196]403
[7347]404    def getCourseAdmitted(self):
405        """Return link, title and code in html format to the certificate
406           admitted.
407        """
408        course_admitted = self.context.course_admitted
[7351]409        if getattr(course_admitted, '__parent__',None):
[7347]410            url = self.url(course_admitted)
411            title = course_admitted.title
412            code = course_admitted.code
413            return '<a href="%s">%s - %s</a>' %(url,code,title)
414        return ''
[6254]415
[7259]416class ApplicantBaseDisplayFormPage(ApplicantDisplayFormPage):
417    grok.context(IApplicant)
418    grok.name('base')
419    form_fields = grok.AutoFields(IApplicant).select(
420        'applicant_id', 'firstname', 'lastname','email', 'course1')
421
[7459]422class CreateStudentPage(UtilityView, grok.View):
[7341]423    """Create a student object from applicatnt data
424    and copy applicant object.
425    """
426    grok.context(IApplicant)
427    grok.name('createstudent')
428    grok.require('waeup.manageStudent')
429
430    def update(self):
431        msg = self.context.createStudent()[1]
432        self.flash(msg)
433        self.redirect(self.url(self.context))
434        return
435
436    def render(self):
437        return
438
[7459]439class AcceptanceFeePaymentAddPage(UtilityView, grok.View):
[7250]440    """ Page to add an online payment ticket
441    """
442    grok.context(IApplicant)
443    grok.name('addafp')
444    grok.require('waeup.payApplicant')
445
446    def update(self):
447        p_category = 'acceptance'
448        session = str(self.context.__parent__.year)
449        try:
450            academic_session = grok.getSite()['configuration'][session]
451        except KeyError:
[7714]452            self.flash(_('Session configuration object is not available.'))
[7250]453            return
454        timestamp = "%d" % int(time()*1000)
455        for key in self.context.keys():
456            ticket = self.context[key]
457            if ticket.p_state == 'paid':
458                  self.flash(
[7714]459                      _('This type of payment has already been made.'))
[7250]460                  self.redirect(self.url(self.context))
461                  return
462        payment = createObject(u'waeup.ApplicantOnlinePayment')
463        payment.p_id = "p%s" % timestamp
464        payment.p_item = self.context.__parent__.title
465        payment.p_year = self.context.__parent__.year
466        payment.p_category = p_category
467        payment.amount_auth = academic_session.acceptance_fee
468        payment.surcharge_1 = academic_session.surcharge_1
469        payment.surcharge_2 = academic_session.surcharge_2
470        payment.surcharge_3 = academic_session.surcharge_3
471        self.context[payment.p_id] = payment
[7714]472        self.flash(_('Payment ticket created.'))
[7250]473        return
474
475    def render(self):
476        usertype = getattr(self.request.principal, 'user_type', None)
477        if usertype == 'applicant':
478            self.redirect(self.url(self.context, '@@edit'))
479            return
480        self.redirect(self.url(self.context, '@@manage'))
481        return
482
483
[7321]484class OnlinePaymentDisplayFormPage(SIRPDisplayFormPage):
[7250]485    """ Page to view an online payment ticket
486    """
487    grok.context(IApplicantOnlinePayment)
488    grok.name('index')
489    grok.require('waeup.viewApplication')
490    form_fields = grok.AutoFields(IApplicantOnlinePayment)
[7363]491    form_fields[
492        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
493    form_fields[
494        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[7250]495    pnav = 3
496
497    @property
498    def label(self):
[7714]499        return _('${a}: Online Payment Ticket ${b}', mapping = {
500            'a':self.context.__parent__.display_fullname, 'b':self.context.p_id})
[7250]501
[7459]502class OnlinePaymentCallbackPage(UtilityView, grok.View):
[7250]503    """ Callback view
504    """
505    grok.context(IApplicantOnlinePayment)
506    grok.name('callback')
507    grok.require('waeup.payApplicant')
508
509    # This update method simulates a valid callback und must be
510    # specified in the customization package. The parameters must be taken
511    # from the incoming request.
512    def update(self):
[7322]513        self.wf_info = IWorkflowInfo(self.context.__parent__)
514        try:
515            self.wf_info.fireTransition('pay')
516        except InvalidTransitionError:
517            self.flash('Error: %s' % sys.exc_info()[1])
[7250]518            return
519        self.context.r_amount_approved = self.context.amount_auth
520        self.context.r_card_num = u'0000'
521        self.context.r_code = u'00'
522        self.context.p_state = 'paid'
523        self.context.payment_date = datetime.now()
524        ob_class = self.__implemented__.__name__.replace('waeup.sirp.','')
525        self.context.__parent__.loggerInfo(
526            ob_class, 'valid callback: %s' % self.context.p_id)
[7714]527        self.flash(_('Valid callback received.'))
[7250]528        return
529
530    def render(self):
531        self.redirect(self.url(self.context, '@@index'))
532        return
533
[7459]534class ExportPDFPaymentSlipPage(UtilityView, grok.View):
[7250]535    """Deliver a PDF slip of the context.
536    """
537    grok.context(IApplicantOnlinePayment)
538    grok.name('payment_receipt.pdf')
539    grok.require('waeup.viewApplication')
540    form_fields = grok.AutoFields(IApplicantOnlinePayment)
541    form_fields['creation_date'].custom_widget = FriendlyDateDisplayWidget('le')
542    form_fields['payment_date'].custom_widget = FriendlyDateDisplayWidget('le')
543    prefix = 'form'
544
545    @property
[7714]546    def title(self):
547        portal_language = getUtility(ISIRPUtils).PORTAL_LANGUAGE
548        return translate(_('Payment Data'), 'waeup.sirp',
549            target_language=portal_language)
550
551    @property
[7250]552    def label(self):
[7714]553        portal_language = getUtility(ISIRPUtils).PORTAL_LANGUAGE
554        return translate(_('Online Payment Receipt'),
555            'waeup.sirp', target_language=portal_language) \
556            + ' %s' % self.context.p_id
[7250]557
558    def render(self):
559        if self.context.p_state != 'paid':
[7714]560            self.flash(_('Ticket not yet paid.'))
[7250]561            self.redirect(self.url(self.context))
562            return
[7259]563        applicantview = ApplicantBaseDisplayFormPage(self.context.__parent__,
[7250]564            self.request)
565        students_utils = getUtility(IStudentsUtils)
[7318]566        return students_utils.renderPDF(self,'payment_receipt.pdf',
[7250]567            self.context.__parent__, applicantview)
568
[7459]569class ExportPDFPage(UtilityView, grok.View):
[6358]570    """Deliver a PDF slip of the context.
571    """
572    grok.context(IApplicant)
573    grok.name('application_slip.pdf')
[7136]574    grok.require('waeup.viewApplication')
[6358]575    form_fields = grok.AutoFields(IApplicant).omit(
[7347]576        'locked', 'course_admitted')
[6358]577    form_fields['date_of_birth'].custom_widget = FriendlyDateDisplayWidget('le')
578    prefix = 'form'
579
[7714]580    #@property
581    #def label(self):
582    #    portal_language = getUtility(ISIRPUtils).PORTAL_LANGUAGE
583    #    container_title = self.context.__parent__.title
584    #    label = translate('Application Record',
585    #        'waeup.sirp', target_language=portal_language)
586    #    return container_title +  label + self.context.application_number
[6363]587
[7714]588    #def getCourseAdmitted(self):
589    #    """Return title and code in html format to the certificate
590    #       admitted.
591    #    """
592    #    course_admitted = self.context.course_admitted
593    #    #if ICertificate.providedBy(course_admitted):
594    #    if getattr(course_admitted, '__parent__',None):
595    #        title = course_admitted.title
596    #        code = course_admitted.code
597    #        return '%s - %s' %(code,title)
598    #    return ''
[6358]599
[7714]600    #def setUpWidgets(self, ignore_request=False):
601    #    self.adapters = {}
602    #    self.widgets = setUpEditWidgets(
603    #        self.form_fields, self.prefix, self.context, self.request,
604    #        adapters=self.adapters, for_display=True,
605    #        ignore_request=ignore_request
606    #        )
[6358]607
608    def render(self):
[7392]609        pdfstream = getAdapter(self.context, IPDF, name='application_slip')(
610            view=self)
[6358]611        self.response.setHeader(
612            'Content-Type', 'application/pdf')
[7392]613        return pdfstream
[6358]614
[7081]615def handle_img_upload(upload, context, view):
[7063]616    """Handle upload of applicant image.
[7081]617
618    Returns `True` in case of success or `False`.
619
620    Please note that file pointer passed in (`upload`) most probably
621    points to end of file when leaving this function.
[7063]622    """
[7081]623    size = file_size(upload)
624    if size > MAX_UPLOAD_SIZE:
[7714]625        view.flash(_('Uploaded image is too big!'))
[7081]626        return False
[7247]627    dummy, ext = os.path.splitext(upload.filename)
628    ext.lower()
629    if ext != '.jpg':
[7714]630        view.flash(_('jpg file extension expected.'))
[7247]631        return False
[7081]632    upload.seek(0) # file pointer moved when determining size
[7063]633    store = getUtility(IExtFileStore)
634    file_id = IFileStoreNameChooser(context).chooseName()
635    store.createFile(file_id, upload)
[7081]636    return True
[7063]637
[7321]638class ApplicantManageFormPage(SIRPEditFormPage):
[6196]639    """A full edit view for applicant data.
640    """
641    grok.context(IApplicant)
[7200]642    grok.name('manage')
[7136]643    grok.require('waeup.manageApplication')
[6476]644    form_fields = grok.AutoFields(IApplicant)
[6196]645    form_fields['date_of_birth'].custom_widget = FriendlyDateWidget('le-year')
[7351]646    form_fields['student_id'].for_display = True
[7378]647    form_fields['applicant_id'].for_display = True
[7423]648    form_fields['phone'].custom_widget = PhoneWidget
[7200]649    grok.template('applicanteditpage')
[6322]650    manage_applications = True
[6196]651    pnav = 3
[7714]652    display_actions = [[_('Save'), _('Final Submit')],
653        [_('Add online payment ticket'),_('Remove selected tickets')]]
[6196]654
655    def update(self):
656        datepicker.need() # Enable jQuery datepicker in date fields.
[7330]657        warning.need()
[7200]658        super(ApplicantManageFormPage, self).update()
[6353]659        self.wf_info = IWorkflowInfo(self.context)
[7081]660        self.max_upload_size = string_from_bytes(MAX_UPLOAD_SIZE)
[7084]661        self.passport_changed = None
[6598]662        upload = self.request.form.get('form.passport', None)
663        if upload:
664            # We got a fresh upload
[7084]665            self.passport_changed = handle_img_upload(
666                upload, self.context, self)
[6196]667        return
668
669    @property
670    def label(self):
671        container_title = self.context.__parent__.title
[7714]672        return _('${a} Application Form ${b}', mapping = {
673            'a':container_title, 'b':self.context.application_number})
[6196]674
[6303]675    def getTransitions(self):
[6351]676        """Return a list of dicts of allowed transition ids and titles.
[6353]677
678        Each list entry provides keys ``name`` and ``title`` for
679        internal name and (human readable) title of a single
680        transition.
[6349]681        """
[6353]682        allowed_transitions = self.wf_info.getManualTransitions()
[7687]683        return [dict(name='', title=_('No transition'))] +[
[6355]684            dict(name=x, title=y) for x, y in allowed_transitions]
[6303]685
[7714]686    @action(_('Save'), style='primary')
[6196]687    def save(self, **data):
[7240]688        form = self.request.form
689        password = form.get('password', None)
690        password_ctl = form.get('control_password', None)
691        if password:
692            validator = getUtility(IPasswordValidator)
693            errors = validator.validate_password(password, password_ctl)
694            if errors:
695                self.flash( ' '.join(errors))
696                return
[7084]697        if self.passport_changed is False:  # False is not None!
698            return # error during image upload. Ignore other values
[6475]699        changed_fields = self.applyData(self.context, **data)
[7199]700        # Turn list of lists into single list
701        if changed_fields:
702            changed_fields = reduce(lambda x,y: x+y, changed_fields.values())
[7240]703        else:
704            changed_fields = []
705        if self.passport_changed:
706            changed_fields.append('passport')
707        if password:
708            # Now we know that the form has no errors and can set password ...
709            IUserAccount(self.context).setPassword(password)
710            changed_fields.append('password')
[7199]711        fields_string = ' + '.join(changed_fields)
[7085]712        trans_id = form.get('transition', None)
713        if trans_id:
714            self.wf_info.fireTransition(trans_id)
[7714]715        self.flash(_('Form has been saved.'))
[6475]716        ob_class = self.__implemented__.__name__.replace('waeup.sirp.','')
[6644]717        if fields_string:
718            self.context.loggerInfo(ob_class, 'saved: % s' % fields_string)
[6196]719        return
720
[7250]721    def unremovable(self, ticket):
[7330]722        return False
[7250]723
724    # This method is also used by the ApplicantEditFormPage
725    def delPaymentTickets(self, **data):
726        form = self.request.form
727        if form.has_key('val_id'):
728            child_id = form['val_id']
729        else:
[7714]730            self.flash(_('No payment selected.'))
[7250]731            self.redirect(self.url(self.context))
732            return
733        if not isinstance(child_id, list):
734            child_id = [child_id]
735        deleted = []
736        for id in child_id:
737            # Applicants are not allowed to remove used payment tickets
738            if not self.unremovable(self.context[id]):
739                try:
740                    del self.context[id]
741                    deleted.append(id)
742                except:
[7714]743                    self.flash(_('Could not delete:') + ' %s: %s: %s' % (
[7250]744                            id, sys.exc_info()[0], sys.exc_info()[1]))
745        if len(deleted):
[7714]746            self.flash(_('Successfully removed:') + ' %s' % ', '.join(deleted))
[7250]747            ob_class = self.__implemented__.__name__.replace('waeup.sirp.','')
[7363]748            self.context.loggerInfo(
749                ob_class, 'removed: % s' % ', '.join(deleted))
[7250]750        return
751
[7252]752    # We explicitely want the forms to be validated before payment tickets
753    # can be created. If no validation is requested, use
[7459]754    # 'validator=NullValidator' in the action directive
[7714]755    @action(_('Add online payment ticket'))
[7250]756    def addPaymentTicket(self, **data):
757        self.redirect(self.url(self.context, '@@addafp'))
[7252]758        return
[7250]759
[7714]760    @jsaction(_('Remove selected tickets'))
[7250]761    def removePaymentTickets(self, **data):
762        self.delPaymentTickets(**data)
763        self.redirect(self.url(self.context) + '/@@manage')
764        return
765
[7200]766class ApplicantEditFormPage(ApplicantManageFormPage):
[5982]767    """An applicant-centered edit view for applicant data.
768    """
[6196]769    grok.context(IApplicantEdit)
[5273]770    grok.name('edit')
[6198]771    grok.require('waeup.handleApplication')
[6459]772    form_fields = grok.AutoFields(IApplicantEdit).omit(
[6476]773        'locked', 'course_admitted', 'student_id',
[7378]774        'screening_score', 'reg_number'
[6459]775        )
[6054]776    form_fields['date_of_birth'].custom_widget = FriendlyDateWidget('le-year')
[7433]777    form_fields['phone'].custom_widget = PhoneWidget
[7459]778    form_fields['applicant_id'].for_display = True
[7200]779    grok.template('applicanteditpage')
[6322]780    manage_applications = False
[5484]781
[7250]782    @property
783    def display_actions(self):
784        state = IWorkflowState(self.context).getState()
785        if state == INITIALIZED:
786            actions = [[],[]]
787        elif state == STARTED:
[7714]788            actions = [[_('Save')],
789                [_('Add online payment ticket'),_('Remove selected tickets')]]
[7250]790        elif state == PAID:
[7714]791            actions = [[_('Save'), _('Final Submit')],
792                [_('Remove selected tickets')]]
[7351]793        else:
[7250]794            actions = [[],[]]
795        return actions
796
[7330]797    def unremovable(self, ticket):
798        state = IWorkflowState(self.context).getState()
799        return ticket.r_code or state in (INITIALIZED, SUBMITTED)
800
[7145]801    def emit_lock_message(self):
[7714]802        self.flash(_('The requested form is locked (read-only).'))
[5941]803        self.redirect(self.url(self.context))
804        return
[6078]805
[5686]806    def update(self):
[5941]807        if self.context.locked:
[7145]808            self.emit_lock_message()
[5941]809            return
[7200]810        super(ApplicantEditFormPage, self).update()
[5686]811        return
[5952]812
[6196]813    def dataNotComplete(self):
[7252]814        store = getUtility(IExtFileStore)
815        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
[7714]816            return _('No passport picture uploaded.')
[6322]817        if not self.request.form.get('confirm_passport', False):
[7714]818            return _('Passport picture confirmation box not ticked.')
[6196]819        return False
[5952]820
[7252]821    # We explicitely want the forms to be validated before payment tickets
822    # can be created. If no validation is requested, use
[7459]823    # 'validator=NullValidator' in the action directive
[7714]824    @action(_('Add online payment ticket'))
[7250]825    def addPaymentTicket(self, **data):
826        self.redirect(self.url(self.context, '@@addafp'))
[7252]827        return
[7250]828
[7714]829    @jsaction(_('Remove selected tickets'))
[7250]830    def removePaymentTickets(self, **data):
831        self.delPaymentTickets(**data)
832        self.redirect(self.url(self.context) + '/@@edit')
833        return
834
[7714]835    @action(_('Save'))
[5273]836    def save(self, **data):
[7084]837        if self.passport_changed is False:  # False is not None!
838            return # error during image upload. Ignore other values
[5273]839        self.applyData(self.context, **data)
[6196]840        self.flash('Form has been saved.')
[5273]841        return
842
[7714]843    @action(_('Final Submit'))
[5484]844    def finalsubmit(self, **data):
[7084]845        if self.passport_changed is False:  # False is not None!
846            return # error during image upload. Ignore other values
[6196]847        if self.dataNotComplete():
848            self.flash(self.dataNotComplete())
[5941]849            return
[7252]850        self.applyData(self.context, **data)
[6303]851        state = IWorkflowState(self.context).getState()
[6322]852        # This shouldn't happen, but the application officer
853        # might have forgotten to lock the form after changing the state
[7250]854        if state != PAID:
[7714]855            self.flash(_('This form cannot be submitted. Wrong state!'))
[6303]856            return
857        IWorkflowInfo(self.context).fireTransition('submit')
[6476]858        self.context.application_date = datetime.now()
[5941]859        self.context.locked = True
[7714]860        self.flash(_('Form has been submitted.'))
[6196]861        self.redirect(self.url(self.context))
[5273]862        return
[5941]863
[7063]864class PassportImage(grok.View):
865    """Renders the passport image for applicants.
866    """
867    grok.name('passport.jpg')
868    grok.context(IApplicant)
[7113]869    grok.require('waeup.viewApplication')
[7063]870
871    def render(self):
872        # A filename chooser turns a context into a filename suitable
873        # for file storage.
874        image = getUtility(IExtFileStore).getFileByContext(self.context)
875        self.response.setHeader(
876            'Content-Type', 'image/jpeg')
877        if image is None:
878            # show placeholder image
[7089]879            return open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb').read()
[7063]880        return image
[7363]881
882class ApplicantRegistrationPage(SIRPAddFormPage):
883    """Captcha'd registration page for applicants.
884    """
885    grok.context(IApplicantsContainer)
886    grok.name('register')
[7373]887    grok.require('waeup.Anonymous')
[7363]888    grok.template('applicantregister')
889    form_fields = grok.AutoFields(IApplicantEdit).select(
890        'firstname', 'middlename', 'lastname', 'email', 'phone')
891    form_fields['phone'].custom_widget = PhoneWidget
892
[7368]893    @property
894    def label(self):
[7714]895        return _('Register for ${a} Application',
896            mapping = {'a':self.context.title})
[7368]897
[7363]898    def update(self):
[7368]899        # Check if application has started ...
900        if not self.context.startdate or self.context.startdate > date.today():
[7714]901            self.flash(_('Application has not yet started.'))
[7368]902            self.redirect(self.url(self.context))
903            return
904        # ... or ended
905        if not self.context.enddate or self.context.enddate < date.today():
[7714]906            self.flash(_('Application has ended.'))
[7368]907            self.redirect(self.url(self.context))
908            return
909        # Handle captcha
[7363]910        self.captcha = getUtility(ICaptchaManager).getCaptcha()
911        self.captcha_result = self.captcha.verify(self.request)
912        self.captcha_code = self.captcha.display(self.captcha_result.error_code)
913        return
914
[7714]915    @action(_('Get login credentials'), style='primary')
[7363]916    def register(self, **data):
917        if not self.captcha_result.is_valid:
918            # captcha will display error messages automatically.
919            # No need to flash something.
920            return
[7365]921        # Add applicant and create password
[7363]922        applicant = createObject('waeup.Applicant')
923        self.applyData(applicant, **data)
924        self.context.addApplicant(applicant)
[7399]925        sirp_utils = getUtility(ISIRPUtils)
926        password = sirp_utils.genPassword()
[7380]927        IUserAccount(applicant).setPassword(password)
[7365]928        # Send email with credentials
[7399]929        login_url = self.url(grok.getSite(), 'login')
[7714]930        msg = _('You have successfully been registered for the')
[7407]931        if sirp_utils.sendCredentials(IUserAccount(applicant),
932            password, login_url, msg):
[7380]933            self.redirect(self.url(self.context, 'registration_complete',
934                                   data = dict(email=applicant.email)))
935            return
936        else:
[7714]937            self.flash(_('Email could not been sent. Please retry later.'))
[7380]938        return
939
940class ApplicantRegistrationEmailSent(SIRPPage):
941    """Landing page after successful registration.
942    """
943    grok.name('registration_complete')
944    grok.require('waeup.Public')
945    grok.template('applicantregemailsent')
[7714]946    label = _('Your registration was successful.')
[7380]947
948    def update(self, email=None):
949        self.email = email
950        return
Note: See TracBrowser for help on using the repository browser.