: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notifications): dispatch approval_requested realtime notifications (#56153)
Yasena70140e8c07a
diff --git a/posthog/approvals/notifications.py b/posthog/approvals/notifications.pyindex 6b3754f12771..a7c374967ece 100644--- a/posthog/approvals/notifications.py+++ b/posthog/approvals/notifications.py@@ -6,13 +6,22 @@ from posthog.email import EmailMessage, is_email_availablefrom posthog.models import Userfrom posthog.utils import absolute_uri+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+)+from products.notifications.backend.facade.enums import NotificationOnlyResourceType+if TYPE_CHECKING:from posthog.approvals.models import Approval, ChangeRequestlogger = get_logger(__name__)-def _get_user_display_name(user: User | None, fallback: str = "A team member") -> str:+def get_user_display_name(user: User | None, fallback: str = "A team member") -> str:"""Get display name for a user, falling back to email or default."""if not user:return fallback@@ -24,6 +33,51 @@ def _build_change_request_url(change_request: "ChangeRequest") -> str:return absolute_uri(f"/project/{change_request.team.project_id}/approvals/{change_request.id}")+def _change_summary(change_request: "ChangeRequest") -> str:+ """Human-readable summary of what is being changed, for notification bodies."""+ description = (change_request.intent_display or {}).get("description")+ return description or change_request.action_key+++def _dispatch_realtime_requested(change_request: "ChangeRequest") -> None:+ """Fan out one in-app notification per approver. Per-iteration try/except so+ one failure does not block notifications for the remaining approvers.+ """+ policy = change_request.get_policy()+ if not policy:+ return+ approver_ids = policy.get_approver_user_ids()+ if not approver_ids:+ return+ requester_name = get_user_display_name(change_request.created_by)+ title = f"{requester_name} needs your sign-off"[:100]+ body = _change_summary(change_request)[:200]+ source_url = f"/project/{change_request.team.project_id}/approvals/{change_request.id}"+ for approver_id in approver_ids:+ try:+ create_notification(+ NotificationData(+ team_id=change_request.team_id,+ notification_type=NotificationType.APPROVAL_REQUESTED,+ priority=Priority.NORMAL,+ title=title,+ body=body,+ target_type=TargetType.USER,+ target_id=str(approver_id),+ resource_type=NotificationOnlyResourceType.APPROVAL,+ resource_id=str(change_request.id),+ source_url=source_url,+ )+ )+ except Exception as e:+ logger.exception(+ "send_approval_requested_notification.realtime_failed",+ change_request_id=str(change_request.id),+ approver_id=str(approver_id),+ error=str(e),+ )++def _send_approval_email(recipient: User,template_name: str,@@ -93,7 +147,7 @@ def send_approval_requested_notification(change_request: "ChangeRequest") -> Nonreturnapprovers = User.objects.filter(id__in=approver_ids)- requester_name = _get_user_display_name(change_request.created_by)+ requester_name = get_user_display_name(change_request.created_by)for approver in approvers:try:@@ -112,6 +166,8 @@ def send_approval_requested_notification(change_request: "ChangeRequest") -> Nonerror=str(e),)+ _dispatch_realtime_requested(change_request)+def send_approval_decision_notification(change_request: "ChangeRequest",@@ -129,7 +185,7 @@ def send_approval_decision_notification(is_approved = approval.decision == "approved"template_name = "approval_approved" if is_approved else "approval_rejected"- approver_name = _get_user_display_name(approval.created_by, fallback="Someone")+ approver_name = get_user_display_name(approval.created_by, fallback="Someone")subject = f"{approver_name} approved your change" if is_approved else "Your change request was declined"try:diff --git a/posthog/approvals/tests/test_notifications.py b/posthog/approvals/tests/test_notifications.pyindex 84f32ba7d3a1..3284926d8853 100644--- a/posthog/approvals/tests/test_notifications.py+++ b/posthog/approvals/tests/test_notifications.py@@ -167,6 +167,85 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):self.assertEqual(mock_send_email.call_count, 2)+class TestRealtimeDispatchOnRequested(TestApprovalNotifications):+ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_dispatches_one_realtime_per_approver(self, _mock_email, mock_create_notification):+ send_approval_requested_notification(self.change_request)++ self.assertEqual(mock_create_notification.call_count, 2)+ target_ids = {call.args[0].target_id for call in mock_create_notification.call_args_list}+ self.assertEqual(target_ids, {str(self.approver.id), str(self.approver2.id)})++ first_data = mock_create_notification.call_args_list[0].args[0]+ self.assertEqual(first_data.notification_type.value, "approval_requested")+ self.assertEqual(first_data.target_type.value, "user")+ self.assertEqual(first_data.team_id, self.change_request.team_id)+ self.assertEqual(first_data.resource_type.value, "approval")+ self.assertEqual(first_data.resource_id, str(self.change_request.id))+ self.assertEqual(first_data.priority.value, "normal")+ self.assertIn("needs your sign-off", first_data.title)+ self.assertEqual(first_data.body, "Update rollout to 50%")+ expected_url = f"/project/{self.change_request.team.project_id}/approvals/{self.change_request.id}"+ self.assertEqual(first_data.source_url, expected_url)++ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_body_falls_back_to_action_key_when_no_description(self, _mock_email, mock_create_notification):+ self.change_request.intent_display = {}+ self.change_request.save()++ send_approval_requested_notification(self.change_request)++ first_data = mock_create_notification.call_args_list[0].args[0]+ self.assertEqual(first_data.body, self.change_request.action_key)++ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_no_realtime_dispatch_when_no_policy(self, _mock_email, mock_create_notification):+ self.policy.delete()++ send_approval_requested_notification(self.change_request)++ mock_create_notification.assert_not_called()++ @patch("posthog.approvals.notifications.create_notification", side_effect=RuntimeError("boom"))+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_realtime_failure_is_swallowed(self, _mock_email, _mock_create):+ # Should not raise — failure is logged and swallowed so email path is not impacted.+ send_approval_requested_notification(self.change_request)++ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_failure_for_one_approver_does_not_block_others(self, _mock_email, mock_create_notification):+ mock_create_notification.side_effect = [RuntimeError("boom"), None]++ send_approval_requested_notification(self.change_request)++ self.assertEqual(mock_create_notification.call_count, 2)+ target_ids = [call.args[0].target_id for call in mock_create_notification.call_args_list]+ self.assertEqual(set(target_ids), {str(self.approver.id), str(self.approver2.id)})++ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_no_realtime_dispatch_when_no_approvers(self, _mock_email, mock_create_notification):+ self.policy.approver_config = {"users": [], "quorum": 1}+ self.policy.save()++ send_approval_requested_notification(self.change_request)++ mock_create_notification.assert_not_called()++ @patch("posthog.approvals.notifications.create_notification")+ @patch("posthog.approvals.notifications._send_approval_email")+ def test_email_failure_does_not_block_realtime(self, mock_email, mock_create_notification):+ mock_email.side_effect = RuntimeError("smtp down")++ send_approval_requested_notification(self.change_request)++ self.assertEqual(mock_create_notification.call_count, 2)++class TestSendApprovalDecisionNotification(TestApprovalNotifications):@patch("posthog.approvals.notifications._send_approval_email")def test_sends_approval_notification(self, mock_send_email):diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 3b88eefb131b..d5462ec031b0 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -9,6 +9,7 @@ class NotificationType(str, Enum):COMMENT_MENTION = "comment_mention"ALERT_FIRING = "alert_firing"ISSUE_ASSIGNED = "issue_assigned"+ APPROVAL_REQUESTED = "approval_requested"class Priority(str, Enum):diff --git a/products/notifications/backend/migrations/0007_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0007_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..ad07a72e0f91--- /dev/null+++ b/products/notifications/backend/migrations/0007_alter_notificationevent_notification_type.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.13 on 2026-05-05 11:27++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0006_alter_notificationevent_notification_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex b0759f082e50..1bf1c5238a6c 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_alter_notificationevent_notification_type+0007_alter_notificationevent_notification_type