Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): add custom property definitions CRUD (#64929)

Arthur Moreira de Deus7e25d6ac30fd
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 802dc0c55763..670047889cbd 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -90,6 +90,7 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomPropertyDefinition
|DAG
|Dashboard
|DashboardTemplate
@@ -354,6 +355,7 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomPropertyDefinition
|DAG
|Dashboard
|DashboardTemplate
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 16978164a7fb..8e2e2d682b2c 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -513,6 +513,7 @@ SPECTACULAR_SETTINGS = {
"HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"PropertyGroupOperator": ["AND", "OR"],
+ "CustomPropertyDisplayTypeEnum": ["text", "number", "currency", "percent", "date", "datetime", "boolean"],
# Experiment now has two serializers (full ExperimentSerializer + ExperimentBasicSerializer
# for the list endpoint) that both expose `type`/`status`. Pin both to their pre-existing
# generated names so the shared enums don't get component-prefixed auto-names on collision.
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index 4db34f9f429d..4b3a80e6a350 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -13,3 +13,5 @@ ACCOUNT_ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")
# in environments where the billing warehouse data exists; elsewhere the agent's lookup falls back.
BILLING_USAGE_INSIGHT_SHORT_IDS = ["fiJDsKLp"]
BILLING_SPEND_INSIGHT_SHORT_IDS = ["o4I9sdFE", "Tjo4bsux"]
+
+CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES = ["text", "number", "currency", "percent", "date", "datetime", "boolean"]
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 7e4c507ed99b..34dba640ea9f 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -32,10 +32,16 @@ from posthog.models.tagged_item import TaggedItem
from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink
from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDS
+from products.customer_analytics.backend.logic.custom_property_definitions import coerce_is_big_number
from products.customer_analytics.backend.logic.usage_spike_notifications import (
notify_managers_of_usage_spike as notify_managers_of_usage_spike,
)
-from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
+from products.customer_analytics.backend.models import (
+ Account,
+ CustomerJourney,
+ CustomerProfileConfig,
+ CustomPropertyDefinition,
+)
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
from products.notebooks.backend.facade import (
api as notebooks,
@@ -371,6 +377,10 @@ class CustomerJourneyConflictError(Exception):
"""Raised when a customer journey already exists for the given insight (per team)."""
+class CustomPropertyDefinitionConflictError(Exception):
+ """Raised when a custom property definition violates the per-team unique name constraint."""
+
+
class ResourceForbiddenError(Exception):
"""Raised when the caller passes resource/object access checks at the team level but
lacks the object-level access required for the action — the view maps this to 403,
@@ -584,6 +594,138 @@ def delete_customer_profile_config(
return True
+# --- CustomPropertyDefinition ---
+
+
+def _to_custom_property_definition_view(
+ definition: CustomPropertyDefinition,
+) -> contracts.CustomPropertyDefinitionView:
+ return contracts.CustomPropertyDefinitionView(
+ id=definition.id,
+ name=definition.name,
+ description=definition.description,
+ display_type=definition.display_type,
+ is_big_number=definition.is_big_number,
+ created_at=definition.created_at,
+ created_by=definition.created_by_id,
+ updated_at=definition.updated_at,
+ )
+
+
+def list_custom_property_definitions(
+ team_id: int, offset: int, limit: int
+) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
+ """Custom property definitions for the team, ordered by name. Returns ``(page, total_count)``."""
+ queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).order_by("name")
+ total_count = queryset.count()
+ page = queryset[offset : offset + limit]
+ return [_to_custom_property_definition_view(d) for d in page], total_count
+
+
+def get_custom_property_definition(team_id: int, definition_id: str) -> contracts.CustomPropertyDefinitionView | None:
+ definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ return _to_custom_property_definition_view(definition) if definition is not None else None
+
+
+def create_custom_property_definition(
+ *,
+ team_id: int,
+ name: str,
+ description: str | None,
+ display_type: str,
+ is_big_number: bool,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomPropertyDefinitionView:
+ try:
+ definition = CustomPropertyDefinition.objects.create(
+ team_id=team_id,
+ created_by=user,
+ name=name,
+ description=description,
+ display_type=display_type,
+ is_big_number=coerce_is_big_number(display_type, is_big_number),
+ )
+ except IntegrityError:
+ raise CustomPropertyDefinitionConflictError("A custom property with this name already exists for this team.")
+ _log_activity_swallowing(
+ instance=definition,
+ scope="CustomPropertyDefinition",
+ activity="created",
+ name=definition.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ return _to_custom_property_definition_view(definition)
+
+
+def update_custom_property_definition(
+ *,
+ team_id: int,
+ definition_id: str,
+ fields: dict[str, Any],
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.CustomPropertyDefinitionView | None:
+ """Apply ``fields`` (only the keys the caller sent) to a team-scoped definition. Returns the
+ updated view, or None when no definition matches the id for this team (→ 404)."""
+ definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ if definition is None:
+ return None
+ previous = CustomPropertyDefinition.objects.get(pk=definition.pk)
+ for attr, value in fields.items():
+ setattr(definition, attr, value)
+ # Re-coerce against the effective display type: a PATCH that only flips the type to a
+ # non-numeric one must clear a previously-set is_big_number (the partial-update case).
+ definition.is_big_number = coerce_is_big_number(definition.display_type, definition.is_big_number)
+ try:
+ definition.save()
+ except IntegrityError:
+ raise CustomPropertyDefinitionConflictError("A custom property with this name already exists for this team.")
+ _log_activity_swallowing(
+ instance=definition,
+ scope="CustomPropertyDefinition",
+ activity="updated",
+ name=definition.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ previous=previous,
+ )
+ return _to_custom_property_definition_view(definition)
+
+
+def delete_custom_property_definition(
+ *,
+ team_id: int,
+ definition_id: str,
+ organization_id,
+ user: "User",
+ was_impersonated: bool,
+) -> bool:
+ """Delete a team-scoped definition. Returns False when none matched (→ 404)."""
+ definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ if definition is None:
+ return False
+ _log_activity_swallowing(
+ instance=definition,
+ scope="CustomPropertyDefinition",
+ activity="deleted",
+ name=definition.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+ definition.delete()
+ return True
+
+
# --- CustomerJourney ---
diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.py
index b1b2e7891797..cb4efa592080 100644
--- a/products/customer_analytics/backend/facade/constants.py
+++ b/products/customer_analytics/backend/facade/constants.py
@@ -9,6 +9,7 @@ from products.customer_analytics.backend.constants import (
ACCOUNT_ASSIGNMENT_ROLE_FIELDS,
BILLING_SPEND_INSIGHT_SHORT_IDS,
BILLING_USAGE_INSIGHT_SHORT_IDS,
+ CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,
CUSTOMER_ANALYTICS_CSP_FLAG,
DEFAULT_ACTIVITY_EVENT,
)
@@ -17,6 +18,7 @@ __all__ = [
"ACCOUNT_ASSIGNMENT_ROLE_FIELDS",
"BILLING_SPEND_INSIGHT_SHORT_IDS",
"BILLING_USAGE_INSIGHT_SHORT_IDS",
+ "CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES",
"CUSTOMER_ANALYTICS_CSP_FLAG",
"DEFAULT_ACTIVITY_EVENT",
]
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 6a70d2149047..6689ab7bad02 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -238,6 +238,26 @@ class CustomerProfileConfigView:
updated_at: datetime | None = None
+@stdlib_dataclass(frozen=True)
+class CustomPropertyDefinitionView:
+ """A team-scoped custom account-property definition as returned by the
+ custom-property-definitions endpoints.
+
+ Defaults exist so the wrapping serializer can parse partial request bodies (see
+ :class:`AccountView`). ``created_by`` is the creator's user id (or ``None``), matching
+ the old model serializer's ``PrimaryKeyRelatedField`` output.
+ """
+
+ id: UUID | None = None
+ name: str = ""
+ description: str | None = None
+ display_type: str = "text"
+ is_big_number: bool = False
+ created_at: datetime | None = None
+ created_by: int | None = None
+ updated_at: datetime | None = None
+
+
@stdlib_dataclass(frozen=True)
class AccountNotebookView:
"""An account notebook as returned by the nested account-notebooks endpoints.
diff --git a/products/customer_analytics/backend/logic/custom_property_definitions.py b/products/customer_analytics/backend/logic/custom_property_definitions.py
new file mode 100644
index 000000000000..752c0cfe2505
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_definitions.py
@@ -0,0 +1,12 @@
+"""Validation rules for custom account-property definitions, shared by the facade write paths."""
+
+from products.customer_analytics.backend.models import DATA_TYPE_BY_DISPLAY_TYPE, DataType, DisplayType
+
+
+def coerce_is_big_number(display_type: str, is_big_number: bool) -> bool:
+ """``is_big_number`` only applies to numeric display types; force it false otherwise.
+
+ A one-way coercion (never rejects) that create and update apply so the flag can't be set on a
+ non-numeric property.
+ """
+ return is_big_number and DATA_TYPE_BY_DISPLAY_TYPE[DisplayType(display_type)] == DataType.NUMERIC
diff --git a/products/customer_analytics/backend/migrations/0007_custom_property_definition.py b/products/customer_analytics/backend/migrations/0007_custom_property_definition.py
new file mode 100644
index 000000000000..fd283deba163
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0007_custom_property_definition.py
@@ -0,0 +1,85 @@
+# Generated by Django 5.2.14 on 2026-06-18 14:42
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0006_migrate_product_analytics_models"),
+ ("posthog", "1226_identityproviderconfig_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomPropertyDefinition",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(null=True)),
+ (
+ "display_type",
+ models.CharField(
+ choices=[
+ ("text", "text"),
+ ("number", "number"),
+ ("currency", "currency"),
+ ("percent", "percent"),
+ ("date", "date"),
+ ("datetime", "datetime"),
+ ("boolean", "boolean"),
+ ],
+ default="text",
+ max_length=20,
+ ),
+ ),
+ (
+ "is_big_number",
+ models.BooleanField(
+ default=False,
+ help_text="Whether the property is a big number and should be abbreviated. E.g.: 10,000 -> 10K",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(fields=("team", "name"), name="unique_custom_property_per_team"),
+ models.CheckConstraint(
+ condition=models.Q(
+ ("is_big_number", False),
+ ("display_type__in", ["number", "currency", "percent"]),
+ _connector="OR",
+ ),
+ name="is_big_number_requires_numeric_display_type",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 02613e949737..8ea4f6e23ae0 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_migrate_product_analytics_models
+0007_custom_property_definition
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 69170b49a50a..73d1ea6547ec 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -1,11 +1,16 @@
from .account import Account
+from .custom_property_definition import DATA_TYPE_BY_DISPLAY_TYPE, CustomPropertyDefinition, DataType, DisplayType
from .customer_journey import CustomerJourney
from .customer_profile_config import CustomerProfileConfig
from .team_customer_analytics_config import TeamCustomerAnalyticsConfig
__all__ = [
+ "DATA_TYPE_BY_DISPLAY_TYPE",
"Account",
+ "CustomPropertyDefinition",
"CustomerJourney",
"CustomerProfileConfig",
+ "DataType",
+ "DisplayType",
"TeamCustomerAnalyticsConfig",
]
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
new file mode 100644
index 000000000000..de99a5396138
--- /dev/null
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -0,0 +1,67 @@
+from enum import StrEnum
+
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+
+class DisplayType(StrEnum):
+ TEXT = "text"
+ NUMBER = "number"
+ CURRENCY = "currency"
+ PERCENT = "percent"
+ DATE = "date"
+ DATETIME = "datetime"
+ BOOLEAN = "boolean"
+
+
+class DataType(StrEnum):
+ STRING = "string"
+ NUMERIC = "numeric"
+ BOOLEAN = "boolean"
+ DATETIME = "datetime"
+
+
+DATA_TYPE_BY_DISPLAY_TYPE: dict[DisplayType, DataType] = {
+ DisplayType.TEXT: DataType.STRING,
+ DisplayType.NUMBER: DataType.NUMERIC,
+ DisplayType.CURRENCY: DataType.NUMERIC,
+ DisplayType.PERCENT: DataType.NUMERIC,
+ DisplayType.DATE: DataType.DATETIME,
+ DisplayType.DATETIME: DataType.DATETIME,
+ DisplayType.BOOLEAN: DataType.BOOLEAN,
+}
+
+NUMERIC_DISPLAY_TYPES = [
+ display_type.value for display_type, data_type in DATA_TYPE_BY_DISPLAY_TYPE.items() if data_type == DataType.NUMERIC
+]
+
+
+class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+
+ name = models.CharField(max_length=400)
+ description = models.TextField(null=True)
+ display_type = models.CharField(
+ choices=[(t.value, t.value) for t in DisplayType], default=DisplayType.TEXT, max_length=20
+ )
+ is_big_number = models.BooleanField(
+ default=False, help_text="Whether the property is a big number and should be abbreviated. E.g.: 10,000 -> 10K"
+ )
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "name"],
+ name="unique_custom_property_per_team",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(is_big_number=False) | models.Q(display_type__in=NUMERIC_DISPLAY_TYPES),
+ name="is_big_number_requires_numeric_display_type",
+ ),
+ ]
+
+ @property
+ def data_type(self) -> DataType:
+ return DATA_TYPE_BY_DISPLAY_TYPE[DisplayType(self.display_type)]
diff --git a/products/customer_analytics/backend/models/custom_property_definition_test.py b/products/customer_analytics/backend/models/custom_property_definition_test.py
new file mode 100644
index 000000000000..fda3e6e0c4bb
--- /dev/null
+++ b/products/customer_analytics/backend/models/custom_property_definition_test.py
@@ -0,0 +1,27 @@
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError, transaction
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.models import CustomPropertyDefinition
+
+
+class TestCustomPropertyDefinitionConstraints(BaseTest):
+ # The facade coerces is_big_number to false for non-numeric types; these assert the DB CHECK
+ # constraint holds the same invariant for writers that bypass the facade (direct ORM, admin).
+ @parameterized.expand(["text", "date", "datetime", "boolean"])
+ def test_big_number_rejected_for_non_numeric_display_type(self, display_type):
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (test exercises the DB constraint directly)
+ CustomPropertyDefinition.objects.unscoped().create(
+ team=self.team, name=f"bad-{display_type}", display_type=display_type, is_big_number=True
+ )
+
+ @parameterized.expand(["number", "currency", "percent"])
+ def test_big_number_allowed_for_numeric_display_type(self, display_type):
+ # nosemgrep: idor-lookup-without-team (test exercises the DB constraint directly)
+ definition = CustomPropertyDefinition.objects.unscoped().create(
+ team=self.team, name=f"ok-{display_type}", display_type=display_type, is_big_number=True
+ )
+ self.assertTrue(definition.is_big_number)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 9ae907ad61aa..7500f53b072e 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -27,11 +27,13 @@ from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.shared import UserBasicSerializer
from posthog.models import OrganizationMembership
+from products.customer_analytics.backend.facade.constants import CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES
from products.customer_analytics.backend.facade.contracts import (
AccountNotebookView,
AccountView,
CustomerJourneyView,
CustomerProfileConfigView,
+ CustomPropertyDefinitionView,
)
# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared
@@ -261,3 +263,55 @@ class AccountNotebookSerializer(DataclassSerializer):
"last_modified_at",
"last_modified_by",
]
+
+
+class CustomPropertyDefinitionSerializer(DataclassSerializer):
+ """A team-scoped definition of a custom account property — the attribute side of the model.
+
+ Holds only the property's shape (name, display type, big-number flag). Per-account values are
+ stored separately, so this serializer never reads or writes account values. The numeric-only
+ big-number rule and the unique-name conflict are enforced behind the facade.
+ """
+
+ id = serializers.UUIDField(read_only=True)
+ name = serializers.CharField(
+ max_length=400,
+ help_text="Human-readable name of the custom property. Unique within the team.",
+ )
+ description = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Optional description of what the property represents.",
+ )
+ display_type = serializers.ChoiceField(
+ choices=CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,
+ help_text=(
+ "How the property is interpreted and rendered: 'text', 'number', 'currency', "
+ "'percent', 'date', 'datetime', or 'boolean'."
+ ),
+ )
+ is_big_number = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.",
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ created_by = serializers.IntegerField(read_only=True, allow_null=True)
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
+
+ class Meta:
+ dataclass = CustomPropertyDefinitionView
+ # Pin the OpenAPI component name to the pre-isolation one (DataclassSerializer would
+ # otherwise name it after the wrapped dataclass, ``CustomPropertyDefinitionView``).
+ ref_name = "CustomPropertyDefinition"
+ fields = [
+ "id",
+ "name",
+ "description",
+ "display_type",
+ "is_big_number",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 16a28e65b21a..7c8c8e0a962e 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -36,6 +36,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
AccountSerializer,
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
+ CustomPropertyDefinitionSerializer,
)
from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes
@@ -178,6 +179,104 @@ def _profile_config_write_fields(validated, raw_data: dict) -> dict:
return fields
+class CustomPropertyDefinitionViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ scope_object = "account"
+ serializer_class = CustomPropertyDefinitionSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_custom_property_definitions(self.team_id, offset=offset, limit=limit),
+ CustomPropertyDefinitionSerializer,
+ )
+
+ def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ definition = api.get_custom_property_definition(self.team_id, self.kwargs["pk"])
+ if definition is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomPropertyDefinitionSerializer(instance=definition).data)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = CustomPropertyDefinitionSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ try:
+ definition = api.create_custom_property_definition(
+ team_id=self.team_id,
+ name=data.name,
+ description=data.description,
+ display_type=data.display_type,
+ is_big_number=data.is_big_number,
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.CustomPropertyDefinitionConflictError as e:
+ raise Conflict(str(e))
+ return Response(CustomPropertyDefinitionSerializer(instance=definition).data, status=status.HTTP_201_CREATED)
+
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ partial = kwargs.pop("partial", False)
+ serializer = CustomPropertyDefinitionSerializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ try:
+ definition = api.update_custom_property_definition(
+ team_id=self.team_id,
+ definition_id=self.kwargs["pk"],
+ fields=_custom_property_definition_write_fields(serializer.validated_data, request.data),
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.CustomPropertyDefinitionConflictError as e:
+ raise Conflict(str(e))
+ if definition is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomPropertyDefinitionSerializer(instance=definition).data)
+
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
+
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ deleted = api.delete_custom_property_definition(
+ team_id=self.team_id,
+ definition_id=self.kwargs["pk"],
+ organization_id=self.organization.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ if not deleted:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+def _custom_property_definition_write_fields(validated, raw_data: dict) -> dict:
+ """The columns the caller actually sent. ``is_big_number`` is re-derived in the facade against
+ the effective display type, so a PATCH that omits it still clears it for a non-numeric type."""
+ fields: dict = {}
+ if "name" in raw_data:
+ fields["name"] = validated.name
+ if "description" in raw_data:
+ fields["description"] = validated.description
+ if "display_type" in raw_data:
+ fields["display_type"] = validated.display_type
+ if "is_big_number" in raw_data:
+ fields["is_big_number"] = validated.is_big_number
+ return fields
+
+
class CustomerJourneyViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index bf2ecdeff307..b72eb4d4bd7e 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -8,6 +8,7 @@ from products.customer_analytics.backend.presentation.views.views import (
AccountViewSet,
CustomerJourneyViewSet,
CustomerProfileConfigViewSet,
+ CustomPropertyDefinitionViewSet,
)
@@ -27,6 +28,12 @@ def register_routes(routers: RouterRegistry) -> None:
routers.register_legacy_dual_route(
r"customer_journeys", CustomerJourneyViewSet, "project_customer_journeys", ["team_id"]
)
+ routers.register_legacy_dual_route(
+ r"custom_property_definitions",
+ CustomPropertyDefinitionViewSet,
+ "project_custom_property_definitions",
+ ["team_id"],
+ )
project_accounts_router, environment_accounts_router = routers.register_legacy_dual_route(
r"accounts", AccountViewSet, "project_accounts", ["team_id"]
)
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index eb83a9410be2..4c023eae445a 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -12,7 +12,12 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
-from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
+from products.customer_analytics.backend.models import (
+ Account,
+ CustomerJourney,
+ CustomerProfileConfig,
+ CustomPropertyDefinition,
+)
from products.customer_analytics.backend.models.account import AccountAssignment
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.models.insight import Insight
@@ -1485,3 +1490,237 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
create_response = self.client.post(url, {"title": "x"}, format="json")
self.assertEqual(create_response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class TestCustomPropertyDefinitionViewSet(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.endpoint_base = f"/api/environments/{self.team.id}/custom_property_definitions/"
+
+ def _create(self, **overrides):
+ payload = {"name": "ARR", "display_type": "currency", "is_big_number": True}
+ payload.update(overrides)
+ return self.client.post(self.endpoint_base, payload, format="json")
+
+ def test_create_success(self):
+ response = self._create()
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ data = response.json()
+ self.assertEqual(data["name"], "ARR")
+ self.assertEqual(data["display_type"], "currency")
+ self.assertTrue(data["is_big_number"])
+ self.assertIn("id", data)
+ self.assertIn("created_at", data)
+
+ # nosemgrep: idor-lookup-without-team (test assertion)
+ definition = CustomPropertyDefinition.objects.unscoped().get(id=data["id"])
+ self.assertEqual(definition.team, self.team)
+ self.assertEqual(definition.created_by, self.user)
+
+ def test_create_text_property(self):
+ response = self._create(name="Tier", display_type="text", is_big_number=False)
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ self.assertEqual(response.json()["display_type"], "text")
+
+ @parameterized.expand(
+ [
+ ("text", "text", status.HTTP_201_CREATED),
+ ("number", "number", status.HTTP_201_CREATED),
+ ("currency", "currency", status.HTTP_201_CREATED),
+ ("percent", "percent", status.HTTP_201_CREATED),
+ ("date", "date", status.HTTP_201_CREATED),
+ ("datetime", "datetime", status.HTTP_201_CREATED),
+ ("boolean", "boolean", status.HTTP_201_CREATED),
+ ("unknown_rejected", "frobnicate", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_display_type_validation(self, _name, display_type, expected_status):
+ response = self.client.post(self.endpoint_base, {"name": "P", "display_type": display_type}, format="json")
+ self.assertEqual(expected_status, response.status_code, response.json())
+
+ def test_is_big_number_forced_false_for_non_numeric(self):
+ response = self._create(name="Tier", display_type="text", is_big_number=True)
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ self.assertFalse(response.json()["is_big_number"])
+
+ def test_create_with_duplicate_name_returns_409(self):
+ self._create(name="ARR")
+
+ response = self._create(name="ARR")
+
+ self.assertEqual(status.HTTP_409_CONFLICT, response.status_code, response.json())
+
+ def test_list_returns_only_current_team_ordered_by_name(self):
+ self._create(name="Beta", display_type="text")
+ self._create(name="Alpha", display_type="text")
+ other_team = Team.objects.create(organization=self.organization)
+ # nosemgrep: idor-lookup-without-team (test setup for another team)
+ CustomPropertyDefinition.objects.unscoped().create(team=other_team, name="Gamma", display_type="text")
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual([row["name"] for row in response.json()["results"]], ["Alpha", "Beta"])
+
+ def test_update_name(self):
+ created = self._create(name="ARR").json()
+
+ response = self.client.patch(f"{self.endpoint_base}{created['id']}/", {"name": "Annual revenue"}, format="json")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["name"], "Annual revenue")
+
+ def test_update_to_duplicate_name_returns_409(self):
+ self._create(name="ARR")
+ other = self._create(name="MRR").json()
+
+ response = self.client.patch(f"{self.endpoint_base}{other['id']}/", {"name": "ARR"}, format="json")
+
+ self.assertEqual(status.HTTP_409_CONFLICT, response.status_code, response.json())
+
+ def test_display_type_is_editable(self):
+ created = self._create(name="Field", display_type="text").json()
+
+ response = self.client.patch(
+ f"{self.endpoint_base}{created['id']}/",
+ {"name": "Field", "display_type": "number", "is_big_number": False},
+ format="json",
+ )
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["display_type"], "number")
+
+ def test_patch_display_type_without_other_fields(self):
+ created = self._create(name="Field", display_type="currency").json()
+
+ response = self.client.patch(f"{self.endpoint_base}{created['id']}/", {"display_type": "text"}, format="json")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["display_type"], "text")
+
+ def test_delete_removes_definition_only(self):
+ keep = self._create(name="Keep", display_type="text").json()
+ remove = self._create(name="Remove", display_type="text").json()
+
+ response = self.client.delete(f"{self.endpoint_base}{remove['id']}/")
+
+ self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
+ # nosemgrep: idor-lookup-without-team (test assertion)
+ self.assertFalse(CustomPropertyDefinition.objects.unscoped().filter(id=remove["id"]).exists())
+ # nosemgrep: idor-lookup-without-team (test assertion)
+ self.assertTrue(CustomPropertyDefinition.objects.unscoped().filter(id=keep["id"]).exists())
+
+ def test_cannot_access_other_teams_definition(self):
+ other_team = Team.objects.create(organization=self.organization)
+ # nosemgrep: idor-lookup-without-team (test setup for another team)
+ other_def = CustomPropertyDefinition.objects.unscoped().create(
+ team=other_team, name="Other", display_type="text"
+ )
+
+ response = self.client.get(f"{self.endpoint_base}{other_def.id}/")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_activity_log_on_create_and_delete(self):
+ created = self._create(name="ARR").json()
+ self.client.delete(f"{self.endpoint_base}{created['id']}/")
+
+ logs = ActivityLog.objects.filter(
+ team_id=self.team.id, scope="CustomPropertyDefinition", item_id=str(created["id"])
+ )
+ self.assertEqual(set(logs.values_list("activity", flat=True)), {"created", "deleted"})
+
+
+class TestCustomPropertyDefinitionAccessControl(APIBaseTest):
+ """Resource-level access control for custom property definitions.
+
+ Definitions are a team-wide ``account``-resource config (no per-object ownership), so they are
+ gated at the resource level by the default ``AccessControlPermission`` (keyed on
+ ``scope_object="account"``) — the same gate as accounts and journeys, including inheritance from
+ the ``customer_analytics`` parent resource. Reads need ``viewer``, writes need ``editor``.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ self.viewer_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.editor_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.no_access_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+
+ # nosemgrep: idor-lookup-without-team (test setup)
+ self.definition = CustomPropertyDefinition.objects.unscoped().create(
+ team=self.team, name="ARR", display_type="currency"
+ )
+ self.endpoint_base = f"/api/environments/{self.team.id}/custom_property_definitions/"
+
+ def _set_access_level(self, user: User, resource: str = "customer_analytics", access_level: str = "viewer") -> None:
+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=None,
+ access_level=access_level,
+ organization_member=membership,
+ )
+
+ def test_viewer_can_list(self):
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ self.assertEqual(self.client.get(self.endpoint_base).status_code, status.HTTP_200_OK)
+
+ def test_viewer_can_retrieve(self):
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ response = self.client.get(f"{self.endpoint_base}{self.definition.id}/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_viewer_cannot_create(self):
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ response = self.client.post(self.endpoint_base, {"name": "New", "display_type": "text"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_viewer_cannot_update(self):
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ response = self.client.patch(f"{self.endpoint_base}{self.definition.id}/", {"name": "x"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_viewer_cannot_delete(self):
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+ response = self.client.delete(f"{self.endpoint_base}{self.definition.id}/")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_editor_can_create(self):
+ self._set_access_level(self.editor_user, access_level="editor")
+ self.client.force_login(self.editor_user)
+ response = self.client.post(self.endpoint_base, {"name": "Editor Prop", "display_type": "text"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ def test_editor_can_delete(self):
+ self._set_access_level(self.editor_user, access_level="editor")
+ self.client.force_login(self.editor_user)
+ response = self.client.delete(f"{self.endpoint_base}{self.definition.id}/")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ def test_none_access_blocks_list(self):
+ self._set_access_level(self.no_access_user, access_level="none")
+ self.client.force_login(self.no_access_user)
+ self.assertEqual(self.client.get(self.endpoint_base).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_org_admin_has_full_access(self):
+ membership = OrganizationMembership.objects.get(user=self.editor_user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.ADMIN
+ membership.save()
+ self.client.force_login(self.editor_user)
+ response = self.client.post(self.endpoint_base, {"name": "Admin Prop", "display_type": "text"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index b1a47df923ba..61a9280e2d5f 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -238,6 +238,113 @@ export interface PatchedAccountApi {
readonly updated_at?: string | null
}
+/**
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean
+ */
+export type CustomPropertyDisplayTypeEnumApi =
+ (typeof CustomPropertyDisplayTypeEnumApi)[keyof typeof CustomPropertyDisplayTypeEnumApi]
+
+export const CustomPropertyDisplayTypeEnumApi = {
+ Text: 'text',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+} as const
+
+/**
+ * A team-scoped definition of a custom account property — the attribute side of the model.
+ *
+ * Holds only the property's shape (name, display type, big-number flag). Per-account values are
+ * stored separately, so this serializer never reads or writes account values. The numeric-only
+ * big-number rule and the unique-name conflict are enforced behind the facade.
+ */
+export interface CustomPropertyDefinitionApi {
+ readonly id: string
+ /**
+ * Human-readable name of the custom property. Unique within the team.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * Optional description of what the property represents.
+ * @nullable
+ */
+ description?: string | null
+ /** How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.
+ *
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean */
+ display_type: CustomPropertyDisplayTypeEnumApi
+ /** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
+ is_big_number?: boolean
+ readonly created_at: string
+ /** @nullable */
+ readonly created_by: number | null
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedCustomPropertyDefinitionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: CustomPropertyDefinitionApi[]
+}
+
+/**
+ * A team-scoped definition of a custom account property — the attribute side of the model.
+ *
+ * Holds only the property's shape (name, display type, big-number flag). Per-account values are
+ * stored separately, so this serializer never reads or writes account values. The numeric-only
+ * big-number rule and the unique-name conflict are enforced behind the facade.
+ */
+export interface PatchedCustomPropertyDefinitionApi {
+ readonly id?: string
+ /**
+ * Human-readable name of the custom property. Unique within the team.
+ * @maxLength 400
+ */
+ name?: string
+ /**
+ * Optional description of what the property represents.
+ * @nullable
+ */
+ description?: string | null
+ /** How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.
+ *
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean */
+ display_type?: CustomPropertyDisplayTypeEnumApi
+ /** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
+ is_big_number?: boolean
+ readonly created_at?: string
+ /** @nullable */
+ readonly created_by?: number | null
+ /** @nullable */
+ readonly updated_at?: string | null
+}
+
export interface CustomerJourneyApi {
readonly id: string
insight: number
@@ -512,6 +619,17 @@ export type AccountsNotebooksListParams = {
offset?: number
}
+export type CustomPropertyDefinitionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 237b268a3f37..f6e41b64c666 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -13,6 +13,8 @@ import type {
AccountNotebookApi,
AccountsListParams,
AccountsNotebooksListParams,
+ CustomPropertyDefinitionApi,
+ CustomPropertyDefinitionsListParams,
CustomerJourneyApi,
CustomerJourneysListParams,
CustomerProfileConfigApi,
@@ -21,10 +23,12 @@ import type {
GroupsTypesMetricsListParams,
PaginatedAccountListApi,
PaginatedAccountNotebookListApi,
+ PaginatedCustomPropertyDefinitionListApi,
PaginatedCustomerJourneyListApi,
PaginatedCustomerProfileConfigListApi,
PaginatedGroupUsageMetricListApi,
PatchedAccountApi,
+ PatchedCustomPropertyDefinitionApi,
PatchedCustomerJourneyApi,
PatchedCustomerProfileConfigApi,
PatchedGroupUsageMetricApi,
@@ -231,6 +235,122 @@ export const accountsDestroy = async (projectId: string, id: string, options?: R
})
}
+export const getCustomPropertyDefinitionsListUrl = (
+ projectId: string,
+ params?: CustomPropertyDefinitionsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/custom_property_definitions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/custom_property_definitions/`
+}
+
+export const customPropertyDefinitionsList = async (
+ projectId: string,
+ params?: CustomPropertyDefinitionsListParams,
+ options?: RequestInit
+): Promise<PaginatedCustomPropertyDefinitionListApi> => {
+ return apiMutator<PaginatedCustomPropertyDefinitionListApi>(
+ getCustomPropertyDefinitionsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getCustomPropertyDefinitionsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/custom_property_definitions/`
+}
+
+export const customPropertyDefinitionsCreate = async (
+ projectId: string,
+ customPropertyDefinitionApi: NonReadonly<CustomPropertyDefinitionApi>,
+ options?: RequestInit
+): Promise<CustomPropertyDefinitionApi> => {
+ return apiMutator<CustomPropertyDefinitionApi>(getCustomPropertyDefinitionsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customPropertyDefinitionApi),
+ })
+}
+
+export const getCustomPropertyDefinitionsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_definitions/${id}/`
+}
+
+export const customPropertyDefinitionsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomPropertyDefinitionApi> => {
+ return apiMutator<CustomPropertyDefinitionApi>(getCustomPropertyDefinitionsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomPropertyDefinitionsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_definitions/${id}/`
+}
+
+export const customPropertyDefinitionsUpdate = async (
+ projectId: string,
+ id: string,
+ customPropertyDefinitionApi: NonReadonly<CustomPropertyDefinitionApi>,
+ options?: RequestInit
+): Promise<CustomPropertyDefinitionApi> => {
+ return apiMutator<CustomPropertyDefinitionApi>(getCustomPropertyDefinitionsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customPropertyDefinitionApi),
+ })
+}
+
+export const getCustomPropertyDefinitionsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_definitions/${id}/`
+}
+
+export const customPropertyDefinitionsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedCustomPropertyDefinitionApi?: NonReadonly<PatchedCustomPropertyDefinitionApi>,
+ options?: RequestInit
+): Promise<CustomPropertyDefinitionApi> => {
+ return apiMutator<CustomPropertyDefinitionApi>(getCustomPropertyDefinitionsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedCustomPropertyDefinitionApi),
+ })
+}
+
+export const getCustomPropertyDefinitionsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/custom_property_definitions/${id}/`
+}
+
+export const customPropertyDefinitionsDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getCustomPropertyDefinitionsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getCustomerJourneysListUrl = (projectId: string, params?: CustomerJourneysListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 6923d19d6539..5c002950598e 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -184,6 +184,92 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
+export const customPropertyDefinitionsCreateBodyNameMax = 400
+
+export const customPropertyDefinitionsCreateBodyIsBigNumberDefault = false
+
+export const CustomPropertyDefinitionsCreateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(customPropertyDefinitionsCreateBodyNameMax)
+ .describe('Human-readable name of the custom property. Unique within the team.'),
+ description: zod.string().nullish().describe('Optional description of what the property represents.'),
+ display_type: zod
+ .enum(['text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean'])
+ .describe(
+ '\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean'
+ )
+ .describe(
+ "How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean"
+ ),
+ is_big_number: zod
+ .boolean()
+ .default(customPropertyDefinitionsCreateBodyIsBigNumberDefault)
+ .describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
+ })
+ .describe(
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ )
+
+export const customPropertyDefinitionsUpdateBodyNameMax = 400
+
+export const customPropertyDefinitionsUpdateBodyIsBigNumberDefault = false
+
+export const CustomPropertyDefinitionsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(customPropertyDefinitionsUpdateBodyNameMax)
+ .describe('Human-readable name of the custom property. Unique within the team.'),
+ description: zod.string().nullish().describe('Optional description of what the property represents.'),
+ display_type: zod
+ .enum(['text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean'])
+ .describe(
+ '\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean'
+ )
+ .describe(
+ "How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean"
+ ),
+ is_big_number: zod
+ .boolean()
+ .default(customPropertyDefinitionsUpdateBodyIsBigNumberDefault)
+ .describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
+ })
+ .describe(
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ )
+
+export const customPropertyDefinitionsPartialUpdateBodyNameMax = 400
+
+export const customPropertyDefinitionsPartialUpdateBodyIsBigNumberDefault = false
+
+export const CustomPropertyDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(customPropertyDefinitionsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable name of the custom property. Unique within the team.'),
+ description: zod.string().nullish().describe('Optional description of what the property represents.'),
+ display_type: zod
+ .enum(['text', 'number', 'currency', 'percent', 'date', 'datetime', 'boolean'])
+ .describe(
+ '\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean'
+ )
+ .optional()
+ .describe(
+ "How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.\n\n\* `text` - text\n\* `number` - number\n\* `currency` - currency\n\* `percent` - percent\n\* `date` - date\n\* `datetime` - datetime\n\* `boolean` - boolean"
+ ),
+ is_big_number: zod
+ .boolean()
+ .default(customPropertyDefinitionsPartialUpdateBodyIsBigNumberDefault)
+ .describe('Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties.'),
+ })
+ .describe(
+ "A team-scoped definition of a custom account property — the attribute side of the model.\n\nHolds only the property's shape (name, display type, big-number flag). Per-account values are\nstored separately, so this serializer never reads or writes account values. The numeric-only\nbig-number rule and the unique-name conflict are enforced behind the facade."
+ )
+
export const customerJourneysCreateBodyNameMax = 400
export const CustomerJourneysCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 599363342456..2c77f494a889 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -183,6 +183,24 @@ tools:
accounts-update:
operation: accounts_update
enabled: false
+ custom-property-definitions-create:
+ operation: custom_property_definitions_create
+ enabled: false
+ custom-property-definitions-destroy:
+ operation: custom_property_definitions_destroy
+ enabled: false
+ custom-property-definitions-list:
+ operation: custom_property_definitions_list
+ enabled: false
+ custom-property-definitions-partial-update:
+ operation: custom_property_definitions_partial_update
+ enabled: false
+ custom-property-definitions-retrieve:
+ operation: custom_property_definitions_retrieve
+ enabled: false
+ custom-property-definitions-update:
+ operation: custom_property_definitions_update
+ enabled: false
customer-journeys-create:
operation: customer_journeys_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c1d556c46ba1..390a13e00b28 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14105,6 +14105,66 @@ export namespace Schemas {
source: string;
}
+ /**
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean
+ */
+ export type CustomPropertyDisplayTypeEnum = typeof CustomPropertyDisplayTypeEnum[keyof typeof CustomPropertyDisplayTypeEnum];
+
+
+ export const CustomPropertyDisplayTypeEnum = {
+ Text: 'text',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+ } as const;
+
+ /**
+ * A team-scoped definition of a custom account property — the attribute side of the model.
+ *
+ * Holds only the property's shape (name, display type, big-number flag). Per-account values are
+ * stored separately, so this serializer never reads or writes account values. The numeric-only
+ * big-number rule and the unique-name conflict are enforced behind the facade.
+ */
+ export interface CustomPropertyDefinition {
+ readonly id: string;
+ /**
+ * Human-readable name of the custom property. Unique within the team.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * Optional description of what the property represents.
+ * @nullable
+ */
+ description?: string | null;
+ /** How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.
+ *
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean */
+ display_type: CustomPropertyDisplayTypeEnum;
+ /** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
+ is_big_number?: boolean;
+ readonly created_at: string;
+ /** @nullable */
+ readonly created_by: number | null;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
export interface CustomerJourney {
readonly id: string;
insight: number;
@@ -29884,6 +29944,15 @@ export namespace Schemas {
results: CoreEvent[];
}
+ export interface PaginatedCustomPropertyDefinitionList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: CustomPropertyDefinition[];
+ }
+
export interface PaginatedCustomerJourneyList {
count: number;
/** @nullable */
@@ -35096,6 +35165,44 @@ export namespace Schemas {
readonly updated_at?: string;
}
+ /**
+ * A team-scoped definition of a custom account property — the attribute side of the model.
+ *
+ * Holds only the property's shape (name, display type, big-number flag). Per-account values are
+ * stored separately, so this serializer never reads or writes account values. The numeric-only
+ * big-number rule and the unique-name conflict are enforced behind the facade.
+ */
+ export interface PatchedCustomPropertyDefinition {
+ readonly id?: string;
+ /**
+ * Human-readable name of the custom property. Unique within the team.
+ * @maxLength 400
+ */
+ name?: string;
+ /**
+ * Optional description of what the property represents.
+ * @nullable
+ */
+ description?: string | null;
+ /** How the property is interpreted and rendered: 'text', 'number', 'currency', 'percent', 'date', 'datetime', or 'boolean'.
+ *
+ * * `text` - text
+ * * `number` - number
+ * * `currency` - currency
+ * * `percent` - percent
+ * * `date` - date
+ * * `datetime` - datetime
+ * * `boolean` - boolean */
+ display_type?: CustomPropertyDisplayTypeEnum;
+ /** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
+ is_big_number?: boolean;
+ readonly created_at?: string;
+ /** @nullable */
+ readonly created_by?: number | null;
+ /** @nullable */
+ readonly updated_at?: string | null;
+ }
+
export interface PatchedCustomerJourney {
readonly id?: string;
insight?: number;
@@ -52280,6 +52387,17 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsCustomPropertyDefinitionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type EnvironmentsCustomerJourneysListParams = {
/**
* Number of results to return per page.
@@ -58024,6 +58142,17 @@ export namespace Schemas {
offset?: number;
};
+ export type CustomPropertyDefinitionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.