def __call__(self):
        """ Remove a selected number of learners from a classlist """

        remove_ids = self.request.get('remove_ids', '')

        if isinstance(remove_ids, basestring):
            # wrap string in a list for deleting mechanism to work
            remove_ids = [remove_ids]

        classlist = self.context
        for remove_id in remove_ids:
            try:
                del classlist[remove_id]
            except:
                # success
                status = 'error'  # class in the template
                status_msg = self.context.translate(
                    _('error'))  # content string
                msg = self.context.translate(_("Delete failed"))
                return json.dumps({
                    'status': status,
                    'status_msg': status_msg,
                    'msg': msg
                })

        # success
        status = 'info'  # class in the template
        status_msg = self.context.translate(_('info'))  # content string
        msg = self.context.translate(_("Learner(s) removed from classlist"))
        return json.dumps({
            'status': status,
            'status_msg': status_msg,
            'msg': msg
        })
Exemple #2
0
class ILearner(form.Schema):
    """ Description of Learner content type
    """

    code = schema.TextLine(
        title=_(u"Code"),
        required=True,
    )

    name = schema.TextLine(
        title=_(u"Name"),
        required=True,
    )

    form.widget(home_language=SelectFieldWidget)
    home_language = RelationChoice(
        title=_(u"Home Language"),
        source=availableLanguages,
    )

    gender = schema.Choice(
        title=_(u"Gender"),
        vocabulary=GENDER,
        required=True,
    )
    def __call__(self):
        """ Remove a selected number of learners from a classlist """

        remove_ids = self.request.get('remove_ids', '')

        if isinstance(remove_ids, basestring):
            # wrap string in a list for deleting mechanism to work
            remove_ids = [remove_ids]

        classlist = self.context
        for remove_id in remove_ids:
            try:
                del classlist[remove_id]
            except:
                # success
                status = 'error' # class in the template
                status_msg = self.context.translate(_('error')) # content string
                msg = self.context.translate(_("Delete failed"))
                return json.dumps({'status' : status,
                                   'status_msg' : status_msg,
                                   'msg'    : msg})

        # success
        status = 'info' # class in the template
        status_msg = self.context.translate(_('info')) # content string
        msg = self.context.translate(_("Learner(s) removed from classlist"))
        return json.dumps({'status' : status,
                           'status_msg' : status_msg,
                           'msg'    : msg})
    def __call__(self):
        """ Export all learners from a classlist into a CSV file, do nothing if 
            the class is empty.
        """

        csv_content = None
        # It is safe to do this at the moment, because the view is bound
        # to IClasslist.
        contentFilter = {'portal_type': 'upfront.classlist.content.learner'}
        contentFilter['sort_on'] = "id"
        contentFilter['sort_order'] = "ascending"
        learners = self.context.getFolderContents(contentFilter,
                                                  full_objects=True)
        learner_csv = StringIO()

        if learners is not None and len(learners) > 0:
            writer = csv.DictWriter(learner_csv,
                                fieldnames=['code', 'name', 'gender',
                                            'language'],
                                restval='',
                                extrasaction='ignore',
                                dialect='excel',
                                quoting=csv.QUOTE_ALL
                               )

            for learner in learners:
                ldict={'code': learner.id,
                       'name': learner.name,
                       'gender': learner.gender,
                       'language': learner.home_language.to_object.title, 
                      }
                writer.writerow(ldict)
            
            csv_content = learner_csv.getvalue()
            learner_csv.close()

            now = DateTime()
            nice_filename = 'classlist-%s' % self.context.title

            self.request.response.setHeader("Content-Disposition",
                                            "attachment; filename=%s.xls" % 
                                             nice_filename)
            self.request.response.setHeader("Content-Type", "text/csv")
            self.request.response.setHeader("Content-Length", len(csv_content))
            self.request.response.setHeader('Last-Modified',
                                            DateTime.rfc822(DateTime()))
            self.request.response.setHeader("Cache-Control", "no-store")
            self.request.response.setHeader("Pragma", "no-cache")

            self.request.response.write(csv_content)
        else:
            msg = _('The classlist has no learners')
            IStatusMessage(self.request).addStatusMessage(msg,"info")

        self.request.response.redirect(
                '/'.join(self.context.getPhysicalPath()))

        return csv_content
    def __call__(self):
        """ Rename the current classlist """

        new_title = self.request.form['rename.form.newtitle']

        # name/title must exist
        if new_title == '':
            msg = _("Name is required")
            IStatusMessage(self.request).addStatusMessage(msg, "error")
            return self.request.RESPONSE.redirect( \
                                            "%s" % self.context.absolute_url())

        classlist = self.context
        old_title = classlist.Title()

        # name/title must be unique
        if old_title.lower() != new_title.lower():
            parent = classlist.aq_inner.aq_parent
            for alist in parent.objectValues():
                if alist != self and alist.Title() == new_title:
                    msg = _("Name is not unique")
                    IStatusMessage(self.request).addStatusMessage(msg, "error")
                    return self.request.RESPONSE.redirect( \
                                             "%s" % self.context.absolute_url())

        # Create/Modify
        if old_title.lower() != new_title.lower():
            classlists = classlist.aq_parent
            classlist.edit(title=new_title)
            name = INameChooser(classlists).chooseName(None, classlist)
            classlists.manage_renameObject(classlist.id, name)
            msg = _("Classlist was modified")
            IStatusMessage(self.request).addStatusMessage(msg, "info")
            return self.request.RESPONSE.redirect( \
                   "%s" % self.context.absolute_url())

        msg = _("New name identical to old name")
        IStatusMessage(self.request).addStatusMessage(msg, "error")
        return self.request.RESPONSE.redirect( \
                   "%s" % self.context.absolute_url())
    def __call__(self):
        """ Rename the current classlist """

        new_title = self.request.form['rename.form.newtitle']

        # name/title must exist
        if new_title == '':
            msg = _("Name is required")
            IStatusMessage(self.request).addStatusMessage(msg,"error")
            return self.request.RESPONSE.redirect( \
                                            "%s" % self.context.absolute_url())

        classlist = self.context
        old_title = classlist.Title()

        # name/title must be unique
        if old_title.lower() != new_title.lower():
            parent = classlist.aq_inner.aq_parent
            for alist in parent.objectValues():
                if alist != self and alist.Title() == new_title:
                    msg = _("Name is not unique")
                    IStatusMessage(self.request).addStatusMessage(msg,"error")
                    return self.request.RESPONSE.redirect( \
                                             "%s" % self.context.absolute_url())

        # Create/Modify
        if old_title.lower() != new_title.lower():
            classlists = classlist.aq_parent
            classlist.edit(title=new_title)
            name = INameChooser(classlists).chooseName(None, classlist)
            classlists.manage_renameObject(classlist.id, name)
            msg = _("Classlist was modified")
            IStatusMessage(self.request).addStatusMessage(msg,"info")
            return self.request.RESPONSE.redirect( \
                   "%s" % self.context.absolute_url())

        msg = _("New name identical to old name")
        IStatusMessage(self.request).addStatusMessage(msg,"error")
        return self.request.RESPONSE.redirect( \
                   "%s" % self.context.absolute_url())
    def validate(self, value):
        super(LearnerCodeValidator, self).validate(value)

        catalog = getToolByName(self.context, 'portal_catalog')
        result = catalog(portal_type='upfront.classlist.content.learner',
                         id=value)
        count = len(result)
        # we are editing a learner without changing the value
        if count == 1 and result[0].UID == IUUID(self.context):
            return True
        elif count > 0:
            raise Invalid(_(u"This learner code already "
                             "exists in the system. The learner code "
                             "must be unique."))
    def __call__(self):
        """ Add a learner to a classlist """

        learner_code    = self.request.get('learner_code', '')
        learner_name    = self.request.get('learner_name', '')
        learner_gender  = self.request.get('learner_gender', '')
        learner_lang_id = self.request.get('learner_lang_id', '')
        learner_lang    = self.request.get('learner_lang', '')

        if learner_name == '' or learner_code == '':
            status = 'error' # class in the template
            status_msg = self.context.translate(_('error')) # content string
            msg = self.context.translate(_("Field cannot be empty"))
            return json.dumps({'status' : status,
                               'status_msg' : status_msg,
                               'msg'    : msg})

        # validate that student code is unique
        status = ''
        catalog = getToolByName(self.context, 'portal_catalog')
        result = catalog(id=learner_code)
        if len(result) != 0:
            status = 'error' # class in the template
            status_msg = self.context.translate(_('error')) # content string
            msg = self.context.translate(_("Student code not unique"))
            return json.dumps({'status' : status,
                               'status_msg' : status_msg,
                               'msg'    : msg})

        classlist = self.context
        classlist.invokeFactory('upfront.classlist.content.learner',
                                learner_code,
                                title=learner_name)
        new_learner = classlist._getOb(learner_code)

        new_learner.code = learner_code
        new_learner.name = learner_name
        new_learner.gender = learner_gender       
        new_learner.home_language = RelationValue(int(learner_lang_id))
        notify(ObjectModifiedEvent(new_learner))

        learner_id = new_learner.id
        learner_editurl = '%s/edit' % new_learner.absolute_url()

        # success
        status = 'info' # class in the template
        status_msg = self.context.translate(_('info')) # content string
        msg = self.context.translate(_("New learner added"))
        return json.dumps({'learner_id'      : learner_id,
                           'learner_code'    : learner_code,
                           'learner_name'    : learner_name,
                           'learner_editurl' : learner_editurl,
                           'learner_gender'  : learner_gender,
                           'learner_lang'    : learner_lang,
                           'status'     : status,
                           'status_msg' : status_msg,
                           'msg'        : msg})
Exemple #9
0
    def validate(self, value):
        super(LearnerCodeValidator, self).validate(value)

        catalog = getToolByName(self.context, 'portal_catalog')
        result = catalog(portal_type='upfront.classlist.content.learner',
                         id=value)
        count = len(result)
        # we are editing a learner without changing the value
        if count == 1 and result[0].UID == IUUID(self.context):
            return True
        elif count > 0:
            raise Invalid(
                _(u"This learner code already "
                  "exists in the system. The learner code "
                  "must be unique."))
 def male_str(self):
     return self.context.translate(_("Male"))
Exemple #11
0
from five import grok
from zope.app.intid.interfaces import IIntIds
from zope.component import getUtility

from zope.component.hooks import getSite
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.vocabulary import SimpleVocabulary
from zope.schema.vocabulary import SimpleTerm

from upfront.classlist import MessageFactory as _

GENDER = SimpleVocabulary([
    SimpleTerm(value=u'Male', title=_(u'Male')),
    SimpleTerm(value=u'Female', title=_(u'Female'))
])


@grok.provider(IContextSourceBinder)
def availableLanguages(context):
    terms = []

    # This method can assume that the language topic tree is in a fixed location
    # in the site eg /topictrees/language for now.

    portal_state = context.restrictedTraverse('@@plone_portal_state')
    portal = portal_state.portal()

    language_folder = portal.topictrees.language

    topics = language_folder.getFolderContents()
    for brain in topics:
 def male_str(self):
     return self.context.translate(_("Male"))
 def female_str(self):
     return self.context.translate(_("Female"))
from five import grok
from zope.app.intid.interfaces import IIntIds
from zope.component import getUtility

from zope.component.hooks import getSite
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.vocabulary import SimpleVocabulary
from zope.schema.vocabulary import SimpleTerm

from upfront.classlist import MessageFactory as _

GENDER = SimpleVocabulary(
    [SimpleTerm(value=u'Male', title=_(u'Male')),
     SimpleTerm(value=u'Female', title=_(u'Female'))]
    )

@grok.provider(IContextSourceBinder)
def availableLanguages(context):
    terms = []

    # This method can assume that the language topic tree is in a fixed location 
    # in the site eg /topictrees/language for now.

    portal_state = context.restrictedTraverse('@@plone_portal_state')
    portal = portal_state.portal()

    language_folder = portal.topictrees.language

    topics = language_folder.getFolderContents()
    for brain in topics:
        topic = brain.getObject()
    def __call__(self):
        """ Export all learners from a classlist into an excel file, do nothing
            if the class is empty.
        """

        csv_content = None
        # It is safe to do this at the moment, because the view is bound
        # to IClasslist.
        contentFilter = {'portal_type': 'upfront.classlist.content.learner'}
        contentFilter['sort_on'] = "id"
        contentFilter['sort_order'] = "ascending"
        learners = self.context.getFolderContents(contentFilter,
                                                  full_objects=True)
        learner_csv = StringIO()

        ezxf = xlwt.easyxf
        headings = [self.context.translate(_('Code')),
                    self.context.translate(_('Name')),
                    self.context.translate(_('Gender')),
                    self.context.translate(_('Language'))]
        kinds =     'text    text    text      text'.split()
        if learners is not None and len(learners) > 0:

            data = []
            for learner in learners:
                data.append([learner.id, 
                             learner.name, 
                             learner.gender,
                             learner.home_language.to_object.title]
                    )

            heading_xf = ezxf('font: bold on; align: wrap on, '
                              'vert centre, horiz center')
            kind_to_xf_map = {
                'text': ezxf(),
                # other examples
                # 'date': ezxf(num_format_str='yyyy-mm-dd'),
                #'int': ezxf(num_format_str='#,##0'),
                #'money': ezxf('font: italic on; pattern: pattern solid,
                #     fore-colour grey25',
                #    num_format_str='$#,##0.00'),
                #'price': ezxf(num_format_str='#0.000000'),
                }
            data_xfs = [kind_to_xf_map[k] for k in kinds]

            book = xlwt.Workbook()
            sheet = book.add_sheet(self.context.title) # XXX make sure it is utf
                                                       # sanitized
            rowx = 0
            for colx, value in enumerate(headings):
                sheet.write(rowx, colx, value, heading_xf)
            sheet.set_panes_frozen(True) # frozen headings instead of 
                                         # split panes
            sheet.set_horz_split_pos(rowx+1) # in general, freeze after last 
                                             # heading row
            sheet.set_remove_splits(True) # if user does unfreeze, don't leave 
                                          # a split there
            for row in data:
                rowx += 1
                for colx, value in enumerate(row):
                    sheet.write(rowx, colx, value, data_xfs[colx])

            book.save(learner_csv)            
            csv_content = learner_csv.getvalue()
            learner_csv.close()

            now = DateTime()
            nice_filename = 'classlist-%s' % self.context.title

            self.request.response.setHeader("Content-Disposition",
                                            "attachment; filename=%s.xls" % 
                                             nice_filename)
            self.request.response.setHeader("Content-Type", "text/csv")
            self.request.response.setHeader("Content-Length", len(csv_content))
            self.request.response.setHeader('Last-Modified',
                                            DateTime.rfc822(DateTime()))
            self.request.response.setHeader("Cache-Control", "no-store")
            self.request.response.setHeader("Pragma", "no-cache")

            self.request.response.write(csv_content)
        else:
            msg = _('The classlist has no learners')
            IStatusMessage(self.request).addStatusMessage(msg,"info")

        self.request.response.redirect(
                '/'.join(self.context.getPhysicalPath()))

        return csv_content
 def unknown_str(self):
     return self.context.translate(_("Unknown"))
 def unknown_str(self):
     return self.context.translate(_("Unknown"))
 def female_str(self):
     return self.context.translate(_("Female"))
    def __call__(self):
        """ Add a learner to a classlist """

        learner_code = self.request.get('learner_code', '')
        learner_name = self.request.get('learner_name', '')
        learner_gender = self.request.get('learner_gender', '')
        learner_lang_id = self.request.get('learner_lang_id', '')
        learner_lang = self.request.get('learner_lang', '')

        if learner_name == '' or learner_code == '':
            status = 'error'  # class in the template
            status_msg = self.context.translate(_('error'))  # content string
            msg = self.context.translate(_("Field cannot be empty"))
            return json.dumps({
                'status': status,
                'status_msg': status_msg,
                'msg': msg
            })

        # validate that student code is unique
        status = ''
        catalog = getToolByName(self.context, 'portal_catalog')
        result = catalog(id=learner_code)
        if len(result) != 0:
            status = 'error'  # class in the template
            status_msg = self.context.translate(_('error'))  # content string
            msg = self.context.translate(_("Student code not unique"))
            return json.dumps({
                'status': status,
                'status_msg': status_msg,
                'msg': msg
            })

        classlist = self.context
        classlist.invokeFactory('upfront.classlist.content.learner',
                                learner_code,
                                title=learner_name)
        new_learner = classlist._getOb(learner_code)

        new_learner.code = learner_code
        new_learner.name = learner_name
        new_learner.gender = learner_gender
        new_learner.home_language = RelationValue(int(learner_lang_id))
        notify(ObjectModifiedEvent(new_learner))

        learner_id = new_learner.id
        learner_editurl = '%s/edit' % new_learner.absolute_url()

        # success
        status = 'info'  # class in the template
        status_msg = self.context.translate(_('info'))  # content string
        msg = self.context.translate(_("New learner added"))
        return json.dumps({
            'learner_id': learner_id,
            'learner_code': learner_code,
            'learner_name': learner_name,
            'learner_editurl': learner_editurl,
            'learner_gender': learner_gender,
            'learner_lang': learner_lang,
            'status': status,
            'status_msg': status_msg,
            'msg': msg
        })