: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
feat(cohorts): expose text and date person operators (#118596)
Paul D'Ambra56b486b84981
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsxindex 0864f6ab1221..79cc0d28efac 100644--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx@@ -927,6 +927,115 @@ describe('cohortEditLogic', () => {definitions.unmount()})++ it.each([+ {+ key: '$browser',+ propertyType: PropertyType.String,+ operator: PropertyOperator.StartsWith,+ value: 'Chr',+ label: 'starts with',+ },+ {+ key: '$browser',+ propertyType: PropertyType.String,+ operator: PropertyOperator.NotStartsWith,+ value: 'Chr',+ label: 'does not start with',+ },+ {+ key: '$browser',+ propertyType: PropertyType.String,+ operator: PropertyOperator.EndsWith,+ value: 'ome',+ label: 'ends with',+ },+ {+ key: '$browser',+ propertyType: PropertyType.String,+ operator: PropertyOperator.NotEndsWith,+ value: 'ome',+ label: 'does not end with',+ },+ {+ key: 'birth_date',+ propertyType: PropertyType.DateTime,+ operator: PropertyOperator.IsSet,+ value: null,+ label: 'is set',+ },+ {+ key: 'birth_date',+ propertyType: PropertyType.DateTime,+ operator: PropertyOperator.IsNotSet,+ value: null,+ label: 'is not set',+ },+ ])(+ 'prefills a recent person filter with $operator during cohort creation',+ async ({ key, propertyType, operator, value, label }) => {+ const definitions = propertyDefinitionsModel.build()+ definitions.mount()+ definitions.actions.updatePropertyDefinitions({+ [`person/${key}`]: {+ id: key,+ name: key,+ property_type: propertyType,+ },+ })+ const recentFilters = recentTaxonomicFiltersLogic.build()+ recentFilters.mount()+ recentFilters.actions.clearRecentFilters()+ recordPersonRecent(recentFilters, key, operator, value)+ 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 userEvent.click(await screen.findByTestId('prop-filter-suggested_filters-1'))++ 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: value ?? undefined,+ })+ )+ expect(document.querySelector('[data-attr="cohort-selector-field-operator"]')).toHaveTextContent(+ label+ )+ if (value) {+ expect(screen.getByText(value)).toBeInTheDocument()+ }+ })+ recentFilters.unmount()+ definitions.unmount()+ }+ )})describe('locked type and populate-from controls on existing cohorts', () => {diff --git a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx b/frontend/src/scenes/cohorts/CohortFilters/constants.tsxindex 2c3e44bf464a..4e7d6017cd5a 100644--- a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/constants.tsx@@ -218,6 +218,12 @@ export const FIELD_VALUES: Record<FieldOptionsType, FieldValues> = {[SingleFieldDateType.IsDateBefore]: {label: 'before',},+ [PropertyOperator.IsSet]: {+ label: 'is set',+ },+ [PropertyOperator.IsNotSet]: {+ label: 'is not set',+ },},},[FieldOptionsType.MathOperators]: {@@ -290,6 +296,18 @@ export const FIELD_VALUES: Record<FieldOptionsType, FieldValues> = {[PropertyOperator.NotIContains]: {label: 'does not contain',},+ [PropertyOperator.StartsWith]: {+ label: 'starts with',+ },+ [PropertyOperator.NotStartsWith]: {+ label: 'does not start with',+ },+ [PropertyOperator.EndsWith]: {+ label: 'ends with',+ },+ [PropertyOperator.NotEndsWith]: {+ label: 'does not end with',+ },[PropertyOperator.IContainsMulti]: {label: 'contains any of',},diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.tsindex 86e64efae657..371debdb94fa 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts@@ -20,6 +20,7 @@ import { urls } from 'scenes/urls'import { toPaginatedResponse } from '~/mocks/handlers'import { useMocks } from '~/mocks/jest'import { cohortsModel } from '~/models/cohortsModel'+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { mockCohort } from '~/test/mocks'@@ -33,6 +34,7 @@ import {FilterLogicalOperator,PropertyFilterType,PropertyOperator,+ PropertyType,TimeUnitType,} from '~/types'@@ -1266,6 +1268,45 @@ describe('cohortEditLogic', () => {await initCohortLogic({ id: 1 })})+ it.each([+ ['email', PropertyOperator.IsSet, PropertyOperator.IsSet],+ ['birth_date', PropertyOperator.IsDateBefore, PropertyOperator.IsDateBefore],+ ['email', PropertyOperator.IContains, PropertyOperator.IsDateExact],+ ])(+ 'switching a %s row on %s to a DateTime property leaves the operator %s',+ async (startKey, startOperator, expectedOperator) => {+ propertyDefinitionsModel.mount()+ propertyDefinitionsModel.actions.updatePropertyDefinitions({+ 'person/email': { id: 'email', name: 'email', property_type: PropertyType.String },+ 'person/birth_date': { id: 'birth_date', name: 'birth_date', property_type: PropertyType.DateTime },+ 'person/signup_date': {+ id: 'signup_date',+ name: 'signup_date',+ property_type: PropertyType.DateTime,+ },+ })+ logic.actions.setCriteria(+ {+ type: BehavioralFilterKey.Person,+ value: BehavioralEventType.HaveProperty,+ key: startKey,+ operator: startOperator,+ },+ 0,+ 0+ )++ await expectLogic(logic, () => {+ logic.actions.setCriteria({ key: 'signup_date' }, 0, 0)+ }).toFinishAllListeners()++ const group = logic.values.cohort.filters.properties.values[0] as CohortCriteriaGroupFilter+ expect(group.values[0]).toEqual(+ expect.objectContaining({ key: 'signup_date', operator: expectedOperator })+ )+ }+ )+it('duplicate group', async () => {const expectedGroupValue = partial({...mockCohort.filters.properties.values[0],diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.tsindex beb975e7d157..6428bfab1f5e 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts@@ -45,6 +45,7 @@ import {createCohortDataNodeLogicKey,createCohortFormData,isCohortCriteriaGroup,+ isPersonOperatorShown,validateGroup,cohortCsvMaxBytes,cohortCsvTooLargeMessage,@@ -1202,7 +1203,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([const isDateTime = propDef?.property_type === PropertyType.DateTimeconst currentOperator = criteria.operator as PropertyOperator | undefined- if (isDateTime && (!currentOperator || !isOperatorDate(currentOperator))) {+ if (isDateTime && (!currentOperator || !isPersonOperatorShown(currentOperator, PropertyType.DateTime))) {actions.setCriteria({ operator: PropertyOperator.IsDateExact }, groupIndex, criteriaIndex)} else if (!isDateTime && currentOperator && isOperatorDate(currentOperator)) {actions.setCriteria({ operator: PropertyOperator.Exact }, groupIndex, criteriaIndex)diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex 154c02477c1a..f24624660e93 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -774,6 +774,10 @@ export function personOperatorOptionsType(propertyType?: PropertyType | null): F: FieldOptionsType.CohortMathOperators}+export function isPersonOperatorShown(operator: PropertyOperator, propertyType?: PropertyType | null): boolean {+ return operator in FIELD_VALUES[personOperatorOptionsType(propertyType)].values+}+export type PropertyDefinitionLookup = (key: string,type: PropertyDefinitionType@@ -795,8 +799,7 @@ export function isRecentPersonFilterUnsupported(if (isOperatorDate(operator) && typeof value === 'string' && isStringDateRegex.test(value)) {return true}- const isOperatorShownFor = (propertyType?: PropertyType): boolean =>- operator in FIELD_VALUES[personOperatorOptionsType(propertyType)].values+ const isOperatorShownFor = (propertyType?: PropertyType): boolean => isPersonOperatorShown(operator, propertyType)const definition = lookupDefinition(filter.key, propertyFilterTypeToPropertyDefinitionType(filter.type))if (typeof definition === 'object' && definition !== null) {return !isOperatorShownFor(definition.property_type)diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex d048cda8d389..7a3408704dea 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -6,12 +6,14 @@ import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patch+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.hogql_cohort_query import HogQLCohortQueryfrom products.cohorts.backend.models.cohort import Cohort+from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyTypeclass TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):@@ -541,6 +543,60 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):self.assertIn(str(new_person.uuid), member_ids)self.assertNotIn(str(old_person.uuid), member_ids)+ @parameterized.expand(+ [+ ("email", "starts_with", "first", "first"),+ ("email", "not_starts_with", "first", "second"),+ ("email", "ends_with", ".org", "second"),+ ("email", "not_ends_with", ".org", "first"),+ ("birth_date", "is_set", None, "first"),+ ("birth_date", "is_not_set", None, "second"),+ ]+ )+ def test_person_property_operators_calculate_cohort_membership(+ self, key: str, operator: str, value: str | None, expected_member: str+ ) -> None:+ PropertyDefinition.objects.create(+ team=self.team,+ name="birth_date",+ property_type=PropertyType.Datetime,+ type=PropertyDefinition.Type.PERSON,+ )+ members = {+ "first": _create_person(+ team=self.team,+ distinct_ids=["first"],+ properties={"email": "[email protected]", "birth_date": "2000-01-01"},+ immediate=True,+ ),+ "second": _create_person(+ team=self.team,+ distinct_ids=["second"],+ properties={"email": "[email protected]"},+ immediate=True,+ ),+ }+ flush_persons_and_events()+ cohort = Cohort.objects.create(+ team=self.team,+ name=f"{operator} cohort",+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [{"key": key, "type": "person", "operator": operator, "value": value}],+ }+ ],+ }+ },+ )++ cohort.calculate_people_ch(pending_version=0)++ self.assertEqual(self._cohort_member_ids(cohort, 0), {str(members[expected_member].uuid)})+def _cohort_member_ids(self, cohort: Cohort, version: int) -> set[str]:rows = sync_execute("SELECT person_id FROM cohortpeople WHERE cohort_id = %(cohort_id)s AND team_id = %(team_id)s "