: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 manual opt-out entry for messaging preferences (#58180)
Meikel Ratza3496b8fc610
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 88eff03a6f8e..fb714c0ceca8 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1934,6 +1934,10 @@ export class ApiRequest {return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('opt_outs')}+ public messagingPreferencesAddOptOut(): ApiRequest {+ return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('add_opt_out')+ }+public hogFlows(): ApiRequest {return this.environments().current().addPathComponent('hog_flows')}@@ -6106,6 +6110,11 @@ const api = {}).get()},+ async addOptOut(identifier: string, categoryKey?: string): Promise<OptOutEntry> {+ return await new ApiRequest().messagingPreferencesAddOptOut().create({+ data: { identifier, category_key: categoryKey },+ })+ },},hogFlows: {async getHogFlows(): Promise<PaginatedResponse<HogFlow>> {diff --git a/products/messaging/backend/api/message_preferences.py b/products/messaging/backend/api/message_preferences.pyindex 71c662e355bd..f20065bcc0d7 100644--- a/products/messaging/backend/api/message_preferences.py+++ b/products/messaging/backend/api/message_preferences.py@@ -1,4 +1,5 @@-from rest_framework import serializers, viewsets+from drf_spectacular.utils import extend_schema+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import PageNumberPaginationfrom rest_framework.response import Response@@ -22,9 +23,9 @@ class OptOutsPagination(PageNumberPagination):class MessagePreferencesSerializer(serializers.ModelSerializer):- identifier = serializers.CharField()- updated_at = serializers.DateTimeField()- preferences = serializers.JSONField()+ identifier = serializers.CharField(help_text="The recipient identifier (e.g. email address).")+ updated_at = serializers.DateTimeField(help_text="When the preference was last updated.")+ preferences = serializers.JSONField(help_text="Map of category ID to preference status.")class Meta:model = MessageRecipientPreference@@ -43,6 +44,17 @@ class MessagePreferencesSerializer(serializers.ModelSerializer):]+class AddOptOutRequestSerializer(serializers.Serializer):+ identifier = serializers.CharField(+ max_length=512,+ help_text="The recipient identifier to opt out (e.g. email address).",+ )+ category_key = serializers.CharField(+ required=False,+ help_text="Optional message category key. If omitted, the recipient is opted out of all marketing messages.",+ )++class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "INTERNAL"serializer_class = _FallbackSerializer@@ -81,6 +93,39 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):serializer = MessagePreferencesSerializer(opt_outs, many=True)return Response(serializer.data)+ @extend_schema(+ request=AddOptOutRequestSerializer,+ responses={201: MessagePreferencesSerializer},+ summary="Manually add a recipient to the opt-out list",+ )+ @action(detail=False, methods=["post"])+ def add_opt_out(self, request, **kwargs):+ """Manually add a recipient to the opt-out list for a specific category or all marketing messages."""+ serializer = AddOptOutRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ identifier = serializer.validated_data["identifier"]+ category_key = serializer.validated_data.get("category_key")++ if category_key:+ try:+ category = MessageCategory.objects.get(key=category_key, team_id=self.team_id)+ except MessageCategory.DoesNotExist:+ return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)+ category_id = str(category.id)+ else:+ category_id = ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ preference, created = MessageRecipientPreference.objects.get_or_create(+ team_id=self.team_id,+ identifier=identifier,+ defaults={"created_by": request.user},+ )+ preference.set_preference(category_id, PreferenceStatus.OPTED_OUT)++ response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK+ return Response(MessagePreferencesSerializer(preference).data, status=response_status)+@action(detail=False, methods=["get"])def webhook_url(self, request, **kwargs):"""Return the webhook URL for Customer.io integration setup."""diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.pyindex 355fb1469847..33f290e377b8 100644--- a/products/messaging/backend/api/test/test_message_preferences.py+++ b/products/messaging/backend/api/test/test_message_preferences.py@@ -334,3 +334,100 @@ class TestMessagePreferencesAPIViewSet(APIBaseTest):self.assertEqual(data["count"], 1)self.assertEqual(len(data["results"]), 1)self.assertEqual(data["results"][0]["identifier"], "[email protected]")++ def test_add_opt_out_global(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": "[email protected]"},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, 201)+ data = response.json()+ self.assertEqual(data["identifier"], "[email protected]")+ self.assertEqual(data["preferences"][ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT.value)++ pref = MessageRecipientPreference.objects.get(team=self.team, identifier="[email protected]")+ self.assertEqual(pref.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID), PreferenceStatus.OPTED_OUT)++ def test_add_opt_out_specific_category(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": "[email protected]", "category_key": self.category.key},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, 201)+ data = response.json()+ self.assertEqual(data["identifier"], "[email protected]")+ self.assertEqual(data["preferences"][str(self.category.id)], PreferenceStatus.OPTED_OUT.value)++ def test_add_opt_out_nonexistent_category(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": "[email protected]", "category_key": "does_not_exist"},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, 404)+ self.assertEqual(response.json()["error"], "Category not found")++ def test_add_opt_out_duplicate_identifier_updates_existing(self):+ existing = MessageRecipientPreference.objects.create(+ team=self.team,+ identifier="[email protected]",+ preferences={str(self.category.id): PreferenceStatus.OPTED_IN.value},+ )+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": "[email protected]"},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, 200)+ existing.refresh_from_db()+ self.assertEqual(existing.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID), PreferenceStatus.OPTED_OUT)+ # existing category preference is preserved+ self.assertEqual(existing.get_preference(str(self.category.id)), PreferenceStatus.OPTED_IN)++ @parameterized.expand(+ [+ ("missing_identifier", {}, 400),+ ("blank_identifier", {"identifier": " "}, 400),+ ("empty_string", {"identifier": ""}, 400),+ ]+ )+ def test_add_opt_out_invalid_identifier(self, _name, payload, expected_status):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ payload,+ content_type="application/json",+ )+ self.assertEqual(response.status_code, expected_status)++ @parameterized.expand(+ [+ ("leading_trailing", " [email protected] ", "[email protected]"),+ ("leading_only", " [email protected]", "[email protected]"),+ ("trailing_only", "[email protected] ", "[email protected]"),+ ("no_whitespace", "[email protected]", "[email protected]"),+ ]+ )+ def test_add_opt_out_identifier_normalization(self, _name, raw_identifier, expected_identifier):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": raw_identifier},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, 201)+ self.assertEqual(response.json()["identifier"], expected_identifier)++ def test_add_opt_out_team_isolation(self):+ other_team = self.organization.teams.create(name="Other Team")+ self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",+ {"identifier": "[email protected]"},+ content_type="application/json",+ )+ self.assertTrue(+ MessageRecipientPreference.objects.filter(team=self.team, identifier="[email protected]").exists()+ )+ self.assertFalse(+ MessageRecipientPreference.objects.filter(team=other_team, identifier="[email protected]").exists()+ )diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex 3f1b88833205..a6589bb7bb3d 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -43,6 +43,26 @@ export interface PaginatedMessageCategoryListApi {results: MessageCategoryApi[]}+export interface AddOptOutRequestApi {+ /**+ * The recipient identifier to opt out (e.g. email address).+ * @maxLength 512+ */+ identifier: string+ /** Optional message category key. If omitted, the recipient is opted out of all marketing messages. */+ category_key?: string+}++export interface MessagePreferencesApi {+ readonly id: string+ /** The recipient identifier (e.g. email address). */+ identifier: string+ /** When the preference was last updated. */+ updated_at: string+ /** Map of category ID to preference status. */+ preferences: unknown+}+/*** * `hog` - hog* `liquid` - liquiddiff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.tsindex 8c2ff9829177..e1029468c533 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -9,7 +9,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ AddOptOutRequestApi,MessageCategoryApi,+ MessagePreferencesApi,MessageTemplateApi,MessagingCategoriesListParams,MessagingTemplatesListParams,@@ -255,6 +257,27 @@ export const messagingCategoriesSaveWebhookConfigCreate = async (})}+export const getMessagingPreferencesAddOptOutCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/messaging_preferences/add_opt_out/`+}++/**+ * Manually add a recipient to the opt-out list for a specific category or all marketing messages.+ * @summary Manually add a recipient to the opt-out list+ */+export const messagingPreferencesAddOptOutCreate = async (+ projectId: string,+ addOptOutRequestApi: AddOptOutRequestApi,+ options?: RequestInit+): Promise<MessagePreferencesApi> => {+ return apiMutator<MessagePreferencesApi>(getMessagingPreferencesAddOptOutCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(addOptOutRequestApi),+ })+}+export const getMessagingPreferencesGenerateLinkCreateUrl = (projectId: string) => {return `/api/environments/${projectId}/messaging_preferences/generate_link/`}diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex a245f78e64b2..f4f7954d638e 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -114,6 +114,23 @@ export const MessagingCategoriesSaveWebhookConfigCreateBody = /* @__PURE__ */ zodeleted: zod.boolean().optional(),})+/**+ * Manually add a recipient to the opt-out list for a specific category or all marketing messages.+ * @summary Manually add a recipient to the opt-out list+ */+export const messagingPreferencesAddOptOutCreateBodyIdentifierMax = 512++export const MessagingPreferencesAddOptOutCreateBody = /* @__PURE__ */ zod.object({+ identifier: zod+ .string()+ .max(messagingPreferencesAddOptOutCreateBodyIdentifierMax)+ .describe('The recipient identifier to opt out (e.g. email address).'),+ category_key: zod+ .string()+ .optional()+ .describe('Optional message category key. If omitted, the recipient is opted out of all marketing messages.'),+})+export const messagingTemplatesCreateBodyNameMax = 400export const messagingTemplatesCreateBodyTypeMax = 24diff --git a/products/workflows/frontend/OptOuts/OptOutList.tsx b/products/workflows/frontend/OptOuts/OptOutList.tsxindex 6b691015e48d..49353a1a5328 100644--- a/products/workflows/frontend/OptOuts/OptOutList.tsx+++ b/products/workflows/frontend/OptOuts/OptOutList.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'-import { IconChevronLeft, IconChevronRight, IconExternal, IconRefresh } from '@posthog/icons'-import { LemonButton, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'+import { IconChevronLeft, IconChevronRight, IconExternal, IconPlus, IconRefresh } from '@posthog/icons'+import { LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { More } from 'lib/lemon-ui/LemonButton/More'@@ -15,10 +15,26 @@ import type { OptOutEntry } from './types'export function OptOutList({ category }: { category?: MessageCategory }): JSX.Element {const logic = optOutListLogic({ category })- const { setSelectedIdentifier, openPreferencesPage, loadNextPage, loadPreviousPage, loadOptOutPersons } =- useActions(logic)- const { selectedIdentifier, optOutPersons, optOutPersonsLoading, preferencesUrlLoading, currentPage } =- useValues(logic)+ const {+ setSelectedIdentifier,+ openPreferencesPage,+ loadNextPage,+ loadPreviousPage,+ loadOptOutPersons,+ setShowAddOptOutModal,+ setNewOptOutIdentifier,+ addOptOut,+ } = useActions(logic)+ const {+ selectedIdentifier,+ optOutPersons,+ optOutPersonsLoading,+ preferencesUrlLoading,+ currentPage,+ showAddOptOutModal,+ addOptOutLoading,+ newOptOutIdentifier,+ } = useValues(logic)const handleShowPersons = (identifier: string): void => {setSelectedIdentifier(identifier)@@ -85,7 +101,15 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.Elreturn (<>- <div className="flex justify-end mb-2 mt-[-3rem]">+ <div className="flex justify-end gap-2 mb-2 mt-[-3rem]">+ <LemonButton+ icon={<IconPlus />}+ size="small"+ type="secondary"+ onClick={() => setShowAddOptOutModal(true)}+ >+ Add opt-out+ </LemonButton><LemonButtonicon={<IconRefresh />}size="small"@@ -154,6 +178,47 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El</div>)}</LemonModal>++ <LemonModal+ isOpen={showAddOptOutModal}+ onClose={() => setShowAddOptOutModal(false)}+ title={`Add opt-out${category?.name ? ` for ${category.name}` : ''}`}+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setShowAddOptOutModal(false)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={addOptOutLoading}+ disabled={!newOptOutIdentifier.trim()}+ onClick={() => {+ addOptOut(newOptOutIdentifier.trim())+ }}+ >+ Add opt-out+ </LemonButton>+ </>+ }+ >+ <div className="space-y-2">+ <label htmlFor="opt-out-identifier" className="text-sm font-medium">+ Recipient identifier (e.g. email address)+ </label>+ <LemonInput+ id="opt-out-identifier"+ placeholder="[email protected]"+ value={newOptOutIdentifier}+ onChange={setNewOptOutIdentifier}+ autoFocus+ onPressEnter={() => {+ if (newOptOutIdentifier.trim()) {+ addOptOut(newOptOutIdentifier.trim())+ }+ }}+ />+ </div>+ </LemonModal></>)}diff --git a/products/workflows/frontend/OptOuts/optOutListLogic.ts b/products/workflows/frontend/OptOuts/optOutListLogic.tsindex 8166236fb6a4..ee2e750fd46c 100644--- a/products/workflows/frontend/OptOuts/optOutListLogic.ts+++ b/products/workflows/frontend/OptOuts/optOutListLogic.ts@@ -34,6 +34,8 @@ export const optOutListLogic = kea<optOutListLogicType>([setCurrentPage: (page: number) => ({ page }),loadNextPage: true,loadPreviousPage: true,+ setShowAddOptOutModal: (show: boolean) => ({ show }),+ setNewOptOutIdentifier: (identifier: string) => ({ identifier }),}),reducers({personsModalOpen: [@@ -75,8 +77,37 @@ export const optOutListLogic = kea<optOutListLogicType>([loadPreviousPageSuccess: (state) => Math.max(1, state - 1),},],+ showAddOptOutModal: [+ false,+ {+ setShowAddOptOutModal: (_, { show }) => show,+ addOptOutSuccess: () => false,+ },+ ],+ newOptOutIdentifier: [+ '',+ {+ setNewOptOutIdentifier: (_, { identifier }) => identifier,+ addOptOutSuccess: () => '',+ setShowAddOptOutModal: (state, { show }) => (show ? state : ''),+ },+ ],}),- loaders(({ props, values }) => ({+ loaders(({ props, values, actions }) => ({+ addOptOut: {+ __default: null as OptOutEntry | null,+ addOptOut: async (identifier: string): Promise<OptOutEntry> => {+ try {+ const result = await api.messaging.addOptOut(identifier, props.category?.key)+ lemonToast.success(`${identifier} added to opt-out list`)+ actions.loadOptOutPersons()+ return result+ } catch (e) {+ lemonToast.error('Failed to add opt-out')+ throw e+ }+ },+ },optOutPersons: {__default: { count: 0, next: null, previous: null, results: [] } as PaginatedOptOuts,loadOptOutPersons: async (): Promise<PaginatedOptOuts> => {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ebd0af323ef0..e71617340929 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3499,6 +3499,16 @@ export namespace Schemas {version?: number | null;}+ export interface AddOptOutRequest {+ /**+ * The recipient identifier to opt out (e.g. email address).+ * @maxLength 512+ */+ identifier: string;+ /** Optional message category key. If omitted, the recipient is opted out of all marketing messages. */+ category_key?: string;+ }+export type AddSnapshotsInputBaselineHashes = {[key: string]: string};export type SnapshotManifestItemMetadata = { [key: string]: unknown };@@ -19730,6 +19740,16 @@ export namespace Schemas {content: string;}+ export interface MessagePreferences {+ readonly id: string;+ /** The recipient identifier (e.g. email address). */+ identifier: string;+ /** When the preference was last updated. */+ updated_at: string;+ /** Map of category ID to preference status. */+ preferences: unknown;+ }+export type MessageSentimentScores = {[key: string]: number};export interface MessageSentiment {