: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cohorts): prefill only supported recent person filters (#118558)
Paul D'Ambra91abbbb43781
diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsxindex 7566f204e743..0295deefa61f 100644--- a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx@@ -38,6 +38,11 @@ export function PropertyFilterDatePicker({const [includeTimeInFilter, setIncludeTimeInFilter] = useState(!!value && !valueIsYYYYMMDD)const [dateFormat, setDateFormat] = useState(valueIsYYYYMMDD ? onlyDateFormat : dateAndTimeFormat)+ useEffect(() => {+ setDatePickerValue(dayJSMightParse(value) ? dayjs(value) : undefined)+ setIncludeTimeInFilter(!!value && !valueIsYYYYMMDD)+ }, [value, valueIsYYYYMMDD])+useEffect(() => {setDateFormat(includeTimeInFilter ? dateAndTimeFormat : onlyDateFormat)}, [includeTimeInFilter])diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsxindex c0e36d44e86f..f972d49eea4b 100644--- a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx@@ -312,6 +312,26 @@ describe('PropertyValue', () => {})})+ it('shows a new date when the date value changes after mount', () => {+ const editor = (value: string): JSX.Element => (+ <Provider>+ <PropertyValue+ propertyKey="signup_date"+ type={PropertyFilterType.Person}+ operator={PropertyOperator.IsDateBefore}+ onSet={jest.fn()}+ value={value}+ />+ </Provider>+ )++ const { rerender } = render(editor('2000-01-01'))+ expect(screen.getByTestId('filter-date-picker')).toHaveTextContent('2000-01-01')++ rerender(editor('2010-06-15'))+ expect(screen.getByTestId('filter-date-picker')).toHaveTextContent('2010-06-15')+ })+it('keeps the suggested values when it mounts with values already loaded and a refresh changes them', async () => {const editor = (<Provider>diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex 15603ad796cf..2663f76c2de1 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -9,6 +9,7 @@ import {listeners,path,props,+ propsChanged,reducers,selectors,} from 'kea'@@ -278,6 +279,7 @@ export interface infiniteListLogicValues {contextFilteredPinnedItems: TaxonomicDefinitionTypes[]contextFilteredRecentItems: TaxonomicDefinitionTypes[]dedupedTopMatches: (SkeletonItem | TaxonomicDefinitionTypes)[]+ excludedOperators: ExcludedOperators | undefinedexcludedProperties: string[] | undefinedexcludedPropertiesWithHiddenEvents: ExcludedProperties | undefinedexpandedCount: number@@ -501,6 +503,9 @@ export interface infiniteListLogicActions {selectSelected: () => {value: true}+ setExcludedOperators: (excludedOperators: ExcludedOperators | undefined) => {+ excludedOperators: ExcludedOperators | undefined+ }setHasMore: (hasMore: boolean) => {hasMore: boolean}@@ -576,8 +581,8 @@ export interface infiniteListLogicMeta {contextFilteredRecentItems: (recentFilterItems: TaxonomicDefinitionTypes[],taxonomicGroupTypes: TaxonomicFilterGroupType[],- arg: ExcludedOperators | undefined,- arg2: SelectingKeyOnly | undefined,+ excludedOperators: ExcludedOperators | undefined,+ arg: SelectingKeyOnly | undefined,excludedPropertiesWithHiddenEvents:| import('lib/components/TaxonomicFilter/types').TaxonomicFilterGroupValueMap| undefined@@ -880,6 +885,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([applyInitialPinnedRow: (rowIndex: number) => ({ rowIndex }),reconcilePinnedRowState: true,setLimit: (limit: number) => ({ limit }),+ setExcludedOperators: (excludedOperators: ExcludedOperators | undefined) => ({ excludedOperators }),onRowsRendered: (rowInfo: RowInfo) => ({ rowInfo }),loadRemoteItems: (options: LoaderOptions) => options,updateRemoteItem: (item: TaxonomicDefinitionTypes) => ({ item }),@@ -1139,6 +1145,14 @@ export const infiniteListLogic = kea<infiniteListLogicType>([setLimit: (_, { limit }) => limit,},],+ // Values are cached per store state, so a new rule passed only as a prop would leave+ // the Recent list stale until some unrelated action ran.+ excludedOperators: [+ props.excludedOperators,+ {+ setExcludedOperators: (_, { excludedOperators }) => excludedOperators,+ },+ ],startIndex: [0, { onRowsRendered: (_, { rowInfo: { startIndex } }) => startIndex }],stopIndex: [0, { onRowsRendered: (_, { rowInfo: { stopIndex } }) => stopIndex }],isExpanded: [false, { expand: () => true }],@@ -1211,7 +1225,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([(s) => [s.recentFilterItems,s.taxonomicGroupTypes,- (_, props: InfiniteListLogicProps) => props.excludedOperators,+ s.excludedOperators,(_, props: InfiniteListLogicProps) => props.selectingKeyOnly,s.excludedPropertiesWithHiddenEvents,],@@ -2225,6 +2239,11 @@ export const infiniteListLogic = kea<infiniteListLogicType>([typeof index === 'number' && index >= startIndex && index <= stopIndex,],}),+ propsChanged(({ actions, props }, oldProps) => {+ if (props.excludedOperators !== oldProps.excludedOperators) {+ actions.setExcludedOperators(props.excludedOperators)+ }+ }),listeners(({ values, actions, props, cache }) => ({reconcilePinnedRowState: () => {let nextPinnedRowIndex = values.pinnedRowIndexdiff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.tsindex a55c95d5889c..b52ac8e13220 100644--- a/frontend/src/lib/components/TaxonomicFilter/types.ts+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts@@ -10,6 +10,7 @@ import { AnyDataNode, DatabaseSchemaField, DatabaseSerializedFieldType } from '~import {ActionFilter,ActionType,+ AnyPropertyFilter,CohortType,EntityFilter,EventDefinition,@@ -69,17 +70,16 @@ export type SelectedProperties = TaxonomicFilterGroupValueMapexport type AllowedProperties = TaxonomicFilterGroupValueMap/**- * Per-group-type **denylist of property-filter operators** the host cannot represent.- * Acts only on the **Recent tab** — items whose stored operator is denylisted for- * their source group are hidden so the picker never surfaces a value the- * surrounding UI can't reproduce.+ * Per-group rule for hiding property filters the host cannot represent.+ * Acts only on the Recent tab. A list hides recent filters whose operator it contains.+ * A callback receives the whole saved filter and returns true to hide it.** Pairs with `selectingKeyOnly` when a host wants both (a) no operator/value* slot in the row *and* (b) impossible recents kept out of the picker — the two* concerns are deliberately separate so callers can use one without the other:* - `selectingKeyOnly` decides whether the row renders an operator+value pair* (UI shape concern).- * - `excludedOperators` decides which stored operators the host is willing to+ * - `excludedOperators` decides which stored filters the host is willing to* surface in Recent (history concern).** NOT the same as `operatorAllowlist` on `OperatorValueSelect` — that's a flat@@ -87,7 +87,9 @@ export type AllowedProperties = TaxonomicFilterGroupValueMap* filter (e.g. survey trigger surfaces only `=` / `contains` regardless of* filter type).*/-export type ExcludedOperators = { [key in TaxonomicFilterGroupType]?: PropertyOperator[] }+export type ExcludedOperators = {+ [key in TaxonomicFilterGroupType]?: PropertyOperator[] | ((filter: AnyPropertyFilter) => boolean)+}/*** Tells `TaxonomicPropertyFilter` to render a row as key-only — the picked@@ -189,7 +191,7 @@ export interface TaxonomicFilterProps {* query matches a known autocapture interaction keyword. Consumers must handle* `isQuickFilterItem(item)` in their onChange to avoid mis-selecting as an event name. */enableKeywordShortcuts?: boolean- /** Hide recent property filters whose operator is denylisted for their source group, so the+ /** Hide recent property filters that the `ExcludedOperators` rule for their source group rejects, so the* picker never surfaces a value the surrounding UI can't represent. See `ExcludedOperators`* above for how this differs from `operatorAllowlist` on `OperatorValueSelect`. */excludedOperators?: ExcludedOperatorsdiff --git a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.test.ts b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.test.tsindex 284c69d1f932..c1dfcd2d27cb 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.test.ts@@ -50,6 +50,21 @@ describe('suggestedContextFilters', () => {).toHaveLength(1)})+ it('checks the whole filter when excluding a recent', () => {+ const items = [+ recent(EventProperties, 'date', {+ propertyFilter: { key: 'date', operator: PropertyOperator.IsSet, value: null },+ }),+ recent(EventProperties, 'name', {+ propertyFilter: { key: 'name', operator: PropertyOperator.IsSet, value: null },+ }),+ ]+ const out = filterRecentsForContext(items, [EventProperties], {+ [EventProperties]: (filter) => filter.key === 'date',+ })+ expect(names(out)).toEqual(['name', 'name'])+ })+it('drops a recent whose value is excluded for its group, keeping others', () => {const items = [recent(EventProperties, 'message'), recent(EventProperties, 'plan')]const out = filterRecentsForContext(items, [EventProperties], undefined, undefined, {diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.tsindex 4ad9eb19cb90..d3474f189ab3 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts@@ -40,10 +40,13 @@ export function filterRecentsForContext(return false}const excludedForGroup = excludedOperators?.[item._recentContext.sourceGroupType]- if (excludedForGroup?.length) {+ if (excludedForGroup) {const propertyFilter = item._recentContext.propertyFilterconst operator = propertyFilter && 'operator' in propertyFilter ? propertyFilter.operator : undefined- if (operator && excludedForGroup.includes(operator)) {+ if (typeof excludedForGroup === 'function' && propertyFilter && excludedForGroup(propertyFilter)) {+ return false+ }+ if (Array.isArray(excludedForGroup) && operator && excludedForGroup.includes(operator)) {return false}}diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsxindex c7f61e92e6d8..9652d0a90724 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx@@ -10,6 +10,7 @@ import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import {DataWarehousePopoverField,DefinitionPopoverRenderer,+ ExcludedOperators,ExcludedProperties,SelectedProperties,TaxonomicFilterGroupType,@@ -49,6 +50,7 @@ export interface TaxonomicPopoverProps<ValueType extends TaxonomicFilterValue =style?: React.CSSPropertiescloseOnChange?: booleanexcludedProperties?: ExcludedProperties+ excludedOperators?: ExcludedOperatorsincludeHiddenEvents?: booleanselectedProperties?: SelectedPropertiesmetadataSource?: AnyDataNode@@ -95,6 +97,7 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<allowClear = false,closeOnChange = true,excludedProperties,+ excludedOperators,includeHiddenEvents,selectedProperties,metadataSource,@@ -171,6 +174,7 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<schemaColumns={schemaColumns}metadataSource={metadataSource}excludedProperties={excludedProperties}+ excludedOperators={excludedOperators}includeHiddenEvents={includeHiddenEvents}selectedProperties={selectedProperties}showNumericalPropsOnly={showNumericalPropsOnly}@@ -255,6 +259,7 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<schemaColumns={schemaColumns}metadataSource={metadataSource}excludedProperties={excludedProperties}+ excludedOperators={excludedOperators}includeHiddenEvents={includeHiddenEvents}selectedProperties={selectedProperties}showNumericalPropsOnly={showNumericalPropsOnly}diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsxindex 9c88a7b1904a..8497b2e4d0d3 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx@@ -31,6 +31,7 @@ import { taxonomicTriggerWrapperClassName } from 'lib/components/TaxonomicFilterimport {AllowedProperties,DataWarehousePopoverField,+ ExcludedOperators,ExcludedProperties,SelectedProperties,SimpleOption,@@ -81,6 +82,7 @@ export interface TaxonomicPopoverMenuProps<ValueType extends TaxonomicFilterValuschemaColumns?: DatabaseSchemaField[]metadataSource?: AnyDataNodeexcludedProperties?: ExcludedProperties+ excludedOperators?: ExcludedOperatorsincludeHiddenEvents?: booleanselectedProperties?: SelectedPropertiespropertyAllowList?: AllowedProperties@@ -233,6 +235,7 @@ function ArmedTaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = TaxoschemaColumns,metadataSource,excludedProperties,+ excludedOperators,includeHiddenEvents,selectedProperties,propertyAllowList,@@ -327,6 +330,7 @@ function ArmedTaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = TaxoschemaColumns={schemaColumns}metadataSource={metadataSource}excludedProperties={excludedProperties}+ excludedOperators={excludedOperators}includeHiddenEvents={includeHiddenEvents}selectedProperties={selectedProperties}propertyAllowList={propertyAllowList}diff --git a/frontend/src/models/propertyDefinitionsModel.ts b/frontend/src/models/propertyDefinitionsModel.tsindex bc8b960cffdc..8eb356a0b01f 100644--- a/frontend/src/models/propertyDefinitionsModel.ts+++ b/frontend/src/models/propertyDefinitionsModel.ts@@ -118,7 +118,7 @@ export type Option = {searchInput?: string}-const getPropertyKey = (+export const getPropertyKey = (type: PropertyDefinitionType,propertyName?: BreakdownKeyType,groupTypeIndex?: number | nulldiff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsxindex e8d67dd55810..0864f6ab1221 100644--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx@@ -1,23 +1,41 @@import '@testing-library/jest-dom'-import { cleanup, render, screen, waitFor, within } from '@testing-library/react'+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { expectLogic, partial } from 'kea-test-utils'+import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'-import { NEW_COHORT } from 'scenes/cohorts/CohortFilters/constants'+import { NEW_COHORT, NEW_CRITERIA_GROUP } from 'scenes/cohorts/CohortFilters/constants'import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'import { urls } from 'scenes/urls'import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'import { toPaginatedResponse } from '~/mocks/handlers'import { useMocks } from '~/mocks/jest'+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { initKeaTests } from '~/test/init'import { mockCohort } from '~/test/mocks'-import { AnyCohortCriteriaType, BehavioralEventType, FilterLogicalOperator, InsightShortId } from '~/types'+import {+ AnyCohortCriteriaType,+ BehavioralEventType,+ FilterLogicalOperator,+ InsightShortId,+ PropertyDefinitionState,+ PropertyFilterType,+ PropertyFilterValue,+ PropertyOperator,+ PropertyType,+} from '~/types'import { CohortEdit } from './CohortEdit'+jest.mock('lib/components/AutoSizer', () => ({+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>+ renderProp({ height: 1000, width: 400 }),+}))+describe('cohortEditLogic', () => {let logic: ReturnType<typeof cohortEditLogic.build>@@ -806,6 +824,111 @@ describe('cohortEditLogic', () => {)})+ describe('prefilling a recent person filter', () => {+ const recordPersonRecent = (+ recentFilters: ReturnType<typeof recentTaxonomicFiltersLogic.build>,+ key: string,+ operator: PropertyOperator,+ value: PropertyFilterValue+ ): void => {+ recentFilters.actions.recordRecentFilter({+ groupType: TaxonomicFilterGroupType.PersonProperties,+ groupName: 'Person properties',+ value: key,+ item: { name: key },+ propertyFilter: { type: PropertyFilterType.Person, key, operator, value },+ })+ }++ const suggestedRows = (): HTMLElement[] =>+ Array.from(document.querySelectorAll<HTMLElement>('[data-attr^="prop-filter-suggested_filters-"]'))+ const suggestedText = (): string =>+ suggestedRows()+ .map((row) => row.textContent ?? '')+ .join('||')++ afterEach(() => {+ cleanup()+ })++ it.each([+ ['$browser', PropertyOperator.IContains, 'Chrome', 'Chrome', 'Chrome', 'contains'],+ ['$email', PropertyOperator.IsSet, PropertyOperator.IsSet, 'is set', undefined, 'is set'],+ ])(+ 'hides unsupported recents and prefills %s',+ async (key, operator, recordedValue, rowText, expectedValue, expectedOperatorLabel) => {+ const definitions = propertyDefinitionsModel.build()+ definitions.mount()+ definitions.actions.updatePropertyDefinitions({+ 'person/$browser': { id: '$browser', name: '$browser', property_type: PropertyType.String },+ 'person/$email': { id: '$email', name: '$email', property_type: PropertyType.String },+ 'person/$os': { id: '$os', name: '$os', property_type: PropertyType.String },+ 'person/birth_date': PropertyDefinitionState.Loading,+ })+ const recentFilters = recentTaxonomicFiltersLogic.build()+ recentFilters.mount()+ recentFilters.actions.clearRecentFilters()+ recordPersonRecent(recentFilters, 'birth_date', PropertyOperator.IsDateBefore, '2000-01-01')+ recordPersonRecent(recentFilters, key, operator, recordedValue)+ recordPersonRecent(recentFilters, '$os', PropertyOperator.NotIn, ['Mac'])+ logic = cohortEditLogic({ id: 'new' })+ logic.mount()+ logic.actions.setCohort({+ ...NEW_COHORT,+ filters: {+ properties: {+ ...NEW_COHORT.filters.properties,+ values: [+ {+ ...NEW_CRITERIA_GROUP,+ values: [+ {+ type: BehavioralFilterKey.Person,+ value: BehavioralEventType.HaveProperty,+ event_type: TaxonomicFilterGroupType.PersonProperties,+ },+ ],+ },+ ],+ },+ },+ })++ render(<CohortEdit id="new" />)+ await userEvent.click(await screen.findByText('Choose person property'))+ await waitFor(() => expect(suggestedText()).toContain(rowText))+ expect(suggestedText()).not.toMatch(/Mac|birth_date/)++ await act(async () => {+ definitions.actions.updatePropertyDefinitions({+ 'person/birth_date': {+ id: 'birth_date',+ name: 'birth_date',+ property_type: PropertyType.DateTime,+ },+ })+ })+ await waitFor(() => expect(suggestedText()).toContain('birth_date'))++ await userEvent.click(suggestedRows().find((row) => row.textContent?.includes(rowText))!)++ await waitFor(() => {+ const group = logic.values.cohort.filters.properties.values[0] as {+ values: AnyCohortCriteriaType[]+ }+ expect(group.values[0]).toEqual(+ expect.objectContaining({ key, operator, value_property: expectedValue })+ )+ expect(document.querySelector('[data-attr="cohort-selector-field-operator"]')).toHaveTextContent(+ expectedOperatorLabel+ )+ })+ recentFilters.unmount()+ definitions.unmount()+ }+ )+ })+describe('locked type and populate-from controls on existing cohorts', () => {afterEach(() => {cleanup()diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsxindex 98993d5cfd5c..338621d78c96 100644--- a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx@@ -2,19 +2,22 @@ import './CohortField.scss'import clsx from 'clsx'import { useActions, useMountedLogic, useValues } from 'kea'-import { useEffect, useId, useRef } from 'react'+import { useEffect, useId, useMemo, useRef } from 'react'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { PropertyValue } from 'lib/components/PropertyFilters/components/PropertyValue'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { isPersonMetadataPropertyFilter, isPersonPropertyFilter } from 'lib/components/PropertyFilters/utils'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'-import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'+import { hasRecentContext } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'+import { ExcludedOperators, TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'import { dayjs } from 'lib/dayjs'import { LemonButton, LemonButtonWithDropdown } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'import { formatDate } from 'lib/utils/datetime'+import { isOperatorFlag } from 'lib/utils/operators'import { cohortFieldLogic } from 'scenes/cohorts/CohortFilters/cohortFieldLogic'import {BehavioralFilterKey,@@ -27,20 +30,23 @@ import {CohortSelectorFieldProps,CohortTaxonomicFieldProps,CohortTextFieldProps,- FieldOptionsType,} from 'scenes/cohorts/CohortFilters/types'-import { determineFilterType } from 'scenes/cohorts/cohortUtils'+import {+ determineFilterType,+ isRecentPersonFilterUnsupported,+ personOperatorOptionsType,+} from 'scenes/cohorts/cohortUtils'import { actionsModel } from '~/models/actionsModel'-import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'+import { getPropertyKey, propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import {AnyCohortCriteriaType,AnyPropertyFilter,+ BehavioralEventType,PropertyDefinitionType,PropertyFilterType,PropertyFilterValue,PropertyOperator,- PropertyType,} from '~/types'const useCohortFieldLogic = (props: CohortFieldBaseProps): { logic: ReturnType<typeof cohortFieldLogic.build> } => {@@ -143,13 +149,10 @@ export function CohortMathOperatorField(props: CohortSelectorFieldProps): JSX.El? PropertyDefinitionType.PersonMetadata: PropertyDefinitionType.Personconst propDef = propertyKey ? getPropertyDefinition(propertyKey, definitionType) : null- const isDateTime = propDef?.property_type === PropertyType.DateTime-- const fieldOptionGroupTypes = isDateTime- ? [FieldOptionsType.SingleFieldDateOperators]- : [FieldOptionsType.CohortMathOperators]- return <CohortSelectorField {...props} fieldOptionGroupTypes={fieldOptionGroupTypes} />+ return (+ <CohortSelectorField {...props} fieldOptionGroupTypes={[personOperatorOptionsType(propDef?.property_type)]} />+ )}export function CohortTaxonomicField({@@ -158,6 +161,7 @@ export function CohortTaxonomicField({cohortFilterLogicKey,criteria,taxonomicGroupTypes = [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],+ hideUnsupportedRecentOperators,placeholder = 'Choose event',onChange: _onChange,}: CohortTaxonomicFieldProps): JSX.Element {@@ -172,7 +176,23 @@ export function CohortTaxonomicField({const { calculatedValue, calculatedValueLoading } = useValues(logic)const { onChange } = useActions(logic)+ const { getPropertyDefinition, propertyDefinitionStorage } = useValues(propertyDefinitionsModel)const groupType = (criteria[groupTypeFieldKey] as TaxonomicFilterGroupType) ?? taxonomicGroupTypes[0]+ const excludedOperators = useMemo<ExcludedOperators | undefined>(() => {+ if (!hideUnsupportedRecentOperators) {+ return undefined+ }+ const isUnsupportedRecent = (filter: AnyPropertyFilter): boolean =>+ isRecentPersonFilterUnsupported(+ filter,+ (key, type) =>+ getPropertyDefinition(key, type) ?? propertyDefinitionStorage[getPropertyKey(type, key)] ?? null+ )+ return {+ [TaxonomicFilterGroupType.PersonProperties]: isUnsupportedRecent,+ [TaxonomicFilterGroupType.PersonMetadata]: isUnsupportedRecent,+ }+ }, [hideUnsupportedRecentOperators, getPropertyDefinition, propertyDefinitionStorage])return (<TaxonomicPopover@@ -180,12 +200,24 @@ export function CohortTaxonomicField({groupType={groupType}loading={calculatedValueLoading(groupType)}value={calculatedValue(groupType) as TaxonomicFilterValue}- onChange={(v, g) => {- onChange({ [fieldKey]: v, [groupTypeFieldKey]: g })+ onChange={(v, g, item) => {+ const recentFilter = hasRecentContext(item) ? item._recentContext.propertyFilter : undefined+ const recentOperatorAndValue =+ fieldKey === 'key' &&+ criteria.value === BehavioralEventType.HaveProperty &&+ (isPersonPropertyFilter(recentFilter) || isPersonMetadataPropertyFilter(recentFilter)) &&+ recentFilter.key === v+ ? {+ operator: recentFilter.operator,+ value_property: isOperatorFlag(recentFilter.operator) ? null : recentFilter.value,+ }+ : {}+ onChange({ [fieldKey]: v, [groupTypeFieldKey]: g, ...recentOperatorAndValue })}}excludedProperties={{[TaxonomicFilterGroupType.Events]: [null], // "All events" isn't supported by Cohorts currently}}+ excludedOperators={excludedOperators}groupTypes={taxonomicGroupTypes}placeholder={placeholder}data-attr={`cohort-taxonomic-field-${fieldKey}`}diff --git a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx b/frontend/src/scenes/cohorts/CohortFilters/constants.tsxindex f4e8a711f89a..2c3e44bf464a 100644--- a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/constants.tsx@@ -976,6 +976,7 @@ export const renderField: Record<FilterType, (props: CohortFieldProps) => JSX.Elreturn (<CohortTaxonomicField{...(p as CohortTaxonomicFieldProps)}+ hideUnsupportedRecentOperatorstaxonomicGroupTypes={[TaxonomicFilterGroupType.PersonProperties,TaxonomicFilterGroupType.PersonMetadata,diff --git a/frontend/src/scenes/cohorts/CohortFilters/types.ts b/frontend/src/scenes/cohorts/CohortFilters/types.tsindex ae2bf19f2413..f7a2dca06599 100644--- a/frontend/src/scenes/cohorts/CohortFilters/types.ts+++ b/frontend/src/scenes/cohorts/CohortFilters/types.ts@@ -103,6 +103,7 @@ export interface CohortTaxonomicFieldProps extends Omit<CohortFieldBaseProps, 'fgroupTypeFieldKey?: keyof AnyCohortCriteriaTypeplaceholder?: stringtaxonomicGroupTypes?: TaxonomicFilterGroupType[]+ hideUnsupportedRecentOperators?: booleanfieldOptionGroupTypes: never}diff --git a/frontend/src/scenes/cohorts/cohortUtils.test.tsx b/frontend/src/scenes/cohorts/cohortUtils.test.tsxindex 109c465e8bdd..6053bc500253 100644--- a/frontend/src/scenes/cohorts/cohortUtils.test.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.test.tsx@@ -7,15 +7,23 @@ import {createCohortFormData,criteriaToHumanSentence,determineFilterType,+ isRecentPersonFilterUnsupported,validateGroup,} from 'scenes/cohorts/cohortUtils'import {AnyCohortCriteriaType,+ AnyPropertyFilter,BehavioralEventType,CohortCriteriaGroupFilter,CohortType,FilterLogicalOperator,+ PropertyDefinition,+ PropertyDefinitionState,+ PropertyFilterType,+ PropertyFilterValue,+ PropertyOperator,+ PropertyType,} from '~/types'describe('validateGroup', () => {@@ -298,3 +306,106 @@ describe('createCohortFormData', () => {expect(filters.filterTestAccounts).toEqual(expected)})})++describe('isRecentPersonFilterUnsupported', () => {+ const definition = (propertyType: PropertyType): PropertyDefinition => ({+ id: 'property',+ name: 'property',+ property_type: propertyType,+ })++ it.each<+ [+ string,+ PropertyFilterType,+ PropertyOperator,+ PropertyFilterValue,+ PropertyDefinition | PropertyDefinitionState | null,+ boolean,+ ]+ >([+ [+ 'text operator on a text property',+ PropertyFilterType.Person,+ PropertyOperator.IContains,+ 'Chrome',+ definition(PropertyType.String),+ false,+ ],+ [+ 'operator the text menu lacks',+ PropertyFilterType.Person,+ PropertyOperator.NotIn,+ ['Mac'],+ definition(PropertyType.String),+ true,+ ],+ [+ 'absolute date on a date property',+ PropertyFilterType.Person,+ PropertyOperator.IsDateBefore,+ '2000-01-01',+ definition(PropertyType.DateTime),+ false,+ ],+ [+ 'relative date on a date property',+ PropertyFilterType.Person,+ PropertyOperator.IsDateBefore,+ '-30d',+ definition(PropertyType.DateTime),+ true,+ ],+ [+ 'text operator on a date property',+ PropertyFilterType.Person,+ PropertyOperator.IContains,+ '2000',+ definition(PropertyType.DateTime),+ true,+ ],+ [+ 'date on person metadata',+ PropertyFilterType.PersonMetadata,+ PropertyOperator.IsDateAfter,+ '2020-01-01',+ definition(PropertyType.DateTime),+ false,+ ],+ [+ 'type still loading',+ PropertyFilterType.Person,+ PropertyOperator.IsDateBefore,+ '2000-01-01',+ PropertyDefinitionState.Loading,+ true,+ ],+ [+ 'type not found',+ PropertyFilterType.Person,+ PropertyOperator.IContains,+ 'pro',+ PropertyDefinitionState.Missing,+ false,+ ],+ [+ 'type lookup failed',+ PropertyFilterType.Person,+ PropertyOperator.IContains,+ 'pro',+ PropertyDefinitionState.Error,+ false,+ ],+ [+ 'event property',+ PropertyFilterType.Event,+ PropertyOperator.IContains,+ 'Chrome',+ definition(PropertyType.String),+ true,+ ],+ ])('%s', (_, type, operator, value, lookupResult, expected) => {+ const filter = { type, key: 'property', operator, value } as AnyPropertyFilter+ expect(isRecentPersonFilterUnsupported(filter, () => lookupResult)).toBe(expected)+ })+})diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex 7cd4b2a7a106..9805d22a0842 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -1,17 +1,30 @@import { deepEqual as equal } from 'fast-equals'import { DeepPartialMap, ValidationErrorType } from 'kea-forms'-import { isEmptyProperty, propertyFilterTypeToPropertyDefinitionType } from 'lib/components/PropertyFilters/utils'+import {+ isEmptyProperty,+ isPersonMetadataPropertyFilter,+ isPersonPropertyFilter,+ propertyFilterTypeToPropertyDefinitionType,+} from 'lib/components/PropertyFilters/utils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { ENTITY_MATCH_TYPE, PROPERTY_MATCH_TYPE } from 'lib/constants'+import { isStringDateRegex } from 'lib/utils/dateFilters'import { calculateDays } from 'lib/utils/durations'import { isNumeric } from 'lib/utils/guards'import { areObjectValuesEmpty } from 'lib/utils/objects'-import { BEHAVIORAL_TYPE_TO_LABEL, CRITERIA_VALIDATIONS, getRowShape } from 'scenes/cohorts/CohortFilters/constants'+import { isOperatorDate } from 'lib/utils/operators'+import {+ BEHAVIORAL_TYPE_TO_LABEL,+ CRITERIA_VALIDATIONS,+ FIELD_VALUES,+ getRowShape,+} from 'scenes/cohorts/CohortFilters/constants'import {BehavioralFilterKey,BehavioralFilterType,CohortClientErrors,+ FieldOptionsType,FieldWithFieldKey,FilterType,} from 'scenes/cohorts/CohortFilters/types'@@ -30,6 +43,9 @@ import {CohortCriteriaType,CohortType,FilterLogicalOperator,+ PropertyDefinition,+ PropertyDefinitionState,+ PropertyDefinitionType,PropertyFilterType,PropertyFilterValue,PropertyOperator,@@ -734,3 +750,42 @@ export function cohortBroadcastAudience(cohort: Pick<CohortType, 'id' | 'name'>)draftSource: { source: 'cohort', source_id: String(cohort.id) },}}++export function personOperatorOptionsType(propertyType?: PropertyType | null): FieldOptionsType {+ return propertyType === PropertyType.DateTime+ ? FieldOptionsType.SingleFieldDateOperators+ : FieldOptionsType.CohortMathOperators+}++export type PropertyDefinitionLookup = (+ key: string,+ type: PropertyDefinitionType+) => PropertyDefinition | PropertyDefinitionState | null++/**+ * True when the cohort editor cannot show a recent filter's operator and value.+ * While a property type is still loading, only operators that both type menus offer count as shown.+ */+export function isRecentPersonFilterUnsupported(+ filter: AnyPropertyFilter,+ lookupDefinition: PropertyDefinitionLookup+): boolean {+ if (!(isPersonPropertyFilter(filter) || isPersonMetadataPropertyFilter(filter)) || !filter.operator) {+ return true+ }+ const { operator, value } = filter+ // The cohort date editor takes an absolute date only, so a relative value such as -30d shows as an invalid date.+ if (isOperatorDate(operator) && typeof value === 'string' && isStringDateRegex.test(value)) {+ return true+ }+ const isOperatorShownFor = (propertyType?: PropertyType): boolean =>+ operator in FIELD_VALUES[personOperatorOptionsType(propertyType)].values+ const definition = lookupDefinition(filter.key, propertyFilterTypeToPropertyDefinitionType(filter.type))+ if (typeof definition === 'object' && definition !== null) {+ return !isOperatorShownFor(definition.property_type)+ }+ if (definition === PropertyDefinitionState.Missing || definition === PropertyDefinitionState.Error) {+ return !isOperatorShownFor()+ }+ return !(isOperatorShownFor(PropertyType.DateTime) && isOperatorShownFor())+}