: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(workflows): warn before sending when a message entry point can't deliver (#114833)
Daniel Marchuk64fe05a3603f
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex 88672161a72c..b9ddd4bca1e6 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -61,6 +61,7 @@ import {captureMessageAudienceClicked,messageAudienceAccessDisabledReason,} from 'products/workflows/frontend/MessageAudience/messageAudience'+import { messageAudienceOpenLogic } from 'products/workflows/frontend/MessageAudience/messageAudienceOpenLogic'import { AddPersonToCohortModal } from './AddPersonToCohortModal'import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'@@ -68,9 +69,9 @@ import { cohortCountWarningLogic } from './cohortCountWarningLogic'import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'import { CohortSceneMenuBar } from './CohortSceneMenuBar'import {+ cohortBroadcastAudience,cohortBroadcastDisabledReason,createCohortDataNodeLogicKey,- urlForCohortBroadcast,urlForCohortWorkflow,} from './cohortUtils'import { PersonSelectList } from './PersonSelectList'@@ -245,6 +246,9 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {const isNewCohort = cohort.id === 'new' || cohort.id === undefinedconst accessDisabledReason = messageAudienceAccessDisabledReason()const broadcastDisabledReason = cohortBroadcastDisabledReason(cohort) ?? accessDisabledReason+ const broadcastLogic = messageAudienceOpenLogic({ audience: cohortBroadcastAudience(cohort) })+ const { opening: openingBroadcast } = useValues(broadcastLogic)+ const { open: openBroadcast } = useActions(broadcastLogic)const dataNodeLogicKey = createCohortDataNodeLogicKey(cohort.id)const warningLogic = cohortCountWarningLogic({ cohort, query: effectiveQuery, dataNodeLogicKey })const { shouldShowCountWarning } = useValues(warningLogic)@@ -296,14 +300,11 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {<ScenePanelActionsSection><ButtonPrimitive- onClick={() => {- if (typeof cohort.id !== 'number') {- return- }- captureMessageAudienceClicked('cohort', 'broadcast')- router.actions.push(urlForCohortBroadcast({ id: cohort.id, name: cohort.name }))+ onClick={() => openBroadcast('broadcast')}+ disabledReasons={{+ ...(broadcastDisabledReason ? { [broadcastDisabledReason]: true } : {}),+ 'Checking whether this email can go out': openingBroadcast,}}- disabledReasons={broadcastDisabledReason ? { [broadcastDisabledReason]: true } : {}}data-attr={`${RESOURCE_TYPE}-send-broadcast`}tooltip="Send a one-time email to everyone in this cohort"menuItemdiff --git a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsxindex ca1f8eee8eee..65109b1f9d8c 100644--- a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx+++ b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx@@ -9,7 +9,11 @@ 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 { cohortBroadcastDisabledReason, urlForCohortBroadcast, urlForCohortWorkflow } from 'scenes/cohorts/cohortUtils'+import {+ cohortBroadcastAudience,+ cohortBroadcastDisabledReason,+ urlForCohortWorkflow,+} from 'scenes/cohorts/cohortUtils'import { NotebookNodeType } from 'scenes/notebooks/types'import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'import { urls } from 'scenes/urls'@@ -27,6 +31,7 @@ import {captureMessageAudienceClicked,messageAudienceAccessDisabledReason,} from 'products/workflows/frontend/MessageAudience/messageAudience'+import { openMessageAudience } from 'products/workflows/frontend/MessageAudience/messageAudienceWarnings'const RESOURCE_TYPE = 'cohort'@@ -64,9 +69,7 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element<SceneMenuBarItemonClick={() => {captureMessageAudienceClicked('cohort', 'broadcast')- router.actions.push(- urlForCohortBroadcast({ id: cohortIdNumber, name: cohort.name })- )+ void openMessageAudience(cohortBroadcastAudience(cohort), 'broadcast')}}disabled={!!broadcastDisabledReason}tooltip={broadcastDisabledReason ?? undefined}diff --git a/frontend/src/scenes/cohorts/cohortSavedToast.ts b/frontend/src/scenes/cohorts/cohortSavedToast.tsindex 3c329b398986..2f66ab6728fd 100644--- a/frontend/src/scenes/cohorts/cohortSavedToast.ts+++ b/frontend/src/scenes/cohorts/cohortSavedToast.ts@@ -9,8 +9,8 @@ import {captureMessageAudienceClicked,cohortAudienceProperties,messageAudienceAccessDisabledReason,- messageAudienceUrl,} from 'products/workflows/frontend/MessageAudience/messageAudience'+import { openMessageAudience } from 'products/workflows/frontend/MessageAudience/messageAudienceWarnings'/** Confirms a static cohort saved from a list of people, with links to the cohort and to a broadcast for it. */export function cohortSavedToast(cohort: Pick<CohortType, 'id' | 'name'>, source: string, toastId?: string): void {@@ -28,15 +28,13 @@ export function cohortSavedToast(cohort: Pick<CohortType, 'id' | 'name'>, sourcedataAttr: `message-audience-${source}-broadcast`,action: () => {captureMessageAudienceClicked(source, 'broadcast')- router.actions.push(- messageAudienceUrl(- {- properties: cohortAudienceProperties(savedCohort),- source,- draftSource: { source: 'cohort', source_id: String(savedCohort.id) },- },- 'broadcast'- )+ void openMessageAudience(+ {+ properties: cohortAudienceProperties(savedCohort),+ source,+ draftSource: { source: 'cohort', source_id: String(savedCohort.id) },+ },+ 'broadcast')},},diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex 7ba7b01bd24e..7cd4b2a7a106 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -37,10 +37,7 @@ import {TimeUnitType,} from '~/types'-import {- cohortAudienceProperties,- messageAudienceUrl,-} from 'products/workflows/frontend/MessageAudience/messageAudience'+import { MessageAudience, cohortAudienceProperties } from 'products/workflows/frontend/MessageAudience/messageAudience'import { urlForNewWorkflowWithTrigger } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'/**@@ -727,13 +724,13 @@ export function cohortBroadcastDisabledReason(cohort: CohortType): string | nullreturn null}-export function urlForCohortBroadcast(cohort: { id: number; name?: string }): string {- return messageAudienceUrl(- {- properties: cohortAudienceProperties(cohort),- source: 'cohort',- draftSource: { source: 'cohort', source_id: String(cohort.id) },- },- 'broadcast'- )+export function cohortBroadcastAudience(cohort: Pick<CohortType, 'id' | 'name'>): MessageAudience {+ if (typeof cohort.id !== 'number') {+ return { properties: [], source: 'cohort' }+ }+ return {+ properties: cohortAudienceProperties({ id: cohort.id, name: cohort.name }),+ source: 'cohort',+ draftSource: { source: 'cohort', source_id: String(cohort.id) },+ }}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsxindex a582a5e0910d..f03b41d1f31f 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueAffectedBroadcastModal.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'import { humanFriendlyNumber } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'@@ -13,7 +13,8 @@ import {export function IssueAffectedBroadcastModal(props: IssueAffectedBroadcastLogicProps): JSX.Element {const logic = issueAffectedBroadcastLogic(props)- const { isModalOpen, affectedCount, affectedCountLoading, countFailed, audienceCohortLoading } = useValues(logic)+ const { isModalOpen, affectedCount, affectedCountLoading, countFailed, audienceCohortLoading, sendWarnings } =+ useValues(logic)const { closeModal, createAudience } = useActions(logic)const lookback = `the last ${AFFECTED_LOOKBACK_DAYS} days`@@ -51,6 +52,11 @@ export function IssueAffectedBroadcastModal(props: IssueAffectedBroadcastLogicPr}><div className="flex flex-col gap-2">+ {sendWarnings.map((warning) => (+ <LemonBanner key={warning} type="warning">+ {warning}+ </LemonBanner>+ ))}{affectedCountLoading ? (<div className="flex items-center gap-2"><Spinner />diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.tsindex e8236c88b08a..20bd54039900 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts@@ -18,6 +18,7 @@ import {cohortAudienceProperties,messageAudienceUrl,} from 'products/workflows/frontend/MessageAudience/messageAudience'+import { loadMessageAudienceWarnings } from 'products/workflows/frontend/MessageAudience/messageAudienceWarnings'import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'export const AFFECTED_LOOKBACK_DAYS = 30@@ -51,6 +52,8 @@ export interface issueAffectedBroadcastLogicValues {audienceCohortLoading: booleancountFailed: booleanisModalOpen: boolean+ sendWarnings: string[]+ sendWarningsLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -94,6 +97,21 @@ export interface issueAffectedBroadcastLogicActions {}payload?: any}+ loadSendWarnings: () => any+ loadSendWarningsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSendWarningsSuccess: (+ sendWarnings: string[],+ payload?: any+ ) => {+ sendWarnings: string[]+ payload?: any+ }openModal: () => {value: true}@@ -148,6 +166,14 @@ export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>(}),loaders(({ props, values }) => ({+ sendWarnings: [+ [] as string[],+ {+ // The audience cohort doesn't exist until Continue, so only the sender problems apply here.+ loadSendWarnings: async () =>+ await loadMessageAudienceWarnings({ properties: [], source: SOURCE }, 'broadcast'),+ },+ ],affectedCount: [null as AffectedPeopleCount | null,{@@ -175,14 +201,16 @@ export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>(listeners(({ actions, props }) => ({openModal: () => {+ // The click on the entry point, before any outcome, so abandoned attempts count too.+ captureMessageAudienceClicked(SOURCE, 'broadcast')actions.loadAffectedCount()+ actions.loadSendWarnings()},createAudienceSuccess: ({ audienceCohort }) => {if (!audienceCohort) {return}actions.closeModal()- captureMessageAudienceClicked(SOURCE, 'broadcast', { succeeded: true })router.actions.push(messageAudienceUrl({@@ -197,7 +225,6 @@ export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>()},createAudienceFailure: () => {- captureMessageAudienceClicked(SOURCE, 'broadcast', { succeeded: false })lemonToast.error("Couldn't save the people affected. Try again.")},})),diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.test.tsindex 05ce15a2dc42..6c9a51ec0792 100644--- a/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts@@ -24,20 +24,29 @@ describe('audienceList', () => {it.each([{cohort: 'an uploaded list still matching',- state: { isStatic: true, isCalculating: true, failed: false },+ state: { isStatic: true, isCalculating: true, calculatedBefore: false, failed: false },expected: '"List" is still matching people. You can launch when it finishes.',},{cohort: 'an uploaded list that failed to match',- state: { isStatic: true, isCalculating: false, failed: true },+ state: { isStatic: true, isCalculating: false, calculatedBefore: true, failed: true },expected: '"List" couldn\'t match its people. Remove it from the recipients, or upload the list again.',},- { cohort: 'a matched list', state: { isStatic: true, isCalculating: false, failed: false }, expected: null },+ {+ cohort: 'a matched list',+ state: { isStatic: true, isCalculating: false, calculatedBefore: true, failed: false },+ expected: null,+ },{cohort: 'a dynamic cohort recalculating',- state: { isStatic: false, isCalculating: true, failed: false },+ state: { isStatic: false, isCalculating: true, calculatedBefore: true, failed: false },expected: null,},+ {+ cohort: 'a new dynamic cohort before its first calculation',+ state: { isStatic: false, isCalculating: true, calculatedBefore: false, failed: false },+ expected: '"List" is still calculating who\'s in it. You can launch when it finishes.',+ },])('decides whether $cohort blocks launch', ({ state, expected }) => {const cohort = { id: 42, name: 'List', count: null, importTotal: null, importUnmatched: null, ...state }expect(audienceCohortLaunchError(cohort)).toEqual(expected)diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.tsindex e82278399e3d..063d05da034d 100644--- a/products/workflows/frontend/Broadcasts/audience/audienceList.ts+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.ts@@ -91,6 +91,7 @@ export function toAudienceCohort(id: number, cohort: CohortApi): AudienceCohortname: cohort.name ?? `Cohort ${id}`,isStatic: !!cohort.is_static,isCalculating: !!cohort.is_calculating,+ calculatedBefore: !!cohort.last_calculation,failed: (cohort.errors_calculating ?? 0) > 0 && !cohort.is_calculating,count: cohort.count ?? null,importTotal: cohort.last_import_total_count ?? null,@@ -101,11 +102,13 @@ export function toAudienceCohort(id: number, cohort: CohortApi): AudienceCohort/*** Why a cohort in the audience stops a launch. A batch sends to the members a cohort has when it runs, so an* uploaded list that is still matching would reach only part of the list. A dynamic cohort keeps its members- * while it recalculates, so it never blocks.+ * while it recalculates, so it blocks only before its first calculation, when a send can find no one in it.*/export function audienceCohortLaunchError(cohort: AudienceCohort): string | null {if (!cohort.isStatic) {- return null+ return cohort.isCalculating && !cohort.calculatedBefore+ ? `"${cohort.name}" is still calculating who's in it. You can launch when it finishes.`+ : null}if (cohort.isCalculating) {return `"${cohort.name}" is still matching people. You can launch when it finishes.`diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.tsindex d8028ccfec17..5d79cbe20f26 100644--- a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts@@ -15,6 +15,8 @@ export interface AudienceCohort {name: stringisStatic: booleanisCalculating: boolean+ // False until the first calculation finishes. A dynamic cohort has no stored members before that.+ calculatedBefore: booleanfailed: booleancount: number | null// Set for a cohort made from a list: how many people were on it and how many of them PostHog didn't find.diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsindex cb6ba813a051..3bfc4eb5898d 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -52,6 +52,7 @@ import type {} from 'products/workflows/frontend/generated/api.schemas'import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'+import { UNVERIFIED_SENDER_MESSAGE } from '../Channels/emailSendingMessages'import {AiEmailDraftResult,DRAFT_SOURCE_PARAM,@@ -2211,7 +2212,7 @@ export function getSenderLaunchError(integrations.find((integration) => integration.kind === 'email' && integration.id === id)?.config?.verified === true)- return allVerified ? null : "Verify the sender's domain before sending"+ return allVerified ? null : UNVERIFIED_SENDER_MESSAGE}export function getSenderIds(from: BroadcastEmailValue['from'] | undefined): number[] {diff --git a/products/workflows/frontend/Channels/emailSendingMessages.ts b/products/workflows/frontend/Channels/emailSendingMessages.tsnew file mode 100644index 000000000000..1573829036cf--- /dev/null+++ b/products/workflows/frontend/Channels/emailSendingMessages.ts@@ -0,0 +1,6 @@+export const EMAIL_SENDING_SUSPENDED_MESSAGE =+ 'Email sending is suspended for this project. Workflow and broadcast emails are not being delivered.'++export const UNVERIFIED_SENDER_MESSAGE = "Verify the sender's domain before sending"++export const NO_EMAIL_SENDER_MESSAGE = 'Set up an email sender before sending'diff --git a/products/workflows/frontend/EmailSuspensionBanner.tsx b/products/workflows/frontend/EmailSuspensionBanner.tsxindex 2d3fb2e43732..6ab51e39c9fa 100644--- a/products/workflows/frontend/EmailSuspensionBanner.tsx+++ b/products/workflows/frontend/EmailSuspensionBanner.tsx@@ -2,6 +2,7 @@ import { useValues } from 'kea'import { LemonBanner } from '@posthog/lemon-ui'+import { EMAIL_SENDING_SUSPENDED_MESSAGE } from './Channels/emailSendingMessages'import { workflowsEmailSuspensionLogic } from './workflowsEmailSuspensionLogic'export function EmailSuspensionBanner(): JSX.Element | null {@@ -13,7 +14,7 @@ export function EmailSuspensionBanner(): JSX.Element | null {return (<LemonBanner type="error" data-attr="workflows-email-suspended-banner">- Email sending is suspended for this project. Workflow and broadcast emails are not being delivered.+ {EMAIL_SENDING_SUSPENDED_MESSAGE}{emailSendingSuspensionReason ? <> Reason: {emailSendingSuspensionReason}.</> : null} Contact support to getsending re-enabled.</LemonBanner>diff --git a/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx b/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsxindex 349016ed79a5..af092f9b15a9 100644--- a/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx+++ b/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx@@ -1,15 +1,10 @@-import { router } from 'kea-router'+import { useActions, useValues } from 'kea'import { IconSend } from '@posthog/icons'import { LemonButton, LemonButtonProps, LemonMenu } from '@posthog/lemon-ui'-import {- MessageAudience,- MessageAudienceDestination,- captureMessageAudienceClicked,- messageAudienceAccessDisabledReason,- messageAudienceUrl,-} from './messageAudience'+import { MessageAudience, MessageAudienceDestination, messageAudienceAccessDisabledReason } from './messageAudience'+import { messageAudienceOpenLogic } from './messageAudienceOpenLogic'const DESTINATION_LABELS: Record<MessageAudienceDestination, string> = {broadcast: 'Send a one-time email',@@ -34,16 +29,16 @@ export function MessageAudienceButton({disabledReason,fullWidth,}: MessageAudienceButtonProps): JSX.Element {- const open = (destination: MessageAudienceDestination): void => {- captureMessageAudienceClicked(audience.source, destination)- router.actions.push(messageAudienceUrl(audience, destination))- }+ const logic = messageAudienceOpenLogic({ audience })+ const { opening } = useValues(logic)+ const { open } = useActions(logic)const buttonProps = {type,size,disabledReason: disabledReason ?? messageAudienceAccessDisabledReason(),fullWidth,icon: <IconSend />,+ loading: opening,}if (destinations.length === 1) {diff --git a/products/workflows/frontend/MessageAudience/messageAudience.ts b/products/workflows/frontend/MessageAudience/messageAudience.tsindex 5468f6e69682..16f1437d7db9 100644--- a/products/workflows/frontend/MessageAudience/messageAudience.ts+++ b/products/workflows/frontend/MessageAudience/messageAudience.ts@@ -58,13 +58,9 @@ export function messageAudienceUrl(audience: MessageAudience, destination: Messa)}-export function captureMessageAudienceClicked(- source: string,- destination: MessageAudienceDestination,- extra: { succeeded?: boolean } = {}-): void {+export function captureMessageAudienceClicked(source: string, destination: MessageAudienceDestination): void {// pinned: analytics event name- posthog.capture('message audience clicked', { source, destination, ...extra })+ posthog.capture('message audience clicked', { source, destination })}/** Why this person can't start a broadcast or workflow, if they can't: both need editor access to workflows. */diff --git a/products/workflows/frontend/MessageAudience/messageAudienceOpenLogic.ts b/products/workflows/frontend/MessageAudience/messageAudienceOpenLogic.tsnew file mode 100644index 000000000000..9e8715b7230b--- /dev/null+++ b/products/workflows/frontend/MessageAudience/messageAudienceOpenLogic.ts@@ -0,0 +1,67 @@+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'++import { MessageAudience, MessageAudienceDestination, captureMessageAudienceClicked } from './messageAudience'+import { openMessageAudience } from './messageAudienceWarnings'++export interface MessageAudienceOpenLogicProps {+ audience: MessageAudience+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface messageAudienceOpenLogicValues {+ opening: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface messageAudienceOpenLogicActions {+ open: (destination: MessageAudienceDestination) => {+ destination: MessageAudienceDestination+ }+ openFinished: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface messageAudienceOpenLogicMeta {+ key: string+}++export type messageAudienceOpenLogicType = MakeLogicType<+ messageAudienceOpenLogicValues,+ messageAudienceOpenLogicActions,+ MessageAudienceOpenLogicProps,+ messageAudienceOpenLogicMeta+>++export const messageAudienceOpenLogic = kea<messageAudienceOpenLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'MessageAudience', 'messageAudienceOpenLogic', key]),+ props({} as MessageAudienceOpenLogicProps),+ key((props) => `${props.audience.source}:${JSON.stringify(props.audience.properties)}`),++ actions({+ open: (destination: MessageAudienceDestination) => ({ destination }),+ openFinished: true,+ }),++ reducers({+ opening: [+ false,+ {+ open: () => true,+ openFinished: () => false,+ },+ ],+ }),++ listeners(({ actions, props }) => ({+ open: async ({ destination }) => {+ captureMessageAudienceClicked(props.audience.source, destination)+ try {+ await openMessageAudience(props.audience, destination)+ } finally {+ actions.openFinished()+ }+ },+ })),+])diff --git a/products/workflows/frontend/MessageAudience/messageAudienceWarnings.test.ts b/products/workflows/frontend/MessageAudience/messageAudienceWarnings.test.tsnew file mode 100644index 000000000000..5ac223a19584--- /dev/null+++ b/products/workflows/frontend/MessageAudience/messageAudienceWarnings.test.ts@@ -0,0 +1,107 @@+import { initKeaTests } from '~/test/init'+import { PropertyFilterType, PropertyOperator } from '~/types'++import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'+import { integrationsList } from 'products/integrations/frontend/generated/api'+import { hogFlowsEmailSendingSuspensionRetrieve } from 'products/workflows/frontend/generated/api'++import { MessageAudience, MessageAudienceDestination } from './messageAudience'+import { loadMessageAudienceWarnings } from './messageAudienceWarnings'++jest.mock('products/cohorts/frontend/generated/api', () => ({ cohortsRetrieve: jest.fn() }))+jest.mock('products/integrations/frontend/generated/api', () => ({ integrationsList: jest.fn() }))+jest.mock('products/workflows/frontend/generated/api', () => ({ hogFlowsEmailSendingSuspensionRetrieve: jest.fn() }))++const SUSPENDED = 'Email sending is suspended for this project. Workflow and broadcast emails are not being delivered.'+const LIST_MATCHING = '"Signups" is still matching people. You can launch when it finishes.'++const verified = { kind: 'email', config: { verified: true } }+const unverified = { kind: 'email', config: { verified: false } }+const matchingList = { name: 'Signups', is_static: true, is_calculating: true, last_calculation: null }+const audience: MessageAudience = {+ source: 'cohort',+ properties: [{ key: 'id', type: PropertyFilterType.Cohort, value: 7, operator: PropertyOperator.In }],+}++describe('loadMessageAudienceWarnings', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it.each<{+ case: string+ destination: MessageAudienceDestination+ suspended?: boolean+ senders?: object[] | Error+ morePages?: boolean+ cohort?: object | Error+ expected: string[]+ }>([+ { case: 'nothing wrong', destination: 'broadcast', expected: [] },+ {+ case: 'no sender while sending is suspended',+ destination: 'broadcast',+ suspended: true,+ senders: [],+ expected: [SUSPENDED, 'Set up an email sender before sending'],+ },+ {+ case: 'only unverified senders',+ destination: 'broadcast',+ senders: [unverified],+ expected: ["Verify the sender's domain before sending"],+ },+ {+ case: 'unverified senders on the first of several pages',+ destination: 'broadcast',+ senders: [unverified],+ morePages: true,+ expected: [],+ },+ { case: 'a list still matching', destination: 'broadcast', cohort: matchingList, expected: [LIST_MATCHING] },+ { case: 'a workflow, which ignores the list', destination: 'workflow', cohort: matchingList, expected: [] },+ {+ case: 'checks that fail',+ destination: 'broadcast',+ senders: new Error('down'),+ cohort: new Error('down'),+ expected: [],+ },+ ])(+ 'reports $case',+ async ({ destination, suspended = false, senders = [verified], morePages, cohort, expected }) => {+ jest.mocked(hogFlowsEmailSendingSuspensionRetrieve).mockResolvedValue({+ email_sending_suspended: suspended,+ } as never)+ jest.mocked(integrationsList).mockImplementation(async () => {+ if (senders instanceof Error) {+ throw senders+ }+ return { count: senders.length, results: senders, next: morePages ? 'page-2' : null } as never+ })+ jest.mocked(cohortsRetrieve).mockImplementation(async () => {+ if (cohort instanceof Error) {+ throw cohort+ }+ return (cohort ?? { name: 'Signups', is_static: true, is_calculating: false }) as never+ })++ expect(await loadMessageAudienceWarnings(audience, destination)).toEqual(expected)+ }+ )++ it('gives up on a check that never answers', async () => {+ jest.useFakeTimers()+ try {+ jest.mocked(hogFlowsEmailSendingSuspensionRetrieve).mockReturnValue(new Promise(() => {}))+ jest.mocked(integrationsList).mockResolvedValue({ count: 0, results: [] } as never)++ const warnings = loadMessageAudienceWarnings(audience, 'workflow')+ await jest.advanceTimersByTimeAsync(5000)++ expect(await warnings).toEqual(['Set up an email sender before sending'])+ } finally {+ jest.useRealTimers()+ }+ })+})diff --git a/products/workflows/frontend/MessageAudience/messageAudienceWarnings.tsx b/products/workflows/frontend/MessageAudience/messageAudienceWarnings.tsxnew file mode 100644index 000000000000..03758588a586--- /dev/null+++ b/products/workflows/frontend/MessageAudience/messageAudienceWarnings.tsx@@ -0,0 +1,122 @@+import { router } from 'kea-router'++import { LemonDialog } from '@posthog/lemon-ui'++import { ApiConfig } from 'lib/api'+import { urls } from 'scenes/urls'++import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'+import { integrationsList } from 'products/integrations/frontend/generated/api'+import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'+import { hogFlowsEmailSendingSuspensionRetrieve } from 'products/workflows/frontend/generated/api'++import { audienceCohortIds, audienceCohortLaunchError, toAudienceCohort } from '../Broadcasts/audience/audienceList'+import {+ EMAIL_SENDING_SUSPENDED_MESSAGE,+ NO_EMAIL_SENDER_MESSAGE,+ UNVERIFIED_SENDER_MESSAGE,+} from '../Channels/emailSendingMessages'+import { MessageAudience, MessageAudienceDestination, messageAudienceUrl } from './messageAudience'++export function emailSenderWarning(integrations: Pick<IntegrationConfigApi, 'kind' | 'config'>[]): string | null {+ const senders = integrations.filter((integration) => integration.kind === 'email')+ if (senders.length === 0) {+ return NO_EMAIL_SENDER_MESSAGE+ }+ const verified = senders.some(+ (integration) => (integration.config as { verified?: boolean } | undefined)?.verified === true+ )+ return verified ? null : UNVERIFIED_SENDER_MESSAGE+}++// The checks only advise, so a slow one must not hold the person on the page.+const CHECK_TIMEOUT_MS = 5000++function withinTimeout<T>(request: Promise<T>): Promise<T | null> {+ return Promise.race([+ request.catch(() => null),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), CHECK_TIMEOUT_MS)),+ ])+}++/**+ * What would stop the email from going out, checked when the person clicks so the entry point costs nothing+ * on page view. A check that fails or times out stays quiet: the broadcast launch and the workflow editor check again.+ */+export async function loadMessageAudienceWarnings(+ audience: MessageAudience,+ destination: MessageAudienceDestination+): Promise<string[]> {+ const projectId = String(ApiConfig.getCurrentProjectId())+ // A workflow sends per person as they qualify, so a cohort that is still calculating doesn't hold it up.+ const cohortIds = destination === 'broadcast' ? audienceCohortIds(audience.properties) : []+ const [suspension, integrations, cohorts] = await Promise.all([+ withinTimeout(hogFlowsEmailSendingSuspensionRetrieve(projectId)),+ withinTimeout(integrationsList(projectId, { kind: 'email' })),+ Promise.all(+ cohortIds.map((id) =>+ withinTimeout(cohortsRetrieve(projectId, id).then((cohort) => toAudienceCohort(id, cohort)))+ )+ ),+ ])+ return [+ suspension?.email_sending_suspended ? EMAIL_SENDING_SUSPENDED_MESSAGE : null,+ // A verified sender can sit on a later page, so only a complete list can say none is verified.+ integrations && !integrations.next ? emailSenderWarning(integrations.results) : null,+ ...cohorts.map((cohort) => (cohort ? audienceCohortLaunchError(cohort) : null)),+ ].filter((warning): warning is string => !!warning)+}++let opening = false++/**+ * Opens the broadcast or workflow, asking first when something would stop the email from going out. A second click+ * while the checks run does nothing.+ */+export async function openMessageAudience(+ audience: MessageAudience,+ destination: MessageAudienceDestination+): Promise<void> {+ if (opening) {+ return+ }+ opening = true+ try {+ const navigate = async (): Promise<void> => {+ router.actions.push(messageAudienceUrl(audience, destination))+ }+ const startedOn = router.values.location.pathname+ const warnings = await loadMessageAudienceWarnings(audience, destination)+ if (router.values.location.pathname !== startedOn) {+ // The person left the page while the checks ran.+ return+ }+ if (warnings.length === 0) {+ await navigate()+ return+ }+ // The modal covers the entry point, and Continue shows its own loading state while it opens the email.+ LemonDialog.open({+ title: 'Before you send',+ content: (+ <ul className="list-disc pl-4 m-0 flex flex-col gap-1" data-attr="message-audience-warnings">+ {warnings.map((warning) => (+ <li key={warning}>{warning}</li>+ ))}+ </ul>+ ),+ shouldAwaitSubmit: true,+ primaryButton: {+ children: 'Continue',+ onClick: navigate,+ 'data-attr': `message-audience-${audience.source}-continue`,+ },+ secondaryButton:+ warnings.includes(NO_EMAIL_SENDER_MESSAGE) || warnings.includes(UNVERIFIED_SENDER_MESSAGE)+ ? { children: 'Set up email', onClick: () => router.actions.push(urls.workflows('channels')) }+ : { children: 'Cancel' },+ })+ } finally {+ opening = false+ }+}