def setUp(self):
        """Custom shared utility setup for tests."""
        self.portal = self.layer['portal']
        # Organizations creation
        self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
        self.portal[DEFAULT_DIRECTORY_ID].invokeFactory(
            'organization', PLONEGROUP_ORG, title='My organization')
        own_orga = get_own_organization()
        own_orga.invokeFactory('organization',
                               'department1',
                               title='Department 1')
        own_orga.invokeFactory('organization',
                               'department2',
                               title='Department 2')
        self.contacts = [own_orga['department1'], own_orga['department2']]

        set_registry_organizations([c.UID() for c in self.contacts])
        set_registry_functions([{
            'fct_title': u'Director',
            'fct_id': u'director',
            'fct_orgs': [],
            'fct_management': False,
            'enabled': True
        }])

        self.portal.invokeFactory('acontent',
                                  'acontent1',
                                  title='Content 1',
                                  pg_organization=self.contacts[0].UID())
        self.portal.invokeFactory('acontent',
                                  'acontent2',
                                  title='Content 2',
                                  pg_organization=self.contacts[1].UID())
Ejemplo n.º 2
0
 def addPersonsAndHeldPositions(self, person_descriptors, source):
     '''Creates persons and eventual held_positions.'''
     own_org = get_own_organization()
     container = own_org.aq_inner.aq_parent
     intids = getUtility(IIntIds)
     for person_descr in person_descriptors:
         # create the person
         person = api.content.create(container=container,
                                     type='person',
                                     **person_descr.getData())
         # person.photo is the name of the photo to use stored in /images
         if person.photo:
             photo_path = '%s/images/%s' % (source, person.photo)
             data = self.find_binary(photo_path)
             photo_file = NamedImage(data, filename=person.photo)
             person.photo = photo_file
             validate_fields(person, raise_on_errors=True)
         for held_pos_descr in person_descr.held_positions:
             # get the position
             data = held_pos_descr.getData()
             org = container.restrictedTraverse(data['position'])
             data['position'] = RelationValue(intids.getId(org))
             held_position = api.content.create(container=person,
                                                type='held_position',
                                                **data)
             validate_fields(held_position, raise_on_errors=True)
 def test_SortedSelectedOrganizationsElephantVocabulary(self):
     """ Test sorted elephant vocabulary """
     factory_all = getUtility(
         IVocabularyFactory, 'collective.contact.plonegroup.organization_services')
     vocab_all = factory_all(self.portal)
     vocab_all_values = [v.value for v in vocab_all]
     self.assertEqual(len(vocab_all), 3)
     self.assertListEqual([v.title for v in vocab_all],
                          ['Department 1', 'Department 1 - Service 1', 'Department 2'])
     set_registry_organizations([vocab_all_values[2], vocab_all_values[0]])
     factory_wrp = getUtility(
         IVocabularyFactory,
         'collective.contact.plonegroup.browser.settings.SortedSelectedOrganizationsElephantVocabulary')
     vocab_wrp = factory_wrp(self.portal)
     self.assertEqual(len(vocab_wrp), 3)
     # values are shown sorted, no matter how it is selected in plonegroup organizations
     self.assertListEqual([v.title for v in vocab_wrp], [u'Department 1', u'Department 2'])
     self.assertListEqual(sorted([v.token for v in vocab_wrp]),
                          sorted(get_registry_organizations()))
     self.assertEqual(vocab_wrp.getTerm(vocab_all_values[1]).title, u'Department 1 - Service 1')
     # vocabulary use caching, when new values added, the vocabulary is correct
     own_orga = get_own_organization()
     own_orga.invokeFactory('organization', 'department3', title='Department 3')
     set_registry_organizations(
         [vocab_all_values[2],
          vocab_all_values[0],
          own_orga['department3'].UID()])
     vocab_wrp = factory_wrp(self.portal)
     self.assertListEqual(
         [v.title for v in vocab_wrp],
         [u'Department 1', u'Department 2', u'Department 3'])
     self.assertListEqual(
         sorted([v.token for v in vocab_wrp]),
         sorted(get_registry_organizations()))
 def test_validateSettingsRemoveFunction(self):
     """A function may only be removed if every linked Plone groups are empty."""
     # add a user to group department1 director
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     api.group.add_user(groupname=plone_group_id, username=TEST_USER_ID)
     invariants = validator.InvariantsValidator(
         None, None, None, settings.IContactPlonegroupConfig, None)
     orgs = get_registry_organizations()
     functions = get_registry_functions()
     data = {'organizations': orgs, 'functions': functions}
     # for now it validates correctly
     self.assertFalse(invariants.validate(data))
     # remove 'director'
     functions.pop(0)
     errors = invariants.validate(data)
     self.assertTrue(isinstance(errors[0], Invalid))
     error_msg = translate(
         msgid=u"can_not_remove_function_every_plone_groups_not_empty",
         domain='collective.contact.plonegroup',
         mapping={'removed_function': 'director',
                  'plone_group_id': plone_group_id})
     self.assertEqual(translate(errors[0].message), error_msg)
     # remove user from plone group, now it validates
     api.group.remove_user(groupname=plone_group_id, username=TEST_USER_ID)
     self.assertFalse(invariants.validate(data))
 def test_validateSettingsSelectFunctionOrgsOnExistingFunction(self):
     """Selecting 'fct_orgs' for an existing function (so for which Plone groups are already created),
        is only possible if groups that will be deleted (Plone groups of organizations not selected
        as 'fct_orgs') are empty."""
     # add a user to group department1 director
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep2 = own_orga['department2']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     api.group.add_user(groupname=plone_group_id, username=TEST_USER_ID)
     invariants = validator.InvariantsValidator(
         None, None, None, settings.IContactPlonegroupConfig, None)
     orgs = get_registry_organizations()
     functions = get_registry_functions()
     data = {'organizations': orgs, 'functions': functions}
     # set dep2 as 'fct_orgs' of 'director' function
     director = functions[0]
     director['fct_orgs'] = [dep2.UID()]
     errors = invariants.validate(data)
     self.assertTrue(isinstance(errors[0], Invalid))
     error_msg = translate(
         msgid=u"can_not_select_function_orgs_every_other_plone_groups_not_empty",
         domain='collective.contact.plonegroup',
         mapping={'function': 'director',
                  'plone_group_id': plone_group_id})
     self.assertEqual(translate(errors[0].message), error_msg)
     # remove user from plone group, now it validates
     api.group.remove_user(groupname=plone_group_id, username=TEST_USER_ID)
     self.assertFalse(invariants.validate(data))
 def test_adaptPloneGroupDefinition(self):
     """ Test event when an organization is changed """
     organizations = get_registry_organizations()
     own_orga = get_own_organization()
     # an organization is modified
     own_orga['department1'].title = 'Department 1 changed'
     event.notify(ObjectModifiedEvent(own_orga['department1']))
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 changed (Director)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 changed - Service 1 (Director)')
     # an organization is moved (service1 in department2)
     clipboard = own_orga['department1'].manage_cutObjects(['service1'])
     own_orga['department2'].manage_pasteObjects(clipboard)
     # the event IObjectMovedEvent is triggered
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 2 - Service 1 (Director)')
     # a configured organization is deleted. Exception raised
     self.assertRaises(Redirect, own_orga['department2'].manage_delObjects, ids=['service1'])
     # THIS IS A KNOWN ERROR: the organization is deleted despite the exception !!!!!!!
     self.assertFalse('service1' in own_orga['department2'])
     # an unused organization is deleted. No exception
     own_orga['department2'].invokeFactory('organization', 'service3', title='Service 3')
     own_orga['department2'].manage_delObjects(ids=['service3'])
     self.assertFalse('service3' in own_orga['department2'])
 def test_adaptPloneGroupDefinition(self):
     """ Test event when an organization is changed """
     organizations = get_registry_organizations()
     own_orga = get_own_organization()
     # an organization is modified
     own_orga['department1'].title = 'Department 1 changed'
     event.notify(ObjectModifiedEvent(own_orga['department1']))
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 changed (Director)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 changed - Service 1 (Director)')
     # an organization is moved (service1 in department2)
     clipboard = own_orga['department1'].manage_cutObjects(['service1'])
     own_orga['department2'].manage_pasteObjects(clipboard)
     # the event IObjectMovedEvent is triggered
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 2 - Service 1 (Director)')
     # a configured organization is deleted. Exception raised
     self.assertRaises(Redirect, own_orga['department2'].manage_delObjects, ids=['service1'])
     # THIS IS A KNOWN ERROR: the organization is deleted despite the exception !!!!!!!
     self.assertFalse('service1' in own_orga['department2'])
     # an unused organization is deleted. No exception
     own_orga['department2'].invokeFactory('organization', 'service3', title='Service 3')
     own_orga['department2'].manage_delObjects(ids=['service3'])
     self.assertFalse('service3' in own_orga['department2'])
    def setUp(self):
        """Custom shared utility setup for tests."""
        self.portal = self.layer['portal']
        # Organizations creation
        self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
        self.portal[DEFAULT_DIRECTORY_ID].invokeFactory('organization', PLONEGROUP_ORG, title='My organization')
        own_orga = get_own_organization()
        own_orga.invokeFactory('organization', 'department1', title='Department 1')
        own_orga.invokeFactory('organization', 'department2', title='Department 2')
        own_orga['department1'].invokeFactory('organization', 'service1', title='Service 1')
        own_orga.invokeFactory('organization', 'inactive_department', title='Inactive department')
        inactive_department = own_orga['inactive_department']
        api.content.transition(obj=inactive_department, transition='deactivate')

        set_registry_organizations([own_orga['department1'].UID(),
                                   own_orga['department1']['service1'].UID(),
                                   own_orga['department2'].UID()])
        set_registry_functions([{'fct_title': u'Director',
                                 'fct_id': u'director',
                                 'fct_orgs': [],
                                 'fct_management': False,
                                 'enabled': True},
                                {'fct_title': u'Worker',
                                 'fct_id': u'worker',
                                 'fct_orgs': [],
                                 'fct_management': False,
                                 'enabled': True}])
 def test_validateSettingsSelectFunctionOrgsOnExistingFunction(self):
     """Selecting 'fct_orgs' for an existing function (so for which Plone groups are already created),
        is only possible if groups that will be deleted (Plone groups of organizations not selected
        as 'fct_orgs') are empty."""
     # add a user to group department1 director
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep2 = own_orga['department2']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     api.group.add_user(groupname=plone_group_id, username=TEST_USER_ID)
     invariants = validator.InvariantsValidator(
         None, None, None, settings.IContactPlonegroupConfig, None)
     orgs = get_registry_organizations()
     functions = get_registry_functions()
     data = {'organizations': orgs, 'functions': functions}
     # set dep2 as 'fct_orgs' of 'director' function
     director = functions[0]
     director['fct_orgs'] = [dep2.UID()]
     errors = invariants.validate(data)
     self.assertTrue(isinstance(errors[0], Invalid))
     error_msg = translate(
         msgid=u"can_not_select_function_orgs_every_other_plone_groups_not_empty",
         domain='collective.contact.plonegroup',
         mapping={'function': 'director',
                  'plone_group_id': plone_group_id})
     self.assertEqual(translate(errors[0].message), error_msg)
     # remove user from plone group, now it validates
     api.group.remove_user(groupname=plone_group_id, username=TEST_USER_ID)
     self.assertFalse(invariants.validate(data))
 def test_validateSettingsDisableFunction(self):
     """A function may only be disabled (enabled=False)
        if every linked Plone groups are empty."""
     # add a user to group department1 director
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     api.group.add_user(groupname=plone_group_id, username=TEST_USER_ID)
     invariants = validator.InvariantsValidator(
         None, None, None, settings.IContactPlonegroupConfig, None)
     orgs = get_registry_organizations()
     functions = get_registry_functions()
     data = {'organizations': orgs, 'functions': functions}
     # for now it validates correctly
     self.assertFalse(invariants.validate(data))
     # disable 'director'
     functions[0]['enabled'] = False
     errors = invariants.validate(data)
     self.assertTrue(isinstance(errors[0], Invalid))
     error_msg = translate(
         msgid=u"can_not_disable_suffix_plone_groups_not_empty",
         domain='collective.contact.plonegroup',
         mapping={'removed_function': 'director',
                  'plone_group_id': plone_group_id})
     self.assertEqual(translate(errors[0].message), error_msg)
     # remove user from plone group, now it validates
     api.group.remove_user(groupname=plone_group_id, username=TEST_USER_ID)
     self.assertFalse(invariants.validate(data))
Ejemplo n.º 11
0
def import_orgs(self, data=None):
    """
      Import the organizations from the 'data' dictionnaty received as parameter
    """
    member = api.user.get_current()
    if not member.has_role('Manager'):
        raise Unauthorized('You must be a Manager to access this script !')

    if not dict:
        return "This script needs a 'dict' parameter"
    if not hasattr(self, 'portal_plonemeeting'):
        return "PloneMeeting must be installed to run this script !"

    own_org = get_own_organization()
    out = []
    data = eval(data)
    for elt_id, elt_infos in data.items():
        if elt_id not in own_org.objectIds():
            api.content.create(container=own_org,
                               type="organization",
                               id=elt_id,
                               title=elt_infos[0],
                               description=elt_infos[1],
                               acronym=elt_infos[2])
            out.append("Organization %s added" % elt_id)
        else:
            out.append("Organization %s already exists" % elt_id)
    return '\n'.join(out)
Ejemplo n.º 12
0
 def test_get_own_organization_path(self):
     """ Test the returned organization path """
     self.assertEqual(get_own_organization(default=True),
                      self.portal[DEFAULT_DIRECTORY_ID][PLONEGROUP_ORG])
     self.assertEqual(get_own_organization(default=False),
                      self.portal[DEFAULT_DIRECTORY_ID][PLONEGROUP_ORG])
     self.assertEqual(get_own_organization_path(default=True),
                      '/plone/contacts/plonegroup-organization')
     self.assertEqual(get_own_organization_path(default=False),
                      '/plone/contacts/plonegroup-organization')
     # remove own organization
     api.content.delete(self.own_orga)
     self.assertIsNone(get_own_organization(default=True))
     self.assertIsNone(get_own_organization(default=False))
     self.assertIsNone(get_own_organization_path(default=True))
     self.assertIsNone(get_own_organization_path(default=False))
     self.assertEqual(get_own_organization_path(not_found_value='unfound'),
                      'unfound')
Ejemplo n.º 13
0
    def _migrate_categories_to_groups_in_charge_field(self):
        logger.info("Migrating Category to Groups in charge field")
        catalog = api.portal.get_tool("portal_catalog")
        own_org = get_own_organization()

        # First we create the appropriate groupsInCharge
        logger.info("Adapting MeetingConfig...")
        cfg = catalog(portal_type="MeetingConfig",
                      id=self.meeting_config_id)[0].getObject()
        categories = cfg.categories
        for cat_id, category in categories.contentItems():
            if cat_id not in own_org.objectIds():
                data = {
                    "id": cat_id,
                    "title": category.Title(),
                    "description": category.Description()
                }
                api.content.create(container=own_org,
                                   type="organization",
                                   **data)
            new_org_uid = org_id_to_uid(cat_id)

            enabled_plonegroup_org_uids = api.portal.get_registry_record(
                ORGANIZATIONS_REGISTRY)
            if new_org_uid not in enabled_plonegroup_org_uids:
                api.portal.set_registry_record(
                    ORGANIZATIONS_REGISTRY,
                    enabled_plonegroup_org_uids + [new_org_uid])

            ordered_group_in_charge_uids = cfg.getOrderedGroupsInCharge()
            if new_org_uid not in ordered_group_in_charge_uids:
                cfg.setOrderedGroupsInCharge(ordered_group_in_charge_uids +
                                             (new_org_uid, ))

            category.enabled = False

        # Next we migrate the category to groupsInCharge on MeetingItems
        brains = catalog(portal_type=(
            cfg.getItemTypeName(),
            cfg.getItemTypeName(configType="MeetingItemRecurring"),
            cfg.getItemTypeName(configType="MeetingItemTemplate"),
        ))
        pghandler = ZLogHandler(steps=1000)
        pghandler.init("Adapting items...", len(brains))
        for i, brain in enumerate(brains):
            pghandler.report(i)
            item = brain.getObject()
            if item.getCategory() != u"_none_":
                item.setGroupsInCharge([org_id_to_uid(item.getCategory())])
                item.setCategory(None)
                item.reindexObject(idxs=["getGroupsInCharge", "getCategory"])
        pghandler.finish()

        logger.info("Done migrating Categories to Groups in charge field")
 def test_detectContactPlonegroupChangeRemoveFunction(self):
     """When a function is removed, every linked Plone groups are deleted as well.
        This is protected by validateSettings that checks first that every Plone groups are empty."""
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     self.assertTrue(api.group.get(plone_group_id))
     functions = get_registry_functions()
     # remove 'director'
     functions.pop(0)
     set_registry_functions(functions)
     # the linked Plone groups are deleted
     self.assertFalse(api.group.get(plone_group_id))
 def test_detectContactPlonegroupChangeDisableFunction(self):
     """When a function is disabled (enabled=False), every linked Plone groups are deleted as well.
        This is protected by validateSettings that checks first that every Plone groups are empty."""
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     plone_group_id = get_plone_group_id(dep1.UID(), 'director')
     self.assertTrue(api.group.get(plone_group_id))
     functions = get_registry_functions()
     # disable 'director'
     functions[0]['enabled'] = False
     set_registry_functions(functions)
     # the linked Plone groups are deleted
     self.assertFalse(api.group.get(plone_group_id))
 def test_detectContactPlonegroupChange(self):
     """Test if group creation works correctly"""
     group_ids = [group.id for group in api.group.get_groups()]
     organizations = get_registry_organizations()
     for uid in organizations:
         self.assertIn('%s_director' % uid, group_ids)
         self.assertIn('%s_worker' % uid, group_ids)
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 (Director)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 - Service 1 (Director)')
     # Changing function title
     set_registry_functions([{'fct_title': u'Directors',
                              'fct_id': u'director',
                              'fct_orgs': [],
                              'fct_management': False,
                              'enabled': True},
                             {'fct_title': u'Worker',
                              'fct_id': u'worker',
                              'fct_orgs': [],
                              'fct_management': False,
                              'enabled': True}])
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 (Directors)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 - Service 1 (Directors)')
     # Adding new organization
     own_orga = get_own_organization()
     own_orga['department2'].invokeFactory('organization', 'service2', title='Service 2')
     # append() method on the registry doesn't trigger the event. += too
     newValue = get_registry_organizations() + [own_orga['department2']['service2'].UID()]
     set_registry_organizations(newValue)
     group_ids = [group.id for group in api.group.get_groups()]
     last_uid = get_registry_organizations()[-1]
     self.assertIn('%s_director' % last_uid, group_ids)
     self.assertIn('%s_worker' % last_uid, group_ids)
     # Adding new function
     newValue = get_registry_functions() + [{'fct_title': u'Chief',
                                             'fct_id': u'chief',
                                             'fct_orgs': [],
                                             'fct_management': False,
                                             'enabled': True}]
     set_registry_functions(newValue)
     group_ids = [group.id for group in api.group.get_groups() if '_' in group.id]
     self.assertEquals(len(group_ids), 12)
     for uid in get_registry_organizations():
         self.assertIn('%s_director' % uid, group_ids)
         self.assertIn('%s_chief' % uid, group_ids)
         self.assertIn('%s_worker' % uid, group_ids)
 def test_onlyRelevantPloneGroupsCreatedWhenFunctionRestrictedToSelectedOrgs(self):
     """Test using 'fct_orgs' when defining functions."""
     # create a new suffix and restrict it to department1
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep1_uid = dep1.UID()
     dep2 = own_orga['department2']
     dep2_uid = dep2.UID()
     functions = get_registry_functions()
     new_function = {'fct_id': u'new', 'fct_title': u'New', 'fct_orgs': [dep1_uid]}
     functions.append(new_function)
     set_registry_functions(functions)
     # 'new' suffixed Plone group was created only for dep1
     self.assertTrue(api.group.get(get_plone_group_id(dep1_uid, u'new')))
     self.assertFalse(api.group.get(get_plone_group_id(dep2_uid, u'new')))
 def test_detectContactPlonegroupChangeSelectOrgs(self):
     """When selecting 'fct_orgs' on a function, Plone groups are create/deleted depending
        on the fact that 'fct_orgs' is empty or contains some organization uids."""
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep1_uid = dep1.UID()
     dep2 = own_orga['department2']
     dep2_uid = dep2.UID()
     dep1_plone_group_id = get_plone_group_id(dep1_uid, 'director')
     dep2_plone_group_id = get_plone_group_id(dep2_uid, 'director')
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select dep2_uid for 'director'
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep2_uid]
     set_registry_functions(functions)
     # dep1 director Plone group is deleted
     self.assertFalse(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select dep1_uid for 'director'
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep1_uid]
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertFalse(api.group.get(dep2_plone_group_id))
     # select nothing for 'director', every groups are created
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = []
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select both dep1 and dep2, every groups are created
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep1_uid, dep2_uid]
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # Changing function title
     dep1_plone_group = api.group.get(dep1_plone_group_id)
     self.assertEquals(dep1_plone_group.getProperty('title'), 'Department 1 (Director)')
     dep2_plone_group = api.group.get(dep2_plone_group_id)
     self.assertEquals(dep2_plone_group.getProperty('title'), 'Department 2 (Director)')
     functions[0]['fct_title'] = u'New title'
     set_registry_functions(functions)
     dep1_plone_group = api.group.get(dep1_plone_group_id)
     self.assertEquals(dep1_plone_group.getProperty('title'), 'Department 1 (New title)')
     dep2_plone_group = api.group.get(dep2_plone_group_id)
     self.assertEquals(dep2_plone_group.getProperty('title'), 'Department 2 (New title)')
 def test_detectContactPlonegroupChangeSelectOrgs(self):
     """When selecting 'fct_orgs' on a function, Plone groups are create/deleted depending
        on the fact that 'fct_orgs' is empty or contains some organization uids."""
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep1_uid = dep1.UID()
     dep2 = own_orga['department2']
     dep2_uid = dep2.UID()
     dep1_plone_group_id = get_plone_group_id(dep1_uid, 'director')
     dep2_plone_group_id = get_plone_group_id(dep2_uid, 'director')
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select dep2_uid for 'director'
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep2_uid]
     set_registry_functions(functions)
     # dep1 director Plone group is deleted
     self.assertFalse(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select dep1_uid for 'director'
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep1_uid]
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertFalse(api.group.get(dep2_plone_group_id))
     # select nothing for 'director', every groups are created
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = []
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # select both dep1 and dep2, every groups are created
     functions = get_registry_functions()
     functions[0]['fct_orgs'] = [dep1_uid, dep2_uid]
     set_registry_functions(functions)
     self.assertTrue(api.group.get(dep1_plone_group_id))
     self.assertTrue(api.group.get(dep2_plone_group_id))
     # Changing function title
     dep1_plone_group = api.group.get(dep1_plone_group_id)
     self.assertEquals(dep1_plone_group.getProperty('title'), 'Department 1 (Director)')
     dep2_plone_group = api.group.get(dep2_plone_group_id)
     self.assertEquals(dep2_plone_group.getProperty('title'), 'Department 2 (Director)')
     functions[0]['fct_title'] = u'New title'
     set_registry_functions(functions)
     dep1_plone_group = api.group.get(dep1_plone_group_id)
     self.assertEquals(dep1_plone_group.getProperty('title'), 'Department 1 (New title)')
     dep2_plone_group = api.group.get(dep2_plone_group_id)
     self.assertEquals(dep2_plone_group.getProperty('title'), 'Department 2 (New title)')
Ejemplo n.º 20
0
    def addUsers(self, org_descriptors):
        '''Creates Plone users and add it to linked Plone groups.'''
        plone_utils = self.portal.plone_utils
        # if we are in dev, we use DEFAULT_USER_PASSWORD, else we will generate a
        # password that is compliant with the current password policy...
        if is_develop_environment():
            password = DEFAULT_USER_PASSWORD
        else:
            password = generate_password()
        msg = "The password used for added users is %s" % (
            password or DEFAULT_USER_PASSWORD)
        logger.info(msg)
        # add a portal_message so admin adding the Plone site knows password
        plone_utils.addPortalMessage(msg, 'warning')

        member_tool = api.portal.get_tool('portal_membership')

        own_org = get_own_organization()
        plonegroup_org_uids = get_registry_organizations()
        for org_descr in org_descriptors:
            if org_descr.parent_path:
                # find parent organization following parent path from container
                container = own_org.restrictedTraverse(org_descr.parent_path)
            else:
                container = own_org
            org = container.get(org_descr.id)
            # Create users
            for userDescr in org_descr.getUsers():
                # if we defined a generated password here above, we use it
                # either we use the password provided in the applied profile
                if password:
                    userDescr.password = password
                self.addUser(userDescr)
            # Add users in the correct Plone groups.
            org_uid = org.UID()
            if org_uid in plonegroup_org_uids:
                for suffix in get_all_suffixes(org_uid):
                    plone_group = get_plone_group(org_uid, suffix)
                    group_members = plone_group.getMemberIds()
                    # protect in case we have suffixes only for some groups
                    for userDescr in getattr(org_descr, suffix, []):
                        if userDescr.id not in group_members:
                            api.group.add_user(group=plone_group,
                                               username=userDescr.id)
                            if userDescr.create_member_area:
                                member_tool.createMemberArea(userDescr.id)
Ejemplo n.º 21
0
 def various_update(self):
     # replace front-page
     frontpage = getattr(self.portal, 'front-page')
     frontpage.title = _translate("front_page_title")
     frontpage.description = _translate("front_page_descr")
     frontpage.text = richtextval(_translate("front_page_text"))
     transitions(frontpage, ('retract', 'publish_internally'))
     frontpage.reindexObject()
     self.portal.templates.layout = 'dg-templates-listing'
     # plonegroup-organization
     pgo = get_own_organization()
     behaviour = ISelectableConstrainTypes(pgo)
     behaviour.setConstrainTypesMode(1)
     behaviour.setLocallyAllowedTypes([])
     behaviour.setImmediatelyAddableTypes([])
     ISelectableConstrainTypes(pgo['echevins']).setConstrainTypesMode(0)
     ISelectableConstrainTypes(pgo['services']).setConstrainTypesMode(0)
Ejemplo n.º 22
0
    def test_OrgNotRemovableIfUsed(self):
        """An organization may not be removed if used in :
           - MeetingConfig.archivingRefs."""
        self.changeUser('siteadmin')
        cfg = self.meetingConfig
        own_org = get_own_organization()

        # create a new organization so it is used nowhere
        new_org = self.create('organization', id='new_org', title=u'New org', acronym='NO1')
        new_org_id = new_org.getId()
        new_org_uid = new_org.UID()
        cfg.setUseGroupsAsCategories(False)
        self._select_organization(new_org_uid)
        self.assertTrue(new_org_uid in cfg.listActiveOrgsForArchivingRefs())
        cfg.setArchivingRefs((
            {'active': '1',
             'restrict_to_groups': [new_org_uid, ],
             'row_id': '1',
             'code': '1',
             'label': "1"},
            {'active': '1',
             'restrict_to_groups': [],
             'row_id': '2',
             'code': '2',
             'label': '2'},))
        self._select_organization(new_org_uid, remove=True)

        with self.assertRaises(BeforeDeleteException) as cm:
            own_org.manage_delObjects([new_org_id])
        self.assertEquals(cm.exception.message, 'can_not_delete_meetinggroup_archivingrefs')
        cfg.setArchivingRefs((
            {'active': '1',
             'restrict_to_groups': [],
             'row_id': '1',
             'code': '1',
             'label': "1"},
            {'active': '1',
             'restrict_to_groups': [],
             'row_id': '2',
             'code': '2',
             'label': '2'},))

        # now it is removable
        own_org.manage_delObjects([new_org_id, ])
        self.assertIsNone(own_org.get(new_org_id, None))
Ejemplo n.º 23
0
    def addOrgs(self, org_descriptors, defer_data=True):
        '''Creates organizations (a list of OrgaDescriptor instances) in the contact own organization.'''
        own_org = get_own_organization()
        orgs = []
        active_orgs = []
        savedOrgsData = {}
        for org_descr in org_descriptors:
            if org_descr.parent_path:
                # find parent organization following parent path from container
                container = own_org.restrictedTraverse(org_descr.parent_path)
            else:
                container = own_org
            # Maybe the organization already exists?
            # It could be the case if we are reapplying a configuration
            if org_descr.id in container.objectIds():
                continue

            # save some informations that will be reinjected at the end
            data = org_descr.getData()
            if defer_data:
                # org is not created and we needs its uid...
                savedOrgsData['dummy'] = {
                    'item_advice_states': data['item_advice_states'],
                    'item_advice_edit_states': data['item_advice_edit_states'],
                    'item_advice_view_states': data['item_advice_view_states'],
                    'groups_in_charge': data['groups_in_charge']
                }
                data['item_advice_states'] = []
                data['item_advice_edit_states'] = []
                data['item_advice_view_states'] = []
                data['groups_in_charge'] = []

            org = api.content.create(container=container,
                                     type='organization',
                                     **data)

            if defer_data:
                # finalize savedOrgsData, store org uid instead 'dummy'
                savedOrgsData[org.UID()] = savedOrgsData['dummy'].copy()
                del savedOrgsData['dummy']
            validate_fields(org, raise_on_errors=True)
            orgs.append(org)
            if org_descr.active:
                active_orgs.append(org)
        return orgs, active_orgs, savedOrgsData
 def setUp(self):
     """Custom shared utility setup for tests."""
     self.portal = self.layer['portal']
     # Organizations creation
     self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
     self.portal[DEFAULT_DIRECTORY_ID].invokeFactory(
         'organization', PLONEGROUP_ORG, title='My organization')
     self.own_orga = get_own_organization()
     self.dep1 = api.content.create(container=self.own_orga,
                                    type='organization',
                                    id='department1',
                                    title='Department 1')
     self.uid = self.dep1.UID()
     self.dep2 = api.content.create(container=self.own_orga,
                                    type='organization',
                                    id='department2',
                                    title='Department 2')
     # users and groups
     api.user.create(u'*****@*****.**',
                     u'dexter',
                     properties={'fullname': u'Dexter Morgan'})
     api.user.create(u'*****@*****.**',
                     u'debra',
                     properties={'fullname': u'Debra Morgan'})
     self.inv_group = api.group.create(u'investigators', u'Investigators')
     self.tech_group = api.group.create(u'technicians', u'Technicians')
     # settings
     self.registry = getUtility(IRegistry)
     set_registry_organizations([self.uid])
     set_registry_functions([
         {
             'fct_title': u'Observers',
             'fct_id': u'observer',
             'fct_orgs': [],
             'fct_management': False,
             'enabled': True
         },
         {
             'fct_title': u'Director',
             'fct_id': u'director',
             'fct_orgs': [],
             'fct_management': False,
             'enabled': True
         },
     ])
 def test_onlyRelevantPloneGroupsCreatedWhenFunctionRestrictedToSelectedOrgs(self):
     """Test using 'fct_orgs' when defining functions."""
     # create a new suffix and restrict it to department1
     own_orga = get_own_organization()
     dep1 = own_orga['department1']
     dep1_uid = dep1.UID()
     dep2 = own_orga['department2']
     dep2_uid = dep2.UID()
     functions = get_registry_functions()
     new_function = {'fct_id': u'new',
                     'fct_title': u'New',
                     'fct_orgs': [dep1_uid],
                     'fct_management': False,
                     'enabled': True}
     functions.append(new_function)
     set_registry_functions(functions)
     # 'new' suffixed Plone group was created only for dep1
     self.assertTrue(api.group.get(get_plone_group_id(dep1_uid, u'new')))
     self.assertFalse(api.group.get(get_plone_group_id(dep2_uid, u'new')))
    def setUp(self):
        """Custom shared utility setup for tests."""
        self.portal = self.layer['portal']
        # Organizations creation
        self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
        self.portal[DEFAULT_DIRECTORY_ID].invokeFactory('organization', PLONEGROUP_ORG, title='My organization')
        own_orga = get_own_organization()
        own_orga.invokeFactory('organization', 'department1', title='Department 1')
        own_orga.invokeFactory('organization', 'department2', title='Department 2')
        self.contacts = [own_orga['department1'], own_orga['department2']]

        set_registry_organizations([c.UID() for c in self.contacts])
        set_registry_functions([{'fct_title': u'Director', 'fct_id': u'director', 'fct_orgs': []}])

        self.portal.invokeFactory('acontent',
                                  'acontent1',
                                  title='Content 1',
                                  pg_organization=self.contacts[0].UID())
        self.portal.invokeFactory('acontent',
                                  'acontent2',
                                  title='Content 2',
                                  pg_organization=self.contacts[1].UID())
    def setUp(self):
        """Custom shared utility setup for tests."""
        self.portal = self.layer['portal']
        # Organizations creation
        self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
        self.portal[DEFAULT_DIRECTORY_ID].invokeFactory('organization', PLONEGROUP_ORG, title='My organization')
        own_orga = get_own_organization()
        own_orga.invokeFactory('organization', 'department1', title='Department 1')
        own_orga.invokeFactory('organization', 'department2', title='Department 2')
        own_orga['department1'].invokeFactory('organization', 'service1', title='Service 1')
        own_orga.invokeFactory('organization', 'inactive_department', title='Inactive department')
        inactive_department = own_orga['inactive_department']
        api.content.transition(obj=inactive_department, transition='deactivate')

        set_registry_organizations([own_orga['department1'].UID(),
                                   own_orga['department1']['service1'].UID(),
                                   own_orga['department2'].UID()])
        set_registry_functions([{'fct_title': u'Director',
                                 'fct_id': u'director',
                                 'fct_orgs': []},
                                {'fct_title': u'Worker',
                                 'fct_id': u'worker',
                                 'fct_orgs': []}])
 def test_detectContactPlonegroupChange(self):
     """Test if group creation works correctly"""
     group_ids = [group.id for group in api.group.get_groups()]
     organizations = get_registry_organizations()
     for uid in organizations:
         self.assertIn('%s_director' % uid, group_ids)
         self.assertIn('%s_worker' % uid, group_ids)
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 (Director)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 - Service 1 (Director)')
     # Changing function title
     set_registry_functions([{'fct_title': u'Directors', 'fct_id': u'director', 'fct_orgs': []},
                             {'fct_title': u'Worker', 'fct_id': u'worker', 'fct_orgs': []}])
     d1_d_group = api.group.get(groupname='%s_director' % organizations[0])
     self.assertEquals(d1_d_group.getProperty('title'), 'Department 1 (Directors)')
     d1s1_d_group = api.group.get(groupname='%s_director' % organizations[1])
     self.assertEquals(d1s1_d_group.getProperty('title'), 'Department 1 - Service 1 (Directors)')
     # Adding new organization
     own_orga = get_own_organization()
     own_orga['department2'].invokeFactory('organization', 'service2', title='Service 2')
     # append() method on the registry doesn't trigger the event. += too
     newValue = get_registry_organizations() + [own_orga['department2']['service2'].UID()]
     set_registry_organizations(newValue)
     group_ids = [group.id for group in api.group.get_groups()]
     last_uid = get_registry_organizations()[-1]
     self.assertIn('%s_director' % last_uid, group_ids)
     self.assertIn('%s_worker' % last_uid, group_ids)
     # Adding new function
     newValue = get_registry_functions() + [{'fct_title': u'Chief', 'fct_id': u'chief', 'fct_orgs': []}]
     set_registry_functions(newValue)
     group_ids = [group.id for group in api.group.get_groups() if '_' in group.id]
     self.assertEquals(len(group_ids), 12)
     for uid in get_registry_organizations():
         self.assertIn('%s_director' % uid, group_ids)
         self.assertIn('%s_chief' % uid, group_ids)
         self.assertIn('%s_worker' % uid, group_ids)
Ejemplo n.º 29
0
 def setUp(self):
     """Custom shared utility setup for tests."""
     self.portal = self.layer['portal']
     # Organizations creation
     self.portal.invokeFactory('directory', DEFAULT_DIRECTORY_ID)
     self.portal[DEFAULT_DIRECTORY_ID].invokeFactory(
         'organization', PLONEGROUP_ORG, title='My organization')
     self.own_orga = get_own_organization()
     self.dep1 = api.content.create(container=self.own_orga,
                                    type='organization',
                                    id='department1',
                                    title='Department 1')
     self.uid = self.dep1.UID()
     self.dep2 = api.content.create(container=self.own_orga,
                                    type='organization',
                                    id='department2',
                                    title='Department 2')
     self.registry = getUtility(IRegistry)
     set_registry_organizations([self.uid])
     set_registry_functions([
         {
             'fct_title': u'Observers',
             'fct_id': u'observer',
             'fct_orgs': [],
             'fct_management': False,
             'enabled': True
         },
         {
             'fct_title': u'Director',
             'fct_id': u'director',
             'fct_orgs': [],
             'fct_management': False,
             'enabled': True
         },
     ])
     api.group.add_user(groupname='%s_director' % self.uid,
                        username=TEST_USER_ID)
Ejemplo n.º 30
0
def getVocabularyTermsForOrganization(context, organization_id='services', states=[], sort_on='path'):
    """
      Submethod called by vocabularies to get their content from a query
      in the organizations of the 'contacts' directory.
      Given p_organisation_id is an organization of the 'plonegroup-organization'
      where to query the elements.
    """
    portal = context.portal_url.getPortalObject()
    terms = []
    own_org = get_own_organization()
    if not own_org or organization_id not in own_org:
        return SimpleVocabulary(terms)
    sub = own_org[organization_id]
    sub_path = '/'.join(sub.getPhysicalPath())
    sub_path_len = len(sub_path) + 1
    catalog = portal.portal_catalog
    crit = {'path': {"query": sub_path, 'depth': 10},
            'portal_type': "organization",
            'sort_on': sort_on}
    if states:
        crit['review_state'] = states
    brains = catalog.unrestrictedSearchResults(**crit)
    levels = {}
    for brain in brains:
        path = brain.getPath()[sub_path_len:]
        if not path:
            continue  # organization_id itself
        value = safe_unicode(brain.UID)
        title = safe_unicode(brain.Title)
        level = len(path.split('/'))
        levels[level] = {'id': value, 'title': title}
        if level > 1:
            #value = u'{}-{}'.format(levels[level-1]['id'], value)
            title = u'{} - {}'.format(levels[level-1]['title'], title)
        terms.append(SimpleTerm(value, token=value, title=title))
    return SimpleVocabulary(terms)
Ejemplo n.º 31
0
    def run(self):
        self.data = self.profileData
        if not self.data:
            return self.noDataMessage
        # Register classes again, after model adaptations have been performed
        # (see comment in __init__.py)
        registerClasses()
        # if we already have existing organizations, we do not add additional ones
        own_org = get_own_organization()
        alreadyHaveGroups = bool(own_org.objectValues())
        savedMeetingConfigsToCloneTo = {}
        savedOrgsData = {}
        if not alreadyHaveGroups or self.data.forceAddUsersAndGroups:
            # 1) create organizations so we have org UIDS to initialize 'fct_orgs'
            orgs, active_orgs, savedOrgsData = self.addOrgs(self.data.orgs)
            # 2) create plonegroup functions (suffixes) to create Plone groups
            functions = get_registry_functions()
            function_ids = [function['fct_id'] for function in functions]
            # append new functions
            suffixes = MEETING_GROUP_SUFFIXES + EXTRA_GROUP_SUFFIXES
            for suffix in suffixes:
                if suffix['fct_id'] not in function_ids:
                    copied_suffix = suffix.copy()
                    copied_suffix['fct_title'] = translate(
                        suffix['fct_title'],
                        domain='PloneMeeting',
                        context=self.request)
                    # if org_path not found, do not fail but log, it is often the case in tests
                    # in which we do not add additional organizations because it breaks some tests
                    copied_suffix['fct_orgs'] = []
                    for org_path in suffix['fct_orgs']:
                        try:
                            fct_org = own_org.restrictedTraverse(org_path)
                        except KeyError:
                            logger.warning(
                                "Could not find an organization with path {0} "
                                "while setting 'fct_orgs' for {1}".format(
                                    org_path, suffix['fct_id']))
                            continue
                        copied_suffix['fct_orgs'].append(fct_org.UID())
                    functions.append(copied_suffix)
            # 3) manage organizations, set every organizations so every Plone groups are created
            # then disable orgs that are not active
            invalidate_soev_cache()
            invalidate_ssoev_cache()
            already_active_orgs = get_registry_organizations()
            org_uids = [
                org_uid for org_uid in get_organizations(only_selected=False,
                                                         the_objects=False)
                if org_uid not in already_active_orgs
            ]
            set_registry_organizations(org_uids)
            set_registry_functions(functions)
            active_org_uids = [org.UID() for org in active_orgs]
            set_registry_organizations(already_active_orgs + active_org_uids)
            # 4) add users to Plone groups
            self.addUsers(self.data.orgs)
            # 5) now that organizations are created, we add persons and held_positions
            self.addPersonsAndHeldPositions(self.data.persons,
                                            source=self.profilePath)

        created_cfgs = []
        for mConfig in self.data.meetingConfigs:
            # XXX we need to defer the management of the 'meetingConfigsToCloneTo'
            # defined on the mConfig after the creation of every mConfigs because
            # if we defined in mConfig1.meetingConfigsToCloneTo the mConfig2 id,
            # it will try to getattr this meetingConfig2 id that does not exist yet...
            # so save defined values, removed them from mConfig and manage that after
            savedMeetingConfigsToCloneTo[
                mConfig.id] = mConfig.meetingConfigsToCloneTo
            mConfig.meetingConfigsToCloneTo = []
            cfg = self.createMeetingConfig(mConfig, source=self.profilePath)
            if cfg:
                created_cfgs.append(cfg)
                self._finishConfigFor(cfg, data=mConfig)

        # manage other_mc_correspondences
        for created_cfg in created_cfgs:
            self._manageOtherMCCorrespondences(created_cfg)

        # now that every meetingConfigs have been created, we can manage the meetingConfigsToCloneTo
        # and orgs advice states related fields
        for mConfigId in savedMeetingConfigsToCloneTo:
            if not savedMeetingConfigsToCloneTo[mConfigId]:
                continue
            # initialize the attribute on the meetingConfig and call _updateCloneToOtherMCActions
            cfg = getattr(self.tool, mConfigId)
            # validate the MeetingConfig.meetingConfigsToCloneTo data that we are about to set
            # first replace cfg1 and cfg2 by corresponding cfg id
            adapted_cfgsToCloneTo = deepcopy(
                savedMeetingConfigsToCloneTo[mConfigId])
            for cfgToCloneTo in adapted_cfgsToCloneTo:
                cfgToCloneTo['meeting_config'] = self.cfg_num_to_id(
                    cfgToCloneTo['meeting_config'])
            error = cfg.validate_meetingConfigsToCloneTo(adapted_cfgsToCloneTo)
            if error:
                raise PloneMeetingError(MEETING_CONFIG_ERROR %
                                        (cfg.Title(), cfg.getId(), error))
            cfg.setMeetingConfigsToCloneTo(adapted_cfgsToCloneTo)
            cfg._updateCloneToOtherMCActions()
        for org_uid, values in savedOrgsData.items():
            org = uuidToObject(org_uid, unrestricted=True)
            # turn cfg1__state__itemcreated into meeting-config-id__state__itemcreated
            org.item_advice_states = self._correct_advice_states(
                values['item_advice_states'])
            org.item_advice_edit_states = self._correct_advice_states(
                values['item_advice_edit_states'])
            org.item_advice_view_states = self._correct_advice_states(
                values['item_advice_view_states'])
            org.groups_in_charge = [
                org_id_to_uid(group_id)
                for group_id in values['groups_in_charge']
            ]

        # finally, create the current user (admin) member area
        self.portal.portal_membership.createMemberArea()
        # at the end, add users outside PloneMeeting groups because
        # they could have to be added in groups created by the MeetingConfig
        if not alreadyHaveGroups:
            # adapt userDescr.ploneGroups to turn cfg_num into cfg_id
            self.addUsersOutsideGroups(self.data.usersOutsideGroups)

        # commit before continuing so elements like scales on annex types are correctly saved
        transaction.commit()
        return self.successMessage
Ejemplo n.º 32
0
 def get_own_org(self):
     ''' '''
     return get_own_organization()
Ejemplo n.º 33
0
    def _hook_after_mgroups_to_orgs(self):
        """Migrate attributes that were using MeetingGroups :
           - MeetingConfig.archivingRefs.restrict_to_groups;
           - MeetingCategory.groupsInCharge;
           - MeetingItem.financeAdvice.
           Remove every users from _observers Plone groups.
           Then manage copyGroups and powerObservers at the end."""

        logger.info("Adapting organizations...")
        own_org = get_own_organization()
        own_org_ids = own_org.objectIds()
        for cfg in self.tool.objectValues('MeetingConfig'):
            # MeetingConfig.archivingRefs
            archivingRefs = deepcopy(cfg.getArchivingRefs())
            migratedArchivingRefs = []
            for archivingRef in archivingRefs:
                migratedArchivingRef = archivingRef.copy()
                migratedArchivingRef['restrict_to_groups'] = [
                    org_id_to_uid(mGroupId)
                    for mGroupId in migratedArchivingRef['restrict_to_groups']
                    if mGroupId in own_org_ids]
                migratedArchivingRefs.append(migratedArchivingRef)
            cfg.setArchivingRefs(migratedArchivingRefs)
            # MeetingCategory.groupsInCharge
            for category in cfg.getCategories(onlySelectable=False, caching=False):
                groupsInCharge = category.getGroupsInCharge()
                migratedGroupsInCharge = [org_id_to_uid(mGroupId) for mGroupId in groupsInCharge]
                category.setGroupsInCharge(migratedGroupsInCharge)
        own_org = get_own_organization()
        for brain in self.portal.portal_catalog(meta_type='MeetingItem'):
            item = brain.getObject()
            financeAdvice = item.getFinanceAdvice()
            if financeAdvice != '_none_':
                finance_org_uid = own_org.get(financeAdvice).UID()
                item.setFinanceAdvice(finance_org_uid)

        # remove users from Plone groups ending with _observers
        logger.info('Removing every users from observers groups...')
        pGroups = api.group.get_groups()
        for pGroup in pGroups:
            if pGroup.getId().endswith('_observers'):
                for member_id in pGroup.getMemberIds():
                    api.group.remove_user(group=pGroup, username=member_id)

        # migrate copyGroups :
        # - adapt configuration, use _copygroup instead _observers
        # - adapt copyGroups on every items (including item templates)
        logger.info("Adapting copyGroups...")
        for cfg in self.tool.objectValues('MeetingConfig'):
            selectableCopyGroups = cfg.getSelectableCopyGroups()
            patched_selectableCopyGroups = [
                copyGroup.replace('_observers', '_incopy')
                for copyGroup in selectableCopyGroups]
            cfg.setSelectableCopyGroups(patched_selectableCopyGroups)
        for brain in self.portal.portal_catalog(meta_type='MeetingItem'):
            item = brain.getObject()
            copyGroups = item.getCopyGroups()
            patched_copyGroups = [copyGroup.replace('_observers', '_incopy')
                                  for copyGroup in copyGroups]
            item.setCopyGroups(patched_copyGroups)

        # configure powerobsevers
        logger.info("Adapting powerObservers...")
        for cfg in self.tool.objectValues('MeetingConfig'):
            power_observers = deepcopy(cfg.getPowerObservers())
            if len(power_observers) == 2:
                if cfg.getId() in ['meeting-config-college', 'meeting-config-council']:
                    cfg.setPowerObservers(deepcopy(collegeMeeting.powerObservers))
                elif cfg.getId() in ['meeting-config-bourgmestre']:
                    cfg.setPowerObservers(deepcopy(bourgmestreMeeting.powerObservers))
                cfg._createOrUpdateAllPloneGroups(force_update_access=True)
Ejemplo n.º 34
0
def position_default(data):
    return get_own_organization()
Ejemplo n.º 35
0
    def setUp(self):
        # enable full diff in failing tests
        self.maxDiff = None
        # Define some useful attributes
        self.app = self.layer['app']
        self.portal = self.layer['portal']
        self.request = self.layer['request']
        self.changeUser('admin')
        # setup manually the correct browserlayer, see:
        # https://dev.plone.org/ticket/11673
        notify(BeforeTraverseEvent(self.portal, self.request))
        self.tool = self.portal.portal_plonemeeting
        self.catalog = self.portal.portal_catalog
        self.wfTool = self.portal.portal_workflow
        self.own_org = get_own_organization()
        # make organizations easily available thru their id and store uid
        # for each organization, we will have self.developers, self.developers_uid
        # as well as every plone groups : self.vendors_creators, self.developers_reviewers, ...
        # include organizations outside own_org as well
        orgs = object_values(self.own_org, 'PMOrganization') + \
            object_values(self.own_org.aq_parent, 'PMOrganization')
        for org in orgs:
            setattr(self, org.getId(), org)
            setattr(self, '{0}_uid'.format(org.getId()), org.UID())
            for plone_group_id in get_plone_groups(org.UID(), ids_only=True):
                org_uid, suffix = plone_group_id.split('_')
                setattr(self,
                        '{0}_{1}'.format(org.getId(), suffix),
                        plone_group_id)
        # make held_position easily available as well
        i = 1
        for person in object_values(self.portal.contacts, 'PMPerson'):
            setattr(self,
                    'hp{0}'.format(i),
                    object_values(person, 'PMHeldPosition')[0])
            setattr(self,
                    'hp{0}_uid'.format(i),
                    object_values(person, 'PMHeldPosition')[0].UID())
            i += 1

        self.pmFolder = os.path.dirname(Products.PloneMeeting.__file__)
        # Disable notifications mechanism. This way, the test suite may be
        # executed even on production sites that contain many real users.
        for cfg in self.tool.objectValues('MeetingConfig'):
            cfg.setMailItemEvents([])
            cfg.setMailMeetingEvents([])
        logout()

        # Set the default meeting config
        self.meetingConfig = getattr(self.tool, self.cfg1_id, None)
        self.meetingConfig2 = getattr(self.tool, self.cfg2_id, None)
        # Set the default file and file type for adding annexes
        self.annexFile = u'FILE.txt'
        self.annexFilePDF = u'file_correct.pdf'
        self.annexFileCorruptedPDF = u'file_errorDuringConversion.pdf'
        self.annexFileType = 'financial-analysis'
        self.annexFileTypeDecision = 'decision-annex'
        self.annexFileTypeAdvice = 'advice-annex'
        self.annexFileTypeMeeting = 'meeting-annex'
        # log current test module and method name
        test_num = self._resultForDoCleanups.testsRun
        test_total = self._resultForDoCleanups.count
        pm_logger.info('Executing [{0}/{1}] {2}:{3}'.format(
            test_num, test_total, self.__class__.__name__, self._testMethodName))
Ejemplo n.º 36
0
    if not hasattr(self, 'portal_plonemeeting'):
        return "PloneMeeting must be installed to run this script !"

    file = None
    try:
        file = open(fname, "rb")
        reader = csv.DictReader(file)
    except Exception, msg:
        if file:
            file.close()
        return "Error with file : %s" % msg.value

    out = []

    own_org = get_own_organization()
    for row in reader:
        data = {}
        org_id = row['id'] or normalizeString(row['title'], self)
        if org_id in own_org.objectIds():
            out.append(
                "Organization '%s' already exists and was not created!" %
                org_id)
            continue
        data['title'] = safe_unicode(row['title'])
        data['description'] = safe_unicode(row['description'])
        data['acronym'] = safe_unicode(row['acronym'])
        # make sure these fields are not None
        data['item_advice_states'] = []
        data['item_advice_edit_states'] = []
        data['item_advice_view_states'] = []