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 values table (#65579)

Arthur Moreira de Deus4091b594f78d
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 670047889cbd..5f2ead32ee4b 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -91,6 +91,7 @@ rules:
|CustomerJourney
|CustomerProfileConfig
|CustomPropertyDefinition
+ |CustomPropertyValue
|DAG
|Dashboard
|DashboardTemplate
@@ -356,6 +357,7 @@ rules:
|CustomerJourney
|CustomerProfileConfig
|CustomPropertyDefinition
+ |CustomPropertyValue
|DAG
|Dashboard
|DashboardTemplate
diff --git a/products/customer_analytics/backend/AGENTS.md b/products/customer_analytics/backend/AGENTS.md
new file mode 100644
index 000000000000..0b7c636b5029
--- /dev/null
+++ b/products/customer_analytics/backend/AGENTS.md
@@ -0,0 +1,25 @@
+# Customer analytics — backend
+
+## Access control: accounts and their sub-resources are resource-level scoped
+
+Account viewsets and their nested sub-resources (custom property values, notebooks, and
+future account children) authorize at the **resource level**, not the object level:
+
+- `AccessControlViewSetMixin` + `scope_object = "account"` enforces the caller's default
+ access to the `account` scope (`viewer` for reads, `editor` for writes) plus project
+ membership.
+- `facade.get_accessible_account_id(...)` additionally filters to accounts the caller can
+ see (effective access above `none`).
+
+Per-account **object-level** access overrides are intentionally **not** enforced on writes
+to nested sub-resources. A caller with resource-level `editor` can therefore write the
+sub-resources of any account they can see, even if their access to that specific account
+was lowered to `viewer`. This is the accepted model for now — keep new account
+sub-resource viewsets consistent with it: gate on `get_accessible_account_id` and rely on
+the mixin for the resource-level `editor` requirement.
+
+Automated security reviewers periodically flag nested account write endpoints as an
+"object-level write access bypass". That is **known and intentional** here — don't treat it
+as a bug to fix. If we later decide to enforce object-level writes, mirror the account
+update/delete path: call `_enforce_object_access(account, user_access_control, "editor")`
+in the nested viewset's `create`/`destroy` before the write.
diff --git a/products/customer_analytics/backend/CLAUDE.md b/products/customer_analytics/backend/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/customer_analytics/backend/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index efbb6d23cd10..ff2c0f3f750e 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -16,6 +16,7 @@ Do NOT:
"""
from typing import TYPE_CHECKING, Any, Optional, cast
+from uuid import UUID
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
@@ -32,6 +33,7 @@ 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 import custom_property_values as _custom_property_values_logic
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,
@@ -59,6 +61,8 @@ if TYPE_CHECKING:
from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl
+ from products.customer_analytics.backend.models import CustomPropertyValue
+
def _to_assignment(assignment) -> contracts.AccountAssignment | None:
if assignment is None:
@@ -1273,3 +1277,47 @@ def _enforce_object_access(obj, user_access_control: "UserAccessControl", requir
return
if not user_access_control.check_access_level_for_object(obj, required_level=required_level): # type: ignore[arg-type]
raise ResourceForbiddenError()
+
+
+# --- Custom property values ---
+
+# Re-exported from logic so the presentation layer can catch them — the import-linter forbids
+# presentation importing logic directly, so these errors are part of the facade's surface.
+CustomPropertyDefinitionNotFound = _custom_property_values_logic.CustomPropertyDefinitionNotFound
+CustomPropertyValueConflict = _custom_property_values_logic.CustomPropertyValueConflict
+InvalidCustomPropertyValue = _custom_property_values_logic.InvalidCustomPropertyValue
+
+
+def _to_custom_property_value(row: "CustomPropertyValue") -> contracts.CustomPropertyValue:
+ return contracts.CustomPropertyValue(
+ id=row.id,
+ account_id=row.account_id,
+ definition_id=row.definition_id,
+ value=_custom_property_values_logic.value_of(row),
+ created_at=row.created_at,
+ created_by_id=row.created_by_id,
+ )
+
+
+def set_custom_property_value(
+ team_id: int,
+ account_id: str | UUID,
+ definition_id: str | UUID,
+ value: Any,
+ *,
+ created_by_id: int | None = None,
+) -> contracts.CustomPropertyValue:
+ row = _custom_property_values_logic.set_custom_property_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition_id=definition_id,
+ value=value,
+ created_by_id=created_by_id,
+ )
+ return _to_custom_property_value(row)
+
+
+def list_active_custom_property_values(team_id: int, account_id: str | UUID) -> list[contracts.CustomPropertyValue]:
+ """The account's current (non-deleted) custom property values as contracts, newest first."""
+ rows = _custom_property_values_logic.list_active_custom_property_values(team_id=team_id, account_id=account_id)
+ return [_to_custom_property_value(row) for row in rows]
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 6689ab7bad02..6e6d5bd61bdc 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -327,3 +327,15 @@ class CreateAccountNotebookInput:
content: Any
text_content: str | None
synthesized_content: Any = None
+
+
+@dataclass(frozen=True)
+class CustomPropertyValue:
+ """An account's value for a custom property."""
+
+ id: UUID
+ account_id: UUID
+ definition_id: UUID
+ value: float | bool | str | datetime | None
+ created_at: datetime
+ created_by_id: int | None
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
new file mode 100644
index 000000000000..cb024822b73f
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -0,0 +1,180 @@
+"""
+Business logic for per-account custom property values.
+
+ORM queries, type validation/coercion, the soft-delete + insert transaction, append-only history.
+Called by facade/api.py. Do not call from outside this module.
+"""
+
+import math
+from collections.abc import Callable
+from datetime import UTC, date, datetime
+from typing import Any
+from uuid import UUID
+
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, CustomPropertyValue, DataType
+from products.customer_analytics.backend.models.custom_property_value import ACTIVE_VALUE_CONSTRAINT_NAME
+
+CoercedValue = float | bool | str | datetime
+
+
+class InvalidCustomPropertyValue(ValueError):
+ """Raised when a value can't be coerced to its definition's data type."""
+
+
+class CustomPropertyDefinitionNotFound(Exception):
+ """Raised when the target custom property definition does not exist for the team."""
+
+
+class CustomPropertyValueConflict(Exception):
+ """Raised when a concurrent write already set an active value for this (account, definition).
+
+ Only the active-value uniqueness race maps to this — retrying succeeds, since the retry
+ soft-deletes the now-existing active row before inserting. Any other integrity error is a real
+ fault and is left to surface.
+ """
+
+
+def set_custom_property_value(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ definition_id: str | UUID,
+ value: Any,
+ created_by_id: int | None = None,
+) -> CustomPropertyValue:
+ """Set an account's value for a custom property, preserving history.
+
+ Coerces `value` to the definition's data type, then atomically soft-deletes the current active
+ row (if any) and inserts the new one — keeping at most one active row per (team, account,
+ definition) while leaving superseded rows for later analysis.
+
+ Raises `CustomPropertyDefinitionNotFound` (unknown definition), `Account.DoesNotExist`
+ (account not in team), `InvalidCustomPropertyValue` (value doesn't match the data type), or
+ `CustomPropertyValueConflict` (a concurrent write won the active-value race — retry).
+ """
+ try:
+ definition = CustomPropertyDefinition.objects.for_team(team_id).get(id=definition_id)
+ except CustomPropertyDefinition.DoesNotExist as exc:
+ raise CustomPropertyDefinitionNotFound(
+ f"Custom property definition {definition_id} not found for team {team_id}."
+ ) from exc
+ _assert_account_in_team(team_id=team_id, account_id=account_id)
+ column, coerced = _coerce_to_column(definition, value)
+
+ try:
+ with transaction.atomic():
+ CustomPropertyValue.objects.for_team(team_id).filter(
+ account_id=account_id, definition_id=definition_id, is_deleted=False
+ ).update(is_deleted=True)
+ row = CustomPropertyValue.objects.for_team(team_id).create(
+ team_id=team_id,
+ account_id=account_id,
+ definition_id=definition_id,
+ created_by_id=created_by_id,
+ **{column: coerced},
+ )
+ except IntegrityError as exc:
+ if _is_active_value_conflict(exc):
+ raise CustomPropertyValueConflict(
+ f"An active value for custom property '{definition.name}' was set concurrently."
+ ) from exc
+ raise
+ # Cache the definition we already hold so callers reading row.definition.* don't trigger a
+ # lazy FK load against the fail-closed manager (which would raise outside request scope).
+ row.definition = definition
+ return row
+
+
+def _is_active_value_conflict(exc: IntegrityError) -> bool:
+ return ACTIVE_VALUE_CONSTRAINT_NAME in str(exc)
+
+
+def list_active_custom_property_values(*, team_id: int, account_id: str | UUID) -> list[CustomPropertyValue]:
+ """The account's current (non-deleted) values, newest first."""
+ return list(
+ CustomPropertyValue.objects.for_team(team_id)
+ .filter(account_id=account_id, is_deleted=False)
+ .select_related("definition", "created_by")
+ .order_by("-created_at")
+ )
+
+
+def _assert_account_in_team(*, team_id: int, account_id: str | UUID) -> None:
+ if not Account.objects.for_team(team_id).filter(id=account_id).exists():
+ raise Account.DoesNotExist(f"Account {account_id} not found for team {team_id}")
+
+
+def _expects(definition: CustomPropertyDefinition, what: str) -> str:
+ return f"Custom property '{definition.name}' expects {what}"
+
+
+def _coerce_numeric(definition: CustomPropertyDefinition, value: Any) -> float:
+ # bool is a subclass of int — reject it so True doesn't silently become 1.0.
+ if isinstance(value, bool):
+ raise InvalidCustomPropertyValue(_expects(definition, "a numeric value"))
+ try:
+ result = float(value)
+ except (TypeError, ValueError):
+ raise InvalidCustomPropertyValue(_expects(definition, "a numeric value"))
+ # Reject NaN/inf: float() accepts "nan"/"inf", but a non-finite value silently corrupts
+ # AVG/SUM aggregates over this column downstream.
+ if not math.isfinite(result):
+ raise InvalidCustomPropertyValue(_expects(definition, "a finite numeric value"))
+ return result
+
+
+def _coerce_boolean(definition: CustomPropertyDefinition, value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str) and (normalized := value.strip().lower()) in ("true", "false"):
+ return normalized == "true"
+ raise InvalidCustomPropertyValue(_expects(definition, "a boolean value"))
+
+
+def _coerce_datetime(definition: CustomPropertyDefinition, value: Any) -> datetime:
+ # datetime must be checked before date — datetime is a subclass of date.
+ if isinstance(value, datetime):
+ return timezone.make_aware(value, UTC) if timezone.is_naive(value) else value
+ if isinstance(value, date):
+ return datetime(value.year, value.month, value.day, tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ # fromisoformat accepts both date-only ("2026-01-01", a DisplayType.DATE input) and a
+ # trailing "Z", which parse_datetime does not.
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ raise InvalidCustomPropertyValue(_expects(definition, "an ISO-8601 datetime"))
+ return timezone.make_aware(parsed, UTC) if timezone.is_naive(parsed) else parsed
+ raise InvalidCustomPropertyValue(_expects(definition, "an ISO-8601 datetime"))
+
+
+def _coerce_string(definition: CustomPropertyDefinition, value: Any) -> str:
+ if isinstance(value, str):
+ return value
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ return str(value)
+ raise InvalidCustomPropertyValue(_expects(definition, "a text value"))
+
+
+# Each data type maps to its CustomPropertyValue column and the coercer that validates a raw value
+# into it (defined here, after the coercers it references).
+_HANDLER_BY_DATA_TYPE: dict[DataType, tuple[str, Callable[[CustomPropertyDefinition, Any], CoercedValue]]] = {
+ DataType.STRING: ("value_str", _coerce_string),
+ DataType.NUMERIC: ("value_num", _coerce_numeric),
+ DataType.BOOLEAN: ("value_bool", _coerce_boolean),
+ DataType.DATETIME: ("value_datetime", _coerce_datetime),
+}
+
+
+def _coerce_to_column(definition: CustomPropertyDefinition, value: Any) -> tuple[str, CoercedValue]:
+ column, coerce = _HANDLER_BY_DATA_TYPE[definition.data_type]
+ return column, coerce(definition, value)
+
+
+def value_of(row: CustomPropertyValue) -> CoercedValue | None:
+ """The value stored on `row`, read from the column matching its definition's data type."""
+ column, _ = _HANDLER_BY_DATA_TYPE[row.definition.data_type]
+ return getattr(row, column)
diff --git a/products/customer_analytics/backend/migrations/0008_custom_property_value.py b/products/customer_analytics/backend/migrations/0008_custom_property_value.py
new file mode 100644
index 000000000000..64bc04dad753
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0008_custom_property_value.py
@@ -0,0 +1,126 @@
+# Generated by Django 5.2.14 on 2026-06-24 18:09
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+from posthog.migration_helpers import AddForeignKeyNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0007_custom_property_definition"),
+ ("posthog", "1237_alter_integration_kind"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomPropertyValue",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("is_deleted", models.BooleanField(default=False)),
+ ("value_str", models.TextField(blank=True, null=True)),
+ ("value_bool", models.BooleanField(blank=True, null=True)),
+ ("value_num", models.FloatField(blank=True, null=True)),
+ ("value_datetime", models.DateTimeField(blank=True, null=True)),
+ (
+ "account",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="custom_property_values",
+ to="customer_analytics.account",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="values",
+ to="customer_analytics.custompropertydefinition",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ condition=models.Q(("is_deleted", False)),
+ fields=("team", "account", "definition"),
+ name="unique_active_custom_property_value",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("value_bool__isnull", True),
+ ("value_datetime__isnull", True),
+ ("value_num__isnull", True),
+ ("value_str__isnull", False),
+ ),
+ models.Q(
+ ("value_bool__isnull", False),
+ ("value_datetime__isnull", True),
+ ("value_num__isnull", True),
+ ("value_str__isnull", True),
+ ),
+ models.Q(
+ ("value_bool__isnull", True),
+ ("value_datetime__isnull", True),
+ ("value_num__isnull", False),
+ ("value_str__isnull", True),
+ ),
+ models.Q(
+ ("value_bool__isnull", True),
+ ("value_datetime__isnull", False),
+ ("value_num__isnull", True),
+ ("value_str__isnull", True),
+ ),
+ _connector="OR",
+ ),
+ name="custom_property_value_exactly_one_value",
+ ),
+ ],
+ },
+ ),
+ AddForeignKeyNotValid(
+ model_name="custompropertyvalue",
+ name="custompropertyvalue_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="custompropertyvalue",
+ name="custompropertyvalue_created_by_id_fk",
+ column="created_by_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0009_custompropertyvalue_validate_fks.py b/products/customer_analytics/backend/migrations/0009_custompropertyvalue_validate_fks.py
new file mode 100644
index 000000000000..3943ca606c7f
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0009_custompropertyvalue_validate_fks.py
@@ -0,0 +1,14 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateForeignKey
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0008_custom_property_value"),
+ ]
+
+ operations = [
+ ValidateForeignKey(model_name="custompropertyvalue", name="custompropertyvalue_created_by_id_fk"),
+ ValidateForeignKey(model_name="custompropertyvalue", name="custompropertyvalue_team_id_fk"),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 8ea4f6e23ae0..43dc6dcd6ea7 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_custom_property_definition
+0009_custompropertyvalue_validate_fks
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 73d1ea6547ec..be5c16683721 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -1,5 +1,6 @@
from .account import Account
from .custom_property_definition import DATA_TYPE_BY_DISPLAY_TYPE, CustomPropertyDefinition, DataType, DisplayType
+from .custom_property_value import CustomPropertyValue
from .customer_journey import CustomerJourney
from .customer_profile_config import CustomerProfileConfig
from .team_customer_analytics_config import TeamCustomerAnalyticsConfig
@@ -8,6 +9,7 @@ __all__ = [
"DATA_TYPE_BY_DISPLAY_TYPE",
"Account",
"CustomPropertyDefinition",
+ "CustomPropertyValue",
"CustomerJourney",
"CustomerProfileConfig",
"DataType",
diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.py
index 6b52ed7620ac..ea5e16623642 100644
--- a/products/customer_analytics/backend/models/account_test.py
+++ b/products/customer_analytics/backend/models/account_test.py
@@ -1,4 +1,3 @@
-from contextlib import AbstractContextManager
from typing import cast
import pytest
@@ -16,29 +15,10 @@ from posthog.models.scoping import team_scope
from products.customer_analytics.backend.models import Account, TeamCustomerAnalyticsConfig
from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
-class _AccountTeamScopedTestMixin:
- """Wraps setUp/tearDown with team_scope so test-body queries to Account find a scope."""
-
- _team_scope_cm: AbstractContextManager[None] | None = None
-
- def setUp(self) -> None:
- super().setUp() # type: ignore[misc]
- cm = team_scope(self.team.id) # type: ignore[attr-defined]
- cm.__enter__()
- self._team_scope_cm = cm
-
- def tearDown(self) -> None:
- if self._team_scope_cm is not None:
- try:
- self._team_scope_cm.__exit__(None, None, None)
- finally:
- self._team_scope_cm = None
- super().tearDown() # type: ignore[misc]
-
-
-class AccountPropertiesValidationTest(_AccountTeamScopedTestMixin, BaseTest):
+class AccountPropertiesValidationTest(TeamScopedTestMixin, BaseTest):
def setUp(self):
super().setUp()
self.user = User.objects.create_user(
@@ -70,7 +50,7 @@ class AccountPropertiesValidationTest(_AccountTeamScopedTestMixin, BaseTest):
account.properties = {"unknown_field": "x"}
-class AccountExternalIdUniquenessTest(_AccountTeamScopedTestMixin, BaseTest):
+class AccountExternalIdUniquenessTest(TeamScopedTestMixin, BaseTest):
def test_duplicate_external_id_within_team_rejected(self):
Account.objects.create(team=self.team, name="First", external_id="acme")
@@ -95,7 +75,7 @@ class AccountExternalIdUniquenessTest(_AccountTeamScopedTestMixin, BaseTest):
assert second.external_id is None
-class TeamCustomerAnalyticsConfigDriftPolicyTest(_AccountTeamScopedTestMixin, BaseTest):
+class TeamCustomerAnalyticsConfigDriftPolicyTest(TeamScopedTestMixin, BaseTest):
def setUp(self):
super().setUp()
self.config = TeamCustomerAnalyticsConfig.objects.get(team=self.team)
@@ -128,7 +108,7 @@ class TeamCustomerAnalyticsConfigDriftPolicyTest(_AccountTeamScopedTestMixin, Ba
assert self.config.account_group_type_index == new_index
-class AccountManagerWriteTest(_AccountTeamScopedTestMixin, BaseTest):
+class AccountManagerWriteTest(TeamScopedTestMixin, BaseTest):
def setUp(self):
super().setUp()
self.user = User.objects.create_user(
diff --git a/products/customer_analytics/backend/models/custom_property_value.py b/products/customer_analytics/backend/models/custom_property_value.py
new file mode 100644
index 000000000000..488fdec9cc8f
--- /dev/null
+++ b/products/customer_analytics/backend/models/custom_property_value.py
@@ -0,0 +1,69 @@
+from django.db import models
+from django.db.models import Q
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UUIDModel
+
+# Partial-unique "one active value per (team, account, definition)" constraint. Shared so the write
+# service can tell this (retriable) race apart from other integrity errors by name.
+ACTIVE_VALUE_CONSTRAINT_NAME = "unique_active_custom_property_value"
+
+
+class CustomPropertyValue(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ definition = models.ForeignKey(
+ "customer_analytics.CustomPropertyDefinition", on_delete=models.CASCADE, related_name="values"
+ )
+ account = models.ForeignKey(
+ "customer_analytics.Account", on_delete=models.CASCADE, related_name="custom_property_values"
+ )
+
+ # Rows are append-only so the value's history can be analyzed; superseded values are soft-deleted
+ # rather than overwritten, leaving at most one active row per (team, account, definition).
+ is_deleted = models.BooleanField(default=False)
+
+ value_str = models.TextField(null=True, blank=True)
+ value_bool = models.BooleanField(null=True, blank=True)
+ value_num = models.FloatField(null=True, blank=True)
+ value_datetime = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "account", "definition"],
+ condition=Q(is_deleted=False),
+ name=ACTIVE_VALUE_CONSTRAINT_NAME,
+ ),
+ models.CheckConstraint(
+ name="custom_property_value_exactly_one_value",
+ condition=(
+ Q(
+ value_str__isnull=False,
+ value_bool__isnull=True,
+ value_num__isnull=True,
+ value_datetime__isnull=True,
+ )
+ | Q(
+ value_str__isnull=True,
+ value_bool__isnull=False,
+ value_num__isnull=True,
+ value_datetime__isnull=True,
+ )
+ | Q(
+ value_str__isnull=True,
+ value_bool__isnull=True,
+ value_num__isnull=False,
+ value_datetime__isnull=True,
+ )
+ | Q(
+ value_str__isnull=True,
+ value_bool__isnull=True,
+ value_num__isnull=True,
+ value_datetime__isnull=False,
+ )
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/models/custom_property_value_test.py b/products/customer_analytics/backend/models/custom_property_value_test.py
new file mode 100644
index 000000000000..748c5e7f5ce5
--- /dev/null
+++ b/products/customer_analytics/backend/models/custom_property_value_test.py
@@ -0,0 +1,81 @@
+from datetime import UTC, datetime
+
+import pytest
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError, transaction
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, CustomPropertyValue
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+
+
+class CustomPropertyValueTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = Account.objects.create(team=self.team, name="Acme")
+ self.definition = CustomPropertyDefinition.objects.create(team=self.team, name="Seats")
+
+ def _create(self, definition: CustomPropertyDefinition | None = None, **kwargs) -> CustomPropertyValue:
+ return CustomPropertyValue.objects.create(
+ team=self.team, account=self.account, definition=definition or self.definition, **kwargs
+ )
+
+ @parameterized.expand(
+ [
+ ("str", "value_str", "enterprise"),
+ ("bool", "value_bool", True),
+ ("num_decimal", "value_num", 9.99),
+ ("num_integer", "value_num", 12),
+ ("datetime", "value_datetime", datetime(2026, 1, 1, tzinfo=UTC)),
+ ]
+ )
+ def test_single_value_of_each_type_persists(self, _name, field, value):
+ definition = CustomPropertyDefinition.objects.create(team=self.team, name=f"def-{_name}")
+
+ instance = self._create(definition=definition, **{field: value})
+ instance.refresh_from_db()
+
+ assert getattr(instance, field) == value
+
+ def test_rejects_no_value_set(self):
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ self._create()
+
+ def test_rejects_multiple_values_set(self):
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ self._create(value_str="enterprise", value_num=1.0)
+
+ def test_rejects_second_active_value_for_same_definition(self):
+ self._create(value_str="first")
+
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ self._create(value_str="second")
+
+ def test_soft_deleting_active_value_allows_a_new_one_and_keeps_history(self):
+ first = self._create(value_str="first")
+ first.is_deleted = True
+ first.save()
+
+ second = self._create(value_str="second")
+
+ rows = CustomPropertyValue.objects.filter(account=self.account, definition=self.definition)
+ assert rows.count() == 2
+ assert rows.get(is_deleted=False) == second
+
+ def test_multiple_deleted_values_coexist(self):
+ for value in ("v1", "v2", "v3"):
+ row = self._create(value_str=value)
+ row.is_deleted = True
+ row.save()
+
+ assert (
+ CustomPropertyValue.objects.filter(
+ account=self.account, definition=self.definition, is_deleted=True
+ ).count()
+ == 3
+ )
diff --git a/products/customer_analytics/backend/models/team_scoped_test_base.py b/products/customer_analytics/backend/models/team_scoped_test_base.py
new file mode 100644
index 000000000000..88446f1dfd9d
--- /dev/null
+++ b/products/customer_analytics/backend/models/team_scoped_test_base.py
@@ -0,0 +1,23 @@
+from contextlib import AbstractContextManager
+
+from posthog.models.scoping import team_scope
+
+
+class TeamScopedTestMixin:
+ """Wraps setUp/tearDown in team_scope so test-body queries to fail-closed models find a scope."""
+
+ _team_scope_cm: AbstractContextManager[None] | None = None
+
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ cm = team_scope(self.team.id) # type: ignore[attr-defined]
+ cm.__enter__()
+ self._team_scope_cm = cm
+
+ def tearDown(self) -> None:
+ if self._team_scope_cm is not None:
+ try:
+ self._team_scope_cm.__exit__(None, None, None)
+ finally:
+ self._team_scope_cm = None
+ super().tearDown() # type: ignore[misc]
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 7500f53b072e..5410ee109397 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -315,3 +315,45 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"created_by",
"updated_at",
]
+
+
+@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})
+class CustomPropertyValueField(serializers.Field):
+ """A custom property value — a JSON scalar (string, number, or boolean).
+
+ Datetimes are sent and returned as ISO-8601 strings. The concrete type a property accepts is
+ set by its definition and validated server-side.
+ """
+
+ def to_internal_value(self, data):
+ if data is None or isinstance(data, dict | list):
+ raise serializers.ValidationError("Value must be a string, number, or boolean.")
+ return data
+
+ def to_representation(self, value):
+ return value
+
+
+class CustomPropertyValueWriteSerializer(serializers.Serializer):
+ definition = serializers.UUIDField(
+ help_text="UUID of the custom property definition whose value to set for this account."
+ )
+ value = CustomPropertyValueField(
+ help_text=(
+ "Value to store, matching the definition's type: a number for number/currency/percent, a "
+ "boolean for boolean, an ISO-8601 string for date/datetime, or text for text properties."
+ )
+ )
+
+
+class CustomPropertyValueSerializer(serializers.Serializer):
+ """An account's current value for a custom property (read shape)."""
+
+ id = serializers.UUIDField(read_only=True, help_text="Unique id of this value record.")
+ account_id = serializers.UUIDField(read_only=True, help_text="Account the value belongs to.")
+ definition_id = serializers.UUIDField(read_only=True, help_text="Custom property definition the value is for.")
+ value = CustomPropertyValueField(read_only=True, help_text="The stored value, typed per the property's data type.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When this value was set.")
+ created_by_id = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="Id of the user who set this value, if known."
+ )
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 5159de4351a5..64efb95e252d 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -37,6 +37,8 @@ from products.customer_analytics.backend.presentation.views.serializers import (
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
CustomPropertyDefinitionSerializer,
+ CustomPropertyValueSerializer,
+ CustomPropertyValueWriteSerializer,
)
from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes
@@ -731,3 +733,63 @@ def _synthesize_notebook_content(text_content, existing_content):
if text_content and not has_usable_content:
return {"type": "doc", "content": markdown_to_tiptap_nodes(text_content) or [{"type": "paragraph"}]}
return None
+
+
+@extend_schema(
+ tags=["customer_analytics"],
+ parameters=[
+ OpenApiParameter(
+ name="account_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.PATH,
+ description="UUID of the parent account.",
+ ),
+ ],
+)
+class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "account"
+ serializer_class = CustomPropertyValueSerializer
+ pagination_class = None
+
+ def _accessible_account_id(self) -> str | None:
+ """The parent account's id when the caller has object-level access to it, else ``None``
+ (mapped to 404). Object-access filtering lives behind the facade — the view imports no models."""
+ return api.get_accessible_account_id(
+ self.team_id, self.parents_query_dict["account_id"], user_access_control=self.user_access_control
+ )
+
+ @extend_schema(responses={200: CustomPropertyValueSerializer(many=True)})
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ account_id = self._accessible_account_id()
+ if account_id is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ values = api.list_active_custom_property_values(self.team_id, account_id)
+ return Response(CustomPropertyValueSerializer(values, many=True).data)
+
+ @extend_schema(request=CustomPropertyValueWriteSerializer, responses={201: CustomPropertyValueSerializer})
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ account_id = self._accessible_account_id()
+ if account_id is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ write = CustomPropertyValueWriteSerializer(data=request.data)
+ write.is_valid(raise_exception=True)
+
+ try:
+ value = api.set_custom_property_value(
+ team_id=self.team_id,
+ account_id=account_id,
+ definition_id=write.validated_data["definition"],
+ value=write.validated_data["value"],
+ created_by_id=request.user.id,
+ )
+ except api.Account_DoesNotExist:
+ # The account passed the access pre-check but was deleted before the write committed.
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.CustomPropertyDefinitionNotFound:
+ raise ValidationError({"definition": "Custom property definition not found."})
+ except api.InvalidCustomPropertyValue as exc:
+ raise ValidationError({"value": str(exc)})
+ except api.CustomPropertyValueConflict as exc:
+ raise Conflict(str(exc))
+
+ return Response(CustomPropertyValueSerializer(value).data, status=status.HTTP_201_CREATED)
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index b72eb4d4bd7e..2141a7169059 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -9,6 +9,7 @@ from products.customer_analytics.backend.presentation.views.views import (
CustomerJourneyViewSet,
CustomerProfileConfigViewSet,
CustomPropertyDefinitionViewSet,
+ CustomPropertyValueViewSet,
)
@@ -43,3 +44,9 @@ def register_routes(routers: RouterRegistry) -> None:
project_accounts_router.register(
r"notebooks", AccountNotebookViewSet, "project_account_notebooks", ["team_id", "account_id"]
)
+ project_accounts_router.register(
+ r"custom_property_values",
+ CustomPropertyValueViewSet,
+ "project_account_custom_property_values",
+ ["team_id", "account_id"],
+ )
diff --git a/products/customer_analytics/backend/test/factories.py b/products/customer_analytics/backend/test/factories.py
index 8d816a9b16ee..c34b14f516c7 100644
--- a/products/customer_analytics/backend/test/factories.py
+++ b/products/customer_analytics/backend/test/factories.py
@@ -1,8 +1,17 @@
from typing import Any
-from products.customer_analytics.backend.models import Account
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, DisplayType
def create_account(*, team_id: int, name: str = "Acme Corp", **kwargs: Any) -> Account:
"""Create an Account for tests. Always supplies `team_id` to make team-isolation cases ergonomic."""
return Account.objects.unscoped().create(team_id=team_id, name=name, **kwargs)
+
+
+def create_custom_property_definition(
+ *, team_id: int, name: str = "Plan", display_type: str = DisplayType.TEXT, **kwargs: Any
+) -> CustomPropertyDefinition:
+ """Create a CustomPropertyDefinition for tests, always supplying `team_id`."""
+ return CustomPropertyDefinition.objects.unscoped().create(
+ team_id=team_id, name=name, display_type=display_type, **kwargs
+ )
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
new file mode 100644
index 000000000000..e17a1c8c16b3
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -0,0 +1,239 @@
+from datetime import UTC, datetime
+from uuid import uuid4
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import IntegrityError
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.customer_analytics.backend.facade import (
+ api as facade,
+ contracts,
+)
+from products.customer_analytics.backend.logic.custom_property_values import (
+ CustomPropertyDefinitionNotFound,
+ CustomPropertyValueConflict,
+ InvalidCustomPropertyValue,
+ list_active_custom_property_values,
+ set_custom_property_value,
+)
+from products.customer_analytics.backend.models import (
+ Account,
+ CustomPropertyDefinition,
+ CustomPropertyValue,
+ DisplayType,
+)
+from products.customer_analytics.backend.models.custom_property_value import ACTIVE_VALUE_CONSTRAINT_NAME
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+
+LOGIC_MODULE = "products.customer_analytics.backend.logic.custom_property_values"
+
+
+class TestSetCustomPropertyValue(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id)
+
+ def _create_property_definition(
+ self, display_type: str = DisplayType.TEXT, name: str = "Prop"
+ ) -> CustomPropertyDefinition:
+ return create_custom_property_definition(team_id=self.team.id, name=name, display_type=display_type)
+
+ def _set(self, *, definition: CustomPropertyDefinition, value: object) -> CustomPropertyValue:
+ return set_custom_property_value(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=definition.id,
+ value=value,
+ created_by_id=self.user.id,
+ )
+
+ @parameterized.expand(
+ [
+ ("text", DisplayType.TEXT, "enterprise", "value_str", "enterprise"),
+ ("number_int", DisplayType.NUMBER, 12, "value_num", 12.0),
+ ("number_decimal", DisplayType.NUMBER, 9.99, "value_num", 9.99),
+ ("number_string", DisplayType.NUMBER, "42", "value_num", 42.0),
+ ("currency", DisplayType.CURRENCY, 1000, "value_num", 1000.0),
+ ("percent", DisplayType.PERCENT, 0.5, "value_num", 0.5),
+ ("boolean_true", DisplayType.BOOLEAN, True, "value_bool", True),
+ ("boolean_true_string", DisplayType.BOOLEAN, "true", "value_bool", True),
+ ("boolean_false_string", DisplayType.BOOLEAN, "FALSE", "value_bool", False),
+ (
+ "datetime",
+ DisplayType.DATETIME,
+ "2026-01-01T12:00:00+00:00",
+ "value_datetime",
+ datetime(2026, 1, 1, 12, tzinfo=UTC),
+ ),
+ (
+ "datetime_z",
+ DisplayType.DATETIME,
+ "2026-01-01T12:00:00Z",
+ "value_datetime",
+ datetime(2026, 1, 1, 12, tzinfo=UTC),
+ ),
+ ("date_only", DisplayType.DATE, "2026-01-01", "value_datetime", datetime(2026, 1, 1, tzinfo=UTC)),
+ ]
+ )
+ def test_writes_coerced_value_into_the_right_column(self, _name, display_type, value, column, expected):
+ definition = self._create_property_definition(display_type=display_type, name=_name)
+
+ instance = self._set(definition=definition, value=value)
+ instance.refresh_from_db()
+
+ assert getattr(instance, column) == expected
+ assert instance.created_by_id == self.user.id
+ assert instance.is_deleted is False
+ # only the target column is populated
+ other_columns = {"value_str", "value_bool", "value_num", "value_datetime"} - {column}
+ assert all(getattr(instance, other) is None for other in other_columns)
+
+ @parameterized.expand(
+ [
+ ("numeric_from_text", DisplayType.NUMBER, "abc"),
+ ("numeric_from_bool", DisplayType.NUMBER, True),
+ ("numeric_from_nan_string", DisplayType.NUMBER, "nan"),
+ ("numeric_from_inf_string", DisplayType.NUMBER, "inf"),
+ ("numeric_from_negative_inf_string", DisplayType.NUMBER, "-inf"),
+ ("numeric_from_nan_float", DisplayType.NUMBER, float("nan")),
+ ("numeric_from_inf_float", DisplayType.NUMBER, float("inf")),
+ ("boolean_from_arbitrary_string", DisplayType.BOOLEAN, "yes"),
+ ("boolean_from_int", DisplayType.BOOLEAN, 1),
+ ("datetime_from_unparseable", DisplayType.DATETIME, "not a date"),
+ ("datetime_from_number", DisplayType.DATETIME, 123),
+ ("text_from_list", DisplayType.TEXT, ["nope"]),
+ ]
+ )
+ def test_rejects_values_that_do_not_match_the_type(self, _name, display_type, value):
+ definition = self._create_property_definition(display_type=display_type, name=_name)
+
+ with pytest.raises(InvalidCustomPropertyValue):
+ self._set(definition=definition, value=value)
+
+ assert not CustomPropertyValue.objects.for_team(self.team.id).filter(definition=definition).exists()
+
+ def test_naive_datetime_is_stored_as_aware_utc(self):
+ definition = self._create_property_definition(display_type=DisplayType.DATETIME)
+
+ instance = self._set(definition=definition, value=datetime(2026, 6, 18, 12))
+ instance.refresh_from_db()
+
+ assert instance.value_datetime is not None
+ assert timezone.is_aware(instance.value_datetime)
+ assert instance.value_datetime == datetime(2026, 6, 18, 12, tzinfo=UTC)
+
+ def test_unknown_definition_raises(self):
+ with pytest.raises(CustomPropertyDefinitionNotFound):
+ set_custom_property_value(
+ team_id=self.team.id, account_id=self.account.id, definition_id=uuid4(), value="x"
+ )
+
+ def test_account_from_another_team_is_rejected(self):
+ other_team = Team.objects.create(organization=self.organization)
+ other_account = create_account(team_id=other_team.id)
+ definition = self._create_property_definition()
+
+ with pytest.raises(Account.DoesNotExist):
+ set_custom_property_value(
+ team_id=self.team.id, account_id=other_account.id, definition_id=definition.id, value="x"
+ )
+
+ def test_setting_a_new_value_soft_deletes_the_previous_and_keeps_history(self):
+ definition = self._create_property_definition()
+
+ first = self._set(definition=definition, value="starter")
+ second = self._set(definition=definition, value="enterprise")
+
+ rows = CustomPropertyValue.objects.for_team(self.team.id).filter(account=self.account, definition=definition)
+ assert rows.count() == 2
+ assert rows.get(is_deleted=False) == second
+
+ first.refresh_from_db()
+ assert first.is_deleted is True
+
+ def test_list_active_returns_only_current_values(self):
+ plan = self._create_property_definition(name="Plan")
+ seats = self._create_property_definition(name="Seats", display_type=DisplayType.NUMBER)
+
+ self._set(definition=plan, value="starter")
+ self._set(definition=plan, value="enterprise") # supersedes the starter row
+ self._set(definition=seats, value=42)
+
+ active = list_active_custom_property_values(team_id=self.team.id, account_id=self.account.id)
+
+ assert {(v.definition_id, v.value_str, v.value_num) for v in active} == {
+ (plan.id, "enterprise", None),
+ (seats.id, None, 42.0),
+ }
+
+ @patch(f"{LOGIC_MODULE}.CustomPropertyValue")
+ def test_losing_the_active_value_race_surfaces_as_a_conflict(self, mock_value_model):
+ definition = self._create_property_definition()
+ mock_value_model.objects.for_team.return_value.create.side_effect = IntegrityError(
+ f'duplicate key value violates unique constraint "{ACTIVE_VALUE_CONSTRAINT_NAME}"'
+ )
+
+ with pytest.raises(CustomPropertyValueConflict):
+ self._set(definition=definition, value="enterprise")
+
+ @patch(f"{LOGIC_MODULE}.CustomPropertyValue")
+ def test_other_integrity_errors_are_not_masked_as_conflicts(self, mock_value_model):
+ definition = self._create_property_definition()
+ mock_value_model.objects.for_team.return_value.create.side_effect = IntegrityError(
+ 'new row violates check constraint "custom_property_value_exactly_one_value"'
+ )
+
+ with pytest.raises(IntegrityError):
+ self._set(definition=definition, value="enterprise")
+
+
+class TestCustomPropertyValueFacade(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id)
+
+ @parameterized.expand(
+ [
+ ("text", DisplayType.TEXT, "enterprise", "enterprise"),
+ ("number", DisplayType.NUMBER, 9.99, 9.99),
+ ("boolean", DisplayType.BOOLEAN, True, True),
+ (
+ "datetime",
+ DisplayType.DATETIME,
+ "2026-01-01T12:00:00Z",
+ datetime(2026, 1, 1, 12, tzinfo=UTC),
+ ),
+ ]
+ )
+ def test_set_returns_a_contract_with_the_typed_value(self, _name, display_type, value, expected_value):
+ definition = create_custom_property_definition(team_id=self.team.id, name=_name, display_type=display_type)
+
+ result = facade.set_custom_property_value(
+ self.team.id, self.account.id, definition.id, value, created_by_id=self.user.id
+ )
+
+ assert isinstance(result, contracts.CustomPropertyValue)
+ assert result.value == expected_value
+ # the union must not coerce across types (e.g. bool True -> 1.0)
+ assert type(result.value) is type(expected_value)
+ assert result.account_id == self.account.id
+ assert result.definition_id == definition.id
+ assert result.created_by_id == self.user.id
+
+ def test_list_active_returns_contracts(self):
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ facade.set_custom_property_value(self.team.id, self.account.id, plan.id, "enterprise")
+
+ result = facade.list_active_custom_property_values(self.team.id, self.account.id)
+
+ assert len(result) == 1
+ assert isinstance(result[0], contracts.CustomPropertyValue)
+ assert result[0].value == "enterprise"
+ assert result[0].definition_id == plan.id
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 0be30b2539e5..2f90d798710c 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -1,6 +1,9 @@
+from uuid import uuid4
+
import pytest
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
@@ -18,8 +21,10 @@ from products.customer_analytics.backend.models import (
CustomerJourney,
CustomerProfileConfig,
CustomPropertyDefinition,
+ DisplayType,
)
from products.customer_analytics.backend.models.account import AccountAssignment
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.models.insight import Insight
@@ -1755,3 +1760,92 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):
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)
+
+
+class TestCustomPropertyValueViewSet(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id)
+ self.text_def = create_custom_property_definition(
+ team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT
+ )
+ self.number_def = create_custom_property_definition(
+ team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER
+ )
+ self.endpoint = f"/api/projects/{self.team.id}/accounts/{self.account.id}/custom_property_values/"
+
+ def _set(self, definition_id, value, endpoint=None):
+ return self.client.post(
+ endpoint or self.endpoint, {"definition": str(definition_id), "value": value}, format="json"
+ )
+
+ def test_create_value_success(self):
+ response = self._set(self.text_def.id, "enterprise")
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ data = response.json()
+ self.assertEqual("enterprise", data["value"])
+ self.assertEqual(str(self.text_def.id), data["definition_id"])
+ self.assertEqual(str(self.account.id), data["account_id"])
+
+ def test_create_numeric_value(self):
+ response = self._set(self.number_def.id, 1234.5)
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ self.assertEqual(1234.5, response.json()["value"])
+
+ def test_wrong_type_value_is_rejected(self):
+ response = self._set(self.number_def.id, "abc")
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+ self.assertEqual("value", response.json()["attr"])
+
+ def test_unknown_definition_is_rejected(self):
+ response = self._set(uuid4(), "x")
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+ self.assertEqual("definition", response.json()["attr"])
+
+ def test_resetting_a_value_supersedes_the_previous_one(self):
+ self._set(self.text_def.id, "starter")
+ self._set(self.text_def.id, "enterprise")
+
+ values = self.client.get(self.endpoint).json()
+ plan_values = [v for v in values if v["definition_id"] == str(self.text_def.id)]
+ self.assertEqual(1, len(plan_values))
+ self.assertEqual("enterprise", plan_values[0]["value"])
+
+ def test_list_returns_active_values(self):
+ self._set(self.text_def.id, "enterprise")
+ self._set(self.number_def.id, 42)
+
+ response = self.client.get(self.endpoint)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ values = {v["definition_id"]: v["value"] for v in response.json()}
+ self.assertEqual({str(self.text_def.id): "enterprise", str(self.number_def.id): 42}, values)
+
+ def test_account_from_another_team_returns_404(self):
+ other_team = Team.objects.create(organization=self.organization)
+ other_account = create_account(team_id=other_team.id)
+ endpoint = f"/api/projects/{self.team.id}/accounts/{other_account.id}/custom_property_values/"
+
+ response = self._set(self.text_def.id, "x", endpoint=endpoint)
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ @patch("products.customer_analytics.backend.facade.api.get_accessible_account_id")
+ def test_account_deleted_after_access_check_returns_404(self, mock_access):
+ # Account passes the access pre-check but is gone by the time the write commits.
+ mock_access.return_value = str(uuid4())
+
+ response = self._set(self.text_def.id, "x")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_unauthenticated_is_rejected(self):
+ self.client.logout()
+
+ response = self.client.get(self.endpoint)
+
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 89f749f8ece4..65eddc7febd7 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -84,6 +84,34 @@ export interface PaginatedAccountListApi {
results: AccountApi[]
}
+/**
+ * An account's current value for a custom property (read shape).
+ */
+export interface CustomPropertyValueApi {
+ /** Unique id of this value record. */
+ readonly id: string
+ /** Account the value belongs to. */
+ readonly account_id: string
+ /** Custom property definition the value is for. */
+ readonly definition_id: string
+ /** The stored value, typed per the property's data type. */
+ readonly value: string | number | boolean
+ /** When this value was set. */
+ readonly created_at: string
+ /**
+ * Id of the user who set this value, if known.
+ * @nullable
+ */
+ readonly created_by_id: number | null
+}
+
+export interface CustomPropertyValueWriteApi {
+ /** UUID of the custom property definition whose value to set for this account. */
+ definition: string
+ /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, or text for text properties. */
+ value: string | number | boolean
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index f6e41b64c666..d91e061c663f 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -15,6 +15,8 @@ import type {
AccountsNotebooksListParams,
CustomPropertyDefinitionApi,
CustomPropertyDefinitionsListParams,
+ CustomPropertyValueApi,
+ CustomPropertyValueWriteApi,
CustomerJourneyApi,
CustomerJourneysListParams,
CustomerProfileConfigApi,
@@ -95,6 +97,39 @@ export const accountsCreate = async (
})
}
+export const getAccountsCustomPropertyValuesListUrl = (projectId: string, accountId: string) => {
+ return `/api/projects/${projectId}/accounts/${accountId}/custom_property_values/`
+}
+
+export const accountsCustomPropertyValuesList = async (
+ projectId: string,
+ accountId: string,
+ options?: RequestInit
+): Promise<CustomPropertyValueApi[]> => {
+ return apiMutator<CustomPropertyValueApi[]>(getAccountsCustomPropertyValuesListUrl(projectId, accountId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAccountsCustomPropertyValuesCreateUrl = (projectId: string, accountId: string) => {
+ return `/api/projects/${projectId}/accounts/${accountId}/custom_property_values/`
+}
+
+export const accountsCustomPropertyValuesCreate = async (
+ projectId: string,
+ accountId: string,
+ customPropertyValueWriteApi: CustomPropertyValueWriteApi,
+ options?: RequestInit
+): Promise<CustomPropertyValueApi> => {
+ return apiMutator<CustomPropertyValueApi>(getAccountsCustomPropertyValuesCreateUrl(projectId, accountId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customPropertyValueWriteApi),
+ })
+}
+
export const getAccountsNotebooksListUrl = (
projectId: string,
accountId: string,
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 5c002950598e..ebaebe352857 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -62,6 +62,15 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
+export const AccountsCustomPropertyValuesCreateBody = /* @__PURE__ */ zod.object({
+ definition: zod.uuid().describe('UUID of the custom property definition whose value to set for this account.'),
+ value: zod
+ .union([zod.string(), zod.number(), zod.boolean()])
+ .describe(
+ "Value to store, matching the definition's type: a number for number\/currency\/percent, a boolean for boolean, an ISO-8601 string for date\/datetime, or text for text properties."
+ ),
+})
+
export const accountsNotebooksCreateBodyTitleMax = 256
export const AccountsNotebooksCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 2c77f494a889..75cf09bd2d97 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -37,6 +37,12 @@ tools:
Tag names to attach to the account. Tags are created on demand if they do not already exist for the
team.
feature_flag: customer-analytics-csp
+ accounts-custom-property-values-create:
+ operation: accounts_custom_property_values_create
+ enabled: false
+ accounts-custom-property-values-list:
+ operation: accounts_custom_property_values_list
+ enabled: false
accounts-destroy:
operation: accounts_destroy
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 43391e547690..cc7f4d117837 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14188,6 +14188,34 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * An account's current value for a custom property (read shape).
+ */
+ export interface CustomPropertyValue {
+ /** Unique id of this value record. */
+ readonly id: string;
+ /** Account the value belongs to. */
+ readonly account_id: string;
+ /** Custom property definition the value is for. */
+ readonly definition_id: string;
+ /** The stored value, typed per the property's data type. */
+ readonly value: string | number | boolean;
+ /** When this value was set. */
+ readonly created_at: string;
+ /**
+ * Id of the user who set this value, if known.
+ * @nullable
+ */
+ readonly created_by_id: number | null;
+ }
+
+ export interface CustomPropertyValueWrite {
+ /** UUID of the custom property definition whose value to set for this account. */
+ definition: string;
+ /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, or text for text properties. */
+ value: string | number | boolean;
+ }
+
export interface CustomerJourney {
readonly id: string;
insight: number;