Esempio n. 1
0
class RepliesCreationFromPForm(_RelatedRepliesCreationBase):
    entity_id_url_kwarg = 'pform_id'
    entity_classes = polls.get_pollform_model()
Esempio n. 2
0
class PollRepliesCreateForm(CremeForm):
    user = ModelChoiceField(
        label=_('User'),
        required=True,
        queryset=get_user_model().objects.filter(is_staff=False),
    )
    name = CharField(label=_('Name'), required=True)
    campaign = CreatorEntityField(
        label=pgettext_lazy('polls', 'Related campaign'),
        model=PollCampaign,
        required=False,
    )
    number = IntegerField(label=_('Number of replies'),
                          initial=1,
                          min_value=1,
                          required=False)
    persons = MultiGenericEntityField(
        label=_('Persons who filled'),
        required=False,
        models=[Organisation, Contact],
        help_text=_('Each reply will be linked to a person '
                    '(and "Number of replies" will be ignored)'),
    )
    pform = CreatorEntityField(label=_('Related form'),
                               model=polls.get_pollform_model())

    def __init__(self, entity=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.instance = None
        self.preplies = []
        fields = self.fields
        fields['user'].initial = self.user.id

        if entity is not None:
            if isinstance(entity, PollCampaign):
                del fields['campaign']
                self.campaign = entity
            elif isinstance(entity, PollForm):
                del fields['pform']
                self._set_pform_n_validate(entity, Http404)
            elif isinstance(entity, (Contact, Organisation)):
                del fields['persons']
                del fields['number']
                self.persons = [entity]

        # get_initial = self.initial.get

        # pform = get_initial('pform')
        # if pform:
        #     del fields['pform']
        #     self._set_pform_n_validate(pform, Http404)

        # campaign = get_initial('campaign')
        # if campaign:
        #     del fields['campaign']
        #     self.campaign = campaign

        # linked_persons = get_initial('persons')
        # if linked_persons is not None:
        #     del fields['persons']
        #     del fields['number']
        #     self.persons = linked_persons

    def clean_campaign(self):
        self.campaign = campaign = self.cleaned_data['campaign']

        return campaign

    def clean_number(self):
        return self.cleaned_data['number'] or 1

    def clean_persons(self):
        self.persons = linked_persons = self.cleaned_data['persons']

        return linked_persons

    def clean_pform(self):
        pform = self.cleaned_data['pform']
        self._set_pform_n_validate(pform, ValidationError)

        return pform

    def _set_pform_n_validate(self, pform, exception_class):
        lines = pform.lines.filter(disabled=False)

        if not lines:
            raise exception_class(
                gettext('The form must contain one line at least.'))

        self.pform = pform
        self.pform_lines = lines

    def create_preply(
            self, index, person,
            total_number):  # Easy to hook it in another app -> do not save
        cleaned_data = self.cleaned_data
        name = cleaned_data['name']

        if total_number != 1:
            name += '#{}'.format(index)

        return PollReply(
            user=cleaned_data['user'],
            pform=self.pform,
            type=self.pform.type,
            name=name,
            campaign=self.campaign,
            person=person,
        )

    def save(self, *args, **kwargs):
        linked_persons = self.persons

        if linked_persons:
            reply_number = len(linked_persons)
            linked_persons = linked_persons
        else:
            reply_number = self.cleaned_data['number']
            linked_persons = repeat(None, reply_number)

        duplicate_tree = self.pform.duplicate_tree
        # instance = None

        for i, person in enumerate(linked_persons, start=1):
            instance = self.create_preply(i, person, reply_number)
            instance.save()
            duplicate_tree(instance, self.pform_lines)
            self.preplies.append(instance)
Esempio n. 3
0
    def populate(self, *args, **kwargs):
        PollCampaign = polls.get_pollcampaign_model()
        PollForm = polls.get_pollform_model()
        PollReply = polls.get_pollreply_model()

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

        create_hf = HeaderFilter.objects.create_if_needed
        create_hf(
            pk=constants.DEFAULT_HFILTER_PFORM,
            model=PollForm,
            name=_('Form view'),
            cells_desc=[(EntityCellRegularField, {
                'name': 'name'
            })],
        )
        create_hf(
            pk=constants.DEFAULT_HFILTER_PREPLY,
            model=PollReply,
            name=_('Reply view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
                (EntityCellRegularField, {
                    'name': 'pform'
                }),
                (EntityCellRegularField, {
                    'name': 'person'
                }),
            ],
        )
        create_hf(
            pk=constants.DEFAULT_HFILTER_PCAMPAIGN,
            model=PollCampaign,
            name=_('Campaign view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
                (EntityCellRegularField, {
                    'name': 'due_date'
                }),
                (EntityCellRegularField, {
                    'name': 'segment'
                }),
            ],
        )

        # ---------------------------
        def build_custom_form_items(creation_descriptor, edition_descriptor,
                                    field_names):
            base_groups_desc = [
                {
                    'name':
                    _('General information'),
                    'cells': [
                        *((EntityCellRegularField, {
                            'name': fname
                        }) for fname in field_names),
                        (
                            EntityCellCustomFormSpecial,
                            {
                                'name':
                                EntityCellCustomFormSpecial.
                                REMAINING_REGULARFIELDS
                            },
                        ),
                    ],
                },
                {
                    'name': _('Description'),
                    'cells': [
                        (EntityCellRegularField, {
                            'name': 'description'
                        }),
                    ],
                },
                {
                    'name':
                    _('Custom fields'),
                    'cells': [
                        (
                            EntityCellCustomFormSpecial,
                            {
                                'name':
                                EntityCellCustomFormSpecial.
                                REMAINING_CUSTOMFIELDS
                            },
                        ),
                    ],
                },
            ]

            CustomFormConfigItem.objects.create_if_needed(
                descriptor=creation_descriptor,
                groups_desc=[
                    *base_groups_desc,
                    {
                        'name':
                        _('Properties'),
                        'cells': [
                            (
                                EntityCellCustomFormSpecial,
                                {
                                    'name':
                                    EntityCellCustomFormSpecial.
                                    CREME_PROPERTIES
                                },
                            ),
                        ],
                    },
                    {
                        'name':
                        _('Relationships'),
                        'cells': [
                            (
                                EntityCellCustomFormSpecial,
                                {
                                    'name':
                                    EntityCellCustomFormSpecial.RELATIONS
                                },
                            ),
                        ],
                    },
                ],
            )
            CustomFormConfigItem.objects.create_if_needed(
                descriptor=edition_descriptor,
                groups_desc=base_groups_desc,
            )

        build_custom_form_items(
            creation_descriptor=custom_forms.CAMPAIGN_CREATION_CFORM,
            edition_descriptor=custom_forms.CAMPAIGN_EDITION_CFORM,
            field_names=[
                'user',
                'name',
                'goal',
                'start',
                'due_date',
                'segment',
                'expected_count',
            ],
        )
        build_custom_form_items(
            creation_descriptor=custom_forms.PFORM_CREATION_CFORM,
            edition_descriptor=custom_forms.PFORM_EDITION_CFORM,
            field_names=['user', 'name', 'type'],
        )

        # ---------------------------
        create_searchconf = SearchConfigItem.objects.create_if_needed
        create_searchconf(PollForm, ['name'])
        create_searchconf(PollReply, ['name'])
        create_searchconf(PollCampaign, ['name'])

        # ---------------------------
        # NB: no straightforward way to test that this populate script has not been already run
        if not PollType.objects.exists():
            create_if_needed(PollType, {'pk': 1}, name=_('Survey'))
            create_if_needed(PollType, {'pk': 2}, name=_('Monitoring'))
            create_if_needed(PollType, {'pk': 3}, name=_('Assessment'))

        # ---------------------------
        # TODO: move to "not already_populated" section in creme2.4
        if not MenuConfigItem.objects.filter(
                entry_id__startswith='polls-').exists():
            container = MenuConfigItem.objects.get_or_create(
                entry_id=ContainerEntry.id,
                entry_data={'label': _('Tools')},
                defaults={'order': 100},
            )[0]

            create_mitem = partial(MenuConfigItem.objects.create,
                                   parent=container)
            create_mitem(
                entry_id=Separator1Entry.id,
                entry_data={'label': _('Polls')},
                order=300,
            )
            create_mitem(entry_id=menu.PollFormsEntry.id, order=305)
            create_mitem(entry_id=menu.PollRepliesEntry.id, order=310)
            create_mitem(entry_id=menu.PollCampaignsEntry.id, order=315)

        # ---------------------------
        # NB: no straightforward way to test that this populate script has not been already run
        if not BrickDetailviewLocation.objects.filter_for_model(
                PollForm).exists():
            TOP = BrickDetailviewLocation.TOP
            LEFT = BrickDetailviewLocation.LEFT
            RIGHT = BrickDetailviewLocation.RIGHT

            BrickDetailviewLocation.objects.multi_create(
                defaults={
                    'model': PollForm,
                    'zone': LEFT
                },
                data=[
                    {
                        'brick': bricks.PollFormLinesBrick,
                        'order': 5,
                        'zone': TOP
                    },
                    {
                        'order': 5
                    },
                    {
                        'brick': core_bricks.CustomFieldsBrick,
                        'order': 40
                    },
                    {
                        'brick': core_bricks.PropertiesBrick,
                        'order': 450
                    },
                    {
                        'brick': core_bricks.RelationsBrick,
                        'order': 500
                    },
                    {
                        'brick': bricks.PollRepliesBrick,
                        'order': 5,
                        'zone': RIGHT
                    },
                    {
                        'brick': core_bricks.HistoryBrick,
                        'order': 20,
                        'zone': RIGHT
                    },
                ],
            )
            BrickDetailviewLocation.objects.multi_create(
                defaults={
                    'model': PollReply,
                    'zone': LEFT
                },
                data=[
                    {
                        'brick': bricks.PollReplyLinesBrick,
                        'order': 5,
                        'zone': TOP
                    },
                    {
                        'order': 5
                    },
                    {
                        'brick': core_bricks.CustomFieldsBrick,
                        'order': 40
                    },
                    {
                        'brick': core_bricks.PropertiesBrick,
                        'order': 450
                    },
                    {
                        'brick': core_bricks.RelationsBrick,
                        'order': 500
                    },
                    {
                        'brick': core_bricks.HistoryBrick,
                        'order': 20,
                        'zone': RIGHT
                    },
                ],
            )
            BrickDetailviewLocation.objects.multi_create(
                defaults={
                    'model': PollCampaign,
                    'zone': LEFT
                },
                data=[
                    {
                        'order': 5
                    },
                    {
                        'brick': core_bricks.CustomFieldsBrick,
                        'order': 40
                    },
                    {
                        'brick': core_bricks.PropertiesBrick,
                        'order': 450
                    },
                    {
                        'brick': core_bricks.RelationsBrick,
                        'order': 500
                    },
                    {
                        'brick': bricks.PollCampaignRepliesBrick,
                        'order': 5,
                        'zone': RIGHT
                    },
                    {
                        'brick': core_bricks.HistoryBrick,
                        'order': 20,
                        'zone': RIGHT
                    },
                ],
            )

            BrickDetailviewLocation.objects.multi_create(
                defaults={
                    'brick': bricks.PersonPollRepliesBrick,
                    'order': 500,
                    'zone': RIGHT
                },
                data=[{
                    'model': Contact
                }, {
                    'model': Organisation
                }],
            )

            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

                for model in (PollForm, PollReply, PollCampaign):
                    BrickDetailviewLocation.objects.multi_create(
                        defaults={
                            'model': model,
                            'zone': RIGHT
                        },
                        data=[
                            {
                                'brick': a_bricks.TodosBrick,
                                'order': 100
                            },
                            {
                                'brick': a_bricks.MemosBrick,
                                'order': 200
                            },
                            {
                                'brick': a_bricks.AlertsBrick,
                                'order': 300
                            },
                            {
                                'brick': a_bricks.UserMessagesBrick,
                                'order': 400
                            },
                        ],
                    )

            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

                BrickDetailviewLocation.objects.multi_create(
                    defaults={
                        'brick': LinkedDocsBrick,
                        'order': 600,
                        'zone': RIGHT
                    },
                    data=[{
                        'model': m
                    } for m in (PollForm, PollReply, PollCampaign)],
                )
Esempio n. 4
0
from creme.creme_core.auth import EntityCredentials
from creme.creme_core.forms import (CremeForm, CremeEntityForm,
                                    CreatorEntityField,
                                    MultiCreatorEntityField,
                                    GenericEntityField,
                                    MultiGenericEntityField)
from creme.creme_core.forms.bulk import BulkDefaultEditForm
from creme.creme_core.forms.widgets import Label

from creme import persons, polls

Contact = persons.get_contact_model()
Organisation = persons.get_organisation_model()
PollCampaign = polls.get_pollcampaign_model()
PollForm = polls.get_pollform_model()
PollReply = polls.get_pollreply_model()


class PollRepliesCreateForm(CremeForm):
    user = ModelChoiceField(
        label=_('User'),
        required=True,
        queryset=get_user_model().objects.filter(is_staff=False),
    )
    name = CharField(label=_('Name'), required=True)
    campaign = CreatorEntityField(
        label=pgettext_lazy('polls', 'Related campaign'),
        model=PollCampaign,
        required=False,
    )
Esempio n. 5
0
    def populate(self, *args, **kwargs):
        PollCampaign = polls.get_pollcampaign_model()
        PollForm = polls.get_pollform_model()
        PollReply = polls.get_pollreply_model()

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

        create_hf = HeaderFilter.create
        create_hf(
            pk=constants.DEFAULT_HFILTER_PFORM,
            model=PollForm,
            name=_('Form view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
            ],
        )
        create_hf(
            pk=constants.DEFAULT_HFILTER_PREPLY,
            model=PollReply,
            name=_('Reply view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
                (EntityCellRegularField, {
                    'name': 'pform'
                }),
                (EntityCellRegularField, {
                    'name': 'person'
                }),
            ],
        )
        create_hf(
            pk=constants.DEFAULT_HFILTER_PCAMPAIGN,
            model=PollCampaign,
            name=_('Campaign view'),
            cells_desc=[
                (EntityCellRegularField, {
                    'name': 'name'
                }),
                (EntityCellRegularField, {
                    'name': 'due_date'
                }),
                (EntityCellRegularField, {
                    'name': 'segment'
                }),
            ],
        )

        # ---------------------------
        create_searchconf = SearchConfigItem.create_if_needed
        create_searchconf(PollForm, ['name'])
        create_searchconf(PollReply, ['name'])
        create_searchconf(PollCampaign, ['name'])

        # ---------------------------
        if not PollType.objects.exists(
        ):  # NB: no straightforward way to test that this populate script has not been already run
            create_if_needed(PollType, {'pk': 1}, name=_('Survey'))
            create_if_needed(PollType, {'pk': 2}, name=_('Monitoring'))
            create_if_needed(PollType, {'pk': 3}, name=_('Assessment'))

        # ---------------------------
        # NB: no straightforward way to test that this populate script has not been already run
        if not BrickDetailviewLocation.objects.filter_for_model(
                PollForm).exists():
            TOP = BrickDetailviewLocation.TOP
            LEFT = BrickDetailviewLocation.LEFT
            RIGHT = BrickDetailviewLocation.RIGHT

            create_bdl = BrickDetailviewLocation.objects.create_if_needed
            create_bdl_4_model = BrickDetailviewLocation.objects.create_for_model_brick

            create_bdl(brick=bricks.PollFormLinesBrick,
                       order=5,
                       zone=TOP,
                       model=PollForm)
            create_bdl_4_model(order=5, zone=LEFT, model=PollForm)
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT,
                       model=PollForm)
            create_bdl(brick=core_bricks.PropertiesBrick,
                       order=450,
                       zone=LEFT,
                       model=PollForm)
            create_bdl(brick=core_bricks.RelationsBrick,
                       order=500,
                       zone=LEFT,
                       model=PollForm)
            create_bdl(brick=bricks.PollRepliesBrick,
                       order=5,
                       zone=RIGHT,
                       model=PollForm)
            create_bdl(brick=core_bricks.HistoryBrick,
                       order=20,
                       zone=RIGHT,
                       model=PollForm)

            # TODO: factorise
            create_bdl(brick=bricks.PollReplyLinesBrick,
                       order=5,
                       zone=TOP,
                       model=PollReply)
            create_bdl_4_model(order=5, zone=LEFT, model=PollReply)
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT,
                       model=PollReply)
            create_bdl(brick=core_bricks.PropertiesBrick,
                       order=450,
                       zone=LEFT,
                       model=PollReply)
            create_bdl(brick=core_bricks.RelationsBrick,
                       order=500,
                       zone=LEFT,
                       model=PollReply)
            create_bdl(brick=core_bricks.HistoryBrick,
                       order=20,
                       zone=RIGHT,
                       model=PollReply)

            create_bdl_4_model(order=5, zone=LEFT, model=PollCampaign)
            create_bdl(brick=core_bricks.CustomFieldsBrick,
                       order=40,
                       zone=LEFT,
                       model=PollCampaign)
            create_bdl(brick=core_bricks.PropertiesBrick,
                       order=450,
                       zone=LEFT,
                       model=PollCampaign)
            create_bdl(brick=core_bricks.RelationsBrick,
                       order=500,
                       zone=LEFT,
                       model=PollCampaign)
            create_bdl(brick=bricks.PollCampaignRepliesBrick,
                       order=5,
                       zone=RIGHT,
                       model=PollCampaign)
            create_bdl(brick=core_bricks.HistoryBrick,
                       order=20,
                       zone=RIGHT,
                       model=PollCampaign)

            create_bdl(brick=bricks.PersonPollRepliesBrick,
                       order=500,
                       zone=RIGHT,
                       model=Contact)
            create_bdl(brick=bricks.PersonPollRepliesBrick,
                       order=500,
                       zone=RIGHT,
                       model=Organisation)

            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

                for model in (PollForm, PollReply, PollCampaign):
                    create_bdl(brick=a_bricks.TodosBrick,
                               order=100,
                               zone=RIGHT,
                               model=model)
                    create_bdl(brick=a_bricks.MemosBrick,
                               order=200,
                               zone=RIGHT,
                               model=model)
                    create_bdl(brick=a_bricks.AlertsBrick,
                               order=300,
                               zone=RIGHT,
                               model=model)
                    create_bdl(brick=a_bricks.UserMessagesBrick,
                               order=400,
                               zone=RIGHT,
                               model=model)

            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

                for model in (PollForm, PollReply, PollCampaign):
                    create_bdl(brick=LinkedDocsBrick,
                               order=600,
                               zone=RIGHT,
                               model=model)