Пример #1
0
def _start_curate_post(request):
    """Start curate POST request.

    Args:
        request:

    Returns:

    """
    template_id = str(request.POST["hidden_value"])
    selected_option = request.POST["curate_form"]
    user_id = str(request.user.id)
    if selected_option == "new" or selected_option == "upload":
        if selected_option == "new":
            new_form = users_forms.NewForm(request.POST)
            if new_form.is_valid():
                name = new_form.data["document_name"]
                curate_data_structure = CurateDataStructure(
                    user=user_id, template=template_id, name=name)
            else:
                raise CurateAjaxError(
                    "An error occurred during the validation " +
                    get_form_label())
        else:
            upload_form = users_forms.UploadForm(request.POST, request.FILES)
            if upload_form.is_valid():
                xml_file = request.FILES["file"]
                xml_data = read_xsd_file(xml_file)
                well_formed = is_well_formed_xml(xml_data)
                name = xml_file.name
                if not well_formed:
                    raise CurateAjaxError(
                        "An error occurred during the file upload: the file is "
                        "not well formed XML")
                else:
                    curate_data_structure = CurateDataStructure(
                        user=user_id,
                        template=template_id,
                        name=name,
                        form_string=xml_data,
                    )
            else:
                raise CurateAjaxError(
                    "An error occurred during the validation " +
                    get_form_label())

        curate_data_structure_api.upsert(curate_data_structure, request.user)
    else:
        open_form = users_forms.OpenForm(request.POST)
        curate_data_structure = curate_data_structure_api.get_by_id(
            open_form.data["forms"], request.user)

    url = reverse("core_curate_enter_data", args=(curate_data_structure.id, ))
    return HttpResponse(url)
Пример #2
0
 def test_upsert_own_data_structure_updates_data_structure(self):
     data_structure = self.fixture.data_structure_1
     data_structure.name = "new_name_1"
     mock_user = create_mock_user(self.fixture.data_structure_1.user)
     result = curate_data_structure_api.upsert(data_structure, mock_user)
     self.assertTrue(isinstance(result, CurateDataStructure))
     self.assertTrue(data_structure.name, result.name)
Пример #3
0
 def test_upsert_others_data_structure_as_superuser_updates_data_structure(self):
     data_structure = self.fixture.data_structure_3
     data_structure.name = "new_name_3"
     mock_user = create_mock_user(
         self.fixture.data_structure_1.user, is_staff=True, is_superuser=True
     )
     result = curate_data_structure_api.upsert(data_structure, mock_user)
     self.assertTrue(isinstance(result, CurateDataStructure))
     self.assertTrue(data_structure.name, result.name)
Пример #4
0
def save_form(request):
    """Save the current form in data base. Converts it to XML format first.

    Args:
        request:

    Returns:

    """
    try:
        # get curate data structure
        curate_data_structure_id = request.POST['id']
        curate_data_structure = curate_data_structure_api.get_by_id(
            curate_data_structure_id)

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

        # generate xml data
        xml_data = render_xml(
            curate_data_structure.data_structure_element_root)

        # update curate data structure data
        curate_data_structure.form_string = xml_data

        # save data structure
        curate_data_structure_api.upsert(curate_data_structure)

        # add success message
        message = Message(
            messages.SUCCESS,
            get_form_label().capitalize() + ' saved with success.')

        return HttpResponse(json.dumps({
            'message': message.message,
            'tags': message.tags
        }),
                            content_type='application/json')
    except:
        return HttpResponseBadRequest()
Пример #5
0
def edit_record(request):
    """ Edit a record.

    Args:
        request:

    Returns:
    """
    try:
        data = data_api.get_by_id(request.POST['id'], request.user)
    except DoesNotExist:
        message = Message(
            messages.ERROR, "It seems a " + get_data_label() +
            " is missing. Please refresh the page.")
        return HttpResponseBadRequest(json.dumps({
            'message': message.message,
            'tags': message.tags
        }),
                                      content_type='application/json')

    # Check if the data is locked
    if lock_api.is_object_locked(data.id, request.user):
        message = Message(
            messages.ERROR,
            "The " + get_data_label() + " is locked. You can't edit it.")
        return HttpResponseBadRequest(json.dumps({
            'message': message.message,
            'tags': message.tags
        }),
                                      content_type='application/json')

    try:
        # Check if a curate data structure already exists
        curate_data_structure = curate_data_structure_api.get_by_data_id(
            data.id)
    except DoesNotExist:
        # Create a new curate data structure
        curate_data_structure = CurateDataStructure(
            user=str(request.user.id),
            template=str(data.template.id),
            name=data.title,
            form_string=data.xml_content,
            data=data)
        curate_data_structure = curate_data_structure_api.upsert(
            curate_data_structure)
    except Exception, e:
        message = Message(messages.ERROR, "A problem occurred while editing.")
        return HttpResponseBadRequest(json.dumps({
            'message': message.message,
            'tags': message.tags
        }),
                                      content_type='application/json')
Пример #6
0
 def test_curate_data_structure_upsert_return_data_structure_element(
         self, mock_save):
     # Arrange
     mock_data_structure = CurateDataStructure(user="******",
                                               template=Template(),
                                               name="name")
     mock_save.return_value = mock_data_structure
     mock_user = create_mock_user("1")
     # Act
     result = curate_data_structure_api.upsert(mock_data_structure,
                                               mock_user)
     # Assert
     self.assertIsInstance(result, CurateDataStructure)
Пример #7
0
def save_form(request):
    """Save the current form in data base. Converts it to XML format first.

    Args:
        request:

    Returns:

    """
    try:
        # get curate data structure
        curate_data_structure_id = request.POST["id"]
        curate_data_structure = curate_data_structure_api.get_by_id(
            curate_data_structure_id, request.user)

        # generate xml data
        xml_data = render_xml(
            request, curate_data_structure.data_structure_element_root)

        # update curate data structure data
        curate_data_structure.form_string = xml_data

        # save data structure
        curate_data_structure_api.upsert(curate_data_structure, request.user)

        # add success message
        message = Message(
            messages.SUCCESS,
            get_form_label().capitalize() + " saved with success.")

        return HttpResponse(
            json.dumps({
                "message": message.message,
                "tags": message.tags
            }),
            content_type="application/json",
        )
    except Exception as e:
        return HttpResponseBadRequest(escape(str(e)))
Пример #8
0
    def update(self, instance, validated_data):
        """
        Update and return an existing `CurateDataStructure` instance, given the validated data.
        """
        instance.name = validated_data.get("name", instance.name)
        instance.form_string = validated_data.get("form_string",
                                                  instance.form_string)
        instance.data_structure_element_root = validated_data.get(
            "data_structure_element_root",
            instance.data_structure_element_root)
        instance.data = validated_data.get("data", instance.data)

        return curate_data_structure_api.upsert(instance,
                                                self.context["request"].user)
Пример #9
0
    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})
Пример #10
0
 def create(self, validated_data):
     """
     Create and return a new `CurateDataStructure` instance, given the validated data.
     """
     # Create data
     curate_data_structure = CurateDataStructure(
         user=validated_data["user"],
         name=validated_data["name"],
         template=validated_data["template"],
         form_string=validated_data["form_string"]
         if "form_string" in validated_data else None,
         data=validated_data["data"] if "data" in validated_data else None,
         data_structure_element_root=validated_data[
             "data_structure_element_root"]
         if "data_structure_element_root" in validated_data else None,
     )
     return curate_data_structure_api.upsert(curate_data_structure,
                                             self.context["request"].user)
Пример #11
0
 def test_upsert_data_structure_as_anonymous_user_raises_error(self):
     data_structure = self.fixture.data_structure_1
     data_structure.name = "new_name_1"
     with self.assertRaises(AccessControlError):
         curate_data_structure_api.upsert(data_structure, AnonymousUser())
Пример #12
0
 def test_upsert_others_data_structure_as_user_raises_error(self):
     data_structure = self.fixture.data_structure_1
     data_structure.name = "new_name_1"
     mock_user = create_mock_user(self.fixture.data_structure_3.user)
     with self.assertRaises(AccessControlError):
         curate_data_structure_api.upsert(data_structure, mock_user)
Пример #13
0
    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)},
            )
Пример #14
0
def _start_curate_post(request):
    """Start curate POST request.

    Args:
        request:

    Returns:

    """
    try:
        template_id = str(request.POST['hidden_value'])
        selected_option = request.POST['curate_form']
        user_id = str(request.user.id)
        if selected_option == "new" or selected_option == "upload":
            if selected_option == "new":
                new_form = users_forms.NewForm(request.POST)
                if new_form.is_valid():
                    name = new_form.data['document_name']
                    curate_data_structure = CurateDataStructure(
                        user=user_id, template=template_id, name=name)
                else:
                    raise exceptions.CurateAjaxError(
                        'Error occurred during the validation ' +
                        get_form_label())
            else:
                try:  # check XML data or not?
                    upload_form = users_forms.UploadForm(
                        request.POST, request.FILES)
                    if upload_form.is_valid():
                        xml_file = request.FILES['file']
                        xml_file.seek(
                            0)  # put the cursor at the beginning of the file
                        xml_data = xml_file.read(
                        )  # read the content of the file
                        well_formed = is_well_formed_xml(xml_data)
                        name = xml_file.name
                        if not well_formed:
                            raise exceptions.CurateAjaxError(
                                'Uploaded File is not well formed XML')
                        else:
                            curate_data_structure = CurateDataStructure(
                                user=user_id,
                                template=template_id,
                                name=name,
                                form_string=xml_data)
                    else:
                        raise exceptions.CurateAjaxError(
                            'Error occurred during the validation ' +
                            get_form_label())
                except Exception as e:
                    raise exceptions.CurateAjaxError(
                        'Error during file uploading')

            curate_data_structure_api.upsert(curate_data_structure)
        else:
            open_form = users_forms.OpenForm(request.POST)
            curate_data_structure = curate_data_structure_api.get_by_id(
                open_form.data['forms'])
        url = reverse("core_curate_enter_data",
                      args=(curate_data_structure.id, ))
        return HttpResponse(url)
    except Exception as e:
        raise exceptions.CurateAjaxError(e.message)
Пример #15
0
        request:
        data_ids:
        user_id:

    Returns:
    """
    try:
        list_form = _get_forms(form_ids, request.user.is_superuser,
                               request.user.id)
    except Exception, e:
        return HttpResponseBadRequest(e.message)

    try:
        for form in list_form:
            form.user = user_id
            curate_data_structure_api.upsert(form)
    except Exception, e:
        return HttpResponseBadRequest(e.message)

    return HttpResponse(json.dumps({}), content_type='application/javascript')


# FIXME: fix error message
def _change_owner_record(request, data_ids, user_id):
    """ Change the owner of a record.

    Args:
        request:
        data_ids:
        user_id: