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(workflows): warn when email recipients lack the to-field property (#114111)

Daniel Marchuk125548f941cd
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index ef0509b25cec..49d7e03c19bb 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -435,6 +435,48 @@ describe('broadcastWizardLogic', () => {
expect(logic.values.stepValidationErrors.review).toEqual(expected)
})
+ it('counts the audience missing the To field property on the review step only, and never for an unfiltered audience', async () => {
+ const missingByProperty: Record<string, number> = { email: 98, $email: 0 }
+ const checkedFilters: { key: string; operator?: string }[][] = []
+ useMocks({
+ post: {
+ '/api/projects/:team_id/hog_flows/user_blast_radius/': async ({ request }) => {
+ const { filters } = (await request.json()) as {
+ filters: { properties: { key: string; operator?: string }[] }
+ }
+ const last = filters.properties[filters.properties.length - 1]
+ if (!last || last.operator !== PropertyOperator.IsNotSet) {
+ return [200, { affected: 98, total: 1000 }]
+ }
+ checkedFilters.push(filters.properties)
+ return [200, { affected: missingByProperty[last.key], total: 1000 }]
+ },
+ },
+ })
+ logic.actions.setAudienceProperties(LOCAL_AUDIENCE)
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ recipientsWithoutEmail: null })
+ expect(checkedFilters).toEqual([])
+
+ logic.actions.setStep('review')
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ recipientsWithoutEmail: 98 })
+ expect(checkedFilters.at(-1)).toEqual([
+ ...LOCAL_AUDIENCE,
+ { key: 'email', type: PropertyFilterType.Person, operator: PropertyOperator.IsNotSet },
+ ])
+
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, to: { email: '{{ person.properties.$email }}' } })
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ recipientsWithoutEmail: 0 })
+
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, to: { email: '[email protected]' } })
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ recipientsWithoutEmail: null })
+
+ const requestsBefore = checkedFilters.length
+ logic.actions.setEmail(DEFAULT_BROADCAST_EMAIL)
+ logic.actions.setAudienceProperties([])
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ recipientsWithoutEmail: null })
+ expect(checkedFilters).toHaveLength(requestsBefore)
+ })
+
it('starts a new broadcast with the only verified sender without creating a draft', async () => {
const createDraft = jest.fn()
useMocks({ post: { '/api/projects/:team_id/hog_flows/': () => createDraft() } })
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index e4af9b5650b9..d392e572c38e 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -15,7 +15,16 @@ import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { AnyPropertyFilter, Breadcrumb, IntegrationType, ResourceEditedEvent, TeamPublicType, TeamType } from '~/types'
+import {
+ AnyPropertyFilter,
+ Breadcrumb,
+ IntegrationType,
+ PropertyFilterType,
+ PropertyOperator,
+ ResourceEditedEvent,
+ TeamPublicType,
+ TeamType,
+} from '~/types'
import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
@@ -40,6 +49,7 @@ import type {
} from 'products/workflows/frontend/generated/api.schemas'
import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'
+import type { MissingRecipientEmailBannerProps } from '../Workflows/hogflows/steps/components/MissingRecipientEmailBanner'
import {
DEFAULT_STATE,
ONE_TIME_RRULE,
@@ -50,6 +60,7 @@ import {
stateToRRule,
} from '../Workflows/hogflows/steps/components/rrule-helpers'
import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
+import { recipientEmailProperty } from '../Workflows/hogflows/steps/recipientEmail'
import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'
import { audienceCohortIds, audienceCohortLaunchError, toAudienceCohort } from './audience/audienceList'
import {
@@ -242,9 +253,13 @@ export interface broadcastWizardLogicValues {
isReadOnly: boolean
launching: boolean
linkAudienceRejected: boolean
+ missingRecipientEmail: MissingRecipientEmailBannerProps | null
movingToDraft: boolean
name: string
rateLimitedSendDuration: string
+ recipientEmailProperty: string | null
+ recipientsWithoutEmail: number | null
+ recipientsWithoutEmailLoading: boolean
recurringRepeating: boolean
recurringStartsAt: string | null
saving: boolean
@@ -361,6 +376,21 @@ export interface broadcastWizardLogicActions {
loadExternalEdit: () => {
value: true
}
+ loadRecipientsWithoutEmail: (_: any) => any
+ loadRecipientsWithoutEmailFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRecipientsWithoutEmailSuccess: (
+ recipientsWithoutEmail: number | null,
+ payload?: any
+ ) => {
+ recipientsWithoutEmail: number | null
+ payload?: any
+ }
moveToDraft: () => {
value: true
}
@@ -496,6 +526,12 @@ export interface broadcastWizardLogicMeta {
) => BroadcastStatus
isReadOnly: (broadcast: HogFlowApi | null) => boolean
effectiveTimezone: (scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null) => string
+ recipientEmailProperty: (email: BroadcastEmailValue) => string | null
+ missingRecipientEmail: (
+ recipientEmailProperty: string | null,
+ recipientsWithoutEmail: number | null,
+ blastRadius: BlastRadiusApi | null
+ ) => MissingRecipientEmailBannerProps | null
selectedSender: (email: BroadcastEmailValue, integrations: IntegrationType[] | null) => IntegrationType | null
stepValidationErrors: (
goalEnabled: boolean,
@@ -609,7 +645,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
duplicateBroadcastFinished: true,
}),
- loaders(({ props, values }) => ({
+ loaders(({ props, values, cache }) => ({
broadcast: [
null as HogFlowApi | null,
{
@@ -635,6 +671,42 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
},
},
],
+ recipientsWithoutEmail: [
+ null as number | null,
+ {
+ loadRecipientsWithoutEmail: async (_, breakpoint) => {
+ await breakpoint(300)
+ const key = values.recipientEmailProperty
+ cache.checkedRecipientEmailProperty = key
+ // Checked only right before launch, and never for an unfiltered audience: its size is a
+ // cached total, and this count would be a scan of every person in the project.
+ if (
+ !values.currentProjectId ||
+ !key ||
+ values.currentStep !== 'review' ||
+ values.audienceProperties.length === 0
+ ) {
+ return null
+ }
+ try {
+ const missing = await hogFlowsUserBlastRadiusCreate(String(values.currentProjectId), {
+ filters: {
+ properties: [
+ ...values.audienceProperties,
+ { key, type: PropertyFilterType.Person, operator: PropertyOperator.IsNotSet },
+ ],
+ },
+ })
+ breakpoint()
+ return missing.affected
+ } catch {
+ breakpoint()
+ // A failed check must not block the send; it only drops the warning.
+ return null
+ }
+ },
+ },
+ ],
batchJobs: [
[] as HogFlowBatchJobApi[],
{
@@ -988,6 +1060,19 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
(scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null): string =>
scheduleTimezone ?? currentTeam?.timezone ?? dayjs.tz.guess(),
],
+ recipientEmailProperty: [
+ (s) => [s.email],
+ (email: BroadcastEmailValue): string | null => recipientEmailProperty(email.to?.email),
+ ],
+ missingRecipientEmail: [
+ (s) => [s.recipientEmailProperty, s.recipientsWithoutEmail, s.blastRadius],
+ (
+ property: string | null,
+ missing: number | null,
+ blastRadius: BlastRadiusApi | null
+ ): MissingRecipientEmailBannerProps | null =>
+ property && missing ? { property, missing, audienceSize: blastRadius?.affected } : null,
+ ],
selectedSender: [
(s) => [s.email, s.integrations],
(email: BroadcastEmailValue, integrations: IntegrationType[] | null): IntegrationType | null =>
@@ -1792,6 +1877,20 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
},
})),
+ listeners(({ actions, values, cache }) => ({
+ loadBlastRadius: () => {
+ actions.loadRecipientsWithoutEmail(null)
+ },
+ setEmail: () => {
+ if (
+ values.currentStep === 'review' &&
+ values.recipientEmailProperty !== cache.checkedRecipientEmailProperty
+ ) {
+ actions.loadRecipientsWithoutEmail(null)
+ }
+ },
+ })),
+
afterMount(({ actions, props }) => {
if (props.id !== 'new') {
actions.loadBroadcast()
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
index 6dc9e78ad638..2f9aef0b85e6 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
@@ -8,6 +8,7 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
+import { MissingRecipientEmailBanner } from '../../Workflows/hogflows/steps/components/MissingRecipientEmailBanner'
import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'
import { broadcastAudienceCohortsLogic } from '../audience/broadcastAudienceCohortsLogic'
import { BroadcastEmailPreview } from '../BroadcastEmailPreview'
@@ -53,7 +54,7 @@ function ReviewRow({
{error}
</LemonButton>
))}
- <div>{children}</div>
+ <div className="flex flex-col gap-2">{children}</div>
</div>
)
}
@@ -70,6 +71,7 @@ export function BroadcastReviewStep(): JSX.Element {
rateLimitedSendDuration,
stepValidationErrors,
emailSettings,
+ missingRecipientEmail,
} = useValues(broadcastWizardLogic)
const { categories } = useValues(optOutCategoriesLogic())
const category = categories.find((item) => item.id === emailSettings.messageCategoryId)
@@ -145,6 +147,7 @@ export function BroadcastReviewStep(): JSX.Element {
</ReviewRow>
<ReviewRow label="Email" step="content">
+ {missingRecipientEmail ? <MissingRecipientEmailBanner {...missingRecipientEmail} /> : null}
{!emailSettings.trackingEnabled && (
<div className="text-xs text-secondary">Open and click tracking is off.</div>
)}
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
index 692993260732..50b6a4b73c43 100644
--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
@@ -12,6 +12,8 @@ import { CyclotronJobInputSchemaType } from '~/types'
import { WorkflowLogicProps, workflowLogic } from '../workflowLogic'
import { hogFlowManualTriggerButtonLogic } from './HogFlowManualTriggerButtonLogic'
import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './steps/batchTriggerLogic'
+import { MissingRecipientEmailBanner } from './steps/components/MissingRecipientEmailBanner'
+import { recipientEmailProperties } from './steps/recipientEmail'
const TriggerPopover = ({
setPopoverVisible,
@@ -27,13 +29,14 @@ const TriggerPopover = ({
const isAccountAudience =
workflow?.trigger?.type === 'batch' && workflow.trigger.filters?.audience_type === 'accounts'
- const { blastRadius, blastRadiusLoading } = useValues(
+ const { blastRadius, blastRadiusLoading, recipientsWithoutEmail } = useValues(
batchTriggerLogic({
id: props.id,
filters: workflow?.trigger?.type === 'batch' ? workflow?.trigger?.filters : undefined,
// Account audiences carry no person, so email dedup never applies to them.
dedupeKey: isAccountAudience ? undefined : getAudienceDedupeKey(workflow),
sendsEmail: hogFlowSendsEmail(workflow),
+ recipientEmailProperties: isAccountAudience ? [] : recipientEmailProperties(workflow),
})
)
@@ -108,6 +111,14 @@ const TriggerPopover = ({
return (
<div className="flex flex-col gap-4 p-3 min-w-80 max-w-96">
{variablesSection}
+ {Object.entries(recipientsWithoutEmail).map(([property, missing]) => (
+ <MissingRecipientEmailBanner
+ key={property}
+ property={property}
+ missing={missing}
+ audienceSize={blastRadius?.affected}
+ />
+ ))}
<div className="flex justify-end border-t pt-3">
<LemonButton
type="primary"
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index 7a36cbbacbfc..abc062cffed5 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -563,7 +563,12 @@ function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; fil
const isAccountAudience = filters?.audience_type === 'accounts'
// Account audiences carry no person, so email dedup never applies to them.
const dedupeKey = isAccountAudience ? undefined : getAudienceDedupeKey(workflow)
- const logic = batchTriggerLogic({ id: actionId, filters, dedupeKey, sendsEmail: hogFlowSendsEmail(workflow) })
+ const logic = batchTriggerLogic({
+ id: actionId,
+ filters,
+ dedupeKey,
+ sendsEmail: hogFlowSendsEmail(workflow),
+ })
const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(logic)
if (blastRadiusLoading) {
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts
index 951f7a8ff818..c2c427de92ae 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts
@@ -1,5 +1,10 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
import { HogFlowAction } from '../types'
-import { getAudienceDedupeKey } from './batchTriggerLogic'
+import { batchTriggerLogic, getAudienceDedupeKey } from './batchTriggerLogic'
const emailAction = (toEmail: string | null): HogFlowAction =>
({
@@ -25,44 +30,92 @@ const emailAction = (toEmail: string | null): HogFlowAction =>
},
}) as any
-describe('getAudienceDedupeKey', () => {
- it.each([
- ['{{ person.properties.email }}', 'email' as const],
- ['{{person.properties.email}}', 'email' as const],
- [' {{ person.properties.email }} ', 'email' as const],
- ])('returns "email" for default recipient template %j', (template, expected) => {
- expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBe(expected)
- })
+describe('batchTriggerLogic', () => {
+ describe('getAudienceDedupeKey', () => {
+ it.each([
+ ['{{ person.properties.email }}', 'email' as const],
+ ['{{person.properties.email}}', 'email' as const],
+ [' {{ person.properties.email }} ', 'email' as const],
+ ])('returns "email" for default recipient template %j', (template, expected) => {
+ expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBe(expected)
+ })
+
+ it.each([
+ ['{{ person.properties.work_email }}', 'custom property'],
+ ['{{ person.properties.email || person.properties.work_email }}', 'computed expression'],
+ ['[email protected]', 'static address'],
+ ['', 'empty string'],
+ [null, 'missing inputs (no email input at all)'],
+ ] as [string | null, string][])(
+ 'returns undefined when recipient is %j (%s) — avoids deduping on the wrong key',
+ (template) => {
+ expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBeUndefined()
+ }
+ )
- it.each([
- ['{{ person.properties.work_email }}', 'custom property'],
- ['{{ person.properties.email || person.properties.work_email }}', 'computed expression'],
- ['[email protected]', 'static address'],
- ['', 'empty string'],
- [null, 'missing inputs (no email input at all)'],
- ] as [string | null, string][])(
- 'returns undefined when recipient is %j (%s) — avoids deduping on the wrong key',
- (template) => {
- expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBeUndefined()
- }
- )
+ it('returns undefined when there is no function_email action at all', () => {
+ const nonEmailAction = { id: 'a1', type: 'function', config: {} } as any
+ expect(getAudienceDedupeKey({ actions: [nonEmailAction] })).toBeUndefined()
+ expect(getAudienceDedupeKey({ actions: [] })).toBeUndefined()
+ expect(getAudienceDedupeKey({})).toBeUndefined()
+ expect(getAudienceDedupeKey(null)).toBeUndefined()
+ })
- it('returns undefined when there is no function_email action at all', () => {
- const nonEmailAction = { id: 'a1', type: 'function', config: {} } as any
- expect(getAudienceDedupeKey({ actions: [nonEmailAction] })).toBeUndefined()
- expect(getAudienceDedupeKey({ actions: [] })).toBeUndefined()
- expect(getAudienceDedupeKey({})).toBeUndefined()
- expect(getAudienceDedupeKey(null)).toBeUndefined()
+ it('returns undefined when any email action uses a non-default recipient — mixed workflows cannot dedupe consistently', () => {
+ expect(
+ getAudienceDedupeKey({
+ actions: [
+ emailAction('{{ person.properties.email }}'),
+ emailAction('{{ person.properties.work_email }}'),
+ ],
+ })
+ ).toBeUndefined()
+ })
})
- it('returns undefined when any email action uses a non-default recipient — mixed workflows cannot dedupe consistently', () => {
- expect(
- getAudienceDedupeKey({
- actions: [
- emailAction('{{ person.properties.email }}'),
- emailAction('{{ person.properties.work_email }}'),
- ],
+ describe('recipientsWithoutEmail', () => {
+ const audience = { properties: [{ key: 'plan', value: 'pro', operator: 'exact', type: 'person' }] }
+
+ beforeEach(() => {
+ useMocks({
+ post: {
+ '/api/projects/:team_id/hog_flows/user_blast_radius/': async ({ request }) => {
+ const { filters } = (await request.json()) as {
+ filters: { properties: { key: string; operator?: string }[] }
+ }
+ const last = filters.properties[filters.properties.length - 1]
+ const missing: Record<string, number> = { email: 98, $email: 0 }
+ return [
+ 200,
+ { affected: last.operator === 'is_not_set' ? missing[last.key] : 100, total: 1000 },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ it.each([
+ {
+ name: 'a filtered person',
+ audience_type: 'persons' as const,
+ properties: audience.properties,
+ expected: { email: 98, $email: 0 },
+ },
+ { name: 'an account', audience_type: 'accounts' as const, properties: audience.properties, expected: {} },
+ { name: 'an unfiltered person', audience_type: 'persons' as const, properties: [], expected: {} },
+ ])('counts each To property for $name audience', async ({ audience_type, properties, expected }) => {
+ const logic = batchTriggerLogic({
+ id: `test-${audience_type}-${properties.length}`,
+ filters: { properties, audience_type },
+ sendsEmail: true,
+ recipientEmailProperties: ['$email', 'email'],
})
- ).toBeUndefined()
+ logic.mount()
+ await expectLogic(logic)
+ .toDispatchActions(['loadRecipientsWithoutEmailSuccess'])
+ .toMatchValues({ recipientsWithoutEmail: expected })
+ logic.unmount()
+ })
})
})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
index 10a32d77d37a..2282d023e522 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
@@ -1,17 +1,27 @@
-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, propsChanged, reducers } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+} from 'kea'
import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
import { objectsEqual } from 'lib/utils/objects'
+import { projectLogic } from 'scenes/projectLogic'
+import { hogFlowsUserBlastRadiusCreate } from 'products/workflows/frontend/generated/api'
import { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'
import { HogFlowAction } from '../types'
-
-// Matches the default email template's `to.email` value: `{{ person.properties.email }}`, whitespace-tolerant.
-// Anything else (custom property, computed Liquid, static address) makes the dedupe key diverge from the
-// actual send target, so dedupe is skipped rather than applied wrongly.
-const DEFAULT_EMAIL_TO_TEMPLATE_RE = /^\s*\{\{\s*person\.properties\.email\s*\}\}\s*$/
+import { recipientEmailProperty } from './recipientEmail'
export function getAudienceDedupeKey(workflow?: { actions?: HogFlowAction[] } | null): 'email' | undefined {
// Mirrors the backend (`canDedupeByEmail` in `nodejs/src/cdp/cdp-api.ts`): batch sends dedupe by
@@ -21,8 +31,9 @@ export function getAudienceDedupeKey(workflow?: { actions?: HogFlowAction[] } |
return undefined
}
const allDefault = emailActions.every((action) => {
- const toEmail = (action as any)?.config?.inputs?.email?.value?.to?.email
- return typeof toEmail === 'string' && DEFAULT_EMAIL_TO_TEMPLATE_RE.test(toEmail)
+ // Any other recipient (custom property, computed Liquid, static address) makes the dedupe key
+ // diverge from the actual send target, so dedupe is skipped rather than applied wrongly.
+ return recipientEmailProperty((action as any)?.config?.inputs?.email?.value?.to?.email) === 'email'
})
return allDefault ? 'email' : undefined
}
@@ -44,14 +55,19 @@ export interface BatchTriggerLogicProps {
dedupeKey?: 'email'
/** Whether the workflow contains an email step, which decides if the tiered audience limit applies. */
sendsEmail?: boolean
+ /** Person properties the email steps send to. Each costs one extra audience query, so pass them only where shown. */
+ recipientEmailProperties?: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchTriggerLogicValues {
+ currentProjectId: number | null // projectLogic
blastRadius: BlastRadiusApi | null
blastRadiusError: string | null
blastRadiusLoading: boolean
filters: any
+ recipientsWithoutEmail: Record<string, number>
+ recipientsWithoutEmailLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -77,6 +93,25 @@ export interface batchTriggerLogicActions {
value: true
}
}
+ loadRecipientsWithoutEmail: (_: any) => any
+ loadRecipientsWithoutEmailFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRecipientsWithoutEmailSuccess: (
+ recipientsWithoutEmail: {
+ [k: string]: number
+ },
+ payload?: any
+ ) => {
+ recipientsWithoutEmail: {
+ [k: string]: number
+ }
+ payload?: any
+ }
setBlastRadiusError: (error: string | null) => {
error: string | null
}
@@ -98,6 +133,9 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([
path(['products', 'workflows', 'frontend', 'Workflows', 'hogflows', 'steps', 'batchTriggerLogic']),
props({} as BatchTriggerLogicProps),
key(({ id }) => `batch-trigger-logic-${id || 'new'}`),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
actions({
loadBlastRadius: true,
setBlastRadiusError: (error: string | null) => ({ error }),
@@ -114,7 +152,48 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([
},
],
})),
- loaders(({ props }) => ({
+ loaders(({ props, values }) => ({
+ recipientsWithoutEmail: [
+ {} as Record<string, number>,
+ {
+ loadRecipientsWithoutEmail: async (_, breakpoint) => {
+ const filters = props.filters
+ const projectId = values.currentProjectId
+ // An unfiltered audience's size is a cached total; this count would scan every person.
+ if (
+ !projectId ||
+ !filters ||
+ filters.audience_type === 'accounts' ||
+ !filters.properties?.length ||
+ !props.recipientEmailProperties?.length
+ ) {
+ return {}
+ }
+ const counts = await Promise.all(
+ props.recipientEmailProperties.map(async (key): Promise<[string, number] | null> => {
+ try {
+ const missing = await hogFlowsUserBlastRadiusCreate(String(projectId), {
+ filters: {
+ ...filters,
+ properties: [
+ ...(filters.properties ?? []),
+ { key, type: 'person', operator: 'is_not_set' },
+ ],
+ },
+ sends_email: props.sendsEmail,
+ })
+ return [key, missing.affected]
+ } catch {
+ // A failed check must not block the run; it only drops the warning.
+ return null
+ }
+ })
+ )
+ breakpoint()
+ return Object.fromEntries(counts.filter((count): count is [string, number] => count !== null))
+ },
+ },
+ ],
blastRadius: [
null as BlastRadiusApi | null,
{
@@ -132,6 +211,9 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([
],
})),
listeners(({ actions }) => ({
+ loadBlastRadius: () => {
+ actions.loadRecipientsWithoutEmail(null)
+ },
loadBlastRadiusFailure: ({ errorObject }) => {
const apiError = errorObject as ApiError | undefined
const message =
@@ -149,6 +231,8 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([
props.sendsEmail !== oldProps.sendsEmail
) {
actions.loadBlastRadius()
+ } else if (!objectsEqual(props.recipientEmailProperties, oldProps.recipientEmailProperties)) {
+ actions.loadRecipientsWithoutEmail(null)
}
}),
afterMount(({ actions }) => {
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/MissingRecipientEmailBanner.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/MissingRecipientEmailBanner.tsx
new file mode 100644
index 000000000000..f99d484de799
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/MissingRecipientEmailBanner.tsx
@@ -0,0 +1,45 @@
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+export interface MissingRecipientEmailBannerProps {
+ /** The person property the To field reads. */
+ property: string
+ /** How many people in the audience have no value for it. */
+ missing: number
+ /** The audience size, when known. A missing count at or above it means nobody has the property. */
+ audienceSize?: number
+}
+
+export function MissingRecipientEmailBanner({
+ property,
+ missing,
+ audienceSize,
+}: MissingRecipientEmailBannerProps): JSX.Element | null {
+ if (missing <= 0) {
+ return null
+ }
+ const code = <code className="break-words">{property}</code>
+ const nobody = audienceSize != null && missing >= audienceSize
+
+ return (
+ <LemonBanner type="warning">
+ {nobody ? (
+ <>Nobody in this audience has the {code} property, so this email won't reach anyone. </>
+ ) : (
+ <>
+ About {humanFriendlyNumber(missing)} people in this audience have no {code} property, so they won't
+ get this email.{' '}
+ </>
+ )}
+ {property === 'email' ? (
+ <>
+ Set the To field to <code className="whitespace-nowrap">{"{{ person.properties['$email'] }}"}</code>{' '}
+ if their address is in <code>$email</code>.
+ </>
+ ) : (
+ <>Set the To field to the property that holds their email address.</>
+ )}
+ </LemonBanner>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.test.ts
new file mode 100644
index 000000000000..9734acacfc8c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.test.ts
@@ -0,0 +1,38 @@
+import { recipientEmailProperties, recipientEmailProperty } from './recipientEmail'
+
+describe('recipientEmailProperty', () => {
+ it.each([
+ { to: '{{ person.properties.email }}', expected: 'email' },
+ { to: '{{person.properties.$email}}', expected: '$email' },
+ { to: ' {{ person.properties.work_email }} ', expected: 'work_email' },
+ { to: "{{ person.properties['$email'] }}", expected: '$email' },
+ { to: "{{person.properties['$email']}}", expected: '$email' },
+ { to: '{{ person.properties["$email"] }}', expected: '$email' },
+ { to: "{{ person.properties[ 'work email' ] }}", expected: 'work email' },
+ { to: '{{ person.properties[\'$email"] }}', expected: null },
+ { to: '[email protected]', expected: null },
+ { to: '{{ person.properties.email }}, [email protected]', expected: null },
+ { to: '{{ person.properties.email | default: "[email protected]" }}', expected: null },
+ { to: '', expected: null },
+ { to: undefined, expected: null },
+ ])('reads $expected from "$to"', ({ to, expected }) => {
+ expect(recipientEmailProperty(to)).toEqual(expected)
+ })
+
+ it('lists each property the email steps send to once', () => {
+ const email = (to: string): any => ({
+ type: 'function_email',
+ config: { inputs: { email: { value: { to: { email: to } } } } },
+ })
+ const workflow = {
+ actions: [
+ email('{{ person.properties.email }}'),
+ email("{{ person.properties['$email'] }}"),
+ email('{{ person.properties.email }}'),
+ email('[email protected]'),
+ { type: 'delay', config: {} } as any,
+ ],
+ }
+ expect(recipientEmailProperties(workflow)).toEqual(['$email', 'email'])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.ts b/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.ts
new file mode 100644
index 000000000000..2fcc26ce18c2
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/recipientEmail.ts
@@ -0,0 +1,19 @@
+import { HogFlowAction } from '../types'
+
+const PERSON_PROPERTY_TEMPLATE =
+ /^\s*\{\{\s*person\.properties(?:\.([\w$-]+)|\[\s*'([^'\\]+)'\s*\]|\[\s*"([^"\\]+)"\s*\])\s*\}\}\s*$/
+
+/** The person property the To field reads, or null for a fixed address or any other template. */
+export function recipientEmailProperty(to: string | undefined): string | null {
+ const match = to?.match(PERSON_PROPERTY_TEMPLATE)
+ return match?.[1] ?? match?.[2] ?? match?.[3] ?? null
+}
+
+/** The distinct person properties the workflow's email steps send to. */
+export function recipientEmailProperties(workflow?: { actions?: HogFlowAction[] } | null): string[] {
+ const properties = (workflow?.actions ?? [])
+ .filter((action) => action.type === 'function_email')
+ .map((action) => recipientEmailProperty((action as any)?.config?.inputs?.email?.value?.to?.email))
+ .filter((property): property is string => property !== null)
+ return [...new Set(properties)].sort()
+}