📈(backend) capture an event when a comment is created

When a new comment is created, we capture an event related to this comment
creation.
This commit is contained in:
Manuel Raynaud
2026-06-01 17:47:28 +02:00
parent ba1a1d469e
commit 0df2d753c4
3 changed files with 39 additions and 9 deletions
+8 -1
View File
@@ -3206,7 +3206,14 @@ class CommentViewSet(
def perform_create(self, serializer):
"""Attach the request user as the comment author."""
user = self.request.user if self.request.user.is_authenticated else None
serializer.save(user=user)
comment = serializer.save(user=user)
posthog_capture(
PosthogEventName.COMMENT_CREATED,
user,
{"comment_id": str(comment.id), "thread_id": str(comment.thread_id)},
document=self.get_document_or_404(),
)
@drf.decorators.action(
detail=True,
@@ -1,6 +1,7 @@
"""Test API for comments on documents."""
import random
from unittest import mock
from django.contrib.auth.models import AnonymousUser
@@ -8,6 +9,7 @@ import pytest
from rest_framework.test import APIClient
from core import factories, models
from core.utils.analytics import PosthogEventName
pytestmark = pytest.mark.django_db
@@ -184,12 +186,21 @@ def test_create_comment_anonymous_user_public_document():
)
thread = factories.ThreadFactory(document=document)
client = APIClient()
response = client.post(
f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/comments/",
{"body": "test"},
)
with mock.patch("core.api.viewsets.posthog_capture") as mock_capture:
response = client.post(
f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/comments/",
{"body": "test"},
)
assert response.status_code == 201
# The comment creation should be tracked in PostHog
mock_capture.assert_called_once_with(
PosthogEventName.COMMENT_CREATED,
None,
{"comment_id": response.json()["id"], "thread_id": str(thread.id)},
document=document,
)
assert response.json() == {
"id": str(response.json()["id"]),
"body": "test",
@@ -231,12 +242,21 @@ def test_create_comment_authenticated_user_accessible_document():
thread = factories.ThreadFactory(document=document)
client = APIClient()
client.force_login(user)
response = client.post(
f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/comments/",
{"body": "test"},
)
with mock.patch("core.api.viewsets.posthog_capture") as mock_capture:
response = client.post(
f"/api/v1.0/documents/{document.id!s}/threads/{thread.id!s}/comments/",
{"body": "test"},
)
assert response.status_code == 201
# The comment creation should be tracked in PostHog
mock_capture.assert_called_once_with(
PosthogEventName.COMMENT_CREATED,
user,
{"comment_id": response.json()["id"], "thread_id": str(thread.id)},
document=document,
)
assert response.json() == {
"id": str(response.json()["id"]),
"body": "test",
+3
View File
@@ -29,6 +29,9 @@ class PosthogEventName(StrEnum):
# Thread
THREAD_CREATED = "thread_created"
# Comment
COMMENT_CREATED = "comment_created"
# User
USER_LOGIN = "user_login"