:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): Add account_group_type_index team config (#58153)
Arthur Moreira de Deus042634861c86
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex df28b4d0b97c..f5dc8aab56f2 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -410,6 +410,7 @@ export const FEATURE_FLAGS = {POSTHOG_AI_QUEUE_MESSAGES_SYSTEM: 'posthog-ai-queue-messages-system', // owner: #team-posthog-aiPOSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-posthog-codePOSTHOG_CODE_SLACK_AVAILABILITY: 'posthog-code-slack-availability', // owner: #team-posthog-code, gates the PostHog Code Slack integration UI+ POSTHOG_CSP: 'posthog-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)PRODUCT_ANALYTICS_DASHBOARD_AI_ANALYSIS: 'product-analytics-dashboard-ai-analysis', // owner: @anirudhpillai #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analyticsdiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 406bf5105325..b45b9550189b 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -11332,6 +11332,16 @@"CustomerAnalyticsConfig": {"additionalProperties": false,"properties": {+ "account_group_type_index": {+ "anyOf": [+ {+ "$ref": "#/definitions/integer"+ },+ {+ "type": "null"+ }+ ]+ },"activity_event": {"anyOf": [{diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 493a5ab16576..86dabec35fa2 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6288,6 +6288,7 @@ export interface CustomerAnalyticsConfig {signup_event: EventsNode | ActionsNodesubscription_event: EventsNode | ActionsNodepayment_event: EventsNode | ActionsNode+ account_group_type_index?: integer | null}/**diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex a66f6fe09e8a..5292f2ea3966 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -41,6 +41,7 @@ import { AccessControlLevel, AccessControlResourceType, Realm } from '~/types'import { ChannelsSection } from 'products/conversations/frontend/scenes/settings/ChannelsSection'import { GeneralSection } from 'products/conversations/frontend/scenes/settings/GeneralSection'import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'+import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/CustomerAnalyticsDashboardEvents'import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'@@ -435,6 +436,14 @@ export const SETTINGS_MAP: SettingSection[] = [flag: 'CUSTOMER_ANALYTICS',keywords: ['dashboard', 'customer', 'events'],},+ {+ id: 'customer-analytics-accounts',+ title: 'Accounts',+ description: 'Select which group type represents an account in customer analytics.',+ component: <CustomerAnalyticsAccountConfig />,+ flag: ['CUSTOMER_ANALYTICS', 'POSTHOG_CSP'],+ keywords: ['accounts', 'group', 'b2b'],+ },],},{diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex a578712f73fd..75c7dc8b9e35 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -98,6 +98,7 @@ export type SettingId =| 'correlation-analysis'| 'customer-analytics-usage-metrics'| 'customer-analytics-dashboard-events'+ | 'customer-analytics-accounts'| 'person-display-name'| 'person-last-seen-at'| 'path-cleaning'diff --git a/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.test.tsx b/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.test.tsxindex ad45b593155a..e92095eace61 100644--- a/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.test.tsx+++ b/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.test.tsx@@ -450,6 +450,48 @@ describe('customerAnalyticsConfigurationDescriber', () => {})})+ describe('account group type index', () => {+ it('describes setting account_group_type_index from unset', () => {+ const result = customerAnalyticsConfigurationDescriber(+ createChange(createEmptyConfig(), createConfig({ account_group_type_index: 0 }))+ )+ expect(result?.description).toHaveLength(1)+ expect(getTextContent(result)).toBe('set Account group type to group 0')+ })++ it('describes clearing account_group_type_index', () => {+ const result = customerAnalyticsConfigurationDescriber(+ createChange(+ createConfig({ account_group_type_index: 1 }),+ createConfig({ account_group_type_index: null })+ )+ )+ expect(result?.description).toHaveLength(1)+ expect(getTextContent(result)).toBe('cleared Account group type')+ })++ it('describes changing account_group_type_index', () => {+ const result = customerAnalyticsConfigurationDescriber(+ createChange(+ createConfig({ account_group_type_index: 0 }),+ createConfig({ account_group_type_index: 2 })+ )+ )+ expect(result?.description).toHaveLength(1)+ expect(getTextContent(result)).toBe('changed Account group type from group 0 to group 2')+ })++ it('returns no description when account_group_type_index is unchanged', () => {+ const result = customerAnalyticsConfigurationDescriber(+ createChange(+ createConfig({ account_group_type_index: 1 }),+ createConfig({ account_group_type_index: 1 })+ )+ )+ expect(result?.description).toEqual([])+ })+ })+describe('edge cases', () => {it('handles missing before/after properties', () => {const result = customerAnalyticsConfigurationDescriber({} as any)diff --git a/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.tsx b/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.tsxindex 5fc7aaa55f78..75332ebd4ce3 100644--- a/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.tsx+++ b/frontend/src/scenes/team-activity/customer_analytics_config/customerAnalyticsConfigurationDescriber.tsx@@ -17,8 +17,42 @@ export const customerAnalyticsConfigurationDescriber = (change?: ActivityChange)const after = (change.after ?? {}) as CustomerAnalyticsConfigconst eventConfigDescriptions = customerAnalyticsEventConfigDescriber(before, after) ?? []+ const accountGroupTypeDescriptions = accountGroupTypeIndexDescriber(before, after) ?? []- return { description: [...eventConfigDescriptions] }+ return { description: [...eventConfigDescriptions, ...accountGroupTypeDescriptions] }+}++const accountGroupTypeIndexDescriber = (+ before: CustomerAnalyticsConfig,+ after: CustomerAnalyticsConfig+): JSX.Element[] | null => {+ const beforeValue = before.account_group_type_index ?? null+ const afterValue = after.account_group_type_index ?? null++ if (beforeValue === afterValue) {+ return null+ }++ if (beforeValue === null) {+ return [+ <>+ set <strong>Account group type</strong> to <code>group {afterValue}</code>+ </>,+ ]+ }+ if (afterValue === null) {+ return [+ <>+ cleared <strong>Account group type</strong>+ </>,+ ]+ }+ return [+ <>+ changed <strong>Account group type</strong> from <code>group {beforeValue}</code> to{' '}+ <code>group {afterValue}</code>+ </>,+ ]}type EventType = 'activity_event' | 'signup_pageview_event' | 'signup_event' | 'subscription_event' | 'payment_event'diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 61fedb0900b6..3a293c53e1b1 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -44,6 +44,7 @@ from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.data_color_theme import DataColorThemefrom posthog.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContext, normalize_context_namefrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig+from posthog.models.filters.utils import validate_group_type_indexfrom posthog.models.group_type_mapping import cached_group_types_for_teamfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.product_intent.product_intent import (@@ -327,11 +328,23 @@ class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAcclass TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):- activity_event = serializers.JSONField(required=False)- signup_pageview_event = serializers.JSONField(required=False)- signup_event = serializers.JSONField(required=False)- subscription_event = serializers.JSONField(required=False)- payment_event = serializers.JSONField(required=False)+ activity_event = serializers.JSONField(required=False, help_text="Event used as the activity signal (DAU/WAU/MAU).")+ signup_pageview_event = serializers.JSONField(+ required=False, help_text="Event used to count signup pageviews on dashboards."+ )+ signup_event = serializers.JSONField(required=False, help_text="Event used to count signups on dashboards.")+ subscription_event = serializers.JSONField(+ required=False, help_text="Event used to count subscriptions on dashboards."+ )+ payment_event = serializers.JSONField(required=False, help_text="Event used to count payments on dashboards.")+ account_group_type_index = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text=(+ "Index of the group type to treat as an Account in customer analytics. "+ "Must reference an existing group type configured for the project."+ ),+ )class Meta:model = TeamCustomerAnalyticsConfig@@ -341,8 +354,13 @@ class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAcc"signup_event","subscription_event","payment_event",+ "account_group_type_index",]+ @staticmethod+ def validate_account_group_type_index(value):+ return validate_group_type_index("account_group_type_index", value)+_VALID_TRIGGER_PROPERTY_OPERATORS = {"exact",@@ -1361,6 +1379,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin"signup_event": instance.customer_analytics_config.signup_event,"subscription_event": instance.customer_analytics_config.subscription_event,"payment_event": instance.customer_analytics_config.payment_event,+ "account_group_type_index": instance.customer_analytics_config.account_group_type_index,}serializer = TeamCustomerAnalyticsConfigSerializer(diff --git a/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr b/posthog/api/test/__snapshots__/test_organization_feature_flag.ambrindex 3b8492799b60..62408bfb105d 100644--- a/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1924,7 +1924,8 @@"customer_analytics_teamcustomeranalyticsconfig"."signup_pageview_event","customer_analytics_teamcustomeranalyticsconfig"."signup_event","customer_analytics_teamcustomeranalyticsconfig"."subscription_event",- "customer_analytics_teamcustomeranalyticsconfig"."payment_event"+ "customer_analytics_teamcustomeranalyticsconfig"."payment_event",+ "customer_analytics_teamcustomeranalyticsconfig"."account_group_type_index"FROM "customer_analytics_teamcustomeranalyticsconfig"WHERE "customer_analytics_teamcustomeranalyticsconfig"."team_id" = 99999LIMIT 21diff --git a/posthog/schema.py b/posthog/schema.pyindex 3e5698ec0971..adb84e8b5e4f 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -19341,6 +19341,7 @@ class CustomerAnalyticsConfig(BaseModel):model_config = ConfigDict(extra="forbid",)+ account_group_type_index: int | None = Noneactivity_event: EventsNode | ActionsNodepayment_event: EventsNode | ActionsNodesignup_event: EventsNode | ActionsNodediff --git a/products/customer_analytics/backend/migrations/0004_teamcustomeranalyticsconfig_account_group_type_index.py b/products/customer_analytics/backend/migrations/0004_teamcustomeranalyticsconfig_account_group_type_index.pynew file mode 100644index 000000000000..efe49211fb65--- /dev/null+++ b/products/customer_analytics/backend/migrations/0004_teamcustomeranalyticsconfig_account_group_type_index.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0003_customer_journey"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamcustomeranalyticsconfig",+ name="account_group_type_index",+ field=models.IntegerField(blank=True, null=True),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 76f294f24d8c..41f397638c65 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_customer_journey+0004_teamcustomeranalyticsconfig_account_group_type_indexdiff --git a/products/customer_analytics/backend/models/team_customer_analytics_config.py b/products/customer_analytics/backend/models/team_customer_analytics_config.pyindex 907ddf9d50bc..181a5386ce45 100644--- a/products/customer_analytics/backend/models/team_customer_analytics_config.py+++ b/products/customer_analytics/backend/models/team_customer_analytics_config.py@@ -19,6 +19,7 @@ class TeamCustomerAnalyticsConfig(models.Model):signup_event = field_access_control(models.JSONField(default=dict), "project", "admin")subscription_event = field_access_control(models.JSONField(default=dict), "project", "admin")payment_event = field_access_control(models.JSONField(default=dict), "project", "admin")+ account_group_type_index = field_access_control(models.IntegerField(null=True, blank=True), "project", "admin")def to_cache_key_dict(self) -> dict:return {diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsxnew file mode 100644index 000000000000..792433ca5b3a--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx@@ -0,0 +1,58 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'+import { capitalizeFirstLetter, wordPluralize } from 'lib/utils'+import { GroupsIntroduction } from 'scenes/groups/GroupsIntroduction'+import { teamLogic } from 'scenes/teamLogic'++import { groupsModel } from '~/models/groupsModel'+import { CustomerAnalyticsConfig } from '~/queries/schema/schema-general'++const NO_ACCOUNT_GROUP = -1++export function CustomerAnalyticsAccountConfig(): JSX.Element {+ const { customerAnalyticsConfig, currentTeamLoading } = useValues(teamLogic)+ const { updateCurrentTeam } = useActions(teamLogic)+ const { groupTypes } = useValues(groupsModel)+ const { shouldShowGroupsIntroduction } = useValues(groupsAccessLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ if (shouldShowGroupsIntroduction) {+ return <GroupsIntroduction />+ }++ const options = [+ { value: NO_ACCOUNT_GROUP, label: 'Not configured' },+ ...Array.from(groupTypes.values()).map((groupType) => ({+ value: groupType.group_type_index,+ label: capitalizeFirstLetter(groupType.name_plural || wordPluralize(groupType.group_type)),+ })),+ ]++ const value = customerAnalyticsConfig.account_group_type_index ?? NO_ACCOUNT_GROUP++ return (+ <LemonSelect+ data-attr="customer-analytics-account-group-type"+ value={value}+ onChange={(newValue) =>+ updateCurrentTeam({+ customer_analytics_config: {+ account_group_type_index: newValue === NO_ACCOUNT_GROUP ? null : newValue,+ } as CustomerAnalyticsConfig,+ })+ }+ disabledReason={currentTeamLoading ? 'Loading...' : restrictedReason}+ fullWidth+ className="max-w-160"+ options={options}+ />+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.tsindex a4cf57388079..c1dbe8c6222d 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts@@ -14,6 +14,7 @@ export type ConfigurationSceneTabType =| 'group-analytics'| 'customer-analytics-usage-metrics'| 'customer-analytics-dashboard-events'+ | 'customer-analytics-accounts'export interface CustomerAnalyticsConfigurationSceneLogicProps {initialTab?: ConfigurationSceneTabTypediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e354d579168c..8ee301d2a160 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30122,11 +30122,21 @@ export namespace Schemas {}export interface TeamCustomerAnalyticsConfig {+ /** Event used as the activity signal (DAU/WAU/MAU). */activity_event?: unknown;+ /** Event used to count signup pageviews on dashboards. */signup_pageview_event?: unknown;+ /** Event used to count signups on dashboards. */signup_event?: unknown;+ /** Event used to count subscriptions on dashboards. */subscription_event?: unknown;+ /** Event used to count payments on dashboards. */payment_event?: unknown;+ /**+ * Index of the group type to treat as an Account in customer analytics. Must reference an existing group type configured for the project.+ * @nullable+ */+ account_group_type_index?: number | null;}export interface PatchedTeam {