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.

feat(error-tracking): gate weekly digest auto-enable by role and add disable command (#59602)

Aleksander Błaszkiewicz1b846c668b5a
diff --git a/products/error_tracking/backend/management/commands/disable_error_tracking_weekly_digest.py b/products/error_tracking/backend/management/commands/disable_error_tracking_weekly_digest.py
new file mode 100644
index 000000000000..172ca1d3f4bb
--- /dev/null
+++ b/products/error_tracking/backend/management/commands/disable_error_tracking_weekly_digest.py
@@ -0,0 +1,169 @@
+"""Disable error tracking weekly digest for specific users.
+
+Admin tool to manually disable the error tracking weekly digest for users,
+identified by email or organization membership.
+
+Usage:
+ # Dry-run for specific user
+ python manage.py disable_error_tracking_weekly_digest --email [email protected] --dry-run
+
+ # Disable for multiple users
+ python manage.py disable_error_tracking_weekly_digest --email [email protected] --email [email protected]
+
+ # Disable for all users in an organization (per-project, scoped to the org's teams only)
+ python manage.py disable_error_tracking_weekly_digest --organization-id 12345
+
+ # Combine email and org filters (union). Users matched by --organization-id are always
+ # disabled per-project for that org's teams, even if also matched via --email.
+ python manage.py disable_error_tracking_weekly_digest --email [email protected] --organization-id 12345
+"""
+
+from typing import Any
+
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from posthog.models import Team
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+
+PROJECT_SETTING_KEY = "error_tracking_weekly_digest_project_enabled"
+GLOBAL_SETTING_KEY = "error_tracking_weekly_digest"
+
+
+class Command(BaseCommand):
+ help = "Disable error tracking weekly digest for users by email or organization membership."
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--email",
+ action="append",
+ default=[],
+ help="User email to disable digest for (repeatable). Disables globally for the user.",
+ )
+ parser.add_argument(
+ "--organization-id",
+ type=str,
+ default=None,
+ help="Disable digest for all users in this organization (UUID). Scoped to the org's projects only.",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show which users would be updated without writing changes.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ emails: list[str] = options["email"]
+ organization_id: str | None = options["organization_id"]
+ dry_run: bool = options["dry_run"]
+
+ if not emails and not organization_id:
+ self.stderr.write(self.style.ERROR("Must provide at least one --email or --organization-id."))
+ return
+
+ org_user_ids: set[int] = set()
+ if organization_id is not None:
+ org_user_ids = set(
+ OrganizationMembership.objects.filter(organization_id=organization_id).values_list("user_id", flat=True)
+ )
+
+ email_user_ids: set[int] = set()
+ if emails:
+ email_user_ids = set(User.objects.filter(email__in=emails).values_list("id", flat=True))
+
+ email_only_user_ids = email_user_ids - org_user_ids
+
+ total_matched = len(org_user_ids) + len(email_only_user_ids)
+ if total_matched == 0:
+ self.stdout.write(self.style.WARNING("No matching users found."))
+ return
+
+ self.stdout.write(f"Found {total_matched} user(s) matching criteria.")
+
+ org_team_ids: list[int] = []
+ if org_user_ids:
+ org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))
+
+ updated_count = 0
+ skipped_count = 0
+
+ for user in User.objects.filter(id__in=org_user_ids).order_by("email"):
+ if self._disable_for_org_teams(user, org_team_ids, dry_run=dry_run):
+ updated_count += 1
+ else:
+ skipped_count += 1
+
+ for user in User.objects.filter(id__in=email_only_user_ids).order_by("email"):
+ if self._disable_globally(user, dry_run=dry_run):
+ updated_count += 1
+ else:
+ skipped_count += 1
+
+ if dry_run:
+ self.stdout.write(
+ self.style.WARNING(f"Dry run — would update {updated_count} user(s), {skipped_count} already disabled.")
+ )
+ else:
+ self.stdout.write(
+ self.style.SUCCESS(f"Done. Updated {updated_count} user(s), {skipped_count} already disabled.")
+ )
+
+ def _disable_for_org_teams(self, user: User, org_team_ids: list[int], *, dry_run: bool) -> bool:
+ if not org_team_ids:
+ self.stdout.write(f" Skipping {user.email} — organization has no projects.")
+ return False
+
+ current_settings = user.partial_notification_settings or {}
+ project_map = current_settings.get(PROJECT_SETTING_KEY) or {}
+
+ if not self._needs_org_update(project_map, org_team_ids):
+ self.stdout.write(f" Skipping {user.email} — already disabled for org's projects.")
+ return False
+
+ if dry_run:
+ self.stdout.write(f" Would disable {len(org_team_ids)} org project(s) for {user.email}")
+ return True
+
+ with transaction.atomic():
+ user_obj = User.objects.select_for_update().get(pk=user.pk)
+ current_settings = user_obj.partial_notification_settings or {}
+ project_map = dict(current_settings.get(PROJECT_SETTING_KEY) or {})
+ if not self._needs_org_update(project_map, org_team_ids):
+ self.stdout.write(f" Skipping {user.email} — already disabled for org's projects.")
+ return False
+ for tid in org_team_ids:
+ project_map[str(tid)] = False
+ current_settings[PROJECT_SETTING_KEY] = project_map
+ user_obj.partial_notification_settings = current_settings
+ user_obj.save(update_fields=["partial_notification_settings"])
+
+ self.stdout.write(f" Disabled {len(org_team_ids)} org project(s) for {user.email}")
+ return True
+
+ def _disable_globally(self, user: User, *, dry_run: bool) -> bool:
+ current_settings = user.partial_notification_settings or {}
+ if current_settings.get(GLOBAL_SETTING_KEY) is False:
+ self.stdout.write(f" Skipping {user.email} — already disabled.")
+ return False
+
+ if dry_run:
+ self.stdout.write(f" Would disable for {user.email}")
+ return True
+
+ with transaction.atomic():
+ user_obj = User.objects.select_for_update().get(pk=user.pk)
+ current_settings = user_obj.partial_notification_settings or {}
+ if current_settings.get(GLOBAL_SETTING_KEY) is False:
+ self.stdout.write(f" Skipping {user.email} — already disabled.")
+ return False
+ current_settings[GLOBAL_SETTING_KEY] = False
+ user_obj.partial_notification_settings = current_settings
+ user_obj.save(update_fields=["partial_notification_settings"])
+
+ self.stdout.write(f" Disabled for {user.email}")
+ return True
+
+ @staticmethod
+ def _needs_org_update(project_map: dict, org_team_ids: list[int]) -> bool:
+ return any(project_map.get(str(tid)) is not False for tid in org_team_ids)
diff --git a/products/error_tracking/backend/management/commands/test/test_disable_error_tracking_weekly_digest.py b/products/error_tracking/backend/management/commands/test/test_disable_error_tracking_weekly_digest.py
new file mode 100644
index 000000000000..673ce93ce13f
--- /dev/null
+++ b/products/error_tracking/backend/management/commands/test/test_disable_error_tracking_weekly_digest.py
@@ -0,0 +1,202 @@
+from io import StringIO
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from posthog.models import Team
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
+
+
+class TestDisableErrorTrackingWeeklyDigest(BaseTest):
+ def test_disables_for_single_email(self):
+ out = StringIO()
+ call_command("disable_error_tracking_weekly_digest", "--email", self.user.email, stdout=out)
+
+ self.user.refresh_from_db()
+ settings = self.user.partial_notification_settings or {}
+ assert settings["error_tracking_weekly_digest"] is False
+ assert "Updated 1 user(s)" in out.getvalue()
+
+ def test_disables_for_multiple_emails(self):
+ user2 = User.objects.create_user(
+ password="testpassword",
+ first_name="Test2",
+ )
+
+ out = StringIO()
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--email",
+ self.user.email,
+ "--email",
+ user2.email,
+ stdout=out,
+ )
+
+ self.user.refresh_from_db()
+ user2.refresh_from_db()
+ settings1 = self.user.partial_notification_settings or {}
+ settings2 = user2.partial_notification_settings or {}
+ assert settings1["error_tracking_weekly_digest"] is False
+ assert settings2["error_tracking_weekly_digest"] is False
+ assert "Updated 2 user(s)" in out.getvalue()
+
+ def test_disables_for_organization(self):
+ user2 = User.objects.create_user(
+ password="testpassword",
+ first_name="Test2",
+ )
+ user2.join(organization=self.organization, level=OrganizationMembership.Level.MEMBER)
+
+ out = StringIO()
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--organization-id",
+ str(self.organization.id),
+ stdout=out,
+ )
+
+ self.user.refresh_from_db()
+ user2.refresh_from_db()
+ settings1 = self.user.partial_notification_settings or {}
+ settings2 = user2.partial_notification_settings or {}
+ assert "error_tracking_weekly_digest" not in settings1
+ assert "error_tracking_weekly_digest" not in settings2
+ assert settings1["error_tracking_weekly_digest_project_enabled"][str(self.team.id)] is False
+ assert settings2["error_tracking_weekly_digest_project_enabled"][str(self.team.id)] is False
+
+ def test_dry_run_does_not_modify(self):
+ out = StringIO()
+ call_command("disable_error_tracking_weekly_digest", "--email", self.user.email, "--dry-run", stdout=out)
+
+ self.user.refresh_from_db()
+ settings = self.user.partial_notification_settings or {}
+ assert settings.get("error_tracking_weekly_digest") is not False
+ assert "Dry run" in out.getvalue()
+ assert "Would disable" in out.getvalue()
+
+ def test_skips_already_disabled(self):
+ self.user.partial_notification_settings = {"error_tracking_weekly_digest": False}
+ self.user.save()
+
+ out = StringIO()
+ call_command("disable_error_tracking_weekly_digest", "--email", self.user.email, stdout=out)
+
+ assert "already disabled" in out.getvalue()
+ assert "Updated 0 user(s), 1 already disabled" in out.getvalue()
+
+ def test_requires_email_or_organization(self):
+ err = StringIO()
+ call_command("disable_error_tracking_weekly_digest", stderr=err)
+ assert "Must provide at least one --email or --organization-id" in err.getvalue()
+
+ def test_handles_nonexistent_email(self):
+ out = StringIO()
+ call_command("disable_error_tracking_weekly_digest", "--email", "[email protected]", stdout=out)
+ assert "No matching users found" in out.getvalue()
+
+ def test_handles_empty_organization(self):
+ empty_org = Organization.objects.create(name="Empty Org")
+
+ out = StringIO()
+ call_command("disable_error_tracking_weekly_digest", "--organization-id", str(empty_org.id), stdout=out)
+ assert "No matching users found" in out.getvalue()
+
+ def test_organization_scope_does_not_touch_global_or_other_orgs(self):
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ self.user.join(organization=other_org, level=OrganizationMembership.Level.MEMBER)
+
+ self.user.partial_notification_settings = {
+ "error_tracking_weekly_digest_project_enabled": {
+ str(other_team.id): True,
+ },
+ }
+ self.user.save()
+
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--organization-id",
+ str(self.organization.id),
+ stdout=StringIO(),
+ )
+
+ self.user.refresh_from_db()
+ settings = self.user.partial_notification_settings or {}
+ assert "error_tracking_weekly_digest" not in settings
+ project_map = settings["error_tracking_weekly_digest_project_enabled"]
+ assert project_map[str(self.team.id)] is False
+ assert project_map[str(other_team.id)] is True
+
+ def test_email_and_organization_overlap_uses_per_project(self):
+ # User matched by both --email and --organization-id should get per-project treatment.
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--email",
+ self.user.email,
+ "--organization-id",
+ str(self.organization.id),
+ stdout=StringIO(),
+ )
+
+ self.user.refresh_from_db()
+ settings = self.user.partial_notification_settings or {}
+ assert "error_tracking_weekly_digest" not in settings
+ assert settings["error_tracking_weekly_digest_project_enabled"][str(self.team.id)] is False
+
+ def test_email_only_user_still_globally_disabled_when_org_also_provided(self):
+ # User matched only by --email (not in org) should still get the global flag set.
+ outside_user = User.objects.create_user(
+ password="testpassword",
+ first_name="Outside",
+ )
+
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--email",
+ outside_user.email,
+ "--organization-id",
+ str(self.organization.id),
+ stdout=StringIO(),
+ )
+
+ outside_user.refresh_from_db()
+ settings = outside_user.partial_notification_settings or {}
+ assert settings["error_tracking_weekly_digest"] is False
+ assert "error_tracking_weekly_digest_project_enabled" not in settings
+
+ def test_organization_skips_when_all_org_teams_already_disabled(self):
+ self.user.partial_notification_settings = {
+ "error_tracking_weekly_digest_project_enabled": {str(self.team.id): False},
+ }
+ self.user.save()
+
+ out = StringIO()
+ call_command(
+ "disable_error_tracking_weekly_digest",
+ "--organization-id",
+ str(self.organization.id),
+ stdout=out,
+ )
+ assert "already disabled for org's projects" in out.getvalue()
+ assert "Updated 0 user(s), 1 already disabled" in out.getvalue()
+
+ def test_preserves_other_notification_settings(self):
+ self.user.partial_notification_settings = {
+ "plugin_disabled": True,
+ "discussions_mentioned": True,
+ }
+ self.user.save()
+
+ call_command("disable_error_tracking_weekly_digest", "--email", self.user.email, stdout=StringIO())
+
+ self.user.refresh_from_db()
+ settings = self.user.partial_notification_settings or {}
+ assert settings["error_tracking_weekly_digest"] is False
+ assert settings["plugin_disabled"] is True
+ assert settings["discussions_mentioned"] is True
diff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.py
index b11a81b4a371..eb72940b3326 100644
--- a/products/error_tracking/backend/test/test_weekly_digest.py
+++ b/products/error_tracking/backend/test/test_weekly_digest.py
@@ -5,6 +5,8 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.models import Team
from posthog.models.organization import Organization
from posthog.models.utils import uuid7
@@ -305,23 +307,40 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
assert result == {} or result["exception_count"] == 0
- def test_auto_select_project_picks_busiest(self):
- team_b = Team.objects.create(organization=self.organization, name="Team B")
+ @parameterized.expand(["engineering", "data", "founder", "Engineering", "DATA", "Founder"])
+ def test_auto_select_project_enrolls_eligible_roles(self, role):
+ self.user.role_at_organization = role
+ self.user.save()
team_exception_counts = {
- self.team.pk: {"exception_count": 5, "ingestion_failure_count": 0, "prev_exception_count": 0},
- team_b.pk: {"exception_count": 15, "ingestion_failure_count": 0, "prev_exception_count": 0},
+ self.team.pk: {"exception_count": 10, "ingestion_failure_count": 0, "prev_exception_count": 0},
+ }
+
+ auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)
+ self.user.refresh_from_db()
+
+ settings = self.user.notification_settings or {}
+ project_enabled = settings.get("error_tracking_weekly_digest_project_enabled", {})
+ assert project_enabled[str(self.team.pk)] is True
+
+ @parameterized.expand(["marketing", "sales", "leadership", "product", "other", None])
+ def test_auto_select_project_sets_empty_for_ineligible_roles(self, role):
+ self.user.role_at_organization = role
+ self.user.save()
+
+ team_exception_counts = {
+ self.team.pk: {"exception_count": 10, "ingestion_failure_count": 0, "prev_exception_count": 0},
}
auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)
self.user.refresh_from_db()
- settings = self.user.notification_settings
+ settings = self.user.notification_settings or {}
project_enabled = settings.get("error_tracking_weekly_digest_project_enabled", {})
- assert str(self.team.pk) not in project_enabled
- assert project_enabled[str(team_b.pk)] is True
+ assert project_enabled == {}
def test_auto_select_project_skips_if_already_configured(self):
+ self.user.role_at_organization = "engineering"
self.user.partial_notification_settings = {
"error_tracking_weekly_digest_project_enabled": {str(self.team.pk): True},
}
@@ -334,7 +353,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):
auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)
self.user.refresh_from_db()
- settings = self.user.notification_settings
+ settings = self.user.notification_settings or {}
assert settings["error_tracking_weekly_digest_project_enabled"] == {str(self.team.pk): True}
def test_auto_select_project_noop_when_no_exceptions(self):
diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.py
index 7d52b138f746..96ab6c7e385f 100644
--- a/products/error_tracking/backend/weekly_digest.py
+++ b/products/error_tracking/backend/weekly_digest.py
@@ -1,4 +1,5 @@
import datetime
+from typing import Any
from django.conf import settings
from django.utils import timezone
@@ -62,15 +63,38 @@ def get_exception_summary_for_team(team: Team) -> dict:
}
-def auto_select_project_for_user(user, org_id: int, team_exception_counts: dict[int, dict]) -> bool:
+ELIGIBLE_ROLES_FOR_AUTO_DIGEST = {"engineering", "data", "founder"}
+
+
+def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts: dict[int, dict]) -> bool:
"""For first-time users who have no ET digest project settings, auto-select the project with the most exceptions
- and persist the selection to their notification settings"""
+ and persist the selection to their notification settings.
+
+ Only auto-enrolls users with engineering, data, or founder roles. Users with other roles
+ (marketing, sales, leadership, product, other, None) are marked as "processed" with an empty
+ project map so auto-selection doesn't run again - they can still opt in manually via settings.
+ """
+ from posthog.models.user import User
from posthog.tasks.email_utils import auto_select_digest_project
+ setting_key = "error_tracking_weekly_digest_project_enabled"
+ current_settings = user.partial_notification_settings or {}
+ if setting_key in current_settings:
+ return False
+
+ if not team_exception_counts:
+ return False
+
+ role = (user.role_at_organization or "").lower()
+ if role not in ELIGIBLE_ROLES_FOR_AUTO_DIGEST:
+ current_settings[setting_key] = {}
+ User.objects.filter(pk=user.pk).update(partial_notification_settings=current_settings)
+ return True
+
return auto_select_digest_project(
user=user,
team_data=team_exception_counts,
- setting_key="error_tracking_weekly_digest_project_enabled",
+ setting_key=setting_key,
sort_key=lambda d: d["exception_count"],
)