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.

refactor(api): split team settings module (#99248)

Paul D'Ambra0413562835e5
diff --git a/posthog/api/product_enablement.py b/posthog/api/product_enablement.py
index 1be49edd53d9..3d06ec2450a1 100644
--- a/posthog/api/product_enablement.py
+++ b/posthog/api/product_enablement.py
@@ -22,7 +22,8 @@ from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.team import TEAM_CONFIG_ADMIN_FIELDS_SET, conversations_settings_as_dict
+from posthog.api.team.conversations_settings import conversations_settings_as_dict
+from posthog.api.team.team_config import TEAM_CONFIG_ADMIN_FIELDS_SET
from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import Detail, dict_changes_between, log_activity
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 2fa13d80407f..2b2397626ca5 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -25,43 +25,49 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import ProjectBackwardCompatBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin
-# These are imported from team.py for now. They are part of the legacy /api/environments/ surface and are
+# These are imported from the team API package for now. They are part of the legacy /api/environments/ surface and are
# expected to move project-side (or to a neutral module) in a later PR once /api/environments/ is retired —
-# project.py must NOT depend on team.py at that point. The parity *logic* (config writes, retention check,
+# project.py must NOT depend on the team API package at that point. The parity *logic* (config writes, retention check,
# and the team-config actions) is defined locally below rather than imported, so it survives that removal.
-from posthog.api.team import (
+from posthog.api.team.conversations_settings import (
LOCKED_CONVERSATIONS_COLUMNS,
- TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS,
- TEAM_CONFIG_FIELDS,
- TEAM_CONFIG_MEMBER_FIELDS_SET,
ConversationsSettingsField,
- EvaluationContextSuggestionRequestSerializer,
- EvaluationContextSuggestionResponseSerializer,
- EventIngestionRestrictionSerializer,
- TeamCustomerAnalyticsConfigSerializer,
- TeamFeatureFlagPolicyConfigSerializer,
+ merge_conversations_settings_locked,
+ report_conversations_settings_changes,
+ strip_managed_conversations_settings,
+)
+from posthog.api.team.integration_config import (
TeamLogsConfigSerializer,
- TeamMarketingAnalyticsConfigSerializer,
- TeamRevenueAnalyticsConfigSerializer,
- TeamSerializer,
TeamTracingConfigSerializer,
- TeamWorkflowsConfigSerializer,
- _default_data_color_theme_id,
- _format_serializer_errors,
handle_experiments_config,
handle_logs_config,
handle_tracing_config,
- heatmaps_screenshot_secret_for_reader,
- live_events_token_for_request,
- merge_conversations_settings_locked,
- merge_modifiers,
- report_conversations_settings_changes,
- strip_managed_conversations_settings,
- team_event_ingestion_restrictions_view,
validate_secret_token_generation,
+)
+from posthog.api.team.live_events import _default_data_color_theme_id, live_events_token_for_request
+from posthog.api.team.marketing_config import TeamMarketingAnalyticsConfigSerializer
+from posthog.api.team.settings_validation import (
+ _format_serializer_errors,
+ heatmaps_screenshot_secret_for_reader,
validate_team_attrs,
validate_team_workflows_config,
)
+from posthog.api.team.team_config import (
+ TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS,
+ TEAM_CONFIG_FIELDS,
+ TEAM_CONFIG_MEMBER_FIELDS_SET,
+ TeamCustomerAnalyticsConfigSerializer,
+ TeamFeatureFlagPolicyConfigSerializer,
+ TeamRevenueAnalyticsConfigSerializer,
+ TeamWorkflowsConfigSerializer,
+)
+from posthog.api.team.team_serializer import (
+ EvaluationContextSuggestionRequestSerializer,
+ EvaluationContextSuggestionResponseSerializer,
+ TeamSerializer,
+ merge_modifiers,
+)
+from posthog.api.team.viewsets import EventIngestionRestrictionSerializer, team_event_ingestion_restrictions_view
from posthog.api.utils import validate_authorized_url_wildcards
from posthog.auth import SessionAuthentication
from posthog.caching.organization_serializer_cache import _bump_org_serializer_cache_version
@@ -151,7 +157,7 @@ MAX_ALLOWED_PROJECTS_PER_ORG = 2000
# --- Backward-compatibility logic for the /api/projects/ surface ---
# These mirror the behaviour of the legacy /api/environments/ (TeamViewSet/TeamSerializer) endpoints, operating
-# on a project's passthrough Team. They live here — not imported from team.py — so /api/projects/ keeps working
+# on a project's passthrough Team. They live here — not imported from the team API package — so /api/projects/ keeps working
# after /api/environments/ is retired. Until then both surfaces intentionally carry equivalent logic; the
# introspection test in test_team_project_parity.py guards against drift.
def capture_team_config_diff(team: Team, key: str, before: dict, after: dict, *, context: dict) -> None:
@@ -543,7 +549,6 @@ def team_evaluation_context_suggestions_view(team: Team, request: request.Reques
context_name = normalize_context_name(context_name)
if not context_name:
return response.Response({"error": "context_name is required"}, status=400)
-
if len(context_name) > 255:
return response.Response({"error": "context_name must be at most 255 characters"}, status=400)
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index d858cafe2774..ef554d4b3cde 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -69,7 +69,6 @@ from . import (
search,
sharing,
tagged_item,
- team,
uploaded_media,
user,
user_facet_settings,
@@ -89,6 +88,7 @@ from .oauth import OrganizationOAuthApplicationViewSet
from .organization_notification_locks import OrganizationNotificationLockViewSet
from .session import SessionViewSet
from .taxonomic_search_intent import SearchIntentViewSet
+from .team import viewsets
@decorators.api_view(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])
@@ -106,7 +106,7 @@ routers.set_root(router)
# Nested endpoints shared
projects_router = routers.add("projects", router.register(r"projects", project.RootProjectViewSet, "projects"))
-projects_router.register(r"environments", team.ProjectEnvironmentsViewSet, "project_environments", ["project_id"])
+projects_router.register(r"environments", viewsets.ProjectEnvironmentsViewSet, "project_environments", ["project_id"])
projects_router.register(r"sdk_health", SdkHealthViewSet, "project_sdk_health", ["project_id"])
projects_router.register(
diff --git a/posthog/api/team.py b/posthog/api/team.py
deleted file mode 100644
index 47edee323990..000000000000
--- a/posthog/api/team.py
+++ /dev/null
@@ -1,3561 +0,0 @@
-import re
-import json
-import secrets
-from datetime import timedelta
-from functools import cached_property
-from typing import Any, Literal, cast
-
-from django.conf import settings
-from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import transaction
-from django.shortcuts import get_object_or_404
-from django.utils import timezone
-from django.utils.dateparse import parse_datetime
-
-import re2
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import extend_schema, extend_schema_field
-from opentelemetry import trace
-from pydantic import (
- RootModel as PydanticRootModel,
- TypeAdapter,
-)
-from pydantic.json_schema import SkipJsonSchema
-from pydantic_core import ValidationError as PydanticValidationError
-from rest_framework import exceptions, request, response, serializers, viewsets
-from rest_framework.permissions import BasePermission, IsAuthenticated
-
-from posthog.schema import (
- AttributionMode,
- CampaignFieldPreference,
- CohortPropertyFilter,
- ConversionGoalFilter1,
- ConversionGoalFilter2,
- ConversionGoalFilter3,
- DataWarehousePropertyFilter,
- ElementPropertyFilter,
- EventPropertyFilter,
- HogQLPropertyFilter,
- HogQLQueryModifiers,
- PersonPropertyFilter,
- SourceMap,
-)
-
-from posthog.api.property_filter_access_gate import table_blocking_property_filters
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
-from posthog.api.shared import TeamBasicSerializer
-from posthog.api.utils import action, validate_authorized_url_wildcards
-from posthog.auth import SessionAuthentication
-from posthog.constants import AvailableFeature
-from posthog.decorators import disallow_if_impersonated
-from posthog.event_usage import report_user_action
-from posthog.geoip import get_geoip_properties
-from posthog.helpers.impersonation import is_impersonated
-from posthog.jwt import PosthogJwtAudience, encode_jwt, signing_key_fingerprint
-from posthog.models import ProductIntent, Team, TeamMarketingAnalyticsConfig, TeamRevenueAnalyticsConfig, User
-from posthog.models.activity_logging.activity_log import (
- ActivityLog,
- Detail,
- dict_changes_between,
- load_activity,
- log_activity,
-)
-from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
-from posthog.models.data_color_theme import DataColorTheme
-from posthog.models.event_ingestion_restriction_config import (
- EventIngestionRestrictionConfig,
- IngestionPipeline,
- RestrictionType,
-)
-from posthog.models.filters.utils import validate_group_type_index
-from posthog.models.group_type_mapping import cached_group_types_for_team
-from posthog.models.integration.model import Integration
-from posthog.models.organization import Organization, OrganizationMembership
-from posthog.models.product_intent.product_intent import (
- ProductIntentSerializer,
- cached_product_intents_for_team,
- enqueue_product_activation_calc_debounced,
-)
-from posthog.models.project import Project
-from posthog.models.team.extensions import get_or_create_team_extension
-from posthog.models.team.logs_retention import (
- LOGS_CUSTOM_RETENTION_FLAG,
- LOGS_RETENTION_BASE_TIERS_DAYS,
- logs_retention_days_error,
- required_logs_retention_feature,
- retention_update_throttle_error,
-)
-from posthog.models.team.setup_tasks import SetupTaskId
-from posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCY
-from posthog.models.team.team_caching import set_team_in_cache
-from posthog.models.team.util import actions_that_require_current_team
-from posthog.models.utils import UUIDT
-from posthog.permissions import (
- CREATE_ACTIONS,
- AccessControlPermission,
- APIScopePermission,
- OrganizationMemberPermissions,
- TeamMemberLightManagementPermission,
- TeamMemberStrictManagementPermission,
- UserCanCreateProjectPermission,
- get_authenticator_scoped_organization_ids,
- get_authenticator_scoped_team_ids,
- get_authenticator_scopes,
- posthog_feature_flag_enabled,
-)
-from posthog.scopes import APIScopeObjectOrNotSupported, scopes_not_covered
-from posthog.session_recordings.data_retention import (
- VALID_RETENTION_PERIODS,
- parse_feature_to_entitlement,
- retention_violates_entitlement,
- validate_retention_period,
-)
-from posthog.types import AnyPropertyFilter
-from posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixin
-from posthog.utils import (
- get_instance_realm,
- get_instance_region,
- get_ip_address,
- get_safe_cache,
- get_week_start_for_country_code,
- safe_cache_set,
-)
-
-from products.access_control.backend.presentation.access_control import (
- AccessControlViewSetMixin,
- UserAccessControlSerializerMixin,
-)
-from products.access_control.backend.presentation.access_control_settings import AccessControlSettingsViewSetMixin
-from products.customer_analytics.backend.facade.account_property_pins import (
- InvalidPinnedAccountProperties,
- validate_pinned_account_properties,
-)
-from products.customer_analytics.backend.facade.contracts import PinnedAccountProperty
-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind
-from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
-from products.dashboards.backend.models import Dashboard
-from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
-from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_mode
-from products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name
-from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig
-from products.logs.backend.models import TeamLogsConfig
-from products.tasks.backend.facade.workflow_tasks import (
- MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY,
- MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
- WORKFLOW_TASK_RATE_CAP_PER_DAY,
- WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
-)
-from products.tracing.backend.facade.team_extension import TeamTracingConfig
-from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
- MAX_CUSTOM_BOT_DEFINITIONS,
- assert_patterns_compile as assert_custom_bot_patterns_compile,
- compiled_patterns as compiled_custom_bot_patterns,
- parse_rules as parse_custom_bot_rules,
- validate_rule as validate_custom_bot_rule,
- validate_rule_set as validate_custom_bot_rule_set,
-)
-from products.workflows.backend.facade.enums import EMAIL_TRACKING_CONSENT_MODE_CHOICES
-from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
-
-tracer = trace.get_tracer(__name__)
-
-
-def _validate_unique_attribute_keys(value: list[str]) -> list[str]:
- # The child CharField already trims whitespace and rejects blanks; only
- # cross-item uniqueness needs checking here.
- if len(set(value)) != len(value):
- raise serializers.ValidationError("Attribute keys must be unique.")
- return value
-
-
-class TeamLogsConfigSerializer(serializers.ModelSerializer):
- logs_distinct_id_attribute_key = serializers.CharField(
- read_only=True,
- help_text=(
- "Legacy single-key alias — always the first entry of "
- "`logs_distinct_id_attribute_keys`. Read-only; write the plural field instead."
- ),
- )
- logs_distinct_id_attribute_keys = serializers.ListField(
- # trim_whitespace is the DRF default, but the uniqueness validator below
- # depends on it — spell it out so it can't drift silently.
- child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
- allow_empty=False,
- max_length=10,
- help_text=(
- "Log attribute keys whose values should match a person's distinct_id — a log "
- "links to a person when any of these attributes equals one of their distinct IDs. "
- "Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to "
- "['posthogDistinctId'] — the convention documented at "
- "https://posthog.com/docs/logs/link-session-replay and the key the "
- "posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your "
- "pipeline emits the person identifier under different attributes."
- ),
- )
- logs_session_id_attribute_keys = serializers.ListField(
- # trim_whitespace is the DRF default, but the uniqueness validator below
- # depends on it — spell it out so it can't drift silently.
- child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
- allow_empty=False,
- max_length=10,
- help_text=(
- "Ordered list of log attribute keys whose values hold the PostHog session ID. "
- "Detection checks keys in order, then falls back to common session ID attribute "
- "conventions; the first key with a value wins. Defaults to ['sessionId'] — the "
- "convention documented at https://posthog.com/docs/logs/link-session-replay and "
- "the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only "
- "if your pipeline emits the session ID under different attributes."
- ),
- )
- logs_pattern_message_keys = serializers.ListField(
- child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
- allow_empty=True,
- max_length=10,
- help_text=(
- "Ordered list of top-level JSON keys whose value is the message text that log "
- "patterns are derived from. Keys are matched literally at the top level of the log "
- "body; a dot in a key is part of the key name, not a path into nested objects. "
- "Selection checks keys in order; the first key whose value is a non-empty string "
- "wins. Defaults to ['message', 'msg', 'event']. An empty list "
- "turns message extraction off, so JSON log bodies group by their key set instead. "
- "The stored log body is never changed by this setting."
- ),
- )
-
- class Meta:
- model = TeamLogsConfig
- fields = [
- "logs_distinct_id_attribute_key",
- "logs_distinct_id_attribute_keys",
- "logs_session_id_attribute_keys",
- "logs_pattern_message_keys",
- ]
-
- def validate_logs_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:
- return _validate_unique_attribute_keys(value)
-
- def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:
- return _validate_unique_attribute_keys(value)
-
- def validate_logs_pattern_message_keys(self, value: list[str]) -> list[str]:
- return _validate_unique_attribute_keys(value)
-
- def update(self, instance: TeamLogsConfig, validated_data: dict) -> TeamLogsConfig:
- # Keep the legacy single-key column in sync so pre-plural readers stay coherent.
- keys = validated_data.get("logs_distinct_id_attribute_keys")
- if keys:
- validated_data["logs_distinct_id_attribute_key"] = keys[0]
- return super().update(instance, validated_data)
-
-
-# Gates changes to the traces default retention period. Mirrored in `FEATURE_FLAGS.TRACING_SETTINGS_RETENTION`.
-TRACES_RETENTION_FLAG = "tracing-settings-retention"
-
-
-class TeamTracingConfigSerializer(serializers.ModelSerializer):
- tracing_distinct_id_attribute_keys = serializers.ListField(
- # trim_whitespace is the DRF default, but the uniqueness validator below
- # depends on it — spell it out so it can't drift silently.
- child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
- allow_empty=False,
- max_length=10,
- help_text=(
- "Span or resource attribute keys whose values should match a person's distinct_id — "
- "a span links to a person when any of these attributes holds one of their distinct "
- "IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / "
- "posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if "
- "your pipeline emits the person identifier under different attributes."
- ),
- )
- tracing_session_id_attribute_keys = serializers.ListField(
- # trim_whitespace is the DRF default, but the uniqueness validator below
- # depends on it — spell it out so it can't drift silently.
- child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
- allow_empty=False,
- max_length=10,
- help_text=(
- "Ordered list of span or resource attribute keys whose values hold the PostHog "
- "session ID. Detection checks keys in order, then falls back to common session ID "
- "attribute conventions; the first key with a value wins. Defaults to ['sessionId'], "
- "the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they "
- "emit. Add keys only if your pipeline emits the session ID under different attributes."
- ),
- )
-
- retention_days = serializers.IntegerField(
- required=False,
- help_text=(
- "How long spans are kept before they are deleted, in days. Applied at ingest, so a "
- "change only affects spans received after it. Can be changed at most once per 24 "
- "hours. Span retention rules override this period for the spans they match."
- ),
- )
-
- class Meta:
- model = TeamTracingConfig
- fields = [
- "tracing_distinct_id_attribute_keys",
- "tracing_session_id_attribute_keys",
- "retention_days",
- "retention_last_updated",
- ]
- read_only_fields = ["retention_last_updated"]
-
- def validate_tracing_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:
- return _validate_unique_attribute_keys(value)
-
- def validate_tracing_session_id_attribute_keys(self, value: list[str]) -> list[str]:
- return _validate_unique_attribute_keys(value)
-
- def validate_retention_days(self, value: int) -> int:
- # Only a changed period is checked against the flags and the entitlement, so an unrelated
- # update that sends the stored period back keeps working after either is turned off.
- if self.instance is not None and self.instance.retention_days == value:
- return value
-
- team = self.context.get("team")
- organization = team.organization if team is not None else None
- user = getattr(self.context.get("request"), "user", None)
- if not _flag_enabled_for_caller(TRACES_RETENTION_FLAG, organization, user, team):
- raise exceptions.PermissionDenied("Changing traces retention is not available for this project yet.")
-
- # Only evaluate the flag outside the base tiers, so the common path makes no flag call.
- custom_enabled = value not in LOGS_RETENTION_BASE_TIERS_DAYS and _custom_retention_flag_enabled(
- organization, user, team
- )
- error = logs_retention_days_error(value, custom_retention_enabled=custom_enabled)
- if error:
- raise exceptions.ValidationError(error)
-
- _check_traces_retention_entitlement(value, organization)
-
- throttle_error = retention_update_throttle_error(
- self.instance.retention_last_updated if self.instance is not None else None
- )
- if throttle_error:
- raise exceptions.ValidationError(throttle_error)
-
- return value
-
- def update(self, instance: TeamTracingConfig, validated_data: dict[str, Any]) -> TeamTracingConfig:
- new_retention = validated_data.get("retention_days")
- if new_retention is not None and new_retention != instance.retention_days:
- validated_data["retention_last_updated"] = timezone.now()
- return super().update(instance, validated_data)
-
-
-def handle_tracing_config(request: request.Request, team: Team) -> response.Response:
- """Shared handler for the tracing_config action — exposed under both the team/environment
- and project routers so the canonical /api/projects/ URL resolves alongside the legacy
- /api/environments/ alias. Both endpoints operate on the env-scoped TeamTracingConfig
- keyed by team_id."""
- config = get_or_create_team_extension(team, TeamTracingConfig)
-
- if request.method == "PATCH":
- serializer = TeamTracingConfigSerializer(
- config, data=request.data, partial=True, context={"request": request, "team": team}
- )
- serializer.is_valid(raise_exception=True)
- with transaction.atomic():
- locked_config = TeamTracingConfig.objects.select_for_update().get(team=team)
- retention = serializer.validated_data.get("retention_days")
- if retention is not None and retention != locked_config.retention_days:
- throttle_error = retention_update_throttle_error(locked_config.retention_last_updated)
- if throttle_error:
- raise exceptions.ValidationError({"retention_days": throttle_error})
- if locked_config.retention_days != config.retention_days:
- # Entitlement resets do not set retention_last_updated, so the throttle cannot see them.
- raise exceptions.ValidationError(
- {"retention_days": "Retention changed. Reload the settings and retry."}
- )
- # Billing can revoke the entitlement after validation read the organization.
- _check_traces_retention_entitlement(
- retention, Organization.objects.only("available_product_features").get(id=team.organization_id)
- )
- serializer.instance = locked_config
- serializer.save()
- return response.Response(serializer.data)
-
- return response.Response(TeamTracingConfigSerializer(config).data)
-
-
-def handle_experiments_config(request: request.Request, team: Team) -> response.Response:
- """Shared handler for the experiments_config action — exposed under both the
- team/environment and project routers so both surfaces stay in parity."""
- # Keeps the products app import off this module's import path.
- from products.experiments.backend.models.team_experiments_config import ( # noqa: PLC0415
- MAX_RECALCULATION_TIMES,
- MIN_RECALCULATION_GAP_HOURS,
- TeamExperimentsConfig,
- validate_recalculation_times,
- )
-
- class TeamExperimentsConfigSerializer(serializers.ModelSerializer):
- experiment_recalculation_times = serializers.ListField(
- child=serializers.RegexField(
- regex=r"^(?:[01]\d|2[0-3]):00:00$",
- error_messages={"invalid": "Recalculation times must be on the hour, in HH:00:00 format (UTC)."},
- ),
- required=False,
- allow_null=True,
- allow_empty=False,
- max_length=MAX_RECALCULATION_TIMES,
- help_text=(
- "Times of day (UTC) when experiment metrics are recalculated, as 'HH:00:00' strings "
- f"on the hour. At most {MAX_RECALCULATION_TIMES} entries, at least "
- f"{MIN_RECALCULATION_GAP_HOURS} hours apart. Null means the default time (02:00 UTC)."
- ),
- )
-
- class Meta:
- model = TeamExperimentsConfig
- fields = [
- "experiment_recalculation_times",
- "default_experiment_confidence_level",
- "default_experiment_stats_method",
- "experiment_precomputation_enabled",
- "default_only_count_matured_users",
- "default_cuped_enabled",
- "default_cuped_lookback_days",
- "default_minimum_detectable_effect",
- "default_sequential_testing_enabled",
- "default_sequential_tuning_parameter",
- "flag_cleanup_repository",
- ]
-
- def validate_experiment_recalculation_times(self, value: list[str] | None) -> list[str] | None:
- try:
- validate_recalculation_times(value)
- except DjangoValidationError as e:
- raise serializers.ValidationError(e.messages)
- return value
-
- def update(self, instance: "TeamExperimentsConfig", validated_data: dict[str, Any]) -> "TeamExperimentsConfig":
- # A human toggling precomputation must stick: the auto-enrollment job only
- # writes when precomputation_enabled_set_by is null or "auto".
- if "experiment_precomputation_enabled" in validated_data:
- instance.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL
- return super().update(instance, validated_data)
-
- def validate_flag_cleanup_repository(self, value: str | None) -> str | None:
- # Keeps the sandbox/LLM runtime the repo-selection module pulls in off the
- # request import path.
- from products.tasks.backend.facade import repo_selection as tasks_repo_selection # noqa: PLC0415
-
- if not value:
- return None
- parts = value.split("/")
- if len(parts) != 2 or not parts[0] or not parts[1]:
- raise serializers.ValidationError("Repository must be in the format organization/repository")
- value = value.lower()
- # Reject repos outside the team's GitHub installation now rather than storing a
- # default the cleanup resolution would silently ignore.
- github = tasks_repo_selection.resolve_team_github_integration(team.id, team=team, team_only=True)
- cached = {
- full_name.lower()
- for repo in (github.list_all_cached_repositories(max_repos=1000) if github else [])
- if (full_name := repo.get("full_name"))
- }
- if value not in cached:
- raise serializers.ValidationError(
- "This repository is not connected to the project's GitHub integration."
- )
- return value
-
- config = get_or_create_team_extension(team, TeamExperimentsConfig)
-
- if request.method == "PATCH":
- serializer = TeamExperimentsConfigSerializer(config, data=request.data, partial=True)
- serializer.is_valid(raise_exception=True)
- serializer.save()
- return response.Response(serializer.data)
-
- return response.Response(TeamExperimentsConfigSerializer(config).data)
-
-
-def handle_logs_config(request: request.Request, team: Team) -> response.Response:
- """Shared handler for the logs_config action — exposed under both the team/environment
- and project routers so the canonical /api/projects/ URL resolves alongside the legacy
- /api/environments/ alias. Both endpoints operate on the env-scoped TeamLogsConfig
- keyed by team_id."""
- config = get_or_create_team_extension(team, TeamLogsConfig)
-
- if request.method == "PATCH":
- serializer = TeamLogsConfigSerializer(config, data=request.data, partial=True)
- serializer.is_valid(raise_exception=True)
- serializer.save()
- return response.Response(serializer.data)
-
- return response.Response(TeamLogsConfigSerializer(config).data)
-
-
-def handle_evaluation_context_suggestions(request: request.Request, team: Team) -> response.Response:
- """Shared handler for the evaluation_context_suggestions action — exposed under both the
- team/environment and project routers so /api/projects/ and /api/environments/ cannot drift apart.
-
- Hide an evaluation context name from the flag editor's suggestion list, or restore it.
- POST hides the name; DELETE restores it. The underlying context row and any flags already
- using it are never modified — this only controls what gets suggested."""
- # Contexts are persisted under the project root team (see default_evaluation_contexts).
- root_team = team.parent_team or team
-
- context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")
- if not isinstance(context_name, str):
- return response.Response({"error": "context_name must be a string"}, status=400)
- context_name = normalize_context_name(context_name)
- if not context_name:
- return response.Response({"error": "context_name is required"}, status=400)
-
- if len(context_name) > 255:
- return response.Response({"error": "context_name must be at most 255 characters"}, status=400)
-
- hidden = request.method == "POST"
-
- with transaction.atomic():
- try:
- ctx = EvaluationContext.objects.select_for_update().get(name=context_name, team=root_team)
- except EvaluationContext.DoesNotExist:
- return response.Response({"error": "Evaluation context not found"}, status=404)
-
- if ctx.hidden_from_suggestions != hidden:
- ctx.hidden_from_suggestions = hidden
- ctx.save(update_fields=["hidden_from_suggestions"])
- report_user_action(
- cast(User, request.user),
- "evaluation context suggestion hidden" if hidden else "evaluation context suggestion restored",
- {"team_id": team.id, "context_name": context_name},
- team=team,
- request=request,
- )
-
- return response.Response({"success": True, "name": context_name, "hidden_from_suggestions": hidden})
-
-
-def validate_secret_token_generation(team: Team) -> None:
- """Rotating an existing legacy secret token stays allowed for safe migration, but minting a
- first one is blocked unless Support is enabled. Project secret API keys replace it."""
- if team.secret_api_token or team.secret_api_token_backup:
- return
- if team.conversations_enabled:
- # Support signs widget identity hashes with the raw token and authenticates its external
- # API against it. Project secret API keys are only ever stored hashed, so they cannot
- # replace it, which would leave Support with no way to verify identity at all.
- return
- raise exceptions.ValidationError(
- "The feature flags secure API key is deprecated. Create a project secret API key with the "
- "feature_flag:read scope instead."
- )
-
-
-def _format_serializer_errors(serializer_errors: dict) -> str:
- """Formats DRF serializer errors into a human readable string."""
- error_messages: list[str] = []
- for field, field_errors in serializer_errors.items():
- if isinstance(field_errors, list):
- error_messages.extend(f"{field}: {error}" for error in field_errors)
- else:
- error_messages.append(f"{field}: {field_errors}")
- return ". ".join(error_messages)
-
-
-class CachingTeamSerializer(serializers.ModelSerializer):
- """
- This serializer is used for caching teams.
- Currently used only in `/decide` endpoint.
- Has all parameters needed for a successful decide request.
- """
-
- organization_id = serializers.UUIDField(read_only=True)
-
- class Meta:
- model = Team
- fields = [
- "id",
- "project_id",
- "organization_id",
- "uuid",
- "name",
- "api_token",
- "autocapture_opt_out",
- "autocapture_exceptions_opt_in",
- "autocapture_web_vitals_opt_in",
- "autocapture_web_vitals_allowed_metrics",
- "autocapture_exceptions_errors_to_ignore",
- "capture_performance_opt_in",
- "capture_console_log_opt_in",
- "extra_settings",
- "secret_api_token",
- "secret_api_token_backup",
- "session_recording_opt_in",
- "session_recording_sample_rate",
- "session_recording_minimum_duration_milliseconds",
- "session_recording_linked_flag",
- "session_recording_network_payload_capture_config",
- "session_recording_masking_config",
- "session_recording_url_trigger_config",
- "session_recording_url_blocklist_config",
- "session_recording_event_trigger_config",
- "session_recording_trigger_match_type_config",
- "session_replay_config",
- "survey_config",
- "recording_domains",
- "inject_web_apps",
- "surveys_opt_in",
- "heatmaps_opt_in",
- "capture_dead_clicks",
- "flags_persistence_default",
- "conversations_enabled",
- "conversations_settings",
- "logs_settings",
- ]
- read_only_fields = fields
-
-
-TEAM_CONFIG_FIELDS = (
- "app_urls",
- "anonymize_ips",
- "completed_snippet_onboarding",
- "test_account_filters",
- "test_account_filters_default_checked",
- "path_cleaning_filters",
- "is_demo",
- "timezone",
- "data_attributes",
- "person_display_name_properties",
- "correlation_config",
- "autocapture_opt_out",
- "autocapture_exceptions_opt_in",
- "autocapture_web_vitals_opt_in",
- "autocapture_web_vitals_allowed_metrics",
- "autocapture_exceptions_errors_to_ignore",
- "capture_console_log_opt_in",
- "logs_settings",
- "capture_performance_opt_in",
- "session_recording_opt_in",
- "session_recording_sample_rate",
- "session_recording_minimum_duration_milliseconds",
- "session_recording_linked_flag",
- "session_recording_network_payload_capture_config",
- "session_recording_masking_config",
- "session_recording_url_trigger_config",
- "session_recording_url_blocklist_config",
- "session_recording_event_trigger_config",
- "session_recording_trigger_match_type_config",
- "session_recording_trigger_groups",
- "session_recording_retention_period",
- "session_replay_config",
- "survey_config",
- "week_start_day",
- "primary_dashboard",
- "home_tab_dashboard",
- "live_events_columns",
- "recording_domains",
- "cookieless_server_hash_mode",
- "human_friendly_comparison_periods",
- "inject_web_apps",
- "extra_settings",
- "modifiers",
- "has_completed_onboarding_for",
- "surveys_opt_in",
- "heatmaps_opt_in",
- "flags_persistence_default",
- "feature_flag_confirmation_enabled",
- "feature_flag_confirmation_message",
- "default_evaluation_contexts_enabled",
- "require_evaluation_contexts",
- "feature_flag_policy_config",
- "capture_dead_clicks",
- "default_data_theme",
- "revenue_analytics_config",
- "marketing_analytics_config",
- "customer_analytics_config",
- "onboarding_tasks",
- "base_currency",
- "web_analytics_pre_aggregated_tables_enabled",
- "receive_org_level_activity_logs",
- "business_model",
- "conversations_enabled",
- "conversations_settings",
- "proactive_tasks_enabled",
- "workflows_config",
-)
-
-TEAM_CONFIG_FIELDS_SET = set(TEAM_CONFIG_FIELDS)
-
-TEAM_CONFIG_MEMBER_FIELDS = (
- "completed_snippet_onboarding",
- "has_completed_onboarding_for",
- "onboarding_tasks",
- "session_recording_opt_in",
- "autocapture_exceptions_opt_in",
- "autocapture_web_vitals_opt_in",
- "autocapture_web_vitals_allowed_metrics",
- "surveys_opt_in",
- "primary_dashboard",
- "home_tab_dashboard",
-)
-TEAM_CONFIG_MEMBER_FIELDS_SET = set(TEAM_CONFIG_MEMBER_FIELDS)
-
-TEAM_CONFIG_ADMIN_FIELDS_SET: set[str] = (TEAM_CONFIG_FIELDS_SET - TEAM_CONFIG_MEMBER_FIELDS_SET) | {
- "is_demo",
- "app_urls",
- "access_control",
- # Renaming a project/environment is admin-only (the settings UI gates TeamDisplayName behind
- # useRestrictedArea(Admin)). Excluded from the create-time gate below so members allowed to
- # create projects can still name them.
- "name",
-}
-
-# Fields that are not member-safe but carry their own `field_access_control` (enforced in
-# UserAccessControlSerializerMixin.validate). The request-level scope can be downgraded for these so
-# the field-level check is the real authority — e.g. `app_urls` is governed by web_analytics:editor.
-TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS: set[str] = {"app_urls"}
-
-
-class TeamRevenueAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
- events = serializers.JSONField(required=False)
- filter_test_accounts = serializers.BooleanField(required=False)
-
- class Meta:
- model = TeamRevenueAnalyticsConfig
- fields = ["base_currency", "events", "filter_test_accounts"]
-
- def to_representation(self, instance):
- repr = super().to_representation(instance)
- if instance.events:
- repr["events"] = [event.model_dump() for event in instance.events]
- return repr
-
- def to_internal_value(self, data):
- internal_value = super().to_internal_value(data)
- if "events" in internal_value:
- internal_value["_events"] = internal_value["events"]
- return internal_value
-
-
-# The filters a conversion goal can carry, rather than every filter HogQL knows about. The goal
-# runtime resolves these through `property_to_expr` with an event scope, where `revenue_analytics`
-# and `account_custom_property` raise and `metric_attribute` is unimplemented, and the goal editor
-# only offers these six. Narrowing here follows `WebAnalyticsPropertyFilter`.
-MarketingAnalyticsConversionGoalPropertyFilter = (
- EventPropertyFilter
- | PersonPropertyFilter
- | CohortPropertyFilter
- | ElementPropertyFilter
- | HogQLPropertyFilter
- | DataWarehousePropertyFilter
-)
-
-
-# Subclassing the canonical goal schemas rather than redeclaring their ~25 fields keeps this write
-# surface from drifting when the query schema changes. The cost is that narrowing a field's type in
-# a subclass is not assignment-compatible, hence the ignores below: each one marks a deliberate
-# divergence from the query schema, not an oversight.
-#
-# `fixedProperties` stays accepted but leaves the documented schema: nothing in the marketing
-# analytics runtime reads it, and advertising it costs a third of this field's generated schema.
-class MarketingAnalyticsEventConversionGoal(ConversionGoalFilter1):
- """A conversion goal counted from events."""
-
- # `validate_conversion_goals` rejects a goal without a string name or an explicit kind, so the
- # documented schema has to require both. `conversion_goal_id` stays required like the query
- # schema: nothing here assigns one, and a goal stored without it fails to rebuild for queries.
- kind: Literal["EventsNode"]
- name: str
- properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
- fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
-
-
-class MarketingAnalyticsActionConversionGoal(ConversionGoalFilter2):
- """A conversion goal counted from an action."""
-
- kind: Literal["ActionsNode"]
- name: str
- properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
- fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
-
-
-class MarketingAnalyticsWarehouseConversionGoal(ConversionGoalFilter3):
- """A conversion goal counted from a data warehouse table."""
-
- kind: Literal["DataWarehouseNode"]
- name: str
- properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
- fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
-
-
-class MarketingAnalyticsConversionGoalList(PydanticRootModel):
- """The conversion goals configured for marketing analytics, in display order."""
-
- root: list[
- MarketingAnalyticsEventConversionGoal
- | MarketingAnalyticsActionConversionGoal
- | MarketingAnalyticsWarehouseConversionGoal
- ]
-
-
-class MarketingAnalyticsSourceMapping(PydanticRootModel):
- """Mapping of external data source id to that source's column mapping."""
-
- root: dict[str, SourceMap]
-
-
-class MarketingAnalyticsCampaignFieldPreferences(PydanticRootModel):
- """Mapping of integration type to the campaign field used when matching campaigns."""
-
- root: dict[str, CampaignFieldPreference]
-
-
-class MarketingAnalyticsCampaignNameMappings(PydanticRootModel):
- """Mapping of integration type to canonical campaign name to the aliases folded into it."""
-
- root: dict[str, dict[str, list[str]]]
-
-
-class MarketingAnalyticsCustomSourceMappings(PydanticRootModel):
- """Mapping of integration type to the custom UTM source values folded into it."""
-
- root: dict[str, list[str]]
-
-
-@extend_schema_field(MarketingAnalyticsCampaignNameMappings) # type: ignore[arg-type]
-class MarketingAnalyticsCampaignNameMappingsField(serializers.JSONField):
- pass
-
-
-@extend_schema_field(MarketingAnalyticsCustomSourceMappings) # type: ignore[arg-type]
-class MarketingAnalyticsCustomSourceMappingsField(serializers.JSONField):
- pass
-
-
-@extend_schema_field(MarketingAnalyticsConversionGoalList) # type: ignore[arg-type]
-class MarketingAnalyticsConversionGoalsField(serializers.JSONField):
- pass
-
-
-@extend_schema_field(MarketingAnalyticsSourceMapping) # type: ignore[arg-type]
-class MarketingAnalyticsSourcesMapField(serializers.JSONField):
- pass
-
-
-@extend_schema_field(MarketingAnalyticsCampaignFieldPreferences) # type: ignore[arg-type]
-class MarketingAnalyticsCampaignFieldPreferencesField(serializers.JSONField):
- pass
-
-
-class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
- sources_map = MarketingAnalyticsSourcesMapField(
- required=False,
- help_text=(
- "Column mapping per external data source, keyed by source id. Tells marketing analytics which column "
- "holds campaign, source, cost, clicks and impressions for that source."
- ),
- )
- conversion_goals = MarketingAnalyticsConversionGoalsField(
- required=False,
- help_text=(
- "Conversion goals to attribute against, in display order. Each goal points at an event, an action or a "
- "data warehouse table, and carries a schema_map describing which fields hold the UTM parameters, the "
- "timestamp and the distinct id. Replaces the whole list on write."
- ),
- )
- attribution_window_days = serializers.IntegerField(
- required=False,
- min_value=1,
- max_value=90,
- help_text="How many days back a touchpoint can be credited for a conversion. Between 1 and 90.",
- )
- attribution_mode = serializers.ChoiceField(
- choices=[(mode.value, mode.value.replace("_", " ").title()) for mode in AttributionMode],
- required=False,
- help_text="How credit is split across touchpoints when a person saw several campaigns before converting.",
- )
- filter_test_accounts = serializers.BooleanField(
- required=False,
- help_text=(
- "Whether marketing analytics drops traffic matching the project's test-account filters. Off by default."
- ),
- )
- campaign_name_mappings = MarketingAnalyticsCampaignNameMappingsField(
- required=False,
- help_text=(
- "Manual campaign name aliases, keyed by integration type then by canonical campaign name, with the list "
- "of names that should be folded into it. Applied before automatic matching."
- ),
- )
- custom_source_mappings = MarketingAnalyticsCustomSourceMappingsField(
- required=False,
- help_text=(
- "Custom UTM source values to fold into an integration, keyed by integration type. A UTM source can only "
- "belong to one integration."
- ),
- )
- campaign_field_preferences = MarketingAnalyticsCampaignFieldPreferencesField(
- required=False,
- help_text=(
- "Which field to match campaigns on per integration type, campaign_name or campaign_id. Manual mappings "
- "in campaign_name_mappings still take precedence."
- ),
- )
-
- class Meta:
- model = TeamMarketingAnalyticsConfig
- fields = [
- "sources_map",
- "conversion_goals",
- "attribution_window_days",
- "attribution_mode",
- "filter_test_accounts",
- "campaign_name_mappings",
- "custom_source_mappings",
- "campaign_field_preferences",
- ]
-
- def to_internal_value(self, data):
- internal_value = super().to_internal_value(data)
- if "sources_map" in internal_value:
- internal_value["_sources_map"] = internal_value["sources_map"]
- if "conversion_goals" in internal_value:
- internal_value["_conversion_goals"] = internal_value["conversion_goals"]
- if "campaign_name_mappings" in internal_value:
- internal_value["_campaign_name_mappings"] = internal_value["campaign_name_mappings"]
- if "custom_source_mappings" in internal_value:
- internal_value["_custom_source_mappings"] = internal_value["custom_source_mappings"]
- if "campaign_field_preferences" in internal_value:
- internal_value["_campaign_field_preferences"] = internal_value["campaign_field_preferences"]
- return internal_value
-
- @transaction.atomic
- def update(self, instance, validated_data):
- instance.refresh_from_db(from_queryset=TeamMarketingAnalyticsConfig.objects.select_for_update())
- # Handle sources_map with partial updates
- if "sources_map" in validated_data:
- new_sources_map = validated_data["sources_map"]
-
- # For each source in the new data, update it individually
- for source_id, field_mapping in new_sources_map.items():
- if field_mapping is None:
- # If None is passed, remove the source entirely
- instance.remove_source_mapping(source_id)
- else:
- # Update the source mapping (this preserves other sources)
- instance.update_source_mapping(source_id, field_mapping)
-
- if "conversion_goals" in validated_data:
- instance.conversion_goals = validated_data["conversion_goals"]
-
- # Handle attribution settings
- if "attribution_window_days" in validated_data:
- instance.attribution_window_days = validated_data["attribution_window_days"]
-
- if "attribution_mode" in validated_data:
- instance.attribution_mode = validated_data["attribution_mode"]
-
- if "filter_test_accounts" in validated_data:
- instance.filter_test_accounts = validated_data["filter_test_accounts"]
-
- if "campaign_name_mappings" in validated_data:
- instance.campaign_name_mappings = validated_data["campaign_name_mappings"]
-
- if "custom_source_mappings" in validated_data:
- instance.custom_source_mappings = validated_data["custom_source_mappings"]
-
- if "campaign_field_preferences" in validated_data:
- instance.campaign_field_preferences = validated_data["campaign_field_preferences"]
-
- instance.save()
- return instance
-
-
-class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
- capture_workflows_engagement_events = serializers.BooleanField(
- required=False,
- help_text=(
- "When enabled, workflows engagement activity (email sends, opens, clicks, bounces, "
- "spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) "
- "alongside the existing workflow metrics."
- ),
- )
- email_tracking_consent_mode = serializers.ChoiceField(
- choices=EMAIL_TRACKING_CONSENT_MODE_CHOICES,
- required=False,
- help_text=(
- "Recipient-consent enforcement for open/click tracking on marketing workflow emails. "
- "'off': no enforcement, tracking follows each email step's own setting. "
- "'opt_out': track by default but not recipients who have opted out. "
- "'opt_in': only track recipients who have explicitly opted in. "
- "Transactional emails are exempt from consent enforcement."
- ),
- )
- workflow_task_rate_limit_per_day = serializers.IntegerField(
- required=False,
- allow_null=True,
- min_value=0,
- help_text=(
- "How many AI tasks one workflow can create in a rolling 24 hours. "
- f"Null uses the default of {WORKFLOW_TASK_RATE_CAP_PER_DAY}; zero pauses task creation "
- f"for every workflow in the project. Support raises the limit above "
- f"{MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY}."
- ),
- )
- workflow_task_team_rate_limit_per_day = serializers.IntegerField(
- required=False,
- allow_null=True,
- min_value=0,
- help_text=(
- "How many AI tasks all workflows in the project can create together in a rolling "
- f"24 hours. Null uses the default of {WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY}; zero pauses "
- f"task creation for the project. Support raises the limit above "
- f"{MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY}."
- ),
- )
- marketing_frequency_cap_max_messages = serializers.IntegerField(
- required=False,
- allow_null=True,
- min_value=1,
- max_value=1000,
- help_text=(
- "Most marketing messages one person can get in the window, across all workflows. "
- "Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off."
- ),
- )
- marketing_frequency_cap_window_days = serializers.IntegerField(
- required=False,
- allow_null=True,
- min_value=1,
- max_value=30,
- help_text=(
- "Length of the rolling frequency cap window in days. "
- "Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off."
- ),
- )
-
- default_email_integration_id = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text=(
- "ID of the verified email integration that new broadcasts and workflow email steps use as "
- "their sender. Null means no default. Set automatically when the project's first email "
- "sender is verified, and cleared when that integration is deleted."
- ),
- )
-
- class Meta:
- model = TeamWorkflowsConfig
- fields = [
- "capture_workflows_engagement_events",
- "email_tracking_consent_mode",
- "workflow_task_rate_limit_per_day",
- "workflow_task_team_rate_limit_per_day",
- "default_email_integration_id",
- "marketing_frequency_cap_max_messages",
- "marketing_frequency_cap_window_days",
- ]
-
- def _enforce_self_serve_ceiling(self, field: str, value: int | None, ceiling: int) -> int | None:
- # As a nested field there is no stored row to compare against; the parent serializer
- # re-runs this serializer bound to the row in validate_workflows_config.
- if self.parent:
- return value
- # Support raises a project past the ceiling in Django admin; clients that echo the whole
- # config must be able to send that value back unchanged. Read the row fresh: the
- # `Team.workflows_config` accessor is cached per process and can be stale.
- if value is not None and value > ceiling:
- stored = (
- TeamWorkflowsConfig.objects.filter(pk=self.instance.pk).values_list(field, flat=True).first()
- if self.instance is not None
- else None
- )
- if stored != value:
- raise serializers.ValidationError(f"Contact support to go above {ceiling} tasks a day.")
- return value
-
- def validate_workflow_task_rate_limit_per_day(self, value: int | None) -> int | None:
- return self._enforce_self_serve_ceiling(
- "workflow_task_rate_limit_per_day", value, MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY
- )
-
- def validate_workflow_task_team_rate_limit_per_day(self, value: int | None) -> int | None:
- return self._enforce_self_serve_ceiling(
- "workflow_task_team_rate_limit_per_day", value, MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY
- )
-
- def validate_default_email_integration_id(self, value: int | None) -> int | None:
- if self.parent or value is None:
- return value
- sender = (
- Integration.objects.filter(team_id=self.instance.team_id, kind="email", id=value).only("config").first()
- if self.instance is not None
- else None
- )
- if sender is None:
- raise serializers.ValidationError("Choose an email sender from this project.")
- if not sender.config.get("verified"):
- raise serializers.ValidationError("Verify this sender's domain before making it the default.")
- return value
-
- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
- # As a nested field of the team serializer there is no stored row to merge a partial update with.
- # validate_team_workflows_config runs this serializer again with the row, and that run does the check.
- if self.parent:
- return attrs
- cap_fields = ("marketing_frequency_cap_max_messages", "marketing_frequency_cap_window_days")
- cap = {field: attrs[field] for field in cap_fields if field in attrs}
- if len(cap) == 1 and self.instance is not None:
- # Read the stored row, because `Team.workflows_config` is a cached_property on the Team instance
- # and can hold values from before an earlier update.
- stored = TeamWorkflowsConfig.objects.filter(pk=self.instance.pk).values(*cap_fields).first() or {}
- cap = {**stored, **cap}
- # The worker treats either null as no cap, so a half-set cap would save but never apply.
- if cap:
- missing = [field for field in cap_fields if cap.get(field) is None]
- if len(missing) == 1:
- other = next(field for field in cap_fields if field != missing[0])
- raise serializers.ValidationError(
- {missing[0]: f"Set this together with {other}, or set both to null to turn the frequency cap off."}
- )
- return attrs
-
-
-def validate_team_workflows_config(team: Team | None, value: dict[str, Any] | None) -> dict[str, Any] | None:
- if value is None:
- return None
-
- serializer = TeamWorkflowsConfigSerializer(team.workflows_config if team else None, data=value)
- if not serializer.is_valid():
- raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
- return serializer.validated_data
-
-
-class TeamFeatureFlagPolicyConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
- require_tags = serializers.BooleanField(
- required=False,
- help_text=(
- "When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its "
- "last one. A create that declares it comes from a survey, experiment, early access feature, "
- "product tour, or web experiment is exempt, because those forms have no tag input. The caller "
- "sets that declaration, so a flag can still be created without a tag."
- ),
- )
-
- class Meta:
- model = TeamFeatureFlagPolicyConfig
- fields = ["require_tags"]
-
-
-class TeamCustomerAnalyticsPinnedAccountPropertySerializer(serializers.Serializer):
- kind = serializers.ChoiceField(
- choices=AccountPropertyPinKind.choices,
- help_text="Definition type for this default pinned account property.",
- )
- id = serializers.UUIDField(help_text="Project-scoped custom property or relationship definition UUID.")
-
- class Meta:
- ref_name = "TeamCustomerAnalyticsPinnedAccountProperty"
-
-
-class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
- activity_event = serializers.JSONField(required=False, help_text="Event used as the activity signal (DAU/WAU/MAU).")
- signup_pageview_event = serializers.JSONField(
- required=False, help_text="Event used to count signup pageviews on dashboards."
- )
- signup_event = serializers.JSONField(required=False, help_text="Event used to count signups on dashboards.")
- subscription_event = serializers.JSONField(
- required=False, help_text="Event used to count subscriptions on dashboards."
- )
- payment_event = serializers.JSONField(required=False, help_text="Event used to count payments on dashboards.")
- account_group_type_index = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text=(
- "Index of the group type to treat as an Account in customer analytics. "
- "Must reference an existing group type configured for the project."
- ),
- )
- default_pinned_properties = TeamCustomerAnalyticsPinnedAccountPropertySerializer(
- many=True,
- allow_empty=True,
- required=False,
- help_text=(
- "Ordered account properties shown until a user saves a personal pinned-property selection. "
- "Pass an empty list to show no properties by default."
- ),
- )
-
- class Meta:
- model = TeamCustomerAnalyticsConfig
- fields = [
- "activity_event",
- "signup_pageview_event",
- "signup_event",
- "subscription_event",
- "payment_event",
- "account_group_type_index",
- "default_pinned_properties",
- ]
-
- def update(
- self, instance: TeamCustomerAnalyticsConfig, validated_data: dict[str, Any]
- ) -> TeamCustomerAnalyticsConfig:
- for attr, value in validated_data.items():
- setattr(instance, attr, value)
- # The account track rules on this row are written by their own path, so a settings save must
- # not carry a stale copy of them back to the database.
- instance.save(update_fields=list(validated_data))
- return instance
-
- @staticmethod
- def validate_account_group_type_index(value):
- return validate_group_type_index("account_group_type_index", value)
-
- def validate_default_pinned_properties(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:
- if self.instance is None:
- return value
- pinned_properties = [PinnedAccountProperty(kind=reference["kind"], id=reference["id"]) for reference in value]
- try:
- validate_pinned_account_properties(
- team_id=self.instance.team_id,
- pinned_properties=pinned_properties,
- )
- except InvalidPinnedAccountProperties as error:
- raise serializers.ValidationError(error.errors)
- return [{"kind": reference["kind"], "id": str(reference["id"])} for reference in value]
-
-
-_VALID_TRIGGER_PROPERTY_OPERATORS = {
- "exact",
- "is_not",
- "icontains",
- "not_icontains",
- "regex",
- "not_regex",
- "gt",
- "lt",
-}
-
-# Property types the SDK can evaluate client-side
-_VALID_TRIGGER_PROPERTY_TYPES = {
- "event",
- "person",
-}
-
-
-def _validate_trigger_property_filters(properties: object, context: str) -> None:
- """Validate property filters on trigger conditions (events, URLs)."""
- if not isinstance(properties, list):
- raise exceptions.ValidationError(f"{context}: 'properties' must be an array.")
-
- for prop_idx, prop in enumerate(properties):
- if not isinstance(prop, dict):
- raise exceptions.ValidationError(f"{context}: property {prop_idx} must be a dictionary.")
- if "key" not in prop or not isinstance(prop["key"], str):
- raise exceptions.ValidationError(f"{context}: property {prop_idx} must have a string 'key' field.")
- if "type" not in prop or prop["type"] not in _VALID_TRIGGER_PROPERTY_TYPES:
- raise exceptions.ValidationError(
- f"{context}: property {prop_idx} must have a 'type' field with value: "
- f"{', '.join(sorted(_VALID_TRIGGER_PROPERTY_TYPES))}."
- )
- if "operator" in prop and prop["operator"] not in _VALID_TRIGGER_PROPERTY_OPERATORS:
- raise exceptions.ValidationError(
- f"{context}: property {prop_idx} has invalid operator '{prop['operator']}'. "
- f"Valid operators: {', '.join(sorted(_VALID_TRIGGER_PROPERTY_OPERATORS))}."
- )
- # All supported operators require a value (is_set/is_not_set are not supported)
- if "value" not in prop:
- raise exceptions.ValidationError(f"{context}: property {prop_idx} must have a 'value' field.")
-
-
-test_account_filters_adapter = TypeAdapter(list[AnyPropertyFilter])
-
-
-def validate_test_account_filters(value: object) -> list[dict[str, object]]:
- try:
- test_account_filters_adapter.validate_python(value)
- except PydanticValidationError as error:
- raise exceptions.ValidationError(f"Must provide an array of valid property filters. {error}") from error
-
- return cast(list[dict[str, object]], value)
-
-
-def _alias_backreferences(alias: str) -> list[int]:
- """Return the capture-group numbers a re2 replacement alias references (`\\1`..`\\9`, `\\0` for the
- whole match). A doubled `\\\\` is a literal backslash, not a back-reference, so it's skipped."""
- refs: list[int] = []
- i = 0
- while i < len(alias):
- if alias[i] == "\\" and i + 1 < len(alias):
- nxt = alias[i + 1]
- if nxt == "\\":
- i += 2
- continue
- # ASCII digits only. `str.isdigit()` also accepts characters like `²` and `٣`, which re2
- # substitutes as literal text, and `int()` rejects `²` outright.
- if "0" <= nxt <= "9":
- refs.append(int(nxt))
- i += 2
- continue
- i += 1
- return refs
-
-
-def validate_path_cleaning_filters(value: object) -> object:
- """Validate path cleaning rules before they're saved. Each regex must compile under re2 (the
- engine ClickHouse `replaceRegexpAll` uses), and any `\\1`..`\\9` back-reference in the alias must
- point at a capture group the regex defines. This surfaces a mistake at save time instead of
- letting it fail the query later, when path cleaning runs."""
- if not value:
- return value
- if not isinstance(value, list):
- raise exceptions.ValidationError("Must provide a list of path cleaning rules.")
-
- for rule in value:
- if not isinstance(rule, dict):
- continue
- regex = rule.get("regex")
- alias = rule.get("alias")
- # A missing or empty regex still reaches ClickHouse, where `replaceRegexpAll` returns NULL for
- # a NULL pattern and an empty pattern matches at every position, interleaving the alias
- # through the whole path. Neither is recoverable at query time, so refuse the rule.
- if not isinstance(regex, str) or not regex:
- raise exceptions.ValidationError("A path cleaning rule needs a regex. Remove the rule or give it one.")
- try:
- compiled = re2.compile(regex)
- except re2.error as error:
- raise exceptions.ValidationError(f"Invalid path cleaning regex '{regex}': {error}") from error
-
- if not alias or not isinstance(alias, str):
- continue
- group_count = compiled.groups
- for ref in _alias_backreferences(alias):
- if ref > group_count:
- raise exceptions.ValidationError(
- f"The alias '{alias}' references capture group \\{ref}, but its regex has "
- f"{group_count} capture group(s). Add the group to the regex or fix the reference."
- )
- return value
-
-
-_default_theme_id_cache: int | None = None
-
-
-def _default_data_color_theme_id() -> int | None:
- """Return the system-wide default DataColorTheme id, cached for process lifetime.
-
- The default is created by data migration `0537_data_color_themes.py` and
- is effectively a constant after deploy - cache it to skip a per-render PG
- round-trip in `TeamSerializer.to_representation` for orgs without the
- DATA_COLOR_THEMES feature.
-
- We deliberately do NOT cache `None`: if the first call lands before the
- migration is applied, or against an instance where no global default
- exists yet, we want subsequent calls to recover automatically once the
- row appears. `.order_by("id")` keeps the chosen ID deterministic across
- workers if multiple globals ever exist.
- """
- global _default_theme_id_cache
- if _default_theme_id_cache is None:
- _default_theme_id_cache = (
- DataColorTheme.objects.filter(team_id__isnull=True).order_by("id").values_list("id", flat=True).first()
- )
- return _default_theme_id_cache
-
-
-def _reset_default_data_color_theme_id_cache() -> None:
- """Test-only helper for explicit cache invalidation."""
- global _default_theme_id_cache
- _default_theme_id_cache = None
-
-
-LIVE_EVENTS_TOKEN_TTL_SECONDS = 24 * 60 * 60
-
-
-def _live_events_token_cache_key(team: Team, user_id: int | None) -> str:
- """Build the cache key for the live-events JWT.
-
- Includes a short fingerprint of `settings.JWT_SIGNING_KEY` so that rotating the
- signing key automatically partitions the cache namespace - cached tokens signed
- with the old key become unreachable rather than served until TTL.
- Hashing also defends the cache key against future api-token formats that
- might contain the `:` separator we use between components.
- """
- signing_fingerprint = signing_key_fingerprint(settings.JWT_SIGNING_KEY)
- return f"live_events_token:{signing_fingerprint}:{team.id}:{user_id}:{team.api_token}:{team.organization_id}"
-
-
-def get_or_mint_live_events_token(team: Team, user_id: int | None) -> str:
- """Return a cached live-events JWT for this (team, user) pair, minting one if missing.
-
- The JWT itself is valid for 7 days. The cache TTL is 24h, so any token returned
- from cache still has at least 6 days of remaining validity. The cache key includes
- every field that ends up in the claims so api-token rotations or organization
- moves automatically force a fresh mint, plus a JWT_SIGNING_KEY fingerprint so
- signing-key rotation auto-partitions the cache namespace (no manual flush needed).
- """
- cache_key = _live_events_token_cache_key(team, user_id)
- cached = get_safe_cache(cache_key)
- if cached is not None:
- return cached
-
- claims = {
- "team_id": team.id,
- "api_token": team.api_token,
- "user_id": user_id,
- "organization_id": str(team.organization_id),
- }
- token = encode_jwt(claims, timedelta(days=7), PosthogJwtAudience.LIVESTREAM)
- safe_cache_set(cache_key, token, timeout=LIVE_EVENTS_TOKEN_TTL_SECONDS)
- return token
-
-
-def heatmaps_screenshot_secret_for_reader(team: Team, user_permissions: UserPermissions) -> str | None:
- level = user_permissions.team(team).effective_membership_level
- if level is None or level < OrganizationMembership.Level.ADMIN:
- return None
- return team.heatmaps_screenshot_secret
-
-
-def _get_organization_for_logs_settings_check(serializer: serializers.BaseSerializer) -> Organization | None:
- if serializer.instance is not None:
- team = (
- serializer.instance.passthrough_team
- if hasattr(serializer.instance, "passthrough_team")
- else serializer.instance
- )
- return team.organization
-
- get_organization = serializer.context.get("get_organization")
- if callable(get_organization):
- return cast(Organization | None, get_organization())
-
- return None
-
-
-def _flag_enabled_for_caller(flag: str, organization: Organization | None, user: Any, team: Team | None) -> bool:
- if organization is None or user is None or not user.is_authenticated:
- return False
- return posthog_feature_flag_enabled(
- flag,
- str(user.distinct_id),
- organization_id=organization.id,
- team_id=team.id if team is not None else None,
- )
-
-
-def _custom_retention_flag_enabled(organization: Organization | None, user: Any, team: Team | None) -> bool:
- """Whether the caller may pick a retention period outside the base tiers."""
- return _flag_enabled_for_caller(LOGS_CUSTOM_RETENTION_FLAG, organization, user, team)
-
-
-def _check_traces_retention_entitlement(days: int, organization: Organization | None) -> None:
- # Traces reuse the Logs retention entitlement.
- required_feature = required_logs_retention_feature(days)
- if required_feature and (organization is None or not organization.is_feature_available(required_feature)):
- raise exceptions.PermissionDenied(
- f"This organization does not have permission to set traces retention to {days} days."
- )
-
-
-def _custom_logs_retention_enabled(serializer: serializers.BaseSerializer, team: Team | None) -> bool:
- request = serializer.context.get("request")
- return _custom_retention_flag_enabled(
- _get_organization_for_logs_settings_check(serializer), getattr(request, "user", None), team
- )
-
-
-@extend_schema_field(OpenApiTypes.OBJECT)
-class ConversationsSettingsField(serializers.JSONField):
- pass
-
-
-def merge_modifiers(requested: dict | None, existing: object) -> dict | None:
- # Django admin can store a scalar or list here. Treat it as empty rather than raising.
- stored = existing if isinstance(existing, dict) else {}
- if requested is not None:
- return {**stored, **requested}
- # PostHog staff set useNewEventsSchema per project, so a client that clears its modifiers keeps it.
- if "useNewEventsSchema" in stored:
- return {"useNewEventsSchema": stored["useNewEventsSchema"]}
- return None
-
-
-def live_events_token_for_request(team: Team, request: request.Request | None) -> str | None:
- if request is None or not request.user.is_authenticated:
- return None
- scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
- if scopes is not None and "*" not in scopes and scopes_not_covered(scopes, ["query:read"]):
- return None
- return get_or_mint_live_events_token(team, request.user.id)
-
-
-class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):
- instance: Team | None
- _group_types_cache: list[dict[str, Any]] | None = None
-
- effective_membership_level = serializers.SerializerMethodField()
- has_group_types = serializers.SerializerMethodField()
- group_types = serializers.SerializerMethodField()
- live_events_token = serializers.SerializerMethodField()
- product_intents = serializers.SerializerMethodField()
- managed_viewsets = serializers.SerializerMethodField()
- flag_evaluations_mode = serializers.SerializerMethodField(
- help_text=(
- "Which table this project's feature flag usage data is read from. PostHog sets it for the "
- "whole organization. 0 reads the events table. 1 and 2 read the flag_evaluations table."
- )
- )
- available_setup_task_ids = serializers.SerializerMethodField()
- revenue_analytics_config = TeamRevenueAnalyticsConfigSerializer(required=False)
- marketing_analytics_config = TeamMarketingAnalyticsConfigSerializer(required=False)
- customer_analytics_config = TeamCustomerAnalyticsConfigSerializer(required=False)
- workflows_config = TeamWorkflowsConfigSerializer(required=False)
- feature_flag_policy_config = TeamFeatureFlagPolicyConfigSerializer(required=False)
- base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, default=DEFAULT_CURRENCY)
- conversations_settings = ConversationsSettingsField(
- required=False,
- allow_null=True,
- help_text="Settings for Conversations. Must be a JSON object or null.",
- )
- home_tab_dashboard = TeamScopedPrimaryKeyRelatedField(
- queryset=Dashboard.objects.all(),
- required=False,
- allow_null=True,
- error_messages={"does_not_exist": "Dashboard does not belong to this team."},
- help_text=(
- "ID of the dashboard shown on the product analytics Home tab. Null shows the built-in generic view."
- ),
- )
-
- heatmaps_screenshot_secret = serializers.SerializerMethodField(
- help_text=(
- "Value this project's heatmap screenshots send as a cookie scoped to your domain, "
- "so bot protection can allow them. Only project admins can read it; null for "
- "everyone else and when none has been generated."
- ),
- )
-
- class Meta:
- model = Team
- fields = (
- "id",
- "uuid",
- "name",
- "access_control",
- "organization",
- "project_id",
- "api_token",
- "secret_api_token",
- "secret_api_token_backup",
- "heatmaps_screenshot_secret",
- "created_at",
- "updated_at",
- "ingested_event",
- "default_modifiers",
- "person_on_events_querying_enabled",
- "user_access_level",
- # Config fields
- *TEAM_CONFIG_FIELDS,
- # Computed fields
- "effective_membership_level",
- "has_group_types",
- "group_types",
- "live_events_token",
- "product_intents",
- "managed_viewsets",
- "flag_evaluations_mode",
- "available_setup_task_ids",
- )
-
- read_only_fields = (
- "id",
- "uuid",
- "organization",
- "project_id",
- "api_token",
- "secret_api_token",
- "secret_api_token_backup",
- "created_at",
- "updated_at",
- "ingested_event",
- "effective_membership_level",
- "has_group_types",
- "group_types",
- "default_modifiers",
- "person_on_events_querying_enabled",
- "live_events_token",
- "user_access_level",
- "product_intents",
- "managed_viewsets",
- "flag_evaluations_mode",
- "available_setup_task_ids",
- )
-
- def get_fields(self) -> dict[str, serializers.Field]:
- if isinstance(self.instance, Team):
- self.context["team_id"] = self.instance.pk
- return super().get_fields()
-
- def to_representation(self, instance):
- with tracer.start_as_current_span("team_serializer.default_fields"):
- representation = super().to_representation(instance)
- # fallback to the default posthog data theme id, if the color feature isn't available e.g. after a downgrade
- if not instance.organization.is_feature_available(AvailableFeature.DATA_COLOR_THEMES):
- with tracer.start_as_current_span("team_serializer.default_data_theme_fallback"):
- representation["default_data_theme"] = _default_data_color_theme_id()
-
- return representation
-
- @tracer.start_as_current_span("team_serializer.effective_membership_level")
- def get_effective_membership_level(self, team: Team) -> OrganizationMembership.Level | None:
- # TODO: Map from user_access_controls
- return self.user_permissions.team(team).effective_membership_level
-
- @tracer.start_as_current_span("team_serializer.has_group_types")
- def get_has_group_types(self, team: Team) -> bool:
- return bool(self._get_group_types(team))
-
- @tracer.start_as_current_span("team_serializer.group_types")
- def get_group_types(self, team: Team) -> list[dict[str, Any]]:
- return self._get_group_types(team)
-
- def _get_group_types(self, team: Team) -> list[dict[str, Any]]:
- group_types = self._group_types_cache
- if group_types is None:
- group_types = cached_group_types_for_team(team)
- self._group_types_cache = group_types
- return group_types
-
- @tracer.start_as_current_span("team_serializer.live_events_token")
- def get_live_events_token(self, team: Team) -> str | None:
- return live_events_token_for_request(team, self.context.get("request"))
-
- @extend_schema_field(serializers.CharField(allow_null=True))
- def get_heatmaps_screenshot_secret(self, team: Team) -> str | None:
- return heatmaps_screenshot_secret_for_reader(team, self.user_permissions)
-
- @extend_schema_field(serializers.ListField(child=serializers.DictField()))
- @tracer.start_as_current_span("team_serializer.product_intents")
- def get_product_intents(self, obj):
- # Debounce-then-enqueue rather than .delay() on every render. The helper
- # checks a cache key first and skips the broker round-trip entirely if
- # we've already enqueued for this team in the last 24h. 99% of renders
- # become a cache hit; the remaining ones still enqueue exactly as before.
- enqueue_product_activation_calc_debounced(obj.id)
- return cached_product_intents_for_team(obj.id)
-
- @extend_schema_field(serializers.DictField(child=serializers.BooleanField()))
- @tracer.start_as_current_span("team_serializer.managed_viewsets")
- def get_managed_viewsets(self, obj):
- from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
- from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind
-
- enabled_viewsets = DataWarehouseManagedViewSet.objects.filter(team=obj).values_list("kind", flat=True)
- enabled_set = set(enabled_viewsets)
-
- return {kind: (kind in enabled_set) for kind, _ in DataWarehouseManagedViewSetKind.choices}
-
- @extend_schema_field(serializers.ChoiceField(choices=FlagEvaluationsMode.choices))
- def get_flag_evaluations_mode(self, obj: Team) -> int:
- return get_flag_evaluations_read_mode(obj.organization_id)
-
- @extend_schema_field(
- serializers.ListField(child=serializers.ChoiceField(choices=[(e.value, e.value) for e in SetupTaskId]))
- )
- def get_available_setup_task_ids(self, obj) -> list[str]:
- return [e.value for e in SetupTaskId]
-
- @staticmethod
- def validate_test_account_filters(value: object) -> list[dict[str, object]]:
- return validate_test_account_filters(value)
-
- @staticmethod
- def validate_path_cleaning_filters(value: object) -> object:
- return validate_path_cleaning_filters(value)
-
- @staticmethod
- def validate_revenue_analytics_config(value):
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- serializer = TeamRevenueAnalyticsConfigSerializer(data=value)
- if not serializer.is_valid():
- raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
-
- return serializer.validated_data
-
- @staticmethod
- def validate_marketing_analytics_config(value):
- if value is None:
- return None
-
- serializer = TeamMarketingAnalyticsConfigSerializer(data=value)
- if not serializer.is_valid():
- raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
- return serializer.validated_data
-
- @staticmethod
- def validate_customer_analytics_config(value):
- if value is None:
- return None
-
- serializer = TeamCustomerAnalyticsConfigSerializer(data=value)
- if not serializer.is_valid():
- raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
- return serializer.validated_data
-
- def validate_workflows_config(self, value):
- return validate_team_workflows_config(self.instance, value)
-
- @staticmethod
- def validate_feature_flag_policy_config(value):
- if value is None:
- return None
-
- serializer = TeamFeatureFlagPolicyConfigSerializer(data=value)
- if not serializer.is_valid():
- raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
- return serializer.validated_data
-
- @staticmethod
- def validate_session_recording_linked_flag(value) -> dict | None:
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
- received_keys = value.keys()
- valid_keys = [
- {"id", "key"},
- {"id", "key", "variant"},
- ]
- if received_keys not in valid_keys:
- raise exceptions.ValidationError(
- "Must provide a dictionary with only 'id' and 'key' keys. _or_ only 'id', 'key', and 'variant' keys."
- )
-
- # jsonb containment (`__contains={"id": <int>}`) is type-sensitive, so a non-integer id
- # makes the flag-delete guard miss this row and delete a flag the team still advertises.
- # A numeric string is normalized instead of rejected, so a client sending "123" stores a
- # usable row rather than a broken one. Bools and floats are excluded because
- # isinstance(True, int) is True, and int(12.5) would silently link flag 12.
- flag_id = value["id"]
- if isinstance(flag_id, bool) or not isinstance(flag_id, int | str):
- raise exceptions.ValidationError("Must provide an integer 'id'.")
- try:
- return {**value, "id": int(flag_id)}
- except ValueError:
- raise exceptions.ValidationError("Must provide an integer 'id'.")
-
- @staticmethod
- def validate_session_recording_trigger_match_type_config(value) -> Literal["all", "any"] | None:
- if value not in ["all", "any", None]:
- raise exceptions.ValidationError(
- "Must provide a valid trigger match type. Only 'all' or 'any' or None are allowed."
- )
-
- return value
-
- @staticmethod
- def validate_session_recording_trigger_groups(value) -> dict | None:
- """
- Validate V2 trigger groups configuration.
-
- Expected schema:
- {
- "version": 2,
- "groups": [
- {
- "id": "string",
- "name": "string" (optional),
- "sampleRate": 0.0-1.0,
- "minDurationMs": 0-30000 (optional),
- "conditions": {
- "matchType": "any" | "all",
- "events": ["event1", ...] (optional),
- "urls": [{"url": "regex", "matching": "regex"}] (optional),
- "flag": "flag-key" | {"id": 1, "key": "flag-key", "variant": "test"} (optional, single flag)
- }
- }
- ]
- }
- """
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- # Validate version
- if "version" not in value:
- raise exceptions.ValidationError("Missing required field: 'version'.")
-
- if value["version"] != 2:
- raise exceptions.ValidationError(f"Invalid version: {value['version']}. Only version 2 is supported.")
-
- # Validate groups array
- if "groups" not in value:
- raise exceptions.ValidationError("Missing required field: 'groups'.")
-
- if not isinstance(value["groups"], list):
- raise exceptions.ValidationError("Field 'groups' must be an array.")
-
- # Validate each group
- for idx, group in enumerate(value["groups"]):
- # Inline validation of each trigger group
- if not isinstance(group, dict):
- raise exceptions.ValidationError(f"Group {idx}: must be a dictionary.")
-
- # Required fields
- required_fields = ["id", "sampleRate", "conditions"]
- for field in required_fields:
- if field not in group:
- raise exceptions.ValidationError(f"Group {idx}: missing required field '{field}'.")
-
- # Validate sampleRate
- rate = group["sampleRate"]
- if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not (0 <= rate <= 1):
- raise exceptions.ValidationError(
- f"Group {idx}: invalid sampleRate '{rate}'. Must be a number between 0 and 1."
- )
-
- # Validate minDurationMs if present
- if "minDurationMs" in group:
- min_duration = group["minDurationMs"]
- if isinstance(min_duration, bool) or not isinstance(min_duration, int):
- raise exceptions.ValidationError(
- f"Group {idx}: 'minDurationMs' must be an integer, got {type(min_duration).__name__}."
- )
- if min_duration < 0 or min_duration > 30000:
- raise exceptions.ValidationError(
- f"Group {idx}: 'minDurationMs' must be between 0 and 30000 (30 seconds). Got: {min_duration}."
- )
-
- # Validate conditions
- conditions = group["conditions"]
- if not isinstance(conditions, dict):
- raise exceptions.ValidationError(f"Group {idx}: field 'conditions' must be a dictionary.")
-
- # Validate matchType
- if "matchType" in conditions:
- if conditions["matchType"] not in ["any", "all"]:
- raise exceptions.ValidationError(
- f"Group {idx}: invalid matchType '{conditions['matchType']}'. Must be 'any' or 'all'."
- )
-
- # Validate events array if present
- if "events" in conditions:
- if not isinstance(conditions["events"], list):
- raise exceptions.ValidationError(f"Group {idx}: field 'events' must be an array.")
- for event_idx, event in enumerate(conditions["events"]):
- if isinstance(event, str):
- pass # Simple event name is valid
- elif isinstance(event, dict):
- if "name" not in event or not isinstance(event["name"], str):
- raise exceptions.ValidationError(
- f"Group {idx}: event {event_idx} object must have a string 'name' field."
- )
- if "properties" in event:
- _validate_trigger_property_filters(
- event["properties"], f"Group {idx}, event '{event['name']}'"
- )
- else:
- raise exceptions.ValidationError(
- f"Group {idx}: event {event_idx} must be a string or object with 'name'."
- )
-
- # Validate URLs array if present
- if "urls" in conditions:
- if not isinstance(conditions["urls"], list):
- raise exceptions.ValidationError(f"Group {idx}: field 'urls' must be an array.")
- for url_config in conditions["urls"]:
- if not isinstance(url_config, dict):
- raise exceptions.ValidationError(f"Group {idx}: URL config must be a dictionary.")
- if "url" not in url_config or "matching" not in url_config:
- raise exceptions.ValidationError(
- f"Group {idx}: URL config must have 'url' and 'matching' fields."
- )
- if url_config["matching"] != "regex":
- raise exceptions.ValidationError(
- f"Group {idx}: URL matching must be 'regex'. Got: '{url_config['matching']}'."
- )
- # Validate regex pattern
- try:
- re.compile(url_config["url"])
- except re.error:
- raise exceptions.ValidationError(
- f"Group {idx}: invalid regex pattern in URL: '{url_config['url']}'."
- )
-
- # Validate flag (single) if present
- if "flag" in conditions:
- flag_config = conditions["flag"]
- if isinstance(flag_config, str):
- pass # Simple flag key is valid
- elif isinstance(flag_config, dict):
- # LinkedFeatureFlag object with id, key, and optional variant
- if "key" not in flag_config:
- raise exceptions.ValidationError(f"Group {idx}: flag object must have 'key' field.")
- if not isinstance(flag_config["key"], str):
- raise exceptions.ValidationError(f"Group {idx}: flag 'key' must be a string.")
- # id and variant are optional
- elif flag_config is not None:
- raise exceptions.ValidationError(
- f"Group {idx}: 'flag' must be a string (flag key), object (LinkedFeatureFlag), or null."
- )
-
- # Validate group-level property filters (shared WHERE clause for all triggers in group)
- if "properties" in conditions:
- _validate_trigger_property_filters(conditions["properties"], f"Group {idx}")
-
- # Note: All matching groups are evaluated independently
- # If any group's sample rate hits, the session is recorded (union behavior)
-
- # Validate fallback sample rate if present
- if "fallbackSampleRate" in value:
- rate = value["fallbackSampleRate"]
- if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not (0 <= rate <= 1):
- raise exceptions.ValidationError(
- f"Invalid fallbackSampleRate: {rate}. Must be a number between 0 and 1."
- )
-
- return value
-
- @staticmethod
- def validate_session_recording_retention_period(value) -> Literal["30d", "90d", "1y", "5y"] | None:
- if not validate_retention_period(value):
- raise exceptions.ValidationError(
- f"Must provide a valid retention period. Options are: {VALID_RETENTION_PERIODS}."
- )
-
- return value
-
- @staticmethod
- def validate_session_recording_network_payload_capture_config(value) -> dict | None:
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- if not all(key in ["recordHeaders", "recordBody"] for key in value.keys()):
- raise exceptions.ValidationError(
- "Must provide a dictionary with only 'recordHeaders' and/or 'recordBody' keys."
- )
-
- return value
-
- @staticmethod
- def validate_session_recording_masking_config(value) -> dict | None:
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- allowed_keys = {"maskAllInputs", "maskTextSelector", "blockSelector"}
-
- if not all(key in allowed_keys for key in value.keys()):
- raise exceptions.ValidationError(
- f"Must provide a dictionary with only known keys: {', '.join(allowed_keys)}."
- )
-
- if "maskAllInputs" in value:
- if not isinstance(value["maskAllInputs"], bool):
- raise exceptions.ValidationError("maskAllInputs must be a boolean.")
-
- if "maskTextSelector" in value:
- if not isinstance(value["maskTextSelector"], str):
- raise exceptions.ValidationError("maskTextSelector must be a string.")
-
- if "blockSelector" in value:
- if not isinstance(value["blockSelector"], str):
- raise exceptions.ValidationError("blockSelector must be a string.")
-
- return value
-
- @staticmethod
- def validate_session_replay_config(value) -> dict | None:
- if value is None:
- return None
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- known_keys = ["record_canvas", "ai_config"]
- if not all(key in known_keys for key in value.keys()):
- raise exceptions.ValidationError(
- f"Must provide a dictionary with only known keys. One or more of {', '.join(known_keys)}."
- )
-
- if "ai_config" in value:
- TeamSerializer.validate_session_replay_ai_summary_config(value["ai_config"])
-
- return value
-
- @staticmethod
- def validate_session_replay_ai_summary_config(value: dict | None) -> dict | None:
- if value is not None:
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- allowed_keys = [
- "included_event_properties",
- "opt_in",
- "preferred_events",
- "excluded_events",
- "important_user_properties",
- ]
- if not all(key in allowed_keys for key in value.keys()):
- raise exceptions.ValidationError(
- f"Must provide a dictionary with only allowed keys: {', '.join(allowed_keys)}."
- )
-
- return value
-
- def validate_access_control(self, value) -> None:
- """Validate that access_control field is not being used as it's deprecated."""
- if value is not None:
- import posthoganalytics
-
- request = self.context.get("request")
- user = request.user if request else None
-
- posthoganalytics.capture_exception(
- Exception("Deprecated access control field used"),
- properties={
- "field": "access_control",
- "value": str(value),
- "user_id": user.id if user else None,
- "team_id": getattr(user, "team_id", None) if user else None,
- },
- )
-
- raise exceptions.ValidationError(
- "The 'access_control' field has been deprecated and is no longer supported. "
- "Please use the new access control system instead. "
- "For more information, visit: https://posthog.com/docs/settings/access-control"
- )
- return None
-
- def validate_app_urls(self, value: list[str | None] | None) -> list[str] | None:
- if value is None:
- return value
- urls = [url for url in value if url]
- validate_authorized_url_wildcards(urls)
- return urls
-
- def validate_recording_domains(self, value: list[str | None] | None) -> list[str] | None:
- if value is None:
- return value
- return [domain for domain in value if domain]
-
- def validate_conversations_settings(self, value: dict | None) -> dict | None:
- if value is None:
- return value
- strip_managed_conversations_settings(value)
- # Filter out None values from widget_domains if present
- if "widget_domains" in value and value["widget_domains"] is not None:
- value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
- validate_authorized_url_wildcards(value["widget_domains"])
- # Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50
- if "slack_channel_ids" in value:
- raw = value.get("slack_channel_ids")
- if isinstance(raw, list):
- cleaned: list[str] = []
- seen: set[str] = set()
- for item in raw:
- if isinstance(item, str) and item and item not in seen:
- seen.add(item)
- cleaned.append(item)
- value["slack_channel_ids"] = cleaned[:50]
- else:
- value.pop("slack_channel_ids", None)
- icon_url = value.get("slack_bot_icon_url")
- if icon_url is not None:
- if not isinstance(icon_url, str):
- raise serializers.ValidationError({"slack_bot_icon_url": "Must be a string."})
- icon_url = icon_url.strip()
- value["slack_bot_icon_url"] = icon_url or None
- if icon_url and not icon_url.startswith("https://"):
- raise serializers.ValidationError({"slack_bot_icon_url": "Must be an HTTPS URL."})
- display_name = value.get("slack_bot_display_name")
- if display_name is not None:
- if not isinstance(display_name, str):
- raise serializers.ValidationError({"slack_bot_display_name": "Must be a string."})
- display_name = display_name.strip()
- value["slack_bot_display_name"] = display_name or None
- if display_name and (len(display_name) > 200 or any(ord(c) < 32 for c in display_name)):
- raise serializers.ValidationError(
- {"slack_bot_display_name": "Must be 200 characters or fewer with no control characters."}
- )
- for toggle_key in ("slack_notify_on_join", "slack_notify_on_leave", "slack_nudge_enabled"):
- if toggle_key in value:
- value[toggle_key] = bool(value[toggle_key])
- if "slack_alert_channel_id" in value:
- alert_channel = value.get("slack_alert_channel_id")
- if alert_channel is None:
- value["slack_alert_channel_id"] = None
- elif isinstance(alert_channel, str):
- value["slack_alert_channel_id"] = alert_channel.strip() or None
- else:
- raise serializers.ValidationError({"slack_alert_channel_id": "Must be a string."})
- # AI resolution channels: list of valid channel strings or null
- VALID_CHANNELS = {"widget", "email", "slack", "teams", "github"}
- if "ai_resolution_channels" in value:
- channels = value.get("ai_resolution_channels")
- if channels is None:
- pass
- elif isinstance(channels, list):
- invalid = [c for c in channels if not isinstance(c, str) or c not in VALID_CHANNELS]
- if invalid:
- raise serializers.ValidationError(
- {
- "ai_resolution_channels": f"Invalid channel(s): {', '.join(str(c) for c in invalid)}. "
- f"Valid options: {', '.join(sorted(VALID_CHANNELS))}."
- }
- )
- value["ai_resolution_channels"] = channels
- else:
- raise serializers.ValidationError(
- {"ai_resolution_channels": "Must be a list of channel names or null."}
- )
- # AI reply modes: { channel: { ticket_type: mode } } or null
- VALID_REPLY_MODES = {"private_note", "bot_reply"}
- VALID_TICKET_TYPES = {"how_to", "diagnostic", "account_billing"}
- # Only how_to replies may be published to the ticket author. diagnostic/account_billing
- # draw on project data (events, persons, recordings, logs) and must stay private notes —
- # there's no per-author authorization that the customer is entitled to that data.
- BOT_REPLY_TICKET_TYPES = {"how_to"}
- if "ai_reply_modes" in value:
- modes = value.get("ai_reply_modes")
- if modes is None:
- pass
- elif isinstance(modes, dict):
- cleaned_modes: dict[str, dict[str, str]] = {}
- for ch, type_map in modes.items():
- if ch not in VALID_CHANNELS or not isinstance(type_map, dict):
- continue
- cleaned_map: dict[str, str] = {}
- for tt, mode in type_map.items():
- if tt not in VALID_TICKET_TYPES or mode not in VALID_REPLY_MODES:
- continue
- # Demote bot_reply to private_note for ticket types that may never be
- # published (diagnostic/account_billing). Coerce rather than reject so a
- # stale value doesn't block unrelated settings saves.
- if mode == "bot_reply" and tt not in BOT_REPLY_TICKET_TYPES:
- mode = "private_note"
- cleaned_map[tt] = mode
- if cleaned_map:
- cleaned_modes[ch] = cleaned_map
- value["ai_reply_modes"] = cleaned_modes
- else:
- raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
- from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
- from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
-
- existing = getattr(self.instance, "conversations_settings", None) if self.instance is not None else None
- validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
- validate_ai_context_conversations_settings(
- value, team_id=self.instance.id if self.instance is not None else None
- )
- return value
-
- def validate_receive_org_level_activity_logs(self, value: bool | None) -> bool | None:
- if value is None:
- return value
-
- request = self.context.get("request")
- if not request:
- return value
-
- user = request.user
-
- if self.instance:
- try:
- membership = OrganizationMembership.objects.get(user=user, organization=self.instance.organization)
- if membership.level < OrganizationMembership.Level.ADMIN:
- raise exceptions.PermissionDenied(
- "Only organization owners and admins can modify the receive_org_level_activity_logs setting."
- )
- except OrganizationMembership.DoesNotExist:
- raise exceptions.PermissionDenied("You must be a member of this organization.")
-
- return value
-
- def validate_logs_settings(self, value: dict | None) -> dict | None:
- if value is None:
- return value
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("logs_settings must be an object or null.")
-
- if "json_parse_logs_attribute_key" in value:
- attribute_key = value["json_parse_logs_attribute_key"]
- # Length is measured after trimming, matching CharField(trim_whitespace=True,
- # max_length=200) on the logs_config key lists.
- if not isinstance(attribute_key, str) or len(attribute_key.strip()) > 200:
- raise exceptions.ValidationError(
- "json_parse_logs_attribute_key must be a string of at most 200 characters. "
- "Use an empty string to disable parsing."
- )
- value["json_parse_logs_attribute_key"] = attribute_key.strip()
-
- team = (
- self.instance.passthrough_team
- if self.instance is not None and hasattr(self.instance, "passthrough_team")
- else self.instance
- )
-
- logs_settings = team.logs_settings if team is not None else None
- old_retention = logs_settings.get("retention_days") if logs_settings else None
-
- new_retention = value.get("retention_days")
- if new_retention is not None and (isinstance(new_retention, bool) or not isinstance(new_retention, int)):
- raise exceptions.ValidationError("retention_days must be an integer")
-
- # Only a changed period is checked against the flag and the entitlement. Unrelated settings
- # updates send the stored period back, and must not fail when the flag is turned off later.
- if new_retention is not None and old_retention != new_retention:
- # Only evaluate the flag for values outside the base tiers, so the common path makes no flag call.
- custom_enabled = new_retention not in LOGS_RETENTION_BASE_TIERS_DAYS and _custom_logs_retention_enabled(
- self, team
- )
- error = logs_retention_days_error(new_retention, custom_retention_enabled=custom_enabled)
- if error:
- raise exceptions.ValidationError(error)
-
- required_feature = required_logs_retention_feature(new_retention)
- if required_feature:
- organization = _get_organization_for_logs_settings_check(self)
- if organization is None or not organization.is_feature_available(required_feature):
- raise exceptions.PermissionDenied(
- f"This organization does not have permission to set Logs retention to {new_retention} days."
- )
-
- # Only validate retention throttling if we have an existing retention setting
- if self.instance and logs_settings:
- old_last_updated = logs_settings.get("retention_last_updated")
-
- # Check if retention_days is being changed
- if new_retention is not None and old_retention != new_retention:
- value["retention_last_updated"] = timezone.now().isoformat()
- throttle_error = retention_update_throttle_error(old_last_updated)
- if throttle_error:
- raise exceptions.ValidationError(throttle_error)
-
- return value
-
- @staticmethod
- def validate_modifiers(value: dict | None) -> dict | None:
- if value is None:
- return value
-
- if not isinstance(value, dict):
- raise exceptions.ValidationError("Must provide a dictionary or None.")
-
- # The native JSON events table is an internal rollout switch that PostHog staff set per project in Django
- # admin. Dropping the key keeps a client from setting or clearing it, including a settings page that echoes
- # the whole modifiers dict back.
- value = {key: item for key, item in value.items() if key != "useNewEventsSchema"}
-
- if "bounceRateDurationSeconds" in value:
- bounce_rate = value["bounceRateDurationSeconds"]
- if bounce_rate is not None:
- if not isinstance(bounce_rate, (int, float)):
- raise exceptions.ValidationError({"bounceRateDurationSeconds": "Must be a number."})
- if bounce_rate < 1 or bounce_rate > 120:
- raise exceptions.ValidationError(
- {"bounceRateDurationSeconds": "Must be between 1 and 120 seconds."}
- )
-
- if "customBotDefinitions" in value and isinstance(value["customBotDefinitions"], list):
- # Cap before parsing, so an oversized list is rejected without instantiating a model
- # per entry.
- if len(value["customBotDefinitions"]) > MAX_CUSTOM_BOT_DEFINITIONS:
- raise exceptions.ValidationError(
- {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}
- )
- # Strict, so a malformed rule is rejected with a specific error rather than the
- # generic "Invalid modifier key.", and the stored list is normalized.
- try:
- parsed = parse_custom_bot_rules(value["customBotDefinitions"], strict=True)
- except ValueError as error:
- raise exceptions.ValidationError({"customBotDefinitions": str(error)})
- value = {**value, "customBotDefinitions": [rule.model_dump(exclude_none=True) for rule in parsed]}
-
- try:
- modifiers = HogQLQueryModifiers(**value)
- except Exception:
- raise exceptions.ValidationError(f"Invalid modifier key.")
-
- if "customBotDefinitions" in value:
- rules = modifiers.customBotDefinitions or []
- if len(rules) > MAX_CUSTOM_BOT_DEFINITIONS:
- raise exceptions.ValidationError(
- {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}
- )
- for rule in rules:
- # An unusable pattern would break every query that reads $virt_is_bot for this
- # project, so it is rejected here rather than dropped silently at query time.
- try:
- validate_custom_bot_rule(rule)
- except ValueError as error:
- # An empty name would render as an orphaned leading colon.
- message = f"{rule.name}: {error}" if rule.name else str(error)
- raise exceptions.ValidationError({"customBotDefinitions": message})
- try:
- validate_custom_bot_rule_set(rules)
- assert_custom_bot_patterns_compile(compiled_custom_bot_patterns(rules))
- except ValueError as error:
- raise exceptions.ValidationError({"customBotDefinitions": str(error)})
-
- return value
-
- def validate_proactive_tasks_enabled(self, value: bool | None) -> bool | None:
- if not value or settings.DEBUG:
- return value
-
- # Only team ID 2 in US region can enable proactive tasks
- if self.instance and self.instance.id == 2 and get_instance_region() == "US":
- return value
-
- raise exceptions.PermissionDenied("Proactive tasks can only be enabled for authorized teams.")
-
- def validate(self, attrs: Any) -> Any:
- attrs = validate_team_attrs(attrs, self.context["view"], self.instance)
- return super().validate(attrs)
-
- def create(self, validated_data: dict[str, Any], **kwargs) -> Team:
- request = self.context["request"]
- if self.context["project_id"] not in self.user_permissions.project_ids_visible_for_user:
- raise exceptions.NotFound("Project not found.")
- validated_data["project_id"] = self.context["project_id"]
- serializers.raise_errors_on_nested_writes("create", self, validated_data)
-
- if "week_start_day" not in validated_data:
- country_code = get_geoip_properties(get_ip_address(request)).get("$geoip_country_code", None)
- if country_code:
- week_start_day_for_user_ip_location = get_week_start_for_country_code(country_code)
- # get_week_start_for_country_code() also returns 6 for countries where the week starts on Saturday,
- # but ClickHouse doesn't support Saturday as the first day of the week, so we fall back to Sunday
- validated_data["week_start_day"] = 1 if week_start_day_for_user_ip_location == 1 else 0
-
- team = Team.objects.create_with_data(
- initiating_user=request.user,
- organization=self.context["view"].organization,
- **validated_data,
- )
-
- request.user.current_team = team
- request.user.team = request.user.current_team # Update cached property
- request.user.save()
-
- log_activity(
- organization_id=team.organization_id,
- team_id=team.pk,
- user=request.user,
- was_impersonated=is_impersonated(request),
- scope="Team",
- item_id=team.pk,
- activity="created",
- detail=Detail(name=str(team.name)),
- )
-
- return team
-
- def update(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- before_update = instance.__dict__.copy()
- # The settings patch persisted under lock below must not be written again from the
- # stale request snapshot; the token handler can add the key later, so capture the
- # client's intent now.
- patch_conversations_settings = "conversations_settings" in validated_data
- # Captured before the locked block pops the keys, so the refresh/re-cache step
- # below still knows this request touched the team row.
- conversations_lock_applied = patch_conversations_settings or "conversations_enabled" in validated_data
- if "home_tab_dashboard" in validated_data:
- dashboard = instance.home_tab_dashboard
- before_update["home_tab_dashboard"] = dashboard.id if dashboard else None
-
- # Should be validated already, but let's be extra sure
- if config_data := validated_data.pop("revenue_analytics_config", None):
- self._update_revenue_analytics_config(instance, config_data)
-
- if config_data := validated_data.pop("marketing_analytics_config", None):
- self._update_marketing_analytics_config(instance, config_data)
-
- if config_data := validated_data.pop("customer_analytics_config", None):
- self._update_customer_analytics_config(instance, config_data)
-
- if config_data := validated_data.pop("workflows_config", None):
- self._update_workflows_config(instance, config_data)
-
- if config_data := validated_data.pop("feature_flag_policy_config", None):
- self._update_feature_flag_policy_config(instance, config_data)
-
- # Lives on a Team extension, not a Team column, so it can't flow through the generic
- # save(update_fields=...) loop below.
- if "home_tab_dashboard" in validated_data:
- dashboard = validated_data.pop("home_tab_dashboard")
- instance.home_tab_dashboard = dashboard
- home_tab_dashboard_id = dashboard.id if dashboard else None
-
- if "session_recording_retention_period" in validated_data:
- self._verify_update_session_recording_retention_period(
- instance, validated_data["session_recording_retention_period"]
- )
-
- if "survey_config" in validated_data:
- if instance.survey_config is not None and validated_data.get("survey_config") is not None:
- validated_data["survey_config"] = {
- **instance.survey_config,
- **validated_data["survey_config"],
- }
-
- if validated_data.get("survey_config") is None:
- del before_update["survey_config"]
-
- survey_config_changes_between = dict_changes_between(
- "Survey",
- before_update.get("survey_config", {}),
- validated_data.get("survey_config", {}),
- use_field_exclusions=True,
- )
-
- if survey_config_changes_between:
- log_activity(
- organization_id=cast(UUIDT, instance.organization_id),
- team_id=instance.pk,
- user=cast(User, self.context["request"].user),
- was_impersonated=is_impersonated(self.context["request"]),
- scope="Survey",
- item_id="",
- activity="updated",
- detail=Detail(
- name="global survey appearance",
- changes=survey_config_changes_between,
- ),
- )
-
- if (
- "session_replay_config" in validated_data
- and validated_data["session_replay_config"] is not None
- and instance.session_replay_config is not None
- ):
- # for session_replay_config and its top level keys we merge existing settings with new settings
- # this way we don't always have to receive the entire settings object to change one setting
- # so for each key in validated_data["session_replay_config"] we merge it with the existing settings
- # and then merge any top level keys that weren't provided
-
- for key, value in validated_data["session_replay_config"].items():
- if key in instance.session_replay_config:
- # if they're both dicts then we merge them, otherwise, the new value overwrites the old
- if isinstance(instance.session_replay_config[key], dict) and isinstance(
- validated_data["session_replay_config"][key], dict
- ):
- validated_data["session_replay_config"][key] = {
- **instance.session_replay_config[key], # existing values
- **value, # and new values on top
- }
-
- # then also add back in any keys that exist but are not in the provided data
- validated_data["session_replay_config"] = {
- **instance.session_replay_config,
- **validated_data["session_replay_config"],
- }
-
- # Merge modifiers with existing values so that updating one modifier doesn't wipe out others
- if "modifiers" in validated_data:
- validated_data["modifiers"] = merge_modifiers(validated_data["modifiers"], instance.modifiers)
-
- # Persist only the fields this request changes. A full-row save() writes back every
- # column from this request's snapshot of the team, so two concurrent PATCHes clobber
- # each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
- # erased `has_completed_onboarding_for` and reverted `completed_snippet_onboarding`,
- # bouncing freshly onboarded users back into onboarding.
- other_team_fields = [attr for attr in validated_data if attr not in LOCKED_CONVERSATIONS_COLUMNS]
- for attr in other_team_fields:
- setattr(instance, attr, validated_data[attr])
-
- # Merge conversations_settings under a lock; a null clear still keeps the managed keys.
- if conversations_lock_applied:
- locked_conversations = merge_conversations_settings_locked(
- instance, validated_data, patch_conversations_settings, other_team_fields
- )
- # The locked re-read is newer than the snapshot, so a concurrent write is not logged as this user's.
- before_update["conversations_settings"] = locked_conversations["conversations_settings"]
- before_update["conversations_enabled"] = locked_conversations["conversations_enabled"]
- elif other_team_fields:
- # auto_now fields only refresh when included in update_fields
- instance.save(update_fields=[*other_team_fields, "updated_at"])
- # Snapshot before the cache refresh below so the audit diff only reflects this
- # request's writes, not fields a concurrent request changed.
- after_update = instance.__dict__.copy()
- if "home_tab_dashboard" in before_update:
- after_update["home_tab_dashboard"] = home_tab_dashboard_id
- if other_team_fields or conversations_lock_applied:
- # The in-memory instance may hold stale values for fields a concurrent request
- # changed, and the post-save receiver has already cached that snapshot. Reload
- # and re-cache so the team cache reflects the merged row.
- instance.refresh_from_db()
- set_team_in_cache(instance.api_token, instance)
- updated_team = instance
-
- changes = dict_changes_between("Team", before_update, after_update, use_field_exclusions=True)
-
- log_activity(
- organization_id=cast(UUIDT, instance.organization_id),
- team_id=instance.pk,
- user=cast(User, self.context["request"].user),
- was_impersonated=is_impersonated(self.context["request"]),
- scope="Team",
- item_id=instance.pk,
- activity="updated",
- detail=Detail(
- name=str(instance.name),
- changes=changes,
- ),
- )
-
- report_conversations_settings_changes(
- cast(User, self.context["request"].user),
- before_update.get("conversations_settings"),
- after_update.get("conversations_settings"),
- updated_team,
- )
-
- return updated_team
-
- def _update_revenue_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- # Capture old config before saving
- old_config = {
- "events": [event.model_dump() for event in (instance.revenue_analytics_config.events or [])],
- "filter_test_accounts": instance.revenue_analytics_config.filter_test_accounts,
- }
-
- serializer = TeamRevenueAnalyticsConfigSerializer(
- instance.revenue_analytics_config,
- data=validated_data,
- partial=True,
- context={**self.context, "user_access_control": self.user_access_control},
- )
- if not serializer.is_valid():
- raise serializers.ValidationError(_format_serializer_errors(serializer.errors))
-
- serializer.save()
-
- # Log activity for revenue analytics config changes
- new_config = {
- "events": validated_data.get("events", []),
- "filter_test_accounts": validated_data.get("filter_test_accounts", False),
- }
-
- self._capture_diff(instance, "revenue_analytics_config", old_config, new_config)
-
- if "events" in validated_data:
- from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
- from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind
-
- managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(
- team=instance,
- kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,
- )
- managed_viewset.sync_views()
-
- return instance
-
- def _update_marketing_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- # Capture the old config before saving
- old_config = {
- "sources_map": (
- instance.marketing_analytics_config.sources_map.copy()
- if instance.marketing_analytics_config.sources_map
- else {}
- ),
- "attribution_window_days": instance.marketing_analytics_config.attribution_window_days,
- "attribution_mode": instance.marketing_analytics_config.attribution_mode,
- "filter_test_accounts": instance.marketing_analytics_config.filter_test_accounts,
- # Add other fields as they're added to the model
- # "conversion_goals": instance.marketing_analytics_config.conversion_goals.copy() if instance.marketing_analytics_config.conversion_goals else [],
- }
-
- marketing_serializer = TeamMarketingAnalyticsConfigSerializer(
- instance.marketing_analytics_config,
- data=validated_data,
- partial=True,
- context={**self.context, "user_access_control": self.user_access_control},
- )
- if not marketing_serializer.is_valid():
- raise serializers.ValidationError(_format_serializer_errors(marketing_serializer.errors))
-
- marketing_serializer.save()
-
- # Log activity for marketing analytics config changes
- new_config = {
- "sources_map": validated_data.get("sources_map", {}),
- "attribution_window_days": validated_data.get("attribution_window_days"),
- "attribution_mode": validated_data.get("attribution_mode"),
- "filter_test_accounts": validated_data.get("filter_test_accounts"),
- # Add other fields as they're added to the model
- # "conversion_goals": validated_data.get("conversion_goals", []),
- }
-
- self._capture_diff(instance, "marketing_analytics_config", old_config, new_config)
- return instance
-
- def _update_customer_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- old_config = {
- "activity_event": instance.customer_analytics_config.activity_event,
- "signup_pageview_event": instance.customer_analytics_config.signup_pageview_event,
- "signup_event": instance.customer_analytics_config.signup_event,
- "subscription_event": instance.customer_analytics_config.subscription_event,
- "payment_event": instance.customer_analytics_config.payment_event,
- "account_group_type_index": instance.customer_analytics_config.account_group_type_index,
- "default_pinned_properties": instance.customer_analytics_config.default_pinned_properties,
- }
-
- serializer = TeamCustomerAnalyticsConfigSerializer(
- instance.customer_analytics_config,
- data=validated_data,
- partial=True,
- context={**self.context, "user_access_control": self.user_access_control},
- )
- if not serializer.is_valid():
- raise serializers.ValidationError(_format_serializer_errors(serializer.errors))
-
- serializer.save()
-
- new_config = {
- field: getattr(instance.customer_analytics_config, field)
- for field in TeamCustomerAnalyticsConfigSerializer.Meta.fields
- }
- self._capture_diff(instance, "customer_analytics_config", old_config, new_config)
- return instance
-
- def _update_workflows_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- old_config = {
- field: getattr(instance.workflows_config, field) for field in TeamWorkflowsConfigSerializer.Meta.fields
- }
-
- serializer = TeamWorkflowsConfigSerializer(
- instance.workflows_config,
- data=validated_data,
- partial=True,
- context={**self.context, "user_access_control": self.user_access_control},
- )
- if not serializer.is_valid():
- raise serializers.ValidationError(_format_serializer_errors(serializer.errors))
-
- serializer.save()
-
- new_config = {
- field: getattr(instance.workflows_config, field) for field in TeamWorkflowsConfigSerializer.Meta.fields
- }
- self._capture_diff(instance, "workflows_config", old_config, new_config)
- return instance
-
- def _update_feature_flag_policy_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
- old_config = {
- field: getattr(instance.feature_flag_policy_config, field)
- for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields
- }
-
- serializer = TeamFeatureFlagPolicyConfigSerializer(
- instance.feature_flag_policy_config,
- data=validated_data,
- partial=True,
- context={**self.context, "user_access_control": self.user_access_control},
- )
- if not serializer.is_valid():
- raise serializers.ValidationError(_format_serializer_errors(serializer.errors))
-
- serializer.save()
-
- new_config = {
- field: getattr(instance.feature_flag_policy_config, field)
- for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields
- }
- self._capture_diff(instance, "feature_flag_policy_config", old_config, new_config)
- return instance
-
- def _verify_update_session_recording_retention_period(self, instance: Team, new_retention_period: str):
- retention_feature = instance.organization.get_available_feature(AvailableFeature.SESSION_REPLAY_DATA_RETENTION)
- highest_retention_entitlement = parse_feature_to_entitlement(retention_feature)
-
- if highest_retention_entitlement is None:
- raise exceptions.APIException(detail="Invalid retention entitlement.") # HTTP 500
-
- # Should be validated already, but let's be extra sure to avoid IndexErrors below
- if not validate_retention_period(new_retention_period):
- raise exceptions.ValidationError( # HTTP 400
- f"Must provide a valid retention period. Options are: {VALID_RETENTION_PERIODS}."
- )
-
- if retention_violates_entitlement(new_retention_period, highest_retention_entitlement):
- raise exceptions.PermissionDenied( # HTTP 403
- f"This organization does not have permission to set retention period of length '{new_retention_period}' - longest allowable retention period is '{highest_retention_entitlement}'."
- )
-
- def _capture_diff(self, instance: Team, key: str, before: dict, after: dict):
- changes = dict_changes_between(
- "Team",
- {key: before},
- {key: after},
- use_field_exclusions=True,
- )
-
- if changes:
- log_activity(
- organization_id=cast(UUIDT, instance.organization_id),
- team_id=instance.pk,
- user=cast(User, self.context["request"].user),
- was_impersonated=is_impersonated(self.context["request"]),
- scope="Team",
- item_id=instance.pk,
- activity="updated",
- detail=Detail(name=str(instance.name), changes=changes),
- )
-
-
-class EvaluationContextSuggestionRequestSerializer(serializers.Serializer):
- context_name = serializers.CharField(
- max_length=255,
- help_text=(
- "Name of the evaluation context to hide from (POST) or restore to (DELETE) "
- "the flag editor's suggestion list. Case-insensitive and whitespace-trimmed."
- ),
- )
-
-
-class EvaluationContextSuggestionResponseSerializer(serializers.Serializer):
- success = serializers.BooleanField(help_text="Whether the suggestion visibility change was applied.")
- name = serializers.CharField(help_text="Normalized name of the affected evaluation context.")
- hidden_from_suggestions = serializers.BooleanField(
- help_text="Whether the context is now hidden from the flag editor's suggestion list."
- )
-
-
-class EventIngestionRestrictionSerializer(serializers.Serializer):
- restriction_type = serializers.ChoiceField(
- choices=RestrictionType.choices,
- help_text="What happens to matching events: dropped, sent to the overflow lane, or ingested without person processing.",
- )
- distinct_ids = serializers.ListField(
- child=serializers.CharField(),
- help_text="Distinct IDs the restriction applies to. Empty means it is not filtered by distinct ID.",
- )
- session_ids = serializers.ListField(
- child=serializers.CharField(),
- help_text="Session IDs the restriction applies to. Empty means it is not filtered by session ID.",
- )
- event_names = serializers.ListField(
- child=serializers.CharField(),
- help_text="Event names the restriction applies to. Empty means it is not filtered by event name.",
- )
- event_uuids = serializers.ListField(
- child=serializers.CharField(),
- help_text="Event UUIDs the restriction applies to. Empty means it is not filtered by event UUID.",
- )
- pipelines = serializers.ListField(
- child=serializers.ChoiceField(choices=IngestionPipeline.choices),
- help_text="Ingestion pipelines the restriction applies to. Filters combine with AND; values within a filter combine with OR.",
- )
-
-
-def team_event_ingestion_restrictions_view(team: Team, request: request.Request) -> response.Response:
- restrictions = EventIngestionRestrictionConfig.objects.filter(token=team.api_token)
- data = [
- {
- "restriction_type": restriction.restriction_type,
- "distinct_ids": restriction.distinct_ids or [],
- "session_ids": restriction.session_ids or [],
- "event_names": restriction.event_names or [],
- "event_uuids": restriction.event_uuids or [],
- "pipelines": restriction.pipelines or [],
- }
- for restriction in restrictions
- ]
- return response.Response(EventIngestionRestrictionSerializer(data, many=True).data)
-
-
-class TeamViewSet(
- TeamAndOrgViewSetMixin, AccessControlSettingsViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet
-):
- """
- Projects for the current organization.
- """
-
- scope_object: APIScopeObjectOrNotSupported = "project"
- serializer_class = TeamSerializer
- queryset = Team.objects.all().select_related("organization")
- lookup_field = "id"
- ordering = "-created_by"
-
- # Actions whose GET is downgraded to project:read for session auth; mutating methods stay on project:write/admin.
- GET_DOWNGRADE_ACTIONS = ("evaluation_context_suggestions",)
-
- def safely_get_queryset(self, queryset):
- user = cast(User, self.request.user)
- # IMPORTANT: This is actually what ensures that a user cannot read/update a project for which they don't have permission
- visible_teams_ids = UserPermissions(user).team_ids_visible_for_user
- queryset = queryset.filter(id__in=visible_teams_ids)
- authenticator = self.request.successful_authenticator
- if scoped_organizations := get_authenticator_scoped_organization_ids(authenticator):
- queryset = queryset.filter(project__organization_id__in=scoped_organizations)
- if scoped_teams := get_authenticator_scoped_team_ids(authenticator):
- queryset = queryset.filter(id__in=scoped_teams)
- return queryset
-
- def get_serializer_class(self) -> type[serializers.BaseSerializer]:
- if self.action == "list":
- return TeamBasicSerializer
- return super().get_serializer_class()
-
- def dangerously_get_required_scopes(self, request, view) -> list[str] | None:
- # Used for the AccessControlViewSetMixin
- mixin_result = super().dangerously_get_required_scopes(request, view)
- if mixin_result is not None:
- return mixin_result
-
- # NOTE: This downgrade only applies to session-based auth (browser users).
- # All other auth methods (API keys, OAuth tokens, etc.) must have project:write
- # to modify any fields, preserving the semantic meaning of read-only API keys.
- if self.action == "partial_update":
- is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
- if is_session_auth:
- request_fields = set(request.data.keys())
- # Member-safe fields, plus fields whose write is governed by their own field-level
- # access control — keep the request gate from demanding project:write (admin) for the
- # latter, otherwise e.g. a web analytics editor on a restricted project is blocked
- # before UserAccessControlSerializerMixin.validate can authorize the field.
- downgradable_fields = TEAM_CONFIG_MEMBER_FIELDS_SET | TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS
- if request_fields and request_fields.issubset(downgradable_fields):
- return ["project:read"]
-
- # Read-only access for member-readable actions — only downgrade GET, not writes.
- if self.action in self.GET_DOWNGRADE_ACTIONS and request.method == "GET":
- is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
- if is_session_auth:
- return ["project:read"]
-
- # Fall back to the default behavior
- return None
-
- # NOTE: Team permissions are somewhat complex so we override the underlying viewset's get_permissions method
- def dangerously_get_permissions(self) -> list:
- """
- Special permissions handling for create requests as the organization is inferred from the current user.
- """
-
- permissions: list = [
- IsAuthenticated,
- APIScopePermission,
- AccessControlPermission,
- PremiumMultiEnvironmentPermission,
- *self.permission_classes,
- ]
-
- # Return early for non-actions (e.g. OPTIONS)
- if self.action:
- if self.action == "create":
- if "is_demo" not in self.request.data or not self.request.data["is_demo"]:
- permissions.append(UserCanCreateProjectPermission)
- else:
- permissions.append(OrganizationMemberPermissions)
- elif self.action != "list":
- # Skip TeamMemberAccessPermission for list action, as list is serialized with limited TeamBasicSerializer.
- # GET_DOWNGRADE_ACTIONS writes stay admin-gated via TeamMemberStrictManagementPermission.
- if self.action in self.GET_DOWNGRADE_ACTIONS:
- if self.request.method != "GET":
- # Writes need strict (admin for all non-safe methods), not light (which only gates DELETE).
- permissions.append(TeamMemberStrictManagementPermission)
- else:
- permissions.append(TeamMemberLightManagementPermission)
-
- return [permission() for permission in permissions]
-
- def safely_get_object(self, queryset):
- lookup_value = self.kwargs[self.lookup_field]
- if lookup_value == "@current":
- team = getattr(self.request.user, "team", None)
- if team is None:
- raise exceptions.NotFound()
- # This branch answers from the user's own state instead of the scoped queryset. A project
- # that moved between organizations leaves that state naming an environment the token's
- # organizations no longer cover, so apply the same restriction the queryset would have.
- scoped_organizations = get_authenticator_scoped_organization_ids(self.request.successful_authenticator)
- if scoped_organizations and str(team.organization_id) not in scoped_organizations:
- raise exceptions.NotFound()
- return team
-
- filter_kwargs = {self.lookup_field: lookup_value}
- try:
- team = get_object_or_404(queryset, **filter_kwargs)
- except ValueError as error:
- raise exceptions.ValidationError(str(error))
- return team
-
- # :KLUDGE: Exposed for compatibility reasons for permission classes.
- @property
- def team(self):
- return self.get_object()
-
- def perform_destroy(self, team: Team):
- # Check if bulk deletion operations are disabled via environment variable
- if settings.DISABLE_BULK_DELETES:
- raise exceptions.ValidationError(
- "Team deletion is temporarily disabled during database migration. Please try again later."
- )
-
- team_id = team.pk
- organization_id = team.organization_id
- team_name = team.name
-
- # Remove the team from the org's managed warehouse first (no-op for orgs without
- # one). Blocks when duckgres refuses — e.g. the warehouse's last team, which
- # requires deprovisioning the warehouse (or deleting the organization) instead.
- # Keep the product API off the core import path.
- from products.managed_warehouse.backend.facade.api import get_team_deletion_block_reason # noqa: PLC0415
-
- warehouse_block_reason = get_team_deletion_block_reason(team_id, organization_id)
- if warehouse_block_reason:
- raise exceptions.ValidationError(warehouse_block_reason)
-
- user = cast(User, self.request.user)
-
- # Hand off all deletion work (bulky postgres, batch exports, team record,
- # ClickHouse, email) to the durable Temporal workflow.
- from posthog.temporal.delete_teams.dispatch import start_delete_project_data_workflow
-
- start_delete_project_data_workflow(
- team_ids=[team_id],
- project_id=None, # Only deleting a team, not the whole project
- user_id=user.id,
- project_name=team_name,
- )
-
- log_activity(
- organization_id=cast(UUIDT, organization_id),
- team_id=team_id,
- user=user,
- was_impersonated=is_impersonated(self.request),
- scope="Team",
- item_id=team_id,
- activity="deleted",
- detail=Detail(name=str(team_name)),
- )
- # TRICKY: We pass in `team` here as access to `user.current_team` can fail if it was deleted
- report_user_action(user, "team deleted", team=team, request=self.request)
-
- @action(
- methods=["PATCH"],
- detail=True,
- # Only ADMIN or higher users are allowed to access this project
- permission_classes=[TeamMemberStrictManagementPermission],
- )
- def reset_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- team.reset_token_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @action(
- methods=["PATCH"],
- detail=True,
- # Only ADMIN or higher users are allowed to access this project
- permission_classes=[TeamMemberStrictManagementPermission],
- )
- def rotate_secret_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- validate_secret_token_generation(team)
- team.rotate_secret_token_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @extend_schema(request=None, responses=TeamSerializer)
- @action(
- methods=["PATCH"],
- detail=True,
- # Only ADMIN or higher users are allowed to access this project
- permission_classes=[TeamMemberStrictManagementPermission],
- )
- def rotate_heatmaps_screenshot_secret(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- team.rotate_heatmaps_screenshot_secret_and_save(
- user=request.user, is_impersonated_session=is_impersonated(request)
- )
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @action(
- methods=["PATCH"],
- detail=True,
- # Only ADMIN or higher users are allowed to access this project
- permission_classes=[TeamMemberStrictManagementPermission],
- )
- def delete_secret_token_backup(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- team.delete_secret_token_backup_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @action(
- methods=["POST"],
- detail=True,
- # Only ADMIN or higher users are allowed to access this project
- permission_classes=[TeamMemberStrictManagementPermission],
- )
- def generate_conversations_public_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- team.generate_conversations_public_token_and_save(
- user=request.user, is_impersonated_session=is_impersonated(request)
- )
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @extend_schema(
- methods=["GET"],
- request=None,
- responses={200: TeamLogsConfigSerializer},
- extensions={"x-product": "logs"},
- )
- @extend_schema(
- methods=["PATCH"],
- request=TeamLogsConfigSerializer,
- responses={200: TeamLogsConfigSerializer},
- extensions={"x-product": "logs"},
- )
- @action(
- methods=["GET", "PATCH"],
- detail=True,
- permission_classes=[TeamMemberStrictManagementPermission],
- url_path="logs_config",
- )
- def logs_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage logs product configuration for this environment. Members can read;
- writing requires project admin, matching the admin-only settings UI."""
- return handle_logs_config(request, self.get_object())
-
- @extend_schema(
- methods=["GET"],
- request=None,
- responses={200: TeamTracingConfigSerializer},
- extensions={"x-product": "tracing"},
- )
- @extend_schema(
- methods=["PATCH"],
- request=TeamTracingConfigSerializer,
- responses={200: TeamTracingConfigSerializer},
- extensions={"x-product": "tracing"},
- )
- @action(
- methods=["GET", "PATCH"],
- detail=True,
- permission_classes=[TeamMemberStrictManagementPermission],
- url_path="tracing_config",
- )
- def tracing_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage tracing product configuration for this environment. Members can read;
- writing requires project admin, matching the admin-only settings UI."""
- return handle_tracing_config(request, self.get_object())
-
- @action(
- methods=["GET", "PATCH"],
- detail=True,
- permission_classes=[TeamMemberStrictManagementPermission],
- url_path="experiments_config",
- )
- def experiments_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage experiment configuration for this environment."""
- return handle_experiments_config(request, self.get_object())
-
- @extend_schema(
- methods=["POST"],
- request=EvaluationContextSuggestionRequestSerializer,
- responses={200: EvaluationContextSuggestionResponseSerializer},
- extensions={"x-product": "feature_flags"},
- )
- @extend_schema(
- methods=["DELETE"],
- parameters=[EvaluationContextSuggestionRequestSerializer],
- responses={200: EvaluationContextSuggestionResponseSerializer},
- extensions={"x-product": "feature_flags"},
- )
- @action(
- methods=["POST", "DELETE"],
- detail=True,
- permission_classes=[IsAuthenticated],
- )
- def evaluation_context_suggestions(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Hide an evaluation context name from the flag editor's suggestion list, or restore it.
-
- POST hides the name; DELETE restores it. The underlying context row and any flags already
- using it are never modified — this only controls what gets suggested.
- """
- return handle_evaluation_context_suggestions(request, self.get_object())
-
- @action(
- methods=["GET"],
- detail=True,
- permission_classes=[IsAuthenticated],
- )
- def is_generating_demo_data(self, request: request.Request, id: str, **kwargs) -> response.Response:
- team = self.get_object()
- return response.Response({"is_generating_demo_data": team.get_is_generating_demo_data()})
-
- @action(methods=["GET"], detail=True)
- def activity(self, request: request.Request, **kwargs):
- page_params = parse_activity_page_params(request)
-
- team = self.get_object()
-
- activity_page = load_activity(
- scope="Team",
- team_id=team.pk,
- item_ids=[str(team.pk)],
- limit=page_params.limit,
- page=page_params.page,
- )
- return activity_page_response(activity_page, page_params.limit, page_params.page, request)
-
- @action(methods=["GET"], detail=True)
- def settings_as_of(self, request: request.Request, **kwargs) -> response.Response:
- """
- Return the team settings as of the provided timestamp.
- Query params:
- - at: ISO8601 datetime (required)
- - scope: optional, one or multiple keys to filter the returned settings
- """
- team = self.get_object()
-
- at_param = request.query_params.get("at")
- if not at_param:
- raise exceptions.ValidationError({"at": "Query parameter 'at' is required (ISO8601)."})
-
- as_of = parse_datetime(at_param)
- if as_of is None:
- raise exceptions.ValidationError(
- {"at": "Invalid datetime format. Use ISO8601 (e.g., 2025-11-24T12:34:56Z)."}
- )
- if timezone.is_naive(as_of):
- as_of = timezone.make_aware(as_of)
-
- # Build starting snapshot from current model values for config fields
- settings_fields = set(TEAM_CONFIG_FIELDS)
- snapshot: dict[str, Any] = {}
- for field_name in settings_fields:
- if hasattr(team, field_name):
- snapshot[field_name] = getattr(team, field_name)
- elif hasattr(team, f"{field_name}_id"):
- snapshot[field_name] = getattr(team, f"{field_name}_id")
- else:
- snapshot[field_name] = None
-
- # Fetch Team-scoped activity logs after the target timestamp
- logs = (
- ActivityLog.objects.filter(team_id=team.id, scope="Team", item_id=str(team.id), created_at__gt=as_of)
- .order_by("-created_at")
- .only("detail", "created_at", "activity")
- )
-
- # Roll back newest → oldest
- for log in logs.iterator():
- detail = log.detail or {}
- changes = detail.get("changes") or []
- for change in changes:
- field = change.get("field")
- action = change.get("action")
- before = change.get("before")
-
- # Normalize FK fields (e.g., primary_dashboard_id → primary_dashboard)
- target = field[:-3] if isinstance(field, str) and field.endswith("_id") else field
- if target not in settings_fields:
- continue
-
- if action == "changed":
- snapshot[target] = before
- elif action == "created":
- snapshot[target] = None
- elif action == "deleted":
- snapshot[target] = before
- # Other actions (created/deleted without relevant field) are ignored
-
- # Optional scope filtering
- scope_values = request.query_params.getlist("scope")
-
- if scope_values:
- filtered = {k: snapshot.get(k, None) for k in scope_values}
- return response.Response(filtered)
-
- return response.Response(snapshot)
-
- @action(
- methods=["PATCH"],
- detail=True,
- required_scopes=["project:read"],
- )
- @disallow_if_impersonated(message="Impersonated sessions cannot set product intents.")
- def add_product_intent(self, request: request.Request, *args, **kwargs):
- team = self.get_object()
- user = request.user
- current_url = request.headers.get("Referer")
- session_id = request.headers.get("X-Posthog-Session-Id")
-
- serializer = ProductIntentSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
-
- ProductIntent.register(
- team=team,
- product_type=serializer.validated_data["product_type"],
- context=serializer.validated_data.get("intent_context"),
- user=cast(User, user),
- metadata={**serializer.validated_data["metadata"], "$current_url": current_url, "$session_id": session_id},
- is_onboarding=False,
- )
-
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data, status=201)
-
- @action(
- methods=["PATCH"],
- detail=True,
- required_scopes=["project:read"],
- )
- @disallow_if_impersonated(message="Impersonated sessions cannot set product intents.")
- def complete_product_onboarding(self, request: request.Request, *args, **kwargs):
- team = self.get_object()
- product_type = request.data.get("product_type")
- user = request.user
- current_url = request.headers.get("Referer")
- session_id = request.headers.get("X-Posthog-Session-Id")
-
- if not product_type:
- return response.Response({"error": "product_type is required"}, status=400)
-
- product_intent_serializer = ProductIntentSerializer(data=request.data)
- product_intent_serializer.is_valid(raise_exception=True)
- intent_data = product_intent_serializer.validated_data
- intent_context = intent_data.get("intent_context")
-
- product_intent = ProductIntent.register(
- team=team,
- product_type=product_type,
- context=intent_context,
- user=cast(User, user),
- metadata={**intent_data["metadata"], "$current_url": current_url, "$session_id": session_id},
- is_onboarding=True,
- )
-
- if isinstance(user, User): # typing
- report_user_action(
- user,
- "product onboarding completed",
- {
- "product_key": product_type,
- "intent_context": intent_context,
- "intent_created_at": product_intent.created_at,
- "intent_updated_at": product_intent.updated_at,
- "realm": get_instance_realm(),
- },
- team=team,
- request=request,
- )
-
- return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
-
- @extend_schema(responses=EventIngestionRestrictionSerializer(many=True))
- @action(
- methods=["GET"],
- detail=True,
- required_scopes=["project:read"],
- url_path="event_ingestion_restrictions",
- pagination_class=None,
- )
- def event_ingestion_restrictions(self, request, **kwargs):
- return team_event_ingestion_restrictions_view(self.get_object(), request)
-
- @cached_property
- def user_permissions(self):
- team = self.get_object() if self.action in actions_that_require_current_team else None
- return UserPermissions(cast(User, self.request.user), team)
-
-
-class RootTeamViewSet(TeamViewSet):
- # NOTE: We don't want people creating environments via the "current_organization"/"current_project" concept, but
- # rather specify the org ID and project ID in the URL - hence this is hidden from the API docs, but used in the app
- hide_api_docs = True
-
-
-class ProjectEnvironmentsViewSet(TeamViewSet):
- """Deprecated: use /api/environments/{id}/ instead.
-
- Hidden from the API docs, so the actions it inherits from TeamViewSet do not reach the
- generated types and MCP tools under a route that rejects every request."""
-
- hide_api_docs = True
-
- def initial(self, request: request.Request, *args, **kwargs) -> None:
- raise exceptions.PermissionDenied(
- "Multiple environments per project are no longer available. Please contact support if you need assistance."
- )
-
-
-def conversations_settings_as_dict(value: object) -> dict[str, Any]:
- """Coerce a conversations_settings value to a dict for merging or diffing.
-
- A row written before validation required an object/null can hold a stray array or scalar;
- treat it as empty rather than raising.
- """
- return value if isinstance(value, dict) else {}
-
-
-def report_conversations_settings_changes(
- user: User, before_settings: dict | None, after_settings: dict | None, team: Team
-) -> None:
- """Fire one "support setting changed" event per changed conversations_settings key.
-
- Shared by the team and project serializers — both endpoints can PATCH the settings.
- Pass the settings this request wrote, not the refreshed row: a write that commits
- after this request's write would otherwise be reported as this user's change.
- """
- old_settings = conversations_settings_as_dict(before_settings)
- new_settings = conversations_settings_as_dict(after_settings)
- changed_keys = sorted(
- k for k in old_settings.keys() | new_settings.keys() if old_settings.get(k) != new_settings.get(k)
- )
- # One event per changed setting so insights can break down by `setting`.
- for key in changed_keys:
- new_value = new_settings.get(key)
- properties: dict[str, Any] = {"setting": key}
- # Only non-string values are safe to report — the dict holds free text and the widget token.
- if isinstance(new_value, (bool, int, float, type(None))):
- properties["value"] = new_value
- report_user_action(user, "support setting changed", properties, team=team)
-
-
-MANAGED_CONVERSATIONS_SETTINGS = (
- # Strip widget_public_token from user input - it's auto-generated only
- "widget_public_token",
- # Integration state is managed only by dedicated endpoints, not user input
- "slack_bot_token",
- "slack_team_id",
- "slack_enabled",
- "slack_scopes",
- "email_enabled",
- "teams_enabled",
- "teams_tenant_id",
- "teams_team_id",
- "teams_team_name",
- "teams_channel_id",
- "teams_channel_name",
- "teams_channels",
- "github_enabled",
- "github_integration_id",
- "github_repos",
-)
-
-LOCKED_CONVERSATIONS_COLUMNS = ("conversations_settings", "conversations_enabled")
-
-
-def merge_conversations_settings_locked(
- team: Team,
- validated_data: dict[str, Any],
- patch_conversations_settings: bool,
- other_update_fields: list[str],
-) -> dict[str, Any]:
- """Merge the conversations columns this request writes under one lock on the team row.
-
- Shared by the team and project serializers — both endpoints can PATCH the settings.
- The merge reads and the save must share one locked view of the team row: a dedicated
- integration update (Slack/Teams OAuth, support token rotation) commits whole-blob
- conversations_settings writes too, and a merge built on the pre-request snapshot would
- silently restore the state that update had just replaced. Keyed on the columns this
- request writes, not on which key the client sent: the token handler can inject
- conversations_settings into a payload that only sent conversations_enabled.
- The same save writes other_update_fields, which the caller already set on the team, so a
- PATCH that mixes conversation and other fields saves the row once and commits all or nothing.
- Returns the locked row's pre-merge conversations_settings and conversations_enabled,
- so the caller can correct its before-snapshot: that snapshot was taken before this
- lock re-read the row, and a concurrent integration write in between would otherwise
- get attributed to this request in the activity log and the settings-changed event.
- """
- with transaction.atomic():
- locked_team = (
- Team.objects.select_for_update(no_key=True)
- .only("conversations_settings", "conversations_enabled")
- .get(pk=team.pk)
- )
- if patch_conversations_settings:
- validated_data["conversations_settings"] = merge_conversations_settings(
- validated_data["conversations_settings"], locked_team.conversations_settings
- )
-
- validated_data = handle_conversations_token_on_update(
- validated_data, locked_team.conversations_enabled, locked_team.conversations_settings
- )
- team.conversations_settings = validated_data.get("conversations_settings", locked_team.conversations_settings)
- # Sync the flag even when this request does not write it. Otherwise the caller's
- # after-snapshot keeps a stale value and a concurrent toggle is logged as this user's.
- team.conversations_enabled = validated_data.get("conversations_enabled", locked_team.conversations_enabled)
- update_fields = ["conversations_settings", *other_update_fields, "updated_at"]
- if "conversations_enabled" in validated_data:
- update_fields.append("conversations_enabled")
- team.save(update_fields=update_fields)
- for column in LOCKED_CONVERSATIONS_COLUMNS:
- validated_data.pop(column, None)
-
- return {
- "conversations_settings": locked_team.conversations_settings,
- "conversations_enabled": locked_team.conversations_enabled,
- }
-
-
-def strip_managed_conversations_settings(value: dict[str, Any]) -> None:
- if not isinstance(value, dict):
- raise serializers.ValidationError("Conversation settings must be an object or null.")
- for managed_key in MANAGED_CONVERSATIONS_SETTINGS:
- value.pop(managed_key, None)
-
-
-def merge_conversations_settings(value: dict[str, Any] | None, existing: object) -> dict[str, Any] | None:
- existing = conversations_settings_as_dict(existing)
- if value is None:
- return {key: existing[key] for key in MANAGED_CONVERSATIONS_SETTINGS if key in existing} or None
- return {**existing, **value}
-
-
-def handle_conversations_token_on_update(
- validated_data: dict[str, Any],
- current_conversations_enabled: bool | None,
- current_conversations_settings: object,
-) -> dict[str, Any]:
- """Auto-generate/clear conversations widget token based on conversations_enabled changes."""
- if "conversations_enabled" not in validated_data:
- return validated_data
-
- is_enabling = validated_data["conversations_enabled"] and not current_conversations_enabled
- is_disabling = not validated_data["conversations_enabled"] and current_conversations_enabled
-
- stored_settings = conversations_settings_as_dict(current_conversations_settings)
-
- if is_enabling:
- # Check if token already exists in current DB state (not user input, which is stripped)
- has_token = stored_settings.get("widget_public_token")
- if not has_token:
- conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
- conv_settings["widget_public_token"] = secrets.token_urlsafe(32)
- validated_data["conversations_settings"] = conv_settings
- elif is_disabling:
- conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
- conv_settings["widget_public_token"] = None
- validated_data["conversations_settings"] = conv_settings
-
- return validated_data
-
-
-def validate_team_attrs(
- attrs: dict[str, Any], view: TeamAndOrgViewSetMixin, instance: Team | Project | None
-) -> dict[str, Any]:
- if instance is not None:
- admin_fields_touched = TEAM_CONFIG_ADMIN_FIELDS_SET & attrs.keys()
- # `app_urls` (the toolbar / web analytics authorized URLs) carries a `field_access_control`
- # tying it to web analytics editor access. When access controls are enabled, defer to that
- # field-level check instead of the blanket project-admin gate, so a web analytics editor can
- # manage authorized URLs. Without access controls we keep the stricter admin-only behavior.
- if view.user_access_control.access_controls_supported:
- admin_fields_touched = admin_fields_touched - {"app_urls"}
- if admin_fields_touched:
- team_for_check = instance if isinstance(instance, Team) else instance.passthrough_team
- level = view.user_permissions.team(team_for_check).effective_membership_level
- if level is None or level < OrganizationMembership.Level.ADMIN:
- raise exceptions.PermissionDenied(
- "Only project admins can modify these settings: " + ", ".join(sorted(admin_fields_touched))
- )
- else:
- # On create there's no team yet, so check the creator's org-level membership. Without this a
- # non-admin member (allowed to create projects via members_can_create_projects) could set
- # admin-only team fields like receive_org_level_activity_logs. `is_demo` is excluded — demo
- # project creation is intentionally open to members and gated separately. `name` is excluded
- # too — naming a project you're allowed to create is not the same as renaming an existing one.
- admin_fields_touched = (TEAM_CONFIG_ADMIN_FIELDS_SET - {"is_demo", "name"}) & attrs.keys()
- if admin_fields_touched:
- membership = OrganizationMembership.objects.filter(
- user=cast(User, view.request.user), organization_id=view.organization_id
- ).first()
- member_level = membership.level if membership else None
- if member_level is None or member_level < OrganizationMembership.Level.ADMIN:
- raise exceptions.PermissionDenied(
- "Only organization admins can set these settings on project creation: "
- + ", ".join(sorted(admin_fields_touched))
- )
-
- # A new team has no warehouse tables yet, so only an update can reach a denied one.
- if "test_account_filters" in attrs and instance is not None:
- team = instance if isinstance(instance, Team) else instance.passthrough_team
- denied_table = table_blocking_property_filters(
- cast(User, view.request.user), team, attrs["test_account_filters"]
- )
- if denied_table:
- raise exceptions.ValidationError(
- {
- "test_account_filters": f"This filter uses the table '{denied_table}', which you don't have access to."
- },
- code="permission_denied",
- )
-
- if "primary_dashboard" in attrs:
- if not instance:
- raise exceptions.ValidationError(
- {"primary_dashboard": "Primary dashboard cannot be set on project creation."}
- )
- if attrs["primary_dashboard"] and attrs["primary_dashboard"].team_id != instance.id:
- raise exceptions.ValidationError({"primary_dashboard": "Dashboard does not belong to this team."})
-
- if "home_tab_dashboard" in attrs:
- if not instance:
- raise exceptions.ValidationError(
- {"home_tab_dashboard": "Home tab dashboard cannot be set on project creation."}
- )
- if attrs["home_tab_dashboard"] and attrs["home_tab_dashboard"].team_id != instance.id:
- raise exceptions.ValidationError({"home_tab_dashboard": "Dashboard does not belong to this team."})
-
- if "autocapture_exceptions_errors_to_ignore" in attrs:
- if not isinstance(attrs["autocapture_exceptions_errors_to_ignore"], list):
- raise exceptions.ValidationError("Must provide a list for field: autocapture_exceptions_errors_to_ignore.")
- for error in attrs["autocapture_exceptions_errors_to_ignore"]:
- if not isinstance(error, str):
- raise exceptions.ValidationError(
- "Must provide a list of strings to field: autocapture_exceptions_errors_to_ignore."
- )
-
- if len(json.dumps(attrs["autocapture_exceptions_errors_to_ignore"])) > 300:
- raise exceptions.ValidationError(
- "Field autocapture_exceptions_errors_to_ignore must be less than 300 characters. Complex config should be provided in posthog-js initialization."
- )
- return attrs
-
-
-class PremiumMultiEnvironmentPermission(BasePermission):
- """Enforce one non-demo team per project limit."""
-
- message = "You have reached the maximum limit of allowed environments for your current plan. Upgrade your plan to be able to create and manage more environments."
-
- def has_permission(self, request: request.Request, view) -> bool:
- if view.action not in CREATE_ACTIONS:
- return True
-
- try:
- project = view.project
- except KeyError: # KeyError occurs when "project_id" is not in parents_query_dict
- raise exceptions.ValidationError(
- "Environments must be created under a specific project. Send the POST request to /api/projects/<project_id>/environments/ instead."
- )
-
- if request.data.get("is_demo"):
- # Allow one demo team per organization
- if project.organization.teams.filter(is_demo=True).exists():
- return False
- return True
-
- # Only allow one non-demo team per project
- current_non_demo_team_count = project.teams.exclude(is_demo=True).count()
- if current_non_demo_team_count >= 1:
- return False
-
- return True
diff --git a/posthog/api/team/__init__.py b/posthog/api/team/__init__.py
new file mode 100644
index 000000000000..615a1df28771
--- /dev/null
+++ b/posthog/api/team/__init__.py
@@ -0,0 +1 @@
+"""Project settings API."""
diff --git a/posthog/api/team/conversations_settings.py b/posthog/api/team/conversations_settings.py
new file mode 100644
index 000000000000..5d1b70389798
--- /dev/null
+++ b/posthog/api/team/conversations_settings.py
@@ -0,0 +1,171 @@
+"""Conversations settings update helpers."""
+
+import secrets
+from typing import Any
+
+from django.db import transaction
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from posthog.event_usage import report_user_action
+from posthog.models import Team, User
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class ConversationsSettingsField(serializers.JSONField):
+ pass
+
+
+MANAGED_CONVERSATIONS_SETTINGS = (
+ # Strip widget_public_token from user input - it's auto-generated only
+ "widget_public_token",
+ # Integration state is managed only by dedicated endpoints, not user input
+ "slack_bot_token",
+ "slack_team_id",
+ "slack_enabled",
+ "slack_scopes",
+ "email_enabled",
+ "teams_enabled",
+ "teams_tenant_id",
+ "teams_team_id",
+ "teams_team_name",
+ "teams_channel_id",
+ "teams_channel_name",
+ "teams_channels",
+ "github_enabled",
+ "github_integration_id",
+ "github_repos",
+)
+
+LOCKED_CONVERSATIONS_COLUMNS = ("conversations_settings", "conversations_enabled")
+
+
+def strip_managed_conversations_settings(value: dict[str, Any]) -> None:
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Conversation settings must be an object or null.")
+ for managed_key in MANAGED_CONVERSATIONS_SETTINGS:
+ value.pop(managed_key, None)
+
+
+def merge_conversations_settings(value: dict[str, Any] | None, existing: object) -> dict[str, Any] | None:
+ existing = conversations_settings_as_dict(existing)
+ if value is None:
+ return {key: existing[key] for key in MANAGED_CONVERSATIONS_SETTINGS if key in existing} or None
+ return {**existing, **value}
+
+
+def merge_conversations_settings_locked(
+ team: Team,
+ validated_data: dict[str, Any],
+ patch_conversations_settings: bool,
+ other_update_fields: list[str],
+) -> dict[str, Any]:
+ """Merge the conversations columns this request writes under one lock on the team row.
+
+ Shared by the team and project serializers — both endpoints can PATCH the settings.
+ The merge reads and the save must share one locked view of the team row: a dedicated
+ integration update (Slack/Teams OAuth, support token rotation) commits whole-blob
+ conversations_settings writes too, and a merge built on the pre-request snapshot would
+ silently restore the state that update had just replaced. Keyed on the columns this
+ request writes, not on which key the client sent: the token handler can inject
+ conversations_settings into a payload that only sent conversations_enabled.
+ The same save writes other_update_fields, which the caller already set on the team, so a
+ PATCH that mixes conversation and other fields saves the row once and commits all or nothing.
+ Returns the locked row's pre-merge conversations_settings and conversations_enabled,
+ so the caller can correct its before-snapshot: that snapshot was taken before this
+ lock re-read the row, and a concurrent integration write in between would otherwise
+ get attributed to this request in the activity log and the settings-changed event.
+ """
+ with transaction.atomic():
+ locked_team = (
+ Team.objects.select_for_update(no_key=True)
+ .only("conversations_settings", "conversations_enabled")
+ .get(pk=team.pk)
+ )
+ if patch_conversations_settings:
+ validated_data["conversations_settings"] = merge_conversations_settings(
+ validated_data["conversations_settings"], locked_team.conversations_settings
+ )
+
+ validated_data = handle_conversations_token_on_update(
+ validated_data, locked_team.conversations_enabled, locked_team.conversations_settings
+ )
+ team.conversations_settings = validated_data.get("conversations_settings", locked_team.conversations_settings)
+ # Sync the flag even when this request does not write it. Otherwise the caller's
+ # after-snapshot keeps a stale value and a concurrent toggle is logged as this user's.
+ team.conversations_enabled = validated_data.get("conversations_enabled", locked_team.conversations_enabled)
+ update_fields = ["conversations_settings", *other_update_fields, "updated_at"]
+ if "conversations_enabled" in validated_data:
+ update_fields.append("conversations_enabled")
+ team.save(update_fields=update_fields)
+ for column in LOCKED_CONVERSATIONS_COLUMNS:
+ validated_data.pop(column, None)
+
+ return {
+ "conversations_settings": locked_team.conversations_settings,
+ "conversations_enabled": locked_team.conversations_enabled,
+ }
+
+
+def conversations_settings_as_dict(value: object) -> dict[str, Any]:
+ """Coerce a conversations_settings value to a dict for merging or diffing.
+
+ A row written before validation required an object/null can hold a stray array or scalar;
+ treat it as empty rather than raising.
+ """
+ return value if isinstance(value, dict) else {}
+
+
+def report_conversations_settings_changes(
+ user: User, before_settings: dict | None, after_settings: dict | None, team: Team
+) -> None:
+ """Fire one "support setting changed" event per changed conversations_settings key.
+
+ Shared by the team and project serializers — both endpoints can PATCH the settings.
+ Pass the settings this request wrote, not the refreshed row: a write that commits
+ after this request's write would otherwise be reported as this user's change.
+ """
+ old_settings = conversations_settings_as_dict(before_settings)
+ new_settings = conversations_settings_as_dict(after_settings)
+ changed_keys = sorted(
+ k for k in old_settings.keys() | new_settings.keys() if old_settings.get(k) != new_settings.get(k)
+ )
+ # One event per changed setting so insights can break down by `setting`.
+ for key in changed_keys:
+ new_value = new_settings.get(key)
+ properties: dict[str, Any] = {"setting": key}
+ # Only non-string values are safe to report — the dict holds free text and the widget token.
+ if isinstance(new_value, (bool, int, float, type(None))):
+ properties["value"] = new_value
+ report_user_action(user, "support setting changed", properties, team=team)
+
+
+def handle_conversations_token_on_update(
+ validated_data: dict[str, Any],
+ current_conversations_enabled: bool | None,
+ current_conversations_settings: object,
+) -> dict[str, Any]:
+ """Auto-generate/clear conversations widget token based on conversations_enabled changes."""
+ if "conversations_enabled" not in validated_data:
+ return validated_data
+
+ is_enabling = validated_data["conversations_enabled"] and not current_conversations_enabled
+ is_disabling = not validated_data["conversations_enabled"] and current_conversations_enabled
+
+ stored_settings = conversations_settings_as_dict(current_conversations_settings)
+
+ if is_enabling:
+ # Check if token already exists in current DB state (not user input, which is stripped)
+ has_token = stored_settings.get("widget_public_token")
+ if not has_token:
+ conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
+ conv_settings["widget_public_token"] = secrets.token_urlsafe(32)
+ validated_data["conversations_settings"] = conv_settings
+ elif is_disabling:
+ conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
+ conv_settings["widget_public_token"] = None
+ validated_data["conversations_settings"] = conv_settings
+
+ return validated_data
diff --git a/posthog/api/team/integration_config.py b/posthog/api/team/integration_config.py
new file mode 100644
index 000000000000..d96b21db9765
--- /dev/null
+++ b/posthog/api/team/integration_config.py
@@ -0,0 +1,423 @@
+"""Serializers and handlers for product-specific project settings."""
+
+from typing import Any, cast
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db import transaction
+from django.utils import timezone
+
+from rest_framework import exceptions, request, response, serializers
+
+from posthog.event_usage import report_user_action
+from posthog.models import Organization, Team, User
+from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.logs_retention import (
+ LOGS_RETENTION_BASE_TIERS_DAYS,
+ logs_retention_days_error,
+ required_logs_retention_feature,
+ retention_update_throttle_error,
+)
+
+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name
+from products.logs.backend.models import TeamLogsConfig
+from products.tracing.backend.facade.team_extension import TeamTracingConfig
+
+from . import settings_validation
+
+# Gates changes to the traces default retention period. Mirrored in `FEATURE_FLAGS.TRACING_SETTINGS_RETENTION`.
+TRACES_RETENTION_FLAG = "tracing-settings-retention"
+
+
+def _validate_unique_attribute_keys(value: list[str]) -> list[str]:
+ # The child CharField already trims whitespace and rejects blanks; only
+ # cross-item uniqueness needs checking here.
+ if len(set(value)) != len(value):
+ raise serializers.ValidationError("Attribute keys must be unique.")
+ return value
+
+
+class TeamLogsConfigSerializer(serializers.ModelSerializer):
+ logs_distinct_id_attribute_key = serializers.CharField(
+ read_only=True,
+ help_text=(
+ "Legacy single-key alias — always the first entry of "
+ "`logs_distinct_id_attribute_keys`. Read-only; write the plural field instead."
+ ),
+ )
+ logs_distinct_id_attribute_keys = serializers.ListField(
+ # trim_whitespace is the DRF default, but the uniqueness validator below
+ # depends on it — spell it out so it can't drift silently.
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=False,
+ max_length=10,
+ help_text=(
+ "Log attribute keys whose values should match a person's distinct_id — a log "
+ "links to a person when any of these attributes equals one of their distinct IDs. "
+ "Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to "
+ "['posthogDistinctId'] — the convention documented at "
+ "https://posthog.com/docs/logs/link-session-replay and the key the "
+ "posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your "
+ "pipeline emits the person identifier under different attributes."
+ ),
+ )
+ logs_session_id_attribute_keys = serializers.ListField(
+ # trim_whitespace is the DRF default, but the uniqueness validator below
+ # depends on it — spell it out so it can't drift silently.
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=False,
+ max_length=10,
+ help_text=(
+ "Ordered list of log attribute keys whose values hold the PostHog session ID. "
+ "Detection checks keys in order, then falls back to common session ID attribute "
+ "conventions; the first key with a value wins. Defaults to ['sessionId'] — the "
+ "convention documented at https://posthog.com/docs/logs/link-session-replay and "
+ "the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only "
+ "if your pipeline emits the session ID under different attributes."
+ ),
+ )
+ logs_pattern_message_keys = serializers.ListField(
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=True,
+ max_length=10,
+ help_text=(
+ "Ordered list of top-level JSON keys whose value is the message text that log "
+ "patterns are derived from. Keys are matched literally at the top level of the log "
+ "body; a dot in a key is part of the key name, not a path into nested objects. "
+ "Selection checks keys in order; the first key whose value is a non-empty string "
+ "wins. Defaults to ['message', 'msg', 'event']. An empty list "
+ "turns message extraction off, so JSON log bodies group by their key set instead. "
+ "The stored log body is never changed by this setting."
+ ),
+ )
+
+ class Meta:
+ model = TeamLogsConfig
+ fields = [
+ "logs_distinct_id_attribute_key",
+ "logs_distinct_id_attribute_keys",
+ "logs_session_id_attribute_keys",
+ "logs_pattern_message_keys",
+ ]
+
+ def validate_logs_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:
+ return _validate_unique_attribute_keys(value)
+
+ def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:
+ return _validate_unique_attribute_keys(value)
+
+ def validate_logs_pattern_message_keys(self, value: list[str]) -> list[str]:
+ return _validate_unique_attribute_keys(value)
+
+ def update(self, instance: TeamLogsConfig, validated_data: dict) -> TeamLogsConfig:
+ # Keep the legacy single-key column in sync so pre-plural readers stay coherent.
+ keys = validated_data.get("logs_distinct_id_attribute_keys")
+ if keys:
+ validated_data["logs_distinct_id_attribute_key"] = keys[0]
+ return super().update(instance, validated_data)
+
+
+def _check_traces_retention_entitlement(days: int, organization: Organization | None) -> None:
+ # Traces reuse the Logs retention entitlement.
+ required_feature = required_logs_retention_feature(days)
+ if required_feature and (organization is None or not organization.is_feature_available(required_feature)):
+ raise exceptions.PermissionDenied(
+ f"This organization does not have permission to set traces retention to {days} days."
+ )
+
+
+class TeamTracingConfigSerializer(serializers.ModelSerializer):
+ tracing_distinct_id_attribute_keys = serializers.ListField(
+ # trim_whitespace is the DRF default, but the uniqueness validator below
+ # depends on it — spell it out so it can't drift silently.
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=False,
+ max_length=10,
+ help_text=(
+ "Span or resource attribute keys whose values should match a person's distinct_id — "
+ "a span links to a person when any of these attributes holds one of their distinct "
+ "IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / "
+ "posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if "
+ "your pipeline emits the person identifier under different attributes."
+ ),
+ )
+ tracing_session_id_attribute_keys = serializers.ListField(
+ # trim_whitespace is the DRF default, but the uniqueness validator below
+ # depends on it — spell it out so it can't drift silently.
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=False,
+ max_length=10,
+ help_text=(
+ "Ordered list of span or resource attribute keys whose values hold the PostHog "
+ "session ID. Detection checks keys in order, then falls back to common session ID "
+ "attribute conventions; the first key with a value wins. Defaults to ['sessionId'], "
+ "the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they "
+ "emit. Add keys only if your pipeline emits the session ID under different attributes."
+ ),
+ )
+
+ retention_days = serializers.IntegerField(
+ required=False,
+ help_text=(
+ "How long spans are kept before they are deleted, in days. Applied at ingest, so a "
+ "change only affects spans received after it. Can be changed at most once per 24 "
+ "hours. Span retention rules override this period for the spans they match."
+ ),
+ )
+
+ class Meta:
+ model = TeamTracingConfig
+ fields = [
+ "tracing_distinct_id_attribute_keys",
+ "tracing_session_id_attribute_keys",
+ "retention_days",
+ "retention_last_updated",
+ ]
+ read_only_fields = ["retention_last_updated"]
+
+ def validate_tracing_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:
+ return _validate_unique_attribute_keys(value)
+
+ def validate_tracing_session_id_attribute_keys(self, value: list[str]) -> list[str]:
+ return _validate_unique_attribute_keys(value)
+
+ def validate_retention_days(self, value: int) -> int:
+ # Only a changed period is checked against the flags and the entitlement, so an unrelated
+ # update that sends the stored period back keeps working after either is turned off.
+ if self.instance is not None and self.instance.retention_days == value:
+ return value
+
+ team = self.context.get("team")
+ organization = team.organization if team is not None else None
+ user = getattr(self.context.get("request"), "user", None)
+ if not settings_validation._flag_enabled_for_caller(TRACES_RETENTION_FLAG, organization, user, team):
+ raise exceptions.PermissionDenied("Changing traces retention is not available for this project yet.")
+
+ # Only evaluate the flag outside the base tiers, so the common path makes no flag call.
+ custom_enabled = (
+ value not in LOGS_RETENTION_BASE_TIERS_DAYS
+ and settings_validation._custom_retention_flag_enabled(organization, user, team)
+ )
+ error = logs_retention_days_error(value, custom_retention_enabled=custom_enabled)
+ if error:
+ raise exceptions.ValidationError(error)
+
+ _check_traces_retention_entitlement(value, organization)
+
+ throttle_error = retention_update_throttle_error(
+ self.instance.retention_last_updated if self.instance is not None else None
+ )
+ if throttle_error:
+ raise exceptions.ValidationError(throttle_error)
+
+ return value
+
+ def update(self, instance: TeamTracingConfig, validated_data: dict[str, Any]) -> TeamTracingConfig:
+ new_retention = validated_data.get("retention_days")
+ if new_retention is not None and new_retention != instance.retention_days:
+ validated_data["retention_last_updated"] = timezone.now()
+ return super().update(instance, validated_data)
+
+
+def handle_tracing_config(request: request.Request, team: Team) -> response.Response:
+ """Shared handler for the tracing_config action — exposed under both the team/environment
+ and project routers so the canonical /api/projects/ URL resolves alongside the legacy
+ /api/environments/ alias. Both endpoints operate on the env-scoped TeamTracingConfig
+ keyed by team_id."""
+ config = get_or_create_team_extension(team, TeamTracingConfig)
+
+ if request.method == "PATCH":
+ serializer = TeamTracingConfigSerializer(
+ config, data=request.data, partial=True, context={"request": request, "team": team}
+ )
+ serializer.is_valid(raise_exception=True)
+ with transaction.atomic():
+ locked_config = TeamTracingConfig.objects.select_for_update().get(team=team)
+ retention = serializer.validated_data.get("retention_days")
+ if retention is not None and retention != locked_config.retention_days:
+ throttle_error = retention_update_throttle_error(locked_config.retention_last_updated)
+ if throttle_error:
+ raise exceptions.ValidationError({"retention_days": throttle_error})
+ if locked_config.retention_days != config.retention_days:
+ # Entitlement resets do not set retention_last_updated, so the throttle cannot see them.
+ raise exceptions.ValidationError(
+ {"retention_days": "Retention changed. Reload the settings and retry."}
+ )
+ # Billing can revoke the entitlement after validation read the organization.
+ _check_traces_retention_entitlement(
+ retention, Organization.objects.only("available_product_features").get(id=team.organization_id)
+ )
+ serializer.instance = locked_config
+ serializer.save()
+ return response.Response(serializer.data)
+
+ return response.Response(TeamTracingConfigSerializer(config).data)
+
+
+def handle_experiments_config(request: request.Request, team: Team) -> response.Response:
+ """Shared handler for the experiments_config action — exposed under both the
+ team/environment and project routers so both surfaces stay in parity."""
+ # Keeps the products app import off this module's import path.
+ from products.experiments.backend.models.team_experiments_config import ( # noqa: PLC0415
+ MAX_RECALCULATION_TIMES,
+ MIN_RECALCULATION_GAP_HOURS,
+ TeamExperimentsConfig,
+ validate_recalculation_times,
+ )
+
+ class TeamExperimentsConfigSerializer(serializers.ModelSerializer):
+ experiment_recalculation_times = serializers.ListField(
+ child=serializers.RegexField(
+ regex=r"^(?:[01]\d|2[0-3]):00:00$",
+ error_messages={"invalid": "Recalculation times must be on the hour, in HH:00:00 format (UTC)."},
+ ),
+ required=False,
+ allow_null=True,
+ allow_empty=False,
+ max_length=MAX_RECALCULATION_TIMES,
+ help_text=(
+ "Times of day (UTC) when experiment metrics are recalculated, as 'HH:00:00' strings "
+ f"on the hour. At most {MAX_RECALCULATION_TIMES} entries, at least "
+ f"{MIN_RECALCULATION_GAP_HOURS} hours apart. Null means the default time (02:00 UTC)."
+ ),
+ )
+
+ class Meta:
+ model = TeamExperimentsConfig
+ fields = [
+ "experiment_recalculation_times",
+ "default_experiment_confidence_level",
+ "default_experiment_stats_method",
+ "experiment_precomputation_enabled",
+ "default_only_count_matured_users",
+ "default_cuped_enabled",
+ "default_cuped_lookback_days",
+ "default_minimum_detectable_effect",
+ "default_sequential_testing_enabled",
+ "default_sequential_tuning_parameter",
+ "flag_cleanup_repository",
+ ]
+
+ def validate_experiment_recalculation_times(self, value: list[str] | None) -> list[str] | None:
+ try:
+ validate_recalculation_times(value)
+ except DjangoValidationError as e:
+ raise serializers.ValidationError(e.messages)
+ return value
+
+ def update(self, instance: "TeamExperimentsConfig", validated_data: dict[str, Any]) -> "TeamExperimentsConfig":
+ # A human toggling precomputation must stick: the auto-enrollment job only
+ # writes when precomputation_enabled_set_by is null or "auto".
+ if "experiment_precomputation_enabled" in validated_data:
+ instance.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL
+ return super().update(instance, validated_data)
+
+ def validate_flag_cleanup_repository(self, value: str | None) -> str | None:
+ # Keeps the sandbox/LLM runtime the repo-selection module pulls in off the
+ # request import path.
+ from products.tasks.backend.facade import repo_selection as tasks_repo_selection # noqa: PLC0415
+
+ if not value:
+ return None
+ parts = value.split("/")
+ if len(parts) != 2 or not parts[0] or not parts[1]:
+ raise serializers.ValidationError("Repository must be in the format organization/repository")
+ value = value.lower()
+ # Reject repos outside the team's GitHub installation now rather than storing a
+ # default the cleanup resolution would silently ignore.
+ github = tasks_repo_selection.resolve_team_github_integration(team.id, team=team, team_only=True)
+ cached = {
+ full_name.lower()
+ for repo in (github.list_all_cached_repositories(max_repos=1000) if github else [])
+ if (full_name := repo.get("full_name"))
+ }
+ if value not in cached:
+ raise serializers.ValidationError(
+ "This repository is not connected to the project's GitHub integration."
+ )
+ return value
+
+ config = get_or_create_team_extension(team, TeamExperimentsConfig)
+
+ if request.method == "PATCH":
+ serializer = TeamExperimentsConfigSerializer(config, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+ return response.Response(serializer.data)
+
+ return response.Response(TeamExperimentsConfigSerializer(config).data)
+
+
+def handle_logs_config(request: request.Request, team: Team) -> response.Response:
+ """Shared handler for the logs_config action — exposed under both the team/environment
+ and project routers so the canonical /api/projects/ URL resolves alongside the legacy
+ /api/environments/ alias. Both endpoints operate on the env-scoped TeamLogsConfig
+ keyed by team_id."""
+ config = get_or_create_team_extension(team, TeamLogsConfig)
+
+ if request.method == "PATCH":
+ serializer = TeamLogsConfigSerializer(config, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+ return response.Response(serializer.data)
+
+ return response.Response(TeamLogsConfigSerializer(config).data)
+
+
+def handle_evaluation_context_suggestions(request: request.Request, team: Team) -> response.Response:
+ """Handler for the evaluation_context_suggestions action on the team/environment router.
+
+ Unlike the other handlers here, this one is not shared: the project router calls its own
+ `team_evaluation_context_suggestions_view`, so a change here does not reach /api/projects/.
+ The import note at the top of `posthog/api/project.py` says why that copy stays local.
+
+ Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+ POST hides the name; DELETE restores it. The underlying context row and any flags already
+ using it are never modified — this only controls what gets suggested."""
+ # Contexts are persisted under the project root team (see default_evaluation_contexts).
+ root_team = team.parent_team or team
+
+ context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")
+ if not isinstance(context_name, str):
+ return response.Response({"error": "context_name must be a string"}, status=400)
+ context_name = normalize_context_name(context_name)
+ if not context_name:
+ return response.Response({"error": "context_name is required"}, status=400)
+ if len(context_name) > 255:
+ return response.Response({"error": "context_name must be at most 255 characters"}, status=400)
+
+ hidden = request.method == "POST"
+
+ with transaction.atomic():
+ try:
+ ctx = EvaluationContext.objects.select_for_update().get(name=context_name, team=root_team)
+ except EvaluationContext.DoesNotExist:
+ return response.Response({"error": "Evaluation context not found"}, status=404)
+
+ if ctx.hidden_from_suggestions != hidden:
+ ctx.hidden_from_suggestions = hidden
+ ctx.save(update_fields=["hidden_from_suggestions"])
+ report_user_action(
+ cast(User, request.user),
+ "evaluation context suggestion hidden" if hidden else "evaluation context suggestion restored",
+ {"team_id": team.id, "context_name": context_name},
+ team=team,
+ request=request,
+ )
+
+ return response.Response({"success": True, "name": context_name, "hidden_from_suggestions": hidden})
+
+
+def validate_secret_token_generation(team: Team) -> None:
+ """Rotating an existing legacy secret token stays allowed for safe migration, but minting a
+ first one is blocked unless Support is enabled. Project secret API keys replace it."""
+ if team.secret_api_token or team.secret_api_token_backup:
+ return
+ if team.conversations_enabled:
+ # Support signs widget identity hashes with the raw token and authenticates its external
+ # API against it. Project secret API keys are only ever stored hashed, so they cannot
+ # replace it, which would leave Support with no way to verify identity at all.
+ return
+ raise exceptions.ValidationError(
+ "The feature flags secure API key is deprecated. Create a project secret API key with the "
+ "feature_flag:read scope instead."
+ )
diff --git a/posthog/api/team/live_events.py b/posthog/api/team/live_events.py
new file mode 100644
index 000000000000..2abfcf221b98
--- /dev/null
+++ b/posthog/api/team/live_events.py
@@ -0,0 +1,92 @@
+"""Project settings helpers for themes and live events tokens."""
+
+from datetime import timedelta
+
+from django.conf import settings
+
+from rest_framework.request import Request
+
+from posthog.jwt import PosthogJwtAudience, encode_jwt, signing_key_fingerprint
+from posthog.models import Team
+from posthog.models.data_color_theme import DataColorTheme
+from posthog.permissions import get_authenticator_scopes
+from posthog.scopes import scopes_not_covered
+from posthog.utils import get_safe_cache, safe_cache_set
+
+_default_theme_id_cache: int | None = None
+LIVE_EVENTS_TOKEN_TTL_SECONDS = 24 * 60 * 60
+
+
+def _default_data_color_theme_id() -> int | None:
+ """Return the system-wide default DataColorTheme id, cached for process lifetime.
+
+ The default is created by data migration `0537_data_color_themes.py` and
+ is effectively a constant after deploy - cache it to skip a per-render PG
+ round-trip in `TeamSerializer.to_representation` for orgs without the
+ DATA_COLOR_THEMES feature.
+
+ We deliberately do NOT cache `None`: if the first call lands before the
+ migration is applied, or against an instance where no global default
+ exists yet, we want subsequent calls to recover automatically once the
+ row appears. `.order_by("id")` keeps the chosen ID deterministic across
+ workers if multiple globals ever exist.
+ """
+ global _default_theme_id_cache
+ if _default_theme_id_cache is None:
+ _default_theme_id_cache = (
+ DataColorTheme.objects.filter(team_id__isnull=True).order_by("id").values_list("id", flat=True).first()
+ )
+ return _default_theme_id_cache
+
+
+def _reset_default_data_color_theme_id_cache() -> None:
+ """Test-only helper for explicit cache invalidation."""
+ global _default_theme_id_cache
+ _default_theme_id_cache = None
+
+
+def _live_events_token_cache_key(team: Team, user_id: int | None) -> str:
+ """Build the cache key for the live-events JWT.
+
+ Includes a short fingerprint of `settings.JWT_SIGNING_KEY` so that rotating the
+ signing key automatically partitions the cache namespace - cached tokens signed
+ with the old key become unreachable rather than served until TTL.
+ Hashing also defends the cache key against future api-token formats that
+ might contain the `:` separator we use between components.
+ """
+ signing_fingerprint = signing_key_fingerprint(settings.JWT_SIGNING_KEY)
+ return f"live_events_token:{signing_fingerprint}:{team.id}:{user_id}:{team.api_token}:{team.organization_id}"
+
+
+def get_or_mint_live_events_token(team: Team, user_id: int | None) -> str:
+ """Return a cached live-events JWT for this (team, user) pair, minting one if missing.
+
+ The JWT itself is valid for 7 days. The cache TTL is 24h, so any token returned
+ from cache still has at least 6 days of remaining validity. The cache key includes
+ every field that ends up in the claims so api-token rotations or organization
+ moves automatically force a fresh mint, plus a JWT_SIGNING_KEY fingerprint so
+ signing-key rotation auto-partitions the cache namespace (no manual flush needed).
+ """
+ cache_key = _live_events_token_cache_key(team, user_id)
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+
+ claims = {
+ "team_id": team.id,
+ "api_token": team.api_token,
+ "user_id": user_id,
+ "organization_id": str(team.organization_id),
+ }
+ token = encode_jwt(claims, timedelta(days=7), PosthogJwtAudience.LIVESTREAM)
+ safe_cache_set(cache_key, token, timeout=LIVE_EVENTS_TOKEN_TTL_SECONDS)
+ return token
+
+
+def live_events_token_for_request(team: Team, request: Request | None) -> str | None:
+ if request is None or not request.user.is_authenticated:
+ return None
+ scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if scopes is not None and "*" not in scopes and scopes_not_covered(scopes, ["query:read"]):
+ return None
+ return get_or_mint_live_events_token(team, request.user.id)
diff --git a/posthog/api/team/marketing_config.py b/posthog/api/team/marketing_config.py
new file mode 100644
index 000000000000..4137bb74abcc
--- /dev/null
+++ b/posthog/api/team/marketing_config.py
@@ -0,0 +1,263 @@
+"""Marketing analytics project settings schemas."""
+
+from typing import Literal
+
+from django.db import transaction
+
+from drf_spectacular.utils import extend_schema_field
+from pydantic import RootModel as PydanticRootModel
+from pydantic.json_schema import SkipJsonSchema
+from rest_framework import serializers
+
+from posthog.schema import (
+ AttributionMode,
+ CampaignFieldPreference,
+ CohortPropertyFilter,
+ ConversionGoalFilter1,
+ ConversionGoalFilter2,
+ ConversionGoalFilter3,
+ DataWarehousePropertyFilter,
+ ElementPropertyFilter,
+ EventPropertyFilter,
+ HogQLPropertyFilter,
+ PersonPropertyFilter,
+ SourceMap,
+)
+
+from posthog.models import TeamMarketingAnalyticsConfig
+
+from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+
+# The filters a conversion goal can carry, rather than every filter HogQL knows about. The goal
+# runtime resolves these through `property_to_expr` with an event scope, where `revenue_analytics`
+# and `account_custom_property` raise and `metric_attribute` is unimplemented, and the goal editor
+# only offers these six. Narrowing here follows `WebAnalyticsPropertyFilter`.
+MarketingAnalyticsConversionGoalPropertyFilter = (
+ EventPropertyFilter
+ | PersonPropertyFilter
+ | CohortPropertyFilter
+ | ElementPropertyFilter
+ | HogQLPropertyFilter
+ | DataWarehousePropertyFilter
+)
+
+
+# Subclassing the canonical goal schemas rather than redeclaring their ~25 fields keeps this write
+# surface from drifting when the query schema changes. The cost is that narrowing a field's type in
+# a subclass is not assignment-compatible, hence the ignores below: each one marks a deliberate
+# divergence from the query schema, not an oversight.
+#
+# `fixedProperties` stays accepted but leaves the documented schema: nothing in the marketing
+# analytics runtime reads it, and advertising it costs a third of this field's generated schema.
+class MarketingAnalyticsEventConversionGoal(ConversionGoalFilter1):
+ """A conversion goal counted from events."""
+
+ # `validate_conversion_goals` rejects a goal without a string name or an explicit kind, so the
+ # documented schema has to require both. `conversion_goal_id` stays required like the query
+ # schema: nothing here assigns one, and a goal stored without it fails to rebuild for queries.
+ kind: Literal["EventsNode"]
+ name: str
+ properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
+ fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
+
+
+class MarketingAnalyticsActionConversionGoal(ConversionGoalFilter2):
+ """A conversion goal counted from an action."""
+
+ kind: Literal["ActionsNode"]
+ name: str
+ properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
+ fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
+
+
+class MarketingAnalyticsWarehouseConversionGoal(ConversionGoalFilter3):
+ """A conversion goal counted from a data warehouse table."""
+
+ kind: Literal["DataWarehouseNode"]
+ name: str
+ properties: list[MarketingAnalyticsConversionGoalPropertyFilter] | None = None # type: ignore[assignment]
+ fixedProperties: SkipJsonSchema[list[MarketingAnalyticsConversionGoalPropertyFilter] | None] = None # type: ignore[assignment]
+
+
+class MarketingAnalyticsConversionGoalList(PydanticRootModel):
+ """The conversion goals configured for marketing analytics, in display order."""
+
+ root: list[
+ MarketingAnalyticsEventConversionGoal
+ | MarketingAnalyticsActionConversionGoal
+ | MarketingAnalyticsWarehouseConversionGoal
+ ]
+
+
+class MarketingAnalyticsSourceMapping(PydanticRootModel):
+ """Mapping of external data source id to that source's column mapping."""
+
+ root: dict[str, SourceMap]
+
+
+class MarketingAnalyticsCampaignFieldPreferences(PydanticRootModel):
+ """Mapping of integration type to the campaign field used when matching campaigns."""
+
+ root: dict[str, CampaignFieldPreference]
+
+
+class MarketingAnalyticsCampaignNameMappings(PydanticRootModel):
+ """Mapping of integration type to canonical campaign name to the aliases folded into it."""
+
+ root: dict[str, dict[str, list[str]]]
+
+
+class MarketingAnalyticsCustomSourceMappings(PydanticRootModel):
+ """Mapping of integration type to the custom UTM source values folded into it."""
+
+ root: dict[str, list[str]]
+
+
+@extend_schema_field(MarketingAnalyticsCampaignNameMappings) # type: ignore[arg-type]
+class MarketingAnalyticsCampaignNameMappingsField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(MarketingAnalyticsCustomSourceMappings) # type: ignore[arg-type]
+class MarketingAnalyticsCustomSourceMappingsField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(MarketingAnalyticsConversionGoalList) # type: ignore[arg-type]
+class MarketingAnalyticsConversionGoalsField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(MarketingAnalyticsSourceMapping) # type: ignore[arg-type]
+class MarketingAnalyticsSourcesMapField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(MarketingAnalyticsCampaignFieldPreferences) # type: ignore[arg-type]
+class MarketingAnalyticsCampaignFieldPreferencesField(serializers.JSONField):
+ pass
+
+
+class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
+ sources_map = MarketingAnalyticsSourcesMapField(
+ required=False,
+ help_text=(
+ "Column mapping per external data source, keyed by source id. Tells marketing analytics which column "
+ "holds campaign, source, cost, clicks and impressions for that source."
+ ),
+ )
+ conversion_goals = MarketingAnalyticsConversionGoalsField(
+ required=False,
+ help_text=(
+ "Conversion goals to attribute against, in display order. Each goal points at an event, an action or a "
+ "data warehouse table, and carries a schema_map describing which fields hold the UTM parameters, the "
+ "timestamp and the distinct id. Replaces the whole list on write."
+ ),
+ )
+ attribution_window_days = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=90,
+ help_text="How many days back a touchpoint can be credited for a conversion. Between 1 and 90.",
+ )
+ # nosemgrep: choices-need-a-class -- an existing list, moved here unchanged from posthog/api/team.py
+ attribution_mode = serializers.ChoiceField(
+ choices=[(mode.value, mode.value.replace("_", " ").title()) for mode in AttributionMode],
+ required=False,
+ help_text="How credit is split across touchpoints when a person saw several campaigns before converting.",
+ )
+ filter_test_accounts = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether marketing analytics drops traffic matching the project's test-account filters. Off by default."
+ ),
+ )
+ campaign_name_mappings = MarketingAnalyticsCampaignNameMappingsField(
+ required=False,
+ help_text=(
+ "Manual campaign name aliases, keyed by integration type then by canonical campaign name, with the list "
+ "of names that should be folded into it. Applied before automatic matching."
+ ),
+ )
+ custom_source_mappings = MarketingAnalyticsCustomSourceMappingsField(
+ required=False,
+ help_text=(
+ "Custom UTM source values to fold into an integration, keyed by integration type. A UTM source can only "
+ "belong to one integration."
+ ),
+ )
+ campaign_field_preferences = MarketingAnalyticsCampaignFieldPreferencesField(
+ required=False,
+ help_text=(
+ "Which field to match campaigns on per integration type, campaign_name or campaign_id. Manual mappings "
+ "in campaign_name_mappings still take precedence."
+ ),
+ )
+
+ class Meta:
+ model = TeamMarketingAnalyticsConfig
+ fields = [
+ "sources_map",
+ "conversion_goals",
+ "attribution_window_days",
+ "attribution_mode",
+ "filter_test_accounts",
+ "campaign_name_mappings",
+ "custom_source_mappings",
+ "campaign_field_preferences",
+ ]
+
+ def to_internal_value(self, data):
+ internal_value = super().to_internal_value(data)
+ if "sources_map" in internal_value:
+ internal_value["_sources_map"] = internal_value["sources_map"]
+ if "conversion_goals" in internal_value:
+ internal_value["_conversion_goals"] = internal_value["conversion_goals"]
+ if "campaign_name_mappings" in internal_value:
+ internal_value["_campaign_name_mappings"] = internal_value["campaign_name_mappings"]
+ if "custom_source_mappings" in internal_value:
+ internal_value["_custom_source_mappings"] = internal_value["custom_source_mappings"]
+ if "campaign_field_preferences" in internal_value:
+ internal_value["_campaign_field_preferences"] = internal_value["campaign_field_preferences"]
+ return internal_value
+
+ @transaction.atomic
+ def update(self, instance, validated_data):
+ instance.refresh_from_db(from_queryset=TeamMarketingAnalyticsConfig.objects.select_for_update())
+ # Handle sources_map with partial updates
+ if "sources_map" in validated_data:
+ new_sources_map = validated_data["sources_map"]
+
+ # For each source in the new data, update it individually
+ for source_id, field_mapping in new_sources_map.items():
+ if field_mapping is None:
+ # If None is passed, remove the source entirely
+ instance.remove_source_mapping(source_id)
+ else:
+ # Update the source mapping (this preserves other sources)
+ instance.update_source_mapping(source_id, field_mapping)
+
+ if "conversion_goals" in validated_data:
+ instance.conversion_goals = validated_data["conversion_goals"]
+
+ # Handle attribution settings
+ if "attribution_window_days" in validated_data:
+ instance.attribution_window_days = validated_data["attribution_window_days"]
+
+ if "attribution_mode" in validated_data:
+ instance.attribution_mode = validated_data["attribution_mode"]
+
+ if "filter_test_accounts" in validated_data:
+ instance.filter_test_accounts = validated_data["filter_test_accounts"]
+
+ if "campaign_name_mappings" in validated_data:
+ instance.campaign_name_mappings = validated_data["campaign_name_mappings"]
+
+ if "custom_source_mappings" in validated_data:
+ instance.custom_source_mappings = validated_data["custom_source_mappings"]
+
+ if "campaign_field_preferences" in validated_data:
+ instance.campaign_field_preferences = validated_data["campaign_field_preferences"]
+
+ instance.save()
+ return instance
diff --git a/posthog/api/team/settings_validation.py b/posthog/api/team/settings_validation.py
new file mode 100644
index 000000000000..ad563354d3ce
--- /dev/null
+++ b/posthog/api/team/settings_validation.py
@@ -0,0 +1,284 @@
+"""Validation, feature flag, and access helpers for project settings."""
+
+import json
+from typing import TYPE_CHECKING, Any, cast
+
+import re2
+from pydantic import TypeAdapter
+from pydantic_core import ValidationError as PydanticValidationError
+from rest_framework import exceptions, serializers
+
+from posthog.api.property_filter_access_gate import table_blocking_property_filters
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import Team, User
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.project import Project
+from posthog.models.team.logs_retention import LOGS_CUSTOM_RETENTION_FLAG
+from posthog.permissions import posthog_feature_flag_enabled
+from posthog.types import AnyPropertyFilter
+
+from . import team_config
+
+if TYPE_CHECKING:
+ from posthog.user_permissions import UserPermissions
+
+test_account_filters_adapter = TypeAdapter(list[AnyPropertyFilter])
+
+
+def _format_serializer_errors(serializer_errors: dict) -> str:
+ """Formats DRF serializer errors into a human readable string."""
+ error_messages: list[str] = []
+ for field, field_errors in serializer_errors.items():
+ if isinstance(field_errors, list):
+ error_messages.extend(f"{field}: {error}" for error in field_errors)
+ else:
+ error_messages.append(f"{field}: {field_errors}")
+ return ". ".join(error_messages)
+
+
+_VALID_TRIGGER_PROPERTY_OPERATORS = {
+ "exact",
+ "is_not",
+ "icontains",
+ "not_icontains",
+ "regex",
+ "not_regex",
+ "gt",
+ "lt",
+}
+
+# Property types the SDK can evaluate client-side
+_VALID_TRIGGER_PROPERTY_TYPES = {
+ "event",
+ "person",
+}
+
+
+def _validate_trigger_property_filters(properties: object, context: str) -> None:
+ """Validate property filters on trigger conditions (events, URLs)."""
+ if not isinstance(properties, list):
+ raise exceptions.ValidationError(f"{context}: 'properties' must be an array.")
+
+ for prop_idx, prop in enumerate(properties):
+ if not isinstance(prop, dict):
+ raise exceptions.ValidationError(f"{context}: property {prop_idx} must be a dictionary.")
+ if "key" not in prop or not isinstance(prop["key"], str):
+ raise exceptions.ValidationError(f"{context}: property {prop_idx} must have a string 'key' field.")
+ if "type" not in prop or prop["type"] not in _VALID_TRIGGER_PROPERTY_TYPES:
+ raise exceptions.ValidationError(
+ f"{context}: property {prop_idx} must have a 'type' field with value: "
+ f"{', '.join(sorted(_VALID_TRIGGER_PROPERTY_TYPES))}."
+ )
+ if "operator" in prop and prop["operator"] not in _VALID_TRIGGER_PROPERTY_OPERATORS:
+ raise exceptions.ValidationError(
+ f"{context}: property {prop_idx} has invalid operator '{prop['operator']}'. "
+ f"Valid operators: {', '.join(sorted(_VALID_TRIGGER_PROPERTY_OPERATORS))}."
+ )
+ # All supported operators require a value (is_set/is_not_set are not supported)
+ if "value" not in prop:
+ raise exceptions.ValidationError(f"{context}: property {prop_idx} must have a 'value' field.")
+
+
+def validate_test_account_filters(value: object) -> list[dict[str, object]]:
+ try:
+ test_account_filters_adapter.validate_python(value)
+ except PydanticValidationError as error:
+ raise exceptions.ValidationError(f"Must provide an array of valid property filters. {error}") from error
+
+ return cast(list[dict[str, object]], value)
+
+
+def _alias_backreferences(alias: str) -> list[int]:
+ """Return the capture-group numbers a re2 replacement alias references (`\\1`..`\\9`, `\\0` for the
+ whole match). A doubled `\\\\` is a literal backslash, not a back-reference, so it's skipped."""
+ refs: list[int] = []
+ i = 0
+ while i < len(alias):
+ if alias[i] == "\\" and i + 1 < len(alias):
+ nxt = alias[i + 1]
+ if nxt == "\\":
+ i += 2
+ continue
+ # ASCII digits only. `str.isdigit()` also accepts characters like `²` and `٣`, which re2
+ # substitutes as literal text, and `int()` rejects `²` outright.
+ if "0" <= nxt <= "9":
+ refs.append(int(nxt))
+ i += 2
+ continue
+ i += 1
+ return refs
+
+
+def validate_path_cleaning_filters(value: object) -> object:
+ """Validate path cleaning rules before they're saved. Each regex must compile under re2 (the
+ engine ClickHouse `replaceRegexpAll` uses), and any `\\1`..`\\9` back-reference in the alias must
+ point at a capture group the regex defines. This surfaces a mistake at save time instead of
+ letting it fail the query later, when path cleaning runs."""
+ if not value:
+ return value
+ if not isinstance(value, list):
+ raise exceptions.ValidationError("Must provide a list of path cleaning rules.")
+
+ for rule in value:
+ if not isinstance(rule, dict):
+ continue
+ regex = rule.get("regex")
+ alias = rule.get("alias")
+ # A missing or empty regex still reaches ClickHouse, where `replaceRegexpAll` returns NULL for
+ # a NULL pattern and an empty pattern matches at every position, interleaving the alias
+ # through the whole path. Neither is recoverable at query time, so refuse the rule.
+ if not isinstance(regex, str) or not regex:
+ raise exceptions.ValidationError("A path cleaning rule needs a regex. Remove the rule or give it one.")
+ try:
+ compiled = re2.compile(regex)
+ except re2.error as error:
+ raise exceptions.ValidationError(f"Invalid path cleaning regex '{regex}': {error}") from error
+
+ if not alias or not isinstance(alias, str):
+ continue
+ group_count = compiled.groups
+ for ref in _alias_backreferences(alias):
+ if ref > group_count:
+ raise exceptions.ValidationError(
+ f"The alias '{alias}' references capture group \\{ref}, but its regex has "
+ f"{group_count} capture group(s). Add the group to the regex or fix the reference."
+ )
+ return value
+
+
+def heatmaps_screenshot_secret_for_reader(team: Team, user_permissions: "UserPermissions") -> str | None:
+ level = user_permissions.team(team).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ return None
+ return team.heatmaps_screenshot_secret
+
+
+def _get_organization_for_logs_settings_check(serializer: serializers.BaseSerializer) -> Organization | None:
+ if serializer.instance is not None:
+ team = (
+ serializer.instance.passthrough_team
+ if hasattr(serializer.instance, "passthrough_team")
+ else serializer.instance
+ )
+ return team.organization
+
+ get_organization = serializer.context.get("get_organization")
+ if callable(get_organization):
+ return cast(Organization | None, get_organization())
+
+ return None
+
+
+def _flag_enabled_for_caller(flag: str, organization: Organization | None, user: Any, team: Team | None) -> bool:
+ if organization is None or user is None or not user.is_authenticated:
+ return False
+ return posthog_feature_flag_enabled(
+ flag,
+ str(user.distinct_id),
+ organization_id=organization.id,
+ team_id=team.id if team is not None else None,
+ )
+
+
+def _custom_retention_flag_enabled(organization: Organization | None, user: Any, team: Team | None) -> bool:
+ """Whether the caller may pick a retention period outside the base tiers."""
+ return _flag_enabled_for_caller(LOGS_CUSTOM_RETENTION_FLAG, organization, user, team)
+
+
+def _custom_logs_retention_enabled(serializer: serializers.BaseSerializer, team: Team | None) -> bool:
+ request = serializer.context.get("request")
+ return _custom_retention_flag_enabled(
+ _get_organization_for_logs_settings_check(serializer), getattr(request, "user", None), team
+ )
+
+
+def validate_team_attrs(
+ attrs: dict[str, Any], view: TeamAndOrgViewSetMixin, instance: Team | Project | None
+) -> dict[str, Any]:
+ if instance is not None:
+ admin_fields_touched = team_config.TEAM_CONFIG_ADMIN_FIELDS_SET & attrs.keys()
+ # `app_urls` (the toolbar / web analytics authorized URLs) carries a `field_access_control`
+ # tying it to web analytics editor access. When access controls are enabled, defer to that
+ # field-level check instead of the blanket project-admin gate, so a web analytics editor can
+ # manage authorized URLs. Without access controls we keep the stricter admin-only behavior.
+ if view.user_access_control.access_controls_supported:
+ admin_fields_touched = admin_fields_touched - {"app_urls"}
+ if admin_fields_touched:
+ team_for_check = instance if isinstance(instance, Team) else instance.passthrough_team
+ level = view.user_permissions.team(team_for_check).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ raise exceptions.PermissionDenied(
+ "Only project admins can modify these settings: " + ", ".join(sorted(admin_fields_touched))
+ )
+ else:
+ # On create there's no team yet, so check the creator's org-level membership. Without this a
+ # non-admin member (allowed to create projects via members_can_create_projects) could set
+ # admin-only team fields like receive_org_level_activity_logs. `is_demo` is excluded — demo
+ # project creation is intentionally open to members and gated separately. `name` is excluded
+ # too — naming a project you're allowed to create is not the same as renaming an existing one.
+ admin_fields_touched = (team_config.TEAM_CONFIG_ADMIN_FIELDS_SET - {"is_demo", "name"}) & attrs.keys()
+ if admin_fields_touched:
+ membership = OrganizationMembership.objects.filter(
+ user=cast(User, view.request.user), organization_id=view.organization_id
+ ).first()
+ member_level = membership.level if membership else None
+ if member_level is None or member_level < OrganizationMembership.Level.ADMIN:
+ raise exceptions.PermissionDenied(
+ "Only organization admins can set these settings on project creation: "
+ + ", ".join(sorted(admin_fields_touched))
+ )
+
+ # A new team has no warehouse tables yet, so only an update can reach a denied one.
+ if "test_account_filters" in attrs and instance is not None:
+ team = instance if isinstance(instance, Team) else instance.passthrough_team
+ denied_table = table_blocking_property_filters(
+ cast(User, view.request.user), team, attrs["test_account_filters"]
+ )
+ if denied_table:
+ raise exceptions.ValidationError(
+ {
+ "test_account_filters": f"This filter uses the table '{denied_table}', which you don't have access to."
+ },
+ code="permission_denied",
+ )
+
+ if "primary_dashboard" in attrs:
+ if not instance:
+ raise exceptions.ValidationError(
+ {"primary_dashboard": "Primary dashboard cannot be set on project creation."}
+ )
+ if attrs["primary_dashboard"] and attrs["primary_dashboard"].team_id != instance.id:
+ raise exceptions.ValidationError({"primary_dashboard": "Dashboard does not belong to this team."})
+
+ if "home_tab_dashboard" in attrs:
+ if not instance:
+ raise exceptions.ValidationError(
+ {"home_tab_dashboard": "Home tab dashboard cannot be set on project creation."}
+ )
+ if attrs["home_tab_dashboard"] and attrs["home_tab_dashboard"].team_id != instance.id:
+ raise exceptions.ValidationError({"home_tab_dashboard": "Dashboard does not belong to this team."})
+
+ if "autocapture_exceptions_errors_to_ignore" in attrs:
+ if not isinstance(attrs["autocapture_exceptions_errors_to_ignore"], list):
+ raise exceptions.ValidationError("Must provide a list for field: autocapture_exceptions_errors_to_ignore.")
+ for error in attrs["autocapture_exceptions_errors_to_ignore"]:
+ if not isinstance(error, str):
+ raise exceptions.ValidationError(
+ "Must provide a list of strings to field: autocapture_exceptions_errors_to_ignore."
+ )
+
+ if len(json.dumps(attrs["autocapture_exceptions_errors_to_ignore"])) > 300:
+ raise exceptions.ValidationError(
+ "Field autocapture_exceptions_errors_to_ignore must be less than 300 characters. Complex config should be provided in posthog-js initialization."
+ )
+ return attrs
+
+
+def validate_team_workflows_config(team: Team | None, value: dict[str, Any] | None) -> dict[str, Any] | None:
+ if value is None:
+ return None
+
+ serializer = team_config.TeamWorkflowsConfigSerializer(team.workflows_config if team else None, data=value)
+ if not serializer.is_valid():
+ raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))
+ return serializer.validated_data
diff --git a/posthog/api/team/team_config.py b/posthog/api/team/team_config.py
new file mode 100644
index 000000000000..6cdde97fbc7b
--- /dev/null
+++ b/posthog/api/team/team_config.py
@@ -0,0 +1,448 @@
+"""Core project settings serializers and field definitions."""
+
+from typing import Any
+
+from rest_framework import serializers
+
+from posthog.models import Team, TeamRevenueAnalyticsConfig
+from posthog.models.filters.utils import validate_group_type_index
+from posthog.models.integration.model import Integration
+
+from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.customer_analytics.backend.facade.account_property_pins import (
+ InvalidPinnedAccountProperties,
+ validate_pinned_account_properties,
+)
+from products.customer_analytics.backend.facade.contracts import PinnedAccountProperty
+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind
+from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig
+from products.tasks.backend.facade.workflow_tasks import (
+ MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY,
+ MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
+ WORKFLOW_TASK_RATE_CAP_PER_DAY,
+ WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
+)
+from products.workflows.backend.facade.enums import EMAIL_TRACKING_CONSENT_MODE_CHOICES
+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
+
+
+class CachingTeamSerializer(serializers.ModelSerializer):
+ """
+ This serializer is used for caching teams.
+ Currently used only in `/decide` endpoint.
+ Has all parameters needed for a successful decide request.
+ """
+
+ organization_id = serializers.UUIDField(read_only=True)
+
+ class Meta:
+ model = Team
+ fields = [
+ "id",
+ "project_id",
+ "organization_id",
+ "uuid",
+ "name",
+ "api_token",
+ "autocapture_opt_out",
+ "autocapture_exceptions_opt_in",
+ "autocapture_web_vitals_opt_in",
+ "autocapture_web_vitals_allowed_metrics",
+ "autocapture_exceptions_errors_to_ignore",
+ "capture_performance_opt_in",
+ "capture_console_log_opt_in",
+ "extra_settings",
+ "secret_api_token",
+ "secret_api_token_backup",
+ "session_recording_opt_in",
+ "session_recording_sample_rate",
+ "session_recording_minimum_duration_milliseconds",
+ "session_recording_linked_flag",
+ "session_recording_network_payload_capture_config",
+ "session_recording_masking_config",
+ "session_recording_url_trigger_config",
+ "session_recording_url_blocklist_config",
+ "session_recording_event_trigger_config",
+ "session_recording_trigger_match_type_config",
+ "session_replay_config",
+ "survey_config",
+ "recording_domains",
+ "inject_web_apps",
+ "surveys_opt_in",
+ "heatmaps_opt_in",
+ "capture_dead_clicks",
+ "flags_persistence_default",
+ "conversations_enabled",
+ "conversations_settings",
+ "logs_settings",
+ ]
+ read_only_fields = fields
+
+
+TEAM_CONFIG_FIELDS = (
+ "app_urls",
+ "anonymize_ips",
+ "completed_snippet_onboarding",
+ "test_account_filters",
+ "test_account_filters_default_checked",
+ "path_cleaning_filters",
+ "is_demo",
+ "timezone",
+ "data_attributes",
+ "person_display_name_properties",
+ "correlation_config",
+ "autocapture_opt_out",
+ "autocapture_exceptions_opt_in",
+ "autocapture_web_vitals_opt_in",
+ "autocapture_web_vitals_allowed_metrics",
+ "autocapture_exceptions_errors_to_ignore",
+ "capture_console_log_opt_in",
+ "logs_settings",
+ "capture_performance_opt_in",
+ "session_recording_opt_in",
+ "session_recording_sample_rate",
+ "session_recording_minimum_duration_milliseconds",
+ "session_recording_linked_flag",
+ "session_recording_network_payload_capture_config",
+ "session_recording_masking_config",
+ "session_recording_url_trigger_config",
+ "session_recording_url_blocklist_config",
+ "session_recording_event_trigger_config",
+ "session_recording_trigger_match_type_config",
+ "session_recording_trigger_groups",
+ "session_recording_retention_period",
+ "session_replay_config",
+ "survey_config",
+ "week_start_day",
+ "primary_dashboard",
+ "home_tab_dashboard",
+ "live_events_columns",
+ "recording_domains",
+ "cookieless_server_hash_mode",
+ "human_friendly_comparison_periods",
+ "inject_web_apps",
+ "extra_settings",
+ "modifiers",
+ "has_completed_onboarding_for",
+ "surveys_opt_in",
+ "heatmaps_opt_in",
+ "flags_persistence_default",
+ "feature_flag_confirmation_enabled",
+ "feature_flag_confirmation_message",
+ "default_evaluation_contexts_enabled",
+ "require_evaluation_contexts",
+ "feature_flag_policy_config",
+ "capture_dead_clicks",
+ "default_data_theme",
+ "revenue_analytics_config",
+ "marketing_analytics_config",
+ "customer_analytics_config",
+ "onboarding_tasks",
+ "base_currency",
+ "web_analytics_pre_aggregated_tables_enabled",
+ "receive_org_level_activity_logs",
+ "business_model",
+ "conversations_enabled",
+ "conversations_settings",
+ "proactive_tasks_enabled",
+ "workflows_config",
+)
+
+TEAM_CONFIG_FIELDS_SET = set(TEAM_CONFIG_FIELDS)
+
+TEAM_CONFIG_MEMBER_FIELDS = (
+ "completed_snippet_onboarding",
+ "has_completed_onboarding_for",
+ "onboarding_tasks",
+ "session_recording_opt_in",
+ "autocapture_exceptions_opt_in",
+ "autocapture_web_vitals_opt_in",
+ "autocapture_web_vitals_allowed_metrics",
+ "surveys_opt_in",
+ "primary_dashboard",
+ "home_tab_dashboard",
+)
+
+TEAM_CONFIG_MEMBER_FIELDS_SET = set(TEAM_CONFIG_MEMBER_FIELDS)
+
+TEAM_CONFIG_ADMIN_FIELDS_SET: set[str] = (TEAM_CONFIG_FIELDS_SET - TEAM_CONFIG_MEMBER_FIELDS_SET) | {
+ "is_demo",
+ "app_urls",
+ "access_control",
+ # Renaming a project/environment is admin-only (the settings UI gates TeamDisplayName behind
+ # useRestrictedArea(Admin)). Excluded from the create-time gate below so members allowed to
+ # create projects can still name them.
+ "name",
+}
+
+# Fields that are not member-safe but carry their own `field_access_control` (enforced in
+# UserAccessControlSerializerMixin.validate). The request-level scope can be downgraded for these so
+# the field-level check is the real authority — e.g. `app_urls` is governed by web_analytics:editor.
+TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS: set[str] = {"app_urls"}
+
+
+class TeamRevenueAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
+ events = serializers.JSONField(required=False)
+ filter_test_accounts = serializers.BooleanField(required=False)
+
+ class Meta:
+ model = TeamRevenueAnalyticsConfig
+ fields = ["base_currency", "events", "filter_test_accounts"]
+
+ def to_representation(self, instance):
+ repr = super().to_representation(instance)
+ if instance.events:
+ repr["events"] = [event.model_dump() for event in instance.events]
+ return repr
+
+ def to_internal_value(self, data):
+ internal_value = super().to_internal_value(data)
+ if "events" in internal_value:
+ internal_value["_events"] = internal_value["events"]
+ return internal_value
+
+
+class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
+ capture_workflows_engagement_events = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "When enabled, workflows engagement activity (email sends, opens, clicks, bounces, "
+ "spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) "
+ "alongside the existing workflow metrics."
+ ),
+ )
+ email_tracking_consent_mode = serializers.ChoiceField(
+ choices=EMAIL_TRACKING_CONSENT_MODE_CHOICES,
+ required=False,
+ help_text=(
+ "Recipient-consent enforcement for open/click tracking on marketing workflow emails. "
+ "'off': no enforcement, tracking follows each email step's own setting. "
+ "'opt_out': track by default but not recipients who have opted out. "
+ "'opt_in': only track recipients who have explicitly opted in. "
+ "Transactional emails are exempt from consent enforcement."
+ ),
+ )
+ workflow_task_rate_limit_per_day = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ help_text=(
+ "How many AI tasks one workflow can create in a rolling 24 hours. "
+ f"Null uses the default of {WORKFLOW_TASK_RATE_CAP_PER_DAY}; zero pauses task creation "
+ f"for every workflow in the project. Support raises the limit above "
+ f"{MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY}."
+ ),
+ )
+ workflow_task_team_rate_limit_per_day = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ help_text=(
+ "How many AI tasks all workflows in the project can create together in a rolling "
+ f"24 hours. Null uses the default of {WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY}; zero pauses "
+ f"task creation for the project. Support raises the limit above "
+ f"{MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY}."
+ ),
+ )
+ marketing_frequency_cap_max_messages = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=1000,
+ help_text=(
+ "Most marketing messages one person can get in the window, across all workflows. "
+ "Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off."
+ ),
+ )
+ marketing_frequency_cap_window_days = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=30,
+ help_text=(
+ "Length of the rolling frequency cap window in days. "
+ "Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off."
+ ),
+ )
+
+ default_email_integration_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "ID of the verified email integration that new broadcasts and workflow email steps use as "
+ "their sender. Null means no default. Set automatically when the project's first email "
+ "sender is verified, and cleared when that integration is deleted."
+ ),
+ )
+
+ class Meta:
+ model = TeamWorkflowsConfig
+ fields = [
+ "capture_workflows_engagement_events",
+ "email_tracking_consent_mode",
+ "workflow_task_rate_limit_per_day",
+ "workflow_task_team_rate_limit_per_day",
+ "default_email_integration_id",
+ "marketing_frequency_cap_max_messages",
+ "marketing_frequency_cap_window_days",
+ ]
+
+ def _enforce_self_serve_ceiling(self, field: str, value: int | None, ceiling: int) -> int | None:
+ # As a nested field there is no stored row to compare against; the parent serializer
+ # re-runs this serializer bound to the row in validate_workflows_config.
+ if self.parent:
+ return value
+ # Support raises a project past the ceiling in Django admin; clients that echo the whole
+ # config must be able to send that value back unchanged. Read the row fresh: the
+ # `Team.workflows_config` accessor is cached per process and can be stale.
+ if value is not None and value > ceiling:
+ stored = (
+ TeamWorkflowsConfig.objects.filter(pk=self.instance.pk).values_list(field, flat=True).first()
+ if self.instance is not None
+ else None
+ )
+ if stored != value:
+ raise serializers.ValidationError(f"Contact support to go above {ceiling} tasks a day.")
+ return value
+
+ def validate_workflow_task_rate_limit_per_day(self, value: int | None) -> int | None:
+ return self._enforce_self_serve_ceiling(
+ "workflow_task_rate_limit_per_day", value, MAX_SELF_SERVE_WORKFLOW_TASK_RATE_CAP_PER_DAY
+ )
+
+ def validate_workflow_task_team_rate_limit_per_day(self, value: int | None) -> int | None:
+ return self._enforce_self_serve_ceiling(
+ "workflow_task_team_rate_limit_per_day", value, MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY
+ )
+
+ def validate_default_email_integration_id(self, value: int | None) -> int | None:
+ if self.parent or value is None:
+ return value
+ sender = (
+ Integration.objects.filter(team_id=self.instance.team_id, kind="email", id=value).only("config").first()
+ if self.instance is not None
+ else None
+ )
+ if sender is None:
+ raise serializers.ValidationError("Choose an email sender from this project.")
+ if not sender.config.get("verified"):
+ raise serializers.ValidationError("Verify this sender's domain before making it the default.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # As a nested field of the team serializer there is no stored row to merge a partial update with.
+ # validate_team_workflows_config runs this serializer again with the row, and that run does the check.
+ if self.parent:
+ return attrs
+ cap_fields = ("marketing_frequency_cap_max_messages", "marketing_frequency_cap_window_days")
+ cap = {field: attrs[field] for field in cap_fields if field in attrs}
+ if len(cap) == 1 and self.instance is not None:
+ # Read the stored row, because `Team.workflows_config` is a cached_property on the Team instance
+ # and can hold values from before an earlier update.
+ stored = TeamWorkflowsConfig.objects.filter(pk=self.instance.pk).values(*cap_fields).first() or {}
+ cap = {**stored, **cap}
+ # The worker treats either null as no cap, so a half-set cap would save but never apply.
+ if cap:
+ missing = [field for field in cap_fields if cap.get(field) is None]
+ if len(missing) == 1:
+ other = next(field for field in cap_fields if field != missing[0])
+ raise serializers.ValidationError(
+ {missing[0]: f"Set this together with {other}, or set both to null to turn the frequency cap off."}
+ )
+ return attrs
+
+
+class TeamFeatureFlagPolicyConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
+ require_tags = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its "
+ "last one. A create that declares it comes from a survey, experiment, early access feature, "
+ "product tour, or web experiment is exempt, because those forms have no tag input. The caller "
+ "sets that declaration, so a flag can still be created without a tag."
+ ),
+ )
+
+ class Meta:
+ model = TeamFeatureFlagPolicyConfig
+ fields = ["require_tags"]
+
+
+class TeamCustomerAnalyticsPinnedAccountPropertySerializer(serializers.Serializer):
+ kind = serializers.ChoiceField(
+ choices=AccountPropertyPinKind.choices,
+ help_text="Definition type for this default pinned account property.",
+ )
+ id = serializers.UUIDField(help_text="Project-scoped custom property or relationship definition UUID.")
+
+ class Meta:
+ ref_name = "TeamCustomerAnalyticsPinnedAccountProperty"
+
+
+class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
+ activity_event = serializers.JSONField(required=False, help_text="Event used as the activity signal (DAU/WAU/MAU).")
+ signup_pageview_event = serializers.JSONField(
+ required=False, help_text="Event used to count signup pageviews on dashboards."
+ )
+ signup_event = serializers.JSONField(required=False, help_text="Event used to count signups on dashboards.")
+ subscription_event = serializers.JSONField(
+ required=False, help_text="Event used to count subscriptions on dashboards."
+ )
+ payment_event = serializers.JSONField(required=False, help_text="Event used to count payments on dashboards.")
+ account_group_type_index = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Index of the group type to treat as an Account in customer analytics. "
+ "Must reference an existing group type configured for the project."
+ ),
+ )
+ default_pinned_properties = TeamCustomerAnalyticsPinnedAccountPropertySerializer(
+ many=True,
+ allow_empty=True,
+ required=False,
+ help_text=(
+ "Ordered account properties shown until a user saves a personal pinned-property selection. "
+ "Pass an empty list to show no properties by default."
+ ),
+ )
+
+ class Meta:
+ model = TeamCustomerAnalyticsConfig
+ fields = [
+ "activity_event",
+ "signup_pageview_event",
+ "signup_event",
+ "subscription_event",
+ "payment_event",
+ "account_group_type_index",
+ "default_pinned_properties",
+ ]
+
+ def update(
+ self, instance: TeamCustomerAnalyticsConfig, validated_data: dict[str, Any]
+ ) -> TeamCustomerAnalyticsConfig:
+ for attr, value in validated_data.items():
+ setattr(instance, attr, value)
+ # The account track rules on this row are written by their own path, so a settings save must
+ # not carry a stale copy of them back to the database.
+ instance.save(update_fields=list(validated_data))
+ return instance
+
+ @staticmethod
+ def validate_account_group_type_index(value):
+ return validate_group_type_index("account_group_type_index", value)
+
+ def validate_default_pinned_properties(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ if self.instance is None:
+ return value
+ pinned_properties = [PinnedAccountProperty(kind=reference["kind"], id=reference["id"]) for reference in value]
+ try:
+ validate_pinned_account_properties(
+ team_id=self.instance.team_id,
+ pinned_properties=pinned_properties,
+ )
+ except InvalidPinnedAccountProperties as error:
+ raise serializers.ValidationError(error.errors)
+ return [{"kind": reference["kind"], "id": str(reference["id"])} for reference in value]
diff --git a/posthog/api/team/team_permissions.py b/posthog/api/team/team_permissions.py
new file mode 100644
index 000000000000..eed32b187c97
--- /dev/null
+++ b/posthog/api/team/team_permissions.py
@@ -0,0 +1,36 @@
+"""Permissions for project settings routes."""
+
+from rest_framework import exceptions, request
+from rest_framework.permissions import BasePermission
+
+from posthog.permissions import CREATE_ACTIONS
+
+
+class PremiumMultiEnvironmentPermission(BasePermission):
+ """Enforce one non-demo team per project limit."""
+
+ message = "You have reached the maximum limit of allowed environments for your current plan. Upgrade your plan to be able to create and manage more environments."
+
+ def has_permission(self, request: request.Request, view) -> bool:
+ if view.action not in CREATE_ACTIONS:
+ return True
+
+ try:
+ project = view.project
+ except KeyError: # KeyError occurs when "project_id" is not in parents_query_dict
+ raise exceptions.ValidationError(
+ "Environments must be created under a specific project. Send the POST request to /api/projects/<project_id>/environments/ instead."
+ )
+
+ if request.data.get("is_demo"):
+ # Allow one demo team per organization
+ if project.organization.teams.filter(is_demo=True).exists():
+ return False
+ return True
+
+ # Only allow one non-demo team per project
+ current_non_demo_team_count = project.teams.exclude(is_demo=True).count()
+ if current_non_demo_team_count >= 1:
+ return False
+
+ return True
diff --git a/posthog/api/team/team_serializer.py b/posthog/api/team/team_serializer.py
new file mode 100644
index 000000000000..3c62e669ebe1
--- /dev/null
+++ b/posthog/api/team/team_serializer.py
@@ -0,0 +1,1328 @@
+"""The main serializer for project settings."""
+
+import re
+from typing import Any, Literal, cast
+
+from django.conf import settings
+from django.utils import timezone
+
+from drf_spectacular.utils import extend_schema_field
+from opentelemetry import trace
+from rest_framework import exceptions, serializers
+
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.api.utils import validate_authorized_url_wildcards
+from posthog.constants import AvailableFeature
+from posthog.geoip import get_geoip_properties
+from posthog.helpers.impersonation import is_impersonated
+from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import Detail, dict_changes_between, log_activity
+from posthog.models.group_type_mapping import cached_group_types_for_team
+from posthog.models.organization import OrganizationMembership
+from posthog.models.product_intent.product_intent import (
+ cached_product_intents_for_team,
+ enqueue_product_activation_calc_debounced,
+)
+from posthog.models.team.logs_retention import (
+ LOGS_RETENTION_BASE_TIERS_DAYS,
+ logs_retention_days_error,
+ required_logs_retention_feature,
+ retention_update_throttle_error,
+)
+from posthog.models.team.setup_tasks import SetupTaskId
+from posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCY
+from posthog.models.team.team_caching import set_team_in_cache
+from posthog.models.utils import UUIDT
+from posthog.session_recordings.data_retention import (
+ VALID_RETENTION_PERIODS,
+ parse_feature_to_entitlement,
+ retention_violates_entitlement,
+ validate_retention_period,
+)
+from posthog.user_permissions import UserPermissionsSerializerMixin
+from posthog.utils import get_instance_region, get_ip_address, get_week_start_for_country_code
+
+from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.dashboards.backend.models import Dashboard
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_mode
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
+ MAX_CUSTOM_BOT_DEFINITIONS,
+ assert_patterns_compile as assert_custom_bot_patterns_compile,
+ compiled_patterns as compiled_custom_bot_patterns,
+ parse_rules as parse_custom_bot_rules,
+ validate_rule as validate_custom_bot_rule,
+ validate_rule_set as validate_custom_bot_rule_set,
+)
+
+from . import conversations_settings, live_events, marketing_config, settings_validation, team_config
+
+tracer = trace.get_tracer(__name__)
+
+
+def merge_modifiers(requested: dict | None, existing: object) -> dict | None:
+ # Django admin can store a scalar or list here. Treat it as empty rather than raising.
+ stored = existing if isinstance(existing, dict) else {}
+ if requested is not None:
+ return {**stored, **requested}
+ # PostHog staff set useNewEventsSchema per project, so a client that clears its modifiers keeps it.
+ if "useNewEventsSchema" in stored:
+ return {"useNewEventsSchema": stored["useNewEventsSchema"]}
+ return None
+
+
+class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):
+ instance: Team | None
+ _group_types_cache: list[dict[str, Any]] | None = None
+
+ effective_membership_level = serializers.SerializerMethodField()
+ has_group_types = serializers.SerializerMethodField()
+ group_types = serializers.SerializerMethodField()
+ live_events_token = serializers.SerializerMethodField()
+ product_intents = serializers.SerializerMethodField()
+ managed_viewsets = serializers.SerializerMethodField()
+ flag_evaluations_mode = serializers.SerializerMethodField(
+ help_text=(
+ "Which table this project's feature flag usage data is read from. PostHog sets it for the "
+ "whole organization. 0 reads the events table. 1 and 2 read the flag_evaluations table."
+ )
+ )
+ available_setup_task_ids = serializers.SerializerMethodField()
+ heatmaps_screenshot_secret = serializers.SerializerMethodField(
+ help_text=(
+ "Value this project's heatmap screenshots send as a cookie scoped to your domain, "
+ "so bot protection can allow them. Only project admins can read it; null for "
+ "everyone else and when none has been generated."
+ ),
+ )
+ revenue_analytics_config = team_config.TeamRevenueAnalyticsConfigSerializer(required=False)
+ marketing_analytics_config = marketing_config.TeamMarketingAnalyticsConfigSerializer(required=False)
+ customer_analytics_config = team_config.TeamCustomerAnalyticsConfigSerializer(required=False)
+ workflows_config = team_config.TeamWorkflowsConfigSerializer(required=False)
+ feature_flag_policy_config = team_config.TeamFeatureFlagPolicyConfigSerializer(required=False)
+ base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, default=DEFAULT_CURRENCY)
+ conversations_settings = conversations_settings.ConversationsSettingsField(
+ required=False,
+ allow_null=True,
+ help_text="Settings for Conversations. Must be a JSON object or null.",
+ )
+ home_tab_dashboard = TeamScopedPrimaryKeyRelatedField(
+ queryset=Dashboard.objects.all(),
+ required=False,
+ allow_null=True,
+ error_messages={"does_not_exist": "Dashboard does not belong to this team."},
+ help_text=(
+ "ID of the dashboard shown on the product analytics Home tab. Null shows the built-in generic view."
+ ),
+ )
+
+ class Meta:
+ model = Team
+ fields = (
+ "id",
+ "uuid",
+ "name",
+ "access_control",
+ "organization",
+ "project_id",
+ "api_token",
+ "secret_api_token",
+ "secret_api_token_backup",
+ "created_at",
+ "updated_at",
+ "ingested_event",
+ "default_modifiers",
+ "person_on_events_querying_enabled",
+ "user_access_level",
+ "heatmaps_screenshot_secret",
+ # Config fields
+ *team_config.TEAM_CONFIG_FIELDS,
+ # Computed fields
+ "effective_membership_level",
+ "has_group_types",
+ "group_types",
+ "live_events_token",
+ "product_intents",
+ "managed_viewsets",
+ "flag_evaluations_mode",
+ "available_setup_task_ids",
+ )
+
+ read_only_fields = (
+ "id",
+ "uuid",
+ "organization",
+ "project_id",
+ "api_token",
+ "secret_api_token",
+ "secret_api_token_backup",
+ "created_at",
+ "updated_at",
+ "ingested_event",
+ "effective_membership_level",
+ "has_group_types",
+ "group_types",
+ "default_modifiers",
+ "person_on_events_querying_enabled",
+ "live_events_token",
+ "user_access_level",
+ "product_intents",
+ "managed_viewsets",
+ "flag_evaluations_mode",
+ "available_setup_task_ids",
+ )
+
+ def get_fields(self) -> dict[str, serializers.Field]:
+ if isinstance(self.instance, Team):
+ self.context["team_id"] = self.instance.pk
+ return super().get_fields()
+
+ def to_representation(self, instance):
+ with tracer.start_as_current_span("team_serializer.default_fields"):
+ representation = super().to_representation(instance)
+ # fallback to the default posthog data theme id, if the color feature isn't available e.g. after a downgrade
+ if not instance.organization.is_feature_available(AvailableFeature.DATA_COLOR_THEMES):
+ with tracer.start_as_current_span("team_serializer.default_data_theme_fallback"):
+ representation["default_data_theme"] = live_events._default_data_color_theme_id()
+
+ return representation
+
+ @tracer.start_as_current_span("team_serializer.effective_membership_level")
+ def get_effective_membership_level(self, team: Team) -> OrganizationMembership.Level | None:
+ # TODO: Map from user_access_controls
+ return self.user_permissions.team(team).effective_membership_level
+
+ @tracer.start_as_current_span("team_serializer.has_group_types")
+ def get_has_group_types(self, team: Team) -> bool:
+ return bool(self._get_group_types(team))
+
+ @tracer.start_as_current_span("team_serializer.group_types")
+ def get_group_types(self, team: Team) -> list[dict[str, Any]]:
+ return self._get_group_types(team)
+
+ def _get_group_types(self, team: Team) -> list[dict[str, Any]]:
+ group_types = self._group_types_cache
+ if group_types is None:
+ group_types = cached_group_types_for_team(team)
+ self._group_types_cache = group_types
+ return group_types
+
+ @tracer.start_as_current_span("team_serializer.live_events_token")
+ def get_live_events_token(self, team: Team) -> str | None:
+ return live_events.live_events_token_for_request(team, self.context.get("request"))
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_heatmaps_screenshot_secret(self, team: Team) -> str | None:
+ return settings_validation.heatmaps_screenshot_secret_for_reader(team, self.user_permissions)
+
+ @extend_schema_field(serializers.ListField(child=serializers.DictField()))
+ @tracer.start_as_current_span("team_serializer.product_intents")
+ def get_product_intents(self, obj):
+ # Debounce-then-enqueue rather than .delay() on every render. The helper
+ # checks a cache key first and skips the broker round-trip entirely if
+ # we've already enqueued for this team in the last 24h. 99% of renders
+ # become a cache hit; the remaining ones still enqueue exactly as before.
+ enqueue_product_activation_calc_debounced(obj.id)
+ return cached_product_intents_for_team(obj.id)
+
+ @extend_schema_field(serializers.DictField(child=serializers.BooleanField()))
+ @tracer.start_as_current_span("team_serializer.managed_viewsets")
+ def get_managed_viewsets(self, obj):
+ from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
+ from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind
+
+ enabled_viewsets = DataWarehouseManagedViewSet.objects.filter(team=obj).values_list("kind", flat=True)
+ enabled_set = set(enabled_viewsets)
+
+ return {kind: (kind in enabled_set) for kind, _ in DataWarehouseManagedViewSetKind.choices}
+
+ @extend_schema_field(serializers.ChoiceField(choices=FlagEvaluationsMode.choices))
+ def get_flag_evaluations_mode(self, obj: Team) -> int:
+ return get_flag_evaluations_read_mode(obj.organization_id)
+
+ @extend_schema_field(
+ # nosemgrep: choices-need-a-class -- an existing list, moved here unchanged from posthog/api/team.py
+ serializers.ListField(child=serializers.ChoiceField(choices=[(e.value, e.value) for e in SetupTaskId]))
+ )
+ def get_available_setup_task_ids(self, obj) -> list[str]:
+ return [e.value for e in SetupTaskId]
+
+ @staticmethod
+ def validate_test_account_filters(value: object) -> list[dict[str, object]]:
+ return settings_validation.validate_test_account_filters(value)
+
+ @staticmethod
+ def validate_path_cleaning_filters(value: object) -> object:
+ return settings_validation.validate_path_cleaning_filters(value)
+
+ @staticmethod
+ def validate_revenue_analytics_config(value):
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ serializer = team_config.TeamRevenueAnalyticsConfigSerializer(data=value)
+ if not serializer.is_valid():
+ raise exceptions.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+
+ return serializer.validated_data
+
+ @staticmethod
+ def validate_marketing_analytics_config(value):
+ if value is None:
+ return None
+
+ serializer = marketing_config.TeamMarketingAnalyticsConfigSerializer(data=value)
+ if not serializer.is_valid():
+ raise exceptions.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+ return serializer.validated_data
+
+ @staticmethod
+ def validate_customer_analytics_config(value):
+ if value is None:
+ return None
+
+ serializer = team_config.TeamCustomerAnalyticsConfigSerializer(data=value)
+ if not serializer.is_valid():
+ raise exceptions.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+ return serializer.validated_data
+
+ def validate_workflows_config(self, value):
+ return settings_validation.validate_team_workflows_config(self.instance, value)
+
+ @staticmethod
+ def validate_feature_flag_policy_config(value):
+ if value is None:
+ return None
+
+ serializer = team_config.TeamFeatureFlagPolicyConfigSerializer(data=value)
+ if not serializer.is_valid():
+ raise exceptions.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+ return serializer.validated_data
+
+ @staticmethod
+ def validate_session_recording_linked_flag(value) -> dict | None:
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+ received_keys = value.keys()
+ valid_keys = [
+ {"id", "key"},
+ {"id", "key", "variant"},
+ ]
+ if received_keys not in valid_keys:
+ raise exceptions.ValidationError(
+ "Must provide a dictionary with only 'id' and 'key' keys. _or_ only 'id', 'key', and 'variant' keys."
+ )
+
+ # jsonb containment (`__contains={"id": <int>}`) is type-sensitive, so a non-integer id
+ # makes the flag-delete guard miss this row and delete a flag the team still advertises.
+ # A numeric string is normalized instead of rejected, so a client sending "123" stores a
+ # usable row rather than a broken one. Bools and floats are excluded because
+ # isinstance(True, int) is True, and int(12.5) would silently link flag 12.
+ flag_id = value["id"]
+ if isinstance(flag_id, bool) or not isinstance(flag_id, int | str):
+ raise exceptions.ValidationError("Must provide an integer 'id'.")
+ try:
+ return {**value, "id": int(flag_id)}
+ except ValueError:
+ raise exceptions.ValidationError("Must provide an integer 'id'.")
+
+ @staticmethod
+ def validate_session_recording_trigger_match_type_config(value) -> Literal["all", "any"] | None:
+ if value not in ["all", "any", None]:
+ raise exceptions.ValidationError(
+ "Must provide a valid trigger match type. Only 'all' or 'any' or None are allowed."
+ )
+
+ return value
+
+ @staticmethod
+ def validate_session_recording_trigger_groups(value) -> dict | None:
+ """
+ Validate V2 trigger groups configuration.
+
+ Expected schema:
+ {
+ "version": 2,
+ "groups": [
+ {
+ "id": "string",
+ "name": "string" (optional),
+ "sampleRate": 0.0-1.0,
+ "minDurationMs": 0-30000 (optional),
+ "conditions": {
+ "matchType": "any" | "all",
+ "events": ["event1", ...] (optional),
+ "urls": [{"url": "regex", "matching": "regex"}] (optional),
+ "flag": "flag-key" | {"id": 1, "key": "flag-key", "variant": "test"} (optional, single flag)
+ }
+ }
+ ]
+ }
+ """
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ # Validate version
+ if "version" not in value:
+ raise exceptions.ValidationError("Missing required field: 'version'.")
+
+ if value["version"] != 2:
+ raise exceptions.ValidationError(f"Invalid version: {value['version']}. Only version 2 is supported.")
+
+ # Validate groups array
+ if "groups" not in value:
+ raise exceptions.ValidationError("Missing required field: 'groups'.")
+
+ if not isinstance(value["groups"], list):
+ raise exceptions.ValidationError("Field 'groups' must be an array.")
+
+ # Validate each group
+ for idx, group in enumerate(value["groups"]):
+ # Inline validation of each trigger group
+ if not isinstance(group, dict):
+ raise exceptions.ValidationError(f"Group {idx}: must be a dictionary.")
+
+ # Required fields
+ required_fields = ["id", "sampleRate", "conditions"]
+ for field in required_fields:
+ if field not in group:
+ raise exceptions.ValidationError(f"Group {idx}: missing required field '{field}'.")
+
+ # Validate sampleRate
+ rate = group["sampleRate"]
+ if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not (0 <= rate <= 1):
+ raise exceptions.ValidationError(
+ f"Group {idx}: invalid sampleRate '{rate}'. Must be a number between 0 and 1."
+ )
+
+ # Validate minDurationMs if present
+ if "minDurationMs" in group:
+ min_duration = group["minDurationMs"]
+ if isinstance(min_duration, bool) or not isinstance(min_duration, int):
+ raise exceptions.ValidationError(
+ f"Group {idx}: 'minDurationMs' must be an integer, got {type(min_duration).__name__}."
+ )
+ if min_duration < 0 or min_duration > 30000:
+ raise exceptions.ValidationError(
+ f"Group {idx}: 'minDurationMs' must be between 0 and 30000 (30 seconds). Got: {min_duration}."
+ )
+
+ # Validate conditions
+ conditions = group["conditions"]
+ if not isinstance(conditions, dict):
+ raise exceptions.ValidationError(f"Group {idx}: field 'conditions' must be a dictionary.")
+
+ # Validate matchType
+ if "matchType" in conditions:
+ if conditions["matchType"] not in ["any", "all"]:
+ raise exceptions.ValidationError(
+ f"Group {idx}: invalid matchType '{conditions['matchType']}'. Must be 'any' or 'all'."
+ )
+
+ # Validate events array if present
+ if "events" in conditions:
+ if not isinstance(conditions["events"], list):
+ raise exceptions.ValidationError(f"Group {idx}: field 'events' must be an array.")
+ for event_idx, event in enumerate(conditions["events"]):
+ if isinstance(event, str):
+ pass # Simple event name is valid
+ elif isinstance(event, dict):
+ if "name" not in event or not isinstance(event["name"], str):
+ raise exceptions.ValidationError(
+ f"Group {idx}: event {event_idx} object must have a string 'name' field."
+ )
+ if "properties" in event:
+ settings_validation._validate_trigger_property_filters(
+ event["properties"], f"Group {idx}, event '{event['name']}'"
+ )
+ else:
+ raise exceptions.ValidationError(
+ f"Group {idx}: event {event_idx} must be a string or object with 'name'."
+ )
+
+ # Validate URLs array if present
+ if "urls" in conditions:
+ if not isinstance(conditions["urls"], list):
+ raise exceptions.ValidationError(f"Group {idx}: field 'urls' must be an array.")
+ for url_config in conditions["urls"]:
+ if not isinstance(url_config, dict):
+ raise exceptions.ValidationError(f"Group {idx}: URL config must be a dictionary.")
+ if "url" not in url_config or "matching" not in url_config:
+ raise exceptions.ValidationError(
+ f"Group {idx}: URL config must have 'url' and 'matching' fields."
+ )
+ if url_config["matching"] != "regex":
+ raise exceptions.ValidationError(
+ f"Group {idx}: URL matching must be 'regex'. Got: '{url_config['matching']}'."
+ )
+ # Validate regex pattern
+ try:
+ re.compile(url_config["url"])
+ except re.error:
+ raise exceptions.ValidationError(
+ f"Group {idx}: invalid regex pattern in URL: '{url_config['url']}'."
+ )
+
+ # Validate flag (single) if present
+ if "flag" in conditions:
+ flag_config = conditions["flag"]
+ if isinstance(flag_config, str):
+ pass # Simple flag key is valid
+ elif isinstance(flag_config, dict):
+ # LinkedFeatureFlag object with id, key, and optional variant
+ if "key" not in flag_config:
+ raise exceptions.ValidationError(f"Group {idx}: flag object must have 'key' field.")
+ if not isinstance(flag_config["key"], str):
+ raise exceptions.ValidationError(f"Group {idx}: flag 'key' must be a string.")
+ # id and variant are optional
+ elif flag_config is not None:
+ raise exceptions.ValidationError(
+ f"Group {idx}: 'flag' must be a string (flag key), object (LinkedFeatureFlag), or null."
+ )
+
+ # Validate group-level property filters (shared WHERE clause for all triggers in group)
+ if "properties" in conditions:
+ settings_validation._validate_trigger_property_filters(conditions["properties"], f"Group {idx}")
+
+ # Note: All matching groups are evaluated independently
+ # If any group's sample rate hits, the session is recorded (union behavior)
+
+ # Validate fallback sample rate if present
+ if "fallbackSampleRate" in value:
+ rate = value["fallbackSampleRate"]
+ if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not (0 <= rate <= 1):
+ raise exceptions.ValidationError(
+ f"Invalid fallbackSampleRate: {rate}. Must be a number between 0 and 1."
+ )
+
+ return value
+
+ @staticmethod
+ def validate_session_recording_retention_period(value) -> Literal["30d", "90d", "1y", "5y"] | None:
+ if not validate_retention_period(value):
+ raise exceptions.ValidationError(
+ f"Must provide a valid retention period. Options are: {VALID_RETENTION_PERIODS}."
+ )
+
+ return value
+
+ @staticmethod
+ def validate_session_recording_network_payload_capture_config(value) -> dict | None:
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ if not all(key in ["recordHeaders", "recordBody"] for key in value.keys()):
+ raise exceptions.ValidationError(
+ "Must provide a dictionary with only 'recordHeaders' and/or 'recordBody' keys."
+ )
+
+ return value
+
+ @staticmethod
+ def validate_session_recording_masking_config(value) -> dict | None:
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ allowed_keys = {"maskAllInputs", "maskTextSelector", "blockSelector"}
+
+ if not all(key in allowed_keys for key in value.keys()):
+ raise exceptions.ValidationError(
+ f"Must provide a dictionary with only known keys: {', '.join(allowed_keys)}."
+ )
+
+ if "maskAllInputs" in value:
+ if not isinstance(value["maskAllInputs"], bool):
+ raise exceptions.ValidationError("maskAllInputs must be a boolean.")
+
+ if "maskTextSelector" in value:
+ if not isinstance(value["maskTextSelector"], str):
+ raise exceptions.ValidationError("maskTextSelector must be a string.")
+
+ if "blockSelector" in value:
+ if not isinstance(value["blockSelector"], str):
+ raise exceptions.ValidationError("blockSelector must be a string.")
+
+ return value
+
+ @staticmethod
+ def validate_session_replay_config(value) -> dict | None:
+ if value is None:
+ return None
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ known_keys = ["record_canvas", "ai_config"]
+ if not all(key in known_keys for key in value.keys()):
+ raise exceptions.ValidationError(
+ f"Must provide a dictionary with only known keys. One or more of {', '.join(known_keys)}."
+ )
+
+ if "ai_config" in value:
+ TeamSerializer.validate_session_replay_ai_summary_config(value["ai_config"])
+
+ return value
+
+ @staticmethod
+ def validate_session_replay_ai_summary_config(value: dict | None) -> dict | None:
+ if value is not None:
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ allowed_keys = [
+ "included_event_properties",
+ "opt_in",
+ "preferred_events",
+ "excluded_events",
+ "important_user_properties",
+ ]
+ if not all(key in allowed_keys for key in value.keys()):
+ raise exceptions.ValidationError(
+ f"Must provide a dictionary with only allowed keys: {', '.join(allowed_keys)}."
+ )
+
+ return value
+
+ def validate_access_control(self, value) -> None:
+ """Validate that access_control field is not being used as it's deprecated."""
+ if value is not None:
+ import posthoganalytics
+
+ request = self.context.get("request")
+ user = request.user if request else None
+
+ posthoganalytics.capture_exception(
+ Exception("Deprecated access control field used"),
+ properties={
+ "field": "access_control",
+ "value": str(value),
+ "user_id": user.id if user else None,
+ "team_id": getattr(user, "team_id", None) if user else None,
+ },
+ )
+
+ raise exceptions.ValidationError(
+ "The 'access_control' field has been deprecated and is no longer supported. "
+ "Please use the new access control system instead. "
+ "For more information, visit: https://posthog.com/docs/settings/access-control"
+ )
+ return None
+
+ def validate_app_urls(self, value: list[str | None] | None) -> list[str] | None:
+ if value is None:
+ return value
+ urls = [url for url in value if url]
+ validate_authorized_url_wildcards(urls)
+ return urls
+
+ def validate_recording_domains(self, value: list[str | None] | None) -> list[str] | None:
+ if value is None:
+ return value
+ return [domain for domain in value if domain]
+
+ def validate_conversations_settings(self, value: dict | None) -> dict | None:
+ if value is None:
+ return value
+ conversations_settings.strip_managed_conversations_settings(value)
+ # Filter out None values from widget_domains if present
+ if "widget_domains" in value and value["widget_domains"] is not None:
+ value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
+ validate_authorized_url_wildcards(value["widget_domains"])
+ # Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50
+ if "slack_channel_ids" in value:
+ raw = value.get("slack_channel_ids")
+ if isinstance(raw, list):
+ cleaned: list[str] = []
+ seen: set[str] = set()
+ for item in raw:
+ if isinstance(item, str) and item and item not in seen:
+ seen.add(item)
+ cleaned.append(item)
+ value["slack_channel_ids"] = cleaned[:50]
+ else:
+ value.pop("slack_channel_ids", None)
+ icon_url = value.get("slack_bot_icon_url")
+ if icon_url is not None:
+ if not isinstance(icon_url, str):
+ raise serializers.ValidationError({"slack_bot_icon_url": "Must be a string."})
+ icon_url = icon_url.strip()
+ value["slack_bot_icon_url"] = icon_url or None
+ if icon_url and not icon_url.startswith("https://"):
+ raise serializers.ValidationError({"slack_bot_icon_url": "Must be an HTTPS URL."})
+ display_name = value.get("slack_bot_display_name")
+ if display_name is not None:
+ if not isinstance(display_name, str):
+ raise serializers.ValidationError({"slack_bot_display_name": "Must be a string."})
+ display_name = display_name.strip()
+ value["slack_bot_display_name"] = display_name or None
+ if display_name and (len(display_name) > 200 or any(ord(c) < 32 for c in display_name)):
+ raise serializers.ValidationError(
+ {"slack_bot_display_name": "Must be 200 characters or fewer with no control characters."}
+ )
+ for toggle_key in ("slack_notify_on_join", "slack_notify_on_leave", "slack_nudge_enabled"):
+ if toggle_key in value:
+ value[toggle_key] = bool(value[toggle_key])
+ if "slack_alert_channel_id" in value:
+ alert_channel = value.get("slack_alert_channel_id")
+ if alert_channel is None:
+ value["slack_alert_channel_id"] = None
+ elif isinstance(alert_channel, str):
+ value["slack_alert_channel_id"] = alert_channel.strip() or None
+ else:
+ raise serializers.ValidationError({"slack_alert_channel_id": "Must be a string."})
+ # AI resolution channels: list of valid channel strings or null
+ VALID_CHANNELS = {"widget", "email", "slack", "teams", "github"}
+ if "ai_resolution_channels" in value:
+ channels = value.get("ai_resolution_channels")
+ if channels is None:
+ pass
+ elif isinstance(channels, list):
+ invalid = [c for c in channels if not isinstance(c, str) or c not in VALID_CHANNELS]
+ if invalid:
+ raise serializers.ValidationError(
+ {
+ "ai_resolution_channels": f"Invalid channel(s): {', '.join(str(c) for c in invalid)}. "
+ f"Valid options: {', '.join(sorted(VALID_CHANNELS))}."
+ }
+ )
+ value["ai_resolution_channels"] = channels
+ else:
+ raise serializers.ValidationError(
+ {"ai_resolution_channels": "Must be a list of channel names or null."}
+ )
+ # AI reply modes: { channel: { ticket_type: mode } } or null
+ VALID_REPLY_MODES = {"private_note", "bot_reply"}
+ VALID_TICKET_TYPES = {"how_to", "diagnostic", "account_billing"}
+ # Only how_to replies may be published to the ticket author. diagnostic/account_billing
+ # draw on project data (events, persons, recordings, logs) and must stay private notes —
+ # there's no per-author authorization that the customer is entitled to that data.
+ BOT_REPLY_TICKET_TYPES = {"how_to"}
+ if "ai_reply_modes" in value:
+ modes = value.get("ai_reply_modes")
+ if modes is None:
+ pass
+ elif isinstance(modes, dict):
+ cleaned_modes: dict[str, dict[str, str]] = {}
+ for ch, type_map in modes.items():
+ if ch not in VALID_CHANNELS or not isinstance(type_map, dict):
+ continue
+ cleaned_map: dict[str, str] = {}
+ for tt, mode in type_map.items():
+ if tt not in VALID_TICKET_TYPES or mode not in VALID_REPLY_MODES:
+ continue
+ # Demote bot_reply to private_note for ticket types that may never be
+ # published (diagnostic/account_billing). Coerce rather than reject so a
+ # stale value doesn't block unrelated settings saves.
+ if mode == "bot_reply" and tt not in BOT_REPLY_TICKET_TYPES:
+ mode = "private_note"
+ cleaned_map[tt] = mode
+ if cleaned_map:
+ cleaned_modes[ch] = cleaned_map
+ value["ai_reply_modes"] = cleaned_modes
+ else:
+ raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
+ from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
+ from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
+
+ existing = getattr(self.instance, "conversations_settings", None) if self.instance is not None else None
+ validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
+ validate_ai_context_conversations_settings(
+ value, team_id=self.instance.id if self.instance is not None else None
+ )
+ return value
+
+ def validate_receive_org_level_activity_logs(self, value: bool | None) -> bool | None:
+ if value is None:
+ return value
+
+ request = self.context.get("request")
+ if not request:
+ return value
+
+ user = request.user
+
+ if self.instance:
+ try:
+ membership = OrganizationMembership.objects.get(user=user, organization=self.instance.organization)
+ if membership.level < OrganizationMembership.Level.ADMIN:
+ raise exceptions.PermissionDenied(
+ "Only organization owners and admins can modify the receive_org_level_activity_logs setting."
+ )
+ except OrganizationMembership.DoesNotExist:
+ raise exceptions.PermissionDenied("You must be a member of this organization.")
+
+ return value
+
+ def validate_logs_settings(self, value: dict | None) -> dict | None:
+ if value is None:
+ return value
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("logs_settings must be an object or null.")
+
+ if "json_parse_logs_attribute_key" in value:
+ attribute_key = value["json_parse_logs_attribute_key"]
+ # Length is measured after trimming, matching CharField(trim_whitespace=True,
+ # max_length=200) on the logs_config key lists.
+ if not isinstance(attribute_key, str) or len(attribute_key.strip()) > 200:
+ raise exceptions.ValidationError(
+ "json_parse_logs_attribute_key must be a string of at most 200 characters. "
+ "Use an empty string to disable parsing."
+ )
+ value["json_parse_logs_attribute_key"] = attribute_key.strip()
+
+ team = (
+ self.instance.passthrough_team
+ if self.instance is not None and hasattr(self.instance, "passthrough_team")
+ else self.instance
+ )
+
+ logs_settings = team.logs_settings if team is not None else None
+ old_retention = logs_settings.get("retention_days") if logs_settings else None
+
+ new_retention = value.get("retention_days")
+ if new_retention is not None and (isinstance(new_retention, bool) or not isinstance(new_retention, int)):
+ raise exceptions.ValidationError("retention_days must be an integer")
+
+ # Only a changed period is checked against the flag and the entitlement. Unrelated settings
+ # updates send the stored period back, and must not fail when the flag is turned off later.
+ if new_retention is not None and old_retention != new_retention:
+ # Only evaluate the flag for values outside the base tiers, so the common path makes no flag call.
+ custom_enabled = new_retention not in LOGS_RETENTION_BASE_TIERS_DAYS and (
+ settings_validation._custom_logs_retention_enabled(self, team)
+ )
+ error = logs_retention_days_error(new_retention, custom_retention_enabled=custom_enabled)
+ if error:
+ raise exceptions.ValidationError(error)
+
+ required_feature = required_logs_retention_feature(new_retention)
+ if required_feature:
+ organization = settings_validation._get_organization_for_logs_settings_check(self)
+ if organization is None or not organization.is_feature_available(required_feature):
+ raise exceptions.PermissionDenied(
+ f"This organization does not have permission to set Logs retention to {new_retention} days."
+ )
+
+ # Only validate retention throttling if we have an existing retention setting
+ if self.instance and logs_settings:
+ old_last_updated = logs_settings.get("retention_last_updated")
+
+ # Check if retention_days is being changed
+ if new_retention is not None and old_retention != new_retention:
+ value["retention_last_updated"] = timezone.now().isoformat()
+ throttle_error = retention_update_throttle_error(old_last_updated)
+ if throttle_error:
+ raise exceptions.ValidationError(throttle_error)
+
+ return value
+
+ @staticmethod
+ def validate_modifiers(value: dict | None) -> dict | None:
+ if value is None:
+ return value
+
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("Must provide a dictionary or None.")
+
+ # The native JSON events table is an internal rollout switch that PostHog staff set per project in Django
+ # admin. Dropping the key keeps a client from setting or clearing it, including a settings page that echoes
+ # the whole modifiers dict back.
+ value = {key: item for key, item in value.items() if key != "useNewEventsSchema"}
+
+ if "bounceRateDurationSeconds" in value:
+ bounce_rate = value["bounceRateDurationSeconds"]
+ if bounce_rate is not None:
+ if not isinstance(bounce_rate, (int, float)):
+ raise exceptions.ValidationError({"bounceRateDurationSeconds": "Must be a number."})
+ if bounce_rate < 1 or bounce_rate > 120:
+ raise exceptions.ValidationError(
+ {"bounceRateDurationSeconds": "Must be between 1 and 120 seconds."}
+ )
+
+ if "customBotDefinitions" in value and isinstance(value["customBotDefinitions"], list):
+ # Cap before parsing, so an oversized list is rejected without instantiating a model
+ # per entry.
+ if len(value["customBotDefinitions"]) > MAX_CUSTOM_BOT_DEFINITIONS:
+ raise exceptions.ValidationError(
+ {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}
+ )
+ # Strict, so a malformed rule is rejected with a specific error rather than the
+ # generic "Invalid modifier key.", and the stored list is normalized.
+ try:
+ parsed = parse_custom_bot_rules(value["customBotDefinitions"], strict=True)
+ except ValueError as error:
+ raise exceptions.ValidationError({"customBotDefinitions": str(error)})
+ value = {**value, "customBotDefinitions": [rule.model_dump(exclude_none=True) for rule in parsed]}
+
+ try:
+ modifiers = HogQLQueryModifiers(**value)
+ except Exception:
+ raise exceptions.ValidationError(f"Invalid modifier key.")
+
+ if "customBotDefinitions" in value:
+ rules = modifiers.customBotDefinitions or []
+ if len(rules) > MAX_CUSTOM_BOT_DEFINITIONS:
+ raise exceptions.ValidationError(
+ {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}
+ )
+ for rule in rules:
+ # An unusable pattern would break every query that reads $virt_is_bot for this
+ # project, so it is rejected here rather than dropped silently at query time.
+ try:
+ validate_custom_bot_rule(rule)
+ except ValueError as error:
+ # An empty name would render as an orphaned leading colon.
+ message = f"{rule.name}: {error}" if rule.name else str(error)
+ raise exceptions.ValidationError({"customBotDefinitions": message})
+ try:
+ validate_custom_bot_rule_set(rules)
+ assert_custom_bot_patterns_compile(compiled_custom_bot_patterns(rules))
+ except ValueError as error:
+ raise exceptions.ValidationError({"customBotDefinitions": str(error)})
+
+ return value
+
+ def validate_proactive_tasks_enabled(self, value: bool | None) -> bool | None:
+ if not value or settings.DEBUG:
+ return value
+
+ # Only team ID 2 in US region can enable proactive tasks
+ if self.instance and self.instance.id == 2 and get_instance_region() == "US":
+ return value
+
+ raise exceptions.PermissionDenied("Proactive tasks can only be enabled for authorized teams.")
+
+ def validate(self, attrs: Any) -> Any:
+ attrs = settings_validation.validate_team_attrs(attrs, self.context["view"], self.instance)
+ return super().validate(attrs)
+
+ def create(self, validated_data: dict[str, Any], **kwargs) -> Team:
+ request = self.context["request"]
+ if self.context["project_id"] not in self.user_permissions.project_ids_visible_for_user:
+ raise exceptions.NotFound("Project not found.")
+ validated_data["project_id"] = self.context["project_id"]
+ serializers.raise_errors_on_nested_writes("create", self, validated_data)
+
+ if "week_start_day" not in validated_data:
+ country_code = get_geoip_properties(get_ip_address(request)).get("$geoip_country_code", None)
+ if country_code:
+ week_start_day_for_user_ip_location = get_week_start_for_country_code(country_code)
+ # get_week_start_for_country_code() also returns 6 for countries where the week starts on Saturday,
+ # but ClickHouse doesn't support Saturday as the first day of the week, so we fall back to Sunday
+ validated_data["week_start_day"] = 1 if week_start_day_for_user_ip_location == 1 else 0
+
+ team = Team.objects.create_with_data(
+ initiating_user=request.user,
+ organization=self.context["view"].organization,
+ **validated_data,
+ )
+
+ request.user.current_team = team
+ request.user.team = request.user.current_team # Update cached property
+ request.user.save()
+
+ log_activity(
+ organization_id=team.organization_id,
+ team_id=team.pk,
+ user=request.user,
+ was_impersonated=is_impersonated(request),
+ scope="Team",
+ item_id=team.pk,
+ activity="created",
+ detail=Detail(name=str(team.name)),
+ )
+
+ return team
+
+ def update(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ before_update = instance.__dict__.copy()
+ # The settings patch persisted under lock below must not be written again from the
+ # stale request snapshot; the token handler can add the key later, so capture the
+ # client's intent now.
+ patch_conversations_settings = "conversations_settings" in validated_data
+ # Captured before the locked block pops the keys, so the refresh/re-cache step
+ # below still knows this request touched the team row.
+ conversations_lock_applied = patch_conversations_settings or "conversations_enabled" in validated_data
+ if "home_tab_dashboard" in validated_data:
+ dashboard = instance.home_tab_dashboard
+ before_update["home_tab_dashboard"] = dashboard.id if dashboard else None
+
+ # Should be validated already, but let's be extra sure
+ if config_data := validated_data.pop("revenue_analytics_config", None):
+ self._update_revenue_analytics_config(instance, config_data)
+
+ if config_data := validated_data.pop("marketing_analytics_config", None):
+ self._update_marketing_analytics_config(instance, config_data)
+
+ if config_data := validated_data.pop("customer_analytics_config", None):
+ self._update_customer_analytics_config(instance, config_data)
+
+ if config_data := validated_data.pop("workflows_config", None):
+ self._update_workflows_config(instance, config_data)
+
+ if config_data := validated_data.pop("feature_flag_policy_config", None):
+ self._update_feature_flag_policy_config(instance, config_data)
+
+ # Lives on a Team extension, not a Team column, so it can't flow through the generic
+ # save(update_fields=...) loop below.
+ if "home_tab_dashboard" in validated_data:
+ dashboard = validated_data.pop("home_tab_dashboard")
+ instance.home_tab_dashboard = dashboard
+ home_tab_dashboard_id = dashboard.id if dashboard else None
+
+ if "session_recording_retention_period" in validated_data:
+ self._verify_update_session_recording_retention_period(
+ instance, validated_data["session_recording_retention_period"]
+ )
+
+ if "survey_config" in validated_data:
+ if instance.survey_config is not None and validated_data.get("survey_config") is not None:
+ validated_data["survey_config"] = {
+ **instance.survey_config,
+ **validated_data["survey_config"],
+ }
+
+ if validated_data.get("survey_config") is None:
+ del before_update["survey_config"]
+
+ survey_config_changes_between = dict_changes_between(
+ "Survey",
+ before_update.get("survey_config", {}),
+ validated_data.get("survey_config", {}),
+ use_field_exclusions=True,
+ )
+
+ if survey_config_changes_between:
+ log_activity(
+ organization_id=cast(UUIDT, instance.organization_id),
+ team_id=instance.pk,
+ user=cast(User, self.context["request"].user),
+ was_impersonated=is_impersonated(self.context["request"]),
+ scope="Survey",
+ item_id="",
+ activity="updated",
+ detail=Detail(
+ name="global survey appearance",
+ changes=survey_config_changes_between,
+ ),
+ )
+
+ if (
+ "session_replay_config" in validated_data
+ and validated_data["session_replay_config"] is not None
+ and instance.session_replay_config is not None
+ ):
+ # for session_replay_config and its top level keys we merge existing settings with new settings
+ # this way we don't always have to receive the entire settings object to change one setting
+ # so for each key in validated_data["session_replay_config"] we merge it with the existing settings
+ # and then merge any top level keys that weren't provided
+
+ for key, value in validated_data["session_replay_config"].items():
+ if key in instance.session_replay_config:
+ # if they're both dicts then we merge them, otherwise, the new value overwrites the old
+ if isinstance(instance.session_replay_config[key], dict) and isinstance(
+ validated_data["session_replay_config"][key], dict
+ ):
+ validated_data["session_replay_config"][key] = {
+ **instance.session_replay_config[key], # existing values
+ **value, # and new values on top
+ }
+
+ # then also add back in any keys that exist but are not in the provided data
+ validated_data["session_replay_config"] = {
+ **instance.session_replay_config,
+ **validated_data["session_replay_config"],
+ }
+
+ # Merge modifiers with existing values so that updating one modifier doesn't wipe out others
+ if "modifiers" in validated_data:
+ validated_data["modifiers"] = merge_modifiers(validated_data["modifiers"], instance.modifiers)
+
+ # Persist only the fields this request changes. A full-row save() writes back every
+ # column from this request's snapshot of the team, so two concurrent PATCHes clobber
+ # each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
+ # erased `has_completed_onboarding_for` and reverted `completed_snippet_onboarding`,
+ # bouncing freshly onboarded users back into onboarding.
+ other_team_fields = [
+ attr for attr in validated_data if attr not in conversations_settings.LOCKED_CONVERSATIONS_COLUMNS
+ ]
+ for attr in other_team_fields:
+ setattr(instance, attr, validated_data[attr])
+
+ # Merge conversations_settings under a lock; a null clear still keeps the managed keys.
+ if conversations_lock_applied:
+ locked_conversations = conversations_settings.merge_conversations_settings_locked(
+ instance, validated_data, patch_conversations_settings, other_team_fields
+ )
+ # The locked re-read is newer than the snapshot, so a concurrent write is not logged as this user's.
+ before_update["conversations_settings"] = locked_conversations["conversations_settings"]
+ before_update["conversations_enabled"] = locked_conversations["conversations_enabled"]
+ elif other_team_fields:
+ # auto_now fields only refresh when included in update_fields
+ instance.save(update_fields=[*other_team_fields, "updated_at"])
+ # Snapshot before the cache refresh below so the audit diff only reflects this
+ # request's writes, not fields a concurrent request changed.
+ after_update = instance.__dict__.copy()
+ if "home_tab_dashboard" in before_update:
+ after_update["home_tab_dashboard"] = home_tab_dashboard_id
+ if other_team_fields or conversations_lock_applied:
+ # The in-memory instance may hold stale values for fields a concurrent request
+ # changed, and the post-save receiver has already cached that snapshot. Reload
+ # and re-cache so the team cache reflects the merged row.
+ instance.refresh_from_db()
+ set_team_in_cache(instance.api_token, instance)
+ updated_team = instance
+
+ changes = dict_changes_between("Team", before_update, after_update, use_field_exclusions=True)
+
+ log_activity(
+ organization_id=cast(UUIDT, instance.organization_id),
+ team_id=instance.pk,
+ user=cast(User, self.context["request"].user),
+ was_impersonated=is_impersonated(self.context["request"]),
+ scope="Team",
+ item_id=instance.pk,
+ activity="updated",
+ detail=Detail(
+ name=str(instance.name),
+ changes=changes,
+ ),
+ )
+
+ conversations_settings.report_conversations_settings_changes(
+ cast(User, self.context["request"].user),
+ before_update.get("conversations_settings"),
+ after_update.get("conversations_settings"),
+ updated_team,
+ )
+
+ return updated_team
+
+ def _update_revenue_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ # Capture old config before saving
+ old_config = {
+ "events": [event.model_dump() for event in (instance.revenue_analytics_config.events or [])],
+ "filter_test_accounts": instance.revenue_analytics_config.filter_test_accounts,
+ }
+
+ serializer = team_config.TeamRevenueAnalyticsConfigSerializer(
+ instance.revenue_analytics_config,
+ data=validated_data,
+ partial=True,
+ context={**self.context, "user_access_control": self.user_access_control},
+ )
+ if not serializer.is_valid():
+ raise serializers.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+
+ serializer.save()
+
+ # Log activity for revenue analytics config changes
+ new_config = {
+ "events": validated_data.get("events", []),
+ "filter_test_accounts": validated_data.get("filter_test_accounts", False),
+ }
+
+ self._capture_diff(instance, "revenue_analytics_config", old_config, new_config)
+
+ if "events" in validated_data:
+ from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
+ from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind
+
+ managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(
+ team=instance,
+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,
+ )
+ managed_viewset.sync_views()
+
+ return instance
+
+ def _update_marketing_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ # Capture the old config before saving
+ old_config = {
+ "sources_map": (
+ instance.marketing_analytics_config.sources_map.copy()
+ if instance.marketing_analytics_config.sources_map
+ else {}
+ ),
+ "attribution_window_days": instance.marketing_analytics_config.attribution_window_days,
+ "attribution_mode": instance.marketing_analytics_config.attribution_mode,
+ "filter_test_accounts": instance.marketing_analytics_config.filter_test_accounts,
+ # Add other fields as they're added to the model
+ # "conversion_goals": instance.marketing_analytics_config.conversion_goals.copy() if instance.marketing_analytics_config.conversion_goals else [],
+ }
+
+ marketing_serializer = marketing_config.TeamMarketingAnalyticsConfigSerializer(
+ instance.marketing_analytics_config,
+ data=validated_data,
+ partial=True,
+ context={**self.context, "user_access_control": self.user_access_control},
+ )
+ if not marketing_serializer.is_valid():
+ raise serializers.ValidationError(
+ settings_validation._format_serializer_errors(marketing_serializer.errors)
+ )
+
+ marketing_serializer.save()
+
+ # Log activity for marketing analytics config changes
+ new_config = {
+ "sources_map": validated_data.get("sources_map", {}),
+ "attribution_window_days": validated_data.get("attribution_window_days"),
+ "attribution_mode": validated_data.get("attribution_mode"),
+ "filter_test_accounts": validated_data.get("filter_test_accounts"),
+ # Add other fields as they're added to the model
+ # "conversion_goals": validated_data.get("conversion_goals", []),
+ }
+
+ self._capture_diff(instance, "marketing_analytics_config", old_config, new_config)
+ return instance
+
+ def _update_customer_analytics_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ old_config = {
+ "activity_event": instance.customer_analytics_config.activity_event,
+ "signup_pageview_event": instance.customer_analytics_config.signup_pageview_event,
+ "signup_event": instance.customer_analytics_config.signup_event,
+ "subscription_event": instance.customer_analytics_config.subscription_event,
+ "payment_event": instance.customer_analytics_config.payment_event,
+ "account_group_type_index": instance.customer_analytics_config.account_group_type_index,
+ "default_pinned_properties": instance.customer_analytics_config.default_pinned_properties,
+ }
+
+ serializer = team_config.TeamCustomerAnalyticsConfigSerializer(
+ instance.customer_analytics_config,
+ data=validated_data,
+ partial=True,
+ context={**self.context, "user_access_control": self.user_access_control},
+ )
+ if not serializer.is_valid():
+ raise serializers.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+
+ serializer.save()
+
+ new_config = {
+ field: getattr(instance.customer_analytics_config, field)
+ for field in team_config.TeamCustomerAnalyticsConfigSerializer.Meta.fields
+ }
+ self._capture_diff(instance, "customer_analytics_config", old_config, new_config)
+ return instance
+
+ def _update_workflows_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ old_config = {
+ field: getattr(instance.workflows_config, field)
+ for field in team_config.TeamWorkflowsConfigSerializer.Meta.fields
+ }
+
+ serializer = team_config.TeamWorkflowsConfigSerializer(
+ instance.workflows_config,
+ data=validated_data,
+ partial=True,
+ context={**self.context, "user_access_control": self.user_access_control},
+ )
+ if not serializer.is_valid():
+ raise serializers.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+
+ serializer.save()
+
+ new_config = {
+ field: getattr(instance.workflows_config, field)
+ for field in team_config.TeamWorkflowsConfigSerializer.Meta.fields
+ }
+ self._capture_diff(instance, "workflows_config", old_config, new_config)
+ return instance
+
+ def _update_feature_flag_policy_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ old_config = {
+ field: getattr(instance.feature_flag_policy_config, field)
+ for field in team_config.TeamFeatureFlagPolicyConfigSerializer.Meta.fields
+ }
+
+ serializer = team_config.TeamFeatureFlagPolicyConfigSerializer(
+ instance.feature_flag_policy_config,
+ data=validated_data,
+ partial=True,
+ context={**self.context, "user_access_control": self.user_access_control},
+ )
+ if not serializer.is_valid():
+ raise serializers.ValidationError(settings_validation._format_serializer_errors(serializer.errors))
+
+ serializer.save()
+
+ new_config = {
+ field: getattr(instance.feature_flag_policy_config, field)
+ for field in team_config.TeamFeatureFlagPolicyConfigSerializer.Meta.fields
+ }
+ self._capture_diff(instance, "feature_flag_policy_config", old_config, new_config)
+ return instance
+
+ def _verify_update_session_recording_retention_period(self, instance: Team, new_retention_period: str):
+ retention_feature = instance.organization.get_available_feature(AvailableFeature.SESSION_REPLAY_DATA_RETENTION)
+ highest_retention_entitlement = parse_feature_to_entitlement(retention_feature)
+
+ if highest_retention_entitlement is None:
+ raise exceptions.APIException(detail="Invalid retention entitlement.") # HTTP 500
+
+ # Should be validated already, but let's be extra sure to avoid IndexErrors below
+ if not validate_retention_period(new_retention_period):
+ raise exceptions.ValidationError( # HTTP 400
+ f"Must provide a valid retention period. Options are: {VALID_RETENTION_PERIODS}."
+ )
+
+ if retention_violates_entitlement(new_retention_period, highest_retention_entitlement):
+ raise exceptions.PermissionDenied( # HTTP 403
+ f"This organization does not have permission to set retention period of length '{new_retention_period}' - longest allowable retention period is '{highest_retention_entitlement}'."
+ )
+
+ def _capture_diff(self, instance: Team, key: str, before: dict, after: dict):
+ changes = dict_changes_between(
+ "Team",
+ {key: before},
+ {key: after},
+ use_field_exclusions=True,
+ )
+
+ if changes:
+ log_activity(
+ organization_id=cast(UUIDT, instance.organization_id),
+ team_id=instance.pk,
+ user=cast(User, self.context["request"].user),
+ was_impersonated=is_impersonated(self.context["request"]),
+ scope="Team",
+ item_id=instance.pk,
+ activity="updated",
+ detail=Detail(name=str(instance.name), changes=changes),
+ )
+
+
+class EvaluationContextSuggestionRequestSerializer(serializers.Serializer):
+ context_name = serializers.CharField(
+ max_length=255,
+ help_text=(
+ "Name of the evaluation context to hide from (POST) or restore to (DELETE) "
+ "the flag editor's suggestion list. Case-insensitive and whitespace-trimmed."
+ ),
+ )
+
+
+class EvaluationContextSuggestionResponseSerializer(serializers.Serializer):
+ success = serializers.BooleanField(help_text="Whether the suggestion visibility change was applied.")
+ name = serializers.CharField(help_text="Normalized name of the affected evaluation context.")
+ hidden_from_suggestions = serializers.BooleanField(
+ help_text="Whether the context is now hidden from the flag editor's suggestion list."
+ )
diff --git a/posthog/api/team/viewsets.py b/posthog/api/team/viewsets.py
new file mode 100644
index 000000000000..e27e8fc2cd39
--- /dev/null
+++ b/posthog/api/team/viewsets.py
@@ -0,0 +1,613 @@
+"""Viewsets and endpoint serializers for project settings."""
+
+from functools import cached_property
+from typing import Any, cast
+
+from django.conf import settings
+from django.shortcuts import get_object_or_404
+from django.utils import timezone
+from django.utils.dateparse import parse_datetime
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import exceptions, request, response, serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import TeamBasicSerializer
+from posthog.api.utils import action
+from posthog.auth import SessionAuthentication
+from posthog.decorators import disallow_if_impersonated
+from posthog.event_usage import report_user_action
+from posthog.helpers.impersonation import is_impersonated
+from posthog.models import ProductIntent, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog, Detail, load_activity, log_activity
+from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
+from posthog.models.event_ingestion_restriction_config import (
+ EventIngestionRestrictionConfig,
+ IngestionPipeline,
+ RestrictionType,
+)
+from posthog.models.product_intent.product_intent import ProductIntentSerializer
+from posthog.models.team.util import actions_that_require_current_team
+from posthog.models.utils import UUIDT
+from posthog.permissions import (
+ AccessControlPermission,
+ APIScopePermission,
+ OrganizationMemberPermissions,
+ TeamMemberLightManagementPermission,
+ TeamMemberStrictManagementPermission,
+ UserCanCreateProjectPermission,
+ get_authenticator_scoped_organization_ids,
+ get_authenticator_scoped_team_ids,
+)
+from posthog.scopes import APIScopeObjectOrNotSupported
+from posthog.user_permissions import UserPermissions
+from posthog.utils import get_instance_realm
+
+from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
+from products.access_control.backend.presentation.access_control_settings import AccessControlSettingsViewSetMixin
+
+from . import integration_config, team_config, team_permissions, team_serializer
+
+
+class EventIngestionRestrictionSerializer(serializers.Serializer):
+ restriction_type = serializers.ChoiceField(
+ choices=RestrictionType.choices,
+ help_text="What happens to matching events: dropped, sent to the overflow lane, or ingested without person processing.",
+ )
+ distinct_ids = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Distinct IDs the restriction applies to. Empty means it is not filtered by distinct ID.",
+ )
+ session_ids = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Session IDs the restriction applies to. Empty means it is not filtered by session ID.",
+ )
+ event_names = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Event names the restriction applies to. Empty means it is not filtered by event name.",
+ )
+ event_uuids = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Event UUIDs the restriction applies to. Empty means it is not filtered by event UUID.",
+ )
+ pipelines = serializers.ListField(
+ child=serializers.ChoiceField(choices=IngestionPipeline.choices),
+ help_text="Ingestion pipelines the restriction applies to. Filters combine with AND; values within a filter combine with OR.",
+ )
+
+
+def team_event_ingestion_restrictions_view(team: Team, request: request.Request) -> response.Response:
+ restrictions = EventIngestionRestrictionConfig.objects.filter(token=team.api_token)
+ data = [
+ {
+ "restriction_type": restriction.restriction_type,
+ "distinct_ids": restriction.distinct_ids or [],
+ "session_ids": restriction.session_ids or [],
+ "event_names": restriction.event_names or [],
+ "event_uuids": restriction.event_uuids or [],
+ "pipelines": restriction.pipelines or [],
+ }
+ for restriction in restrictions
+ ]
+ return response.Response(EventIngestionRestrictionSerializer(data, many=True).data)
+
+
+class TeamViewSet(
+ TeamAndOrgViewSetMixin, AccessControlSettingsViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet
+):
+ """
+ Projects for the current organization.
+ """
+
+ scope_object: APIScopeObjectOrNotSupported = "project"
+ serializer_class = team_serializer.TeamSerializer
+ queryset = Team.objects.all().select_related("organization")
+ lookup_field = "id"
+ ordering = "-created_by"
+
+ # Actions whose GET is downgraded to project:read for session auth; mutating methods stay on project:write/admin.
+ GET_DOWNGRADE_ACTIONS = ("evaluation_context_suggestions",)
+
+ def safely_get_queryset(self, queryset):
+ user = cast(User, self.request.user)
+ # IMPORTANT: This is actually what ensures that a user cannot read/update a project for which they don't have permission
+ visible_teams_ids = UserPermissions(user).team_ids_visible_for_user
+ queryset = queryset.filter(id__in=visible_teams_ids)
+ authenticator = self.request.successful_authenticator
+ if scoped_organizations := get_authenticator_scoped_organization_ids(authenticator):
+ queryset = queryset.filter(project__organization_id__in=scoped_organizations)
+ if scoped_teams := get_authenticator_scoped_team_ids(authenticator):
+ queryset = queryset.filter(id__in=scoped_teams)
+ return queryset
+
+ def get_serializer_class(self) -> type[serializers.BaseSerializer]:
+ if self.action == "list":
+ return TeamBasicSerializer
+ return super().get_serializer_class()
+
+ def dangerously_get_required_scopes(self, request, view) -> list[str] | None:
+ # Used for the AccessControlViewSetMixin
+ mixin_result = super().dangerously_get_required_scopes(request, view)
+ if mixin_result is not None:
+ return mixin_result
+
+ # NOTE: This downgrade only applies to session-based auth (browser users).
+ # All other auth methods (API keys, OAuth tokens, etc.) must have project:write
+ # to modify any fields, preserving the semantic meaning of read-only API keys.
+ if self.action == "partial_update":
+ is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
+ if is_session_auth:
+ request_fields = set(request.data.keys())
+ # Member-safe fields, plus fields whose write is governed by their own field-level
+ # access control — keep the request gate from demanding project:write (admin) for the
+ # latter, otherwise e.g. a web analytics editor on a restricted project is blocked
+ # before UserAccessControlSerializerMixin.validate can authorize the field.
+ downgradable_fields = (
+ team_config.TEAM_CONFIG_MEMBER_FIELDS_SET | team_config.TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS
+ )
+ if request_fields and request_fields.issubset(downgradable_fields):
+ return ["project:read"]
+
+ # Read-only access for member-readable actions — only downgrade GET, not writes.
+ if self.action in self.GET_DOWNGRADE_ACTIONS and request.method == "GET":
+ is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
+ if is_session_auth:
+ return ["project:read"]
+
+ # Fall back to the default behavior
+ return None
+
+ # NOTE: Team permissions are somewhat complex so we override the underlying viewset's get_permissions method
+ def dangerously_get_permissions(self) -> list:
+ """
+ Special permissions handling for create requests as the organization is inferred from the current user.
+ """
+
+ permissions: list = [
+ IsAuthenticated,
+ APIScopePermission,
+ AccessControlPermission,
+ team_permissions.PremiumMultiEnvironmentPermission,
+ *self.permission_classes,
+ ]
+
+ # Return early for non-actions (e.g. OPTIONS)
+ if self.action:
+ if self.action == "create":
+ if "is_demo" not in self.request.data or not self.request.data["is_demo"]:
+ permissions.append(UserCanCreateProjectPermission)
+ else:
+ permissions.append(OrganizationMemberPermissions)
+ elif self.action != "list":
+ # Skip TeamMemberAccessPermission for list action, as list is serialized with limited TeamBasicSerializer.
+ # GET_DOWNGRADE_ACTIONS writes stay admin-gated via TeamMemberStrictManagementPermission.
+ if self.action in self.GET_DOWNGRADE_ACTIONS:
+ if self.request.method != "GET":
+ # Writes need strict (admin for all non-safe methods), not light (which only gates DELETE).
+ permissions.append(TeamMemberStrictManagementPermission)
+ else:
+ permissions.append(TeamMemberLightManagementPermission)
+
+ return [permission() for permission in permissions]
+
+ def safely_get_object(self, queryset):
+ lookup_value = self.kwargs[self.lookup_field]
+ if lookup_value == "@current":
+ team = getattr(self.request.user, "team", None)
+ if team is None:
+ raise exceptions.NotFound()
+ # This branch answers from the user's own state instead of the scoped queryset. A project
+ # that moved between organizations leaves that state naming an environment the token's
+ # organizations no longer cover, so apply the same restriction the queryset would have.
+ scoped_organizations = get_authenticator_scoped_organization_ids(self.request.successful_authenticator)
+ if scoped_organizations and str(team.organization_id) not in scoped_organizations:
+ raise exceptions.NotFound()
+ return team
+
+ filter_kwargs = {self.lookup_field: lookup_value}
+ try:
+ team = get_object_or_404(queryset, **filter_kwargs)
+ except ValueError as error:
+ raise exceptions.ValidationError(str(error))
+ return team
+
+ # :KLUDGE: Exposed for compatibility reasons for permission classes.
+ @property
+ def team(self):
+ return self.get_object()
+
+ def perform_destroy(self, team: Team):
+ # Check if bulk deletion operations are disabled via environment variable
+ if settings.DISABLE_BULK_DELETES:
+ raise exceptions.ValidationError(
+ "Team deletion is temporarily disabled during database migration. Please try again later."
+ )
+
+ team_id = team.pk
+ organization_id = team.organization_id
+ team_name = team.name
+
+ # Remove the team from the org's managed warehouse first (no-op for orgs without
+ # one). Blocks when duckgres refuses — e.g. the warehouse's last team, which
+ # requires deprovisioning the warehouse (or deleting the organization) instead.
+ # Keep the product API off the core import path.
+ from products.managed_warehouse.backend.facade.api import get_team_deletion_block_reason # noqa: PLC0415
+
+ warehouse_block_reason = get_team_deletion_block_reason(team_id, organization_id)
+ if warehouse_block_reason:
+ raise exceptions.ValidationError(warehouse_block_reason)
+
+ user = cast(User, self.request.user)
+
+ # Hand off all deletion work (bulky postgres, batch exports, team record,
+ # ClickHouse, email) to the durable Temporal workflow.
+ from posthog.temporal.delete_teams.dispatch import start_delete_project_data_workflow
+
+ start_delete_project_data_workflow(
+ team_ids=[team_id],
+ project_id=None, # Only deleting a team, not the whole project
+ user_id=user.id,
+ project_name=team_name,
+ )
+
+ log_activity(
+ organization_id=cast(UUIDT, organization_id),
+ team_id=team_id,
+ user=user,
+ was_impersonated=is_impersonated(self.request),
+ scope="Team",
+ item_id=team_id,
+ activity="deleted",
+ detail=Detail(name=str(team_name)),
+ )
+ # TRICKY: We pass in `team` here as access to `user.current_team` can fail if it was deleted
+ report_user_action(user, "team deleted", team=team, request=self.request)
+
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ # Only ADMIN or higher users are allowed to access this project
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def reset_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ team.reset_token_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ # Only ADMIN or higher users are allowed to access this project
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def rotate_secret_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ integration_config.validate_secret_token_generation(team)
+ team.rotate_secret_token_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ # Only ADMIN or higher users are allowed to access this project
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def delete_secret_token_backup(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ team.delete_secret_token_backup_and_save(user=request.user, is_impersonated_session=is_impersonated(request))
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @extend_schema(request=None, responses=team_serializer.TeamSerializer)
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ # Only ADMIN or higher users are allowed to access this project
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def rotate_heatmaps_screenshot_secret(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ team.rotate_heatmaps_screenshot_secret_and_save(
+ user=request.user, is_impersonated_session=is_impersonated(request)
+ )
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @action(
+ methods=["POST"],
+ detail=True,
+ # Only ADMIN or higher users are allowed to access this project
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def generate_conversations_public_token(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ team.generate_conversations_public_token_and_save(
+ user=request.user, is_impersonated_session=is_impersonated(request)
+ )
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @extend_schema(
+ methods=["GET"],
+ request=None,
+ responses={200: integration_config.TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
+ @extend_schema(
+ methods=["PATCH"],
+ request=integration_config.TeamLogsConfigSerializer,
+ responses={200: integration_config.TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
+ @action(
+ methods=["GET", "PATCH"],
+ detail=True,
+ permission_classes=[TeamMemberStrictManagementPermission],
+ url_path="logs_config",
+ )
+ def logs_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Manage logs product configuration for this environment. Members can read;
+ writing requires project admin, matching the admin-only settings UI."""
+ return integration_config.handle_logs_config(request, self.get_object())
+
+ @extend_schema(
+ methods=["GET"],
+ request=None,
+ responses={200: integration_config.TeamTracingConfigSerializer},
+ extensions={"x-product": "tracing"},
+ )
+ @extend_schema(
+ methods=["PATCH"],
+ request=integration_config.TeamTracingConfigSerializer,
+ responses={200: integration_config.TeamTracingConfigSerializer},
+ extensions={"x-product": "tracing"},
+ )
+ @action(
+ methods=["GET", "PATCH"],
+ detail=True,
+ permission_classes=[TeamMemberStrictManagementPermission],
+ url_path="tracing_config",
+ )
+ def tracing_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Manage tracing product configuration for this environment. Members can read;
+ writing requires project admin, matching the admin-only settings UI."""
+ return integration_config.handle_tracing_config(request, self.get_object())
+
+ @action(
+ methods=["GET", "PATCH"],
+ detail=True,
+ permission_classes=[TeamMemberStrictManagementPermission],
+ url_path="experiments_config",
+ )
+ def experiments_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Manage experiment configuration for this environment."""
+ return integration_config.handle_experiments_config(request, self.get_object())
+
+ @extend_schema(
+ methods=["POST"],
+ request=team_serializer.EvaluationContextSuggestionRequestSerializer,
+ responses={200: team_serializer.EvaluationContextSuggestionResponseSerializer},
+ extensions={"x-product": "feature_flags"},
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ parameters=[team_serializer.EvaluationContextSuggestionRequestSerializer],
+ responses={200: team_serializer.EvaluationContextSuggestionResponseSerializer},
+ extensions={"x-product": "feature_flags"},
+ )
+ @action(
+ methods=["POST", "DELETE"],
+ detail=True,
+ permission_classes=[IsAuthenticated],
+ )
+ def evaluation_context_suggestions(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+
+ POST hides the name; DELETE restores it. The underlying context row and any flags already
+ using it are never modified — this only controls what gets suggested.
+ """
+ return integration_config.handle_evaluation_context_suggestions(request, self.get_object())
+
+ @action(
+ methods=["GET"],
+ detail=True,
+ permission_classes=[IsAuthenticated],
+ )
+ def is_generating_demo_data(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ team = self.get_object()
+ return response.Response({"is_generating_demo_data": team.get_is_generating_demo_data()})
+
+ @action(methods=["GET"], detail=True)
+ def activity(self, request: request.Request, **kwargs):
+ page_params = parse_activity_page_params(request)
+
+ team = self.get_object()
+
+ activity_page = load_activity(
+ scope="Team",
+ team_id=team.pk,
+ item_ids=[str(team.pk)],
+ limit=page_params.limit,
+ page=page_params.page,
+ )
+ return activity_page_response(activity_page, page_params.limit, page_params.page, request)
+
+ @action(methods=["GET"], detail=True)
+ def settings_as_of(self, request: request.Request, **kwargs) -> response.Response:
+ """
+ Return the team settings as of the provided timestamp.
+ Query params:
+ - at: ISO8601 datetime (required)
+ - scope: optional, one or multiple keys to filter the returned settings
+ """
+ team = self.get_object()
+
+ at_param = request.query_params.get("at")
+ if not at_param:
+ raise exceptions.ValidationError({"at": "Query parameter 'at' is required (ISO8601)."})
+
+ as_of = parse_datetime(at_param)
+ if as_of is None:
+ raise exceptions.ValidationError(
+ {"at": "Invalid datetime format. Use ISO8601 (e.g., 2025-11-24T12:34:56Z)."}
+ )
+ if timezone.is_naive(as_of):
+ as_of = timezone.make_aware(as_of)
+
+ # Build starting snapshot from current model values for config fields
+ settings_fields = set(team_config.TEAM_CONFIG_FIELDS)
+ snapshot: dict[str, Any] = {}
+ for field_name in settings_fields:
+ if hasattr(team, field_name):
+ snapshot[field_name] = getattr(team, field_name)
+ elif hasattr(team, f"{field_name}_id"):
+ snapshot[field_name] = getattr(team, f"{field_name}_id")
+ else:
+ snapshot[field_name] = None
+
+ # Fetch Team-scoped activity logs after the target timestamp
+ logs = (
+ ActivityLog.objects.filter(team_id=team.id, scope="Team", item_id=str(team.id), created_at__gt=as_of)
+ .order_by("-created_at")
+ .only("detail", "created_at", "activity")
+ )
+
+ # Roll back newest → oldest
+ for log in logs.iterator():
+ detail = log.detail or {}
+ changes = detail.get("changes") or []
+ for change in changes:
+ field = change.get("field")
+ action = change.get("action")
+ before = change.get("before")
+
+ # Normalize FK fields (e.g., primary_dashboard_id → primary_dashboard)
+ target = field[:-3] if isinstance(field, str) and field.endswith("_id") else field
+ if target not in settings_fields:
+ continue
+
+ if action == "changed":
+ snapshot[target] = before
+ elif action == "created":
+ snapshot[target] = None
+ elif action == "deleted":
+ snapshot[target] = before
+ # Other actions (created/deleted without relevant field) are ignored
+
+ # Optional scope filtering
+ scope_values = request.query_params.getlist("scope")
+
+ if scope_values:
+ filtered = {k: snapshot.get(k, None) for k in scope_values}
+ return response.Response(filtered)
+
+ return response.Response(snapshot)
+
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ required_scopes=["project:read"],
+ )
+ @disallow_if_impersonated(message="Impersonated sessions cannot set product intents.")
+ def add_product_intent(self, request: request.Request, *args, **kwargs):
+ team = self.get_object()
+ user = request.user
+ current_url = request.headers.get("Referer")
+ session_id = request.headers.get("X-Posthog-Session-Id")
+
+ serializer = ProductIntentSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ ProductIntent.register(
+ team=team,
+ product_type=serializer.validated_data["product_type"],
+ context=serializer.validated_data.get("intent_context"),
+ user=cast(User, user),
+ metadata={**serializer.validated_data["metadata"], "$current_url": current_url, "$session_id": session_id},
+ is_onboarding=False,
+ )
+
+ return response.Response(
+ team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data, status=201
+ )
+
+ @action(
+ methods=["PATCH"],
+ detail=True,
+ required_scopes=["project:read"],
+ )
+ @disallow_if_impersonated(message="Impersonated sessions cannot set product intents.")
+ def complete_product_onboarding(self, request: request.Request, *args, **kwargs):
+ team = self.get_object()
+ product_type = request.data.get("product_type")
+ user = request.user
+ current_url = request.headers.get("Referer")
+ session_id = request.headers.get("X-Posthog-Session-Id")
+
+ if not product_type:
+ return response.Response({"error": "product_type is required"}, status=400)
+
+ product_intent_serializer = ProductIntentSerializer(data=request.data)
+ product_intent_serializer.is_valid(raise_exception=True)
+ intent_data = product_intent_serializer.validated_data
+ intent_context = intent_data.get("intent_context")
+
+ product_intent = ProductIntent.register(
+ team=team,
+ product_type=product_type,
+ context=intent_context,
+ user=cast(User, user),
+ metadata={**intent_data["metadata"], "$current_url": current_url, "$session_id": session_id},
+ is_onboarding=True,
+ )
+
+ if isinstance(user, User): # typing
+ report_user_action(
+ user,
+ "product onboarding completed",
+ {
+ "product_key": product_type,
+ "intent_context": intent_context,
+ "intent_created_at": product_intent.created_at,
+ "intent_updated_at": product_intent.updated_at,
+ "realm": get_instance_realm(),
+ },
+ team=team,
+ request=request,
+ )
+
+ return response.Response(team_serializer.TeamSerializer(team, context=self.get_serializer_context()).data)
+
+ @extend_schema(responses=EventIngestionRestrictionSerializer(many=True))
+ @action(
+ methods=["GET"],
+ detail=True,
+ required_scopes=["project:read"],
+ url_path="event_ingestion_restrictions",
+ pagination_class=None,
+ )
+ def event_ingestion_restrictions(self, request, **kwargs):
+ return team_event_ingestion_restrictions_view(self.get_object(), request)
+
+ @cached_property
+ def user_permissions(self):
+ team = self.get_object() if self.action in actions_that_require_current_team else None
+ return UserPermissions(cast(User, self.request.user), team)
+
+
+class RootTeamViewSet(TeamViewSet):
+ # NOTE: We don't want people creating environments via the "current_organization"/"current_project" concept, but
+ # rather specify the org ID and project ID in the URL - hence this is hidden from the API docs, but used in the app
+ hide_api_docs = True
+
+
+class ProjectEnvironmentsViewSet(TeamViewSet):
+ """Deprecated: use /api/environments/{id}/ instead.
+
+ Hidden from the API docs, so the actions it inherits from TeamViewSet do not reach the
+ generated types and MCP tools under a route that rejects every request."""
+
+ hide_api_docs = True
+
+ def initial(self, request: request.Request, *args, **kwargs) -> None:
+ raise exceptions.PermissionDenied(
+ "Multiple environments per project are no longer available. Please contact support if you need assistance."
+ )
diff --git a/posthog/api/test/test_bulk_deletion_disabled.py b/posthog/api/test/test_bulk_deletion_disabled.py
index 652971817831..feb03f8e4faa 100644
--- a/posthog/api/test/test_bulk_deletion_disabled.py
+++ b/posthog/api/test/test_bulk_deletion_disabled.py
@@ -14,7 +14,7 @@ class TestBulkDeletionDisabled(APIBaseTest):
super().setUp()
self.additional_team = Team.objects.create(organization=self.organization, name="Test Team for Deletion")
- @patch("posthog.api.team.settings.DISABLE_BULK_DELETES", True)
+ @patch("posthog.api.team.viewsets.settings.DISABLE_BULK_DELETES", True)
def test_team_deletion_disabled(self):
"""Test that team deletion returns 400 when DISABLE_BULK_DELETES is True."""
self.organization_membership.level = OrganizationMembership.Level.ADMIN
@@ -28,7 +28,7 @@ class TestBulkDeletionDisabled(APIBaseTest):
self.assertTrue(Team.objects.filter(id=self.additional_team.id).exists())
@patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")
- @patch("posthog.api.team.settings.DISABLE_BULK_DELETES", False)
+ @patch("posthog.api.team.viewsets.settings.DISABLE_BULK_DELETES", False)
def test_team_deletion_enabled(self, mock_start_deletion):
"""Test that team deletion is allowed (hands off to Temporal) when DISABLE_BULK_DELETES is False."""
self.organization_membership.level = OrganizationMembership.Level.ADMIN
diff --git a/posthog/api/test/test_path_cleaning_validation.py b/posthog/api/test/test_path_cleaning_validation.py
index 4dfa03f1d98e..a383e5d47afe 100644
--- a/posthog/api/test/test_path_cleaning_validation.py
+++ b/posthog/api/test/test_path_cleaning_validation.py
@@ -3,7 +3,8 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import exceptions
-from posthog.api.team import TeamSerializer, validate_path_cleaning_filters
+from posthog.api.team.settings_validation import validate_path_cleaning_filters
+from posthog.api.team.team_serializer import TeamSerializer
class TestPathCleaningFilterValidation(SimpleTestCase):
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 25554f808173..4ee92edf3c14 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -13,7 +13,8 @@ from rest_framework.test import APIRequestFactory
from posthog.api.project import ProjectBackwardCompatSerializer, ProjectCreateRequestSerializer, ProjectViewSet
from posthog.api.project_tags import MAX_TAGS_PER_FILTER
-from posthog.api.team import TeamCustomerAnalyticsConfigSerializer, TeamSerializer
+from posthog.api.team.team_config import TeamCustomerAnalyticsConfigSerializer
+from posthog.api.team.team_serializer import TeamSerializer
from posthog.api.test.test_team import EnvironmentToProjectRewriteClient, team_api_test_factory
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -1000,7 +1001,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
with (
capture_db_queries() as queries,
- patch("posthog.api.team.report_user_action") as mock_report,
+ patch("posthog.api.team.conversations_settings.report_user_action") as mock_report,
):
with (
patch.object(Team.objects, "select_for_update", simulate_integration_update),
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 7777a39969a9..cac2bff5498f 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -18,16 +18,14 @@ from parameterized import parameterized
from rest_framework import status, test
from posthog.api.project import ProjectBackwardCompatSerializer, log_activity
-from posthog.api.team import (
+from posthog.api.team.conversations_settings import handle_conversations_token_on_update, merge_conversations_settings
+from posthog.api.team.live_events import _default_data_color_theme_id, _reset_default_data_color_theme_id_cache
+from posthog.api.team.team_config import (
TEAM_CONFIG_FIELDS_SET,
TEAM_CONFIG_MEMBER_FIELDS_SET,
- TeamSerializer,
TeamWorkflowsConfigSerializer,
- _default_data_color_theme_id,
- _reset_default_data_color_theme_id_cache,
- handle_conversations_token_on_update,
- merge_conversations_settings,
)
+from posthog.api.team.team_serializer import TeamSerializer
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -1596,7 +1594,7 @@ def team_api_test_factory():
team=self.team,
)
- @patch("posthog.api.team.enqueue_product_activation_calc_debounced", MagicMock())
+ @patch("posthog.api.team.team_serializer.enqueue_product_activation_calc_debounced", MagicMock())
@patch("posthog.models.product_intent.ProductIntent.check_and_update_activation", return_value=False)
@patch("posthog.event_usage.report_user_action")
@time_machine.travel("2024-01-01T00:00:00Z", tick=False)
@@ -1666,7 +1664,7 @@ def team_api_test_factory():
assert self.team.session_recording_opt_in is True
@patch("posthog.api.project.report_user_action")
- @patch("posthog.api.team.report_user_action")
+ @patch("posthog.api.team.viewsets.report_user_action")
def test_can_complete_product_onboarding(
self, mock_report_user_action: MagicMock, mock_report_user_action_legacy_endpoint: MagicMock
) -> None:
@@ -1701,7 +1699,7 @@ def team_api_test_factory():
)
@patch("posthog.api.project.report_user_action")
- @patch("posthog.api.team.report_user_action")
+ @patch("posthog.api.team.viewsets.report_user_action")
def test_can_complete_product_onboarding_as_member(
self, mock_report_user_action: MagicMock, mock_report_user_action_legacy_endpoint: MagicMock
) -> None:
@@ -2095,7 +2093,7 @@ def team_api_test_factory():
assert response.json()["conversations_settings"]["widget_color"] == "#ff0000"
def test_conversations_settings_change_reports_event_per_setting(self):
- with patch("posthog.api.team.report_user_action") as mock_report:
+ with patch("posthog.api.team.conversations_settings.report_user_action") as mock_report:
response = self.client.patch(
"/api/environments/@current/",
{"conversations_settings": {"slack_nudge_enabled": False, "widget_greeting_text": "Hi!"}},
@@ -2112,7 +2110,7 @@ def team_api_test_factory():
assert "value" not in props_by_setting["widget_greeting_text"]
# A no-op save (same values) must not re-fire the event.
- with patch("posthog.api.team.report_user_action") as mock_report:
+ with patch("posthog.api.team.conversations_settings.report_user_action") as mock_report:
response = self.client.patch(
"/api/environments/@current/",
{"conversations_settings": {"slack_nudge_enabled": False}},
@@ -3845,7 +3843,7 @@ class TestTeamSerializerHomeViewWins(APIBaseTest):
def test_default_data_color_theme_id_is_cached_for_process_lifetime(self):
# System-wide default DataColorTheme is a deploy-time fixture; cache for
# process lifetime to skip a per-render PG round-trip on the home view.
- with patch("posthog.api.team.DataColorTheme.objects") as mock_objects:
+ with patch("posthog.api.team.live_events.DataColorTheme.objects") as mock_objects:
chained = mock_objects.filter.return_value.order_by.return_value.values_list.return_value
chained.first.return_value = 42
@@ -3859,7 +3857,7 @@ class TestTeamSerializerHomeViewWins(APIBaseTest):
# If the very first call lands before the data migration is applied, a
# None must NOT be cached - subsequent calls should retry so we recover
# automatically once the row appears.
- with patch("posthog.api.team.DataColorTheme.objects") as mock_objects:
+ with patch("posthog.api.team.live_events.DataColorTheme.objects") as mock_objects:
chained = mock_objects.filter.return_value.order_by.return_value.values_list.return_value
chained.first.return_value = None
@@ -3868,7 +3866,7 @@ class TestTeamSerializerHomeViewWins(APIBaseTest):
assert mock_objects.filter.call_count == 2
- with patch("posthog.api.team.DataColorTheme.objects") as mock_objects:
+ with patch("posthog.api.team.live_events.DataColorTheme.objects") as mock_objects:
chained = mock_objects.filter.return_value.order_by.return_value.values_list.return_value
chained.first.return_value = 7
@@ -3890,7 +3888,7 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):
]
)
def test_returns_a_signed_jwt_with_expected_claims(self, _name: str, anonymous: bool) -> None:
- from posthog.api.team import get_or_mint_live_events_token
+ from posthog.api.team.live_events import get_or_mint_live_events_token
from posthog.jwt import PosthogJwtAudience, decode_jwt
user_id = None if anonymous else self.user.id
@@ -3908,11 +3906,11 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):
]
)
def test_second_call_returns_cached_token_without_re_signing(self, _name: str, anonymous: bool) -> None:
- from posthog.api.team import get_or_mint_live_events_token
+ from posthog.api.team.live_events import get_or_mint_live_events_token
user_id = None if anonymous else self.user.id
first = get_or_mint_live_events_token(self.team, user_id)
- with patch("posthog.api.team.encode_jwt") as mock_encode:
+ with patch("posthog.api.team.live_events.encode_jwt") as mock_encode:
second = get_or_mint_live_events_token(self.team, user_id)
mock_encode.assert_not_called()
assert first == second
@@ -3930,7 +3928,7 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):
]
)
def test_cache_key_component_changes_force_a_fresh_mint(self, _name: str, mutation_factory) -> None:
- from posthog.api.team import get_or_mint_live_events_token
+ from posthog.api.team.live_events import get_or_mint_live_events_token
mutation = mutation_factory(self)
first_user_id = mutation.get("first_user_id", self.user.id)
@@ -3948,7 +3946,7 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):
# the livestream service would reject the cached old-key signatures for up
# to the cache TTL. We embed a fingerprint of JWT_SIGNING_KEY in the cache key so
# the namespace partitions cleanly on rotation.
- from posthog.api.team import get_or_mint_live_events_token
+ from posthog.api.team.live_events import get_or_mint_live_events_token
token_old_key = get_or_mint_live_events_token(self.team, self.user.id)
with override_settings(JWT_SIGNING_KEY="completely-different-rotated-secret"):
@@ -4267,7 +4265,9 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):
"conversations_settings": merge_conversations_settings(None, current),
}
- with patch("posthog.api.team.secrets.token_urlsafe", return_value="test-generated-token"):
+ with patch(
+ "posthog.api.team.conversations_settings.secrets.token_urlsafe", return_value="test-generated-token"
+ ):
result = handle_conversations_token_on_update(updates, not enabling, current)
token = ("test-existing-token" if has_token else "test-generated-token") if enabling else None
@@ -4285,7 +4285,9 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):
if settings_input != "omitted":
updates["conversations_settings"] = None if settings_input == "null" else {}
- with patch("posthog.api.team.secrets.token_urlsafe", return_value="test-generated-token"):
+ with patch(
+ "posthog.api.team.conversations_settings.secrets.token_urlsafe", return_value="test-generated-token"
+ ):
result = handle_conversations_token_on_update(updates, not enabling, current_settings)
expected: dict[str, str | None] = dict(current_settings) if settings_input == "omitted" else {}
@@ -4320,7 +4322,7 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):
team = Team(id=1)
serializer = serializer_class(context={"request": request})
- with patch("posthog.api.team.get_or_mint_live_events_token", return_value="test-live-token"):
+ with patch("posthog.api.team.live_events.get_or_mint_live_events_token", return_value="test-live-token"):
if isinstance(serializer, TeamSerializer):
token = serializer.get_live_events_token(team)
else:
diff --git a/posthog/api/test/test_team_logs_config.py b/posthog/api/test/test_team_logs_config.py
index 261c3570d55d..67c474f54c21 100644
--- a/posthog/api/test/test_team_logs_config.py
+++ b/posthog/api/test/test_team_logs_config.py
@@ -5,7 +5,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
-from posthog.api.team import TeamLogsConfigSerializer
+from posthog.api.team.integration_config import TeamLogsConfigSerializer
from posthog.models import OrganizationMembership, Team
from posthog.models.team.extensions import get_or_create_team_extension
@@ -18,7 +18,7 @@ from products.logs.backend.models import (
)
# Both routes resolve to the same handler — /api/projects/ is canonical, /api/environments/
-# remains as the back-compat alias. See `handle_logs_config` in posthog/api/team.py.
+# remains as the back-compat alias. See `handle_logs_config` in posthog/api/team/integration_config.py.
URL_PREFIXES = [("projects", "api/projects"), ("environments", "api/environments")]
DEFAULT_CONFIG = {
diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.py
index ad9ea69b48ed..16b16780a34c 100644
--- a/posthog/api/test/test_team_project_differential.py
+++ b/posthog/api/test/test_team_project_differential.py
@@ -6,7 +6,7 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
-from posthog.api.team import TEAM_CONFIG_FIELDS
+from posthog.api.team.team_config import TEAM_CONFIG_FIELDS
from posthog.models.organization import OrganizationMembership
from posthog.models.project import Project
from posthog.models.team.team import Team
diff --git a/posthog/api/test/test_team_project_parity.py b/posthog/api/test/test_team_project_parity.py
index 940368e4c51f..a934d446cc57 100644
--- a/posthog/api/test/test_team_project_parity.py
+++ b/posthog/api/test/test_team_project_parity.py
@@ -4,7 +4,8 @@ from rest_framework import viewsets
from posthog.api.project import ProjectBackwardCompatSerializer, ProjectViewSet
from posthog.api.shared import ProjectBackwardCompatBasicSerializer, TeamBasicSerializer
-from posthog.api.team import TeamSerializer, TeamViewSet
+from posthog.api.team.team_serializer import TeamSerializer
+from posthog.api.team.viewsets import TeamViewSet
# /api/projects/ (Project model) is the canonical surface; /api/environments/ (Team model) is the
# backward-compat alias, now served through /api/projects/ by an in-process path rewrite
diff --git a/posthog/api/test/test_team_tracing_config.py b/posthog/api/test/test_team_tracing_config.py
index ea8843a925f6..5491ee41f8af 100644
--- a/posthog/api/test/test_team_tracing_config.py
+++ b/posthog/api/test/test_team_tracing_config.py
@@ -10,7 +10,7 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.api.team import TRACES_RETENTION_FLAG, TeamTracingConfigSerializer
+from posthog.api.team.integration_config import TRACES_RETENTION_FLAG, TeamTracingConfigSerializer
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, Team
from posthog.models.team.extensions import get_or_create_team_extension
@@ -217,7 +217,7 @@ class TestTeamTracingConfigRetention(APIBaseTest):
self.organization_membership.save()
self.url = f"/api/projects/{self.team.id}/tracing_config/"
self.flag_patcher = patch(
- "posthog.api.team.posthog_feature_flag_enabled",
+ "posthog.api.team.settings_validation.posthog_feature_flag_enabled",
side_effect=lambda flag, *args, **kwargs: flag == TRACES_RETENTION_FLAG,
)
self.flag_patcher.start()
@@ -237,7 +237,9 @@ class TestTeamTracingConfigRetention(APIBaseTest):
self.assertEqual(len(connection.savepoint_ids), transaction_depth)
return True
- with patch("posthog.api.team.posthog_feature_flag_enabled", side_effect=flag_enabled) as mock_flag:
+ with patch(
+ "posthog.api.team.settings_validation.posthog_feature_flag_enabled", side_effect=flag_enabled
+ ) as mock_flag:
response = self.client.patch(self.url, {"retention_days": 30}, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
self.assertGreater(mock_flag.call_count, 0)
@@ -258,7 +260,7 @@ class TestTeamTracingConfigRetention(APIBaseTest):
def test_changing_the_period_requires_the_flag(self):
self._grant_30d_retention()
self.flag_patcher.stop()
- with patch("posthog.api.team.posthog_feature_flag_enabled", return_value=False):
+ with patch("posthog.api.team.settings_validation.posthog_feature_flag_enabled", return_value=False):
denied = self.client.patch(self.url, {"retention_days": 30}, format="json")
unchanged = self.client.patch(
self.url,
@@ -282,7 +284,7 @@ class TestTeamTracingConfigRetention(APIBaseTest):
if not stale_config:
config.refresh_from_db()
- with patch("posthog.api.team.get_or_create_team_extension", return_value=config):
+ with patch("posthog.api.team.integration_config.get_or_create_team_extension", return_value=config):
second = self.client.patch(self.url, {"retention_days": 14}, format="json")
self.assertEqual(second.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("once per 24 hours", str(second.json()))
@@ -300,7 +302,7 @@ class TestTeamTracingConfigRetention(APIBaseTest):
# An entitlement reset lands after the read and leaves retention_last_updated alone.
TeamTracingConfig.objects.filter(team=self.team).update(retention_days=DEFAULT_TRACES_RETENTION_DAYS)
- with patch("posthog.api.team.get_or_create_team_extension", return_value=snapshot):
+ with patch("posthog.api.team.integration_config.get_or_create_team_extension", return_value=snapshot):
response = self.client.patch(self.url, {"retention_days": 30}, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("Reload the settings and retry", str(response.json()))
@@ -316,7 +318,9 @@ class TestTeamTracingConfigRetention(APIBaseTest):
Organization.objects.filter(id=self.organization.id).update(available_product_features=[])
return flag == TRACES_RETENTION_FLAG
- with patch("posthog.api.team.posthog_feature_flag_enabled", side_effect=revoke_during_validation):
+ with patch(
+ "posthog.api.team.settings_validation.posthog_feature_flag_enabled", side_effect=revoke_during_validation
+ ):
response = self.client.patch(self.url, {"retention_days": 30}, format="json")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())
diff --git a/posthog/models/team/team_caching.py b/posthog/models/team/team_caching.py
index 7e4e7a986b56..8673112d8f18 100644
--- a/posthog/models/team/team_caching.py
+++ b/posthog/models/team/team_caching.py
@@ -12,7 +12,7 @@ FIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in seconds
def set_team_in_cache(token: str, team: Optional["Team"] = None) -> None:
- from posthog.api.team import CachingTeamSerializer
+ from posthog.api.team.team_config import CachingTeamSerializer
from posthog.models.team import Team
if not team:
diff --git a/posthog/utils.py b/posthog/utils.py
index 781ac5af9f4a..a6b1fd69de69 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -597,7 +597,7 @@ def _build_template_context(
from posthog.api.file_system.user_product_list import UserProductListSerializer
from posthog.api.project import ProjectSerializer
from posthog.api.shared import TeamPublicSerializer
- from posthog.api.team import TeamSerializer
+ from posthog.api.team.team_serializer import TeamSerializer
from posthog.api.user import UserSerializer
from posthog.models.file_system.user_product_list import UserProductList
from posthog.models.user_home_settings import UserHomeSettings
diff --git a/products/annotations/backend/api/test/test_annotation.py b/products/annotations/backend/api/test/test_annotation.py
index 32f9e0271f41..ba5b2d6e7e6c 100644
--- a/products/annotations/backend/api/test/test_annotation.py
+++ b/products/annotations/backend/api/test/test_annotation.py
@@ -375,7 +375,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):
instance = Annotation.objects.create(organization=self.organization, team=self.team, created_by=self.user)
self.client.force_login(new_user)
- with patch("posthog.api.team.report_user_action"):
+ with patch("posthog.api.team.viewsets.report_user_action"):
response = self.client.delete(f"/api/projects/{self.team.id}/annotations/{instance.pk}/")
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
index c0d0381af38d..dc90d182a06c 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
@@ -7,7 +7,7 @@ from rest_framework.parsers import JSONParser
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
-from posthog.api.team import handle_evaluation_context_suggestions
+from posthog.api.team.integration_config import handle_evaluation_context_suggestions
from posthog.models import Team
from posthog.models.organization import OrganizationMembership
diff --git a/products/marketing_analytics/backend/hogql_queries/test_utils.py b/products/marketing_analytics/backend/hogql_queries/test_utils.py
index db09e509b9a0..63dfaafb7c9d 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_utils.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_utils.py
@@ -10,7 +10,7 @@ from pydantic import (
from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3
-from posthog.api.team import MarketingAnalyticsConversionGoalList
+from posthog.api.team.marketing_config import MarketingAnalyticsConversionGoalList
from products.marketing_analytics.backend.hogql_queries.utils import convert_team_conversion_goals_to_objects
diff --git a/products/marketing_analytics/backend/test_api_conversion_goals.py b/products/marketing_analytics/backend/test_api_conversion_goals.py
index 88c5569af8b2..4ad1f28f1332 100644
--- a/products/marketing_analytics/backend/test_api_conversion_goals.py
+++ b/products/marketing_analytics/backend/test_api_conversion_goals.py
@@ -9,7 +9,7 @@ from django.db import close_old_connections, connection, transaction
from parameterized import parameterized
-from posthog.api.team import TeamMarketingAnalyticsConfigSerializer
+from posthog.api.team.marketing_config import TeamMarketingAnalyticsConfigSerializer
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import OrganizationMembership
diff --git a/products/surveys/backend/debug.py b/products/surveys/backend/debug.py
index e1f7ea4e24df..47dac14cb061 100644
--- a/products/surveys/backend/debug.py
+++ b/products/surveys/backend/debug.py
@@ -1,6 +1,6 @@
from typing import Any
-from posthog.api.team import CachingTeamSerializer
+from posthog.api.team.team_config import CachingTeamSerializer
from posthog.models.team import Team
from posthog.models.team.team_caching import get_team_in_cache, set_team_in_cache