Esempio n. 1
0
class StartCurate(View):
    """Start Curate Ajax"""

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            raise_exception=True,
        )
    )
    def get(self, request):
        """Load forms to start curating.

        Args:
           request:

        Returns:

        """
        return curate_ajax.start_curate(request)

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            raise_exception=True,
        )
    )
    def post(self, request):
        """Load forms to start curating.
        Add role to response url.

        Args:
           request:

        Returns:

        """
        response = curate_ajax.start_curate(request)
        if response.status_code == 200:
            role = request.GET.get("role", None)
            response.content = "{0}?role={1}".format(
                response.content.decode("utf-8"), role
            )
        return response
Esempio n. 2
0
class StartCurate(View):
    """Start curate."""
    def __init__(self):
        super(StartCurate, self).__init__()
        self.assets = {
            "js": [
                {
                    "path": "core_curate_app/user/js/select_template.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_registry_app/user/js/start_curate.js",
                    "is_raw": False,
                },
            ],
            "css": ["core_curate_app/user/css/style.css"],
        }
        self.modals = []

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self, request, role):
        """Start curate with role parameter.
        Args:
            request:
            role:

        Returns:
        """
        try:
            # Get custom resources for the current template
            custom_resource = custom_resource_api.get_by_current_template_and_slug(
                role, request=request)
        except exceptions.DoesNotExist:
            custom_resource = None

        context = {
            "template_id":
            version_manager_api.get_active_global_version_manager_by_title(
                REGISTRY_XSD_FILENAME, request=request).current,
            "role":
            role,
            "custom_resource":
            custom_resource,
        }
        return render(
            request,
            "core_curate_app/user/curate.html",
            assets=self.assets,
            modals=self.modals,
            context=context,
        )
Esempio n. 3
0
class SaveQueryView(View):
    fields_to_query_func = None

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_save_query,
            raise_exception=True,
        ))
    def post(self, request):
        """Save a query and update the html display

        Args:
            request:

        Returns:

        """
        form_values = json.loads(request.POST["formValues"])
        template_id = request.POST["templateID"]

        # Check that the user can save a query
        if "_auth_user_id" not in request.session:
            error = "You have to login to save a query."
            return HttpResponseBadRequest(
                error, content_type="application/javascript")

        # Check that the query is valid
        errors = check_query_form(form_values, template_id, request=request)
        if len(errors) == 0:
            try:
                query = self.fields_to_query_func(form_values,
                                                  template_id,
                                                  request=request)
                displayed_query = fields_to_pretty_query(form_values)

                # save the query in the data base
                saved_query = SavedQuery(
                    user_id=str(request.user.id),
                    template=template_api.get(template_id, request=request),
                    query=json.dumps(query),
                    displayed_query=displayed_query,
                )
                saved_query_api.upsert(saved_query)
            except MongoQueryException as e:
                errors = [str(e)]
                return HttpResponseBadRequest(
                    _render_errors(errors),
                    content_type="application/javascript")
        else:
            return HttpResponseBadRequest(
                _render_errors(errors), content_type="application/javascript")

        return HttpResponse(json.dumps({}),
                            content_type="application/javascript")
Esempio n. 4
0
class GetQueryView(View):
    fields_to_query_func = None

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            raise_exception=True))
    def post(self, request):
        """Get a query

        Args:
            request:

        Returns:

        """
        try:
            template_id = request.POST['templateID']
            query_id = request.POST['queryID']
            form_values = json.loads(request.POST['formValues'])

            # save current query builder in session to restore it when coming back to the page
            query_form = request.POST['queryForm']
            request.session['savedQueryFormExplore'] = query_form

            errors = check_query_form(form_values, template_id)
            query_object = query_api.get_by_id(query_id)
            if len(query_object.data_sources) == 0:
                errors.append("Please select at least 1 data source.")

            if len(errors) == 0:
                query_content = self.fields_to_query_func(
                    form_values, template_id)
                query_object.content = json.dumps(query_content)
                query_api.upsert(query_object)
            else:
                return HttpResponseBadRequest(
                    _render_errors(errors),
                    content_type='application/javascript')

            return HttpResponse(json.dumps({}),
                                content_type='application/javascript')
        except exceptions.ModelError:
            return HttpResponseBadRequest(
                'Invalid input.', content_type='application/javascript')
        except Exception:
            return HttpResponseBadRequest(
                'An unexpected error occurred.',
                content_type='application/javascript')
class ResultQueryExampleRedirectView(ResultQueryRedirectView):
    model_name = PersistentQueryExample.__name__
    object_name = "persistent_query_example"
    redirect_url = "core_explore_example_results"

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self, request, *args, **kwargs):
        return super(ResultQueryExampleRedirectView,
                     self).get(self, request, *args, **kwargs)

    @staticmethod
    def _get_persistent_query_by_id(persistent_query_id, user):
        return persistent_query_example_api.get_by_id(persistent_query_id,
                                                      user)

    @staticmethod
    def _get_persistent_query_by_name(persistent_query_name, user):
        return persistent_query_example_api.get_by_name(
            persistent_query_name, user)

    @staticmethod
    def get_url_path():
        return reverse(
            ResultQueryExampleRedirectView.redirect_url,
            kwargs={
                "template_id": "template_id",
                "query_id": "query_id"
            },
        ).split("results")[0]

    @staticmethod
    def _get_reversed_url(query):
        return reverse(
            ResultQueryExampleRedirectView.redirect_url,
            kwargs={
                "template_id": query.templates[0].id,
                "query_id": query.id
            },
        )

    @staticmethod
    def _get_reversed_url_if_failed():
        return reverse("core_explore_example_index")
class SuggestionsKeywordSearchView(View):
    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_keyword_content_type,
            permission=rights.explore_keyword_access,
            login_url=reverse_lazy("core_main_app_login")))
    def post(self, request, *args, **kwargs):
        """ POST

        Args:
            request:
            *args:
            **kwargs:

        Returns:

        """
        suggestions = []
        search_form = KeywordForm(data=request.POST)
        keywords = request.POST.get('term')

        if search_form.is_valid():
            try:
                # get form values
                query_id = search_form.cleaned_data.get('query_id', None)
                global_templates = search_form.cleaned_data.get(
                    'global_templates', [])
                user_templates = search_form.cleaned_data.get(
                    'user_templates', [])

                # get all template version manager ids
                template_version_manager_ids = global_templates + user_templates

                # from ids, get all version manager
                version_manager_list = version_manager_api.get_by_id_list(
                    template_version_manager_ids)

                # from all version manager, build a list of all version (template)
                template_ids = []
                map(lambda x: template_ids.extend(x.versions),
                    version_manager_list)

                if query_id is not None and keywords is not None:
                    # get query
                    query = query_api.get_by_id(query_id)

                    # Check the selected data sources
                    if check_data_source(query):

                        # Prepare query
                        query = self._get_query_prepared(
                            keywords, query, request, template_ids)

                        # Send query
                        dict_results = send(request, query,
                                            len(query.data_sources) - 1, 1)

                        if dict_results['count'] > 0:
                            self._extract_suggestion_from_results(
                                dict_results, keywords, suggestions)

            except Exception, e:
                logger.error("Exception while generating suggestions: " +
                             e.message)

        return HttpResponse(json.dumps({'suggestions': suggestions}),
                            content_type='application/javascript')
Esempio n. 7
0
class GetQueryView(View):
    fields_to_query_func = None

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            raise_exception=True,
        ))
    def post(self, request):
        """Get a query

        Args:
            request:

        Returns:

        """
        try:
            template_id = request.POST["templateID"]
            query_id = request.POST["queryID"]
            form_values = (json.loads(request.POST["formValues"])
                           if "formValues" in request.POST else None)
            order_by_field = request.POST["orderByField"].strip()
            order_by_field_array = order_by_field.split(";")

            # save current query builder in session to restore it when coming
            # back to the page
            if "queryForm" in request.POST:
                query_form = request.POST["queryForm"]
                request.session["savedQueryFormExplore"] = query_form

            errors = []
            query_object = query_api.get_by_id(query_id, request.user)
            # set the data-sources sorting value according to the POST request field
            for data_sources_index in range(len(query_object.data_sources)):
                # updating only the existing data-sources (the new data-source already got
                # the default filter value)
                if data_sources_index in range(0, len(order_by_field_array)):
                    query_object.data_sources[
                        data_sources_index].order_by_field = order_by_field_array[
                            data_sources_index]
            if len(query_object.data_sources) == 0:
                errors.append("Please select at least 1 data source.")

            if len(errors) == 0 and form_values:
                errors.append(
                    check_query_form(form_values, template_id,
                                     request=request))
                query_content = self.fields_to_query_func(form_values,
                                                          template_id,
                                                          request=request)
                query_object.content = json.dumps(query_content)
            elif len(errors) > 0:
                return HttpResponseBadRequest(
                    _render_errors(errors),
                    content_type="application/javascript")

            query_api.upsert(query_object, request.user)

            return HttpResponse(json.dumps({}),
                                content_type="application/javascript")
        except exceptions.ModelError:
            return HttpResponseBadRequest(
                "Invalid input.", content_type="application/javascript")
        except Exception as e:
            return HttpResponseBadRequest(
                "An unexpected error occurred: %s" % escape(str(e)),
                content_type="application/javascript",
            )
Esempio n. 8
0
class SelectFieldsView(View):
    build_query_url = 'core_explore_example_build_query'
    load_form_url = 'core_explore_example_load_form'
    generate_element_url = 'core_explore_example_generate_element'
    remove_element_url = 'core_explore_example_remove_element'
    generate_choice_url = 'core_explore_example_generate_choice'

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self, request, template_id, *args, **kwargs):
        """Loads view to customize exploration tree

        Args:
            request:
            template_id:

        Returns:

        """
        try:
            # Set the assets
            assets = {
                "js": [
                    {
                        "path": 'core_main_app/common/js/XMLTree.js',
                        "is_raw": False
                    },
                    {
                        "path": "core_parser_app/js/autosave.js",
                        "is_raw": False
                    },
                    {
                        "path": "core_parser_app/js/autosave_checkbox.js",
                        "is_raw": False
                    },
                    {
                        "path": "core_parser_app/js/autosave.raw.js",
                        "is_raw": True
                    },
                    {
                        "path": "core_parser_app/js/buttons.js",
                        "is_raw": False
                    },
                    {
                        "path":
                        "core_explore_example_app/user/js/buttons.raw.js",
                        "is_raw": True
                    },
                    {
                        "path": "core_parser_app/js/modules.js",
                        "is_raw": False
                    },
                    {
                        "path": "core_parser_app/js/choice.js",
                        "is_raw": False
                    },
                    {
                        "path":
                        "core_explore_example_app/user/js/choice.raw.js",
                        "is_raw": True
                    },
                    {
                        "path":
                        "core_explore_example_app/user/js/select_fields.js",
                        "is_raw": False
                    },
                    {
                        "path":
                        "core_explore_example_app/user/js/select_fields.raw.js",
                        "is_raw": True
                    },
                ],
                "css": [
                    'core_explore_example_app/user/css/xsd_form.css',
                    'core_explore_example_app/user/css/style.css'
                ]
            }

            template = template_api.get(template_id)
            # get data structure
            data_structure = explore_data_structure_api.create_and_get_explore_data_structure(
                template, request.user.id)
            root_element = data_structure.data_structure_element_root

            # renders the form
            xsd_form = render_form(request, root_element)

            # Set the context
            context = {
                "template_id": template_id,
                "build_query_url": self.build_query_url,
                "load_form_url": self.load_form_url,
                "generate_element_url": self.generate_element_url,
                "remove_element_url": self.remove_element_url,
                "generate_choice_url": self.generate_choice_url,
                "data_structure_id": str(data_structure.id),
                "xsd_form": xsd_form
            }

            return render(request,
                          'core_explore_example_app/user/select_fields.html',
                          assets=assets,
                          context=context)
        except Exception, e:
            return render(request,
                          'core_explore_example_app/user/errors.html',
                          assets={},
                          context={'errors': e.message})
Esempio n. 9
0
class EnterDataView(View):
    def __init__(self):
        super(EnterDataView, self).__init__()
        self.assets = {
            "js": [
                {
                    "path": "core_main_app/common/js/debounce.js",
                    "is_raw": False
                },
                {
                    "path": "core_main_app/common/js/elementViewport.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/enter_data.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/enter_data.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/modules.js",
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/modules.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_main_app/common/js/XMLTree.js",
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/autosave.js",
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/autosave.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/buttons.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/buttons.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/choice.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/choice.raw.js",
                    "is_raw": True
                },
            ],
            "css": [
                "core_curate_app/user/css/common.css",
                "core_curate_app/user/css/xsd_form.css",
                "core_parser_app/css/use.css",
            ],
        }

        if ENABLE_XML_ENTITIES_TOOLTIPS:
            self.assets["js"].append({
                "path": "core_curate_app/user/js/xml_entities_tooltip.js",
                "is_raw": False,
            })

        self.modals = [
            "core_curate_app/user/data-entry/modals/cancel-changes.html",
            "core_curate_app/user/data-entry/modals/cancel-form.html",
            "core_curate_app/user/data-entry/modals/clear-fields.html",
            "core_curate_app/user/data-entry/modals/download-options.html",
            "core_curate_app/user/data-entry/modals/save-form.html",
            "core_curate_app/user/data-entry/modals/use-validation.html",
            "core_curate_app/user/data-entry/modals/xml-error.html",
            "core_curate_app/user/data-entry/modals/xml-valid.html",
        ]

    def build_context(self, request, curate_data_structure,
                      reload_unsaved_changes):
        """Build the context of the view

        Args:
            request:
            curate_data_structure:
            reload_unsaved_changes:

        Returns:

        """
        # get xsd string from the template
        template = template_api.get(str(curate_data_structure.template.id),
                                    request=request)
        xsd_string = template.content

        if reload_unsaved_changes:
            # get root element from the data structure
            root_element = curate_data_structure.data_structure_element_root
        else:
            # if form string provided, use it to generate the form
            xml_string = curate_data_structure.form_string

            # get the root element
            root_element = generate_form(
                xsd_string,
                xml_string,
                data_structure=curate_data_structure,
                request=request,
            )

            # save the root element in the data structure
            curate_data_structure_api.update_data_structure_root(
                curate_data_structure, root_element, request.user)

        # renders the form
        xsd_form = render_form(request, root_element)

        return {
            "edit": True if curate_data_structure.data is not None else False,
            "xsd_form": xsd_form,
            "data_structure": curate_data_structure,
        }

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self,
            request,
            curate_data_structure_id,
            reload_unsaved_changes=False):
        """Load view to enter data.

        Args:
            request:
            curate_data_structure_id:
            reload_unsaved_changes:

        Returns:

        """
        curate_data_structure = None
        try:
            # Retrieve CurateDataStructure and lock the object for the current
            # user.
            curate_data_structure = _get_curate_data_structure_by_id(
                curate_data_structure_id, request)

            # Lock from database
            if curate_data_structure.data is not None:
                lock_api.set_lock_object(curate_data_structure.data,
                                         request.user)

            # Check if we need to change the user. Code executed only if the
            # data is unlocked. set_lock_object() raises LockError.
            if str(request.user.id) != curate_data_structure.user:
                curate_data_structure.user = str(request.user.id)
                curate_data_structure = curate_data_structure_api.upsert(
                    curate_data_structure, request.user)

            return render(
                request,
                "core_curate_app/user/data-entry/enter_data.html",
                assets=self.assets,
                context=self.build_context(request, curate_data_structure,
                                           reload_unsaved_changes),
                modals=self.modals,
            )
        except (LockError, AccessControlError, ModelError, DoesNotExist) as ex:
            return render(
                request,
                "core_curate_app/user/errors.html",
                assets={},
                context={"errors": str(ex)},
            )
        except Exception as e:
            try:
                # Unlock from database
                if (curate_data_structure is not None
                        and curate_data_structure.data is not None):
                    lock_api.remove_lock_on_object(curate_data_structure.data,
                                                   request.user)
            except Exception as lock_exc:
                # CurateDataStructure not found, continue search
                logger.warning(
                    "'EnterDataView.get' threw an exception: {0}".format(
                        str(lock_exc)))

            return render(
                request,
                "core_curate_app/user/errors.html",
                assets={},
                context={"errors": str(e)},
            )
Esempio n. 10
0
class IndexView(View):
    api = template_version_manager_api
    get_redirect = 'core_explore_example_app/user/index.html'
    select_object_redirect = "core_explore_example_select_fields"
    build_query_redirect = "core_explore_example_build_query"
    object_name = "template"

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self, request, *args, **kwargs):
        """ Page that allows to select a template to start exploring data

        Args:
            request:

        Returns:

        """
        assets = {"css": ['core_explore_example_app/user/css/style.css']}

        global_active_template_list = self.get_global_active_list()
        user_active_template_list = self.get_user_active_list(request.user.id)

        context = {
            'global_objects': global_active_template_list,
            'user_objects': user_active_template_list,
            'object_name': self.object_name,
            'select_object_redirect': self.select_object_redirect,
            'build_query_redirect': self.build_query_redirect,
        }

        return render(request,
                      self.get_redirect,
                      assets=assets,
                      context=context)

    def get_global_active_list(self):
        """ Get all global version managers.

        Args:

        Returns:
            List of all global version managers

        """
        return self.api.get_active_global_version_manager()

    def get_user_active_list(self, user_id):
        """ Get all active version managers with given user id.

        Args:
            user_id:

        Returns:
            List of all global version managers with given user.

        """
        return self.api.get_active_version_manager_by_user_id(user_id)
Esempio n. 11
0
class BuildQueryView(View):
    build_query_url = 'core_explore_example_build_query'
    get_query_url = 'core_explore_example_get_query'
    save_query_url = 'core_explore_example_save_query'
    results_url = 'core_explore_example_results'
    select_fields_url = 'core_explore_example_select_fields'
    object_name = "template"
    data_sources_selector_template = 'core_explore_common_app/user/selector/data_sources_selector' \
                                     '.html'
    query_builder_interface = 'core_explore_example_app/user/query_builder/initial_form.html'

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self, request, template_id, query_id=None):
        """Page that allows to build and submit queries

        Args:
            request:
            template_id:
            query_id:

        Returns:

        """
        try:
            template = template_api.get(template_id)
            if template is None:
                return render(request,
                              'core_explore_example_app/user/errors.html',
                              assets={},
                              context={
                                  'errors':
                                  "The selected {0} does not exist".format(
                                      self.object_name)
                              })

            # Init variables
            saved_query_form = ""

            try:
                explore_data_structure = explore_data_structure_api.get_by_user_id_and_template_id(
                    str(request.user.id), template_id)
                # If custom fields form present, set it
                custom_form = explore_data_structure.selected_fields_html_tree
            except exceptions.DoesNotExist:
                custom_form = None

            # If new form
            if query_id is None:
                # empty session variables
                request.session['mapCriteriaExplore'] = dict()
                request.session['savedQueryFormExplore'] = ""
                # create new query object
                query = self._create_new_query(request, template)
            else:
                # if not a new form and a query form is present in session
                if 'savedQueryFormExplore' in request.session:
                    saved_query_form = request.session['savedQueryFormExplore']
                query = query_api.get_by_id(query_id)

            # Get saved queries of a user
            if '_auth_user_id' in request.session:
                user_id = request.session['_auth_user_id']
                user_queries = saved_query_api.get_all_by_user_and_template(
                    user_id=user_id, template_id=template_id)
            else:
                user_queries = []

            assets = {"js": self._get_js(), "css": self._get_css()}

            context = {
                'queries': user_queries,
                'template_id': template_id,
                'description': self.get_description(),
                'title': self.get_title(),
                'custom_form': custom_form,
                'query_form': saved_query_form,
                'query_id': str(query.id),
                "build_query_url": self.build_query_url,
                "results_url": self.results_url,
                "get_query_url": self.get_query_url,
                "save_query_url": self.save_query_url,
                "select_fields_url": self.select_fields_url,
                "data_sources_selector_template":
                self.data_sources_selector_template,
                "query_builder_interface": self.query_builder_interface
            }

            modals = [
                "core_explore_example_app/user/modals/custom_tree.html",
                "core_explore_example_app/user/modals/sub_elements_query_builder.html",
                "core_main_app/common/modals/error_page_modal.html",
                "core_explore_example_app/user/modals/delete_all_queries.html",
                "core_explore_example_app/user/modals/delete_query.html"
            ]

            return render(request,
                          'core_explore_example_app/user/build_query.html',
                          assets=assets,
                          context=context,
                          modals=modals)
        except Exception, e:
            return render(request,
                          'core_explore_example_app/user/errors.html',
                          assets={},
                          context={'errors': e.message})
Esempio n. 12
0
class EnterDataView(View):
    def __init__(self):
        super(EnterDataView, self).__init__()
        self.assets = {
            "js": [
                {
                    "path": "core_curate_app/user/js/enter_data.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/enter_data.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/modules.js",
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/modules.raw.js",
                    "is_raw": True
                },
                {
                    "path": 'core_main_app/common/js/XMLTree.js',
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/autosave.js",
                    "is_raw": False
                },
                {
                    "path": "core_parser_app/js/autosave.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/buttons.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/buttons.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_parser_app/js/choice.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/choice.raw.js",
                    "is_raw": True
                },
            ],
            "css": [
                'core_curate_app/user/css/xsd_form.css',
                'core_parser_app/css/use.css'
            ]
        }
        self.modals = [
            'core_curate_app/user/data-entry/modals/cancel-changes.html',
            'core_curate_app/user/data-entry/modals/cancel-form.html',
            'core_curate_app/user/data-entry/modals/clear-fields.html',
            'core_curate_app/user/data-entry/modals/download-options.html',
            'core_curate_app/user/data-entry/modals/save-form.html',
            'core_curate_app/user/data-entry/modals/use-validation.html',
            'core_curate_app/user/data-entry/modals/xml-error.html',
            'core_curate_app/user/data-entry/modals/xml-valid.html',
        ]

    def build_context(self, request, curate_data_structure,
                      reload_unsaved_changes):
        """ Build the context of the view

        Args:
            request:
            curate_data_structure:
            reload_unsaved_changes:

        Returns:

        """
        # get xsd string from the template
        xsd_string = curate_data_structure.template.content

        if reload_unsaved_changes:
            # get root element from the data structure
            root_element = curate_data_structure.data_structure_element_root
        else:
            # if form string provided, use it to generate the form
            xml_string = curate_data_structure.form_string

            # get the root element
            root_element = generate_form(xsd_string, xml_string)

            # save the root element in the data structure
            curate_data_structure_api.update_data_structure_root(
                curate_data_structure, root_element)

        # renders the form
        xsd_form = render_form(request, root_element)

        return {
            "edit": True if curate_data_structure.data is not None else False,
            "xsd_form": xsd_form,
            "data_structure": curate_data_structure,
        }

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self,
            request,
            curate_data_structure_id,
            reload_unsaved_changes=False):
        """Load view to enter data.

        Args:
            request:
            curate_data_structure_id:
            reload_unsaved_changes:

        Returns:

        """
        try:
            # get data structure
            curate_data_structure = _get_curate_data_structure_by_id(
                curate_data_structure_id, request)

            # lock from database
            if curate_data_structure.data is not None:
                lock_api.set_lock_object(curate_data_structure.data,
                                         request.user)

            # Check if we need to change the user.
            # Code executed only if the data is unlocked. set_lock_object() raises LockError.
            if str(request.user.id) != curate_data_structure.user:
                curate_data_structure.user = str(request.user.id)
                curate_data_structure = curate_data_structure_api.upsert(
                    curate_data_structure)

            # Set the context
            context = self.build_context(request, curate_data_structure,
                                         reload_unsaved_changes)

            return render(request,
                          'core_curate_app/user/data-entry/enter_data.html',
                          assets=self.assets,
                          context=context,
                          modals=self.modals)
        except LockError, ler:
            return render(request,
                          'core_curate_app/user/errors.html',
                          assets={},
                          context={'errors': ler.message})
        except Exception, e:
            try:
                # unlock from database
                if curate_data_structure is not None and curate_data_structure.data is not None:
                    lock_api.remove_lock_on_object(curate_data_structure.data,
                                                   request.user)
            except:
                pass

            return render(request,
                          'core_curate_app/user/errors.html',
                          assets={},
                          context={'errors': e.message})
Esempio n. 13
0
class ResultQueryView(ResultsView):
    back_to_query_redirect = "core_explore_example_build_query"
    get_query_url = "core_explore_example_get_query"

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self, request, template_id, query_id):
        """Query results view

        Args:
            request:
            template_id:
            query_id:

        Returns:

        """

        # get query
        query = query_api.get_by_id(query_id, request.user)

        context = {
            "template_id": template_id,
            "query_id": query_id,
            "exporter_app": False,
            "back_to_query_redirect": self.back_to_query_redirect,
            "get_query_url": self.get_query_url,
            "default_date_toggle_value": DEFAULT_DATE_TOGGLE_VALUE,
            "data_sorting_fields": super().build_sorting_context_array(query),
            "default_data_sorting_fields": ",".join(DATA_SORTING_FIELDS),
        }

        if "core_exporters_app" in INSTALLED_APPS:
            query = query_api.get_by_id(query_id, request.user)

            context["exporter_app"] = True
            context["templates_list"] = json.dumps(
                [str(template.id) for template in query.templates])

        return render(
            request,
            "core_explore_example_app/user/results.html",
            assets=self.assets,
            modals=self.modals,
            context=context,
        )

    def _load_assets(self):
        assets = super()._load_assets()
        extra_assets = {
            "js": [
                {
                    "path":
                    "core_explore_example_app/user/js/refresh_sorting.raw.js",
                    "is_raw": True,
                },
                {
                    "path":
                    "core_explore_example_app/user/js/refresh_sorting.js",
                    "is_raw": False,
                },
                {
                    "path":
                    "core_explore_example_app/user/js/persistent_query.raw.js",
                    "is_raw": True,
                },
            ],
            "css": [],
        }

        assets["js"].extend(extra_assets["js"])
        assets["css"].extend(extra_assets["css"])

        return assets

    def _load_modals(self):
        """Return modals structure

        Returns:

        """
        return super()._load_modals()
Esempio n. 14
0
class BuildQueryView(View):
    build_query_url = "core_explore_example_build_query"
    get_query_url = "core_explore_example_get_query"
    save_query_url = "core_explore_example_save_query"
    results_url = "core_explore_example_results"
    select_fields_url = "core_explore_example_select_fields"
    object_name = "template"
    data_sources_selector_template = (
        "core_explore_common_app/user/selector/data_sources_selector"
        ".html")
    query_builder_interface = (
        "core_explore_example_app/user/query_builder/initial_form.html")

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self, request, template_id, query_id=None):
        """Page that allows to build and submit queries

        Args:
            request:
            template_id:
            query_id:

        Returns:

        """
        try:
            template = template_api.get(template_id, request=request)
            if template is None:
                return render(
                    request,
                    "core_explore_example_app/user/errors.html",
                    assets={},
                    context={
                        "errors":
                        "The selected {0} does not exist".format(
                            self.object_name)
                    },
                )

            # Init variables
            saved_query_form = ""

            try:
                explore_data_structure = (
                    explore_data_structure_api.get_by_user_id_and_template_id(
                        str(request.user.id), template_id))
                # If custom fields form present, set it
                custom_form = explore_data_structure.selected_fields_html_tree
            except exceptions.DoesNotExist:
                custom_form = None

            # If new form
            if query_id is None:
                # empty session variables
                request.session["mapCriteriaExplore"] = dict()
                request.session["savedQueryFormExplore"] = ""
                # create new query object
                query = self._create_new_query(request, template)
            else:
                # if not a new form and a query form is present in session
                if "savedQueryFormExplore" in request.session:
                    saved_query_form = request.session["savedQueryFormExplore"]
                query = query_api.get_by_id(query_id, request.user)

            # Get saved queries of a user
            if "_auth_user_id" in request.session:
                user_id = request.session["_auth_user_id"]
                user_queries = saved_query_api.get_all_by_user_and_template(
                    user_id=user_id, template_id=template_id)
            else:
                user_queries = []

            assets = {"js": self._get_js(), "css": self._get_css()}

            context = {
                "queries": user_queries,
                "template_id": template_id,
                "description": self.get_description(),
                "title": self.get_title(),
                "data_sorting_fields": build_sorting_context_array(query),
                "default_data_sorting_fields": ",".join(DATA_SORTING_FIELDS),
                "custom_form": custom_form,
                "query_form": saved_query_form,
                "query_id": str(query.id),
                "build_query_url": self.build_query_url,
                "results_url": self.results_url,
                "get_query_url": self.get_query_url,
                "save_query_url": self.save_query_url,
                "select_fields_url": self.select_fields_url,
                "data_sources_selector_template":
                self.data_sources_selector_template,
                "query_builder_interface": self.query_builder_interface,
            }

            modals = [
                "core_explore_example_app/user/modals/custom_tree.html",
                "core_explore_example_app/user/modals/sub_elements_query_builder.html",
                "core_main_app/common/modals/error_page_modal.html",
                "core_explore_example_app/user/modals/delete_all_queries.html",
                "core_explore_example_app/user/modals/delete_query.html",
            ]

            return render(
                request,
                "core_explore_example_app/user/build_query.html",
                assets=assets,
                context=context,
                modals=modals,
            )
        except Exception as e:
            return render(
                request,
                "core_explore_example_app/user/errors.html",
                assets={},
                context={"errors": str(e)},
            )

    @staticmethod
    def _create_new_query(request, template):
        """Create a new query
        Args:
            request:
            template:

        """
        # from the template, we get the version manager
        template_version_manager = template_version_manager_api.get_by_version_id(
            str(template.id), request=request)
        # from the version manager, we get all the version
        template_ids = template_api.get_all_accessible_by_id_list(
            template_version_manager.versions, request=request)
        # create query
        query = create_default_query(request, template_ids)
        # then upsert
        return query_api.upsert(query, request.user)

    @staticmethod
    def _get_js():
        return [
            {
                "path": "core_explore_example_app/user/js/build_query.js",
                "is_raw": False,
            },
            {
                "path": "core_explore_example_app/user/js/build_query.raw.js",
                "is_raw": True,
            },
            {
                "path": "core_parser_app/js/autosave.raw.js",
                "is_raw": True
            },
            {
                "path": "core_parser_app/js/choice.js",
                "is_raw": False
            },
            {
                "path": "core_main_app/common/js/modals/error_page_modal.js",
                "is_raw": True,
            },
        ]

    @staticmethod
    def _get_css():
        return [
            "core_explore_common_app/user/css/results.css",
            "core_explore_example_app/user/css/query_builder.css",
            "core_explore_example_app/user/css/xsd_form.css",
        ]

    @staticmethod
    def get_description():
        # FIXME should be in template
        return (
            "Click on a field of the Query Builder to add an element to your query. "
            "The elements selected in the previous step will appear and you will be "
            "able to insert them in the query builder. Click on plus/minus icons to "
            "add/remove criteria. You can save queries to build more complex queries "
            "and you will retrieve them on your next connection. When your query is "
            "done, please click on Submit Query to get XML documents that match the "
            "criteria.")

    @staticmethod
    def get_title():
        return "Query Builder"
Esempio n. 15
0
class KeywordSearchView(View):
    def __init__(self, **kwargs):
        self.assets = self._load_assets()
        self.modals = self._load_modals()

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_keyword_content_type,
            permission=rights.explore_keyword_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self, request, *args, **kwargs):
        """ GET

        Args:
            request:
            *args:
            **kwargs:

        Returns:

        """
        query_id = str(kwargs['query_id']) if 'query_id' in kwargs else None

        # assets / modals / forms
        context = self._get(request, query_id)

        return render(request,
                      'core_explore_keyword_app/user/index.html',
                      assets=self.assets,
                      modals=self.modals,
                      context=context)

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_keyword_content_type,
            permission=rights.explore_keyword_access,
            login_url=reverse_lazy("core_main_app_login")))
    def post(self, request, *args, **kwargs):
        """ POST

        Args:
            request:
            *args:
            **kwargs:

        Returns:

        """

        # assets / modals / forms
        context = self._post(request)

        return render(request,
                      'core_explore_keyword_app/user/index.html',
                      assets=self.assets,
                      modals=self.modals,
                      context=context)

    def _get(self, request, query_id):
        """ Prepare the GET context

        Args:
            user:
            query_id:

        Returns:

        """
        error = None
        display_persistent_query_button = True
        if query_id is None:
            # create query
            query = create_default_query(request, [])
            # upsert the query
            query_api.upsert(query)
            # create keyword form
            # create all data for select values in forms
            keywords_data_form = {
                'query_id': str(query.id),
                'user_id': query.user_id,
            }
        else:
            try:
                # get the query id
                query = query_api.get_by_id(query_id)
                user_id = query.user_id
                # get all keywords back
                query_json = json.loads(query.content)
                keywords = None
                if '$text' in query_json:
                    keywords = query_json['$text']['$search'].replace(
                        " ", ",").replace('"', '')
                # get all version managers
                version_managers = []
                for template in query.templates:
                    version_managers.append(
                        str(version_manager_api.get_from_version(template).id))
                # create all data for select values in forms
                keywords_data_form = {
                    'query_id': str(query.id),
                    'user_id': user_id,
                    'keywords': keywords,
                    'global_templates': version_managers,
                    'user_templates': version_managers
                }
            except Exception, e:
                error = "An unexpected error occurred while loading the query: {}.".format(
                    e.message)
                return {'error': error}

        search_form = KeywordForm(data=keywords_data_form)
        return _format_keyword_search_context(search_form, error, None,
                                              display_persistent_query_button)
Esempio n. 16
0
class ResultQueryView(View):
    back_to_query_redirect = 'core_explore_example_build_query'

    @method_decorator(
        decorators.permission_required(
            content_type=rights.explore_example_content_type,
            permission=rights.explore_example_access,
            login_url=reverse_lazy("core_main_app_login")))
    def get(self, request, template_id, query_id):
        """Query results view

        Args:
            request:
            template_id:
            query_id:

        Returns:

        """
        context = {
            'template_id':
            template_id,
            'query_id':
            query_id,
            'exporter_app':
            False,
            'back_to_query_redirect':
            self.back_to_query_redirect,
            'get_shareable_link_url':
            reverse("core_explore_example_get_persistent_query_url")
        }

        assets = {
            "js": [
                {
                    "path": 'core_explore_common_app/user/js/results.js',
                    "is_raw": False
                },
                {
                    "path": 'core_explore_common_app/user/js/results.raw.js',
                    "is_raw": True
                },
                {
                    "path": 'core_main_app/common/js/XMLTree.js',
                    "is_raw": False
                },
                {
                    "path":
                    'core_main_app/common/js/modals/error_page_modal.js',
                    "is_raw": True
                },
                {
                    "path":
                    'core_explore_common_app/user/js/button_persistent_query.js',
                    "is_raw": False
                },
            ],
            "css": [
                "core_explore_common_app/user/css/query_result.css",
                "core_main_app/common/css/XMLTree.css",
                "core_explore_common_app/user/css/results.css"
            ],
        }

        modals = [
            "core_main_app/common/modals/error_page_modal.html",
            "core_explore_common_app/user/persistent_query/modals/persistent_query_modal.html"
        ]

        if 'core_exporters_app' in INSTALLED_APPS:
            # add all assets needed
            assets['js'].extend([{
                "path":
                'core_exporters_app/user/js/exporters/list/modals/list_exporters_selector.js',
                "is_raw": False
            }])
            # add the modal
            modals.extend([
                "core_exporters_app/user/exporters/list/modals/list_exporters_selector.html"
            ])
            # the modal need all selected template
            query = query_api.get_by_id(query_id)

            context['exporter_app'] = True
            context['templates_list'] = json.dumps(
                [str(template.id) for template in query.templates])

        return render(request,
                      'core_explore_example_app/user/results.html',
                      assets=assets,
                      modals=modals,
                      context=context)
Esempio n. 17
0
    url(r'^generate-choice/(?P<curate_data_structure_id>\w+)$',
        user_ajax.generate_choice,
        name='core_curate_generate_choice'),
    url(r'^generate-element/(?P<curate_data_structure_id>\w+)$',
        user_ajax.generate_element,
        name='core_curate_generate_element'),
    url(r'^remove-element$',
        user_ajax.remove_element,
        name='core_curate_remove_element'),
    url(r'^clear-fields$',
        user_ajax.clear_fields,
        name='core_curate_clear_fields'),
    url(r'^cancel-changes$',
        user_ajax.cancel_changes,
        name='core_curate_cancel_changes'),
    url(r'^cancel-form$',
        user_ajax.cancel_form,
        name='core_curate_cancel_form'),
    url(r'^save-form$', user_ajax.save_form, name='core_curate_save_form'),
    url(r'^save-data$', user_ajax.save_data, name='core_curate_save_data'),
    url(r'^validate-form$',
        user_ajax.validate_form,
        name='core_curate_validate_form'),
    url(r'^view-form/(?P<curate_data_structure_id>\w+)$',
        permission_required(content_type=rights.curate_content_type,
                            permission=rights.curate_access,
                            login_url=reverse_lazy("core_main_app_login"))(
                                common_views.FormView.as_view()),
        name='core_curate_view_form')
]
Esempio n. 18
0
class ViewDataView(View):
    def __init__(self):
        super(ViewDataView, self).__init__()
        self.assets: Dict[str, List[any]] = {
            "js": [
                {
                    "path": "core_curate_app/user/js/view_data.js",
                    "is_raw": False
                },
                {
                    "path": "core_curate_app/user/js/view_data.raw.js",
                    "is_raw": True
                },
                {
                    "path": "core_main_app/common/js/XMLTree.js",
                    "is_raw": False
                },
            ],
            "css": ["core_main_app/common/css/XMLTree.css"],
        }

        self.modals = [
            "core_curate_app/user/data-review/modals/save-error.html",
        ]

    def build_context(self, request, curate_data_structure):
        """Build XML string from CurateDataStructure

        Args:
            request:
            curate_data_structure:

        Returns:
        """
        xml_string = render_xml(
            request, curate_data_structure.data_structure_element_root)

        return {
            "edit": True if curate_data_structure.data is not None else False,
            "xml_string": xml_string,
            "data_structure": curate_data_structure,
        }

    @method_decorator(
        decorators.permission_required(
            content_type=rights.curate_content_type,
            permission=rights.curate_access,
            login_url=reverse_lazy("core_main_app_login"),
        ))
    def get(self, request, curate_data_structure_id):

        try:
            curate_data_structure = _get_curate_data_structure_by_id(
                curate_data_structure_id, request)

            if "core_file_preview_app" in INSTALLED_APPS:
                self.assets["js"].extend([{
                    "path": "core_file_preview_app/user/js/file_preview.js",
                    "is_raw": False,
                }])
                self.assets["css"].append(
                    "core_file_preview_app/user/css/file_preview.css")
                self.modals.append(
                    "core_file_preview_app/user/file_preview_modal.html")

            return render(
                request,
                "core_curate_app/user/data-review/view_data.html",
                assets=self.assets,
                context=self.build_context(request, curate_data_structure),
                modals=self.modals,
            )
        except Exception as e:
            return render(
                request,
                "core_curate_app/user/errors.html",
                assets={},
                context={"errors": str(e)},
            )