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.

fix(marketing-analytics): convert conversion goal revenue to the team base currency (#73047)

Javier Bahamondes0a1f13a3764f
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index 41c180bada4f..d0449408904c 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -23,6 +23,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr
+from posthog.hogql.database.schema.exchange_rate import convert_currency_call
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.hogql.timings import HogQLTimings
@@ -296,17 +297,62 @@ class ConversionGoalProcessor:
if self.goal.kind == "DataWarehouseNode":
property_field = ast.Field(chain=[math_property])
+ timestamp_field = self.goal.schema_map.get("timestamp_field", "timestamp")
+ timestamp_expr: ast.Expr = ast.Field(chain=[timestamp_field])
else:
property_field = ast.Field(chain=["events", "properties", math_property])
+ timestamp_expr = ast.Field(chain=["events", "timestamp"])
+
+ value_per_row = self._to_base_currency(property_field, timestamp_expr)
return ast.Call(
name="round",
args=[
- ast.Call(name="sum", args=[ast.Call(name="toFloat", args=[property_field])]),
+ ast.Call(name="sum", args=[value_per_row]),
ast.Constant(value=self.config.decimal_precision),
],
)
+ def _to_base_currency(self, property_field: ast.Expr, timestamp_expr: ast.Expr) -> ast.Expr:
+ """Turn a raw revenue property into a float in the team's base currency.
+
+ When the goal declares a math_property_revenue_currency, convert each value at the exchange
+ rate of its own event day. Without it, the value is assumed to already be in the base currency
+ and is only cast to float, which keeps goals that never set a currency behaving as before.
+ """
+ amount = ast.Call(name="toFloat", args=[property_field])
+ currency = self.goal.math_property_revenue_currency
+ if currency is None:
+ return amount
+
+ base_currency = ast.Constant(value=self.team.base_currency)
+ date = ast.Call(name="_toDate", args=[timestamp_expr])
+
+ if currency.property:
+ if self.goal.kind == "DataWarehouseNode":
+ currency_from: ast.Expr = ast.Field(chain=[currency.property])
+ else:
+ currency_from = ast.Field(chain=["events", "properties", currency.property])
+ currency_from = ast.Call(
+ name="nullIf", args=[ast.Call(name="upper", args=[currency_from]), ast.Constant(value="")]
+ )
+ # A row can be missing the currency property or carry an empty string; treat those as already
+ # in the base currency rather than letting convertCurrency null the whole amount out.
+ return ast.Call(
+ name="if",
+ args=[
+ ast.Call(name="isNull", args=[currency_from]),
+ amount,
+ ast.Call(name="toFloat", args=[convert_currency_call(amount, currency_from, base_currency, date)]),
+ ],
+ )
+
+ if currency.static:
+ currency_from = ast.Constant(value=currency.static.value)
+ return ast.Call(name="toFloat", args=[convert_currency_call(amount, currency_from, base_currency, date)])
+
+ return amount
+
def get_base_where_conditions(self) -> list[ast.Expr]:
"""Build base WHERE conditions for conversion goal filtering"""
conditions: list[ast.Expr] = []
@@ -473,6 +519,11 @@ class ConversionGoalProcessor:
math_property = getattr(self.goal, "math_property", None)
if math_property:
props.add(math_property)
+ # A property-sourced currency is folded into conversion_math_value by _to_base_currency, so the
+ # converted amount leaks it just as directly as math_property itself.
+ currency = getattr(self.goal, "math_property_revenue_currency", None)
+ if currency is not None and currency.property:
+ props.add(currency.property)
return props
def _precompute_properties_restricted_for_user(self) -> bool:
@@ -1223,8 +1274,8 @@ class ConversionGoalProcessor:
math_property = self.goal.math_property
if math_property:
property_field = ast.Field(chain=["events", "properties", math_property])
- to_float_expr = ast.Call(name="toFloat", args=[property_field])
- return ast.Call(name="coalesce", args=[to_float_expr, ast.Constant(value=0.0)])
+ value = self._to_base_currency(property_field, ast.Field(chain=["events", "timestamp"]))
+ return ast.Call(name="coalesce", args=[value, ast.Constant(value=0.0)])
return ast.Call(name="toFloat", args=[ast.Constant(value=1)])
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
index 65845fff1dbd..fb34e71fc103 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
@@ -651,6 +651,73 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
f"Expected total revenue of 100 (100+0+missing=0+missing=0), got {total_revenue}. Missing revenue properties should be treated as 0."
)
+ @parameterized.expand(
+ [
+ ("no_currency", None),
+ ("static_currency", {"static": "EUR"}),
+ ("property_currency", {"property": "currency_code"}),
+ ]
+ )
+ def test_sum_math_currency_conversion_matches_across_live_and_precompute_paths(self, _name, currency_config):
+ goal = ConversionGoalFilter1(
+ kind="EventsNode",
+ event="purchase",
+ conversion_goal_id="currency_goal",
+ conversion_goal_name="Currency Goal",
+ math=PropertyMathType.SUM,
+ math_property="revenue",
+ math_property_revenue_currency=currency_config,
+ schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},
+ )
+ processor = ConversionGoalProcessor(goal=goal, index=0, team=self.team, config=self.config)
+
+ live = processor.get_select_field().to_hogql()
+ precompute = processor._get_conversion_value_expr().to_hogql()
+
+ should_convert = currency_config is not None
+ assert ("convertCurrency" in live) is should_convert
+ assert ("convertCurrency" in precompute) is should_convert
+
+ def test_sum_math_static_currency_uses_the_configured_code_without_a_property_lookup(self):
+ goal = ConversionGoalFilter1(
+ kind="EventsNode",
+ event="purchase",
+ conversion_goal_id="static_goal",
+ conversion_goal_name="Static Goal",
+ math=PropertyMathType.SUM,
+ math_property="revenue",
+ math_property_revenue_currency={"static": "GBP"},
+ schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},
+ )
+ processor = ConversionGoalProcessor(goal=goal, index=0, team=self.team, config=self.config)
+
+ live = processor.get_select_field().to_hogql()
+
+ assert "'GBP'" in live
+ assert "upper(" not in live
+
+ def test_sum_math_property_currency_reads_the_property_and_falls_back_to_base_when_missing(self):
+ goal = ConversionGoalFilter1(
+ kind="EventsNode",
+ event="purchase",
+ conversion_goal_id="property_goal",
+ conversion_goal_name="Property Goal",
+ math=PropertyMathType.SUM,
+ math_property="revenue",
+ math_property_revenue_currency={"property": "currency_code"},
+ schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},
+ )
+ processor = ConversionGoalProcessor(goal=goal, index=0, team=self.team, config=self.config)
+
+ live = processor.get_select_field().to_hogql()
+
+ assert "upper(" in live
+ assert "currency_code" in live
+ # The guard keeps rows with no currency property (or an empty-string value, which convertCurrency
+ # would null out) in the base currency instead of dropping their revenue
+ assert "isNull(" in live
+ assert "nullIf(" in live
+
def test_math_type_average_fallback_behavior(self):
"""Test AVERAGE math type fallback behavior - counts events since AVG not implemented - business logic validation"""
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
index 2c2b61508330..b6ab9180f294 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
@@ -7,7 +7,14 @@ from unittest.mock import patch
from parameterized import parameterized
-from posthog.schema import AttributionMode, BaseMathType, ConversionGoalFilter1, EventPropertyFilter, PropertyOperator
+from posthog.schema import (
+ AttributionMode,
+ BaseMathType,
+ ConversionGoalFilter1,
+ EventPropertyFilter,
+ PropertyOperator,
+ RevenueCurrencyPropertyConfig,
+)
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
@@ -22,6 +29,8 @@ def _make_event_goal(
event: str = "purchase",
properties: list | None = None,
schema_map: dict | None = None,
+ math_property: str | None = None,
+ math_property_revenue_currency: RevenueCurrencyPropertyConfig | None = None,
) -> ConversionGoalFilter1:
return ConversionGoalFilter1(
kind="EventsNode",
@@ -31,6 +40,8 @@ def _make_event_goal(
math=BaseMathType.TOTAL,
schema_map=schema_map or {"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},
properties=properties or [],
+ math_property=math_property,
+ math_property_revenue_currency=math_property_revenue_currency,
)
@@ -97,11 +108,27 @@ class TestConversionGoalProcessorRefactor(BaseTest):
assert single.select != multi.select
- def test_precompute_skipped_when_tracked_property_restricted(self):
- # Precompute materializes tracked attribution properties via the touchpoints table, bypassing
- # the per-user masking HogQL applies to events.properties. When such a property is restricted
- # for the user, eligibility must fail so the direct (masked) events query is used instead.
- processor = self._processor()
+ @parameterized.expand(
+ [
+ # utm_source is one of the tracked attribution properties resolved from the goal's schema_map.
+ ("tracked_utm_property", {}, "utm_source"),
+ (
+ "revenue_currency_property",
+ {
+ "math_property": "revenue",
+ "math_property_revenue_currency": RevenueCurrencyPropertyConfig(property="currency_code"),
+ },
+ "currency_code",
+ ),
+ ]
+ )
+ def test_precompute_skipped_when_materialized_property_restricted(
+ self, _name: str, goal_overrides: dict, restricted_property: str
+ ):
+ # Precompute materializes these properties into scalar columns, bypassing the per-user masking
+ # HogQL applies to events.properties. When one is restricted for the user, eligibility must fail
+ # so the direct (masked) events query is used instead.
+ processor = self._processor(**goal_overrides)
processor.config.conversion_goal_precomputation_enabled = True
date_from = datetime(2025, 1, 1, tzinfo=UTC)
date_to = datetime(2025, 1, 31, tzinfo=UTC)
@@ -112,8 +139,7 @@ class TestConversionGoalProcessorRefactor(BaseTest):
with patch(target, return_value=set()):
assert processor._should_use_precompute(date_from, date_to) is True
- # utm_source is one of the tracked attribution properties resolved from the goal's schema_map.
- with patch(target, return_value={"utm_source"}):
+ with patch(target, return_value={restricted_property}):
assert processor._should_use_precompute(date_from, date_to) is False
def test_tracked_fields_match_touchpoints_table_schema(self):