sadpandajoe commented on code in PR #41028:
URL: https://github.com/apache/superset/pull/41028#discussion_r3501222668
##########
superset/charts/client_processing.py:
##########
@@ -278,6 +291,38 @@ def pivot_table_v2(
show_columns_total=bool(form_data.get("colTotals")),
apply_metrics_on_rows=form_data.get("metricsLayout") == "ROWS",
)
+ if apply_number_format:
+ return apply_pivot_number_formats(pivoted, form_data)
+ return pivoted
+
+
+def apply_pivot_number_formats(
+ df: pd.DataFrame, form_data: dict[str, Any]
+) -> pd.DataFrame:
+ """
+ Apply `valueFormat`/`columnFormats` and currency config to pivot values.
+
+ The metric name is the first column level, or the last when `combineMetric`
+ moves it there; per-metric overrides fall back to the global value format.
In
+ the ROWS metrics layout the metric is on the index, so every value column
+ uses the global format.
+ """
+ value_format = form_data.get("valueFormat")
+ column_formats = form_data.get("columnFormats") or {}
+ currency_format = form_data.get("currencyFormat") or {}
+ currency_formats = form_data.get("currencyFormats") or {}
+ metric_level = -1 if form_data.get("combineMetric") else 0
Review Comment:
Will this drop per-metric pivot formats when `metricsLayout == "ROWS"`?
##########
superset/utils/number_format.py:
##########
@@ -0,0 +1,333 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Server-side port of the d3-format based number and currency formatters used by
+the Table and Pivot Table chart plugins.
+
+Report notifications that embed a chart as text build the table in Python and
+have no access to the frontend formatters, so chart number/currency format
+configuration has to be reproduced here to render the same values an end user
+sees in the browser.
+
+Only d3-format specifiers (and the ``SMART_NUMBER`` pseudo-formats) are ported.
+Non-d3 presets such as ``DURATION``, ``DURATION_SUB`` and the ``MEMORY_*``
+formatters are not supported: they do not parse as a d3 specifier and fall back
+to the raw value, so a column using one of those renders unformatted in
reports.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from decimal import Decimal, ROUND_HALF_UP
+from typing import Any
+
+from babel.numbers import get_currency_symbol
+
+SMART_NUMBER = "SMART_NUMBER"
+SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED"
+AUTO_CURRENCY = "AUTO"
+
+LOCALE = "en_US"
+
+# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format.
+SI_PREFIXES = {
+ -8: "y",
+ -7: "z",
+ -6: "a",
+ -5: "f",
+ -4: "p",
+ -3: "n",
+ -2: "ยต",
+ -1: "m",
+ 0: "",
+ 1: "k",
+ 2: "M",
+ 3: "G",
+ 4: "T",
+ 5: "P",
+ 6: "E",
+ 7: "Z",
+ 8: "Y",
+}
+
+# d3-format specifier grammar:
+# [[fill]align][sign][symbol][0][width][,][.precision][~][type]
+D3_FORMAT_RE = re.compile(
+ r"^(?:(.)?([<>=^]))?([+\-(
])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$",
+ re.IGNORECASE,
+)
+
+
+def format_number_with_config(
+ d3_format: str | None,
+ currency: dict[str, Any] | None,
+ value: Any,
+) -> Any:
+ """
+ Format ``value`` using a d3-format string and optional currency config.
+
+ :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or
``SMART_NUMBER``
+ :param currency: ``{"symbol": <ISO 4217>, "symbolPosition":
"prefix"|"suffix"}``
+ :param value: the raw value to format
+ :return: the formatted string, or the value unchanged when it is not a
+ number that can be formatted
+ """
+ if value is None:
+ return ""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
Review Comment:
Won't this skip `Decimal` values entirely since `int`/`float` are treated as
numeric?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]