示例#1
0
    def populate(self):
        Report = get_report_model()

        HeaderFilter.create(
            pk=constants.DEFAULT_HFILTER_REPORT,
            name=_('Report view'),
            model=Report,
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
                (EntityCellRegularField, {
                    'name': 'ct'
                }),
            ],
        )

        # ---------------------------
        SearchConfigItem.create_if_needed(Report, ['name'])

        # ---------------------------
        # NB: no straightforward way to test that this populate script has not been already run
        if not BrickDetailviewLocation.objects.filter_for_model(
                Report).exists():
            create_bdl = partial(
                BrickDetailviewLocation.objects.create_if_needed, model=Report)
            LEFT = BrickDetailviewLocation.LEFT
            RIGHT = BrickDetailviewLocation.RIGHT

            BrickDetailviewLocation.objects.create_for_model_brick(
                order=5, zone=LEFT, model=Report)
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT)
            create_bdl(brick=bricks.ReportFieldsBrick, order=50, zone=LEFT)
            create_bdl(brick=bricks.ReportGraphsBrick, order=60, zone=LEFT)
            create_bdl(brick=core_bricks.PropertiesBrick, order=450, zone=LEFT)
            create_bdl(brick=core_bricks.RelationsBrick, order=500, zone=LEFT)
            create_bdl(brick=core_bricks.HistoryBrick, order=20, zone=RIGHT)

            if apps.is_installed('creme.assistants'):
                logger.info(
                    'Assistants app is installed => we use the assistants blocks on detail view'
                )

                from creme.assistants import bricks as a_bricks

                create_bdl(brick=a_bricks.TodosBrick, order=100, zone=RIGHT)
                create_bdl(brick=a_bricks.MemosBrick, order=200, zone=RIGHT)
                create_bdl(brick=a_bricks.AlertsBrick, order=300, zone=RIGHT)
                create_bdl(brick=a_bricks.UserMessagesBrick,
                           order=400,
                           zone=RIGHT)

            if apps.is_installed('creme.documents'):
                # logger.info('Documents app is installed => we use the documents block on detail views')

                from creme.documents.bricks import LinkedDocsBrick

                create_bdl(brick=LinkedDocsBrick, order=600, zone=RIGHT)
示例#2
0
 def _setup_contacts(self, disabled=False, user=None):
     SearchConfigItem.create_if_needed(
         FakeContact,
         ['first_name', 'last_name', 'sector__title'],
         disabled=disabled,
     )
     self._build_contacts(user)
示例#3
0
    def test_search08(self):
        "Use Role's config if it exists"
        self.login(is_superuser=False, allowed_apps=['creme_core'])

        SearchConfigItem.create_if_needed(FakeContact, ['description'], role=self.role)
        self._setup_contacts()

        response = self._search('bear', self.contact_ct_id)
        self.assertEqual(200, response.status_code)

        self.assertNotContains(response, self.linus.get_absolute_url())
        self.assertNotContains(response, self.linus2.get_absolute_url())
        self.assertContains(response, self.alan.get_absolute_url())
示例#4
0
    def test_add04(self):
        "Unique configuration (super-user)"
        ct = self.ct_contact
        SearchConfigItem.create_if_needed(FakeContact, role='superuser',
                                          fields=['first_name', 'last_name'],
                                         )

        response = self.assertGET200(self._build_add_url(ct))

        with self.assertNoException():
            role_f = response.context['form'].fields['role']

        self.assertIsNone(role_f.empty_label)
示例#5
0
    def test_search09(self):
        "Use Role's config if it exists (super-user)"
        self.login()

        SearchConfigItem.create_if_needed(FakeContact, ['description'], role='superuser')
        self._setup_contacts()

        response = self._search('bear', self.contact_ct_id)
        self.assertEqual(200, response.status_code)

        self.assertNotContains(response, self.linus.get_absolute_url())
        self.assertNotContains(response, self.linus2.get_absolute_url())
        self.assertContains(response, self.alan.get_absolute_url())
示例#6
0
    def test_search10(self):
        "With FieldsConfig"
        user = self.login()

        hidden_fname1 = 'description'
        hidden_fname2 = 'sector'
        SearchConfigItem.create_if_needed(
            FakeContact,
            [
                'first_name',
                'last_name',
                hidden_fname1,
                hidden_fname2 + '__title',
            ],
        )

        sector = FakeSector.objects.create(title='Linux dev')

        create_contact = partial(FakeContact.objects.create, user=user)
        linus = create_contact(first_name='Linus',
                               last_name='Torvalds',
                               description="Alan's friend")
        alan = create_contact(first_name='Alan',
                              last_name='Cox',
                              description="Linus' friend")
        andrew = create_contact(first_name='Andrew',
                                last_name='Morton',
                                sector=sector)

        FieldsConfig.create(FakeContact,
                            descriptions=[
                                (hidden_fname1, {
                                    FieldsConfig.HIDDEN: True
                                }),
                                (hidden_fname2, {
                                    FieldsConfig.HIDDEN: True
                                }),
                            ])

        response = self._search('Linu', self.contact_ct_id)
        self.assertEqual(200, response.status_code)

        self.assertContains(response, linus.get_absolute_url())
        self.assertNotContains(response, alan.get_absolute_url())
        self.assertNotContains(response, andrew.get_absolute_url())

        self.assertContains(response, _('First name'))
        self.assertContains(response, _('Last name'))
        self.assertNotContains(response, _('Description'))
        self.assertNotContains(response, _('Sector'))
示例#7
0
 def test_delete03(self):
     "Cannot delete the default configuration"
     sci = SearchConfigItem.create_if_needed(FakeContact,
                                             ['first_name', 'last_name'])
     self.assertPOST409(reverse('creme_config__delete_search_config'),
                        data={'id': sci.id})
     self.assertStillExists(sci)
示例#8
0
    def test_edit07(self):
        "With FieldsConfig + selected hidden fields"
        model = FakeContact
        hidden_fname1 = 'description'
        hidden_fname2 = 'position'
        hidden_sub_fname2 = hidden_fname2 + '__title'
        sci = SearchConfigItem.create_if_needed(model,
                                                fields=[
                                                    'first_name',
                                                    hidden_fname1,
                                                    hidden_sub_fname2,
                                                ])

        FieldsConfig.create(model,
                            descriptions=[
                                (hidden_fname1, {
                                    FieldsConfig.HIDDEN: True
                                }),
                                (hidden_fname2, {
                                    FieldsConfig.HIDDEN: True
                                }),
                            ])

        response = self.assertGET200(self._build_edit_url(sci))

        with self.assertNoException():
            fields_f = response.context['form'].fields['fields']

        self.assertEqual(['first_name', hidden_fname1, hidden_sub_fname2],
                         fields_f.initial)

        self._find_field_index(fields_f, 'first_name')
        self._find_field_index(fields_f, hidden_fname1)
        self._find_field_index(fields_f, hidden_sub_fname2)
示例#9
0
    def test_edit06(self):
        "With FieldsConfig"
        model = FakeContact
        hidden_fname1 = 'description'
        hidden_fname2 = 'position'
        FieldsConfig.create(model,
                            descriptions=[
                                (hidden_fname1, {
                                    FieldsConfig.HIDDEN: True
                                }),
                                (hidden_fname2, {
                                    FieldsConfig.HIDDEN: True
                                }),
                            ])
        sci = SearchConfigItem.create_if_needed(model, fields=['first_name'])

        response = self.assertGET200(self._build_edit_url(sci))

        with self.assertNoException():
            fields_f = response.context['form'].fields['fields']

        self.assertEqual(['first_name'], fields_f.initial)

        self._find_field_index(fields_f, 'first_name')
        self._find_field_index(fields_f, 'civility__title')

        self._assertNotInChoices(fields_f, hidden_fname1)
        self._assertNotInChoices(fields_f, 'position__title')
示例#10
0
    def test_edit01(self):
        sci = SearchConfigItem.create_if_needed(FakeContact,
                                                fields=['last_name'])
        self.assertIsNone(sci.role)

        url = self._build_edit_url(sci)
        response = self.assertGET200(url)
        # self.assertTemplateUsed(response, 'creme_core/generics/blockform/edit_popup.html')
        self.assertTemplateUsed(
            response, 'creme_core/generics/blockform/edit-popup.html')

        context = response.context
        self.assertEqual(
            _('Edit «{object}»').format(object=sci), context.get('title'))

        with self.assertNoException():
            fields = context['form'].fields['fields']

        self.assertEqual(['last_name'], fields.initial)

        fname1 = 'last_name'
        index1 = self._find_field_index(fields, fname1)

        fname2 = 'first_name'
        index2 = self._find_field_index(fields, fname2)

        self._find_field_index(fields, 'civility__title')
        self.assertNoChoice(fields, 'birthday')

        sci = self._edit_config(url, sci, ((fname1, index1), (fname2, index2)))
        self.assertFalse(sci.disabled)
示例#11
0
 def test_delete02(self):
     "Super users"
     sci = SearchConfigItem.create_if_needed(FakeContact, role='superuser',
                                             fields=['first_name', 'last_name'],
                                             )
     self.assertPOST200(reverse('creme_config__delete_search_config'), data={'id': sci.id})
     self.assertDoesNotExist(sci)
示例#12
0
    def test_create_if_needed05(self):
        "Invalid fields : no subfield"
        sc_item = SearchConfigItem.create_if_needed(
            FakeContact, ['last_name__invalid', 'first_name'])

        sfields = sc_item.searchfields
        self.assertEqual(1, len(sfields))
        self.assertEqual('first_name', sfields[0].name)
示例#13
0
    def test_create_if_needed06(self):
        "Disabled"
        self.login()

        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation, [],
                                                    disabled=True)
        self.assertTrue(sc_item.disabled)
        self.assertFalse(sc_item.field_names)
示例#14
0
    def test_searchfields_setter03(self):
        "Invalid fields"
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation,
                                                    ['name', 'phone'])

        sc_item.searchfields = ['invalid']
        sc_item.save()
        self.assertIsNone(self.refresh(sc_item).field_names)
示例#15
0
 def test_searchfields_setter04(self):
     "Fields + disabled"
     sc_item = SearchConfigItem.create_if_needed(
         FakeOrganisation,
         ['name', 'phone'],
         disabled=True,
     )
     self.assertEqual(['name', 'phone'],
                      [sf.name for sf in sc_item.searchfields])
示例#16
0
    def test_allfields01(self):
        "True"
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation, [])
        self.assertTrue(sc_item.all_fields)

        sfields = {sf.name for sf in sc_item.searchfields}
        self.assertIn('name', sfields)
        self.assertIn('address__city', sfields)
        self.assertNotIn('creation_date', sfields)
示例#17
0
    def test_get_4_models03(self):
        "One model, 1 config in DB"
        user = self.login()

        sc_item = SearchConfigItem.create_if_needed(
            FakeContact, ['first_name', 'last_name'])

        configs = list(SearchConfigItem.get_4_models([FakeContact], user))
        self.assertEqual(1, len(configs))
        self.assertEqual(sc_item, configs[0])
示例#18
0
    def test_create_if_needed01(self):
        # self.assertEqual(0, SearchConfigItem.objects.count())
        count = SearchConfigItem.objects.count()
        ct = ContentType.objects.get_for_model(FakeContact)
        self.assertFalse(SearchConfigItem.objects.filter(content_type=ct))

        SearchConfigItem.create_if_needed(FakeContact,
                                          ['first_name', 'last_name'])
        # sc_items = SearchConfigItem.objects.all()
        self.assertEqual(count + 1, SearchConfigItem.objects.count())

        sc_items = SearchConfigItem.objects.filter(content_type=ct)
        self.assertEqual(1, len(sc_items))

        sc_item = sc_items[0]
        self.assertEqual(FakeContact, sc_item.content_type.model_class())
        self.assertIsNone(sc_item.role)
        self.assertIs(sc_item.superuser, False)
        self.assertEqual('first_name,last_name', sc_item.field_names)
        self.assertIs(sc_item.all_fields, False)
        self.assertIs(sc_item.disabled, False)

        sfields = sc_item.searchfields
        self.assertEqual(2, len(sfields))

        fn_field = sfields[0]
        self.assertEqual('first_name', fn_field.name)
        self.assertEqual(_('First name'), fn_field.verbose_name)
        self.assertEqual(_('First name'), str(fn_field))

        ln_field = sfields[1]
        self.assertEqual('last_name', ln_field.name)
        self.assertEqual(_('Last name'), ln_field.verbose_name)
        self.assertEqual(_('Last name'), str(ln_field))

        self.assertEqual(
            _('Default search configuration for «{model}»').format(
                model='Test Contact'), str(sc_item))

        SearchConfigItem.create_if_needed(FakeContact,
                                          ['first_name', 'last_name'])
        self.assertEqual(count + 1, SearchConfigItem.objects.count())
示例#19
0
    def test_search15(self):
        "Grouped words."
        self.login()

        SearchConfigItem.create_if_needed(FakeOrganisation, ['name'])

        create_orga = partial(FakeOrganisation.objects.create, user=self.user)
        orga1 = create_orga(name='Foobar Foundation')
        orga2 = create_orga(name='Foobar Mega Foundation')
        orga3 = create_orga(name='Mega Foobar Foundation')

        response = self._search(
            '"Foobar Foundation"',
            ct_id=ContentType.objects.get_for_model(FakeOrganisation).id,
        )
        self.assertEqual(200, response.status_code)

        self.assertContains(response, orga1.get_absolute_url())
        self.assertContains(response, orga3.get_absolute_url())
        self.assertNotContains(response, orga2.get_absolute_url())
示例#20
0
    def test_search11(self):
        "With FieldsConfig: all fields are hidden"
        self.login()

        hidden_fname = 'description'
        SearchConfigItem.create_if_needed(FakeContact, [hidden_fname])
        FieldsConfig.create(FakeContact,
                            descriptions=[(hidden_fname, {FieldsConfig.HIDDEN: True})]
                           )
        self._build_contacts()

        response = self._search('Cool', self.contact_ct_id)
        self.assertEqual(200, response.status_code)

        self.assertNotContains(response, self.linus.get_absolute_url())
        self.assertNotContains(response, self.alan.get_absolute_url())
        self.assertNotContains(response, self.andrew.get_absolute_url())

        self.assertContains(response,
                            _('It seems that all fields are hidden. Ask your administrator to fix the configuration.')
                           )
示例#21
0
    def populate(self):
        RecurrentGenerator = get_rgenerator_model()

        HeaderFilter.create(
            pk=constants.DEFAULT_HFILTER_RGENERATOR,
            model=RecurrentGenerator,
            name=_('Generator view'),
            cells_desc=[(EntityCellRegularField, {
                'name': 'name'
            })],
        )

        SearchConfigItem.create_if_needed(RecurrentGenerator,
                                          ['name', 'description'])

        Job.objects.get_or_create(
            type_id=recurrents_gendocs_type.id,
            defaults={
                'language': settings.LANGUAGE_CODE,
                'status': Job.STATUS_OK,
            },
        )
示例#22
0
    def test_searchfields_setter02(self):
        "No fields"
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation,
                                                    ['name', 'phone'])

        sc_item.searchfields = []
        sc_item.save()
        self.assertIsNone(self.refresh(sc_item).field_names)
        self.assertTrue(sc_item.all_fields)

        sc_item.searchfields = ['name']
        self.assertEqual(['name'], [sf.name for sf in sc_item.searchfields])
        self.assertFalse(sc_item.all_fields)
示例#23
0
    def test_searchfields01(self):
        "Invalid field are deleted automatically"
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation,
                                                    ['name', 'phone'])

        sc_item.field_names += ',invalid'
        sc_item.save()

        sc_item = self.refresh(sc_item)  # No cache any more

        self.assertEqual(['name', 'phone'],
                         [sf.name for sf in sc_item.searchfields])
        self.assertEqual('name,phone', sc_item.field_names)
示例#24
0
    def test_create_if_needed03(self):
        "For super users"
        self.login()

        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation, ['name'],
                                                    role='superuser')

        self.assertEqual(FakeOrganisation, sc_item.content_type.model_class())
        self.assertIsNone(sc_item.role)
        self.assertTrue(sc_item.superuser)

        self.assertEqual(
            _('Search configuration of super-users for «{model}»').format(
                model='Test Organisation'), str(sc_item))
示例#25
0
    def test_searchfields02(self):
        "Invalid field are deleted automatically => if no more valid field, all are used"
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation,
                                                    ['name', 'phone'])
        sc_item.field_names = 'invalid01,invalid02'
        sc_item.save()

        sc_item = self.refresh(sc_item)  # No cache anymore

        sfields = {sf.name for sf in sc_item.searchfields}
        self.assertIn('name', sfields)
        self.assertIn('capital', sfields)
        self.assertNotIn('created', sfields)

        self.assertTrue(sc_item.all_fields)
        self.assertIsNone(sc_item.field_names)
示例#26
0
    def test_create_if_needed02(self):
        "With a role"
        self.login()
        count = SearchConfigItem.objects.count()

        role = self.role
        sc_item = SearchConfigItem.create_if_needed(FakeOrganisation, ['name'],
                                                    role=role)
        self.assertIsInstance(sc_item, SearchConfigItem)

        self.assertEqual(count + 1, SearchConfigItem.objects.count())

        self.assertEqual(FakeOrganisation, sc_item.content_type.model_class())
        self.assertEqual(role, sc_item.role)
        self.assertFalse(sc_item.superuser)

        self.assertEqual(
            _('Search configuration of «{role}» for «{model}»').format(
                role=role,
                model='Test Organisation',
            ), str(sc_item))
示例#27
0
    def _setup_orgas(self):
        SearchConfigItem.create_if_needed(FakeOrganisation, ['name'])

        create_orga = partial(FakeOrganisation.objects.create, user=self.user)
        self.linusfo = create_orga(name='FoobarLinusFoundation')
        self.coxco   = create_orga(name='StuffCoxCorp')
示例#28
0
 def test_allfields02(self):
     "False"
     sc_item = SearchConfigItem.create_if_needed(FakeOrganisation,
                                                 ['name', 'phone'])
     self.assertFalse(sc_item.all_fields)
示例#29
0
    def populate(self):
        already_populated = RelationType.objects.filter(
            pk=constants.REL_SUB_LINKED_2_ACTIVITY).exists()

        Contact = persons.get_contact_model()
        Organisation = persons.get_organisation_model()

        Activity = get_activity_model()

        # ---------------------------
        create_rtype = RelationType.create
        create_rtype(
            (constants.REL_SUB_LINKED_2_ACTIVITY,
             _('related to the activity')),
            (constants.REL_OBJ_LINKED_2_ACTIVITY, _('(activity) related to'),
             [Activity]),
            minimal_display=(True, False),
        )
        rt_obj_activity_subject = create_rtype(
            (constants.REL_SUB_ACTIVITY_SUBJECT,
             _('is subject of the activity'), [Contact, Organisation]),
            (constants.REL_OBJ_ACTIVITY_SUBJECT,
             _('(activity) has for subject'), [Activity]),
            minimal_display=(True, False),
        )[1]
        rt_obj_part_2_activity = create_rtype(
            (constants.REL_SUB_PART_2_ACTIVITY,
             _('participates to the activity'), [Contact]),
            (constants.REL_OBJ_PART_2_ACTIVITY,
             _('(activity) has as participant'), [Activity]),
            is_internal=True,
            minimal_display=(True, False),
        )[1]

        # ---------------------------
        create_if_needed(Status, {'pk': constants.STATUS_PLANNED},
                         name=pgettext('activities-status', 'Planned'),
                         description=pgettext('activities-status', 'Planned'),
                         is_custom=False)
        create_if_needed(Status, {'pk': constants.STATUS_IN_PROGRESS},
                         name=pgettext('activities-status', 'In progress'),
                         description=pgettext('activities-status',
                                              'In progress'),
                         is_custom=False)
        create_if_needed(Status, {'pk': constants.STATUS_DONE},
                         name=pgettext('activities-status', 'Done'),
                         description=pgettext('activities-status', 'Done'),
                         is_custom=False)
        create_if_needed(Status, {'pk': constants.STATUS_DELAYED},
                         name=pgettext('activities-status', 'Delayed'),
                         description=pgettext('activities-status', 'Delayed'),
                         is_custom=False)
        create_if_needed(Status, {'pk': constants.STATUS_CANCELLED},
                         name=pgettext('activities-status', 'Cancelled'),
                         description=pgettext('activities-status',
                                              'Cancelled'),
                         is_custom=False)

        # ---------------------------
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_TASK},
                         name=_('Task'),
                         default_day_duration=0,
                         default_hour_duration="00:15:00",
                         is_custom=False)
        meeting_type = \
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_MEETING},   name=_('Meeting'),        default_day_duration=0, default_hour_duration="00:15:00", is_custom=False)
        phone_call_type = \
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_PHONECALL}, name=_('Phone call'),     default_day_duration=0, default_hour_duration="00:15:00", is_custom=False)
        create_if_needed(ActivityType,
                         {'pk': constants.ACTIVITYTYPE_GATHERING},
                         name=_('Gathering'),
                         default_day_duration=0,
                         default_hour_duration="00:15:00",
                         is_custom=False)
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_SHOW},
                         name=_('Show'),
                         default_day_duration=1,
                         default_hour_duration="00:00:00",
                         is_custom=False)
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_DEMO},
                         name=_('Demonstration'),
                         default_day_duration=0,
                         default_hour_duration="01:00:00",
                         is_custom=False)
        create_if_needed(ActivityType, {'pk': constants.ACTIVITYTYPE_INDISPO},
                         name=_('Unavailability'),
                         default_day_duration=1,
                         default_hour_duration="00:00:00",
                         is_custom=False)

        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_MEETING_MEETING},
                         name=_('Meeting'),
                         type=meeting_type,
                         is_custom=False)
        create_if_needed(
            ActivitySubType,
            {'pk': constants.ACTIVITYSUBTYPE_MEETING_QUALIFICATION},
            name=_('Qualification'),
            type=meeting_type,
            is_custom=False)
        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_MEETING_REVIVAL},
                         name=_('Revival'),
                         type=meeting_type,
                         is_custom=False)
        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_MEETING_NETWORK},
                         name=_('Network'),
                         type=meeting_type,
                         is_custom=False)
        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_MEETING_OTHER},
                         name=pgettext('activities-meeting', 'Other'),
                         type=meeting_type,
                         is_custom=False)

        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_PHONECALL_INCOMING},
                         name=_('Incoming'),
                         type=phone_call_type,
                         is_custom=False)
        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_PHONECALL_OUTGOING},
                         name=_('Outgoing'),
                         type=phone_call_type,
                         is_custom=False)
        create_if_needed(
            ActivitySubType,
            {'pk': constants.ACTIVITYSUBTYPE_PHONECALL_CONFERENCE},
            name=_('Conference'),
            type=phone_call_type,
            is_custom=False)
        create_if_needed(ActivitySubType,
                         {'pk': constants.ACTIVITYSUBTYPE_PHONECALL_FAILED},
                         name=_('Outgoing - Failed'),
                         type=phone_call_type,
                         is_custom=False)

        # ---------------------------
        HeaderFilter.create(
            pk=constants.DEFAULT_HFILTER_ACTIVITY,
            name=_('Activity view'),
            model=Activity,
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'start'
                }),
                (EntityCellRegularField, {
                    'name': 'title'
                }),
                (EntityCellRegularField, {
                    'name': 'type'
                }),
                EntityCellRelation(model=Activity,
                                   rtype=rt_obj_part_2_activity),
                EntityCellRelation(model=Activity,
                                   rtype=rt_obj_activity_subject),
                (EntityCellRegularField, {
                    'name': 'user'
                }),
                (EntityCellRegularField, {
                    'name': 'end'
                }),
            ],
        )

        # ---------------------------
        create_efilter = EntityFilter.create

        for pk, name, atype_id in (
            (constants.EFILTER_MEETINGS, _('Meetings'),
             constants.ACTIVITYTYPE_MEETING),
            (constants.EFILTER_PHONECALLS, _('Phone calls'),
             constants.ACTIVITYTYPE_PHONECALL),
            (constants.EFILTER_TASKS, _('Tasks'), constants.ACTIVITYTYPE_TASK),
        ):
            create_efilter(
                pk,
                name=name,
                model=Activity,
                is_custom=False,
                user='******',
                conditions=[
                    # EntityFilterCondition.build_4_field(
                    #     model=Activity,
                    #     operator=EntityFilterCondition.EQUALS,
                    #     name='type',
                    #     values=[atype_id],
                    # ),
                    condition_handler.RegularFieldConditionHandler.
                    build_condition(
                        model=Activity,
                        operator=operators.EqualsOperator,
                        field_name='type',
                        values=[atype_id],
                    ),
                ],
            )

        create_efilter(
            constants.EFILTER_PARTICIPATE,
            name=_('In which I participate'),
            model=Activity,
            is_custom=False,
            user='******',
            conditions=[
                # EntityFilterCondition.build_4_relation_subfilter(
                #     rtype=rt_obj_part_2_activity,
                #     subfilter=EntityFilter.get_latest_version(FILTER_CONTACT_ME)
                # ),
                condition_handler.RelationSubFilterConditionHandler.
                build_condition(
                    model=Activity,
                    rtype=rt_obj_part_2_activity,
                    subfilter=EntityFilter.get_latest_version(
                        FILTER_CONTACT_ME),
                ),
            ],
        )

        # ---------------------------
        SearchConfigItem.create_if_needed(
            Activity, ['title', 'description', 'type__name'])

        # ---------------------------
        # for user in get_user_model().objects.all():
        #     Calendar.objects.get_default_calendar(user)
        # TODO: remove this code in Creme 2.2 (it avoids install of creme which
        #       are upgraded to 2.1 to force using the command "activities_create_default_calendars")
        cal_is_public = settings.ACTIVITIES_DEFAULT_CALENDAR_IS_PUBLIC

        if cal_is_public is not None:
            if isinstance(cal_is_public, bool):
                users = get_user_model().objects.filter(
                    is_staff=False,
                    is_active=True,
                    calendar__is_default__isnull=True,
                )

                for user in users:
                    Calendar.objects.create_default_calendar(
                        user=user, is_public=cal_is_public)
            else:
                logger.error(
                    'ACTIVITIES_DEFAULT_CALENDAR_IS_PUBLIC is invalid '
                    '(not in {None, True, False}) ')

        # ---------------------------
        create_svalue = SettingValue.objects.get_or_create
        create_svalue(key_id=setting_keys.review_key.id,
                      defaults={'value': True})
        create_svalue(key_id=setting_keys.auto_subjects_key.id,
                      defaults={'value': True})
        create_svalue(key_id=setting_keys.form_user_messages_key.id,
                      defaults={'value': False})

        # ---------------------------
        if not already_populated:
            LEFT = BrickDetailviewLocation.LEFT
            RIGHT = BrickDetailviewLocation.RIGHT

            BrickDetailviewLocation.objects.create_for_model_brick(
                order=5, zone=LEFT, model=Activity)

            create_bdl = BrickDetailviewLocation.objects.create_if_needed
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=bricks.RelatedCalendarBrick,
                       order=90,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=bricks.ParticipantsBrick,
                       order=100,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=bricks.SubjectsBrick,
                       order=120,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=core_bricks.PropertiesBrick,
                       order=450,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=core_bricks.RelationsBrick,
                       order=500,
                       zone=LEFT,
                       model=Activity)
            create_bdl(brick=core_bricks.HistoryBrick,
                       order=20,
                       zone=RIGHT,
                       model=Activity)

            if apps.is_installed('creme.assistants'):
                logger.info(
                    'Assistants app is installed => we use the assistants blocks on detail views'
                )

                from creme.assistants import bricks as a_bricks

                create_bdl(brick=a_bricks.TodosBrick,
                           order=100,
                           zone=RIGHT,
                           model=Activity)
                create_bdl(brick=a_bricks.MemosBrick,
                           order=200,
                           zone=RIGHT,
                           model=Activity)
                create_bdl(brick=a_bricks.AlertsBrick,
                           order=300,
                           zone=RIGHT,
                           model=Activity)
                create_bdl(brick=a_bricks.UserMessagesBrick,
                           order=400,
                           zone=RIGHT,
                           model=Activity)

            if apps.is_installed('creme.documents'):
                # logger.info('Documents app is installed => we use the documents block on detail views')

                from creme.documents.bricks import LinkedDocsBrick

                create_bdl(brick=LinkedDocsBrick,
                           order=600,
                           zone=RIGHT,
                           model=Activity)

            future_id = bricks.FutureActivitiesBrick.id_
            past_id = bricks.PastActivitiesBrick.id_
            create_bdl(brick=future_id, order=20, zone=RIGHT, model=Contact)
            create_bdl(brick=past_id, order=21, zone=RIGHT, model=Contact)
            create_bdl(brick=future_id,
                       order=20,
                       zone=RIGHT,
                       model=Organisation)
            create_bdl(brick=past_id, order=21, zone=RIGHT, model=Organisation)

            BrickHomeLocation.objects.create(brick_id=future_id, order=20)
            BrickHomeLocation.objects.create(brick_id=past_id, order=21)

            # ---------------------------
            create_button = ButtonMenuItem.create_if_needed
            create_button('activities-add_activity_button',
                          model=None,
                          button=buttons.AddRelatedActivityButton,
                          order=10)
            create_button('activities-add_meeting_button',
                          model=None,
                          button=buttons.AddMeetingButton,
                          order=11)
            create_button('activities-add_phonecall_button',
                          model=None,
                          button=buttons.AddPhoneCallButton,
                          order=12)
示例#30
0
    def populate(self):
        already_populated = RelationType.objects.filter(
            pk=constants.REL_SUB_LINKED_2_TICKET).exists()

        Ticket = get_ticket_model()
        TicketTemplate = get_tickettemplate_model()

        RelationType.create(
            (constants.REL_SUB_LINKED_2_TICKET, _('is linked to the ticket')),
            (constants.REL_OBJ_LINKED_2_TICKET,
             _('(ticket) linked to the entity'), [Ticket]),
        )

        if apps.is_installed('creme.activities'):
            logger.info(
                'Activities app is installed => a Ticket can be the subject of an Activity'
            )

            from creme.activities.constants import REL_SUB_ACTIVITY_SUBJECT

            RelationType.objects.get(
                pk=REL_SUB_ACTIVITY_SUBJECT).add_subject_ctypes(Ticket)

        # ---------------------------
        for pk, name in BASE_STATUS:
            create_if_needed(Status, {'pk': pk},
                             name=str(name),
                             is_custom=False,
                             order=pk)

        # ---------------------------
        create_hf = HeaderFilter.create
        create_hf(
            pk=constants.DEFAULT_HFILTER_TICKET,
            model=Ticket,
            name=_('Ticket view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'number'
                }),
                (EntityCellRegularField, {
                    'name': 'title'
                }),
                (EntityCellRegularField, {
                    'name': 'status'
                }),
                (EntityCellRegularField, {
                    'name': 'priority'
                }),
                (EntityCellRegularField, {
                    'name': 'criticity'
                }),
                (EntityCellRegularField, {
                    'name': 'closing_date'
                }),
            ],
        )
        create_hf(
            pk=constants.DEFAULT_HFILTER_TTEMPLATE,
            model=TicketTemplate,
            name=_('Ticket template view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'title'
                }),
                (EntityCellRegularField, {
                    'name': 'status'
                }),
                (EntityCellRegularField, {
                    'name': 'priority'
                }),
                (EntityCellRegularField, {
                    'name': 'criticity'
                }),
            ],
        )

        # ---------------------------
        SearchConfigItem.create_if_needed(Ticket, [
            'title',
            'number',
            'description',
            'status__name',
            'priority__name',
            'criticity__name',
        ])

        # ---------------------------
        if not already_populated:
            for i, name in enumerate(
                [_('Low'),
                 _('Normal'),
                 _('High'),
                 _('Urgent'),
                 _('Blocking')],
                    start=1):
                create_if_needed(Priority, {'pk': i}, name=name, order=i)

            for i, name in enumerate([
                    _('Minor'),
                    _('Major'),
                    _('Feature'),
                    _('Critical'),
                    _('Enhancement'),
                    _('Error')
            ],
                                     start=1):
                create_if_needed(Criticity, {'pk': i}, name=name, order=i)

            # ---------------------------
            rbi = RelationBrickItem.objects.create_if_needed(
                constants.REL_OBJ_LINKED_2_TICKET)

            create_bdl = partial(
                BrickDetailviewLocation.objects.create_if_needed, model=Ticket)
            LEFT = BrickDetailviewLocation.LEFT
            RIGHT = BrickDetailviewLocation.RIGHT

            BrickDetailviewLocation.objects.create_for_model_brick(
                order=5, zone=LEFT, model=Ticket)
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT)
            create_bdl(brick=core_bricks.PropertiesBrick, order=450, zone=LEFT)
            create_bdl(brick=core_bricks.RelationsBrick, order=500, zone=LEFT)
            create_bdl(brick=rbi.brick_id, order=1, zone=RIGHT)
            create_bdl(brick=core_bricks.HistoryBrick, order=20, zone=RIGHT)

            if apps.is_installed('creme.assistants'):
                logger.info(
                    'Assistants app is installed => we use the assistants blocks on detail view'
                )

                from creme.assistants import bricks as a_bricks

                create_bdl(brick=a_bricks.TodosBrick, order=100, zone=RIGHT)
                create_bdl(brick=a_bricks.MemosBrick, order=200, zone=RIGHT)
                create_bdl(brick=a_bricks.AlertsBrick, order=300, zone=RIGHT)
                create_bdl(brick=a_bricks.UserMessagesBrick,
                           order=400,
                           zone=RIGHT)

            if apps.is_installed('creme.documents'):
                # logger.info("Documents app is installed => we use the documents block on Ticket's detail views")

                from creme.documents.bricks import LinkedDocsBrick

                create_bdl(brick=LinkedDocsBrick, order=600, zone=RIGHT)

            # ---------------------------
            if apps.is_installed('creme.persons'):
                try:
                    from creme.persons import get_contact_model, get_organisation_model
                except ImportError as e:
                    logger.info(str(e))
                else:
                    from creme.tickets.buttons import Linked2TicketButton

                    create_bmi = ButtonMenuItem.create_if_needed
                    create_bmi(pk='tickets-linked_contact_button',
                               model=get_contact_model(),
                               button=Linked2TicketButton,
                               order=50)
                    create_bmi(pk='tickets-linked_orga_button',
                               model=get_organisation_model(),
                               button=Linked2TicketButton,
                               order=50)

                    logger.info(
                        "'Persons' app is installed => add button 'Linked to a ticket' to Contact & Organisation"
                    )