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.

chore(groups): move the groups api out of ee into products/groups (#115274)

Thomas Obermüllerc709e7d86ae8
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
index 13057f7e751a..fb2f2ffc3f90 100644
--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
@@ -30,7 +30,7 @@ Suggested entry format:
## 2026-10-06: Single-person event lookups under override-based person IDs: prefilter on stored person ID or override distinct IDs, keep the resolved check
-**Context.** The related groups panel on person pages (`ee/clickhouse/queries/related_actors_query.py`, `_query_related_groups`): `SELECT DISTINCT` group keys `FROM events WHERE person_id = {person} AND timestamp` in the last 90 days. Under the override-based persons-on-events modes, HogQL resolves `events.person_id` through `person_distinct_id_overrides` for every row in the window before the person filter can apply. On team 2 a large share of loads failed with `MEMORY_LIMIT_EXCEEDED` after ~40s.
+**Context.** The related groups panel on person pages (`products/groups/backend/logic/related_actors_query.py`, `_query_related_groups`): `SELECT DISTINCT` group keys `FROM events WHERE person_id = {person} AND timestamp` in the last 90 days. Under the override-based persons-on-events modes, HogQL resolves `events.person_id` through `person_distinct_id_overrides` for every row in the window before the person filter can apply. On team 2 a large share of loads failed with `MEMORY_LIMIT_EXCEEDED` after ~40s.
**Question.** Can the lookup stop resolving identity for the whole team's window without changing which groups come back for merged, detached or squashed persons?
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index 04fe5a11e700..f1bed0ee997d 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -28,6 +28,7 @@ products/cohorts
products/customer_analytics/backend/hogql_queries
products/error_tracking/backend/hogql_queries
products/experiments
+products/groups/backend/tests
products/marketing_analytics/backend/hogql_queries
products/marketing_analytics/backend/services/test_attribution_health.py
products/marketing_analytics/backend/services/test_conversion_recordings.py
diff --git a/ee/owners.yaml b/ee/owners.yaml
index 7baa0cde61a8..851ba24a1803 100644
--- a/ee/owners.yaml
+++ b/ee/owners.yaml
@@ -9,8 +9,6 @@ rules:
owners: team-growth
- match: '/clickhouse/materialized_columns/'
owners: team-analytics-platform
- - match: ['/clickhouse/queries/related_actors_query.py', '/clickhouse/views/groups.py']
- owners: team-product-analytics
- match: '/hogai/'
owners: team-self-driving
- match: '/session_recordings/'
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 8ba5053400ba..d858cafe2774 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -478,16 +478,8 @@ projects_router.register(
projects_router.register(r"sessions", SessionViewSet, "project_sessions", ["team_id"])
if EE_AVAILABLE:
- from ee.clickhouse.views.groups import GroupsTypesViewSet, GroupsViewSet, GroupUsageMetricViewSet
from ee.clickhouse.views.person import EnterprisePersonViewSet, LegacyEnterprisePersonViewSet
- projects_router.register(r"groups", GroupsViewSet, "project_groups", ["team_id"])
- group_types_router = projects_router.register(
- r"groups_types", GroupsTypesViewSet, "project_groups_types", ["project_id"]
- )
- group_types_router.register(
- r"metrics", GroupUsageMetricViewSet, "project_groups_metrics", ["project_id", "group_type_index"]
- )
projects_router.register(r"persons", EnterprisePersonViewSet, "project_persons", ["team_id"])
router.register(r"person", LegacyEnterprisePersonViewSet, "persons")
vercel_installations_router = router.register(
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f9fb229b232d..2a43bd03877a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -127,6 +127,7 @@ PRODUCTS_APPS = [
"products.security.backend.apps.SecurityConfig",
"products.webmcp.backend.apps.WebmcpConfig",
"products.warehouse_suggestions.backend.apps.WarehouseSuggestionsConfig",
+ "products.groups.backend.apps.GroupsConfig",
]
INSTALLED_APPS = [
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 87c06887aad0..1ca6f5d96496 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -33,8 +33,6 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"ee.api.subscription.SubscriptionDeliveryViewSet",
"ee.api.subscription.SubscriptionViewSet",
"ee.clickhouse.views.experiment_saved_metrics.ExperimentSavedMetricViewSet",
- "ee.clickhouse.views.groups.GroupsTypesViewSet",
- "ee.clickhouse.views.groups.GroupsViewSet",
"ee.clickhouse.views.person.EnterprisePersonViewSet",
"ee.clickhouse.views.person.LegacyEnterprisePersonViewSet",
"posthog.api.advanced_activity_logs.viewset.ActivityLogViewSet",
@@ -175,6 +173,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.feature_flags.backend.api.staff_teams.FeatureFlagsStaffTeamSearchViewSet",
"products.feature_flags.backend.presentation.request_usage.FeatureFlagRequestUsageViewSet",
"products.field_notes.backend.api.FieldNoteViewSet",
+ "products.groups.backend.presentation.views.GroupsTypesViewSet",
+ "products.groups.backend.presentation.views.GroupsViewSet",
"products.growth.backend.api.identity_matching.IdentityMatchingLinkViewSet",
"products.legal_documents.backend.presentation.views.LegalDocumentViewSet",
"products.logs.backend.presentation.views.alerts_api.LogsAlertViewSet",
diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
index 572649e90db8..8d81c85ba7bd 100644
--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
@@ -87,7 +87,6 @@ REVIEWED_WRITABLE: dict[str, str] = {
"ee.api.subscription.SubscriptionSerializer.until_date": "Client sets when delivery stops, or null for indefinite",
"ee.api.subscription.SubscriptionWriteSerializer.start_date": "Client sets when delivery starts",
"ee.api.subscription.SubscriptionWriteSerializer.until_date": "Client sets when delivery stops, or null for indefinite",
- "ee.clickhouse.views.groups.GroupTypeSerializer.created_at": "TODO: server-owned, the model sets it on creation itself",
"posthog.api.advanced_activity_logs.viewset.ActivityLogFlatExportSerializer.created_at": "TODO: server-owned audit timestamp, make read-only",
"posthog.api.advanced_activity_logs.viewset.ActivityLogSerializer.created_at": "TODO: server-owned audit timestamp, make read-only",
"posthog.api.event_definition.EventDefinitionSerializer.created_at": "TODO: server-owned, set when ingestion first sees the event",
@@ -124,6 +123,7 @@ REVIEWED_WRITABLE: dict[str, str] = {
"products.experiments.backend.presentation.serializers.ExperimentWriteSerializer.start_date": "Client launches the experiment by setting this",
"products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.end_date": "Client picks when a recurring schedule stops",
"products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.scheduled_at": "Client picks when the change is applied",
+ "products.groups.backend.presentation.views.GroupTypeSerializer.created_at": "TODO: server-owned, the model sets it on creation itself",
"products.logs.backend.presentation.views.alerts_api.LogsAlertConfigurationSerializer.snooze_until": "Client-set instant: update() pops snooze_until and assigns it to instance.snooze_until, with no relative-duration parsing on this path",
"products.product_tours.backend.api.product_tour.ProductTourSerializer.end_date": "Client schedules when the tour stops",
"products.product_tours.backend.api.product_tour.ProductTourSerializer.start_date": "Client schedules when the tour starts",
diff --git a/products/groups/__init__.py b/products/groups/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/groups/backend/__init__.py b/products/groups/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/groups/backend/apps.py b/products/groups/backend/apps.py
new file mode 100644
index 000000000000..e55e70aa00dd
--- /dev/null
+++ b/products/groups/backend/apps.py
@@ -0,0 +1,8 @@
+"""Django app configuration for groups."""
+
+from django.apps import AppConfig
+
+
+class GroupsConfig(AppConfig):
+ name = "products.groups.backend"
+ label = "groups"
diff --git a/products/groups/backend/facade/__init__.py b/products/groups/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/groups/backend/facade/api.py b/products/groups/backend/facade/api.py
new file mode 100644
index 000000000000..dc572fa357f7
--- /dev/null
+++ b/products/groups/backend/facade/api.py
@@ -0,0 +1,36 @@
+"""
+Facade for groups.
+
+The ONLY module other products are allowed to import.
+Accept frozen dataclasses, call logic/, return frozen
+dataclasses. Never return ORM instances or import DRF.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..logic.property_definitions import create_property_definition
+from ..logic.related_actors_query import RelatedActorsQuery
+from . import contracts
+
+if TYPE_CHECKING:
+ from posthog.hogql_queries.serialized_actors import SerializedActor
+ from posthog.models import Team
+ from posthog.models.property import GroupTypeIndex
+
+
+def get_related_actors(
+ team: Team, group_type_index: GroupTypeIndex | str | None, actor_id: str
+) -> list[SerializedActor]:
+ return RelatedActorsQuery(team, group_type_index, actor_id).run()
+
+
+def upsert_group_property_definition(input: contracts.GroupPropertyDefinitionInput) -> None:
+ create_property_definition(
+ team_id=input.team_id,
+ project_id=input.project_id,
+ group_type_index=input.group_type_index,
+ property_name=input.property_name,
+ property_value=input.property_value,
+ )
diff --git a/products/groups/backend/facade/contracts.py b/products/groups/backend/facade/contracts.py
new file mode 100644
index 000000000000..d1000abc45be
--- /dev/null
+++ b/products/groups/backend/facade/contracts.py
@@ -0,0 +1,18 @@
+"""
+Contract types for groups.
+
+Frozen dataclasses that define what this product exposes.
+No Django imports. Used by facade as inputs/outputs.
+"""
+
+from pydantic import JsonValue
+from pydantic.dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class GroupPropertyDefinitionInput:
+ team_id: int
+ project_id: int
+ group_type_index: int
+ property_name: str
+ property_value: JsonValue
diff --git a/products/groups/backend/logic/property_definitions.py b/products/groups/backend/logic/property_definitions.py
new file mode 100644
index 000000000000..044535d71af5
--- /dev/null
+++ b/products/groups/backend/logic/property_definitions.py
@@ -0,0 +1,46 @@
+from posthog.models import PropertyDefinition
+
+from products.event_definitions.backend.models import PropertyType, effective_project_id_expr, group_type_index_key_expr
+
+
+def detect_group_property_type(value: object) -> PropertyType:
+ if value is None:
+ return PropertyType.String
+ elif isinstance(value, bool):
+ return PropertyType.Boolean
+ elif isinstance(value, int | float):
+ return PropertyType.Numeric
+ elif isinstance(value, str):
+ if value.lower() in ("true", "false"):
+ return PropertyType.Boolean
+ return PropertyType.String
+ return PropertyType.String
+
+
+def create_property_definition(
+ team_id: int, project_id: int, group_type_index: int, property_name: str, property_value: object
+) -> None:
+ """Create or update PostgreSQL PropertyDefinition for group property"""
+ property_type = detect_group_property_type(property_value)
+ is_numerical = property_type == PropertyType.Numeric
+
+ # Match on the key of posthog_propdef_proj_uniq. Then the lookup is a single index seek, and it finds a
+ # definition that another environment of the project created, so the insert cannot violate that constraint.
+ PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr(),
+ group_type_index_key=group_type_index_key_expr(),
+ ).filter(effective_project_id=project_id, group_type_index_key=group_type_index).update_or_create(
+ name=property_name,
+ type=PropertyDefinition.Type.GROUP,
+ defaults={
+ "property_type": property_type.value,
+ "is_numerical": is_numerical,
+ },
+ create_defaults={
+ "team_id": team_id,
+ "project_id": project_id,
+ "group_type_index": group_type_index,
+ "property_type": property_type.value,
+ "is_numerical": is_numerical,
+ },
+ )
diff --git a/ee/clickhouse/queries/related_actors_query.py b/products/groups/backend/logic/related_actors_query.py
similarity index 97%
rename from ee/clickhouse/queries/related_actors_query.py
rename to products/groups/backend/logic/related_actors_query.py
index a707d533b8d3..c629a75667c0 100644
--- a/ee/clickhouse/queries/related_actors_query.py
+++ b/products/groups/backend/logic/related_actors_query.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+from datetime import datetime, timedelta
from functools import cached_property
from typing import Any, Optional, Union, cast
@@ -21,6 +21,7 @@ from posthog.hogql_queries.serialized_actors import (
)
from posthog.models import Team
from posthog.models.filters.utils import validate_group_type_index
+from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.property import GroupTypeIndex
from posthog.personhog_client.caller_tag import personhog_caller_tag
@@ -37,7 +38,7 @@ class RelatedActorsQuery:
team: Team,
group_type_index: Optional[Union[GroupTypeIndex, str]],
id: str,
- ):
+ ) -> None:
self.team = team
self.group_type_index = validate_group_type_index("group_type_index", group_type_index)
self.id = id
@@ -72,8 +73,6 @@ class RelatedActorsQuery:
@cached_property
def _group_types(self) -> dict[int, dict[str, Any]]:
- from posthog.models.group_type_mapping import get_group_types_for_project
-
return {m["group_type_index"]: m for m in get_group_types_for_project(self.team.project_id)}
def _group_key_field(self, group_index: int) -> ast.Expr:
@@ -214,9 +213,9 @@ class RelatedActorsQuery:
return serialized_results
@cached_property
- def _after(self):
+ def _after(self) -> datetime:
return now() - timedelta(days=90)
@cached_property
- def _before(self):
+ def _before(self) -> datetime:
return now()
diff --git a/products/groups/backend/presentation/__init__.py b/products/groups/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/ee/clickhouse/views/exceptions.py b/products/groups/backend/presentation/exceptions.py
similarity index 64%
rename from ee/clickhouse/views/exceptions.py
rename to products/groups/backend/presentation/exceptions.py
index 61984c19fbe8..41912a7aed6c 100644
--- a/ee/clickhouse/views/exceptions.py
+++ b/products/groups/backend/presentation/exceptions.py
@@ -1,4 +1,4 @@
class TriggerGroupIdentifyException(Exception):
- def __init__(self, exception_data: dict, status_code: int):
+ def __init__(self, exception_data: dict, status_code: int) -> None:
self.exception_data = exception_data
self.status_code = status_code
diff --git a/ee/clickhouse/views/groups.py b/products/groups/backend/presentation/views.py
similarity index 91%
rename from ee/clickhouse/views/groups.py
rename to products/groups/backend/presentation/views.py
index 10d51b83ea23..9b0196d9f7b2 100644
--- a/ee/clickhouse/views/groups.py
+++ b/products/groups/backend/presentation/views.py
@@ -4,6 +4,7 @@ from typing import Any, Literal, Optional, cast, overload
from urllib.parse import urlencode
from django.db import IntegrityError
+from django.db.models import QuerySet
from django.utils import timezone
import structlog
@@ -28,7 +29,7 @@ from posthog.api.utils import action
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.helpers.impersonation import is_impersonated
-from posthog.models import GroupUsageMetric, PropertyDefinition
+from posthog.models import GroupUsageMetric
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
from posthog.models.filters.utils import GroupTypeIndex
@@ -49,7 +50,9 @@ from posthog.ph_client import feature_enabled_or_false
from posthog.utils import str_to_bool
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
-from products.event_definitions.backend.models import PropertyType, effective_project_id_expr, group_type_index_key_expr
+from products.groups.backend.facade import api as groups
+from products.groups.backend.facade.contracts import GroupPropertyDefinitionInput
+from products.groups.backend.presentation.exceptions import TriggerGroupIdentifyException
from products.notebooks.backend.facade import api as notebooks
from products.notebooks.backend.facade.content import (
build_markdown_notebook_content,
@@ -60,9 +63,7 @@ from products.notebooks.backend.facade.content import (
create_paragraph_with_text,
create_text_content,
)
-
-from ee.clickhouse.queries.related_actors_query import RelatedActorsQuery
-from ee.clickhouse.views.exceptions import TriggerGroupIdentifyException
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
@@ -89,49 +90,6 @@ def _decode_groups_cursor(cursor: str) -> tuple[int, str]:
return 0, ""
-def detect_group_property_type(value):
- if value is None:
- return PropertyType.String
- elif isinstance(value, bool):
- return PropertyType.Boolean
- elif isinstance(value, int | float):
- return PropertyType.Numeric
- elif isinstance(value, str):
- if value.lower() in ("true", "false"):
- return PropertyType.Boolean
- return PropertyType.String
- return PropertyType.String
-
-
-def create_property_definition(
- team_id: int, project_id: int, group_type_index: int, property_name: str, property_value
-):
- """Create or update PostgreSQL PropertyDefinition for group property"""
- property_type = detect_group_property_type(property_value)
- is_numerical = property_type == PropertyType.Numeric
-
- # Match on the key of posthog_propdef_proj_uniq. Then the lookup is a single index seek, and it finds a
- # definition that another environment of the project created, so the insert cannot violate that constraint.
- PropertyDefinition.objects.alias(
- effective_project_id=effective_project_id_expr(),
- group_type_index_key=group_type_index_key_expr(),
- ).filter(effective_project_id=project_id, group_type_index_key=group_type_index).update_or_create(
- name=property_name,
- type=PropertyDefinition.Type.GROUP,
- defaults={
- "property_type": property_type.value,
- "is_numerical": is_numerical,
- },
- create_defaults={
- "team_id": team_id,
- "project_id": project_id,
- "group_type_index": group_type_index,
- "property_type": property_type.value,
- "is_numerical": is_numerical,
- },
- )
-
-
class GroupTypeSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
class Meta:
model = GroupTypeMapping
@@ -139,6 +97,36 @@ class GroupTypeSerializer(serializers.ModelSerializer, UserAccessControlSerializ
read_only_fields = ["group_type", "group_type_index"]
+class GroupTypeMetadataUpdateSerializer(serializers.Serializer):
+ group_type_index = serializers.IntegerField(help_text="Index of the group type to update.")
+ name_singular = serializers.CharField(
+ max_length=400,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Singular display name of the group type.",
+ )
+ name_plural = serializers.CharField(
+ max_length=400,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Plural display name of the group type.",
+ )
+
+
+class GroupTypeCreateDetailDashboardSerializer(serializers.Serializer):
+ group_type_index = serializers.IntegerField(help_text="Index of the group type that gets the detail dashboard.")
+
+
+class GroupTypeSetDefaultColumnsSerializer(serializers.Serializer):
+ group_type_index = serializers.IntegerField(help_text="Index of the group type to update.")
+ default_columns = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Columns that the groups list of this group type shows by default.",
+ )
+
+
def _group_type_row_to_response(row: dict[str, Any]) -> dict[str, Any]:
"""Shape a get_group_types_for_project row like GroupTypeSerializer output.
@@ -172,8 +160,11 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
rows = get_group_types_for_project(self.team.project_id, caller_tag="groups/list")
return response.Response([_group_type_row_to_response(row) for row in rows])
+ @extend_schema(
+ request=GroupTypeMetadataUpdateSerializer(many=True), responses={200: GroupTypeSerializer(many=True)}
+ )
@action(detail=False, methods=["PATCH"], name="Update group types metadata")
- def update_metadata(self, request: request.Request, *args, **kwargs):
+ def update_metadata(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
for row in cast(list[dict], request.data):
instance = get_group_type_mapping_instance(
self.team.project_id,
@@ -195,8 +186,9 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
invalidate_group_types_cache(self.team.project_id)
return self.list(request, *args, **kwargs)
+ @extend_schema(request=GroupTypeCreateDetailDashboardSerializer, responses={200: GroupTypeSerializer})
@action(methods=["PUT"], detail=False)
- def create_detail_dashboard(self, request: request.Request, **kw):
+ def create_detail_dashboard(self, request: request.Request, **kw: Any) -> response.Response:
try:
group_type_mapping = get_group_type_mapping_instance(
self.team.project_id,
@@ -223,7 +215,7 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
invalidate_group_types_cache(self.team.project_id)
return response.Response(self.get_serializer(group_type_mapping).data)
- def destroy(self, request: request.Request, *args, **kwargs):
+ def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
group_type_index = int(kwargs[self.lookup_field])
try:
instance = get_group_type_mapping_instance(
@@ -239,8 +231,9 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
invalidate_group_types_cache(self.team.project_id)
return response.Response(status=status.HTTP_204_NO_CONTENT)
+ @extend_schema(request=GroupTypeSetDefaultColumnsSerializer, responses={200: GroupTypeSerializer})
@action(methods=["PUT"], detail=False)
- def set_default_columns(self, request: request.Request, **kw):
+ def set_default_columns(self, request: request.Request, **kw: Any) -> response.Response:
try:
group_type_mapping = get_group_type_mapping_instance(
self.team.project_id,
@@ -340,7 +333,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
"default": GroupSerializer,
}
- def get_serializer_class(self):
+ def get_serializer_class(self) -> type[serializers.BaseSerializer]:
return self.serializer_classes.get(self.action, self.serializer_classes["default"])
@overload
@@ -358,14 +351,14 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
raise ValidationError({"group_key": ["This query parameter is required."]})
return group_type_index, group_key
- def safely_get_queryset(self, queryset):
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
group_type_index, _ = self._safely_get_query_params()
return queryset.filter(
group_type_index=group_type_index,
group_key__icontains=self.request.GET.get("group_key", ""),
)
- def safely_get_object(self, queryset):
+ def safely_get_object(self, queryset: QuerySet) -> Group:
group_type_index, group_key = self._safely_get_query_params(require_group_key=True)
group = get_group_by_key(self.team.pk, int(group_type_index), group_key)
if group is None:
@@ -378,7 +371,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
return GroupTypeMappingResult(group_type=m["group_type"], group_type_index=m["group_type_index"])
raise NotFound()
- def trigger_group_identify(self, group: Group, operation: str, group_properties: Optional[dict] = None):
+ def trigger_group_identify(self, group: Group, operation: str, group_properties: Optional[dict] = None) -> None:
group_type_mapping = self.get_group_type_mapping_or_404(cast(GroupTypeIndex, group.group_type_index))
properties = {
"$group_type": group_type_mapping.group_type,
@@ -443,7 +436,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
),
]
)
- def list(self, request, *args, **kwargs):
+ def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
"""
List all groups of a specific group type. You must pass ?group_type_index= in the URL.
To get a list of valid group types, call /api/:project_id/groups_types/.
@@ -499,7 +492,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
return response.Response({"next": next_url, "previous": None, "results": serializer.data})
@extend_schema(request=CreateGroupSerializer, responses={status.HTTP_201_CREATED: serializer_classes["default"]})
- def create(self, request, *args, **kwargs):
+ def create(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
request_data = CreateGroupSerializer(data=request.data)
request_data.is_valid(raise_exception=True)
@@ -533,12 +526,14 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
return response.Response(data=exc.exception_data, status=exc.status_code)
for prop_name, prop_value in group.group_properties.items():
- create_property_definition(
- team_id=self.team.pk,
- project_id=self.team.project_id,
- group_type_index=group.group_type_index,
- property_name=prop_name,
- property_value=prop_value,
+ groups.upsert_group_property_definition(
+ GroupPropertyDefinitionInput(
+ team_id=self.team.pk,
+ project_id=self.team.project_id,
+ group_type_index=group.group_type_index,
+ property_name=prop_name,
+ property_value=prop_value,
+ )
)
details = [
@@ -652,12 +647,14 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
group.group_properties[property_key] = property_value
save_group(group, operation="group_update_property")
- create_property_definition(
- team_id=self.team.pk,
- project_id=self.team.project_id,
- group_type_index=group.group_type_index,
- property_name=property_key,
- property_value=property_value,
+ groups.upsert_group_property_definition(
+ GroupPropertyDefinitionInput(
+ team_id=self.team.pk,
+ project_id=self.team.project_id,
+ group_type_index=group.group_type_index,
+ property_name=property_key,
+ property_value=property_value,
+ )
)
# Need to update ClickHouse too
@@ -825,7 +822,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
]
)
@action(methods=["GET"], detail=False, required_scopes=["activity_log:read"])
- def activity(self, request: request.Request, pk=None, **kwargs):
+ def activity(self, request: request.Request, pk: str | None = None, **kwargs: Any) -> response.Response:
try:
group = self.get_object()
except Group.DoesNotExist:
@@ -860,17 +857,17 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
responses={200: RELATED_ACTORS_SCHEMA},
)
@action(methods=["GET"], detail=False, required_scopes=["group:read"])
- def related(self, request: request.Request, pk=None, **kw) -> response.Response:
+ def related(self, request: request.Request, pk: str | None = None, **kw: Any) -> response.Response:
group_type_index = request.GET.get("group_type_index")
actor_id = request.GET.get("id")
if not actor_id:
raise ValidationError({"id": ["This query parameter is required."]})
- results = RelatedActorsQuery(self.team, group_type_index, actor_id).run()
+ results = groups.get_related_actors(self.team, group_type_index, actor_id)
return response.Response(results)
@action(methods=["GET"], detail=False, required_scopes=["group:read"])
- def property_values(self, request: request.Request, **kw):
+ def property_values(self, request: request.Request, **kw: Any) -> response.Response:
with (
PROPERTY_VALUES_DURATION.labels(endpoint_type="group").time(),
tracer.start_as_current_span("groups_api_property_values") as span,
@@ -936,7 +933,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
send_feature_flag_events=False,
)
- def _create_notebook_for_group(self, group: Group):
+ def _create_notebook_for_group(self, group: Group) -> None:
# A group name is customer data and can hold line breaks. Markdown escapes inline syntax
# but keeps line breaks, so a second line starts its own block — a heading, a list, or a
# live component. Collapse the name to one line, which is what a title is anyway.
@@ -1022,7 +1019,7 @@ class GroupUsageMetricSerializer(serializers.ModelSerializer, UserAccessControlS
model = GroupUsageMetric
fields = ("id", "name", "format", "interval", "display", "filters", "math", "math_property")
- def validate(self, data):
+ def validate(self, data: dict[str, Any]) -> dict[str, Any]:
data = super().validate(data)
math = data.get("math", self.instance.math if self.instance else GroupUsageMetric.Math.COUNT)
@@ -1032,7 +1029,7 @@ class GroupUsageMetricSerializer(serializers.ModelSerializer, UserAccessControlS
source = (filters or {}).get("source") if isinstance(filters, dict) else None
if source == GroupUsageMetric.Source.DATA_WAREHOUSE:
- self._validate_data_warehouse(filters, math, math_property)
+ self._validate_data_warehouse(cast(dict, filters), math, math_property)
elif source in (None, GroupUsageMetric.Source.EVENTS):
self._validate_events(math, math_property)
else:
@@ -1040,15 +1037,13 @@ class GroupUsageMetricSerializer(serializers.ModelSerializer, UserAccessControlS
return data
- def _validate_events(self, math, math_property):
+ def _validate_events(self, math: str, math_property: str | None) -> None:
if math == GroupUsageMetric.Math.SUM and not math_property:
raise serializers.ValidationError({"math_property": "math_property is required when math is 'sum'."})
if math == GroupUsageMetric.Math.COUNT and math_property:
raise serializers.ValidationError({"math_property": "math_property must be empty when math is 'count'."})
- def _validate_data_warehouse(self, filters: dict, math, math_property):
- from products.warehouse_sources.backend.facade.models import DataWarehouseTable
-
+ def _validate_data_warehouse(self, filters: dict, math: str, math_property: str | None) -> None:
missing = [field for field in _DW_FILTER_REQUIRED_FIELDS if not filters.get(field)]
if missing:
raise serializers.ValidationError(
@@ -1075,5 +1070,5 @@ class GroupUsageMetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
queryset = GroupUsageMetric.objects.all()
serializer_class = GroupUsageMetricSerializer
- def perform_create(self, serializer):
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
serializer.save(team=self.team, group_type_index=self.parents_query_dict["group_type_index"])
diff --git a/products/groups/backend/routes.py b/products/groups/backend/routes.py
new file mode 100644
index 000000000000..093578235438
--- /dev/null
+++ b/products/groups/backend/routes.py
@@ -0,0 +1,18 @@
+from posthog.api.routing import RouterRegistry
+from posthog.settings import EE_AVAILABLE
+
+from products.groups.backend.presentation.views import GroupsTypesViewSet, GroupsViewSet, GroupUsageMetricViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ # The groups API is part of the enterprise edition, so a non-EE install serves none of these routes.
+ if not EE_AVAILABLE:
+ return
+
+ routers.projects.register(r"groups", GroupsViewSet, "project_groups", ["team_id"])
+ group_types_router = routers.projects.register(
+ r"groups_types", GroupsTypesViewSet, "project_groups_types", ["project_id"]
+ )
+ group_types_router.register(
+ r"metrics", GroupUsageMetricViewSet, "project_groups_metrics", ["project_id", "group_type_index"]
+ )
diff --git a/products/groups/backend/tests/__init__.py b/products/groups/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr b/products/groups/backend/tests/__snapshots__/test_clickhouse_groups.ambr
similarity index 100%
rename from ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
rename to products/groups/backend/tests/__snapshots__/test_clickhouse_groups.ambr
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr b/products/groups/backend/tests/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
similarity index 100%
rename from ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
rename to products/groups/backend/tests/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr b/products/groups/backend/tests/__snapshots__/test_related_actors_query.ambr
similarity index 100%
rename from ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
rename to products/groups/backend/tests/__snapshots__/test_related_actors_query.ambr
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr b/products/groups/backend/tests/__snapshots__/test_related_actors_query.new_events_schema.ambr
similarity index 100%
rename from ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr
rename to products/groups/backend/tests/__snapshots__/test_related_actors_query.new_events_schema.ambr
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/products/groups/backend/tests/test_clickhouse_groups.py
similarity index 98%
rename from ee/clickhouse/views/test/test_clickhouse_groups.py
rename to products/groups/backend/tests/test_clickhouse_groups.py
index 7cf93d596f85..cf04113f4acf 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/products/groups/backend/tests/test_clickhouse_groups.py
@@ -26,6 +26,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
+from posthog.constants import AvailableFeature
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.models import GroupUsageMetric, PropertyDefinition
from posthog.models.filters.utils import GroupTypeIndex
@@ -38,18 +39,20 @@ from posthog.models.group_type_mapping import (
get_group_types_for_project,
update_group_type_mapping_fields,
)
-from posthog.models.organization import Organization
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team.team import Team
+from posthog.personhog_client.fake_client import fake_personhog_client
from posthog.test.persons import create_group_type_mapping, create_person
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.access_control.backend.models.access_control import AccessControl
+from products.groups.backend.presentation.views import _decode_groups_cursor, _encode_groups_cursor
from products.notebooks.backend.facade.content import convert_notebook_content_to_markdown, is_markdown_notebook_content
from products.notebooks.backend.models import Notebook, ResourceNotebook
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
-from ee.clickhouse.views.groups import _decode_groups_cursor, _encode_groups_cursor
-
-PATH = "ee.clickhouse.views.groups"
+PATH = "products.groups.backend.presentation.views"
def typed_group_type_index(value: int) -> GroupTypeIndex:
@@ -371,7 +374,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(message["event"], "Group notebook creation failed")
@time_machine.travel("2021-05-02", tick=False)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_missing_group_properties(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -403,7 +406,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
mock_capture.assert_called_once()
@time_machine.travel("2021-05-02", tick=False)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
@pytest.mark.flaky(reruns=2)
def test_create_group(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -491,7 +494,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
prop_name = result["detail"]["name"]
self.assertEqual(result["detail"]["changes"][0]["after"], group_properties[prop_name])
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_duplicated_group_key(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -528,10 +531,9 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_duplicated_group_key_via_personhog(self, mock_capture):
"""Personhog upserts on duplicate so the pre-check must catch it."""
- from posthog.personhog_client.fake_client import fake_personhog_client
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -564,7 +566,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(create_calls), 0, "create_group should not be called for duplicates")
mock_capture.assert_not_called()
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_missing_group_key(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -594,7 +596,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_missing_group_type_index(self, mock_capture):
response = self.client.post(
f"/api/projects/{self.team.id}/groups",
@@ -618,7 +620,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
mock_capture.assert_not_called()
@time_machine.travel("2021-05-02", tick=False)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_group_property_crud_add_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -703,7 +705,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
@time_machine.travel("2021-05-02", tick=False)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_group_property_crud_update_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -784,7 +786,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["before"], "finance")
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_group_property_update_reuses_definition_from_another_environment(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -866,7 +868,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 404)
@time_machine.travel("2021-05-02", tick=False)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_group_property_crud_delete_success(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -1001,7 +1003,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 400)
@time_machine.travel("2021-05-02", tick=False)
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("products.groups.backend.presentation.views.capture_internal")
def test_delete_property_nonexistent_property(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group_type_mapping_without_created_at(
@@ -1046,7 +1048,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 400)
@time_machine.travel("2021-05-02", tick=False)
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("products.groups.backend.presentation.views.capture_internal")
def test_get_group_activities_success(self, mock_capture):
# Mock the response to return a 200 OK
mock_capture.return_value = mock.MagicMock(status_code=200)
@@ -1086,7 +1088,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["action"], "changed")
@time_machine.travel("2021-05-02", tick=False)
- @patch("ee.clickhouse.views.groups.capture_internal")
+ @patch("products.groups.backend.presentation.views.capture_internal")
def test_get_group_activities_invalid_group(self, mock_capture):
# Mock the response to return a 200 OK
mock_capture.return_value = mock.MagicMock(status_code=200)
@@ -1868,11 +1870,6 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
self.assertIsNone(cache.get(stale_cache_key))
def test_update_metadata_non_admin_cannot_modify_protected_fields(self):
- from posthog.constants import AvailableFeature
- from posthog.models.organization import OrganizationMembership
-
- from products.access_control.backend.models.access_control import AccessControl
-
group_type = create_group_type_mapping(
team=self.team, project=self.project, group_type="organization", group_type_index=0
)
@@ -1904,8 +1901,6 @@ class GroupsTypesViewSetTestCase(APIBaseTest):
self.assertIsNone(group_type.name_plural)
def test_update_metadata_admin_can_modify_protected_fields(self):
- from posthog.models.organization import OrganizationMembership
-
group_type = create_group_type_mapping(
team=self.team, project=self.project, group_type="organization", group_type_index=0
)
@@ -2114,11 +2109,6 @@ class GroupUsageMetricViewSetTestCase(APIBaseTest):
self.assertTrue(GroupUsageMetric.objects.filter(id=other_metric.id).exists())
def test_non_admin_cannot_update_metric(self):
- from posthog.constants import AvailableFeature
- from posthog.models.organization import OrganizationMembership
-
- from products.access_control.backend.models.access_control import AccessControl
-
metric = self._create_metric()
url = f"{self.url}/{metric.id}"
self.organization_membership.level = OrganizationMembership.Level.MEMBER
@@ -2142,8 +2132,6 @@ class GroupUsageMetricViewSetTestCase(APIBaseTest):
self.assertEqual(metric.name, "Events")
def test_admin_can_update_metric(self):
- from posthog.models.organization import OrganizationMembership
-
metric = self._create_metric()
url = f"{self.url}/{metric.id}"
self.organization_membership.level = OrganizationMembership.Level.ADMIN
@@ -2156,8 +2144,6 @@ class GroupUsageMetricViewSetTestCase(APIBaseTest):
self.assertEqual(metric.name, "Updated by admin")
def _create_dw_table(self, name: str = "stripe_charges"):
- from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
-
credential = DataWarehouseCredential.objects.create(team=self.team, access_key="key", access_secret="secret")
return DataWarehouseTable.objects.create(
team=self.team,
@@ -2301,7 +2287,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.group_key = "test_company"
self.base_url = f"/api/projects/{self.team.id}/groups/"
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_create_group_creates_property_definitions(self, mock_capture):
data = {
"group_type_index": self.group_type_index,
@@ -2335,7 +2321,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(revenue_prop.property_type, "Numeric")
self.assertTrue(revenue_prop.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_update_property_creates_property_definition(self, mock_capture):
create_group(
team_id=self.team.pk,
@@ -2365,7 +2351,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, "String")
self.assertFalse(prop_def.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_update_property_with_different_types(self, mock_capture):
create_group(
team_id=self.team.pk, group_type_index=self.group_type_index, group_key=self.group_key, properties={}
@@ -2402,7 +2388,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, expected_type)
self.assertEqual(prop_def.is_numerical, expected_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_update_existing_property_definition(self, mock_capture):
create_group(
team_id=self.team.pk, group_type_index=self.group_type_index, group_key=self.group_key, properties={}
@@ -2430,7 +2416,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(prop_def.property_type, "Numeric")
self.assertTrue(prop_def.is_numerical)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_update_property_missing_key(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group(
@@ -2444,7 +2430,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_update_property_empty_key(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
create_group(
@@ -2458,7 +2444,7 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @mock.patch("ee.clickhouse.views.groups.capture_internal")
+ @mock.patch("products.groups.backend.presentation.views.capture_internal")
def test_property_definitions_have_correct_group_type_index(self, mock_capture):
self.group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -2811,7 +2797,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 404
@time_machine.travel("2021-05-02", tick=False)
- @patch("ee.clickhouse.views.groups.list_groups")
+ @patch("products.groups.backend.presentation.views.list_groups")
def test_list_api_has_more_produces_next_url(self, mock_list_groups):
# The viewset turns a has_more result into a forward cursor in the `next` URL.
groups = [
diff --git a/ee/clickhouse/queries/test/test_related_actors_query.py b/products/groups/backend/tests/test_related_actors_query.py
similarity index 99%
rename from ee/clickhouse/queries/test/test_related_actors_query.py
rename to products/groups/backend/tests/test_related_actors_query.py
index 08c69278c1fe..84f04c936c4e 100644
--- a/ee/clickhouse/queries/test/test_related_actors_query.py
+++ b/products/groups/backend/tests/test_related_actors_query.py
@@ -24,7 +24,7 @@ from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group.util import create_group
from posthog.test.persons import create_group_type_mapping
-from ee.clickhouse.queries.related_actors_query import RelatedActorsQuery
+from products.groups.backend.logic.related_actors_query import RelatedActorsQuery
RECENT_DATE = datetime(2025, 2, 15, 12, 0, 0)
diff --git a/products/groups/frontend/generated/api.schemas.ts b/products/groups/frontend/generated/api.schemas.ts
index 8ecb0740057b..4c59994a8390 100644
--- a/products/groups/frontend/generated/api.schemas.ts
+++ b/products/groups/frontend/generated/api.schemas.ts
@@ -170,6 +170,56 @@ export interface GroupUpdatePropertyRequestApi {
value: GroupUpdatePropertyRequestApiValue
}
+export interface GroupTypeApi {
+ readonly group_type: string
+ readonly group_type_index: number
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name_singular?: string | null
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name_plural?: string | null
+ /** @nullable */
+ detail_dashboard?: number | null
+ /** @nullable */
+ default_columns?: string[] | null
+ /** @nullable */
+ created_at?: string | null
+}
+
+export interface GroupTypeCreateDetailDashboardApi {
+ /** Index of the group type that gets the detail dashboard. */
+ group_type_index: number
+}
+
+export interface GroupTypeSetDefaultColumnsApi {
+ /** Index of the group type to update. */
+ group_type_index: number
+ /** Columns that the groups list of this group type shows by default. */
+ default_columns: string[]
+}
+
+export interface GroupTypeMetadataUpdateApi {
+ /** Index of the group type to update. */
+ group_type_index: number
+ /**
+ * Singular display name of the group type.
+ * @maxLength 400
+ * @nullable
+ */
+ name_singular?: string | null
+ /**
+ * Plural display name of the group type.
+ * @maxLength 400
+ * @nullable
+ */
+ name_plural?: string | null
+}
+
export type GroupsListParams = {
/**
* Pagination cursor returned in the `next` URL of a previous response
diff --git a/products/groups/frontend/generated/api.ts b/products/groups/frontend/generated/api.ts
index 438a74946a04..c886a686e0a2 100644
--- a/products/groups/frontend/generated/api.ts
+++ b/products/groups/frontend/generated/api.ts
@@ -13,6 +13,10 @@ import type {
FindGroupApi,
GroupApi,
GroupDeletePropertyApi,
+ GroupTypeApi,
+ GroupTypeCreateDetailDashboardApi,
+ GroupTypeMetadataUpdateApi,
+ GroupTypeSetDefaultColumnsApi,
GroupUpdatePropertyRequestApi,
GroupsActivityRetrieveParams,
GroupsDeletePropertyCreateParams,
@@ -225,3 +229,80 @@ export const groupsUpdatePropertyCreate = async (
body: JSON.stringify(groupUpdatePropertyRequestApi),
})
}
+
+export const getGroupsTypesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/groups_types/`
+}
+
+export const groupsTypesList = async (projectId: string, options?: RequestInit): Promise<GroupTypeApi[]> => {
+ return apiMutator<GroupTypeApi[]>(getGroupsTypesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getGroupsTypesDestroyUrl = (projectId: string, groupTypeIndex: number) => {
+ return `/api/projects/${projectId}/groups_types/${groupTypeIndex}/`
+}
+
+export const groupsTypesDestroy = async (
+ projectId: string,
+ groupTypeIndex: number,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getGroupsTypesDestroyUrl(projectId, groupTypeIndex), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getGroupsTypesCreateDetailDashboardUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/groups_types/create_detail_dashboard/`
+}
+
+export const groupsTypesCreateDetailDashboardUpdate = async (
+ projectId: string,
+ groupTypeCreateDetailDashboardApi: GroupTypeCreateDetailDashboardApi,
+ options?: RequestInit
+): Promise<GroupTypeApi> => {
+ return apiMutator<GroupTypeApi>(getGroupsTypesCreateDetailDashboardUpdateUrl(projectId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(groupTypeCreateDetailDashboardApi),
+ })
+}
+
+export const getGroupsTypesSetDefaultColumnsUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/groups_types/set_default_columns/`
+}
+
+export const groupsTypesSetDefaultColumnsUpdate = async (
+ projectId: string,
+ groupTypeSetDefaultColumnsApi: GroupTypeSetDefaultColumnsApi,
+ options?: RequestInit
+): Promise<GroupTypeApi> => {
+ return apiMutator<GroupTypeApi>(getGroupsTypesSetDefaultColumnsUpdateUrl(projectId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(groupTypeSetDefaultColumnsApi),
+ })
+}
+
+export const getGroupsTypesUpdateMetadataPartialUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/groups_types/update_metadata/`
+}
+
+export const groupsTypesUpdateMetadataPartialUpdate = async (
+ projectId: string,
+ groupTypeMetadataUpdateApi: GroupTypeMetadataUpdateApi[],
+ options?: RequestInit
+): Promise<GroupTypeApi[]> => {
+ return apiMutator<GroupTypeApi[]>(getGroupsTypesUpdateMetadataPartialUpdateUrl(projectId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(groupTypeMetadataUpdateApi),
+ })
+}
diff --git a/products/groups/frontend/generated/api.zod.ts b/products/groups/frontend/generated/api.zod.ts
index c2863b14e608..383d01c07b52 100644
--- a/products/groups/frontend/generated/api.zod.ts
+++ b/products/groups/frontend/generated/api.zod.ts
@@ -30,3 +30,35 @@ export const GroupsUpdatePropertyCreateBody = /* @__PURE__ */ zod.object({
.union([zod.string(), zod.number(), zod.boolean(), zod.looseObject({}), zod.array(zod.unknown())])
.describe('Value to set. Any JSON value other than null.'),
})
+
+export const GroupsTypesCreateDetailDashboardUpdateBody = /* @__PURE__ */ zod.object({
+ group_type_index: zod.number().describe('Index of the group type that gets the detail dashboard.'),
+})
+
+export const GroupsTypesSetDefaultColumnsUpdateBody = /* @__PURE__ */ zod.object({
+ group_type_index: zod.number().describe('Index of the group type to update.'),
+ default_columns: zod
+ .array(zod.string())
+ .describe('Columns that the groups list of this group type shows by default.'),
+})
+
+export const groupsTypesUpdateMetadataPartialUpdateBodyNameSingularMax = 400
+
+export const groupsTypesUpdateMetadataPartialUpdateBodyNamePluralMax = 400
+
+export const GroupsTypesUpdateMetadataPartialUpdateBodyItem = /* @__PURE__ */ zod.object({
+ group_type_index: zod.number().describe('Index of the group type to update.'),
+ name_singular: zod
+ .string()
+ .max(groupsTypesUpdateMetadataPartialUpdateBodyNameSingularMax)
+ .nullish()
+ .describe('Singular display name of the group type.'),
+ name_plural: zod
+ .string()
+ .max(groupsTypesUpdateMetadataPartialUpdateBodyNamePluralMax)
+ .nullish()
+ .describe('Plural display name of the group type.'),
+})
+export const GroupsTypesUpdateMetadataPartialUpdateBody = /* @__PURE__ */ zod.array(
+ GroupsTypesUpdateMetadataPartialUpdateBodyItem
+)
diff --git a/products/groups/package.json b/products/groups/package.json
index b640de4638c5..c95f9cf816db 100644
--- a/products/groups/package.json
+++ b/products/groups/package.json
@@ -1,5 +1,9 @@
{
"name": "@posthog/products-groups",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ },
"dependencies": {
"kea": "catalog:",
"kea-forms": "catalog:",
diff --git a/products/groups/product.yaml b/products/groups/product.yaml
new file mode 100644
index 000000000000..c9b49f7acd1d
--- /dev/null
+++ b/products/groups/product.yaml
@@ -0,0 +1,3 @@
+name: Groups
+owners:
+ - team-product-analytics
diff --git a/products/groups/tsconfig.json b/products/groups/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/groups/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/groups/turbo.json b/products/groups/turbo.json
new file mode 100644
index 000000000000..2f891fa60904
--- /dev/null
+++ b/products/groups/turbo.json
@@ -0,0 +1,16 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/models.py",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d80cad7eb7c2..c4755874963e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53905,6 +53905,35 @@ export namespace Schemas {
created_at?: string | null;
}
+ export interface GroupTypeCreateDetailDashboard {
+ /** Index of the group type that gets the detail dashboard. */
+ group_type_index: number;
+ }
+
+ export interface GroupTypeMetadataUpdate {
+ /** Index of the group type to update. */
+ group_type_index: number;
+ /**
+ * Singular display name of the group type.
+ * @maxLength 400
+ * @nullable
+ */
+ name_singular?: string | null;
+ /**
+ * Plural display name of the group type.
+ * @maxLength 400
+ * @nullable
+ */
+ name_plural?: string | null;
+ }
+
+ export interface GroupTypeSetDefaultColumns {
+ /** Index of the group type to update. */
+ group_type_index: number;
+ /** Columns that the groups list of this group type shows by default. */
+ default_columns: string[];
+ }
+
/**
* Value to set. Any JSON value other than null.
*/
@@ -80828,27 +80857,6 @@ export namespace Schemas {
readonly user_access_level?: string | null;
}
- export interface PatchedGroupType {
- readonly group_type?: string;
- readonly group_type_index?: number;
- /**
- * @maxLength 400
- * @nullable
- */
- name_singular?: string | null;
- /**
- * @maxLength 400
- * @nullable
- */
- name_plural?: string | null;
- /** @nullable */
- detail_dashboard?: number | null;
- /** @nullable */
- default_columns?: string[] | null;
- /** @nullable */
- created_at?: string | null;
- }
-
/**
* Filter definition for the metric. Two shapes are accepted, discriminated by an optional `source` key.
*
diff --git a/tach.toml b/tach.toml
index dda7e99cf869..0dc2532cc36c 100644
--- a/tach.toml
+++ b/tach.toml
@@ -331,7 +331,13 @@ layer = "modules"
[[modules]]
path = "products.groups"
-depends_on = []
+depends_on = [
+ "posthog",
+ "products.access_control",
+ "products.event_definitions",
+ "products.notebooks",
+ "products.warehouse_sources",
+]
layer = "modules"
[[modules]]
@@ -1113,7 +1119,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|visual_review|warehouse_sources|workflows)",
+ "products\\.(autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|groups|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|visual_review|warehouse_sources|workflows)",
]
# TODO: Experiments-specific temporary interface