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.

chore(insights): delete unused legacy filter classes (#115260)

Thomas Obermüllere51dcc1c3bbd
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fac18b886508..0c3b4f0e7f55 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3673,7 +3673,6 @@ export interface FunnelConversionWindow {
funnelWindowInterval?: number
}
-// https://github.com/PostHog/posthog/blob/master/posthog/models/filters/mixins/funnel.py#L100
export enum FunnelConversionWindowTimeUnit {
Second = 'second',
Minute = 'minute',
diff --git a/posthog/api/shared.py b/posthog/api/shared.py
index db505beaf40e..d0a94f1c076c 100644
--- a/posthog/api/shared.py
+++ b/posthog/api/shared.py
@@ -320,20 +320,6 @@ class OrganizationBasicSerializer(serializers.ModelSerializer):
return super().to_representation(instance)
-class FilterBaseSerializer(serializers.Serializer):
- type = serializers.ChoiceField(choices=["events", "actions"])
- id = serializers.CharField(required=False)
- name = serializers.CharField(required=False, allow_null=True)
- order = serializers.IntegerField(required=False)
- properties = serializers.ListField(child=serializers.DictField(), default=[])
-
-
-class FiltersSerializer(serializers.Serializer):
- events = FilterBaseSerializer(many=True, required=False)
- actions = FilterBaseSerializer(many=True, required=False)
- filter_test_accounts = serializers.BooleanField(required=False)
-
-
# These mirror the TypedDicts in posthog/hogql_queries/serialized_actors.py, so a field added
# there needs adding here. Only the Optional[...] ones are nullable; the rest are always-set keys.
#
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index ffb7ad09c3a7..31304fdaad35 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -30,7 +30,6 @@ from .file_system.file_system import FileSystem
from .file_system.file_system_home_folder import FileSystemHomeFolder
from .file_system.file_system_view_log import FileSystemViewLog
from .file_system.user_product_list import UserProductList
-from .filters import RetentionFilter
from .group import Group
from .group_usage_metric import GroupUsageMetric
from .group_type_mapping import GroupTypeMapping
@@ -158,7 +157,6 @@ __all__ = [
"PropertyDefinition",
"ProxyRecord",
"QuickFilter",
- "RetentionFilter",
"RemoteConfig",
"ResourceTransfer",
"EventSchema",
diff --git a/posthog/models/entity/__init__.py b/posthog/models/entity/__init__.py
index cb6b13f3edb0..1aaf2fc47536 100644
--- a/posthog/models/entity/__init__.py
+++ b/posthog/models/entity/__init__.py
@@ -1,3 +1,3 @@
-from .entity import Entity, ExclusionEntity, MathType
+from .entity import Entity, MathType
-__all__ = ["Entity", "ExclusionEntity", "MathType"]
+__all__ = ["Entity", "MathType"]
diff --git a/posthog/models/entity/entity.py b/posthog/models/entity/entity.py
index fe194359e328..5a4df118d43a 100644
--- a/posthog/models/entity/entity.py
+++ b/posthog/models/entity/entity.py
@@ -1,5 +1,4 @@
import json
-import inspect
from collections import Counter
from typing import TYPE_CHECKING, Any, Literal, Optional
@@ -15,7 +14,6 @@ from posthog.constants import (
TREND_FILTER_TYPE_DATA_WAREHOUSE,
TREND_FILTER_TYPE_EVENTS,
)
-from posthog.models.filters.mixins.funnel import FunnelFromToStepsMixin
from posthog.models.filters.mixins.property import PropertyMixin
from posthog.models.filters.utils import validate_group_type_index
from posthog.models.property import GroupTypeIndex
@@ -207,25 +205,6 @@ class Entity(PropertyMixin):
)
-class ExclusionEntity(Entity, FunnelFromToStepsMixin):
- """
- Exclusion Entities represent Entities in Filter objects
- with extra parameters for exclusion semantics.
- """
-
- def __init__(self, data: dict[str, Any]) -> None:
- super().__init__(data)
-
- def to_dict(self) -> dict[str, Any]:
- ret = super().to_dict()
-
- for _, func in inspect.getmembers(self, inspect.ismethod):
- if hasattr(func, "include_dict"): # provided by @include_dict decorator
- ret.update(func())
-
- return ret
-
-
def parse_entities(data: dict) -> list["Entity"]:
"""Build the ordered entity list from an insight-style filter dict."""
processed_entities: list[Entity] = []
diff --git a/posthog/models/filters/__init__.py b/posthog/models/filters/__init__.py
index fc5496ea745e..7aca236ce85c 100644
--- a/posthog/models/filters/__init__.py
+++ b/posthog/models/filters/__init__.py
@@ -1,11 +1,5 @@
-from .path_filter import PathFilter
from .properties_timeline_filter import PropertiesTimelineFilter
-from .retention_filter import RetentionFilter
-from .stickiness_filter import StickinessFilter
__all__ = [
- "PathFilter",
- "RetentionFilter",
- "StickinessFilter",
"PropertiesTimelineFilter",
]
diff --git a/posthog/models/filters/base_filter.py b/posthog/models/filters/base_filter.py
index dea97226b047..2eeb037f3a12 100644
--- a/posthog/models/filters/base_filter.py
+++ b/posthog/models/filters/base_filter.py
@@ -70,10 +70,6 @@ class BaseFilter(BaseParamMixin):
if self.team:
self.hogql_context.modifiers.personsOnEventsMode = self.team.person_on_events_mode
- if self.team and hasattr(self, "simplify") and not getattr(self, "is_simplified", False):
- simplified_filter = self.simplify(self.team)
- self._data = simplified_filter._data
-
def to_dict(self) -> dict[str, Any]:
ret = {}
diff --git a/posthog/models/filters/mixins/base.py b/posthog/models/filters/mixins/base.py
index a4640f0aae12..cbcdc33318c8 100644
--- a/posthog/models/filters/mixins/base.py
+++ b/posthog/models/filters/mixins/base.py
@@ -2,7 +2,6 @@ from typing import Literal
BreakdownType = Literal["event", "person", "cohort", "group", "session", "hogql"]
IntervalType = Literal["hour", "day", "week", "month"]
-FunnelWindowIntervalType = Literal["second", "minute", "hour", "day", "week", "month"]
class BaseParamMixin:
diff --git a/posthog/models/filters/mixins/common.py b/posthog/models/filters/mixins/common.py
index 5e66a425e167..19d360e07167 100644
--- a/posthog/models/filters/mixins/common.py
+++ b/posthog/models/filters/mixins/common.py
@@ -23,71 +23,29 @@ from posthog.constants import (
BREAKDOWN_NORMALIZE_URL,
BREAKDOWN_TYPE,
BREAKDOWNS,
- CLIENT_QUERY_ID,
- COMPARE,
- COMPARE_TO,
DATA_WAREHOUSE_ENTITIES,
DATE_FROM,
DATE_TO,
DISPLAY,
DISPLAY_TYPES,
EVENTS,
- EXCLUSIONS,
EXPLICIT_DATE,
- FILTER_TEST_ACCOUNTS,
INSIGHT,
INSIGHT_TO_DISPLAY,
INSIGHT_TRENDS,
- LIMIT,
- OFFSET,
- SAMPLING_FACTOR,
- SHOWN_AS,
TREND_FILTER_TYPE_ACTIONS,
TREND_FILTER_TYPE_DATA_WAREHOUSE,
TREND_FILTER_TYPE_EVENTS,
TRENDS_WORLD_MAP,
BreakdownAttributionType,
)
-from posthog.models.entity import Entity, ExclusionEntity, MathType
+from posthog.models.entity import Entity
from posthog.models.filters.mixins.base import BaseParamMixin, BreakdownType
from posthog.models.filters.mixins.utils import cached_property, include_dict, include_query_tags, process_bool
from posthog.models.filters.utils import GroupTypeIndex, validate_group_type_index
from posthog.utils import DEFAULT_DATE_FROM_DAYS, relative_date_parse_with_delta_mapping
-class ShownAsMixin(BaseParamMixin):
- @cached_property
- def shown_as(self) -> Optional[str]:
- return self._data.get(SHOWN_AS, None)
-
- @include_dict
- def shown_as_to_dict(self):
- return {"shown_as": self.shown_as} if self.shown_as else {}
-
-
-class ClientQueryIdMixin(BaseParamMixin):
- @cached_property
- def client_query_id(self) -> Optional[str]:
- return self._data.get(CLIENT_QUERY_ID, None)
-
- @include_query_tags
- def client_query_tags(self):
- return {"client_query_id": self.client_query_id} if self.client_query_id else {}
-
-
-class FilterTestAccountsMixin(BaseParamMixin):
- @cached_property
- def filter_test_accounts(self) -> bool:
- setting = self._data.get(FILTER_TEST_ACCOUNTS, None)
- if setting is True or setting == "true":
- return True
- return False
-
- @include_dict
- def filter_out_team_members_to_dict(self):
- return {"filter_test_accounts": self.filter_test_accounts} if self.filter_test_accounts else {}
-
-
class BreakdownMixin(BaseParamMixin):
@cached_property
def breakdown(self) -> Optional[Union[str, list[Union[str, int]]]]:
@@ -250,48 +208,6 @@ class DisplayDerivedMixin(InsightMixin):
return {"display": self.display}
-class OffsetMixin(BaseParamMixin):
- @cached_property
- def offset(self) -> int:
- offset_raw = self._data.get(OFFSET)
- return int(offset_raw) if offset_raw else 0
-
- @include_dict
- def offset_to_dict(self):
- return {"offset": self.offset} if self.offset else {}
-
-
-class LimitMixin(BaseParamMixin):
- @cached_property
- def limit(self) -> int:
- limit_raw = self._data.get(LIMIT, None)
- return int(limit_raw) if limit_raw else 0
-
- @include_dict
- def limit_to_dict(self):
- return {"limit": self.limit} if self.limit else {}
-
-
-class CompareMixin(BaseParamMixin):
- @cached_property
- def compare(self) -> bool:
- _compare = self._data.get(COMPARE, None)
- return process_bool(_compare)
-
- @include_dict
- def compare_to_dict(self):
- return {"compare": self.compare} if self.compare else {}
-
- @cached_property
- def compare_to(self) -> bool:
- _compare_to = self._data.get(COMPARE_TO, None)
- return bool(_compare_to)
-
- @include_dict
- def compare_to_to_dict(self):
- return {"compare_to": self.compare_to} if self.compare_to else {}
-
-
class DateMixin(BaseParamMixin):
date_from_delta_mapping: Optional[dict[str, int]]
date_to_delta_mapping: Optional[dict[str, int]]
@@ -445,113 +361,13 @@ class EntitiesMixin(BaseParamMixin):
def data_warehouse_entities(self) -> list[Entity]:
return [entity for entity in self.entities if entity.type == TREND_FILTER_TYPE_DATA_WAREHOUSE]
- @cached_property
- def exclusions(self) -> list[ExclusionEntity]:
- _exclusions: list[ExclusionEntity] = []
- if self._data.get(EXCLUSIONS):
- exclusion_list = self._data.get(EXCLUSIONS, [])
- if isinstance(exclusion_list, str):
- exclusion_list = json.loads(exclusion_list)
-
- _exclusions.extend([ExclusionEntity({**entity}) for entity in exclusion_list if entity])
-
- return _exclusions
-
@include_dict
def entities_to_dict(self):
return {
**({"events": [entity.to_dict() for entity in self.events]} if len(self.events) > 0 else {}),
**({"actions": [entity.to_dict() for entity in self.actions]} if len(self.actions) > 0 else {}),
- **({"exclusions": [entity.to_dict() for entity in self.exclusions]} if len(self.exclusions) > 0 else {}),
}
@include_query_tags
def entities_query_tags(self):
return {"entity_math": list({entity.math for entity in self.entities if entity.math})}
-
-
-# These arguments are used to specify the target entity for insight actor retrieval on trend graphs
-class EntityIdMixin(BaseParamMixin):
- @cached_property
- def target_entity_id(self) -> Optional[str]:
- return self._data.get("entityId", None) or self._data.get("entity_id", None)
-
- @include_dict
- def entity_id_to_dict(self):
- return {"entity_id": self.target_entity_id} if self.target_entity_id else {}
-
-
-class EntityTypeMixin(BaseParamMixin):
- @cached_property
- def target_entity_type(self) -> Optional[str]:
- return self._data.get("type", None) or self._data.get("entity_type", None)
-
- @include_dict
- def entity_type_to_dict(self):
- return {"entity_type": self.target_entity_type} if self.target_entity_type else {}
-
-
-class EntityMathMixin(BaseParamMixin):
- @cached_property
- def target_entity_math(self) -> Optional[MathType]:
- return self._data.get("entity_math", None)
-
- @include_dict
- def entity_math_to_dict(self):
- return {"entity_math": self.target_entity_math} if self.target_entity_math else {}
-
-
-class EntityOrderMixin(BaseParamMixin):
- @cached_property
- def target_entity_order(self) -> Optional[str]:
- return self._data.get("entity_order", None) or self._data.get("target_entity_order", None)
-
- @include_dict
- def entity_order_to_dict(self):
- return {"entity_order": self.target_entity_order} if self.target_entity_order else {}
-
-
-class IncludeRecordingsMixin(BaseParamMixin):
- @cached_property
- def include_recordings(self) -> bool:
- include_recordings = self._data.get("include_recordings")
- return include_recordings is True or include_recordings == "true"
-
- @include_dict
- def include_recordings_to_dict(self):
- return {"include_recordings": self.include_recordings} if self.include_recordings else {}
-
-
-class SearchMixin(BaseParamMixin):
- @cached_property
- def search(self) -> Optional[str]:
- search = self._data.get("search", None)
- return search
-
- @include_dict
- def search_to_dict(self):
- return {"search": self.search} if self.search else {}
-
-
-class SampleMixin(BaseParamMixin):
- """
- Sample factor for a query.
- """
-
- @cached_property
- def sampling_factor(self) -> Optional[float]:
- sampling_factor = self._data.get("sampling_factor", None)
-
- # cover for both None and empty strings - also ok to filter out 0s here
- if sampling_factor:
- sampling_factor = float(sampling_factor)
- if sampling_factor < 0 or sampling_factor > 1:
- raise ValueError("Sampling factor must be greater than 0 and smaller or equal to 1")
-
- return sampling_factor
-
- return None
-
- @include_dict
- def sampling_factor_to_dict(self):
- return {SAMPLING_FACTOR: self.sampling_factor or ""}
diff --git a/posthog/models/filters/mixins/funnel.py b/posthog/models/filters/mixins/funnel.py
deleted file mode 100644
index d89db3a0c4db..000000000000
--- a/posthog/models/filters/mixins/funnel.py
+++ /dev/null
@@ -1,194 +0,0 @@
-import json
-from typing import Optional
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import (
- FUNNEL_CORRELATION_EVENT_EXCLUDE_PROPERTY_NAMES,
- FUNNEL_CORRELATION_EVENT_NAMES,
- FUNNEL_CORRELATION_EXCLUDE_EVENT_NAMES,
- FUNNEL_CORRELATION_EXCLUDE_NAMES,
- FUNNEL_CORRELATION_NAMES,
- FUNNEL_CORRELATION_TYPE,
- FUNNEL_CUSTOM_STEPS,
- FUNNEL_FROM_STEP,
- FUNNEL_STEP,
- FUNNEL_TO_STEP,
- FUNNEL_WINDOW_INTERVAL,
- FUNNEL_WINDOW_INTERVAL_TYPES,
- FUNNEL_WINDOW_INTERVAL_UNIT,
- FunnelCorrelationType,
-)
-from posthog.models.filters.mixins.base import BaseParamMixin, FunnelWindowIntervalType
-from posthog.models.filters.mixins.utils import cached_property, include_dict
-
-
-class FunnelFromToStepsMixin(BaseParamMixin):
- @cached_property
- def funnel_from_step(self) -> Optional[int]:
- if self._data.get(FUNNEL_FROM_STEP) is not None:
- return int(self._data[FUNNEL_FROM_STEP])
- return None
-
- @cached_property
- def funnel_to_step(self) -> Optional[int]:
- if self._data.get(FUNNEL_TO_STEP) is not None:
- return int(self._data[FUNNEL_TO_STEP])
- return None
-
- @include_dict
- def funnel_from_to_steps_to_dict(self):
- dict_part = {}
- if self.funnel_from_step is not None:
- dict_part[FUNNEL_FROM_STEP] = self.funnel_from_step
- if self.funnel_to_step is not None:
- dict_part[FUNNEL_TO_STEP] = self.funnel_to_step
- return dict_part
-
-
-class FunnelWindowMixin(BaseParamMixin):
- @cached_property
- def funnel_window_interval(self) -> Optional[int]:
- _amt = int(self._data.get(FUNNEL_WINDOW_INTERVAL, "0"))
- if _amt == 0:
- return None
- return _amt
-
- @cached_property
- def funnel_window_interval_unit(self) -> Optional[FunnelWindowIntervalType]:
- _unit = self._data.get(FUNNEL_WINDOW_INTERVAL_UNIT, None)
- return _unit.lower() if _unit is not None else _unit
-
- @include_dict
- def funnel_window_to_dict(self):
- dict_part: dict = {}
- if self.funnel_window_interval is not None:
- dict_part[FUNNEL_WINDOW_INTERVAL] = self.funnel_window_interval
- if self.funnel_window_interval_unit is not None:
- dict_part[FUNNEL_WINDOW_INTERVAL_UNIT] = self.funnel_window_interval_unit
- return dict_part
-
- def funnel_window_interval_unit_ch(self) -> FUNNEL_WINDOW_INTERVAL_TYPES:
- if self.funnel_window_interval_unit is None:
- return "DAY"
-
- if self.funnel_window_interval_unit == "second":
- return "SECOND"
- if self.funnel_window_interval_unit == "minute":
- return "MINUTE"
- elif self.funnel_window_interval_unit == "hour":
- return "HOUR"
- elif self.funnel_window_interval_unit == "week":
- return "WEEK"
- elif self.funnel_window_interval_unit == "month":
- return "MONTH"
- elif self.funnel_window_interval_unit == "day":
- return "DAY"
- else:
- raise ValidationError("{interval} not supported")
-
-
-class FunnelPersonsStepMixin(BaseParamMixin):
- # first step is 0
- # -1 means dropoff into step 1
- @cached_property
- def funnel_step(self) -> Optional[int]:
- """
- Specifies the step index within a funnel entities definition for which
- we want to get the `timestamp` for, per person.
- """
- _step_as_string = self._data.get(FUNNEL_STEP)
-
- if _step_as_string is None:
- return None
- return int(_step_as_string)
-
- @cached_property
- def funnel_custom_steps(self) -> list[int]:
- """
- Custom step numbers to get persons for. This overrides FunnelPersonsStepMixin::funnel_step
- """
- raw_steps = self._data.get(FUNNEL_CUSTOM_STEPS, [])
- if isinstance(raw_steps, str):
- return json.loads(raw_steps)
-
- return raw_steps
-
- @include_dict
- def funnel_step_to_dict(self):
- result: dict = {}
- if self.funnel_step is not None:
- result[FUNNEL_STEP] = self.funnel_step
- if self.funnel_custom_steps:
- result[FUNNEL_CUSTOM_STEPS] = self.funnel_custom_steps
- return result
-
-
-class FunnelCorrelationMixin(BaseParamMixin):
- @cached_property
- def correlation_type(self) -> Optional[FunnelCorrelationType]:
- raw_type = self._data.get(FUNNEL_CORRELATION_TYPE)
- if raw_type:
- try:
- return FunnelCorrelationType(raw_type)
- except ValueError:
- return None
-
- return None
-
- @cached_property
- def correlation_property_names(self) -> list[str]:
- # Person Property names for which to run Person Properties correlation
- property_names = self._data.get(FUNNEL_CORRELATION_NAMES, [])
- if isinstance(property_names, str):
- return json.loads(property_names)
- return property_names
-
- @cached_property
- def correlation_property_exclude_names(self) -> list[str]:
- # Person Property names to exclude from Person Properties correlation
- property_names = self._data.get(FUNNEL_CORRELATION_EXCLUDE_NAMES, [])
- if isinstance(property_names, str):
- return json.loads(property_names)
- return property_names
-
- @cached_property
- def correlation_event_names(self) -> list[str]:
- # Event names for which to run EventWithProperties correlation
- event_names = self._data.get(FUNNEL_CORRELATION_EVENT_NAMES, [])
- if isinstance(event_names, str):
- return json.loads(event_names)
- return event_names
-
- @cached_property
- def correlation_event_exclude_names(self) -> list[str]:
- # Exclude event names from Event correlation
- property_names = self._data.get(FUNNEL_CORRELATION_EXCLUDE_EVENT_NAMES, [])
- if isinstance(property_names, str):
- return json.loads(property_names)
- return property_names
-
- @cached_property
- def correlation_event_exclude_property_names(self) -> list[str]:
- # Event Property names to exclude from EventWithProperties correlation
- property_names = self._data.get(FUNNEL_CORRELATION_EVENT_EXCLUDE_PROPERTY_NAMES, [])
- if isinstance(property_names, str):
- return json.loads(property_names)
- return property_names
-
- @include_dict
- def funnel_correlation_to_dict(self):
- result_dict: dict = {}
- if self.correlation_type:
- result_dict[FUNNEL_CORRELATION_TYPE] = self.correlation_type
- if self.correlation_property_names:
- result_dict[FUNNEL_CORRELATION_NAMES] = self.correlation_property_names
- if self.correlation_property_exclude_names:
- result_dict[FUNNEL_CORRELATION_EXCLUDE_NAMES] = self.correlation_property_exclude_names
- if self.correlation_event_names:
- result_dict[FUNNEL_CORRELATION_EVENT_NAMES] = self.correlation_event_names
- if self.correlation_event_exclude_names:
- result_dict[FUNNEL_CORRELATION_EXCLUDE_EVENT_NAMES] = self.correlation_event_exclude_names
- if self.correlation_event_exclude_property_names:
- result_dict[FUNNEL_CORRELATION_EVENT_EXCLUDE_PROPERTY_NAMES] = self.correlation_event_exclude_property_names
- return result_dict
diff --git a/posthog/models/filters/mixins/paths.py b/posthog/models/filters/mixins/paths.py
deleted file mode 100644
index ed898062682f..000000000000
--- a/posthog/models/filters/mixins/paths.py
+++ /dev/null
@@ -1,266 +0,0 @@
-import json
-from typing import Literal, Optional
-
-from posthog.constants import (
- CUSTOM_EVENT,
- END_POINT,
- FUNNEL_PATHS,
- HOGQL,
- LOCAL_PATH_CLEANING_FILTERS,
- PAGEVIEW_EVENT,
- PATH_DROPOFF_KEY,
- PATH_EDGE_LIMIT,
- PATH_END_KEY,
- PATH_GROUPINGS,
- PATH_MAX_EDGE_WEIGHT,
- PATH_MIN_EDGE_WEIGHT,
- PATH_REPLACEMENTS,
- PATH_START_KEY,
- PATH_TYPE,
- PATHS_EXCLUDE_EVENTS,
- PATHS_HOGQL_EXPRESSION,
- PATHS_INCLUDE_CUSTOM_EVENTS,
- PATHS_INCLUDE_EVENT_TYPES,
- SCREEN_EVENT,
- START_POINT,
- STEP_LIMIT,
-)
-from posthog.models.filters.mixins.common import BaseParamMixin
-from posthog.models.filters.mixins.utils import cached_property, include_dict
-
-PathType = Literal["$pageview", "$screen", "custom_event"]
-
-FunnelPathsType = Literal["funnel_path_before_step", "funnel_path_between_steps", "funnel_path_after_step"]
-
-
-def remove_trailing_slash(input: Optional[str]) -> Optional[str]:
- if input and len(input) > 1 and input.endswith("/"):
- return input[:-1]
- return input
-
-
-class PathTypeMixin(BaseParamMixin):
- @cached_property
- def path_type(self) -> Optional[PathType]:
- return self._data.get(PATH_TYPE, None)
-
- @include_dict
- def path_type_to_dict(self):
- return {"path_type": self.path_type} if self.path_type else {}
-
-
-class StartPointMixin(BaseParamMixin):
- @cached_property
- def start_point(self) -> Optional[str]:
- return remove_trailing_slash(self._data.get(START_POINT, None))
-
- @include_dict
- def start_point_to_dict(self):
- return {"start_point": self.start_point} if self.start_point else {}
-
-
-class EndPointMixin(BaseParamMixin):
- @cached_property
- def end_point(self) -> Optional[str]:
- return remove_trailing_slash(self._data.get(END_POINT, None))
-
- @include_dict
- def end_point_to_dict(self):
- return {"end_point": self.end_point} if self.end_point else {}
-
-
-class PathsHogQLExpressionMixin(PathTypeMixin):
- @cached_property
- def paths_hogql_expression(self) -> Optional[str]:
- if self.path_type == HOGQL or HOGQL in self._data.get(PATHS_INCLUDE_EVENT_TYPES, []):
- return self._data.get(PATHS_HOGQL_EXPRESSION, "event")
- else:
- return None
-
- @include_dict
- def paths_hogql_expression_to_dict(self):
- return {"paths_hogql_expression": self.paths_hogql_expression} if self.paths_hogql_expression else {}
-
-
-class TargetEventsMixin(BaseParamMixin):
- @cached_property
- def target_events(self) -> list[str]:
- target_events = self._data.get(PATHS_INCLUDE_EVENT_TYPES, [])
- if isinstance(target_events, str):
- return json.loads(target_events)
- return target_events
-
- @cached_property
- def custom_events(self) -> list[str]:
- custom_events = self._data.get(PATHS_INCLUDE_CUSTOM_EVENTS, [])
- if isinstance(custom_events, str):
- return json.loads(custom_events)
- return custom_events
-
- @cached_property
- def exclude_events(self) -> list[str]:
- _exclude_events = self._data.get(PATHS_EXCLUDE_EVENTS, [])
- if isinstance(_exclude_events, str):
- return json.loads(_exclude_events)
-
- return _exclude_events
-
- @property
- def include_pageviews(self) -> bool:
- return PAGEVIEW_EVENT in self.target_events
-
- @property
- def include_screenviews(self) -> bool:
- return SCREEN_EVENT in self.target_events
-
- @property
- def include_all_custom_events(self) -> bool:
- return CUSTOM_EVENT in self.target_events
-
- @property
- def include_hogql(self) -> bool:
- return HOGQL in self.target_events
-
- @include_dict
- def target_events_to_dict(self) -> dict:
- result = {}
- if self.target_events:
- result[PATHS_INCLUDE_EVENT_TYPES] = self.target_events
-
- if self.custom_events:
- result[PATHS_INCLUDE_CUSTOM_EVENTS] = self.custom_events
-
- if self.exclude_events:
- result[PATHS_EXCLUDE_EVENTS] = self.exclude_events
- return result
-
-
-class PathStepLimitMixin(BaseParamMixin):
- @cached_property
- def step_limit(self) -> Optional[int]:
- if self._data.get(STEP_LIMIT) is not None:
- return int(self._data[STEP_LIMIT])
- return None
-
- @include_dict
- def step_limit_to_dict(self):
- return {"step_limit": self.step_limit} if self.step_limit else {}
-
-
-class FunnelPathsMixin(BaseParamMixin):
- @cached_property
- def funnel_paths(self) -> Optional[FunnelPathsType]:
- _funnel_paths = self._data.get(FUNNEL_PATHS, None)
- return _funnel_paths
-
- @include_dict
- def funnel_paths_to_dict(self):
- return {"funnel_paths": self.funnel_paths} if self.funnel_paths else {}
-
-
-class PathGroupingMixin(BaseParamMixin):
- @cached_property
- def path_groupings(self) -> Optional[list[str]]:
- path_groupings = self._data.get(PATH_GROUPINGS, None)
- if isinstance(path_groupings, str):
- return json.loads(path_groupings)
-
- return path_groupings
-
- @include_dict
- def path_groupings_to_dict(self):
- return {PATH_GROUPINGS: self.path_groupings} if self.path_groupings else {}
-
-
-class PathReplacementMixin(BaseParamMixin):
- @cached_property
- def path_replacements(self) -> bool:
- path_replacements = self._data.get(PATH_REPLACEMENTS)
- if not path_replacements:
- return False
- if path_replacements is True:
- return True
-
- if isinstance(path_replacements, str) and path_replacements.lower() == "true":
- return True
-
- return False
-
- @include_dict
- def path_replacements_to_dict(self):
- return {PATH_REPLACEMENTS: self.path_replacements} if self.path_replacements else {}
-
-
-class LocalPathCleaningFiltersMixin(BaseParamMixin):
- @cached_property
- def local_path_cleaning_filters(self) -> Optional[list[dict[str, str]]]:
- local_path_cleaning_filters = self._data.get(LOCAL_PATH_CLEANING_FILTERS, None)
- if isinstance(local_path_cleaning_filters, str):
- return json.loads(local_path_cleaning_filters)
-
- return local_path_cleaning_filters
-
- @include_dict
- def local_path_cleaning_filters_to_dict(self):
- return (
- {LOCAL_PATH_CLEANING_FILTERS: self.local_path_cleaning_filters} if self.local_path_cleaning_filters else {}
- )
-
-
-class PathPersonsMixin(BaseParamMixin):
- @cached_property
- def path_start_key(self) -> Optional[str]:
- return self._data.get(PATH_START_KEY)
-
- @cached_property
- def path_end_key(self) -> Optional[str]:
- return self._data.get(PATH_END_KEY)
-
- @cached_property
- def path_dropoff_key(self) -> Optional[str]:
- return self._data.get(PATH_DROPOFF_KEY)
-
- @include_dict
- def path_start_end_to_dict(self):
- result = {}
- if self.path_start_key:
- result[PATH_START_KEY] = self.path_start_key
-
- if self.path_end_key:
- result[PATH_END_KEY] = self.path_end_key
-
- if self.path_dropoff_key:
- result[PATH_DROPOFF_KEY] = self.path_dropoff_key
-
- return result
-
-
-class PathLimitsMixin(BaseParamMixin):
- @cached_property
- def edge_limit(self) -> Optional[int]:
- raw_value = self._data.get(PATH_EDGE_LIMIT, None)
- return int(raw_value) if raw_value is not None else None
-
- @cached_property
- def min_edge_weight(self) -> Optional[int]:
- raw_value = self._data.get(PATH_MIN_EDGE_WEIGHT, None)
- return int(raw_value) if raw_value else None
-
- @cached_property
- def max_edge_weight(self) -> Optional[int]:
- raw_value = self._data.get(PATH_MAX_EDGE_WEIGHT, None)
- return int(raw_value) if raw_value else None
-
- @include_dict
- def path_edge_limit_to_dict(self):
- result = {}
- if self.edge_limit:
- result[PATH_EDGE_LIMIT] = self.edge_limit
-
- if self.min_edge_weight:
- result[PATH_MIN_EDGE_WEIGHT] = self.min_edge_weight
-
- if self.max_edge_weight:
- result[PATH_MAX_EDGE_WEIGHT] = self.max_edge_weight
-
- return result
diff --git a/posthog/models/filters/mixins/retention.py b/posthog/models/filters/mixins/retention.py
deleted file mode 100644
index 9dc737fbbcca..000000000000
--- a/posthog/models/filters/mixins/retention.py
+++ /dev/null
@@ -1,153 +0,0 @@
-import json
-from datetime import datetime, timedelta
-from typing import Literal, Optional, Union
-
-from django.utils import timezone
-
-from dateutil.relativedelta import relativedelta
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import (
- PERIOD,
- RETENTION_RECURRING,
- RETENTION_TYPE,
- RETURNING_ENTITY,
- SELECTED_INTERVAL,
- TARGET_ENTITY,
- TOTAL_INTERVALS,
- TREND_FILTER_TYPE_EVENTS,
-)
-from posthog.models.entity import Entity
-from posthog.models.filters.mixins.common import BaseParamMixin, DateMixin, EntitiesMixin
-from posthog.models.filters.mixins.utils import cached_property, include_dict
-from posthog.utils import relative_date_parse
-
-
-class RetentionTypeMixin(BaseParamMixin):
- @cached_property
- def retention_type(self) -> Literal["retention_recurring", "retention_first_time"]:
- return self._data.get(RETENTION_TYPE, RETENTION_RECURRING)
-
- @include_dict
- def retention_type_to_dict(self):
- return {"retention_type": self.retention_type}
-
-
-RETENTION_DEFAULT_INTERVALS = 11
-
-
-class TotalIntervalsMixin(BaseParamMixin):
- @cached_property
- def total_intervals(self) -> int:
- return int(self._data.get(TOTAL_INTERVALS, RETENTION_DEFAULT_INTERVALS))
-
- @include_dict
- def total_intervals_to_dict(self):
- return {"total_intervals": self.total_intervals} if self.total_intervals else {}
-
-
-class SelectedIntervalMixin(BaseParamMixin):
- @cached_property
- def selected_interval(self) -> int:
- return int(self._data.get(SELECTED_INTERVAL, 0))
-
- @include_dict
- def selected_interval_to_dict(self):
- return {"selected_interval": self.selected_interval} if self.selected_interval else {}
-
-
-class PeriodMixin(BaseParamMixin):
- @cached_property
- def period(self) -> str:
- return self._data.get(PERIOD, "Day")
-
- @include_dict
- def period_to_dict(self):
- return {"period": self.period} if self.period else {}
-
-
-class RetentionDateDerivedMixin(PeriodMixin, TotalIntervalsMixin, DateMixin, SelectedIntervalMixin):
- @cached_property
- def date_from(self) -> datetime:
- tdelta, _ = RetentionDateDerivedMixin.determine_time_delta(self.total_intervals, self.period)
- if self.period == "Hour":
- return self.date_to - tdelta
- elif self.period == "Week":
- date_from: datetime = self.date_to - tdelta
- week_start_alignment_days = date_from.isoweekday() % 7
- if team := getattr(self, "team", None):
- from posthog.models.team.team import WeekStartDay
-
- if team.week_start_day == WeekStartDay.MONDAY:
- week_start_alignment_days = date_from.weekday()
- return date_from - timedelta(days=week_start_alignment_days)
- else:
- date_to: datetime = self.date_to.replace(hour=0, minute=0, second=0, microsecond=0)
- return date_to - tdelta
-
- @cached_property
- def date_to(self) -> datetime:
- if self._date_to:
- if isinstance(self._date_to, str):
- date_to = relative_date_parse(self._date_to, self.team.timezone_info) # type: ignore
- else:
- date_to = self._date_to
- else:
- date_to = timezone.now()
-
- date_to = date_to + self.period_increment
- if self.period == "Hour":
- return date_to.replace(minute=0, second=0, microsecond=0)
- else:
- return date_to.replace(hour=0, minute=0, second=0, microsecond=0)
-
- @cached_property
- def period_increment(self) -> Union[timedelta, relativedelta]:
- _, t1 = RetentionDateDerivedMixin.determine_time_delta(self.total_intervals, self.period)
- return t1
-
- @staticmethod
- def determine_time_delta(
- total_intervals: int, period: str
- ) -> tuple[Union[timedelta, relativedelta], Union[timedelta, relativedelta]]:
- if period == "Hour":
- return timedelta(hours=total_intervals), timedelta(hours=1)
- elif period == "Week":
- return timedelta(weeks=total_intervals), timedelta(weeks=1)
- elif period == "Month":
- return relativedelta(months=total_intervals), relativedelta(months=1)
- elif period == "Day":
- return timedelta(days=total_intervals), timedelta(days=1)
- else:
- raise ValidationError(f"Period {period} is unsupported.")
-
-
-class EntitiesDerivedMixin(EntitiesMixin):
- @cached_property
- def target_entity(self) -> Entity:
- return self._parse_entity(self._data.get(TARGET_ENTITY)) or Entity(
- {"id": "$pageview", "type": TREND_FILTER_TYPE_EVENTS}
- )
-
- @include_dict
- def target_entity_to_dict(self):
- return {"target_entity": self.target_entity.to_dict()} if self.target_entity else {}
-
- def _parse_entity(self, entity_data) -> Optional[Entity]:
- if entity_data:
- if isinstance(entity_data, str):
- _data = json.loads(entity_data)
- else:
- _data = entity_data
- return Entity({"id": _data["id"], "type": _data["type"]})
- return None
-
- @cached_property
- def returning_entity(self) -> Entity:
- if self._data.get(RETURNING_ENTITY):
- return self._parse_entity(self._data[RETURNING_ENTITY]) or self.target_entity
- return self.target_entity
-
- @include_dict
- def returning_entity_to_dict(self):
- return {"returning_entity": self.returning_entity.to_dict()} if self.returning_entity else {}
diff --git a/posthog/models/filters/mixins/simplify.py b/posthog/models/filters/mixins/simplify.py
deleted file mode 100644
index 68bf81747d6e..000000000000
--- a/posthog/models/filters/mixins/simplify.py
+++ /dev/null
@@ -1,107 +0,0 @@
-from typing import TYPE_CHECKING, Any, Literal, cast
-
-from posthog.constants import PropertyOperatorType
-from posthog.models.property import GroupTypeIndex, PropertyGroup
-
-if TYPE_CHECKING: # Avoid circular import
- from posthog.models import Property, Team
-
-
-class SimplifyFilterMixin:
- # :KLUDGE: A lot of this logic ignores typing since generics w/ mixins are hard to get working properly
- def simplify(self, team: "Team", **kwargs) -> Any:
- """
- Expands this filter to not refer to external resources of the team.
-
- Actions taken:
- - if filter.filter_test_accounts, adds property filters to `filter.properties`
- - if aggregating by groups, adds property filter to remove blank groups
- - for cohort properties, replaces them with more concrete lookups or with cohort conditions
- """
- self_any = cast(Any, self)
-
- if self_any._data.get("is_simplified"):
- return self
-
- # :TRICKY: Make a copy to avoid caching issues
- result: Any = self_any.shallow_clone({"is_simplified": True})
-
- if getattr(result, "filter_test_accounts", False):
- new_group = {"type": "AND", "values": team.test_account_filters}
- prop_group = (
- {"type": "AND", "values": [new_group, result.property_groups.to_dict()]}
- if result.property_groups.to_dict()
- else new_group
- )
- result = result.shallow_clone({"properties": prop_group, "filter_test_accounts": False})
-
- updated_entities = {}
- if hasattr(result, "entities_to_dict"):
- for entity_type, entities in result.entities_to_dict().items():
- updated_entities[entity_type] = [
- result._simplify_entity(team, entity_type, entity, **kwargs) for entity in entities
- ]
-
- from posthog.models.property.util import clear_excess_levels
-
- prop_group = clear_excess_levels(
- result._simplify_property_group(team, result.property_groups, **kwargs),
- skip=True,
- )
- prop_group = prop_group.to_dict()
-
- new_group_props = []
- if getattr(result, "aggregation_group_type_index", None) is not None:
- new_group_props.append(
- result._group_set_property(cast(GroupTypeIndex, result.aggregation_group_type_index)).to_dict()
- )
-
- if new_group_props:
- new_group = {"type": "AND", "values": new_group_props}
- prop_group = {"type": "AND", "values": [new_group, prop_group]} if prop_group else new_group
-
- return result.shallow_clone({**updated_entities, "properties": prop_group})
-
- def _simplify_entity(
- self,
- team: "Team",
- entity_type: Literal["events", "actions", "exclusions"],
- entity_params: dict,
- **kwargs,
- ) -> dict:
- from posthog.models.entity import Entity, ExclusionEntity
-
- EntityClass = ExclusionEntity if entity_type == "exclusions" else Entity
-
- entity = EntityClass(entity_params)
- # TODO: when we support AND-ORs in entities, unflatten them here
- properties = self._simplify_properties(team, entity.property_groups.flat, **kwargs).flat
- if entity.math == "unique_group":
- properties.append(self._group_set_property(cast(GroupTypeIndex, entity.math_group_type_index)))
-
- return EntityClass({**entity_params, "properties": properties}).to_dict()
-
- def _simplify_properties(self, team: "Team", properties: list["Property"], **kwargs) -> "PropertyGroup":
- simplified_properties_values = []
- for prop in properties:
- simplified_properties_values.append(self._simplify_property(team, prop, **kwargs))
- return PropertyGroup(type=PropertyOperatorType.AND, values=simplified_properties_values)
-
- def _simplify_property_group(self, team: "Team", prop_group: "PropertyGroup", **kwargs) -> "PropertyGroup":
- from posthog.models.property.parse import expand_cohort_group
-
- return expand_cohort_group(prop_group, team)
-
- def _simplify_property(self, team: "Team", property: "Property", **kwargs) -> "PropertyGroup":
- from posthog.models.property.parse import expand_cohort_property
-
- return expand_cohort_property(property, team)
-
- def _group_set_property(self, group_type_index: GroupTypeIndex) -> "Property":
- from posthog.models.property import Property
-
- return Property(key=f"$group_{group_type_index}", value="", operator="is_not")
-
- @property
- def is_simplified(self) -> bool:
- return cast(dict[str, Any], getattr(self, "_data", {})).get("is_simplified", False)
diff --git a/posthog/models/filters/mixins/stickiness.py b/posthog/models/filters/mixins/stickiness.py
deleted file mode 100644
index 635e632f32df..000000000000
--- a/posthog/models/filters/mixins/stickiness.py
+++ /dev/null
@@ -1,83 +0,0 @@
-from collections.abc import Callable
-from datetime import datetime
-from typing import TYPE_CHECKING, Optional, Union
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import DATE_FROM, DATE_TO, STICKINESS_DAYS
-from posthog.models.filters.mixins.common import BaseParamMixin, DateMixin
-from posthog.models.filters.mixins.interval import IntervalMixin
-from posthog.models.filters.mixins.utils import cached_property, include_dict
-from posthog.utils import relative_date_parse
-
-if TYPE_CHECKING:
- from posthog.models.team import Team
-
-
-class SelectedIntervalMixin(BaseParamMixin):
- @cached_property
- def selected_interval(self) -> int:
- return int(self._data.get(STICKINESS_DAYS, "0")) or int(self._data.get("selected_interval", "0"))
-
- @include_dict
- def selected_interval_to_dict(self):
- return {"selected_interval": self.selected_interval} if self.selected_interval else {}
-
-
-class StickinessDateMixin(DateMixin):
- get_earliest_timestamp: Optional[Callable]
- team: "Team"
-
- @cached_property
- def _date_from(self) -> Optional[Union[str, datetime]]:
- if not self.team:
- raise AttributeError("StickinessDateMixin requires team to be provided")
-
- _date_from = self._data.get(DATE_FROM, None)
- if _date_from == "all":
- if not self.get_earliest_timestamp:
- raise ValidationError(
- "get_earliest_timestamp: Callable must be provided when date filtering is all time"
- )
- return self.get_earliest_timestamp(team_id=self.team.pk)
- elif _date_from:
- return _date_from
- else:
- return relative_date_parse("-7d", self.team.timezone_info)
-
- @cached_property
- def _date_to(self) -> Optional[Union[str, datetime]]:
- return self._data.get(DATE_TO)
-
-
-class TotalIntervalsDerivedMixin(IntervalMixin, StickinessDateMixin):
- """
- Properties
- -----------
- - total_intervals
- - date_from (inherited)
- - date_to (inherited)
- - interval (inherited)
- """
-
- @cached_property
- def total_intervals(self) -> int:
- assert self.date_from is not None
- assert self.date_to is not None
-
- _num_intervals = 0
- _total_seconds = (self.date_to - self.date_from).total_seconds()
- if self.interval == "hour":
- _num_intervals = int(divmod(_total_seconds, 3600)[0])
- elif self.interval == "day":
- _num_intervals = int(divmod(_total_seconds, 86400)[0])
- elif self.interval == "week":
- _num_intervals = (self.date_to - self.date_from).days // 7
- elif self.interval == "month":
- _num_intervals = (self.date_to.year - self.date_from.year) * 12 + (
- self.date_to.month - self.date_from.month
- )
- else:
- raise ValidationError(f"{self.interval} not supported")
- _num_intervals += 2
- return _num_intervals
diff --git a/posthog/models/filters/path_filter.py b/posthog/models/filters/path_filter.py
deleted file mode 100644
index 6f80c621e6fa..000000000000
--- a/posthog/models/filters/path_filter.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from typing import Any, Optional
-
-from rest_framework.request import Request
-
-from posthog.constants import INSIGHT_PATHS
-
-from .base_filter import BaseFilter
-from .mixins.common import (
- BreakdownMixin,
- ClientQueryIdMixin,
- DateMixin,
- EntitiesMixin,
- FilterTestAccountsMixin,
- IncludeRecordingsMixin,
- InsightMixin,
- LimitMixin,
- OffsetMixin,
- SampleMixin,
- SearchMixin,
-)
-from .mixins.funnel import FunnelCorrelationMixin, FunnelPersonsStepMixin, FunnelWindowMixin
-from .mixins.groups import GroupsAggregationMixin
-from .mixins.interval import IntervalMixin
-from .mixins.paths import (
- EndPointMixin,
- FunnelPathsMixin,
- LocalPathCleaningFiltersMixin,
- PathGroupingMixin,
- PathLimitsMixin,
- PathPersonsMixin,
- PathReplacementMixin,
- PathsHogQLExpressionMixin,
- PathStepLimitMixin,
- StartPointMixin,
- TargetEventsMixin,
-)
-from .mixins.property import PropertyMixin
-from .mixins.simplify import SimplifyFilterMixin
-
-
-class PathFilter(
- StartPointMixin,
- EndPointMixin,
- PropertyMixin,
- IntervalMixin,
- InsightMixin,
- FilterTestAccountsMixin,
- DateMixin,
- BreakdownMixin,
- EntitiesMixin,
- PathsHogQLExpressionMixin,
- PathStepLimitMixin,
- FunnelPathsMixin,
- TargetEventsMixin,
- FunnelWindowMixin,
- FunnelPersonsStepMixin,
- PathGroupingMixin,
- PathReplacementMixin,
- LocalPathCleaningFiltersMixin,
- PathPersonsMixin,
- LimitMixin,
- OffsetMixin,
- PathLimitsMixin,
- GroupsAggregationMixin,
- FunnelCorrelationMixin, # Kept so all filter classes expose the same attribute surface
- ClientQueryIdMixin,
- SimplifyFilterMixin,
- IncludeRecordingsMixin,
- SearchMixin,
- # TODO: proper fix for EventQuery abstraction
- BaseFilter,
- SampleMixin,
-):
- def __init__(
- self,
- data: Optional[dict[str, Any]] = None,
- request: Optional[Request] = None,
- **kwargs,
- ) -> None:
- if data:
- data["insight"] = INSIGHT_PATHS
- else:
- data = {"insight": INSIGHT_PATHS}
- super().__init__(data, request, **kwargs)
diff --git a/posthog/models/filters/retention_filter.py b/posthog/models/filters/retention_filter.py
deleted file mode 100644
index 5133cab77a87..000000000000
--- a/posthog/models/filters/retention_filter.py
+++ /dev/null
@@ -1,70 +0,0 @@
-import json
-from typing import Any, Optional, Union
-
-from rest_framework.request import Request
-
-from posthog.constants import INSIGHT_RETENTION
-
-from .base_filter import BaseFilter
-from .mixins.common import (
- BreakdownMixin,
- ClientQueryIdMixin,
- DisplayDerivedMixin,
- FilterTestAccountsMixin,
- InsightMixin,
- LimitMixin,
- OffsetMixin,
- SampleMixin,
-)
-from .mixins.funnel import FunnelCorrelationMixin
-from .mixins.groups import GroupsAggregationMixin
-from .mixins.property import PropertyMixin
-from .mixins.retention import EntitiesDerivedMixin, RetentionDateDerivedMixin, RetentionTypeMixin
-from .mixins.simplify import SimplifyFilterMixin
-from .mixins.utils import cached_property, include_dict
-
-RETENTION_DEFAULT_INTERVALS = 11
-
-
-class RetentionFilter(
- RetentionTypeMixin,
- EntitiesDerivedMixin,
- RetentionDateDerivedMixin,
- PropertyMixin,
- DisplayDerivedMixin,
- FilterTestAccountsMixin,
- BreakdownMixin,
- InsightMixin,
- OffsetMixin,
- LimitMixin,
- GroupsAggregationMixin,
- FunnelCorrelationMixin, # Kept so all filter classes expose the same attribute surface
- # TODO: proper fix for EventQuery abstraction, make filters uniform
- ClientQueryIdMixin,
- SimplifyFilterMixin,
- SampleMixin,
- BaseFilter,
-):
- def __init__(self, data: Optional[dict[str, Any]] = None, request: Optional[Request] = None, **kwargs) -> None:
- if data is None:
- data = {}
- if data:
- data["insight"] = INSIGHT_RETENTION
- else:
- data = {"insight": INSIGHT_RETENTION}
- super().__init__(data, request, **kwargs)
-
- @cached_property
- def breakdown_values(self) -> Optional[tuple[Union[str, int], ...]]:
- raw_value = self._data.get("breakdown_values", None)
- if raw_value is None:
- return None
-
- if isinstance(raw_value, str):
- return tuple(json.loads(raw_value))
-
- return tuple(raw_value)
-
- @include_dict
- def breakdown_values_to_dict(self):
- return {"breakdown_values": self.breakdown_values} if self.breakdown_values else {}
diff --git a/posthog/models/filters/stickiness_filter.py b/posthog/models/filters/stickiness_filter.py
deleted file mode 100644
index b13b23f6812b..000000000000
--- a/posthog/models/filters/stickiness_filter.py
+++ /dev/null
@@ -1,87 +0,0 @@
-from collections.abc import Callable
-from typing import TYPE_CHECKING, Any, Optional, Union
-
-from django.db.models.functions.datetime import TruncDay, TruncHour, TruncMonth, TruncWeek
-
-from rest_framework.exceptions import ValidationError
-from rest_framework.request import Request
-
-from posthog.constants import INSIGHT_STICKINESS
-
-from .base_filter import BaseFilter
-from .mixins.common import (
- ClientQueryIdMixin,
- CompareMixin,
- EntitiesMixin,
- EntityIdMixin,
- EntityMathMixin,
- EntityOrderMixin,
- EntityTypeMixin,
- FilterTestAccountsMixin,
- InsightMixin,
- LimitMixin,
- OffsetMixin,
- SampleMixin,
- SearchMixin,
- ShownAsMixin,
-)
-from .mixins.property import PropertyMixin
-from .mixins.simplify import SimplifyFilterMixin
-from .mixins.stickiness import SelectedIntervalMixin, TotalIntervalsDerivedMixin
-
-if TYPE_CHECKING:
- from posthog.models.team import Team
-
-
-class StickinessFilter(
- TotalIntervalsDerivedMixin,
- EntitiesMixin,
- EntityIdMixin,
- EntityTypeMixin,
- EntityOrderMixin,
- EntityMathMixin,
- SelectedIntervalMixin,
- SearchMixin,
- PropertyMixin,
- FilterTestAccountsMixin,
- OffsetMixin,
- CompareMixin,
- ShownAsMixin,
- InsightMixin,
- SimplifyFilterMixin,
- LimitMixin,
- ClientQueryIdMixin,
- SampleMixin,
- BaseFilter,
-):
- get_earliest_timestamp: Optional[Callable]
- team: "Team"
-
- def __init__(
- self,
- data: Optional[dict[str, Any]] = None,
- request: Optional[Request] = None,
- **kwargs,
- ) -> None:
- if data:
- data["insight"] = INSIGHT_STICKINESS
- else:
- data = {"insight": INSIGHT_STICKINESS}
- super().__init__(data, request, **kwargs)
- team: Optional[Team] = kwargs.get("team", None)
- if not team:
- raise ValidationError("Team must be provided to stickiness filter")
- self.team = team
- self.get_earliest_timestamp = kwargs.get("get_earliest_timestamp", None)
-
- def trunc_func(self, field_name: str) -> Union[TruncHour, TruncDay, TruncWeek, TruncMonth]:
- if self.interval == "hour":
- return TruncHour(field_name)
- elif self.interval == "day":
- return TruncDay(field_name)
- elif self.interval == "week":
- return TruncWeek(field_name)
- elif self.interval == "month":
- return TruncMonth(field_name)
- else:
- raise ValidationError(f"{self.interval} not supported")
diff --git a/posthog/models/filters/test/test_path_filter.py b/posthog/models/filters/test/test_path_filter.py
deleted file mode 100644
index fb11df9fd5c0..000000000000
--- a/posthog/models/filters/test/test_path_filter.py
+++ /dev/null
@@ -1,72 +0,0 @@
-from posthog.test.base import BaseTest
-
-from posthog.models.filters import PathFilter
-
-
-class TestPathFilter(BaseTest):
- def test_to_dict(self):
- filter = PathFilter(
- data={
- "date_from": "-14d",
- "exclude_events": [],
- "include_custom_events": ["potato"],
- "filter_test_accounts": False,
- "include_event_types": ["$pageview", "$screen", "custom_event"],
- "insight": "PATHS",
- "start_point": "https://www.random.com/pricing/",
- "step_limit": 3,
- "sampling_factor": 0.1,
- }
- )
-
- self.assertEqual(
- filter.to_dict(),
- filter.to_dict()
- | {
- "date_from": "-14d",
- "include_event_types": ["$pageview", "$screen", "custom_event"],
- "insight": "PATHS",
- "start_point": "https://www.random.com/pricing",
- "step_limit": 3,
- "include_custom_events": ["potato"],
- # always included defaults
- "breakdown_attribution_type": "first_touch",
- "breakdown_normalize_url": False,
- "interval": "day",
- "sampling_factor": 0.1,
- },
- )
-
- def test_to_dict_hogql(self):
- filter = PathFilter(
- data={
- "date_from": "-14d",
- "exclude_events": [],
- "include_custom_events": ["potato"],
- "filter_test_accounts": False,
- "include_event_types": ["$pageview", "hogql"],
- "insight": "PATHS",
- "start_point": "https://www.random.com/pricing/",
- "step_limit": 3,
- "sampling_factor": 0.1,
- }
- )
-
- self.assertEqual(
- filter.to_dict(),
- filter.to_dict()
- | {
- "date_from": "-14d",
- "include_event_types": ["$pageview", "hogql"],
- "insight": "PATHS",
- "start_point": "https://www.random.com/pricing",
- "step_limit": 3,
- "include_custom_events": ["potato"],
- # always included defaults
- "breakdown_attribution_type": "first_touch",
- "breakdown_normalize_url": False,
- "interval": "day",
- "sampling_factor": 0.1,
- "paths_hogql_expression": "event",
- },
- )
diff --git a/posthog/models/filters/test/test_retention_filter.py b/posthog/models/filters/test/test_retention_filter.py
deleted file mode 100644
index efcc17e4d899..000000000000
--- a/posthog/models/filters/test/test_retention_filter.py
+++ /dev/null
@@ -1,125 +0,0 @@
-import time_machine
-from posthog.test.base import BaseTest
-
-from posthog.models.filters.retention_filter import RetentionFilter
-
-
-class TestFilter(BaseTest):
- maxDiff = None
-
- def test_fill_date_from_and_date_to(self):
- with time_machine.travel("2020-10-01T12:00:00Z", tick=False):
- filter = RetentionFilter(data={}, team=self.team)
- self.assertEqual(filter.date_from.isoformat(), "2020-09-21T00:00:00+00:00")
- self.assertEqual(filter.date_to.isoformat(), "2020-10-02T00:00:00+00:00")
- #  Make sure these dates aren't present in final filter to ensure rolling retention
- assert filter.to_dict() == {
- "display": "ActionsTable",
- "date_from": "-7d",
- "insight": "RETENTION",
- "period": "Day",
- "retention_type": "retention_recurring",
- "total_intervals": 11,
- "returning_entity": {
- "distinct_id_field": None,
- "id": "$pageview",
- "id_field": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_property_revenue_currency": None,
- "math_group_type_index": None,
- "name": "$pageview",
- "custom_name": None,
- "order": None,
- "properties": {},
- "table_name": None,
- "timestamp_field": None,
- "type": "events",
- },
- "target_entity": {
- "distinct_id_field": None,
- "id": "$pageview",
- "id_field": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_property_revenue_currency": None,
- "math_group_type_index": None,
- "name": "$pageview",
- "custom_name": None,
- "order": None,
- "properties": {},
- "table_name": None,
- "timestamp_field": None,
- "type": "events",
- },
- "breakdown_attribution_type": "first_touch",
- "breakdown_normalize_url": False,
- "sampling_factor": "",
- }
-
- with time_machine.travel("2020-10-01T12:00:00Z", tick=False):
- filter = RetentionFilter(data={"date_to": "2020-08-01"}, team=self.team)
- self.assertEqual(filter.date_from.isoformat(), "2020-07-22T00:00:00+00:00")
- self.assertEqual(filter.date_to.isoformat(), "2020-08-02T00:00:00+00:00")
- #  Make sure these dates aren't present in final filter to ensure rolling retention
-
- # The date_to below is the base value that's provided when the object was created (_date_to).
- # It doesn't match the date_to above because the retention filter will transform date_to to include one period ahead
- assert filter.to_dict() == {
- "date_to": "2020-08-01",
- "display": "ActionsTable",
- "insight": "RETENTION",
- "period": "Day",
- "retention_type": "retention_recurring",
- "total_intervals": 11,
- "returning_entity": {
- "distinct_id_field": None,
- "id": "$pageview",
- "id_field": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_property_revenue_currency": None,
- "math_group_type_index": None,
- "name": "$pageview",
- "custom_name": None,
- "order": None,
- "properties": {},
- "table_name": None,
- "timestamp_field": None,
- "type": "events",
- },
- "target_entity": {
- "distinct_id_field": None,
- "id": "$pageview",
- "id_field": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_property_revenue_currency": None,
- "math_group_type_index": None,
- "name": "$pageview",
- "custom_name": None,
- "order": None,
- "properties": {},
- "table_name": None,
- "timestamp_field": None,
- "type": "events",
- },
- "breakdown_attribution_type": "first_touch",
- "date_from": "-7d",
- "breakdown_normalize_url": False,
- "sampling_factor": "",
- }
-
- def test_entities(self):
- filter = RetentionFilter(
- data={
- "target_entity": {"id": "$autocapture", "type": "events"},
- "returning_entity": '{"id": "signup", "type": "events"}',
- }
- ).to_dict()
- self.assertEqual(filter["target_entity"]["id"], "$autocapture")
- self.assertEqual(filter["returning_entity"]["id"], "signup")
diff --git a/posthog/models/filters/test/test_stickiness_filter.py b/posthog/models/filters/test/test_stickiness_filter.py
deleted file mode 100644
index 48aa6d66914f..000000000000
--- a/posthog/models/filters/test/test_stickiness_filter.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from posthog.test.base import BaseTest
-
-from posthog.models.filters.stickiness_filter import StickinessFilter
-from posthog.models.filters.utils import earliest_timestamp_func
-
-
-class TestStickinessFilter(BaseTest):
- def test_filter_properties(self):
- filter = StickinessFilter(
- data={
- "interval": "month",
- "date_from": "2020-01-01T20:00:00Z",
- "date_to": "2020-02-01T20:00:00Z",
- "events": [{"id": "$pageview", "custom_name": "Custom event"}],
- "compare": True,
- "sampling_factor": 0.1,
- },
- team=self.team,
- get_earliest_timestamp=earliest_timestamp_func,
- )
- self.assertEqual(
- filter.to_dict(),
- {
- "compare": True,
- "date_from": "2020-01-01T20:00:00Z",
- "date_to": "2020-02-01T20:00:00Z",
- "events": [
- {
- "distinct_id_field": None,
- "id": "$pageview",
- "id_field": None,
- "type": "events",
- "order": None,
- "name": "$pageview",
- "custom_name": "Custom event",
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_property_revenue_currency": None,
- "math_group_type_index": None,
- "properties": {},
- "table_name": None,
- "timestamp_field": None,
- }
- ],
- "insight": "STICKINESS",
- "interval": "month",
- "sampling_factor": 0.1,
- },
- )
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
index 276839f7e2e3..c514f4929d48 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -131,7 +131,6 @@ posthog/kafka_client/test/test_client.py::KafkaClientRoundtripTestCase
posthog/management/commands/test/test_analyze_migration_risk.py::TestAnalyzeMigrationRisk
posthog/management/commands/test/test_base_hypercache_command.py::TestVerificationResultsErrorReporting
posthog/management/commands/test/test_survey_cohort_bytecode_stl.py::TestBytecodeWalker
-posthog/models/filters/test/test_path_filter.py::TestPathFilter
posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyBytecodeCondition
posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyDateRangeValidation
posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyValueAlias