Beispiel #1
0
 def creat_idea(self):
     behavior = None
     try:
         behavior = self.behaviors_instances['Create_an_idea']
         values = {'title': self.params('title'),
                   'text': self.params('text')}
         idea = Idea()
         idea.set_data(values) 
         appstruct = {'_object_data': idea,
                      'keywords': self.params('keywords')}
         behavior.execute(self.context, self.request, appstruct)
         oid = get_oid(idea)
         localizer = self.request.localizer
         user = get_current()
         time = to_localized_time(datetime.datetime.today())
         new_title = localizer.translate(_('Idea by'))+' '+\
                 getattr(user, 'title', user.name)+' '+\
                 localizer.translate(_('the'))+' '+\
                 time+' (UTC)'
         data = {'title': idea.title,
                 'oid': str(oid),
                 'body': renderers.render(self.idea_template,
                                          {'idea':idea},
                                          self.request),
                 'new_title': new_title
                 }
         result = data
         return result
     except Exception:
         return {}
Beispiel #2
0
    def update(self):
        self.execute(None)
        user = get_current()
        objects = [obj for obj
                   in self.context.get_sub_nodes()
                   if can_access(user, obj)]
        objects = sorted(
            objects,
            key=lambda e: getattr(e, 'modified_at'),
            reverse=True)
        url = self.request.resource_url(self.context, self.name)
        batch = Batch(objects, self.request,
                      url=url,
                      default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_node_dependencies_" + str(self.context.__oid__)
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(WG_MESSAGES[index], mapping={'number': len_result})
        result = {}
        result_body = render_small_listing_objs(
            self.request, batch, user)

        values = {
            'bodies': result_body,
            'batch': batch,
            'empty_message': _("No association"),
            'empty_icon': 'glyphicon glyphicon-link'
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #3
0
    def update(self):
        self.execute(None)
        user = get_current()
        objects = getattr(self.context.working_group, 'members', [])
        url = self.request.resource_url(self.context, self.name)
        batch = Batch(objects, self.request,
                      url=url,
                      default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_proposal_members" + str(self.context.__oid__)
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        result_body = render_small_listing_objs(
            self.request, batch, user)
        result = {}
        self.title = _(MEMBERS_MESSAGES[index], mapping={'number': len_result})
        values = {
            'bodies': result_body,
            'batch': batch,
            'empty_message': _("No members"),
            'empty_icon': 'glyphicon glyphicon-user'
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #4
0
def define_date_node(schema):
    schema['vote'] = colander.SchemaNode(
            colander.DateTime(),
            widget=deform.widget.DateTimeInputWidget(),
            validator=colander.Range(min=datetime.datetime.today(),
                min_err=_('${val} is earlier than earliest datetime ${min}')),
            title=_('Date')
            )               
Beispiel #5
0
 def default_data(self):
     localizer = self.request.localizer
     user = get_current()
     time = to_localized_time(datetime.datetime.today())
     title = localizer.translate(_('Idea by'))+' '+\
             getattr(user, 'title', user.name)+' '+\
             localizer.translate(_('the'))+' '+\
             time+' (UTC)'
     return {'title': title}
Beispiel #6
0
 def before_update(self):
     target = self.schema.get('targets')
     target.title = _("Related contents")
     formwidget = deform.widget.FormWidget(css_class='controled-form', 
                             activable=True,
                             button_css_class="pull-right",
                             picto_css_class="glyphicon glyphicon-link",
                             button_title=_("Associate"))
     formwidget.template = 'novaideo:views/templates/ajax_form.pt'
     self.schema.widget = formwidget
Beispiel #7
0
    def __init__(self, report, vote_process_id='referendumprocess', **kwargs):
        self.vote_process_id = vote_process_id
        self.report = report
        if isinstance(self.report.subjects, (list, tuple, PersistentList)):
            self.subject = self.report.subjects[0]
        else:
            self.subject = self.report.subjects

        self.false_val = kwargs.get('false_val', _('In favour'))
        self.true_val = kwargs.get('true_val', _('Against'))
Beispiel #8
0
def get_contents_forms(request):
    result = {
        'forms': [],
        'css_links': [],
        'js_links': [],
        'has_forms': False}
    if request.view_name not in ('', 'index', 'seemycontents'):
        return result

    root = getSite()
    result_idea = get_home_actions_bodies(
        'ideamanagement', 'creat', 'formcreateideahome',
        request, root)
    result['forms'].append({
        'id': 'ideahomeform',
        'active': True,
        'title': _('Create an idea'),
        'form': result_idea['form'],
        'action': result_idea['action'],
        'search_url': request.resource_url(
            root, '@@novaideoapi', query={'op': 'get_similar_ideas'}),
        'action_url': request.resource_url(
            root, '@@ideasmanagement',
            query={'op': 'creat_home_idea'}),
        'css_class': 'home-add-idea'
    })
    has_forms = result_idea['form'] is not None
    result['js_links'] = result_idea['js_links']
    result['css_links'] = result_idea['css_links']
    if 'question' in request.content_to_manage:
        result_question = get_home_actions_bodies(
            'questionmanagement', 'creat',
            'formaskquestionhome', request, root)
        result['forms'].append({
            'id': 'questionhomeform',
            'title': _('Ask a question'),
            'form': result_question['form'],
            'action': result_question['action'],
            'search_url': request.resource_url(
                root, '@@novaideoapi', query={'op': 'get_similar_questions'}),
            'action_url': request.resource_url(
                root, '@@questionsmanagement',
                query={'op': 'creat_home_question'}),
            'css_class': 'home-add-question'
        })
        has_forms = has_forms or result_question['form'] is not None
        result['js_links'].extend(result_question['js_links'])
        result['css_links'].extend(result_question['css_links'])

    result['has_forms'] = has_forms
    result['js_links'] = list(set(result['js_links']))
    result['css_links'] = list(set(result['css_links']))
    return result
Beispiel #9
0
    def update(self):
        self.execute(None)
        user = get_current()
        objects = [proposal for proposal
                   in self.context.related_proposals
                   if proposal.working_group and
                   'archived' not in proposal.state and
                   'censored' not in proposal.state and
                   can_access(user, proposal)]
        objects = sorted(
            objects,
            key=lambda e: getattr(e, 'modified_at'),
            reverse=True)
        is_small = True
        current_is_small = self.params('is_small')
        if current_is_small is not None:
            current_is_small = current_is_small.lower()
            is_small = current_is_small == 'true'
        elif self.parent or self.request.view_name == self.name:
            is_small = False

        url = self.request.resource_url(
            self.context, self.name, query={'is_small': str(is_small)})
        batch = Batch(objects, self.request,
                      url=url,
                      default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_idea_working_groups" + \
            str(self.context.__oid__) + \
            (is_small and 'is_small' or '')
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(WG_MESSAGES[index], mapping={'number': len_result})
        result = {}
        if is_small:
            result_body = render_small_listing_objs(
                self.request, batch, user)
        else:
            result_body, result = render_listing_objs(
                self.request, batch, user)

        values = {
            'bodies': result_body,
            'batch': batch,
            'empty_message': _("No working group created"),
            'empty_icon': 'novaideo-icon icon-wg'
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #10
0
 def _init_definition(self):
     self.defineNodes(
             start = StartEventDefinition(),
             vote = ActivityDefinition(contexts=[Vote],
                                    description=_("Vote"),
                                    title=_("Vote"),
                                    groups=[]),
             end = EndEventDefinition(),
     )
     self.defineTransitions(
             TransitionDefinition('start', 'vote'),
             TransitionDefinition('vote', 'end'),
     )
Beispiel #11
0
    def start(self, context, request, appstruct, **kw):
        root = getSite()
        copy_of_amendment = copy(context, 
                                 (context.proposal, 'amendments'),
                                 omit=('created_at',
                                       'modified_at',
                                       'explanations'))
        keywords_ids = appstruct.pop('keywords')
        result, newkeywords = root.get_keywords(keywords_ids)
        for nkw in newkeywords:
            root.addtoproperty('keywords', nkw)

        result.extend(newkeywords)
        appstruct['keywords_ref'] = result
        copy_of_amendment.set_data(appstruct)
        copy_of_amendment.text = normalize_text(copy_of_amendment.text)
        copy_of_amendment.setproperty('originalentity', context)
        copy_of_amendment.state = PersistentList(['draft'])
        copy_of_amendment.setproperty('author', get_current())
        localizer = request.localizer
        # copy_of_amendment.title = context.proposal.title + \
        #                         localizer.translate(_('_Amended version ')) + \
        #                         str(getattr(context.proposal,
        #                                    '_amendments_counter', 1)) 
        copy_of_amendment.title = localizer.translate(_('Amended version ')) + \
                                str(getattr(context.proposal,
                                           '_amendments_counter', 1)) 
        grant_roles(roles=(('Owner', copy_of_amendment), ))
        copy_of_amendment.text_diff = get_text_amendment_diff(
                                           context.proposal, copy_of_amendment)
        copy_of_amendment.reindex()
        context.proposal._amendments_counter = getattr(context.proposal, 
                                                 '_amendments_counter', 1) + 1
        context.reindex()
        return {'newcontext': copy_of_amendment}
Beispiel #12
0
 def start(self, context, request, appstruct, **kw):
     root = getSite()
     user = get_current()
     proposal = context.proposal
     working_group = proposal.working_group
     author = working_group.get_member(user)
     copy_of_amendment = copy(context,
                              (proposal, 'amendments'),
                              omit=('created_at',
                                    'modified_at',
                                    'explanations'))
     copy_of_amendment.set_data(appstruct)
     copy_of_amendment.text = html_diff_wrapper.normalize_text(
         copy_of_amendment.text)
     copy_of_amendment.setproperty('originalentity', context)
     copy_of_amendment.state = PersistentList(['draft'])
     copy_of_amendment.setproperty('author', author)
     localizer = request.localizer
     copy_of_amendment.title = localizer.translate(
         _('Amended version ')) + str(getattr(proposal,
                                      '_amendments_counter', 1))
     grant_roles(user=author, roles=(('Owner', copy_of_amendment), ))
     copy_of_amendment.text_diff = get_text_amendment_diff(
         proposal, copy_of_amendment)
     copy_of_amendment.reindex()
     proposal._amendments_counter = getattr(
         proposal, '_amendments_counter', 1) + 1
     context.reindex()
     request.registry.notify(ActivityExecuted(self, [context], author))
     return {'newcontext': copy_of_amendment}
Beispiel #13
0
    def update(self):
        self.execute(None)
        user = get_current()
        relatedideas = [{'content':target, 
                         'url':target.url(self.request),
                         'correlation': correlation} \
                        for target, correlation in \
                            self.context.related_ideas.items()]
        len_ideas = len(relatedideas)

        index = str(len_ideas)
        if len_ideas > 1:
            index = '*'

        message = (_(ADDIDEAS_MESSAGES[index]),
                   len_ideas,
                   index)
        result = {}
        values = {
                'relatedcontents': relatedideas,
                'current_user': user,
                'message': message
               }
        self.message = message
        body = self.content(result=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates:[item]}
        return result
Beispiel #14
0
    def before_update(self):
        root = getSite()
        if getattr(self.context.working_group, 'work_mode', None):
            self.schema = select(PublishProposalSchema(), ['vote', 'elected', 'members_to_invite'])

        can_submit_directly = getattr(root, 'can_submit_directly', False)
        if not can_submit_directly:
            self.schema = select(
                PublishProposalSchema(), ['work_mode', 'elected', 'members_to_invite'])

        duration_ballot = self.context.working_group.duration_configuration_ballot
        vp_ballot = self.context.working_group.vp_ballot
        duration_ballot_report = duration_ballot.report if duration_ballot else None
        vp_ballot_report = vp_ballot.report if vp_ballot else None
        subjects_widget = subjects_choice(duration_ballot_report)
        elected_node = self.schema.get('elected')
        elected_node.title = getattr(duration_ballot_report.ballottype,
                                     'group_title', _('Choices'))
        group_default = getattr(duration_ballot_report.ballottype,
                                'group_default', None)
        if group_default:
            elected_node.default = group_default

        elected_node.widget = subjects_widget
        if can_submit_directly:
            vote_widget = vote_choice(vp_ballot_report)
            self.schema.get('vote').widget = vote_widget

        self.schema.view = self
        self.action = self.request.resource_url(
            self.context, 'novaideoapi',
            query={'op': 'update_action_view',
                   'node_id': PublishProposal.node_definition.id})
        self.schema.widget = deform.widget.FormWidget(
            css_class='deform novaideo-ajax-form publish-proposal-form')
    def default_data(self):
        root = self.request.root
        template = getattr(root, 'proposal_template', None)
        text = '<p>{idea_text}</p>'
        if template:
            try:
                text = template.fp.readall().decode()
            except Exception as error:
                log.warning(error)

        localizer = self.request.localizer
        title = self.context.title + \
            localizer.translate(_(" (the proposal)"))
        data = {'title': title,
                'description': self.context.text,
                'text': text.format(
                    idea_text=self.context.text.replace('\n', '<br/>')),
                'keywords': self.context.keywords,
                'related_ideas': [self.context]}
        attached_files = self.context.attached_files
        data['add_files'] = {'attached_files': []}
        files = []
        for file_ in attached_files:
            file_data = add_file_data(file_)
            if file_data:
                files.append(file_data)

        if files:
            data['add_files']['attached_files'] = files

        challenge = getattr(self.context, 'challenge', None)
        if challenge and challenge.can_add_content:
            data['challenge'] = challenge

        return data
Beispiel #16
0
def challenge_choice(node, kw):
    request = node.bindings['request']
    root = getSite()
    values = [('', _('- Select -'))]

    def title_getter(id):
        try:
            obj = get_obj(int(id), None)
            if obj:
                return obj.title
            else:
                return id
        except Exception as e:
            log.warning(e)
            return id

    ajax_url = request.resource_url(
        root, '@@novaideoapi',
        query={'op': 'find_challenges'})
    return AjaxSelect2Widget(
        values=values,
        ajax_url=ajax_url,
        ajax_item_template="related_item_template",
        title_getter=title_getter,
        multiple=False,
        page_limit=20,
        add_clear=True,
        item_css_class='challenge-input')
Beispiel #17
0
    def start(self, context, request, appstruct, **kw):
        login = appstruct['email']
        adapter = request.registry.queryMultiAdapter(
                    (context, request),
                    IUserLocator
                    )
        if adapter is None:
            adapter = DefaultUserLocator(context, request)

        user = adapter.get_user_by_email(login)
        if user is not None:
            principals = find_service(user, 'principals')
            reset = principals.add_reset(user)
            reseturl = request.resource_url(reset)
            if not user.email:
                raise ValueError('User does not possess a valid email address.')

            subject = RESETPW_SUBJECT.format(novaideo_title=request.root.title)
            localizer = request.localizer
            message = RESETPW_MESSAGE.format(
                recipient_title=localizer.translate(_(getattr(user, 'user_title',''))),
                recipient_first_name=getattr(user, 'first_name', user.name),
                recipient_last_name=getattr(user, 'last_name',''),
                reseturl=reseturl,
                novaideo_title=request.root.title
                 )
            mailer_send(subject=subject, 
                recipients=[user.email], 
                body=message)

        return {}
Beispiel #18
0
    def contact_invariant(self, appstruct):
        appstruct_copy = appstruct.copy()
        appstruct_copy.pop('surtax')
        if 'title' in appstruct_copy:
            appstruct_copy.pop('title')

        if not any(v != "" and v != colander.null
                   for v in list(appstruct_copy.values())):
            raise colander.Invalid(self,
                                   _('One value must be entered.'))

        if 'phone' in appstruct and appstruct['phone'] and \
            ('surtax' not in appstruct or \
             'surtax' in appstruct and not appstruct['surtax']):
            raise colander.Invalid(self,
                                   _('Surcharge field must be filled in.'))
Beispiel #19
0
    def update(self):
        self.execute(None)
        user = get_current()
        folders = find_entities(
            user=user,
            interfaces=[ISmartFolder])
        folders = [sf for sf in folders if not sf.parents]
        folders = sorted(folders, key=lambda e: e.get_order())
        root_navbars = generate_navbars(
            self.request, self.context,
            process_id='smartfoldermanagement',
            descriminators=['body-action'])
        len_result = len(folders)
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(CONTENTS_MESSAGES[index],
                       mapping={'number': len_result})
        result_body, result = render_listing_objs(
            self.request, folders, user)
        values = {
            'folders': result_body,
            'body_actions': root_navbars['body_actions']
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #20
0
    def update(self):
        self.execute(None)
        user = get_current()
        objects = [o for o in getattr( self.context, 'amendments', []) \
                  if not('archived' in o.state) and can_access(user, o)]
        objects = sorted(objects, 
                         key=lambda e: getattr(e, 'modified_at', 
                                               datetime.datetime.today()), 
                         reverse=True)
        lenamendments = len(objects)
        index = str(lenamendments)
        if lenamendments > 1:
            index = '*'

        message = (_(AMENDMENTS_MESSAGES[index]),
                   lenamendments,
                   index)

        result = {}
        values = {'amendments': objects,
                  'current_user': user,
                  'message': message,
                  'get_states_mapping': get_states_mapping
                   }
        self.message = message
        body = self.content(result=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #21
0
    def update(self):
        self.execute(None)
        objects = self.context.organizations
        now = datetime.datetime.now(tz=pytz.UTC)
        objects = sorted(objects,
                         key=lambda e: getattr(e, 'modified_at', now),
                         reverse=True)
        batch = Batch(
            objects, self.request, default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_organizations"
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(CONTENTS_MESSAGES[index],
                       mapping={'number': len_result})
        user = get_current()
        result_body, result = render_listing_objs(
            self.request, batch, user)
        values = {
            'bodies': result_body,
            'length': len_result,
            'batch': batch,
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #22
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.default_folder = SmartFolder(title=_('My topics of interest'),
                                       style=DEFAULT_FOLDER_COLORS,
                                       )
     self.default_folder.folder_order = -1
Beispiel #23
0
    def update(self):
        self.execute(None)
        user = get_current()
        objects = find_entities(
            user=user,
            interfaces=[IPreregistration],
            sort_on='release_date')
        batch = Batch(
            objects, self.request,
            default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_registrations"
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(CONTENTS_MESSAGES[index],
                       mapping={'number': len_result})
        result_body, result = render_listing_objs(
            self.request, batch, user)

        values = {
            'bodies': result_body,
            'length': len_result,
            'batch': batch,
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #24
0
    def before_update(self):
        ballot_report = None
        try:
            vote_actions = list(self.behaviors_instances.values())
            ballot_report = vote_actions[0].process.ballot.report
        except Exception:
            return

        subjects_widget = subjects_choice(ballot_report)
        elected_node = self.schema.get('elected')
        elected_node.title = getattr(ballot_report.ballottype,
                                     'group_title', _('Choices'))
        group_default = getattr(ballot_report.ballottype, 'group_default', None)
        if group_default:
            elected_node.default = group_default

        elected_node.widget = subjects_widget
        self.schema.view = self
        self.action = self.request.resource_url(
            self.context, 'novaideoapi',
            query={'op': 'update_action_view',
                   'node_id': Vote.node_definition.id,
                   'action_uid': getattr(vote_actions[0], '__oid__', '')})
        self.schema.widget = deform.widget.FormWidget(
            css_class='deform vote-form')
Beispiel #25
0
def content_validator(node, kw):
    context = node.bindings['context']
    if kw.find('{unsubscribeurl}') >= 0 and\
       not getattr(context, 'allow_unsubscribing', True):
        raise colander.Invalid(
            node,
            _('The content does not contain the variable "unsubscribeurl"'))
Beispiel #26
0
    def update(self):
        self.execute(None)
        objects = self.context.newsletters
        batch = Batch(objects, self.request, default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_newsletters"
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(CONTENTS_MESSAGES[index],
                       mapping={'number': len_result})

        user = get_current()
        result_body, result = render_listing_objs(
            self.request, batch, user)

        result = {}
        values = {
            'bodies': result_body,
            'length': len_result,
            'batch': batch,
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #27
0
    def start(self, context, request, appstruct, **kw):
        person = appstruct['_object_data']
        root = context
        principals = find_service(root, 'principals')
        name = person.first_name + ' ' +person.last_name
        name = name_chooser(name=name)
        principals['users'][name] = person
        grant_roles(person, roles=('Member',))
        grant_roles(person, (('Owner', person),))
        person.state.append('active')
        localizer = request.localizer
        for i in range(root.tokens_mini):
            token = Token(title='Token_'+str(i))
            person.addtoproperty('tokens_ref', token)
            person.addtoproperty('tokens', token)
            token.setproperty('owner', person)

        subject = CONFIRMATION_SUBJECT.format(novaideo_title=request.root.title)
        message = CONFIRMATION_MESSAGE.format(
                    person=person,
                    user_title=localizer.translate(
                                   _(getattr(person, 'user_title', ''))),
                    login_url=request.resource_url(root, '@@login'),
                    novaideo_title=request.root.title)
        mailer_send(subject=subject,
                recipients=[person.email], body=message)

        person.reindex()
        return {'person': person}
Beispiel #28
0
 def contact_invariant(self, appstruct):
     can_add_keywords = appstruct.get('can_add_keywords', 'false')
     can_add_keywords = False if can_add_keywords == 'false' else True
     keywords = appstruct.get('keywords', colander.null)
     if not can_add_keywords and keywords is colander.null:
         raise colander.Invalid(
             self, _('You must enter at least one keyword.'))
Beispiel #29
0
 def update(self):
     user = get_current()
     context_oid = get_oid(self.context)
     dace_index = find_catalog('dace')
     dace_container_oid = dace_index['container_oid']
     query = dace_container_oid.eq(context_oid)
     objects = find_entities(
         user=user,
         interfaces=[ISReport],
         metadata_filter={
             'states': [self.report_state]
         },
         add_query=query)
     url = self.request.resource_url(
         self.context, '',
         query={'view_report_state': self.report_state})
     batch = Batch(objects,
                   self.request,
                   url=url,
                   default_size=BATCH_DEFAULT_SIZE)
     self.title = _(self.title, mapping={'nb': batch.seqlen})
     batch.target = "#results"+"-report-" + self.report_state.replace(' ', '')
     result_body, result = render_listing_objs(
         self.request, batch, user)
     values = {'bodies': result_body,
               'batch': batch,
               'empty_message': self.empty_message,
               'empty_icon': self.empty_icon}
     body = self.content(args=values, template=self.template)['body']
     item = self.adapt_item(body, self.viewid)
     result['coordinates'] = {self.coordinates: [item]}
     return result
Beispiel #30
0
    def update(self):
        user = get_current()
        correlations = [c for c in self.context.source_correlations \
                        if c.type == 0 and can_access(user, c)]
        target_correlations = [c for c in self.context.target_correlations \
                               if c.type == 0 and can_access(user, c)]
        relatedcontents = []
        all_messages = {}
        isactive = False
        all_resources = {}
        all_resources['js_links'] = []
        all_resources['css_links'] = []
        for correlation in correlations:
            contents = correlation.targets
            for content in contents:
                correlation_data, resources, \
                messages, action_updated = self._correlation_action(correlation)
                correlation_data.update({'content': content, 
                                         'url': content.url(self.request), 
                                         'correlation': correlation})
                relatedcontents.append(correlation_data)
                isactive = action_updated or isactive
                self._update_data(messages, resources, 
                                  all_messages, all_resources)

        for correlation in target_correlations:
            content = correlation.source
            correlation_data, resources, \
            messages, action_updated = self._correlation_action(correlation)
            correlation_data.update({'content': content, 
                                     'url': content.url(self.request), 
                                     'correlation': correlation})
            relatedcontents.append(correlation_data)
            isactive = action_updated or isactive
            self._update_data(messages, resources, all_messages, all_resources)

        len_contents = len(relatedcontents)
        index = str(len_contents)
        if len_contents > 1:
            index = '*'

        message = (_(ASSOCIATION_MESSAGES[index]),
                  len_contents,
                  index)
        self.message = message
        result = {}
        values = {
                'relatedcontents': relatedcontents,
                'current_user': user,
                'message': message
               }
        body = self.content(result=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates:[item]}
        item['messages'] = all_messages
        item['isactive'] = isactive
        result.update(all_resources)
        result  = merge_dicts(self.requirements_copy, result)
        return result
Beispiel #31
0
def locale_widget(node, kw):
    locales = [(l, LANGUAGES_TITLES.get(l, l)) for l in AVAILABLE_LANGUAGES]
    sorted_locales = sorted(locales)
    sorted_locales.insert(0, ('', _('- Select -')))
    return Select2Widget(values=sorted_locales)
Beispiel #32
0
 def _init_definition(self):
     self.defineNodes(
             start = StartEventDefinition(),
             pg = ParallelGatewayDefinition(),
             respond = ActivityDefinition(contexts=[Respond],
                                    description=_("Answer"),
                                    title=_("Answer"),
                                    groups=[]),
             edit = ActivityDefinition(contexts=[Edit],
                                    description=_("Edit"),
                                    title=_("Edit"),
                                    groups=[]),
             remove = ActivityDefinition(contexts=[Remove],
                                    description=_("Remove"),
                                    title=_("Remove"),
                                    groups=[]),
             pin = ActivityDefinition(contexts=[Pin],
                                    description=_("Pin"),
                                    title=_("Pin"),
                                    groups=[]),
             unpin = ActivityDefinition(contexts=[Unpin],
                                    description=_("Unpin"),
                                    title=_("Unpin"),
                                    groups=[]),
             transformtoidea = ActivityDefinition(contexts=[TransformToIdea],
                                    description=_("Transform the comment into an idea"),
                                    title=_("Transform into an idea"),
                                    groups=[]),
             transformtoquestion = ActivityDefinition(contexts=[TransformToQuestion],
                                    description=_("Transform the comment into a question"),
                                    title=_("Transform into a question"),
                                    groups=[]),
             see = ActivityDefinition(contexts=[SeeComment],
                                    description=_("Details"),
                                    title=_("Details"),
                                    groups=[]),
             eg = ExclusiveGatewayDefinition(),
             end = EndEventDefinition(),
     )
     self.defineTransitions(
             TransitionDefinition('start', 'pg'),
             TransitionDefinition('pg', 'respond'),
             TransitionDefinition('respond', 'eg'),
             TransitionDefinition('pg', 'transformtoidea'),
             TransitionDefinition('transformtoidea', 'eg'),
             TransitionDefinition('pg', 'transformtoquestion'),
             TransitionDefinition('transformtoquestion', 'eg'),
             TransitionDefinition('pg', 'edit'),
             TransitionDefinition('edit', 'eg'),
             TransitionDefinition('pg', 'remove'),
             TransitionDefinition('remove', 'eg'),
             TransitionDefinition('pg', 'pin'),
             TransitionDefinition('pin', 'eg'),
             TransitionDefinition('pg', 'unpin'),
             TransitionDefinition('unpin', 'eg'),
             TransitionDefinition('pg', 'see'),
             TransitionDefinition('see', 'eg'),
             TransitionDefinition('eg', 'end'),
     )
Beispiel #33
0
from pontus.view import BasicView
from pontus.util import merge_dicts
from pontus.view_operation import MultipleView

from novaideo.utilities.util import render_listing_objs
from novaideo.content.processes.reports_management.behaviors import SeeReports
from novaideo import _
from novaideo.core import BATCH_DEFAULT_SIZE
from novaideo.views.filter import find_entities
from novaideo.core import SignalableEntity
from novaideo.content.interface import ISReport
from novaideo.utilities.util import (generate_navbars, ObjectRemovedException,
                                     get_vote_actions_body)

CONTENTS_MESSAGES = {
    '0': _(u"""No element found"""),
    '1': _(u"""One element found"""),
    '*': _(u"""${number} elements found""")
}


class ReportView(BasicView):
    template = 'novaideo:views/novaideo_view_manager/templates/home.pt'
    wrapper_template = 'novaideo:views/templates/simple_wrapper.pt'
    report_state = 'pending'

    def update(self):
        user = get_current()
        context_oid = get_oid(self.context)
        dace_index = find_catalog('dace')
        dace_container_oid = dace_index['container_oid']
Beispiel #34
0
 def __init__(self, **kwargs):
     super(FacebookProcess, self).__init__(**kwargs)
     self.title = _('Facebook process')
     self.description = _('Facebook process')
Beispiel #35
0
class SeeMyContentsView(BasicView):
    title = _('My contents')
    name = 'seemycontents'
    behaviors = [SeeMyContents]
    template = 'novaideo:views/novaideo_view_manager/templates/search_result.pt'
    viewid = 'seemycontents'
    wrapper_template = 'novaideo:views/templates/simple_wrapper.pt'
    css_class = 'panel-transparent'
    contents_messages = CONTENTS_MESSAGES
    selected_filter = ['metadata_filter', ('temporal_filter', ['negation', 'created_date']),
                       'text_filter', 'other_filter']
    include_archived = True
    content_types = ['idea', 'proposal', 'question', 'event']

    def _get_title(self, **args):
        return _(self.contents_messages[args.get('index')],
                       mapping={'number': args.get('len_result')})

    def _add_filter(self, user):
        def source(**args):
            objects = find_entities(
                user=user,
                intersect=self._get_content_ids(user), **args)
            return objects

        url = self.request.resource_url(self.context,
                                        '@@novaideoapi')
        return get_filter(
            self, url=url,
            select=self.selected_filter,
            source=source)

    def _get_content_ids(self, user):
        contents = user.get_contents(user) \
            if hasattr(user, 'get_contents') else []
        return [get_oid(o) for o in contents]

    def update(self):
        self.execute(None)
        user = get_current()
        filter_form, filter_data = self._add_filter(user)
        args = merge_with_filter_view(self, {})
        args['request'] = self.request
        objects = find_entities(
            user=user,
            intersect=self._get_content_ids(user),
            include_archived=self.include_archived,
            **args)
        objects, sort_body = sort_view_objects(
            self, objects, self.content_types, user,
            intersect=getattr(self, 'sorts', None))
        url = self.request.resource_url(self.context, self.name)
        batch = Batch(objects, self.request,
                      url=url,
                      default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_contents"
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = self._get_title(
            index=index, len_result=len_result, user=user)
        filter_data['filter_message'] = self.title
        filter_body = self.filter_instance.get_body(filter_data)
        result_body, result = render_listing_objs(
            self.request, batch, user,
            display_state=getattr(self, 'display_state', True))
        if filter_form:
            result = merge_dicts(
                {'css_links': filter_form['css_links'],
                 'js_links': filter_form['js_links']
                }, result)

        values = {'bodies': result_body,
                  'batch': batch,
                  'filter_body': filter_body,
                  'sort_body': sort_body}
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
Beispiel #36
0
from novaideo.content.processes.novaideo_view_manager.behaviors import (
    SeeAnalytics)
from novaideo.utilities.analytics_utility import hover_color
from novaideo.utilities.util import to_localized_time
from novaideo.content.processes import get_content_types_states
from novaideo import core, _, log
from novaideo.content.novaideo_application import NovaIdeoApplication
from novaideo.views.filter import (get_contents_by_keywords,
                                   get_contents_by_states,
                                   get_contents_by_dates,
                                   get_organizations_by_evaluations)
from novaideo.content.keyword import DEFAULT_TREE, ROOT_TREE

DEFAULT_CONTENT_TYPES = ['idea', 'proposal', 'question']

DATESOF = [('publication', _('Publication')),
           ('examination', _('Examination'))]

DATE_FORMAT = {'day': '%d/%m/%Y', 'month': '%m/%Y', 'year': '%Y'}

FREQUENCY = [('day', _('Day')), ('month', _('Month')), ('year', _('Year'))]


class Compute(Behavior):

    behavior_id = "compute"
    title = _("Compute")
    description = ""

    def start(self, context, request, appstruct, **kw):
        return {}
Beispiel #37
0
class UploadUsers(InfiniteCardinality):
    style = 'button'  #TODO add style abstract class
    style_descriminator = 'admin-action'
    style_picto = 'glyphicon glyphicon-bullhorn'
    style_order = 5.2
    submission_title = _('Import')
    isSequential = False
    context = INovaIdeoApplication
    roles_validation = uploaduser_roles_validation
    processsecurity_validation = uploaduser_processsecurity_validation

    def start(self, context, request, appstruct, **kw):
        root = getSite()
        user = get_current()
        novaideo_catalog = find_catalog('novaideo')
        identifier_index = novaideo_catalog['identifier']
        user_titles = {str(i).lower(): str(i) for i in root.titles}
        title_template = u"""{title} {first_name} {last_name}"""
        mail_template = root.get_mail_template('invitation')
        localizer = request.localizer
        novaideo_title = root.title
        xlfile = appstruct['file']['_object_data']
        invitations_data = get_data_from_xl(file=xlfile,
                                            properties={
                                                'first_name':
                                                ('String', False),
                                                'last_name': ('String', False),
                                                'user_title':
                                                ('String', False),
                                                'email': ('String', False),
                                                'organization':
                                                ('String', False),
                                                'ismanager':
                                                ('Boolean', False),
                                                'roles': ('String', True)
                                            })
        for invitation_data in invitations_data:
            email = invitation_data['email']
            if email and invitation_data['first_name'] and invitation_data[
                    'last_name']:
                query = identifier_index.any([email])
                users = list(query.execute().all())
                if not users:
                    organization_title = invitation_data.pop(
                        'organization', None)
                    organizations = list(
                        get_entities_by_title([IOrganization],
                                              organization_title).all())
                    organization = organizations[0] if organizations else None

                    roles = invitation_data.get('roles', [])
                    roles = [
                        INVITATION_ROLES.get(r.lower()) for r in roles
                        if r.lower() in INVITATION_ROLES
                    ]
                    roles = roles or ['Member']
                    invitation_data['roles'] = roles

                    user_title = invitation_data['user_title']
                    invitation_data['user_title'] = user_titles.get(
                        user_title.lower(), 'Mr') if user_title else 'Mr'

                    invitation_data['title'] = title_template.format(
                        title=invitation_data['user_title'],
                        first_name=invitation_data['first_name'],
                        last_name=invitation_data['last_name'])
                    invitation = Invitation(**invitation_data)
                    invitation.state.append('pending')
                    invitation.setproperty('manager', user)
                    invitation.__name__ = gen_random_token()
                    if organization:
                        invitation.setproperty('organization', organization)

                    root.addtoproperty('invitations', invitation)
                    roles_translate = [
                        localizer.translate(APPLICATION_ROLES.get(r, r))
                        for r in getattr(invitation, 'roles', [])
                    ]

                    subject = mail_template['subject'].format(
                        novaideo_title=novaideo_title)
                    email_data = get_user_data(invitation, 'recipient',
                                               request)
                    email_data.update(
                        get_entity_data(invitation, 'invitation', request))
                    message = mail_template['template'].format(
                        roles=", ".join(roles_translate),
                        novaideo_title=novaideo_title,
                        **email_data)
                    alert('email', [root.get_site_sender()],
                          [invitation.email],
                          subject=subject,
                          body=message)

        return {}

    def redirect(self, context, request, **kw):
        return HTTPFound(request.resource_url(request.root,
                                              '@@seeinvitations'))
Beispiel #38
0
class Challenge(SearchableEntity, CorrelableEntity, PresentableEntity,
                ExaminableEntity, Node, Emojiable, SignalableEntity,
                Debatable):
    """Challenge class"""
    type_title = _('Challenge')
    icon = 'ion-trophy'
    templates = {
        'default': 'novaideo:views/templates/challenge_result.pt',
        'bloc': 'novaideo:views/templates/challenge_card.pt',
        'small': 'novaideo:views/templates/small_challenge_result.pt',
        'popover': 'novaideo:views/templates/challenge_popover.pt',
        'card': 'novaideo:views/templates/challenge_card.pt'
    }
    name = renamer()
    author = SharedUniqueProperty('author', 'challenges')
    image = CompositeUniqueProperty('image')
    proposals = SharedMultipleProperty('proposals', 'challenge')
    ideas = SharedMultipleProperty('ideas', 'challenge')
    questions = SharedMultipleProperty('questions', 'challenge')
    attached_files = CompositeMultipleProperty('attached_files')
    invited_users = SharedMultipleProperty('invited_users')
    url_files = CompositeMultipleProperty('url_files')
    ballots = CompositeMultipleProperty('ballots')
    ballot_processes = SharedMultipleProperty('ballot_processes')

    def __init__(self, **kwargs):
        super(Challenge, self).__init__(**kwargs)
        self.set_data(kwargs)
        self.addtoproperty('channels', Channel())
        self.urls = PersistentDict({})

    def __setattr__(self, name, value):
        super(Challenge, self).__setattr__(name, value)
        if name in ('deadline', 'published_at', 'created_at') and value:
            self.init_total_days()

    @property
    def related_contents(self):
        return [content[0] for content in self.all_related_contents]

    @property
    def challenge(self):
        return self

    @property
    def transformed_from(self):
        """Return all related contents"""
        transformed_from = [
            correlation[1].context
            for correlation in self.get_related_contents(
                CorrelationType.solid, ['transformation'])
            if correlation[1].context
        ]
        return transformed_from[0] if transformed_from else None

    @property
    def is_expired(self):
        if 'closed' in self.state:
            return True

        deadline = getattr(self, 'deadline', None)
        if deadline is not None:
            now = datetime.datetime.now(tz=pytz.UTC)
            return now.date() >= deadline

        return False

    @property
    def can_add_content(self):
        return not self.is_expired and 'pending' in self.state

    @property
    def remaining_duration(self):
        deadline = getattr(self, 'deadline', None)
        duration = getattr(self, 'duration', None)
        if deadline is not None and duration is not None:
            now = datetime.datetime.now(tz=pytz.UTC)
            remaining = (deadline - now.date()).days
            return remaining if remaining >= 0 else 0

        return None

    def init_published_at(self):
        setattr(self, 'published_at', datetime.datetime.now(tz=pytz.UTC))

    def init_support_history(self):
        if not hasattr(self, '_support_history'):
            setattr(self, '_support_history', PersistentList())

    def init_total_days(self):
        deadline = getattr(self, 'deadline', None)
        date = getattr(self, 'published_at', None)
        date = date if date else getattr(self, 'created_at', None)
        if deadline is not None and date is not None:
            duration = (deadline - date.date()).days
            setattr(self, 'duration', duration)

    def is_managed(self, root):
        return root.manage_challenges

    def get_attached_files_data(self):
        return get_files_data(self.attached_files)

    def get_all_attached_files_data(self):
        files = list(self.attached_files)
        files.append(self.image)
        return get_files_data(files)

    def get_node_descriminator(self):
        return 'challenge'

    def format(self, request):
        text = getattr(self, 'text', '')
        all_urls, url_files, text_urls, formatted_text = text_urls_format(
            text, request, True)
        self.urls = PersistentDict(all_urls)
        self.setproperty('url_files', url_files)
        self.formatted_text = formatted_text
        self.formatted_urls = text_urls
Beispiel #39
0
class WorkParamsConfigurationSchema(Schema):
    """Schema for site configuration."""

    content_to_manage = colander.SchemaNode(
        colander.Set(),
        widget=content_manage_choices,
        title=_('Contents to be managed with the ideas'),
        description=_('Content that can be created by members. Ideas are included by default.'),
        default=DEFAULT_CONTENT_TO_MANAGE,
        missing=DEFAULT_CONTENT_TO_MANAGE
    )

    content_to_moderate = colander.SchemaNode(
        colander.Set(),
        widget=content_types_choices,
        title=_('Contents to be moderated'),
        description=_('Contents can be moderated.'),
        missing=[]
    )

    content_to_support = colander.SchemaNode(
        colander.Set(),
        widget=content_types_choices,
        title=_('Contents to be supported'),
        description=_('Contents can be supported by users.'),
        missing=[]
    )

    content_to_examine = colander.SchemaNode(
        colander.Set(),
        widget=content_types_choices,
        title=_('Contents to be examined'),
        description=_('Contents must be examined by a review committee.'),
        missing=[]
    )

    proposal_template = colander.SchemaNode(
        ObjectData(File),
        widget=get_file_widget(file_extensions=['html']),
        title=_('Proposal template'),
        missing=None,
        description=_("Only HTML files are supported."),
        )

    work_modes = colander.SchemaNode(
        colander.Set(),
        title=_('Work modes'),
        description=_('Work modes of the working group (for proposals).'),
        widget=modes_choice,
        default=[],
    )

    nonproductive_cycle_nb = colander.SchemaNode(
        colander.Integer(),
        validator=colander.Range(1, 10),
        title=_('Number of non-productive cycles'),
        description=_('The number of non-productive improvement cycles before the closure of the working group.'),
        default=3,
        )

    can_submit_directly = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(),
        label=_('Allow direct submission of proposal'),
        description=_('Members can submit directly the proposal.'),
        title='',
        missing=False
    )
Beispiel #40
0
from novaideo import _
from novaideo.content.interface import (IChallenge, Iidea, IProposal,
                                        IQuestion, IPerson, IOrganization,
                                        INovaIdeoApplication)

DEFAULT_STAT_TEMPLATE = 'novaideo:views/templates/entity_stats.pt'

DEFAULT_EVALUATION_STAT_TEMPLATE = 'novaideo:views/templates/entity_stats_chart.pt'

SUPPORT_COLOR = '#2ea88d'

OPPOSE_COLOR = '#de6819'

EXAMINATION_VALUES = {
    'favorable': {
        'title': _('Positive'),
        'color': '#40b322'
    },
    'to_study': {
        'title': _('To be re-worked upon'),
        'color': '#f1a02d'
    },
    'unfavorable': {
        'title': _('Negative'),
        'color': '#f13b2d'
    }
}


class IStat(Interface):
    def get_content_stat(request):
Beispiel #41
0
class UserParamsConfigurationSchema(Schema):

    only_invitation = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(),
        label=_('By invitation only'),
        description=_('Users can register by invitation only.'),
        title='',
        missing=False
    )

    moderate_registration = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(),
        label=_('Moderate user registration'),
        description=_('Moderate user registration.'),
        title='',
        missing=False
    )

    trusted_emails = colander.SchemaNode(
        colander.Set(),
        widget=Select2Widget(
            values=[],
            create=True,
            multiple=True),
        title=_('Trusted email addresses'),
        description=_("To add trusted email addresses, you need to tap the « Enter »"
                      " key after each email address or to separate them with commas."),
        missing=[]
        )

    only_for_members = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(),
        label=_('Accessible by Members only'),
        description=_('Contents can be displayed by Member sonly.'),
        title='',
        missing=False
    )

    # participants_mini = colander.SchemaNode(
    #     colander.Integer(),
    #     title=_('Minimum number of participants for a working group'),
    #     default=3,
    #     )

    anonymisation = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(
            item_css_class='conf-form-anonymisation'),
        label=_('Users can be anonymous'),
        description=_('Users can submit content anonymously.'),
        title='',
        missing=False
    )

    anonymisation_kind = colander.SchemaNode(
        colander.String(),
        widget=anonymisation_kind_widget,
        description=_('Choose the anonymization kind.'),
        title=_('Anonymization kind'),
        default='anonymity'
    )

    participants_maxi = colander.SchemaNode(
        colander.Integer(),
        title=_('Maximum number of Participants per Working Group'),
        default=12,
        )

    participations_maxi = colander.SchemaNode(
        colander.Integer(),
        title=_('Maximum number of Working Groups per Member'),
        default=5,
        )

    tokens_mini = colander.SchemaNode(
        colander.Integer(),
        title=_('Minimum number of evaluation Tokens allocated to a Member'),
        default=7,
        )
Beispiel #42
0
def view_type_widget(node, kw):
    values = list(VIEW_TYPES.items())
    values.insert(0, ('', _('- Select -')))
    return Select2Widget(css_class="viewtype-field", values=values)
Beispiel #43
0
 def contact_invariant(self, appstruct):
     contents = appstruct.get('contents', [])
     filters = appstruct.get('filters', [])
     if not contents and not filters:
         raise colander.Invalid(
             self, _('Filters or associated contents must be specified.'))
Beispiel #44
0
class SmartFolderSchema(VisualisableElementSchema):
    """Schema for keyword"""

    name = NameSchemaNode(editing=context_is_a_smartfolder, )

    title = colander.SchemaNode(
        colander.String(),
        widget=TextInputWidget(css_class="smartfolder-title-field"),
        title=_('Title'),
    )

    description = colander.SchemaNode(
        colander.String(),
        widget=deform.widget.TextAreaWidget(rows=4, cols=60),
        title=_("Description"),
    )

    locale = colander.SchemaNode(
        colander.String(),
        title=_('Locale'),
        description=_('The language for which the folder will be displayed'),
        widget=locale_widget,
        missing='')

    cover_picture = colander.SchemaNode(
        ObjectData(File),
        widget=get_file_widget(file_extensions=['png', 'jpg', 'svg']),
        title=_('Cover picture'),
        missing=None,
        description=_("Only PNG and SVG files are supported."),
    )

    filters = colander.SchemaNode(
        colander.Sequence(),
        omit(
            select(
                FilterSchema(name='filter',
                             title=_('Filter'),
                             widget=SimpleMappingWidget(
                                 css_class='object-well default-well')),
                [
                    'metadata_filter', 'temporal_filter',
                    'contribution_filter', 'text_filter', 'other_filter'
                ]), ["_csrf_token_"]),
        widget=SequenceWidget(add_subitem_text_template=_('Add a new filter')),
        title=_('Filters'),
        description=_('Applied filters'),
        missing=[])

    contents = colander.SchemaNode(
        colander.Set(),
        widget=relatedcontents_choice,
        title=_('Associated contents'),
        description=_('Choose the contents to be associated'),
        missing=[],
        default=[],
    )

    view_type = colander.SchemaNode(colander.String(),
                                    widget=view_type_widget,
                                    title=_("View type"),
                                    description=_('How to display contents'),
                                    default='default')

    icon_data = colander.SchemaNode(DictSchemaType(),
                                    widget=BootstrapIconInputWidget(),
                                    title=_('Icon'),
                                    default={
                                        'icon': 'glyphicon-folder-open',
                                        'icon_class': 'glyphicon'
                                    },
                                    description=_('Select an icon.'))

    style = omit(CssSchema(widget=SimpleMappingWidget()), ["_csrf_token_"])

    @invariant
    def contact_invariant(self, appstruct):
        contents = appstruct.get('contents', [])
        filters = appstruct.get('filters', [])
        if not contents and not filters:
            raise colander.Invalid(
                self, _('Filters or associated contents must be specified.'))
Beispiel #45
0
from substanced.util import Batch

from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from dace.objectofcollaboration.principal.util import get_current
from pontus.view import BasicView

from novaideo.content.processes.proposal_management.behaviors import (
    SeeMembers)
from novaideo.content.proposal import Proposal
from novaideo.utilities.util import render_small_listing_objs
from novaideo import _

BATCH_DEFAULT_SIZE = 30

MEMBERS_MESSAGES = {
    '0': _(u"""No member"""),
    '1': _(u"""One member"""),
    '*': _(u"""${number} members""")
}


@view_config(
    name='seeproposalmembers',
    context=Proposal,
    renderer='pontus:templates/views_templates/grid.pt',
)
class SeeMembersView(BasicView):
    title = _('Members')
    name = 'seeproposalmembers'
    description = _("See members")
    behaviors = [SeeMembers]
from substanced.util import get_oid

from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS

from novaideo.content.processes.novaideo_view_manager.behaviors import (
    SeeMySupports)
from novaideo.content.novaideo_application import NovaIdeoApplication
from novaideo import _
from novaideo.views.filter import (FILTER_SOURCES)
from .see_my_contents import SeeMyContentsView
from novaideo.views.core import asyn_component_config

CONTENTS_MESSAGES = {
    '0':
    _(u"""You have evaluated no content so far. You have ${tokens} remaining evaluation tokens"""
      ),
    '1':
    _(u"""You have evaluated one content so far. You have ${tokens} remaining evaluation tokens"""
      ),
    '*':
    _(u"""You have evaluated ${number} contents so far. You have ${tokens} remaining evaluation tokens"""
      )
}


@asyn_component_config(id='novaideoapp_seemysupports')
@view_config(
    name='seemysupports',
    context=NovaIdeoApplication,
    renderer='pontus:templates/views_templates/grid.pt',
)
Beispiel #47
0
class EditQuestionView(MultipleView):
    title = _('Edit the question')
    name = 'editquestion'
    wrapper_template = 'novaideo:views/templates/view_wrapper.pt'
    template = 'pontus:templates/views_templates/simple_multipleview.pt'
    views = (EditQuestionFormView, )
Beispiel #48
0
def keywords_validator(node, kw):
    if DEFAULT_TREE == kw or tree_min_len(kw) < 2:
        raise colander.Invalid(
            node,
            _('Minimum one keyword required. You can specify a second keyword level for each keyword chosen.'
              ))
Beispiel #49
0
class ChallengeSchema(VisualisableElementSchema, SearchableEntitySchema):
    """Schema for challenge"""

    name = NameSchemaNode(editing=context_is_a_challenge, )

    description = colander.SchemaNode(
        colander.String(),
        validator=colander.Length(max=300),
        widget=LimitedTextAreaWidget(rows=5, cols=30, limit=300),
        title=_("Abstract"),
        description=_("Describe in a few words the challenge."))

    text = colander.SchemaNode(
        colander.String(),
        widget=RichTextWidget(),
        title=_("Text"),
        description=_("You can describe in detail the challenge."))

    image = colander.SchemaNode(
        ObjectData(Image),
        widget=image_widget,
        title=_('Image'),
        description=
        _('You see a square on the top left of the image if it exceeds the maximum'
          ' size allowed. Move and enlarge it if necessary, to determine an area of'
          ' interest. Several images will be generated from this area.'),
    )

    attached_files = colander.SchemaNode(
        colander.Sequence(),
        colander.SchemaNode(ObjectData(File),
                            name=_("File"),
                            widget=get_file_widget()),
        widget=FilesWidget(add_subitem_text_template='',
                           item_css_class='files-block'),
        missing=[],
        title=_('Attached files'),
    )

    is_restricted = colander.SchemaNode(
        colander.Boolean(),
        widget=deform.widget.CheckboxWidget(
            item_css_class='is-restricted-input'),
        label=_('Is restricted'),
        title='',
        description=
        _('Check this box if the challenge is restricted to a set of members. '
          'Only concerned members can add and see the contents created in this challenge.'
          ),
        missing=False)

    invited_users = colander.SchemaNode(
        colander.Set(),
        widget=users_to_invite,
        title=_('Concerned users'),
        description=_(
            'Find and select the concerned members or organizations. '
            'If you want to see the members or organizations... already '
            'registered on the platform, enter a *'),
        missing=[],
    )

    deadline = colander.SchemaNode(
        colander.Date(),
        title=_('Deadline'),
        description=
        _("If your challenge is punctual, you can add a deadline for participation."
          ),
        missing=None)

    anonymous = colander.SchemaNode(
        colander.Boolean(),
        widget=anonymous_widget,
        label=_('Remain anonymous'),
        description=_('Check this box if you want to remain anonymous.'),
        title='',
        missing=False,
        default=False)
Beispiel #50
0
 def get_items(cls):
     return {
         cls.anonymity: _('Anonymity'),
         cls.pseudonymity: _('Pseudonymity')
     }
Beispiel #51
0
class AcceptInvitation(InfiniteCardinality):
    style = 'button'  #TODO add style abstract class
    style_descriminator = 'primary-action'
    style_interaction = 'ajax-action'
    context = IInvitation
    style_picto = 'glyphicon glyphicon-ok'
    submission_title = _('Save')
    roles_validation = accept_roles_validation
    state_validation = accept_state_validation

    def start(self, context, request, appstruct, **kw):
        datas = context.get_data(
            select(omit(InvitationSchema(), ['_csrf_token_']), [
                'user_title', 'roles', 'first_name', 'last_name', 'email',
                'organization'
            ]))
        roles = datas.pop('roles')
        password = appstruct['password']
        datas['locale'] = my_locale_negotiator(request)
        person = Person(password=password, **datas)
        root = getSite(context)
        principals = find_service(root, 'principals')
        users = principals['users']
        name = person.first_name + ' ' + person.last_name
        name = name_chooser(users, name=name)
        users[name] = person
        if getattr(context, 'ismanager', False) and \
           context.organization:
            grant_roles(person,
                        (('OrganizationResponsible', context.organization), ))

        person.state.append('active')
        grant_roles(person, roles)
        grant_roles(person, (('Owner', person), ))
        manager = context.manager
        root.delfromproperty('invitations', context)
        root.addtoproperty('news_letter_members', person)
        newsletters = root.get_newsletters_automatic_registration()
        email = getattr(person, 'email', '')
        if newsletters and email:
            for newsletter in newsletters:
                newsletter.subscribe(person.first_name, person.last_name,
                                     email)

        context.person = person
        if manager:
            mail_template = root.get_mail_template(
                'accept_invitation',
                getattr(manager, 'user_locale', root.locale))
            localizer = request.localizer
            email_data = get_user_data(person, 'user', request)
            novaideo_title = request.root.title
            roles_translate = [
                localizer.translate(APPLICATION_ROLES.get(r, r)) for r in roles
            ]
            subject = mail_template['subject'].format(
                novaideo_title=novaideo_title, **email_data)
            email_data.update(get_user_data(manager, 'recipient', request))
            email_data.update(get_entity_data(person, 'user', request))
            message = mail_template['template'].format(
                roles=", ".join(roles_translate),
                novaideo_title=novaideo_title,
                **email_data)
            alert('email', [root.get_site_sender()], [manager.email],
                  subject=subject,
                  body=message)

        return {}

    def redirect(self, context, request, **kw):
        return nothing
Beispiel #52
0
from dace.util import get_obj
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from pontus.util import merge_dicts
from pontus.view_operation import MultipleView

from novaideo.content.processes.novaideo_view_manager.behaviors import SeeBallot
from novaideo.content.ballot import Ballot
from novaideo.utilities.util import (render_listing_objs)
from novaideo import _, log
from novaideo.content.novaideo_application import NovaIdeoApplication

BATCH_DEFAULT_SIZE = 20

CONTENTS_MESSAGES = {
    '0': _(u"""No vote"""),
    '1': _(u"""One vote"""),
    '*': _(u"""${number} votes""")
}


@view_config(
    name='seevotes',
    context=Ballot,
    renderer='pontus:templates/views_templates/grid.pt',
)
class VotesView(BasicView):
    name = 'seevotes'
    viewid = 'seevotes'
    template = 'novaideo:views/novaideo_view_manager/templates/table_result.pt'
    wrapper_template = 'pontus:templates/views_templates/simple_view_wrapper.pt'
Beispiel #53
0
 def _get_title(self, **args):
     return _(self.contents_messages[args.get('index')],
                    mapping={'number': args.get('len_result')})
Beispiel #54
0
class AssociateView(AssociateIdeaView):
    title = _('Associate the amendment')
    description = _("Associate the amendment to an other content")
    views = (RelatedContentsView, AssociateFormView)
Beispiel #55
0
from novaideo.utilities.util import render_listing_objs
from novaideo.content.processes.novaideo_view_manager.behaviors import (
    SeeMyContents)
from novaideo.content.novaideo_application import NovaIdeoApplication
from novaideo import _
from novaideo.core import BATCH_DEFAULT_SIZE
from novaideo.views.filter import (
    get_filter, FILTER_SOURCES, merge_with_filter_view, find_entities)
from novaideo.views.filter.sort import (
    sort_view_objects)
from novaideo.views.core import asyn_component_config


CONTENTS_MESSAGES = {
    '0': _(u"""I have contributed to no content so far"""),
    '1': _(u"""I have contributed to one content so far"""),
    '*': _(u"""I have contributed to ${number} contents so far""")
    }


@asyn_component_config(id='novaideoapp_seemycontent')
@view_config(
    name='seemycontents',
    context=NovaIdeoApplication,
    renderer='pontus:templates/views_templates/grid.pt',
    )
class SeeMyContentsView(BasicView):
    title = _('My contents')
    name = 'seemycontents'
    behaviors = [SeeMyContents]
Beispiel #56
0
    ImproveProposal,
    VotingAmendments,
    Alert,
    AmendmentsResult,
    ImproveProposalAndExplain,
    VOTE_AMENDMENTS_MESSAGE,
    AMENDMENTS_VOTE_DEFAULT_DURATION,
    close_votes
    )
from novaideo import _
from novaideo.content.ballot import Ballot


VOTE_AMENDMENT_GROUP = {
    'group_id': 'vote_amendments',
    'group_title': _('Vote on amendments'),
    'group_activate': True,
    'group_activator_title': _('Vote on amendments'),
    'group_activator_class_css': 'vote-action',
    'group_activator_style_picto': 'glyphicon glyphicon-stats',
    'group_activator_order': 80
}


def eg4_votingamendments_condition(process):
    proposal = process.attachedTo.process.execution_context.created_entity(
        'proposal')
    if any('submitted' in a.state for a in proposal.amendments):
        return True

    return False
Beispiel #57
0
 def __init__(self, **kwargs):
     super(CommentManagement, self).__init__(**kwargs)
     self.title = _('Comment management')
     self.description = _('Comment management')
Beispiel #58
0
 def __init__(self, **kwargs):
     super(AmendmentWorkModeProcess, self).__init__(**kwargs)
     self.title = _('Change with amendments')
     self.description = _('Change with amendments')
class SeeRelatedWorkingGroupsView(BasicView):
    name = 'relatedworkinggroups'
    viewid = 'relatedworkinggroups'
    behaviors = [SeeRelatedWorkingGroups]
    template = 'novaideo:views/novaideo_view_manager/templates/home.pt'
    wrapper_template = 'pontus:templates/views_templates/simple_view_wrapper.pt'
    view_icon = 'icon icon novaideo-icon icon-wg'
    contextual_help = 'related-wg-help'
    title = _('The working groups')
    description = _('See the related working groups')

    def update(self):
        self.execute(None)
        user = get_current()
        objects = [
            proposal for proposal in self.context.related_proposals
            if proposal.working_group and 'archived' not in proposal.state and
            'censored' not in proposal.state and can_access(user, proposal)
        ]
        objects = sorted(objects,
                         key=lambda e: getattr(e, 'modified_at'),
                         reverse=True)
        is_small = True
        current_is_small = self.params('is_small')
        if current_is_small is not None:
            current_is_small = current_is_small.lower()
            is_small = current_is_small == 'true'
        elif self.parent or self.request.view_name == self.name:
            is_small = False

        url = self.request.resource_url(self.context,
                                        self.name,
                                        query={'is_small': str(is_small)})
        batch = Batch(objects,
                      self.request,
                      url=url,
                      default_size=BATCH_DEFAULT_SIZE)
        batch.target = "#results_idea_working_groups" + \
            str(self.context.__oid__) + \
            (is_small and 'is_small' or '')
        len_result = batch.seqlen
        index = str(len_result)
        if len_result > 1:
            index = '*'

        self.title = _(WG_MESSAGES[index], mapping={'number': len_result})
        result = {}
        if is_small:
            result_body = render_small_listing_objs(self.request, batch, user)
        else:
            result_body, result = render_listing_objs(self.request, batch,
                                                      user)

        values = {
            'bodies': result_body,
            'batch': batch,
            'empty_message': _("No working group created"),
            'empty_icon': 'novaideo-icon icon-wg'
        }
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        result['coordinates'] = {self.coordinates: [item]}
        return result
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from dace.objectofcollaboration.principal.util import get_current
from pontus.view import BasicView

from novaideo.core import can_access
from novaideo.content.processes.idea_management.behaviors import (
    SeeRelatedWorkingGroups)
from novaideo.content.idea import Idea
from novaideo.utilities.util import (render_small_listing_objs,
                                     render_listing_objs)
from novaideo import _

BATCH_DEFAULT_SIZE = 8

WG_MESSAGES = {
    '0': _(u"""No related working group"""),
    '1': _(u"""One related working group"""),
    '*': _(u"""${number} related working groups""")
}


@view_config(
    name='relatedworkinggroups',
    context=Idea,
    renderer='pontus:templates/views_templates/grid.pt',
)
class SeeRelatedWorkingGroupsView(BasicView):
    name = 'relatedworkinggroups'
    viewid = 'relatedworkinggroups'
    behaviors = [SeeRelatedWorkingGroups]
    template = 'novaideo:views/novaideo_view_manager/templates/home.pt'