mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-03 09:48:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1df3be234 |
No files matched your search
@@ -1330,11 +1330,6 @@ class SavedViewFilterRuleSerializer(serializers.ModelSerializer[SavedViewFilterR
|
||||
|
||||
class SavedViewSerializer(OwnedObjectSerializer):
|
||||
filter_rules = SavedViewFilterRuleSerializer(many=True)
|
||||
display_fields = serializers.ListField(
|
||||
child=serializers.CharField(),
|
||||
required=False,
|
||||
allow_null=True,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SavedView
|
||||
@@ -1476,13 +1471,11 @@ class SavedViewSerializer(OwnedObjectSerializer):
|
||||
attrs = super().validate(attrs)
|
||||
if "display_fields" in attrs and attrs["display_fields"] is not None:
|
||||
for field in attrs["display_fields"]:
|
||||
# i.e. 'custom_field_' followed by the id of a custom field
|
||||
custom_field = re.fullmatch(
|
||||
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
|
||||
field,
|
||||
)
|
||||
if custom_field:
|
||||
if not CustomField.objects.filter(id=custom_field[1]).exists():
|
||||
if (
|
||||
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field
|
||||
): # i.e. check for 'custom_field_' prefix
|
||||
field_id = int(re.search(r"\d+", field)[0])
|
||||
if not CustomField.objects.filter(id=field_id).exists():
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from documents.models import Tag
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import TagFactory
|
||||
|
||||
|
||||
class TestBulkSelectionRejectsInvalidFilters:
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[{"created__year": "abc"}, {"correspondent__id": "abc"}],
|
||||
)
|
||||
def test_documents_are_not_selected(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
filters: dict[str, str],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Documents exist
|
||||
WHEN:
|
||||
- A bulk delete of all documents is requested with a filter that is invalid
|
||||
THEN:
|
||||
- The response is a 400 and nothing is queued, a filter that is dropped
|
||||
would select every document
|
||||
"""
|
||||
DocumentFactory.create()
|
||||
|
||||
execute = mocker.patch("documents.views.execute_bulk_operation")
|
||||
# A real id, so a request that is wrongly accepted fails the assertions
|
||||
# below instead of failing to render a mock as JSON
|
||||
execute.apply_async.return_value.id = "task-id"
|
||||
response = admin_client.post(
|
||||
"/api/documents/delete/",
|
||||
{"all": True, "filters": filters},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
execute.apply_async.assert_not_called()
|
||||
assert Document.objects.count() == 1
|
||||
|
||||
def test_objects_are_not_selected(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Tags exist
|
||||
WHEN:
|
||||
- A bulk delete of all tags is requested with a filter that is invalid
|
||||
THEN:
|
||||
- The response is a 400 and no tag is deleted
|
||||
"""
|
||||
TagFactory.create()
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/bulk_edit_objects/",
|
||||
{
|
||||
"object_type": "tags",
|
||||
"operation": "delete",
|
||||
"all": True,
|
||||
"filters": {"id": "abc"},
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert Tag.objects.count() == 1
|
||||
|
||||
def test_a_valid_filter_still_selects_its_documents(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two documents
|
||||
WHEN:
|
||||
- A bulk delete of all documents is requested with a valid filter
|
||||
THEN:
|
||||
- Only the matching document is queued
|
||||
"""
|
||||
keep = DocumentFactory.create(title="keep")
|
||||
DocumentFactory.create(title="other")
|
||||
|
||||
execute = mocker.patch("documents.views.execute_bulk_operation")
|
||||
execute.apply_async.return_value.id = "task-id"
|
||||
response = admin_client.post(
|
||||
"/api/documents/delete/",
|
||||
{"all": True, "filters": {"title__iexact": "keep"}},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
queued = execute.apply_async.call_args.kwargs["kwargs"]["document_ids"]
|
||||
assert queued == [keep.pk]
|
||||
@@ -1,82 +0,0 @@
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import CustomField
|
||||
from documents.models import SavedView
|
||||
|
||||
|
||||
class TestSavedViewDisplayFields:
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
pytest.param(["custom_field_abc"], id="no-id"),
|
||||
pytest.param(["custom_field_"], id="empty-id"),
|
||||
pytest.param(["xcustom_field_{id}"], id="prefixed"),
|
||||
pytest.param(["custom_field_{id}x"], id="suffixed"),
|
||||
pytest.param([1], id="not-a-string"),
|
||||
],
|
||||
)
|
||||
def test_malformed_display_fields_are_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
value: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A saved view and a custom field
|
||||
WHEN:
|
||||
- Its display fields are patched to something that names no field
|
||||
THEN:
|
||||
- The response is a 400 and the stored display fields are unchanged
|
||||
"""
|
||||
custom_field = CustomField.objects.create(
|
||||
name="cf",
|
||||
data_type=CustomField.FieldDataType.STRING,
|
||||
)
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
display_fields=["title"],
|
||||
)
|
||||
if isinstance(value, list):
|
||||
value = [
|
||||
item.format(id=custom_field.pk) if isinstance(item, str) else item
|
||||
for item in value
|
||||
]
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"display_fields": value},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
view.refresh_from_db()
|
||||
assert view.display_fields == ["title"]
|
||||
|
||||
def test_a_custom_field_display_name_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
) -> None:
|
||||
custom_field = CustomField.objects.create(
|
||||
name="cf",
|
||||
data_type=CustomField.FieldDataType.STRING,
|
||||
)
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
)
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"display_fields": ["title", f"custom_field_{custom_field.pk}"]},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
+13
-4
@@ -72,6 +72,7 @@ from django.views.decorators.csrf import ensure_csrf_cookie
|
||||
from django.views.decorators.http import condition
|
||||
from django.views.generic import TemplateView
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from django_filters.utils import translate_validation
|
||||
from drf_spectacular.openapi import AutoSchema
|
||||
from drf_spectacular.types import OpenApiTypes
|
||||
from drf_spectacular.utils import OpenApiParameter
|
||||
@@ -3069,11 +3070,15 @@ class DocumentSelectionMixin:
|
||||
root_document__isnull=True,
|
||||
)
|
||||
# orm-filtered docs
|
||||
filtered_documents = DocumentFilterSet(
|
||||
filterset = DocumentFilterSet(
|
||||
data=orm_filters,
|
||||
queryset=permitted_documents,
|
||||
user=user,
|
||||
).qs.distinct()
|
||||
)
|
||||
# .qs silently drops an invalid filter, which would select every document
|
||||
if not filterset.is_valid():
|
||||
raise translate_validation(filterset.errors)
|
||||
filtered_documents = filterset.qs.distinct()
|
||||
# tantivy-filtered docs (if search params provided)
|
||||
search_filtered_ids = self._get_search_document_ids(
|
||||
user=user,
|
||||
@@ -5334,10 +5339,14 @@ class BulkEditObjectsView(PassUserMixin):
|
||||
user_permitted_objects = object_class.objects.filter(
|
||||
id__in=permitted_object_ids(user, object_class, perm_codename),
|
||||
)
|
||||
objs = filterset_class(
|
||||
filterset = filterset_class(
|
||||
data=filters,
|
||||
queryset=user_permitted_objects,
|
||||
).qs
|
||||
)
|
||||
# .qs silently drops an invalid filter, which would select every object
|
||||
if not filterset.is_valid():
|
||||
raise translate_validation(filterset.errors)
|
||||
objs = filterset.qs
|
||||
if object_type == "tags":
|
||||
editable_ids = set(user_permitted_objects.values_list("pk", flat=True))
|
||||
all_ids = set(objs.values_list("pk", flat=True))
|
||||
|
||||
Reference in new issue
Block a user