Esempio n. 1
0
    def get(self, request):
        mobile_survey_models = models.MobileSurveyModel.objects.order_by("name")
        mobile_surveys = []
        serializer = JSONSerializer()
        for survey in mobile_survey_models:
            survey.deactivate_expired_survey()
            serialized_survey = serializer.serializeToPython(survey)
            serialized_survey["edited_by"] = {
                "username": survey.lasteditedby.username,
                "first": survey.lasteditedby.first_name,
                "last": survey.lasteditedby.last_name,
                "id": survey.lasteditedby.id,
            }
            serialized_survey["created_by"] = created_by = {
                "username": survey.createdby.username,
                "first": survey.createdby.first_name,
                "last": survey.createdby.last_name,
                "id": survey.createdby.id,
            }
            mobile_surveys.append(serialized_survey)

        context = self.get_context_data(
            mobile_surveys=serializer.serialize(mobile_surveys, sort_keys=False), main_script="views/mobile-survey-manager"
        )

        context["nav"]["title"] = _("Arches Collector Manager")
        context["nav"]["icon"] = "fa-globe"
        context["nav"]["help"] = {"title": _("Arches Collector Manager"), "template": "arches-collector-manager-help"}

        return render(request, "views/mobile-survey-manager.htm", context)
Esempio n. 2
0
    def get(self, request):

        def get_last_login(date):
            result = _("Not yet logged in")
            try:
                result = datetime.strftime(date, '%Y-%m-%d %H:%M')
            except TypeError as e:
                print e
            return result

        identities = []
        for group in Group.objects.all():
            users = group.user_set.all()
            if len(users) > 0:
                groupUsers = [{'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'last_login': get_last_login(user.last_login), 'username': user.username, 'groups': [g.id for g in user.groups.all()], 'group_names': ', '.join([g.name for g in user.groups.all()]) } for user in users]
            identities.append({'name': group.name, 'type': 'group', 'id': group.pk, 'users': groupUsers, 'default_permissions': group.permissions.all()})
        for user in User.objects.filter():
            groups = []
            group_ids = []
            default_perms = []
            for group in user.groups.all():
                groups.append(group.name)
                group_ids.append(group.id)
                default_perms = default_perms + list(group.permissions.all())
            identities.append({'name': user.email or user.username, 'groups': ', '.join(groups), 'type': 'user', 'id': user.pk, 'default_permissions': set(default_perms), 'is_superuser':user.is_superuser, 'group_ids': group_ids, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email})


        mobile_survey_models = models.MobileSurveyModel.objects.order_by('name')

        mobile_surveys, resources = self.get_survey_resources(mobile_survey_models)

        serializer = JSONSerializer()
        context = self.get_context_data(
            mobile_surveys=serializer.serialize(mobile_surveys, sort_keys=False),
            identities=serializer.serialize(identities, sort_keys=False),
            resources=serializer.serialize(resources, sort_keys=False),
            main_script='views/mobile-survey-manager',
        )

        context['nav']['title'] = _('Mobile Survey Manager')
        context['nav']['icon'] = 'fa-server'
        context['nav']['help'] = (_('Mobile Survey Manager'),'help/mobile-survey-manager-help.htm')

        return render(request, 'views/mobile-survey-manager.htm', context)
Esempio n. 3
0
    def get(self, request):
        mobile_survey_models = models.MobileSurveyModel.objects.order_by(
            'name')
        mobile_surveys = []
        serializer = JSONSerializer()
        for survey in mobile_survey_models:
            expired = deactivate_expired_survey(survey)
            serialized_survey = serializer.serializeToPython(survey)
            serialized_survey['expired'] = expired
            if expired is True:
                serialized_survey['active'] = False
            serialized_survey['edited_by'] = {
                'username': survey.lasteditedby.username,
                'first': survey.lasteditedby.first_name,
                'last': survey.lasteditedby.last_name,
                'id': survey.lasteditedby.id
            }
            serialized_survey['created_by'] = created_by = {
                'username': survey.createdby.username,
                'first': survey.createdby.first_name,
                'last': survey.createdby.last_name,
                'id': survey.createdby.id
            }
            mobile_surveys.append(serialized_survey)

        context = self.get_context_data(
            mobile_surveys=serializer.serialize(mobile_surveys,
                                                sort_keys=False),
            main_script='views/mobile-survey-manager',
        )

        context['nav']['title'] = _('Mobile Survey Manager')
        context['nav']['icon'] = 'fa-server'
        context['nav']['help'] = {
            'title': _('Mobile Survey Manager'),
            'template': 'mobile-survey-manager-help',
        }

        return render(request, 'views/mobile-survey-manager.htm', context)
Esempio n. 4
0
    def post(self, request, graphid=None):
        ret = {}
        try:
            if self.action == "import_graph":
                graph_file = request.FILES.get("importedGraph").read()
                graphs = JSONDeserializer().deserialize(graph_file)["graph"]
                ret = GraphImporter.import_graph(graphs)
            else:
                if graphid is not None:
                    graph = Graph.objects.get(graphid=graphid)
                data = JSONDeserializer().deserialize(request.body)

                if self.action == "new_graph":
                    isresource = data[
                        "isresource"] if "isresource" in data else False
                    name = _("New Resource Model") if isresource else _(
                        "New Branch")
                    author = request.user.first_name + " " + request.user.last_name
                    ret = Graph.new(name=name,
                                    is_resource=isresource,
                                    author=author)

                elif self.action == "update_node":
                    old_node_data = graph.nodes.get(uuid.UUID(data["nodeid"]))
                    nodegroup_changed = str(
                        old_node_data.nodegroup_id) != data["nodegroup_id"]
                    updated_values = graph.update_node(data)
                    if "nodeid" in data and nodegroup_changed is False:
                        graph.save(nodeid=data["nodeid"])
                    else:
                        graph.save()
                    ret = JSONSerializer().serializeToPython(graph)
                    ret["updated_values"] = updated_values
                    ret["default_card_name"] = graph.temp_node_name

                elif self.action == "update_node_layer":
                    nodeid = uuid.UUID(str(data.get("nodeid")))
                    node = graph.nodes[nodeid]
                    node.config = data["config"]
                    ret = graph
                    node.save()

                elif self.action == "append_branch":
                    ret = graph.append_branch(data["property"],
                                              nodeid=data["nodeid"],
                                              graphid=data["graphid"])
                    ret = ret.serialize()
                    ret["nodegroups"] = graph.get_nodegroups()
                    ret["cards"] = graph.get_cards()
                    ret["widgets"] = graph.get_widgets()
                    graph.save()

                elif self.action == "append_node":
                    ret = graph.append_node(nodeid=data["nodeid"])
                    graph.save()

                elif self.action == "move_node":
                    ret = graph.move_node(data["nodeid"], data["property"],
                                          data["newparentnodeid"])
                    graph.save()

                elif self.action == "export_branch":
                    clone_data = graph.copy(root=data)
                    clone_data["copy"].slug = None
                    clone_data["copy"].save()
                    ret = {"success": True, "graphid": clone_data["copy"].pk}

                elif self.action == "clone_graph":
                    clone_data = graph.copy()
                    ret = clone_data["copy"]
                    ret.slug = None
                    ret.save()
                    ret.copy_functions(
                        graph, [clone_data["nodes"], clone_data["nodegroups"]])

                elif self.action == "reorder_nodes":
                    json = request.body
                    if json is not None:
                        data = JSONDeserializer().deserialize(json)

                        if "nodes" in data and len(data["nodes"]) > 0:
                            sortorder = 0
                            with transaction.atomic():
                                for node in data["nodes"]:
                                    no = models.Node.objects.get(
                                        pk=node["nodeid"])
                                    no.sortorder = sortorder
                                    no.save()
                                    sortorder = sortorder + 1
                            ret = data

            return JSONResponse(ret)
        except GraphValidationError as e:
            return JSONErrorResponse(e.title, e.message, {"status": "Failed"})
        except ModelInactiveError as e:
            return JSONErrorResponse(e.title, e.message)
        except RequestError as e:
            return JSONErrorResponse(
                _("Elasticsearch indexing error"),
                _("""If you want to change the datatype of an existing node.  
                    Delete and then re-create the node, or export the branch then edit the datatype and re-import the branch."""
                  ),
            )
Esempio n. 5
0
    def post(self, request, graphid=None):
        ret = {}
        try:
            if self.action == 'import_graph':
                graph_file = request.FILES.get('importedGraph').read()
                graphs = JSONDeserializer().deserialize(graph_file)['graph']
                ret = GraphImporter.import_graph(graphs)
            else:
                if graphid is not None:
                    graph = Graph.objects.get(graphid=graphid)
                data = JSONDeserializer().deserialize(request.body)

                if self.action == 'new_graph':
                    isresource = data[
                        'isresource'] if 'isresource' in data else False
                    name = _('New Resource Model') if isresource else _(
                        'New Branch')
                    author = request.user.first_name + ' ' + request.user.last_name
                    ret = Graph.new(name=name,
                                    is_resource=isresource,
                                    author=author)

                elif self.action == 'update_node':
                    updated_values = graph.update_node(data)
                    graph.save()
                    ret = JSONSerializer().serializeToPython(graph)
                    ret['updated_values'] = updated_values

                elif self.action == 'update_node_layer':
                    nodeid = uuid.UUID(str(data.get('nodeid')))
                    node = graph.nodes[nodeid]
                    node.config = data['config']
                    ret = graph
                    node.save()

                elif self.action == 'append_branch':
                    ret = graph.append_branch(data['property'],
                                              nodeid=data['nodeid'],
                                              graphid=data['graphid'])
                    ret = ret.serialize()
                    ret['nodegroups'] = graph.get_nodegroups()
                    ret['cards'] = graph.get_cards()
                    ret['widgets'] = graph.get_widgets()
                    graph.save()

                elif self.action == 'append_node':
                    ret = graph.append_node(nodeid=data['nodeid'])
                    graph.save()

                elif self.action == 'move_node':
                    ret = graph.move_node(data['nodeid'], data['property'],
                                          data['newparentnodeid'])
                    graph.save()

                elif self.action == 'export_branch':
                    clone_data = graph.copy(root=data)
                    clone_data['copy'].save()
                    ret = {'success': True, 'graphid': clone_data['copy'].pk}

                elif self.action == 'clone_graph':
                    clone_data = graph.copy()
                    ret = clone_data['copy']
                    ret.save()
                    ret.copy_functions(
                        graph, [clone_data['nodes'], clone_data['nodegroups']])

                elif self.action == 'reorder_nodes':
                    json = request.body
                    if json is not None:
                        data = JSONDeserializer().deserialize(json)

                        if 'nodes' in data and len(data['nodes']) > 0:
                            sortorder = 0
                            with transaction.atomic():
                                for node in data['nodes']:
                                    no = models.Node.objects.get(
                                        pk=node['nodeid'])
                                    no.sortorder = sortorder
                                    no.save()
                                    sortorder = sortorder + 1
                            ret = data

            return JSONResponse(ret)
        except GraphValidationError as e:
            return JSONResponse(
                {
                    'status': 'false',
                    'success': False,
                    'message': e.message,
                    'title': e.title
                },
                status=500)
Esempio n. 6
0
    def get(self, request):

        def get_last_login(date):
            result = _("Not yet logged in")
            try:
                if date is not None:
                    result = datetime.strftime(date, '%Y-%m-%d %H:%M')
            except TypeError as e:
                print e
            return result

        identities = []
        for group in Group.objects.all():
            users = group.user_set.all()
            if len(users) > 0:
                groupUsers = [{'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'last_login': get_last_login(user.last_login), 'username': user.username, 'groups': [g.id for g in user.groups.all()], 'group_names': ', '.join([g.name for g in user.groups.all()]) } for user in users]
            identities.append({'name': group.name, 'type': 'group', 'id': group.pk, 'users': groupUsers, 'default_permissions': group.permissions.all()})
        for user in User.objects.filter():
            groups = []
            group_ids = []
            default_perms = []
            for group in user.groups.all():
                groups.append(group.name)
                group_ids.append(group.id)
                default_perms = default_perms + list(group.permissions.all())
            identities.append({'name': user.email or user.username, 'groups': ', '.join(groups), 'type': 'user', 'id': user.pk, 'default_permissions': set(default_perms), 'is_superuser':user.is_superuser, 'group_ids': group_ids, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email})

        map_layers = models.MapLayer.objects.all()
        map_markers = models.MapMarker.objects.all()
        map_sources = models.MapSource.objects.all()
        geocoding_providers = models.Geocoder.objects.all()

        mobile_survey_models = models.MobileSurveyModel.objects.order_by('name')
        mobile_surveys, resources = self.get_survey_resources(mobile_survey_models)

        for mobile_survey in mobile_surveys:
            try:
                mobile_survey['datadownloadconfig'] = json.loads(mobile_survey['datadownloadconfig'])
            except TypeError:
                pass
            multipart = mobile_survey['bounds']
            singlepart = GeoUtils().convert_multipart_to_singlepart(multipart)
            mobile_survey['bounds'] = singlepart

        serializer = JSONSerializer()
        context = self.get_context_data(
            map_layers=map_layers,
            map_markers=map_markers,
            map_sources=map_sources,
            geocoding_providers=geocoding_providers,
            mobile_surveys=serializer.serialize(mobile_surveys, sort_keys=False),
            identities=serializer.serialize(identities, sort_keys=False),
            resources=serializer.serialize(resources, sort_keys=False),
            resource_download_limit=settings.MOBILE_DOWNLOAD_RESOURCE_LIMIT,
            main_script='views/mobile-survey-manager',
        )

        context['nav']['title'] = _('Mobile Survey Manager')
        context['nav']['icon'] = 'fa-server'
        context['nav']['help'] = {
            'title': _('Mobile Survey Manager'),
            'template': 'mobile-survey-manager-help',
        }

        return render(request, 'views/mobile-survey-manager.htm', context)
Esempio n. 7
0
    def get(self, request, surveyid):
        def get_history(survey, history):
            sync_log_records = models.MobileSyncLog.objects.order_by(
                '-finished').values().filter(survey=survey)
            resourceedits = models.TileRevisionLog.objects.filter(
                survey=survey).values('resourceid').annotate(
                    Count('tileid', distinct=True))
            if len(sync_log_records) > 0:
                lastsync = datetime.strftime(sync_log_records[0]['finished'],
                                             '%Y-%m-%d %H:%M:%S')
                history['lastsync'] = lastsync
            for entry in sync_log_records:
                history['edits'] = len(resourceedits)
                if entry['user'] not in history['editors']:
                    history['editors'][entry['user']] = {
                        'edits': entry['tilesupdated'],
                        'lastsync': entry['finished']
                    }
                else:
                    history['editors'][
                        entry['user']]['edits'] += entry['tilesupdated']
                    if entry['finished'] > history['editors'][
                            entry['user']]['lastsync']:
                        history['editors'][
                            entry['user']]['lastsync'] = entry['finished']
            for id, editor in iter(history['editors'].items()):
                editor['lastsync'] = datetime.strftime(editor['lastsync'],
                                                       '%Y-%m-%d %H:%M:%S')
            return history

        identities = []
        for group in Group.objects.all():
            users = group.user_set.all()
            if len(users) > 0:
                groupUsers = [{
                    'id':
                    user.id,
                    'first_name':
                    user.first_name,
                    'last_name':
                    user.last_name,
                    'email':
                    user.email,
                    'username':
                    user.username,
                    'groups': [g.id for g in user.groups.all()],
                    'group_names':
                    ', '.join([g.name for g in user.groups.all()])
                } for user in users]
            identities.append({
                'name': group.name,
                'type': 'group',
                'id': group.pk,
                'users': groupUsers,
                'default_permissions': group.permissions.all()
            })
        for user in User.objects.filter():
            groups = []
            group_ids = []
            default_perms = []
            for group in user.groups.all():
                groups.append(group.name)
                group_ids.append(group.id)
                default_perms = default_perms + list(group.permissions.all())
            identities.append({
                'name': user.email or user.username,
                'groups': ', '.join(groups),
                'type': 'user',
                'id': user.pk,
                'default_permissions': set(default_perms),
                'is_superuser': user.is_superuser,
                'group_ids': group_ids,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'email': user.email
            })

        history = {'lastsync': '', 'edits': 0, 'editors': {}}
        map_layers = models.MapLayer.objects.all()
        map_markers = models.MapMarker.objects.all()
        map_sources = models.MapSource.objects.all()
        geocoding_providers = models.Geocoder.objects.all()

        survey_exists = models.MobileSurveyModel.objects.filter(
            pk=surveyid).exists()

        if survey_exists is True:
            survey = MobileSurvey.objects.get(pk=surveyid)
            mobile_survey = survey.serialize()
            history = get_history(survey, history)
            resources = get_survey_resources(mobile_survey)
        else:
            survey = MobileSurvey(
                id=surveyid,
                name=_(''),
                datadownloadconfig={
                    "download": False,
                    "count": 100,
                    "resources": [],
                    "custom": None
                },
                onlinebasemaps=settings.MOBILE_DEFAULT_ONLINE_BASEMAP,
            )
            mobile_survey = survey.serialize()
            mobile_survey['bounds'] = settings.DEFAULT_BOUNDS

        resources = get_survey_resources(mobile_survey)

        try:
            mobile_survey['datadownloadconfig'] = json.loads(
                mobile_survey['datadownloadconfig'])
        except TypeError:
            pass

        try:
            if mobile_survey['bounds']['type'] == 'MultiPolygon':
                multipart = mobile_survey['bounds']
                singlepart = GeoUtils().convert_multipart_to_singlepart(
                    multipart)
                mobile_survey['bounds'] = singlepart
        except TypeError as e:
            pass

        serializer = JSONSerializer()
        context = self.get_context_data(
            map_layers=map_layers,
            map_markers=map_markers,
            map_sources=map_sources,
            history=serializer.serialize(history),
            geocoding_providers=geocoding_providers,
            mobile_survey=serializer.serialize(mobile_survey, sort_keys=False),
            identities=serializer.serialize(identities, sort_keys=False),
            resources=serializer.serialize(resources, sort_keys=False),
            resource_download_limit=mobile_survey['datadownloadconfig']
            ['count'],
            main_script='views/mobile-survey-designer',
        )

        context['nav']['menu'] = True
        context['nav']['title'] = _('Mobile Survey Manager')
        context['nav']['icon'] = 'fa-server'
        context['nav']['help'] = {
            'title': _('Mobile Survey Manager'),
            'template': 'mobile-survey-manager-help',
        }

        return render(request, 'views/mobile-survey-designer.htm', context)
Esempio n. 8
0
    def get(self, request, surveyid):
        def get_history(survey, history):
            sync_log_records = models.MobileSyncLog.objects.order_by("-finished").values().filter(survey=survey)
            resourceedits = (
                models.TileRevisionLog.objects.filter(survey=survey).values("resourceid").annotate(Count("tileid", distinct=True))
            )
            if len(sync_log_records) > 0:
                lastsync = datetime.strftime(sync_log_records[0]["finished"], "%Y-%m-%d %H:%M:%S")
                history["lastsync"] = lastsync
            for entry in sync_log_records:
                history["edits"] = len(resourceedits)
                if entry["userid"] not in history["editors"]:
                    history["editors"][entry["userid"]] = {"lastsync": entry["finished"]}
                else:
                    if entry["finished"] > history["editors"][entry["userid"]]["lastsync"]:
                        history["editors"][entry["userid"]]["lastsync"] = entry["finished"]
            for id, editor in iter(list(history["editors"].items())):
                editor["lastsync"] = datetime.strftime(editor["lastsync"], "%Y-%m-%d %H:%M:%S")
            return history

        identities = []
        for group in Group.objects.all():
            users = group.user_set.all()
            if len(users) > 0:
                groupUsers = [
                    {
                        "id": user.id,
                        "first_name": user.first_name,
                        "last_name": user.last_name,
                        "email": user.email,
                        "username": user.username,
                        "groups": [g.id for g in user.groups.all()],
                        "group_names": ", ".join([g.name for g in user.groups.all()]),
                    }
                    for user in users
                ]
            identities.append(
                {"name": group.name, "type": "group", "id": group.pk, "users": groupUsers, "default_permissions": group.permissions.all()}
            )
        for user in User.objects.filter():
            groups = []
            group_ids = []
            default_perms = []
            for group in user.groups.all():
                groups.append(group.name)
                group_ids.append(group.id)
                default_perms = default_perms + list(group.permissions.all())
            identities.append(
                {
                    "name": user.email or user.username,
                    "groups": ", ".join(groups),
                    "type": "user",
                    "id": user.pk,
                    "default_permissions": set(default_perms),
                    "is_superuser": user.is_superuser,
                    "group_ids": group_ids,
                    "first_name": user.first_name,
                    "last_name": user.last_name,
                    "email": user.email,
                }
            )

        history = {"lastsync": "", "edits": 0, "editors": {}}
        map_layers = models.MapLayer.objects.all()
        map_markers = models.MapMarker.objects.all()
        map_sources = models.MapSource.objects.all()
        geocoding_providers = models.Geocoder.objects.all()

        survey_exists = models.MobileSurveyModel.objects.filter(pk=surveyid).exists()

        if survey_exists is True:
            survey = MobileSurvey.objects.get(pk=surveyid)
            mobile_survey = survey.serialize()
            history = get_history(survey, history)
            resources = get_survey_resources(mobile_survey)
        else:
            survey = MobileSurvey(
                id=surveyid,
                name="",
                datadownloadconfig={"download": False, "count": 100, "resources": [], "custom": None},
                onlinebasemaps=settings.MOBILE_DEFAULT_ONLINE_BASEMAP,
            )
            mobile_survey = survey.serialize()
            mobile_survey["bounds"] = settings.DEFAULT_BOUNDS

        resources = get_survey_resources(mobile_survey)

        try:
            mobile_survey["datadownloadconfig"] = json.loads(mobile_survey["datadownloadconfig"])
        except TypeError:
            pass

        try:
            if mobile_survey["bounds"]["type"] == "MultiPolygon":
                multipart = mobile_survey["bounds"]
                singlepart = GeoUtils().convert_multipart_to_singlepart(multipart)
                mobile_survey["bounds"] = singlepart
        except TypeError as e:
            pass

        serializer = JSONSerializer()
        context = self.get_context_data(
            map_layers=map_layers,
            map_markers=map_markers,
            map_sources=map_sources,
            history=serializer.serialize(history),
            geocoding_providers=geocoding_providers,
            mobile_survey=serializer.serialize(mobile_survey, sort_keys=False),
            identities=serializer.serialize(identities, sort_keys=False),
            resources=serializer.serialize(resources, sort_keys=False),
            resource_download_limit=mobile_survey["datadownloadconfig"]["count"],
            main_script="views/mobile-survey-designer",
        )

        context["nav"]["menu"] = True
        context["nav"]["title"] = _("Arches Collector Manager")
        context["nav"]["icon"] = "fa-globe"
        context["nav"]["help"] = {"title": _("Arches Collector Manager"), "template": "arches-collector-manager-help"}

        return render(request, "views/mobile-survey-designer.htm", context)
Esempio n. 9
0
    def get(self, request):

        def get_last_login(date):
            result = _("Not yet logged in")
            try:
                if date is not None:
                    result = datetime.strftime(date, '%Y-%m-%d %H:%M')
            except TypeError as e:
                print e
            return result

        identities = []
        for group in Group.objects.all():
            users = group.user_set.all()
            if len(users) > 0:
                groupUsers = [{'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'last_login': get_last_login(user.last_login), 'username': user.username, 'groups': [g.id for g in user.groups.all()], 'group_names': ', '.join([g.name for g in user.groups.all()]) } for user in users]
            identities.append({'name': group.name, 'type': 'group', 'id': group.pk, 'users': groupUsers, 'default_permissions': group.permissions.all()})
        for user in User.objects.filter():
            groups = []
            group_ids = []
            default_perms = []
            for group in user.groups.all():
                groups.append(group.name)
                group_ids.append(group.id)
                default_perms = default_perms + list(group.permissions.all())
            identities.append({'name': user.email or user.username, 'groups': ', '.join(groups), 'type': 'user', 'id': user.pk, 'default_permissions': set(default_perms), 'is_superuser':user.is_superuser, 'group_ids': group_ids, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email})

        map_layers = models.MapLayer.objects.all()
        map_markers = models.MapMarker.objects.all()
        map_sources = models.MapSource.objects.all()
        geocoding_providers = models.Geocoder.objects.all()

        mobile_survey_models = models.MobileSurveyModel.objects.order_by('name')
        mobile_surveys, resources = self.get_survey_resources(mobile_survey_models)

        for mobile_survey in mobile_surveys:
            try:
                mobile_survey['datadownloadconfig'] = json.loads(mobile_survey['datadownloadconfig'])
            except TypeError:
                pass
            multipart = mobile_survey['bounds']
            singlepart = GeoUtils().convert_multipart_to_singlepart(multipart)
            mobile_survey['bounds'] = singlepart

        serializer = JSONSerializer()
        context = self.get_context_data(
            map_layers=map_layers,
            map_markers=map_markers,
            map_sources=map_sources,
            geocoding_providers=geocoding_providers,
            mobile_surveys=serializer.serialize(mobile_surveys, sort_keys=False),
            identities=serializer.serialize(identities, sort_keys=False),
            resources=serializer.serialize(resources, sort_keys=False),
            resource_download_limit=settings.MOBILE_DOWNLOAD_RESOURCE_LIMIT,
            main_script='views/mobile-survey-manager',
        )

        context['nav']['title'] = _('Mobile Survey Manager')
        context['nav']['icon'] = 'fa-server'
        context['nav']['help'] = (_('Mobile Survey Manager'),'help/base-help.htm')
        context['help'] = 'mobile-survey-manager-help'


        return render(request, 'views/mobile-survey-manager.htm', context)
Esempio n. 10
0
    def post(self, request, graphid=None):
        ret = {}
        try:
            if self.action == "import_graph":
                graph_file = request.FILES.get("importedGraph").read()
                graphs = JSONDeserializer().deserialize(graph_file)["graph"]
                ret = GraphImporter.import_graph(graphs)
            else:
                if graphid is not None:
                    graph = Graph.objects.get(graphid=graphid)
                data = JSONDeserializer().deserialize(request.body)

                if self.action == "new_graph":
                    isresource = data[
                        "isresource"] if "isresource" in data else False
                    name = _("New Resource Model") if isresource else _(
                        "New Branch")
                    author = request.user.first_name + " " + request.user.last_name
                    ret = Graph.new(name=name,
                                    is_resource=isresource,
                                    author=author)

                elif self.action == "update_node":
                    updated_values = graph.update_node(data)
                    graph.save()
                    ret = JSONSerializer().serializeToPython(graph)
                    ret["updated_values"] = updated_values

                elif self.action == "update_node_layer":
                    nodeid = uuid.UUID(str(data.get("nodeid")))
                    node = graph.nodes[nodeid]
                    node.config = data["config"]
                    ret = graph
                    node.save()

                elif self.action == "append_branch":
                    ret = graph.append_branch(data["property"],
                                              nodeid=data["nodeid"],
                                              graphid=data["graphid"])
                    ret = ret.serialize()
                    ret["nodegroups"] = graph.get_nodegroups()
                    ret["cards"] = graph.get_cards()
                    ret["widgets"] = graph.get_widgets()
                    graph.save()

                elif self.action == "append_node":
                    ret = graph.append_node(nodeid=data["nodeid"])
                    graph.save()

                elif self.action == "move_node":
                    ret = graph.move_node(data["nodeid"], data["property"],
                                          data["newparentnodeid"])
                    graph.save()

                elif self.action == "export_branch":
                    clone_data = graph.copy(root=data)
                    clone_data["copy"].save()
                    ret = {"success": True, "graphid": clone_data["copy"].pk}

                elif self.action == "clone_graph":
                    clone_data = graph.copy()
                    ret = clone_data["copy"]
                    ret.save()
                    ret.copy_functions(
                        graph, [clone_data["nodes"], clone_data["nodegroups"]])

                elif self.action == "reorder_nodes":
                    json = request.body
                    if json is not None:
                        data = JSONDeserializer().deserialize(json)

                        if "nodes" in data and len(data["nodes"]) > 0:
                            sortorder = 0
                            with transaction.atomic():
                                for node in data["nodes"]:
                                    no = models.Node.objects.get(
                                        pk=node["nodeid"])
                                    no.sortorder = sortorder
                                    no.save()
                                    sortorder = sortorder + 1
                            ret = data

            return JSONResponse(ret)
        except GraphValidationError as e:
            return JSONResponse(
                {
                    "status": "false",
                    "success": False,
                    "message": e.message,
                    "title": e.title
                },
                status=500)