You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by jl...@apache.org on 2026/08/06 00:45:13 UTC

(superset) 07/10: fix(reports): preserve per-row currency context through pivoting

This is an automated email from the ASF dual-hosted git repository.

sadpandajoe pushed a commit to branch fix-reports-text-number-formatting
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 62df3cc486b687e2af6d774b3f36e2c222d2c1a2
Author: sadpandajoe <jc...@gmail.com>
AuthorDate: Thu Aug 6 00:09:45 2026 +0000

    fix(reports): preserve per-row currency context through pivoting
    
    AUTO currency resolved only to the query-wide detected currency, so a chart
    carrying per-row currency context rendered differently in a report than in
    Explore.
    
    The query already returns the currency column and the payload retains it;
    the association was being lost in pivot_df. A parallel pivot now carries the
    set of contributing currencies through cells, totals and subtotals. A cell
    backed by a single currency renders that symbol, a cell mixing currencies
    stays neutral, and an empty context follows the existing fallback.
---
 superset/charts/client_processing.py              | 293 +++++++++++++++++++---
 superset/utils/number_format.py                   |  51 +++-
 tests/unit_tests/charts/test_client_processing.py | 262 +++++++++++++++++++
 tests/unit_tests/utils/number_format_test.py      |  33 ++-
 4 files changed, 600 insertions(+), 39 deletions(-)

diff --git a/superset/charts/client_processing.py b/superset/charts/client_processing.py
index 5f666da8bf7..bc0fe563dc4 100644
--- a/superset/charts/client_processing.py
+++ b/superset/charts/client_processing.py
@@ -43,6 +43,7 @@ from superset.utils.core import (
     get_metric_names,
 )
 from superset.utils.number_format import (
+    AUTO_CURRENCY,
     format_number_with_config,
     resolve_auto_currency,
 )
@@ -79,8 +80,9 @@ def pivot_df(  # pylint: disable=too-many-locals, too-many-arguments, too-many-s
     show_rows_total: bool = False,
     show_columns_total: bool = False,
     apply_metrics_on_rows: bool = False,
+    metric_name_aggfunc: Optional[str] = None,
 ) -> pd.DataFrame:
-    metric_name = __("Total (%(aggfunc)s)", aggfunc=aggfunc)
+    metric_name = __("Total (%(aggfunc)s)", aggfunc=metric_name_aggfunc or aggfunc)
 
     if transpose_pivot:
         rows, columns = columns, rows
@@ -203,9 +205,12 @@ def pivot_df(  # pylint: disable=too-many-locals, too-many-arguments, too-many-s
                     )
                     raise
 
-                subtotal = pivot_v2_aggfunc_map[aggfunc](
-                    df.iloc[slice_, :].apply(pd.to_numeric, errors="coerce"), axis=0
-                )
+                subtotal_values = df.iloc[slice_, :]
+                if aggfunc != CURRENCY_CONTEXT_AGGREGATION:
+                    subtotal_values = subtotal_values.apply(
+                        pd.to_numeric, errors="coerce"
+                    )
+                subtotal = pivot_v2_aggfunc_map[aggfunc](subtotal_values, axis=0)
                 depth = groups.nlevels - len(subgroup) - 1
                 total = metric_name if level == 0 else __("Subtotal")
                 subtotal.name = tuple([*subgroup, total, *([""] * depth)])  # noqa: C409
@@ -237,6 +242,41 @@ def list_unique_values(series: pd.Series) -> str:
     return ", ".join({str(v) for v in pd.Series.unique(series)})
 
 
+def union_currency_context(
+    values: Union[pd.Series, pd.DataFrame], axis: int = 0
+) -> Union[tuple[str, ...], pd.Series]:
+    """Union the currency sets contributing to a Pivot Table cell or total."""
+    if isinstance(values, pd.DataFrame):
+        contexts = (
+            [union_currency_context(values[column]) for column in values.columns]
+            if axis == 0
+            else [union_currency_context(values.loc[index]) for index in values.index]
+        )
+        index = values.columns if axis == 0 else values.index
+        return pd.Series(contexts, index=index, dtype=object)
+
+    currencies: dict[str, None] = {}
+    for value in values:
+        if isinstance(value, (list, set, frozenset, tuple)):
+            currencies.update((str(currency), None) for currency in value)
+    return tuple(currencies)
+
+
+CURRENCY_CONTEXT_AGGREGATION = "__currency_context__"
+
+# The frontend's plain Count aggregator is the only Pivot Table aggregator
+# without ``getCurrencies()``. Fraction wrappers inherit that absence, so these
+# modes use the query-wide detected fallback instead of per-cell context.
+PIVOT_AGGREGATIONS_WITHOUT_CURRENCY_CONTEXT = frozenset(
+    {
+        "Count",
+        "Count as Fraction of Total",
+        "Count as Fraction of Rows",
+        "Count as Fraction of Columns",
+    }
+)
+
+
 pivot_v2_aggfunc_map = {
     "Count": pd.Series.count,
     "Count Unique Values": pd.Series.nunique,
@@ -258,6 +298,7 @@ pivot_v2_aggfunc_map = {
     "Count as Fraction of Total": pd.Series.count,
     "Count as Fraction of Rows": pd.Series.count,
     "Count as Fraction of Columns": pd.Series.count,
+    CURRENCY_CONTEXT_AGGREGATION: union_currency_context,
 }
 
 
@@ -267,21 +308,39 @@ def format_column(
     d3_format: Optional[str],
     currency: dict[str, Any],
     detected_currency: Optional[str] = None,
+    currency_context: Optional[pd.Series] = None,
+    fallback_to_detected: bool = True,
 ) -> None:
     """
     Format a column in place when a number or currency format is configured.
 
-    ``detected_currency`` represents the query-wide single currency. Per-cell
-    AUTO currency needs row context, while this helper receives one value
-    series and the pivot path does not retain each cell's contributing currency
-    rows. Mixed-currency results therefore use the formatted number without a
-    currency symbol.
+    ``detected_currency`` represents the query-wide single currency. When a
+    parallel ``currency_context`` series is present, AUTO uses each row/cell's
+    contributing currencies first. Mixed context renders a neutral number;
+    empty context optionally falls back to query-wide detection.
     """
-    currency = resolve_auto_currency(currency, detected_currency)
     if d3_format or currency.get("symbol"):
-        df[column] = df[column].apply(
-            partial(format_number_with_config, d3_format, currency)
-        )
+        if currency_context is None:
+            resolved_currency = resolve_auto_currency(currency, detected_currency)
+            df[column] = df[column].apply(
+                partial(format_number_with_config, d3_format, resolved_currency)
+            )
+            return
+
+        contexts = currency_context.reindex(df.index)
+        df[column] = [
+            format_number_with_config(
+                d3_format,
+                resolve_auto_currency(
+                    currency,
+                    detected_currency,
+                    context,
+                    fallback_to_detected,
+                ),
+                value,
+            )
+            for value, context in zip(df[column], contexts, strict=True)
+        ]
 
 
 def get_datasource_column_formats(
@@ -298,6 +357,122 @@ def get_datasource_column_formats(
     )
 
 
+def get_datasource_currency_formats(
+    datasource: Optional[Union["BaseDatasource", "Query"]],
+) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
+    """Return saved metric currencies and verbose labels from a datasource.
+
+    The frontend derives ``datasource.currencyFormats`` from each metric's
+    ``currency`` property in ``hydrateExplore.ts``. Report processing receives
+    the raw datasource payload, so it performs the same derivation here.
+    """
+    if not datasource:
+        return {}, {}
+
+    datasource_data = datasource.data
+    stored_currency_formats = datasource_data.get("currency_formats")
+    currency_formats: dict[str, dict[str, Any]] = (
+        {
+            metric: currency
+            for metric, currency in stored_currency_formats.items()
+            if isinstance(metric, str) and isinstance(currency, dict)
+        }
+        if isinstance(stored_currency_formats, dict)
+        else {}
+    )
+    currency_formats.update(
+        {
+            metric["metric_name"]: metric["currency"]
+            for metric in datasource_data.get("metrics") or []
+            if isinstance(metric, dict)
+            and isinstance(metric.get("metric_name"), str)
+            and isinstance(metric.get("currency"), dict)
+            and metric["currency"].get("symbol")
+        }
+    )
+    return currency_formats, datasource_data.get("verbose_map") or {}
+
+
+def get_datasource_currency_column(
+    datasource: Optional[Union["BaseDatasource", "Query"]],
+    df: pd.DataFrame,
+) -> Optional[str]:
+    """Return the currency-code column name as represented in ``df``."""
+    if not datasource:
+        return None
+
+    datasource_data = datasource.data
+    currency_column = datasource_data.get("currency_code_column")
+    if not isinstance(currency_column, str):
+        return None
+    if currency_column in df.columns:
+        return currency_column
+
+    verbose_column = (datasource_data.get("verbose_map") or {}).get(
+        currency_column, currency_column
+    )
+    return verbose_column if verbose_column in df.columns else None
+
+
+def currency_context_value(value: Any) -> tuple[str, ...]:
+    """Convert a truthy row currency value to frontend-compatible context."""
+    try:
+        if value is None or pd.isna(value) or not value:
+            return ()
+    except (TypeError, ValueError):
+        return ()
+    return (str(value),)
+
+
+def build_pivot_currency_context(
+    df: pd.DataFrame,
+    currency_column: str,
+    metrics: list[str],
+    pivot_options: dict[str, Any],
+) -> pd.DataFrame:
+    """
+    Pivot contributing currency sets through the same layout as metric values.
+
+    This mirrors the frontend Pivot Table aggregators' ``currencySet``: every
+    output cell, subtotal, and total carries the union of currencies from its
+    contributing records while numeric aggregation remains unchanged.
+    """
+    currency_source = df.copy()
+    row_context = currency_source[currency_column].map(currency_context_value)
+    for metric in metrics:
+        currency_source[metric] = row_context
+
+    currency_pivot_options = {
+        **pivot_options,
+        "aggfunc": CURRENCY_CONTEXT_AGGREGATION,
+        "metric_name_aggfunc": pivot_options["aggfunc"],
+    }
+    return pivot_df(currency_source, **currency_pivot_options)
+
+
+def get_pivot_currency_format(form_data: dict[str, Any]) -> dict[str, Any]:
+    """Return Pivot Table currency config from transformed or stored form data."""
+    currency_format = form_data.get("currencyFormat") or form_data.get(
+        "currency_format"
+    )
+    return currency_format if isinstance(currency_format, dict) else {}
+
+
+def has_auto_currency_format(
+    form_data: dict[str, Any],
+    datasource: Optional[Union["BaseDatasource", "Query"]] = None,
+) -> bool:
+    """Return whether the Pivot Table has a global or per-metric AUTO format."""
+    currency_formats = [
+        get_pivot_currency_format(form_data),
+        *merge_currency_formats(form_data, datasource).values(),
+    ]
+    return any(
+        isinstance(currency, dict) and currency.get("symbol") == AUTO_CURRENCY
+        for currency in currency_formats
+    )
+
+
 def merge_column_formats(
     form_data: dict[str, Any],
     datasource: Optional[Union["BaseDatasource", "Query"]],
@@ -318,6 +493,26 @@ def merge_column_formats(
     return column_formats
 
 
+def merge_currency_formats(
+    form_data: dict[str, Any],
+    datasource: Optional[Union["BaseDatasource", "Query"]],
+) -> dict[str, dict[str, Any]]:
+    """Merge saved metric currencies with chart overrides by verbose label."""
+    saved_formats, verbose_map = get_datasource_currency_formats(datasource)
+    currency_formats = {
+        verbose_map.get(metric, metric): currency
+        for metric, currency in saved_formats.items()
+    }
+    currency_formats.update(
+        {
+            verbose_map.get(metric, metric): currency
+            for metric, currency in (form_data.get("currencyFormats") or {}).items()
+            if isinstance(currency, dict) and currency.get("symbol")
+        }
+    )
+    return currency_formats
+
+
 def pivot_table_v2(
     df: pd.DataFrame,
     form_data: dict[str, Any],
@@ -329,22 +524,39 @@ def pivot_table_v2(
     Pivot table v2.
     """
     verbose_map = datasource.data["verbose_map"] if datasource else None
+    metrics = get_metric_names(form_data["metrics"], verbose_map)
+    pivot_options: dict[str, Any] = {
+        "rows": get_column_names(form_data.get("groupbyRows"), verbose_map),
+        "columns": get_column_names(form_data.get("groupbyColumns"), verbose_map),
+        "metrics": metrics,
+        "aggfunc": form_data.get("aggregateFunction", "Sum"),
+        "transpose_pivot": bool(form_data.get("transposePivot")),
+        "combine_metrics": bool(form_data.get("combineMetric")),
+        "show_rows_total": bool(form_data.get("rowTotals")),
+        "show_columns_total": bool(form_data.get("colTotals")),
+        "apply_metrics_on_rows": form_data.get("metricsLayout") == "ROWS",
+    }
 
-    pivoted = pivot_df(
-        df,
-        rows=get_column_names(form_data.get("groupbyRows"), verbose_map),
-        columns=get_column_names(form_data.get("groupbyColumns"), verbose_map),
-        metrics=get_metric_names(form_data["metrics"], verbose_map),
-        aggfunc=form_data.get("aggregateFunction", "Sum"),
-        transpose_pivot=bool(form_data.get("transposePivot")),
-        combine_metrics=bool(form_data.get("combineMetric")),
-        show_rows_total=bool(form_data.get("rowTotals")),
-        show_columns_total=bool(form_data.get("colTotals")),
-        apply_metrics_on_rows=form_data.get("metricsLayout") == "ROWS",
-    )
+    pivoted = pivot_df(df, **pivot_options)
     if apply_number_format:
+        currency_context = None
+        if (
+            pivot_options["aggfunc"] not in PIVOT_AGGREGATIONS_WITHOUT_CURRENCY_CONTEXT
+            and has_auto_currency_format(form_data, datasource)
+            and (currency_column := get_datasource_currency_column(datasource, df))
+        ):
+            currency_context = build_pivot_currency_context(
+                df,
+                currency_column,
+                metrics,
+                pivot_options,
+            )
         return apply_pivot_number_formats(
-            pivoted, form_data, detected_currency, datasource
+            pivoted,
+            form_data,
+            detected_currency,
+            datasource,
+            currency_context,
         )
     return pivoted
 
@@ -354,6 +566,7 @@ def apply_pivot_number_formats(
     form_data: dict[str, Any],
     detected_currency: Optional[str] = None,
     datasource: Optional[Union["BaseDatasource", "Query"]] = None,
+    currency_context: Optional[pd.DataFrame] = None,
 ) -> pd.DataFrame:
     """
     Apply `valueFormat`/`columnFormats` and currency config to pivot values.
@@ -364,22 +577,30 @@ def apply_pivot_number_formats(
     """
     value_format = form_data.get("valueFormat")
     column_formats = merge_column_formats(form_data, datasource)
-    currency_format = form_data.get("currencyFormat") or {}
-    currency_formats = form_data.get("currencyFormats") or {}
+    currency_format = get_pivot_currency_format(form_data)
+    currency_formats = merge_currency_formats(form_data, datasource)
     metric_level = -1 if form_data.get("combineMetric") else 0
     metrics_on_rows = form_data.get("metricsLayout") == "ROWS"
 
     if metrics_on_rows:
         df = df.T
+        if currency_context is not None:
+            currency_context = currency_context.T
 
     for column in df.columns:
         metric = column[metric_level] if isinstance(column, tuple) else column
+        column_currency_context = (
+            currency_context[column]
+            if currency_context is not None and column in currency_context.columns
+            else None
+        )
         format_column(
             df,
             column,
             column_formats.get(metric) or value_format,
             currency_formats.get(metric) or currency_format,
             detected_currency,
+            column_currency_context,
         )
 
     return df.T if metrics_on_rows else df
@@ -399,8 +620,13 @@ def table(
         return df
 
     saved_formats, verbose_map = get_datasource_column_formats(datasource)
+    saved_currency_formats, _ = get_datasource_currency_formats(datasource)
+    currency_column = get_datasource_currency_column(datasource, df)
+    row_currency_context = (
+        df[currency_column].map(currency_context_value) if currency_column else None
+    )
     column_config = form_data.get("column_config") or {}
-    columns = dict.fromkeys([*saved_formats, *column_config])
+    columns = dict.fromkeys([*saved_formats, *saved_currency_formats, *column_config])
     for original_column in columns:
         column = (
             original_column
@@ -409,12 +635,19 @@ def table(
         )
         if column in df.columns:
             config = column_config.get(original_column) or {}
+            configured_currency = config.get("currencyFormat") or {}
             format_column(
                 df,
                 column,
                 config.get("d3NumberFormat") or saved_formats.get(original_column),
-                config.get("currencyFormat") or {},
+                (
+                    configured_currency
+                    if configured_currency.get("symbol")
+                    else saved_currency_formats.get(original_column) or {}
+                ),
                 detected_currency,
+                row_currency_context,
+                fallback_to_detected=False,
             )
 
     return df
diff --git a/superset/utils/number_format.py b/superset/utils/number_format.py
index 00db1201c4e..1a15d44da15 100644
--- a/superset/utils/number_format.py
+++ b/superset/utils/number_format.py
@@ -38,7 +38,7 @@ import math
 import re
 from decimal import Decimal, ROUND_HALF_UP
 from functools import lru_cache
-from typing import Any
+from typing import Any, Iterable
 
 from babel.numbers import format_currency, get_currency_symbol
 from flask import current_app
@@ -96,22 +96,61 @@ D3_FORMAT_RE: re.Pattern[str] = re.compile(
 
 
 def resolve_auto_currency(
-    currency: dict[str, Any], detected_currency: str | None
+    currency: dict[str, Any],
+    detected_currency: str | None,
+    currency_context: Iterable[Any] | None = None,
+    fallback_to_detected: bool = True,
 ) -> dict[str, Any]:
     """
     Resolve an ``AUTO`` currency to the code detected from the data.
 
-    Mirrors ``currency-format/utils.ts::resolveAutoCurrency``. Without a
-    detected query-wide currency (mixed-currency data), the returned config
-    stays ``AUTO`` and the caller renders the bare formatted number.
+    Mirrors ``currency-format/utils.ts::resolveAutoCurrency`` and the per-cell
+    handling in the Table and Pivot Table plugins. A single valid currency in
+    ``currency_context`` takes precedence over the query-wide detection. Mixed
+    cell currencies deliberately keep ``AUTO`` so the caller renders a neutral
+    number. Empty cell context can use the detected fallback when the plugin's
+    behavior allows it.
 
     :return: a copied config containing the detected code, or the input config
     """
-    if currency.get("symbol") == AUTO_CURRENCY and detected_currency:
+    if currency.get("symbol") != AUTO_CURRENCY:
+        return currency
+
+    if currency_context is not None:
+        context_values = list(currency_context)
+        normalized_currencies = {
+            normalized
+            for value in context_values
+            if (normalized := normalize_currency(value)) is not None
+        }
+        if len(normalized_currencies) > 1:
+            return currency
+        if context_values and (cell_currency := normalize_currency(context_values[0])):
+            return {**currency, "symbol": cell_currency}
+        if not fallback_to_detected:
+            return currency
+
+    if detected_currency := normalize_currency(detected_currency):
         return {**currency, "symbol": detected_currency}
     return currency
 
 
+def normalize_currency(value: Any) -> str | None:
+    """
+    Normalize a possible ISO-4217 code for AUTO currency resolution.
+
+    Mirrors ``currency-format/CurrencyFormatter.ts::normalizeCurrency``:
+    non-strings and values other than three ASCII letters are rejected, while
+    valid strings are stripped and upper-cased.
+
+    :return: the normalized three-letter code, or ``None``
+    """
+    if not isinstance(value, str):
+        return None
+    normalized = value.strip().upper()
+    return normalized if re.fullmatch(r"[A-Z]{3}", normalized) else None
+
+
 def format_number_with_config(
     d3_format: str | None,
     currency: dict[str, Any] | None,
diff --git a/tests/unit_tests/charts/test_client_processing.py b/tests/unit_tests/charts/test_client_processing.py
index 2bd9f68cb74..ddefdaff940 100644
--- a/tests/unit_tests/charts/test_client_processing.py
+++ b/tests/unit_tests/charts/test_client_processing.py
@@ -2036,6 +2036,64 @@ def test_table_auto_currency_uses_detected_currency() -> None:
     assert formatted["amount"].tolist() == ["1,234.50"]
 
 
+def test_table_auto_currency_uses_per_row_currency_context() -> None:
+    form_data = {
+        "viz_type": "table",
+        "column_config": {
+            "amount": {
+                "d3NumberFormat": ",.2f",
+                "currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"},
+            }
+        },
+    }
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    df = pd.DataFrame(
+        {
+            "amount": [100.0, 200.0, 300.0, 400.0],
+            "currency": ["USD", " eur ", None, "invalid"],
+        }
+    )
+
+    formatted = table(df, form_data, datasource, detected_currency="GBP")
+
+    assert formatted["amount"].tolist() == [
+        "$ 100.00",
+        "€ 200.00",
+        "300.00",
+        "400.00",
+    ]
+
+
+def test_table_saved_auto_currency_uses_per_row_currency_context() -> None:
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {"amount": ",.2f"},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+        "metrics": [
+            {
+                "metric_name": "amount",
+                "currency": {"symbol": "AUTO", "symbolPosition": "prefix"},
+            }
+        ],
+    }
+    df = pd.DataFrame(
+        {
+            "amount": [100.0, 200.0],
+            "currency": ["USD", "EUR"],
+        }
+    )
+
+    formatted = table(df, {"viz_type": "table"}, datasource)
+
+    assert formatted["amount"].tolist() == ["$ 100.00", "€ 200.00"]
+
+
 def test_pivot_table_v2_auto_currency_uses_detected_currency() -> None:
     """
     AUTO currency in pivot tables resolves to the payload's `detected_currency`.
@@ -2054,6 +2112,210 @@ def test_pivot_table_v2_auto_currency_uses_detected_currency() -> None:
     assert formatted[("sales",)].tolist() == ["€ 1,234.50", "€ 6,789.00"]
 
 
+def test_pivot_table_v2_auto_currency_uses_per_cell_currency_context() -> None:
+    df = pd.DataFrame(
+        {
+            "region": ["USD cell", "USD cell", "EUR cell", "Mixed", "Mixed", "Empty"],
+            "sales": [100.0, 50.0, 200.0, 300.0, 400.0, 500.0],
+            "currency": ["USD", " usd ", "EUR", "USD", "EUR", None],
+        }
+    )
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": [],
+        "metrics": ["sales"],
+        "aggregateFunction": "Sum",
+        "valueFormat": ",.2f",
+        "currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"},
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource, detected_currency="GBP")
+
+    assert formatted[("sales",)].to_dict() == {
+        ("EUR cell",): "€ 200.00",
+        ("Empty",): "£ 500.00",
+        ("Mixed",): "700.00",
+        ("USD cell",): "$ 150.00",
+    }
+
+
+def test_pivot_table_v2_auto_currency_reads_stored_form_data_key() -> None:
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    df = pd.DataFrame(
+        {
+            "region": ["US", "EU"],
+            "sales": [100.0, 200.0],
+            "currency": ["USD", "EUR"],
+        }
+    )
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": [],
+        "metrics": ["sales"],
+        "aggregateFunction": "Sum",
+        "valueFormat": ",.2f",
+        "currency_format": {"symbol": "AUTO", "symbolPosition": "prefix"},
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource)
+
+    assert formatted[("sales",)].to_dict() == {
+        ("EU",): "€ 200.00",
+        ("US",): "$ 100.00",
+    }
+
+
+def test_pivot_table_v2_saved_auto_currency_uses_per_cell_context() -> None:
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {"sales": ",.2f"},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+        "metrics": [
+            {
+                "metric_name": "sales",
+                "currency": {"symbol": "AUTO", "symbolPosition": "prefix"},
+            }
+        ],
+    }
+    df = pd.DataFrame(
+        {
+            "region": ["US", "EU"],
+            "sales": [100.0, 200.0],
+            "currency": ["USD", "EUR"],
+        }
+    )
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": [],
+        "metrics": ["sales"],
+        "aggregateFunction": "Sum",
+        "valueFormat": ",.1f",
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource)
+
+    assert formatted[("sales",)].to_dict() == {
+        ("EU",): "€ 200.00",
+        ("US",): "$ 100.00",
+    }
+
+
+def test_pivot_table_v2_count_auto_currency_uses_detected_fallback() -> None:
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    df = pd.DataFrame(
+        {
+            "region": ["US", "EU"],
+            "sales": [100.0, 200.0],
+            "currency": ["USD", "EUR"],
+        }
+    )
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": [],
+        "metrics": ["sales"],
+        "aggregateFunction": "Count",
+        "valueFormat": ",d",
+        "currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"},
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource, detected_currency="GBP")
+
+    assert formatted[("sales",)].to_dict() == {
+        ("EU",): "£ 1",
+        ("US",): "£ 1",
+    }
+
+
+def test_pivot_table_v2_auto_currency_tracks_mixed_total_context() -> None:
+    df = pd.DataFrame(
+        {
+            "region": ["US", "EU"],
+            "sales": [100.0, 200.0],
+            "currency": ["USD", "EUR"],
+        }
+    )
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": [],
+        "metrics": ["sales"],
+        "aggregateFunction": "Sum",
+        "valueFormat": ",.2f",
+        "currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"},
+        "colTotals": True,
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource)
+
+    assert formatted[("sales",)].to_dict() == {
+        ("EU",): "€ 200.00",
+        ("US",): "$ 100.00",
+        ("Total (Sum)",): "300.00",
+    }
+
+
+def test_pivot_table_v2_auto_currency_tracks_subtotal_context() -> None:
+    df = pd.DataFrame(
+        {
+            "region": ["Mixed", "Mixed", "USD", "USD"],
+            "quarter": ["Q1", "Q2", "Q1", "Q2"],
+            "sales": [100.0, 200.0, 300.0, 400.0],
+            "currency": ["USD", "EUR", "USD", "USD"],
+        }
+    )
+    datasource = MagicMock()
+    datasource.data = {
+        "column_formats": {},
+        "verbose_map": {},
+        "currency_code_column": "currency",
+    }
+    form_data = {
+        "viz_type": "pivot_table_v2",
+        "groupbyRows": ["region"],
+        "groupbyColumns": ["quarter"],
+        "metrics": ["sales"],
+        "aggregateFunction": "Sum",
+        "valueFormat": ",.2f",
+        "currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"},
+        "rowTotals": True,
+    }
+
+    formatted = pivot_table_v2(df, form_data, datasource)
+
+    assert formatted.loc[("Mixed",), ("sales", "Q1")] == "$ 100.00"
+    assert formatted.loc[("Mixed",), ("sales", "Q2")] == "€ 200.00"
+    assert formatted.loc[("Mixed",), ("sales", "Subtotal")] == "300.00"
+    assert formatted.loc[("USD",), ("sales", "Subtotal")] == "$ 700.00"
+    assert formatted.loc[("Mixed",), ("Total (Sum)", "")] == "300.00"
+
+
 def test_apply_client_processing_passes_detected_currency() -> None:
     """
     The query payload's `detected_currency` reaches the number formatters.
diff --git a/tests/unit_tests/utils/number_format_test.py b/tests/unit_tests/utils/number_format_test.py
index 0451e1352a8..60a6bc7ef34 100644
--- a/tests/unit_tests/utils/number_format_test.py
+++ b/tests/unit_tests/utils/number_format_test.py
@@ -95,6 +95,33 @@ def test_resolve_auto_currency_uses_detected_single_currency() -> None:
     assert resolve_auto_currency(explicit, "USD") is explicit
 
 
+def test_resolve_auto_currency_prefers_cell_context_and_detects_mixed() -> None:
+    currency = {"symbol": "AUTO", "symbolPosition": "prefix"}
+
+    assert resolve_auto_currency(
+        currency, "GBP", currency_context=frozenset({" usd "})
+    ) == {"symbol": "USD", "symbolPosition": "prefix"}
+    assert (
+        resolve_auto_currency(
+            currency, "GBP", currency_context=frozenset({"USD", "EUR"})
+        )
+        is currency
+    )
+    assert resolve_auto_currency(currency, "GBP", currency_context=frozenset()) == {
+        "symbol": "GBP",
+        "symbolPosition": "prefix",
+    }
+    assert (
+        resolve_auto_currency(
+            currency,
+            "GBP",
+            currency_context=frozenset(),
+            fallback_to_detected=False,
+        )
+        is currency
+    )
+
+
 @pytest.mark.parametrize(
     "value,expected",
     [
@@ -392,9 +419,9 @@ EXPECTED: dict[str, list[str]] = {
 def test_matches_frontend_d3_format(d3_format: str) -> None:
     for value, expected in zip(VALUES, EXPECTED[d3_format], strict=True):
         result = format_number_with_config(d3_format, None, value)
-        assert result == expected.replace(
-            "−", "-"
-        ), f"{d3_format!r} of {value}: got {result!r}, expected {expected!r}"
+        assert result == expected.replace("−", "-"), (
+            f"{d3_format!r} of {value}: got {result!r}, expected {expected!r}"
+        )
 
 
 @pytest.mark.parametrize(