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())
 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 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_plonegroupOrganizationRemoved_3(self):
     """ We can remove an organization no more selected in settings and no more used in an object """
     set_registry_organizations([self.contacts[0].UID()
                                 ])  # unselects the contact
     self.portal['acontent2'].pg_organization = None
     self.portal.restrictedTraverse(
         '{0}/{1}/department2/delete_confirmation'.format(
             DEFAULT_DIRECTORY_ID, PLONEGROUP_ORG))
def select_organization(org_uid, remove=False):
    """Select organization in ORGANIZATIONS_REGISTRY."""
    plonegroup_organizations = get_registry_organizations()
    if remove:
        plonegroup_organizations.remove(org_uid)
    else:
        plonegroup_organizations.append(org_uid)
    set_registry_organizations(plonegroup_organizations)
 def test_plonegroup_contact_transition_3(self):
     """ We can deactivate an organization not at all used """
     set_registry_organizations([self.contacts[1].UID()
                                 ])  # unselects the contact
     self.portal['acontent1'].pg_organization = None
     api.content.transition(obj=self.contacts[0], transition='deactivate')
     self.assertEqual(api.content.get_state(obj=self.contacts[0]),
                      'deactivated')
 def test_plonegroup_contact_transition_2(self):
     """ We cannot deactivate an organization used in objects """
     set_registry_organizations([self.contacts[1].UID()
                                 ])  # unselects the contact
     self.assertRaises(Redirect,
                       api.content.transition,
                       obj=self.contacts[0],
                       transition='deactivate')
     self.assertEqual(api.content.get_state(obj=self.contacts[0]), 'active')
 def test_plonegroupOrganizationRemoved_2(self):
     """ We cannot remove an organization no more selected in settings and used in an object """
     set_registry_organizations([self.contacts[0].UID()])  # unselects the contact
     view = self.portal.restrictedTraverse(
         '{0}/{1}/department2/delete_confirmation'.format(DEFAULT_DIRECTORY_ID, PLONEGROUP_ORG))
     self.assertRaises(LinkIntegrityNotificationException, view.render)
     storage = ILinkIntegrityInfo(view.REQUEST)
     breaches = storage.getIntegrityBreaches()
     self.assertIn(self.contacts[1], breaches)
     self.assertSetEqual(breaches[self.contacts[1]], set([self.portal['acontent2']]))
Ejemplo n.º 9
0
 def test_contact_plonegroup_change(self):
     e_groups = [('%s_encodeur' % uid, ('Contributor', ))
                 for uid in get_registry_organizations()]
     e_groups.append(('admin', ('Owner', )))
     e_groups.append(('expedition', ('Contributor', )))
     e_groups.append(('dir_general', ('Contributor', )))
     self.assertSetEqual(set(self.omf.get_local_roles()), set(e_groups))
     self.assertEqual(len(self.omf.get_local_roles()), 14)
     set_registry_organizations(get_registry_organizations()[:3])
     self.assertEqual(len(self.omf.get_local_roles()), 6)
 def test_plonegroupOrganizationRemoved_2(self):
     """ We cannot remove an organization no more selected in settings and used in an object """
     set_registry_organizations([self.contacts[0].UID()
                                 ])  # unselects the contact
     view = self.portal.restrictedTraverse(
         '{0}/{1}/department2/delete_confirmation'.format(
             DEFAULT_DIRECTORY_ID, PLONEGROUP_ORG))
     self.assertRaises(LinkIntegrityNotificationException, view.render)
     storage = ILinkIntegrityInfo(view.REQUEST)
     breaches = storage.getIntegrityBreaches()
     self.assertIn(self.contacts[1], breaches)
     self.assertSetEqual(breaches[self.contacts[1]],
                         set([self.portal['acontent2']]))
Ejemplo n.º 11
0
 def test_user_related_modification(self):
     voc_inst = AssignedUsersWithDeactivatedVocabulary()
     voc_list = [(t.value, t.title) for t in voc_inst(self.imail)]
     self.assertListEqual(voc_list,
                          [('__empty_string__', u'Empty value'),
                           ('agent', u'Fred Agent'),
                           ('encodeur', u'Jean Encodeur'),
                           ('lecteur', u'Jef Lecteur'),
                           ('dirg', u'Maxime DG'), ('chef', u'Michel Chef'),
                           ('scanner', u'Scanner'),
                           ('agent1', u'Stef Agent'),
                           ('test-user', u'test-user (Désactivé)')])
     # we change a user property
     member = api.user.get(userid='chef')
     member.setMemberProperties({'fullname': 'Michel Chef 2'})
     # we simulate the user form change event
     zope.event.notify(
         ConfigurationChangedEvent(
             UserDataConfiglet(self.portal, self.portal.REQUEST), {}))
     voc_list = [(t.value, t.title) for t in voc_inst(self.imail)]
     self.assertListEqual(voc_list,
                          [('__empty_string__', u'Empty value'),
                           ('agent', u'Fred Agent'),
                           ('encodeur', u'Jean Encodeur'),
                           ('lecteur', u'Jef Lecteur'),
                           ('dirg', u'Maxime DG'),
                           ('chef', u'Michel Chef 2'),
                           ('scanner', u'Scanner'),
                           ('agent1', u'Stef Agent'),
                           ('test-user', u'test-user (Désactivé)')])
     # we change the activated services
     set_registry_organizations(
         get_registry_organizations()[0:1])  # only keep Direction générale
     api.group.remove_user(
         groupname='createurs_dossier',
         username='******')  # remove agent from global group
     voc_list = [(t.value, t.title) for t in voc_inst(self.imail)]
     self.assertListEqual(voc_list,
                          [('__empty_string__', u'Empty value'),
                           ('encodeur', u'Jean Encodeur'),
                           ('dirg', u'Maxime DG'),
                           ('chef', u'Michel Chef 2'),
                           ('scanner', u'Scanner'),
                           ('agent', u'Fred Agent (Désactivé)'),
                           ('lecteur', u'Jef Lecteur (Désactivé)'),
                           ('agent1', u'Stef Agent (Désactivé)'),
                           ('test-user', u'test-user (Désactivé)')])
     # wrong configuration change
     zope.event.notify(ConfigurationChangedEvent(self.portal, {}))
 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_SelectedOrganizationsElephantVocabulary(self):
     """ Test 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.selected_organization_services")
     vocab_wrp = factory_wrp(self.portal)
     self.assertEqual(len(vocab_wrp), 3)
     # values are sorted by title
     self.assertListEqual(sorted([v.value for v in vocab_wrp]), sorted(get_registry_organizations()))
     self.assertListEqual([v.title for v in vocab_wrp], ['Department 1', 'Department 2'])
     self.assertEqual(vocab_wrp.getTerm(vocab_all_values[1]).title, 'Department 1 - Service 1')
 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
         },
     ])
Ejemplo n.º 15
0
 def test_group_deleted(self):
     request = self.portal.REQUEST
     # protected group
     self.assertRaises(Redirect, api.group.delete, groupname='expedition')
     smi = IStatusMessage(request)
     msgs = smi.show()
     self.assertEqual(msgs[0].message,
                      u"You cannot delete the group 'expedition'.")
     # is used in content
     group = '%s_editeur' % get_registry_organizations()[0]
     # we remove this organization to escape plonegroup subscriber
     set_registry_organizations(get_registry_organizations()[1:])
     self.assertRaises(Redirect, api.group.delete, groupname=group)
     msgs = smi.show()
     self.assertEqual(
         msgs[0].message,
         u"You cannot delete the group '%s', used in 'Assigned group' index."
         % group)
    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': []}])
Ejemplo n.º 18
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)
 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.º 20
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.º 21
0
def clean_examples(self, doit='1'):
    """ Clean created examples """
    if not check_zope_admin():
        return "You must be a zope manager to run this script"
    if doit == '1':
        doit = True
    else:
        doit = False
    out = []
    portal = api.portal.getSite()
    if doit:
        portal.portal_properties.site_properties.enable_link_integrity_checks = False
    registry = getUtility(IRegistry)

    # Delete om
    brains = find(unrestricted=True, portal_type='dmsoutgoingmail')
    for brain in brains:
        log_list(out, "Deleting om '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    if doit:
        registry['collective.dms.mailcontent.browser.settings.IDmsMailConfig.outgoingmail_number'] = 1
    # Create test om
    params = {'title': u'Courrier test pour création de modèles (ne pas effacer)',
              'internal_reference_no': internalReferenceOutgoingMailDefaultValue(DummyView(portal, portal.REQUEST)),
              'mail_date': date.today(),
              'mail_type': 'type1',
              }
    if doit:
        sub_create(portal['outgoing-mail'], 'dmsoutgoingmail', datetime.now(), 'test_creation_modele', **params)

    # Delete im
    brains = find(unrestricted=True, portal_type=['dmsincomingmail', 'dmsincoming_email'])
    for brain in brains:
        log_list(out, "Deleting im '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    if doit:
        registry['collective.dms.mailcontent.browser.settings.IDmsMailConfig.incomingmail_number'] = 1
    # Delete own personnel
    pf = portal['contacts']['personnel-folder']
    brains = find(unrestricted=True, context=pf, portal_type='person')
    for brain in brains:
        log_list(out, "Deleting person '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    # Deactivate own organizations
    ownorg = portal['contacts']['plonegroup-organization']
    brains = find(unrestricted=True, context=ownorg, portal_type='organization',
                  id=['plonegroup-organization', 'college-communal'])
    kept_orgs = [brain.UID for brain in brains]
    log_list(out, "Activating only 'college-communal'")
    if doit:
        set_registry_organizations([ownorg['college-communal'].UID()])
    # Delete organization and template folders
    tmpl_folder = portal['templates']['om']
    brains = find(unrestricted=True, context=ownorg, portal_type='organization', sort_on='path',
                  sort_order='descending')
    for brain in brains:
        uid = brain.UID
        if uid in kept_orgs:
            continue
        log_list(out, "Deleting organization '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
        if uid in tmpl_folder:
            log_list(out, "Deleting template folder '%s'" % '/'.join(tmpl_folder[uid].getPhysicalPath()))
            if doit:
                api.content.delete(obj=tmpl_folder[uid])
    # Delete contacts
    brains = find(unrestricted=True, context=portal['contacts'], portal_type='contact_list')
    for brain in brains:
        log_list(out, "Deleting contact list '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    brains = find(unrestricted=True, context=portal['contacts'], portal_type='person',
                  id=['jeancourant', 'sergerobinet', 'bernardlermitte'])
    for brain in brains:
        log_list(out, "Deleting person '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    brains = find(unrestricted=True, context=portal['contacts'], portal_type='organization', id=['electrabel', 'swde'])
    for brain in brains:
        log_list(out, "Deleting organization '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
    # Delete users
    for userid in ['encodeur', 'dirg', 'chef', 'agent', 'agent1', 'lecteur']:
        user = api.user.get(userid=userid)
        for brain in find(unrestricted=True, Creator=userid, sort_on='path', sort_order='descending'):
            log_list(out, "Deleting object '%s' created by '%s'" % (brain.getPath(), userid))
            if doit:
                api.content.delete(obj=brain._unrestrictedGetObject(), check_linkintegrity=False)
        for group in api.group.get_groups(user=user):
            if group.id == 'AuthenticatedUsers':
                continue
            log_list(out, "Removing user '%s' from group '%s'" % (userid, group.getProperty('title')))
            if doit:
                api.group.remove_user(group=group, user=user)
        log_list(out, "Deleting user '%s'" % userid)
        if doit:
            api.user.delete(user=user)
    # Delete groups
    functions = [dic['fct_id'] for dic in get_registry_functions()]
    groups = api.group.get_groups()
    for group in groups:
        if '_' not in group.id or group.id in ['createurs_dossier', 'dir_general', 'lecteurs_globaux_ce',
                                               'lecteurs_globaux_cs']:
            continue
        parts = group.id.split('_')
        if len(parts) == 1:
            continue
        org_uid = parts[0]
        function = '_'.join(parts[1:])
        if org_uid in kept_orgs or function not in functions:
            continue
        log_list(out, "Deleting group '%s'" % group.getProperty('title'))
        if doit:
            api.group.delete(group=group)
    # Delete folders
    for brain in find(unrestricted=True, portal_type=('ClassificationFolder', 'ClassificationSubfolder'),
                      sort_on='path', sort_order='descending'):
        log_list(out, "Deleting classification folder '%s'" % brain.getPath())
        if doit:
            api.content.delete(obj=brain._unrestrictedGetObject())
    # Delete categories
    caching.invalidate_cache("collective.classification.tree.utils.iterate_over_tree", portal['tree'].UID())
    res = iterate_over_tree(portal['tree'])
    for category in reversed(res):
        log_list(out, "Deleting category '%s - %s'" % (safe_encode(category.identifier), safe_encode(category.title)))
        if doit:
            api.content.delete(obj=category)
    if doit:
        caching.invalidate_cache("collective.classification.tree.utils.iterate_over_tree", portal['tree'].UID())
        portal.portal_properties.site_properties.enable_link_integrity_checks = True
    return '\n'.join(out)
 def test_plonegroupOrganizationRemoved_3(self):
     """ We can remove an organization no more selected in settings and no more used in an object """
     set_registry_organizations([self.contacts[0].UID()])  # unselects the contact
     self.portal['acontent2'].pg_organization = None
     self.portal.restrictedTraverse(
         '{0}/{1}/department2/delete_confirmation'.format(DEFAULT_DIRECTORY_ID, PLONEGROUP_ORG))
 def test_plonegroup_contact_transition_3(self):
     """ We can deactivate an organization not at all used """
     set_registry_organizations([self.contacts[1].UID()])  # unselects the contact
     self.portal['acontent1'].pg_organization = None
     api.content.transition(obj=self.contacts[0], transition='deactivate')
     self.assertEqual(api.content.get_state(obj=self.contacts[0]), 'deactivated')
 def test_plonegroup_contact_transition_2(self):
     """ We cannot deactivate an organization used in objects """
     set_registry_organizations([self.contacts[1].UID()])  # unselects the contact
     self.assertRaises(Redirect, api.content.transition, obj=self.contacts[0], transition='deactivate')
     self.assertEqual(api.content.get_state(obj=self.contacts[0]), 'active')