: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(conversations): show mrr and lifetime value in related groups panel (#110629)
Christian Rafferty96cb8ecb7390
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3e3b823d6841..4242c24c4b20 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12910,6 +12910,14 @@ snapshots:hash: v1.k794b7964.6b6e47f7a6e819c6f5001b08535c3dff93cbad7acf5ebfeafeff9c5dcfc36189.lZn-6YFthsicyD42YSyFBP-KQ1ghbNYQ1C4uqgeTvlMscenes-app-support-aipanel--suggested--light:hash: v1.k794b7964.6c3b559141a22910e91279c6a78db5b3eb7c8c6fd603b0c9604dda0b18561f26.LPgQxRSVfVCglr43R6HXDc9tsTy6zB9W81t1WTzsB8I+ scenes-app-support-grouprevenue--from-revenue-analytics--dark:+ hash: v1.k794b7964.c422e690e5d597b7ccbeee9fc6656893b68e5a2abf17c2c9b411009b413c0460.4h2u5iNaeTBSTHWIQObDxV4T6W2YLqmIymqNwgMGrqk+ scenes-app-support-grouprevenue--from-revenue-analytics--light:+ hash: v1.k794b7964.1f516758e8bc6f08fdc97d012bf7a208e2f657bfc1dace6e45b1fe0b1a4dc463.SvaOZZYVTI5ff9hCYkwminwj910vZcqATfA-eMwgkc4+ scenes-app-support-grouprevenue--only-mrr-from-group-properties--dark:+ hash: v1.k794b7964.c6299ce9c9f6b7e785f1efcb79f8d6b094b26484a544e1d6674cacf4472508ae.nNpGp13zyL__JEBS4O3erFqmI_N8rHLw-RQxj6ZlZD0+ scenes-app-support-grouprevenue--only-mrr-from-group-properties--light:+ hash: v1.k794b7964.82bce2bbc0eb23eff8e9c0708c93dd239dccea0fe815bbcdf4b680b86b7d2cb0.nMRLbQvkGfmd9JMySDaaKW00sTo-v4GQaj7E1Z2ceUQscenes-app-support-supportplaybookeditor--customized--dark:hash: v1.k794b7964.56dd8c26993da8181fb09aa4d9868be1f5925885f1f1854ca38100636acdaaec.yjA6yaERFMxD3ydwD-uPOPa4qSoIgBECHwHq3wOm_1Escenes-app-support-supportplaybookeditor--customized--light:diff --git a/products/conversations/frontend/components/GroupRevenue/GroupRevenue.stories.tsx b/products/conversations/frontend/components/GroupRevenue/GroupRevenue.stories.tsxnew file mode 100644index 000000000000..49e9d674a1c5--- /dev/null+++ b/products/conversations/frontend/components/GroupRevenue/GroupRevenue.stories.tsx@@ -0,0 +1,37 @@+import type { Meta, StoryObj } from '@storybook/react'++import { GroupRevenue } from './GroupRevenue'++const meta: Meta<typeof GroupRevenue> = {+ title: 'Scenes-App/Support/GroupRevenue',+ component: GroupRevenue,+ parameters: { layout: 'padded', viewMode: 'story' },+ decorators: [+ (Story) => (+ <div className="w-[300px]">+ <Story />+ </div>+ ),+ ],+}+export default meta++type Story = StoryObj<typeof GroupRevenue>++export const FromRevenueAnalytics: Story = {+ args: {+ revenue: {+ mrr: { value: 1250, source: 'revenue-analytics' },+ lifetimeValue: { value: 1234567.89, source: 'revenue-analytics' },+ },+ },+}++export const OnlyMrrFromGroupProperties: Story = {+ args: {+ revenue: {+ mrr: { value: 99, source: 'properties' },+ lifetimeValue: { value: null, source: null },+ },+ },+}diff --git a/products/conversations/frontend/components/GroupRevenue/GroupRevenue.tsx b/products/conversations/frontend/components/GroupRevenue/GroupRevenue.tsxnew file mode 100644index 000000000000..5c977b793a1a--- /dev/null+++ b/products/conversations/frontend/components/GroupRevenue/GroupRevenue.tsx@@ -0,0 +1,50 @@+import { useValues } from 'kea'++import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'++import { formatCurrency } from 'lib/utils/currency'+import { DataSourceIcon } from 'scenes/notebooks/Nodes/components/DataSourceIcon'+import { teamLogic } from 'scenes/teamLogic'++import type { GroupRevenue as GroupRevenueData } from '../../scenes/ticket/groupRevenue'++export interface GroupRevenueProps {+ revenue: GroupRevenueData+ loading?: boolean+}++export function GroupRevenue({ revenue, loading = false }: GroupRevenueProps): JSX.Element | null {+ const { baseCurrency } = useValues(teamLogic)++ if (loading) {+ return <LemonSkeleton className="h-3 w-40" />+ }++ const { mrr, lifetimeValue } = revenue+ if (mrr.value === null && lifetimeValue.value === null) {+ return null+ }++ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs" data-attr="ticket-group-revenue">+ {mrr.value !== null && (+ <div className="flex items-center gap-1">+ <Tooltip title="Monthly recurring revenue">+ <span className="text-secondary">MRR</span>+ </Tooltip>+ <span translate="no">{formatCurrency(mrr.value, baseCurrency)}</span>+ <DataSourceIcon source={mrr.source} />+ </div>+ )}+ {lifetimeValue.value !== null && (+ <div className="flex items-center gap-1">+ <Tooltip title="Total revenue from this customer over the whole relationship">+ <span className="text-secondary">Lifetime value</span>+ </Tooltip>+ <span translate="no">{formatCurrency(lifetimeValue.value, baseCurrency)}</span>+ <DataSourceIcon source={lifetimeValue.source} />+ </div>+ )}+ </div>+ )+}diff --git a/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx b/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsxindex 2a07dd9fe531..dfcaf9eef30f 100644--- a/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx@@ -1,4 +1,5 @@import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'import { LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'@@ -9,7 +10,10 @@ import { RelatedGroups } from 'products/groups/frontend/components/RelatedGroupsimport { relatedGroupsLogic } from 'products/groups/frontend/logics/relatedGroupsLogic'import { GroupActorDisplay } from 'products/persons/frontend/components/GroupActorDisplay'+import { GroupRevenue } from '../../components/GroupRevenue/GroupRevenue'import { creationGroupLogic } from './creationGroupLogic'+import { resolveGroupRevenue } from './groupRevenue'+import { groupRevenueLogic } from './groupRevenueLogic'const ORIGIN_LABEL = 'Ticket origin'const STALE_TOOLTIP =@@ -65,6 +69,16 @@ function toGroupActor(group: Group): GroupActorType {} as GroupActorType}+function GroupRevenueDetail({ actor, groupKeys }: { actor: GroupActorType; groupKeys: string[] }): JSX.Element {+ const { revenueByGroupKey, revenueByGroupKeyLoading } = useValues(groupRevenueLogic({ groupKeys }))+ return (+ <GroupRevenue+ revenue={resolveGroupRevenue(revenueByGroupKey[actor.group_key], actor.properties)}+ loading={revenueByGroupKeyLoading}+ />+ )+}+function PersonRelatedGroups({personUuid,organizationId,@@ -92,7 +106,27 @@ function PersonRelatedGroups({// When the snapshot group isn't in the live related list, fetch it and append it as a real row// (type + name + link) rather than a bare key, tagged via highlightGroupKey below.- const extraActors: ActorType[] = showFallback && creationGroup ? [toGroupActor(creationGroup)] : []+ const extraActors = useMemo<ActorType[]>(+ () => (showFallback && creationGroup ? [toGroupActor(creationGroup)] : []),+ [showFallback, creationGroup]+ )++ // Every row reads from one logic keyed by the full list, so the panel issues a single revenue query.+ const groupKeys = useMemo(+ () =>+ Array.from(+ new Set(+ [...relatedActors, ...extraActors].flatMap((actor) =>+ actor.type === 'group' ? [actor.group_key] : []+ )+ )+ ),+ [relatedActors, extraActors]+ )+ const renderGroupDetail = useCallback(+ (actor: GroupActorType) => <GroupRevenueDetail actor={actor} groupKeys={groupKeys} />,+ [groupKeys]+ )return (<RelatedGroups@@ -107,6 +141,7 @@ function PersonRelatedGroups({highlightStale={!fromChannelAccount && showFallback}highlightStaleTooltip={STALE_TOOLTIP}extraActors={extraActors}+ renderGroupDetail={renderGroupDetail}/>)}@@ -133,14 +168,19 @@ function CreationGroupOnly({return <div className="text-secondary">No related groups found</div>}+ const creationActor = toGroupActor(creationGroup)+return (- <div className="flex items-center gap-2">- <GroupActorDisplay actor={toGroupActor(creationGroup)} />- <Tooltip title={fromChannelAccount ? CHANNEL_ACCOUNT_TOOLTIP : undefined}>- <LemonTag type="muted" size="small">- {fromChannelAccount ? CHANNEL_ACCOUNT_LABEL : ORIGIN_LABEL}- </LemonTag>- </Tooltip>+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <GroupActorDisplay actor={creationActor} />+ <Tooltip title={fromChannelAccount ? CHANNEL_ACCOUNT_TOOLTIP : undefined}>+ <LemonTag type="muted" size="small">+ {fromChannelAccount ? CHANNEL_ACCOUNT_LABEL : ORIGIN_LABEL}+ </LemonTag>+ </Tooltip>+ </div>+ <GroupRevenueDetail actor={creationActor} groupKeys={[creationActor.group_key]} /></div>)}diff --git a/products/conversations/frontend/scenes/ticket/groupRevenue.test.ts b/products/conversations/frontend/scenes/ticket/groupRevenue.test.tsnew file mode 100644index 000000000000..ee6b5a8fa51e--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/groupRevenue.test.ts@@ -0,0 +1,62 @@+import { GroupRevenue, GroupRevenueAnalyticsRow, resolveGroupRevenue } from './groupRevenue'++describe('resolveGroupRevenue', () => {+ it.each<[string, GroupRevenueAnalyticsRow | undefined, Record<string, any> | undefined, GroupRevenue]>([+ [+ 'revenue analytics wins over group properties',+ { mrr: 100, lifetimeValue: 2000 },+ { mrr: 5, customer_lifetime_value: 50 },+ {+ mrr: { value: 100, source: 'revenue-analytics' },+ lifetimeValue: { value: 2000, source: 'revenue-analytics' },+ },+ ],+ [+ 'a zero from revenue analytics is a value, not a gap',+ { mrr: 0, lifetimeValue: 2000 },+ { mrr: 5 },+ {+ mrr: { value: 0, source: 'revenue-analytics' },+ lifetimeValue: { value: 2000, source: 'revenue-analytics' },+ },+ ],+ [+ 'falls back to group properties per field',+ { mrr: null, lifetimeValue: 2000 },+ { mrr: 5, customer_lifetime_value: 50 },+ {+ mrr: { value: 5, source: 'properties' },+ lifetimeValue: { value: 2000, source: 'revenue-analytics' },+ },+ ],+ [+ 'no revenue analytics row',+ undefined,+ { mrr: 5, customer_lifetime_value: 50 },+ {+ mrr: { value: 5, source: 'properties' },+ lifetimeValue: { value: 50, source: 'properties' },+ },+ ],+ [+ 'non-numeric group properties are ignored',+ undefined,+ { mrr: '5', customer_lifetime_value: NaN },+ {+ mrr: { value: null, source: null },+ lifetimeValue: { value: null, source: null },+ },+ ],+ [+ 'no data at all',+ undefined,+ undefined,+ {+ mrr: { value: null, source: null },+ lifetimeValue: { value: null, source: null },+ },+ ],+ ])('%s', (_label, analyticsRow, groupProperties, expected) => {+ expect(resolveGroupRevenue(analyticsRow, groupProperties)).toEqual(expected)+ })+})diff --git a/products/conversations/frontend/scenes/ticket/groupRevenue.ts b/products/conversations/frontend/scenes/ticket/groupRevenue.tsnew file mode 100644index 000000000000..368d0e22bff0--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/groupRevenue.ts@@ -0,0 +1,38 @@+export type GroupRevenueSource = 'revenue-analytics' | 'properties' | null++export interface GroupRevenueValue {+ value: number | null+ source: GroupRevenueSource+}++export interface GroupRevenue {+ mrr: GroupRevenueValue+ lifetimeValue: GroupRevenueValue+}++export interface GroupRevenueAnalyticsRow {+ mrr: number | null+ lifetimeValue: number | null+}++function resolveValue(analyticsValue: number | null | undefined, propertyValue: unknown): GroupRevenueValue {+ if (analyticsValue !== null && analyticsValue !== undefined) {+ return { value: analyticsValue, source: 'revenue-analytics' }+ }+ if (typeof propertyValue === 'number' && !isNaN(propertyValue)) {+ return { value: propertyValue, source: 'properties' }+ }+ return { value: null, source: null }+}++// Revenue analytics is the preferred source. The `mrr` and `customer_lifetime_value` group properties+// cover teams that set revenue on the group themselves, which matches the group page.+export function resolveGroupRevenue(+ analyticsRow: GroupRevenueAnalyticsRow | undefined,+ groupProperties: Record<string, any> | undefined+): GroupRevenue {+ return {+ mrr: resolveValue(analyticsRow?.mrr, groupProperties?.mrr),+ lifetimeValue: resolveValue(analyticsRow?.lifetimeValue, groupProperties?.customer_lifetime_value),+ }+}diff --git a/products/conversations/frontend/scenes/ticket/groupRevenueLogic.ts b/products/conversations/frontend/scenes/ticket/groupRevenueLogic.tsnew file mode 100644index 000000000000..1d5d245b1544--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/groupRevenueLogic.ts@@ -0,0 +1,99 @@+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import api from 'lib/api'++import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'++import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/customer_analytics/frontend/constants'++import { GroupRevenueAnalyticsRow } from './groupRevenue'++export type GroupRevenueLogicProps = {+ groupKeys: string[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface groupRevenueLogicValues {+ revenueByGroupKey: Record<string, GroupRevenueAnalyticsRow>+ revenueByGroupKeyLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface groupRevenueLogicActions {+ loadRevenue: () => any+ loadRevenueFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRevenueSuccess: (+ revenueByGroupKey: Record<string, GroupRevenueAnalyticsRow>,+ payload?: any+ ) => {+ revenueByGroupKey: Record<string, GroupRevenueAnalyticsRow>+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface groupRevenueLogicMeta {+ key: string+}++export type groupRevenueLogicType = MakeLogicType<+ groupRevenueLogicValues,+ groupRevenueLogicActions,+ GroupRevenueLogicProps,+ groupRevenueLogicMeta+>++export const groupRevenueLogic = kea<groupRevenueLogicType>([+ props({} as GroupRevenueLogicProps),+ key((props) => [...props.groupKeys].sort().join(',')),+ path((key) => ['products', 'conversations', 'frontend', 'scenes', 'ticket', 'groupRevenueLogic', key]),+ loaders(({ props }) => ({+ revenueByGroupKey: [+ {} as Record<string, GroupRevenueAnalyticsRow>,+ {+ loadRevenue: async () => {+ if (props.groupKeys.length === 0) {+ return {}+ }+ try {+ const response = await api.query<HogQLQuery>({+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ group_key,+ toFloat(sum(mrr)),+ toFloat(sum(revenue))+ FROM groups_revenue_analytics+ WHERE group_key IN {groupKeys}+ GROUP BY group_key+ `,+ values: { groupKeys: props.groupKeys },+ tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,+ })++ const revenueByGroupKey: Record<string, GroupRevenueAnalyticsRow> = {}+ for (const [groupKey, mrr, lifetimeValue] of response?.results ?? []) {+ revenueByGroupKey[groupKey] = { mrr: mrr ?? null, lifetimeValue: lifetimeValue ?? null }+ }+ return revenueByGroupKey+ } catch (error) {+ // The panel falls back to the revenue group properties, so the failure is not surfaced.+ posthog.captureException(error, { tag: 'ticket_group_revenue_query_failed' })+ return {}+ }+ },+ },+ ],+ })),+ afterMount(({ actions }) => {+ actions.loadRevenue()+ }),+])diff --git a/products/groups/frontend/components/RelatedGroups.tsx b/products/groups/frontend/components/RelatedGroups.tsxindex eff24e9ff729..49d65f91273b 100644--- a/products/groups/frontend/components/RelatedGroups.tsx+++ b/products/groups/frontend/components/RelatedGroups.tsx@@ -8,7 +8,7 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { capitalizeFirstLetter } from 'lib/utils/strings'import { groupsModel } from '~/models/groupsModel'-import { ActorType } from '~/types'+import { ActorType, GroupActorType } from '~/types'import { relatedGroupsLogic } from 'products/groups/frontend/logics/relatedGroupsLogic'import { GroupActorDisplay } from 'products/persons/frontend/components/GroupActorDisplay'@@ -32,6 +32,8 @@ export interface RelatedGroupsProps {highlightStaleTooltip?: string/** Extra group rows to append (deduped by id), e.g. a group not in the live related list. */extraActors?: ActorType[]+ /** Extra content shown under a group's name, e.g. figures the caller loads for that group. */+ renderGroupDetail?: (actor: GroupActorType) => React.ReactNode}export function RelatedGroups({@@ -46,6 +48,7 @@ export function RelatedGroups({highlightStale = false,highlightStaleTooltip,extraActors,+ renderGroupDetail,}: RelatedGroupsProps): JSX.Element {const { relatedActors, relatedPeople, relatedActorsLoading } = useValues(relatedGroupsLogic({ groupTypeIndex, id }))const { aggregationLabel } = useValues(groupsModel)@@ -80,7 +83,7 @@ export function RelatedGroups({render: function RenderActor(_, actor: ActorType) {if (actor.type === 'group') {const isHighlighted = highlightGroupKey != null && actor.group_key === highlightGroupKey- return (+ const nameRow = (<div className="flex items-center gap-2"><GroupActorDisplay actor={actor} />{isHighlighted && highlightLabel && (@@ -99,6 +102,15 @@ export function RelatedGroups({)}</div>)+ if (!renderGroupDetail) {+ return nameRow+ }+ return (+ <div className="flex flex-col gap-1">+ {nameRow}+ {renderGroupDetail(actor)}+ </div>+ )}return <PersonDisplay person={actor} withIcon={false} />},@@ -111,6 +123,7 @@ export function RelatedGroups({highlightLabelTooltip,highlightStale,highlightStaleTooltip,+ renderGroupDetail,])