Example #1
0
    def manage(self):
        survey_manage.need()
        manage_css.need()
        post = self.request.POST
        if 'cancel' in self.request.POST:
            self.flash_messages.add(_("Canceled"))
            url = self.request.resource_url(self.context)
            return HTTPFound(location = url)
        if 'save' in post:
            self.process_question_ids()
            self.flash_messages.add(_("Saved"))
            url = self.request.resource_url(self.context, 'manage')
            return HTTPFound(location = url)

        response = {}
        picked_questions = set()
        survey_sections = []
        for section in self.context.values():
            if not ISurveySection.providedBy(section):
                continue
            picked_questions.update(section.question_ids)
            survey_sections.append(section)
        response['survey_sections'] = survey_sections
        if not survey_sections:
            msg = _(u"no_sections_added_notice",
                    default = u"You need to add a Survey section "
                        "and then use this view to manage the questions.")
            self.flash_messages.add(msg, auto_destruct = False)
        #Load all question objects that haven't been picked
        response['available_questions'] = self.get_questions(exclude = picked_questions)
        return response
Example #2
0
 def __call__(self, form, value):
     root = find_root(self.context)
     parent = find_resource(root, value['new_parent'])
     slug = generate_slug(parent, value['new_name'])
     if slug != value['new_name']:
         exc = colander.Invalid(form, _("Check name"))
         exc['new_name'] = _("bad_name_error",
                             default = "Name isn't valid. This would work: '${name}'",
                             mapping = {'name': slug})
         raise exc
Example #3
0
def new_parent_widget(node, kw):
    choices = [('', _("<Pick>"))]
    root = find_root(kw['context'])
    request = kw['request']
    if request.has_permission(ADD_SURVEY, root):
        choices.append(('/', _("Root")))
    view = kw['view']
    for obj in view.catalog_query("type_name == 'Organisation'", resolve = True):
        if request.has_permission(ADD_SURVEY, obj):
            choices.append((resource_path(obj), obj.title))
    return deform.widget.SelectWidget(values = choices)
Example #4
0
 def __call__(self):
     output = StringIO()
     lang_name = self.request.locale_name
     writer = csv.writer(output, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, dialect = csv.excel)
     writer.writerow([self.context.title.encode('utf-8')])
     writer.writerow([_('Export using language:'), lang_name])
     langs = self.context.languages
     lrow = [_("Survey languages").encode('utf-8')]
     for lang in langs:
         lrow.append(lang)
     writer.writerow(lrow)
     writer.writerow([])
     for section in self.get_sections():
         writer.writerow([])
         writer.writerow([_('Section:'), section.title.encode('utf-8')])
         writer.writerow([_('Responses:'), len(section.responses)])
         writer.writerow([])
         for (choices, questions) in self.get_choice_sorted_questions(section).items():
             write_header = True
             for question in questions:
                 question_widget = self.request.get_question_widget(question)
                 choice_objects = self.get_choices(question)
                 if write_header:
                     row = ['']
                     for choice in choice_objects:
                         row.append(choice.title.encode('utf-8'))
                     writer.writerow(row)
                     write_header = False
                 response = question_widget.responses(section, question)
                 if isinstance(response, dict):
                     results = dict([(x, 0) for x in choices])
                     results.update(response)
                     out = [question.title.encode('utf-8')]
                     for choice in choice_objects:
                         out.append(results.get(choice.cluster))
                     writer.writerow(out)
                 else:
                     writer.writerow([])
                     writer.writerow([question.title.encode('utf-8')])
                     for x in response:
                         if x:
                             if isinstance(x, unicode):
                                 writer.writerow([x.encode('utf-8')])
                             else:
                                 writer.writerow([x])
     contents = output.getvalue()
     output.close()
     return Response(content_type = 'text/csv', body = contents)
def choice_language_guard(context, event):
    parent_lang = getattr(context.__parent__, 'language', None)
    if parent_lang and parent_lang != context.language:
        raise HTTPForbidden(_("It's not possible to add choices with language "
                              "'${choice_lang}' to a parent with the language '${parent_lang}'.",
                              mapping = {'choice_lang': context.language,
                                         'parent_lang': parent_lang}))
Example #6
0
def deferred_translations_node(nodes, kw):
    """ Use translate and translate_missing properties on a schema to generate
        translation subnodes.
    """
    _marker = object()
    request = kw['request']
    languages = request.registry.settings.get('m2m.languages', 'en').split()
    default_lang = request.registry.settings.get('pyramid.default_locale_name', 'en')
    if default_lang in languages:
        languages.remove(default_lang)
    if not languages:
        return
    #find translatables
    translatables = []
    for node in nodes:
        if getattr(node, 'translate', False):
            translatables.append(node.name)
    if not translatables:
        return
    schema = colander.Schema()
    schema.title = _("Translations")
    for lang in languages:
        schema[lang] = colander.Schema()
        schema[lang].title = lang
        for trans in translatables:
            clone = nodes[trans].clone()
            missing = getattr(nodes[trans], 'translate_missing', _marker)
            if missing is not _marker:
                clone.missing = missing
            schema[lang].add(clone)
    nodes['translations'] = schema
Example #7
0
 def get_schema(self):
     locale_name = self.request.locale_name
     title = self.context.translate('title', locale_name)
     description = self.context.translate('body', locale_name)
     schema = colander.Schema(title = title, description = description)
     for qid in self.context.question_ids:
         docids = self.catalog_search(cluster = qid, language = self.request.locale_name)
         if docids:
             question = None
             for question in self.resolve_docids(docids, perm = None):
                 #Only one or none
                 pass
             question_type = self.resolve_uid(question.question_type, perm = None)
             question_widget = self.request.registry.queryAdapter(question_type,
                                                                  IQuestionWidget,
                                                                  name = getattr(question_type, 'input_widget', ''))
             if question_widget:
                 title = question.title
                 if self.organisation:
                     title = self.organisation.variants.get(question.uid, title)
                 schema.add(question_widget.node(question.cluster,
                                                      lang = self.request.locale_name,
                                                      question = question,
                                                      title = title))
         else:
             schema.add(colander.SchemaNode(colander.String(),
                                            widget = deform.widget.TextInputWidget(readonly = True),
                                            title = _("<Missing question>"),))
     return schema
Example #8
0
 def get_schema(self):
     schema = colander.Schema(title = _("Preview"))
     if self.question_widget:
         schema.add(self.question_widget.node(self.context.__name__,
                                             lang = self.context.language,
                                             question = self.context,
                                             title = self.context.title))
     return schema
Example #9
0
 def send_success(self, appstruct):
     """ Performed when send button is clicked, and schema validates correctly. """
     #FIXME: It might be smarter to create a schema type that splits rows into a list
     emails = set()
     for email in appstruct['emails'].splitlines():
         emails.add(email.strip())
     appstruct['emails'] = emails
     self.send_invitations(**appstruct)
     self.flash_messages.add(_("Invitations sent"))
     return HTTPFound(location = self.request.resource_url(self.context))
Example #10
0
def multiple_email_validator(node, value):
    """ Checks that each line of value is a correct email
    """
    validator = colander.Email()
    invalid = []
    for email in value.splitlines():
        email = email.strip()
        if not email:
            continue
        try:
            validator(node, email)
        except colander.Invalid:
            invalid.append(email)
    if invalid:
        emails = ", ".join(invalid)
        raise colander.Invalid(node, _(u"The following addresses is invalid: ${emails}", mapping={'emails': emails}))
Example #11
0
from arche.models.workflow import Workflow
from arche.models.workflow import Transition
from arche import security

from arche_m2m import _
from arche_m2m import permissions


_closed_to_open = \
    Transition(from_state = 'closed',
               to_state = 'open',
               permission = security.PERM_EDIT,
               title = _("Open"),
               message = _("Survey opened for participants"))

_open_to_closed = \
    Transition(from_state = 'open',
               to_state = 'closed',
               permission = security.PERM_EDIT,
               title = _("Closed"),
               message = _("Now closed for new participants"))


class SurveyWorkflow(Workflow):
    """ To manage states for surveys"""
    name = 'survey_workflow'
    title = _("Survey workflow")
    states = {'open': _("Open"),
              'closed': _("Closed")}
    transitions = {_closed_to_open.name: _closed_to_open,
                   _open_to_closed.name: _open_to_closed}
Example #12
0
 def get_schema(self):
     schema = colander.Schema(title = _("Preview"))
     if self.question_widget:
         schema.add(self.question_widget.node(self.context.__name__))
     return schema
Example #13
0
 def check_success(self, appstruct):
     self.flash_messages.add(_('Success, captured: ${appstruct}',
                               mapping = {'appstruct': appstruct}))
     return HTTPFound(location = self.request.resource_url(self.context))