: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): add messaging settings and a sending rules step to setup (#118415)
Meikel Ratzfeb0662b5a9d
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex a79f6f55e713..ef920c95fcc3 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -381,6 +381,7 @@ export const productRoutes: Record<string, [string, string]> = {'/broadcasts/opt-outs': ['Broadcasts', 'broadcasts'],'/broadcasts/suppression': ['Broadcasts', 'broadcasts'],'/broadcasts/reputation': ['Broadcasts', 'broadcasts'],+ '/broadcasts/settings': ['Broadcasts', 'broadcasts'],'/broadcasts/new': ['Broadcast', 'broadcast'],'/broadcasts/:id': ['Broadcast', 'broadcast'],}@@ -3352,6 +3353,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [{ name: 'Opt-outs', href: urls.workflows('opt-outs') },{ name: 'Suppression list', href: urls.workflows('suppression') },{ name: 'Reputation', href: urls.workflows('reputation') },+ { name: 'Settings', href: urls.workflows('settings') },],type: 'workflows',category: ProductItemCategory.MESSAGING,diff --git a/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts b/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.tsindex d61905473ee4..2d2d072295d8 100644--- a/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts@@ -40,6 +40,7 @@ describe('broadcasts routes', () => {['/broadcasts/opt-outs', 'Broadcasts'],['/broadcasts/suppression', 'Broadcasts'],['/broadcasts/reputation', 'Broadcasts'],+ ['/broadcasts/settings', 'Broadcasts'],['/broadcasts/new', 'Broadcast'],['/broadcasts/01a05e5e-38c2-0000-b81a-21fe48581914', 'Broadcast'],])('opens %s in the %s scene', (url, scene) => {diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex a7af4b7b9e0b..21b2bdd49139 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -42,6 +42,7 @@ const WORKFLOW_SCENE_TABS = ['opt-outs','suppression','reputation',+ 'settings','onboarding',] as constexport type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]@@ -66,6 +67,7 @@ export interface workflowsSceneLogicActions {| 'onboarding'| 'opt-outs'| 'reputation'+ | 'settings'| 'suppression'| 'templates'| 'workflows'@@ -83,6 +85,7 @@ export interface workflowsSceneLogicMeta {| 'onboarding'| 'opt-outs'| 'reputation'+ | 'settings'| 'suppression'| 'templates'| 'workflows'diff --git a/products/workflows/frontend/messagingTabs.tsx b/products/workflows/frontend/messagingTabs.tsxindex 46c0a0eb257d..b7ba20eda65e 100644--- a/products/workflows/frontend/messagingTabs.tsx+++ b/products/workflows/frontend/messagingTabs.tsx@@ -1,3 +1,5 @@+import { Settings } from 'scenes/settings/Settings'+import { MessageChannels } from './Channels/MessageChannels'import { OptOutScene } from './OptOuts/OptOutScene'import { SuppressionScene } from './Suppression/SuppressionScene'@@ -5,11 +7,18 @@ import { MessageTemplatesTable } from './TemplateLibrary/MessageTemplatesTable'import { WorkflowsReputation } from './Workflows/Reputation/WorkflowsReputation'// pinned: URL path segments under /workflows and /broadcasts - renaming breaks bookmarks-export const MESSAGING_NAV_TAB_KEYS = ['library', 'channels', 'opt-outs', 'suppression', 'reputation'] as const+export const MESSAGING_NAV_TAB_KEYS = [+ 'library',+ 'channels',+ 'opt-outs',+ 'suppression',+ 'reputation',+ 'settings',+] as constexport type MessagingNavTabKey = (typeof MESSAGING_NAV_TAB_KEYS)[number]/** The tabs that configure sending, grouped under one "Messaging" tab. */-export const MESSAGING_SETUP_TAB_KEYS = ['channels', 'opt-outs', 'suppression', 'reputation'] as const+export const MESSAGING_SETUP_TAB_KEYS = ['channels', 'opt-outs', 'suppression', 'reputation', 'settings'] as constexport type MessagingSetupTabKey = (typeof MESSAGING_SETUP_TAB_KEYS)[number]export const MESSAGING_TAB_LABELS: Record<MessagingNavTabKey, string> = {@@ -18,6 +27,7 @@ export const MESSAGING_TAB_LABELS: Record<MessagingNavTabKey, string> = {'opt-outs': 'Opt-outs',suppression: 'Suppression list',reputation: 'Reputation',+ settings: 'Settings',}export const MESSAGING_TAB_CONTENT: Record<MessagingNavTabKey, JSX.Element> = {@@ -26,6 +36,9 @@ export const MESSAGING_TAB_CONTENT: Record<MessagingNavTabKey, JSX.Element> = {'opt-outs': <OptOutScene />,suppression: <SuppressionScene />,reputation: <WorkflowsReputation />,+ settings: (+ <Settings logicKey="workflowsMessagingSettings" sectionId="environment-workflows" handleLocally hideSections />+ ),}export function isMessagingSetupTab(tab: string): tab is MessagingSetupTabKey {diff --git a/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsxindex e0bfab0e3971..9a3a92ad8761 100644--- a/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx+++ b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx@@ -8,23 +8,12 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { teamLogic } from 'scenes/teamLogic'-// Kept in step with the max_value on TeamWorkflowsConfigSerializer.-const MAX_MESSAGES = 1000-const MAX_WINDOW_DAYS = 30--// A cleared number input reports NaN, which must save as null to turn the cap off.-function toInputValue(value: number | null | undefined): number | null {- return typeof value === 'number' && Number.isFinite(value) ? value : null-}--function errorFor(value: number | null, other: number | null, max: number): string | undefined {- if (value === null) {- return other === null ? undefined : 'Fill in both fields, or clear both to turn the cap off'- }- return Number.isInteger(value) && value >= 1 && value <= max- ? undefined- : `Enter a whole number from 1 to ${max.toLocaleString()}`-}+import {+ MAX_FREQUENCY_CAP_MESSAGES,+ MAX_FREQUENCY_CAP_WINDOW_DAYS,+ frequencyCapFieldError,+ toFrequencyCapInputValue,+} from './frequencyCap'export function WorkflowsFrequencyCapSettings(): JSX.Element {const { currentTeam, currentTeamLoading } = useValues(teamLogic)@@ -34,8 +23,10 @@ export function WorkflowsFrequencyCapSettings(): JSX.Element {minimumAccessLevel: TeamMembershipLevel.Admin,})- const savedMaxMessages = toInputValue(currentTeam?.workflows_config?.marketing_frequency_cap_max_messages)- const savedWindowDays = toInputValue(currentTeam?.workflows_config?.marketing_frequency_cap_window_days)+ const savedMaxMessages = toFrequencyCapInputValue(+ currentTeam?.workflows_config?.marketing_frequency_cap_max_messages+ )+ const savedWindowDays = toFrequencyCapInputValue(currentTeam?.workflows_config?.marketing_frequency_cap_window_days)const [maxMessages, setMaxMessages] = useState<number | null>(savedMaxMessages)const [windowDays, setWindowDays] = useState<number | null>(savedWindowDays)@@ -45,8 +36,8 @@ export function WorkflowsFrequencyCapSettings(): JSX.Element {setWindowDays(savedWindowDays)}, [savedMaxMessages, savedWindowDays])- const maxMessagesError = errorFor(maxMessages, windowDays, MAX_MESSAGES)- const windowDaysError = errorFor(windowDays, maxMessages, MAX_WINDOW_DAYS)+ const maxMessagesError = frequencyCapFieldError(maxMessages, windowDays, MAX_FREQUENCY_CAP_MESSAGES)+ const windowDaysError = frequencyCapFieldError(windowDays, maxMessages, MAX_FREQUENCY_CAP_WINDOW_DAYS)const unchanged = maxMessages === savedMaxMessages && windowDays === savedWindowDaysreturn (@@ -62,9 +53,9 @@ export function WorkflowsFrequencyCapSettings(): JSX.Element {id="workflows-frequency-cap-max-messages"type="number"min={1}- max={MAX_MESSAGES}+ max={MAX_FREQUENCY_CAP_MESSAGES}value={maxMessages ?? undefined}- onChange={(value) => setMaxMessages(toInputValue(value))}+ onChange={(value) => setMaxMessages(toFrequencyCapInputValue(value))}placeholder="No cap"disabledReason={restrictedReason}data-attr="workflows-frequency-cap-max-messages"@@ -80,9 +71,9 @@ export function WorkflowsFrequencyCapSettings(): JSX.Element {id="workflows-frequency-cap-window-days"type="number"min={1}- max={MAX_WINDOW_DAYS}+ max={MAX_FREQUENCY_CAP_WINDOW_DAYS}value={windowDays ?? undefined}- onChange={(value) => setWindowDays(toInputValue(value))}+ onChange={(value) => setWindowDays(toFrequencyCapInputValue(value))}placeholder="No cap"disabledReason={restrictedReason}data-attr="workflows-frequency-cap-window-days"diff --git a/products/workflows/frontend/scenes/settings/frequencyCap.ts b/products/workflows/frontend/scenes/settings/frequencyCap.tsnew file mode 100644index 000000000000..d164dc15154c--- /dev/null+++ b/products/workflows/frontend/scenes/settings/frequencyCap.ts@@ -0,0 +1,17 @@+// Kept in step with the max_value on TeamWorkflowsConfigSerializer.+export const MAX_FREQUENCY_CAP_MESSAGES = 1000+export const MAX_FREQUENCY_CAP_WINDOW_DAYS = 30++// A cleared number input reports NaN, which must save as null to turn the cap off.+export function toFrequencyCapInputValue(value: number | null | undefined): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null+}++export function frequencyCapFieldError(value: number | null, other: number | null, max: number): string | undefined {+ if (value === null) {+ return other === null ? undefined : 'Fill in both fields, or clear both to turn the cap off'+ }+ return Number.isInteger(value) && value >= 1 && value <= max+ ? undefined+ : `Enter a whole number from 1 to ${max.toLocaleString()}`+}diff --git a/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsx b/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsxnew file mode 100644index 000000000000..a8c962717710--- /dev/null+++ b/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsx@@ -0,0 +1,141 @@+import { useActions, useValues } from 'kea'++import { LemonDivider, LemonSwitch } from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'++import {+ MAX_FREQUENCY_CAP_MESSAGES,+ MAX_FREQUENCY_CAP_WINDOW_DAYS,+ frequencyCapFieldError,+ toFrequencyCapInputValue,+} from '../../scenes/settings/frequencyCap'+import { WorkflowsEmailTrackingConsentSettings } from '../../scenes/settings/WorkflowsEmailTrackingConsentSettings'+import { FrequencyCapChoice } from './onboardingWizardSteps'+import { workflowsOnboardingWizardLogic } from './workflowsOnboardingWizardLogic'++const ADMIN_ONLY_REASON = 'Only project admins can change sending rules'++const CAP_OPTIONS: LemonRadioOption<FrequencyCapChoice>[] = [+ {+ value: 'recommended',+ label: 'At most 1 email every 2 days (recommended)',+ description: 'Keeps marketing email from piling up when several workflows reach the same person.',+ },+ { value: 'off', label: 'No cap', description: 'Each workflow and broadcast sends on its own schedule.' },+ { value: 'custom', label: 'Set your own cap' },+]++function SendingRule({+ title,+ description,+ children,+}: {+ title: string+ description: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <section className="flex flex-col gap-3">+ <div>+ <h3 className="mb-0.5 text-base font-semibold">{title}</h3>+ <p className="mb-0 text-sm text-secondary">{description}</p>+ </div>+ {children}+ </section>+ )+}++export function WizardSendingRulesStep(): JSX.Element {+ const { shownFrequencyCapChoice, shownCustomFrequencyCap, canEditSendingRules, shownEngagementEvents } =+ useValues(workflowsOnboardingWizardLogic)+ const { setFrequencyCapChoice, setCustomFrequencyCap, setEngagementEventsChoice } =+ useActions(workflowsOnboardingWizardLogic)+ const disabledReason = canEditSendingRules ? undefined : ADMIN_ONLY_REASON+ const { maxMessages, windowDays } = shownCustomFrequencyCap++ return (+ <div className="flex flex-col gap-6">+ <SendingRule+ title="Frequency cap"+ description="The most marketing emails one person gets across all workflows and broadcasts. Transactional email is never capped."+ >+ <LemonRadio+ value={shownFrequencyCapChoice}+ onChange={setFrequencyCapChoice}+ aria-label="Frequency cap"+ options={CAP_OPTIONS.map((option) => ({+ ...option,+ disabledReason,+ 'data-attr': `workflows-onboarding-wizard-frequency-cap-${option.value}`,+ }))}+ />+ {shownFrequencyCapChoice === 'custom' && (+ <div className="flex flex-wrap gap-4 pl-6">+ <LemonField.Pure+ className="flex-1 min-w-60"+ label="Messages per person"+ htmlFor="workflows-onboarding-wizard-frequency-cap-max-messages"+ error={frequencyCapFieldError(maxMessages, windowDays, MAX_FREQUENCY_CAP_MESSAGES)}+ >+ <LemonInput+ id="workflows-onboarding-wizard-frequency-cap-max-messages"+ type="number"+ min={1}+ max={MAX_FREQUENCY_CAP_MESSAGES}+ value={maxMessages ?? undefined}+ onChange={(value) =>+ setCustomFrequencyCap({ maxMessages: toFrequencyCapInputValue(value), windowDays })+ }+ disabledReason={disabledReason}+ data-attr="workflows-onboarding-wizard-frequency-cap-max-messages"+ />+ </LemonField.Pure>+ <LemonField.Pure+ className="flex-1 min-w-60"+ label="Within this many days"+ htmlFor="workflows-onboarding-wizard-frequency-cap-window-days"+ error={frequencyCapFieldError(windowDays, maxMessages, MAX_FREQUENCY_CAP_WINDOW_DAYS)}+ >+ <LemonInput+ id="workflows-onboarding-wizard-frequency-cap-window-days"+ type="number"+ min={1}+ max={MAX_FREQUENCY_CAP_WINDOW_DAYS}+ value={windowDays ?? undefined}+ onChange={(value) =>+ setCustomFrequencyCap({ maxMessages, windowDays: toFrequencyCapInputValue(value) })+ }+ disabledReason={disabledReason}+ data-attr="workflows-onboarding-wizard-frequency-cap-window-days"+ />+ </LemonField.Pure>+ </div>+ )}+ </SendingRule>+ <LemonDivider className="my-0" />+ <SendingRule+ title="Email tracking consent"+ description="Whether tracking opens and clicks on marketing email needs the recipient's consent."+ >+ <WorkflowsEmailTrackingConsentSettings />+ </SendingRule>+ <LemonDivider className="my-0" />+ <SendingRule+ title="Engagement events"+ description="Capture sends, opens, clicks and bounces as PostHog events, so you can use them in insights and funnels. These events count toward your event usage."+ >+ <LemonSwitch+ checked={shownEngagementEvents}+ onChange={setEngagementEventsChoice}+ label="Capture email engagement events"+ bordered+ disabledReason={disabledReason}+ data-attr="workflows-onboarding-wizard-engagement-events"+ />+ </SendingRule>+ </div>+ )+}diff --git a/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx b/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsxindex 370169cad22a..9e4e2e423b22 100644--- a/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx+++ b/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx@@ -19,6 +19,7 @@ import { WizardConnectStep } from './WizardConnectStep'import { WizardCreateStep } from './WizardCreateStep'import { WizardDomainStep } from './WizardDomainStep'import { WizardPushStep } from './WizardPushStep'+import { WizardSendingRulesStep } from './WizardSendingRulesStep'import { WizardTemplateStep } from './WizardTemplateStep'import { workflowsOnboardingWizardLogic } from './workflowsOnboardingWizardLogic'@@ -128,6 +129,7 @@ export function WorkflowsOnboardingWizard(): JSX.Element {<CustomerIOImportModal /></>)}+ {currentStep === 'sending-rules' && <WizardSendingRulesStep />}{currentStep === 'push' && <WizardPushStep />}{(currentStep === 'journey' || currentStep === 'template') && <WizardTemplateStep />}{currentStep === 'connect' && <WizardConnectStep />}diff --git a/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.test.ts b/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.test.tsindex 0d6107a56594..3ae3247ed2c6 100644--- a/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.test.ts+++ b/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.test.ts@@ -1,4 +1,12 @@-import { MESSAGING_WIZARD_STEPS, firstOpenStepIndex, requiredConnections, wizardSteps } from './onboardingWizardSteps'+import {+ MESSAGING_WIZARD_STEPS,+ customFrequencyCapError,+ firstOpenStepIndex,+ initialFrequencyCapChoice,+ requiredConnections,+ sendingRulesToSave,+ wizardSteps,+} from './onboardingWizardSteps'describe('onboardingWizardSteps', () => {test.each<[string, (string | undefined)[], string[]]>([@@ -15,7 +23,12 @@ describe('onboardingWizardSteps', () => {['a new project starts at the channel', {}, 0],['a connected channel starts at the domain', { channel: true }, 1],['an unverified domain stays open even when later steps are done', { channel: true, 'opt-outs': true }, 1],- ['everything done lands on the last step', { channel: true, domain: true, 'opt-outs': true, journey: true }, 3],+ [+ 'everything done lands on the last step',+ { channel: true, domain: true, 'opt-outs': true, 'sending-rules': true, journey: true },+ 4,+ ],+ ['an unset frequency cap stops before the journey', { channel: true, domain: true, 'opt-outs': true }, 3],])('%s', (_, done, expected) => {expect(firstOpenStepIndex(MESSAGING_WIZARD_STEPS, done)).toBe(expected)})@@ -25,22 +38,70 @@ describe('onboardingWizardSteps', () => {'messaging asks about push before the journey','messaging',true,- ['channel', 'domain', 'opt-outs', 'push', 'journey'],+ ['channel', 'domain', 'opt-outs', 'sending-rules', 'push', 'journey'],],['messaging without push keeps the email steps','messaging',false,- ['channel', 'domain', 'opt-outs', 'journey'],+ ['channel', 'domain', 'opt-outs', 'sending-rules', 'journey'],],['automation never asks about push', 'automation', true, ['template', 'connect', 'create']],['broadcasts send email only, so they never ask about push','broadcast',true,- ['channel', 'domain', 'opt-outs', 'broadcast'],+ ['channel', 'domain', 'opt-outs', 'sending-rules', 'broadcast'],],])('%s', (_, path, pushEnabled, expected) => {expect(wizardSteps(path, pushEnabled)).toEqual(expected)})++ const unset = { maxMessages: null, windowDays: null }+ test.each<[string, Parameters<typeof initialFrequencyCapChoice>[0], boolean, string]>([+ ['a new setup starts on the recommended cap', unset, true, 'recommended'],+ ['a non-admin sees an unset cap as no cap', unset, false, 'off'],+ ['a saved recommended cap starts on recommended', { maxMessages: 1, windowDays: 2 }, true, 'recommended'],+ ['a saved custom cap starts on custom', { maxMessages: 3, windowDays: 5 }, true, 'custom'],+ ])('%s', (_, saved, canEdit, expected) => {+ expect(initialFrequencyCapChoice(saved, canEdit)).toBe(expected)+ })++ test.each<[string, Parameters<typeof customFrequencyCapError>[0], boolean]>([+ ['an empty field blocks a custom cap', { maxMessages: 3, windowDays: null }, true],+ ['a window above 30 days blocks a custom cap', { maxMessages: 3, windowDays: 31 }, true],+ ['a valid custom cap passes', { maxMessages: 3, windowDays: 5 }, false],+ ])('%s', (_, cap, blocked) => {+ expect(customFrequencyCapError(cap) !== null).toBe(blocked)+ })++ const saved = { ...unset, engagementEvents: false }+ test.each<[string, Parameters<typeof sendingRulesToSave>, ReturnType<typeof sendingRulesToSave>]>([+ [+ 'a new setup saves the recommended cap and engagement events',+ [saved, { maxMessages: 1, windowDays: 2 }, true, true],+ {+ capture_workflows_engagement_events: true,+ marketing_frequency_cap_max_messages: 1,+ marketing_frequency_cap_window_days: 2,+ },+ ],+ [+ 'an unchanged custom cap is not saved again',+ [{ maxMessages: 3, windowDays: 5, engagementEvents: true }, { maxMessages: 3, windowDays: 5 }, true, true],+ null,+ ],+ [+ 'no cap clears a saved cap',+ [{ maxMessages: 3, windowDays: 5, engagementEvents: true }, unset, true, true],+ {+ capture_workflows_engagement_events: true,+ marketing_frequency_cap_max_messages: null,+ marketing_frequency_cap_window_days: null,+ },+ ],+ ['a non-admin saves nothing', [saved, { maxMessages: 1, windowDays: 2 }, true, false], null],+ ])('%s', (_, args, expected) => {+ expect(sendingRulesToSave(...args)).toEqual(expected)+ })})diff --git a/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.ts b/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.tsindex 68b89a9a7e51..a500de65b7aa 100644--- a/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.ts+++ b/products/workflows/frontend/setupGuide/wizard/onboardingWizardSteps.ts@@ -2,13 +2,20 @@ import { combineUrl } from 'kea-router'import { urls } from 'scenes/urls'+import type { WorkflowsConfig } from '~/types'++import {+ MAX_FREQUENCY_CAP_MESSAGES,+ MAX_FREQUENCY_CAP_WINDOW_DAYS,+ frequencyCapFieldError,+} from '../../scenes/settings/frequencyCap'import type { HogFlowAction } from '../../Workflows/hogflows/types'import type { WorkflowsOnboardingPath } from '../workflowsSetupGuideLogic'// pinned: URL values and analytics property values for the wizard events - renaming breaks links and dashboards-export const MESSAGING_WIZARD_STEPS = ['channel', 'domain', 'opt-outs', 'journey'] as const+export const MESSAGING_WIZARD_STEPS = ['channel', 'domain', 'opt-outs', 'sending-rules', 'journey'] as constexport const AUTOMATION_WIZARD_STEPS = ['template', 'connect', 'create'] as const-export const BROADCAST_WIZARD_STEPS = ['channel', 'domain', 'opt-outs', 'broadcast'] as const+export const BROADCAST_WIZARD_STEPS = ['channel', 'domain', 'opt-outs', 'sending-rules', 'broadcast'] as constexport const PUSH_WIZARD_STEP = 'push' as constexport type WizardStepKey =| (typeof MESSAGING_WIZARD_STEPS)[number]@@ -76,6 +83,13 @@ export const WIZARD_STEP_COPY: Record<WizardStepKey, WizardStepCopy> = {'Opt-out categories let people unsubscribe from one kind of message, such as product updates, and keep the rest. Every email has an unsubscribe link either way.',optional: true,},+ 'sending-rules': {+ label: 'Sending rules',+ title: 'Choose how often people hear from you',+ description:+ 'These rules apply to every workflow and broadcast in this project. The defaults keep people from getting too many marketing emails. You can change them later in Messaging settings.',+ optional: false,+ },push: {label: 'Push',title: 'Send push notifications too?',@@ -117,6 +131,71 @@ export const WIZARD_STEP_COPY: Record<WizardStepKey, WizardStepCopy> = {},}+export interface FrequencyCap {+ maxMessages: number | null+ windowDays: number | null+}++export const RECOMMENDED_FREQUENCY_CAP: FrequencyCap = { maxMessages: 1, windowDays: 2 }+const NO_FREQUENCY_CAP: FrequencyCap = { maxMessages: null, windowDays: null }++// pinned: analytics property values for the sending rules step - renaming breaks dashboards+export type FrequencyCapChoice = 'recommended' | 'custom' | 'off'++function sameFrequencyCap(a: FrequencyCap, b: FrequencyCap): boolean {+ return a.maxMessages === b.maxMessages && a.windowDays === b.windowDays+}++/** The choice the step starts on. An unset cap starts on the recommended cap when the person can save it. */+export function initialFrequencyCapChoice(saved: FrequencyCap, canEdit: boolean): FrequencyCapChoice {+ if (saved.maxMessages === null || saved.windowDays === null) {+ return canEdit ? 'recommended' : 'off'+ }+ return sameFrequencyCap(saved, RECOMMENDED_FREQUENCY_CAP) ? 'recommended' : 'custom'+}++export function chosenFrequencyCap(choice: FrequencyCapChoice, custom: FrequencyCap): FrequencyCap {+ return choice === 'recommended' ? RECOMMENDED_FREQUENCY_CAP : choice === 'off' ? NO_FREQUENCY_CAP : custom+}++// Both fields are required here, because "No cap" is its own choice in the wizard.+export function customFrequencyCapError(cap: FrequencyCap): string | null {+ if (cap.maxMessages === null || cap.windowDays === null) {+ return 'Fill in both fields'+ }+ return (+ frequencyCapFieldError(cap.maxMessages, cap.windowDays, MAX_FREQUENCY_CAP_MESSAGES) ??+ frequencyCapFieldError(cap.windowDays, cap.maxMessages, MAX_FREQUENCY_CAP_WINDOW_DAYS) ??+ null+ )+}++/** What the sending rules step saves when the person continues, or null when nothing changes. */+export function sendingRulesToSave(+ saved: FrequencyCap & { engagementEvents: boolean },+ cap: FrequencyCap,+ engagementEvents: boolean,+ canEdit: boolean+): WorkflowsConfig | null {+ // The backend lets only project admins change any part of workflows_config.+ if (!canEdit) {+ return null+ }+ const setCap = !sameFrequencyCap(saved, cap)+ if (!setCap && engagementEvents === saved.engagementEvents) {+ return null+ }+ return {+ capture_workflows_engagement_events: engagementEvents,+ ...(setCap+ ? {+ marketing_frequency_cap_max_messages: cap.maxMessages,+ marketing_frequency_cap_window_days: cap.windowDays,+ }+ : {}),+ }+}+// pinned: integration kinds - these are the `kind` values the integrations API returnsexport type WizardConnection = 'slack'diff --git a/products/workflows/frontend/setupGuide/wizard/workflowsOnboardingWizardLogic.ts b/products/workflows/frontend/setupGuide/wizard/workflowsOnboardingWizardLogic.tsindex 389f981b1b54..6e5aa03af262 100644--- a/products/workflows/frontend/setupGuide/wizard/workflowsOnboardingWizardLogic.ts+++ b/products/workflows/frontend/setupGuide/wizard/workflowsOnboardingWizardLogic.ts@@ -3,12 +3,13 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'-import { FEATURE_FLAGS } from 'lib/constants'+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import type { IntegrationType } from '~/types'+import type { IntegrationType, TeamPublicType, TeamType } from '~/types'import { newBroadcastAgentLogic } from '../../Broadcasts/newBroadcastAgentLogic'import type { HogFlowTemplate } from '../../Workflows/hogflows/types'@@ -20,12 +21,19 @@ import { WorkflowsOnboardingPath, workflowsSetupGuideLogic } from '../workflowsSimport {BLANK_START_ID,DATA_SUGGESTION_START_ID,+ FrequencyCap,+ FrequencyCapChoice,+ RECOMMENDED_FREQUENCY_CAP,ONBOARDING_WIZARD_TAB,WIZARD_STEP_COPY,WizardConnection,WizardStepKey,+ chosenFrequencyCap,+ customFrequencyCapError,firstOpenStepIndex,+ initialFrequencyCapChoice,requiredConnections,+ sendingRulesToSave,wizardSteps,} from './onboardingWizardSteps'@@ -37,12 +45,20 @@ function isOnboardingPath(value: unknown): value is WorkflowsOnboardingPath {export interface workflowsOnboardingWizardLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicintegrations: IntegrationType[] | null // integrationsLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ currentTeamLoading: boolean // teamLogicworkflowTemplates: HogFlowTemplate[] // workflowTemplatesLogicworkflowTemplatesLoading: boolean // workflowTemplatesLogicguideSteps: SetupGuideStep[] | null // workflowsSetupGuideLogic+ canEditSendingRules: boolean+ chosenFrequencyCap: FrequencyCapconnectionsNeeded: WizardConnection[]continueDisabledReason: string | nullcurrentStep: WizardStepKey+ customFrequencyCap: FrequencyCap | null+ engagementEventsChoice: boolean | null+ frequencyCapChoice: FrequencyCapChoice | null+ frequencyCapError: string | nullhasPositioned: booleaninitialized: booleanisLastStep: boolean@@ -50,9 +66,13 @@ export interface workflowsOnboardingWizardLogicValues {offersSuggestions: booleanpushEnabled: booleanpushSetupStarted: boolean+ savedFrequencyCap: FrequencyCapselectedTemplate: HogFlowTemplate | nullselectedTemplateId: string | nullsetupCheckFailed: boolean+ shownCustomFrequencyCap: FrequencyCap+ shownEngagementEvents: boolean+ shownFrequencyCapChoice: FrequencyCapChoicestartsBlank: booleanstepDone: Partial<Record<WizardStepKey, boolean>> | nullstepIndex: number@@ -74,6 +94,7 @@ export interface workflowsOnboardingWizardLogicActions {createWorkflowFromTemplate: (template: HogFlowTemplate) => {template: HogFlowTemplate} // newWorkflowLogic+ updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogicloadHasMessagingWorkflow: () => any // workflowsSetupGuideLogicloadHasMessagingWorkflowFailure: (error: string,@@ -124,6 +145,15 @@ export interface workflowsOnboardingWizardLogicActions {selectTemplate: (templateId: string) => {templateId: string}+ setCustomFrequencyCap: (cap: FrequencyCap) => {+ cap: FrequencyCap+ }+ setEngagementEventsChoice: (enabled: boolean) => {+ enabled: boolean+ }+ setFrequencyCapChoice: (choice: FrequencyCapChoice) => {+ choice: FrequencyCapChoice+ }setStepIndex: (index: number) => {index: number}@@ -139,6 +169,31 @@ export interface workflowsOnboardingWizardLogicActions {export interface workflowsOnboardingWizardLogicMeta {__keaTypeGenInternalSelectorTypes: {pushEnabled: (featureFlags: FeatureFlagsSet) => boolean+ savedFrequencyCap: (currentTeam: TeamPublicType | TeamType | null) => FrequencyCap+ shownFrequencyCapChoice: (+ frequencyCapChoice: FrequencyCapChoice | null,+ savedFrequencyCap: FrequencyCap,+ canEditSendingRules: boolean+ ) => FrequencyCapChoice+ shownCustomFrequencyCap: (+ customFrequencyCap: FrequencyCap | null,+ savedFrequencyCap: FrequencyCap+ ) => FrequencyCap+ chosenFrequencyCap: (+ shownFrequencyCapChoice: FrequencyCapChoice,+ shownCustomFrequencyCap: FrequencyCap+ ) => FrequencyCap+ frequencyCapError: (+ shownFrequencyCapChoice: FrequencyCapChoice,+ shownCustomFrequencyCap: FrequencyCap,+ canEditSendingRules: boolean+ ) => string | null+ shownEngagementEvents: (+ engagementEventsChoice: boolean | null,+ currentTeam: TeamPublicType | TeamType | null,+ canEditSendingRules: boolean+ ) => boolean+ canEditSendingRules: (currentTeam: TeamPublicType | TeamType | null) => booleanstepKeys: (wizardPath: WorkflowsOnboardingPath, pushEnabled: boolean) => readonly WizardStepKey[]currentStep: (stepKeys: readonly WizardStepKey[], stepIndex: number) => WizardStepKeyoffersSuggestions: (wizardPath: WorkflowsOnboardingPath, featureFlags: FeatureFlagsSet) => boolean@@ -159,13 +214,16 @@ export interface workflowsOnboardingWizardLogicMeta {missingConnections: 'slack'[],integrations: IntegrationType[] | null,startsBlank: boolean,- setupCheckFailed: boolean+ setupCheckFailed: boolean,+ savedFrequencyCap: FrequencyCap) => Partial<Record<WizardStepKey, boolean>> | nullcontinueDisabledReason: (currentStep: WizardStepKey,stepDone: Partial<Record<WizardStepKey, boolean>> | null,selectedTemplate: HogFlowTemplate | null,- startsBlank: boolean+ startsBlank: boolean,+ frequencyCapError: string | null,+ currentTeamLoading: boolean) => string | null}}@@ -189,6 +247,8 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogic['featureFlags'],workflowTemplatesLogic,['workflowTemplates', 'workflowTemplatesLoading'],+ teamLogic,+ ['currentTeam', 'currentTeamLoading'],],actions: [newWorkflowLogic,@@ -197,6 +257,8 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogic['startNewBroadcast'],workflowsSetupGuideLogic,['loadHasMessagingWorkflow', 'loadHasMessagingWorkflowFailure', 'loadHasMessagingWorkflowSuccess'],+ teamLogic,+ ['updateCurrentTeam'],],})),actions({@@ -220,6 +282,9 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogicpositionAtFirstOpenStep: (index: number) => ({ index }),positionIfReady: true,startPushSetup: true,+ setEngagementEventsChoice: (enabled: boolean) => ({ enabled }),+ setFrequencyCapChoice: (choice: FrequencyCapChoice) => ({ choice }),+ setCustomFrequencyCap: (cap: FrequencyCap) => ({ cap }),setTemplatesShown: (shown: boolean) => ({ shown }),finishWithSuggestion: true,}),@@ -272,6 +337,24 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogicsetTemplatesShown: (_, { shown }) => shown,},],+ frequencyCapChoice: [+ null as FrequencyCapChoice | null,+ {+ setFrequencyCapChoice: (_, { choice }) => choice,+ },+ ],+ customFrequencyCap: [+ null as FrequencyCap | null,+ {+ setCustomFrequencyCap: (_, { cap }) => cap,+ },+ ],+ engagementEventsChoice: [+ null as boolean | null,+ {+ setEngagementEventsChoice: (_, { enabled }) => enabled,+ },+ ],pushSetupStarted: [false,{@@ -292,6 +375,63 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogic(s) => [s.featureFlags],(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS],],+ savedFrequencyCap: [+ (s) => [s.currentTeam],+ (currentTeam: TeamType | null): FrequencyCap => ({+ maxMessages: currentTeam?.workflows_config?.marketing_frequency_cap_max_messages ?? null,+ windowDays: currentTeam?.workflows_config?.marketing_frequency_cap_window_days ?? null,+ }),+ ],+ // A non-admin cannot save, so the step shows what is saved instead of the defaults.+ shownFrequencyCapChoice: [+ (s) => [s.frequencyCapChoice, s.savedFrequencyCap, s.canEditSendingRules],+ (+ frequencyCapChoice: FrequencyCapChoice | null,+ savedFrequencyCap: FrequencyCap,+ canEditSendingRules: boolean+ ): FrequencyCapChoice =>+ frequencyCapChoice ?? initialFrequencyCapChoice(savedFrequencyCap, canEditSendingRules),+ ],+ shownCustomFrequencyCap: [+ (s) => [s.customFrequencyCap, s.savedFrequencyCap],+ (customFrequencyCap: FrequencyCap | null, savedFrequencyCap: FrequencyCap): FrequencyCap =>+ customFrequencyCap ??+ (savedFrequencyCap.maxMessages !== null && savedFrequencyCap.windowDays !== null+ ? savedFrequencyCap+ : RECOMMENDED_FREQUENCY_CAP),+ ],+ chosenFrequencyCap: [+ (s) => [s.shownFrequencyCapChoice, s.shownCustomFrequencyCap],+ (shownFrequencyCapChoice: FrequencyCapChoice, shownCustomFrequencyCap: FrequencyCap): FrequencyCap =>+ chosenFrequencyCap(shownFrequencyCapChoice, shownCustomFrequencyCap),+ ],+ frequencyCapError: [+ (s) => [s.shownFrequencyCapChoice, s.shownCustomFrequencyCap, s.canEditSendingRules],+ (+ shownFrequencyCapChoice: FrequencyCapChoice,+ shownCustomFrequencyCap: FrequencyCap,+ canEditSendingRules: boolean+ ): string | null =>+ canEditSendingRules && shownFrequencyCapChoice === 'custom'+ ? customFrequencyCapError(shownCustomFrequencyCap)+ : null,+ ],+ shownEngagementEvents: [+ (s) => [s.engagementEventsChoice, s.currentTeam, s.canEditSendingRules],+ (+ engagementEventsChoice: boolean | null,+ currentTeam: TeamPublicType | TeamType | null,+ canEditSendingRules: boolean+ ): boolean =>+ engagementEventsChoice ??+ (canEditSendingRules || !!currentTeam?.workflows_config?.capture_workflows_engagement_events),+ ],+ // Matches the admin restriction on the frequency cap in project settings.+ canEditSendingRules: [+ (s) => [s.currentTeam],+ (currentTeam: TeamType | null): boolean =>+ (currentTeam?.effective_membership_level ?? -1) >= TeamMembershipLevel.Admin,+ ],stepKeys: [(s) => [s.wizardPath, s.pushEnabled],(wizardPath: WorkflowsOnboardingPath, pushEnabled: boolean): readonly WizardStepKey[] =>@@ -356,6 +496,7 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogics.integrations,s.startsBlank,s.setupCheckFailed,+ s.savedFrequencyCap,],(wizardPath: WorkflowsOnboardingPath,@@ -364,7 +505,8 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogicmissingConnections: WizardConnection[],integrations: IntegrationType[] | null,startsBlank: boolean,- setupCheckFailed: boolean+ setupCheckFailed: boolean,+ savedFrequencyCap: FrequencyCap): Partial<Record<WizardStepKey, boolean>> | null => {const picked = !!selectedTemplate || startsBlankif (wizardPath === 'automation') {@@ -380,6 +522,7 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogicchannel: !!integrations?.some((integration) => integration.kind === 'email'),domain: guideDone('domain'),'opt-outs': guideDone('opt-outs'),+ 'sending-rules': savedFrequencyCap.maxMessages !== null && savedFrequencyCap.windowDays !== null,push: !!integrations?.some((integration) => integration.kind === 'firebase' || integration.kind === 'apns'),@@ -390,13 +533,28 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogic],/** Why the person cannot move on from this step yet, or null when they can. */continueDisabledReason: [- (s) => [s.currentStep, s.stepDone, s.selectedTemplate, s.startsBlank],+ (s) => [+ s.currentStep,+ s.stepDone,+ s.selectedTemplate,+ s.startsBlank,+ s.frequencyCapError,+ s.currentTeamLoading,+ ],(currentStep: WizardStepKey,stepDone: Partial<Record<WizardStepKey, boolean>> | null,selectedTemplate: HogFlowTemplate | null,- startsBlank: boolean+ startsBlank: boolean,+ frequencyCapError: string | null,+ currentTeamLoading: boolean): string | null => {+ if (currentStep === 'sending-rules') {+ if (currentTeamLoading) {+ return 'Saving your sending rules'+ }+ return frequencyCapError ? 'Fix the frequency cap to continue' : null+ }if (currentStep === 'broadcast') {return null}@@ -421,7 +579,26 @@ export const workflowsOnboardingWizardLogic = kea<workflowsOnboardingWizardLogicpath: values.wizardPath,step,skipped: WIZARD_STEP_COPY[step].optional && !values.stepDone?.[step],+ ...(step === 'sending-rules'+ ? { frequency_cap: values.shownFrequencyCapChoice, engagement_events: values.shownEngagementEvents }+ : {}),})+ const rulesToSave =+ step === 'sending-rules'+ ? sendingRulesToSave(+ {+ ...values.savedFrequencyCap,+ engagementEvents:+ !!values.currentTeam?.workflows_config?.capture_workflows_engagement_events,+ },+ values.chosenFrequencyCap,+ values.shownEngagementEvents,+ values.canEditSendingRules+ )+ : null+ if (rulesToSave) {+ actions.updateCurrentTeam({ workflows_config: rulesToSave })+ }if (values.isLastStep) {actions.finish()} else {diff --git a/products/workflows/manifest.tsx b/products/workflows/manifest.tsxindex 0347c53c242e..542faf180567 100644--- a/products/workflows/manifest.tsx+++ b/products/workflows/manifest.tsx@@ -62,6 +62,7 @@ export const manifest: ProductManifest = {'/broadcasts/opt-outs': ['Broadcasts', 'broadcasts'],'/broadcasts/suppression': ['Broadcasts', 'broadcasts'],'/broadcasts/reputation': ['Broadcasts', 'broadcasts'],+ '/broadcasts/settings': ['Broadcasts', 'broadcasts'],// kea-router matches in declaration order, so the literal 'new' comes before ':id'.'/broadcasts/new': ['Broadcast', 'broadcast'],'/broadcasts/:id': ['Broadcast', 'broadcast'],@@ -100,6 +101,7 @@ export const manifest: ProductManifest = {{ name: 'Opt-outs', href: urls.workflows('opt-outs') },{ name: 'Suppression list', href: urls.workflows('suppression') },{ name: 'Reputation', href: urls.workflows('reputation') },+ { name: 'Settings', href: urls.workflows('settings') },],type: 'workflows',category: ProductItemCategory.MESSAGING,