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): add team defaults for utm tags on new email links (#118211)

Daniel Marchuk32497d6d9ba1
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 7dc761ca3697..6e96c245b32c 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1751,6 +1751,29 @@ export const EmailTrackingConsentModeEnumApi = {
OptIn: 'opt_in',
} as const
+export interface EmailUtmParamsApi {
+ /**
+ * Default utm_source. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_source?: string
+ /**
+ * Default utm_medium. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_medium?: string
+ /**
+ * Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_campaign?: string
+ /**
+ * Default utm_content. Empty uses the email step name. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_content?: string
+}
+
export interface TeamWorkflowsConfigApi {
/** When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) alongside the existing workflow metrics. */
capture_workflows_engagement_events?: boolean
@@ -1760,6 +1783,10 @@ export interface TeamWorkflowsConfigApi {
* * `opt_out` - Opt Out
* * `opt_in` - Opt In */
email_tracking_consent_mode?: EmailTrackingConsentModeEnumApi
+ /** Whether new email steps and broadcasts start with UTM tags on their links. Each email can still change it. Existing emails keep their current values. */
+ email_utm_tags_enabled?: boolean
+ /** Default UTM values that new email steps and broadcasts copy. An empty value keeps the built-in default for that tag. */
+ email_utm_params?: EmailUtmParamsApi
/**
* How many AI tasks one workflow can create in a rolling 24 hours. Null uses the default of 100; zero pauses task creation for every workflow in the project. Support raises the limit above 500.
* @minimum 0
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index cc5e0a22b5d9..ab2bd2fa51d8 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -81,6 +81,7 @@ import { WorkflowsDailyLimitsSettings } from 'products/workflows/frontend/scenes
import { WorkflowsEmailTrackingConsentSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings'
import { WorkflowsEngagementEventsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEngagementEventsSettings'
import { WorkflowsFrequencyCapSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings'
+import { WorkflowsUtmDefaultsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsUtmDefaultsSettings'
import { IntegrationsList } from '../../lib/integrations/IntegrationsList'
import { SettingScopeTag } from './components/SettingScopeTag'
@@ -1837,6 +1838,14 @@ export const SETTINGS_MAP: SettingSection[] = [
'failed',
],
},
+ {
+ id: 'workflows-utm-defaults',
+ title: 'UTM tags on email links',
+ description:
+ 'Default UTM tags for new broadcasts and workflow emails, so visits from your emails show up as their own campaigns in web analytics. Each email can still change them.',
+ component: <WorkflowsUtmDefaultsSettings />,
+ keywords: ['workflows', 'broadcasts', 'email', 'utm', 'campaign', 'links', 'web analytics'],
+ },
{
id: 'workflows-email-tracking-consent',
title: 'Email tracking consent',
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 5b4f827f2084..82dfecba2204 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -320,6 +320,7 @@ export type SettingId =
| 'workflows-ai-task-limits'
| 'workflows-replay-vision-limits'
| 'workflows-email-tracking-consent'
+ | 'workflows-utm-defaults'
| 'workflows-engagement-events'
| 'xaa-configuration'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index b6766bf92905..7ff47ef082a5 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -934,6 +934,9 @@ export interface WorkflowsConfig {
// Null uses the product default.
workflow_task_rate_limit_per_day?: number | null
workflow_task_team_rate_limit_per_day?: number | null
+ // Optional so cached team objects from before these fields shipped still typecheck.
+ email_utm_tags_enabled?: boolean
+ email_utm_params?: Partial<Record<'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_content', string>>
replay_vision_scan_rate_limit_per_day?: number | null
replay_vision_scan_team_rate_limit_per_day?: number | null
default_email_integration_id?: number | null
diff --git a/posthog/api/project.py b/posthog/api/project.py
index db961810ae70..d56955e467ec 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -62,6 +62,7 @@ from posthog.api.team.team_config import (
TeamFeatureFlagPolicyConfigSerializer,
TeamRevenueAnalyticsConfigSerializer,
TeamWorkflowsConfigSerializer,
+ drop_cached_workflows_config,
)
from posthog.api.team.team_serializer import (
EvaluationContextSuggestionRequestSerializer,
@@ -280,6 +281,7 @@ def update_team_customer_analytics_config(team: Team, validated_data: dict[str,
def update_team_workflows_config(team: Team, validated_data: dict[str, Any], *, context: dict) -> None:
user_access_control = context.get("user_access_control")
+ drop_cached_workflows_config(team)
old_config = {field: getattr(team.workflows_config, field) for field in TeamWorkflowsConfigSerializer.Meta.fields}
serializer = TeamWorkflowsConfigSerializer(
diff --git a/posthog/api/team/team_config.py b/posthog/api/team/team_config.py
index b497243ee4b2..cc9f6d120dfb 100644
--- a/posthog/api/team/team_config.py
+++ b/posthog/api/team/team_config.py
@@ -2,6 +2,7 @@
from typing import Any
+from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from posthog.models import Team, TeamRevenueAnalyticsConfig
@@ -209,6 +210,44 @@ class TeamRevenueAnalyticsConfigSerializer(serializers.ModelSerializer, UserAcce
return internal_value
+class EmailUtmParamsSerializer(serializers.Serializer):
+ utm_source = serializers.CharField(
+ required=False, allow_blank=True, max_length=500, help_text="Default utm_source. Supports Liquid variables."
+ )
+ utm_medium = serializers.CharField(
+ required=False, allow_blank=True, max_length=500, help_text="Default utm_medium. Supports Liquid variables."
+ )
+ utm_campaign = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=500,
+ help_text="Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.",
+ )
+ utm_content = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=500,
+ help_text="Default utm_content. Empty uses the email step name. Supports Liquid variables.",
+ )
+
+
+@extend_schema_field(EmailUtmParamsSerializer)
+class EmailUtmParamsField(serializers.JSONField):
+ def to_internal_value(self, data: Any) -> dict[str, str]:
+ # The value replaces the saved defaults, so a misspelled key would otherwise clear them silently.
+ if isinstance(data, dict) and (unknown := sorted(set(data) - set(EmailUtmParamsSerializer().fields))):
+ raise serializers.ValidationError(f"Unknown UTM parameters: {', '.join(unknown)}.")
+ serializer = EmailUtmParamsSerializer(data=data)
+ serializer.is_valid(raise_exception=True)
+ return {key: value for key, value in serializer.validated_data.items() if value.strip()}
+
+
+def drop_cached_workflows_config(team: Team) -> None:
+ # The config save writes every column, so a row this team instance loaded earlier would undo
+ # settings another admin changed since.
+ team.__dict__.pop(Team.workflows_config.cache_name, None)
+
+
class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):
capture_workflows_engagement_events = serializers.BooleanField(
required=False,
@@ -304,11 +343,28 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
),
)
+ email_utm_tags_enabled = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether new email steps and broadcasts start with UTM tags on their links. "
+ "Each email can still change it. Existing emails keep their current values."
+ ),
+ )
+ email_utm_params = EmailUtmParamsField(
+ required=False,
+ help_text=(
+ "Default UTM values that new email steps and broadcasts copy. An empty value keeps the "
+ "built-in default for that tag."
+ ),
+ )
+
class Meta:
model = TeamWorkflowsConfig
fields = [
"capture_workflows_engagement_events",
"email_tracking_consent_mode",
+ "email_utm_tags_enabled",
+ "email_utm_params",
"workflow_task_rate_limit_per_day",
"workflow_task_team_rate_limit_per_day",
"replay_vision_scan_rate_limit_per_day",
diff --git a/posthog/api/team/team_serializer.py b/posthog/api/team/team_serializer.py
index 6d344448146c..e4262b58aaff 100644
--- a/posthog/api/team/team_serializer.py
+++ b/posthog/api/team/team_serializer.py
@@ -797,6 +797,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
return instance
def _update_workflows_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:
+ team_config.drop_cached_workflows_config(instance)
old_config = {
field: getattr(instance.workflows_config, field)
for field in team_config.TeamWorkflowsConfigSerializer.Meta.fields
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index ebee62d0412f..1f1d89da1f0d 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -8742,6 +8742,12 @@ export namespace Schemas {
* * `opt_in` - Opt In
*/
export type EmailTrackingConsentModeEnum = "off" | "opt_out" | "opt_in";
+ export type EmailUtmParams = Partial<{
+ utm_source: string;
+ utm_medium: string;
+ utm_campaign: string;
+ utm_content: string;
+ }>;
export type EngineEnum =
| "duckdb"
| "postgres"
@@ -19963,6 +19969,8 @@ export namespace Schemas {
export type TeamWorkflowsConfig = Partial<{
capture_workflows_engagement_events: boolean;
email_tracking_consent_mode: EmailTrackingConsentModeEnum;
+ email_utm_tags_enabled: boolean;
+ email_utm_params: EmailUtmParams;
workflow_task_rate_limit_per_day: number | null;
workflow_task_team_rate_limit_per_day: number | null;
replay_vision_scan_rate_limit_per_day: number | null;
diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.py
index 7cf10cd1e02b..a513ba552bcc 100644
--- a/products/workflows/backend/facade/api.py
+++ b/products/workflows/backend/facade/api.py
@@ -13,6 +13,7 @@ from products.workflows.backend.facade.contracts import (
EmailDomainDnsRecord,
EmailDomainVerification,
RecentWorkflow,
+ TeamUtmDefaults,
TierDecision,
TwilioAccount,
TwilioPhoneNumber,
@@ -26,6 +27,7 @@ from products.workflows.backend.facade.contracts import (
)
from products.workflows.backend.models import HogFlow, TeamWorkflowsConfig
from products.workflows.backend.models.hog_flow.hog_flow import opt_out_category_ids, static_cohort_ids
+from products.workflows.backend.services import email_utm_defaults
from products.workflows.backend.services.batch_jobs import create_batch_job
from products.workflows.backend.services.default_email_sender import (
clear_default_email_sender,
@@ -339,3 +341,24 @@ def get_twilio_account_info(*, account_sid: str, auth_token: str) -> TwilioAccou
from products.workflows.backend import providers # noqa: PLC0415
return providers.TwilioProvider(account_sid=account_sid, auth_token=auth_token).get_account_info()
+
+
+def load_team_utm_defaults(team_id: int) -> TeamUtmDefaults:
+ return email_utm_defaults.load_team_utm_defaults(team_id)
+
+
+def seed_new_email_steps_with_utm_defaults(
+ actions: list[dict[str, Any]], existing_action_ids: Iterable[str], defaults: TeamUtmDefaults
+) -> None:
+ email_utm_defaults.seed_new_email_actions(actions, existing_action_ids, defaults)
+
+
+def release_edited_email_utm_keys(
+ actions: list[dict[str, Any]],
+ stored_actions: list[Any],
+ stored_draft: dict[str, Any] | None,
+ defaults: TeamUtmDefaults,
+ *,
+ saving_draft: bool,
+) -> None:
+ email_utm_defaults.release_edited_keys(actions, stored_actions, stored_draft, defaults, saving_draft=saving_draft)
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 7a15184f6125..5143ffb93f5d 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -436,6 +436,12 @@ class TwilioAccount(TypedDict, total=False):
sid: str
+@frozen
+class TeamUtmDefaults:
+ enabled: bool
+ params: dict[str, str]
+
+
@frozen
class MessageAsset:
invocation_id: str
diff --git a/products/workflows/backend/migrations/0036_teamworkflowsconfig_email_utm_defaults.py b/products/workflows/backend/migrations/0036_teamworkflowsconfig_email_utm_defaults.py
new file mode 100644
index 000000000000..e1b650f8e89c
--- /dev/null
+++ b/products/workflows/backend/migrations/0036_teamworkflowsconfig_email_utm_defaults.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-10-05 23:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("workflows", "0035_hogflowbatchjob_waiting_index"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamworkflowsconfig",
+ name="email_utm_params",
+ field=models.JSONField(blank=True, db_default={}, default=dict),
+ ),
+ migrations.AddField(
+ model_name="teamworkflowsconfig",
+ name="email_utm_tags_enabled",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txt
index 4081a0c3419b..d122755b7922 100644
--- a/products/workflows/backend/migrations/max_migration.txt
+++ b/products/workflows/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0035_hogflowbatchjob_waiting_index
+0036_teamworkflowsconfig_email_utm_defaults
diff --git a/products/workflows/backend/models/team_workflows_config.py b/products/workflows/backend/models/team_workflows_config.py
index a1868ff77c7d..81731ce0d844 100644
--- a/products/workflows/backend/models/team_workflows_config.py
+++ b/products/workflows/backend/models/team_workflows_config.py
@@ -54,6 +54,10 @@ class TeamWorkflowsConfig(models.Model):
# foreign key: the editors ignore an id that no longer points at a verified sender, and the
# integration delete signal clears it.
default_email_integration_id = models.BigIntegerField(null=True, blank=True)
+ # Team defaults for UTM tags on email links. New email steps copy them when they are created, and a
+ # bulk apply rewrites the steps whose values still follow them. Off by default.
+ email_utm_tags_enabled = models.BooleanField(default=False, db_default=False)
+ email_utm_params = models.JSONField(default=dict, db_default={}, blank=True)
# Overrides for AI tasks created by workflows. Null keeps the product defaults;
# zero pauses new task creation at that scope.
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 678bdfc1cedb..0b8a622fc51d 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -152,6 +152,11 @@ from products.workflows.backend.facade.activity import (
log_workflow_schedule_activity,
resume_workflow_email_sending,
)
+from products.workflows.backend.facade.api import (
+ load_team_utm_defaults,
+ release_edited_email_utm_keys,
+ seed_new_email_steps_with_utm_defaults,
+)
from products.workflows.backend.facade.batch_jobs import (
create_batch_job,
get_batch_job,
@@ -3546,6 +3551,28 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
{"actions": stored.actions, "conversion": stored.conversion} if stored else None,
)
+ get_team = self.context.get("get_team")
+ if isinstance(submitted_actions, list) and get_team is not None:
+ # A test invocation passes the workflow through the context rather than as the instance.
+ stored_actions = stored.actions if stored and isinstance(stored.actions, list) else []
+ # A step saved only in the staged draft of an active workflow already exists too, so it is never seeded.
+ draft_actions = (stored.draft or {}).get("actions") if stored else None
+ existing_ids = [
+ str(a["id"])
+ for a in [*stored_actions, *(draft_actions if isinstance(draft_actions, list) else [])]
+ if isinstance(a, dict) and a.get("id")
+ ]
+ utm_defaults = load_team_utm_defaults(get_team().id)
+ seed_new_email_steps_with_utm_defaults(actions, existing_ids, utm_defaults)
+ if stored:
+ release_edited_email_utm_keys(
+ actions,
+ stored_actions,
+ stored.draft,
+ utm_defaults,
+ saving_draft=stored.status == HogFlowState.ACTIVE,
+ )
+
# A Replay Vision step can read its session from a variable, so changing variables alone changes what
# it scans. Submitted actions get this check through HogFlowActionSerializer.
if instance and "variables" in data and "actions" not in data:
diff --git a/products/workflows/backend/services/email_utm_defaults.py b/products/workflows/backend/services/email_utm_defaults.py
new file mode 100644
index 000000000000..c6e3ba72ba81
--- /dev/null
+++ b/products/workflows/backend/services/email_utm_defaults.py
@@ -0,0 +1,101 @@
+from collections.abc import Iterable
+from typing import Any
+
+from products.workflows.backend.facade.contracts import TeamUtmDefaults
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+
+UTM_KEYS = ("utm_source", "utm_medium", "utm_campaign", "utm_content")
+# Lists the utm_params keys that follow the team default, so a value someone typed into one email
+# stays apart from a copied default when the team defaults change.
+UTM_FROM_DEFAULT_KEY = "utm_params_from_default"
+
+
+def load_team_utm_defaults(team_id: int) -> TeamUtmDefaults:
+ # Read fresh rather than through Team.workflows_config, which is cached per process.
+ row = (
+ TeamWorkflowsConfig.objects.filter(team_id=team_id).values("email_utm_tags_enabled", "email_utm_params").first()
+ )
+ if row is None:
+ return TeamUtmDefaults(enabled=False, params={})
+ return TeamUtmDefaults(enabled=row["email_utm_tags_enabled"], params=clean_utm_params(row["email_utm_params"]))
+
+
+def clean_utm_params(params: Any) -> dict[str, str]:
+ if not isinstance(params, dict):
+ return {}
+ return {key: value for key in UTM_KEYS if isinstance(value := params.get(key), str) and value.strip()}
+
+
+def is_email_action(action: Any) -> bool:
+ return (
+ isinstance(action, dict) and action.get("type") == "function_email" and isinstance(action.get("config"), dict)
+ )
+
+
+def seed_new_email_actions(
+ actions: list[dict[str, Any]], existing_action_ids: Iterable[str], defaults: TeamUtmDefaults
+) -> None:
+ existing = set(existing_action_ids)
+ for action in actions:
+ if not is_email_action(action) or action.get("id") in existing:
+ continue
+ config = action["config"]
+ # Values the caller supplied for this email are its own, so only the keys it left out follow the default.
+ # A new step without a marker would otherwise count as following every default on the next bulk apply.
+ # An empty value is a choice too: it asks for the built-in tag, such as the workflow name for utm_campaign.
+ raw = config.get("utm_params")
+ supplied = {key: raw[key] for key in UTM_KEYS if isinstance(raw, dict) and isinstance(raw.get(key), str)}
+ config.setdefault(UTM_FROM_DEFAULT_KEY, [key for key in UTM_KEYS if key not in supplied])
+ if "utm_tags_enabled" in config:
+ continue
+ config["utm_tags_enabled"] = defaults.enabled
+ config["utm_params"] = {
+ **{key: value for key, value in defaults.params.items() if key not in supplied},
+ **supplied,
+ }
+
+
+def _keys_following_default(marker: Any) -> list[str]:
+ # Steps saved before the team defaults existed carry no marker. None of them had custom values when
+ # the defaults shipped, so every key counts as following the default.
+ return [key for key in marker if key in UTM_KEYS] if isinstance(marker, list) else list(UTM_KEYS)
+
+
+def release_edited_keys(
+ actions: list[dict[str, Any]],
+ stored_actions: list[Any],
+ stored_draft: dict[str, Any] | None,
+ defaults: TeamUtmDefaults,
+ *,
+ saving_draft: bool,
+) -> None:
+ """Stops a key from following the team default when an edit changes its value, like the email editor does."""
+ draft_actions = stored_draft.get("actions") if isinstance(stored_draft, dict) else None
+ live = {str(a["id"]): a["config"] for a in stored_actions if is_email_action(a) and a.get("id")}
+ draft = {
+ str(a["id"]): a["config"]
+ for a in (draft_actions if isinstance(draft_actions, list) else [])
+ if is_email_action(a) and a.get("id")
+ }
+
+ for action in actions:
+ if not is_email_action(action):
+ continue
+ action_id = str(action.get("id"))
+ # A draft save edits the staged draft, so its values are the ones the edit started from.
+ baseline = (draft.get(action_id) if saving_draft else None) or live.get(action_id) or draft.get(action_id)
+ if baseline is None:
+ continue
+ config = action["config"]
+ # A client that resends the config without the marker has not changed which keys follow the default.
+ following = _keys_following_default(config.get(UTM_FROM_DEFAULT_KEY, baseline.get(UTM_FROM_DEFAULT_KEY)))
+ previous = clean_utm_params(baseline.get("utm_params"))
+ current = clean_utm_params(config.get("utm_params"))
+ # A value equal to the team default still follows it, so "Save as team default" and the bulk apply keep the key.
+ kept = [
+ key
+ for key in following
+ if current.get(key) == defaults.params.get(key) or current.get(key) == previous.get(key)
+ ]
+ if kept != following or (UTM_FROM_DEFAULT_KEY not in config and UTM_FROM_DEFAULT_KEY in baseline):
+ config[UTM_FROM_DEFAULT_KEY] = kept
diff --git a/products/workflows/backend/test/test_email_utm_defaults.py b/products/workflows/backend/test/test_email_utm_defaults.py
new file mode 100644
index 000000000000..8d9df752675a
--- /dev/null
+++ b/products/workflows/backend/test/test_email_utm_defaults.py
@@ -0,0 +1,127 @@
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.workflows.backend.facade.contracts import TeamUtmDefaults
+from products.workflows.backend.services.email_utm_defaults import (
+ UTM_FROM_DEFAULT_KEY,
+ UTM_KEYS,
+ release_edited_keys,
+ seed_new_email_actions,
+)
+
+DEFAULTS = TeamUtmDefaults(
+ enabled=True, params={"utm_source": "newsletter", "utm_campaign": "{{ person.properties.plan }}"}
+)
+
+
+def _email(action_id: str, **config: Any) -> dict[str, Any]:
+ return {"id": action_id, "type": "function_email", "config": {"template_id": "template-email", **config}}
+
+
+class TestEmailUtmDefaults(SimpleTestCase):
+ def test_seed_new_email_actions_only_fills_new_steps_without_a_choice(self) -> None:
+ actions = [
+ _email("existing"),
+ _email("new_unset"),
+ _email("new_chosen", utm_tags_enabled=False),
+ _email("new_with_values", utm_params={"utm_source": "partner"}),
+ _email("new_chosen_with_values", utm_tags_enabled=True, utm_params={"utm_source": "partner"}),
+ _email("new_with_marker", **{UTM_FROM_DEFAULT_KEY: ["utm_medium"]}),
+ _email("new_with_empty_campaign", utm_params={"utm_campaign": ""}),
+ {"id": "trigger", "type": "trigger", "config": {}},
+ ]
+
+ seed_new_email_actions(actions, ["existing"], DEFAULTS)
+
+ configs = {action["id"]: action["config"] for action in actions}
+ assert "utm_tags_enabled" not in configs["existing"]
+ assert configs["new_unset"]["utm_tags_enabled"] is True
+ assert configs["new_unset"]["utm_params"] == DEFAULTS.params
+ assert configs["new_unset"][UTM_FROM_DEFAULT_KEY] == list(UTM_KEYS)
+ assert configs["new_chosen"] == {
+ "template_id": "template-email",
+ "utm_tags_enabled": False,
+ UTM_FROM_DEFAULT_KEY: list(UTM_KEYS),
+ }
+ assert configs["new_chosen_with_values"]["utm_params"] == {"utm_source": "partner"}
+ assert configs["new_chosen_with_values"][UTM_FROM_DEFAULT_KEY] == ["utm_medium", "utm_campaign", "utm_content"]
+ assert configs["new_with_marker"][UTM_FROM_DEFAULT_KEY] == ["utm_medium"]
+ assert configs["new_with_values"]["utm_params"] == {
+ "utm_source": "partner",
+ "utm_campaign": "{{ person.properties.plan }}",
+ }
+ assert configs["new_with_values"][UTM_FROM_DEFAULT_KEY] == ["utm_medium", "utm_campaign", "utm_content"]
+ assert configs["new_with_empty_campaign"]["utm_params"] == {"utm_source": "newsletter", "utm_campaign": ""}
+ assert configs["new_with_empty_campaign"][UTM_FROM_DEFAULT_KEY] == ["utm_source", "utm_medium", "utm_content"]
+
+ @parameterized.expand(
+ [
+ (
+ "an edited value stops following the default",
+ {"utm_params": {"utm_source": "newsletter"}},
+ None,
+ {"utm_params": {"utm_source": "partner"}, UTM_FROM_DEFAULT_KEY: list(UTM_KEYS)},
+ False,
+ ["utm_medium", "utm_campaign", "utm_content"],
+ ),
+ (
+ "a step only the staged draft has is compared with the draft",
+ None,
+ {"utm_params": {"utm_source": "newsletter"}},
+ {"utm_params": {"utm_source": "partner"}, UTM_FROM_DEFAULT_KEY: list(UTM_KEYS)},
+ True,
+ ["utm_medium", "utm_campaign", "utm_content"],
+ ),
+ (
+ "a value changed to the team default keeps following it",
+ {"utm_params": {"utm_source": "partner"}},
+ None,
+ {"utm_params": {"utm_source": "newsletter"}, UTM_FROM_DEFAULT_KEY: list(UTM_KEYS)},
+ False,
+ list(UTM_KEYS),
+ ),
+ (
+ "an unchanged step from before team defaults gets no marker",
+ {"utm_params": {"utm_source": "old"}},
+ None,
+ {"utm_params": {"utm_source": "old"}},
+ False,
+ None,
+ ),
+ (
+ "a resend without the marker keeps the stored marker",
+ {"utm_params": {"utm_source": "partner"}, UTM_FROM_DEFAULT_KEY: ["utm_medium"]},
+ None,
+ {"utm_params": {"utm_source": "partner"}},
+ False,
+ ["utm_medium"],
+ ),
+ (
+ "an unchanged draft value is compared with the draft, not the live step",
+ {"utm_params": {"utm_source": "spring"}},
+ {"utm_params": {"utm_source": "summer"}},
+ {"utm_params": {"utm_source": "summer"}, UTM_FROM_DEFAULT_KEY: list(UTM_KEYS)},
+ True,
+ list(UTM_KEYS),
+ ),
+ ]
+ )
+ def test_release_edited_keys(
+ self,
+ _name: str,
+ live_config: dict[str, Any] | None,
+ draft_config: dict[str, Any] | None,
+ submitted_config: dict[str, Any],
+ saving_draft: bool,
+ expected_marker: list[str] | None,
+ ) -> None:
+ stored_actions = [_email("email_1", **live_config)] if live_config is not None else []
+ stored_draft = {"actions": [_email("email_1", **draft_config)]} if draft_config is not None else None
+ actions = [_email("email_1", **submitted_config)]
+
+ release_edited_keys(actions, stored_actions, stored_draft, DEFAULTS, saving_draft=saving_draft)
+
+ assert actions[0]["config"].get(UTM_FROM_DEFAULT_KEY) == expected_marker
diff --git a/products/workflows/backend/test/test_team_workflows_config.py b/products/workflows/backend/test/test_team_workflows_config.py
index 0ebb51229f10..2499e3807dd3 100644
--- a/products/workflows/backend/test/test_team_workflows_config.py
+++ b/products/workflows/backend/test/test_team_workflows_config.py
@@ -6,6 +6,7 @@ from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from rest_framework import status
+from posthog.api.project import update_team_workflows_config
from posthog.models import OrganizationMembership, Team
from posthog.models.integration import Integration
@@ -54,6 +55,8 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"default_email_integration_id": None,
"marketing_frequency_cap_max_messages": None,
"marketing_frequency_cap_window_days": None,
+ "email_utm_tags_enabled": False,
+ "email_utm_params": {},
}
def test_patch_enables_capture(self) -> None:
@@ -94,6 +97,33 @@ class TestTeamWorkflowsConfig(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "workflows_config__email_tracking_consent_mode"
+ def test_patch_rejects_unknown_utm_keys_and_keeps_saved_defaults(self) -> None:
+ self.client.patch(self.url, {"workflows_config": {"email_utm_params": {"utm_source": "newsletter"}}})
+
+ response = self.client.patch(self.url, {"workflows_config": {"email_utm_params": {"utm_soucre": "typo"}}})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "workflows_config__email_utm_params"
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_utm_params == {"utm_source": "newsletter"}
+
+ def test_a_utm_save_keeps_settings_another_admin_changed_after_the_team_loaded(self) -> None:
+ team = Team.objects.get(pk=self.team.pk)
+ assert team.workflows_config.email_tracking_consent_mode == "off"
+ TeamWorkflowsConfig.objects.filter(team=self.team).update(
+ email_tracking_consent_mode="opt_in", workflow_task_rate_limit_per_day=0
+ )
+ request = RequestFactory().patch(self.url)
+ request.user = self.user
+
+ update_team_workflows_config(
+ team, {"email_utm_params": {"utm_source": "newsletter"}}, context={"request": request}
+ )
+
+ row = TeamWorkflowsConfig.objects.get(team=self.team)
+ assert row.email_tracking_consent_mode == "opt_in"
+ assert row.workflow_task_rate_limit_per_day == 0
+ assert row.email_utm_params == {"utm_source": "newsletter"}
+
def test_patch_rejects_non_boolean_capture_workflows_engagement_events(self) -> None:
response = self.client.patch(
self.url, {"workflows_config": {"capture_workflows_engagement_events": "yes please"}}
@@ -120,6 +150,8 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"default_email_integration_id": None,
"marketing_frequency_cap_max_messages": None,
"marketing_frequency_cap_window_days": None,
+ "email_utm_tags_enabled": False,
+ "email_utm_params": {},
}
@parameterized.expand(
diff --git a/products/workflows/backend/tests/api/test_hog_flow_utm_defaults.py b/products/workflows/backend/tests/api/test_hog_flow_utm_defaults.py
new file mode 100644
index 000000000000..d37f3b5e506a
--- /dev/null
+++ b/products/workflows/backend/tests/api/test_hog_flow_utm_defaults.py
@@ -0,0 +1,126 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.cdp.backend.templates.hog_function_template import sync_template_to_db
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.tests.api.test_hog_flow import _email_function_template, _valid_email_inputs
+
+TRIGGER = {
+ "id": "trigger_node",
+ "name": "trigger",
+ "type": "trigger",
+ "config": {"type": "event", "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events"}]}},
+}
+
+
+def _email_action(**config: Any) -> dict[str, Any]:
+ return {
+ "id": "email_1",
+ "name": "Send email",
+ "type": "function_email",
+ "config": {"template_id": "template-email", "inputs": _valid_email_inputs(), **config},
+ }
+
+
+class TestHogFlowUtmDefaults(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ sync_template_to_db(_email_function_template())
+ TeamWorkflowsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"email_utm_tags_enabled": True, "email_utm_params": {"utm_source": "newsletter"}},
+ )
+
+ def _email_config(self, flow: HogFlow) -> dict[str, Any]:
+ flow.refresh_from_db()
+ return next(a for a in flow.actions if a["type"] == "function_email")["config"]
+
+ @parameterized.expand(
+ [
+ ("no choice made copies the team defaults", {}, True, {"utm_source": "newsletter"}),
+ ("an explicit choice is kept", {"utm_tags_enabled": False}, False, None),
+ (
+ "values the caller supplied are kept",
+ {"utm_params": {"utm_source": "partner"}},
+ True,
+ {"utm_source": "partner"},
+ ),
+ ]
+ )
+ def test_create_copies_team_defaults_into_new_email_steps(
+ self, _name: str, email_config: dict, expected_on: bool, expected_params: dict | None
+ ) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "New flow", "actions": [TRIGGER, _email_action(**email_config)]},
+ format="json",
+ )
+
+ assert response.status_code == 201, response.json()
+ config = self._email_config(HogFlow.objects.get(pk=response.json()["id"]))
+ assert config["utm_tags_enabled"] is expected_on
+ assert config.get("utm_params") == expected_params
+
+ def test_test_invocation_leaves_existing_steps_without_team_defaults(self) -> None:
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Old flow", "actions": [TRIGGER, _email_action(utm_tags_enabled=False)]},
+ format="json",
+ )
+ assert created.status_code == 201, created.json()
+ flow = HogFlow.objects.get(pk=created.json()["id"])
+ # A step saved before team defaults existed carries no UTM settings.
+ flow.actions = [
+ {**a, "config": {k: v for k, v in a["config"].items() if not k.startswith("utm_")}} for a in flow.actions
+ ]
+ flow.save()
+
+ with patch(
+ "products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test"
+ ) as mock_invoke:
+ mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}/invocations/",
+ {
+ "configuration": {"name": "Old flow", "actions": [TRIGGER, _email_action()]},
+ "globals": {"event": {"event": "$pageview", "distinct_id": "test-distinct-id"}},
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ actions = mock_invoke.call_args.kwargs["payload"]["configuration"]["actions"]
+ email_config = next(a for a in actions if a["type"] == "function_email")["config"]
+ assert "utm_tags_enabled" not in email_config
+ assert "utm_params" not in email_config
+
+ @parameterized.expand([("staging the draft", True), ("publishing", False)])
+ def test_an_email_step_only_in_the_staged_draft_is_not_seeded(self, _name: str, stage_draft: bool) -> None:
+ # The step was staged before the team turned on defaults, so it carries no UTM settings.
+ email = _email_action()
+ flow = HogFlow.objects.create(
+ team=self.team,
+ name="Live flow",
+ status=HogFlow.State.ACTIVE,
+ created_by=self.user,
+ actions=[TRIGGER],
+ draft={"actions": [TRIGGER, email]},
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",
+ {"actions": [TRIGGER, email], **({"stage_draft": True} if stage_draft else {})},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ flow.refresh_from_db()
+ saved = ((flow.draft or {}).get("actions") if stage_draft else flow.actions) or []
+ email_config = next(a for a in saved if a["type"] == "function_email")["config"]
+ assert "utm_tags_enabled" not in email_config
+ assert "utm_params" not in email_config
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index bb48cd5f94e5..17ae6ae27e91 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -1,3 +1,5 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -6,6 +8,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -379,6 +382,30 @@ describe('broadcastWizardLogic', () => {
}
})
+ it.each([
+ { case: 'untouched settings', edit: false, enabled: true, params: { utm_source: 'newsletter' } },
+ { case: 'settings the user changed', edit: true, enabled: false, params: {} },
+ ])('seeds team UTM defaults when the team loads after mount, for $case', ({ edit, enabled, params }) => {
+ logic.unmount()
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+ if (edit) {
+ logic.actions.setEmailSettings({ trackingEnabled: false })
+ }
+
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ workflows_config: {
+ capture_workflows_engagement_events: false,
+ email_utm_tags_enabled: true,
+ email_utm_params: { utm_source: 'newsletter' },
+ },
+ })
+
+ expect(logic.values.emailSettings).toMatchObject({ utmTagsEnabled: enabled, utmParams: params })
+ })
+
it('moves a new broadcast onto its draft URL once the draft is created', async () => {
router.actions.push('/broadcasts/new')
await expectLogic(logic, () => {
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 3c202167222e..b839d5121387 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -78,7 +78,8 @@ import {
parseRRuleToState,
stateToRRule,
} from '../Workflows/hogflows/steps/components/rrule-helpers'
-import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
+import { getTeamUtmDefaults, newEmailUtmConfig } from '../Workflows/hogflows/steps/components/utmDefaults'
+import type { UtmTagKey, UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
import {
REALTIME_COHORT_STATUS_POLL_MS,
isRealtimeCohortUnresolved,
@@ -181,6 +182,8 @@ export interface BroadcastEmailSettings {
trackingEnabled: boolean
utmTagsEnabled: boolean
utmParams: UtmTagValues
+ /** The utmParams keys that still follow the team default. Absent on broadcasts saved before team defaults. */
+ utmParamsFromDefault?: UtmTagKey[]
}
export const DEFAULT_BROADCAST_EMAIL_SETTINGS: BroadcastEmailSettings = {
@@ -202,6 +205,7 @@ function readEmailSettings(broadcast: HogFlowApi): BroadcastEmailSettings | null
trackingEnabled: config.tracking_enabled !== false,
utmTagsEnabled: config.utm_tags_enabled === true,
utmParams: config.utm_params ?? {},
+ utmParamsFromDefault: config.utm_params_from_default,
}
}
@@ -215,6 +219,7 @@ function emailSettingsConfig(settings: BroadcastEmailSettings | undefined): Reco
tracking_enabled: settings.trackingEnabled,
utm_tags_enabled: settings.utmTagsEnabled,
utm_params: settings.utmParams,
+ utm_params_from_default: settings.utmParamsFromDefault,
}
}
@@ -496,6 +501,11 @@ export interface broadcastWizardLogicActions {
saveName: () => {
value: true
}
+ seedTeamUtmDefaults: (
+ settings: Pick<BroadcastEmailSettings, 'utmParams' | 'utmParamsFromDefault' | 'utmTagsEnabled'>
+ ) => {
+ settings: Pick<BroadcastEmailSettings, 'utmParams' | 'utmParamsFromDefault' | 'utmTagsEnabled'>
+ }
sendToEveryoneAfterRejectedLink: () => {
value: true
}
@@ -693,6 +703,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
setConversion: (conversion: HogFlowConversionApi) => ({ conversion }),
setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => ({ emailRateLimit }),
setEmailSettings: (settings: Partial<BroadcastEmailSettings>) => ({ settings }),
+ seedTeamUtmDefaults: (
+ settings: Pick<BroadcastEmailSettings, 'utmTagsEnabled' | 'utmParams' | 'utmParamsFromDefault'>
+ ) => ({ settings }),
setEmail: (email: BroadcastEmailValue) => ({ email }),
applyAiEmailDraft: (draft: MessageDraft) => ({ draft }),
applyDefaultSender: true,
@@ -959,6 +972,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
DEFAULT_BROADCAST_EMAIL_SETTINGS,
{
setEmailSettings: (state, { settings }) => ({ ...state, ...settings }),
+ // Not setEmailSettings: that one autosaves, and opening /broadcasts/new must not create a draft.
+ seedTeamUtmDefaults: (state, { settings }) => ({ ...state, ...settings }),
hydrateFromBroadcast: (state, { broadcast }) => readEmailSettings(broadcast) ?? state,
applyExternalEdit: (state, { broadcast, base }) =>
changedElsewhere(broadcast, base, readEmailSettings)
@@ -1405,7 +1420,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.applyDefaultSender()
actions.landOnPrefilledStep()
},
- [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {
+ // A new broadcast that mounted before the team loaded still shows the built-in settings.
+ // Anything the user changed since replaced that object, so it is left alone.
+ if (props.id === 'new' && currentTeam && values.emailSettings === DEFAULT_BROADCAST_EMAIL_SETTINGS) {
+ seedTeamUtmDefaults(actions, currentTeam)
+ }
actions.applyDefaultSender()
actions.landOnPrefilledStep()
},
@@ -2192,6 +2212,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.loadBroadcast()
return
}
+ if (values.currentTeam) {
+ seedTeamUtmDefaults(actions, values.currentTeam)
+ }
actions.applyDefaultSender()
const {
[AUDIENCE_PREFILL_PARAM]: audience,
@@ -2285,6 +2308,18 @@ async function saveDraftSchedule(
}
}
+function seedTeamUtmDefaults(
+ actions: broadcastWizardLogicType['actions'],
+ currentTeam: TeamPublicType | TeamType
+): void {
+ const utm = newEmailUtmConfig(getTeamUtmDefaults(currentTeam.workflows_config))
+ actions.seedTeamUtmDefaults({
+ utmTagsEnabled: utm.utm_tags_enabled,
+ utmParams: utm.utm_params,
+ utmParamsFromDefault: utm.utm_params_from_default,
+ })
+}
+
async function createDraft(projectId: string, values: broadcastWizardLogicType['values']): Promise<HogFlowApi> {
const created = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
// pinned: analytics event name
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
index a0bd5fc919ed..b8d9c58abd41 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
@@ -12,7 +12,9 @@ import { IntegrationType } from '~/types'
import { EmailSetupModal } from '../../Channels/EmailSetup/EmailSetupModal'
import { AiEmailDraftStatus } from '../../MessageAudience/AiEmailDraftStatus'
import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'
-import { UtmTagFields } from '../../Workflows/hogflows/steps/components/UtmTagFields'
+import { utmKeysFromDefaultAfterEdit } from '../../Workflows/hogflows/steps/components/utmDefaults'
+import { UTM_TAG_KEYS, UtmTagFields } from '../../Workflows/hogflows/steps/components/UtmTagFields'
+import { UtmTeamDefaultControls } from '../../Workflows/hogflows/steps/components/UtmTeamDefaultControls'
import {
BroadcastEmailValue,
DEFAULT_BROADCAST_EMAIL,
@@ -157,14 +159,29 @@ export function BroadcastContentStep(): JSX.Element {
data-attr="broadcast-utm-tags-toggle"
/>
{emailSettings.utmTagsEnabled && (
- <UtmTagFields
- value={emailSettings.utmParams}
- onChange={(utmParams) => setEmailSettings({ utmParams })}
- campaignDefault={name || 'Broadcast name'}
- contentDefault={
- broadcast?.actions?.find((action) => action.type === 'function_email')?.name ?? 'Send email'
- }
- />
+ <>
+ <UtmTagFields
+ value={emailSettings.utmParams}
+ onChange={(utmParams) =>
+ setEmailSettings({
+ utmParams,
+ utmParamsFromDefault: utmKeysFromDefaultAfterEdit(
+ emailSettings.utmParamsFromDefault,
+ emailSettings.utmParams,
+ utmParams
+ ),
+ })
+ }
+ campaignDefault={name || 'Broadcast name'}
+ contentDefault={
+ broadcast?.actions?.find((action) => action.type === 'function_email')?.name ?? 'Send email'
+ }
+ />
+ <UtmTeamDefaultControls
+ value={emailSettings.utmParams}
+ onSavedAsTeamDefault={() => setEmailSettings({ utmParamsFromDefault: [...UTM_TAG_KEYS] })}
+ />
+ </>
)}
</div>
)
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
index ff35dd53ef47..1e5d9ce8a1df 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts
@@ -1,7 +1,10 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
@@ -216,6 +219,103 @@ describe('hogFlowEditorLogic', () => {
])
})
+ it('keeps edits made while "Save as team default" was saving', () => {
+ const email = {
+ id: 'email',
+ name: 'Send email',
+ description: '',
+ type: 'function_email',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ template_id: 'template-email',
+ inputs: {},
+ utm_tags_enabled: true,
+ utm_params: { utm_source: 'partner', utm_campaign: 'spring' },
+ utm_params_from_default: [],
+ },
+ } as HogFlowAction
+ workflowLogic().actions.setWorkflowInfo({
+ actions: [NEW_WORKFLOW.actions[0], email, NEW_WORKFLOW.actions[1]],
+ edges: [edge(TRIGGER_NODE_ID, email.id, 'continue'), edge(email.id, EXIT_NODE_ID, 'continue')],
+ })
+ const saved = { utm_source: 'partner', utm_campaign: 'spring' }
+ logic.actions.setWorkflowAction(email.id, {
+ ...email,
+ name: 'Renamed while saving',
+ config: { ...email.config, utm_params: { utm_source: 'partner', utm_campaign: 'summer' } },
+ } as HogFlowAction)
+
+ logic.actions.markUtmSavedAsTeamDefault(email.id, saved)
+
+ const latest = logic.values.workflow.actions.find((action) => action.id === email.id)
+ expect(latest).toMatchObject({
+ name: 'Renamed while saving',
+ config: {
+ utm_params: { utm_source: 'partner', utm_campaign: 'summer' },
+ utm_params_from_default: ['utm_source', 'utm_medium', 'utm_content'],
+ },
+ })
+ })
+
+ it.each([
+ {
+ case: 'a delay',
+ step: {
+ id: 'step',
+ name: 'Delay',
+ description: '',
+ type: 'delay',
+ created_at: 0,
+ updated_at: 0,
+ config: { delay_duration: '1d' },
+ } as HogFlowAction,
+ },
+ {
+ case: 'an email with its own UTM settings',
+ step: {
+ id: 'step',
+ name: 'Send email',
+ description: '',
+ type: 'function_email',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ template_id: 'template-email',
+ inputs: {},
+ utm_tags_enabled: false,
+ utm_params: { utm_source: 'partner' },
+ utm_params_from_default: ['utm_medium'],
+ },
+ } as HogFlowAction,
+ },
+ ])('duplicates $case below itself', ({ step }) => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ workflows_config: {
+ capture_workflows_engagement_events: false,
+ email_utm_tags_enabled: true,
+ email_utm_params: { utm_source: 'newsletter' },
+ },
+ })
+ workflowLogic().actions.setWorkflowInfo({
+ actions: [NEW_WORKFLOW.actions[0], step, NEW_WORKFLOW.actions[1]],
+ edges: [edge(TRIGGER_NODE_ID, step.id, 'continue'), edge(step.id, EXIT_NODE_ID, 'continue')],
+ })
+
+ logic.actions.duplicateNodeBelow(step.id)
+
+ const duplicatedAction = logic.values.workflow.actions.find(
+ (action) => action.id !== step.id && action.type === step.type
+ )
+ expect(duplicatedAction).toMatchObject({ name: step.name, config: step.config })
+ expect(logic.values.workflow.edges).toEqual([
+ edge(TRIGGER_NODE_ID, step.id, 'continue'),
+ edge(step.id, duplicatedAction!.id, 'continue'),
+ edge(duplicatedAction!.id, EXIT_NODE_ID, 'continue'),
+ ])
+ })
+
describe('conditional branch naming', () => {
const createMockHogFlow = (conditionNames?: (string | undefined)[]): HogFlow => ({
id: 'test-flow',
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index df51d07a4001..c66aa6e1c3bc 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -34,8 +34,13 @@ import { templateToConfiguration } from 'scenes/hog-functions/configuration/hogF
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import type { HogFunctionTemplateType, UserBasicType } from '../../../../../frontend/src/types'
-import type { IntegrationType, TeamPublicType, TeamType } from '../../../../../frontend/src/types'
+import type {
+ HogFunctionTemplateType,
+ IntegrationType,
+ TeamPublicType,
+ TeamType,
+ UserBasicType,
+} from '../../../../../frontend/src/types'
import { resolveDefaultEmailSender } from '../../Channels/defaultEmailSender'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
import type { MessageCategory } from '../../OptOuts/optOutCategoriesLogic'
@@ -51,6 +56,9 @@ import {
TOP_HANDLE_POSITION,
} from './react_flow_utils/constants'
import { getSmartStepPath } from './react_flow_utils/SmartEdge'
+import { getTeamUtmDefaults, newEmailUtmConfig, utmKeysFollowingSavedDefault } from './steps/components/utmDefaults'
+import type { UtmTagValues } from './steps/components/UtmTagFields'
+import type { UtmTagKey } from './steps/components/UtmTagFields'
import { getHogFlowStep } from './steps/HogFlowSteps'
import { CyclotronInputType, StepViewNodeHandle } from './steps/types'
import { isWorkflowTreeComplete } from './tree/workflowTree'
@@ -805,6 +813,9 @@ export interface hogFlowEditorLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?:
+ | ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[]
+ | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -1688,6 +1699,9 @@ export interface hogFlowEditorLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?:
+ | ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[]
+ | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -2136,6 +2150,13 @@ export interface hogFlowEditorLogicActions {
timezone: string
}
}
+ markUtmSavedAsTeamDefault: (
+ actionId: string,
+ saved: UtmTagValues
+ ) => {
+ actionId: string
+ saved: Partial<Record<UtmTagKey, string>>
+ }
moveNodeToEdge: (
movingNodeId: string,
targetEdge: HogFlowEdge,
@@ -2346,6 +2367,7 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
joinEdges,
}),
duplicateNodeBelow: (actionId: string) => ({ actionId }),
+ markUtmSavedAsTeamDefault: (actionId: string, saved: UtmTagValues) => ({ actionId, saved }),
loadActionMetricsById: (
params: Pick<AppMetricsTotalsRequest, 'appSource' | 'appSourceId' | 'dateFrom' | 'dateTo'>,
timezone: string
@@ -2878,6 +2900,20 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}
}
+ // A copied email keeps its own UTM choice. Without the team loaded the UTM keys stay out, so
+ // the API copies the team defaults on save.
+ if (
+ !isHogFlowActionNode &&
+ partialNewAction.type === 'function_email' &&
+ !('utm_tags_enabled' in config) &&
+ values.currentTeam
+ ) {
+ config = {
+ ...config,
+ ...newEmailUtmConfig(getTeamUtmDefaults(values.currentTeam.workflows_config)),
+ }
+ }
+
if (!isHogFlowActionNode && 'template_id' in config && config.template_id === 'template-email') {
const emailInput = config.inputs?.email
const team = values.currentTeam
@@ -3145,6 +3181,20 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
actions.setWorkflowInfo({ actions: values.workflow.actions, edges: newEdges })
actions.setSelectedNodeId(movingNodeId)
},
+ markUtmSavedAsTeamDefault: ({ actionId, saved }) => {
+ // The save takes a round trip, so start from the step as it is now to keep edits made meanwhile.
+ const latest = values.workflow.actions.find((action) => action.id === actionId)
+ if (!latest || latest.type !== 'function_email') {
+ return
+ }
+ actions.setWorkflowAction(actionId, {
+ ...latest,
+ config: {
+ ...latest.config,
+ utm_params_from_default: utmKeysFollowingSavedDefault(latest.config.utm_params ?? {}, saved),
+ },
+ })
+ },
duplicateNodeBelow: ({ actionId }) => {
const action = values.workflow.actions.find((action) => action.id === actionId)
const targetEdge = values.workflow.edges.find((edge) => edge.from === actionId)
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
index 8f014e90d2e8..d286f90d9abe 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
@@ -27,7 +27,9 @@ import { CategorySelect } from 'products/workflows/frontend/OptOuts/CategorySele
import { workflowLogic } from '../../workflowLogic'
import { HogFlowPropertyFilters } from '../filters/HogFlowFilters'
import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { utmKeysFromDefaultAfterEdit } from '../steps/components/utmDefaults'
import { UtmTagFields } from '../steps/components/UtmTagFields'
+import { UtmTeamDefaultControls } from '../steps/components/UtmTeamDefaultControls'
import { useHogFlowStep } from '../steps/HogFlowSteps'
import { isEmailAction, isOptOutEligibleAction } from '../steps/types'
import type { HogFlowAction } from '../types'
@@ -40,7 +42,7 @@ import { OutputTestResultTree } from './OutputTestResultTree'
export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
const { selectedNode, workflow, categories, categoriesLoading } = useValues(hogFlowEditorLogic)
- const { setWorkflowAction, setMode } = useActions(hogFlowEditorLogic)
+ const { setWorkflowAction, setMode, markUtmSavedAsTeamDefault } = useActions(hogFlowEditorLogic)
const { logicProps } = useValues(workflowLogic)
const { mappings, pendingPath, testLoading, testError, testResultData, shakePickButton, pendingSuggestions } =
useValues(hogFlowOutputMappingLogic(logicProps))
@@ -174,18 +176,30 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
/>
</div>
{action.config.utm_tags_enabled === true && (
- <div className="px-2 pb-2">
+ <div className="px-2 pb-2 flex flex-col gap-2">
<UtmTagFields
value={action.config.utm_params ?? {}}
onChange={(utmParams) => {
setWorkflowAction(action.id, {
...action,
- config: { ...action.config, utm_params: utmParams },
+ config: {
+ ...action.config,
+ utm_params: utmParams,
+ utm_params_from_default: utmKeysFromDefaultAfterEdit(
+ action.config.utm_params_from_default,
+ action.config.utm_params ?? {},
+ utmParams
+ ),
+ },
})
}}
campaignDefault={workflow.name || 'Workflow name'}
contentDefault={action.name}
/>
+ <UtmTeamDefaultControls
+ value={action.config.utm_params ?? {}}
+ onSavedAsTeamDefault={(saved) => markUtmSavedAsTeamDefault(action.id, saved)}
+ />
</div>
)}
</>
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx
index 4cb08c5060e2..376f13e8c298 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx
@@ -3,7 +3,7 @@ import { LemonInput } from '@posthog/lemon-ui'
export type UtmTagKey = 'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_content'
export type UtmTagValues = Partial<Record<UtmTagKey, string>>
-const UTM_TAG_KEYS: UtmTagKey[] = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content']
+export const UTM_TAG_KEYS: UtmTagKey[] = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content']
export interface UtmTagFieldsProps {
value: UtmTagValues
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTeamDefaultControls.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTeamDefaultControls.tsx
new file mode 100644
index 000000000000..05eab7dd7454
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTeamDefaultControls.tsx
@@ -0,0 +1,63 @@
+import { useAsyncActions, useValues } from 'kea'
+
+import { LemonButton, Link } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import type { WorkflowsConfig } from '~/types'
+
+import { getTeamUtmDefaults, matchesTeamUtmDefaults } from './utmDefaults'
+import type { UtmTagValues } from './UtmTagFields'
+
+export interface UtmTeamDefaultControlsProps {
+ value: UtmTagValues
+ /** Called after the values become the team default, so the email can mark them as following it. */
+ onSavedAsTeamDefault: (saved: UtmTagValues) => void
+}
+
+export function UtmTeamDefaultControls({ value, onSavedAsTeamDefault }: UtmTeamDefaultControlsProps): JSX.Element {
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const { updateCurrentTeam } = useAsyncActions(teamLogic)
+ const defaults = getTeamUtmDefaults(currentTeam?.workflows_config)
+ const editDefaultsLink = (
+ <Link to={urls.settings('environment-workflows', 'workflows-utm-defaults')} target="_blank">
+ Edit team defaults
+ </Link>
+ )
+
+ // Callers show this only for emails with tags on, so an email matches the default only when the default is on.
+ if (defaults.enabled && matchesTeamUtmDefaults(value, defaults)) {
+ return <span className="text-xs text-secondary">Using your team's default values. {editDefaultsLink}</span>
+ }
+
+ return (
+ <div className="flex items-center gap-2 flex-wrap">
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ loading={currentTeamLoading}
+ disabledReason={currentTeam?.workflows_config ? undefined : 'Loading your workflow settings'}
+ onClick={async () => {
+ await updateCurrentTeam({
+ // The API updates only the fields sent. A copy of the cached config would overwrite newer settings.
+ workflows_config: {
+ email_utm_tags_enabled: true,
+ email_utm_params: value,
+ } satisfies Partial<WorkflowsConfig> as WorkflowsConfig,
+ })
+ // A failed save still resolves, so check what was saved. teamLogic shows the error, and the
+ // email keeps its values as its own so a later bulk apply skips them.
+ const saved = getTeamUtmDefaults(teamLogic.values.currentTeam?.workflows_config)
+ if (saved.enabled && matchesTeamUtmDefaults(value, saved)) {
+ onSavedAsTeamDefault(value)
+ }
+ }}
+ data-attr="email-utm-save-as-team-default"
+ >
+ Save as team default
+ </LemonButton>
+ <span className="text-xs text-secondary">New emails will start with these values. {editDefaultsLink}</span>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.test.ts
new file mode 100644
index 000000000000..c4464b6435d3
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.test.ts
@@ -0,0 +1,42 @@
+import { matchesTeamUtmDefaults, utmKeysFromDefaultAfterEdit } from './utmDefaults'
+import type { UtmTagKey } from './UtmTagFields'
+
+describe('utmDefaults', () => {
+ describe('utmKeysFromDefaultAfterEdit', () => {
+ it.each([
+ {
+ case: 'an edited value stops following the team default',
+ fromDefault: ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content'] as UtmTagKey[],
+ next: { utm_source: 'partner', utm_campaign: 'spring' },
+ expected: ['utm_medium', 'utm_campaign', 'utm_content'],
+ },
+ {
+ case: 'a step from before team defaults follows every key it did not change',
+ fromDefault: undefined,
+ next: { utm_source: 'newsletter', utm_campaign: 'summer' },
+ expected: ['utm_source', 'utm_medium', 'utm_content'],
+ },
+ {
+ case: 'a key that already stopped following never comes back on its own',
+ fromDefault: ['utm_medium'] as UtmTagKey[],
+ next: { utm_source: 'newsletter', utm_campaign: 'spring' },
+ expected: ['utm_medium'],
+ },
+ ])('$case', ({ fromDefault, next, expected }) => {
+ const previous = { utm_source: 'newsletter', utm_campaign: 'spring' }
+
+ expect(utmKeysFromDefaultAfterEdit(fromDefault, previous, next)).toEqual(expected)
+ })
+ })
+
+ describe('matchesTeamUtmDefaults', () => {
+ it.each([
+ { case: 'surrounding spaces still match the saved value', value: ' newsletter ', expected: true },
+ { case: 'a different value does not match', value: 'partner', expected: false },
+ ])('$case', ({ value, expected }) => {
+ const defaults = { enabled: true, params: { utm_source: 'newsletter' } }
+
+ expect(matchesTeamUtmDefaults({ utm_source: value }, defaults)).toBe(expected)
+ })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.ts
new file mode 100644
index 000000000000..1fbe06b74db6
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/utmDefaults.ts
@@ -0,0 +1,62 @@
+import type { WorkflowsConfig } from '~/types'
+
+import { UTM_TAG_KEYS, type UtmTagKey, type UtmTagValues } from './UtmTagFields'
+
+export interface TeamUtmDefaults {
+ enabled: boolean
+ params: UtmTagValues
+}
+
+/** Drops empty values and trims the rest, the same way the team API stores them. */
+export function cleanUtmParams(params: UtmTagValues | null | undefined): UtmTagValues {
+ const cleaned: UtmTagValues = {}
+ for (const key of UTM_TAG_KEYS) {
+ const value = params?.[key]?.trim()
+ if (value) {
+ cleaned[key] = value
+ }
+ }
+ return cleaned
+}
+
+export function getTeamUtmDefaults(config: WorkflowsConfig | null | undefined): TeamUtmDefaults {
+ return { enabled: config?.email_utm_tags_enabled === true, params: cleanUtmParams(config?.email_utm_params) }
+}
+
+export function newEmailUtmConfig(defaults: TeamUtmDefaults): {
+ utm_tags_enabled: boolean
+ utm_params: UtmTagValues
+ utm_params_from_default: UtmTagKey[]
+} {
+ return {
+ utm_tags_enabled: defaults.enabled,
+ utm_params: { ...defaults.params },
+ utm_params_from_default: [...UTM_TAG_KEYS],
+ }
+}
+
+/**
+ * Which keys still follow the team default after an edit. A key someone changed stops following it,
+ * so applying new team defaults later leaves that value alone. Steps from before team defaults have
+ * no list, and all their keys count as following.
+ */
+export function utmKeysFromDefaultAfterEdit(
+ fromDefault: UtmTagKey[] | undefined,
+ previous: UtmTagValues,
+ next: UtmTagValues
+): UtmTagKey[] {
+ const following = fromDefault ?? [...UTM_TAG_KEYS]
+ return following.filter((key) => (previous[key] ?? '') === (next[key] ?? ''))
+}
+
+export function matchesTeamUtmDefaults(params: UtmTagValues, defaults: TeamUtmDefaults): boolean {
+ const cleaned = cleanUtmParams(params)
+ return UTM_TAG_KEYS.every((key) => (cleaned[key] ?? '') === (defaults.params[key] ?? ''))
+}
+
+/** Which keys follow the team default after "Save as team default": those still holding the saved value. */
+export function utmKeysFollowingSavedDefault(current: UtmTagValues, saved: UtmTagValues): UtmTagKey[] {
+ const cleanedCurrent = cleanUtmParams(current)
+ const cleanedSaved = cleanUtmParams(saved)
+ return UTM_TAG_KEYS.filter((key) => (cleanedCurrent[key] ?? '') === (cleanedSaved[key] ?? ''))
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
index db33a10173bd..a29f00f9869b 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
@@ -482,6 +482,7 @@ export interface stepDelayLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
) => {
@@ -796,6 +797,7 @@ export interface stepDelayLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
} // workflowLogic
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
index 754633a23188..03774975f160 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
@@ -408,6 +408,7 @@ export interface stepWaitUntilTimeWindowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
>
@@ -723,6 +724,7 @@ export interface stepWaitUntilTimeWindowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
>
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
index 8b5c12608113..0e8286a80f0f 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
@@ -390,6 +390,10 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
utm_content: z.string().optional(),
})
.optional(),
+ // utm_params keys that follow the team default. Only the Django API reads it, so Node does not declare it.
+ utm_params_from_default: z
+ .array(z.enum(['utm_source', 'utm_medium', 'utm_campaign', 'utm_content']))
+ .optional(),
template_uuid: z.string().optional(), // May be used later to specify a specific template version
template_id: z.literal('template-email'),
inputs: z.record(z.string(), CyclotronInputSchema),
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index a214c9bf928c..30c1c98c0ce6 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -676,6 +676,9 @@ export interface workflowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?:
+ | ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[]
+ | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -1559,6 +1562,9 @@ export interface workflowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?:
+ | ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[]
+ | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -2499,6 +2505,7 @@ export interface workflowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
>
@@ -2899,6 +2906,7 @@ export interface workflowLogicActions {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
}
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index 99cb2b67cbea..b22485b8d432 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -524,6 +524,7 @@ export interface workflowMetricsSummaryLogicValues {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -761,6 +762,7 @@ export interface workflowMetricsSummaryLogicMeta {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?: ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[] | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
@@ -903,6 +905,9 @@ export interface workflowMetricsSummaryLogicMeta {
utm_source?: string | undefined
}
| undefined
+ utm_params_from_default?:
+ | ('utm_campaign' | 'utm_content' | 'utm_medium' | 'utm_source')[]
+ | undefined
utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
diff --git a/products/workflows/frontend/scenes/settings/WorkflowsUtmDefaultsSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsUtmDefaultsSettings.tsx
new file mode 100644
index 000000000000..16ffb06aed41
--- /dev/null
+++ b/products/workflows/frontend/scenes/settings/WorkflowsUtmDefaultsSettings.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { UtmTagFields } from '../../Workflows/hogflows/steps/components/UtmTagFields'
+import { workflowsUtmDefaultsSettingsLogic } from './workflowsUtmDefaultsSettingsLogic'
+
+export function WorkflowsUtmDefaultsSettings(): JSX.Element {
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const { form, hasUnsavedChanges } = useValues(workflowsUtmDefaultsSettingsLogic)
+ const { setDraftEnabled, setDraftParams, saveDefaults } = useActions(workflowsUtmDefaultsSettingsLogic)
+
+ return (
+ <div className="flex flex-col gap-2 max-w-160">
+ <LemonSwitch
+ id="workflows-email-utm-defaults"
+ checked={form.enabled}
+ onChange={setDraftEnabled}
+ label="Add UTM tags to links in new emails"
+ bordered
+ data-attr="workflows-utm-defaults-toggle"
+ />
+ <UtmTagFields
+ value={form.params}
+ onChange={setDraftParams}
+ campaignDefault="Broadcast or workflow name"
+ contentDefault="Email step name"
+ />
+ <div className="flex gap-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={currentTeamLoading}
+ disabledReason={
+ !currentTeam?.workflows_config
+ ? 'Loading your workflow settings'
+ : hasUnsavedChanges
+ ? undefined
+ : 'No changes to save'
+ }
+ onClick={saveDefaults}
+ data-attr="workflows-utm-defaults-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/scenes/settings/workflowsUtmDefaultsSettingsLogic.ts b/products/workflows/frontend/scenes/settings/workflowsUtmDefaultsSettingsLogic.ts
new file mode 100644
index 000000000000..2d6fd440ec60
--- /dev/null
+++ b/products/workflows/frontend/scenes/settings/workflowsUtmDefaultsSettingsLogic.ts
@@ -0,0 +1,122 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { TeamPublicType, TeamType, WorkflowsConfig } from '../../../../../frontend/src/types'
+import {
+ cleanUtmParams,
+ getTeamUtmDefaults,
+ matchesTeamUtmDefaults,
+ type TeamUtmDefaults,
+} from '../../Workflows/hogflows/steps/components/utmDefaults'
+import type { UtmTagValues } from '../../Workflows/hogflows/steps/components/UtmTagFields'
+import type { UtmTagKey } from '../../Workflows/hogflows/steps/components/UtmTagFields'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsUtmDefaultsSettingsLogicValues {
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ draft: Partial<TeamUtmDefaults> | null
+ form: TeamUtmDefaults
+ hasUnsavedChanges: boolean
+ savedDefaults: TeamUtmDefaults
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsUtmDefaultsSettingsLogicActions {
+ resetDraft: () => {
+ value: true
+ }
+ saveDefaults: () => {
+ value: true
+ }
+ setDraftEnabled: (enabled: boolean) => {
+ enabled: boolean
+ }
+ setDraftParams: (params: UtmTagValues) => {
+ params: Partial<Record<UtmTagKey, string>>
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowsUtmDefaultsSettingsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ savedDefaults: (currentTeam: TeamPublicType | TeamType | null) => TeamUtmDefaults
+ form: (draft: Partial<TeamUtmDefaults> | null, savedDefaults: TeamUtmDefaults) => TeamUtmDefaults
+ hasUnsavedChanges: (form: TeamUtmDefaults, savedDefaults: TeamUtmDefaults) => boolean
+ }
+}
+
+export type workflowsUtmDefaultsSettingsLogicType = MakeLogicType<
+ workflowsUtmDefaultsSettingsLogicValues,
+ workflowsUtmDefaultsSettingsLogicActions,
+ Record<string, any>,
+ workflowsUtmDefaultsSettingsLogicMeta
+>
+
+export const workflowsUtmDefaultsSettingsLogic = kea<workflowsUtmDefaultsSettingsLogicType>([
+ path(['products', 'workflows', 'frontend', 'scenes', 'settings', 'workflowsUtmDefaultsSettingsLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam']],
+ })),
+ actions({
+ setDraftEnabled: (enabled: boolean) => ({ enabled }),
+ setDraftParams: (params: UtmTagValues) => ({ params }),
+ resetDraft: true,
+ saveDefaults: true,
+ }),
+ reducers({
+ // Null while the form shows the saved defaults, so a team that loads or changes later fills it in.
+ draft: [
+ null as Partial<TeamUtmDefaults> | null,
+ {
+ setDraftEnabled: (state, { enabled }) => ({ ...state, enabled }),
+ setDraftParams: (state, { params }) => ({ ...state, params }),
+ resetDraft: () => null,
+ },
+ ],
+ }),
+ selectors({
+ savedDefaults: [
+ (s) => [s.currentTeam],
+ (currentTeam: TeamPublicType | TeamType | null): TeamUtmDefaults =>
+ getTeamUtmDefaults(currentTeam?.workflows_config),
+ ],
+ form: [
+ (s) => [s.draft, s.savedDefaults],
+ (draft: Partial<TeamUtmDefaults> | null, saved: TeamUtmDefaults): TeamUtmDefaults => ({
+ enabled: draft?.enabled ?? saved.enabled,
+ params: draft?.params ?? saved.params,
+ }),
+ ],
+ hasUnsavedChanges: [
+ (s) => [s.form, s.savedDefaults],
+ (form: TeamUtmDefaults, saved: TeamUtmDefaults): boolean =>
+ form.enabled !== saved.enabled || !matchesTeamUtmDefaults(form.params, saved),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ saveDefaults: async () => {
+ const form = values.form
+ const params = cleanUtmParams(form.params)
+ if (!values.currentTeam?.workflows_config) {
+ return
+ }
+ await teamLogic.asyncActions.updateCurrentTeam({
+ // The API updates only the fields sent. A copy of the cached config would overwrite newer settings.
+ workflows_config: {
+ email_utm_tags_enabled: form.enabled,
+ email_utm_params: params,
+ } satisfies Partial<WorkflowsConfig> as WorkflowsConfig,
+ })
+ // A failed save still resolves, so check what was saved. On failure the form keeps the edits.
+ const saved = values.savedDefaults
+ if (saved.enabled !== form.enabled || !matchesTeamUtmDefaults(params, saved)) {
+ return
+ }
+ // Edits made while the save was in flight are not saved yet, so they stay in the form.
+ if (values.form.enabled === form.enabled && matchesTeamUtmDefaults(values.form.params, saved)) {
+ actions.resetDraft()
+ }
+ },
+ })),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5725685cbae8..2d8f8abd1638 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39655,6 +39655,29 @@ export namespace Schemas {
OptIn: 'opt_in',
} as const;
+ export interface EmailUtmParams {
+ /**
+ * Default utm_source. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_source?: string;
+ /**
+ * Default utm_medium. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_medium?: string;
+ /**
+ * Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_campaign?: string;
+ /**
+ * Default utm_content. Empty uses the email step name. Supports Liquid variables.
+ * @maxLength 500
+ */
+ utm_content?: string;
+ }
+
export type EmbeddingStatusEnum = typeof EmbeddingStatusEnum[keyof typeof EmbeddingStatusEnum];
@@ -86022,6 +86045,10 @@ export namespace Schemas {
* * `opt_out` - Opt Out
* * `opt_in` - Opt In */
email_tracking_consent_mode?: EmailTrackingConsentModeEnum;
+ /** Whether new email steps and broadcasts start with UTM tags on their links. Each email can still change it. Existing emails keep their current values. */
+ email_utm_tags_enabled?: boolean;
+ /** Default UTM values that new email steps and broadcasts copy. An empty value keeps the built-in default for that tag. */
+ email_utm_params?: EmailUtmParams;
/**
* How many AI tasks one workflow can create in a rolling 24 hours. Null uses the default of 100; zero pauses task creation for every workflow in the project. Support raises the limit above 500.
* @minimum 0
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 5b909a313c5f..9b0bf337a0ab 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -349,6 +349,14 @@ export const organizationsProjectsCreateBodyMarketingAnalyticsConfigConversionGo
export const organizationsProjectsCreateBodyMarketingAnalyticsConfigConversionGoalsOneItemThreePropertiesOneItemSixTypeDefault = `data_warehouse`
export const organizationsProjectsCreateBodyMarketingAnalyticsConfigAttributionWindowDaysMax = 90
+export const organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmSourceMax = 500
+
+export const organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmMediumMax = 500
+
+export const organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmCampaignMax = 500
+
+export const organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmContentMax = 500
+
export const organizationsProjectsCreateBodyWorkflowsConfigWorkflowTaskRateLimitPerDayMin = 0
export const organizationsProjectsCreateBodyWorkflowsConfigWorkflowTaskTeamRateLimitPerDayMin = 0
@@ -2805,6 +2813,43 @@ export const OrganizationsProjectsCreateBody = () => zod
.describe(
"Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"
),
+ email_utm_tags_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether new email steps and broadcasts start with UTM tags on their links. Each email can still change it. Existing emails keep their current values.'
+ ),
+ email_utm_params: zod
+ .object({
+ utm_source: zod
+ .string()
+ .max(organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmSourceMax)
+ .optional()
+ .describe('Default utm_source. Supports Liquid variables.'),
+ utm_medium: zod
+ .string()
+ .max(organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmMediumMax)
+ .optional()
+ .describe('Default utm_medium. Supports Liquid variables.'),
+ utm_campaign: zod
+ .string()
+ .max(organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmCampaignMax)
+ .optional()
+ .describe(
+ 'Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.'
+ ),
+ utm_content: zod
+ .string()
+ .max(organizationsProjectsCreateBodyWorkflowsConfigEmailUtmParamsOneUtmContentMax)
+ .optional()
+ .describe(
+ 'Default utm_content. Empty uses the email step name. Supports Liquid variables.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'Default UTM values that new email steps and broadcasts copy. An empty value keeps the built-in default for that tag.'
+ ),
workflow_task_rate_limit_per_day: zod
.number()
.min(organizationsProjectsCreateBodyWorkflowsConfigWorkflowTaskRateLimitPerDayMin)
@@ -3148,6 +3193,14 @@ export const organizationsProjectsPartialUpdateBodyMarketingAnalyticsConfigConve
export const organizationsProjectsPartialUpdateBodyMarketingAnalyticsConfigConversionGoalsOneItemThreePropertiesOneItemSixTypeDefault = `data_warehouse`
export const organizationsProjectsPartialUpdateBodyMarketingAnalyticsConfigAttributionWindowDaysMax = 90
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmSourceMax = 500
+
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmMediumMax = 500
+
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmCampaignMax = 500
+
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmContentMax = 500
+
export const organizationsProjectsPartialUpdateBodyWorkflowsConfigWorkflowTaskRateLimitPerDayMin = 0
export const organizationsProjectsPartialUpdateBodyWorkflowsConfigWorkflowTaskTeamRateLimitPerDayMin = 0
@@ -5618,6 +5671,43 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod
.describe(
"Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"
),
+ email_utm_tags_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether new email steps and broadcasts start with UTM tags on their links. Each email can still change it. Existing emails keep their current values.'
+ ),
+ email_utm_params: zod
+ .object({
+ utm_source: zod
+ .string()
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmSourceMax)
+ .optional()
+ .describe('Default utm_source. Supports Liquid variables.'),
+ utm_medium: zod
+ .string()
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmMediumMax)
+ .optional()
+ .describe('Default utm_medium. Supports Liquid variables.'),
+ utm_campaign: zod
+ .string()
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmCampaignMax)
+ .optional()
+ .describe(
+ 'Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.'
+ ),
+ utm_content: zod
+ .string()
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigEmailUtmParamsOneUtmContentMax)
+ .optional()
+ .describe(
+ 'Default utm_content. Empty uses the email step name. Supports Liquid variables.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'Default UTM values that new email steps and broadcasts copy. An empty value keeps the built-in default for that tag.'
+ ),
workflow_task_rate_limit_per_day: zod
.number()
.min(organizationsProjectsPartialUpdateBodyWorkflowsConfigWorkflowTaskRateLimitPerDayMin)
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index a1fb78b71248..04261ac8699f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -4391,6 +4391,36 @@
"enum": ["off", "opt_out", "opt_in"],
"type": "string"
},
+ "email_utm_params": {
+ "description": "Default UTM values that new email steps and broadcasts copy. An empty value keeps the built-in default for that tag.",
+ "properties": {
+ "utm_campaign": {
+ "description": "Default utm_campaign. Empty uses the broadcast or workflow name. Supports Liquid variables.",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "utm_content": {
+ "description": "Default utm_content. Empty uses the email step name. Supports Liquid variables.",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "utm_medium": {
+ "description": "Default utm_medium. Supports Liquid variables.",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "utm_source": {
+ "description": "Default utm_source. Supports Liquid variables.",
+ "maxLength": 500,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "email_utm_tags_enabled": {
+ "description": "Whether new email steps and broadcasts start with UTM tags on their links. Each email can still change it. Existing emails keep their current values.",
+ "type": "boolean"
+ },
"marketing_frequency_cap_max_messages": {
"anyOf": [
{