Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix: mark a notification read when it is archived (#91590)

Alex Liderc9e8a0dcf299
diff --git a/products/notifications/backend/presentation/views.py b/products/notifications/backend/presentation/views.py
index 0c63b732c27a..eb0875cd51aa 100644
--- a/products/notifications/backend/presentation/views.py
+++ b/products/notifications/backend/presentation/views.py
@@ -1,6 +1,9 @@
+from collections.abc import Sequence
from datetime import datetime
from typing import cast
+from uuid import UUID
+from django.db import transaction
from django.db.models import Exists, OuterRef, QuerySet, Subquery
from django.shortcuts import get_object_or_404
from django.utils.dateparse import parse_datetime
@@ -356,6 +359,23 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
invalidate_unread_count(user.id, self.team.organization_id)
return Response({"updated": len(eligible_ids)})
+ # `Sequence`, not `list`: the viewset defines a `list` action, which shadows the builtin
+ # when this annotation is evaluated in the class body.
+ def _archive_events(self, user: User, event_ids: Sequence[UUID]) -> None:
+ # Archiving takes a notification out of the unread count, so the read state has to follow.
+ # Read and archive are independent tables, so without this an archived notification keeps
+ # `read: false` and the archived list shows it as unread.
+ with transaction.atomic():
+ NotificationArchiveState.objects.bulk_create(
+ [NotificationArchiveState(notification_event_id=eid, user=user) for eid in event_ids],
+ ignore_conflicts=True,
+ )
+ NotificationReadState.objects.bulk_create(
+ [NotificationReadState(notification_event_id=eid, user=user) for eid in event_ids],
+ ignore_conflicts=True,
+ )
+ invalidate_unread_count(user.id, self.team.organization_id)
+
@extend_schema(request=None)
@action(methods=["POST"], detail=True, url_path="archive")
def archive(self, request: Request, **kwargs) -> Response:
@@ -364,8 +384,7 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
user = self._get_user()
event = self._get_recipient_event_or_404()
- NotificationArchiveState.objects.get_or_create(notification_event=event, user=user)
- invalidate_unread_count(user.id, self.team.organization_id)
+ self._archive_events(user, [event.id])
return Response({"status": "ok"})
@validated_request(request_serializer=BulkNotificationIdsRequestSerializer)
@@ -387,9 +406,7 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
).values_list("id", flat=True)
)
if eligible_ids:
- archive_states = [NotificationArchiveState(notification_event_id=eid, user=user) for eid in eligible_ids]
- NotificationArchiveState.objects.bulk_create(archive_states, ignore_conflicts=True)
- invalidate_unread_count(user.id, self.team.organization_id)
+ self._archive_events(user, eligible_ids)
return Response({"updated": len(eligible_ids)})
@extend_schema(request=None)
@@ -402,7 +419,5 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
queryset = self._get_base_queryset().filter(archived=False)
event_ids = list(queryset.values_list("id", flat=True))
if event_ids:
- archive_states = [NotificationArchiveState(notification_event_id=eid, user=user) for eid in event_ids]
- NotificationArchiveState.objects.bulk_create(archive_states, ignore_conflicts=True)
- invalidate_unread_count(user.id, self.team.organization_id)
+ self._archive_events(user, event_ids)
return Response({"updated": len(event_ids)})
diff --git a/products/notifications/backend/tests/test_api.py b/products/notifications/backend/tests/test_api.py
index 5722f4c0de0c..eb56d0063094 100644
--- a/products/notifications/backend/tests/test_api.py
+++ b/products/notifications/backend/tests/test_api.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from django.core.cache import cache
from django.utils import timezone
+from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models import Organization, Team, User
@@ -526,6 +527,43 @@ class TestNotificationsAPI(BaseTest):
for ev in (self.event, a1, a2):
assert NotificationArchiveState.objects.filter(notification_event=ev, user=self.user).exists()
+ @parameterized.expand(
+ [
+ ("detail", "{base}/{id}/archive/", None),
+ ("bulk", "{base}/archive_bulk/", "notification_ids"),
+ ("all", "{base}/archive_all/", None),
+ ]
+ )
+ def test_archive_marks_notification_read(self, _name, path_template, ids_field):
+ event = self._create_notification()
+ base = f"/api/environments/{self.team.id}/notifications"
+ path = path_template.format(base=base, id=event.id)
+ payload = {ids_field: [str(event.id)]} if ids_field else None
+
+ resp = self.client.post(path, payload, format="json") if payload else self.client.post(path)
+
+ assert resp.status_code == 200
+ assert NotificationReadState.objects.filter(notification_event=event, user=self.user).exists()
+
+ def test_archived_notification_serializes_as_read(self):
+ event = self._create_notification()
+ self.client.post(f"/api/environments/{self.team.id}/notifications/{event.id}/archive/")
+
+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/?archived=true")
+
+ row = next(r for r in resp.json()["results"] if r["id"] == str(event.id))
+ assert row["read"] is True
+ assert row["read_at"] is not None
+
+ def test_archive_does_not_mark_read_for_another_user(self):
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ event = self._create_notification()
+ NotificationEvent.objects.filter(pk=event.pk).update(resolved_user_ids=[self.user.id, other_user.id])
+
+ self.client.post(f"/api/environments/{self.team.id}/notifications/{event.id}/archive/")
+
+ assert not NotificationReadState.objects.filter(notification_event=event, user=other_user).exists()
+
def test_archive_is_per_user(self):
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
event = self._create_notification()