Ejemplo n.º 1
0
def persons_contact_first_employer(contact, user):
    info = {}
    managed_ids = []
    employing_ids = []

    for rtype_id, orga_id in contact.relations.filter(type__in=(REL_SUB_EMPLOYED_BY, REL_SUB_MANAGES))\
                                    .values_list('type', 'object_entity'):
        if rtype_id == REL_SUB_MANAGES:
            managed_ids.append(orga_id)
        else:
            employing_ids.append(orga_id)

    if managed_ids:
        orga = EntityCredentials.filter(
            user,
            get_organisation_model().objects.filter(id__in=managed_ids, is_deleted=False),
        ).first()

        if orga:
            info['organisation'] = orga
            info['as_manager'] = True

    if not info and employing_ids:
        orga = EntityCredentials.filter(
            user,
            get_organisation_model().objects.filter(id__in=employing_ids, is_deleted=False),
        ).first()

        if orga:
            info['organisation'] = orga
            info['as_manager'] = False

    return info
Ejemplo n.º 2
0
    def __init__(self, event, contact, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = self.fields
        self.event = event

        qs = get_organisation_model().objects.filter(
            relations__type__in=[
                REL_OBJ_EMPLOYED_BY,
                REL_OBJ_MANAGES,
            ],
            relations__object_entity=contact.id,
        )

        description_f = fields.get('description')
        if description_f:
            description_f.initial = gettext(
                'Generated by the event «{}»').format(event)

        if not qs:
            fields['target'].help_text = \
                gettext('(The contact «{}» is not related to an organisation).').format(contact)
        else:
            fields['target'] = ModelChoiceField(
                label=pgettext(
                    'events-opportunity',
                    'Target organisation',
                ),
                queryset=qs,
                empty_label=None,
            )
Ejemplo n.º 3
0
    def detailview_display(self, context):
        entity = context['object']
        pk = entity.pk

        # if isinstance(entity, get_organisation_model()) and \
        #    not SettingValue.objects.get(key_id=DISPLAY_ONLY_ORGA_COM_APPROACH_ON_ORGA_DETAILVIEW).value:
        if isinstance(entity, get_organisation_model()) and \
           not SettingValue.objects.get_4_key(orga_approaches_key, default=True).value:
            # TODO: regroup the queries
            managers_ids = entity.get_managers().values_list('id', flat=True)
            employees_ids = entity.get_employees().values_list('id', flat=True)
            opportunities_ids = Opportunity.objects.filter(relations__type=REL_SUB_TARGETS,
                                                           relations__object_entity=entity,
                                                          ) \
                                                   .values_list('id',flat=True)

            approaches = CommercialApproach.objects.filter(
                # ok_or_in_futur=False,
                entity_id__in=chain([pk], managers_ids, employees_ids,
                                    opportunities_ids), )
        else:
            approaches = CommercialApproach.get_approaches(pk)

        return self._render(self.get_template_context(
            context,
            approaches,
        ))
Ejemplo n.º 4
0
class RelatedBaseCreation(generic.AddingInstanceToEntityPopup):
    model = Base
    permissions: Union[str, Sequence[str],
                       None] = 'billing'  # Need creation perm too
    initial_status = 1
    entity_id_url_kwarg = 'target_id'
    entity_classes = [
        persons.get_organisation_model(),
        persons.get_contact_model(),
    ]
    entity_form_kwarg = None

    def get_initial(self):
        initial = super().get_initial()
        initial['status'] = self.initial_status

        target = self.get_related_entity()
        # initial['target'] = target  # DEPRECATED
        initial[base_forms.BillingTargetSubCell(
            model=self.model).into_cell().key] = target

        return initial

    def get_success_url(self):
        if bool_from_str_extended(self.request.GET.get('redirection', '0')):
            return self.object.get_absolute_url()

        return super().get_success_url()
Ejemplo n.º 5
0
def _get_organisation_n_factory(locale):
    from creme.persons import get_organisation_model

    Organisation = get_organisation_model()

    # build_email_domain = partial(factory.Faker('free_email_domain', locale=locale).generate, {})
    build_email_domain = partial(
        factory.Faker('free_email_domain', locale=locale).evaluate,
        step=None,
    )

    def build_email(orga):
        # return '{0}@{1}'.format(orga.name, build_email_domain()).lower()
        domain = build_email_domain(orga, extra={'locale': locale})
        return '{}@{}'.format(orga.name, domain).lower()

    class OrganisationFactory(DjangoModelFactory):
        class Meta:
            model = Organisation

        user = factory.LazyAttribute(get_user)
        name = factory.Faker('company', locale=locale)
        email = factory.LazyAttribute(or_blank(build_email))

    return Organisation, OrganisationFactory
Ejemplo n.º 6
0
 def formfield(self, instance, user, **kwargs):
     return CreatorEntityField(
         label=self.verbose_name,
         model=get_organisation_model(),
         user=user,
         initial=first_managed_organisation() if not instance.pk else instance.source,
     )
Ejemplo n.º 7
0
class RelatedBaseCreation(generic.AddingInstanceToEntityPopup):
    model = Base
    # form_class = base_forms.BaseCreateForm
    template_name = 'billing/form/add-popup.html'
    permissions = 'billing'  # Need creation perm too
    initial_status = 1
    entity_id_url_kwarg = 'target_id'
    entity_classes = [
        persons.get_organisation_model(),
        persons.get_contact_model(),
    ]
    entity_form_kwarg = None

    def get_initial(self):
        initial = super().get_initial()
        initial['status'] = self.initial_status
        initial['target'] = self.get_related_entity()

        return initial

    def get_success_url(self):
        if bool_from_str_extended(self.request.GET.get('redirection', '0')):
            return self.object.get_absolute_url()

        return super().get_success_url()
Ejemplo n.º 8
0
class PaymentInformationCreation(generic.AddingInstanceToEntityPopup):
    model = PaymentInformation
    form_class = pi_forms.PaymentInformationCreateForm
    permissions = 'billing'
    entity_id_url_kwarg = 'orga_id'
    entity_classes = get_organisation_model()
    title = _('New payment information in the organisation «{entity}»')
Ejemplo n.º 9
0
class AddressesInformation(BaseAddressesInformation):
    entity_classes = [
        persons.get_contact_model(),
        persons.get_organisation_model(),
    ]

    def get_info(self, request):
        entity_filter = self.get_efilter()
        user = request.user

        def owner_groups():
            if entity_filter:
                # TODO: assert in self.entity_classes
                model = entity_filter.entity_type.model_class()
                yield entity_filter.filter(model.objects.all(), user=user)
            else:
                for model in self.entity_classes:
                    yield model.objects.all()

        addresses = [
            address for owners in owner_groups()
            for address in addresses_from_persons(owners, user)
        ]

        GeoAddress.populate_geoaddresses(addresses)

        return {
            'addresses': [address_as_dict(address) for address in addresses]
        }
Ejemplo n.º 10
0
    def emitter(self):
        if not self._opp_emitter:
            self._opp_emitter = get_organisation_model().objects.get(
                relations__type=constants.REL_SUB_EMIT_ORGA,
                relations__object_entity=self.id,
            )

        return self._opp_emitter
Ejemplo n.º 11
0
class PersonPollRepliesBrick(_RelatedRepliesBrick):
    id_ = _RelatedRepliesBrick.generate_id('polls', 'person_replies')
    template_name = 'polls/bricks/person-preplies.html'
    target_ctypes = (persons.get_contact_model(),
                     persons.get_organisation_model())

    def _get_replies(self, pk):
        return PollReply.objects.filter(person=pk)
Ejemplo n.º 12
0
def _get_strategy_n_orga(request, strategy_id, orga_id):
    strategy = get_object_or_404(Strategy, pk=strategy_id)
    has_perm = request.user.has_perm_to_view_or_die
    has_perm(strategy)

    orga = get_object_or_404(get_organisation_model(), pk=orga_id)
    has_perm(orga)

    return strategy, orga
Ejemplo n.º 13
0
    def register_fields_config(self, fields_config_registry):
        from creme import persons

        fields_config_registry.register_needed_fields(
            'cti', persons.get_contact_model(),
            'phone', 'mobile',
        ).register_needed_fields(
            'cti', persons.get_organisation_model(),
            'phone',
        )
Ejemplo n.º 14
0
    def populate(self):
        already_populated = SettingValue.objects.filter(
            key_id=setting_keys.NEIGHBOURHOOD_DISTANCE.id).exists()

        create_skey = SettingValue.objects.get_or_create
        create_skey(
            key_id=setting_keys.NEIGHBOURHOOD_DISTANCE.id,
            defaults={'value': constants.DEFAULT_SEPARATING_NEIGHBOURS})
        create_skey(key_id=setting_keys.GOOGLE_API_KEY.id,
                    defaults={'value': ''})

        if not already_populated:
            if self.verbosity:
                self.stdout.write('\n ', ending='')
                self.stdout.flush()

            GeolocationCommand().import_town_all(verbosity=self.verbosity)

        if not already_populated:
            Contact = persons.get_contact_model()
            Organisation = persons.get_organisation_model()

            create_bdl = BrickDetailviewLocation.create_if_needed
            create_bdl(brick_id=bricks.GoogleDetailMapBrick.id_,
                       order=70,
                       zone=BrickDetailviewLocation.LEFT,
                       model=Organisation)
            create_bdl(brick_id=bricks.GoogleDetailMapBrick.id_,
                       order=70,
                       zone=BrickDetailviewLocation.LEFT,
                       model=Contact)
            create_bdl(brick_id=bricks.GoogleNeighboursMapBrick.id_,
                       order=600,
                       zone=BrickDetailviewLocation.BOTTOM,
                       model=Organisation)
            create_bdl(brick_id=bricks.GoogleNeighboursMapBrick.id_,
                       order=600,
                       zone=BrickDetailviewLocation.BOTTOM,
                       model=Contact)

            BrickMypageLocation.objects.create(
                brick_id=bricks.GoogleFilteredMapBrick.id_,
                order=20,
                user=None)

            # Add this bloc only if the root user exists (creme_core populated)
            root = get_user_model().objects.filter(pk=1).first()
            if root:
                logger.info(
                    'Creme core is installed => the block PersonsFilterMap can be activated'
                )
                BrickMypageLocation.objects.create(
                    brick_id=bricks.GoogleFilteredMapBrick.id_,
                    order=8,
                    user=root)
Ejemplo n.º 15
0
    def formfield(self, instance, user, **kwargs):
        field = GenericEntityField(
            label=self.verbose_name,
            models=[get_organisation_model(), get_contact_model()],
            user=user,
        )

        if instance.pk:
            field.initial = instance.target

        return field
Ejemplo n.º 16
0
    def all_apps_ready(self):
        from creme import persons

        self.Contact = persons.get_contact_model()
        self.Organisation = persons.get_organisation_model()
        self.Address = persons.get_address_model()
        super().all_apps_ready()
        self.hook_user()
        self.hook_user_form()

        from . import signals
Ejemplo n.º 17
0
    def get_organisation(self):
        orga = self.organisation

        if orga is None:
            self.organisation = orga = get_object_or_404(
                get_organisation_model(),
                pk=self.kwargs[self.orga_id_url_kwarg],
            )
            self.request.user.has_perm_to_view_or_die(orga)

        return orga
Ejemplo n.º 18
0
    def register_fields_config(self, fields_config_registry):
        from creme import persons

        fields_config_registry.register_needed_fields(
            'emails',
            persons.get_contact_model(),
            'email',
        ).register_needed_fields(
            'emails',
            persons.get_organisation_model(),
            'email',
        )
Ejemplo n.º 19
0
class AddOrganisationForm(CremeForm):
    organisations = MultiCreatorEntityField(label=_('Organisations'),
                                            model=get_organisation_model())

    def __init__(self, entity, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._strategy = entity

    def save(self):
        eval_orgas = self._strategy.evaluated_orgas

        for orga in self.cleaned_data['organisations']:
            eval_orgas.add(orga)
Ejemplo n.º 20
0
    def register_statistics(self, statistics_registry):
        from creme.persons import get_organisation_model

        from .statistics import CurrentYearStatistics

        statistics_registry.register(
            id='opportunities',
            label=CurrentYearStatistics.label,
            func=CurrentYearStatistics(opp_model=self.Opportunity,
                                       orga_model=get_organisation_model()),
            perm='opportunities',
            priority=15,
        )
Ejemplo n.º 21
0
    def __init__(self, entity1, entity2, *args, **kwargs):
        if isinstance(entity1, Contact):  # TODO: create a ContactMergeForm ?
            if entity2.is_user:
                if entity1.is_user:
                    raise self.CanNotMergeError(_('Can not merge 2 Contacts which represent some users.'))

                entity1, entity2 = entity2, entity1
        else:
            assert isinstance(entity1, persons.get_organisation_model())

            if entity2.is_managed and not entity1.is_managed:
                entity1, entity2 = entity2, entity1

        super().__init__(entity1, entity2, *args, **kwargs)
Ejemplo n.º 22
0
    def all_apps_ready(self):
        from creme import persons

        self.Contact = persons.get_contact_model()
        self.Organisation = persons.get_organisation_model()
        self.Address = persons.get_address_model()
        super().all_apps_ready()
        self.hook_user()
        self.hook_user_form()

        from . import signals  # NOQA

        if apps.is_installed('creme.reports'):
            self.register_reports_graph_fetchers()
Ejemplo n.º 23
0
    def __init__(self, opportunity, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.opportunity = opportunity

        target = opportunity.target

        if isinstance(target, persons.get_organisation_model()):
            has_perm = self.user.has_perm_to_link

            # TODO: Label() if not allowed ?
            if has_perm(target) and has_perm(Contact):
                self.fields['is_employed'] = BooleanField(
                    label=_('Is employed by «{}»?').format(opportunity.target),
                    required=False,
                )
Ejemplo n.º 24
0
    def register_function_fields(self, function_field_registry):
        from creme import persons

        from . import function_fields as ffields

        register = function_field_registry.register
        register(self.TemplateBase, ffields.TemplateBaseVerboseStatusField)

        for model in (persons.get_organisation_model(),
                      persons.get_contact_model()):
            register(
                model,
                ffields._TotalPendingPayment,
                ffields._TotalWonQuoteThisYear,
                ffields._TotalWonQuoteLastYear,
            )
Ejemplo n.º 25
0
def get_addresses_from_filter(request):  # TODO: rename 'get_addresses()'
    filter_id = request.GET.get('id')
    entity_filter = get_object_or_404(EntityFilter, pk=filter_id) if filter_id else None
    owner_groups = (get_contact_model().objects, get_organisation_model().objects,)

    user = request.user

    if entity_filter:
        model = entity_filter.entity_type.model_class()
        owner_groups = (entity_filter.filter(model.objects, user),)

    addresses = list(chain(*(iter(addresses_from_persons(owners, user)) for owners in owner_groups)))

    GeoAddress.populate_geoaddresses(addresses)

    return {'addresses': [address_as_dict(address) for address in addresses]}
Ejemplo n.º 26
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # self.fields['source'].initial = first_managed_orga_id()
        try:
            managed_orga = get_organisation_model(
            ).objects.filter_managed_by_creme()[0]
        except IndexError:
            logger.warning('No managed organisation ?!')
        else:
            fields = self.fields
            fields['source'].initial = managed_orga

            if type(self.instance).generate_number_in_create:
                fields['number'].help_text = _(
                    'If you chose an organisation managed by Creme (like «{}») '
                    'as source organisation, a number will be automatically generated.'
                ).format(managed_orga)
Ejemplo n.º 27
0
class RelatedOpportunityCreation(EntityRelatedMixin, _BaseOpportunityCreation):
    entity_id_url_kwarg = 'person_id'
    entity_classes = [
        persons.get_contact_model(),
        persons.get_organisation_model(),
    ]

    def check_related_entity_permissions(self, entity, user):
        # We don't need the link credentials with future Opportunity because
        # Target/emitter relationships are internal (they are mandatory
        # and can be seen as ForeignKeys).
        user.has_perm_to_link_or_die(entity)

    def get_initial(self):
        initial = super().get_initial()
        initial['target'] = self.get_related_entity()

        return initial
Ejemplo n.º 28
0
class RelatedBaseCreation(generic.AddingInstanceToEntityPopup):
    model = Base
    # form_class = BaseCreateForm
    permissions = 'billing'  # Need creation perm too
    initial_status = 1
    entity_id_url_kwarg = 'target_id'
    entity_classes = [
        persons.get_organisation_model(),
        persons.get_contact_model(),
    ]
    entity_form_kwarg = None

    def get_initial(self):
        initial = super().get_initial()
        initial['status'] = self.initial_status
        initial['target'] = self.get_related_entity()

        return initial
Ejemplo n.º 29
0
    def get_organisation(self):
        try:
            orga = getattr(self, 'organisation')
        except AttributeError:
            orga_id = self.kwargs[self.orga_id_url_kwarg]
            strategy = self.get_strategy()

            try:
                self.organisation = orga = strategy.evaluated_orgas.get(id=orga_id)
            except get_organisation_model().DoesNotExist:
                raise Http404(gettext(
                    'This organisation «{orga}» is not (no more ?) evaluated by '
                    'the strategy «{strategy}»').format(
                    orga=orga_id, strategy=strategy,
                ))

            self.request.user.has_perm_to_view_or_die(orga)

        return orga
Ejemplo n.º 30
0
class RelatedOpportunityCreationPopup(generic.AddingInstanceToEntityPopup):
    model = Opportunity
    form_class = opp_forms.TargetedOpportunityCreationForm
    permissions = ['opportunities', cperm(Opportunity)]
    title = _('New opportunity targeting «{entity}»')
    entity_id_url_kwarg = 'person_id'
    entity_form_kwarg = 'target'
    entity_classes = [
        persons.get_contact_model(),
        persons.get_organisation_model(),
    ]

    def check_related_entity_permissions(self, entity, user):
        # We don't need the link credentials with future Opportunity because
        # Target/emitter relationships are internal (they are mandatory
        # and can be seen as ForeignKeys).
        user.has_perm_to_link_or_die(entity)

    def get_initial(self):
        initial = super().get_initial()
        initial['sales_phase'] = SalesPhase.objects.first()

        return initial