Ejemplo n.º 1
0
    def after_create(self, obj):
        super(LabelledPageBuilder, self).after_create(obj)

        ILabeling(obj).update(self.activated_label_ids)
        ILabeling(obj).pers_update(self.personal_label_ids, True)
        if self.session.auto_commit:
            transaction.commit()
Ejemplo n.º 2
0
    def test_deactivate_labels(self, browser):
        root = create(
            Builder('label root').with_labels(('Question', 'purple', False),
                                              ('Bug', 'red', False),
                                              ('Feature', 'blue', True)))
        page = create(
            Builder('labelled page').within(root).with_labels(
                'question', 'bug').with_pers_labels('feature'))

        browser.login().open(page, view='labeling/update', data={})

        self.assertItemsEqual([{
            'label_id': 'feature',
            'title': 'Feature',
            'color': 'blue',
            'by_user': True
        }],
                              ILabeling(page).active_labels())

        browser.login().open(page,
                             view='pers-labeling/pers_update',
                             data={
                                 'label_id': 'feature',
                                 'active': 'True'
                             })

        self.assertItemsEqual([], ILabeling(page).active_labels())
Ejemplo n.º 3
0
 def update(self):
     """Update activated labels.
     """
     labeling = ILabeling(self.context)
     activate_labels = self.request.form.get('activate_labels', [])
     labeling.update(activate_labels)
     self.context.reindexObject(idxs=['labels'])
     return self._redirect()
Ejemplo n.º 4
0
 def update(self):
     """Update activated labels.
     """
     labeling = ILabeling(self.context)
     activate_labels = self.request.form.get('activate_labels', [])
     labeling.update(activate_labels)
     self.context.reindexObject(idxs=['labels'])
     return self._redirect()
Ejemplo n.º 5
0
 def test_available_labels(self):
     self.jar.add('Question', '#00FF00')
     labeling = ILabeling(self.document)
     self.assertEqual(
         [{'label_id': 'question',
          'title': 'Question',
          'color': '#00FF00',
          'active': False}],
         list(labeling.available_labels()))
Ejemplo n.º 6
0
    def test_activate_labels(self, browser):
        root = create(
            Builder('label root').with_labels(('Question', 'purple', False),
                                              ('Bug', 'red', False),
                                              ('Feature', 'blue', True)))
        page = create(Builder('labelled page').within(root))
        self.assertFalse(self.indexed_labels_for(page))

        browser.login().open(page,
                             view='labeling/update',
                             data={'activate_labels': ['question', 'bug']})

        self.assertItemsEqual([{
            'label_id': 'question',
            'title': 'Question',
            'color': 'purple',
            'by_user': False
        }, {
            'label_id': 'bug',
            'title': 'Bug',
            'color': 'red',
            'by_user': False
        }],
                              ILabeling(page).active_labels())

        self.assertItemsEqual(['bug', 'question'],
                              self.indexed_labels_for(page))

        browser.login().open(page,
                             view='pers-labeling/pers_update',
                             data={
                                 'label_id': 'feature',
                                 'active': 'False'
                             })

        self.assertItemsEqual([{
            'label_id': 'question',
            'title': 'Question',
            'color': 'purple',
            'by_user': False
        }, {
            'label_id': 'bug',
            'title': 'Bug',
            'color': 'red',
            'by_user': False
        }, {
            'label_id': 'feature',
            'title': 'Feature',
            'color': 'blue',
            'by_user': True
        }],
                              ILabeling(page).active_labels())

        self.assertItemsEqual(
            ['bug', 'question', 'feature', 'test_user_1_:feature'],
            self.indexed_labels_for(page))
Ejemplo n.º 7
0
    def test_update__enable_labels(self):
        self.jar.add('Bug', 'red')
        self.jar.add('Question', 'green')
        self.jar.add('Feature', 'purple')

        labeling = ILabeling(self.document)
        self.assertEqual([], labeling.active_labels())

        labeling.update(['bug', 'feature'])
        self.assertItemsEqual(['Bug', 'Feature'],
                              label_titles(labeling.active_labels()))
Ejemplo n.º 8
0
    def test_update_raises_LookupError_when_label_not_in_jar(self):
        self.assertEqual(0, len(self.jar.list()))
        self.jar.add('Question', '', False)
        labeling = ILabeling(self.document)
        with self.assertRaises(LookupError) as cm:
            labeling.update(['something'])

        self.assertEqual(
            'Cannot activate label: the label'
            ' "something" is not in the label jar. '
            'Following labels ids are available: question', str(cm.exception))
Ejemplo n.º 9
0
    def test_update_raises_LookupError_when_label_not_in_jar(self):
        self.assertEqual(0, len(self.jar.list()))
        self.jar.add('Question', '')
        labeling = ILabeling(self.document)
        with self.assertRaises(LookupError) as cm:
            labeling.update(['something'])

        self.assertEqual(
            'Cannot activate label: the label'
            ' "something" is not in the label jar. '
            'Following labels ids are available: question',
            str(cm.exception))
Ejemplo n.º 10
0
    def test_active_labels(self):
        self.jar.add('Question', '')
        self.jar.add('Bug', '')
        self.jar.add('Duplicate', '')

        labeling = ILabeling(self.document)
        labeling.update(['bug'])
        self.assertEqual(
            [{'label_id': 'bug',
              'title': 'Bug',
              'color': ''}],
            labeling.active_labels())
Ejemplo n.º 11
0
 def pers_update(self):
     """Update personal labels.
     """
     labeling = ILabeling(self.context)
     label_id = self.request.form.get('label_id')
     activate = self.request.form.get('active')
     if not label_id or activate not in ['True', 'False']:
         return self._redirect()
     activate = not eval(activate)
     ret = labeling.pers_update(label_id, activate)
     self.context.reindexObject(idxs=['labels'])
     writer = getUtility(IJSONWriter)
     self.request.response.setHeader('content-type', 'application/json')
     return writer.write({'ret': (ret and 'ok' or 'nok'), 'new_status': str(activate)})
Ejemplo n.º 12
0
    def test_active_labels_filters_deleted_labels(self):
        self.jar.add('Question', 'blue')
        self.jar.add('Bug', 'red')

        labeling = ILabeling(self.document)
        labeling.update(['question', 'bug'])

        self.jar.remove('bug')

        self.assertEqual(
            [{'label_id': 'question',
             'title': 'Question',
             'color': 'blue'}],
            list(labeling.active_labels()))
Ejemplo n.º 13
0
    def test_active_labels_filters_deleted_labels(self):
        self.jar.add('Question', 'blue', False)
        self.jar.add('Bug', 'red', False)

        labeling = ILabeling(self.document)
        labeling.update(['question', 'bug'])

        self.jar.remove('bug')

        self.assertEqual([{
            'label_id': 'question',
            'title': 'Question',
            'color': 'blue',
            'by_user': False
        }], list(labeling.active_labels()))
Ejemplo n.º 14
0
def mark_copy_im_as_read(context):
    if not context.readDataFile("imiodmsmail_singles_marker.txt"):
        return
    site = context.getSite()
    # adapted = ILabelJar(site['incoming-mail']); adapted.list()
    days_back = 5
    start = datetime.datetime(1973, 2, 12)
    end = datetime.datetime.now() - datetime.timedelta(days=days_back)
    users = {}
    functions = {
        'i': IM_READER_SERVICE_FUNCTIONS,
        'o': OM_READER_SERVICE_FUNCTIONS
    }
    brains = site.portal_catalog.unrestrictedSearchResults(
        portal_type=['dmsincomingmail', 'dmsincoming_email'],
        created={
            'query': (start, end),
            'range': 'min:max'
        },
        sort_on='created')
    out = ["%d mails" % len(brains)]
    changed_mails = 0
    related_users = set()
    for brain in brains:
        if not brain.recipient_groups:
            continue
        typ = brain.portal_type[3:4]
        user_ids = set()
        for org_uid in brain.recipient_groups:
            if org_uid not in users:
                users[org_uid] = {}
            if typ not in users[org_uid]:
                users[org_uid][typ] = [
                    u.id for u in get_selected_org_suffix_users(
                        org_uid, functions[typ])
                ]
            for userid in users[org_uid][typ]:
                user_ids.add(userid)
        if len(user_ids):
            related_users.update(user_ids)
            obj = brain._unrestrictedGetObject()
            labeling = ILabeling(obj)
            labeling.storage['lu'] = PersistentList(user_ids)
            obj.reindexObject(idxs=['labels'])
            changed_mails += 1
    out.append('%d mails labelled with "lu"' % changed_mails)
    out.append('%d users are concerned' % len(related_users))
    return '\n'.join(out)
Ejemplo n.º 15
0
    def test_mixed_updating_labels(self, browser):
        root = create(
            Builder('label root').with_labels(('Question', 'purple', False),
                                              ('Bug', 'red', False),
                                              ('Feature', 'blue', False)))
        page = create(
            Builder('labelled page').within(root).with_labels(
                'question', 'bug'))

        browser.login().open(page,
                             view='labeling/update',
                             data={'activate_labels': ['question', 'feature']})

        self.assertItemsEqual([{
            'label_id': 'question',
            'title': 'Question',
            'color': 'purple',
            'by_user': False
        }, {
            'label_id': 'feature',
            'title': 'Feature',
            'color': 'blue',
            'by_user': False
        }],
                              ILabeling(page).active_labels())
Ejemplo n.º 16
0
def labels(obj):
    """Indexer of 'labels' for ILabelSupport.

    Stores a list of:
        * '_' : no label
        * label_id : for 'global' label
        * user_id:label_id : for 'by_user' label
    """
    labeling = ILabeling(obj)
    labels = []
    for label_id in labeling.storage:
        try:
            label = labeling.jar.get(label_id)
            if label['by_user']:
                if len(labeling.storage[label_id]):
                    # if at least one user has selected the label, we add it
                    labels.append(label_id)
                    # add each combination user:label
                    for user_id in labeling.storage[label_id]:
                        labels.append('%s:%s' % (user_id, label_id))
            else:
                labels.append(label_id)
        except KeyError:
            pass
    # store something when no label. Query with 'not' in ZCatalog>=3 will retrieve it.
    if not labels:
        return ['_']
    return labels
Ejemplo n.º 17
0
 def pers_update(self):
     """Update personal labels.
     """
     labeling = ILabeling(self.context)
     label_id = self.request.form.get('label_id')
     activate = self.request.form.get('active')
     if not label_id or activate not in ['True', 'False']:
         return self._redirect()
     activate = not eval(activate)
     ret = labeling.pers_update([label_id], activate)
     self.context.reindexObject(idxs=['labels'])
     writer = getUtility(IJSONWriter)
     self.request.response.setHeader('content-type', 'application/json')
     return writer.write({
         'ret': (ret and 'ok' or 'nok'),
         'new_status': str(activate)
     })
Ejemplo n.º 18
0
 def test_available_labels(self):
     self.jar.add('Question', '#00FF00', False)
     self.jar.add('Read', 'red', True)
     labeling = ILabeling(self.document)
     self.assertEqual([[{
         'label_id': 'read',
         'title': 'Read',
         'color': 'red',
         'active': False,
         'by_user': True
     }],
                       [{
                           'label_id': 'question',
                           'title': 'Question',
                           'color': '#00FF00',
                           'active': False,
                           'by_user': False
                       }]], list(labeling.available_labels()))
Ejemplo n.º 19
0
    def test_active_labels_is_sorted(self):
        self.jar.add('Zeta-0', '')
        self.jar.add('zeta-1', '')
        self.jar.add('alpha-0', '')
        self.jar.add('\xc3\x84lpha-1', '')
        self.jar.add('Alpha-2', '')

        labeling = ILabeling(self.document)
        labeling.update([
                'zeta-0',
                'zeta-1',
                'alpha-0',
                'alpha-1',
                'alpha-2',
                ])

        self.assertEqual(
            ['alpha-0', '\xc3\x84lpha-1', 'Alpha-2', 'Zeta-0', 'zeta-1'],
            [label.get('title') for label in labeling.active_labels()])
Ejemplo n.º 20
0
    def test_update__enable_labels(self):
        self.jar.add('Bug', 'red', False)
        self.jar.add('Question', 'green', True)
        self.jar.add('Feature', 'purple', True)

        labeling = ILabeling(self.document)
        self.assertEqual([], labeling.active_labels())

        labeling.update(['bug'])
        labeling.pers_update('feature', True)
        self.assertItemsEqual(['Bug', 'Feature'],
                              label_titles(labeling.active_labels()))
Ejemplo n.º 21
0
    def test_active_labels_is_sorted(self):
        self.jar.add('Zeta-0', '', False)
        self.jar.add('zeta-1', '', False)
        self.jar.add('alpha-0', '', False)
        self.jar.add('\xc3\x84lpha-1', '', False)
        self.jar.add('Alpha-2', '', False)

        labeling = ILabeling(self.document)
        labeling.update([
            'zeta-0',
            'zeta-1',
            'alpha-0',
            'alpha-1',
            'alpha-2',
        ])

        self.assertEqual(
            ['alpha-0', '\xc3\x84lpha-1', 'Alpha-2', 'Zeta-0', 'zeta-1'],
            [label.get('title') for label in labeling.active_labels()])
Ejemplo n.º 22
0
 def setUp(self):
     """ """
     super(TestLabels, self).setUp()
     self.doc1 = api.content.create(self.portal, 'Document', 'doc1')
     self.doc2 = api.content.create(self.portal, 'Document', 'doc2')
     # defined some labels
     alsoProvides(self.portal, ILabelRoot)
     adapted = ILabelJar(self.portal)
     adapted.add('Pers1', 'green', True)  # label_id = pers1
     adapted.add('Pers2', 'green', True)  # label_id = pers2
     adapted.add('Pers3', 'green', True)  # label_id = pers3
     adapted.add('Glob1', 'red', False)  # label_id = glob1
     adapted.add('Glob2', 'red', False)  # label_id = glob2
     adapted.add('Glob3', 'red', False)  # label_id = glob3
     # can label created objects
     for obj in (self.doc1, self.doc2):
         alsoProvides(obj, ILabelSupport)
     self.lab_doc1 = ILabeling(self.doc1)
     self.lab_doc2 = ILabeling(self.doc2)
     login(self.portal, TEST_USER_NAME)
Ejemplo n.º 23
0
    def test_active_labels(self):
        self.jar.add('Question', '', False)
        self.jar.add('Bug', '', False)
        self.jar.add('Duplicate', '', True)

        labeling = ILabeling(self.document)
        labeling.update(['bug'])
        labeling.pers_update('duplicate', True)
        self.assertListEqual([{
            'label_id': 'bug',
            'title': 'Bug',
            'color': '',
            'by_user': False
        }, {
            'label_id': 'duplicate',
            'title': 'Duplicate',
            'color': '',
            'by_user': True
        }], labeling.active_labels())
Ejemplo n.º 24
0
    def test_labelled_page_builder(self):
        root = create(
            Builder('label root').with_labels(('Questions', 'blue', False),
                                              ('Bugs', 'red', True),
                                              ('Enhancements', 'green', True)))
        page = create(
            Builder('labelled page').within(root).with_labels(
                'questions').with_pers_labels('bugs'))

        self.assertItemsEqual([{
            'label_id': 'questions',
            'title': 'Questions',
            'color': 'blue',
            'by_user': False
        }, {
            'label_id': 'bugs',
            'title': 'Bugs',
            'color': 'red',
            'by_user': True
        }],
                              ILabeling(page).active_labels())
Ejemplo n.º 25
0
 def test_available_labels_empty(self):
     labeling = ILabeling(self.document)
     self.assertEqual([], list(labeling.available_labels()))
Ejemplo n.º 26
0
def labels(obj):
    labeling = ILabeling(obj)
    return map(itemgetter('label_id'), labeling.active_labels())
Ejemplo n.º 27
0
def group_assignment(event):
    """
        manage the add of a user in a plone group
    """
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.AssignedUsersWithDeactivatedVocabulary')
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.AssignedUsersForFacetedFilterVocabulary')
    if event.group_id.endswith(CREATING_GROUP_SUFFIX):
        invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.ActiveCreatingGroupVocabulary')
    # we update dms config
    if 'n_plus_' in event.group_id:
        update_transitions_auc_config('dmsincomingmail', action='add', group_id=event.group_id)  # i_e ok
        update_transitions_levels_config(['dmsincomingmail', 'dmsoutgoingmail', 'task'], action='add',  # i_e ok
                                         group_id=event.group_id)
    # we manage the 'lu' label for a new assignment
    # same functions as IncomingMailInCopyGroupUnreadCriterion
    userid = event.principal
    orgs = organizations_with_suffixes([event.group_id], IM_READER_SERVICE_FUNCTIONS, group_as_str=True)
    if orgs:
        days_back = 5
        start = datetime.datetime(1973, 2, 12)
        end = datetime.datetime.now() - datetime.timedelta(days=days_back)
        catalog = api.portal.get_tool('portal_catalog')
        for brain in catalog(portal_type=['dmsincomingmail', 'dmsincoming_email'], recipient_groups=orgs,
                             labels={'not': ['%s:lu' % userid]},
                             created={'query': (start, end), 'range': 'min:max'}):
            # if not brain.recipient_groups:
            #    continue
            obj = brain.getObject()
            labeling = ILabeling(obj)
            user_ids = labeling.storage.setdefault('lu', PersistentList())  # _p_changed is managed
            user_ids.append(userid)  # _p_changed is managed
            obj.reindexObject(idxs=['labels'])
    # we manage the personnel-folder person and held position
    orgs = organizations_with_suffixes([event.group_id], ['encodeur'], group_as_str=True)
    if orgs:
        user = api.user.get(userid)
        start = api.portal.get_registry_record('omail_fullname_used_form', IImioDmsMailConfig, default='firstname')
        firstname, lastname = separate_fullname(user, start=start)
        portal = api.portal.get()
        intids = getUtility(IIntIds)
        pf = portal['contacts']['personnel-folder']
        # exists already
        exist = portal.portal_catalog.unrestrictedSearchResults(mail_type=userid, portal_type='person')
        if userid in pf:
            pers = pf[userid]
        elif exist:
            pers = exist[0]._unrestrictedGetObject()
        else:
            pers = api.content.create(container=pf, type='person', id=userid, userid=userid, lastname=lastname,
                                      firstname=firstname, use_parent_address=False)
        if api.content.get_state(pers) == 'deactivated':
            api.content.transition(pers, 'activate')
        hps = [b._unrestrictedGetObject() for b in
               portal.portal_catalog.unrestrictedSearchResults(path='/'.join(pers.getPhysicalPath()),
                                                               portal_type='held_position')]
        hps_orgs = dict([(hp.get_organization(), hp) for hp in hps])
        uid = orgs[0]
        org = uuidToObject(uid, unrestricted=True)
        if not org:
            return
        if uid in pers:
            hp = pers[uid]
        elif org in hps_orgs:
            hp = hps_orgs[org]
        else:
            hp = api.content.create(container=pers, id=uid, type='held_position',
                                    email=safe_unicode(user.getProperty('email').lower()),
                                    position=RelationValue(intids.getId(org)), use_parent_address=True)
        if api.content.get_state(hp) == 'deactivated':
            api.content.transition(hp, 'activate')
Ejemplo n.º 28
0
 def _apply(self, **data):
     if ((data.get('removed_values', None)
          and data['action_choice'] in ('remove', 'replace'))
             or (data.get('added_values', None))
             and data['action_choice'] in ('add', 'replace', 'overwrite')):
         values = {'p_a': [], 'p_r': [], 'g_a': [], 'g_r': []}
         for act, lst in (('a', data.get('added_values', [])),
                          ('r', data.get('removed_values', []))):
             for val in lst:
                 typ = (':' in val) and 'p' or 'g'
                 values['{}_{}'.format(typ, act)].append(val.split(':')[0])
         for brain in self.brains:
             obj = brain.getObject()
             labeling = ILabeling(obj)
             p_act, g_act = active_labels(labeling)
             # manage global labels
             if self.can_change_labels and (values['g_a'] or values['g_r']):
                 if data['action_choice'] in ('overwrite'):
                     items = set(values['g_a'])
                 else:
                     items = set(g_act)  # currently active labels
                     if data['action_choice'] in ('remove', 'replace'):
                         items = items.difference(values['g_r'])
                     if data['action_choice'] in ('add', 'replace'):
                         items = items.union(values['g_a'])
                 labeling.update(items)
             # manage personal labels
             if values['p_a'] or values['p_r']:
                 if data['action_choice'] in ('overwrite'):
                     items = set(values['p_a'])
                     labeling.pers_update(self.p_labels.difference(items),
                                          False)
                     labeling.pers_update(items, True)
                 else:
                     if data['action_choice'] in ('remove', 'replace'):
                         labeling.pers_update(
                             set(p_act).intersection(values['p_r']), False)
                     if data['action_choice'] in ('add', 'replace'):
                         labeling.pers_update(values['p_a'], True)
             obj.reindexObject(['labels'])
Ejemplo n.º 29
0
 def active_labels(self):
     return ILabeling(self.context).active_labels()
Ejemplo n.º 30
0
 def available_labels(self):
     return ILabeling(self.context).available_labels()
Ejemplo n.º 31
0
 def test_available_labels_empty(self):
     labeling = ILabeling(self.document)
     self.assertEqual([[], []], labeling.available_labels())