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(marketing-analytics): add granular conversion goal write endpoints (#73012)

Javier Bahamondes46fb3162a34e
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index d02e7b360f52..2e05eed06f4e 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -1,25 +1,42 @@
+import uuid
from dataclasses import asdict
-from typing import cast
+from functools import reduce
+from operator import or_
+from typing import Any, Optional, cast
+
+from django.db import transaction
import structlog
from asgiref.sync import async_to_sync
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ RootModel as PydanticRootModel,
+ TypeAdapter,
+ ValidationError as PydanticValidationError,
+ create_model,
+)
from rest_framework import serializers, status
from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
-from posthog.schema import DateRange, SourceMap
+from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3, DateRange, SourceMap
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.api.documentation import _FallbackSerializer
from posthog.api.mixins import validated_request
+from posthog.api.project import capture_team_config_diff
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import DEFAULT_CURRENCY
+from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
from posthog.models.user import User
from products.marketing_analytics.backend.hogql_queries.adapters.base import ExternalConfig, QueryContext
@@ -199,6 +216,137 @@ class ConversionGoalsListResponseSerializer(serializers.Serializer):
has_misconfigured = serializers.BooleanField(help_text="True if any goal is misconfigured")
+# --- conversion goal writes ---
+
+
+_CONVERSION_GOAL_ADAPTER: TypeAdapter[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3] = (
+ TypeAdapter(ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3)
+)
+
+
+class ConversionGoalWrittenList(PydanticRootModel):
+ """List wrapper for OpenAPI schema generation - the response carries every configured goal."""
+
+ root: list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3]
+
+
+class ConversionGoal(PydanticRootModel):
+ """Wrapper for OpenAPI schema generation - one goal, in any of the three node shapes."""
+
+ root: ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
+
+
+def _partial_goal_model(model: type[BaseModel]) -> type[BaseModel]:
+ """The same goal shape with every field optional, for the update request body.
+
+ Update merges what you send into the stored goal, so the request is a patch, not a whole goal.
+ Annotating it with the full model generates a type whose members all require an id, a name and a
+ schema map, making the endpoint's own documented call — `{"goal": {"counts_as_customer": true}}` —
+ a type error that a client can only get past by casting. Derived from the real model so a new
+ field can't be forgotten here.
+ """
+ return create_model( # type: ignore[call-overload]
+ f"Partial{model.__name__}",
+ __config__=ConfigDict(extra="forbid"),
+ __doc__=f"{model.__name__} with every field optional - the fields you send are merged into the stored goal.",
+ **{
+ name: (Optional[field.annotation], None if name != "kind" else field.default)
+ for name, field in model.model_fields.items()
+ },
+ )
+
+
+def _conversion_goal_patch_model() -> Any:
+ """Wrapper for OpenAPI schema generation - the fields to change on one existing goal.
+
+ Built rather than declared: the members are derived from the real goal models, which a class-body
+ annotation can't name.
+ """
+ partials = [
+ _partial_goal_model(model) for model in (ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3)
+ ]
+ union = reduce(or_, partials)
+ return create_model("ConversionGoalPatch", __base__=PydanticRootModel, root=(union, ...))
+
+
+ConversionGoalPatch = _conversion_goal_patch_model()
+
+
+@extend_schema_field(ConversionGoal) # type: ignore[arg-type]
+class ConversionGoalField(serializers.JSONField):
+ def to_internal_value(self, data: Any) -> dict:
+ value = super().to_internal_value(data)
+ # JSONField accepts any JSON value; a non-object goal would 500 at the dict() call downstream
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("goal must be a JSON object.")
+ return value
+
+
+@extend_schema_field(ConversionGoalPatch)
+class ConversionGoalPatchField(ConversionGoalField):
+ pass
+
+
+@extend_schema_field(ConversionGoalWrittenList) # type: ignore[arg-type]
+class ConversionGoalListField(serializers.JSONField):
+ pass
+
+
+_GOAL_MODEL_BY_KIND = {
+ model.model_fields["kind"].default: model.__name__
+ for model in (ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3)
+}
+
+
+def _normalized_goal_name(name: Any) -> str | None:
+ """Goal names as compared for uniqueness — they become SQL column aliases downstream."""
+ return name.strip().casefold() if isinstance(name, str) else None
+
+
+def _readable_pydantic_errors(error: PydanticValidationError, kind: Any = None) -> list[str]:
+ """Pydantic reports one error per union member, which is noise. Keep the field and the message.
+
+ Errors are preferred from the member matching the payload's `kind`: otherwise the first member
+ wins per field, so a data warehouse payload could be told about the events node's requirements
+ for a field it did send correctly.
+ """
+ preferred_model = _GOAL_MODEL_BY_KIND.get(kind)
+ seen: dict[str, str] = {}
+ for detail in sorted(error.errors(), key=lambda d: str(d["loc"][:1]) != str((preferred_model,))):
+ field = ".".join(str(part) for part in detail["loc"] if not str(part).startswith("ConversionGoalFilter"))
+ seen.setdefault(field or "goal", detail["msg"])
+ return [f"{field}: {message}" for field, message in seen.items()]
+
+
+class ConversionGoalWriteSerializer(serializers.Serializer):
+ goal = ConversionGoalField(
+ help_text=(
+ "The conversion goal. Must match one of the ConversionGoalFilter shapes: an events node, an actions "
+ "node or a data warehouse node. conversion_goal_id is assigned by the server and any value sent "
+ "is ignored."
+ )
+ )
+
+
+class ConversionGoalUpdateSerializer(serializers.Serializer):
+ """Separate from create: the body is a patch, so the documented partial has to type-check."""
+
+ goal = ConversionGoalPatchField(
+ help_text=(
+ "The fields to change, merged into the stored goal — anything you leave out is kept, and the goal "
+ "keeps its position in the list. schema_map is merged key by key. The merged result must still match "
+ "one of the ConversionGoalFilter shapes. Send `kind` only to change the goal's shape, in which case "
+ "the goal is replaced rather than merged and the whole new shape is required. conversion_goal_id "
+ "comes from the URL and any value sent is ignored."
+ )
+ )
+
+
+class ConversionGoalWriteResponseSerializer(serializers.Serializer):
+ goal = ConversionGoalField(help_text="The goal as stored after the write")
+ conversion_goals = ConversionGoalListField(help_text="Every configured goal after the write, in display order")
+
+
# --- list_data_sources ---
@@ -581,6 +729,189 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+ @validated_request(
+ request_serializer=ConversionGoalWriteSerializer,
+ responses={
+ 201: OpenApiResponse(response=ConversionGoalWriteResponseSerializer, description="The goal as created"),
+ 400: OpenApiResponse(description="The goal does not match any conversion goal shape"),
+ 403: OpenApiResponse(description="Requires project admin access"),
+ },
+ summary="Create conversion goal",
+ description="Add one conversion goal to the project. The server assigns conversion_goal_id and appends the goal to the end of the list, leaving existing goals untouched.",
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ url_path="conversion_goals/create",
+ required_scopes=["marketing_analytics:write"],
+ )
+ def create_conversion_goal(self, request: Request, *args, **kwargs) -> Response:
+ self._require_project_admin()
+ goal = dict(request.validated_data["goal"])
+ goal["conversion_goal_id"] = str(uuid.uuid4())
+
+ with transaction.atomic():
+ config = self._locked_config()
+ previous = list(config.conversion_goals)
+ goals = list(previous)
+ goals.append(self._validated_goal(goal, existing=goals))
+ self._store_goals(config, goals, previous=previous)
+
+ return Response(
+ {"goal": goals[-1], "conversion_goals": goals},
+ status=status.HTTP_201_CREATED,
+ )
+
+ @validated_request(
+ request_serializer=ConversionGoalUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=ConversionGoalWriteResponseSerializer, description="The goal as updated"),
+ 400: OpenApiResponse(description="The resulting goal does not match any conversion goal shape"),
+ 403: OpenApiResponse(description="Requires project admin access"),
+ 404: OpenApiResponse(description="No goal with that conversion_goal_id"),
+ },
+ summary="Update conversion goal",
+ description=(
+ "Change one conversion goal in place. Fields you send are merged into the stored goal, the rest are "
+ "kept, and the goal keeps its position in the list. Sending a different `kind` replaces the goal "
+ "instead, since the shapes don't share their fields."
+ ),
+ )
+ @action(
+ methods=["PATCH"],
+ detail=False,
+ url_path="conversion_goals/(?P<conversion_goal_id>[^/.]+)/update",
+ required_scopes=["marketing_analytics:write"],
+ )
+ def update_conversion_goal(self, request: Request, *args, **kwargs) -> Response:
+ self._require_project_admin()
+ conversion_goal_id = kwargs["conversion_goal_id"]
+ patch = dict(request.validated_data["goal"])
+
+ with transaction.atomic():
+ config = self._locked_config()
+ previous = list(config.conversion_goals)
+ goals = list(previous)
+ index = self._index_of(goals, conversion_goal_id)
+
+ merged = self._merged_goal(goals[index], patch, conversion_goal_id)
+ goals[index] = self._validated_goal(merged, existing=goals, ignore_index=index)
+ self._store_goals(config, goals, previous=previous)
+
+ return Response({"goal": goals[index], "conversion_goals": goals})
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=ConversionGoalWriteResponseSerializer, description="The goals left after the delete"
+ ),
+ 403: OpenApiResponse(description="Requires project admin access"),
+ 404: OpenApiResponse(description="No goal with that conversion_goal_id"),
+ },
+ summary="Delete conversion goal",
+ description="Remove one conversion goal from the project, leaving the others in place.",
+ )
+ @action(
+ methods=["DELETE"],
+ detail=False,
+ url_path="conversion_goals/(?P<conversion_goal_id>[^/.]+)/delete",
+ required_scopes=["marketing_analytics:write"],
+ )
+ def delete_conversion_goal(self, request: Request, *args, **kwargs) -> Response:
+ self._require_project_admin()
+ conversion_goal_id = kwargs["conversion_goal_id"]
+
+ with transaction.atomic():
+ config = self._locked_config()
+ previous = list(config.conversion_goals)
+ goals = list(previous)
+ removed = goals.pop(self._index_of(goals, conversion_goal_id))
+ self._store_goals(config, goals, previous=previous)
+
+ return Response({"goal": removed, "conversion_goals": goals})
+
+ def _require_project_admin(self) -> None:
+ # The settings PATCH path puts these fields behind ADMIN, so these endpoints have to clear
+ # the same bar or they route around it. RBAC alone doesn't: `check_access_level_for_object`
+ # is permissive without the ACCESS_CONTROL feature. Either check satisfies.
+ if self.user_access_control.access_controls_supported:
+ if self.user_access_control.check_access_level_for_object(self.team, "admin"):
+ return
+
+ level = self.user_permissions.team(self.team).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied("You need admin access to this project to modify conversion goals.")
+
+ def _locked_config(self) -> TeamMarketingAnalyticsConfig:
+ """Take a row lock so concurrent single-goal writes can't clobber each other."""
+ config = self.team.marketing_analytics_config
+ return TeamMarketingAnalyticsConfig.objects.select_for_update().get(pk=config.pk)
+
+ def _validated_goal(self, goal: dict, existing: list[Any], ignore_index: int | None = None) -> dict[str, Any]:
+ try:
+ validated = _CONVERSION_GOAL_ADAPTER.validate_python(goal)
+ except PydanticValidationError as e:
+ raise serializers.ValidationError({"goal": _readable_pydantic_errors(e, goal.get("kind"))})
+
+ name = goal.get("conversion_goal_name")
+ # Normalized, because names differing only in case collide as SQL column aliases.
+ # Storage keeps the name as sent.
+ normalized = _normalized_goal_name(name)
+ for index, other in enumerate(existing):
+ # A malformed sibling can't collide by name, and failing this write over a row it never
+ # touches is the trade `_store_goals` already refuses to make.
+ if not isinstance(other, dict):
+ continue
+ if index != ignore_index and _normalized_goal_name(other.get("conversion_goal_name")) == normalized:
+ raise serializers.ValidationError({"goal": f"A conversion goal named '{name}' already exists."})
+
+ stored = validated.model_dump(exclude_none=True, mode="json")
+ # `name` is optional on the schema but required by the legacy full-config PATCH the settings
+ # UI still sends, and the UI never exposes it, so a goal stored without one can't be repaired
+ # from the product. Mirrored rather than defaulted, or a rename leaves a stale `name`.
+ stored["name"] = stored["conversion_goal_name"]
+ return stored
+
+ def _merged_goal(self, stored: dict, patch: dict, conversion_goal_id: str) -> dict:
+ """Apply a partial goal onto the stored one, per the endpoint's documented merge semantics."""
+ if not isinstance(stored, dict):
+ # `_index_of` tolerates a non-dict row via `.get`, so don't blow up with a TypeError here.
+ raise serializers.ValidationError(
+ {"goal": "The stored conversion goal is malformed and cannot be updated."}
+ )
+
+ # The models are `extra="forbid"`, so a merge leaves old-kind keys behind and pydantic
+ # rejects a field the client never sent.
+ if patch.get("kind") not in (None, stored.get("kind")):
+ return {**patch, "conversion_goal_id": conversion_goal_id}
+
+ merged = {**stored, **patch, "conversion_goal_id": conversion_goal_id}
+ # No key on `schema_map` is required, so a top-level merge drops what the patch omits and the
+ # query runner then skips the goal with a warning — a successful write that stops reporting.
+ if isinstance(patch.get("schema_map"), dict) and isinstance(stored.get("schema_map"), dict):
+ merged["schema_map"] = {**stored["schema_map"], **patch["schema_map"]}
+ return merged
+
+ def _index_of(self, goals: list[dict], conversion_goal_id: str) -> int:
+ for index, goal in enumerate(goals):
+ if isinstance(goal, dict) and goal.get("conversion_goal_id") == conversion_goal_id:
+ return index
+ raise NotFound(f"No conversion goal with id '{conversion_goal_id}'.")
+
+ def _store_goals(self, config: TeamMarketingAnalyticsConfig, goals: list[dict], *, previous: list[dict]) -> None:
+ # Direct, not through the `conversion_goals` setter: it would re-run the older validator on
+ # every sibling goal and fail this write for a pre-existing row it never touched.
+ config._conversion_goals = goals
+ config.save()
+ # Same trail the settings path produces, so an MCP-driven edit still records who did what.
+ capture_team_config_diff(
+ self.team,
+ "marketing_analytics_config",
+ {"conversion_goals": previous},
+ {"conversion_goals": goals},
+ context=self.get_serializer_context(),
+ )
+
@validated_request(
query_serializer=DataSourcesQuerySerializer,
responses={
diff --git a/products/marketing_analytics/backend/test_api_conversion_goals.py b/products/marketing_analytics/backend/test_api_conversion_goals.py
new file mode 100644
index 000000000000..c2d6ea2b793b
--- /dev/null
+++ b/products/marketing_analytics/backend/test_api_conversion_goals.py
@@ -0,0 +1,358 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
+
+from ee.models.rbac.access_control import AccessControl
+
+SCHEMA_MAP = {"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"}
+
+
+def goal_payload(name: str, event: str = "sign_up", **extra) -> dict:
+ return {"kind": "EventsNode", "event": event, "conversion_goal_name": name, "schema_map": SCHEMA_MAP, **extra}
+
+
+class TestConversionGoalWrites(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.base_url = f"/api/projects/{self.team.pk}/marketing_analytics/conversion_goals"
+ # Writing goals needs the same project-admin level the settings PATCH path requires.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def create_goal(self, name: str, **extra):
+ return self.client.post(f"{self.base_url}/create", {"goal": goal_payload(name, **extra)}, format="json")
+
+ def stored_goals(self) -> list[dict]:
+ return TeamMarketingAnalyticsConfig.objects.get(team=self.team).conversion_goals
+
+ def test_create_appends_without_touching_existing_goals(self):
+ first = self.create_goal("Sign ups").json()["goal"]
+ response = self.create_goal("Purchases", event="purchase")
+
+ assert response.status_code == 201, response.json()
+ goals = self.stored_goals()
+ assert [g["conversion_goal_name"] for g in goals] == ["Sign ups", "Purchases"]
+ assert goals[0]["conversion_goal_id"] == first["conversion_goal_id"]
+
+ def test_create_assigns_a_server_side_id_and_ignores_a_client_supplied_one(self):
+ response = self.create_goal("Sign ups", conversion_goal_id="pick-me")
+
+ assert response.json()["goal"]["conversion_goal_id"] != "pick-me"
+
+ def test_update_merges_fields_and_keeps_position_and_siblings(self):
+ first = self.create_goal("Sign ups").json()["goal"]
+ self.create_goal("Purchases", event="purchase")
+
+ response = self.client.patch(
+ f"{self.base_url}/{first['conversion_goal_id']}/update",
+ {"goal": {"kind": "EventsNode", "counts_as_customer": True}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ goals = self.stored_goals()
+ assert [g["conversion_goal_name"] for g in goals] == ["Sign ups", "Purchases"]
+ assert goals[0]["counts_as_customer"] is True
+ assert goals[0]["event"] == "sign_up"
+
+ def test_update_does_not_report_the_goal_as_a_duplicate_of_itself(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ response = self.client.patch(
+ f"{self.base_url}/{goal['conversion_goal_id']}/update",
+ {"goal": {"kind": "EventsNode", "conversion_goal_name": "Sign ups", "counts_as_revenue": False}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+
+ def test_delete_removes_only_the_requested_goal(self):
+ first = self.create_goal("Sign ups").json()["goal"]
+ self.create_goal("Purchases", event="purchase")
+
+ response = self.client.delete(f"{self.base_url}/{first['conversion_goal_id']}/delete")
+
+ assert response.status_code == 200, response.json()
+ assert [g["conversion_goal_name"] for g in self.stored_goals()] == ["Purchases"]
+
+ @parameterized.expand([("update", "patch"), ("delete", "delete")])
+ def test_unknown_goal_id_is_a_404(self, action: str, method: str):
+ response = getattr(self.client, method)(f"{self.base_url}/nope/{action}", {"goal": {}}, format="json")
+
+ assert response.status_code == 404, response.json()
+
+ def test_member_without_project_admin_access_cannot_write_goals(self):
+ existing = self.create_goal("Sign ups").json()["goal"]
+
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=self.team.id, access_level="member"
+ )
+
+ create = self.create_goal("Purchases", event="purchase")
+ update = self.client.patch(
+ f"{self.base_url}/{existing['conversion_goal_id']}/update",
+ {"goal": {"kind": "EventsNode", "counts_as_customer": True}},
+ format="json",
+ )
+ delete = self.client.delete(f"{self.base_url}/{existing['conversion_goal_id']}/delete")
+
+ assert (create.status_code, update.status_code, delete.status_code) == (403, 403, 403)
+ assert [g["conversion_goal_name"] for g in self.stored_goals()] == ["Sign ups"]
+ # reads stay open to every member
+ assert self.client.get(self.base_url).status_code == 200
+
+ @parameterized.expand(
+ [
+ ("missing_schema_map", {"kind": "EventsNode", "event": "sign_up", "conversion_goal_name": "x"}),
+ ("unknown_kind", {"kind": "NotANode", "conversion_goal_name": "x", "schema_map": SCHEMA_MAP}),
+ ("schema_map_not_an_object", {"kind": "EventsNode", "conversion_goal_name": "x", "schema_map": "utm"}),
+ (
+ "wrong_field_type",
+ {
+ "kind": "EventsNode",
+ "conversion_goal_name": "x",
+ "schema_map": SCHEMA_MAP,
+ "counts_as_customer": "maybe",
+ },
+ ),
+ (
+ "data_warehouse_node_without_table",
+ {"kind": "DataWarehouseNode", "id": "x", "conversion_goal_name": "x", "schema_map": SCHEMA_MAP},
+ ),
+ ("goal_is_a_string", "sign_up"),
+ ("goal_is_a_list", [{"kind": "EventsNode", "conversion_goal_name": "x", "schema_map": SCHEMA_MAP}]),
+ ]
+ )
+ def test_malformed_goal_is_rejected(self, _name: str, goal: object):
+ response = self.client.post(f"{self.base_url}/create", {"goal": goal}, format="json")
+
+ assert response.status_code == 400, response.json()
+ assert self.stored_goals() == []
+
+ def test_duplicate_name_is_rejected(self):
+ self.create_goal("Sign ups")
+
+ response = self.create_goal("Sign ups", event="signed_up")
+
+ assert response.status_code == 400, response.json()
+ assert len(self.stored_goals()) == 1
+
+ def test_a_malformed_stored_goal_does_not_block_writing_a_new_one(self):
+ config = TeamMarketingAnalyticsConfig.objects.get(team=self.team)
+ config._conversion_goals = ["not-a-goal"]
+ config.save()
+
+ response = self.create_goal("Sign ups")
+
+ assert response.status_code == 201, response.json()
+ assert [g["conversion_goal_name"] for g in self.stored_goals() if isinstance(g, dict)] == ["Sign ups"]
+
+ @parameterized.expand([("trailing_space", "Sign ups "), ("different_case", "SIGN UPS")])
+ def test_duplicate_name_is_rejected_ignoring_case_and_padding(self, _name: str, duplicate: str):
+ # Goal names become SQL column aliases downstream, where these collide.
+ self.create_goal("Sign ups")
+
+ response = self.create_goal(duplicate, event="signed_up")
+
+ assert response.status_code == 400, response.json()
+ assert len(self.stored_goals()) == 1
+
+ # --- the legacy full-config path ---
+ #
+ # The settings UI saves by PATCHing the whole marketing_analytics_config, which runs
+ # `validate_conversion_goals`. That validator requires a top-level `name` the goal schema treats
+ # as optional, so a goal written here without one makes every later UI save fail — and the UI
+ # never exposes `name`, so there is no way to repair it from the product.
+
+ def test_written_goals_carry_the_name_the_legacy_validator_requires(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ assert goal["name"] == "Sign ups"
+ assert self.stored_goals()[0]["name"] == "Sign ups"
+
+ def test_renaming_keeps_the_legacy_name_in_step(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ self.client.patch(
+ f"{self.base_url}/{goal['conversion_goal_id']}/update",
+ {"goal": {"conversion_goal_name": "Registrations"}},
+ format="json",
+ )
+
+ stored = self.stored_goals()[0]
+ assert (stored["conversion_goal_name"], stored["name"]) == ("Registrations", "Registrations")
+
+ def test_goals_written_here_round_trip_through_the_settings_save(self):
+ self.create_goal("Sign ups")
+ self.create_goal("Purchases", event="purchase")
+
+ # Exactly what marketingAnalyticsSettingsLogic sends on any settings change: the whole config.
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/",
+ {"marketing_analytics_config": {"conversion_goals": self.stored_goals()}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ assert [g["conversion_goal_name"] for g in self.stored_goals()] == ["Sign ups", "Purchases"]
+
+ # --- merge semantics ---
+
+ def test_update_merges_schema_map_key_by_key(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ response = self.client.patch(
+ f"{self.base_url}/{goal['conversion_goal_id']}/update",
+ {"goal": {"schema_map": {"utm_source_name": "source"}}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ # Dropping utm_campaign_name here would leave the goal silently unreported: the query runner
+ # falls back to a default column name and skips the goal with only a log warning.
+ assert self.stored_goals()[0]["schema_map"] == {
+ "utm_campaign_name": "utm_campaign",
+ "utm_source_name": "source",
+ }
+
+ def test_update_can_change_a_goals_kind_by_replacing_it(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ response = self.client.patch(
+ f"{self.base_url}/{goal['conversion_goal_id']}/update",
+ {
+ "goal": {
+ "kind": "ActionsNode",
+ "id": "7",
+ "conversion_goal_name": "Sign ups",
+ "schema_map": SCHEMA_MAP,
+ }
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ stored = self.stored_goals()[0]
+ # Merging would have carried `event` over, which ActionsNode forbids — a 400 about a field
+ # the client never sent.
+ assert stored["kind"] == "ActionsNode"
+ assert "event" not in stored
+ assert stored["conversion_goal_id"] == goal["conversion_goal_id"]
+
+ def test_error_message_describes_the_shape_that_was_sent(self):
+ response = self.client.post(
+ f"{self.base_url}/create",
+ {"goal": {"kind": "DataWarehouseNode", "conversion_goal_name": "x", "schema_map": SCHEMA_MAP}},
+ format="json",
+ )
+
+ assert response.status_code == 400, response.json()
+ # Only the first message survives the exception handler, so it has to be the useful one: a
+ # field the data warehouse shape actually needs, not the events node's objection to a `kind`
+ # the client set deliberately.
+ detail = response.json()["detail"]
+ assert "'EventsNode'" not in detail, detail
+ assert detail.split(":")[0] in {"id", "id_field", "distinct_id_field", "table_name", "timestamp_field"}, detail
+
+ @parameterized.expand([("omitted", {}), ("null", {"goal": None})])
+ def test_goal_is_required_on_update(self, _name: str, body: dict):
+ goal = self.create_goal("Sign ups").json()["goal"]
+
+ response = self.client.patch(f"{self.base_url}/{goal['conversion_goal_id']}/update", body, format="json")
+
+ assert response.status_code == 400, response.json()
+ assert self.stored_goals()[0]["conversion_goal_name"] == "Sign ups"
+
+ @parameterized.expand([("update", "patch"), ("delete", "delete")])
+ def test_a_rejected_write_leaves_the_stored_goals_untouched(self, action: str, method: str):
+ first = self.create_goal("Sign ups").json()["goal"]
+ self.create_goal("Purchases", event="purchase")
+ before = self.stored_goals()
+
+ if action == "update":
+ # A merge that can't validate: counts_as_customer is a bool.
+ response = self.client.patch(
+ f"{self.base_url}/{first['conversion_goal_id']}/update",
+ {"goal": {"counts_as_customer": "maybe"}},
+ format="json",
+ )
+ assert response.status_code == 400, response.json()
+ else:
+ response = self.client.delete(f"{self.base_url}/does-not-exist/delete")
+ assert response.status_code == 404, response.json()
+
+ assert self.stored_goals() == before
+
+ def test_another_teams_goals_are_not_reachable(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+
+ other_url = f"/api/projects/{other_team.pk}/marketing_analytics/conversion_goals"
+ update = self.client.patch(
+ f"{other_url}/{goal['conversion_goal_id']}/update",
+ {"goal": {"counts_as_customer": True}},
+ format="json",
+ )
+ delete = self.client.delete(f"{other_url}/{goal['conversion_goal_id']}/delete")
+
+ # The id belongs to this team's config, so the other project simply has no such goal.
+ assert (update.status_code, delete.status_code) == (404, 404)
+ assert "counts_as_customer" not in self.stored_goals()[0]
+
+ def test_plain_member_cannot_write_goals_without_access_controls(self):
+ """The endpoint must not be a way around the bar the settings page enforces.
+
+ `marketing_analytics_config` sits in TEAM_CONFIG_ADMIN_FIELDS_SET, so the settings PATCH
+ demands ADMIN. The RBAC check alone doesn't reproduce that: without the ACCESS_CONTROL
+ feature it resolves permissively, and a plain member could edit goals here that the same
+ member is refused on the settings page.
+ """
+ existing = self.create_goal("Sign ups").json()["goal"]
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ create = self.create_goal("Purchases", event="purchase")
+ update = self.client.patch(
+ f"{self.base_url}/{existing['conversion_goal_id']}/update",
+ {"goal": {"counts_as_customer": True}},
+ format="json",
+ )
+ delete = self.client.delete(f"{self.base_url}/{existing['conversion_goal_id']}/delete")
+ # Same user, same payload, through the settings page the UI actually uses.
+ legacy = self.client.patch(
+ f"/api/projects/{self.team.pk}/",
+ {"marketing_analytics_config": {"conversion_goals": []}},
+ format="json",
+ )
+
+ assert (create.status_code, update.status_code, delete.status_code) == (403, 403, 403)
+ assert legacy.status_code == 403, legacy.json()
+ assert [g["conversion_goal_name"] for g in self.stored_goals()] == ["Sign ups"]
+ assert self.client.get(self.base_url).status_code == 200
+
+ def test_writes_leave_an_activity_log_trail(self):
+ goal = self.create_goal("Sign ups").json()["goal"]
+ self.client.patch(
+ f"{self.base_url}/{goal['conversion_goal_id']}/update",
+ {"goal": {"counts_as_customer": True}},
+ format="json",
+ )
+ self.client.delete(f"{self.base_url}/{goal['conversion_goal_id']}/delete")
+
+ # Without this, a goal changed by a person — or increasingly by an agent over MCP — leaves
+ # no record of who changed what.
+ entries = ActivityLog.objects.filter(team_id=self.team.pk, scope="Team", activity="updated")
+ assert entries.count() == 3
+ assert {entry.user_id for entry in entries} == {self.user.pk}
diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index 289dcecc3e98..a87e292b0c84 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -87,6 +87,1129 @@ export interface ConversionGoalsListResponseApi {
has_misconfigured: boolean
}
+export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]
+
+export const PropertyOperatorApi = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ StartsWith: 'starts_with',
+ NotStartsWith: 'not_starts_with',
+ EndsWith: 'ends_with',
+ NotEndsWith: 'not_ends_with',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+ Gt: 'gt',
+ Gte: 'gte',
+ Lt: 'lt',
+ Lte: 'lte',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ IsDateExact: 'is_date_exact',
+ IsDateBefore: 'is_date_before',
+ IsDateAfter: 'is_date_after',
+ Between: 'between',
+ NotBetween: 'not_between',
+ Min: 'min',
+ Max: 'max',
+ In: 'in',
+ NotIn: 'not_in',
+ IsCleanedPathExact: 'is_cleaned_path_exact',
+ FlagEvaluatesTo: 'flag_evaluates_to',
+ SemverEq: 'semver_eq',
+ SemverNeq: 'semver_neq',
+ SemverGt: 'semver_gt',
+ SemverGte: 'semver_gte',
+ SemverLt: 'semver_lt',
+ SemverLte: 'semver_lte',
+ SemverTilde: 'semver_tilde',
+ SemverCaret: 'semver_caret',
+ SemverWildcard: 'semver_wildcard',
+ IcontainsMulti: 'icontains_multi',
+ NotIcontainsMulti: 'not_icontains_multi',
+} as const
+
+export interface EventPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator?: PropertyOperatorApi | null
+ /** Event properties */
+ type?: 'event'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface PersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Person properties */
+ type?: 'person'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface PersonMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
+ type?: 'person_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
+
+export const Key10Api = {
+ TagName: 'tag_name',
+ Text: 'text',
+ Href: 'href',
+ Selector: 'selector',
+} as const
+
+export interface ElementPropertyFilterApi {
+ key: Key10Api
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'element'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface EventMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'event_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface SessionPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'session'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface CohortPropertyFilterApi {
+ cohort_name?: string | null
+ key?: 'id'
+ label?: string | null
+ operator?: PropertyOperatorApi | null
+ type?: 'cohort'
+ value: number
+}
+
+export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
+
+export const DurationTypeApi = {
+ Duration: 'duration',
+ ActiveSeconds: 'active_seconds',
+ InactiveSeconds: 'inactive_seconds',
+} as const
+
+export interface RecordingPropertyFilterApi {
+ key: DurationTypeApi | string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'recording'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface LogEntryPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'log_entry'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
+
+export interface GroupPropertyFilterApi {
+ group_key_names?: GroupPropertyFilterApiGroupKeyNames
+ group_type_index?: number | null
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'group'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface FeaturePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Event property with "$feature/" prepended */
+ type?: 'feature'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface FlagPropertyFilterApi {
+ /** The key should be the flag ID */
+ key: string
+ label?: string | null
+ /** Only flag_evaluates_to operator is allowed for flag dependencies */
+ operator?: 'flag_evaluates_to'
+ /** Feature flag dependency */
+ type?: 'flag'
+ /** The value can be true, false, or a variant name */
+ value: boolean | string
+}
+
+export interface HogQLPropertyFilterApi {
+ key: string
+ label?: string | null
+ type?: 'hogql'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export const EmptyPropertyFilterApiValue = {
+ type: 'empty',
+} as const
+export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
+
+export interface DataWarehousePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface DataWarehousePersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse_person_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface ErrorTrackingIssueFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'error_tracking_issue'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
+
+export const LogPropertyFilterTypeApi = {
+ Log: 'log',
+ LogAttribute: 'log_attribute',
+ LogResourceAttribute: 'log_resource_attribute',
+} as const
+
+export interface LogPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: LogPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface MetricPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'metric_attribute'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
+
+export const SpanPropertyFilterTypeApi = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
+} as const
+
+export interface SpanPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: SpanPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface RevenueAnalyticsPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'revenue_analytics'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface AccountCustomPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Customer analytics account custom property — the key is the property definition id */
+ type?: 'account_custom_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface WorkflowVariablePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'workflow_variable'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type BaseMathTypeApi = (typeof BaseMathTypeApi)[keyof typeof BaseMathTypeApi]
+
+export const BaseMathTypeApi = {
+ Total: 'total',
+ Dau: 'dau',
+ WeeklyActive: 'weekly_active',
+ MonthlyActive: 'monthly_active',
+ UniqueSession: 'unique_session',
+ FirstTimeForUser: 'first_time_for_user',
+ FirstMatchingEventForUser: 'first_matching_event_for_user',
+} as const
+
+export type FunnelMathTypeApi = (typeof FunnelMathTypeApi)[keyof typeof FunnelMathTypeApi]
+
+export const FunnelMathTypeApi = {
+ Total: 'total',
+ FirstTimeForUser: 'first_time_for_user',
+ FirstTimeForUserWithFilters: 'first_time_for_user_with_filters',
+} as const
+
+export type PropertyMathTypeApi = (typeof PropertyMathTypeApi)[keyof typeof PropertyMathTypeApi]
+
+export const PropertyMathTypeApi = {
+ Avg: 'avg',
+ Sum: 'sum',
+ Min: 'min',
+ Max: 'max',
+ Median: 'median',
+ P75: 'p75',
+ P90: 'p90',
+ P95: 'p95',
+ P99: 'p99',
+} as const
+
+export type CountPerActorMathTypeApi = (typeof CountPerActorMathTypeApi)[keyof typeof CountPerActorMathTypeApi]
+
+export const CountPerActorMathTypeApi = {
+ AvgCountPerActor: 'avg_count_per_actor',
+ MinCountPerActor: 'min_count_per_actor',
+ MaxCountPerActor: 'max_count_per_actor',
+ MedianCountPerActor: 'median_count_per_actor',
+ P75CountPerActor: 'p75_count_per_actor',
+ P90CountPerActor: 'p90_count_per_actor',
+ P95CountPerActor: 'p95_count_per_actor',
+ P99CountPerActor: 'p99_count_per_actor',
+} as const
+
+export type ExperimentMetricMathTypeApi = (typeof ExperimentMetricMathTypeApi)[keyof typeof ExperimentMetricMathTypeApi]
+
+export const ExperimentMetricMathTypeApi = {
+ Total: 'total',
+ Sum: 'sum',
+ UniqueSession: 'unique_session',
+ Min: 'min',
+ Max: 'max',
+ Avg: 'avg',
+ Dau: 'dau',
+ UniqueGroup: 'unique_group',
+ Hogql: 'hogql',
+} as const
+
+export type CalendarHeatmapMathTypeApi = (typeof CalendarHeatmapMathTypeApi)[keyof typeof CalendarHeatmapMathTypeApi]
+
+export const CalendarHeatmapMathTypeApi = {
+ Total: 'total',
+ Dau: 'dau',
+} as const
+
+export type MathGroupTypeIndexApi = (typeof MathGroupTypeIndexApi)[keyof typeof MathGroupTypeIndexApi]
+
+export const MathGroupTypeIndexApi = {
+ Number0: 0,
+ Number1: 1,
+ Number2: 2,
+ Number3: 3,
+ Number4: 4,
+} as const
+
+export type CurrencyCodeApi = (typeof CurrencyCodeApi)[keyof typeof CurrencyCodeApi]
+
+export const CurrencyCodeApi = {
+ Aed: 'AED',
+ Afn: 'AFN',
+ All: 'ALL',
+ Amd: 'AMD',
+ Ang: 'ANG',
+ Aoa: 'AOA',
+ Ars: 'ARS',
+ Aud: 'AUD',
+ Awg: 'AWG',
+ Azn: 'AZN',
+ Bam: 'BAM',
+ Bbd: 'BBD',
+ Bdt: 'BDT',
+ Bgn: 'BGN',
+ Bhd: 'BHD',
+ Bif: 'BIF',
+ Bmd: 'BMD',
+ Bnd: 'BND',
+ Bob: 'BOB',
+ Brl: 'BRL',
+ Bsd: 'BSD',
+ Btc: 'BTC',
+ Btn: 'BTN',
+ Bwp: 'BWP',
+ Byn: 'BYN',
+ Bzd: 'BZD',
+ Cad: 'CAD',
+ Cdf: 'CDF',
+ Chf: 'CHF',
+ Clp: 'CLP',
+ Cny: 'CNY',
+ Cop: 'COP',
+ Crc: 'CRC',
+ Cve: 'CVE',
+ Czk: 'CZK',
+ Djf: 'DJF',
+ Dkk: 'DKK',
+ Dop: 'DOP',
+ Dzd: 'DZD',
+ Egp: 'EGP',
+ Ern: 'ERN',
+ Etb: 'ETB',
+ Eur: 'EUR',
+ Fjd: 'FJD',
+ Gbp: 'GBP',
+ Gel: 'GEL',
+ Ghs: 'GHS',
+ Gip: 'GIP',
+ Gmd: 'GMD',
+ Gnf: 'GNF',
+ Gtq: 'GTQ',
+ Gyd: 'GYD',
+ Hkd: 'HKD',
+ Hnl: 'HNL',
+ Hrk: 'HRK',
+ Htg: 'HTG',
+ Huf: 'HUF',
+ Idr: 'IDR',
+ Ils: 'ILS',
+ Inr: 'INR',
+ Iqd: 'IQD',
+ Irr: 'IRR',
+ Isk: 'ISK',
+ Jmd: 'JMD',
+ Jod: 'JOD',
+ Jpy: 'JPY',
+ Kes: 'KES',
+ Kgs: 'KGS',
+ Khr: 'KHR',
+ Kmf: 'KMF',
+ Krw: 'KRW',
+ Kwd: 'KWD',
+ Kyd: 'KYD',
+ Kzt: 'KZT',
+ Lak: 'LAK',
+ Lbp: 'LBP',
+ Lkr: 'LKR',
+ Lrd: 'LRD',
+ Ltl: 'LTL',
+ Lvl: 'LVL',
+ Lsl: 'LSL',
+ Lyd: 'LYD',
+ Mad: 'MAD',
+ Mdl: 'MDL',
+ Mga: 'MGA',
+ Mkd: 'MKD',
+ Mmk: 'MMK',
+ Mnt: 'MNT',
+ Mop: 'MOP',
+ Mru: 'MRU',
+ Mtl: 'MTL',
+ Mur: 'MUR',
+ Mvr: 'MVR',
+ Mwk: 'MWK',
+ Mxn: 'MXN',
+ Myr: 'MYR',
+ Mzn: 'MZN',
+ Nad: 'NAD',
+ Ngn: 'NGN',
+ Nio: 'NIO',
+ Nok: 'NOK',
+ Npr: 'NPR',
+ Nzd: 'NZD',
+ Omr: 'OMR',
+ Pab: 'PAB',
+ Pen: 'PEN',
+ Pgk: 'PGK',
+ Php: 'PHP',
+ Pkr: 'PKR',
+ Pln: 'PLN',
+ Pyg: 'PYG',
+ Qar: 'QAR',
+ Ron: 'RON',
+ Rsd: 'RSD',
+ Rub: 'RUB',
+ Rwf: 'RWF',
+ Sar: 'SAR',
+ Sbd: 'SBD',
+ Scr: 'SCR',
+ Sdg: 'SDG',
+ Sek: 'SEK',
+ Sgd: 'SGD',
+ Srd: 'SRD',
+ Ssp: 'SSP',
+ Stn: 'STN',
+ Syp: 'SYP',
+ Szl: 'SZL',
+ Thb: 'THB',
+ Tjs: 'TJS',
+ Tmt: 'TMT',
+ Tnd: 'TND',
+ Top: 'TOP',
+ Try: 'TRY',
+ Ttd: 'TTD',
+ Twd: 'TWD',
+ Tzs: 'TZS',
+ Uah: 'UAH',
+ Ugx: 'UGX',
+ Usd: 'USD',
+ Uyu: 'UYU',
+ Uzs: 'UZS',
+ Ves: 'VES',
+ Vnd: 'VND',
+ Vuv: 'VUV',
+ Wst: 'WST',
+ Xaf: 'XAF',
+ Xcd: 'XCD',
+ Xof: 'XOF',
+ Xpf: 'XPF',
+ Yer: 'YER',
+ Zar: 'ZAR',
+ Zmw: 'ZMW',
+} as const
+
+export interface RevenueCurrencyPropertyConfigApi {
+ property?: string | null
+ static?: CurrencyCodeApi | null
+}
+
+export type ConversionGoalFilter1ApiResponse = { [key: string]: unknown } | null
+
+export type ConversionGoalFilter1ApiSchemaMap = { [key: string]: string | unknown }
+
+export interface ConversionGoalFilter1Api {
+ conversion_goal_id: string
+ conversion_goal_name: string
+ /** Marks this goal as customer-defining: a conversion here means the person became a customer (e.g. a payment or subscription), not an intermediate step like a sign up. It gates customer-based metrics such as CAC and LTV:CAC, whose denominator is new customers (counted once per person via first_time_for_user) rather than every conversion. Defaults to false. */
+ counts_as_customer?: boolean | null
+ /** Marks this goal as revenue-bearing: the value of a conversion is a monetary amount, not a count or an arbitrary numeric property. It gates revenue metrics such as ROAS and LTV:CAC. The amount itself comes from math_property, and its currency from math_property_revenue_currency, the same shape Revenue analytics uses for revenue events. Independent of counts_as_customer: a purchase is usually both, a trial signup neither. Defaults to false. */
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ /** The event or `null` for all events. */
+ event?: string | null
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ kind?: 'EventsNode'
+ limit?: number | null
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ /** Columns to order by */
+ orderBy?: string[] | null
+ /** Properties configurable in the interface */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: ConversionGoalFilter1ApiResponse
+ schema_map: ConversionGoalFilter1ApiSchemaMap
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
+export type ConversionGoalFilter2ApiResponse = { [key: string]: unknown } | null
+
+export type ConversionGoalFilter2ApiSchemaMap = { [key: string]: string | unknown }
+
+export interface ConversionGoalFilter2Api {
+ conversion_goal_id: string
+ conversion_goal_name: string
+ /** Marks this goal as customer-defining: a conversion here means the person became a customer (e.g. a payment or subscription), not an intermediate step like a sign up. It gates customer-based metrics such as CAC and LTV:CAC, whose denominator is new customers (counted once per person via first_time_for_user) rather than every conversion. Defaults to false. */
+ counts_as_customer?: boolean | null
+ /** Marks this goal as revenue-bearing: the value of a conversion is a monetary amount, not a count or an arbitrary numeric property. It gates revenue metrics such as ROAS and LTV:CAC. The amount itself comes from math_property, and its currency from math_property_revenue_currency, the same shape Revenue analytics uses for revenue events. Independent of counts_as_customer: a purchase is usually both, a trial signup neither. Defaults to false. */
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ id: number
+ kind?: 'ActionsNode'
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ /** Properties configurable in the interface */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: ConversionGoalFilter2ApiResponse
+ schema_map: ConversionGoalFilter2ApiSchemaMap
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
+export type ConversionGoalFilter3ApiResponse = { [key: string]: unknown } | null
+
+export type ConversionGoalFilter3ApiSchemaMap = { [key: string]: string | unknown }
+
+export interface ConversionGoalFilter3Api {
+ conversion_goal_id: string
+ conversion_goal_name: string
+ /** Marks this goal as customer-defining: a conversion here means the person became a customer (e.g. a payment or subscription), not an intermediate step like a sign up. It gates customer-based metrics such as CAC and LTV:CAC, whose denominator is new customers (counted once per person via first_time_for_user) rather than every conversion. Defaults to false. */
+ counts_as_customer?: boolean | null
+ /** Marks this goal as revenue-bearing: the value of a conversion is a monetary amount, not a count or an arbitrary numeric property. It gates revenue metrics such as ROAS and LTV:CAC. The amount itself comes from math_property, and its currency from math_property_revenue_currency, the same shape Revenue analytics uses for revenue events. Independent of counts_as_customer: a purchase is usually both, a trial signup neither. Defaults to false. */
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ distinct_id_field: string
+ dw_source_type?: string | null
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ id: string
+ id_field: string
+ kind?: 'DataWarehouseNode'
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ /** Properties configurable in the interface */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: ConversionGoalFilter3ApiResponse
+ schema_map: ConversionGoalFilter3ApiSchemaMap
+ table_name: string
+ timestamp_field: string
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
+/**
+ * Wrapper for OpenAPI schema generation - one goal, in any of the three node shapes.
+ */
+export type ConversionGoalApi = ConversionGoalFilter1Api | ConversionGoalFilter2Api | ConversionGoalFilter3Api
+
+/**
+ * List wrapper for OpenAPI schema generation - the response carries every configured goal.
+ */
+export type ConversionGoalWrittenListApi = (
+ | ConversionGoalFilter1Api
+ | ConversionGoalFilter2Api
+ | ConversionGoalFilter3Api
+)[]
+
+export interface ConversionGoalWriteResponseApi {
+ /** The goal as stored after the write */
+ goal: ConversionGoalApi
+ /** Every configured goal after the write, in display order */
+ conversion_goals: ConversionGoalWrittenListApi
+}
+
+export type PartialConversionGoalFilter1ApiResponse = { [key: string]: unknown } | null
+
+export type PartialConversionGoalFilter1ApiSchemaMap = { [key: string]: string | unknown } | null
+
+/**
+ * ConversionGoalFilter1 with every field optional - the fields you send are merged into the stored goal.
+ */
+export interface PartialConversionGoalFilter1Api {
+ conversion_goal_id?: string | null
+ conversion_goal_name?: string | null
+ counts_as_customer?: boolean | null
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ event?: string | null
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ kind?: 'EventsNode' | null
+ limit?: number | null
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ orderBy?: string[] | null
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: PartialConversionGoalFilter1ApiResponse
+ schema_map?: PartialConversionGoalFilter1ApiSchemaMap
+ version?: number | null
+}
+
+export type PartialConversionGoalFilter2ApiResponse = { [key: string]: unknown } | null
+
+export type PartialConversionGoalFilter2ApiSchemaMap = { [key: string]: string | unknown } | null
+
+/**
+ * ConversionGoalFilter2 with every field optional - the fields you send are merged into the stored goal.
+ */
+export interface PartialConversionGoalFilter2Api {
+ conversion_goal_id?: string | null
+ conversion_goal_name?: string | null
+ counts_as_customer?: boolean | null
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ id?: number | null
+ kind?: 'ActionsNode' | null
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: PartialConversionGoalFilter2ApiResponse
+ schema_map?: PartialConversionGoalFilter2ApiSchemaMap
+ version?: number | null
+}
+
+export type PartialConversionGoalFilter3ApiResponse = { [key: string]: unknown } | null
+
+export type PartialConversionGoalFilter3ApiSchemaMap = { [key: string]: string | unknown } | null
+
+/**
+ * ConversionGoalFilter3 with every field optional - the fields you send are merged into the stored goal.
+ */
+export interface PartialConversionGoalFilter3Api {
+ conversion_goal_id?: string | null
+ conversion_goal_name?: string | null
+ counts_as_customer?: boolean | null
+ counts_as_revenue?: boolean | null
+ custom_name?: string | null
+ distinct_id_field?: string | null
+ dw_source_type?: string | null
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ id?: string | null
+ id_field?: string | null
+ kind?: 'DataWarehouseNode' | null
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'unique_group'
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | null
+ response?: PartialConversionGoalFilter3ApiResponse
+ schema_map?: PartialConversionGoalFilter3ApiSchemaMap
+ table_name?: string | null
+ timestamp_field?: string | null
+ version?: number | null
+}
+
+export type ConversionGoalPatchApi =
+ | PartialConversionGoalFilter1Api
+ | PartialConversionGoalFilter2Api
+ | PartialConversionGoalFilter3Api
+
+/**
+ * Separate from create: the body is a patch, so the documented partial has to type-check.
+ */
+export interface PatchedConversionGoalUpdateApi {
+ /** The fields to change, merged into the stored goal — anything you leave out is kept, and the goal keeps its position in the list. schema_map is merged key by key. The merged result must still match one of the ConversionGoalFilter shapes. Send `kind` only to change the goal's shape, in which case the goal is replaced rather than merged and the whole new shape is required. conversion_goal_id comes from the URL and any value sent is ignored. */
+ goal?: ConversionGoalPatchApi
+}
+
+export interface ConversionGoalWriteApi {
+ /** The conversion goal. Must match one of the ConversionGoalFilter shapes: an events node, an actions node or a data warehouse node. conversion_goal_id is assigned by the server and any value sent is ignored. */
+ goal: ConversionGoalApi
+}
+
export interface RequiredTableStatusApi {
/** Name of the required source table (e.g. 'campaign', 'campaign_stats') */
table_name: string
diff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.ts
index 691eae373499..79604d203306 100644
--- a/products/marketing_analytics/frontend/generated/api.ts
+++ b/products/marketing_analytics/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ ConversionGoalWriteApi,
+ ConversionGoalWriteResponseApi,
ConversionGoalsListResponseApi,
DataSourceHealthResponseApi,
EventSuggestionsResponseApi,
@@ -20,6 +22,7 @@ import type {
MarketingAnalyticsSuggestUtmMappingsRetrieveParams,
MarketingAnalyticsUtmAuditRetrieveParams,
MarketingDiagnosticResponseApi,
+ PatchedConversionGoalUpdateApi,
UtmAuditResponseApi,
UtmMappingSuggestionsResponseApi,
} from './api.schemas'
@@ -42,6 +45,77 @@ export const marketingAnalyticsConversionGoalsRetrieve = async (
})
}
+export const getMarketingAnalyticsConversionGoalsDeleteDestroyUrl = (projectId: string, conversionGoalId: string) => {
+ return `/api/projects/${projectId}/marketing_analytics/conversion_goals/${conversionGoalId}/delete/`
+}
+
+/**
+ * Remove one conversion goal from the project, leaving the others in place.
+ * @summary Delete conversion goal
+ */
+export const marketingAnalyticsConversionGoalsDeleteDestroy = async (
+ projectId: string,
+ conversionGoalId: string,
+ options?: RequestInit
+): Promise<ConversionGoalWriteResponseApi> => {
+ return apiMutator<ConversionGoalWriteResponseApi>(
+ getMarketingAnalyticsConversionGoalsDeleteDestroyUrl(projectId, conversionGoalId),
+ {
+ ...options,
+ method: 'DELETE',
+ }
+ )
+}
+
+export const getMarketingAnalyticsConversionGoalsUpdatePartialUpdateUrl = (
+ projectId: string,
+ conversionGoalId: string
+) => {
+ return `/api/projects/${projectId}/marketing_analytics/conversion_goals/${conversionGoalId}/update/`
+}
+
+/**
+ * Change one conversion goal in place. Fields you send are merged into the stored goal, the rest are kept, and the goal keeps its position in the list. Sending a different `kind` replaces the goal instead, since the shapes don't share their fields.
+ * @summary Update conversion goal
+ */
+export const marketingAnalyticsConversionGoalsUpdatePartialUpdate = async (
+ projectId: string,
+ conversionGoalId: string,
+ patchedConversionGoalUpdateApi?: PatchedConversionGoalUpdateApi,
+ options?: RequestInit
+): Promise<ConversionGoalWriteResponseApi> => {
+ return apiMutator<ConversionGoalWriteResponseApi>(
+ getMarketingAnalyticsConversionGoalsUpdatePartialUpdateUrl(projectId, conversionGoalId),
+ {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedConversionGoalUpdateApi),
+ }
+ )
+}
+
+export const getMarketingAnalyticsConversionGoalsCreateCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/marketing_analytics/conversion_goals/create/`
+}
+
+/**
+ * Add one conversion goal to the project. The server assigns conversion_goal_id and appends the goal to the end of the list, leaving existing goals untouched.
+ * @summary Create conversion goal
+ */
+export const marketingAnalyticsConversionGoalsCreateCreate = async (
+ projectId: string,
+ conversionGoalWriteApi: ConversionGoalWriteApi,
+ options?: RequestInit
+): Promise<ConversionGoalWriteResponseApi> => {
+ return apiMutator<ConversionGoalWriteResponseApi>(getMarketingAnalyticsConversionGoalsCreateCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(conversionGoalWriteApi),
+ })
+}
+
export const getMarketingAnalyticsDataSourcesRetrieveUrl = (
projectId: string,
params?: MarketingAnalyticsDataSourcesRetrieveParams
diff --git a/products/marketing_analytics/frontend/generated/api.zod.ts b/products/marketing_analytics/frontend/generated/api.zod.ts
index e8a15d4e1b52..d396a4507993 100644
--- a/products/marketing_analytics/frontend/generated/api.zod.ts
+++ b/products/marketing_analytics/frontend/generated/api.zod.ts
@@ -7,3 +7,20 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+import * as zod from 'zod'
+
+/**
+ * Change one conversion goal in place. Fields you send are merged into the stored goal, the rest are kept, and the goal keeps its position in the list. Sending a different `kind` replaces the goal instead, since the shapes don't share their fields.
+ * @summary Update conversion goal
+ */
+export const MarketingAnalyticsConversionGoalsUpdatePartialUpdateBody = /* @__PURE__ */ zod
+ .record(zod.string(), zod.unknown())
+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+
+/**
+ * Add one conversion goal to the project. The server assigns conversion_goal_id and appends the goal to the end of the list, leaving existing goals untouched.
+ * @summary Create conversion goal
+ */
+export const MarketingAnalyticsConversionGoalsCreateCreateBody = /* @__PURE__ */ zod
+ .record(zod.string(), zod.unknown())
+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yaml
index 34e69e577b29..adcd4a87b8ab 100644
--- a/products/marketing_analytics/mcp/tools.yaml
+++ b/products/marketing_analytics/mcp/tools.yaml
@@ -26,6 +26,15 @@ tools:
events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count
may differ from the dashboard's attribution-windowed number.
feature_flag: marketing-analytics-mcp
+ marketing-analytics-conversion-goals-create-create:
+ operation: marketing_analytics_conversion_goals_create_create
+ enabled: false
+ marketing-analytics-conversion-goals-delete-destroy:
+ operation: marketing_analytics_conversion_goals_delete_destroy
+ enabled: false
+ marketing-analytics-conversion-goals-update-partial-update:
+ operation: marketing_analytics_conversion_goals_update_partial_update
+ enabled: false
marketing-analytics-data-sources:
operation: marketing_analytics_data_sources_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a5f163882a4c..e909148b8ba2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16289,6 +16289,11 @@ export namespace Schemas {
images?: ConversationsTicketImage[] | null;
}
+ /**
+ * Wrapper for OpenAPI schema generation - one goal, in any of the three node shapes.
+ */
+ export type ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3;
+
/**
* * `EventsNode` - EventsNode
* * `ActionsNode` - ActionsNode
@@ -16303,6 +16308,108 @@ export namespace Schemas {
DataWarehouseNode: 'DataWarehouseNode',
} as const;
+ export type PartialConversionGoalFilter1Response = { [key: string]: unknown } | null;
+
+ export type PartialConversionGoalFilter1SchemaMap = {[key: string]: string | unknown} | null;
+
+ /**
+ * ConversionGoalFilter1 with every field optional - the fields you send are merged into the stored goal.
+ */
+ export interface PartialConversionGoalFilter1 {
+ conversion_goal_id?: string | null;
+ conversion_goal_name?: string | null;
+ counts_as_customer?: boolean | null;
+ counts_as_revenue?: boolean | null;
+ custom_name?: string | null;
+ event?: string | null;
+ fixedProperties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ kind?: 'EventsNode' | null;
+ limit?: number | null;
+ math?: BaseMathType | FunnelMathType | PropertyMathType | CountPerActorMathType | ExperimentMetricMathType | CalendarHeatmapMathType | 'unique_group' | 'hogql' | null;
+ math_group_type_index?: MathGroupTypeIndex | null;
+ math_hogql?: string | null;
+ math_multiplier?: number | null;
+ math_property?: string | null;
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfig | null;
+ math_property_type?: string | null;
+ name?: string | null;
+ optionalInFunnel?: boolean | null;
+ orderBy?: string[] | null;
+ properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ response?: PartialConversionGoalFilter1Response;
+ schema_map?: PartialConversionGoalFilter1SchemaMap;
+ version?: number | null;
+ }
+
+ export type PartialConversionGoalFilter2Response = { [key: string]: unknown } | null;
+
+ export type PartialConversionGoalFilter2SchemaMap = {[key: string]: string | unknown} | null;
+
+ /**
+ * ConversionGoalFilter2 with every field optional - the fields you send are merged into the stored goal.
+ */
+ export interface PartialConversionGoalFilter2 {
+ conversion_goal_id?: string | null;
+ conversion_goal_name?: string | null;
+ counts_as_customer?: boolean | null;
+ counts_as_revenue?: boolean | null;
+ custom_name?: string | null;
+ fixedProperties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ id?: number | null;
+ kind?: 'ActionsNode' | null;
+ math?: BaseMathType | FunnelMathType | PropertyMathType | CountPerActorMathType | ExperimentMetricMathType | CalendarHeatmapMathType | 'unique_group' | 'hogql' | null;
+ math_group_type_index?: MathGroupTypeIndex | null;
+ math_hogql?: string | null;
+ math_multiplier?: number | null;
+ math_property?: string | null;
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfig | null;
+ math_property_type?: string | null;
+ name?: string | null;
+ optionalInFunnel?: boolean | null;
+ properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ response?: PartialConversionGoalFilter2Response;
+ schema_map?: PartialConversionGoalFilter2SchemaMap;
+ version?: number | null;
+ }
+
+ export type PartialConversionGoalFilter3Response = { [key: string]: unknown } | null;
+
+ export type PartialConversionGoalFilter3SchemaMap = {[key: string]: string | unknown} | null;
+
+ /**
+ * ConversionGoalFilter3 with every field optional - the fields you send are merged into the stored goal.
+ */
+ export interface PartialConversionGoalFilter3 {
+ conversion_goal_id?: string | null;
+ conversion_goal_name?: string | null;
+ counts_as_customer?: boolean | null;
+ counts_as_revenue?: boolean | null;
+ custom_name?: string | null;
+ distinct_id_field?: string | null;
+ dw_source_type?: string | null;
+ fixedProperties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ id?: string | null;
+ id_field?: string | null;
+ kind?: 'DataWarehouseNode' | null;
+ math?: BaseMathType | FunnelMathType | PropertyMathType | CountPerActorMathType | ExperimentMetricMathType | CalendarHeatmapMathType | 'unique_group' | 'hogql' | null;
+ math_group_type_index?: MathGroupTypeIndex | null;
+ math_hogql?: string | null;
+ math_multiplier?: number | null;
+ math_property?: string | null;
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfig | null;
+ math_property_type?: string | null;
+ name?: string | null;
+ optionalInFunnel?: boolean | null;
+ properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ response?: PartialConversionGoalFilter3Response;
+ schema_map?: PartialConversionGoalFilter3SchemaMap;
+ table_name?: string | null;
+ timestamp_field?: string | null;
+ version?: number | null;
+ }
+
+ export type ConversionGoalPatch = PartialConversionGoalFilter1 | PartialConversionGoalFilter2 | PartialConversionGoalFilter3;
+
export interface ConversionGoalSummary {
/** Unique id of the goal (event name, action id, or DW goal id) */
id: string;
@@ -16359,6 +16466,23 @@ export namespace Schemas {
approximation_reason: string | null;
}
+ export interface ConversionGoalWrite {
+ /** The conversion goal. Must match one of the ConversionGoalFilter shapes: an events node, an actions node or a data warehouse node. conversion_goal_id is assigned by the server and any value sent is ignored. */
+ goal: ConversionGoal;
+ }
+
+ /**
+ * List wrapper for OpenAPI schema generation - the response carries every configured goal.
+ */
+ export type ConversionGoalWrittenList = (ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3)[];
+
+ export interface ConversionGoalWriteResponse {
+ /** The goal as stored after the write */
+ goal: ConversionGoal;
+ /** Every configured goal after the write, in display order */
+ conversion_goals: ConversionGoalWrittenList;
+ }
+
export interface ConversionGoalsListResponse {
/** One summary entry per configured conversion goal */
goals: ConversionGoalSummary[];
@@ -52891,6 +53015,14 @@ export namespace Schemas {
readonly task?: ConversationTask | null;
}
+ /**
+ * Separate from create: the body is a patch, so the documented partial has to type-check.
+ */
+ export interface PatchedConversionGoalUpdate {
+ /** The fields to change, merged into the stored goal — anything you leave out is kept, and the goal keeps its position in the list. schema_map is merged key by key. The merged result must still match one of the ConversionGoalFilter shapes. Send `kind` only to change the goal's shape, in which case the goal is replaced rather than merged and the whole new shape is required. conversion_goal_id comes from the URL and any value sent is ignored. */
+ goal?: ConversionGoalPatch;
+ }
+
export interface PatchedCoreEvent {
readonly id?: string;
/**