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.

feat(error-tracking): email the people affected by an issue (#112998)

Daniel Marchuke2473b60c797
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
index 215ee6bba9ee..4f7e2204d700 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
@@ -25,6 +25,7 @@ import { ErrorTrackingRelationalIssue, ProductIntentContext, ProductKey } from '
import { ExternalReferences } from '../../../components/ExternalReferences'
import { manageFingerprintsLogic } from '../../../components/FingerprintPreview/manageFingerprintsLogic'
import { errorTrackingIssueSceneLogic } from '../errorTrackingIssueSceneLogic'
+import { IssueAffectedBroadcastButton } from './IssueAffectedBroadcastButton'
import { IssueCohort } from './IssueCohort'
import { IssueWorkflowButton } from './IssueWorkflowButton'
@@ -45,6 +46,7 @@ export const ErrorTrackingIssueScenePanel = ({
<ScenePanelDivider />
<ScenePanelActionsSection>
<CreateSurveyButton />
+ <IssueAffectedBroadcastButton issueId={issue.id} issueName={issue.name} />
<IssueWorkflowButton issueId={issue.id} />
<SceneComment dataAttrKey="issue" />
<SceneShareButton
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastButton.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastButton.tsx
new file mode 100644
index 000000000000..49e543229d35
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastButton.tsx
@@ -0,0 +1,21 @@
+import { useActions } from 'kea'
+
+import { IconSend } from '@posthog/icons'
+
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+
+import { IssueAffectedBroadcastLogicProps, issueAffectedBroadcastLogic } from './issueAffectedBroadcastLogic'
+import { IssueAffectedBroadcastModal } from './IssueAffectedBroadcastModal'
+
+export function IssueAffectedBroadcastButton(props: IssueAffectedBroadcastLogicProps): JSX.Element {
+ const { openModal } = useActions(issueAffectedBroadcastLogic(props))
+ return (
+ <>
+ <ButtonPrimitive fullWidth onClick={openModal} data-attr="issue-panel-email-affected">
+ <IconSend />
+ Email the people affected
+ </ButtonPrimitive>
+ <IssueAffectedBroadcastModal {...props} />
+ </>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx
new file mode 100644
index 000000000000..bc74a533dd6e
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx
@@ -0,0 +1,84 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+import {
+ AFFECTED_LOOKBACK_DAYS,
+ IssueAffectedBroadcastLogicProps,
+ issueAffectedBroadcastLogic,
+} from './issueAffectedBroadcastLogic'
+
+export function IssueAffectedBroadcastModal(props: IssueAffectedBroadcastLogicProps): JSX.Element {
+ const logic = issueAffectedBroadcastLogic(props)
+ const { isModalOpen, affectedCount, affectedCountLoading, countFailed, audienceCohortLoading } = useValues(logic)
+ const { closeModal, createAudience } = useActions(logic)
+
+ const lookback = `the last ${AFFECTED_LOOKBACK_DAYS} days`
+ const disabledReason = affectedCountLoading
+ ? 'Counting the people affected'
+ : countFailed
+ ? "Couldn't count the people affected"
+ : !affectedCount?.people
+ ? `Nobody hit this issue in ${lookback}`
+ : !affectedCount.withEmail
+ ? 'Nobody affected has an email address'
+ : undefined
+
+ return (
+ <LemonModal
+ isOpen={isModalOpen}
+ onClose={closeModal}
+ title="Email the people affected"
+ width={480}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={createAudience}
+ loading={audienceCohortLoading}
+ disabledReason={disabledReason}
+ data-attr="issue-affected-broadcast-continue"
+ >
+ Continue to broadcast
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-2">
+ {affectedCountLoading ? (
+ <div className="flex items-center gap-2">
+ <Spinner />
+ Counting the people affected
+ </div>
+ ) : countFailed ? (
+ <p className="m-0">Couldn't count the people affected. Close this and try again.</p>
+ ) : !affectedCount?.people ? (
+ <p className="m-0">Nobody hit this issue in {lookback}, so there is no one to email.</p>
+ ) : !affectedCount.withEmail ? (
+ <p className="m-0">
+ <strong>{pluralize(affectedCount.people, 'person', 'people')}</strong> hit this issue in{' '}
+ {lookback}, but nobody affected has an email address, so there is no one to email.
+ </p>
+ ) : (
+ <>
+ <p className="m-0">
+ <strong>{pluralize(affectedCount.people, 'person', 'people')}</strong> hit this issue in{' '}
+ {lookback}. {humanFriendlyNumber(affectedCount.withEmail)} of them{' '}
+ {pluralize(affectedCount.withEmail, 'has', 'have', false)} an email address. Only people
+ with an email address receive the broadcast.
+ </p>
+ <p className="m-0 text-secondary">
+ Continuing saves these people as a static cohort and opens a new broadcast to them.
+ </p>
+ </>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.test.ts
new file mode 100644
index 000000000000..7d1824aa9b60
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.test.ts
@@ -0,0 +1,55 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { cohortsCreate } from 'products/cohorts/frontend/generated/api'
+import { parseBroadcastAudiencePrefill } from 'products/workflows/frontend/Broadcasts/broadcastAudiencePrefill'
+
+import { issueAffectedBroadcastLogic } from './issueAffectedBroadcastLogic'
+
+jest.mock('products/cohorts/frontend/generated/api', () => ({
+ cohortsCreate: jest.fn(),
+}))
+
+const mockCohortsCreate = jest.mocked(cohortsCreate)
+
+describe('issueAffectedBroadcastLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ mockCohortsCreate.mockResolvedValue({ id: 42, name: 'People affected by Checkout timeout' } as never)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('saves the affected people as a static cohort and opens a broadcast to it', async () => {
+ const logic = issueAffectedBroadcastLogic({ issueId: 'issue-1', issueName: 'Checkout timeout' })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.createAudience()
+ }).toDispatchActions(['createAudienceSuccess'])
+
+ const body = mockCohortsCreate.mock.calls[0][1]
+ expect(body).toMatchObject({
+ name: 'People affected by Checkout timeout',
+ is_static: true,
+ query: {
+ query: expect.stringMatching(
+ /^SELECT DISTINCT person_id FROM events WHERE event = '\$exception' AND issue_id = 'issue-1'/
+ ),
+ },
+ })
+
+ const { pathname, searchParams } = router.values.currentLocation
+ expect(pathname).toContain('/broadcasts/new')
+ expect(searchParams.name).toEqual('We fixed Checkout timeout')
+ expect(searchParams.source).toEqual('error_tracking_affected')
+ expect(parseBroadcastAudiencePrefill(searchParams.audience)).toMatchObject([
+ { type: 'cohort', key: 'id', value: 42 },
+ ])
+ logic.unmount()
+ })
+})
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts
new file mode 100644
index 000000000000..cc23c5d7b80d
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts
@@ -0,0 +1,200 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { truncate } from 'lib/utils/strings'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { hogqlQuery } from '~/queries/query'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { HogQLQueryString, hogql } from '~/queries/utils'
+
+import { cohortsCreate } from 'products/cohorts/frontend/generated/api'
+import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'
+import {
+ captureMessageAudienceClicked,
+ cohortAudienceProperties,
+ messageAudienceUrl,
+} from 'products/workflows/frontend/MessageAudience/messageAudience'
+
+export const AFFECTED_LOOKBACK_DAYS = 30
+// pinned: sent as the broadcast's entry_source and the click event's source, so renaming it splits the history
+const SOURCE = 'error_tracking_affected'
+const MAX_NAME_LENGTH = 200
+
+export interface IssueAffectedBroadcastLogicProps {
+ issueId: string
+ issueName: string | null
+}
+
+export interface AffectedPeopleCount {
+ people: number
+ withEmail: number
+}
+
+export function affectedPeopleQuery(issueId: string, select: 'count' | 'people'): HogQLQueryString {
+ const where = hogql`event = '$exception' AND issue_id = ${issueId} AND timestamp >= now() - toIntervalDay(${AFFECTED_LOOKBACK_DAYS})`
+ return select === 'count'
+ ? (`SELECT uniqExact(person_id), uniqExactIf(person_id, notEmpty(toString(person.properties.email))) FROM events WHERE ${where}` as HogQLQueryString)
+ : (`SELECT DISTINCT person_id FROM events WHERE ${where}` as HogQLQueryString)
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface issueAffectedBroadcastLogicValues {
+ currentProjectId: number | string // teamLogic
+ affectedCount: AffectedPeopleCount | null
+ affectedCountLoading: boolean
+ audienceCohort: CohortApi | null
+ audienceCohortLoading: boolean
+ countFailed: boolean
+ isModalOpen: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface issueAffectedBroadcastLogicActions {
+ closeModal: () => {
+ value: true
+ }
+ createAudience: () => any
+ createAudienceFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ createAudienceSuccess: (
+ audienceCohort: CohortApi,
+ payload?: any
+ ) => {
+ audienceCohort: CohortApi
+ payload?: any
+ }
+ loadAffectedCount: () => any
+ loadAffectedCountFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAffectedCountSuccess: (
+ affectedCount: {
+ people: number
+ withEmail: number
+ },
+ payload?: any
+ ) => {
+ affectedCount: {
+ people: number
+ withEmail: number
+ }
+ payload?: any
+ }
+ openModal: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface issueAffectedBroadcastLogicMeta {
+ key: string
+}
+
+export type issueAffectedBroadcastLogicType = MakeLogicType<
+ issueAffectedBroadcastLogicValues,
+ issueAffectedBroadcastLogicActions,
+ IssueAffectedBroadcastLogicProps,
+ issueAffectedBroadcastLogicMeta
+>
+
+export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>([
+ path((issueId) => [
+ 'products',
+ 'error_tracking',
+ 'scenes',
+ 'ErrorTrackingIssueScene',
+ 'ScenePanel',
+ 'issueAffectedBroadcastLogic',
+ issueId,
+ ]),
+ props({} as IssueAffectedBroadcastLogicProps),
+ key((props) => props.issueId),
+ connect(() => ({ values: [teamLogic, ['currentProjectId']] })),
+
+ actions({
+ openModal: true,
+ closeModal: true,
+ }),
+
+ reducers({
+ isModalOpen: [
+ false,
+ {
+ openModal: () => true,
+ closeModal: () => false,
+ },
+ ],
+ countFailed: [
+ false,
+ {
+ loadAffectedCount: () => false,
+ loadAffectedCountFailure: () => true,
+ },
+ ],
+ }),
+
+ loaders(({ props, values }) => ({
+ affectedCount: [
+ null as AffectedPeopleCount | null,
+ {
+ loadAffectedCount: async () => {
+ const response = await hogqlQuery(affectedPeopleQuery(props.issueId, 'count'))
+ const [people, withEmail] = (response.results?.[0] ?? [0, 0]) as [number, number]
+ return { people, withEmail }
+ },
+ },
+ ],
+ audienceCohort: [
+ null as CohortApi | null,
+ {
+ createAudience: async () => {
+ const issueName = props.issueName || 'this issue'
+ return await cohortsCreate(String(values.currentProjectId), {
+ name: truncate(`People affected by ${issueName}`, MAX_NAME_LENGTH),
+ is_static: true,
+ query: { kind: NodeKind.HogQLQuery, query: affectedPeopleQuery(props.issueId, 'people') },
+ })
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions, props }) => ({
+ openModal: () => {
+ actions.loadAffectedCount()
+ },
+ createAudienceSuccess: ({ audienceCohort }) => {
+ if (!audienceCohort) {
+ return
+ }
+ actions.closeModal()
+ router.actions.push(
+ messageAudienceUrl(
+ {
+ properties: cohortAudienceProperties(audienceCohort),
+ source: SOURCE,
+ broadcastName: truncate(`We fixed ${props.issueName || 'an error'}`, MAX_NAME_LENGTH),
+ },
+ 'broadcast'
+ )
+ )
+ captureMessageAudienceClicked(SOURCE, 'broadcast')
+ },
+ createAudienceFailure: () => {
+ lemonToast.error("Couldn't save the people affected. Try again.")
+ },
+ })),
+])