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.

fix(customer-analytics): hydrate columns with account rows (#115870)

jake sciotto3358e72e4d42
diff --git a/docs/internal/customer-analytics/accounts-table.md b/docs/internal/customer-analytics/accounts-table.md
index 52665a11bacb..e0f823f01a68 100644
--- a/docs/internal/customer-analytics/accounts-table.md
+++ b/docs/internal/customer-analytics/accounts-table.md
@@ -11,6 +11,36 @@ Reads resolve the current project defaults without copying them into the user ro
A personal save stores the complete ordered list and an override marker.
A saved empty list means the user chose no pinned properties and no longer inherits project changes.
+## Table columns and definitions
+
+The first table response contains rows, ordered columns, and the metadata needed to show and edit those columns.
+A default view sends `useDefaultColumns: true`. The backend selects the name, tags, note count, and all project relationships.
+Saved views store their selected column expressions. Relationship expressions contain the definition ID and a stable alias:
+
+```text
+accounts.relationships.values.`<definition-id>` AS rel_<definition-id-without-hyphens>
+```
+
+Relationship sort entries use the same alias followed by `ASC` or `DESC`.
+The column picker and default-column builder create this format. Saved views preserve it unchanged.
+The query planner sends typed definition references to the table endpoint.
+Empty results still include column metadata.
+
+The table and overview queries start without waiting for definition catalogs.
+The backend validates custom-property and relationship filters, including filters for columns outside the table.
+The Accounts UI requests that missing definitions be omitted, so deleted properties do not block saved views.
+The response omits their columns and values. A deleted sort column falls back to the default row order.
+Saved custom-property filters with incompatible operators are omitted after a definition changes type.
+Other API callers retain strict validation by default.
+
+Saved overview metrics use their definition IDs without waiting for catalogs.
+Missing or nonnumeric metric definitions produce an empty metric value.
+Table metadata caches workflow-reference flags for 60 seconds per project.
+
+Opening a column, filter, or overview editor loads each definition catalog once with `pagination=none`.
+The API keeps its `results`, `count`, `next`, and `previous` envelope. Other callers keep pagination by default.
+Catalog responses update picker options without changing the table request.
+
## Query scheduling
Account row and overview requests use a dedicated frontend queue with two concurrent slots.
diff --git a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
index f01a6e22e240..5c401a2ae34e 100644
--- a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
+++ b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
@@ -83,6 +83,8 @@ export interface PropertyFiltersProps {
addFilterSuffix?: ((addFilter: (property: AnyPropertyFilter) => void) => JSX.Element) | null
addFilterDivider?: boolean
framedRows?: boolean
+ filterHeader?: React.ReactNode
+ onFilterOpen?: () => void
renderControls?: (controls: {
addFilter: React.ReactNode
activeFilters: JSX.Element[]
@@ -138,6 +140,8 @@ export function PropertyFilters({
addFilterDivider = false,
framedRows = false,
renderControls,
+ onFilterOpen,
+ filterHeader,
}: PropertyFiltersProps): JSX.Element {
const logicProps = { propertyFilters, onChange, pageKey, sendAllKeyUpdates }
const { filters, filtersWithNew, filterIds, filterIdsWithNew } = useValues(propertyFilterLogic(logicProps))
@@ -175,6 +179,8 @@ export function PropertyFilters({
index === displayedFilters.length - 1 &&
filters.length > 0 && <LemonDivider className="my-1 w-full" />}
<FilterRow
+ onOpen={onFilterOpen}
+ header={filterHeader}
item={item}
index={index}
totalCount={displayedFilters.length - 1} // empty state
diff --git a/frontend/src/lib/components/PropertyFilters/components/FilterRow.tsx b/frontend/src/lib/components/PropertyFilters/components/FilterRow.tsx
index e1efa7f07c42..1286d1528cc7 100644
--- a/frontend/src/lib/components/PropertyFilters/components/FilterRow.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/FilterRow.tsx
@@ -15,6 +15,8 @@ import { OperandTag } from './OperandTag'
import { PropertyFilterButton } from './PropertyFilterButton'
interface FilterRowProps {
+ header?: React.ReactNode
+ onOpen?: () => void
item: Record<string, any>
index: number
filters: PropertyFilterRow[] | PathCleaningFilter[]
@@ -38,6 +40,8 @@ interface FilterRowProps {
export const FilterRow = React.memo(function FilterRow({
item,
+ onOpen,
+ header,
index,
filters,
pageKey,
@@ -63,6 +67,9 @@ export const FilterRow = React.memo(function FilterRow({
const isValid = isValidPropertyFilter(item)
const handleVisibleChange = (visible: boolean): void => {
+ if (visible) {
+ onOpen?.()
+ }
if (!visible && isValid && !item.key) {
onRemove(index)
}
@@ -101,18 +108,23 @@ export const FilterRow = React.memo(function FilterRow({
className="filter-row-popover"
visible={open}
onClickOutside={() => handleVisibleChange(false)}
- overlay={filterComponent(() => setOpen(false))}
+ overlay={
+ <>
+ {header}
+ {filterComponent(() => setOpen(false))}
+ </>
+ }
>
{isValid ? (
<PropertyFilterButton
- onClick={() => setOpen(!open)}
+ onClick={() => handleVisibleChange(!open)}
onClose={() => onRemove(index)}
item={item}
disabledReason={disabledReason}
/>
) : !disabledReason ? (
<LemonButton
- onClick={() => setOpen(!open)}
+ onClick={() => handleVisibleChange(!open)}
className={clsx('new-prop-filter', labelClassName)}
data-attr={'new-prop-filter-' + pageKey}
type="secondary"
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 7d21d4c22e5e..466a98105dd8 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -485,6 +485,61 @@
"required": ["kind", "definitionId"],
"type": "object"
},
+ "AccountsTableCustomPropertyDefinition": {
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "type": ["string", "null"]
+ },
+ "display_type": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDisplayType"
+ },
+ "has_workflow_reference": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "is_big_number": {
+ "type": "boolean"
+ },
+ "is_canonical": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ },
+ "options": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyOption"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "source": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/AccountsTableCustomPropertySource"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": ["id", "name", "display_type", "is_canonical", "has_workflow_reference"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertyDisplayType": {
+ "enum": ["text", "link", "number", "currency", "percent", "date", "datetime", "boolean", "select"],
+ "type": "string"
+ },
"AccountsTableCustomPropertyFilter": {
"additionalProperties": false,
"properties": {
@@ -563,6 +618,32 @@
],
"type": "string"
},
+ "AccountsTableCustomPropertyOption": {
+ "additionalProperties": false,
+ "properties": {
+ "color": {
+ "type": "string"
+ },
+ "id": {
+ "type": ["string", "null"]
+ },
+ "label": {
+ "type": "string"
+ }
+ },
+ "required": ["label", "color"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertySource": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+ },
"AccountsTableCustomPropertyValue": {
"type": ["string", "number", "boolean", "null"]
},
@@ -673,6 +754,10 @@
},
"type": "array"
},
+ "ignoreMissingDefinitions": {
+ "description": "Omit missing definitions and custom-property filters incompatible with their current types.",
+ "type": "boolean"
+ },
"includeChurned": {
"description": "Include churned accounts. Churned accounts are hidden by default.",
"type": "boolean"
@@ -711,6 +796,9 @@
"tags": {
"$ref": "#/definitions/QueryLogTags"
},
+ "useDefaultColumns": {
+ "type": "boolean"
+ },
"version": {
"description": "version of the node, used for schema migrations",
"type": "number"
@@ -722,6 +810,18 @@
"AccountsTableQueryResponse": {
"additionalProperties": false,
"properties": {
+ "columns": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableResolvedColumn"
+ },
+ "type": "array"
+ },
+ "customPropertyDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDefinition"
+ },
+ "type": "array"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -758,6 +858,12 @@
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
},
+ "relationshipDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRelationshipDefinition"
+ },
+ "type": "array"
+ },
"resolved_compare_date_range": {
"$ref": "#/definitions/ResolvedDateRangeResponse",
"description": "The resolved previous/comparison period date range, when comparing against another period"
@@ -819,6 +925,28 @@
"required": ["kind", "definitionId"],
"type": "object"
},
+ "AccountsTableRelationshipDefinition": {
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "type": ["string", "null"]
+ },
+ "id": {
+ "type": "string"
+ },
+ "is_controlled": {
+ "type": "boolean"
+ },
+ "is_single_holder": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "is_controlled"],
+ "type": "object"
+ },
"AccountsTableRelationshipFilter": {
"additionalProperties": false,
"properties": {
@@ -846,6 +974,33 @@
"enum": ["exact", "is_not", "is_set", "is_not_set"],
"type": "string"
},
+ "AccountsTableResolvedColumn": {
+ "discriminator": {
+ "propertyName": "kind"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/definitions/AccountsTableAccountFieldColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableTagsColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableNoteCountColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableRelationshipColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableCustomPropertyColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableCustomPropertyHistoryColumn"
+ }
+ ],
+ "required": ["kind"],
+ "type": "object"
+ },
"AccountsTableRow": {
"additionalProperties": false,
"properties": {
@@ -7493,6 +7648,18 @@
"description": "What triggered the calculation of the query, leave empty if user/immediate",
"type": "string"
},
+ "columns": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableResolvedColumn"
+ },
+ "type": "array"
+ },
+ "customPropertyDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDefinition"
+ },
+ "type": "array"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -7547,6 +7714,12 @@
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
},
+ "relationshipDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRelationshipDefinition"
+ },
+ "type": "array"
+ },
"resolved_compare_date_range": {
"$ref": "#/definitions/ResolvedDateRangeResponse",
"description": "The resolved previous/comparison period date range, when comparing against another period"
@@ -20832,6 +21005,18 @@
{
"additionalProperties": false,
"properties": {
+ "columns": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableResolvedColumn"
+ },
+ "type": "array"
+ },
+ "customPropertyDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDefinition"
+ },
+ "type": "array"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -20868,6 +21053,12 @@
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
},
+ "relationshipDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRelationshipDefinition"
+ },
+ "type": "array"
+ },
"resolved_compare_date_range": {
"$ref": "#/definitions/ResolvedDateRangeResponse",
"description": "The resolved previous/comparison period date range, when comparing against another period"
@@ -46762,6 +46953,18 @@
{
"additionalProperties": false,
"properties": {
+ "columns": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableResolvedColumn"
+ },
+ "type": "array"
+ },
+ "customPropertyDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDefinition"
+ },
+ "type": "array"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -46798,6 +47001,12 @@
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
},
+ "relationshipDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRelationshipDefinition"
+ },
+ "type": "array"
+ },
"resolved_compare_date_range": {
"$ref": "#/definitions/ResolvedDateRangeResponse",
"description": "The resolved previous/comparison period date range, when comparing against another period"
@@ -48804,6 +49013,18 @@
{
"additionalProperties": false,
"properties": {
+ "columns": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableResolvedColumn"
+ },
+ "type": "array"
+ },
+ "customPropertyDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyDefinition"
+ },
+ "type": "array"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -48840,6 +49061,12 @@
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
},
+ "relationshipDefinitions": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRelationshipDefinition"
+ },
+ "type": "array"
+ },
"resolved_compare_date_range": {
"$ref": "#/definitions/ResolvedDateRangeResponse",
"description": "The resolved previous/comparison period date range, when comparing against another period"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d7be2c9b9417..dee73bd23e5b 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3378,9 +3378,62 @@ export interface AccountsTableRow {
export type CachedAccountsTableQueryResponse = CachedQueryResponse<AccountsTableQueryResponse>
+export type AccountsTableCustomPropertyDisplayType =
+ | 'text'
+ | 'link'
+ | 'number'
+ | 'currency'
+ | 'percent'
+ | 'date'
+ | 'datetime'
+ | 'boolean'
+ | 'select'
+
+export interface AccountsTableCustomPropertySource {
+ id: string
+}
+
+export interface AccountsTableCustomPropertyOption {
+ id?: string | null
+ label: string
+ color: string
+}
+
+export interface AccountsTableCustomPropertyDefinition {
+ id: string
+ name: string
+ description?: string | null
+ display_type: AccountsTableCustomPropertyDisplayType
+ is_big_number?: boolean
+ is_canonical: boolean
+ has_workflow_reference: boolean
+ source?: AccountsTableCustomPropertySource | null
+ options?: AccountsTableCustomPropertyOption[] | null
+}
+
+export interface AccountsTableRelationshipDefinition {
+ id: string
+ name: string
+ description?: string | null
+ is_single_holder?: boolean
+ is_controlled: boolean
+}
+
+/** @discriminator kind */
+export type AccountsTableResolvedColumn =
+ | AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+
export interface AccountsTableQueryResponse extends AnalyticsQueryResponseBase {
kind: NodeKind.AccountsTableQuery
results: AccountsTableRow[]
+ columns?: AccountsTableResolvedColumn[]
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[]
+ relationshipDefinitions?: AccountsTableRelationshipDefinition[]
hasMore: boolean
limit: integer
offset: integer
@@ -3396,6 +3449,9 @@ export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse>
includeIgnored?: boolean
/** Columns to load for each account. Account identity fields are always returned. */
columns: AccountsTableColumn[]
+ useDefaultColumns?: boolean
+ /** Omit missing definitions and custom-property filters incompatible with their current types. */
+ ignoreMissingDefinitions?: boolean
/** Filters are combined with AND. Values within tag and assignment filters use OR. */
filters?: AccountsTableFilter[]
/** Nonempty property-filter groups are ORed together; filters within each group use AND. Global filters still apply. */
diff --git a/posthog/schema.py b/posthog/schema.py
index 54135d61e68b..e6b828e1e8cb 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -16,6 +16,7 @@ from posthog.schema_enums import (
AccountsTableAccountField as AccountsTableAccountField,
AccountsTableAccountFieldOperator as AccountsTableAccountFieldOperator,
AccountsTableAggregation as AccountsTableAggregation,
+ AccountsTableCustomPropertyDisplayType as AccountsTableCustomPropertyDisplayType,
AccountsTableCustomPropertyOperator as AccountsTableCustomPropertyOperator,
AccountsTableRelationshipOperator as AccountsTableRelationshipOperator,
AccountsTableSortDirection as AccountsTableSortDirection,
@@ -441,6 +442,22 @@ class AccountsTableCustomPropertyHistoryPoint(BaseModel):
value: float
+class AccountsTableCustomPropertyOption(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ color: str
+ id: str | None = None
+ label: str
+
+
+class AccountsTableCustomPropertySource(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ id: str
+
+
class AccountsTableNoteCountColumn(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -459,6 +476,17 @@ class AccountsTableRelationshipColumn(BaseModel):
kind: Literal["relationship"] = "relationship"
+class AccountsTableRelationshipDefinition(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ description: str | None = None
+ id: str
+ is_controlled: bool
+ is_single_holder: bool | None = None
+ name: str
+
+
class AccountsTableSearchFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -3713,6 +3741,21 @@ class AccountsTableCountThresholdMetric(BaseModel):
value: float
+class AccountsTableCustomPropertyDefinition(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ description: str | None = None
+ display_type: AccountsTableCustomPropertyDisplayType
+ has_workflow_reference: bool
+ id: str
+ is_big_number: bool | None = None
+ is_canonical: bool
+ name: str
+ options: list[AccountsTableCustomPropertyOption] | None = None
+ source: AccountsTableCustomPropertySource | None = None
+
+
class AccountsTableCustomPropertyFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -10109,6 +10152,18 @@ class AccountsTableQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ columns: (
+ list[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ ]
+ | None
+ ) = None
+ customPropertyDefinitions: list[AccountsTableCustomPropertyDefinition] | None = None
error: str | None = Field(
default=None,
description=(
@@ -10129,6 +10184,7 @@ class AccountsTableQueryResponse(BaseModel):
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
)
+ relationshipDefinitions: list[AccountsTableRelationshipDefinition] | None = None
resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
default=None,
description=("The resolved previous/comparison period date range, when comparing against another period"),
@@ -11796,6 +11852,18 @@ class CachedAccountsTableQueryResponse(BaseModel):
default=None,
description=("What triggered the calculation of the query, leave empty if user/immediate"),
)
+ columns: (
+ list[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ ]
+ | None
+ ) = None
+ customPropertyDefinitions: list[AccountsTableCustomPropertyDefinition] | None = None
error: str | None = Field(
default=None,
description=(
@@ -11824,6 +11892,7 @@ class CachedAccountsTableQueryResponse(BaseModel):
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
)
+ relationshipDefinitions: list[AccountsTableRelationshipDefinition] | None = None
resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
default=None,
description=("The resolved previous/comparison period date range, when comparing against another period"),
@@ -18159,6 +18228,18 @@ class Response20(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ columns: (
+ list[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ ]
+ | None
+ ) = None
+ customPropertyDefinitions: list[AccountsTableCustomPropertyDefinition] | None = None
error: str | None = Field(
default=None,
description=(
@@ -18179,6 +18260,7 @@ class Response20(BaseModel):
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
)
+ relationshipDefinitions: list[AccountsTableRelationshipDefinition] | None = None
resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
default=None,
description=("The resolved previous/comparison period date range, when comparing against another period"),
@@ -23921,6 +24003,18 @@ class QueryResponseAlternative59(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ columns: (
+ list[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ ]
+ | None
+ ) = None
+ customPropertyDefinitions: list[AccountsTableCustomPropertyDefinition] | None = None
error: str | None = Field(
default=None,
description=(
@@ -23941,6 +24035,7 @@ class QueryResponseAlternative59(BaseModel):
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
)
+ relationshipDefinitions: list[AccountsTableRelationshipDefinition] | None = None
resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
default=None,
description=("The resolved previous/comparison period date range, when comparing against another period"),
@@ -25135,6 +25230,18 @@ class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ columns: (
+ list[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ ]
+ | None
+ ) = None
+ customPropertyDefinitions: list[AccountsTableCustomPropertyDefinition] | None = None
error: str | None = Field(
default=None,
description=(
@@ -25155,6 +25262,7 @@ class QueryResponseAlternative89(BaseModel):
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
)
+ relationshipDefinitions: list[AccountsTableRelationshipDefinition] | None = None
resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
default=None,
description=("The resolved previous/comparison period date range, when comparing against another period"),
@@ -27232,6 +27340,10 @@ class AccountsTableQuery(BaseModel):
default=None,
description=("Filters are combined with AND. Values within tag and assignment filters use OR."),
)
+ ignoreMissingDefinitions: bool | None = Field(
+ default=None,
+ description=("Omit missing definitions and custom-property filters incompatible with their current types."),
+ )
includeChurned: bool | None = Field(
default=None,
description="Include churned accounts. Churned accounts are hidden by default.",
@@ -27253,6 +27365,7 @@ class AccountsTableQuery(BaseModel):
response: AccountsTableQueryResponse | None = None
sort: AccountsTableSort | None = None
tags: QueryLogTags | None = None
+ useDefaultColumns: bool | None = None
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 2d6943366901..bdb16538c48a 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -64,6 +64,18 @@ class AccountsTableAggregation(StrEnum):
MEDIAN = "median"
+class AccountsTableCustomPropertyDisplayType(StrEnum):
+ TEXT = "text"
+ LINK = "link"
+ NUMBER = "number"
+ CURRENCY = "currency"
+ PERCENT = "percent"
+ DATE = "date"
+ DATETIME = "datetime"
+ BOOLEAN = "boolean"
+ SELECT = "select"
+
+
class WindowDays(float, Enum):
NUMBER_7 = 7
NUMBER_14 = 14
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 25fb5cb1896d..cb397f302fab 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -17,6 +17,7 @@ Do NOT:
import asyncio
from collections.abc import Iterable
+from dataclasses import replace
from datetime import UTC, date, datetime, time, timedelta
from enum import Enum
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
@@ -124,6 +125,7 @@ from products.customer_analytics.backend.logic.account_filters import (
InvalidAccountFilter,
account_search_q,
apply_account_filters,
+ filter_valid_account_filters,
parse_email_search,
)
from products.customer_analytics.backend.logic.account_logo import resolve_logo_domain
@@ -1514,7 +1516,7 @@ def _definition_source_view(
def list_custom_property_definitions(
team_id: int,
offset: int,
- limit: int,
+ limit: int | None,
*,
user_access_control: "UserAccessControl",
exclude_group_targets: bool = False,
@@ -1532,7 +1534,7 @@ def list_custom_property_definitions(
if target_type is not None:
queryset = queryset.filter(target_type=target_type)
total_count = queryset.count()
- page = list(queryset[offset : offset + limit])
+ page = list(queryset[offset : offset + limit] if limit is not None else queryset)
workflow_references = _custom_property_references_by_definition_id(team_id)
references = filter_hog_flow_references_by_access_level(team_id, workflow_references, user_access_control)
sources: list[CustomPropertySource] = []
@@ -3195,13 +3197,53 @@ def _account_table_field_values(
return values
+@frozen
+class _AccountTableDefinitions:
+ selection: contracts.AccountTableColumnSelection
+ sort: contracts.AccountTableSort | None
+ relationships: dict[UUID, AccountRelationshipDefinition]
+ custom_properties: dict[UUID, CustomPropertyDefinition]
+
+ def filter_supported_filters(
+ self,
+ filters: tuple[contracts.AccountTableFilter, ...],
+ *,
+ ignore_invalid_custom_property_filters: bool,
+ ) -> tuple[contracts.AccountTableFilter, ...]:
+ known_filters = tuple(
+ filter_
+ for filter_ in filters
+ if (
+ not isinstance(
+ filter_, contracts.AccountTableRelationshipFilter | contracts.AccountTableCustomPropertyFilter
+ )
+ or (
+ isinstance(filter_, contracts.AccountTableRelationshipFilter)
+ and filter_.definition_id in self.relationships
+ )
+ or (
+ isinstance(filter_, contracts.AccountTableCustomPropertyFilter)
+ and filter_.definition_id in self.custom_properties
+ )
+ )
+ )
+ if ignore_invalid_custom_property_filters:
+ return filter_valid_account_filters(known_filters, custom_property_display_types=self.display_types)
+ return known_filters
+
+ @property
+ def display_types(self) -> dict[UUID, DisplayType]:
+ return {id_: DisplayType(definition.display_type) for id_, definition in self.custom_properties.items()}
+
+
def _validate_account_table_definitions(
*,
team_id: int,
selection: contracts.AccountTableColumnSelection,
filters: tuple[contracts.AccountTableFilter, ...],
sort: contracts.AccountTableSort | None,
-) -> dict[UUID, DisplayType]:
+ ignore_missing_definitions: bool = False,
+) -> _AccountTableDefinitions:
relationship_ids = set(selection.relationship_definition_ids)
relationship_ids.update(
filter_.definition_id for filter_ in filters if isinstance(filter_, contracts.AccountTableRelationshipFilter)
@@ -3209,18 +3251,28 @@ def _validate_account_table_definitions(
if sort and sort.kind == contracts.AccountTableSortKind.RELATIONSHIP:
if sort.definition_id is None:
raise InvalidAccountTableColumn("Relationship sorting requires a definition.")
- relationship_ids.add(sort.definition_id)
- if relationship_ids:
- valid_relationship_ids = set(
- AccountRelationshipDefinition.objects.for_team(team_id)
- .filter(id__in=relationship_ids)
- .values_list("id", flat=True)
- )
- invalid_relationship_ids = relationship_ids - valid_relationship_ids
- if invalid_relationship_ids:
- invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_relationship_ids))
- raise InvalidAccountTableColumn(f"Unknown relationship definitions: {invalid_ids}")
-
+ if sort.definition_id:
+ relationship_ids.add(sort.definition_id)
+ relationships = AccountRelationshipDefinition.objects.for_team(team_id).order_by("name", "id")
+ if not selection.use_default_columns:
+ relationships = relationships.filter(id__in=relationship_ids)
+ relationship_definitions = {definition.id: definition for definition in relationships}
+ invalid_relationship_ids = relationship_ids - relationship_definitions.keys()
+ if invalid_relationship_ids and not ignore_missing_definitions:
+ invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_relationship_ids))
+ raise InvalidAccountTableColumn(f"Unknown relationship definitions: {invalid_ids}")
+ selected_relationship_ids = set(selection.relationship_definition_ids) & relationship_definitions.keys()
+ if selection.use_default_columns:
+ selected_relationship_ids.update(relationship_definitions)
+ selection = replace(
+ selection,
+ relationship_definition_ids=frozenset(selected_relationship_ids),
+ account_fields=frozenset({contracts.AccountTableField.NAME})
+ if selection.use_default_columns
+ else selection.account_fields,
+ include_tags=selection.use_default_columns or selection.include_tags,
+ include_note_count=selection.use_default_columns or selection.include_note_count,
+ )
custom_property_ids = set(selection.custom_property_definition_ids) | set(selection.custom_property_history_windows)
custom_property_ids.update(
filter_.definition_id for filter_ in filters if isinstance(filter_, contracts.AccountTableCustomPropertyFilter)
@@ -3229,20 +3281,38 @@ def _validate_account_table_definitions(
if sort.definition_id is None:
raise InvalidAccountTableColumn("Custom property sorting requires a definition.")
custom_property_ids.add(sort.definition_id)
- if not custom_property_ids:
- return {}
-
- custom_property_display_types = {
- definition_id: DisplayType(display_type)
- for definition_id, display_type in CustomPropertyDefinition.objects.for_team(team_id)
+ custom_properties = {
+ definition.id: definition
+ for definition in CustomPropertyDefinition.objects.for_team(team_id)
.filter(id__in=custom_property_ids, target_type=TargetType.ACCOUNT)
- .values_list("id", "display_type")
+ .select_related("source")
+ }
+ custom_property_display_types = {
+ id_: DisplayType(definition.display_type) for id_, definition in custom_properties.items()
}
invalid_custom_property_ids = custom_property_ids - set(custom_property_display_types)
- if invalid_custom_property_ids:
+ if invalid_custom_property_ids and not ignore_missing_definitions:
invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_custom_property_ids))
raise InvalidAccountTableColumn(f"Unknown account custom property definitions: {invalid_ids}")
+ selection = replace(
+ selection,
+ custom_property_definition_ids=frozenset(selection.custom_property_definition_ids & custom_properties.keys()),
+ custom_property_history_windows={
+ id_: days for id_, days in selection.custom_property_history_windows.items() if id_ in custom_properties
+ },
+ )
+ if sort and sort.definition_id is not None:
+ if (
+ sort.kind == contracts.AccountTableSortKind.RELATIONSHIP
+ and sort.definition_id not in relationship_definitions
+ ) or (
+ sort.kind == contracts.AccountTableSortKind.CUSTOM_PROPERTY and sort.definition_id not in custom_properties
+ ):
+ sort = None
+ definitions = _AccountTableDefinitions(
+ selection=selection, sort=sort, relationships=relationship_definitions, custom_properties=custom_properties
+ )
non_numeric_history_ids = {
definition_id
for definition_id in selection.custom_property_history_windows
@@ -3251,7 +3321,7 @@ def _validate_account_table_definitions(
if non_numeric_history_ids:
invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in non_numeric_history_ids))
raise InvalidAccountTableColumn(f"Custom property history requires numeric definitions: {invalid_ids}")
- return custom_property_display_types
+ return definitions
LIFECYCLE_ACCOUNT_TABLE_FIELDS = frozenset(
@@ -3445,21 +3515,41 @@ def query_accounts_metrics(
filter_groups: tuple[tuple[contracts.AccountTableFilter, ...], ...] = (),
include_churned: bool = False,
include_ignored: bool = False,
+ ignore_missing_definitions: bool = False,
) -> list[float | int | None]:
definition_ids = frozenset(
metric.definition_id
for metric in metrics
if isinstance(metric, contracts.AccountTableAggregateMetric | contracts.AccountTableCountThresholdMetric)
)
- custom_property_display_types = _validate_account_table_definitions(
+ definitions = _validate_account_table_definitions(
team_id=team_id,
selection=contracts.AccountTableColumnSelection(custom_property_definition_ids=definition_ids),
filters=filters + tuple(filter_ for group in filter_groups for filter_ in group),
sort=None,
+ ignore_missing_definitions=ignore_missing_definitions,
+ )
+ filters = definitions.filter_supported_filters(
+ filters, ignore_invalid_custom_property_filters=ignore_missing_definitions
)
- for definition_id in definition_ids:
- if DATA_TYPE_BY_DISPLAY_TYPE[custom_property_display_types[definition_id]] != DataType.NUMERIC:
- raise InvalidAccountTableColumn("Account table metrics require numeric custom properties.")
+ filter_groups = tuple(
+ known
+ for group in filter_groups
+ if (
+ known := definitions.filter_supported_filters(
+ group, ignore_invalid_custom_property_filters=ignore_missing_definitions
+ )
+ )
+ )
+ custom_property_display_types = definitions.display_types
+ non_numeric_definition_ids = {
+ definition_id
+ for definition_id in definition_ids
+ if definition_id in custom_property_display_types
+ and DATA_TYPE_BY_DISPLAY_TYPE[custom_property_display_types[definition_id]] != DataType.NUMERIC
+ }
+ if non_numeric_definition_ids and not ignore_missing_definitions:
+ raise InvalidAccountTableColumn("Account table metrics require numeric custom properties.")
accounts = _accounts_queryset(team_id, user_access_control)
if not filter_groups:
@@ -3484,6 +3574,11 @@ def query_accounts_metrics(
aggregate_expressions: dict[str, Aggregate] = {}
for index, metric in enumerate(metrics):
alias = f"metric_{index}"
+ if isinstance(metric, contracts.AccountTableAggregateMetric | contracts.AccountTableCountThresholdMetric) and (
+ metric.definition_id not in custom_property_display_types
+ or metric.definition_id in non_numeric_definition_ids
+ ):
+ continue
if isinstance(metric, contracts.AccountTableAggregateMetric):
aggregate_type = {
contracts.AccountTableAggregation.SUM: Sum,
@@ -3518,6 +3613,8 @@ def query_accounts_metrics(
)
aggregated = values.aggregate(**aggregate_expressions)
for index, metric in enumerate(metrics):
+ if f"metric_{index}" not in aggregated:
+ continue
value = aggregated.get(f"metric_{index}")
if isinstance(metric, contracts.AccountTableAggregateMetric) and value is not None:
results[index] = float(value) * (metric.scale if metric.scale is not None else 1)
@@ -3546,14 +3643,32 @@ def query_accounts_table(
filter_groups: tuple[tuple[contracts.AccountTableFilter, ...], ...] = (),
include_churned: bool = False,
include_ignored: bool = False,
+ ignore_missing_definitions: bool = False,
) -> contracts.AccountTablePage:
- custom_property_display_types = _validate_account_table_definitions(
+ definitions = _validate_account_table_definitions(
team_id=team_id,
selection=selection,
filters=filters + tuple(filter_ for group in filter_groups for filter_ in group),
sort=sort,
+ ignore_missing_definitions=ignore_missing_definitions,
)
+ filters = definitions.filter_supported_filters(
+ filters, ignore_invalid_custom_property_filters=ignore_missing_definitions
+ )
+ filter_groups = tuple(
+ known
+ for group in filter_groups
+ if (
+ known := definitions.filter_supported_filters(
+ group, ignore_invalid_custom_property_filters=ignore_missing_definitions
+ )
+ )
+ )
+ custom_property_display_types = definitions.display_types
+ selection = definitions.selection
+ sort = definitions.sort
+
queryset = _accounts_queryset(team_id, user_access_control)
if not filter_groups:
queryset = _filter_out_hidden_lifecycle_accounts(
@@ -3681,7 +3796,49 @@ def query_accounts_table(
)
for account in accounts
]
- return contracts.AccountTablePage(rows=rows, has_more=has_more, limit=limit, offset=offset)
+ workflow_reference_ids: frozenset[str] = (
+ frozenset(
+ cast(
+ list[str],
+ cache.get_or_set(
+ f"customer_analytics:account_table_workflow_references:{team_id}",
+ lambda: list(_custom_property_references_by_definition_id(team_id)),
+ timeout=60,
+ ),
+ )
+ )
+ if definitions.custom_properties
+ else frozenset()
+ )
+ property_definitions = []
+ for definition in definitions.custom_properties.values():
+ try:
+ source_id = definition.source.id
+ except CustomPropertySource.DoesNotExist:
+ source_id = None
+ property_definitions.append(
+ contracts.AccountTableCustomPropertyDefinition(
+ id=definition.id,
+ name=definition.name,
+ description=definition.description,
+ display_type=definition.display_type,
+ is_big_number=definition.is_big_number,
+ is_canonical=definition.name in CANONICAL_DISPLAY_TYPE_BY_NAME,
+ has_workflow_reference=str(definition.id) in workflow_reference_ids,
+ source_id=source_id,
+ options=definition.options,
+ )
+ )
+ return contracts.AccountTablePage(
+ rows=rows,
+ has_more=has_more,
+ limit=limit,
+ offset=offset,
+ relationship_definitions=[
+ _to_account_relationship_definition(definition) for definition in definitions.relationships.values()
+ ],
+ custom_property_definitions=property_definitions,
+ )
def list_accounts_for_view(
@@ -5101,11 +5258,11 @@ def _to_account_relationship(relationship: AccountRelationship) -> contracts.Acc
def list_account_relationship_definitions(
- team_id: int, offset: int = 0, limit: int = 100
+ team_id: int, offset: int = 0, limit: int | None = 100
) -> tuple[list[contracts.AccountRelationshipDefinition], int]:
queryset = AccountRelationshipDefinition.objects.for_team(team_id).order_by("name")
total_count = queryset.count()
- page = queryset[offset : offset + limit]
+ page = queryset[offset : offset + limit] if limit is not None else queryset
return [_to_account_relationship_definition(definition) for definition in page], total_count
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 22d194021395..2a0907267131 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -269,6 +269,7 @@ class AccountTableField(str, Enum):
@dataclass(frozen=True, kw_only=True)
class AccountTableColumnSelection:
+ use_default_columns: bool = False
account_fields: frozenset[AccountTableField] = frozenset()
include_tags: bool = False
include_note_count: bool = False
@@ -531,8 +532,23 @@ class AccountTableRow:
custom_property_history: dict[UUID, list[AccountTableCustomPropertyHistoryPoint]] = field(default_factory=dict)
+@dataclass(frozen=True, kw_only=True)
+class AccountTableCustomPropertyDefinition:
+ id: UUID
+ name: str
+ description: str | None
+ display_type: str
+ is_big_number: bool
+ is_canonical: bool
+ has_workflow_reference: bool
+ source_id: UUID | None
+ options: list[dict[str, str]] | None
+
+
@dataclass(frozen=True, kw_only=True)
class AccountTablePage:
+ relationship_definitions: list[AccountRelationshipDefinition] = field(default_factory=list)
+ custom_property_definitions: list[AccountTableCustomPropertyDefinition] = field(default_factory=list)
rows: list[AccountTableRow]
has_more: bool
limit: int
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
index 1dc2b105f615..9a3f73de62b8 100644
--- a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
@@ -5,6 +5,7 @@ from uuid import UUID
from rest_framework.exceptions import ValidationError
from posthog.schema import (
+ AccountsTableAccountField,
AccountsTableAccountFieldColumn,
AccountsTableAccountFieldFilter,
AccountsTableAccountIdFilter,
@@ -14,13 +15,18 @@ from posthog.schema import (
AccountsTableCountMetric,
AccountsTableCountThresholdMetric,
AccountsTableCustomPropertyColumn,
+ AccountsTableCustomPropertyDefinition,
+ AccountsTableCustomPropertyDisplayType,
AccountsTableCustomPropertyFilter,
AccountsTableCustomPropertyHistoryColumn,
AccountsTableCustomPropertyHistoryPoint,
+ AccountsTableCustomPropertyOption,
+ AccountsTableCustomPropertySource,
AccountsTableNoteCountColumn,
AccountsTableQuery,
AccountsTableQueryResponse,
AccountsTableRelationshipColumn,
+ AccountsTableRelationshipDefinition,
AccountsTableRelationshipFilter,
AccountsTableRow,
AccountsTableSearchFilter,
@@ -60,6 +66,16 @@ AccountsTableQueryFilter = (
)
+AccountsTableResolvedQueryColumn = (
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+)
+
+
class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse]):
query: AccountsTableQuery
cached_response: CachedAccountsTableQueryResponse
@@ -101,7 +117,7 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
custom_property_history_windows: dict[UUID, int] = {}
try:
- for column in self.query.columns:
+ for column in [] if self.query.useDefaultColumns else self.query.columns:
if isinstance(column, AccountsTableAccountFieldColumn):
account_fields.add(contracts.AccountTableField(column.field.value))
elif isinstance(column, AccountsTableTagsColumn):
@@ -123,6 +139,7 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
raise ValidationError("Account table definition IDs must be valid UUIDs.") from error
return contracts.AccountTableColumnSelection(
+ use_default_columns=bool(self.query.useDefaultColumns),
account_fields=frozenset(account_fields),
include_tags=include_tags,
include_note_count=include_note_count,
@@ -285,6 +302,32 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
raise ValidationError("Account table metric definition IDs must be valid UUIDs.") from error
return tuple(metrics)
+ def _resolved_columns(self, page: contracts.AccountTablePage) -> list[AccountsTableResolvedQueryColumn]:
+ if self.query.useDefaultColumns:
+ return [
+ AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME),
+ AccountsTableTagsColumn(),
+ AccountsTableNoteCountColumn(),
+ *[
+ AccountsTableRelationshipColumn(definitionId=str(definition.id))
+ for definition in page.relationship_definitions
+ ],
+ ]
+ else:
+ resolved_columns: list[AccountsTableResolvedQueryColumn] = []
+ for column in self.query.columns:
+ if isinstance(column, AccountsTableRelationshipColumn):
+ if any(str(definition.id) == column.definitionId for definition in page.relationship_definitions):
+ resolved_columns.append(column)
+ elif isinstance(column, AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn):
+ if any(
+ str(definition.id) == column.definitionId for definition in page.custom_property_definitions
+ ):
+ resolved_columns.append(column)
+ else:
+ resolved_columns.append(column)
+ return resolved_columns
+
def _calculate(self) -> AccountsTableQueryResponse:
user_access_control = self.user_access_control
if user_access_control is None:
@@ -309,6 +352,7 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
metrics=self._metrics(),
include_churned=bool(self.query.includeChurned),
include_ignored=bool(self.query.includeIgnored),
+ ignore_missing_definitions=bool(self.query.ignoreMissingDefinitions),
)
return AccountsTableQueryResponse(
results=[],
@@ -328,11 +372,46 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
limit=limit,
include_churned=bool(self.query.includeChurned),
include_ignored=bool(self.query.includeIgnored),
+ ignore_missing_definitions=bool(self.query.ignoreMissingDefinitions),
)
except api.InvalidAccountTableColumn as error:
raise ValidationError(str(error)) from error
return AccountsTableQueryResponse(
+ columns=self._resolved_columns(page),
+ relationshipDefinitions=[
+ AccountsTableRelationshipDefinition(
+ id=str(definition.id),
+ name=definition.name,
+ description=definition.description,
+ is_single_holder=definition.is_single_holder,
+ is_controlled=definition.is_controlled,
+ )
+ for definition in page.relationship_definitions
+ ],
+ customPropertyDefinitions=[
+ AccountsTableCustomPropertyDefinition(
+ id=str(definition.id),
+ name=definition.name,
+ description=definition.description,
+ display_type=AccountsTableCustomPropertyDisplayType(definition.display_type),
+ is_big_number=definition.is_big_number,
+ is_canonical=definition.is_canonical,
+ has_workflow_reference=definition.has_workflow_reference,
+ source=AccountsTableCustomPropertySource(id=str(definition.source_id))
+ if definition.source_id
+ else None,
+ options=[
+ AccountsTableCustomPropertyOption(
+ id=option.get("id"), label=option["label"], color=option["color"]
+ )
+ for option in definition.options
+ ]
+ if definition.options is not None
+ else None,
+ )
+ for definition in page.custom_property_definitions
+ ],
results=[
AccountsTableRow(
id=str(row.id),
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
index 7841236b093f..02d6fdbdbe25 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -5,6 +5,7 @@ import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
+from django.core.cache import cache
from django.utils import timezone
from parameterized import parameterized
@@ -76,6 +77,92 @@ class TestAccountsTableQueryRunner(BaseTest):
def _run(self, query: AccountsTableQuery) -> AccountsTableQueryResponse:
return AccountsTableQueryRunner(query=query, team=self.team, user=self.user).calculate()
+ def test_resolves_default_columns_and_metadata_without_accounts(self) -> None:
+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM"
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ AccountRelationshipDefinition.objects.for_team(other_team.id).create(team_id=other_team.id, name="Private role")
+
+ response = self._run(AccountsTableQuery(columns=[], useDefaultColumns=True))
+
+ assert response.results == []
+ assert response.columns == [
+ AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME),
+ AccountsTableTagsColumn(),
+ AccountsTableNoteCountColumn(),
+ AccountsTableRelationshipColumn(definitionId=str(definition.id)),
+ ]
+ assert response.relationshipDefinitions is not None
+ assert [(item.id, item.name) for item in response.relationshipDefinitions] == [(str(definition.id), "CSM")]
+
+ def test_returns_filter_definition_metadata_without_selecting_its_values(self) -> None:
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name="Tier", display_type=DisplayType.SELECT
+ )
+ definition.options = [{"id": "option-1", "label": "Standard", "color": "preset-1"}]
+ definition.save(update_fields=["options"])
+ account = create_account(team_id=self.team.id, name="Unset")
+
+ response = self._run(
+ AccountsTableQuery(
+ columns=[AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME)],
+ filters=[
+ AccountsTableCustomPropertyFilter(
+ definitionId=str(definition.id), operator=AccountsTableCustomPropertyOperator.IS_NOT_SET
+ )
+ ],
+ )
+ )
+
+ assert response.results[0].id == str(account.id)
+ assert response.results[0].customProperties == {}
+ assert response.customPropertyDefinitions is not None
+ metadata = response.customPropertyDefinitions[0]
+ assert metadata.id == str(definition.id)
+ assert metadata.name == "Tier"
+ assert metadata.display_type == "select"
+ assert metadata.options is not None
+ assert metadata.options[0].label == "Standard"
+ assert not metadata.is_canonical
+ assert metadata.source is None
+
+ def test_saved_view_omits_deleted_columns_and_sort_without_blocking_rows(self) -> None:
+ account = create_account(team_id=self.team.id, name="Remaining account")
+ deleted = create_custom_property_definition(
+ team_id=self.team.id, name="Removed score", display_type=DisplayType.NUMBER
+ )
+ deleted_id = str(deleted.id)
+ deleted.delete()
+ deleted_relationship = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="Removed role"
+ )
+ relationship_id = str(deleted_relationship.id)
+ deleted_relationship.delete()
+ name_column = AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME)
+ deleted_column = AccountsTableCustomPropertyColumn(definitionId=deleted_id)
+
+ response = self._run(
+ AccountsTableQuery(
+ columns=[
+ name_column,
+ deleted_column,
+ AccountsTableCustomPropertyHistoryColumn(definitionId=deleted_id, windowDays=7),
+ AccountsTableRelationshipColumn(definitionId=relationship_id),
+ ],
+ sort=AccountsTableSort(column=deleted_column, direction=AccountsTableSortDirection.ASC),
+ ignoreMissingDefinitions=True,
+ )
+ )
+
+ assert response.columns == [name_column]
+ assert [row.id for row in response.results] == [str(account.id)]
+ assert response.results[0].customProperties == {}
+ assert response.results[0].customPropertyHistory == {}
+ assert response.results[0].relationships == {}
+ assert response.customPropertyDefinitions == []
+ assert response.relationshipDefinitions == []
+
def test_returns_requested_postgres_cells_with_typed_defaults(self) -> None:
empty_account = create_account(team_id=self.team.id, name="Empty")
cleared_account = create_account(team_id=self.team.id, name="Cleared", external_id="cleared")
@@ -322,6 +409,81 @@ class TestAccountsTableQueryRunner(BaseTest):
assert remaining_response.results == []
assert remaining_response.metricsResults == [12.5, 1]
+ definition.display_type = DisplayType.TEXT
+ definition.save(update_fields=["display_type"])
+ restored = self._run(
+ AccountsTableQuery(
+ columns=[],
+ ignoreMissingDefinitions=True,
+ metrics=[
+ AccountsTableCountMetric(),
+ AccountsTableAggregateMetric(aggregation=AccountsTableAggregation.SUM, column=column),
+ ],
+ )
+ )
+ assert restored.metricsResults == [3, None]
+ with self.assertRaises(ValidationError):
+ self._run(
+ AccountsTableQuery(
+ columns=[],
+ metrics=[AccountsTableAggregateMetric(aggregation=AccountsTableAggregation.SUM, column=column)],
+ )
+ )
+
+ @parameterized.expand(
+ [
+ ("comparison_on_text", DisplayType.TEXT, AccountsTableCustomPropertyOperator.GT, [10]),
+ ("equality_on_number", DisplayType.NUMBER, AccountsTableCustomPropertyOperator.EXACT, ["gold"]),
+ ("contains_on_number", DisplayType.NUMBER, AccountsTableCustomPropertyOperator.ICONTAINS, ["large"]),
+ ("date_on_text", DisplayType.TEXT, AccountsTableCustomPropertyOperator.IS_DATE_AFTER, ["2026-01-01"]),
+ ]
+ )
+ def test_recovers_saved_filters_with_incompatible_property_types(
+ self,
+ _name: str,
+ display_type: DisplayType,
+ operator: AccountsTableCustomPropertyOperator,
+ values: list[int] | list[str],
+ ) -> None:
+ definition = create_custom_property_definition(team_id=self.team.id, name="Changed", display_type=display_type)
+ account = create_account(team_id=self.team.id, name="Visible")
+ other = create_account(team_id=self.team.id, name="Other")
+ query = AccountsTableQuery(
+ columns=[AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME)],
+ filterGroups=[
+ [
+ AccountsTableCustomPropertyFilter(
+ definitionId=str(definition.id), operator=operator, values=values
+ ),
+ AccountsTableAccountFieldFilter(
+ field=AccountsTableAccountField.NAME,
+ operator=AccountsTableAccountFieldOperator.EXACT,
+ values=["Visible"],
+ ),
+ ]
+ ],
+ )
+ with self.assertRaises(ValidationError):
+ self._run(query)
+
+ query.ignoreMissingDefinitions = True
+ assert query.filterGroups is not None
+ invalid_filter, valid_filter = query.filterGroups[0]
+ for split_groups in (False, True):
+ query.filterGroups = (
+ [[invalid_filter], [valid_filter]] if split_groups else [[invalid_filter, valid_filter]]
+ )
+ rows = self._run(query)
+ metrics = self._run(query.model_copy(update={"columns": [], "metrics": [AccountsTableCountMetric()]}))
+ assert [row.id for row in rows.results] == [str(account.id)]
+ assert metrics.metricsResults == [1]
+
+ query.filterGroups = [[invalid_filter]]
+ rows = self._run(query)
+ metrics = self._run(query.model_copy(update={"columns": [], "metrics": [AccountsTableCountMetric()]}))
+ assert {row.id for row in rows.results} == {str(account.id), str(other.id)}
+ assert metrics.metricsResults == [2]
+
def test_hydrates_custom_properties_with_bounded_queries(self) -> None:
definition = create_custom_property_definition(
team_id=self.team.id,
@@ -337,8 +499,27 @@ class TestAccountsTableQueryRunner(BaseTest):
value_num=index,
)
- with self.assertNumQueries(7):
- page = api.query_accounts_table(
+ cache.delete(f"customer_analytics:account_table_workflow_references:{self.team.id}")
+ with patch(
+ "products.customer_analytics.backend.facade.api._custom_property_references_by_definition_id",
+ wraps=api._custom_property_references_by_definition_id,
+ ) as references:
+ with self.assertNumQueries(9):
+ page = api.query_accounts_table(
+ team_id=self.team.id,
+ user_access_control=UserAccessControl(user=self.user, team=self.team),
+ selection=contracts.AccountTableColumnSelection(
+ custom_property_definition_ids=frozenset({definition.id})
+ ),
+ filters=(),
+ sort=None,
+ offset=0,
+ limit=100,
+ )
+
+ assert {row.custom_properties[definition.id] for row in page.rows} == {0.0, 1.0, 2.0}
+
+ api.query_accounts_table(
team_id=self.team.id,
user_access_control=UserAccessControl(user=self.user, team=self.team),
selection=contracts.AccountTableColumnSelection(
@@ -346,11 +527,10 @@ class TestAccountsTableQueryRunner(BaseTest):
),
filters=(),
sort=None,
- offset=0,
- limit=100,
+ offset=1,
+ limit=1,
)
-
- assert {row.custom_properties[definition.id] for row in page.rows} == {0.0, 1.0, 2.0}
+ assert references.call_count == 1
def test_resolves_the_logo_domain_from_account_properties(self) -> None:
from_website_domain = create_account(
diff --git a/products/customer_analytics/backend/logic/account_filters.py b/products/customer_analytics/backend/logic/account_filters.py
index 75f171ac8eab..cc376f55c0e8 100644
--- a/products/customer_analytics/backend/logic/account_filters.py
+++ b/products/customer_analytics/backend/logic/account_filters.py
@@ -285,6 +285,24 @@ def _custom_property_filter_predicate(
raise InvalidAccountFilter(f"Unsupported custom property filter operator: {operator.value}")
+def filter_valid_account_filters(
+ filters: tuple[contracts.AccountTableFilter, ...],
+ *,
+ custom_property_display_types: dict[UUID, DisplayType],
+) -> tuple[contracts.AccountTableFilter, ...]:
+ valid_filters: list[contracts.AccountTableFilter] = []
+ for filter_ in filters:
+ if isinstance(filter_, contracts.AccountTableCustomPropertyFilter):
+ try:
+ _custom_property_filter_predicate(
+ filter_, custom_property_display_types[filter_.definition_id], timezone_info=UTC_TIMEZONE
+ )
+ except InvalidAccountFilter:
+ continue
+ valid_filters.append(filter_)
+ return tuple(valid_filters)
+
+
def apply_account_filters(
queryset: QuerySet[Account],
*,
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 52b6c0f8300c..1eba7d332741 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import json
import builtins
+from collections.abc import Callable, Sequence
from dataclasses import asdict
from functools import cached_property
from typing import Any, Protocol, cast
@@ -33,6 +34,7 @@ from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.serializers import BaseSerializer
from rest_framework.throttling import UserRateThrottle
from posthog.api.mixins import ValidatedRequest, validated_request
@@ -1267,10 +1269,30 @@ def _profile_config_write_fields(validated, raw_data: dict) -> dict:
return fields
+class _DefinitionPaginationMixin(_FacadePaginationMixin):
+ def _paginate_via_facade(
+ self,
+ request: Request,
+ fetch: Callable[..., tuple[Sequence[object], int]],
+ serializer_class: type[BaseSerializer],
+ ) -> Response:
+ if request.query_params.get("pagination") == "none":
+ page, count = fetch(offset=0, limit=None)
+ return Response(
+ {
+ "count": count,
+ "next": None,
+ "previous": None,
+ "results": serializer_class(instance=page, many=True).data,
+ }
+ )
+ return super()._paginate_via_facade(request, fetch, serializer_class)
+
+
class CustomPropertyDefinitionViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
+ _DefinitionPaginationMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@@ -1286,6 +1308,16 @@ class CustomPropertyDefinitionViewSet(
serializer_class = CustomPropertyDefinitionSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ name="pagination",
+ type=str,
+ enum=["none"],
+ description="Return all definitions in one response when set to none.",
+ )
+ ]
+ )
def list(self, request: Request, *args, **kwargs) -> Response:
# Callers without group read authorization don't see group-target definitions.
exclude_group_targets = not _has_group_scope(request, write=False)
@@ -1456,13 +1488,23 @@ def _custom_property_option_dicts(options) -> list[dict] | None:
class AccountRelationshipDefinitionViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
+ _DefinitionPaginationMixin,
viewsets.ModelViewSet,
):
scope_object = "account"
serializer_class = AccountRelationshipDefinitionSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ name="pagination",
+ type=str,
+ enum=["none"],
+ description="Return all definitions in one response when set to none.",
+ )
+ ]
+ )
def list(self, request: Request, *args, **kwargs) -> Response:
return self._paginate_via_facade(
request,
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index edca3f4d1fc7..c3ecf775d257 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -1834,6 +1834,21 @@ class TestCustomPropertyDefinitionViewSet(APIBaseTest):
super().setUp()
self.endpoint_base = f"/api/environments/{self.team.id}/custom_property_definitions/"
+ def test_list_without_pagination_preserves_envelope(self):
+ self._create(name="A")
+ self._create(name="B")
+ paginated = self.client.get(self.endpoint_base, {"limit": 1})
+ complete = self.client.get(self.endpoint_base, {"limit": "1", "offset": "1", "pagination": "none"})
+
+ self.assertEqual(paginated.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(paginated.json()["results"]), 1)
+ self.assertIsNotNone(paginated.json()["next"])
+ self.assertEqual(complete.status_code, status.HTTP_200_OK)
+ self.assertEqual([definition["name"] for definition in complete.json()["results"]], ["A", "B"])
+ self.assertEqual(complete.json()["count"], 2)
+ self.assertIsNone(complete.json()["next"])
+ self.assertIsNone(complete.json()["previous"])
+
def _create(self, **overrides):
payload = {"name": "ARR", "display_type": "currency", "is_big_number": True}
payload.update(overrides)
@@ -3012,6 +3027,21 @@ class TestAccountRelationshipDefinitionViewSet(APIBaseTest):
super().setUp()
self.endpoint_base = f"/api/projects/{self.team.id}/account_relationship_definitions/"
+ def test_list_without_pagination_preserves_envelope(self):
+ self._create(name="A")
+ self._create(name="B")
+ paginated = self.client.get(self.endpoint_base, {"limit": 1})
+ complete = self.client.get(self.endpoint_base, {"limit": "1", "offset": "1", "pagination": "none"})
+
+ self.assertEqual(paginated.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(paginated.json()["results"]), 1)
+ self.assertIsNotNone(paginated.json()["next"])
+ self.assertEqual(complete.status_code, status.HTTP_200_OK)
+ self.assertEqual([definition["name"] for definition in complete.json()["results"]], ["A", "B"])
+ self.assertEqual(complete.json()["count"], 2)
+ self.assertIsNone(complete.json()["next"])
+ self.assertIsNone(complete.json()["previous"])
+
def _create(self, **overrides):
payload = {"name": "CSM", "description": "Customer success manager"}
payload.update(overrides)
diff --git a/products/customer_analytics/frontend/components/AccountPropertiesInput/accountPropertiesInputLogic.ts b/products/customer_analytics/frontend/components/AccountPropertiesInput/accountPropertiesInputLogic.ts
index 9080fc592ab2..8526ae2c4c73 100644
--- a/products/customer_analytics/frontend/components/AccountPropertiesInput/accountPropertiesInputLogic.ts
+++ b/products/customer_analytics/frontend/components/AccountPropertiesInput/accountPropertiesInputLogic.ts
@@ -6,6 +6,9 @@ import { projectLogic } from 'scenes/projectLogic'
import { customPropertyDefinitionsList } from 'products/customer_analytics/frontend/generated/api'
import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { loadAllPages } from 'products/customer_analytics/frontend/utils'
+
+const DEFINITIONS_PAGE_SIZE = 300
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountPropertiesInputLogicValues {
@@ -54,10 +57,13 @@ export const accountPropertiesInputLogic = kea<accountPropertiesInputLogicType>(
definitions: [
[] as CustomPropertyDefinitionApi[],
{
- loadDefinitions: async (): Promise<CustomPropertyDefinitionApi[]> => {
- const response = await customPropertyDefinitionsList(String(values.currentProjectId))
- return response.results
- },
+ loadDefinitions: async (): Promise<CustomPropertyDefinitionApi[]> =>
+ loadAllPages((offset) =>
+ customPropertyDefinitionsList(String(values.currentProjectId), {
+ limit: DEFINITIONS_PAGE_SIZE,
+ offset,
+ })
+ ),
},
],
})),
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index aa09699cf8bd..c9bc30447df3 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -84,10 +84,10 @@ Selecting users or checking "My accounts" narrows the assigned status to those u
Legacy compatibility: a saved view or shared link created before this field defaulted to assigned-only, so any persisted filters object with no `assignmentStatus` resolves to `assigned` (an old `unassigned: true` resolves to `unassigned`) — they never silently broaden to `all`.
New saved views always store `assignmentStatus`. Fresh list defaults use `all`. Legacy snapshot links remain readable, but new links identify a saved view with `?view=<id>`.
-Overview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:
+Overview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or saved-view state is still loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:
- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, `externalId`, and `logoDomain`. This is the row's identity: `id` (the account PK) drives expansion, scroll, and role updates; `externalId` is the copyable group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. `AccountNameCell.tsx` owns the shared name, deep link, and copyable external ID presentation. `AccountsTableNameCell.tsx` owns list selection behavior. The Accounts list passes `logoDomain`, which adds `AccountLogo`. Other account tables omit the logo and use normal deep-link navigation.
-- **relationship columns** — returned in `AccountsTableRow.relationships` as arrays of active assignee user ids keyed by definition id (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain stored in defaults, saved views, and URL state, then translate into typed relationship columns matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Each `MemberSelect` builds its searchable member options only while open. Mounting closed table cells does not alter shared member search, and closing a picker clears its search before the next open. Sorting uses the alias directly (arrays of ids — deterministic but not email order).
+- **relationship columns** — returned in `AccountsTableRow.relationships` as arrays of active assignee user ids keyed by definition id (`[]` when unassigned). Defaults and picker selections use relationship definition IDs with `rel_<id-without-hyphens>` aliases. Saved views preserve these expressions, and `aliasToRelationshipDefinition` resolves their display names. See the [stored column format](../../../../../docs/internal/customer-analytics/accounts-table.md#table-columns-and-definitions). Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Each `MemberSelect` builds its searchable member options only while open. Mounting closed table cells does not alter shared member search, and closing a picker clears its search before the next open. Sorting uses the alias directly (arrays of ids — deterministic but not email order).
### Account logos
@@ -106,9 +106,9 @@ The `tag_names` cell is editable in place: `TagsCell` renders the editable `Obje
The Accounts table sets `editorFullWidth` so the tag editor fits its column after a manual resize. The `EditableTagsInNarrowContainer` ObjectTags story checks the narrow editor layout.
-Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_DEFAULT_COLUMNS` is the stored-state seed name, but execution is fully typed. Once `loadRelationshipDefinitionsSuccess` fires, still-default columns upgrade to `defaultSelectColumns`. The name column is force-kept because removing it breaks identity, scroll, and role edits. `buildAccountColumnGroups` offers tags as one `tags` option with the `tags` type under Account properties instead of exposing the raw tags join fields. Restoring a saved view maps the old raw `names` expression to this column and removes the unsupported raw `account_id` expression. It also offers typed account fields, notes, relationships, and custom properties. Warehouse-backed columns, arbitrary lazy joins, and SQL expressions are unsupported. Older saved expressions are omitted from the query plan.
+Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_DEFAULT_COLUMNS` is the stored-state seed name, but execution is fully typed. Default requests send `useDefaultColumns: true`. The backend resolves defaults and returns ordered `columns`. `hydrateTableDefinitions` updates displayed defaults without changing the request. The name column is force-kept because removing it breaks identity, scroll, and role edits. `buildAccountColumnGroups` offers tags as one `tags` option with the `tags` type under Account properties instead of exposing the raw tags join fields. Restoring a saved view maps the old raw `names` expression to this column and removes the unsupported raw `account_id` expression. It also offers typed account fields, notes, relationships, and custom properties. Warehouse-backed columns, arbitrary lazy joins, and SQL expressions are unsupported. Older saved expressions are omitted from the query plan.
-**Custom property columns** surface the team's `CustomPropertyDefinition`s (loaded in `accountsColumnConfigLogic` via the generated `customPropertyDefinitionsList`) as a "Custom properties" picker group. Each is selected as ``accounts.custom_properties.values.`<definition-id>` AS cp_<id>`` — a JSON dot-access through the `custom_properties` lazy join on `system.accounts` (backed by the `customer_analytics_custompropertyvalue` EAV table; one JOIN regardless of column count). Because the alias is an opaque `cp_<id>`, every label-bearing surface must resolve it back via the `aliasToDefinition` selector: the table header (`useContextColumns` in `AccountsTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, link→new-tab URL, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). Server-side sorting uses the typed custom property reference, and the backend chooses the value column from the definition's display type. The stored sort state (URL hash, saved views) keeps the clean column name. Numeric custom properties are also selectable in the **overview tiles** sum/avg/min/max/median/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.
+**Custom property columns** surface the team's `CustomPropertyDefinition`s (selected metadata comes from the table response. Column, filter, and overview pickers request the full catalogs through `accountsColumnConfigLogic.ensureDefinitionsLoaded`, using `pagination=none` once per definition type) as a "Custom properties" picker group. Stored expressions use ``accounts.custom_properties.values.`<definition-id>` AS cp_<id>``. The query planner converts them to typed IDs. The backend reads current values in a batch for the page. Because the alias is an opaque `cp_<id>`, every label-bearing surface must resolve it back via the `aliasToDefinition` selector: the table header (`useContextColumns` in `AccountsTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, link→new-tab URL, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). Server-side sorting uses the typed custom property reference, and the backend chooses the value column from the definition's display type. Saved views store the column alias for sorting. Numeric custom properties are also selectable in the **overview tiles** sum/avg/min/max/median/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.
**Custom property display modes (sparkline/trend)** let numeric custom property columns render their value history instead of the current value.
The per-view config lives in `accountsColumnConfigLogic.columnDisplay` (`Record<definitionId, { mode: 'sparkline' | 'trend', window_days }>`), edited from the Configure Columns modal's edit section (the pencil on a custom-property row swaps the modal's bottom half from "Available columns" to the display editor).
@@ -122,7 +122,7 @@ Relationship options come from the team's relationship definitions. They use the
Native fields cover names, external and connection IDs, created and updated timestamps, and the `churned_at` and `ignored_at` lifecycle timestamps. Text fields support exact, negative, contains, and set operators. Timestamp fields support exact date, before, after, and set operators. A lifecycle timestamp filter with any operator except `is not set` lifts both default hides before applying its predicate, so `Ignored at is set` returns every ignored account, churned ones included, while an unfiltered list still hides them. Track Rules skip churned accounts, so a churned account keeps its `ignored_at`.
Custom property options come from `accountsColumnConfigLogic.customPropertyTaxonomicOptions` via `optionsFromProp`. The filter `key` is the stable definition ID, and the definition name rides on the filter's `label` for display.
Operator sets honor each field's type because `accountsColumnConfigLogic` seeds `propertyDefinitionsModel` under `PropertyDefinitionType.Account` and `PropertyDefinitionType.AccountCustomProperty`. The dropdown is narrowed to operators the Postgres runner supports. Regex and negative regex operators are not available.
-`accountsTableQuery.ts` translates all three filter kinds into typed query filters. The backend filters relationships through active assignments, native model or JSON fields directly, and custom properties through storage chosen from the definition type. Negative operators include accounts where the value is unset. Invalid native combinations and deleted or incompatible custom properties are omitted rather than changing query engines.
+`accountsTableQuery.ts` translates all three filter kinds into typed query filters. The backend filters relationships through active assignments, native model or JSON fields directly, and custom properties through storage chosen from the definition type. Negative operators include accounts where the value is unset. The frontend rejects unsupported native combinations. The backend validates custom-property operators and resolves missing filter definitions when the Accounts UI requests it. Catalog failures preserve active filters.
Custom property value suggestions load from `GET /api/projects/:team_id/custom_property_definitions/values/?key=<definition-id>&value=<search>`. Native account fields do not fetch suggestions.
A custom-property column is editable unless its definition is canonical or has a data warehouse source. Workflow-referenced properties stay editable and show a warning that a future workflow run overwrites a manual value. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. In inline edit mode, the input fits the available column width. Save and Cancel stay together and wrap below the input when needed, aligned to the right. Wrapped controls have an 8px gap between rows. The row grows without widening the column. Date and datetime properties use the Lemon Calendar picker and save from its Apply action. Link properties reject values outside HTTP and HTTPS before saving. Every inline editor offers Clear value with confirmation, including date and datetime editors. Clearing writes `null`, which remains an explicit override so the cell shows an unset value while the query refreshes. An absent override is `undefined`, not `null`. `accountsLogic.updateAccountCustomProperty` writes through the generated custom-property-values endpoint, blocks duplicate writes, masks stale query data with a per-account override, refreshes the list and metrics, and restores the previous override after a failed write. The list response for a write's refresh clears the overrides of completed writes. The override of a write that is still pending stays until the refresh that follows it. The event records only the display type, never the property name or value.
@@ -315,8 +315,8 @@ Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer
`accountsViewState.ts` is a pure module that maps UI state ↔ the `ColumnConfiguration` payload:
-- `columns` ← `selectColumns` (column names in order)
-- `order_by` ← sort, stored as `["<column> <ASC|DESC>"]` using the logical column name, then translated into a typed sort reference at query-build time
+- `columns` ← `selectColumns` (ordered column expressions, including definition IDs and aliases for relationships)
+- `order_by` ← sort, stored as `["<column> <ASC|DESC>"]` using the column alias, then translated into a typed sort reference at query-build time
- `filters` ← search text, tags, assignment status (`assignmentStatus`, always stored so a new `all` view is distinct from a legacy field-less view that restores as assigned-only), assigned-to filter, tile filter, custom-property filters (JSON; custom-property filters key by definition **id**, so they survive renames)
- `properties` ← `{ tiles }` — overview tile configuration (a `properties` field added to the `ColumnConfiguration` model)
@@ -388,6 +388,7 @@ The seed command also adds billing insights, meetings, an email thread, a Suppor
We track user actions on the Accounts list with `posthog.capture()`. Conventions:
- Event names: `customer analytics accounts <verb> <object>` — lowercase, spaces. Property keys are `snake_case`.
+- Relationship events retain their established `role` values through `ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES` in `constants.ts`.
- **Reference event names via the `AccountsEvents` const in `constants.ts`** — never pass a raw string to `posthog.capture`. A typo'd literal silently forks a new event in PostHog and breaks reporting with no error. When adding an event, add it to `AccountsEvents` and to the table below.
- Fire events in the **kea logic listeners** (where the action and its values live), not in components. Only fire from a component when no action exists for the interaction (the expanded-row links/notes).
- **Filters use a dedicated `reportFilterChange` action.** The raw filter setters (`setTagsFilter`, `setAssignedToFilter`, …) are also dispatched by URL sync (shared view links) and by cross-filter cascades (selecting users forces the `assigned` status, and leaving that status clears the user list), so capturing in their listeners would log phantom events. The filter controls dispatch `reportFilterChange(filterType)` on genuine interaction only; its listener reads the post-change state and captures. Add new filters the same way.
@@ -485,7 +486,7 @@ Account detail view events use singular `accountViewsLogic`, separate from Accou
- **Instrument every new feature as you build it.** Any new user action on the accounts list should emit a `posthog.capture`, following this product's pattern and the wider PostHog pattern:
- Add the event name to the `AccountsEvents` const in `constants.ts` and capture through it — never a raw string (a typo silently forks a new event in PostHog).
- Keep the naming convention (`customer analytics accounts <verb> <object>`) and `snake_case` property keys.
- - Type discriminator property _values_ with a union (e.g. `AccountFilterType`, `AccountRoleKey`) rather than bare strings, so the value set is typo-proof and self-documenting — these are what dashboard breakdowns key off.
+ - Type discriminator property _values_ with a union (e.g. `AccountFilterType`) rather than bare strings, so the value set is typo-proof and self-documenting — these are what dashboard breakdowns key off.
- Fire from the kea logic listener where the values live; only fire from a component when no action exists. If the trigger is also dispatched by URL sync or cross-filter cascades, add a dedicated report action (see `reportFilterChange`).
- Add a row to the table above.
- **Update the monitoring dashboard whenever events change.** New or changed events must be reflected in the "Customer analytics: Accounts list usage" dashboard in PostHog — add a new insight or extend an existing one so the metric is actually visible, don't just emit the event. For example, if you add a new tab to the expanded account row, its click event should feed the engagement-funnel insight (the "opened a link or note" step) and the feature-adoption insight — not just be captured.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
index 6d82c6acd66f..30eca596cfaf 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
@@ -20,8 +20,7 @@ import { IconTuning, SortableDragIcon } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
-
-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { AccountsTableCustomPropertyDefinition } from '~/queries/schema/schema-general'
import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import {
@@ -34,6 +33,7 @@ import {
PickerGroupKey,
accountsColumnConfigLogic,
} from './accountsColumnConfigLogic'
+import { AccountsDefinitionStatus } from './AccountsDefinitionStatus'
import { accountsViewsLogic } from './accountsViewsLogic'
const ACCOUNT_COLUMN_LABELS: Record<string, string> = {
@@ -61,8 +61,15 @@ export function AccountsColumnConfigurator(): JSX.Element {
}
function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {
- const { selectColumns, accountsColumnGroups, databaseLoading, editingColumn, editingColumnIndex } =
- useValues(accountsColumnConfigLogic)
+ const {
+ selectColumns,
+ accountsColumnGroups,
+ databaseLoading,
+ customPropertyDefinitionsLoading,
+ relationshipDefinitionsLoading,
+ editingColumn,
+ editingColumnIndex,
+ } = useValues(accountsColumnConfigLogic)
const { moveColumn, resetColumns, unselectColumn, setEditingColumnIndex } = useActions(accountsColumnConfigLogic)
return (
@@ -127,7 +134,15 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;
) : (
<div className="w-full">
<h4 className="secondary uppercase text-secondary">Available columns</h4>
- <AvailableColumnsPicker groups={accountsColumnGroups} loading={databaseLoading} />
+ <AccountsDefinitionStatus />
+ <AvailableColumnsPicker
+ groups={accountsColumnGroups}
+ loading={
+ databaseLoading ||
+ customPropertyDefinitionsLoading ||
+ relationshipDefinitionsLoading
+ }
+ />
</div>
)}
</div>
@@ -195,7 +210,11 @@ function ColumnEditSection({ column, onClose }: { column: string; onClose: () =>
)
}
-function CustomPropertyDisplayEditor({ definition }: { definition: CustomPropertyDefinitionApi }): JSX.Element {
+function CustomPropertyDisplayEditor({
+ definition,
+}: {
+ definition: AccountsTableCustomPropertyDefinition
+}): JSX.Element {
const { columnDisplay } = useValues(accountsColumnConfigLogic)
const { setColumnDisplay } = useActions(accountsColumnConfigLogic)
const definitionId = definition.id
@@ -280,8 +299,6 @@ function SelectedAccountColumn({
const { aliasToDefinition, aliasToRelationshipDefinition } = useValues(accountsColumnConfigLogic)
const { setNodeRef, attributes, transform, transition, listeners } = useSortable({ id: column })
const alias = extractDisplayLabel(column)
- // Custom-property and relationship columns are aliased to opaque `cp_<id>` / `rel_<id>`
- // (or legacy role keys); show the definition name instead.
const label =
aliasToDefinition[alias]?.name ??
aliasToRelationshipDefinition[alias]?.name ??
@@ -346,8 +363,8 @@ function AvailableColumnsPicker({ groups, loading }: { groups: AccountColumnGrou
suffix={<CategoryPicker groups={groups} activeKey={pickerGroupKey} onChange={setPickerGroupKey} />}
/>
<div className="AvailableColumnsList border border-border rounded">
- {loading && filteredColumnOptions.length === 0 ? (
- <div className="p-3 text-secondary">Loading schema…</div>
+ {loading ? (
+ <div className="p-3 text-secondary">Loading columns…</div>
) : filteredColumnOptions.length === 0 ? (
<div className="p-3 text-secondary">
{pickerSearch.trim() ? 'No matching columns' : 'No columns available'}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsDefinitionStatus.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsDefinitionStatus.tsx
new file mode 100644
index 000000000000..b4382da77d0b
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsDefinitionStatus.tsx
@@ -0,0 +1,31 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+
+export function AccountsDefinitionStatus(): JSX.Element | null {
+ const {
+ customPropertyDefinitionsLoading,
+ relationshipDefinitionsLoading,
+ customPropertyDefinitionsError,
+ relationshipDefinitionsError,
+ } = useValues(accountsColumnConfigLogic)
+ const { ensureDefinitionsLoaded } = useActions(accountsColumnConfigLogic)
+ const loading = customPropertyDefinitionsLoading || relationshipDefinitionsLoading
+ if (customPropertyDefinitionsError || relationshipDefinitionsError) {
+ return (
+ <div role="alert" className="flex flex-wrap items-center gap-2 p-2">
+ Could not load properties. Try again.
+ <LemonButton size="small" onClick={ensureDefinitionsLoaded} loading={loading}>
+ Retry
+ </LemonButton>
+ </div>
+ )
+ }
+ return loading ? (
+ <div role="status" className="p-2 text-secondary">
+ Loading properties…
+ </div>
+ ) : null
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsFilterGroups.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsFilterGroups.tsx
index 7abee17a2119..31d045f12d4f 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsFilterGroups.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsFilterGroups.tsx
@@ -11,6 +11,7 @@ import type { AnyPropertyFilter } from '~/types'
import { AccountRelationshipOperatorValueSelect } from './AccountRelationshipOperatorValueSelect'
import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import { AccountsDefinitionStatus } from './AccountsDefinitionStatus'
import { accountsLogic } from './accountsLogic'
import {
ACCOUNT_FIELD_TAXONOMIC_OPTIONS,
@@ -29,6 +30,7 @@ export function AccountsFilterGroups(): JSX.Element {
removeAccountFilterGroup,
updateAccountFilterGroup,
} = useActions(accountsLogic)
+ const { ensureDefinitionsLoaded } = useActions(accountsColumnConfigLogic)
const { customPropertyTaxonomicOptions, relationshipTaxonomicOptions } = useValues(accountsColumnConfigLogic)
const detailsId = useId()
const [expanded, setExpanded] = useState(false)
@@ -38,6 +40,8 @@ export function AccountsFilterGroups(): JSX.Element {
function renderFilters(filters: AccountFilter[], groupIndex: number): JSX.Element {
return (
<PropertyFilters
+ onFilterOpen={ensureDefinitionsLoaded}
+ filterHeader={<AccountsDefinitionStatus />}
propertyFilters={filters as AnyPropertyFilter[]}
onChange={(updatedFilters) => {
setExpanded(true)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
index 09aeb21a27c0..faf0da7c47a8 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
@@ -12,6 +12,7 @@ import { SortableDragIcon } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { AccountColumnOption } from './accountsColumnConfigLogic'
+import { AccountsDefinitionStatus } from './AccountsDefinitionStatus'
import {
accountsOverviewTilesLogic,
AccountsOverviewTile,
@@ -136,6 +137,7 @@ export function AccountsOverviewTilesEditor({
</>
}
>
+ <AccountsDefinitionStatus />
<div className="flex flex-col gap-3">
{tiles.length === 0 ? (
<div className="text-secondary text-sm">No tiles configured yet — add one to get started.</div>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
index 06fc5c0be80a..b1e69d6f431e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
@@ -8,6 +8,11 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
import type { MockResolverInfo, Mocks } from '~/mocks/utils'
+import {
+ AccountsTableAccountField,
+ type AccountsTableQuery,
+ type AccountsTableResolvedColumn,
+} from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
import type {
@@ -17,7 +22,7 @@ import type {
UserCustomerAnalyticsConfigApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_DEFAULT_COLUMNS, customPropertyAlias } from './accountsColumnConfigLogic'
+import { ACCOUNTS_DEFAULT_COLUMNS, customPropertyAlias, relationshipAlias } from './accountsColumnConfigLogic'
const QUERY_ENDPOINT = '/api/projects/:team_id/accounts_table_query/'
const COLUMN_CONFIGURATIONS_ENDPOINT = 'api/projects/:team_id/column_configurations/'
@@ -79,9 +84,28 @@ const RELATIONSHIP_DEFINITIONS = {
function buildAccountsTableQueryResponse(
rows: AccountRow[],
- customProperties: Record<string, string> = {}
+ customProperties: Record<string, string> = {},
+ definitions: CustomPropertyDefinitionApi[] = [],
+ query?: AccountsTableQuery
): Record<string, unknown> {
+ const columns: AccountsTableResolvedColumn[] =
+ query?.useDefaultColumns || !query
+ ? [
+ { kind: 'account_field', field: AccountsTableAccountField.Name },
+ { kind: 'tags' },
+ { kind: 'note_count' },
+ ...RELATIONSHIP_DEFINITIONS.results.map(
+ ({ id }): AccountsTableResolvedColumn => ({ kind: 'relationship', definitionId: id })
+ ),
+ ]
+ : query.columns
return {
+ columns,
+ customPropertyDefinitions: definitions,
+ relationshipDefinitions: RELATIONSHIP_DEFINITIONS.results.map((definition) => ({
+ ...definition,
+ is_controlled: false,
+ })),
kind: 'AccountsTableQuery',
results: rows.map(([account, tags, noteCount, csm, accountExecutive, accountOwner]) => ({
id: account.id,
@@ -286,10 +310,11 @@ const EXPANDED_ROW_TEST_OPTIONS = {
function mockAccountsTableQuery(
rows: AccountRow[],
- customProperties: Record<string, string> = {}
+ customProperties: Record<string, string> = {},
+ definitions: CustomPropertyDefinitionApi[] = []
): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
return async ({ request }) => {
- const body = (await request.json()) as { query?: { kind?: string; metrics?: unknown[] } }
+ const body = (await request.json()) as { query?: AccountsTableQuery }
const query = body?.query
if (query?.kind === 'AccountsTableQuery') {
return query.metrics
@@ -304,7 +329,7 @@ function mockAccountsTableQuery(
metricsResults: [rows.length],
},
]
- : [200, buildAccountsTableQueryResponse(rows, customProperties)]
+ : [200, buildAccountsTableQueryResponse(rows, customProperties, definitions, query)]
}
return undefined
}
@@ -409,7 +434,7 @@ export const ManyColumns: Story = {
JSON.stringify({
columns: [
...ACCOUNTS_DEFAULT_COLUMNS,
- 'csm',
+ `accounts.relationships.values.\`${RELATIONSHIP_DEFINITIONS.results[0].id}\` AS ${relationshipAlias(RELATIONSHIP_DEFINITIONS.results[0].id)}`,
'external_id',
...ADDITIONAL_COLUMN_DEFINITIONS.map(
({ id }) => `accounts.custom_properties.values.\`${id}\` AS ${customPropertyAlias(id)}`
@@ -435,7 +460,11 @@ export const ManyColumns: Story = {
},
},
post: {
- [QUERY_ENDPOINT]: mockAccountsTableQuery(SAMPLE_ROWS, ADDITIONAL_COLUMN_VALUES),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(
+ SAMPLE_ROWS,
+ ADDITIONAL_COLUMN_VALUES,
+ ADDITIONAL_COLUMN_DEFINITIONS
+ ),
},
}),
],
@@ -577,7 +606,7 @@ export const ClearCustomProperties: Story = {
},
},
post: {
- [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW, values),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW, values, CLEARABLE_PROPERTY_DEFINITIONS),
[ACCOUNT_PROPERTY_VALUES_ENDPOINT]: async ({ request }) => {
const body = (await request.json()) as { definition: string; value: unknown }
if (body.value !== null) {
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 9243676aa2c5..97c8b2966c0c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -34,19 +34,18 @@ import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { DataTable } from '~/queries/nodes/DataTable/DataTable'
+import type {
+ AccountsTableCustomPropertyDefinition,
+ AccountsTableRelationshipDefinition,
+} from '~/queries/schema/schema-general'
import { DataTableNode } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~/queries/types'
-import type {
- AccountRelationshipDefinitionApi,
- CustomPropertyDefinitionApi,
-} from 'products/customer_analytics/frontend/generated/api.schemas'
-
import { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'
import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
import { AccountPinnedPropertiesExpansion } from './AccountPinnedPropertiesExpansion'
-import { AccountColumnDisplayConfig, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import { AccountColumnDisplayConfig, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, customPropertySavingKey, savingRoleKey } from './accountsLogic'
import { AccountsTableNameCell } from './AccountsTableNameCell'
@@ -147,7 +146,7 @@ function RelationshipCell({
}: {
record: unknown
column: string
- definition: AccountRelationshipDefinitionApi
+ definition: AccountsTableRelationshipDefinition
}): JSX.Element {
const { isRoleSaving, relationshipOverrides } = useValues(accountsLogic)
const { updateAccountRole } = useActions(accountsLogic)
@@ -253,7 +252,7 @@ function CustomPropertyHistoryCell({
display,
}: {
raw: unknown
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
display: AccountColumnDisplayConfig
}): JSX.Element {
const { latest, baseline, chartPoints } = buildHistoryDisplay(
@@ -319,7 +318,9 @@ const CANONICAL_PROPERTY_TAB: Record<string, AccountExpansionTab> = {
'Last Slack message at': 'conversations',
}
-export function getCanonicalPropertyTab(definition: CustomPropertyDefinitionApi): AccountExpansionTab | undefined {
+export function getCanonicalPropertyTab(
+ definition: AccountsTableCustomPropertyDefinition
+): AccountExpansionTab | undefined {
return definition.is_canonical ? CANONICAL_PROPERTY_TAB[definition.name] : undefined
}
@@ -330,7 +331,7 @@ function CanonicalTimestampCell({
tab,
}: {
record: unknown
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
value: string
tab: AccountExpansionTab
}): JSX.Element {
@@ -364,13 +365,16 @@ function CanonicalTimestampCell({
)
}
-export function isCustomPropertyEditable(definition: CustomPropertyDefinitionApi): boolean {
+export function isCustomPropertyEditable(definition: AccountsTableCustomPropertyDefinition): boolean {
return !definition.is_canonical && !definition.source
}
type CustomPropertyDraft = boolean | string
-function customPropertyDraftValue(value: unknown, definition: CustomPropertyDefinitionApi): CustomPropertyDraft {
+function customPropertyDraftValue(
+ value: unknown,
+ definition: AccountsTableCustomPropertyDefinition
+): CustomPropertyDraft {
if (definition.display_type === 'boolean') {
return value === true || value === 'true' || value === '1'
}
@@ -386,7 +390,7 @@ function customPropertyDraftValue(value: unknown, definition: CustomPropertyDefi
function customPropertyValueToSave(
draft: CustomPropertyDraft,
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
): string | number | boolean {
if (definition.display_type === 'boolean') {
return draft === true
@@ -411,7 +415,7 @@ function isHttpUrl(value: string): boolean {
export function isCustomPropertyValueValid(
draft: CustomPropertyDraft,
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
): boolean {
if (definition.display_type === 'boolean') {
return true
@@ -432,7 +436,7 @@ export function isCustomPropertyValueValid(
function renderCustomPropertyValue(
record: unknown,
value: string,
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
): JSX.Element {
if (!value) {
return <span className="text-muted">—</span>
@@ -468,7 +472,7 @@ function renderCustomPropertyValue(
function renderCustomPropertyEditor(
draft: CustomPropertyDraft,
- definition: CustomPropertyDefinitionApi,
+ definition: AccountsTableCustomPropertyDefinition,
setDraft: (draft: CustomPropertyDraft) => void,
saveValue: (nextValue?: CustomPropertyDraft) => void,
cancelEdit: () => void
@@ -571,7 +575,7 @@ function CustomPropertyCell({
}: {
record: unknown
column: string
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
display?: AccountColumnDisplayConfig
isEditable: boolean
}): JSX.Element {
@@ -905,16 +909,6 @@ const SKELETON_COLUMNS: LemonTableColumns<{ key: number }> = [
width: COLUMN_WIDTHS.notebook_count,
render: () => <LemonSkeleton className="h-4 w-4" />,
},
- ...Object.values(LEGACY_ROLE_COLUMNS).map((label) => ({
- title: label,
- width: COLUMN_WIDTHS.relationship,
- render: () => (
- <div className="flex items-center gap-2">
- <LemonSkeleton.Circle className="h-5 w-5" />
- <LemonSkeleton className="h-4 w-24" />
- </div>
- ),
- })),
]
function AccountsTableSkeleton(): JSX.Element {
@@ -962,8 +956,6 @@ export function AccountsTable(): JSX.Element {
}),
[contextColumns, columnWidths, hasAutoSizedColumns, expandable, sortedRowsTransformer]
)
- // A null source means the query is still waiting on the relationship
- // definitions — same skeleton as the initial fetch, not an empty table.
if ((responseLoading || !accountsQuerySource) && !response) {
return <AccountsTableSkeleton />
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index 6c700435739f..c1c82e122c40 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -20,11 +20,12 @@ import type {
AccountRelationshipDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { AccountsTableRelationshipDefinition } from '../../../../../frontend/src/queries/schema/schema-general'
import { ACCOUNTS_TABLE_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
import { accountPropertyUpdatesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic'
-import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'
+import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
-import { AccountsEvents } from './constants'
+import { ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES, AccountsEvents } from './constants'
export interface AccountRelationshipsLogicProps extends AccountViewTileLogicProps {
accountId: string
@@ -38,7 +39,7 @@ function refreshAccountsList(): void {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountRelationshipsLogicValues {
- relationshipDefinitions: AccountRelationshipDefinitionApi[] // accountsColumnConfigLogic
+ relationshipDefinitions: AccountsTableRelationshipDefinition[] // accountsColumnConfigLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamId: number | null // teamLogic
activeRelationships: AccountRelationshipApi[]
@@ -116,7 +117,7 @@ export interface accountRelationshipsLogicMeta {
) => AccountRelationshipApi[]
assignDefinition: (
assignDefinitionId: string | null,
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
+ relationshipDefinitions: AccountsTableRelationshipDefinition[]
) => AccountRelationshipDefinitionApi | null
definitionFilterOptions: (relationships: AccountRelationshipApi[] | null) => AccountRelationshipDefinitionApi[]
}
@@ -272,7 +273,7 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
user: user.id,
})
posthog.capture(AccountsEvents.RoleAssigned, {
- role: ROLE_KEY_BY_NAME[definition.name] ?? definition.name,
+ role: ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES[definition.name] ?? definition.name,
is_assigned: true,
assigned_user_id: user.id,
source: 'relationships_tab',
@@ -294,7 +295,9 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
try {
await accountsRelationshipsEndCreate(String(values.currentTeamId), props.accountId, relationship.id)
posthog.capture(AccountsEvents.RoleAssigned, {
- role: ROLE_KEY_BY_NAME[relationship.definition.name] ?? relationship.definition.name,
+ role:
+ ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES[relationship.definition.name] ??
+ relationship.definition.name,
is_assigned: false,
assigned_user_id: null,
source: 'relationships_tab',
@@ -327,6 +330,7 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
}
}),
afterMount(({ actions }) => {
+ accountsColumnConfigLogic.actions.ensureDefinitionsLoaded()
actions.loadRelationships()
}),
])
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index 3cee3143af1f..631fc70e138e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -15,8 +15,6 @@ import {
filterColumnOptions,
normalizeAccountColumns,
relationshipAlias,
- roleKeyToDefinitionMap,
- translateSelectColumns,
} from './accountsColumnConfigLogic'
function definition(
@@ -97,13 +95,16 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
expect(extractDisplayLabel(group.options[0].expression)).toBe(customPropertyAlias(id))
})
- it('relationships group offers legacy names for seeded definitions and rel_ aliases for others', () => {
+ it('relationships group uses definition IDs for every relationship', () => {
const seeded = relationshipDefinition('11111111-2222-3333-4444-555555555555', 'CSM')
const custom = relationshipDefinition('66666666-7777-8888-9999-000000000000', 'Onboarding manager')
const group = buildAccountColumnGroups({}, [], [seeded, custom]).find((g) => g.key === 'relationships')!
expect(group.options).toEqual([
- { name: 'CSM', expression: 'csm' },
+ {
+ name: 'CSM',
+ expression: `accounts.relationships.values.\`${seeded.id}\` AS ${relationshipAlias(seeded.id)}`,
+ },
{
name: 'Onboarding manager',
expression: `accounts.relationships.values.\`${custom.id}\` AS ${relationshipAlias(custom.id)}`,
@@ -176,19 +177,6 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
).toEqual(['name', ACCOUNTS_TAGS_COLUMN])
})
- it('translateSelectColumns resolves legacy roles through the lazy join and drops unmatched ones', () => {
- const csm = relationshipDefinition('11111111-2222-3333-4444-555555555555', 'CSM')
- const map = roleKeyToDefinitionMap([
- csm,
- relationshipDefinition('99999999-0000-1111-2222-333333333333', 'Renamed'),
- ])
-
- expect(translateSelectColumns(['name', 'csm', 'account_owner'], map)).toEqual([
- 'name',
- `accounts.relationships.values.\`${csm.id}\` AS csm`,
- ])
- })
-
it('applyColumnDisplayToSelect swaps only configured custom property columns to the history join', () => {
const id = '11111111-2222-3333-4444-555555555555'
const scalar = `accounts.custom_properties.values.\`${id}\` AS ${customPropertyAlias(id)}`
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index e5ff5f842bed..8d317c53ecee 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -9,6 +9,10 @@ import { teamLogic } from 'scenes/teamLogic'
import { propertyDefinitionsModel, updatePropertyDefinitions } from '~/models/propertyDefinitionsModel'
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
+import type {
+ AccountsTableCustomPropertyDefinition,
+ AccountsTableRelationshipDefinition,
+} from '~/queries/schema/schema-general'
import { AccountsTableAccountField, DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schema-general'
import { PropertyDefinitionType, PropertyType } from '~/types'
@@ -16,11 +20,8 @@ import {
accountRelationshipDefinitionsList,
customPropertyDefinitionsList,
} from 'products/customer_analytics/frontend/generated/api'
-import type {
- AccountRelationshipDefinitionApi,
- CustomPropertyDefinitionApi,
-} from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { AccountsTableQueryResponse } from '../../../../../frontend/src/queries/schema/schema-general'
import { ACCOUNT_FIELD_TAXONOMIC_OPTIONS, propertyTypeForDisplayType } from './accountsPropertyFilters'
export const ACCOUNTS_NAME_COLUMN = 'name'
@@ -28,20 +29,6 @@ export const ACCOUNTS_TAGS_COLUMN = 'accounts.tags.names AS tag_names'
const LEGACY_ACCOUNTS_TAGS_NAME_COLUMN = 'accounts.tags.names AS names'
const LEGACY_ACCOUNTS_TAGS_ACCOUNT_ID_COLUMN = 'accounts.tags.account_id AS account_id'
-// Legacy role names remain serialized for saved views and shared URLs.
-// Query planning maps them to seeded relationship definitions.
-export const LEGACY_ROLE_COLUMNS = {
- csm: 'CSM',
- account_executive: 'Account executive',
- account_owner: 'Account owner',
-} as const
-
-export type AccountRoleKey = keyof typeof LEGACY_ROLE_COLUMNS
-
-export function isLegacyRoleColumn(column: string): column is AccountRoleKey {
- return column in LEGACY_ROLE_COLUMNS
-}
-
export const ACCOUNTS_DEFAULT_COLUMNS: string[] = [
ACCOUNTS_NAME_COLUMN,
ACCOUNTS_TAGS_COLUMN,
@@ -112,7 +99,7 @@ export const DEFAULT_COLUMN_DISPLAY_WINDOW_DAYS = 7
const CUSTOM_PROPERTY_COLUMN_REGEX = /^accounts\.custom_properties\.values\.`([0-9a-fA-F-]+)` AS (cp_[0-9a-fA-F]+)$/
-// Keep stored column strings scalar so saved views and shared URLs stay stable.
+// Keep stored column strings scalar so saved column identities stay stable.
export function applyColumnDisplayToSelect(columns: string[], columnDisplay: AccountColumnDisplayState): string[] {
if (Object.keys(columnDisplay).length === 0) {
return columns
@@ -126,36 +113,8 @@ export function applyColumnDisplayToSelect(columns: string[], columnDisplay: Acc
})
}
-function relationshipExpression(definition: AccountRelationshipDefinitionApi, alias: string): string {
- return `accounts.relationships.values.\`${definition.id}\` AS ${alias}`
-}
-
-export const ROLE_KEY_BY_NAME: Record<string, AccountRoleKey> = Object.fromEntries(
- Object.entries(LEGACY_ROLE_COLUMNS).map(([key, name]) => [name, key as AccountRoleKey])
-)
-
-export function roleKeyToDefinitionMap(
- definitions: AccountRelationshipDefinitionApi[]
-): Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>> {
- return Object.fromEntries(
- definitions
- .filter((definition) => ROLE_KEY_BY_NAME[definition.name])
- .map((definition) => [ROLE_KEY_BY_NAME[definition.name], definition])
- )
-}
-
-// Keep legacy role names stable in persisted state. Omit roles without a matching definition.
-export function translateSelectColumns(
- columns: string[],
- roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
-): string[] {
- return columns.flatMap((column) => {
- if (!isLegacyRoleColumn(column)) {
- return [column]
- }
- const definition = roleKeyToDefinition[column]
- return definition ? [relationshipExpression(definition, column)] : []
- })
+function getRelationshipColumn(definitionId: string): string {
+ return `accounts.relationships.values.\`${definitionId}\` AS ${relationshipAlias(definitionId)}`
}
export type AccountColumnOption = {
@@ -228,7 +187,7 @@ function joinOptionsFromSchema(
return buildJoinOptions(field.name, names, joinedTable)
}
-function customPropertyOptions(definitions: CustomPropertyDefinitionApi[]): AccountColumnOption[] {
+function customPropertyOptions(definitions: AccountsTableCustomPropertyDefinition[]): AccountColumnOption[] {
return definitions.map((definition) => ({
name: definition.name,
type: definition.display_type,
@@ -236,19 +195,17 @@ function customPropertyOptions(definitions: CustomPropertyDefinitionApi[]): Acco
}))
}
-// Keep seeded role names compatible with default columns and persisted selections.
-function relationshipOptions(definitions: AccountRelationshipDefinitionApi[]): AccountColumnOption[] {
+function relationshipOptions(definitions: AccountsTableRelationshipDefinition[]): AccountColumnOption[] {
return definitions.map((definition) => ({
name: definition.name,
- expression:
- ROLE_KEY_BY_NAME[definition.name] ?? relationshipExpression(definition, relationshipAlias(definition.id)),
+ expression: getRelationshipColumn(definition.id),
}))
}
export function buildAccountColumnGroups(
allTablesMap: Record<string, DatabaseSchemaTable> | null | undefined,
- customPropertyDefinitions: CustomPropertyDefinitionApi[] = [],
- relationshipDefinitions: AccountRelationshipDefinitionApi[] = []
+ customPropertyDefinitions: AccountsTableCustomPropertyDefinition[] = [],
+ relationshipDefinitions: AccountsTableRelationshipDefinition[] = []
): AccountColumnGroup[] {
const accountsTable = allTablesMap?.[ACCOUNTS_ACCOUNTS_TABLE_NAME]
const directOptions: AccountColumnOption[] = []
@@ -331,12 +288,18 @@ export interface accountsColumnConfigLogicValues {
currentTeamId: number | null // teamLogic
accountsColumnGroups: AccountColumnGroup[]
activePickerGroup: AccountColumnGroup | null
- aliasToDefinition: Record<string, CustomPropertyDefinitionApi>
- aliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi>
+ aliasToDefinition: Record<string, AccountsTableCustomPropertyDefinition>
+ aliasToRelationshipDefinition: Record<string, AccountsTableRelationshipDefinition>
columnConfiguratorVisible: boolean
columnDisplay: AccountColumnDisplayState
- customPropertyDefinitions: CustomPropertyDefinitionApi[]
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
+ customPropertyCatalog: AccountsTableCustomPropertyDefinition[]
+ customPropertyCatalogLoaded: boolean
+ customPropertyCatalogLoading: boolean
+ customPropertyCatalogProjectId: number | null
+ customPropertyDefinitions: AccountsTableCustomPropertyDefinition[]
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
+ customPropertyDefinitionsError: string | null
+ customPropertyDefinitionsLoaded: boolean
customPropertyDefinitionsLoading: boolean
customPropertyTaxonomicOptions: (SimpleOption & {
description?: string
@@ -353,16 +316,28 @@ export interface accountsColumnConfigLogicValues {
pickerSearch: string
pickerSearchPlaceholder: string
querySelectColumns: string[]
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>
+ relationshipCatalog: AccountsTableRelationshipDefinition[]
+ relationshipCatalogLoaded: boolean
+ relationshipCatalogLoading: boolean
+ relationshipCatalogProjectId: number | null
+ relationshipDefinitions: AccountsTableRelationshipDefinition[]
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
+ relationshipDefinitionsError: string | null
relationshipDefinitionsLoaded: boolean
relationshipDefinitionsLoading: boolean
relationshipTaxonomicOptions: (SimpleOption & {
id: string
property_type: PropertyType
})[]
- roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
+ renderSelectColumns: string[]
selectColumns: string[]
+ tableColumnResponse: {
+ definitionIds: string[]
+ requested: string[] | undefined
+ } | null
+ tableCustomPropertyDefinitions: AccountsTableCustomPropertyDefinition[]
+ tableRelationshipDefinitions: AccountsTableRelationshipDefinition[]
+ useDefaultColumns: boolean
visibleColumnNames: string[]
}
@@ -382,10 +357,22 @@ export interface accountsColumnConfigLogicActions {
force?: boolean
shallow?: boolean
} // databaseTableListLogic
+ ensureDefinitionsLoaded: () => {
+ value: true
+ }
hideColumnConfigurator: () => {
value: true
}
- loadCustomPropertyDefinitions: () => any
+ hydrateTableDefinitions: (
+ response: import('~/queries/schema/schema-general').AccountsTableQueryResponse,
+ requestedColumns?: string[]
+ ) => {
+ requestedColumns: string[] | undefined
+ response: AccountsTableQueryResponse
+ }
+ loadCustomPropertyDefinitions: (params?: { projectId?: number | null }) => {
+ projectId?: number | null
+ }
loadCustomPropertyDefinitionsFailure: (
error: string,
errorObject?: any
@@ -394,13 +381,19 @@ export interface accountsColumnConfigLogicActions {
errorObject?: any
}
loadCustomPropertyDefinitionsSuccess: (
- customPropertyDefinitions: CustomPropertyDefinitionApi[],
- payload?: any
+ customPropertyCatalog: AccountsTableCustomPropertyDefinition[],
+ payload?: {
+ projectId?: number | null
+ }
) => {
- customPropertyDefinitions: CustomPropertyDefinitionApi[]
- payload?: any
+ customPropertyCatalog: AccountsTableCustomPropertyDefinition[]
+ payload?: {
+ projectId?: number | null
+ }
+ }
+ loadRelationshipDefinitions: (params?: { projectId?: number | null }) => {
+ projectId?: number | null
}
- loadRelationshipDefinitions: () => any
loadRelationshipDefinitionsFailure: (
error: string,
errorObject?: any
@@ -409,11 +402,15 @@ export interface accountsColumnConfigLogicActions {
errorObject?: any
}
loadRelationshipDefinitionsSuccess: (
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- payload?: any
+ relationshipCatalog: AccountsTableRelationshipDefinition[],
+ payload?: {
+ projectId?: number | null
+ }
) => {
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- payload?: any
+ relationshipCatalog: AccountsTableRelationshipDefinition[]
+ payload?: {
+ projectId?: number | null
+ }
}
moveColumn: (
oldIndex: number,
@@ -425,6 +422,9 @@ export interface accountsColumnConfigLogicActions {
resetColumns: () => {
value: true
}
+ resetDefinitionCatalogs: () => {
+ value: true
+ }
restoreSelectColumns: (columns: string[]) => {
columns: string[]
}
@@ -467,22 +467,53 @@ export interface accountsColumnConfigLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsColumnConfigLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- defaultSelectColumns: (relationshipDefinitions: AccountRelationshipDefinitionApi[]) => string[]
- roleKeyToDefinition: (
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- ) => Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
- querySelectColumns: (
- selectColumns: string[],
- roleKeyToDefinition: Partial<
- Record<'account_executive' | 'account_owner' | 'csm', AccountRelationshipDefinitionApi>
- >,
- columnDisplay: AccountColumnDisplayState
+ customPropertyDefinitions: (
+ customPropertyCatalog: AccountsTableCustomPropertyDefinition[],
+ customPropertyCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => AccountsTableCustomPropertyDefinition[]
+ customPropertyDefinitionsLoaded: (
+ customPropertyCatalogLoaded: boolean,
+ customPropertyCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => boolean
+ customPropertyDefinitionsLoading: (
+ customPropertyCatalogLoading: boolean,
+ customPropertyCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => boolean
+ relationshipDefinitions: (
+ relationshipCatalog: AccountsTableRelationshipDefinition[],
+ relationshipCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => AccountsTableRelationshipDefinition[]
+ relationshipDefinitionsLoaded: (
+ relationshipCatalogLoaded: boolean,
+ relationshipCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => boolean
+ relationshipDefinitionsLoading: (
+ relationshipCatalogLoading: boolean,
+ relationshipCatalogProjectId: number | null,
+ currentProjectId: number | null
+ ) => boolean
+ defaultSelectColumns: (
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
+ ) => string[]
+ querySelectColumns: (selectColumns: string[], columnDisplay: AccountColumnDisplayState) => string[]
+ renderSelectColumns: (
+ querySelectColumns: string[],
+ tableColumnResponse: {
+ definitionIds: string[]
+ requested: string[] | undefined
+ } | null,
+ useDefaultColumns: boolean
) => string[]
- visibleColumnNames: (querySelectColumns: string[]) => string[]
+ visibleColumnNames: (renderSelectColumns: string[]) => string[]
accountsColumnGroups: (
allTablesMap: Record<string, DatabaseSchemaTable>,
- customPropertyDefinitions: CustomPropertyDefinitionApi[],
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
+ customPropertyDefinitions: AccountsTableCustomPropertyDefinition[],
+ relationshipDefinitions: AccountsTableRelationshipDefinition[]
) => AccountColumnGroup[]
activePickerGroup: (
accountsColumnGroups: AccountColumnGroup[],
@@ -496,32 +527,35 @@ export interface accountsColumnConfigLogicMeta {
) => AccountPickerColumnOption[]
pickerSearchPlaceholder: (activePickerGroup: AccountColumnGroup | null) => string
customPropertyDefinitionsById: (
- customPropertyDefinitions: CustomPropertyDefinitionApi[]
- ) => Record<string, CustomPropertyDefinitionApi>
+ customPropertyDefinitions: AccountsTableCustomPropertyDefinition[],
+ tableCustomPropertyDefinitions: AccountsTableCustomPropertyDefinition[]
+ ) => Record<string, AccountsTableCustomPropertyDefinition>
editingColumn: (selectColumns: string[], editingColumnIndex: number | null) => string | null
displayByAlias: (columnDisplay: AccountColumnDisplayState) => AccountColumnDisplayState
aliasToDefinition: (
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
- ) => Record<string, CustomPropertyDefinitionApi>
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
+ ) => Record<string, AccountsTableCustomPropertyDefinition>
relationshipDefinitionsById: (
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- ) => Record<string, AccountRelationshipDefinitionApi>
- relationshipTaxonomicOptions: (relationshipDefinitions: AccountRelationshipDefinitionApi[]) => (SimpleOption & {
+ relationshipDefinitions: AccountsTableRelationshipDefinition[],
+ tableRelationshipDefinitions: AccountsTableRelationshipDefinition[]
+ ) => Record<string, AccountsTableRelationshipDefinition>
+ relationshipTaxonomicOptions: (
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
+ ) => (SimpleOption & {
id: string
property_type: PropertyType
})[]
- customPropertyTaxonomicOptions: (customPropertyDefinitions: CustomPropertyDefinitionApi[]) => (SimpleOption & {
+ customPropertyTaxonomicOptions: (
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
+ ) => (SimpleOption & {
description?: string
id: string
is_canonical?: boolean
property_type: PropertyType
})[]
aliasToRelationshipDefinition: (
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- roleKeyToDefinition: Partial<
- Record<'account_executive' | 'account_owner' | 'csm', AccountRelationshipDefinitionApi>
- >
- ) => Record<string, AccountRelationshipDefinitionApi>
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
+ ) => Record<string, AccountsTableRelationshipDefinition>
}
}
@@ -548,6 +582,12 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
logic: [propertyDefinitionsModel],
})),
actions({
+ ensureDefinitionsLoaded: true,
+ resetDefinitionCatalogs: true,
+ hydrateTableDefinitions: (
+ response: import('~/queries/schema/schema-general').AccountsTableQueryResponse,
+ requestedColumns?: string[]
+ ) => ({ response, requestedColumns }),
setSelectColumns: (columns: string[]) => ({ columns }),
setDefaultSelectColumns: (columns: string[]) => ({ columns }),
restoreSelectColumns: (columns: string[]) => ({ columns }),
@@ -567,6 +607,44 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
setPickerSearch: (search: string) => ({ search }),
}),
reducers({
+ tableColumnResponse: [
+ null as { requested: string[] | undefined; definitionIds: string[] } | null,
+ {
+ hydrateTableDefinitions: (_, { response, requestedColumns }) => ({
+ requested: requestedColumns,
+ definitionIds: (response.columns ?? []).flatMap((column) =>
+ 'definitionId' in column ? [column.definitionId] : []
+ ),
+ }),
+ resetDefinitionCatalogs: () => null,
+ },
+ ],
+ tableCustomPropertyDefinitions: [
+ [] as AccountsTableCustomPropertyDefinition[],
+ {
+ hydrateTableDefinitions: (_, { response }) => response.customPropertyDefinitions ?? [],
+ resetDefinitionCatalogs: () => [],
+ },
+ ],
+ tableRelationshipDefinitions: [
+ [] as AccountsTableRelationshipDefinition[],
+ {
+ hydrateTableDefinitions: (_, { response }) => response.relationshipDefinitions ?? [],
+ resetDefinitionCatalogs: () => [],
+ },
+ ],
+ useDefaultColumns: [
+ true,
+ {
+ resetColumns: () => true,
+ setDefaultSelectColumns: () => true,
+ restoreSelectColumns: () => false,
+ setSelectColumns: () => false,
+ selectColumn: () => false,
+ unselectColumn: () => false,
+ moveColumn: () => false,
+ },
+ ],
selectColumns: [
[...ACCOUNTS_DEFAULT_COLUMNS],
{
@@ -636,74 +714,172 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
setColumnDisplayConfig: (_, { config }) => config,
},
],
- // Wait for definitions to avoid a second query and visible column changes.
- relationshipDefinitionsLoaded: [
- false,
- {
- loadRelationshipDefinitionsSuccess: () => true,
- loadRelationshipDefinitionsFailure: () => true,
- },
- ],
}),
loaders(({ values }) => ({
- customPropertyDefinitions: [
- [] as CustomPropertyDefinitionApi[],
+ customPropertyCatalog: [
+ [] as AccountsTableCustomPropertyDefinition[],
{
- loadCustomPropertyDefinitions: async (): Promise<CustomPropertyDefinitionApi[]> => {
- const response = await customPropertyDefinitionsList(String(values.currentProjectId))
- return response.results
+ loadCustomPropertyDefinitions: async (
+ params: { projectId?: number | null } = {},
+ breakpoint
+ ): Promise<AccountsTableCustomPropertyDefinition[]> => {
+ const projectId = params.projectId ?? values.currentProjectId
+ const response = await customPropertyDefinitionsList(String(projectId), { pagination: 'none' })
+ breakpoint()
+ return response.results.filter(
+ (definition) => !definition.target_type || definition.target_type === 'account'
+ )
},
},
],
- relationshipDefinitions: [
- [] as AccountRelationshipDefinitionApi[],
+ relationshipCatalog: [
+ [] as AccountsTableRelationshipDefinition[],
{
- loadRelationshipDefinitions: async (): Promise<AccountRelationshipDefinitionApi[]> => {
- const response = await accountRelationshipDefinitionsList(String(values.currentProjectId))
+ loadRelationshipDefinitions: async (
+ params: { projectId?: number | null } = {},
+ breakpoint
+ ): Promise<AccountsTableRelationshipDefinition[]> => {
+ const projectId = params.projectId ?? values.currentProjectId
+ const response = await accountRelationshipDefinitionsList(String(projectId), { pagination: 'none' })
+ breakpoint()
return response.results
},
},
],
})),
+ reducers({
+ customPropertyCatalog: { resetDefinitionCatalogs: () => [] },
+ customPropertyCatalogLoading: { resetDefinitionCatalogs: () => false },
+ customPropertyCatalogProjectId: [
+ null as number | null,
+ {
+ loadCustomPropertyDefinitions: (_, { projectId = null }) => projectId,
+ loadCustomPropertyDefinitionsSuccess: (_, { payload }) => payload?.projectId ?? null,
+ resetDefinitionCatalogs: () => null,
+ },
+ ],
+ customPropertyCatalogLoaded: [
+ false,
+ {
+ loadCustomPropertyDefinitionsSuccess: () => true,
+ resetDefinitionCatalogs: () => false,
+ },
+ ],
+ customPropertyDefinitionsError: [
+ null as string | null,
+ {
+ loadCustomPropertyDefinitions: () => null,
+ loadCustomPropertyDefinitionsFailure: (_, { error }) => error,
+ resetDefinitionCatalogs: () => null,
+ },
+ ],
+ relationshipCatalog: { resetDefinitionCatalogs: () => [] },
+ relationshipCatalogLoading: { resetDefinitionCatalogs: () => false },
+ relationshipCatalogProjectId: [
+ null as number | null,
+ {
+ loadRelationshipDefinitions: (_, { projectId = null }) => projectId,
+ loadRelationshipDefinitionsSuccess: (_, { payload }) => payload?.projectId ?? null,
+ resetDefinitionCatalogs: () => null,
+ },
+ ],
+ relationshipCatalogLoaded: [
+ false,
+ {
+ loadRelationshipDefinitionsSuccess: () => true,
+ resetDefinitionCatalogs: () => false,
+ },
+ ],
+ relationshipDefinitionsError: [
+ null as string | null,
+ {
+ loadRelationshipDefinitions: () => null,
+ loadRelationshipDefinitionsFailure: (_, { error }) => error,
+ resetDefinitionCatalogs: () => null,
+ },
+ ],
+ }),
selectors({
- // Keep legacy names so defaults dedupe persisted selections.
+ customPropertyDefinitions: [
+ (s) => [s.customPropertyCatalog, s.customPropertyCatalogProjectId, s.currentProjectId],
+ (
+ definitions: AccountsTableCustomPropertyDefinition[],
+ projectId: number | null,
+ currentProjectId: number | null
+ ): AccountsTableCustomPropertyDefinition[] =>
+ projectId === null || projectId === currentProjectId ? definitions : [],
+ ],
+ customPropertyDefinitionsLoaded: [
+ (s) => [s.customPropertyCatalogLoaded, s.customPropertyCatalogProjectId, s.currentProjectId],
+ (loaded: boolean, projectId: number | null, currentProjectId: number | null): boolean =>
+ loaded && (projectId === null || projectId === currentProjectId),
+ ],
+ customPropertyDefinitionsLoading: [
+ (s) => [s.customPropertyCatalogLoading, s.customPropertyCatalogProjectId, s.currentProjectId],
+ (loading: boolean, projectId: number | null, currentProjectId: number | null): boolean =>
+ loading && (projectId === null || projectId === currentProjectId),
+ ],
+ relationshipDefinitions: [
+ (s) => [s.relationshipCatalog, s.relationshipCatalogProjectId, s.currentProjectId],
+ (
+ definitions: AccountsTableRelationshipDefinition[],
+ projectId: number | null,
+ currentProjectId: number | null
+ ): AccountsTableRelationshipDefinition[] =>
+ projectId === null || projectId === currentProjectId ? definitions : [],
+ ],
+ relationshipDefinitionsLoaded: [
+ (s) => [s.relationshipCatalogLoaded, s.relationshipCatalogProjectId, s.currentProjectId],
+ (loaded: boolean, projectId: number | null, currentProjectId: number | null): boolean =>
+ loaded && (projectId === null || projectId === currentProjectId),
+ ],
+ relationshipDefinitionsLoading: [
+ (s) => [s.relationshipCatalogLoading, s.relationshipCatalogProjectId, s.currentProjectId],
+ (loading: boolean, projectId: number | null, currentProjectId: number | null): boolean =>
+ loading && (projectId === null || projectId === currentProjectId),
+ ],
defaultSelectColumns: [
- (s) => [s.relationshipDefinitions],
- (relationshipDefinitions: AccountRelationshipDefinitionApi[]): string[] => [
+ (s) => [s.relationshipDefinitionsById],
+ (definitions: Record<string, AccountsTableRelationshipDefinition>): string[] => [
...ACCOUNTS_DEFAULT_COLUMNS,
- ...relationshipDefinitions.map(
- (definition) =>
- ROLE_KEY_BY_NAME[definition.name] ??
- relationshipExpression(definition, relationshipAlias(definition.id))
- ),
+ ...Object.values(definitions).map((definition) => getRelationshipColumn(definition.id)),
],
],
- roleKeyToDefinition: [
- (s) => [s.relationshipDefinitions],
- (
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- ): Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>> =>
- roleKeyToDefinitionMap(relationshipDefinitions),
- ],
querySelectColumns: [
- (s) => [s.selectColumns, s.roleKeyToDefinition, s.columnDisplay],
+ (s) => [s.selectColumns, s.columnDisplay],
+ (selectColumns: string[], columnDisplay: AccountColumnDisplayState): string[] =>
+ applyColumnDisplayToSelect(selectColumns, columnDisplay),
+ ],
+ renderSelectColumns: [
+ (s) => [s.querySelectColumns, s.tableColumnResponse, s.useDefaultColumns],
(
- selectColumns: string[],
- roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>,
- columnDisplay: AccountColumnDisplayState
+ columns: string[],
+ response: { requested: string[] | undefined; definitionIds: string[] } | null,
+ useDefaults: boolean
): string[] =>
- applyColumnDisplayToSelect(translateSelectColumns(selectColumns, roleKeyToDefinition), columnDisplay),
+ columns.filter((column) => {
+ const id = column.match(
+ /^accounts\.(?:custom_properties(?:_history)?|relationships)\.values\.`([^`]+)`/
+ )?.[1]
+ return (
+ !id ||
+ useDefaults ||
+ !response ||
+ !objectsEqual(response.requested, columns) ||
+ response.definitionIds.includes(id)
+ )
+ }),
],
visibleColumnNames: [
- (s) => [s.querySelectColumns],
+ (s) => [s.renderSelectColumns],
(querySelectColumns: string[]): string[] => querySelectColumns.map((c) => extractDisplayLabel(c)),
],
accountsColumnGroups: [
(s) => [s.allTablesMap, s.customPropertyDefinitions, s.relationshipDefinitions],
(
allTablesMap: Record<string, DatabaseSchemaTable>,
- customPropertyDefinitions: CustomPropertyDefinitionApi[],
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
+ customPropertyDefinitions: AccountsTableCustomPropertyDefinition[],
+ relationshipDefinitions: AccountsTableRelationshipDefinition[]
): AccountColumnGroup[] =>
buildAccountColumnGroups(allTablesMap, customPropertyDefinitions, relationshipDefinitions),
],
@@ -730,9 +906,12 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
activePickerGroup ? `Search ${activePickerGroup.label.toLowerCase()}` : 'Search all columns',
],
customPropertyDefinitionsById: [
- (s) => [s.customPropertyDefinitions],
- (customPropertyDefinitions: CustomPropertyDefinitionApi[]): Record<string, CustomPropertyDefinitionApi> =>
- Object.fromEntries(customPropertyDefinitions.map((definition) => [definition.id, definition])),
+ (s) => [s.customPropertyDefinitions, s.tableCustomPropertyDefinitions],
+ (
+ catalog: AccountsTableCustomPropertyDefinition[],
+ table: AccountsTableCustomPropertyDefinition[]
+ ): Record<string, AccountsTableCustomPropertyDefinition> =>
+ Object.fromEntries([...catalog, ...table].map((definition) => [definition.id, definition])),
],
editingColumn: [
(s) => [s.selectColumns, s.editingColumnIndex],
@@ -752,8 +931,8 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
aliasToDefinition: [
(s) => [s.customPropertyDefinitionsById],
(
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
- ): Record<string, CustomPropertyDefinitionApi> =>
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
+ ): Record<string, AccountsTableCustomPropertyDefinition> =>
Object.fromEntries(
Object.values(customPropertyDefinitionsById).map((definition) => [
customPropertyAlias(definition.id),
@@ -762,37 +941,38 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
),
],
relationshipDefinitionsById: [
- (s) => [s.relationshipDefinitions],
+ (s) => [s.relationshipDefinitions, s.tableRelationshipDefinitions],
(
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
- ): Record<string, AccountRelationshipDefinitionApi> =>
- Object.fromEntries(relationshipDefinitions.map((definition) => [definition.id, definition])),
+ catalog: AccountsTableRelationshipDefinition[],
+ table: AccountsTableRelationshipDefinition[]
+ ): Record<string, AccountsTableRelationshipDefinition> =>
+ Object.fromEntries([...catalog, ...table].map((definition) => [definition.id, definition])),
],
relationshipTaxonomicOptions: [
- (s) => [s.relationshipDefinitions],
+ (s) => [s.relationshipDefinitionsById],
(
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
): (SimpleOption & {
id: string
property_type: PropertyType
})[] =>
- relationshipDefinitions.map((definition) => ({
+ Object.values(relationshipDefinitionsById).map((definition) => ({
id: definition.id,
name: definition.name,
property_type: PropertyType.Assignee,
})),
],
customPropertyTaxonomicOptions: [
- (s) => [s.customPropertyDefinitions],
+ (s) => [s.customPropertyDefinitionsById],
(
- customPropertyDefinitions: CustomPropertyDefinitionApi[]
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
): (SimpleOption & {
id: string
description?: string
is_canonical?: boolean
property_type: PropertyType
})[] =>
- customPropertyDefinitions.map((definition) => ({
+ Object.values(customPropertyDefinitionsById).map((definition) => ({
id: definition.id,
name: definition.name,
description: definition.description ?? undefined,
@@ -801,19 +981,16 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
})),
],
aliasToRelationshipDefinition: [
- (s) => [s.relationshipDefinitions, s.roleKeyToDefinition],
+ (s) => [s.relationshipDefinitionsById],
(
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
- ): Record<string, AccountRelationshipDefinitionApi> => ({
- ...Object.fromEntries(
- relationshipDefinitions.map((definition) => [relationshipAlias(definition.id), definition])
+ definitions: Record<string, AccountsTableRelationshipDefinition>
+ ): Record<string, AccountsTableRelationshipDefinition> =>
+ Object.fromEntries(
+ Object.values(definitions).map((definition) => [relationshipAlias(definition.id), definition])
),
- ...roleKeyToDefinition,
- }),
],
}),
- listeners(({ actions, values, selectors, cache }) => ({
+ listeners(({ actions, values, cache }) => ({
// Seed property types so filters show valid operators.
loadCustomPropertyDefinitionsSuccess: () => {
updatePropertyDefinitions(
@@ -826,11 +1003,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
)
)
},
- restoreSelectColumns: () => {
- cache.hasRestoredColumns = true
- },
- // Only upgrade unchanged defaults. Never replace restored selections.
- loadRelationshipDefinitionsSuccess: (_, __, ___, previousState) => {
+ loadRelationshipDefinitionsSuccess: () => {
updatePropertyDefinitions(
Object.fromEntries(
values.relationshipTaxonomicOptions.map((option) => [
@@ -839,23 +1012,51 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
])
)
)
- const previousDefault = selectors.defaultSelectColumns(previousState)
- if (
- !cache.hasRestoredColumns &&
- objectsEqual(values.selectColumns, previousDefault) &&
- !objectsEqual(values.defaultSelectColumns, values.selectColumns)
- ) {
- actions.setDefaultSelectColumns(values.defaultSelectColumns)
+ },
+ [projectLogic.actionTypes.loadCurrentProjectSuccess]: ({ currentProject }) => {
+ if (cache.definitionProjectId !== currentProject?.id) {
+ cache.definitionProjectId = currentProject?.id
+ actions.resetDefinitionCatalogs()
+ }
+ },
+ resetColumns: () => actions.setDefaultSelectColumns(values.defaultSelectColumns),
+ ensureDefinitionsLoaded: () => {
+ if (!values.customPropertyDefinitionsLoaded && !values.customPropertyDefinitionsLoading) {
+ actions.loadCustomPropertyDefinitions({ projectId: values.currentProjectId })
+ }
+ if (!values.relationshipDefinitionsLoaded && !values.relationshipDefinitionsLoading) {
+ actions.loadRelationshipDefinitions({ projectId: values.currentProjectId })
}
},
- resetColumns: () => {
- cache.hasRestoredColumns = false
- if (!objectsEqual(values.selectColumns, values.defaultSelectColumns)) {
- actions.setSelectColumns(values.defaultSelectColumns)
+ showColumnConfigurator: () => actions.ensureDefinitionsLoaded(),
+ hydrateTableDefinitions: ({ response }) => {
+ if (values.useDefaultColumns && response.columns) {
+ actions.setDefaultSelectColumns([
+ ...ACCOUNTS_DEFAULT_COLUMNS,
+ ...response.columns.flatMap((column) => {
+ if (column.kind !== 'relationship') {
+ return []
+ }
+ return [getRelationshipColumn(column.definitionId)]
+ }),
+ ])
}
+ updatePropertyDefinitions(
+ Object.fromEntries([
+ ...values.customPropertyTaxonomicOptions.map((option) => [
+ `${PropertyDefinitionType.AccountCustomProperty}/${option.id}`,
+ { id: option.id, name: option.id, property_type: option.property_type },
+ ]),
+ ...values.relationshipTaxonomicOptions.map((option) => [
+ `${PropertyDefinitionType.AccountRelationship}/${option.id}`,
+ { id: option.id, name: option.id, property_type: option.property_type },
+ ]),
+ ])
+ )
},
})),
- afterMount(({ actions, values }) => {
+ afterMount(({ actions, values, cache }) => {
+ cache.definitionProjectId = values.currentProjectId
updatePropertyDefinitions(
Object.fromEntries(
ACCOUNT_FIELD_TAXONOMIC_OPTIONS.map((option) => [
@@ -870,7 +1071,5 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
// The picker needs fields when the SQL editor loaded only shallow schemas.
actions.ensureAllTableFields()
}
- actions.loadCustomPropertyDefinitions()
- actions.loadRelationshipDefinitions()
}),
])
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 1b7e2590a7d5..13681ceca71d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -15,7 +15,9 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import {
AccountsTableAccountField,
AccountsTableAccountFieldOperator,
+ AccountsTableAggregation,
AccountsTableCustomPropertyOperator,
+ AccountsTableThresholdOperator,
type AccountsTableQuery,
type AccountsTableQueryResponse,
NodeKind,
@@ -48,6 +50,7 @@ import {
ACCOUNTS_DEFAULT_COLUMNS,
ACCOUNTS_NAME_COLUMN,
accountsColumnConfigLogic,
+ customPropertyAlias,
relationshipAlias,
} from './accountsColumnConfigLogic'
import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'
@@ -98,6 +101,12 @@ const mockAccountsPresenceList = accountsPresenceList as jest.MockedFunction<typ
const CSM_DEFINITION_ID = '11111111-2222-3333-4444-555555555555'
const AE_DEFINITION_ID = '66666666-7777-8888-9999-aaaaaaaaaaaa'
const OWNER_DEFINITION_ID = 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff'
+const CSM_COLUMN = `accounts.relationships.values.\`${CSM_DEFINITION_ID}\` AS ${relationshipAlias(CSM_DEFINITION_ID)}`
+const AE_COLUMN = `accounts.relationships.values.\`${AE_DEFINITION_ID}\` AS ${relationshipAlias(AE_DEFINITION_ID)}`
+const OWNER_COLUMN = `accounts.relationships.values.\`${OWNER_DEFINITION_ID}\` AS ${relationshipAlias(OWNER_DEFINITION_ID)}`
+const CSM_ALIAS = relationshipAlias(CSM_DEFINITION_ID)
+const AE_ALIAS = relationshipAlias(AE_DEFINITION_ID)
+const OWNER_ALIAS = relationshipAlias(OWNER_DEFINITION_ID)
const TILE_FILTER = {
tileId: 'tile-1',
filter: {
@@ -234,7 +243,17 @@ describe('accountsLogic', () => {
logic.mount()
// Saved-view restoration has its own suite; these tests exercise the settled list.
logic.actions.applyViewState(logic.values.viewState, { source: 'draft', columns: 'keep' })
- // Legacy role columns only resolve into the query once definitions load.
+ const config = accountsColumnConfigLogic.findMounted()!
+ config.actions.hydrateTableDefinitions({
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: DEFINITIONS.map((definition) => ({ kind: 'relationship', definitionId: definition.id })),
+ relationshipDefinitions: DEFINITIONS,
+ })
+ config.actions.loadRelationshipDefinitionsSuccess(DEFINITIONS)
await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
})
@@ -261,14 +280,8 @@ describe('accountsLogic', () => {
it('runs the list and overview through typed Postgres queries', () => {
const source = logic.values.accountsQuerySource as AccountsTableQuery
expect(source.kind).toBe('AccountsTableQuery')
- expect(source.columns).toEqual([
- { kind: 'account_field', field: 'name' },
- { kind: 'tags' },
- { kind: 'note_count' },
- { kind: 'relationship', definitionId: CSM_DEFINITION_ID },
- { kind: 'relationship', definitionId: AE_DEFINITION_ID },
- { kind: 'relationship', definitionId: OWNER_DEFINITION_ID },
- ])
+ expect(source.columns).toEqual([])
+ expect(source.useDefaultColumns).toBe(true)
expect(logic.values.metricsQuery).toMatchObject({
kind: 'AccountsTableQuery',
columns: [],
@@ -290,8 +303,8 @@ describe('accountsLogic', () => {
expect(logic.values.accountsDataTableQuery.columns).not.toContain('arbitrary_hogql()')
})
- it('removes restored unsupported custom-property filters', () => {
- logic.actions.loadCustomPropertyDefinitionsSuccess([
+ it('removes unsupported operators while keeping unknown IDs for backend validation', () => {
+ accountsColumnConfigLogic.findMounted()!.actions.loadCustomPropertyDefinitionsSuccess([
{
id: CSM_DEFINITION_ID,
name: 'Plan',
@@ -320,7 +333,7 @@ describe('accountsLogic', () => {
])
expect(logic.values.accountFilters).toEqual([])
- expect(logic.values.accountFilterGroups).toEqual([[ACCOUNT_FILTERS[0]]])
+ expect(logic.values.accountFilterGroups[0]).toHaveLength(2)
expect(logic.values.activeFilterCount).toBe(1)
})
@@ -405,22 +418,57 @@ describe('accountsLogic', () => {
expect(logic.values.searchQuery).toBe('acme')
})
- it('withholds the list and metrics queries until relationship definitions settle', async () => {
+ it('starts table and overview queries without loading definition catalogs', () => {
logic.unmount()
- let resolveDefinitions: (value: { count: number; results: AccountRelationshipDefinitionApi[] }) => void
- mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))
logic = accountsLogic()
logic.mount()
logic.actions.setAwaitingSavedView(false)
+ const tiles = accountsOverviewTilesLogic.findMounted()!
+ const columnExpression = `toFloatOrNull(accounts.custom_properties.values.\`${CSM_DEFINITION_ID}\`)`
+ tiles.actions.setTiles([
+ { id: 'saved-total', label: 'Total', metric: { type: 'sum', columnExpression, columnLabel: 'Amount' } },
+ {
+ id: 'saved-threshold',
+ label: 'Above threshold',
+ metric: { type: 'count_threshold', columnExpression, columnLabel: 'Amount', operator: '>', value: 10 },
+ },
+ ])
- expect(logic.values.accountsQuerySource).toBeNull()
- expect(logic.values.metricsQuery).toBeNull()
-
- resolveDefinitions!({ count: DEFINITIONS.length, results: DEFINITIONS })
- await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
+ expect(logic.values.accountsQuerySource?.useDefaultColumns).toBe(true)
+ expect(logic.values.metricsQuery?.metrics).toEqual([
+ {
+ kind: 'aggregate',
+ aggregation: AccountsTableAggregation.Sum,
+ column: { kind: 'custom_property', definitionId: CSM_DEFINITION_ID },
+ },
+ {
+ kind: 'count_threshold',
+ column: { kind: 'custom_property', definitionId: CSM_DEFINITION_ID },
+ operator: AccountsTableThresholdOperator.GreaterThan,
+ value: 10,
+ },
+ ])
+ expect(mockDefinitionsList).not.toHaveBeenCalled()
+ expect(mockCustomPropertiesList).not.toHaveBeenCalled()
+ })
- expect(logic.values.accountsQuerySource?.kind).toBe('AccountsTableQuery')
- expect(logic.values.metricsQuery).not.toBeNull()
+ it('hydrates defaults without changing the table or overview request', () => {
+ const config = accountsColumnConfigLogic.findMounted()!
+ config.actions.resetColumns()
+ const beforeTable = logic.values.accountsQuerySource
+ const beforeMetrics = logic.values.metricsQuery
+ config.actions.hydrateTableDefinitions({
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: DEFINITIONS.map((definition) => ({ kind: 'relationship', definitionId: definition.id })),
+ relationshipDefinitions: DEFINITIONS,
+ })
+ expect(logic.values.visibleColumnNames).toContain(relationshipAlias(CSM_DEFINITION_ID))
+ expect(logic.values.accountsQuerySource).toEqual(beforeTable)
+ expect(logic.values.metricsQuery).toEqual(beforeMetrics)
})
it.each([
@@ -460,59 +508,71 @@ describe('accountsLogic', () => {
expect(logic.values.awaitingSavedView).toBe(true)
})
- it('removes relationship filters when relationship definitions fail to load', async () => {
+ it('keeps active relationship filters when the catalog request fails', async () => {
logic.unmount()
silenceKeaLoadersErrors()
mockDefinitionsList.mockRejectedValueOnce(new Error('network'))
logic = accountsLogic()
logic.mount()
-
- logic.actions.updateAccountFilters([
- {
- type: PropertyFilterType.AccountRelationship,
- key: CSM_DEFINITION_ID,
- operator: PropertyOperator.Exact,
- value: [42],
- },
- ])
-
- await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
-
- expect(logic.values.accountFilters).toEqual([])
- expect(logic.values.accountsQuerySource?.filters).not.toContainEqual(
- expect.objectContaining({ kind: 'relationship' })
- )
- expect(logic.values.activeFilterCount).toBe(0)
+ logic.actions.setAwaitingSavedView(false)
+ const filter = {
+ type: PropertyFilterType.AccountRelationship as const,
+ key: CSM_DEFINITION_ID,
+ operator: PropertyOperator.Exact,
+ value: [42],
+ }
+ logic.actions.updateAccountFilters([filter])
+ const config = accountsColumnConfigLogic.findMounted()!
+ await expectLogic(config, () => config.actions.ensureDefinitionsLoaded()).toFinishAllListeners()
+ expect(logic.values.accountFilters).toEqual([filter])
+ expect(logic.values.accountsQuerySource?.filters).toContainEqual({
+ kind: 'relationship',
+ definitionId: CSM_DEFINITION_ID,
+ operator: 'exact',
+ userIds: [42],
+ })
})
- it('keeps custom-property groups until definitions load after a relationship failure', async () => {
+ it('loads each complete catalog once when a picker needs it', async () => {
logic.unmount()
- silenceKeaLoadersErrors()
- let resolveDefinitions!: (result: Awaited<ReturnType<typeof customPropertyDefinitionsList>>) => void
- mockCustomPropertiesList.mockReturnValueOnce(
- new Promise<Awaited<ReturnType<typeof customPropertyDefinitionsList>>>((resolve) => {
- resolveDefinitions = resolve
- })
- )
- mockDefinitionsList.mockRejectedValueOnce(new Error('network'))
+ const first = buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID, name: 'Plan' })
+ const last = buildCustomPropertyDefinition({ id: AE_DEFINITION_ID, name: 'Renewal' })
+ mockCustomPropertiesList.mockResolvedValue({ count: 2, next: null, results: [first, last] })
logic = accountsLogic()
logic.mount()
- const customFilter = {
- type: PropertyFilterType.AccountCustomProperty as const,
- key: CSM_DEFINITION_ID,
- operator: PropertyOperator.Exact,
- value: 5,
- }
- logic.actions.setAccountFilterGroups([[customFilter]])
+ const config = accountsColumnConfigLogic.findMounted()!
+ expect(mockCustomPropertiesList).not.toHaveBeenCalled()
+ await expectLogic(config, () => config.actions.showColumnConfigurator()).toFinishAllListeners()
+ await expectLogic(config, () => config.actions.ensureDefinitionsLoaded()).toFinishAllListeners()
+ expect(mockCustomPropertiesList).toHaveBeenCalledTimes(1)
+ expect(mockCustomPropertiesList).toHaveBeenCalledWith(expect.any(String), { pagination: 'none' })
+ expect(mockDefinitionsList).toHaveBeenCalledTimes(1)
+ expect(mockDefinitionsList).toHaveBeenCalledWith(expect.any(String), { pagination: 'none' })
+ expect(config.values.aliasToDefinition[customPropertyAlias(AE_DEFINITION_ID)]).toEqual(last)
+ })
- await expectLogic(accountsColumnConfigLogic.findMounted()!).toDispatchActions([
- 'loadRelationshipDefinitionsFailure',
+ it('hides a deleted saved column without changing the table request', () => {
+ const config = accountsColumnConfigLogic.findMounted()!
+ config.actions.restoreSelectColumns([
+ 'name',
+ `accounts.custom_properties.values.\`${CSM_DEFINITION_ID}\` AS ${customPropertyAlias(CSM_DEFINITION_ID)}`,
])
- expect(logic.values.accountFilterGroups).toEqual([[customFilter]])
-
- resolveDefinitions({ count: 1, results: [buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID })] })
- await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
- expect(logic.values.accountFilterGroups).toEqual([[customFilter]])
+ const request = logic.values.accountsQuerySource
+ config.actions.hydrateTableDefinitions(
+ {
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: [{ kind: 'account_field', field: AccountsTableAccountField.Name }],
+ customPropertyDefinitions: [],
+ relationshipDefinitions: [],
+ },
+ config.values.querySelectColumns
+ )
+ expect(logic.values.visibleColumnNames).toEqual(['name'])
+ expect(logic.values.accountsQuerySource).toEqual(request)
})
it('keeps overview metrics off the list query', () => {
@@ -850,7 +910,7 @@ describe('accountsLogic', () => {
it('replaces a removed pinned server sort with the active client sort', async () => {
logic.actions.setSortOrder({ column: 'notebook_count', direction: 'asc' })
receiveResponse('complete-request', false)
- logic.actions.setSortOrder({ column: 'csm', direction: 'asc' })
+ logic.actions.setSortOrder({ column: relationshipAlias(CSM_DEFINITION_ID), direction: 'asc' })
expect(logic.values.serverSortOrder).toEqual({ column: 'notebook_count', direction: 'asc' })
@@ -861,8 +921,11 @@ describe('accountsLogic', () => {
}).toFinishAllListeners()
expect(logic.values.visibleColumnNames).not.toContain('notebook_count')
- expect(logic.values.sortOrder).toEqual({ column: 'csm', direction: 'asc' })
- expect(logic.values.serverSortOrder).toEqual({ column: 'csm', direction: 'asc' })
+ expect(logic.values.sortOrder).toEqual({ column: relationshipAlias(CSM_DEFINITION_ID), direction: 'asc' })
+ expect(logic.values.serverSortOrder).toEqual({
+ column: relationshipAlias(CSM_DEFINITION_ID),
+ direction: 'asc',
+ })
expect(logic.values.accountsQuerySource?.sort).toEqual({
column: { kind: 'relationship', definitionId: CSM_DEFINITION_ID },
direction: 'asc',
@@ -915,37 +978,42 @@ describe('accountsLogic', () => {
const config = accountsColumnConfigLogic.findMounted()
expect(config?.values.selectColumns).toEqual([
...ACCOUNTS_DEFAULT_COLUMNS,
- 'csm',
- 'account_executive',
- 'account_owner',
+ CSM_COLUMN,
+ AE_COLUMN,
+ OWNER_COLUMN,
])
expect(config?.values.selectColumns).toContain(ACCOUNTS_NAME_COLUMN)
})
- it('translates legacy role columns into typed relationship columns', () => {
+ it('sends saved relationship IDs without waiting for catalogs', () => {
+ const config = accountsColumnConfigLogic.findMounted()!
+ config.actions.restoreSelectColumns(['name', CSM_COLUMN, AE_COLUMN, OWNER_COLUMN])
expect(logic.values.accountsQuerySource?.columns).toEqual([
{ kind: 'account_field', field: 'name' },
- { kind: 'tags' },
- { kind: 'note_count' },
{ kind: 'relationship', definitionId: CSM_DEFINITION_ID },
{ kind: 'relationship', definitionId: AE_DEFINITION_ID },
{ kind: 'relationship', definitionId: OWNER_DEFINITION_ID },
])
})
- it('drops legacy role columns from the query when no matching definition exists', () => {
- accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])
- expect(logic.values.accountsQuerySource?.columns).toEqual([
- { kind: 'account_field', field: 'name' },
- { kind: 'tags' },
- { kind: 'note_count' },
- ])
+ it('omits missing relationships from resolved default columns', () => {
+ const config = accountsColumnConfigLogic.findMounted()!
+ config.actions.hydrateTableDefinitions({
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: [],
+ relationshipDefinitions: [],
+ })
+ expect(logic.values.accountsQuerySource?.columns).toEqual([])
expect(logic.values.visibleColumnNames).toEqual([ACCOUNTS_NAME_COLUMN, 'tag_names', 'notebook_count'])
})
- it('materializes pristine defaults into one column per definition once definitions load', () => {
+ it('materializes pristine defaults from the table response', () => {
const config = accountsColumnConfigLogic.findMounted()!
- config.actions.loadRelationshipDefinitionsSuccess([
+ const relationships = [
...DEFINITIONS,
{
id: 'def-os',
@@ -954,19 +1022,28 @@ describe('accountsLogic', () => {
is_single_holder: true,
is_controlled: false,
},
- ])
+ ]
+ config.actions.hydrateTableDefinitions({
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: relationships.map((definition) => ({ kind: 'relationship', definitionId: definition.id })),
+ relationshipDefinitions: relationships,
+ })
expect(config.values.selectColumns).toEqual([
...ACCOUNTS_DEFAULT_COLUMNS,
- 'csm',
- 'account_executive',
- 'account_owner',
+ CSM_COLUMN,
+ AE_COLUMN,
+ OWNER_COLUMN,
`accounts.relationships.values.\`def-os\` AS ${relationshipAlias('def-os')}`,
])
})
it('leaves customized columns alone when definitions load', () => {
const config = accountsColumnConfigLogic.findMounted()!
- config.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ config.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
config.actions.loadRelationshipDefinitionsSuccess([
...DEFINITIONS,
{
@@ -977,7 +1054,7 @@ describe('accountsLogic', () => {
is_controlled: false,
},
])
- expect(config.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])
+ expect(config.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
})
it('refuses to remove the name column via unselectColumn', () => {
@@ -988,14 +1065,14 @@ describe('accountsLogic', () => {
it('re-inserts the name column when setSelectColumns omits it', () => {
const config = accountsColumnConfigLogic.findMounted()
- config?.actions.setSelectColumns(['csm', 'account_executive'])
- expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm', 'account_executive'])
+ config?.actions.setSelectColumns([CSM_COLUMN, AE_COLUMN])
+ expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, CSM_COLUMN, AE_COLUMN])
})
it('keeps user ordering when setSelectColumns already contains name', () => {
const config = accountsColumnConfigLogic.findMounted()
- config?.actions.setSelectColumns(['csm', ACCOUNTS_NAME_COLUMN, 'account_executive'])
- expect(config?.values.selectColumns).toEqual(['csm', ACCOUNTS_NAME_COLUMN, 'account_executive'])
+ config?.actions.setSelectColumns([CSM_COLUMN, ACCOUNTS_NAME_COLUMN, AE_COLUMN])
+ expect(config?.values.selectColumns).toEqual([CSM_COLUMN, ACCOUNTS_NAME_COLUMN, AE_COLUMN])
})
})
@@ -1067,7 +1144,7 @@ describe('accountsLogic', () => {
expect(logic.values.tiles).toEqual(DEFAULT_TILES)
})
- it.each(['name', 'csm'])(
+ it.each(['name', CSM_ALIAS])(
'discards the %s sort on browser Back without a return token while columns load',
async (column) => {
logic.actions.setSortOrder({ column, direction: 'desc' })
@@ -1113,7 +1190,7 @@ describe('accountsLogic', () => {
search: 'acme',
tags: ['enterprise'],
assignedTo: [7],
- columns: [ACCOUNTS_NAME_COLUMN, 'csm'],
+ columns: [ACCOUNTS_NAME_COLUMN, CSM_COLUMN],
customProperties: [
{
type: PropertyFilterType.Account,
@@ -1159,13 +1236,13 @@ describe('accountsLogic', () => {
urls.customerAnalyticsAccounts(),
{},
{
- view: { columns: [ACCOUNTS_NAME_COLUMN, 'csm'] },
+ view: { columns: [ACCOUNTS_NAME_COLUMN, CSM_COLUMN] },
}
)
await expectLogic(logic).toFinishAllListeners()
const config = accountsColumnConfigLogic.findMounted()
- expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])
+ expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
})
it.each([
@@ -1177,18 +1254,20 @@ describe('accountsLogic', () => {
count: 1,
results: [buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID })],
})
- logic.actions.loadCustomPropertyDefinitionsSuccess([
- buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID }),
- ])
+ accountsColumnConfigLogic
+ .findMounted()!
+ .actions.loadCustomPropertyDefinitionsSuccess([
+ buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID }),
+ ])
const columnConfig = accountsColumnConfigLogic.findMounted()!
- columnConfig.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ columnConfig.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
columnConfig.actions.moveColumn(0, 1)
columnConfig.actions.setColumnDisplay(CSM_DEFINITION_ID, { mode: 'sparkline', window_days: 30 })
logic.actions.setSearchQuery('draft search')
logic.actions.setTagsFilter(['enterprise'])
logic.actions.setAssignedToFilter([7])
logic.actions.updateAccountFilters(ACCOUNT_FILTERS)
- logic.actions.setSortOrder({ column: 'csm', direction: 'desc' })
+ logic.actions.setSortOrder({ column: relationshipAlias(CSM_DEFINITION_ID), direction: 'desc' })
const overviewTiles = accountsOverviewTilesLogic.findMounted()!
overviewTiles.actions.addTile(CUSTOM_TILES[0])
overviewTiles.actions.moveTile(0, 1)
@@ -1236,7 +1315,7 @@ describe('accountsLogic', () => {
['a populated shared view', { search: 'shared', assignmentStatus: 'all' }, 'shared', 'all'],
])('uses %s instead of session edits and keeps it in memory', async (_, sharedView, search, status) => {
logic.actions.setSearchQuery('draft')
- logic.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ logic.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
logic.actions.setAssignedToFilter([7])
await expectLogic(logic).toFinishAllListeners()
logic.unmount()
@@ -1341,11 +1420,35 @@ describe('accountsLogic', () => {
it('resolves to the account even when the viewer has filters of their own', async () => {
logic.actions.setSearchQuery('something else')
logic.actions.setAssignedToFilter([99])
+ const customFilter = {
+ type: PropertyFilterType.AccountCustomProperty as const,
+ key: CSM_DEFINITION_ID,
+ operator: PropertyOperator.Exact,
+ value: 'saved filter',
+ }
+ logic.actions.setAccountFilters([customFilter])
+ logic.actions.setAccountFilterGroups([[customFilter]])
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.accountsQuerySource?.filters).toEqual([{ kind: 'account_id', accountId: ACCOUNT_ID }])
+ logic.actions.listLoadData(undefined, 'deep-link-response')
+ logic.actions.listLoadDataSuccess(
+ {
+ kind: NodeKind.AccountsTableQuery,
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ columns: [],
+ customPropertyDefinitions: [],
+ relationshipDefinitions: [],
+ },
+ { queryId: 'deep-link-response', overrideQuery: undefined, pollOnly: true, refresh: undefined }
+ )
+ expect(logic.values.accountFilters).toEqual([customFilter])
+ expect(logic.values.accountFilterGroups).toEqual([[customFilter]])
})
it('clears OR groups when opening an account hidden by the current filters', () => {
@@ -1364,7 +1467,7 @@ describe('accountsLogic', () => {
const deepLinkPath = router.values.location.pathname
// Column initialization must not send an account deep link back to the list.
- accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, CSM_COLUMN])
await expectLogic(logic).toFinishAllListeners()
expect(router.values.location.pathname).toBe(deepLinkPath)
@@ -1527,17 +1630,19 @@ describe('accountsLogic', () => {
describe('updateAccountRole', () => {
it('assigns via the relationships API and masks the cell with an override', async () => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
const user = buildUser()
mockRelationshipsCreate.mockResolvedValue(buildRelationship())
- logic.actions.updateAccountRole('acc-1', 'csm', user)
+ logic.actions.updateAccountRole('acc-1', CSM_ALIAS, user)
await expectLogic(logic).toFinishAllListeners()
expect(mockRelationshipsCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
definition: CSM_DEFINITION_ID,
user: user.id,
})
- expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'csm')]).toEqual([user.id])
+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', CSM_ALIAS)]).toEqual([user.id])
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.RoleAssigned, expect.objectContaining({ role: 'csm' }))
})
it('unassigning ends only the active assignments of that definition', async () => {
@@ -1549,16 +1654,16 @@ describe('accountsLogic', () => {
buildRelationship({ id: 'rel-csm', ended_at: '2026-01-02T00:00:00Z' })
)
- logic.actions.updateAccountRole('acc-1', 'csm', null)
+ logic.actions.updateAccountRole('acc-1', CSM_ALIAS, null)
await expectLogic(logic).toFinishAllListeners()
expect(mockRelationshipsEnd).toHaveBeenCalledTimes(1)
expect(mockRelationshipsEnd).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', 'rel-csm')
- expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'csm')]).toEqual([])
+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', CSM_ALIAS)]).toEqual([])
})
it('flips savingRoles during the in-flight window', async () => {
- const key = savingRoleKey('acc-1', 'account_executive')
+ const key = savingRoleKey('acc-1', AE_ALIAS)
let resolveCreate!: (value: AccountRelationshipApi) => void
mockRelationshipsCreate.mockReturnValueOnce(
new Promise<AccountRelationshipApi>((resolve) => {
@@ -1566,26 +1671,26 @@ describe('accountsLogic', () => {
})
)
- logic.actions.updateAccountRole('acc-1', 'account_executive', buildUser())
+ logic.actions.updateAccountRole('acc-1', AE_ALIAS, buildUser())
await new Promise<void>((r) => setTimeout(r, 0))
expect(logic.values.savingRoles[key]).toBe(true)
- expect(logic.values.isRoleSaving('acc-1', 'account_executive')).toBe(true)
+ expect(logic.values.isRoleSaving('acc-1', AE_ALIAS)).toBe(true)
resolveCreate(buildRelationship())
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.savingRoles[key]).toBeUndefined()
- expect(logic.values.isRoleSaving('acc-1', 'account_executive')).toBe(false)
+ expect(logic.values.isRoleSaving('acc-1', AE_ALIAS)).toBe(false)
})
it('leaves overrides untouched on failure', async () => {
mockRelationshipsCreate.mockRejectedValueOnce(new Error('boom'))
- logic.actions.updateAccountRole('acc-1', 'account_owner', buildUser())
+ logic.actions.updateAccountRole('acc-1', OWNER_ALIAS, buildUser())
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'account_owner')]).toBeUndefined()
- expect(logic.values.isRoleSaving('acc-1', 'account_owner')).toBe(false)
+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', OWNER_ALIAS)]).toBeUndefined()
+ expect(logic.values.isRoleSaving('acc-1', OWNER_ALIAS)).toBe(false)
})
it('is a no-op while a save for the same role is already in flight', async () => {
@@ -1596,9 +1701,9 @@ describe('accountsLogic', () => {
})
)
- logic.actions.updateAccountRole('acc-1', 'csm', buildUser({ id: 1, email: '[email protected]' }))
+ logic.actions.updateAccountRole('acc-1', CSM_ALIAS, buildUser({ id: 1, email: '[email protected]' }))
await new Promise<void>((r) => setTimeout(r, 0))
- logic.actions.updateAccountRole('acc-1', 'csm', buildUser({ id: 2, email: '[email protected]' }))
+ logic.actions.updateAccountRole('acc-1', CSM_ALIAS, buildUser({ id: 2, email: '[email protected]' }))
await new Promise<void>((r) => setTimeout(r, 0))
expect(mockRelationshipsCreate).toHaveBeenCalledTimes(1)
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index b582acf6ad2d..f9445b15c2c7 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -18,9 +18,14 @@ import { userLogic } from 'scenes/userLogic'
import { tagsModel } from '~/models/tagsModel'
import { type DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
+import type {
+ AccountsTableCustomPropertyDefinition,
+ AccountsTableRelationshipDefinition,
+} from '~/queries/schema/schema-general'
import {
AccountsTableMetric,
AccountsTableQuery,
+ AccountsTableQueryResponse,
DataNode,
DataTableNode,
NodeKind,
@@ -46,11 +51,9 @@ import {
import type {
AccountPresenceApi,
AccountPresenceViewerApi,
- AccountRelationshipDefinitionApi,
- CustomPropertyDefinitionApi,
CustomPropertyValueWriteApi,
} from '../../generated/api.schemas'
-import { accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'
+import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
import {
ACCOUNT_EXPANSION_TABS,
@@ -73,7 +76,7 @@ import {
} from './accountsTableQuery'
import { getAccountsViewSession } from './accountsViewSessionLogic'
import { AccountsViewState, normalizeRoleFilter } from './accountsViewState'
-import { AccountsEvents, DEFAULT_TILES } from './constants'
+import { ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES, AccountsEvents, DEFAULT_TILES } from './constants'
export const SEARCH_DEBOUNCE_MS = 300
@@ -245,15 +248,16 @@ function accountsViewStateFromUrl(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsLogicValues {
- aliasToDefinition: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogic
- aliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi> // accountsColumnConfigLogic
+ aliasToDefinition: Record<string, AccountsTableCustomPropertyDefinition> // accountsColumnConfigLogic
+ aliasToRelationshipDefinition: Record<string, AccountsTableRelationshipDefinition> // accountsColumnConfigLogic
columnDisplay: AccountColumnDisplayState // accountsColumnConfigLogic
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogic
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition> // accountsColumnConfigLogic
defaultSelectColumns: string[] // accountsColumnConfigLogic
querySelectColumns: string[] // accountsColumnConfigLogic
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi> // accountsColumnConfigLogic
- relationshipDefinitionsLoaded: boolean // accountsColumnConfigLogic
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition> // accountsColumnConfigLogic
+ renderSelectColumns: string[] // accountsColumnConfigLogic
selectColumns: string[] // accountsColumnConfigLogic
+ useDefaultColumns: boolean // accountsColumnConfigLogic
visibleColumnNames: string[] // accountsColumnConfigLogic
overviewMetrics: AccountsTableMetric[] // accountsOverviewTilesLogic
tileFilter: TileFilter | null // accountsOverviewTilesLogic
@@ -300,26 +304,12 @@ export interface accountsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsLogicActions {
- loadCustomPropertyDefinitionsSuccess: (
- customPropertyDefinitions: CustomPropertyDefinitionApi[],
- payload?: any
- ) => {
- customPropertyDefinitions: CustomPropertyDefinitionApi[]
- payload?: any
- } // accountsColumnConfigLogic
- loadRelationshipDefinitionsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- } // accountsColumnConfigLogic
- loadRelationshipDefinitionsSuccess: (
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- payload?: any
+ hydrateTableDefinitions: (
+ response: AccountsTableQueryResponse,
+ requestedColumns?: string[] | undefined
) => {
- payload?: any
- relationshipDefinitions: AccountRelationshipDefinitionApi[]
+ requestedColumns: string[] | undefined
+ response: AccountsTableQueryResponse
} // accountsColumnConfigLogic
resetColumns: () => {
value: true
@@ -600,11 +590,11 @@ export interface accountsLogicActions {
}
updateAccountCustomProperty: (
accountId: string,
- definition: CustomPropertyDefinitionApi,
+ definition: AccountsTableCustomPropertyDefinition,
value: CustomPropertyValueWriteApi['value']
) => {
accountId: string
- definition: CustomPropertyDefinitionApi
+ definition: AccountsTableCustomPropertyDefinition
value: boolean | number | string | null
}
updateAccountFilterGroup: (
@@ -675,8 +665,8 @@ export interface accountsLogicMeta {
tileFilter: TileFilter | null,
accountFilters: AccountFilter[],
accountFilterGroups: AccountFilter[][],
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>,
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>,
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
) => string
listDataCompleteness: (
listResponseState: AccountListResponseState | null,
@@ -697,6 +687,8 @@ export interface accountsLogicMeta {
accountsTableQueryPlanInput: (
querySelectColumns: string[],
visibleColumnNames: string[],
+ useDefaultColumns: boolean,
+ renderSelectColumns: string[],
searchQuery: string,
tagsFilter: string[],
assignmentStatus: AssignmentStatus,
@@ -705,8 +697,8 @@ export interface accountsLogicMeta {
tileFilter: TileFilter | null,
accountFilters: AccountFilter[],
accountFilterGroups: AccountFilter[][],
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>,
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>,
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>,
columnDisplay: AccountColumnDisplayState,
serverSortOrder: AccountSortOrder
) => BuildAccountsTableQueryPlanInput
@@ -715,7 +707,6 @@ export interface accountsLogicMeta {
) => AccountsTableQueryPlan
accountsQuerySource: (
accountsTableQueryPlan: AccountsTableQueryPlan,
- relationshipDefinitionsLoaded: boolean,
awaitingSavedView: boolean,
viewStateHydrated: boolean
) => AccountsTableQuery | null
@@ -726,7 +717,6 @@ export interface accountsLogicMeta {
metricsQuery: (
overviewMetrics: AccountsTableMetric[],
accountsTableQueryPlan: AccountsTableQueryPlan,
- relationshipDefinitionsLoaded: boolean,
awaitingSavedView: boolean,
viewStateHydrated: boolean
) => AccountsTableQuery | null
@@ -757,7 +747,8 @@ export const accountsLogic = kea<accountsLogicType>([
'aliasToRelationshipDefinition',
'aliasToDefinition',
'relationshipDefinitionsById',
- 'relationshipDefinitionsLoaded',
+ 'useDefaultColumns',
+ 'renderSelectColumns',
'customPropertyDefinitionsById',
'columnDisplay',
],
@@ -767,9 +758,7 @@ export const accountsLogic = kea<accountsLogicType>([
actions: [
accountsColumnConfigLogic,
[
- 'loadCustomPropertyDefinitionsSuccess',
- 'loadRelationshipDefinitionsSuccess',
- 'loadRelationshipDefinitionsFailure',
+ 'hydrateTableDefinitions',
'setSelectColumns',
'selectColumn',
'unselectColumn',
@@ -826,7 +815,7 @@ export const accountsLogic = kea<accountsLogicType>([
reportFilterChange: (filterType: AccountFilterType) => ({ filterType }),
updateAccountCustomProperty: (
accountId: string,
- definition: CustomPropertyDefinitionApi,
+ definition: AccountsTableCustomPropertyDefinition,
value: CustomPropertyValueWriteApi['value']
) => ({ accountId, definition, value }),
customPropertyUpdateStarted: (accountId: string, definitionId: string) => ({ accountId, definitionId }),
@@ -1141,8 +1130,8 @@ export const accountsLogic = kea<accountsLogicType>([
tileFilter: TileFilter | null,
accountFilters: AccountFilter[],
accountFilterGroups: AccountFilter[][],
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>,
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>,
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
): string =>
`${currentTeamId ?? 'none'}:${accountsTableDatasetKey({
searchQuery,
@@ -1200,6 +1189,8 @@ export const accountsLogic = kea<accountsLogicType>([
(s) => [
s.querySelectColumns,
s.visibleColumnNames,
+ s.useDefaultColumns,
+ s.renderSelectColumns,
s.searchQuery,
s.tagsFilter,
s.assignmentStatus,
@@ -1216,6 +1207,8 @@ export const accountsLogic = kea<accountsLogicType>([
(
querySelectColumns: string[],
visibleColumnNames: string[],
+ useDefaultColumns: boolean,
+ renderSelectColumns: string[],
searchQuery: string,
tagsFilter: string[],
assignmentStatus: AssignmentStatus,
@@ -1224,13 +1217,15 @@ export const accountsLogic = kea<accountsLogicType>([
tileFilter: TileFilter | null,
accountFilters: AccountFilter[],
accountFilterGroups: AccountFilter[][],
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>,
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>,
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>,
columnDisplay: AccountColumnDisplayState,
serverSortOrder: AccountSortOrder
): BuildAccountsTableQueryPlanInput => ({
querySelectColumns,
visibleColumnNames,
+ useDefaultColumns,
+ renderSelectColumns,
searchQuery,
tagsFilter,
assignmentStatus,
@@ -1250,21 +1245,13 @@ export const accountsLogic = kea<accountsLogicType>([
(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan => buildAccountsTableQueryPlan(input),
],
accountsQuerySource: [
- (s) => [
- s.accountsTableQueryPlan,
- s.relationshipDefinitionsLoaded,
- s.awaitingSavedView,
- s.viewStateHydrated,
- ],
+ (s) => [s.accountsTableQueryPlan, s.awaitingSavedView, s.viewStateHydrated],
(
accountsTableQueryPlan: AccountsTableQueryPlan,
- relationshipDefinitionsLoaded: boolean,
awaitingSavedView: boolean,
viewStateHydrated: boolean
): AccountsTableQuery | null =>
- relationshipDefinitionsLoaded && !awaitingSavedView && viewStateHydrated
- ? accountsTableQueryPlan.query
- : null,
+ !awaitingSavedView && viewStateHydrated ? accountsTableQueryPlan.query : null,
],
accountsDataTableQuery: [
(s) => [s.accountsTableQueryPlan, s.accountsQuerySource],
@@ -1280,31 +1267,20 @@ export const accountsLogic = kea<accountsLogicType>([
}),
],
metricsQuery: [
- (s) => [
- s.overviewMetrics,
- s.accountsTableQueryPlan,
- s.relationshipDefinitionsLoaded,
- s.awaitingSavedView,
- s.viewStateHydrated,
- ],
+ (s) => [s.overviewMetrics, s.accountsTableQueryPlan, s.awaitingSavedView, s.viewStateHydrated],
(
overviewMetrics: AccountsTableMetric[],
accountsTableQueryPlan: AccountsTableQueryPlan,
- relationshipDefinitionsLoaded: boolean,
awaitingSavedView: boolean,
viewStateHydrated: boolean
): AccountsTableQuery | null => {
- if (
- overviewMetrics.length === 0 ||
- !relationshipDefinitionsLoaded ||
- awaitingSavedView ||
- !viewStateHydrated
- ) {
+ if (overviewMetrics.length === 0 || awaitingSavedView || !viewStateHydrated) {
return null
}
return {
...accountsTableQueryPlan.query,
columns: [],
+ useDefaultColumns: undefined,
metrics: overviewMetrics,
sort: undefined,
tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_overview' },
@@ -1409,6 +1385,7 @@ export const accountsLogic = kea<accountsLogicType>([
queryId,
datasetKey: values.listDatasetKey,
serverSortOrder: values.serverSortOrder,
+ validatesViewFilters: !values.accountIdFilter,
}
if (cache.awaitingCustomPropertyRefresh) {
cache.awaitingCustomPropertyRefresh = false
@@ -1443,6 +1420,32 @@ export const accountsLogic = kea<accountsLogicType>([
'hasMore' in response &&
typeof response.hasMore === 'boolean'
) {
+ if ('columns' in response && 'kind' in response && response.kind === NodeKind.AccountsTableQuery) {
+ const tableResponse = response as AccountsTableQueryResponse
+ actions.hydrateTableDefinitions(tableResponse, values.querySelectColumns)
+ if (
+ requestState.validatesViewFilters &&
+ tableResponse.customPropertyDefinitions &&
+ tableResponse.relationshipDefinitions
+ ) {
+ const customById = Object.fromEntries(
+ tableResponse.customPropertyDefinitions.map((definition) => [definition.id, definition])
+ )
+ const relationshipsById = Object.fromEntries(
+ tableResponse.relationshipDefinitions.map((definition) => [definition.id, definition])
+ )
+ const filters = supportedAccountFilters(values.accountFilters, customById, relationshipsById)
+ const groups = values.accountFilterGroups.map((group) =>
+ supportedAccountFilters(group, customById, relationshipsById)
+ )
+ if (!objectsEqual(filters, values.accountFilters)) {
+ actions.setAccountFilters(filters)
+ }
+ if (!objectsEqual(groups, values.accountFilterGroups)) {
+ actions.setAccountFilterGroups(groups)
+ }
+ }
+ }
// Pin the request sort for complete sets so this response does not change the query that produced it.
actions.setListResponseState(
requestState.datasetKey,
@@ -1480,76 +1483,12 @@ export const accountsLogic = kea<accountsLogicType>([
}
}
},
- loadCustomPropertyDefinitionsSuccess: ({ customPropertyDefinitions }) => {
- cache.customPropertyDefinitionsLoaded = true
- if (!cache.relationshipDefinitionsLoaded) {
- return
- }
- const definitionsById = Object.fromEntries(
- customPropertyDefinitions.map((definition) => [definition.id, definition])
- )
- const supportedFilters = supportedAccountFilters(
- values.accountFilters,
- definitionsById,
- values.relationshipDefinitionsById
- )
- if (!objectsEqual(supportedFilters, values.accountFilters)) {
- actions.setAccountFilters(supportedFilters)
- }
- const supportedGroups = values.accountFilterGroups.map((group) =>
- supportedAccountFilters(group, definitionsById, values.relationshipDefinitionsById)
- )
- if (!objectsEqual(supportedGroups, values.accountFilterGroups)) {
- actions.setAccountFilterGroups(supportedGroups)
- }
- },
- loadRelationshipDefinitionsSuccess: () => {
- cache.relationshipDefinitionsLoaded = true
- if (!cache.customPropertyDefinitionsLoaded) {
- return
- }
- const supportedFilters = supportedAccountFilters(
- values.accountFilters,
- values.customPropertyDefinitionsById,
- values.relationshipDefinitionsById
- )
- if (!objectsEqual(supportedFilters, values.accountFilters)) {
- actions.setAccountFilters(supportedFilters)
- }
- const supportedGroups = values.accountFilterGroups.map((group) =>
- supportedAccountFilters(group, values.customPropertyDefinitionsById, values.relationshipDefinitionsById)
- )
- if (!objectsEqual(supportedGroups, values.accountFilterGroups)) {
+ setAccountFilterGroups: ({ groups }) => {
+ const supportedGroups = groups.map((group) => supportedAccountFilters(group))
+ if (!objectsEqual(supportedGroups, groups)) {
actions.setAccountFilterGroups(supportedGroups)
- }
- },
- loadRelationshipDefinitionsFailure: () => {
- cache.relationshipDefinitionsLoaded = true
- actions.setAccountFilters(values.accountFilters)
- if (!cache.customPropertyDefinitionsLoaded) {
return
}
- const supportedGroups = values.accountFilterGroups.map((group) =>
- supportedAccountFilters(group, values.customPropertyDefinitionsById, values.relationshipDefinitionsById)
- )
- if (!objectsEqual(supportedGroups, values.accountFilterGroups)) {
- actions.setAccountFilterGroups(supportedGroups)
- }
- },
- setAccountFilterGroups: ({ groups }) => {
- if (cache.customPropertyDefinitionsLoaded && cache.relationshipDefinitionsLoaded) {
- const supportedGroups = groups.map((group) =>
- supportedAccountFilters(
- group,
- values.customPropertyDefinitionsById,
- values.relationshipDefinitionsById
- )
- )
- if (!objectsEqual(supportedGroups, groups)) {
- actions.setAccountFilterGroups(supportedGroups)
- return
- }
- }
persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
},
addAccountFilterGroup: () => {
@@ -1573,27 +1512,13 @@ export const accountsLogic = kea<accountsLogicType>([
},
setAccountFilters: ({ filters }) => {
persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
- if (!cache.customPropertyDefinitionsLoaded || !cache.relationshipDefinitionsLoaded) {
- return
- }
- const supportedFilters = supportedAccountFilters(
- filters,
- values.customPropertyDefinitionsById,
- values.relationshipDefinitionsById
- )
+ const supportedFilters = supportedAccountFilters(filters)
if (!objectsEqual(supportedFilters, filters)) {
actions.setAccountFilters(supportedFilters)
}
},
updateAccountFilters: ({ filters }, _, __, previousState) => {
- const supportedFilters =
- cache.customPropertyDefinitionsLoaded && cache.relationshipDefinitionsLoaded
- ? supportedAccountFilters(
- filters,
- values.customPropertyDefinitionsById,
- values.relationshipDefinitionsById
- )
- : filters
+ const supportedFilters = supportedAccountFilters(filters)
const previousFilters = selectors.accountFilters(previousState)
const changedFilter =
supportedFilters.find((filter, index) => !objectsEqual(filter, previousFilters[index])) ??
@@ -1893,7 +1818,7 @@ export const accountsLogic = kea<accountsLogicType>([
}
actions.setRelationshipOverride(accountId, column, user ? [user.id] : [])
posthog.capture(AccountsEvents.RoleAssigned, {
- role: isLegacyRoleColumn(column) ? column : definition.name,
+ role: ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES[definition.name] ?? definition.name,
is_assigned: user !== null,
assigned_user_id: user?.id ?? null,
source: 'list_row',
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
index 6c2deec7987d..f87f8caab569 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -238,18 +238,6 @@ export function parseTileValues(
return values
}
-function reconcileTilesAgainstSchema(
- tiles: AccountsOverviewTile[],
- numericExpressions: Set<string>
-): AccountsOverviewTile[] {
- return tiles.filter((tile) => {
- if (tile.metric.type === 'count') {
- return true
- }
- return numericExpressions.has(tile.metric.columnExpression) && tileQueryMetric(tile) !== null
- })
-}
-
export function diffOverviewTiles(
before: AccountsOverviewTile[],
after: AccountsOverviewTile[]
@@ -312,7 +300,6 @@ export interface accountsOverviewTilesLogicValues {
accountsResponseLoading: boolean // dataNodeLogic
editorVisible: boolean
metrics: AccountsTableMetric[]
- numericColumnExpressions: Set<string>
numericColumns: AccountColumnOption[]
reconciledTiles: AccountsOverviewTile[]
selectedTileId: string | null
@@ -324,6 +311,9 @@ export interface accountsOverviewTilesLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsOverviewTilesLogicActions {
+ ensureDefinitionsLoaded: () => {
+ value: true
+ } // accountsColumnConfigLogic
addTile: (
tile: Omit<AccountsOverviewTile, 'id'> & {
id?: string
@@ -374,11 +364,7 @@ export interface accountsOverviewTilesLogicActions {
export interface accountsOverviewTilesLogicMeta {
__keaTypeGenInternalSelectorTypes: {
numericColumns: (accountsColumnGroups: AccountColumnGroup[]) => AccountColumnOption[]
- numericColumnExpressions: (numericColumns: AccountColumnOption[]) => Set<string>
- reconciledTiles: (
- tiles: AccountsOverviewTile[],
- numericColumnExpressions: Set<string>
- ) => AccountsOverviewTile[]
+ reconciledTiles: (tiles: AccountsOverviewTile[]) => AccountsOverviewTile[]
metrics: (reconciledTiles: AccountsOverviewTile[]) => AccountsTableMetric[]
tileValues: (
accountsResponse:
@@ -414,6 +400,7 @@ export type accountsOverviewTilesLogicType = MakeLogicType<
export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
path(['scenes', 'customerAnalytics', 'accounts', 'accountsOverviewTilesLogic']),
connect(() => ({
+ actions: [accountsColumnConfigLogic, ['ensureDefinitionsLoaded']],
values: [
accountsColumnConfigLogic,
['accountsColumnGroups'],
@@ -484,14 +471,10 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
(s) => [s.accountsColumnGroups],
(groups: AccountColumnGroup[]): AccountColumnOption[] => numericColumnOptions(groups),
],
- numericColumnExpressions: [
- (s) => [s.numericColumns],
- (options: AccountColumnOption[]): Set<string> => new Set(options.map((o) => o.expression)),
- ],
reconciledTiles: [
- (s) => [s.tiles, s.numericColumnExpressions],
- (tiles: AccountsOverviewTile[], expressions: Set<string>): AccountsOverviewTile[] =>
- reconcileTilesAgainstSchema(tiles, expressions),
+ (s) => [s.tiles],
+ (tiles: AccountsOverviewTile[]): AccountsOverviewTile[] =>
+ tiles.filter((tile) => tileQueryMetric(tile) !== null),
],
metrics: [
(s) => [s.reconciledTiles],
@@ -510,6 +493,7 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
}),
listeners(({ actions, values, cache }) => ({
showEditor: () => {
+ actions.ensureDefinitionsLoaded()
cache.tilesSnapshot = values.tiles
},
hideEditor: () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
index 51f451028577..48f93215c5e8 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
@@ -3,7 +3,7 @@ import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import type { AccountSortOrder } from './accountsLogic'
import { sortAccountRows } from './accountsSort'
-const COLUMNS = ['name', 'notebook_count', 'csm']
+const COLUMNS = ['name', 'notebook_count', 'rel_11111111222233334444555555555555']
const buildRow = ({
name,
@@ -65,10 +65,9 @@ describe('sortAccountRows', () => {
it('treats an empty relationship array as an empty cell (sorts last)', () => {
const rows = [buildRow({ name: 'unassigned', csm: [] }), buildRow({ name: 'assigned', csm: [42] })]
- expect(names(sortAccountRows(rows, { column: 'csm', direction: 'asc' }, getCell))).toEqual([
- 'assigned',
- 'unassigned',
- ])
+ expect(
+ names(sortAccountRows(rows, { column: 'rel_11111111222233334444555555555555', direction: 'asc' }, getCell))
+ ).toEqual(['assigned', 'unassigned'])
})
it('keeps equal-keyed rows in their incoming order (stable)', () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
index f0605e48de67..2fef478af2fc 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
@@ -13,6 +13,7 @@ import type {
CustomPropertyDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { relationshipAlias } from './accountsColumnConfigLogic'
import type { AccountPropertyFilter, AccountRelationshipFilter } from './accountsPropertyFilters'
import {
AccountsTableQueryPlan,
@@ -67,9 +68,9 @@ function queryInput(overrides: Partial<BuildAccountsTableQueryPlanInput> = {}):
'name',
'accounts.tags.names AS tag_names',
'accounts.notebooks.count AS notebook_count',
- `accounts.relationships.values.\`${RELATIONSHIP_ID}\` AS csm`,
+ `accounts.relationships.values.\`${RELATIONSHIP_ID}\` AS ${relationshipAlias(RELATIONSHIP_ID)}`,
],
- visibleColumnNames: ['name', 'tag_names', 'notebook_count', 'csm'],
+ visibleColumnNames: ['name', 'tag_names', 'notebook_count', relationshipAlias(RELATIONSHIP_ID)],
searchQuery: '',
tagsFilter: [],
assignmentStatus: 'all',
@@ -97,7 +98,7 @@ describe('accountsTableQuery', () => {
assignmentStatus: 'assigned',
assignedToFilter: [7, 9],
accountFilters: [relationshipFilter(), customFilter()],
- serverSortOrder: { column: 'csm', direction: 'desc' },
+ serverSortOrder: { column: relationshipAlias(RELATIONSHIP_ID), direction: 'desc' },
})
)
@@ -154,7 +155,7 @@ describe('accountsTableQuery', () => {
)
})
- it('keeps valid conditions when a restored group contains deleted properties', () => {
+ it('sends restored definition IDs to the backend for validation', () => {
const validName = accountFieldFilter({
key: AccountsTableAccountField.Name,
operator: PropertyOperator.Exact,
@@ -169,9 +170,20 @@ describe('accountsTableQuery', () => {
)
expect(plan.query.filters).toEqual([])
+ const missing = { kind: 'custom_property', definitionId: missingProperty.key, operator: 'gt', values: [10] }
+ expect(plan.query.ignoreMissingDefinitions).toBe(true)
expect(plan.query.filterGroups).toEqual([
- [{ kind: 'account_field', field: AccountsTableAccountField.Name, operator: 'exact', values: ['Example'] }],
- [{ kind: 'relationship', definitionId: RELATIONSHIP_ID, operator: 'exact', userIds: [7] }],
+ [
+ {
+ kind: 'account_field',
+ field: AccountsTableAccountField.Name,
+ operator: 'exact',
+ values: ['Example'],
+ },
+ missing,
+ ],
+ [{ kind: 'relationship', definitionId: RELATIONSHIP_ID, operator: 'exact', userIds: [7] }, missing],
+ [missing],
])
})
@@ -350,20 +362,37 @@ describe('accountsTableQuery', () => {
])
})
+ it.each([
+ [PropertyOperator.IContains, 'text', 'standard'],
+ [PropertyOperator.GreaterThan, 'currency', 10],
+ [PropertyOperator.IsDateBefore, 'datetime', '2026-01-01'],
+ ] as const)('keeps filter transport independent of definition metadata for %s', (operator, displayType, value) => {
+ const input = queryInput({
+ accountFilters: [customFilter({ operator, value }), relationshipFilter()],
+ customPropertyDefinitionsById: { [CUSTOM_PROPERTY_ID]: { ...definition, display_type: displayType } },
+ })
+ const known = buildAccountsTableQueryPlan(input)
+ const unknown = buildAccountsTableQueryPlan({
+ ...input,
+ customPropertyDefinitionsById: {},
+ relationshipDefinitionsById: {},
+ })
+ expect(unknown.query).toEqual(known.query)
+ expect(unknown.query.filters).toHaveLength(2)
+ })
+
it.each([
['regex', 'currency', PropertyOperator.Regex],
- ['contains on a number', 'currency', PropertyOperator.IContains],
['comparison on text', 'text', PropertyOperator.GreaterThan],
- ['date comparison on boolean', 'boolean', PropertyOperator.IsDateBefore],
- ])('omits unsupported %s custom property filters', (_, displayType, operator) => {
- const incompatibleDefinition = { ...definition, display_type: displayType } as CustomPropertyDefinitionApi
+ ['contains on number', 'number', PropertyOperator.IContains],
+ ['date on text', 'text', PropertyOperator.IsDateAfter],
+ ] as const)('omits unsupported %s filters', (_, displayType, operator) => {
const plan = buildAccountsTableQueryPlan(
queryInput({
- customPropertyDefinitionsById: { [CUSTOM_PROPERTY_ID]: incompatibleDefinition },
+ customPropertyDefinitionsById: { [CUSTOM_PROPERTY_ID]: { ...definition, display_type: displayType } },
accountFilters: [customFilter({ operator })],
})
)
-
expect(plan.query.filters).toEqual([])
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
index 970da90347ea..20f8d346c30f 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
@@ -1,6 +1,11 @@
import type { AssignmentStatus } from 'lib/components/AccountAssignmentFilter/accountAssignmentFilterTypes'
import { isUUIDLike } from 'lib/utils/guards'
+import { chooseOperatorMap } from 'lib/utils/operators'
+import type {
+ AccountsTableCustomPropertyDefinition,
+ AccountsTableRelationshipDefinition,
+} from '~/queries/schema/schema-general'
import {
AccountsTableAccountField,
AccountsTableAccountFieldFilter,
@@ -26,13 +31,7 @@ import {
} from '~/queries/schema/schema-general'
import { AccountCustomPropertyFilter, PropertyOperator, PropertyType } from '~/types'
-import type {
- AccountRelationshipDefinitionApi,
- CustomPropertyDefinitionApi,
-} from 'products/customer_analytics/frontend/generated/api.schemas'
-
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
-import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'
import type { TileFilter } from './accountsOverviewTilesLogic'
@@ -41,6 +40,7 @@ import {
AccountFilter,
isAccountPropertyFilter,
isAccountRelationshipFilter,
+ propertyTypeForDisplayType,
} from './accountsPropertyFilters'
const RELATIONSHIP_COLUMN_REGEX = /^accounts\.relationships\.values\.`([0-9a-fA-F-]+)` AS [A-Za-z_][\w]*$/
@@ -121,12 +121,14 @@ export interface AccountsTableDatasetInput {
tileFilter: TileFilter | null
accountFilters: AccountFilter[]
accountFilterGroups: AccountFilter[][]
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
+ relationshipDefinitionsById: Record<string, AccountsTableRelationshipDefinition>
+ customPropertyDefinitionsById: Record<string, AccountsTableCustomPropertyDefinition>
}
export interface BuildAccountsTableQueryPlanInput extends AccountsTableDatasetInput {
querySelectColumns: string[]
+ renderSelectColumns?: string[]
+ useDefaultColumns?: boolean
visibleColumnNames: string[]
columnDisplay: AccountColumnDisplayState
serverSortOrder: AccountSortOrder
@@ -204,9 +206,9 @@ function accountFieldFilter(filter: AccountFilter): AccountsTableAccountFieldFil
function relationshipFilter(
filter: AccountFilter,
- definitionsById: Record<string, AccountRelationshipDefinitionApi>
+ _definitionsById: Record<string, AccountsTableRelationshipDefinition>
): AccountsTableRelationshipFilter | null {
- if (!isAccountRelationshipFilter(filter) || !isUUIDLike(filter.key) || !definitionsById[filter.key]) {
+ if (!isAccountRelationshipFilter(filter) || !isUUIDLike(filter.key)) {
return null
}
const operator = RELATIONSHIP_OPERATOR_MAP[filter.operator]
@@ -227,41 +229,17 @@ function relationshipFilter(
function customPropertyFilter(
filter: AccountCustomPropertyFilter,
- definitionsById: Record<string, CustomPropertyDefinitionApi>
+ definitionsById: Record<string, AccountsTableCustomPropertyDefinition>
): AccountsTableCustomPropertyFilter | null {
if (!filter.key || !isUUIDLike(filter.key)) {
return null
}
- const definition = definitionsById[filter.key]
const operator = CUSTOM_PROPERTY_OPERATOR_MAP[filter.operator]
- if (!definition || !operator) {
- return null
- }
- if (
- (operator === AccountsTableCustomPropertyOperator.Contains ||
- operator === AccountsTableCustomPropertyOperator.DoesNotContain) &&
- definition.display_type !== 'text' &&
- definition.display_type !== 'link' &&
- definition.display_type !== 'select'
- ) {
- return null
- }
- if (
- (operator === AccountsTableCustomPropertyOperator.GreaterThan ||
- operator === AccountsTableCustomPropertyOperator.GreaterThanOrEqual ||
- operator === AccountsTableCustomPropertyOperator.LessThan ||
- operator === AccountsTableCustomPropertyOperator.LessThanOrEqual) &&
- !isNumericDisplayType(definition.display_type)
- ) {
+ if (!operator) {
return null
}
- if (
- (operator === AccountsTableCustomPropertyOperator.DateExact ||
- operator === AccountsTableCustomPropertyOperator.DateBefore ||
- operator === AccountsTableCustomPropertyOperator.DateAfter) &&
- definition.display_type !== 'date' &&
- definition.display_type !== 'datetime'
- ) {
+ const definition = definitionsById[filter.key]
+ if (definition && !(filter.operator in chooseOperatorMap(propertyTypeForDisplayType(definition.display_type)))) {
return null
}
const rawValues = Array.isArray(filter.value) ? filter.value : filter.value == null ? [] : [filter.value]
@@ -285,15 +263,17 @@ function customPropertyFilter(
export function supportedAccountFilters(
filters: AccountFilter[],
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
- relationshipDefinitionsById: Record<string, AccountRelationshipDefinitionApi>
+ customPropertyDefinitionsById?: Record<string, AccountsTableCustomPropertyDefinition>,
+ relationshipDefinitionsById?: Record<string, AccountsTableRelationshipDefinition>
): AccountFilter[] {
return filters.filter((filter) =>
isAccountPropertyFilter(filter)
? accountFieldFilter(filter) !== null
: isAccountRelationshipFilter(filter)
- ? relationshipFilter(filter, relationshipDefinitionsById) !== null
- : customPropertyFilter(filter, customPropertyDefinitionsById) !== null
+ ? (!relationshipDefinitionsById || !!relationshipDefinitionsById[filter.key]) &&
+ relationshipFilter(filter, relationshipDefinitionsById ?? {}) !== null
+ : (!customPropertyDefinitionsById || !!customPropertyDefinitionsById[filter.key]) &&
+ customPropertyFilter(filter, customPropertyDefinitionsById ?? {}) !== null
)
}
@@ -350,8 +330,7 @@ function queryFilters(
}
if (input.tileFilter?.filter) {
const filter = input.tileFilter.filter
- const definition = input.customPropertyDefinitionsById[filter.definitionId]
- if (isUUIDLike(filter.definitionId) && definition && isNumericDisplayType(definition.display_type)) {
+ if (isUUIDLike(filter.definitionId)) {
if (filter.operator === AccountsTableCustomPropertyOperator.IsNot) {
filters.push({
kind: 'custom_property',
@@ -384,22 +363,46 @@ function sortableColumn(column: AccountsTableColumn): AccountsTableSortableColum
return column
}
-export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan {
- const columns: AccountsTablePlannedColumn[] = []
- const columnCount = Math.min(input.querySelectColumns.length, input.visibleColumnNames.length)
- for (let index = 0; index < columnCount; index++) {
- const column = columnFromExpression(input.querySelectColumns[index], input.columnDisplay)
- if (column) {
- columns.push({ visibleName: input.visibleColumnNames[index], column })
- }
+function sortColumnFromAlias(alias: string): AccountsTableSortableColumn | null {
+ if (alias === 'tag_names') {
+ return { kind: 'tags' }
}
+ if (alias === 'notebook_count') {
+ return { kind: 'note_count' }
+ }
+ const reference = alias.match(/^(cp|rel)_([0-9a-fA-F]{32})$/)
+ if (reference) {
+ const hex = reference[2]
+ const definitionId =
+ `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`.toLowerCase()
+ return { kind: reference[1] === 'cp' ? 'custom_property' : 'relationship', definitionId }
+ }
+ const column = columnFromExpression(alias, {})
+ return column ? sortableColumn(column) : null
+}
+
+export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan {
+ const planColumns = (expressions: string[]): AccountsTablePlannedColumn[] =>
+ expressions.flatMap((expression) => {
+ const column = columnFromExpression(expression, input.columnDisplay)
+ return column
+ ? [{ visibleName: expression.includes(' AS ') ? expression.split(' AS ').pop()! : expression, column }]
+ : []
+ })
+ const requestedColumns = planColumns(input.querySelectColumns)
+ const columns = planColumns(input.renderSelectColumns ?? input.querySelectColumns)
let sort: AccountsTableSort | undefined
if (input.serverSortOrder) {
- const plannedColumn = columns.find((column) => column.visibleName === input.serverSortOrder?.column)
- if (plannedColumn) {
+ const plannedColumn = requestedColumns.find((column) => column.visibleName === input.serverSortOrder?.column)
+ const sortColumn = plannedColumn
+ ? sortableColumn(plannedColumn.column)
+ : input.useDefaultColumns
+ ? sortColumnFromAlias(input.serverSortOrder.column)
+ : null
+ if (sortColumn) {
sort = {
- column: sortableColumn(plannedColumn.column),
+ column: sortColumn,
direction:
input.serverSortOrder.direction === 'asc'
? AccountsTableSortDirection.Ascending
@@ -414,7 +417,9 @@ export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanIn
return {
query: {
kind: NodeKind.AccountsTableQuery,
- columns: columns.map(({ column }) => column),
+ columns: input.useDefaultColumns ? [] : requestedColumns.map(({ column }) => column),
+ useDefaultColumns: input.useDefaultColumns || undefined,
+ ignoreMissingDefinitions: true,
filters,
filterGroups: propertyGroups.length > 1 ? propertyGroups : undefined,
includeChurned: input.accountIdFilter !== null,
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
index 4fc306ff935f..51c7aee00726 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
@@ -1,7 +1,7 @@
import { AccountsTableAccountField, AccountsTableCustomPropertyOperator } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
-import { ACCOUNTS_DEFAULT_COLUMNS } from './accountsColumnConfigLogic'
+import { ACCOUNTS_DEFAULT_COLUMNS, relationshipAlias } from './accountsColumnConfigLogic'
import {
AccountsViewState,
accountsViewIdStorageKey,
@@ -16,6 +16,10 @@ import {
} from './accountsViewState'
import { DEFAULT_TILES } from './constants'
+const RELATIONSHIP_ID = '11111111-2222-3333-4444-555555555555'
+const RELATIONSHIP_ALIAS = relationshipAlias(RELATIONSHIP_ID)
+const RELATIONSHIP_COLUMN = `accounts.relationships.values.\`${RELATIONSHIP_ID}\` AS ${RELATIONSHIP_ALIAS}`
+
describe('accountsViewState', () => {
describe('saved-view references', () => {
beforeEach(() => localStorage.clear())
@@ -66,8 +70,13 @@ describe('accountsViewState', () => {
})
it('round-trips a descending role/tuple column by its logical name', () => {
- expect(sortOrderToOrderBy({ column: 'csm', direction: 'desc' })).toEqual(['csm DESC'])
- expect(orderByToSortOrder(['csm DESC'])).toEqual({ column: 'csm', direction: 'desc' })
+ expect(sortOrderToOrderBy({ column: RELATIONSHIP_ALIAS, direction: 'desc' })).toEqual([
+ `${RELATIONSHIP_ALIAS} DESC`,
+ ])
+ expect(orderByToSortOrder([`${RELATIONSHIP_ALIAS} DESC`])).toEqual({
+ column: RELATIONSHIP_ALIAS,
+ direction: 'desc',
+ })
})
it('treats null / empty as no sort', () => {
@@ -99,8 +108,8 @@ describe('accountsViewState', () => {
describe('serializeAccountsView / deserializeAccountsView', () => {
it('round-trips a fully populated view', () => {
const state: AccountsViewState = {
- columns: ['name', 'csm'],
- sortOrder: { column: 'csm' as const, direction: 'desc' as const },
+ columns: ['name', RELATIONSHIP_COLUMN],
+ sortOrder: { column: RELATIONSHIP_ALIAS, direction: 'desc' as const },
filters: {
search: 'acme',
assignmentStatus: 'assigned',
@@ -149,8 +158,8 @@ describe('accountsViewState', () => {
},
}
const payload = serializeAccountsView(state)
- expect(payload.order_by).toEqual(['csm DESC'])
- expect(payload.columns).toEqual(['name', 'csm'])
+ expect(payload.order_by).toEqual([`${RELATIONSHIP_ALIAS} DESC`])
+ expect(payload.columns).toEqual(['name', RELATIONSHIP_COLUMN])
expect(payload.properties).toEqual({ tiles: state.tiles, column_display: state.columnDisplay })
expect(deserializeAccountsView(payload)).toEqual(state)
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
index f104ba93f0b9..03c7fb92e9a5 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
@@ -110,7 +110,7 @@ export function normalizeRoleFilter(value: unknown): RoleFilterValue {
return typeof value === 'number' ? [value] : []
}
-// Persist logical column names so views do not depend on typed query references.
+// Persist column aliases so saved views do not depend on typed query references.
export function sortOrderToOrderBy(sortOrder: AccountSortOrder): string[] {
if (!sortOrder) {
return []
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
index fabaaf86774d..53bb98f9a4b7 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
@@ -47,10 +47,13 @@ const accountId = '0190da51-0b0e-7000-8000-000000000001'
const buildView = (overrides: Partial<ColumnConfigurationApi> = {}): ColumnConfigurationApi => ({
id: 'view-1',
context_key: 'customer_analytics_accounts_columns',
- columns: ['name', 'csm'],
+ columns: [
+ 'name',
+ 'accounts.relationships.values.`11111111-2222-3333-4444-555555555555` AS rel_11111111222233334444555555555555',
+ ],
name: 'Enterprise',
filters: { search: 'example', assignmentStatus: 'assigned', assignedTo: [1] },
- order_by: ['csm DESC'],
+ order_by: ['rel_11111111222233334444555555555555 DESC'],
properties: { tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' } }] },
visibility: 'shared',
created_by: MOCK_DEFAULT_USER.id,
@@ -536,7 +539,7 @@ describe('accountsViewsLogic', () => {
expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)
})
- it('normalizes legacy saved columns without marking the view dirty', async () => {
+ it('normalizes saved tag columns without marking the view dirty', async () => {
const view = buildView({ columns: ['accounts.tags.account_id AS account_id', 'accounts.tags.names AS names'] })
mockList.mockResolvedValue(response([view]))
localStorage.setItem(scopedKey, JSON.stringify(view.id))
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 1ee7a3f7ceae..ca97e8bc39af 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -22,6 +22,12 @@ export const DEFAULT_TILES: AccountsOverviewTile[] = [
const overviewTilesTeamId = window.POSTHOG_APP_CONTEXT?.current_team?.id
export const ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX = `${overviewTilesTeamId}_customer_analytics_accounts_overview__`
+export const ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES: Record<string, string> = {
+ CSM: 'csm',
+ 'Account executive': 'account_executive',
+ 'Account owner': 'account_owner',
+}
+
// Canonical analytics event names for the accounts list. Every `posthog.capture`
// in this directory must reference these — a mistyped string silently forks a new
// event in PostHog and breaks reporting without any error. Keep in sync with the
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 37334e551e12..272dc77a6ea6 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1803,6 +1803,43 @@ export interface HogQLQueryModifiersApi {
webAnalyticsFirstPageviewFilters?: boolean | null
}
+export type AccountsTableCustomPropertyDisplayTypeApi =
+ (typeof AccountsTableCustomPropertyDisplayTypeApi)[keyof typeof AccountsTableCustomPropertyDisplayTypeApi]
+
+export const AccountsTableCustomPropertyDisplayTypeApi = {
+ Text: 'text',
+ Link: 'link',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+ Select: 'select',
+} as const
+
+export interface AccountsTableCustomPropertyOptionApi {
+ color: string
+ id?: string | null
+ label: string
+}
+
+export interface AccountsTableCustomPropertySourceApi {
+ id: string
+}
+
+export interface AccountsTableCustomPropertyDefinitionApi {
+ description?: string | null
+ display_type: AccountsTableCustomPropertyDisplayTypeApi
+ has_workflow_reference: boolean
+ id: string
+ is_big_number?: boolean | null
+ is_canonical: boolean
+ name: string
+ options?: AccountsTableCustomPropertyOptionApi[] | null
+ source?: AccountsTableCustomPropertySourceApi | null
+}
+
export interface ClickhouseQueryProgressApi {
active_cpu_time: number
bytes_read: number
@@ -1903,6 +1940,14 @@ export interface QueryStatusApi {
team_id: number
}
+export interface AccountsTableRelationshipDefinitionApi {
+ description?: string | null
+ id: string
+ is_controlled: boolean
+ is_single_holder?: boolean | null
+ name: string
+}
+
export interface ResolvedDateRangeResponseApi {
date_from: string
date_to: string
@@ -2000,6 +2045,17 @@ export interface AccessControlFilterWarningApi {
}
export interface AccountsTableQueryResponseApi {
+ columns?:
+ | (
+ | AccountsTableAccountFieldColumnApi
+ | AccountsTableTagsColumnApi
+ | AccountsTableNoteCountColumnApi
+ | AccountsTableRelationshipColumnApi
+ | AccountsTableCustomPropertyColumnApi
+ | AccountsTableCustomPropertyHistoryColumnApi
+ )[]
+ | null
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinitionApi[] | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore: boolean
@@ -2014,6 +2070,7 @@ export interface AccountsTableQueryResponseApi {
offset: number
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
+ relationshipDefinitions?: AccountsTableRelationshipDefinitionApi[] | null
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
/** The date range used for the query */
@@ -2089,6 +2146,8 @@ export interface AccountsTableQueryApi {
| AccountsTableCustomPropertyFilterApi
)[]
| null
+ /** Omit missing definitions and custom-property filters incompatible with their current types. */
+ ignoreMissingDefinitions?: boolean | null
/** Include churned accounts. Churned accounts are hidden by default. */
includeChurned?: boolean | null
/** Include ignored accounts. Ignored accounts are hidden by default. */
@@ -2105,6 +2164,7 @@ export interface AccountsTableQueryApi {
response?: AccountsTableQueryResponseApi | null
sort?: AccountsTableSortApi | null
tags?: QueryLogTagsApi | null
+ useDefaultColumns?: boolean | null
/** version of the node, used for schema migrations */
version?: number | null
}
@@ -4858,8 +4918,19 @@ export type AccountRelationshipDefinitionsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Return all definitions in one response when set to none.
+ */
+ pagination?: AccountRelationshipDefinitionsListPagination
}
+export type AccountRelationshipDefinitionsListPagination =
+ (typeof AccountRelationshipDefinitionsListPagination)[keyof typeof AccountRelationshipDefinitionsListPagination]
+
+export const AccountRelationshipDefinitionsListPagination = {
+ None: 'none',
+} as const
+
export type AccountTrackRulesRunsListParams = {
/**
* Number of results to return per page.
@@ -5031,8 +5102,19 @@ export type CustomPropertyDefinitionsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Return all definitions in one response when set to none.
+ */
+ pagination?: CustomPropertyDefinitionsListPagination
}
+export type CustomPropertyDefinitionsListPagination =
+ (typeof CustomPropertyDefinitionsListPagination)[keyof typeof CustomPropertyDefinitionsListPagination]
+
+export const CustomPropertyDefinitionsListPagination = {
+ None: 'none',
+} as const
+
export type CustomPropertyDefinitionsValuesRetrieveParams = {
/**
* Id of the custom property definition to suggest values for.
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
index 39d44c35c675..be9003fb7496 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
@@ -22,8 +22,10 @@ import { membersLogic } from 'scenes/organization/membersLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { AccessControlLevel, AccessControlResourceType, OrganizationMemberType } from '~/types'
-import { ROLE_KEY_BY_NAME } from 'products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic'
-import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
+import {
+ ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES,
+ AccountsEvents,
+} from 'products/customer_analytics/frontend/components/Accounts/constants'
import {
ACCOUNTS_METRICS_DATA_NODE_KEY,
ACCOUNTS_TABLE_DATA_NODE_KEY,
@@ -751,7 +753,11 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
posthog.capture(AccountsEvents.RoleAssigned, {
...(payload?.source === 'account_view'
? {}
- : { role: ROLE_KEY_BY_NAME[property.definition.name] ?? property.definition.name }),
+ : {
+ role:
+ ACCOUNT_RELATIONSHIP_ANALYTICS_ROLES[property.definition.name] ??
+ property.definition.name,
+ }),
is_assigned: memberIds.length > 0,
assigned_user_id: memberIds.length === 1 ? memberIds[0] : null,
source: payload?.source ?? 'account_sidebar',
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx
index 46dc5d4b3d6b..22f559919327 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx
@@ -25,6 +25,7 @@ import { TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { humanFriendlyDiff } from 'lib/utils/durations'
+import type { AccountsTableCustomPropertyDefinition } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator, type AnyPropertyFilter } from '~/types'
import { AccountNameCell } from 'products/customer_analytics/frontend/components/Accounts/AccountNameCell'
@@ -41,7 +42,6 @@ import type {
AccountTrackRuleGroupApi,
AccountTrackRuleRunViewApi,
AccountTrackRuleSampleApi,
- CustomPropertyDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountTrackRulesLogic, type accountTrackRulesLogicValues } from './accountTrackRulesLogic'
@@ -97,7 +97,7 @@ export function accountFiltersToRuleGroup(filters: AccountFilter[]): AccountTrac
export function ruleGroupToAccountFilters(
group: AccountTrackRuleGroupApi,
- definitionsById: Record<string, CustomPropertyDefinitionApi>
+ definitionsById: Record<string, AccountsTableCustomPropertyDefinition>
): AccountFilter[] {
return group.conditions.map((condition) => {
const isNative = condition.field.kind === 'account_field'
@@ -354,12 +354,12 @@ type PreviewSampleKind = 'included' | 'excluded'
type PreviewRuleColumn = {
key: string
label: string
- definition?: CustomPropertyDefinitionApi
+ definition?: AccountsTableCustomPropertyDefinition
}
export function getPreviewRuleColumns(
groups: readonly AccountTrackRuleGroupApi[],
- definitionsById: Record<string, CustomPropertyDefinitionApi>
+ definitionsById: Record<string, AccountsTableCustomPropertyDefinition>
): PreviewRuleColumn[] {
const columns: PreviewRuleColumn[] = []
const keys = new Set<string>()
@@ -397,7 +397,7 @@ function PreviewRuleValue({
definition,
}: {
value: unknown
- definition?: CustomPropertyDefinitionApi
+ definition?: AccountsTableCustomPropertyDefinition
}): JSX.Element {
if (value === null || value === undefined || value === '') {
return <span className="text-muted">—</span>
@@ -437,7 +437,7 @@ function PreviewResult({
preview: NonNullable<accountTrackRulesLogicValues['previewResponse']>
current: boolean
ruleGroups: readonly AccountTrackRuleGroupApi[]
- definitionsById: Record<string, CustomPropertyDefinitionApi>
+ definitionsById: Record<string, AccountsTableCustomPropertyDefinition>
}): JSX.Element {
const [sampleKind, setSampleKind] = useState<PreviewSampleKind>('included')
const samples = sampleKind === 'included' ? preview.tracked_samples : preview.ignored_samples
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts
index 6ff188d4dcfb..7a6c30cc2dab 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts
@@ -7,6 +7,7 @@ import { ApiError } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
+import { accountsColumnConfigLogic } from 'products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic'
import {
accountTrackRulesList,
accountTrackRulesPreviewCreate,
@@ -60,6 +61,7 @@ export interface accountTrackRulesLogicValues {
}
export interface accountTrackRulesLogicActions {
+ ensureDefinitionsLoaded: () => { value: true }
loadConfig: () => { value: true }
loadConfigSuccess: (config: AccountTrackRulesConfigApi | null) => { config: AccountTrackRulesConfigApi | null }
loadConfigFailure: (error: unknown) => { error: unknown }
@@ -93,6 +95,7 @@ export const accountTrackRulesLogic = kea<accountTrackRulesLogicType>([
path(['products', 'customerAnalytics', 'configuration', 'accountTrackRulesLogic']),
connect(() => ({
+ actions: [accountsColumnConfigLogic, ['ensureDefinitionsLoaded']],
values: [teamLogic, ['currentTeamId']],
})),
@@ -363,6 +366,7 @@ export const accountTrackRulesLogic = kea<accountTrackRulesLogicType>([
})),
afterMount(({ actions }) => {
+ actions.ensureDefinitionsLoaded()
actions.loadConfig()
actions.loadRuns()
}),
diff --git a/products/customer_analytics/frontend/utils.ts b/products/customer_analytics/frontend/utils.ts
index ed1dc1698730..6ee4d886e700 100644
--- a/products/customer_analytics/frontend/utils.ts
+++ b/products/customer_analytics/frontend/utils.ts
@@ -12,3 +12,18 @@ export const buildDashboardItemId = (uniqueKey: string): InsightLogicProps['dash
export function isPageviewWithoutFilters(event: SeriesNode): boolean {
return isEventsNode(event) && event.event === '$pageview' && (!event.properties || event.properties.length === 0)
}
+
+interface PaginatedPage<T> {
+ results: T[]
+ next?: string | null
+}
+
+export async function loadAllPages<T>(loadPage: (offset: number) => Promise<PaginatedPage<T>>): Promise<T[]> {
+ const results: T[] = []
+ let page: PaginatedPage<T>
+ do {
+ page = await loadPage(results.length)
+ results.push(...page.results)
+ } while (page.next && page.results.length > 0)
+ return results
+}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 12fbbd1270a7..ca2aeed0ad7b 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -5956,6 +5956,112 @@ export interface Response19Api {
warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
}
+export type AccountsTableAccountFieldApi =
+ (typeof AccountsTableAccountFieldApi)[keyof typeof AccountsTableAccountFieldApi]
+
+export const AccountsTableAccountFieldApi = {
+ Name: 'name',
+ ExternalId: 'external_id',
+ CreatedAt: 'created_at',
+ UpdatedAt: 'updated_at',
+ ChurnedAt: 'churned_at',
+ IgnoredAt: 'ignored_at',
+ StripeCustomerId: 'stripe_customer_id',
+ HubspotDealId: 'hubspot_deal_id',
+ BillingId: 'billing_id',
+ SfdcId: 'sfdc_id',
+ ZendeskId: 'zendesk_id',
+} as const
+
+export interface AccountsTableAccountFieldColumnApi {
+ field: AccountsTableAccountFieldApi
+ kind?: 'account_field'
+}
+
+export const AccountsTableTagsColumnApiValue = {
+ kind: 'tags',
+} as const
+export type AccountsTableTagsColumnApi = typeof AccountsTableTagsColumnApiValue
+
+export const AccountsTableNoteCountColumnApiValue = {
+ kind: 'note_count',
+} as const
+export type AccountsTableNoteCountColumnApi = typeof AccountsTableNoteCountColumnApiValue
+
+export interface AccountsTableRelationshipColumnApi {
+ /** Team-scoped relationship definition to return for each account. */
+ definitionId: string
+ kind?: 'relationship'
+}
+
+export interface AccountsTableCustomPropertyColumnApi {
+ /** Team-scoped custom property definition to return for each account. */
+ definitionId: string
+ kind?: 'custom_property'
+}
+
+export type WindowDaysApi = (typeof WindowDaysApi)[keyof typeof WindowDaysApi]
+
+export const WindowDaysApi = {
+ Number7: 7,
+ Number14: 14,
+ Number30: 30,
+ Number90: 90,
+} as const
+
+export interface AccountsTableCustomPropertyHistoryColumnApi {
+ /** Team-scoped numeric custom property definition whose write history should be returned. */
+ definitionId: string
+ kind?: 'custom_property_history'
+ /** Number of days of history to return. The current value is included even when it is older. */
+ windowDays: WindowDaysApi
+}
+
+export type AccountsTableCustomPropertyDisplayTypeApi =
+ (typeof AccountsTableCustomPropertyDisplayTypeApi)[keyof typeof AccountsTableCustomPropertyDisplayTypeApi]
+
+export const AccountsTableCustomPropertyDisplayTypeApi = {
+ Text: 'text',
+ Link: 'link',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+ Select: 'select',
+} as const
+
+export interface AccountsTableCustomPropertyOptionApi {
+ color: string
+ id?: string | null
+ label: string
+}
+
+export interface AccountsTableCustomPropertySourceApi {
+ id: string
+}
+
+export interface AccountsTableCustomPropertyDefinitionApi {
+ description?: string | null
+ display_type: AccountsTableCustomPropertyDisplayTypeApi
+ has_workflow_reference: boolean
+ id: string
+ is_big_number?: boolean | null
+ is_canonical: boolean
+ name: string
+ options?: AccountsTableCustomPropertyOptionApi[] | null
+ source?: AccountsTableCustomPropertySourceApi | null
+}
+
+export interface AccountsTableRelationshipDefinitionApi {
+ description?: string | null
+ id: string
+ is_controlled: boolean
+ is_single_holder?: boolean | null
+ name: string
+}
+
export interface AccountsTableCustomPropertyHistoryPointApi {
timestamp: string
value: number
@@ -6002,6 +6108,17 @@ export interface AccountsTableRowApi {
}
export interface Response20Api {
+ columns?:
+ | (
+ | AccountsTableAccountFieldColumnApi
+ | AccountsTableTagsColumnApi
+ | AccountsTableNoteCountColumnApi
+ | AccountsTableRelationshipColumnApi
+ | AccountsTableCustomPropertyColumnApi
+ | AccountsTableCustomPropertyHistoryColumnApi
+ )[]
+ | null
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinitionApi[] | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore: boolean
@@ -6016,6 +6133,7 @@ export interface Response20Api {
offset: number
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
+ relationshipDefinitions?: AccountsTableRelationshipDefinitionApi[] | null
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
/** The date range used for the query */
@@ -8659,67 +8777,6 @@ export interface AccountsQueryApi {
version?: number | null
}
-export type AccountsTableAccountFieldApi =
- (typeof AccountsTableAccountFieldApi)[keyof typeof AccountsTableAccountFieldApi]
-
-export const AccountsTableAccountFieldApi = {
- Name: 'name',
- ExternalId: 'external_id',
- CreatedAt: 'created_at',
- UpdatedAt: 'updated_at',
- ChurnedAt: 'churned_at',
- IgnoredAt: 'ignored_at',
- StripeCustomerId: 'stripe_customer_id',
- HubspotDealId: 'hubspot_deal_id',
- BillingId: 'billing_id',
- SfdcId: 'sfdc_id',
- ZendeskId: 'zendesk_id',
-} as const
-
-export interface AccountsTableAccountFieldColumnApi {
- field: AccountsTableAccountFieldApi
- kind?: 'account_field'
-}
-
-export const AccountsTableTagsColumnApiValue = {
- kind: 'tags',
-} as const
-export type AccountsTableTagsColumnApi = typeof AccountsTableTagsColumnApiValue
-
-export const AccountsTableNoteCountColumnApiValue = {
- kind: 'note_count',
-} as const
-export type AccountsTableNoteCountColumnApi = typeof AccountsTableNoteCountColumnApiValue
-
-export interface AccountsTableRelationshipColumnApi {
- /** Team-scoped relationship definition to return for each account. */
- definitionId: string
- kind?: 'relationship'
-}
-
-export interface AccountsTableCustomPropertyColumnApi {
- /** Team-scoped custom property definition to return for each account. */
- definitionId: string
- kind?: 'custom_property'
-}
-
-export type WindowDaysApi = (typeof WindowDaysApi)[keyof typeof WindowDaysApi]
-
-export const WindowDaysApi = {
- Number7: 7,
- Number14: 14,
- Number30: 30,
- Number90: 90,
-} as const
-
-export interface AccountsTableCustomPropertyHistoryColumnApi {
- /** Team-scoped numeric custom property definition whose write history should be returned. */
- definitionId: string
- kind?: 'custom_property_history'
- /** Number of days of history to return. The current value is included even when it is older. */
- windowDays: WindowDaysApi
-}
-
export type AccountsTableAccountFieldOperatorApi =
(typeof AccountsTableAccountFieldOperatorApi)[keyof typeof AccountsTableAccountFieldOperatorApi]
@@ -8862,6 +8919,17 @@ export interface AccountsTableCountThresholdMetricApi {
}
export interface AccountsTableQueryResponseApi {
+ columns?:
+ | (
+ | AccountsTableAccountFieldColumnApi
+ | AccountsTableTagsColumnApi
+ | AccountsTableNoteCountColumnApi
+ | AccountsTableRelationshipColumnApi
+ | AccountsTableCustomPropertyColumnApi
+ | AccountsTableCustomPropertyHistoryColumnApi
+ )[]
+ | null
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinitionApi[] | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore: boolean
@@ -8876,6 +8944,7 @@ export interface AccountsTableQueryResponseApi {
offset: number
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
+ relationshipDefinitions?: AccountsTableRelationshipDefinitionApi[] | null
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
/** The date range used for the query */
@@ -8940,6 +9009,8 @@ export interface AccountsTableQueryApi {
| AccountsTableCustomPropertyFilterApi
)[]
| null
+ /** Omit missing definitions and custom-property filters incompatible with their current types. */
+ ignoreMissingDefinitions?: boolean | null
/** Include churned accounts. Churned accounts are hidden by default. */
includeChurned?: boolean | null
/** Include ignored accounts. Ignored accounts are hidden by default. */
@@ -8956,6 +9027,7 @@ export interface AccountsTableQueryApi {
response?: AccountsTableQueryResponseApi | null
sort?: AccountsTableSortApi | null
tags?: QueryLogTagsApi | null
+ useDefaultColumns?: boolean | null
/** version of the node, used for schema migrations */
version?: number | null
}
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 1868977b28a4..bd9eee6a6413 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -545,6 +545,33 @@ export namespace Schemas {
operator: AccountsTableThresholdOperator;
value: number;
};
+ export type AccountsTableCustomPropertyDisplayType =
+ | "text"
+ | "link"
+ | "number"
+ | "currency"
+ | "percent"
+ | "date"
+ | "datetime"
+ | "boolean"
+ | "select";
+ export type AccountsTableCustomPropertyOption = {
+ color: string;
+ id?: (string | null) | undefined;
+ label: string;
+ };
+ export type AccountsTableCustomPropertySource = { id: string };
+ export type AccountsTableCustomPropertyDefinition = {
+ description?: (string | null) | undefined;
+ display_type: AccountsTableCustomPropertyDisplayType;
+ has_workflow_reference: boolean;
+ id: string;
+ is_big_number?: (boolean | null) | undefined;
+ is_canonical: boolean;
+ name: string;
+ options?: (Array<AccountsTableCustomPropertyOption> | null) | undefined;
+ source?: (AccountsTableCustomPropertySource | null) | undefined;
+ };
export type AccountsTableCustomPropertyOperator =
| "exact"
| "is_not"
@@ -615,6 +642,13 @@ export namespace Schemas {
tagNames: Array<string>;
};
export type AccountsTableUnassignedFilter = Partial<{ kind: string }>;
+ export type AccountsTableRelationshipDefinition = {
+ description?: (string | null) | undefined;
+ id: string;
+ is_controlled: boolean;
+ is_single_holder?: (boolean | null) | undefined;
+ name: string;
+ };
export type AccountsTableRow = {
/**
* Requested direct Account fields, keyed by their typed field reference.
@@ -643,6 +677,19 @@ export namespace Schemas {
tags?: (Array<string> | null) | undefined;
};
export type AccountsTableQueryResponse = {
+ columns?:
+ | (Array<
+ | AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ > | null)
+ | undefined;
+ customPropertyDefinitions?:
+ | (Array<AccountsTableCustomPropertyDefinition> | null)
+ | undefined;
error?: (string | null) | undefined;
hasMore: boolean;
hogql?: (string | null) | undefined;
@@ -652,6 +699,9 @@ export namespace Schemas {
modifiers?: (HogQLQueryModifiers | null) | undefined;
offset: number;
query_status?: (QueryStatus | null) | undefined;
+ relationshipDefinitions?:
+ | (Array<AccountsTableRelationshipDefinition> | null)
+ | undefined;
resolved_compare_date_range?:
| (ResolvedDateRangeResponse | null)
| undefined;
@@ -714,6 +764,7 @@ export namespace Schemas {
| AccountsTableCustomPropertyFilter
> | null)
| undefined;
+ ignoreMissingDefinitions?: (boolean | null) | undefined;
includeChurned?: (boolean | null) | undefined;
includeIgnored?: (boolean | null) | undefined;
kind?: string | undefined;
@@ -730,6 +781,7 @@ export namespace Schemas {
response?: (AccountsTableQueryResponse | null) | undefined;
sort?: (AccountsTableSort | null) | undefined;
tags?: (QueryLogTags | null) | undefined;
+ useDefaultColumns?: (boolean | null) | undefined;
version?: (number | null) | undefined;
};
/**
@@ -7428,6 +7480,19 @@ export namespace Schemas {
| undefined;
};
export type Response20 = {
+ columns?:
+ | (Array<
+ | AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+ > | null)
+ | undefined;
+ customPropertyDefinitions?:
+ | (Array<AccountsTableCustomPropertyDefinition> | null)
+ | undefined;
error?: (string | null) | undefined;
hasMore: boolean;
hogql?: (string | null) | undefined;
@@ -7437,6 +7502,9 @@ export namespace Schemas {
modifiers?: (HogQLQueryModifiers | null) | undefined;
offset: number;
query_status?: (QueryStatus | null) | undefined;
+ relationshipDefinitions?:
+ | (Array<AccountsTableRelationshipDefinition> | null)
+ | undefined;
resolved_compare_date_range?:
| (ResolvedDateRangeResponse | null)
| undefined;
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index f6170dc4f378..baa9e757933d 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -4811,6 +4811,112 @@ export interface Response19Api {
warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
}
+export type AccountsTableAccountFieldApi =
+ (typeof AccountsTableAccountFieldApi)[keyof typeof AccountsTableAccountFieldApi]
+
+export const AccountsTableAccountFieldApi = {
+ Name: 'name',
+ ExternalId: 'external_id',
+ CreatedAt: 'created_at',
+ UpdatedAt: 'updated_at',
+ ChurnedAt: 'churned_at',
+ IgnoredAt: 'ignored_at',
+ StripeCustomerId: 'stripe_customer_id',
+ HubspotDealId: 'hubspot_deal_id',
+ BillingId: 'billing_id',
+ SfdcId: 'sfdc_id',
+ ZendeskId: 'zendesk_id',
+} as const
+
+export interface AccountsTableAccountFieldColumnApi {
+ field: AccountsTableAccountFieldApi
+ kind?: 'account_field'
+}
+
+export const AccountsTableTagsColumnApiValue = {
+ kind: 'tags',
+} as const
+export type AccountsTableTagsColumnApi = typeof AccountsTableTagsColumnApiValue
+
+export const AccountsTableNoteCountColumnApiValue = {
+ kind: 'note_count',
+} as const
+export type AccountsTableNoteCountColumnApi = typeof AccountsTableNoteCountColumnApiValue
+
+export interface AccountsTableRelationshipColumnApi {
+ /** Team-scoped relationship definition to return for each account. */
+ definitionId: string
+ kind?: 'relationship'
+}
+
+export interface AccountsTableCustomPropertyColumnApi {
+ /** Team-scoped custom property definition to return for each account. */
+ definitionId: string
+ kind?: 'custom_property'
+}
+
+export type WindowDaysApi = (typeof WindowDaysApi)[keyof typeof WindowDaysApi]
+
+export const WindowDaysApi = {
+ Number7: 7,
+ Number14: 14,
+ Number30: 30,
+ Number90: 90,
+} as const
+
+export interface AccountsTableCustomPropertyHistoryColumnApi {
+ /** Team-scoped numeric custom property definition whose write history should be returned. */
+ definitionId: string
+ kind?: 'custom_property_history'
+ /** Number of days of history to return. The current value is included even when it is older. */
+ windowDays: WindowDaysApi
+}
+
+export type AccountsTableCustomPropertyDisplayTypeApi =
+ (typeof AccountsTableCustomPropertyDisplayTypeApi)[keyof typeof AccountsTableCustomPropertyDisplayTypeApi]
+
+export const AccountsTableCustomPropertyDisplayTypeApi = {
+ Text: 'text',
+ Link: 'link',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+ Select: 'select',
+} as const
+
+export interface AccountsTableCustomPropertyOptionApi {
+ color: string
+ id?: string | null
+ label: string
+}
+
+export interface AccountsTableCustomPropertySourceApi {
+ id: string
+}
+
+export interface AccountsTableCustomPropertyDefinitionApi {
+ description?: string | null
+ display_type: AccountsTableCustomPropertyDisplayTypeApi
+ has_workflow_reference: boolean
+ id: string
+ is_big_number?: boolean | null
+ is_canonical: boolean
+ name: string
+ options?: AccountsTableCustomPropertyOptionApi[] | null
+ source?: AccountsTableCustomPropertySourceApi | null
+}
+
+export interface AccountsTableRelationshipDefinitionApi {
+ description?: string | null
+ id: string
+ is_controlled: boolean
+ is_single_holder?: boolean | null
+ name: string
+}
+
export interface AccountsTableCustomPropertyHistoryPointApi {
timestamp: string
value: number
@@ -4857,6 +4963,17 @@ export interface AccountsTableRowApi {
}
export interface Response20Api {
+ columns?:
+ | (
+ | AccountsTableAccountFieldColumnApi
+ | AccountsTableTagsColumnApi
+ | AccountsTableNoteCountColumnApi
+ | AccountsTableRelationshipColumnApi
+ | AccountsTableCustomPropertyColumnApi
+ | AccountsTableCustomPropertyHistoryColumnApi
+ )[]
+ | null
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinitionApi[] | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore: boolean
@@ -4871,6 +4988,7 @@ export interface Response20Api {
offset: number
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
+ relationshipDefinitions?: AccountsTableRelationshipDefinitionApi[] | null
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
/** The date range used for the query */
@@ -7525,67 +7643,6 @@ export interface AccountsQueryApi {
version?: number | null
}
-export type AccountsTableAccountFieldApi =
- (typeof AccountsTableAccountFieldApi)[keyof typeof AccountsTableAccountFieldApi]
-
-export const AccountsTableAccountFieldApi = {
- Name: 'name',
- ExternalId: 'external_id',
- CreatedAt: 'created_at',
- UpdatedAt: 'updated_at',
- ChurnedAt: 'churned_at',
- IgnoredAt: 'ignored_at',
- StripeCustomerId: 'stripe_customer_id',
- HubspotDealId: 'hubspot_deal_id',
- BillingId: 'billing_id',
- SfdcId: 'sfdc_id',
- ZendeskId: 'zendesk_id',
-} as const
-
-export interface AccountsTableAccountFieldColumnApi {
- field: AccountsTableAccountFieldApi
- kind?: 'account_field'
-}
-
-export const AccountsTableTagsColumnApiValue = {
- kind: 'tags',
-} as const
-export type AccountsTableTagsColumnApi = typeof AccountsTableTagsColumnApiValue
-
-export const AccountsTableNoteCountColumnApiValue = {
- kind: 'note_count',
-} as const
-export type AccountsTableNoteCountColumnApi = typeof AccountsTableNoteCountColumnApiValue
-
-export interface AccountsTableRelationshipColumnApi {
- /** Team-scoped relationship definition to return for each account. */
- definitionId: string
- kind?: 'relationship'
-}
-
-export interface AccountsTableCustomPropertyColumnApi {
- /** Team-scoped custom property definition to return for each account. */
- definitionId: string
- kind?: 'custom_property'
-}
-
-export type WindowDaysApi = (typeof WindowDaysApi)[keyof typeof WindowDaysApi]
-
-export const WindowDaysApi = {
- Number7: 7,
- Number14: 14,
- Number30: 30,
- Number90: 90,
-} as const
-
-export interface AccountsTableCustomPropertyHistoryColumnApi {
- /** Team-scoped numeric custom property definition whose write history should be returned. */
- definitionId: string
- kind?: 'custom_property_history'
- /** Number of days of history to return. The current value is included even when it is older. */
- windowDays: WindowDaysApi
-}
-
export type AccountsTableAccountFieldOperatorApi =
(typeof AccountsTableAccountFieldOperatorApi)[keyof typeof AccountsTableAccountFieldOperatorApi]
@@ -7728,6 +7785,17 @@ export interface AccountsTableCountThresholdMetricApi {
}
export interface AccountsTableQueryResponseApi {
+ columns?:
+ | (
+ | AccountsTableAccountFieldColumnApi
+ | AccountsTableTagsColumnApi
+ | AccountsTableNoteCountColumnApi
+ | AccountsTableRelationshipColumnApi
+ | AccountsTableCustomPropertyColumnApi
+ | AccountsTableCustomPropertyHistoryColumnApi
+ )[]
+ | null
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinitionApi[] | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore: boolean
@@ -7742,6 +7810,7 @@ export interface AccountsTableQueryResponseApi {
offset: number
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
+ relationshipDefinitions?: AccountsTableRelationshipDefinitionApi[] | null
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
/** The date range used for the query */
@@ -7806,6 +7875,8 @@ export interface AccountsTableQueryApi {
| AccountsTableCustomPropertyFilterApi
)[]
| null
+ /** Omit missing definitions and custom-property filters incompatible with their current types. */
+ ignoreMissingDefinitions?: boolean | null
/** Include churned accounts. Churned accounts are hidden by default. */
includeChurned?: boolean | null
/** Include ignored accounts. Ignored accounts are hidden by default. */
@@ -7822,6 +7893,7 @@ export interface AccountsTableQueryApi {
response?: AccountsTableQueryResponseApi | null
sort?: AccountsTableSortApi | null
tags?: QueryLogTagsApi | null
+ useDefaultColumns?: boolean | null
/** version of the node, used for schema migrations */
version?: number | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e88c9d5d98c7..303db48b942d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3371,6 +3371,43 @@ export namespace Schemas {
value: number;
}
+ export type AccountsTableCustomPropertyDisplayType = typeof AccountsTableCustomPropertyDisplayType[keyof typeof AccountsTableCustomPropertyDisplayType];
+
+
+ export const AccountsTableCustomPropertyDisplayType = {
+ Text: 'text',
+ Link: 'link',
+ Number: 'number',
+ Currency: 'currency',
+ Percent: 'percent',
+ Date: 'date',
+ Datetime: 'datetime',
+ Boolean: 'boolean',
+ Select: 'select',
+ } as const;
+
+ export interface AccountsTableCustomPropertyOption {
+ color: string;
+ id?: string | null;
+ label: string;
+ }
+
+ export interface AccountsTableCustomPropertySource {
+ id: string;
+ }
+
+ export interface AccountsTableCustomPropertyDefinition {
+ description?: string | null;
+ display_type: AccountsTableCustomPropertyDisplayType;
+ has_workflow_reference: boolean;
+ id: string;
+ is_big_number?: boolean | null;
+ is_canonical: boolean;
+ name: string;
+ options?: AccountsTableCustomPropertyOption[] | null;
+ source?: AccountsTableCustomPropertySource | null;
+ }
+
export type AccountsTableCustomPropertyOperator = typeof AccountsTableCustomPropertyOperator[keyof typeof AccountsTableCustomPropertyOperator];
@@ -3472,6 +3509,14 @@ export namespace Schemas {
} as const;
export type AccountsTableUnassignedFilter = typeof AccountsTableUnassignedFilterValue;
+ export interface AccountsTableRelationshipDefinition {
+ description?: string | null;
+ id: string;
+ is_controlled: boolean;
+ is_single_holder?: boolean | null;
+ name: string;
+ }
+
/**
* Requested direct Account fields, keyed by their typed field reference.
*/
@@ -3513,6 +3558,8 @@ export namespace Schemas {
}
export interface AccountsTableQueryResponse {
+ columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -3527,6 +3574,7 @@ export namespace Schemas {
offset: number;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
+ relationshipDefinitions?: AccountsTableRelationshipDefinition[] | null;
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
@@ -3561,6 +3609,8 @@ export namespace Schemas {
filterGroups?: ((AccountsTableAccountFieldFilter | AccountsTableRelationshipFilter | AccountsTableCustomPropertyFilter)[])[] | null;
/** Filters are combined with AND. Values within tag and assignment filters use OR. */
filters?: (AccountsTableSearchFilter | AccountsTableTagsFilter | AccountsTableAssignedToFilter | AccountsTableAssignedFilter | AccountsTableUnassignedFilter | AccountsTableRelationshipFilter | AccountsTableAccountIdFilter | AccountsTableAccountFieldFilter | AccountsTableCustomPropertyFilter)[] | null;
+ /** Omit missing definitions and custom-property filters incompatible with their current types. */
+ ignoreMissingDefinitions?: boolean | null;
/** Include churned accounts. Churned accounts are hidden by default. */
includeChurned?: boolean | null;
/** Include ignored accounts. Ignored accounts are hidden by default. */
@@ -3575,6 +3625,7 @@ export namespace Schemas {
response?: AccountsTableQueryResponse | null;
sort?: AccountsTableSort | null;
tags?: QueryLogTags | null;
+ useDefaultColumns?: boolean | null;
/** version of the node, used for schema migrations */
version?: number | null;
}
@@ -9105,6 +9156,8 @@ export namespace Schemas {
}
export interface Response20 {
+ columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -9119,6 +9172,7 @@ export namespace Schemas {
offset: number;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
+ relationshipDefinitions?: AccountsTableRelationshipDefinition[] | null;
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
@@ -101484,6 +101538,8 @@ export namespace Schemas {
}
export interface QueryResponseAlternative59 {
+ columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -101498,6 +101554,7 @@ export namespace Schemas {
offset: number;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
+ relationshipDefinitions?: AccountsTableRelationshipDefinition[] | null;
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
@@ -102114,6 +102171,8 @@ export namespace Schemas {
}
export interface QueryResponseAlternative89 {
+ columns?: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[] | null;
+ customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore: boolean;
@@ -102128,6 +102187,7 @@ export namespace Schemas {
offset: number;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
+ relationshipDefinitions?: AccountsTableRelationshipDefinition[] | null;
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
@@ -129170,8 +129230,19 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Return all definitions in one response when set to none.
+ */
+ pagination?: AccountRelationshipDefinitionsListPagination;
};
+ export type AccountRelationshipDefinitionsListPagination = typeof AccountRelationshipDefinitionsListPagination[keyof typeof AccountRelationshipDefinitionsListPagination];
+
+
+ export const AccountRelationshipDefinitionsListPagination = {
+ None: 'none',
+ } as const;
+
export type AccountTrackRulesRunsListParams = {
/**
* Number of results to return per page.
@@ -131802,8 +131873,19 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Return all definitions in one response when set to none.
+ */
+ pagination?: CustomPropertyDefinitionsListPagination;
};
+ export type CustomPropertyDefinitionsListPagination = typeof CustomPropertyDefinitionsListPagination[keyof typeof CustomPropertyDefinitionsListPagination];
+
+
+ export const CustomPropertyDefinitionsListPagination = {
+ None: 'none',
+ } as const;
+
export type CustomPropertyDefinitionsValuesRetrieveParams = {
/**
* Id of the custom property definition to suggest values for.
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 4d9f646c5786..387d183a02f7 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -19,6 +19,7 @@ export const AccountRelationshipDefinitionsListParams = () => zod.object({
export const AccountRelationshipDefinitionsListQueryParams = () => zod.object({
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ pagination: zod.enum(['none']).optional().describe('Return all definitions in one response when set to none.'),
})
export const AccountRelationshipDefinitionsCreateParams = () => zod.object({
@@ -564,6 +565,7 @@ export const CustomPropertyDefinitionsListParams = () => zod.object({
export const CustomPropertyDefinitionsListQueryParams = () => zod.object({
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ pagination: zod.enum(['none']).optional().describe('Return all definitions in one response when set to none.'),
})
export const CustomPropertyDefinitionsCreateParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 9cfea33be911..1b0dcdae577a 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -98,6 +98,7 @@ const accountRelationshipDefinitionsList = (): ToolBase<
query: {
limit: params.limit,
offset: params.offset,
+ pagination: params.pagination,
},
})
const filtered = {
@@ -869,6 +870,7 @@ const customPropertyDefinitionsList = (): ToolBase<
query: {
limit: params.limit,
offset: params.offset,
+ pagination: params.pagination,
},
})
const filtered = {