:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): send a broadcast from a cohort (#112993)
Daniel Marchukeba05dfe0e81
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex 9a1484d7fb2a..ebb0f5b972e7 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -8,6 +8,7 @@ import {IconCopy,IconExpand,IconInfo,+ IconLetter,IconRefresh,IconSend,IconTrash,@@ -64,12 +65,18 @@ import { ActivityScope, CohortType, InsightShortId, SidePanelTab } from '~/typesimport type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'import { CohortRealtimeStatus } from 'products/cohorts/frontend/realtime/CohortRealtimeStatus'+import { captureMessageAudienceClicked } from 'products/workflows/frontend/MessageAudience/messageAudience'import { AddPersonToCohortModal } from './AddPersonToCohortModal'import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'import { cohortCountWarningLogic } from './cohortCountWarningLogic'import { CohortSceneMenuBar } from './CohortSceneMenuBar'-import { createCohortDataNodeLogicKey, urlForCohortWorkflow } from './cohortUtils'+import {+ cohortBroadcastDisabledReason,+ createCohortDataNodeLogicKey,+ urlForCohortBroadcast,+ urlForCohortWorkflow,+} from './cohortUtils'import { PersonSelectList } from './PersonSelectList'import { PersonDisplayNameType, RemovePersonFromCohortButton } from './RemovePersonFromCohortButton'@@ -240,6 +247,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {const { openSidePanel } = useActions(sidePanelStateLogic)const isNewCohort = cohort.id === 'new' || cohort.id === undefined+ const broadcastDisabledReason = cohortBroadcastDisabledReason(cohort)const dataNodeLogicKey = createCohortDataNodeLogicKey(cohort.id)const warningLogic = cohortCountWarningLogic({ cohort, query: effectiveQuery, dataNodeLogicKey })const { shouldShowCountWarning } = useValues(warningLogic)@@ -302,6 +310,22 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {<IconSend /> Message this cohort</ButtonPrimitive>+ <ButtonPrimitive+ onClick={() => {+ if (typeof cohort.id !== 'number') {+ return+ }+ captureMessageAudienceClicked('cohort', 'broadcast')+ router.actions.push(urlForCohortBroadcast({ id: cohort.id, name: cohort.name }))+ }}+ disabledReasons={broadcastDisabledReason ? { [broadcastDisabledReason]: true } : {}}+ data-attr={`${RESOURCE_TYPE}-send-broadcast`}+ tooltip="Send a one-time email to everyone in this cohort"+ menuItem+ >+ <IconLetter /> Send a broadcast+ </ButtonPrimitive>+<SceneAddToNotebookDropdownMenudataAttrKey={RESOURCE_TYPE}disabledReasons={{diff --git a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsxindex 91b121a50642..6d6d0df959e8 100644--- a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx+++ b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { IconClock, IconCopy, IconRefresh, IconSend, IconTrash } from '@posthog/icons'+import { IconClock, IconCopy, IconLetter, IconRefresh, IconSend, IconTrash } from '@posthog/icons'import { LemonDialog } from '@posthog/lemon-ui'import { SceneMenuBarAddToNotebook } from 'lib/components/Scenes/SceneMenuBarAddToNotebook'@@ -9,7 +9,7 @@ import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileIteimport { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'-import { urlForCohortWorkflow } from 'scenes/cohorts/cohortUtils'+import { cohortBroadcastDisabledReason, urlForCohortBroadcast, urlForCohortWorkflow } from 'scenes/cohorts/cohortUtils'import { NotebookNodeType } from 'scenes/notebooks/types'import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'import { urls } from 'scenes/urls'@@ -23,6 +23,8 @@ import {} from '~/layout/scenes/components/SceneMenuBar'import { CohortType } from '~/types'+import { captureMessageAudienceClicked } from 'products/workflows/frontend/MessageAudience/messageAudience'+const RESOURCE_TYPE = 'cohort'export function CohortSceneMenuBar({ id }: { id?: CohortType['id'] }): JSX.Element | null {@@ -47,6 +49,7 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Elementconst isDeleted = cohort.deletedconst cohortIdNumber = typeof cohort.id === 'number' ? cohort.id : undefined+ const broadcastDisabledReason = cohortBroadcastDisabledReason(cohort)return (<SceneMenuBar>@@ -61,6 +64,20 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element<IconSend />Message this cohort</SceneMenuBarItem>+ <SceneMenuBarItem+ onClick={() => {+ captureMessageAudienceClicked('cohort', 'broadcast')+ router.actions.push(+ urlForCohortBroadcast({ id: cohortIdNumber, name: cohort.name })+ )+ }}+ disabled={!!broadcastDisabledReason}+ tooltip={broadcastDisabledReason ?? undefined}+ data-attr={`${RESOURCE_TYPE}-menubar-send-broadcast`}+ >+ <IconLetter />+ Send a broadcast+ </SceneMenuBarItem><SceneMenuBarAddToNotebookdataAttrKey={RESOURCE_TYPE}notebookSelectButtonProps={{diff --git a/frontend/src/scenes/cohorts/cohortUtils.test.tsx b/frontend/src/scenes/cohorts/cohortUtils.test.tsxindex 8c0b6df6e35f..a3a89180ba38 100644--- a/frontend/src/scenes/cohorts/cohortUtils.test.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.test.tsx@@ -3,12 +3,19 @@ import { BehavioralFilterKey, CohortClientErrors } from 'scenes/cohorts/CohortFiimport {cleanBehavioralTypeCriteria,cleanCriteria,+ cohortBroadcastDisabledReason,criteriaToHumanSentence,determineFilterType,validateGroup,} from 'scenes/cohorts/cohortUtils'-import { AnyCohortCriteriaType, BehavioralEventType, CohortCriteriaGroupFilter, FilterLogicalOperator } from '~/types'+import {+ AnyCohortCriteriaType,+ BehavioralEventType,+ CohortCriteriaGroupFilter,+ CohortType,+ FilterLogicalOperator,+} from '~/types'describe('validateGroup', () => {function groupWithNegatedCriteria(criteria: AnyCohortCriteriaType[]): CohortCriteriaGroupFilter {@@ -229,3 +236,33 @@ describe('criteria whose value collides with an Object.prototype key', () => {})})++describe('cohortBroadcastDisabledReason', () => {+ const behavioral = { type: BehavioralFilterKey.Behavioral, value: BehavioralEventType.PerformEvent }+ const person = { type: BehavioralFilterKey.Person, key: 'email', value: 'is_set' }+ const cohort = (criteria: AnyCohortCriteriaType[], overrides: Partial<CohortType> = {}): CohortType => ({+ id: 1,+ groups: [],+ filters: {+ properties: {+ type: FilterLogicalOperator.Or,+ values: [{ type: FilterLogicalOperator.And, values: criteria }],+ },+ },+ ...overrides,+ })++ it.each([+ ['a property-based cohort', cohort([person as AnyCohortCriteriaType]), null],+ ['a static cohort built from events', cohort([behavioral as AnyCohortCriteriaType], { is_static: true }), null],+ [+ 'an event condition in a nested group',+ cohort([person, behavioral] as AnyCohortCriteriaType[]),+ "Broadcasts can't send to cohorts with event conditions. Use a static or property-based cohort.",+ ],+ ['an unsaved cohort', cohort([], { id: 'new' }), 'Save the cohort first'],+ ['a deleted cohort', cohort([], { deleted: true }), 'Restore the cohort first'],+ ])('for %s', (_, input, expected) => {+ expect(cohortBroadcastDisabledReason(input)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex 3f64a98b8a52..d447e1cfdfe6 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -37,6 +37,10 @@ import {TimeUnitType,} from '~/types'+import {+ cohortAudienceProperties,+ messageAudienceUrl,+} from 'products/workflows/frontend/MessageAudience/messageAudience'import { urlForNewWorkflowWithTrigger } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'/**@@ -707,3 +711,28 @@ export const COHORT_MATCHING_DAYS = {'14': '2 weeks','30': 'month',}++function hasBehavioralCriteria(group: CohortCriteriaGroupFilter | AnyCohortCriteriaType): boolean {+ if ('values' in group && Array.isArray(group.values)) {+ return (group.values as (CohortCriteriaGroupFilter | AnyCohortCriteriaType)[]).some(hasBehavioralCriteria)+ }+ return group.type === BehavioralFilterKey.Behavioral+}++/** Why a broadcast can't send to this cohort, mirroring the batch audience check on the server. */+export function cohortBroadcastDisabledReason(cohort: CohortType): string | null {+ if (typeof cohort.id !== 'number') {+ return 'Save the cohort first'+ }+ if (cohort.deleted) {+ return 'Restore the cohort first'+ }+ if (!cohort.is_static && cohort.filters?.properties && hasBehavioralCriteria(cohort.filters.properties)) {+ return "Broadcasts can't send to cohorts with event conditions. Use a static or property-based cohort."+ }+ return null+}++export function urlForCohortBroadcast(cohort: { id: number; name?: string }): string {+ return messageAudienceUrl({ properties: cohortAudienceProperties(cohort), source: 'cohort' }, 'broadcast')+}