repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
posthog
posthog/models/team/team_caching.py
.py
import json from typing import TYPE_CHECKING, Optional from django.core.cache import cache from posthog.exceptions_capture import capture_exception if TYPE_CHECKING: from posthog.models.team import Team FIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in seconds def set_team_in_cache(token: str, team: Optional["Team"] ...
50
1,352
posthog
posthog/models/team/team_marketing_analytics_config.py
.py
import logging from typing import TYPE_CHECKING from django.core.exceptions import ValidationError from django.db import models from posthog.models.team import Team from posthog.models.team.extensions import register_team_extension_signal from posthog.rbac.decorators import field_access_control from posthog.schema_en...
488
21,331
posthog
posthog/models/team/util.py
.py
import time from datetime import timedelta from typing import Any from django.apps import apps import structlog from posthog.cache_utils import cache_for from posthog.models.async_migration import is_async_migration_complete from posthog.temporal.common.client import sync_connect from products.batch_exports.backend...
371
14,991
posthog
posthog/models/team/test_production_event_activation.py
.py
from contextlib import contextmanager from datetime import UTC, datetime, timedelta from typing import Any from freezegun import freeze_time from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events from unittest import TestCase from unittest.mock import MagicMock, patch fro...
485
22,497
posthog
posthog/models/team/logs_retention.py
.py
import structlog from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS from posthog.models.organization import Organization from posthog.models.team.team import Team logger = structlog.get_logger(__name__) DEFAULT_LOGS_RETENTION_DAYS = 14 def reset_revoked_logs_retention(organization: Organization, revoked...
43
1,599
posthog
posthog/models/team/test_conversion_goals_validation.py
.py
import pytest from posthog.test.base import BaseTest from django.core.exceptions import ValidationError from posthog.schema import NodeKind class TestConversionGoalsValidation(BaseTest): def _goal(self, conversion_goal_name: str) -> dict: return { "kind": NodeKind.EVENTS_NODE, "i...
36
1,253
posthog
posthog/models/team/extensions.py
.py
""" Shared utilities for Team extension models. Team extensions are one-to-one models that extend the Team model with domain-specific configuration. This module provides helpers to reduce boilerplate when creating them. See README.md in this directory for full documentation on when and how to use extensions. """ imp...
116
3,936
posthog
posthog/models/team/test_campaign_field_preferences.py
.py
import pytest from posthog.test.base import BaseTest from django.core.exceptions import ValidationError class TestCampaignFieldPreferencesValidation(BaseTest): """ Tests for campaign_field_preferences validation on TeamMarketingAnalyticsConfig. """ def test_valid_campaign_field_preferences_structure...
139
6,571
posthog
posthog/models/team/production_event_activation.py
.py
""" Detection of whether a team has begun ingesting real production traffic. This is the activation milestone behind `Team.ingested_production_event`. The file is split into two layers so the heuristic can be retuned without touching the rest of the system: 1. CRITERION — `_teams_meeting_criterion(team_ids)` is th...
662
31,026
posthog
posthog/models/team/team_revenue_analytics_config.py
.py
import logging from typing import TYPE_CHECKING from django.core.exceptions import ValidationError from django.db import models from posthog.models.team import Team from posthog.models.team.extensions import register_team_extension_signal from posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCY fr...
71
3,144
posthog
posthog/models/team/js_snippet_config.py
.py
import logging from django.db import models from posthog.models.team.extensions import register_team_extension_signal logger = logging.getLogger(__name__) class TeamJsSnippetConfig(models.Model): team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True) # Version pin: null = ...
18
543
posthog
posthog/models/team/setup_tasks.py
.py
from enum import StrEnum class SetupTaskId(StrEnum): # Global tasks (apply to all products) IngestFirstEvent = "ingest_first_event" SetUpReverseProxy = "set_up_reverse_proxy" # Product Analytics CreateFirstInsight = "create_first_insight" CreateFirstDashboard = "create_first_dashboard" Tr...
100
3,637
posthog
posthog/models/team/team_provisioning_config.py
.py
import logging from django.db import models from posthog.models.team.extensions import register_team_extension_signal logger = logging.getLogger(__name__) class TeamProvisioningConfig(models.Model): team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True) # The OAuth applica...
35
1,160
posthog
posthog/models/team/event_retention.py
.py
from typing import TYPE_CHECKING, Optional from django.conf import settings import posthoganalytics from posthog.cloud_utils import is_cloud from posthog.constants import AvailableFeature from posthog.models.organization import ProductFeature from posthog.models.team.team import Team if TYPE_CHECKING: from post...
113
4,408
posthog
posthog/models/team/test/test_event_retention.py
.py
from typing import cast from posthog.test.base import BaseTest from parameterized import parameterized from posthog.models.organization import Organization, ProductFeature from posthog.models.team.event_retention import parse_events_feature_to_months, reconcile_organization_events_retention from posthog.models.team....
70
2,946
posthog
posthog/models/kafka_partition_stats/sql.py
.py
from dataclasses import dataclass from posthog.clickhouse.kafka_engine import kafka_engine from posthog.clickhouse.table_engines import ReplacingMergeTree from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE @dataclass class PartitionStatsKafkaTable: brokers: list[str] topic: str consumer...
101
3,672
posthog
posthog/models/channel_type/sql.py
.py
import os import json from posthog.clickhouse.client import sync_execute from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.table_engines import MergeTreeEngine, ReplicationScheme from posthog.settings i...
97
3,455
posthog
posthog/models/ai_events/person_shims.py
.py
from django.conf import settings from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.table_engines import Distributed from posthog.models.person.sql import ( PERSON_DISTINCT_ID2_TABLE, PERSON_DISTINCT_ID2_TABLE_BASE_SQL, PERSONS_TABLE, PERSONS_TABLE_BASE_SQL, ) # Distribut...
40
1,543
posthog
posthog/models/ai_events/sql.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_AI_EVENTS, CONSUMER_GROUP_AI_EVENTS_WS, kafka_engine from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_AI_EVENTS_JSON TABLE_BA...
336
12,841
posthog
posthog/models/ai_events/test_util.py
.py
"""Test utilities for creating AI events in the ai_events ClickHouse table.""" import json import uuid from datetime import UTC, datetime from typing import Any from posthog.clickhouse.client import sync_execute def _prop_str(name: str, props: dict) -> str | None: val = props.get(name) if val is None: ...
211
10,038
posthog
posthog/models/ai_events/test/test_person_shims.py
.py
import re import pytest from posthog.models.ai_events.person_shims import PERSON_AI_EVENTS_SHIM_SQL, PERSON_DISTINCT_ID2_AI_EVENTS_SHIM_SQL from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE_BASE_SQL, PERSONS_TABLE_BASE_SQL def _extract_column_names(create_table_sql: str) -> set[str]: match = re.se...
78
2,703
posthog
posthog/models/product_intent/__init__.py
.py
from .product_intent import ProductIntent __all__ = ["ProductIntent"]
4
71
posthog
posthog/models/product_intent/product_intent.py
.py
from collections.abc import Callable from datetime import UTC, datetime from typing import Any, Optional from django.core.cache import cache from django.db import models, transaction from django.db.models.signals import post_delete, post_save, pre_save from django.dispatch import receiver import structlog from celery...
505
21,592
posthog
posthog/models/bot_definition/sql.py
.py
from django.conf import settings from posthog.clickhouse.dictionaries import dictionary_source_clickhouse from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS # Topology mirrors the web-an...
132
4,741
posthog
posthog/models/property/util.py
.py
import re from collections import ( Counter, Counter as TCounter, ) from collections.abc import Callable, Iterable from typing import Any, Literal, Optional, Union, cast from rest_framework import exceptions from posthog.hogql import ast from posthog.hogql.database.s3_table import S3Table from posthog.hogql.e...
1,047
44,178
posthog
posthog/models/property/property.py
.py
import json import math from enum import StrEnum from typing import Any, Literal, Optional, Union, cast from posthog.constants import PropertyOperatorType from posthog.models.filters.mixins.utils import cached_property from posthog.models.filters.utils import GroupTypeIndex, validate_group_type_index # Relocated to t...
486
18,332
posthog
posthog/models/property/test/test_property_parse_value.py
.py
from typing import Any from posthog.test.base import BaseTest from parameterized import parameterized from posthog.models.property import Property class TestPropertyParseValue(BaseTest): """Test the Property._parse_value method to ensure it handles all edge cases correctly.""" @parameterized.expand( ...
209
9,902
posthog
posthog/models/property/test/test_property_behavioral_validation.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.models.property import BehavioralPropertyType, Property class TestBehavioralPropertyDateRangeValidation(BaseTest): """Validation of the explicit_datetime / explicit_datetime_to combo on behavioral cohort filters.""" ...
150
6,023
posthog
posthog/models/filters/stickiness_filter.py
.py
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...
88
2,490
posthog
posthog/models/filters/utils.py
.py
from typing import Any, Literal, Optional, cast from rest_framework.exceptions import ValidationError from rest_framework.request import Request from posthog.constants import ( GROUP_TYPES_LIMIT, INSIGHT_FUNNELS, INSIGHT_PATHS, INSIGHT_RETENTION, INSIGHT_STICKINESS, INSIGHT_TRENDS, ) GroupTyp...
79
2,606
posthog
posthog/models/filters/lifecycle_filter.py
.py
import datetime from typing import Any, Optional from rest_framework.exceptions import ValidationError from rest_framework.request import Request from posthog.models import Filter from posthog.utils import relative_date_parse class LifecycleFilter(Filter): target_date: Optional[datetime.datetime] = None lif...
37
1,217
posthog
posthog/models/filters/__init__.py
.py
from .filter import Filter from .path_filter import PathFilter from .properties_timeline_filter import PropertiesTimelineFilter from .retention_filter import RetentionFilter from .stickiness_filter import StickinessFilter __all__ = [ "Filter", "PathFilter", "RetentionFilter", "StickinessFilter", "P...
19
549
posthog
posthog/models/filters/filter.py
.py
from .base_filter import BaseFilter from .mixins.common import ( BreakdownMixin, BreakdownValueMixin, ClientQueryIdMixin, CompareMixin, DateMixin, DisplayDerivedMixin, DistinctIdMixin, EmailMixin, EntitiesMixin, EntityIdMixin, EntityMathMixin, EntityOrderMixin, Entity...
100
2,423
posthog
posthog/models/filters/path_filter.py
.py
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, IncludeRecordingsMixi...
85
2,121
posthog
posthog/models/filters/properties_timeline_filter.py
.py
from .base_filter import BaseFilter from .mixins.common import BreakdownMixin, DisplayDerivedMixin, EntitiesMixin from .mixins.groups import GroupsAggregationMixin from .mixins.interval import IntervalMixin from .mixins.property import PropertyMixin class PropertiesTimelineFilter( IntervalMixin, EntitiesMixin...
18
442
posthog
posthog/models/filters/retention_filter.py
.py
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, Insight...
71
2,110
posthog
posthog/models/filters/base_filter.py
.py
import json import inspect from typing import TYPE_CHECKING, Any, Optional from rest_framework import request from rest_framework.exceptions import ValidationError from posthog.constants import PROPERTIES from posthog.models.utils import sane_repr from posthog.utils import encode_get_request_params from .mixins.comm...
109
3,647
posthog
posthog/models/filters/mixins/utils.py
.py
from collections.abc import Callable from functools import lru_cache from typing import Optional, TypeVar, Union from posthog.utils import str_to_bool T = TypeVar("T") # can't use cached_property directly from functools because of 3.7 compatibilty def cached_property(func: Callable[..., T]) -> T: return propert...
38
989
posthog
posthog/models/filters/mixins/interval.py
.py
from typing import cast from posthog.constants import INTERVAL from posthog.models.filters.mixins.base import IntervalType from posthog.models.filters.mixins.common import DateMixin from posthog.models.filters.mixins.utils import cached_property, include_dict class IntervalMixin(DateMixin): # Interval doesn't make ...
31
1,293
posthog
posthog/models/filters/mixins/retention.py
.py
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_...
154
5,518
posthog
posthog/models/filters/mixins/groups.py
.py
from typing import Optional from posthog.constants import AGGREGATION_GROUP_TYPE_INDEX from posthog.models.filters.mixins.common import BaseParamMixin from posthog.models.filters.mixins.utils import cached_property, include_dict from posthog.models.filters.utils import GroupTypeIndex, validate_group_type_index class...
22
850
posthog
posthog/models/filters/mixins/stickiness.py
.py
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 p...
84
2,963
posthog
posthog/models/filters/mixins/common.py
.py
import json import datetime from math import ceil from typing import Any, Literal, Optional, Union, cast from zoneinfo import ZoneInfo from django.utils import timezone from dateutil.relativedelta import relativedelta from rest_framework.exceptions import ValidationError from posthog.hogql.constants import BREAKDOWN...
633
21,667
posthog
posthog/models/filters/mixins/paths.py
.py
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_EDG...
267
8,114
posthog
posthog/models/filters/mixins/funnel.py
.py
import json import datetime from typing import TYPE_CHECKING, Literal, Optional, Union from posthog.models.property import Property if TYPE_CHECKING: from posthog.models.entity import Entity from rest_framework.exceptions import ValidationError from posthog.constants import ( BIN_COUNT, DISPLAY, DRO...
451
16,224
posthog
posthog/models/filters/mixins/base.py
.py
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: _data: dict
10
292
posthog
posthog/models/filters/mixins/property.py
.py
import json from typing import Any, Optional, Union, cast import posthoganalytics from rest_framework.exceptions import ValidationError from posthog.constants import PROPERTIES, PropertyOperatorType from posthog.exceptions_capture import capture_exception from posthog.models.filters.mixins.base import BaseParamMixin ...
169
7,380
posthog
posthog/models/filters/mixins/simplify.py
.py
from typing import TYPE_CHECKING, Any, Literal, cast from posthog.constants import PropertyOperatorType from posthog.models.property import GroupTypeIndex, PropertyGroup from posthog.schema_enums import PropertyOperator if TYPE_CHECKING: # Avoid circular import from posthog.models import Property, Team class S...
130
5,792
posthog
posthog/models/filters/mixins/test/test_property.py
.py
import json import pytest from unittest.mock import patch from posthoganalytics.contexts import get_capture_exception_code_variables_context from rest_framework.exceptions import ValidationError from posthog.models import Filter from posthog.models.property import Property, PropertyGroup, PropertyValidationError d...
340
12,753
posthog
posthog/models/filters/mixins/test/test_groups.py
.py
import pytest from rest_framework.exceptions import ValidationError from posthog.models.filters.utils import validate_group_type_index def test_validate_group_type_index(): assert validate_group_type_index("field", None) is None assert validate_group_type_index("field", 0) == 0 assert validate_group_typ...
26
979
posthog
posthog/models/filters/mixins/test/test_interval.py
.py
import pytest from posthog.models import Filter @pytest.mark.parametrize( "filter,expected_interval", [ (Filter(data={"interval": "hour"}), "hour"), (Filter(data={"interval": "day"}), "day"), (Filter(data={"interval": "week"}), "week"), (Filter(data={"interval": "month"}), "mo...
39
1,231
posthog
posthog/models/filters/test/test_filter.py
.py
from typing import cast from posthog.test.base import BaseTest from posthog.constants import FILTER_TEST_ACCOUNTS from posthog.models import Filter from posthog.models.property import Property class TestFilter(BaseTest): def test_old_style_properties(self): filter = Filter(data={"properties": {"$browser...
131
4,575
posthog
posthog/models/filters/test/test_lifecycle_filter.py
.py
from posthog.test.base import BaseTest from posthog.models.filters.lifecycle_filter import LifecycleFilter from posthog.utils import relative_date_parse class TestLifecycleFilter(BaseTest): def test_filter_properties(self): target_date = "2023-05-15" lifecycle_type = "new" filter = Lifecy...
77
2,992
posthog
posthog/models/filters/test/test_filter_mixins.py
.py
from posthog.test.base import BaseTest from posthog.models.filters.mixins.funnel import FunnelWindowDaysMixin class TestFilterMixins(BaseTest): def test_funnel_window_days_to_microseconds(self): one_day = FunnelWindowDaysMixin.microseconds_from_days(1) two_days = FunnelWindowDaysMixin.microsecond...
19
729
posthog
posthog/models/filters/test/test_path_filter.py
.py
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...
73
2,526
posthog
posthog/models/filters/test/test_retention_filter.py
.py
from freezegun.api import freeze_time 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 freeze_time("2020-10-01T12:00:00Z"): filter = Retent...
126
4,977
posthog
posthog/models/filters/test/test_stickiness_filter.py
.py
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={ ...
51
1,855
posthog
posthog/models/ingestion_warnings/sql.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import ( CONSUMER_GROUP_INGESTION_WARNINGS, CONSUMER_GROUP_INGESTION_WARNINGS_WS, KAFKA_COLUMNS_WITH_PARTITION, kafka_engine, ) from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from posthog...
145
4,427
posthog
posthog/models/ingestion_warnings/sql_v2.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_INGESTION_WARNINGS_V2, kafka_engine from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from posthog.kafka_client.topics import KAFKA_INGESTION_WARNINGS # Ingestion warnings v2: additiv...
127
4,849
posthog
posthog/models/async_deletion/delete.py
.py
from abc import ABC, abstractmethod from collections import defaultdict from django.utils import timezone import structlog from prometheus_client import Counter from posthog.models.async_deletion import AsyncDeletion, DeletionType logger = structlog.get_logger(__name__) deletions_counter = Counter("deletions_conf...
87
3,392
posthog
posthog/models/async_deletion/delete_person.py
.py
import time import uuid from posthog.clickhouse.client import sync_execute from posthog.clickhouse.client.connection import ClickHouseUser, Workload, get_clickhouse_creds from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE # Prefix ...
85
3,959
posthog
posthog/models/async_deletion/__init__.py
.py
from .async_deletion import AsyncDeletion, DeletionType __all__ = ["AsyncDeletion", "DeletionType"]
4
101
posthog
posthog/models/async_deletion/delete_cohorts.py
.py
from typing import Any from posthog.clickhouse.client import sync_execute from posthog.models.async_deletion import AsyncDeletion, DeletionType from posthog.models.async_deletion.delete import AsyncDeletionProcess, logger class AsyncCohortDeletion(AsyncDeletionProcess): DELETION_TYPES = [DeletionType.Cohort_full...
89
3,469
posthog
posthog/models/async_deletion/async_deletion.py
.py
from django.db import models class DeletionType(models.IntegerChoices): Team = 0 Person = 1 Group = 2 Cohort_stale = 3 Cohort_full = 4 # This model represents deletions that should delete (other, unrelated) data async class AsyncDeletion(models.Model): id = models.BigAutoField(primary_key=Tr...
48
1,994
posthog
posthog/models/async_deletion/test_delete_person.py
.py
import pytest from posthog.test.base import BaseTest, ClickhouseTestMixin from django.conf import settings from posthog.clickhouse.client import sync_execute from posthog.models.async_deletion.delete_person import DELETED_PERSON_IDS_DICTIONARY, remove_deleted_person_data from posthog.models.person.util import create_...
95
4,020
posthog
posthog/models/async_deletion/delete_events.py
.py
from typing import Any from clickhouse_driver.errors import SocketTimeoutError from prometheus_client import Counter from posthog.clickhouse.client import sync_execute from posthog.models.async_deletion import AsyncDeletion, DeletionType from posthog.models.async_deletion.delete import AsyncDeletionProcess, logger fr...
190
9,124
posthog
posthog/admin/test_ai_training_opt_in_history.py
.py
from posthog.test.base import APIBaseTest from django.contrib.admin.sites import AdminSite from parameterized import parameterized from posthog.admin.admins.organization_admin import OrganizationAdmin from posthog.admin.ai_training_opt_in_history import MAX_ENTRIES_SHOWN, get_ai_training_opt_in_history from posthog....
209
9,114
posthog
posthog/admin/test_oauth_admin.py
.py
from datetime import timedelta from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib.admin import AdminSite from django.contrib.auth.hashers import check_password from django.test import RequestFactory from django.utils import timezone from param...
191
8,447
posthog
posthog/admin/test_conversation_admin.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib.admin.sites import AdminSite from django.contrib.messages import constants as message_constants from django.contrib.messages.storage.fallback import FallbackStorage from django.core.exceptions import PermissionDenied from django...
90
3,865
posthog
posthog/admin/inline_registry.py
.py
"""Cross-app admin inline registration. Lets a product surface a Django admin inline on a *core* admin page (e.g. the Organization change page) without core importing the product. A Django inline must be listed in its parent ModelAdmin, and core admins live in posthog/admin/ — so a product that owns an inline would ot...
40
1,720
posthog
posthog/admin/test_data_deletion_request_admin.py
.py
from datetime import datetime, timedelta from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import Group from django.contrib.messages import get_messages from django.contrib.messages....
1,008
43,577
posthog
posthog/admin/filters.py
.py
from django.contrib import admin class DeletedFilter(admin.SimpleListFilter): """Sidebar filter for models with a soft-delete `deleted` boolean, defaulting to hiding deleted rows.""" title = "deleted" parameter_name = "deleted" def lookups(self, request, model_admin): return (("no", "No"), (...
29
936
posthog
posthog/admin/__init__.py
.py
# Lazy load admin classes to avoid loading all at startup. # Admin classes are loaded when Django admin site is first accessed def register_all_admin(): """Trigger every admin registration. Called lazily on first `admin.site._registry` access via `LazyAdminRegistry`. `INSTALLED_APPS` uses `SimpleAdminCon...
130
5,911
posthog
posthog/admin/ai_training_opt_in_history.py
.py
"""Reconstructs an organization's AI training opt-in history for the Django admin. This module reads two sources: the organization's current value, and the `ActivityLog` rows that changed `is_ai_training_opted_in`. It reports only what those sources recorded. It does not repeat the rules that set the starting value. T...
200
8,222
posthog
posthog/admin/test_team_admin.py
.py
import hashlib from datetime import UTC, datetime, timedelta from decimal import Decimal from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib.admin.sites import AdminSite from django.contrib.messages.storage.fallback import FallbackStorage from d...
890
43,575
posthog
posthog/admin/test_send_ai_observability_usage_report_admin.py
.py
from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib import messages from django.contrib.admin.sites import AdminSite from django.contrib.messages.storage.fallback import FallbackStorage from django.core.management.base import CommandError from dj...
88
3,776
posthog
posthog/admin/test_code_based_verification_global_disable_admin.py
.py
from posthog.test.base import APIBaseTest from rest_framework import status from rest_framework.test import APIRequestFactory, force_authenticate from posthog.admin.admins.code_based_verification_bypass_admin import CodeBasedVerificationGlobalDisableViewSet from posthog.helpers.two_factor_session import ( MAX_COD...
82
3,858
posthog
posthog/admin/test_inline_registry.py
.py
import pytest from django.contrib import admin from posthog.admin import inline_registry from posthog.admin.inline_registry import extra_inlines_for, register_admin_inline from posthog.models import Organization, Team class _DummyInline(admin.TabularInline): model = Organization @pytest.fixture(autouse=True) ...
32
988
posthog
posthog/admin/test_admin.py
.py
import pytest from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.contrib import admin from django.contrib.admin import AdminSite from django.test import RequestFactory from posthog.admin import _OAUTH_ADMIN_MODEL_NAMES, install_admin_app_list_overrides, register_all_admin fr...
291
13,006
posthog
posthog/admin/test_tophog_admin.py
.py
from urllib.parse import parse_qs, urlparse from posthog.test.base import BaseTest from django.contrib import admin from django.test import RequestFactory from django.urls import reverse from parameterized import parameterized from posthog.admin.admins.event_ingestion_restriction_config import ( EventIngestionR...
179
7,607
posthog
posthog/admin/test_trigger_deletion_admin.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import Group from django.contrib.messages.storage.fallback import FallbackStorage from django.test import RequestFactory, override_settings from temporalio.exceptions...
231
9,716
posthog
posthog/admin/test_user_admin.py
.py
import uuid from importlib import import_module from posthog.test.base import BaseTest from unittest.mock import patch from django.conf import settings from django.contrib.admin.sites import AdminSite from django.contrib.auth import SESSION_KEY from django.contrib.messages.storage.fallback import FallbackStorage from...
113
4,834
posthog
posthog/admin/authorization.py
.py
from django.http import HttpRequest # Staff access alone must not authorize irreversible org/project deletions from Django # admin. Django's model permissions are useless as a gate here: User.is_superuser mirrors # is_staff, so every active staff user passes has_delete_permission(). Gate destructive # deletions behind...
13
643
posthog
posthog/admin/inlines/user_social_auth_inline.py
.py
from django.contrib import admin from social_django.models import UserSocialAuth class UserSocialAuthInline(admin.TabularInline): """ Inline table for UserSocialAuth records on the User admin page. Allows viewing and deleting social auth connections. """ model = UserSocialAuth extra = 0 ...
29
840
posthog
posthog/admin/inlines/organization_member_inline.py
.py
from django_admin_inline_paginator.admin import TabularInlinePaginated from posthog.models.organization import OrganizationMembership class OrganizationMemberInline(TabularInlinePaginated): extra = 0 model = OrganizationMembership per_page = 20 pagination_key = "page-member" show_change_link = Tr...
25
1,041
posthog
posthog/admin/inlines/organization_member_for_related_inline.py
.py
from typing import Any from django.contrib import admin from django.forms import BaseInlineFormSet, ModelForm, modelformset_factory from django.urls import reverse from django.utils.html import format_html from django_admin_inline_paginator.admin import PaginationFormSetBase, TabularInlinePaginated from posthog.mode...
118
4,199
posthog
posthog/admin/inlines/totp_device_inline.py
.py
from django.contrib import admin from django_otp.plugins.otp_totp.models import TOTPDevice class TOTPDeviceInline(admin.TabularInline): model = TOTPDevice extra = 0 # only include non-sensitive fields fields = ("name", "confirmed", "throttling_failure_timestamp", "throttling_failure_count", "last_use...
26
983
posthog
posthog/admin/inlines/personal_api_key_inline.py
.py
from django.contrib import admin from posthog.models.personal_api_key import PersonalAPIKey class PersonalAPIKeyInline(admin.TabularInline): model = PersonalAPIKey extra = 0 fields = ("label", "mask_value", "created_at", "last_used_at", "scopes") readonly_fields = ("label", "mask_value", "created_at"...
26
912
posthog
posthog/admin/inlines/project_inline.py
.py
from django.utils.html import format_html from django_admin_inline_paginator.admin import TabularInlinePaginated from posthog.admin.admins.project_admin import ProjectAdmin from posthog.models import Project class ProjectInline(TabularInlinePaginated): extra = 0 model = Project per_page = 20 paginat...
32
979
posthog
posthog/admin/inlines/scim_provisioned_user_inline.py
.py
from django.contrib import admin from ee.models.scim_provisioned_user import SCIMProvisionedUser class SCIMProvisionedUserInline(admin.TabularInline): """ Inline table for SCIMProvisionedUser records on the User admin page. Shows SCIM provisioning details and allows deletion. """ model = SCIMPro...
45
1,240
posthog
posthog/admin/inlines/organization_domain_inline.py
.py
from django_admin_inline_paginator.admin import TabularInlinePaginated from posthog.models.organization_domain import OrganizationDomain class OrganizationDomainInline(TabularInlinePaginated): extra = 0 model = OrganizationDomain per_page = 20 pagination_key = "page-domain" show_change_link = Tru...
28
750
posthog
posthog/admin/inlines/user_product_list_inline.py
.py
from django import forms from django.contrib import admin from django.core.exceptions import ValidationError from posthog.models.file_system.user_product_list import UserProductList from posthog.products import Products class UserProductListInlineForm(forms.ModelForm): class Meta: model = UserProductList...
160
6,706
posthog
posthog/admin/inlines/team_inline.py
.py
from django.utils.html import format_html from django_admin_inline_paginator.admin import TabularInlinePaginated from posthog.admin.admins.team_admin import TeamAdmin, TeamAdminForm from posthog.models import Team class TeamInline(TabularInlinePaginated): extra = 0 model = Team # The default ModelForm r...
70
2,005
posthog
posthog/admin/inlines/team_marketing_analytics_config_inline.py
.py
from django.contrib import admin from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig class TeamMarketingAnalyticsConfigInline(admin.StackedInline): model = TeamMarketingAnalyticsConfig extra = 0 max_num = 1 classes = ("collapse",) fieldsets = [ ( ...
24
711
posthog
posthog/admin/inlines/team_experiments_config_inline.py
.py
from django.contrib import admin from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig class TeamExperimentsConfigInline(admin.StackedInline): model = TeamExperimentsConfig extra = 0 max_num = 1 classes = ("collapse",) fieldsets = [ ( "...
33
998
posthog
posthog/admin/inlines/organization_invite_inline.py
.py
from django_admin_inline_paginator.admin import TabularInlinePaginated from posthog.models.organization_invite import OrganizationInvite class OrganizationInviteInline(TabularInlinePaginated): extra = 0 model = OrganizationInvite per_page = 20 pagination_key = "page-invite" readonly_fields = ("cr...
22
646
posthog
posthog/admin/paginators/no_count_paginator.py
.py
from django.core.paginator import Paginator class NoCountPaginator(Paginator): @property def count(self): return 999999
8
138
posthog
posthog/admin/admins/cohort_admin.py
.py
from django.contrib import admin, messages from django.urls import reverse from django.utils.html import format_html from products.cohorts.backend.models.cohort import Cohort @admin.register(Cohort) class CohortAdmin(admin.ModelAdmin): list_display = ( "id", "name", "team_link", "...
64
2,094
posthog
posthog/admin/admins/project_secret_api_key_admin.py
.py
from django.contrib import admin from django.db.models import QuerySet from django.http import HttpRequest from django.urls import reverse from django.utils.html import format_html from django.utils.safestring import SafeString from posthog.admin.admins.api_key_roll_mixin import RollApiKeyAdminMixin from posthog.api.p...
65
2,435
posthog
posthog/admin/admins/distinct_id_usage_admin.py
.py
import logging from datetime import UTC, datetime, timedelta from django import forms from django.conf import settings from django.contrib import admin, messages from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import ...
467
17,481