Skip to content

A community-supported supercharged document management system: scan, index and archive all your documents

Fix: Getting next ASN when no documents have an ASN (#5431)

Trenton H51dd95be3d90
diff --git a/src/documents/tests/test_api_documents.py b/src/documents/tests/test_api_documents.py
index 7b81c8df0..510e2b1b3 100644
--- a/src/documents/tests/test_api_documents.py
+++ b/src/documents/tests/test_api_documents.py
@@ -2051,6 +2051,35 @@ class TestDocumentApi(DirectoriesMixin, DocumentConsumeDelayMixin, APITestCase):
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.content, b"1000")
+ def test_next_asn_no_documents_with_asn(self):
+ """
+ GIVEN:
+ - Existing document, but with no ASN assugned
+ WHEN:
+ - API request to get next ASN
+ THEN:
+ - ASN 1 is returned
+ """
+ user1 = User.objects.create_user(username="test1")
+ user1.user_permissions.add(*Permission.objects.all())
+ user1.save()
+
+ doc1 = Document.objects.create(
+ title="test",
+ mime_type="application/pdf",
+ content="this is a document 1",
+ checksum="1",
+ )
+ doc1.save()
+
+ self.client.force_authenticate(user1)
+
+ resp = self.client.get(
+ "/api/documents/next_asn/",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.content, b"1")
+
class TestDocumentApiV2(DirectoriesMixin, APITestCase):
def setUp(self):
diff --git a/src/documents/views.py b/src/documents/views.py
index 6dd8f3baa..9d44ecbc4 100644
--- a/src/documents/views.py
+++ b/src/documents/views.py
@@ -757,16 +757,12 @@ class UnifiedSearchViewSet(DocumentViewSet):
@action(detail=False, methods=["GET"], name="Get Next ASN")
def next_asn(self, request, *args, **kwargs):
- return Response(
- (
- Document.objects.filter(archive_serial_number__gte=0)
- .order_by("archive_serial_number")
- .last()
- .archive_serial_number
- or 0
- )
- + 1,
+ max_asn = Document.objects.aggregate(
+ Max("archive_serial_number", default=0),
+ ).get(
+ "archive_serial_number__max",
)
+ return Response(max_asn + 1)
class LogViewSet(ViewSet):