def perform_create(self, serializer):
        # from rest_framework.exceptions import ValidationError

        data = self.request.data

        # if "form" not in data:
        #     raise ValidationError({
        #         "form": "No Form Selected ",
        #     })
        # if data.has_key('site'):
        #     if FieldSightXF.objects.filter(xf=data["form"], is_scheduled=True, site=data["site"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })
        #     if FieldSightXF.objects.filter(xf=data["form"],is_scheduled=True, project=data["project"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })

        schedule = serializer.save()

        fxf = FieldSightXF(xf_id=data["xf"],
                           is_scheduled=True,
                           schedule=schedule,
                           site=schedule.site,
                           project=schedule.project)
        if data.has_key("site"):
            fxf.is_deployed = True
        fxf.save()
Example #2
0
def clone_form(project_id, task_id):
    time.sleep(10)
    project = Project.objects.get(id=project_id)

    organization = project.organization
    try:
        super_org = organization.parent
        library_forms = super_org.library_forms.filter(deleted=False,
                                                       form_type__in=[0, 1])

        fsxf_list = []

        for lf in library_forms:
            if lf.form_type == 0:
                fsxf = FieldSightXF(
                    xf=lf.xf,
                    project=project,
                    is_deployed=True,
                    default_submission_status=lf.default_submission_status,
                    organization_form_lib=lf)
                fsxf_list.append(fsxf)
            else:
                scheduled_obj = Schedule.objects.\
                    create(project=project, date_range_start=lf.date_range_start,
                           date_range_end=lf.date_range_end,
                           schedule_level_id=lf.schedule_level_id, frequency=lf.frequency,
                           month_day=lf.month_day, organization_form_lib=lf)
                scheduled_obj.selected_days.add(
                    *lf.selected_days.values_list('id', flat=True))
                scheduled_obj.save()

                scheduled_fxf = FieldSightXF(
                    xf=lf.xf,
                    project=project,
                    is_deployed=True,
                    is_scheduled=True,
                    default_submission_status=lf.default_submission_status,
                    schedule=scheduled_obj,
                    organization_form_lib=lf)
                fsxf_list.append(scheduled_fxf)

        FieldSightXF.objects.bulk_create(fsxf_list)

        CeleryTaskProgress.objects.filter(id=task_id).update(status=2)
    except Exception as e:
        CeleryTaskProgress.objects.filter(id=task_id).update(
            status=2, description=str(e))
Example #3
0
def clone_form(project_id, task_id):
    time.sleep(10)
    project = Project.objects.get(id=project_id)

    organization = project.organization
    try:
        super_org = organization.parent
        library_forms = super_org.library_forms.filter(deleted=False)
        fsxf_list = []
        for lf in library_forms:
            fsxf = FieldSightXF(xf=lf.xf,project=project, is_deployed=True)
            fsxf_list.append(fsxf)
        FieldSightXF.objects.bulk_create(fsxf_list)
        CeleryTaskProgress.objects.filter(id=task_id).update(status=2)
    except Exception as e:
        CeleryTaskProgress.objects.filter(id=task_id).update(status=2, description=str(e))
    def post(self, request, pk, format=None):
        team_ids = request.data.get('team_ids', None)

        if team_ids:
            Organization.objects.filter(id__in=team_ids).update(parent_id=pk)
            projects = Project.objects.filter(organization__id__in=team_ids)
            library_forms = OrganizationFormLibrary.objects.filter(
                organization=pk)
            fsxf_list = []
            for p in projects:
                for lf in library_forms:
                    fsxf = FieldSightXF(xf=lf.xf, project=p, is_deployed=True)
                    fsxf_list.append(fsxf)
            FieldSightXF.objects.bulk_create(fsxf_list)

            return Response(status=status.HTTP_200_OK,
                            data={'detail': 'successfully updated.'})

        else:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={'detail': 'team_ids field is required.'})
Example #5
0
    def create(self, validated_data):
        id = self.context['request'].data.get('id', False)
        api_request = self.context['request']
        with transaction.atomic():
            sub_stages_datas = self.context['request'].data.get('parent')
            if not id:
                stage = Stage.objects.create(**validated_data)
                for order, ss in enumerate(sub_stages_datas):
                    ss.pop('id')
                    stage_forms_dict = ss.pop('stage_forms')
                    xf_id = stage_forms_dict['xf']['id']
                    ss.update({'stage':stage, 'order':order+1})
                    default_submission_status = stage_forms_dict['default_submission_status']
                    sub_stage_obj = Stage.objects.create(**ss)
                    fxf = FieldSightXF(xf_id=xf_id, site=stage.site, project=stage.project, is_staged=True,
                                       stage=sub_stage_obj, default_submission_status=default_submission_status)
                    fxf.save()
                    if stage.project:
                        noti = fxf.logs.create(source=api_request.user, type=18, title="Stage",
                                               organization=fxf.project.organization,
                                               project = fxf.project,
                                               content_object = fxf,
                                               extra_object = fxf.project,
                                               description='{0} assigned new Stage form  {1} to {2} '.format(
                                                   api_request.user.get_full_name(),
                                                   fxf.xf.title,
                                                   fxf.project.name
                                               ))
                        result = {}
                        result['description'] = noti.description
                        result['url'] = noti.get_absolute_url()
                        # ChannelGroup("site-{}".format(fxf.site.id)).send({"text": json.dumps(result)})
                        ChannelGroup("project-{}".format(fxf.project.id)).send({"text": json.dumps(result)})
                    else:
                        fxf.from_project = False
                        fxf.save()
                        noti = fxf.logs.create(source=api_request.user, type=19, title="Stage",
                                               organization=fxf.site.project.organization,
                                               project=fxf.site.project,
                                               site=fxf.site,
                                               content_object=fxf,
                                               extra_object=fxf.site,
                                               description='{0} assigned new Stage form  {1} to {2} '.format(
                                                   api_request.user.get_full_name(),
                                                   fxf.xf.title,
                                                   fxf.site.name
                                               ))
                        result = {}
                        result['description'] = noti.description
                        result['url'] = noti.get_absolute_url()
                        ChannelGroup("site-{}".format(fxf.site.id)).send({"text": json.dumps(result)})
                        ChannelGroup("project-{}".format(fxf.site.project.id)).send({"text": json.dumps(result)})



            else:
                # Stage.objects.filter(pk=id).update(**validated_data)
                stage = Stage.objects.get(pk=id)
                for attr, value in validated_data.items():
                    setattr(stage, attr, value)
                stage.save()
                for order, sub_stage_data in enumerate(sub_stages_datas):
                    old_substage = sub_stage_data.get('id', False)
                    if old_substage:
                        sub_id = sub_stage_data.pop('id')
                        fxf = sub_stage_data.pop('stage_forms')
                        sub_stage_data.update({'stage':stage,'order':order+1})
                        sub_stage = Stage.objects.get(pk=sub_id)
                        for attr, value in sub_stage_data.items():
                            setattr(sub_stage, attr, value)
                        sub_stage.save()

                        old_fsxf = sub_stage.stage_forms
                        old_xf = old_fsxf.xf

                        xf = fxf.get('xf')
                        default_submission_status = fxf.get('default_submission_status')
                        xf_id = xf.get('id')

                        if old_xf.id  != xf_id:
                            # xform changed history and mew fsf
                            old_fsxf.is_deployed = False
                            old_fsxf.is_deleted = True
                            old_fsxf.stage=None
                            old_fsxf.save()
                            #create new fieldsight form
                            if stage.project:
                                FieldSightXF.objects.create(xf_id=xf_id, site=stage.site, project=stage.project,
                                                            is_staged=True, stage=sub_stage, default_submission_status=default_submission_status)
                            else:
                                FieldSightXF.objects.create(xf_id=xf_id, site=stage.site, project=stage.project,
                                                            is_staged=True, stage=sub_stage,from_project=False, default_submission_status=default_submission_status)

                            # org = stage.project.organization if stage.project else stage.site.project.organization
                            # desc = "deleted form of stage {} substage {} by {}".format(stage.name, sub_stage.name,
                            #                                                            self.context['request'].user.username)
                            # noti = old_fsxf.logs.create(source=self.context['request'].user, type=1, title="form Deleted",
                            #         organization=org, description=desc)
                            # result = {}
                            # result['description'] = desc
                            # result['url'] = noti.get_absolute_url()
                            # ChannelGroup("notify-{}".format(org.id)).send({"text": json.dumps(result)})
                            # ChannelGroup("notify-0").send({"text": json.dumps(result)})

                        #     notify mobile and web

                    #     if form change update fxf object's xf
                    else:
                        fxf = sub_stage_data.pop('stage_forms')
                        xf = fxf.get('xf')
                        default_submission_status = fxf.get('default_submission_status')
                        xf_id = xf.get('id')
                        # fxf_id = fxf.get('id')
                        sub_stage_data.pop('id')

                        sub_stage_data.update({'stage':stage, 'order':order+1})
                        sub_stage_obj = Stage.objects.create(**sub_stage_data)
                        if stage.project:
                            FieldSightXF.objects.create(xf_id=xf_id,site=stage.site, project=stage.project,
                                                        is_staged=True, stage=sub_stage_obj, default_submission_status=default_submission_status)
                        else:
                            FieldSightXF.objects.create(xf_id=xf_id, site=stage.site, project=stage.project,
                                                        is_staged=True, stage=sub_stage_obj,from_project=False, default_submission_status=default_submission_status)
            return stage
Example #6
0
    def perform_create(self, serializer):
        # from rest_framework.exceptions import ValidationError

        data = self.request.data

        # if "form" not in data:
        #     raise ValidationError({
        #         "form": "No Form Selected ",
        #     })
        # if data.has_key('site'):
        #     if FieldSightXF.objects.filter(xf=data["form"], is_scheduled=True, site=data["site"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })
        #     if FieldSightXF.objects.filter(xf=data["form"],is_scheduled=True, project=data["project"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })

        schedule = serializer.save()

        fxf = FieldSightXF(xf_id=data["xf"],
                           is_scheduled=True,
                           schedule=schedule,
                           site=schedule.site,
                           project=schedule.project,
                           default_submission_status=data.get(
                               'default_submission_status', 0))
        if data.has_key("site"):
            fxf.is_deployed = True
            fxf.from_project = False
            fxf.save()
            noti = fxf.logs.create(
                source=self.request.user,
                type=19,
                title="Schedule",
                organization=fxf.site.project.organization,
                project=fxf.site.project,
                site=fxf.site,
                content_object=fxf,
                extra_object=fxf.site,
                extra_message='{0} form {1}'.format(fxf.form_type(),
                                                    fxf.xf.title),
                description='{0} assigned new Schedule form  {1} to {2} '.
                format(self.request.user.get_full_name(), fxf.xf.title,
                       fxf.site.name))

        else:
            fxf.save()
            noti = fxf.logs.create(
                source=self.request.user,
                type=18,
                title="Schedule",
                organization=fxf.project.organization,
                project=fxf.project,
                content_object=fxf,
                extra_object=fxf.project,
                extra_message='{0} form {1}'.format(fxf.form_type(),
                                                    fxf.xf.title),
                description='{0} assigned new Schedule form  {1} to {2} '.
                format(self.request.user.get_full_name(), fxf.xf.title,
                       fxf.project.name))
Example #7
0
    def create(self, validated_data):
        id = self.context['request'].data.get('id', False)
        api_request = self.context['request']
        with transaction.atomic():
            sub_stages_datas = self.context['request'].data.get('parent')
            if not id:
                stage = Stage.objects.create(**validated_data)
                for order, ss in enumerate(sub_stages_datas):
                    ss.pop('id')
                    stage_forms_dict = ss.pop('stage_forms')
                    xf_id = stage_forms_dict['xf']['id']
                    ss.update({'stage': stage, 'order': order + 1})
                    default_submission_status = stage_forms_dict[
                        'default_submission_status']
                    sub_stage_obj = Stage.objects.create(**ss)
                    fxf = FieldSightXF(
                        xf_id=xf_id,
                        site=stage.site,
                        project=stage.project,
                        is_staged=True,
                        stage=sub_stage_obj,
                        default_submission_status=default_submission_status)
                    fxf.save()
                    if stage.project:
                        noti = fxf.logs.create(
                            source=api_request.user,
                            type=18,
                            title="Stage",
                            organization=fxf.project.organization,
                            project=fxf.project,
                            content_object=fxf,
                            extra_object=fxf.project,
                            description=
                            '{0} assigned new Stage form  {1} to {2} '.format(
                                api_request.user.get_full_name(), fxf.xf.title,
                                fxf.project.name))
                    else:
                        fxf.from_project = False
                        fxf.save()
                        noti = fxf.logs.create(
                            source=api_request.user,
                            type=19,
                            title="Stage",
                            organization=fxf.site.project.organization,
                            project=fxf.site.project,
                            site=fxf.site,
                            content_object=fxf,
                            extra_object=fxf.site,
                            description=
                            '{0} assigned new Stage form  {1} to {2} '.format(
                                api_request.user.get_full_name(), fxf.xf.title,
                                fxf.site.name))

            else:
                # Stage.objects.filter(pk=id).update(**validated_data)
                stage = Stage.objects.get(pk=id)
                for attr, value in validated_data.items():
                    setattr(stage, attr, value)
                stage.save()
                for order, sub_stage_data in enumerate(sub_stages_datas):
                    old_substage = sub_stage_data.get('id', False)
                    if old_substage:
                        sub_id = sub_stage_data.pop('id')
                        fxf = sub_stage_data.pop('stage_forms')
                        sub_stage_data.update({
                            'stage': stage,
                            'order': order + 1
                        })
                        sub_stage = Stage.objects.get(pk=sub_id)
                        for attr, value in sub_stage_data.items():
                            setattr(sub_stage, attr, value)
                        sub_stage.save()

                        old_fsxf = sub_stage.stage_forms
                        old_xf = old_fsxf.xf

                        xf = fxf.get('xf')
                        default_submission_status = fxf.get(
                            'default_submission_status')
                        xf_id = xf.get('id')

                        if old_xf.id != xf_id:
                            # xform changed history and mew fsf
                            old_fsxf.is_deployed = False
                            old_fsxf.is_deleted = True
                            old_fsxf.stage = None
                            old_fsxf.save()
                            #create new fieldsight form
                            if stage.project:
                                FieldSightXF.objects.create(
                                    xf_id=xf_id,
                                    site=stage.site,
                                    project=stage.project,
                                    is_staged=True,
                                    stage=sub_stage,
                                    default_submission_status=
                                    default_submission_status)
                            else:
                                FieldSightXF.objects.create(
                                    xf_id=xf_id,
                                    site=stage.site,
                                    project=stage.project,
                                    is_staged=True,
                                    stage=sub_stage,
                                    from_project=False,
                                    default_submission_status=
                                    default_submission_status)
                    else:
                        fxf = sub_stage_data.pop('stage_forms')
                        xf = fxf.get('xf')
                        default_submission_status = fxf.get(
                            'default_submission_status')
                        xf_id = xf.get('id')
                        # fxf_id = fxf.get('id')
                        sub_stage_data.pop('id')

                        sub_stage_data.update({
                            'stage': stage,
                            'order': order + 1
                        })
                        sub_stage_obj = Stage.objects.create(**sub_stage_data)
                        if stage.project:
                            FieldSightXF.objects.create(
                                xf_id=xf_id,
                                site=stage.site,
                                project=stage.project,
                                is_staged=True,
                                stage=sub_stage_obj,
                                default_submission_status=
                                default_submission_status)
                        else:
                            FieldSightXF.objects.create(
                                xf_id=xf_id,
                                site=stage.site,
                                project=stage.project,
                                is_staged=True,
                                stage=sub_stage_obj,
                                from_project=False,
                                default_submission_status=
                                default_submission_status)
            return stage
    def post(self, request, pk, format=None):
        team_ids = request.data.get('team_ids', None)
        team_id = request.data.get('team_id', None)

        if team_ids:
            """
                Add teams in super organization
            """
            Organization.objects.filter(id__in=team_ids).update(parent_id=pk)

            projects = Project.objects.filter(organization__id__in=team_ids)
            library_forms = OrganizationFormLibrary.objects.filter(organization=pk)
            fsxf_list = []
            for project in projects:
                for obj in library_forms:
                    if obj.form_type == 0:
                        fsxf = FieldSightXF(xf=obj.xf, project=project,
                                            is_deployed=True,
                                            default_submission_status=obj.default_submission_status,
                                            organization_form_lib=obj
                                            )
                        fsxf_list.append(fsxf)
                    else:
                        scheduled_obj = Schedule.objects. \
                            create(project=project, date_range_start=obj.date_range_start,
                                   date_range_end=obj.date_range_end,
                                   schedule_level_id=obj.schedule_level_id, frequency=obj.frequency,
                                   month_day=obj.month_day,
                                   organization_form_lib=obj
                                   )
                        scheduled_obj.selected_days.add(*obj.selected_days.values_list('id', flat=True))
                        scheduled_obj.save()
                        scheduled_fxf = FieldSightXF(xf=obj.xf, project=project, is_deployed=True,
                                                     is_scheduled=True,
                                                     default_submission_status=obj.default_submission_status,
                                                     schedule=scheduled_obj,
                                                     organization_form_lib=obj
                                                     )
                        fsxf_list.append(scheduled_fxf)

            FieldSightXF.objects.bulk_create(fsxf_list)
            selected_teams_qs = Organization.objects.filter(parent_id=pk)
            selected_teams = TeamSerializer(selected_teams_qs, many=True).data
            return Response(status=status.HTTP_200_OK, data=selected_teams)

        elif team_id:
            """
                Remove team from super organization
            """
            org = SuperOrganization.objects.get(id=pk)
            task_obj = CeleryTaskProgress.objects.create(user=request.user, task_type=29,
                                                         content_object=org)
            if task_obj:
                task = remove_forms_instances.delay(None, task_obj.id, team_id, pk)
                task_obj.task_id = task.id
                task_obj.save()

            return Response(status=status.HTTP_200_OK, data={'detail': 'successfully removed.'})

        else:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail': 'team_ids or team_id '
                                                                                'field is required.'})
    def perform_create(self, serializer):
        # from rest_framework.exceptions import ValidationError

        data = self.request.data

        # if "form" not in data:
        #     raise ValidationError({
        #         "form": "No Form Selected ",
        #     })
        # if data.has_key('site'):
        #     if FieldSightXF.objects.filter(xf=data["form"], is_scheduled=True, site=data["site"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })
        #     if FieldSightXF.objects.filter(xf=data["form"],is_scheduled=True, project=data["project"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })

        schedule = serializer.save()

        fxf = FieldSightXF(xf_id=data["xf"],
                           is_scheduled=True,
                           schedule=schedule,
                           site=schedule.site,
                           project=schedule.project)
        if data.has_key("site"):
            fxf.is_deployed = True
            noti = fxf.logs.create(
                source=self.request.user,
                type=19,
                title="Schedule",
                organization=fxf.project.organization,
                project=fxf.project,
                site=fxf.site,
                content_object=fxf.site,
                extra_message='{0} form {1}'.format(fxf.form_type(),
                                                    fxf.xf.title),
                description='{0} assigned new Schedule form  {1} to {2} '.
                format(self.request.user.get_full_name(), fxf.xf.title,
                       fxf.site.name))
            result = {}
            result['description'] = noti.description
            result['url'] = noti.get_absolute_url()
            ChannelGroup("site-{}".format(fxf.site.id)).send(
                {"text": json.dumps(result)})
            ChannelGroup("project-{}".format(fxf.site.project.id)).send(
                {"text": json.dumps(result)})
        else:
            noti = fxf.logs.create(
                source=self.request.user,
                type=18,
                title="Schedule",
                organization=fxf.project.organization,
                project=fxf.project,
                content_object=fxf.project,
                extra_message='{0} form {1}'.format(fxf.form_type(),
                                                    fxf.xf.title),
                description='{0} assigned new Schedule form  {1} to {2} '.
                format(self.request.user.get_full_name(), fxf.xf.title,
                       fxf.project.name))
            result = {}
            result['description'] = noti.description
            result['url'] = noti.get_absolute_url()
            # ChannelGroup("site-{}".format(fxf.site.id)).send({"text": json.dumps(result)})
            ChannelGroup("project-{}".format(fxf.project.id)).send(
                {"text": json.dumps(result)})
        fxf.save()