(backend) add number of direct accesses related to a document

The "nb_accesses" field was displaying the number of access instances
related to a document or any of its ancestors. Some features on the
frontend require to know how many of these access instances are related
to the document directly.
This commit is contained in:
Samuel Paccoud - DINUM
2025-02-26 09:27:00 +01:00
committed by Manuel Raynaud
parent 20315e9b60
commit 76c01df3ae
11 changed files with 282 additions and 95 deletions

View File

@@ -654,20 +654,39 @@ class Document(MP_Node, BaseModel):
"""Generate a unique cache key for each document."""
return f"document_{self.id!s}_nb_accesses"
@property
def nb_accesses(self):
"""Calculate the number of accesses."""
def get_nb_accesses(self):
"""
Calculate the number of accesses:
- directly attached to the document
- attached to any of the document's ancestors
"""
cache_key = self.get_nb_accesses_cache_key()
nb_accesses = cache.get(cache_key)
if nb_accesses is None:
nb_accesses = DocumentAccess.objects.filter(
document__path=Left(models.Value(self.path), Length("document__path")),
).count()
nb_accesses = (
DocumentAccess.objects.filter(document=self).count(),
DocumentAccess.objects.filter(
document__path=Left(
models.Value(self.path), Length("document__path")
),
document__ancestors_deleted_at__isnull=True,
).count(),
)
cache.set(cache_key, nb_accesses)
return nb_accesses
@property
def nb_accesses_direct(self):
"""Returns the number of accesses related to the document or one of its ancestors."""
return self.get_nb_accesses()[0]
@property
def nb_accesses_ancestors(self):
"""Returns the number of accesses related to the document or one of its ancestors."""
return self.get_nb_accesses()[1]
def invalidate_nb_accesses_cache(self):
"""
Invalidate the cache for number of accesses, including on affected descendants.
@@ -855,6 +874,11 @@ class Document(MP_Node, BaseModel):
self.send_email(subject, [email], context, language)
def delete(self, *args, **kwargs):
"""Invalidate cache for number of accesses when deleting a document."""
super().delete(*args, **kwargs)
self.invalidate_nb_accesses_cache()
@transaction.atomic
def soft_delete(self):
"""
@@ -875,6 +899,7 @@ class Document(MP_Node, BaseModel):
self.ancestors_deleted_at = self.deleted_at = timezone.now()
self.save()
self.invalidate_nb_accesses_cache()
# Mark all descendants as soft deleted
self.get_descendants().filter(ancestors_deleted_at__isnull=True).update(
@@ -909,6 +934,7 @@ class Document(MP_Node, BaseModel):
)
self.ancestors_deleted_at = ancestors_deleted_at
self.save(update_fields=["deleted_at", "ancestors_deleted_at"])
self.invalidate_nb_accesses_cache()
self.get_descendants().exclude(
models.Q(deleted_at__isnull=False)