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 select custom property type to the backend (#68299)

Arthur Moreira de Deus8a4afbf04ac4
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index 4b3a80e6a350..58f29d52f946 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -15,3 +15,6 @@ 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"]
+
+# Mirrors OPTION_COLOR_TOKENS in the frontend's customPropertyTypes.ts (DataColorToken presets).
+CUSTOM_PROPERTY_OPTION_COLORS = [f"preset-{i}" for i in range(1, 11)]
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 8bb5c3689cfe..44fc1c7c9e05 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -37,7 +37,12 @@ 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.custom_property_definitions import (
+ InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,
+ apply_option_side_effects,
+ coerce_is_big_number,
+ normalize_options,
+)
from products.customer_analytics.backend.logic.usage_spike_notifications import (
notify_managers_of_usage_spike as notify_managers_of_usage_spike,
)
@@ -47,6 +52,7 @@ from products.customer_analytics.backend.models import (
CustomerProfileConfig,
CustomPropertyDefinition,
CustomPropertySource,
+ DisplayType,
)
from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties
from products.notebooks.backend.facade import (
@@ -684,9 +690,18 @@ def _to_custom_property_definition_view(
updated_at=definition.updated_at,
references=references or [],
source=_definition_source_view(definition),
+ options=_to_custom_property_options(definition.options),
)
+def _to_custom_property_options(
+ options: list[dict[str, Any]] | None,
+) -> list[contracts.CustomPropertyOption] | None:
+ if options is None:
+ return None
+ return [contracts.CustomPropertyOption(**option) for option in options]
+
+
def _can_read_workflow_references(user_access_control: "UserAccessControl") -> bool:
"""Whether the caller may see the workflows that reference a custom property.
@@ -764,6 +779,7 @@ def create_custom_property_definition(
description: str | None,
display_type: str,
is_big_number: bool,
+ options: list[dict[str, Any]] | None = None,
organization_id,
user: "User",
was_impersonated: bool,
@@ -776,6 +792,7 @@ def create_custom_property_definition(
description=description,
display_type=display_type,
is_big_number=coerce_is_big_number(display_type, is_big_number),
+ options=normalize_options(DisplayType(display_type), options),
)
except IntegrityError:
raise CustomPropertyDefinitionConflictError("A custom property with this name already exists for this team.")
@@ -812,8 +829,21 @@ def update_custom_property_definition(
# 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)
+ definition.options = normalize_options(
+ DisplayType(definition.display_type),
+ definition.options,
+ existing_ids=frozenset(option["id"] for option in previous.options or []),
+ )
try:
- definition.save()
+ with transaction.atomic():
+ definition.save()
+ if DisplayType(definition.display_type) == DisplayType.SELECT:
+ apply_option_side_effects(
+ team_id=team_id,
+ definition_id=definition.id,
+ previous_options=previous.options,
+ new_options=definition.options,
+ )
except IntegrityError:
raise CustomPropertyDefinitionConflictError("A custom property with this name already exists for this team.")
_log_activity_swallowing(
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 58fc06441168..6c07ad7f830d 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -249,6 +249,16 @@ class CustomPropertyReference:
type: str = "workflow"
+@stdlib_dataclass(frozen=True)
+class CustomPropertyOption:
+ """One allowed value of a select custom property. ``id`` is server-assigned and stable across
+ renames so option edits can be diffed; ``color`` is a preset data-color token."""
+
+ label: str = ""
+ color: str = ""
+ id: str | None = None
+
+
@stdlib_dataclass(frozen=True)
class CustomPropertyDefinitionView:
"""A team-scoped custom account-property definition as returned by the
@@ -271,6 +281,7 @@ class CustomPropertyDefinitionView:
updated_at: datetime | None = None
references: list[CustomPropertyReference] = field(default_factory=list)
source: "CustomPropertySourceView | None" = None
+ options: list[CustomPropertyOption] | None = None
@stdlib_dataclass(frozen=True)
diff --git a/products/customer_analytics/backend/logic/custom_property_definitions.py b/products/customer_analytics/backend/logic/custom_property_definitions.py
index 752c0cfe2505..01dd0fde3f30 100644
--- a/products/customer_analytics/backend/logic/custom_property_definitions.py
+++ b/products/customer_analytics/backend/logic/custom_property_definitions.py
@@ -1,6 +1,21 @@
"""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
+from typing import Any
+from uuid import uuid4
+
+from django.db.models import Case, F, QuerySet, TextField, Value, When
+
+from products.customer_analytics.backend.constants import CUSTOM_PROPERTY_OPTION_COLORS
+from products.customer_analytics.backend.models import (
+ DATA_TYPE_BY_DISPLAY_TYPE,
+ CustomPropertyValue,
+ DataType,
+ DisplayType,
+)
+
+
+class InvalidCustomPropertyOptions(ValueError):
+ """Raised when a select property's options fail validation; the viewset maps it to a 400."""
def coerce_is_big_number(display_type: str, is_big_number: bool) -> bool:
@@ -10,3 +25,85 @@ def coerce_is_big_number(display_type: str, is_big_number: bool) -> bool:
non-numeric property.
"""
return is_big_number and DATA_TYPE_BY_DISPLAY_TYPE[DisplayType(display_type)] == DataType.NUMERIC
+
+
+def normalize_options(
+ display_type: DisplayType,
+ options: list[dict[str, Any]] | None,
+ existing_ids: frozenset[str] = frozenset(),
+) -> list[dict[str, Any]] | None:
+ if display_type != DisplayType.SELECT:
+ return None
+ if not options:
+ raise InvalidCustomPropertyOptions("A select property needs at least one option.")
+ normalized = [_normalize_option(option, existing_ids) for option in options]
+ _assert_unique_labels(normalized)
+ _assert_unique_ids(normalized)
+ return normalized
+
+
+def _normalize_option(option: dict[str, Any], existing_ids: frozenset[str]) -> dict[str, Any]:
+ label = (option.get("label") or "").strip()
+ if not label:
+ raise InvalidCustomPropertyOptions("Option labels can't be blank.")
+ color = option.get("color")
+ if color not in CUSTOM_PROPERTY_OPTION_COLORS:
+ raise InvalidCustomPropertyOptions(f"Invalid option color: '{color}'.")
+ option_id = option.get("id")
+ if option_id and option_id not in existing_ids:
+ raise InvalidCustomPropertyOptions("Option ids are assigned by the server; omit them for new options.")
+ return {"id": option_id or str(uuid4()), "label": label, "color": color}
+
+
+def _assert_unique_labels(options: list[dict[str, Any]]) -> None:
+ seen: set[str] = set()
+ for option in options:
+ if option["label"] in seen:
+ raise InvalidCustomPropertyOptions(f"Duplicate option label: '{option['label']}'.")
+ seen.add(option["label"])
+
+
+def _assert_unique_ids(options: list[dict[str, Any]]) -> None:
+ seen: set[str] = set()
+ for option in options:
+ if option["id"] in seen:
+ raise InvalidCustomPropertyOptions(f"Duplicate option id: '{option['id']}'.")
+ seen.add(option["id"])
+
+
+def apply_option_side_effects(
+ *,
+ team_id: int,
+ definition_id: Any,
+ previous_options: list[dict[str, Any]] | None,
+ new_options: list[dict[str, Any]] | None,
+) -> None:
+ previous_by_id = {option["id"]: option for option in previous_options or []}
+ new_by_id = {option["id"]: option for option in new_options or []}
+ removed_labels = [option["label"] for option_id, option in previous_by_id.items() if option_id not in new_by_id]
+ renames = [
+ (previous_by_id[option_id]["label"], option["label"])
+ for option_id, option in new_by_id.items()
+ if option_id in previous_by_id and previous_by_id[option_id]["label"] != option["label"]
+ ]
+ values = CustomPropertyValue.objects.for_team(team_id).filter(definition_id=definition_id)
+ _soft_delete_active_values(values, labels=removed_labels)
+ _backfill_renamed_labels(values, renames=renames)
+
+
+def _soft_delete_active_values(values: QuerySet[CustomPropertyValue], *, labels: list[str]) -> None:
+ if labels:
+ values.filter(value_str__in=labels, is_deleted=False).update(is_deleted=True)
+
+
+# Compromise: rewrites value rows inline, within the definition-update transaction — see COMPROMISES.md.
+def _backfill_renamed_labels(values: QuerySet[CustomPropertyValue], *, renames: list[tuple[str, str]]) -> None:
+ if not renames:
+ return
+ values.filter(value_str__in=[old_label for old_label, _ in renames]).update(
+ value_str=Case(
+ *[When(value_str=old_label, then=Value(new_label)) for old_label, new_label in renames],
+ default=F("value_str"),
+ output_field=TextField(),
+ )
+ )
diff --git a/products/customer_analytics/backend/logic/custom_property_definitions_test.py b/products/customer_analytics/backend/logic/custom_property_definitions_test.py
new file mode 100644
index 000000000000..caefc71c07c7
--- /dev/null
+++ b/products/customer_analytics/backend/logic/custom_property_definitions_test.py
@@ -0,0 +1,71 @@
+import pytest
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.logic.custom_property_definitions import (
+ InvalidCustomPropertyOptions,
+ normalize_options,
+)
+from products.customer_analytics.backend.models import DisplayType
+
+
+def test_non_select_types_never_store_options():
+ assert normalize_options(DisplayType.TEXT, [{"id": "x", "label": "A", "color": "preset-1"}]) is None
+
+
+def test_select_keeps_sent_ids_and_assigns_missing_ones():
+ result = normalize_options(
+ DisplayType.SELECT,
+ [
+ {"id": "opt-1", "label": " Enterprise ", "color": "preset-1"},
+ {"label": "Startup", "color": "preset-2"},
+ ],
+ existing_ids=frozenset({"opt-1"}),
+ )
+
+ assert result is not None
+ assert result[0] == {"id": "opt-1", "label": "Enterprise", "color": "preset-1"}
+ assert result[1]["label"] == "Startup"
+ assert result[1]["id"]
+
+
+ [
+ ("no_options", None, "A select property needs at least one option."),
+ ("empty_options", [], "A select property needs at least one option."),
+ ("blank_label", [{"label": " ", "color": "preset-1"}], "Option labels can't be blank."),
+ (
+ "duplicate_label",
+ [{"label": "A", "color": "preset-1"}, {"label": "A", "color": "preset-2"}],
+ "Duplicate option label: 'A'.",
+ ),
+ (
+ "duplicate_after_trim",
+ [{"label": "A", "color": "preset-1"}, {"label": " A ", "color": "preset-2"}],
+ "Duplicate option label: 'A'.",
+ ),
+ ("invalid_color", [{"label": "A", "color": "chartreuse"}], "Invalid option color: 'chartreuse'."),
+ (
+ "unknown_id",
+ [{"id": "made-up", "label": "A", "color": "preset-1"}],
+ "Option ids are assigned by the server; omit them for new options.",
+ ),
+ ]
+)
+def test_select_rejects_invalid_options(_name, options, expected_error):
+ with pytest.raises(InvalidCustomPropertyOptions) as err:
+ normalize_options(DisplayType.SELECT, options)
+
+ assert str(err.value) == expected_error
+
+
+def test_select_rejects_the_same_existing_id_sent_twice():
+ options = [
+ {"id": "opt-1", "label": "A", "color": "preset-1"},
+ {"id": "opt-1", "label": "B", "color": "preset-2"},
+ ]
+
+ with pytest.raises(InvalidCustomPropertyOptions) as err:
+ normalize_options(DisplayType.SELECT, options, existing_ids=frozenset({"opt-1"}))
+
+ assert str(err.value) == "Duplicate option id: 'opt-1'."
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index a02a43d61efe..7cefbbb89865 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -15,7 +15,13 @@ from django.core.exceptions import ValidationError
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 import (
+ Account,
+ CustomPropertyDefinition,
+ CustomPropertyValue,
+ DataType,
+ DisplayType,
+)
from products.customer_analytics.backend.models.custom_property_value import ACTIVE_VALUE_CONSTRAINT_NAME
CoercedValue = float | bool | str | datetime
@@ -220,6 +226,13 @@ def _coerce_string(definition: CustomPropertyDefinition, value: Any) -> str:
raise InvalidCustomPropertyValue(_expects(definition, "a text value"))
+def _coerce_select(definition: CustomPropertyDefinition, value: Any) -> str:
+ labels = [option["label"] for option in definition.options or []]
+ if isinstance(value, str) and value in labels:
+ return value
+ raise InvalidCustomPropertyValue(_expects(definition, f"one of its options: {', '.join(labels)}"))
+
+
# 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]]] = {
@@ -231,6 +244,8 @@ _HANDLER_BY_DATA_TYPE: dict[DataType, tuple[str, Callable[[CustomPropertyDefinit
def _coerce_to_column(definition: CustomPropertyDefinition, value: Any) -> tuple[str, CoercedValue]:
+ if definition.display_type == DisplayType.SELECT:
+ return "value_str", _coerce_select(definition, value)
column, coerce = _HANDLER_BY_DATA_TYPE[definition.data_type]
return column, coerce(definition, value)
diff --git a/products/customer_analytics/backend/migrations/0012_custompropertydefinition_options_and_more.py b/products/customer_analytics/backend/migrations/0012_custompropertydefinition_options_and_more.py
new file mode 100644
index 000000000000..582a2eeb6b4a
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0012_custompropertydefinition_options_and_more.py
@@ -0,0 +1,42 @@
+# Generated by Django 5.2.14 on 2026-07-03 13:18
+
+from django.db import migrations, models
+
+import products.customer_analytics.backend.models.custom_property_definition
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0011_custompropertysource_validate_fks"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertydefinition",
+ name="options",
+ field=models.JSONField(
+ blank=True,
+ default=None,
+ help_text="For select properties: the allowed options, each {'id', 'label', 'color'}. Null for other types.",
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="custompropertydefinition",
+ name="display_type",
+ field=models.CharField(
+ choices=[
+ ("text", "text"),
+ ("number", "number"),
+ ("currency", "currency"),
+ ("percent", "percent"),
+ ("date", "date"),
+ ("datetime", "datetime"),
+ ("boolean", "boolean"),
+ ("select", "select"),
+ ],
+ default=products.customer_analytics.backend.models.custom_property_definition.DisplayType["TEXT"],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 21b6750ba376..3ed99d736ca0 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_custompropertysource_validate_fks
+0012_custompropertydefinition_options_and_more
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
index de99a5396138..511388c3e5ca 100644
--- a/products/customer_analytics/backend/models/custom_property_definition.py
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -14,6 +14,7 @@ class DisplayType(StrEnum):
DATE = "date"
DATETIME = "datetime"
BOOLEAN = "boolean"
+ SELECT = "select"
class DataType(StrEnum):
@@ -31,6 +32,7 @@ DATA_TYPE_BY_DISPLAY_TYPE: dict[DisplayType, DataType] = {
DisplayType.DATE: DataType.DATETIME,
DisplayType.DATETIME: DataType.DATETIME,
DisplayType.BOOLEAN: DataType.BOOLEAN,
+ DisplayType.SELECT: DataType.STRING,
}
NUMERIC_DISPLAY_TYPES = [
@@ -49,6 +51,12 @@ class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields
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"
)
+ options = models.JSONField(
+ null=True,
+ blank=True,
+ default=None,
+ help_text="For select properties: the allowed options, each {'id', 'label', 'color'}. Null for other types.",
+ )
class Meta:
constraints = [
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index b61bd21591a3..4ea447b75adc 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -37,6 +37,11 @@ from products.workflows.backend.models import HogFlow
LOGIC_MODULE = "products.customer_analytics.backend.logic.custom_property_values"
+SELECT_OPTIONS = [
+ {"id": "opt-1", "label": "Enterprise", "color": "preset-1"},
+ {"id": "opt-2", "label": "Startup", "color": "preset-2"},
+]
+
class TestSetCustomPropertyValue(BaseTest):
def setUp(self):
@@ -122,6 +127,37 @@ class TestSetCustomPropertyValue(BaseTest):
assert not CustomPropertyValue.objects.for_team(self.team.id).filter(definition=definition).exists()
+ def test_select_writes_matching_label_into_value_str(self):
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name="Tier", display_type=DisplayType.SELECT, options=SELECT_OPTIONS
+ )
+
+ instance = self._set(definition=definition, value="Enterprise")
+ instance.refresh_from_db()
+
+ assert instance.value_str == "Enterprise"
+ assert instance.value_num is None and instance.value_bool is None and instance.value_datetime is None
+
+ @parameterized.expand(
+ [
+ ("unknown_label", "Mid-market"),
+ ("case_mismatch", "enterprise"),
+ ("empty_string", ""),
+ ("number", 3),
+ ("boolean", True),
+ ("list", ["Enterprise"]),
+ ]
+ )
+ def test_select_rejects_values_not_matching_an_option(self, _name, value):
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name=f"Tier {_name}", display_type=DisplayType.SELECT, options=SELECT_OPTIONS
+ )
+
+ 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)
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index 540e7fb06625..e76b9936c9bb 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -18,7 +18,14 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
-from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, CustomPropertySource
+from products.customer_analytics.backend.logic.custom_property_definitions import InvalidCustomPropertyOptions
+from products.customer_analytics.backend.logic.custom_property_values import set_custom_property_value
+from products.customer_analytics.backend.models import (
+ Account,
+ CustomPropertyDefinition,
+ CustomPropertySource,
+ CustomPropertyValue,
+)
from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties
from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
from products.customer_analytics.backend.test.factories import create_account
@@ -495,6 +502,117 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
)
+class TestCustomPropertyDefinitionOptionsFacade(TeamScopedTestMixin, BaseTest):
+ OPTIONS = [
+ {"label": "Red", "color": "preset-1"},
+ {"label": "Blue", "color": "preset-2"},
+ ]
+
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id)
+
+ def _create_select(self, options=None):
+ return facade.create_custom_property_definition(
+ team_id=self.team.id,
+ name="Stage",
+ description=None,
+ display_type="select",
+ is_big_number=False,
+ options=self.OPTIONS if options is None else options,
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ def _update(self, definition_id, **fields):
+ return facade.update_custom_property_definition(
+ team_id=self.team.id,
+ definition_id=definition_id,
+ fields=fields,
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ def _set_value(self, definition_id, value, account_id=None):
+ return set_custom_property_value(
+ team_id=self.team.id,
+ account_id=account_id or self.account.id,
+ definition_id=definition_id,
+ value=value,
+ )
+
+ def _values(self, definition_id):
+ return CustomPropertyValue.objects.for_team(self.team.id).filter(definition_id=definition_id)
+
+ def test_create_assigns_option_ids(self):
+ view = self._create_select()
+
+ assert view.options is not None
+ assert [option.label for option in view.options] == ["Red", "Blue"]
+ assert all(option.id for option in view.options)
+
+ def test_create_select_without_options_raises(self):
+ with pytest.raises(InvalidCustomPropertyOptions):
+ self._create_select(options=[])
+
+ def test_rename_backfills_active_and_historical_values(self):
+ view = self._create_select()
+ self._set_value(view.id, "Red")
+ self._set_value(view.id, "Blue") # supersedes: the "Red" row becomes historical
+
+ self._update(
+ view.id,
+ options=[
+ {"id": view.options[0].id, "label": "Crimson", "color": "preset-1"},
+ {"id": view.options[1].id, "label": "Blue", "color": "preset-2"},
+ ],
+ )
+
+ stored = list(self._values(view.id).order_by("created_at").values_list("value_str", "is_deleted"))
+ assert stored == [("Crimson", True), ("Blue", False)]
+
+ def test_removed_option_soft_deletes_active_values(self):
+ view = self._create_select()
+ self._set_value(view.id, "Red")
+
+ updated = self._update(view.id, options=[{"id": view.options[1].id, "label": "Blue", "color": "preset-2"}])
+
+ assert updated is not None and [option.label for option in updated.options] == ["Blue"]
+ row = self._values(view.id).get()
+ assert row.value_str == "Red"
+ assert row.is_deleted is True
+
+ def test_label_swap_between_options_does_not_cascade(self):
+ view = self._create_select()
+ other_account = create_account(team_id=self.team.id, name="Globex")
+ self._set_value(view.id, "Red")
+ self._set_value(view.id, "Blue", account_id=other_account.id)
+
+ self._update(
+ view.id,
+ options=[
+ {"id": view.options[0].id, "label": "Blue", "color": "preset-1"},
+ {"id": view.options[1].id, "label": "Red", "color": "preset-2"},
+ ],
+ )
+
+ by_account = {row.account_id: row.value_str for row in self._values(view.id)}
+ assert by_account == {self.account.id: "Blue", other_account.id: "Red"}
+
+ def test_converting_select_to_text_keeps_values_and_clears_options(self):
+ view = self._create_select()
+ self._set_value(view.id, "Red")
+
+ updated = self._update(view.id, display_type="text")
+
+ assert updated is not None and updated.options is None
+ row = self._values(view.id).get()
+ assert row.value_str == "Red"
+ assert row.is_deleted is False
+
+
class TestCustomPropertySourceFacade(TeamScopedTestMixin, BaseTest):
def setUp(self):
super().setUp()