You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by el...@apache.org on 2026/01/17 05:58:49 UTC
(superset) branch master updated: feat: Dynamic currency (#36416)
This is an automated email from the ASF dual-hosted git repository.
elizabeth pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new f4474b2e3e feat: Dynamic currency (#36416)
f4474b2e3e is described below
commit f4474b2e3e97b0dafbfdcb9fa5ca5850c432efcc
Author: Richard Fogaca Nienkotter <63...@users.noreply.github.com>
AuthorDate: Sat Jan 17 02:58:41 2026 -0300
feat: Dynamic currency (#36416)
---
.../src/shared-controls/sharedControls.tsx | 3 +
.../superset-ui-chart-controls/src/types.ts | 1 +
.../{index.ts => CurrencyFormats.ts} | 8 +-
.../src/currency-format/CurrencyFormatter.ts | 88 +++++-
.../superset-ui-core/src/currency-format/index.ts | 10 +-
.../src/currency-format/{index.ts => types.ts} | 15 +-
.../superset-ui-core/src/currency-format/utils.ts | 129 +++++++-
.../superset-ui-core/src/query/types/Datasource.ts | 1 +
.../src/query/types/QueryResponse.ts | 6 +
.../test/currency-format/CurrencyFormatter.test.ts | 31 ++
.../currency-format/analyzeCurrencyInData.test.ts} | 19 +-
.../currency-format/hasMixedCurrencies.test.ts} | 18 +-
.../currency-format/normalizeCurrency.test.ts} | 20 +-
.../src/transformProps.js | 13 +-
.../BigNumberPeriodOverPeriod/transformProps.ts | 13 +-
.../src/BigNumber/BigNumberTotal/transformProps.ts | 16 +-
.../BigNumberWithTrendline/transformProps.ts | 11 +-
.../plugin-chart-echarts/src/BigNumber/types.ts | 2 +-
.../src/Funnel/transformProps.ts | 11 +-
.../src/Gauge/transformProps.ts | 6 +
.../src/Heatmap/transformProps.ts | 17 +-
.../src/MixedTimeseries/transformProps.ts | 36 ++-
.../plugin-chart-echarts/src/Pie/transformProps.ts | 13 +-
.../src/Sunburst/transformProps.ts | 11 +-
.../src/Timeseries/transformProps.ts | 29 +-
.../src/Treemap/transformProps.ts | 12 +-
.../test/BigNumber/transformProps.test.ts | 56 ++++
.../test/Timeseries/transformProps.test.ts | 132 ++++++++
.../src/PivotTableChart.tsx | 124 +++++++-
.../src/plugin/transformProps.ts | 18 +-
.../src/react-pivottable/TableRenderers.jsx | 8 +-
.../src/react-pivottable/utilities.js | 56 +++-
.../plugins/plugin-chart-pivot-table/src/types.ts | 2 +
.../test/plugin/transformProps.test.ts | 189 ++++++++++++
.../plugins/plugin-chart-table/src/TableChart.tsx | 2 +-
.../plugin-chart-table/src/transformProps.ts | 35 ++-
.../plugins/plugin-chart-table/src/types.ts | 1 +
.../plugin-chart-table/src/utils/formatValue.ts | 11 +-
.../plugin-chart-table/src/utils/isEqualColumns.ts | 3 +
.../test/utils/formatValue.test.ts | 155 ++++++++++
.../Datasource/DatasourceModal/index.tsx | 1 +
.../DatasourceEditor/DatasourceEditor.jsx | 183 ++++++++----
.../tests/DatasourceEditor.test.tsx | 44 ++-
.../tests/DatasourceEditorCurrency.test.tsx | 67 +++++
.../ColumnConfigControl/ColumnConfigControl.tsx | 2 +
.../controls/ColumnConfigControl/constants.tsx | 2 +-
.../CurrencyControl/CurrencyControl.test.tsx} | 24 +-
.../controls/CurrencyControl/CurrencyControl.tsx | 80 ++++-
superset-frontend/src/features/datasets/types.ts | 1 +
superset/charts/schemas.py | 9 +
superset/cli/examples.py | 3 +
superset/common/query_actions.py | 65 ++++
superset/common/query_context_factory.py | 34 +++
superset/connectors/sqla/models.py | 6 +-
superset/dashboards/schemas.py | 1 +
superset/datasets/api.py | 2 +
superset/datasets/schemas.py | 2 +
superset/examples/data_loading.py | 2 +
superset/examples/international_sales.py | 238 +++++++++++++++
...-00_9787190b3d89_add_currency_column_support.py | 62 ++--
superset/superset_typing.py | 2 +
superset/utils/currency.py | 160 ++++++++++
superset/views/core.py | 21 +-
superset/viz.py | 1 +
tests/integration_tests/datasets/commands_tests.py | 3 +
tests/integration_tests/fixtures/importexport.py | 1 +
.../common/test_query_actions_currency.py | 290 ++++++++++++++++++
.../common/test_query_context_factory.py | 106 +++++++
tests/unit_tests/connectors/sqla/models_test.py | 64 ++++
tests/unit_tests/datasets/commands/export_test.py | 1 +
tests/unit_tests/datasets/schema_tests.py | 29 ++
tests/unit_tests/utils/currency_test.py | 332 +++++++++++++++++++++
72 files changed, 2942 insertions(+), 227 deletions(-)
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx
index 0dc760c3cb..0b9953b95a 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx
@@ -325,6 +325,9 @@ const currency_format: SharedControlConfig<'CurrencyControl'> = {
type: 'CurrencyControl',
label: t('Currency format'),
renderTrigger: true,
+ description: t(
+ "Format metrics or columns with currency symbols as prefixes or suffixes. Choose a symbol manually or use 'Auto-detect' to apply the correct symbol based on the dataset's currency code column. When multiple currencies are present, formatting falls back to neutral numbers.",
+ ),
};
const x_axis_time_format: SharedControlConfig<
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
index 115eb0b65b..ffb32bf9d2 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
@@ -72,6 +72,7 @@ export interface Dataset {
currency_formats?: Record<string, Currency>;
verbose_map: Record<string, string>;
main_dttm_col: string;
+ currency_code_column?: string;
// eg. ['["ds", true]', 'ds [asc]']
order_by_choices?: [string, string][] | null;
time_grain_sqla?: [string, string][];
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormats.ts
similarity index 85%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormats.ts
index 45fa851e88..17f257112a 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormats.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -17,6 +17,6 @@
* under the License.
*/
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+export const AUTO_CURRENCY_SYMBOL = 'AUTO';
+
+export const ISO_4217_REGEX = /^[A-Z]{3}$/;
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts b/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts
index 9dd503cea6..a7997879c5 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts
+++ b/superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts
@@ -20,6 +20,8 @@
import { ExtensibleFunction } from '../models';
import { getNumberFormatter, NumberFormats } from '../number-format';
import { Currency } from '../query';
+import { RowData, RowDataValue } from './types';
+import { AUTO_CURRENCY_SYMBOL, ISO_4217_REGEX } from './CurrencyFormats';
/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
@@ -30,7 +32,11 @@ interface CurrencyFormatterConfig {
}
interface CurrencyFormatter {
- (value: number | null | undefined): string;
+ (
+ value: number | null | undefined,
+ rowData?: RowData,
+ currencyColumn?: string,
+ ): string;
}
export const getCurrencySymbol = (currency: Partial<Currency>) =>
@@ -41,6 +47,32 @@ export const getCurrencySymbol = (currency: Partial<Currency>) =>
.formatToParts(1)
.find(x => x.type === 'currency')?.value;
+export function normalizeCurrency(value: RowDataValue): string | null {
+ if (value === null || value === undefined) return null;
+ if (typeof value !== 'string') return null;
+
+ const normalized = value.trim().toUpperCase();
+
+ return ISO_4217_REGEX.test(normalized) ? normalized : null;
+}
+
+export function hasMixedCurrencies(currencies: RowDataValue[]): boolean {
+ let first: string | null = null;
+
+ for (const c of currencies) {
+ const normalized = normalizeCurrency(c);
+ if (normalized === null) continue;
+
+ if (first === null) {
+ first = normalized;
+ } else if (normalized !== first) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
class CurrencyFormatter extends ExtensibleFunction {
d3Format: string;
@@ -49,7 +81,9 @@ class CurrencyFormatter extends ExtensibleFunction {
currency: Currency;
constructor(config: CurrencyFormatterConfig) {
- super((value: number) => this.format(value));
+ super((value: number, rowData?: RowData, currencyColumn?: string) =>
+ this.format(value, rowData, currencyColumn),
+ );
this.d3Format = config.d3Format || NumberFormats.SMART_NUMBER;
this.currency = config.currency;
this.locale = config.locale || 'en-US';
@@ -67,19 +101,59 @@ class CurrencyFormatter extends ExtensibleFunction {
return value.replace(/%/g, '');
}
- format(value: number) {
+ format(value: number, rowData?: RowData, currencyColumn?: string): string {
const formattedValue = getNumberFormatter(this.getNormalizedD3Format())(
value,
);
- if (!this.hasValidCurrency()) {
+
+ const isAutoMode = this.currency?.symbol === AUTO_CURRENCY_SYMBOL;
+
+ if (!this.hasValidCurrency() && !isAutoMode) {
return formattedValue as string;
}
+ // Remove % signs from formatted value for currency display
const normalizedValue = this.normalizeForCurrency(formattedValue);
- if (this.currency.symbolPosition === 'prefix') {
- return `${getCurrencySymbol(this.currency)} ${normalizedValue}`;
+
+ if (isAutoMode) {
+ if (rowData && currencyColumn && rowData[currencyColumn]) {
+ const rawCurrency = rowData[currencyColumn];
+ const normalizedCurrency = normalizeCurrency(rawCurrency);
+
+ if (normalizedCurrency) {
+ try {
+ const symbol = getCurrencySymbol({ symbol: normalizedCurrency });
+ if (symbol) {
+ if (this.currency.symbolPosition === 'prefix') {
+ return `${symbol} ${normalizedValue}`;
+ } else if (this.currency.symbolPosition === 'suffix') {
+ return `${normalizedValue} ${symbol}`;
+ }
+ // Unknown symbolPosition - default to suffix
+ return `${normalizedValue} ${symbol}`;
+ }
+ } catch {
+ // Invalid currency code - return value without currency symbol
+ return formattedValue;
+ }
+ }
+ }
+ return formattedValue;
+ }
+
+ try {
+ const symbol = getCurrencySymbol(this.currency);
+ if (this.currency.symbolPosition === 'prefix') {
+ return `${symbol} ${normalizedValue}`;
+ } else if (this.currency.symbolPosition === 'suffix') {
+ return `${normalizedValue} ${symbol}`;
+ }
+ // Unknown symbolPosition - default to suffix
+ return `${normalizedValue} ${symbol}`;
+ } catch {
+ // Invalid currency code - return value without currency symbol
+ return formattedValue;
}
- return `${normalizedValue} ${getCurrencySymbol(this.currency)}`;
}
}
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
index 45fa851e88..8f696f40cb 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -18,5 +18,11 @@
*/
export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
+export {
+ getCurrencySymbol,
+ normalizeCurrency,
+ hasMixedCurrencies,
+} from './CurrencyFormatter';
+export { AUTO_CURRENCY_SYMBOL, ISO_4217_REGEX } from './CurrencyFormats';
+export * from './types';
export * from './utils';
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/src/currency-format/types.ts
similarity index 83%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/packages/superset-ui-core/src/currency-format/types.ts
index 45fa851e88..882fca6f42 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/src/currency-format/types.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -17,6 +17,13 @@
* under the License.
*/
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+export type RowDataValue =
+ | string
+ | number
+ | boolean
+ | Date
+ | bigint
+ | null
+ | undefined;
+
+export type RowData = Record<string, RowDataValue>;
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/utils.ts b/superset-frontend/packages/superset-ui-core/src/currency-format/utils.ts
index 14228ea77f..53a704ab97 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/utils.ts
+++ b/superset-frontend/packages/superset-ui-core/src/currency-format/utils.ts
@@ -25,21 +25,104 @@ import {
QueryFormMetric,
ValueFormatter,
} from '@superset-ui/core';
+import { normalizeCurrency, hasMixedCurrencies } from './CurrencyFormatter';
+import { RowData, RowDataValue } from './types';
+import { AUTO_CURRENCY_SYMBOL } from './CurrencyFormats';
+
+export const analyzeCurrencyInData = (
+ data: RowData[],
+ currencyColumn: string | undefined,
+): string | null => {
+ if (!currencyColumn || !data || data.length === 0) {
+ return null;
+ }
+
+ const currencies: RowDataValue[] = data
+ .map(row => row[currencyColumn])
+ .filter(val => val !== null && val !== undefined);
+
+ if (currencies.length === 0) {
+ return null;
+ }
+
+ if (hasMixedCurrencies(currencies)) {
+ return null;
+ }
+
+ return normalizeCurrency(currencies[0]);
+};
+
+export const resolveAutoCurrency = (
+ currencyFormat: Currency | undefined,
+ backendDetected: string | null | undefined,
+ data?: RowData[],
+ currencyCodeColumn?: string,
+): Currency | undefined | null => {
+ if (currencyFormat?.symbol !== AUTO_CURRENCY_SYMBOL) return currencyFormat;
+
+ const detectedCurrency =
+ backendDetected ??
+ (data && currencyCodeColumn
+ ? analyzeCurrencyInData(data, currencyCodeColumn)
+ : null);
+
+ if (detectedCurrency) {
+ return {
+ symbol: detectedCurrency,
+ symbolPosition: currencyFormat.symbolPosition,
+ };
+ }
+ return null; // Mixed currencies
+};
+
+const getEffectiveCurrencyFormat = (
+ resolvedCurrencyFormat: Currency | undefined | null,
+ savedFormat: Currency | undefined,
+): Currency | undefined => {
+ if (resolvedCurrencyFormat === null) {
+ return undefined;
+ }
+ if (resolvedCurrencyFormat?.symbol) {
+ return resolvedCurrencyFormat;
+ }
+ return savedFormat;
+};
export const buildCustomFormatters = (
metrics: QueryFormMetric | QueryFormMetric[] | undefined,
savedCurrencyFormats: Record<string, Currency>,
savedColumnFormats: Record<string, string>,
d3Format: string | undefined,
- currencyFormat: Currency | undefined,
+ currencyFormat: Currency | undefined | null,
+ data?: RowData[],
+ currencyCodeColumn?: string,
) => {
const metricsArray = ensureIsArray(metrics);
+
+ let resolvedCurrencyFormat = currencyFormat;
+ if (
+ currencyFormat?.symbol === AUTO_CURRENCY_SYMBOL &&
+ data &&
+ currencyCodeColumn
+ ) {
+ const detectedCurrency = analyzeCurrencyInData(data, currencyCodeColumn);
+ if (detectedCurrency) {
+ resolvedCurrencyFormat = {
+ symbol: detectedCurrency,
+ symbolPosition: currencyFormat.symbolPosition,
+ };
+ } else {
+ resolvedCurrencyFormat = null;
+ }
+ }
+
return metricsArray.reduce((acc, metric) => {
if (isSavedMetric(metric)) {
const actualD3Format = d3Format ?? savedColumnFormats[metric];
- const actualCurrencyFormat = currencyFormat?.symbol
- ? currencyFormat
- : savedCurrencyFormats[metric];
+ const actualCurrencyFormat = getEffectiveCurrencyFormat(
+ resolvedCurrencyFormat,
+ savedCurrencyFormats[metric],
+ );
return actualCurrencyFormat?.symbol
? {
...acc,
@@ -76,14 +159,40 @@ export const getValueFormatter = (
d3Format: string | undefined,
currencyFormat: Currency | undefined,
key?: string,
+ data?: RowData[],
+ currencyCodeColumn?: string,
+ detectedCurrency?: string | null,
) => {
+ let resolvedCurrencyFormat: Currency | undefined | null = currencyFormat;
+ if (currencyFormat?.symbol === AUTO_CURRENCY_SYMBOL) {
+ // Use backend-detected currency, or fallback to frontend analysis
+ if (detectedCurrency !== undefined) {
+ resolvedCurrencyFormat = detectedCurrency
+ ? {
+ symbol: detectedCurrency,
+ symbolPosition: currencyFormat.symbolPosition,
+ }
+ : null;
+ } else if (data && currencyCodeColumn) {
+ const frontendDetected = analyzeCurrencyInData(data, currencyCodeColumn);
+ resolvedCurrencyFormat = frontendDetected
+ ? {
+ symbol: frontendDetected,
+ symbolPosition: currencyFormat.symbolPosition,
+ }
+ : null;
+ } else {
+ resolvedCurrencyFormat = null;
+ }
+ }
+
const customFormatter = getCustomFormatter(
buildCustomFormatters(
metrics,
savedCurrencyFormats,
savedColumnFormats,
d3Format,
- currencyFormat,
+ resolvedCurrencyFormat,
),
metrics,
key,
@@ -92,8 +201,14 @@ export const getValueFormatter = (
if (customFormatter) {
return customFormatter;
}
- if (currencyFormat?.symbol) {
- return new CurrencyFormatter({ currency: currencyFormat, d3Format });
+ if (resolvedCurrencyFormat === null) {
+ return getNumberFormatter(d3Format);
+ }
+ if (resolvedCurrencyFormat?.symbol) {
+ return new CurrencyFormatter({
+ currency: resolvedCurrencyFormat,
+ d3Format,
+ });
}
return getNumberFormatter(d3Format);
};
diff --git a/superset-frontend/packages/superset-ui-core/src/query/types/Datasource.ts b/superset-frontend/packages/superset-ui-core/src/query/types/Datasource.ts
index c5ce93c1e9..47902cf07a 100644
--- a/superset-frontend/packages/superset-ui-core/src/query/types/Datasource.ts
+++ b/superset-frontend/packages/superset-ui-core/src/query/types/Datasource.ts
@@ -53,6 +53,7 @@ export interface Datasource {
verboseMap?: {
[key: string]: string;
};
+ currencyCodeColumn?: string;
}
export const DEFAULT_METRICS: Metric[] = [
diff --git a/superset-frontend/packages/superset-ui-core/src/query/types/QueryResponse.ts b/superset-frontend/packages/superset-ui-core/src/query/types/QueryResponse.ts
index 71aef8a75c..a1786da738 100644
--- a/superset-frontend/packages/superset-ui-core/src/query/types/QueryResponse.ts
+++ b/superset-frontend/packages/superset-ui-core/src/query/types/QueryResponse.ts
@@ -77,6 +77,12 @@ export interface ChartDataResponseResult {
// TODO(hainenber): define proper type for below attributes
rejected_filters?: any[];
applied_filters?: any[];
+ /**
+ * Detected ISO 4217 currency code when AUTO mode is used.
+ * Returns the currency code if all filtered data contains a single currency,
+ * or null if multiple currencies are present.
+ */
+ detected_currency?: string | null;
}
export interface TimeseriesChartDataResponseResult extends ChartDataResponseResult {
diff --git a/superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.test.ts b/superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.test.ts
index 8f15886576..979c4c1d61 100644
--- a/superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.test.ts
+++ b/superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.test.ts
@@ -156,3 +156,34 @@ test('CurrencyFormatter:format', () => {
});
expect(currencyFormatterWithCurrencyD3(VALUE)).toEqual('56,100,057.0 PLN');
});
+
+test('CurrencyFormatter AUTO mode uses row context', () => {
+ const formatter = new CurrencyFormatter({
+ currency: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ d3Format: ',.2f',
+ });
+
+ const row = { currency: 'EUR' };
+ expect(formatter.format(1000, row, 'currency')).toContain('€');
+ expect(formatter.format(1000)).toBe('1,000.00');
+});
+
+test('CurrencyFormatter static mode ignores row context', () => {
+ const formatter = new CurrencyFormatter({
+ currency: { symbol: 'USD', symbolPosition: 'prefix' },
+ d3Format: ',.2f',
+ });
+
+ const row = { currency: 'EUR' };
+ expect(formatter.format(1000, row, 'currency')).toContain('$');
+});
+
+test('CurrencyFormatter gracefully handles invalid currency code', () => {
+ const formatter = new CurrencyFormatter({
+ currency: { symbol: 'INVALID_CODE', symbolPosition: 'prefix' },
+ d3Format: ',.2f',
+ });
+
+ // Should not throw, should return formatted value without currency symbol
+ expect(formatter.format(1000)).toBe('1,000.00');
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/test/currency-format/analyzeCurrencyInData.test.ts
similarity index 56%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/packages/superset-ui-core/test/currency-format/analyzeCurrencyInData.test.ts
index 45fa851e88..ababbf4447 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/test/currency-format/analyzeCurrencyInData.test.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -16,7 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
+import { analyzeCurrencyInData } from '../../src/currency-format/utils';
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+test('analyzeCurrencyInData returns currency code for single currency', () => {
+ const data = [
+ { currency_code: 'USD', value: 100 },
+ { currency_code: 'usd', value: 200 },
+ ];
+ expect(analyzeCurrencyInData(data, 'currency_code')).toBe('USD');
+});
+
+test('analyzeCurrencyInData returns null for mixed or invalid data', () => {
+ expect(analyzeCurrencyInData([], 'currency_code')).toBeNull();
+ expect(analyzeCurrencyInData([{ c: 'USD' }], undefined)).toBeNull();
+ expect(analyzeCurrencyInData([{ c: 'USD' }, { c: 'EUR' }], 'c')).toBeNull();
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/test/currency-format/hasMixedCurrencies.test.ts
similarity index 59%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/packages/superset-ui-core/test/currency-format/hasMixedCurrencies.test.ts
index 45fa851e88..1cdd9eda16 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/test/currency-format/hasMixedCurrencies.test.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -17,6 +17,16 @@
* under the License.
*/
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+import { hasMixedCurrencies } from '../../src/currency-format/CurrencyFormatter';
+
+test('hasMixedCurrencies detects mixed vs single currency', () => {
+ expect(hasMixedCurrencies(['USD', 'EUR'])).toBe(true);
+ expect(hasMixedCurrencies(['USD', 'usd'])).toBe(false);
+ expect(hasMixedCurrencies(['USD'])).toBe(false);
+ expect(hasMixedCurrencies([])).toBe(false);
+});
+
+test('hasMixedCurrencies ignores null values', () => {
+ expect(hasMixedCurrencies(['USD', null, 'USD'])).toBe(false);
+ expect(hasMixedCurrencies(['USD', null, 'EUR'])).toBe(true);
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/packages/superset-ui-core/test/currency-format/normalizeCurrency.test.ts
similarity index 57%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/packages/superset-ui-core/test/currency-format/normalizeCurrency.test.ts
index 45fa851e88..9048a9bb04 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/packages/superset-ui-core/test/currency-format/normalizeCurrency.test.ts
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -17,6 +17,18 @@
* under the License.
*/
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+import { normalizeCurrency } from '../../src/currency-format/CurrencyFormatter';
+
+test('normalizeCurrency normalizes valid ISO 4217 codes', () => {
+ expect(normalizeCurrency('USD')).toBe('USD');
+ expect(normalizeCurrency('usd')).toBe('USD');
+ expect(normalizeCurrency(' eur ')).toBe('EUR');
+});
+
+test('normalizeCurrency returns null for invalid input', () => {
+ expect(normalizeCurrency(null)).toBe(null);
+ expect(normalizeCurrency('')).toBe(null);
+ expect(normalizeCurrency('$')).toBe(null);
+ expect(normalizeCurrency('DOLLAR')).toBe(null);
+ expect(normalizeCurrency('USDD')).toBe(null);
+});
diff --git a/superset-frontend/plugins/legacy-plugin-chart-world-map/src/transformProps.js b/superset-frontend/plugins/legacy-plugin-chart-world-map/src/transformProps.js
index 4069e29428..92be0f8b01 100644
--- a/superset-frontend/plugins/legacy-plugin-chart-world-map/src/transformProps.js
+++ b/superset-frontend/plugins/legacy-plugin-chart-world-map/src/transformProps.js
@@ -47,7 +47,12 @@ export default function transformProps(chartProps) {
currencyFormat,
} = formData;
const { r, g, b } = colorPicker;
- const { currencyFormats = {}, columnFormats = {} } = datasource;
+ const {
+ currencyFormats = {},
+ columnFormats = {},
+ currencyCodeColumn,
+ } = datasource;
+ const { data, detected_currency: detectedCurrency } = queriesData[0];
const formatter = getValueFormatter(
metric,
@@ -55,12 +60,16 @@ export default function transformProps(chartProps) {
columnFormats,
yAxisFormat,
currencyFormat,
+ undefined, // key - not needed for single-metric charts
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
return {
countryFieldtype,
entity,
- data: queriesData[0].data,
+ data,
width,
height,
maxBubbleSize: parseInt(maxBubbleSize, 10),
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
index 647b6b1aed..b610d5b35d 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
@@ -82,7 +82,11 @@ export default function transformProps(chartProps: ChartProps) {
height,
formData,
queriesData,
- datasource: { currencyFormats = {}, columnFormats = {} },
+ datasource: {
+ currencyFormats = {},
+ columnFormats = {},
+ currencyCodeColumn,
+ },
} = chartProps;
const {
boldText,
@@ -100,7 +104,8 @@ export default function transformProps(chartProps: ChartProps) {
subtitleFontSize,
columnConfig = {},
} = formData;
- const { data: dataA = [] } = queriesData[0];
+ const { data: dataA = [], detected_currency: detectedCurrency } =
+ queriesData[0] || {};
const data = dataA;
const metricName = metric ? getMetricLabel(metric) : '';
const metrics = chartProps.datasource?.metrics || [];
@@ -162,6 +167,10 @@ export default function transformProps(chartProps: ChartProps) {
columnFormats,
metricEntry?.d3format || yAxisFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const compTitles = {
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberTotal/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberTotal/transformProps.ts
index 6181ca23f6..ef9501fe9a 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberTotal/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberTotal/transformProps.ts
@@ -42,7 +42,11 @@ export default function transformProps(
formData,
rawFormData,
hooks,
- datasource: { currencyFormats = {}, columnFormats = {} },
+ datasource: {
+ currencyFormats = {},
+ columnFormats = {},
+ currencyCodeColumn,
+ },
theme,
} = chartProps;
const {
@@ -60,7 +64,11 @@ export default function transformProps(
subheaderFontSize,
} = formData;
const refs: Refs = {};
- const { data = [], coltypes = [] } = queriesData[0] || {};
+ const {
+ data = [],
+ coltypes = [],
+ detected_currency: detectedCurrency,
+ } = queriesData[0] || {};
const granularity = extractTimegrain(rawFormData as QueryFormData);
const metrics = chartProps.datasource?.metrics || [];
const originalLabel = getOriginalLabel(metric, metrics);
@@ -92,6 +100,10 @@ export default function transformProps(
columnFormats,
metricEntry?.d3format || yAxisFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const headerFormatter =
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.ts
index c9f18207d9..7b3337fdb1 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.ts
@@ -83,7 +83,11 @@ export default function transformProps(
hooks,
inContextMenu,
theme,
- datasource: { currencyFormats = {}, columnFormats = {} },
+ datasource: {
+ currencyFormats = {},
+ columnFormats = {},
+ currencyCodeColumn,
+ },
} = chartProps;
const {
colorPicker,
@@ -117,6 +121,7 @@ export default function transformProps(
coltypes = [],
from_dttm: fromDatetime,
to_dttm: toDatetime,
+ detected_currency: detectedCurrency,
} = queriesData[0];
const aggregatedQueryData = queriesData.length > 1 ? queriesData[1] : null;
@@ -259,6 +264,10 @@ export default function transformProps(
columnFormats,
metricEntry?.d3format || yAxisFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const xAxisFormatter = getXAxisFormatter(timeFormat);
const yAxisFormatter =
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/types.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/types.ts
index 394c7b1c18..e1f115c28b 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/types.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/types.ts
@@ -31,7 +31,7 @@ import { ColorFormatters } from '@superset-ui/chart-controls';
import { BaseChartProps, Refs } from '../types';
export interface BigNumberDatum {
- [key: string]: number | null;
+ [key: string]: number | string | null;
}
export type BigNumberTotalFormData = QueryFormData & {
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts
index 7245f67024..fd3cce40c0 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts
@@ -99,6 +99,7 @@ export default function transformProps(
datasource,
} = chartProps;
const data: DataRecord[] = queriesData[0].data || [];
+ const detectedCurrency = queriesData[0]?.detected_currency;
const coltypeMapping = getColtypesMapping(queriesData[0]);
const {
colorScheme,
@@ -127,7 +128,11 @@ export default function transformProps(
...DEFAULT_FUNNEL_FORM_DATA,
...formData,
};
- const { currencyFormats = {}, columnFormats = {} } = datasource;
+ const {
+ currencyFormats = {},
+ columnFormats = {},
+ currencyCodeColumn,
+ } = datasource;
const refs: Refs = {};
const metricLabel = getMetricLabel(metric);
const groupbyLabels = groupby.map(getColumnLabel);
@@ -154,6 +159,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const transformedData: {
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
index 79075b35db..cd4f2610f7 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
@@ -112,6 +112,7 @@ export default function transformProps(
verboseMap = {},
currencyFormats = {},
columnFormats = {},
+ currencyCodeColumn,
} = datasource;
const {
groupby,
@@ -139,6 +140,7 @@ export default function transformProps(
}: EchartsGaugeFormData = { ...DEFAULT_GAUGE_FORM_DATA, ...formData };
const refs: Refs = {};
const data = (queriesData[0]?.data || []) as DataRecord[];
+ const detectedCurrency = queriesData[0]?.detected_currency;
const coltypeMapping = getColtypesMapping(queriesData[0]);
const numberFormatter = getValueFormatter(
metric,
@@ -146,6 +148,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const colorFn = CategoricalColorNamespace.getScale(colorScheme as string);
const axisLineWidth = calculateAxisLineWidth(data, fontSize, overlap);
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Heatmap/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Heatmap/transformProps.ts
index 211b1170c6..118082015c 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Heatmap/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Heatmap/transformProps.ts
@@ -201,8 +201,17 @@ export default function transformProps(
const xAxisLabel = getColumnLabel(xAxis);
// groupby is overridden to be a single value
const yAxisLabel = getColumnLabel(groupby as unknown as QueryFormColumn);
- const { data, colnames, coltypes } = queriesData[0];
- const { columnFormats = {}, currencyFormats = {} } = datasource;
+ const {
+ data,
+ colnames,
+ coltypes,
+ detected_currency: detectedCurrency,
+ } = queriesData[0];
+ const {
+ columnFormats = {},
+ currencyFormats = {},
+ currencyCodeColumn,
+ } = datasource;
const colorColumn = normalized ? 'rank' : metricLabel;
const colors = getSequentialSchemeRegistry().get(linearColorScheme)?.colors;
const getAxisFormatter =
@@ -225,6 +234,10 @@ export default function transformProps(
columnFormats,
yAxisFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
let [min, max] = (valueBounds || []).map(parseAxisBound);
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
index b25245fd9b..ebc13fcb39 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
@@ -36,6 +36,7 @@ import {
isTimeseriesAnnotationLayer,
QueryFormData,
QueryFormMetric,
+ resolveAutoCurrency,
TimeseriesChartDataResponseResult,
TimeseriesDataRecord,
tooltipHtml,
@@ -138,10 +139,11 @@ export default function transformProps(
verboseMap = {},
currencyFormats = {},
columnFormats = {},
+ currencyCodeColumn,
} = datasource;
- const { label_map: labelMap } =
+ const { label_map: labelMap, detected_currency: backendDetectedCurrency } =
queriesData[0] as TimeseriesChartDataResponseResult;
- const { label_map: labelMapB } =
+ const { label_map: labelMapB, detected_currency: backendDetectedCurrencyB } =
queriesData[1] as TimeseriesChartDataResponseResult;
const data1 = (queriesData[0].data || []) as TimeseriesDataRecord[];
const data2 = (queriesData[1].data || []) as TimeseriesDataRecord[];
@@ -279,20 +281,34 @@ export default function transformProps(
xAxisType,
});
const series: SeriesOption[] = [];
+
+ const resolvedCurrency = resolveAutoCurrency(
+ currencyFormat,
+ backendDetectedCurrency,
+ data1,
+ currencyCodeColumn,
+ );
+ const resolvedCurrencySecondary = resolveAutoCurrency(
+ currencyFormatSecondary,
+ backendDetectedCurrencyB,
+ data2,
+ currencyCodeColumn,
+ );
+
const formatter = contributionMode
? getNumberFormatter(',.0%')
- : currencyFormat?.symbol
+ : resolvedCurrency?.symbol
? new CurrencyFormatter({
d3Format: yAxisFormat,
- currency: currencyFormat,
+ currency: resolvedCurrency,
})
: getNumberFormatter(yAxisFormat);
const formatterSecondary = contributionMode
? getNumberFormatter(',.0%')
- : currencyFormatSecondary?.symbol
+ : resolvedCurrencySecondary?.symbol
? new CurrencyFormatter({
d3Format: yAxisFormatSecondary,
- currency: currencyFormatSecondary,
+ currency: resolvedCurrencySecondary,
})
: getNumberFormatter(yAxisFormatSecondary);
const customFormatters = buildCustomFormatters(
@@ -300,14 +316,18 @@ export default function transformProps(
currencyFormats,
columnFormats,
yAxisFormat,
- currencyFormat,
+ resolvedCurrency,
+ data1,
+ currencyCodeColumn,
);
const customFormattersSecondary = buildCustomFormatters(
[...ensureIsArray(metrics), ...ensureIsArray(metricsB)],
currencyFormats,
columnFormats,
yAxisFormatSecondary,
- currencyFormatSecondary,
+ resolvedCurrencySecondary,
+ data2,
+ currencyCodeColumn,
);
const primarySeries = new Set<string>();
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts
index fa2972383a..d33110f6ab 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Pie/transformProps.ts
@@ -135,8 +135,13 @@ export default function transformProps(
emitCrossFilters,
datasource,
} = chartProps;
- const { columnFormats = {}, currencyFormats = {} } = datasource;
- const { data: rawData = [] } = queriesData[0];
+ const {
+ columnFormats = {},
+ currencyFormats = {},
+ currencyCodeColumn,
+ } = datasource;
+ const { data: rawData = [], detected_currency: detectedCurrency } =
+ queriesData[0];
const coltypeMapping = getColtypesMapping(queriesData[0]);
const {
@@ -181,6 +186,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ rawData,
+ currencyCodeColumn,
+ detectedCurrency,
);
let data = rawData;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Sunburst/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Sunburst/transformProps.ts
index 6c5614e042..f1861ab558 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Sunburst/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Sunburst/transformProps.ts
@@ -170,7 +170,7 @@ export default function transformProps(
emitCrossFilters,
datasource,
} = chartProps;
- const { data = [] } = queriesData[0];
+ const { data = [], detected_currency: detectedCurrency } = queriesData[0];
const coltypeMapping = getColtypesMapping(queriesData[0]);
const {
groupby = [],
@@ -192,6 +192,7 @@ export default function transformProps(
currencyFormats = {},
columnFormats = {},
verboseMap = {},
+ currencyCodeColumn,
} = datasource;
const refs: Refs = {};
const primaryValueFormatter = getValueFormatter(
@@ -200,6 +201,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const secondaryValueFormatter = secondaryMetric
? getValueFormatter(
@@ -208,6 +213,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
)
: undefined;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
index d1675454fe..fe37eea027 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
@@ -37,6 +37,7 @@ import {
isIntervalAnnotationLayer,
isPhysicalColumn,
isTimeseriesAnnotationLayer,
+ resolveAutoCurrency,
TimeseriesChartDataResponseResult,
NumberFormats,
} from '@superset-ui/core';
@@ -134,10 +135,14 @@ export default function transformProps(
verboseMap = {},
columnFormats = {},
currencyFormats = {},
+ currencyCodeColumn,
} = datasource;
const [queryData] = queriesData;
- const { data = [], label_map = {} } =
- queryData as TimeseriesChartDataResponseResult;
+ const {
+ data = [],
+ label_map = {},
+ detected_currency: backendDetectedCurrency,
+ } = queryData as TimeseriesChartDataResponseResult;
const dataTypes = getColtypesMapping(queryData);
const annotationData = getAnnotationData(chartProps);
@@ -275,15 +280,29 @@ export default function transformProps(
const percentFormatter = forcePercentFormatter
? getPercentFormatter(yAxisFormat)
: getPercentFormatter(NumberFormats.PERCENT_2_POINT);
- const defaultFormatter = currencyFormat?.symbol
- ? new CurrencyFormatter({ d3Format: yAxisFormat, currency: currencyFormat })
+
+ // Resolve currency for AUTO mode (backend detection takes precedence)
+ const resolvedCurrency = resolveAutoCurrency(
+ currencyFormat,
+ backendDetectedCurrency,
+ data,
+ currencyCodeColumn,
+ );
+
+ const defaultFormatter = resolvedCurrency?.symbol
+ ? new CurrencyFormatter({
+ d3Format: yAxisFormat,
+ currency: resolvedCurrency,
+ })
: getNumberFormatter(yAxisFormat);
const customFormatters = buildCustomFormatters(
metrics,
currencyFormats,
columnFormats,
yAxisFormat,
- currencyFormat,
+ resolvedCurrency,
+ data,
+ currencyCodeColumn,
);
const array = ensureIsArray(chartProps.rawFormData?.time_compare);
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts
index 5ed0c565c3..e4fe3053ee 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts
@@ -119,8 +119,12 @@ export default function transformProps(
emitCrossFilters,
datasource,
} = chartProps;
- const { data = [] } = queriesData[0];
- const { columnFormats = {}, currencyFormats = {} } = datasource;
+ const { data = [], detected_currency: detectedCurrency } = queriesData[0];
+ const {
+ columnFormats = {},
+ currencyFormats = {},
+ currencyCodeColumn,
+ } = datasource;
const { setDataMask = () => {}, onContextMenu } = hooks;
const coltypeMapping = getColtypesMapping(queriesData[0]);
const BORDER_COLOR = theme.colorBgBase;
@@ -150,6 +154,10 @@ export default function transformProps(
columnFormats,
numberFormat,
currencyFormat,
+ undefined,
+ data,
+ currencyCodeColumn,
+ detectedCurrency,
);
const formatter = (params: TreemapSeriesCallbackDataParams) =>
diff --git a/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
index fc0b979e20..cd1b00100e 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
@@ -492,3 +492,59 @@ describe('BigNumberWithTrendline - Aggregation Tests', () => {
expect(transformed.bigNumber).toStrictEqual(10);
});
});
+
+test('BigNumberWithTrendline AUTO mode should detect single currency', () => {
+ const props = generateProps(
+ [
+ { __timestamp: 1607558400000, value: 1000, currency_code: 'USD' },
+ { __timestamp: 1607558500000, value: 2000, currency_code: 'USD' },
+ ],
+ {
+ yAxisFormat: ',.2f',
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ },
+ );
+ props.datasource.currencyCodeColumn = 'currency_code';
+
+ const transformed = transformProps(props);
+ // The headerFormatter should include $ for USD
+ expect(transformed.headerFormatter(1000)).toContain('$');
+});
+
+test('BigNumberWithTrendline AUTO mode should use neutral formatting for mixed currencies', () => {
+ const props = generateProps(
+ [
+ { __timestamp: 1607558400000, value: 1000, currency_code: 'USD' },
+ { __timestamp: 1607558500000, value: 2000, currency_code: 'EUR' },
+ ],
+ {
+ yAxisFormat: ',.2f',
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ },
+ );
+ props.datasource.currencyCodeColumn = 'currency_code';
+
+ const transformed = transformProps(props);
+ // With mixed currencies, should not show currency symbol
+ const formatted = transformed.headerFormatter(1000);
+ expect(formatted).not.toContain('$');
+ expect(formatted).not.toContain('€');
+});
+
+test('BigNumberWithTrendline should preserve static currency format', () => {
+ const props = generateProps(
+ [
+ { __timestamp: 1607558400000, value: 1000, currency_code: 'USD' },
+ { __timestamp: 1607558500000, value: 2000, currency_code: 'EUR' },
+ ],
+ {
+ yAxisFormat: ',.2f',
+ currencyFormat: { symbol: 'GBP', symbolPosition: 'prefix' },
+ },
+ );
+ props.datasource.currencyCodeColumn = 'currency_code';
+
+ const transformed = transformProps(props);
+ // Static mode should always show £
+ expect(transformed.headerFormatter(1000)).toContain('£');
+});
diff --git a/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts
index 42ecb1803d..b3ecf9a7ab 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts
@@ -31,6 +31,20 @@ import { supersetTheme } from '@apache-superset/core/ui';
import { EchartsTimeseriesChartProps } from '../../src/types';
import transformProps from '../../src/Timeseries/transformProps';
+type YAxisFormatter = (value: number, index: number) => string;
+
+function getYAxisFormatter(
+ transformed: ReturnType<typeof transformProps>,
+): YAxisFormatter {
+ const yAxis = transformed.echartOptions.yAxis as {
+ axisLabel?: { formatter?: YAxisFormatter };
+ };
+ expect(yAxis).toBeDefined();
+ expect(yAxis.axisLabel).toBeDefined();
+ expect(yAxis.axisLabel?.formatter).toBeDefined();
+ return yAxis.axisLabel!.formatter!;
+}
+
const formData: SqlaFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
@@ -723,3 +737,121 @@ describe('legend sorting', () => {
]);
});
});
+
+test('EchartsTimeseries AUTO mode should detect single currency and format with $ for USD', () => {
+ const chartProps = new ChartProps<SqlaFormData>({
+ ...chartPropsConfig,
+ formData: {
+ ...formData,
+ metrics: ['sum__num'],
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ },
+ datasource: {
+ currencyCodeColumn: 'currency_code',
+ columnFormats: {},
+ currencyFormats: {},
+ verboseMap: {},
+ },
+ queriesData: [
+ {
+ data: [
+ {
+ 'San Francisco': 1000,
+ __timestamp: 599616000000,
+ currency_code: 'USD',
+ },
+ {
+ 'San Francisco': 2000,
+ __timestamp: 599916000000,
+ currency_code: 'USD',
+ },
+ ],
+ },
+ ],
+ });
+
+ const transformed = transformProps(chartProps as EchartsTimeseriesChartProps);
+
+ const formatter = getYAxisFormatter(transformed);
+ expect(formatter(1000, 0)).toContain('$');
+});
+
+test('EchartsTimeseries AUTO mode should use neutral formatting for mixed currencies', () => {
+ const chartProps = new ChartProps<SqlaFormData>({
+ ...chartPropsConfig,
+ formData: {
+ ...formData,
+ metrics: ['sum__num'],
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ },
+ datasource: {
+ currencyCodeColumn: 'currency_code',
+ columnFormats: {},
+ currencyFormats: {},
+ verboseMap: {},
+ },
+ queriesData: [
+ {
+ data: [
+ {
+ 'San Francisco': 1000,
+ __timestamp: 599616000000,
+ currency_code: 'USD',
+ },
+ {
+ 'San Francisco': 2000,
+ __timestamp: 599916000000,
+ currency_code: 'EUR',
+ },
+ ],
+ },
+ ],
+ });
+
+ const transformed = transformProps(chartProps as EchartsTimeseriesChartProps);
+
+ // With mixed currencies, Y-axis should use neutral formatting
+ const formatter = getYAxisFormatter(transformed);
+ const formatted = formatter(1000, 0);
+ expect(formatted).not.toContain('$');
+ expect(formatted).not.toContain('€');
+});
+
+test('EchartsTimeseries should preserve static currency format with £ for GBP', () => {
+ const chartProps = new ChartProps<SqlaFormData>({
+ ...chartPropsConfig,
+ formData: {
+ ...formData,
+ metrics: ['sum__num'],
+ currencyFormat: { symbol: 'GBP', symbolPosition: 'prefix' },
+ },
+ datasource: {
+ currencyCodeColumn: 'currency_code',
+ columnFormats: {},
+ currencyFormats: {},
+ verboseMap: {},
+ },
+ queriesData: [
+ {
+ data: [
+ {
+ 'San Francisco': 1000,
+ __timestamp: 599616000000,
+ currency_code: 'USD',
+ },
+ {
+ 'San Francisco': 2000,
+ __timestamp: 599916000000,
+ currency_code: 'EUR',
+ },
+ ],
+ },
+ ],
+ });
+
+ const transformed = transformProps(chartProps as EchartsTimeseriesChartProps);
+
+ // Static mode should always show £
+ const formatter = getYAxisFormatter(transformed);
+ expect(formatter(1000, 0)).toContain('£');
+});
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx b/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
index 09e62069fc..1c2f5cbc05 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
@@ -22,15 +22,18 @@ import { t } from '@apache-superset/core';
import {
AdhocMetric,
BinaryQueryObjectFilterClause,
+ Currency,
CurrencyFormatter,
DataRecordValue,
FeatureFlag,
getColumnLabel,
getNumberFormatter,
getSelectedText,
+ hasMixedCurrencies,
isAdhocColumn,
isFeatureEnabled,
isPhysicalColumn,
+ normalizeCurrency,
NumberFormatter,
} from '@superset-ui/core';
import { styled, useTheme } from '@apache-superset/core/ui';
@@ -101,6 +104,71 @@ const StyledMinusSquareOutlined = styled(MinusSquareOutlined)`
stroke-width: 16px;
`;
+/** Aggregator with currency tracking support */
+interface CurrencyTrackingAggregator {
+ getCurrencies?: () => string[];
+}
+
+type BaseFormatter = NumberFormatter | CurrencyFormatter;
+
+/** Create formatter that handles AUTO mode with per-cell currency detection */
+const createCurrencyAwareFormatter = (
+ baseFormatter: BaseFormatter,
+ currencyConfig: Currency | undefined,
+ d3Format: string,
+ fallbackCurrency?: string,
+): ((value: number, aggregator?: CurrencyTrackingAggregator) => string) => {
+ const isAutoMode = currencyConfig?.symbol === 'AUTO';
+
+ return (value: number, aggregator?: CurrencyTrackingAggregator): string => {
+ // If not AUTO mode, use base formatter directly
+ if (!isAutoMode) {
+ return baseFormatter(value);
+ }
+
+ // AUTO mode: check aggregator for currency tracking
+ if (aggregator && typeof aggregator.getCurrencies === 'function') {
+ const currencies = aggregator.getCurrencies();
+
+ if (currencies && currencies.length > 0) {
+ if (hasMixedCurrencies(currencies)) {
+ return getNumberFormatter(d3Format)(value);
+ }
+
+ const detectedCurrency = normalizeCurrency(currencies[0]);
+ if (detectedCurrency && currencyConfig) {
+ const cellFormatter = new CurrencyFormatter({
+ currency: {
+ symbol: detectedCurrency,
+ symbolPosition: currencyConfig.symbolPosition,
+ },
+ d3Format,
+ });
+ return cellFormatter(value);
+ }
+ }
+ }
+
+ // Fallback: use detected_currency from API response if available
+ if (fallbackCurrency && currencyConfig) {
+ const normalizedFallback = normalizeCurrency(fallbackCurrency);
+ if (normalizedFallback) {
+ const fallbackFormatter = new CurrencyFormatter({
+ currency: {
+ symbol: normalizedFallback,
+ symbolPosition: currencyConfig.symbolPosition,
+ },
+ d3Format,
+ });
+ return fallbackFormatter(value);
+ }
+ }
+
+ // Final fallback to neutral format
+ return getNumberFormatter(d3Format)(value);
+ };
+};
+
const aggregatorsFactory = (formatter: NumberFormatter) => ({
Count: aggregatorTemplates.count(formatter),
'Count Unique Values': aggregatorTemplates.countUnique(formatter),
@@ -171,6 +239,8 @@ export default function PivotTableChart(props: PivotTableProps) {
rowSubTotals,
valueFormat,
currencyFormat,
+ currencyCodeColumn,
+ detectedCurrency,
emitCrossFilters,
setDataMask,
selectedFilters,
@@ -186,9 +256,11 @@ export default function PivotTableChart(props: PivotTableProps) {
} = props;
const theme = useTheme();
- const defaultFormatter = useMemo(
+
+ // Base formatter without currency-awareness (for non-AUTO mode or as fallback)
+ const baseFormatter = useMemo(
() =>
- currencyFormat?.symbol
+ currencyFormat?.symbol && currencyFormat.symbol !== 'AUTO'
? new CurrencyFormatter({
currency: currencyFormat,
d3Format: valueFormat,
@@ -196,6 +268,18 @@ export default function PivotTableChart(props: PivotTableProps) {
: getNumberFormatter(valueFormat),
[valueFormat, currencyFormat],
);
+
+ // Currency-aware formatter for AUTO mode support
+ const defaultFormatter = useMemo(
+ () =>
+ createCurrencyAwareFormatter(
+ baseFormatter,
+ currencyFormat,
+ valueFormat,
+ detectedCurrency ?? undefined,
+ ),
+ [baseFormatter, currencyFormat, valueFormat, detectedCurrency],
+ );
const customFormatsArray = useMemo(
() =>
Array.from(
@@ -216,19 +300,31 @@ export default function PivotTableChart(props: PivotTableProps) {
hasCustomMetricFormatters
? {
[METRIC_KEY]: Object.fromEntries(
- customFormatsArray.map(([metric, d3Format, currency]) => [
- metric,
- currency
- ? new CurrencyFormatter({
- currency,
- d3Format,
- })
- : getNumberFormatter(d3Format),
- ]),
+ customFormatsArray.map(([metric, d3Format, currency]) => {
+ // Create base formatter
+ const metricBaseFormatter =
+ currency && (currency as Currency).symbol !== 'AUTO'
+ ? new CurrencyFormatter({
+ currency: currency as Currency,
+ d3Format: d3Format as string,
+ })
+ : getNumberFormatter(d3Format as string);
+
+ // Wrap with currency-aware formatter for AUTO mode support
+ return [
+ metric,
+ createCurrencyAwareFormatter(
+ metricBaseFormatter,
+ currency as Currency | undefined,
+ d3Format as string,
+ detectedCurrency ?? undefined,
+ ),
+ ];
+ }),
),
}
: undefined,
- [customFormatsArray, hasCustomMetricFormatters],
+ [customFormatsArray, hasCustomMetricFormatters, detectedCurrency],
);
const metricNames = useMemo(
@@ -249,12 +345,14 @@ export default function PivotTableChart(props: PivotTableProps) {
...record,
[METRIC_KEY]: name,
value: record[name],
+ // Mark currency column for per-cell currency detection in aggregators
+ __currencyColumn: currencyCodeColumn,
}))
.filter(record => record.value !== null),
],
[],
),
- [data, metricNames],
+ [data, metricNames, currencyCodeColumn],
);
const groupbyRows = useMemo(
() => groupbyRowsRaw.map(getColumnLabel),
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
index 9d5339a4dd..847247a214 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
@@ -79,11 +79,21 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
rawFormData,
hooks: { setDataMask = () => {}, onContextMenu },
filterState,
- datasource: { verboseMap = {}, columnFormats = {}, currencyFormats = {} },
+ datasource: {
+ verboseMap = {},
+ columnFormats = {},
+ currencyFormats = {},
+ currencyCodeColumn,
+ },
emitCrossFilters,
theme,
} = chartProps;
- const { data, colnames, coltypes } = queriesData[0];
+ const {
+ data,
+ colnames,
+ coltypes,
+ detected_currency: detectedCurrency,
+ } = queriesData[0];
const {
groupbyRows,
groupbyColumns,
@@ -148,6 +158,8 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
theme,
);
+ // AUTO symbol passed through - PivotTableChart handles per-cell currency detection
+
return {
width,
height,
@@ -169,6 +181,8 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
rowSubTotals,
valueFormat,
currencyFormat,
+ currencyCodeColumn,
+ detectedCurrency,
emitCrossFilters,
setDataMask,
selectedFilters,
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx
index 13a983ecc3..5fefac2904 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx
@@ -749,7 +749,7 @@ export class TableRenderer extends Component {
onContextMenu={e => this.props.onContextMenu(e, colKey, rowKey)}
style={style}
>
- {displayCell(agg.format(aggValue), allowRenderHtml)}
+ {displayCell(agg.format(aggValue, agg), allowRenderHtml)}
</td>
);
});
@@ -766,7 +766,7 @@ export class TableRenderer extends Component {
onClick={rowTotalCallbacks[flatRowKey]}
onContextMenu={e => this.props.onContextMenu(e, undefined, rowKey)}
>
- {displayCell(agg.format(aggValue), allowRenderHtml)}
+ {displayCell(agg.format(aggValue, agg), allowRenderHtml)}
</td>
);
}
@@ -830,7 +830,7 @@ export class TableRenderer extends Component {
onContextMenu={e => this.props.onContextMenu(e, colKey, undefined)}
style={{ padding: '5px' }}
>
- {displayCell(agg.format(aggValue), this.props.allowRenderHtml)}
+ {displayCell(agg.format(aggValue, agg), this.props.allowRenderHtml)}
</td>
);
});
@@ -847,7 +847,7 @@ export class TableRenderer extends Component {
onClick={grandTotalCallback}
onContextMenu={e => this.props.onContextMenu(e, undefined, undefined)}
>
- {displayCell(agg.format(aggValue), this.props.allowRenderHtml)}
+ {displayCell(agg.format(aggValue, agg), this.props.allowRenderHtml)}
</td>
);
}
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js
index 17f33a7ea8..100f2defa0 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js
@@ -186,9 +186,13 @@ const usFmtPct = numberFormat({
suffix: '%',
});
-const fmtNonString = formatter => x =>
- typeof x === 'string' ? x : formatter(x);
+const fmtNonString = formatter => (x, aggregator) =>
+ typeof x === 'string' ? x : formatter(x, aggregator);
+/*
+ * Aggregators track currencies via push() and expose them via getCurrencies()
+ * for per-cell currency detection in AUTO mode.
+ */
const baseAggregatorTemplates = {
count(formatter = usFmtInt) {
return () =>
@@ -211,14 +215,21 @@ const baseAggregatorTemplates = {
return function () {
return {
uniq: [],
+ currencySet: new Set(),
push(record) {
if (!Array.from(this.uniq).includes(record[attr])) {
this.uniq.push(record[attr]);
}
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
return fn(this.uniq);
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format: fmtNonString(formatter),
numInputs: typeof attr !== 'undefined' ? 0 : 1,
};
@@ -231,16 +242,23 @@ const baseAggregatorTemplates = {
return function () {
return {
sum: 0,
+ currencySet: new Set(),
push(record) {
if (Number.isNaN(Number(record[attr]))) {
this.sum = record[attr];
} else {
this.sum += parseFloat(record[attr]);
}
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
return this.sum;
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format: fmtNonString(formatter),
numInputs: typeof attr !== 'undefined' ? 0 : 1,
};
@@ -253,6 +271,7 @@ const baseAggregatorTemplates = {
return function (data) {
return {
val: null,
+ currencySet: new Set(),
sorter: getSort(
typeof data !== 'undefined' ? data.sorters : null,
attr,
@@ -285,10 +304,16 @@ const baseAggregatorTemplates = {
) {
this.val = x;
}
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
return this.val;
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format(x) {
if (typeof x === 'number') {
return formatter(x);
@@ -307,6 +332,7 @@ const baseAggregatorTemplates = {
return {
vals: [],
strMap: {},
+ currencySet: new Set(),
push(record) {
const val = record[attr];
const x = Number(val);
@@ -316,6 +342,9 @@ const baseAggregatorTemplates = {
} else {
this.vals.push(x);
}
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
if (
@@ -339,6 +368,9 @@ const baseAggregatorTemplates = {
const i = (this.vals.length - 1) * q;
return (this.vals[Math.floor(i)] + this.vals[Math.ceil(i)]) / 2.0;
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format: fmtNonString(formatter),
numInputs: typeof attr !== 'undefined' ? 0 : 1,
};
@@ -354,11 +386,15 @@ const baseAggregatorTemplates = {
m: 0.0,
s: 0.0,
strValue: null,
+ currencySet: new Set(),
push(record) {
const x = Number(record[attr]);
if (Number.isNaN(x)) {
this.strValue =
typeof record[attr] === 'string' ? record[attr] : this.strValue;
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
return;
}
this.n += 1.0;
@@ -368,6 +404,9 @@ const baseAggregatorTemplates = {
const mNew = this.m + (x - this.m) / this.n;
this.s += (x - this.m) * (x - mNew);
this.m = mNew;
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
if (this.strValue) {
@@ -392,6 +431,9 @@ const baseAggregatorTemplates = {
throw new Error('unknown mode for runningStat');
}
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format: fmtNonString(formatter),
numInputs: typeof attr !== 'undefined' ? 0 : 1,
};
@@ -405,6 +447,7 @@ const baseAggregatorTemplates = {
return {
sumNum: 0,
sumDenom: 0,
+ currencySet: new Set(),
push(record) {
if (!Number.isNaN(Number(record[num]))) {
this.sumNum += parseFloat(record[num]);
@@ -412,10 +455,16 @@ const baseAggregatorTemplates = {
if (!Number.isNaN(Number(record[denom]))) {
this.sumDenom += parseFloat(record[denom]);
}
+ if (record.__currencyColumn && record[record.__currencyColumn]) {
+ this.currencySet.add(record[record.__currencyColumn]);
+ }
},
value() {
return this.sumNum / this.sumDenom;
},
+ getCurrencies() {
+ return Array.from(this.currencySet);
+ },
format: formatter,
numInputs:
typeof num !== 'undefined' && typeof denom !== 'undefined' ? 0 : 2,
@@ -447,6 +496,9 @@ const baseAggregatorTemplates = {
return this.inner.value() / acc;
},
+ getCurrencies() {
+ return this.inner.getCurrencies ? this.inner.getCurrencies() : [];
+ },
numInputs: wrapped(...Array.from(x || []))().numInputs,
};
};
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts b/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
index 83c4e76b86..d154031397 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
@@ -68,6 +68,8 @@ interface PivotTableCustomizeProps {
rowSubTotals: boolean;
valueFormat: string;
currencyFormat: Currency;
+ currencyCodeColumn?: string;
+ detectedCurrency?: string | null;
setDataMask: SetDataMaskHook;
emitCrossFilters?: boolean;
selectedFilters?: SelectedFiltersType;
diff --git a/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
index 9327dcffe8..7a6fa52f7d 100644
--- a/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
@@ -96,4 +96,193 @@ describe('PivotTableChart transformProps', () => {
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
});
});
+
+ describe('Per-cell currency detection (AUTO mode passes through)', () => {
+ it('should pass AUTO mode through for per-cell detection (single currency data)', () => {
+ const autoFormData = {
+ ...formData,
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ };
+ const autoChartProps = new ChartProps<QueryFormData>({
+ formData: autoFormData,
+ width: 800,
+ height: 600,
+ queriesData: [
+ {
+ data: [
+ { country: 'USA', currency: 'USD', revenue: 100 },
+ { country: 'Canada', currency: 'USD', revenue: 200 },
+ { country: 'Mexico', currency: 'usd', revenue: 150 },
+ ],
+ colnames: ['country', 'currency', 'revenue'],
+ coltypes: [1, 1, 0],
+ },
+ ],
+ hooks: { setDataMask },
+ filterState: { selectedFilters: {} },
+ datasource: {
+ verboseMap: {},
+ columnFormats: {},
+ currencyCodeColumn: 'currency',
+ },
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(autoChartProps);
+ // AUTO mode should be preserved for per-cell detection in PivotTableChart
+ expect(result.currencyFormat).toEqual({
+ symbol: 'AUTO',
+ symbolPosition: 'prefix',
+ });
+ // currencyCodeColumn should be passed through for per-cell detection
+ expect(result.currencyCodeColumn).toBe('currency');
+ });
+
+ it('should pass AUTO mode through for per-cell detection (mixed currency data)', () => {
+ const autoFormData = {
+ ...formData,
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ };
+ const autoChartProps = new ChartProps<QueryFormData>({
+ formData: autoFormData,
+ width: 800,
+ height: 600,
+ queriesData: [
+ {
+ data: [
+ { country: 'USA', currency: 'USD', revenue: 100 },
+ { country: 'UK', currency: 'GBP', revenue: 200 },
+ { country: 'France', currency: 'EUR', revenue: 150 },
+ ],
+ colnames: ['country', 'currency', 'revenue'],
+ coltypes: [1, 1, 0],
+ },
+ ],
+ hooks: { setDataMask },
+ filterState: { selectedFilters: {} },
+ datasource: {
+ verboseMap: {},
+ columnFormats: {},
+ currencyCodeColumn: 'currency',
+ },
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(autoChartProps);
+ // AUTO mode should be preserved - per-cell detection happens in PivotTableChart
+ expect(result.currencyFormat).toEqual({
+ symbol: 'AUTO',
+ symbolPosition: 'prefix',
+ });
+ expect(result.currencyCodeColumn).toBe('currency');
+ });
+
+ it('should pass AUTO mode through when no currency column is defined', () => {
+ const autoFormData = {
+ ...formData,
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ };
+ const autoChartProps = new ChartProps<QueryFormData>({
+ formData: autoFormData,
+ width: 800,
+ height: 600,
+ queriesData: [
+ {
+ data: [
+ { country: 'USA', revenue: 100 },
+ { country: 'UK', revenue: 200 },
+ ],
+ colnames: ['country', 'revenue'],
+ coltypes: [1, 0],
+ },
+ ],
+ hooks: { setDataMask },
+ filterState: { selectedFilters: {} },
+ datasource: {
+ verboseMap: {},
+ columnFormats: {},
+ // No currencyCodeColumn defined
+ },
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(autoChartProps);
+ expect(result.currencyFormat).toEqual({
+ symbol: 'AUTO',
+ symbolPosition: 'prefix',
+ });
+ // currencyCodeColumn should be undefined when not configured
+ expect(result.currencyCodeColumn).toBeUndefined();
+ });
+
+ it('should handle empty data gracefully in AUTO mode', () => {
+ const autoFormData = {
+ ...formData,
+ currencyFormat: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ };
+ const autoChartProps = new ChartProps<QueryFormData>({
+ formData: autoFormData,
+ width: 800,
+ height: 600,
+ queriesData: [
+ {
+ data: [],
+ colnames: ['country', 'currency', 'revenue'],
+ coltypes: [1, 1, 0],
+ },
+ ],
+ hooks: { setDataMask },
+ filterState: { selectedFilters: {} },
+ datasource: {
+ verboseMap: {},
+ columnFormats: {},
+ currencyCodeColumn: 'currency',
+ },
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(autoChartProps);
+ expect(result.currencyFormat).toEqual({
+ symbol: 'AUTO',
+ symbolPosition: 'prefix',
+ });
+ expect(result.currencyCodeColumn).toBe('currency');
+ });
+
+ it('should preserve static currency format when not using AUTO mode', () => {
+ const staticFormData = {
+ ...formData,
+ currencyFormat: { symbol: 'EUR', symbolPosition: 'suffix' },
+ };
+ const staticChartProps = new ChartProps<QueryFormData>({
+ formData: staticFormData,
+ width: 800,
+ height: 600,
+ queriesData: [
+ {
+ data: [
+ { country: 'USA', currency: 'USD', revenue: 100 },
+ { country: 'UK', currency: 'GBP', revenue: 200 },
+ ],
+ colnames: ['country', 'currency', 'revenue'],
+ coltypes: [1, 1, 0],
+ },
+ ],
+ hooks: { setDataMask },
+ filterState: { selectedFilters: {} },
+ datasource: {
+ verboseMap: {},
+ columnFormats: {},
+ currencyCodeColumn: 'currency',
+ },
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(staticChartProps);
+ expect(result.currencyFormat).toEqual({
+ symbol: 'EUR',
+ symbolPosition: 'suffix',
+ });
+ });
+ });
});
diff --git a/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx b/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
index a4c20bb8df..90d894d9a9 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
@@ -892,7 +892,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
columnKey: key,
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value, row }: { value: DataRecordValue; row: Row<D> }) => {
- const [isHtml, text] = formatColumnValue(column, value);
+ const [isHtml, text] = formatColumnValue(column, value, row.original);
const html = isHtml && allowRenderHtml ? { __html: text } : undefined;
let backgroundColor;
diff --git a/superset-frontend/plugins/plugin-chart-table/src/transformProps.ts b/superset-frontend/plugins/plugin-chart-table/src/transformProps.ts
index 0e80b9eb81..949d7410cc 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-table/src/transformProps.ts
@@ -29,6 +29,7 @@ import {
getNumberFormatter,
getTimeFormatter,
getTimeFormatterForGranularity,
+ normalizeCurrency,
NumberFormats,
QueryMode,
SMART_DATE_ID,
@@ -200,7 +201,12 @@ const processColumns = memoizeOne(function processColumns(
props: TableChartProps,
) {
const {
- datasource: { columnFormats, currencyFormats, verboseMap },
+ datasource: {
+ columnFormats,
+ currencyFormats,
+ verboseMap,
+ currencyCodeColumn,
+ },
rawFormData: {
table_timestamp_format: tableTimestampFormat,
metrics: metrics_,
@@ -210,7 +216,12 @@ const processColumns = memoizeOne(function processColumns(
queriesData,
} = props;
const granularity = extractTimegrain(props.rawFormData);
- const { data: records, colnames, coltypes } = queriesData[0] || {};
+ const {
+ data: records,
+ colnames,
+ coltypes,
+ detected_currency: detectedCurrency,
+ } = queriesData[0] || {};
// convert `metrics` and `percentMetrics` to the key names in `data.records`
const metrics = (metrics_ ?? []).map(getMetricLabel);
const rawPercentMetrics = (percentMetrics_ ?? []).map(getMetricLabel);
@@ -276,10 +287,25 @@ const processColumns = memoizeOne(function processColumns(
// percent metrics have a default format
formatter = getNumberFormatter(numberFormat || PERCENT_3_POINT);
} else if (isMetric || (isNumber && (numberFormat || currency))) {
- formatter = currency?.symbol
+ // Resolve AUTO currency when currency column isn't in query results
+ let resolvedCurrency = currency;
+ if (
+ currency?.symbol === 'AUTO' &&
+ detectedCurrency &&
+ (!currencyCodeColumn || !colnames?.includes(currencyCodeColumn))
+ ) {
+ const normalizedCurrency = normalizeCurrency(detectedCurrency);
+ if (normalizedCurrency) {
+ resolvedCurrency = {
+ ...currency,
+ symbol: normalizedCurrency,
+ };
+ }
+ }
+ formatter = resolvedCurrency?.symbol
? new CurrencyFormatter({
d3Format: numberFormat,
- currency,
+ currency: resolvedCurrency,
})
: getNumberFormatter(numberFormat);
}
@@ -292,6 +318,7 @@ const processColumns = memoizeOne(function processColumns(
isPercentMetric,
formatter,
config,
+ currencyCodeColumn,
};
});
return [metrics, percentMetrics, columns] as [
diff --git a/superset-frontend/plugins/plugin-chart-table/src/types.ts b/superset-frontend/plugins/plugin-chart-table/src/types.ts
index 2708e02e44..721c80dfbf 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/types.ts
+++ b/superset-frontend/plugins/plugin-chart-table/src/types.ts
@@ -72,6 +72,7 @@ export interface DataColumnMeta {
isNumeric?: boolean;
config?: TableColumnConfig;
isChildColumn?: boolean;
+ currencyCodeColumn?: string;
}
export interface TableChartData {
diff --git a/superset-frontend/plugins/plugin-chart-table/src/utils/formatValue.ts b/superset-frontend/plugins/plugin-chart-table/src/utils/formatValue.ts
index 7f067cd195..3769abe551 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/utils/formatValue.ts
+++ b/superset-frontend/plugins/plugin-chart-table/src/utils/formatValue.ts
@@ -33,6 +33,8 @@ import DateWithFormatter from './DateWithFormatter';
function formatValue(
formatter: DataColumnMeta['formatter'],
value: DataRecordValue,
+ rowData?: Record<string, DataRecordValue>,
+ currencyColumn?: string,
): [boolean, string] {
// render undefined as empty string
if (value === undefined) {
@@ -48,6 +50,10 @@ function formatValue(
return [false, 'N/A'];
}
if (formatter) {
+ // If formatter is a CurrencyFormatter, pass row context for AUTO mode
+ if (formatter instanceof CurrencyFormatter) {
+ return [false, formatter(value as number, rowData, currencyColumn)];
+ }
return [false, formatter(value as number)];
}
if (typeof value === 'string') {
@@ -59,8 +65,9 @@ function formatValue(
export function formatColumnValue(
column: DataColumnMeta,
value: DataRecordValue,
+ rowData?: Record<string, DataRecordValue>,
) {
- const { dataType, formatter, config = {} } = column;
+ const { dataType, formatter, config = {}, currencyCodeColumn } = column;
const isNumber = dataType === GenericDataType.Numeric;
const smallNumberFormatter =
config.d3SmallNumberFormat === undefined
@@ -76,5 +83,7 @@ export function formatColumnValue(
? smallNumberFormatter
: formatter,
value,
+ rowData,
+ currencyCodeColumn,
);
}
diff --git a/superset-frontend/plugins/plugin-chart-table/src/utils/isEqualColumns.ts b/superset-frontend/plugins/plugin-chart-table/src/utils/isEqualColumns.ts
index 28731c73c2..0643eaab68 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/utils/isEqualColumns.ts
+++ b/superset-frontend/plugins/plugin-chart-table/src/utils/isEqualColumns.ts
@@ -28,6 +28,7 @@ export default function isEqualColumns(
return (
a.datasource.columnFormats === b.datasource.columnFormats &&
a.datasource.currencyFormats === b.datasource.currencyFormats &&
+ a.datasource.currencyCodeColumn === b.datasource.currencyCodeColumn &&
a.datasource.verboseMap === b.datasource.verboseMap &&
a.formData.tableTimestampFormat === b.formData.tableTimestampFormat &&
a.formData.timeGrainSqla === b.formData.timeGrainSqla &&
@@ -36,6 +37,8 @@ export default function isEqualColumns(
isEqualArray(a.formData.metrics, b.formData.metrics) &&
isEqualArray(a.queriesData?.[0]?.colnames, b.queriesData?.[0]?.colnames) &&
isEqualArray(a.queriesData?.[0]?.coltypes, b.queriesData?.[0]?.coltypes) &&
+ a.queriesData?.[0]?.detected_currency ===
+ b.queriesData?.[0]?.detected_currency &&
JSON.stringify(a.formData.extraFilters || null) ===
JSON.stringify(b.formData.extraFilters || null) &&
JSON.stringify(a.formData.extraFormData || null) ===
diff --git a/superset-frontend/plugins/plugin-chart-table/test/utils/formatValue.test.ts b/superset-frontend/plugins/plugin-chart-table/test/utils/formatValue.test.ts
new file mode 100644
index 0000000000..7443092414
--- /dev/null
+++ b/superset-frontend/plugins/plugin-chart-table/test/utils/formatValue.test.ts
@@ -0,0 +1,155 @@
+/**
+ * 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.
+ */
+import { CurrencyFormatter, getNumberFormatter } from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/api/core';
+import { formatColumnValue } from '../../src/utils/formatValue';
+import { DataColumnMeta } from '../../src/types';
+
+test('formatColumnValue with CurrencyFormatter AUTO mode uses row context', () => {
+ const formatter = new CurrencyFormatter({
+ d3Format: ',.2f',
+ currency: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ });
+
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter,
+ isNumeric: true,
+ currencyCodeColumn: 'currency_code',
+ };
+
+ const rowData = { revenue: 1000, currency_code: 'EUR' };
+ const [isHtml, result] = formatColumnValue(column, 1000, rowData);
+
+ expect(isHtml).toBe(false);
+ expect(result).toContain('€');
+ expect(result).toContain('1,000.00');
+});
+
+test('formatColumnValue with CurrencyFormatter AUTO mode returns neutral format without row context', () => {
+ const formatter = new CurrencyFormatter({
+ d3Format: ',.2f',
+ currency: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ });
+
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter,
+ isNumeric: true,
+ currencyCodeColumn: 'currency_code',
+ };
+
+ // No row data provided
+ const [isHtml, result] = formatColumnValue(column, 1000);
+
+ expect(isHtml).toBe(false);
+ expect(result).toBe('1,000.00');
+ expect(result).not.toContain('$');
+ expect(result).not.toContain('€');
+});
+
+test('formatColumnValue with static CurrencyFormatter ignores row context', () => {
+ const formatter = new CurrencyFormatter({
+ d3Format: ',.2f',
+ currency: { symbol: 'USD', symbolPosition: 'prefix' },
+ });
+
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter,
+ isNumeric: true,
+ };
+
+ // Row has EUR but static mode should show $
+ const rowData = { revenue: 1000, currency_code: 'EUR' };
+ const [isHtml, result] = formatColumnValue(column, 1000, rowData);
+
+ expect(isHtml).toBe(false);
+ expect(result).toContain('$');
+ expect(result).not.toContain('€');
+});
+
+test('formatColumnValue with AUTO mode normalizes currency codes', () => {
+ const formatter = new CurrencyFormatter({
+ d3Format: ',.2f',
+ currency: { symbol: 'AUTO', symbolPosition: 'prefix' },
+ });
+
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter,
+ isNumeric: true,
+ currencyCodeColumn: 'currency_code',
+ };
+
+ // Test lowercase currency code
+ const rowData1 = { revenue: 500, currency_code: 'usd' };
+ const [, result1] = formatColumnValue(column, 500, rowData1);
+ expect(result1).toContain('$');
+
+ // Test uppercase currency code (GBP -> £)
+ const rowData2 = { revenue: 750, currency_code: 'GBP' };
+ const [, result2] = formatColumnValue(column, 750, rowData2);
+ expect(result2).toContain('£');
+});
+
+test('formatColumnValue handles null values', () => {
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter: getNumberFormatter(',.2f'),
+ isNumeric: true,
+ };
+
+ const [, nullResult] = formatColumnValue(column, null);
+ expect(nullResult).toBe('N/A');
+});
+
+test('formatColumnValue with small number format and currency', () => {
+ const formatter = new CurrencyFormatter({
+ d3Format: ',.2f',
+ currency: { symbol: 'EUR', symbolPosition: 'prefix' },
+ });
+
+ const column: DataColumnMeta = {
+ key: 'revenue',
+ label: 'Revenue',
+ dataType: GenericDataType.Numeric,
+ formatter,
+ isNumeric: true,
+ config: {
+ d3SmallNumberFormat: ',.4f',
+ currencyFormat: { symbol: 'EUR', symbolPosition: 'prefix' },
+ },
+ };
+
+ // Small number should use small number format
+ const [, result] = formatColumnValue(column, 0.5);
+ expect(result).toContain('€');
+ expect(result).toContain('0.5000');
+});
diff --git a/superset-frontend/src/components/Datasource/DatasourceModal/index.tsx b/superset-frontend/src/components/Datasource/DatasourceModal/index.tsx
index 413ddbd577..56379a40e2 100644
--- a/superset-frontend/src/components/Datasource/DatasourceModal/index.tsx
+++ b/superset-frontend/src/components/Datasource/DatasourceModal/index.tsx
@@ -119,6 +119,7 @@ const DatasourceModal: FunctionComponent<DatasourceModalProps> = ({
datasource.schema,
description: datasource.description,
main_dttm_col: datasource.main_dttm_col,
+ currency_code_column: datasource.currency_code_column ?? null,
normalize_columns: datasource.normalize_columns,
always_filter_main_dttm: datasource.always_filter_main_dttm,
offset: datasource.offset,
diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.jsx b/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.jsx
index 1412b4cedf..fc22031759 100644
--- a/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.jsx
+++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.jsx
@@ -30,6 +30,7 @@ import {
getClientErrorObject,
getExtensionsRegistry,
} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/api/core';
import {
css,
styled,
@@ -56,8 +57,10 @@ import {
Col,
Divider,
EditableTitle,
+ Flex,
FormLabel,
Icons,
+ InfoTooltip,
Loading,
Row,
Select,
@@ -157,6 +160,31 @@ const StyledTableTabWrapper = styled.div`
}
`;
+const DefaultColumnSettingsContainer = styled.div`
+ ${({ theme }) => css`
+ margin-bottom: ${theme.sizeUnit * 4}px;
+ `}
+`;
+
+const DefaultColumnSettingsTitle = styled.h4`
+ ${({ theme }) => css`
+ margin: 0 0 ${theme.sizeUnit * 2}px 0;
+ font-size: ${theme.fontSizeLG}px;
+ font-weight: ${theme.fontWeightMedium};
+ color: ${theme.colorText};
+ `}
+`;
+
+const FieldLabelWithTooltip = styled.div`
+ ${({ theme }) => css`
+ display: flex;
+ align-items: center;
+ gap: ${theme.sizeUnit}px;
+ font-size: ${theme.fontSizeSM}px;
+ color: ${theme.colorTextLabel};
+ `}
+`;
+
const StyledButtonWrapper = styled.span`
${({ theme }) => `
margin-top: ${theme.sizeUnit * 3}px;
@@ -234,18 +262,10 @@ function ColumnCollectionTable({
'advanced_data_type',
'type',
'is_dttm',
- 'main_dttm_col',
- 'filterable',
- 'groupby',
- ]
- : [
- 'column_name',
- 'type',
- 'is_dttm',
- 'main_dttm_col',
'filterable',
'groupby',
]
+ : ['column_name', 'type', 'is_dttm', 'filterable', 'groupby']
}
sortColumns={
isFeatureEnabled(FeatureFlag.EnableAdvancedDataTypes)
@@ -254,18 +274,10 @@ function ColumnCollectionTable({
'advanced_data_type',
'type',
'is_dttm',
- 'main_dttm_col',
- 'filterable',
- 'groupby',
- ]
- : [
- 'column_name',
- 'type',
- 'is_dttm',
- 'main_dttm_col',
'filterable',
'groupby',
]
+ : ['column_name', 'type', 'is_dttm', 'filterable', 'groupby']
}
allowDeletes
allowAddItem={allowAddItem}
@@ -403,7 +415,6 @@ function ColumnCollectionTable({
type: t('Data type'),
groupby: t('Is dimension'),
is_dttm: t('Is temporal'),
- main_dttm_col: t('Default datetime'),
filterable: t('Is filterable'),
}
: {
@@ -411,7 +422,6 @@ function ColumnCollectionTable({
type: t('Data type'),
groupby: t('Is dimension'),
is_dttm: t('Is temporal'),
- main_dttm_col: t('Default datetime'),
filterable: t('Is filterable'),
}
}
@@ -445,27 +455,6 @@ function ColumnCollectionTable({
{v}
</StyledLabelWrapper>
),
- main_dttm_col: (value, _onItemChange, _label, record) => {
- const checked = datasource.main_dttm_col === record.column_name;
- const disabled = !record?.is_dttm;
- return (
- <Radio
- aria-label={t(
- 'Set %s as default datetime column',
- record.column_name,
- )}
- data-test={`radio-default-dttm-${record.column_name}`}
- checked={checked}
- disabled={disabled}
- onChange={() =>
- onDatasourceChange({
- ...datasource,
- main_dttm_col: record.column_name,
- })
- }
- />
- );
- },
type: d => (d ? <Label>{d}</Label> : null),
advanced_data_type: d => (
<Label onChange={onColumnsChange}>{d}</Label>
@@ -497,27 +486,6 @@ function ColumnCollectionTable({
{v}
</StyledLabelWrapper>
),
- main_dttm_col: (value, _onItemChange, _label, record) => {
- const checked = datasource.main_dttm_col === record.column_name;
- const disabled = !record?.is_dttm;
- return (
- <Radio
- aria-label={t(
- 'Set %s as default datetime column',
- record.column_name,
- )}
- data-test={`radio-default-dttm-${record.column_name}`}
- checked={checked}
- disabled={disabled}
- onChange={() =>
- onDatasourceChange({
- ...datasource,
- main_dttm_col: record.column_name,
- })
- }
- />
- );
- },
type: d => (d ? <Label>{d}</Label> : null),
is_dttm: checkboxGenerator,
filterable: checkboxGenerator,
@@ -1083,11 +1051,12 @@ class DatasourceEditor extends PureComponent {
),
);
- // validate currency code
+ // validate currency code (skip 'AUTO' - it's a placeholder for auto-detection)
try {
this.state.datasource.metrics?.forEach(
metric =>
metric.currency?.symbol &&
+ metric.currency.symbol !== 'AUTO' &&
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: metric.currency.symbol,
@@ -1108,6 +1077,86 @@ class DatasourceEditor extends PureComponent {
return metrics.sort(({ id: a }, { id: b }) => b - a);
}
+ renderDefaultColumnSettings() {
+ const { datasource, databaseColumns, calculatedColumns } = this.state;
+ const { theme } = this.props;
+ const allColumns = [...databaseColumns, ...calculatedColumns];
+
+ // Get datetime-compatible columns for the default datetime dropdown
+ const datetimeColumns = allColumns
+ .filter(col => col.is_dttm)
+ .map(col => ({
+ value: col.column_name,
+ label: col.verbose_name || col.column_name,
+ }));
+
+ // Get string-type columns for the currency code dropdown
+ const stringColumns = allColumns
+ .filter(col => col.type_generic === GenericDataType.String)
+ .map(col => ({
+ value: col.column_name,
+ label: col.verbose_name || col.column_name,
+ }));
+
+ return (
+ <DefaultColumnSettingsContainer data-test="default-column-settings">
+ <DefaultColumnSettingsTitle>
+ {t('Default Column Settings')}
+ </DefaultColumnSettingsTitle>
+ <Flex vertical gap={theme.sizeUnit * 3}>
+ <Flex vertical gap={theme.sizeUnit}>
+ <FieldLabelWithTooltip>
+ <span>{t('Default datetime column')}</span>
+ <InfoTooltip
+ tooltip={t(
+ 'Sets the default temporal column for this dataset. Automatically selected as the time column when building charts that require a time dimension and used in dashboard level time filters.',
+ )}
+ />
+ </FieldLabelWithTooltip>
+ <Select
+ ariaLabel={t('Default datetime column')}
+ options={datetimeColumns}
+ value={datasource.main_dttm_col}
+ onChange={value =>
+ this.onDatasourceChange({
+ ...datasource,
+ main_dttm_col: value,
+ })
+ }
+ placeholder={t('Select datetime column')}
+ allowClear
+ data-test="default-datetime-column-select"
+ />
+ </Flex>
+ <Flex vertical gap={theme.sizeUnit}>
+ <FieldLabelWithTooltip>
+ <span>{t('Currency code column')}</span>
+ <InfoTooltip
+ tooltip={t(
+ "Select the column containing currency codes such as USD, EUR, GBP, etc. Used when building charts when 'Auto-detect' currency formatting is enabled. If this column is not set or if a chart metric contains multiple currencies, charts will fall back to neutral numeric formatting.",
+ )}
+ />
+ </FieldLabelWithTooltip>
+ <Select
+ ariaLabel={t('Currency code column')}
+ options={stringColumns}
+ value={datasource.currency_code_column}
+ onChange={value =>
+ this.onDatasourceChange({
+ ...datasource,
+ currency_code_column: value,
+ })
+ }
+ placeholder={t('Select currency code column')}
+ allowClear
+ data-test="currency-code-column-select"
+ />
+ </Flex>
+ </Flex>
+ </DefaultColumnSettingsContainer>
+ );
+ }
+
renderSettingsFieldset() {
const { datasource } = this.state;
return (
@@ -1889,6 +1938,10 @@ class DatasourceEditor extends PureComponent {
),
children: (
<StyledTableTabWrapper>
+ {this.renderDefaultColumnSettings()}
+ <DefaultColumnSettingsTitle>
+ {t('Column Settings')}
+ </DefaultColumnSettingsTitle>
<ColumnButtonWrapper>
<StyledButtonWrapper>
<Button
@@ -1926,6 +1979,10 @@ class DatasourceEditor extends PureComponent {
),
children: (
<StyledTableTabWrapper>
+ {this.renderDefaultColumnSettings()}
+ <DefaultColumnSettingsTitle>
+ {t('Column Settings')}
+ </DefaultColumnSettingsTitle>
<ColumnCollectionTable
columns={this.state.calculatedColumns}
onColumnsChange={calculatedColumns =>
diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditor.test.tsx b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditor.test.tsx
index e8dfc51b6d..bab512914d 100644
--- a/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditor.test.tsx
+++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditor.test.tsx
@@ -365,34 +365,52 @@ test('properly updates the metric information', async () => {
});
});
-test('shows the default datetime column', async () => {
+test('shows the default datetime column in dropdown', async () => {
await asyncRender(createProps());
const columnsButton = screen.getByTestId('collection-tab-Columns');
await userEvent.click(columnsButton);
- const dsDefaultDatetimeRadio = screen.getByTestId('radio-default-dttm-ds');
- expect(dsDefaultDatetimeRadio).toBeChecked();
+ // Find the Default Column Settings section
+ const defaultColumnSettings = screen.getByTestId('default-column-settings');
+ expect(defaultColumnSettings).toBeInTheDocument();
- const genderDefaultDatetimeRadio = screen.getByTestId(
- 'radio-default-dttm-gender',
- );
- expect(genderDefaultDatetimeRadio).not.toBeChecked();
+ // Find the default datetime column dropdown
+ const defaultDatetimeDropdown = screen.getByRole('combobox', {
+ name: 'Default datetime column',
+ });
+ expect(defaultDatetimeDropdown).toBeInTheDocument();
+
+ // Verify the current value is 'ds' (from main_dttm_col in props)
+ const selectedValue = await screen.findByText('ds', {
+ selector: '.ant-select-selection-item',
+ });
+ expect(selectedValue).toBeInTheDocument();
});
-test('allows choosing only temporal columns as the default datetime', async () => {
+test('default datetime dropdown shows only temporal columns', async () => {
await asyncRender(createProps());
const columnsButton = screen.getByTestId('collection-tab-Columns');
await userEvent.click(columnsButton);
- const dsDefaultDatetimeRadio = screen.getByTestId('radio-default-dttm-ds');
- expect(dsDefaultDatetimeRadio).toBeEnabled();
+ // Find the default datetime column dropdown
+ const defaultDatetimeDropdown = screen.getByRole('combobox', {
+ name: 'Default datetime column',
+ });
+
+ await userEvent.click(defaultDatetimeDropdown);
+
+ // Check that temporal column 'ds' is in the dropdown options
+ const options = document.querySelectorAll('.ant-select-item-option');
+ const dsOption = Array.from(options).find(o => o.textContent?.includes('ds'));
+ expect(dsOption).toBeDefined();
- const genderDefaultDatetimeRadio = screen.getByTestId(
- 'radio-default-dttm-gender',
+ // Check that non-temporal column 'gender' is NOT in the dropdown
+ const genderOption = Array.from(options).find(o =>
+ o.textContent?.includes('gender'),
);
- expect(genderDefaultDatetimeRadio).toBeDisabled();
+ expect(genderOption).toBeUndefined();
});
test('aborts pending requests on unmount without errors', async () => {
diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorCurrency.test.tsx b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorCurrency.test.tsx
index 6f6b83b6d6..1d9692c41d 100644
--- a/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorCurrency.test.tsx
+++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorCurrency.test.tsx
@@ -23,6 +23,7 @@ import {
userEvent,
selectOption,
} from 'spec/helpers/testing-library';
+import { GenericDataType } from '@apache-superset/core/api/core';
import type { DatasetObject } from 'src/features/datasets/types';
import {
createProps,
@@ -136,3 +137,69 @@ test('changes currency symbol from USD to GBP', async () => {
);
expect(updatedMetric?.currency?.symbolPosition).toBe('prefix');
}, 60000);
+
+test('currency code column dropdown shows only string columns', async () => {
+ const baseProps = createProps();
+ const testProps = {
+ ...baseProps,
+ datasource: {
+ ...baseProps.datasource,
+ columns: [
+ {
+ id: 100,
+ type: 'VARCHAR(255)',
+ type_generic: GenericDataType.String,
+ filterable: true,
+ is_dttm: false,
+ is_active: true,
+ expression: '',
+ groupby: true,
+ column_name: 'currency_code',
+ },
+ {
+ id: 101,
+ type: 'DECIMAL',
+ type_generic: GenericDataType.Numeric,
+ filterable: false,
+ is_dttm: false,
+ is_active: true,
+ expression: '',
+ groupby: false,
+ column_name: 'amount',
+ },
+ ...baseProps.datasource.columns,
+ ],
+ },
+ onChange: jest.fn(),
+ };
+
+ fastRender(testProps);
+ await dismissDatasourceWarning();
+
+ // Navigate to columns tab
+ const columnsTab = await screen.findByTestId('collection-tab-Columns');
+ await userEvent.click(columnsTab);
+
+ // Find the currency code column dropdown
+ const currencyCodeDropdown = await screen.findByRole('combobox', {
+ name: 'Currency code column',
+ });
+
+ await userEvent.click(currencyCodeDropdown);
+
+ // Verify STRING column is available
+ await waitFor(() => {
+ const options = document.querySelectorAll('.ant-select-item-option');
+ const currencyCodeOption = Array.from(options).find(o =>
+ o.textContent?.includes('currency_code'),
+ );
+ expect(currencyCodeOption).toBeDefined();
+ });
+
+ // Verify NUMERIC column is NOT available
+ const options = document.querySelectorAll('.ant-select-item-option');
+ const amountOption = Array.from(options).find(o =>
+ o.textContent?.includes('amount'),
+ );
+ expect(amountOption).toBeUndefined();
+}, 60000);
diff --git a/superset-frontend/src/explore/components/controls/ColumnConfigControl/ColumnConfigControl.tsx b/superset-frontend/src/explore/components/controls/ColumnConfigControl/ColumnConfigControl.tsx
index 6db50d1e3f..2fac42ba05 100644
--- a/superset-frontend/src/explore/components/controls/ColumnConfigControl/ColumnConfigControl.tsx
+++ b/superset-frontend/src/explore/components/controls/ColumnConfigControl/ColumnConfigControl.tsx
@@ -82,6 +82,7 @@ export default function ColumnConfigControl<T extends ColumnConfig>({
});
}
const theme = useTheme();
+
const columnConfigs = useMemo(() => {
const configs: Record<string, ColumnConfigInfo> = {};
colnames?.forEach((col, idx) => {
@@ -100,6 +101,7 @@ export default function ColumnConfigControl<T extends ColumnConfig>({
const [showAllColumns, setShowAllColumns] = useState(false);
const getColumnInfo = (col: string) => columnConfigs[col] || {};
+
const setColumnConfig = (col: string, config: T) => {
if (onChange) {
// Only keep configs for known columns
diff --git a/superset-frontend/src/explore/components/controls/ColumnConfigControl/constants.tsx b/superset-frontend/src/explore/components/controls/ColumnConfigControl/constants.tsx
index 1275242fe7..088a06d899 100644
--- a/superset-frontend/src/explore/components/controls/ColumnConfigControl/constants.tsx
+++ b/superset-frontend/src/explore/components/controls/ColumnConfigControl/constants.tsx
@@ -168,7 +168,7 @@ const currencyFormat: ControlFormItemSpec<'CurrencyControl'> = {
controlType: 'CurrencyControl',
label: t('Currency format'),
description: t(
- 'Customize chart metrics or columns with currency symbols as prefixes or suffixes. Choose a symbol from dropdown or type your own.',
+ "Format metrics or columns with currency symbols as prefixes or suffixes. Choose a symbol manually or use 'Auto-detect' to apply the correct symbol based on the dataset's currency code column. When multiple currencies are present, formatting falls back to neutral numbers.",
),
debounceDelay: 200,
};
diff --git a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts b/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.test.tsx
similarity index 57%
copy from superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
copy to superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.test.tsx
index 45fa851e88..39a1a64ee2 100644
--- a/superset-frontend/packages/superset-ui-core/src/currency-format/index.ts
+++ b/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.test.tsx
@@ -1,4 +1,4 @@
-/*
+/**
* 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
@@ -16,7 +16,23 @@
* specific language governing permissions and limitations
* under the License.
*/
+import { render } from 'spec/helpers/testing-library';
+import { CurrencyControl } from './CurrencyControl';
-export { default as CurrencyFormatter } from './CurrencyFormatter';
-export * from './CurrencyFormatter';
-export * from './utils';
+test('CurrencyControl renders position and symbol selects', () => {
+ const { container } = render(
+ <CurrencyControl onChange={jest.fn()} value={{}} />,
+ {
+ useRedux: true,
+ initialState: {
+ common: { currencies: ['USD', 'EUR'] },
+ explore: { datasource: {} },
+ },
+ },
+ );
+
+ expect(
+ container.querySelector('[data-test="currency-control-container"]'),
+ ).toBeInTheDocument();
+ expect(container.querySelectorAll('.ant-select')).toHaveLength(2);
+});
diff --git a/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.tsx b/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.tsx
index d4c5c6e6ab..8ec6890444 100644
--- a/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.tsx
+++ b/superset-frontend/src/explore/components/controls/CurrencyControl/CurrencyControl.tsx
@@ -16,14 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { t } from '@apache-superset/core';
import { Currency, ensureIsArray, getCurrencySymbol } from '@superset-ui/core';
-import { css, styled } from '@apache-superset/core/ui';
+import { css, styled, useTheme } from '@apache-superset/core/ui';
import { CSSObject } from '@emotion/react';
import { Select, type SelectProps } from '@superset-ui/core/components';
import { ViewState } from 'src/views/types';
+import { ExplorePageState } from 'src/explore/types';
import ControlHeader from '../../ControlHeader';
export interface CurrencyControlProps {
@@ -67,19 +68,74 @@ export const CurrencyControl = ({
currencySelectAdditionalStyles,
...props
}: CurrencyControlProps) => {
+ const theme = useTheme();
const currencies = useSelector<ViewState, string[]>(
state => state.common?.currencies,
);
- const currenciesOptions = useMemo(
+ const currencyCodeColumn = useSelector<ExplorePageState, string | undefined>(
+ state => state?.explore?.datasource?.currency_code_column,
+ );
+
+ const currenciesOptions = useMemo(() => {
+ const options = ensureIsArray(currencies).map(currencyCode => ({
+ value: currencyCode,
+ label: `${getCurrencySymbol({
+ symbol: currencyCode,
+ })} (${currencyCode})`,
+ }));
+
+ const autoDetectOption = currencyCodeColumn
+ ? [
+ {
+ value: 'AUTO',
+ label: t('Auto-detect'),
+ className: 'currency-auto-detect-option',
+ },
+ ]
+ : [];
+
+ return [
+ ...autoDetectOption,
+ ...options,
+ { value: '', label: t('Custom...') },
+ ];
+ }, [currencies, currencyCodeColumn]);
+
+ const currencySortComparator = useCallback(
+ (
+ a: { value?: string | number },
+ b: { value?: string | number },
+ ): number => {
+ if (a.value === 'AUTO') return -1;
+ if (b.value === 'AUTO') return 1;
+ if (a.value === '') return 1;
+ if (b.value === '') return -1;
+ const labelA = String(a.value ?? '');
+ const labelB = String(b.value ?? '');
+ return labelA.localeCompare(labelB);
+ },
+ [],
+ );
+
+ const renderCurrencyPopup = useMemo(
() =>
- ensureIsArray(currencies).map(currencyCode => ({
- value: currencyCode,
- label: `${getCurrencySymbol({
- symbol: currencyCode,
- })} (${currencyCode})`,
- })),
- [currencies],
+ currencyCodeColumn
+ ? (menu: React.ReactNode) => (
+ <div
+ css={css`
+ .currency-auto-detect-option {
+ border-bottom: 1px solid ${theme.colorBorderSecondary};
+ margin-bottom: ${theme.sizeUnit}px;
+ }
+ `}
+ >
+ {menu}
+ </div>
+ )
+ : undefined,
+ [currencyCodeColumn, theme],
);
+
return (
<>
<ControlHeader {...props} />
@@ -92,7 +148,7 @@ export const CurrencyControl = ({
${currencySelectAdditionalStyles};
}
`}
- className="currency-control-container"
+ data-test="currency-control-container"
>
<Select
ariaLabel={t('Currency prefix or suffix')}
@@ -117,6 +173,8 @@ export const CurrencyControl = ({
value={currency?.symbol}
allowClear
allowNewOptions
+ sortComparator={currencySortComparator}
+ popupRender={renderCurrencyPopup}
{...currencySelectOverrideProps}
/>
</CurrencyControlContainer>
diff --git a/superset-frontend/src/features/datasets/types.ts b/superset-frontend/src/features/datasets/types.ts
index 3e91e8effa..62f48f42b4 100644
--- a/superset-frontend/src/features/datasets/types.ts
+++ b/superset-frontend/src/features/datasets/types.ts
@@ -65,6 +65,7 @@ export type DatasetObject = {
catalog?: string;
description: string | null;
main_dttm_col: string;
+ currency_code_column?: string;
offset?: number;
default_endpoint?: string;
cache_timeout?: number;
diff --git a/superset/charts/schemas.py b/superset/charts/schemas.py
index 2ed6446cee..fc7af43aef 100644
--- a/superset/charts/schemas.py
+++ b/superset/charts/schemas.py
@@ -1533,6 +1533,15 @@ class ChartDataResponseResult(Schema):
rejected_filters = fields.List(
fields.Dict(), metadata={"description": "A list with rejected filters"}
)
+ detected_currency = fields.String(
+ metadata={
+ "description": "Detected ISO 4217 currency code when AUTO mode is used. "
+ "Returns the currency code if all filtered data contains a single currency "
+ "or null if multiple currencies are present."
+ },
+ allow_none=True,
+ load_default=None,
+ )
from_dttm = fields.Integer(
metadata={"description": "Start timestamp of time range"},
required=False,
diff --git a/superset/cli/examples.py b/superset/cli/examples.py
index 4c2d93b9d2..cf7c569df9 100755
--- a/superset/cli/examples.py
+++ b/superset/cli/examples.py
@@ -52,6 +52,9 @@ def load_examples_run(
logger.info("Loading [Birth names]")
examples.load_birth_names(only_metadata, force)
+ logger.info("Loading [International Sales]")
+ examples.load_international_sales(only_metadata, force)
+
if load_test_data:
logger.info("Loading [Tabbed dashboard]")
examples.load_tabbed_dashboard(only_metadata)
diff --git a/superset/common/query_actions.py b/superset/common/query_actions.py
index c7760ebd4e..5479e12d88 100644
--- a/superset/common/query_actions.py
+++ b/superset/common/query_actions.py
@@ -17,6 +17,7 @@
from __future__ import annotations
import copy
+import logging
from typing import Any, Callable, TYPE_CHECKING
from flask_babel import _
@@ -32,11 +33,18 @@ from superset.utils.core import (
get_column_name,
get_time_filter_status,
)
+from superset.utils.currency import (
+ detect_currency,
+ detect_currency_from_df,
+ has_auto_currency_in_column_config,
+)
if TYPE_CHECKING:
from superset.common.query_context import QueryContext
from superset.common.query_object import QueryObject
+logger = logging.getLogger(__name__)
+
def _get_datasource(query_context: QueryContext, query_obj: QueryObject) -> Explorable:
return query_obj.datasource or query_context.datasource
@@ -89,6 +97,59 @@ def _get_query(
return result
+def _detect_currency(
+ query_context: QueryContext,
+ query_obj: QueryObject,
+ datasource: Explorable,
+ df: Any = None,
+) -> str | None:
+ """
+ Detect currency from filtered data for AUTO mode currency formatting.
+
+ First attempts to detect from the provided dataframe if the currency
+ column is present. Falls back to a separate query only when needed.
+
+ Checks both top-level currency_format (used by Pie, Timeseries, etc.)
+ and column_config (used by Table charts) for AUTO currency settings.
+
+ :param query_context: The query context with form_data containing currency_format
+ :param query_obj: The original query object with filters
+ :param datasource: The datasource being queried
+ :param df: Optional dataframe to detect currency from (avoids extra query)
+ :return: ISO 4217 currency code (e.g., "USD") or None
+ """
+ form_data = query_context.form_data or {}
+
+ # Check top-level currency_format (for Pie, Timeseries, etc.)
+ currency_format = form_data.get("currency_format", {})
+ top_level_auto = (
+ isinstance(currency_format, dict) and currency_format.get("symbol") == "AUTO"
+ )
+
+ # Check column_config (for Table charts)
+ column_config_auto = has_auto_currency_in_column_config(form_data)
+
+ # Only detect if AUTO is configured somewhere
+ if not top_level_auto and not column_config_auto:
+ return None
+
+ currency_column = getattr(datasource, "currency_code_column", None)
+ if not currency_column:
+ return None
+
+ if df is not None and currency_column in df.columns:
+ return detect_currency_from_df(df, currency_column)
+
+ return detect_currency(
+ datasource=datasource,
+ filters=query_obj.filter,
+ granularity=query_obj.granularity,
+ from_dttm=query_obj.from_dttm,
+ to_dttm=query_obj.to_dttm,
+ extras=query_obj.extras,
+ )
+
+
def _get_full(
query_context: QueryContext,
query_obj: QueryObject,
@@ -105,6 +166,9 @@ def _get_full(
payload["coltypes"] = extract_dataframe_dtypes(df, datasource)
payload["data"] = query_context.get_data(df, payload["coltypes"])
payload["result_format"] = query_context.result_format
+ payload["detected_currency"] = _detect_currency(
+ query_context, query_obj, datasource, df
+ )
del payload["df"]
applied_time_columns, rejected_time_columns = get_time_filter_status(
@@ -133,6 +197,7 @@ def _get_full(
"coltypes": payload.get("coltypes"),
"rowcount": payload.get("rowcount"),
"sql_rowcount": payload.get("sql_rowcount"),
+ "detected_currency": payload.get("detected_currency"),
}
return payload
diff --git a/superset/common/query_context_factory.py b/superset/common/query_context_factory.py
index 7b61cf6ea9..a60eac4384 100644
--- a/superset/common/query_context_factory.py
+++ b/superset/common/query_context_factory.py
@@ -120,6 +120,7 @@ class QueryContextFactory: # pylint: disable=too-few-public-methods
self._apply_granularity(query_object, form_data, datasource)
self._apply_filters(query_object)
self._add_tooltip_columns(query_object, form_data)
+ self._add_currency_column(query_object, form_data, datasource)
return query_object
def _add_tooltip_columns(
@@ -195,6 +196,39 @@ class QueryContextFactory: # pylint: disable=too-few-public-methods
tooltip_columns.append(column_name)
return tooltip_columns
+ def _add_currency_column(
+ self,
+ query_object: QueryObject,
+ form_data: dict[str, Any] | None,
+ datasource: Explorable,
+ ) -> None:
+ """
+ Add currency_code_column to the query for pivot_table_v2 cell-level formatting.
+
+ When currency_format.symbol is 'AUTO', injects the datasource's
+ currency_code_column into query columns for per-cell currency formatting.
+ """
+ if not form_data or not query_object.columns:
+ return
+
+ if form_data.get("viz_type") != "pivot_table_v2":
+ return
+
+ currency_format = form_data.get("currency_format", {})
+ if not (
+ isinstance(currency_format, dict)
+ and currency_format.get("symbol") == "AUTO"
+ ):
+ return
+
+ currency_column = getattr(datasource, "currency_code_column", None)
+ if not currency_column:
+ return
+
+ existing_columns = self._get_existing_column_names(query_object.columns)
+ if currency_column not in existing_columns:
+ query_object.columns.append(currency_column)
+
def _apply_granularity( # noqa: C901
self,
query_object: QueryObject,
diff --git a/superset/connectors/sqla/models.py b/superset/connectors/sqla/models.py
index 8f7a60d270..0e3777ba4b 100644
--- a/superset/connectors/sqla/models.py
+++ b/superset/connectors/sqla/models.py
@@ -1221,6 +1221,7 @@ class SqlaTable(
table_name = Column(String(250), nullable=False)
main_dttm_col = Column(String(250))
+ currency_code_column = Column(String(250))
database_id = Column(Integer, ForeignKey("dbs.id"), nullable=False)
fetch_values_predicate = Column(Text)
owners = relationship(owner_class, secondary=sqlatable_user, backref="tables")
@@ -1244,6 +1245,7 @@ class SqlaTable(
export_fields = [
"table_name",
"main_dttm_col",
+ "currency_code_column",
"description",
"default_endpoint",
"database_id",
@@ -1331,7 +1333,8 @@ class SqlaTable(
@property
def link(self) -> Markup:
name = escape(self.name)
- anchor = f'<a target="_blank" href="{self.explore_url}">{name}</a>'
+ url = escape(self.explore_url)
+ anchor = f'<a target="_blank" href="{url}">{name}</a>'
return Markup(anchor)
def get_catalog_perm(self) -> str | None:
@@ -1448,6 +1451,7 @@ class SqlaTable(
data_["granularity_sqla"] = self.granularity_sqla
data_["time_grain_sqla"] = self.time_grain_sqla
data_["main_dttm_col"] = self.main_dttm_col
+ data_["currency_code_column"] = self.currency_code_column
data_["fetch_values_predicate"] = self.fetch_values_predicate
data_["template_params"] = self.template_params
data_["is_sqllab_view"] = self.is_sqllab_view
diff --git a/superset/dashboards/schemas.py b/superset/dashboards/schemas.py
index ba7d5dc458..06f3efc798 100644
--- a/superset/dashboards/schemas.py
+++ b/superset/dashboards/schemas.py
@@ -295,6 +295,7 @@ class DashboardDatasetSchema(Schema):
sql = fields.Str()
select_star = fields.Str()
main_dttm_col = fields.Str()
+ currency_code_column = fields.Str()
health_check_message = fields.Str()
fetch_values_predicate = fields.Str()
template_params = fields.Str()
diff --git a/superset/datasets/api.py b/superset/datasets/api.py
index 14e5464d8d..dbb51b9bf3 100644
--- a/superset/datasets/api.py
+++ b/superset/datasets/api.py
@@ -167,6 +167,7 @@ class DatasetRestApi(BaseSupersetModelRestApi):
"schema",
"description",
"main_dttm_col",
+ "currency_code_column",
"normalize_columns",
"always_filter_main_dttm",
"offset",
@@ -250,6 +251,7 @@ class DatasetRestApi(BaseSupersetModelRestApi):
"schema",
"description",
"main_dttm_col",
+ "currency_code_column",
"normalize_columns",
"always_filter_main_dttm",
"offset",
diff --git a/superset/datasets/schemas.py b/superset/datasets/schemas.py
index e92ab9c751..8216c96cae 100644
--- a/superset/datasets/schemas.py
+++ b/superset/datasets/schemas.py
@@ -166,6 +166,7 @@ class DatasetPutSchema(Schema):
schema = fields.String(allow_none=True, validate=Length(0, 255))
description = fields.String(allow_none=True)
main_dttm_col = fields.String(allow_none=True)
+ currency_code_column = fields.String(allow_none=True, validate=Length(0, 250))
normalize_columns = fields.Boolean(allow_none=True, dump_default=False)
always_filter_main_dttm = fields.Boolean(load_default=False)
offset = fields.Integer(allow_none=True)
@@ -313,6 +314,7 @@ class ImportV1DatasetSchema(Schema):
table_name = fields.String(required=True)
main_dttm_col = fields.String(allow_none=True)
+ currency_code_column = fields.String(allow_none=True)
description = fields.String(allow_none=True)
default_endpoint = fields.String(allow_none=True)
offset = fields.Integer()
diff --git a/superset/examples/data_loading.py b/superset/examples/data_loading.py
index 9cffa06e85..b7d9c663f6 100644
--- a/superset/examples/data_loading.py
+++ b/superset/examples/data_loading.py
@@ -22,6 +22,7 @@ from .css_templates import load_css_templates
from .deck import load_deck_dash
from .energy import load_energy
from .flights import load_flights
+from .international_sales import load_international_sales
from .long_lat import load_long_lat_data
from .misc_dashboard import load_misc_dashboard
from .multiformat_time_series import load_multiformat_time_series
@@ -39,6 +40,7 @@ __all__ = [
"load_birth_names",
"load_country_map_data",
"load_css_templates",
+ "load_international_sales",
"load_deck_dash",
"load_energy",
"load_flights",
diff --git a/superset/examples/international_sales.py b/superset/examples/international_sales.py
new file mode 100644
index 0000000000..3cfd4ed430
--- /dev/null
+++ b/superset/examples/international_sales.py
@@ -0,0 +1,238 @@
+# 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.
+"""International sales dataset demonstrating multi-currency transactions."""
+
+import logging
+
+import pandas as pd
+from sqlalchemy import Date, inspect, Integer, Numeric, String
+
+from superset import db
+from superset.connectors.sqla.models import SqlaTable
+from superset.models.core import Database
+from superset.sql.parse import Table
+
+from ..utils.database import get_example_database # noqa: TID252
+from .helpers import get_table_connector_registry
+
+logger = logging.getLogger(__name__)
+
+
+def get_international_sales_data() -> pd.DataFrame:
+ """Generate the international sales dataset with multiple currencies."""
+ # fmt: off
+ data = [
+ # North America - USA (USD)
+ (1, "2024-01-15", "North America", "USA", "Electronics", "Laptop Pro",
+ 50, 1299.99, 64999.50, 45000.00, 19999.50, "USD", "$"),
+ (2, "2024-01-15", "North America", "USA", "Electronics", "Smartphone X",
+ 200, 899.99, 179998.00, 120000.00, 59998.00, "USD", "$"),
+ (3, "2024-01-15", "North America", "USA", "Software", "Office Suite",
+ 500, 149.99, 74995.00, 15000.00, 59995.00, "USD", "$"),
+ (4, "2024-02-15", "North America", "USA", "Electronics", "Laptop Pro",
+ 75, 1299.99, 97499.25, 67500.00, 29999.25, "USD", "$"),
+ (5, "2024-02-15", "North America", "USA", "Electronics", "Smartphone X",
+ 250, 899.99, 224997.50, 150000.00, 74997.50, "USD", "$"),
+ (6, "2024-02-15", "North America", "USA", "Software", "Office Suite",
+ 600, 149.99, 89994.00, 18000.00, 71994.00, "USD", "$"),
+ (7, "2024-03-15", "North America", "USA", "Electronics", "Laptop Pro",
+ 100, 1299.99, 129999.00, 90000.00, 39999.00, "USD", "$"),
+ (8, "2024-03-15", "North America", "USA", "Electronics", "Smartphone X",
+ 300, 899.99, 269997.00, 180000.00, 89997.00, "USD", "$"),
+ # Case normalization test - lowercase 'usd'
+ (9, "2024-03-15", "North America", "USA", "Software", "Office Suite",
+ 700, 149.99, 104993.00, 21000.00, 83993.00, "usd", "$"),
+ # North America - Canada (CAD)
+ (10, "2024-01-15", "North America", "Canada", "Electronics", "Laptop Pro",
+ 30, 1599.99, 47999.70, 35000.00, 12999.70, "CAD", "CA$"),
+ (11, "2024-01-15", "North America", "Canada", "Electronics", "Smartphone X",
+ 100, 1099.99, 109999.00, 75000.00, 34999.00, "CAD", "CA$"),
+ (12, "2024-02-15", "North America", "Canada", "Electronics", "Laptop Pro",
+ 40, 1599.99, 63999.60, 46000.00, 17999.60, "CAD", "CA$"),
+ (13, "2024-02-15", "North America", "Canada", "Software", "Office Suite",
+ 200, 199.99, 39998.00, 8000.00, 31998.00, "CAD", "CA$"),
+ # Case normalization test - mixed case 'Cad'
+ (14, "2024-03-15", "North America", "Canada", "Electronics", "Laptop Pro",
+ 50, 1599.99, 79999.50, 57500.00, 22499.50, "Cad", "CA$"),
+ # Europe - Germany/France (EUR)
+ (15, "2024-01-15", "Europe", "Germany", "Electronics", "Laptop Pro",
+ 40, 1199.99, 47999.60, 32000.00, 15999.60, "EUR", "€"),
+ (16, "2024-01-15", "Europe", "Germany", "Electronics", "Smartphone X",
+ 150, 849.99, 127498.50, 85000.00, 42498.50, "EUR", "€"),
+ (17, "2024-01-15", "Europe", "France", "Software", "Office Suite",
+ 300, 139.99, 41997.00, 9000.00, 32997.00, "EUR", "€"),
+ (18, "2024-02-15", "Europe", "Germany", "Electronics", "Laptop Pro",
+ 55, 1199.99, 65999.45, 44000.00, 21999.45, "EUR", "€"),
+ (19, "2024-02-15", "Europe", "France", "Electronics", "Smartphone X",
+ 180, 849.99, 152998.20, 102000.00, 50998.20, "EUR", "€"),
+ # Case normalization test - lowercase 'eur'
+ (20, "2024-02-15", "Europe", "Germany", "Software", "Office Suite",
+ 350, 139.99, 48996.50, 10500.00, 38496.50, "eur", "€"),
+ # Europe - UK (GBP)
+ (21, "2024-01-15", "Europe", "UK", "Electronics", "Laptop Pro",
+ 35, 999.99, 34999.65, 24500.00, 10499.65, "GBP", "£"),
+ (22, "2024-01-15", "Europe", "UK", "Electronics", "Smartphone X",
+ 120, 749.99, 89998.80, 66000.00, 23998.80, "GBP", "£"),
+ (23, "2024-02-15", "Europe", "UK", "Electronics", "Laptop Pro",
+ 45, 999.99, 44999.55, 31500.00, 13499.55, "GBP", "£"),
+ (24, "2024-02-15", "Europe", "UK", "Software", "Office Suite",
+ 250, 119.99, 29997.50, 7500.00, 22497.50, "GBP", "£"),
+ # Case normalization test - mixed case 'Gbp'
+ (25, "2024-03-15", "Europe", "UK", "Electronics", "Laptop Pro",
+ 60, 999.99, 59999.40, 42000.00, 17999.40, "Gbp", "£"),
+ # Asia - Japan (JPY)
+ (26, "2024-01-15", "Asia", "Japan", "Electronics", "Laptop Pro",
+ 25, 149999.00, 3749975.00, 2625000.00, 1124975.00, "JPY", "¥"),
+ (27, "2024-01-15", "Asia", "Japan", "Electronics", "Smartphone X",
+ 80, 99999.00, 7999920.00, 5600000.00, 2399920.00, "JPY", "¥"),
+ (28, "2024-02-15", "Asia", "Japan", "Electronics", "Laptop Pro",
+ 30, 149999.00, 4499970.00, 3150000.00, 1349970.00, "JPY", "¥"),
+ (29, "2024-03-15", "Asia", "Japan", "Software", "Office Suite",
+ 150, 14999.00, 2249850.00, 450000.00, 1799850.00, "JPY", "¥"),
+ # Asia Pacific - Australia (AUD)
+ (30, "2024-01-15", "Asia Pacific", "Australia", "Electronics", "Laptop Pro",
+ 20, 1899.99, 37999.80, 26000.00, 11999.80, "AUD", "A$"),
+ (31, "2024-02-15", "Asia Pacific", "Australia", "Electronics", "Smartphone X",
+ 60, 1299.99, 77999.40, 48000.00, 29999.40, "AUD", "A$"),
+ (32, "2024-03-15", "Asia Pacific", "Australia", "Software", "Office Suite",
+ 100, 219.99, 21999.00, 6000.00, 15999.00, "AUD", "A$"),
+ # NULL currency tests - Other region
+ (33, "2024-01-15", "Other", "Unknown", "Electronics", "Generic Device",
+ 10, 500.00, 5000.00, 3500.00, 1500.00, None, None),
+ (34, "2024-02-15", "Other", "Unknown", "Software", "Basic App",
+ 50, 50.00, 2500.00, 1000.00, 1500.00, None, None),
+ # Empty string currency test
+ (35, "2024-03-15", "Other", "Unknown", "Electronics", "Unknown Product",
+ 5, 100.00, 500.00, 350.00, 150.00, "", ""),
+ # Additional rows for aggregation tests
+ (36, "2024-01-15", "North America", "USA", "Electronics", "Tablet Pro",
+ 80, 599.99, 47999.20, 32000.00, 15999.20, "USD", "$"),
+ (37, "2024-02-15", "Europe", "Germany", "Electronics", "Tablet Pro",
+ 65, 549.99, 35749.35, 22750.00, 12999.35, "EUR", "€"),
+ (38, "2024-03-15", "Asia", "Japan", "Electronics", "Tablet Pro",
+ 45, 64999.00, 2924955.00, 1575000.00, 1349955.00, "JPY", "¥"),
+ # Euro word/symbol normalization tests
+ (39, "2024-01-15", "Europe", "Spain", "Software", "Cloud Service",
+ 100, 99.99, 9999.00, 5000.00, 4999.00, "euro", "€"),
+ (40, "2024-02-15", "Europe", "Italy", "Software", "Cloud Service",
+ 120, 99.99, 11998.80, 6000.00, 5998.80, "EURO", "€"),
+ (41, "2024-03-15", "Europe", "Portugal", "Software", "Cloud Service",
+ 80, 99.99, 7999.20, 4000.00, 3999.20, "€", "€"),
+ # Invalid currency code fallback test
+ (42, "2024-01-15", "Other", "Unknown", "Electronics", "Mystery Device",
+ 25, 200.00, 5000.00, 3000.00, 2000.00, "XYZ", "?"),
+ ]
+ # fmt: on
+
+ columns = [
+ "id",
+ "transaction_date",
+ "region",
+ "country",
+ "product_category",
+ "product_name",
+ "quantity",
+ "unit_price",
+ "revenue",
+ "cost",
+ "profit",
+ "currency_code",
+ "currency_symbol",
+ ]
+
+ return pd.DataFrame(data, columns=columns)
+
+
+def load_data(tbl_name: str, database: Database) -> None:
+ """Load the international sales data into the database."""
+ pdf = get_international_sales_data()
+ pdf["transaction_date"] = pd.to_datetime(pdf["transaction_date"])
+
+ with database.get_sqla_engine() as engine:
+ schema = inspect(engine).default_schema_name
+
+ pdf.to_sql(
+ tbl_name,
+ engine,
+ schema=schema,
+ if_exists="replace",
+ chunksize=50,
+ dtype={
+ "id": Integer,
+ "transaction_date": Date,
+ "region": String(50),
+ "country": String(50),
+ "product_category": String(50),
+ "product_name": String(100),
+ "quantity": Integer,
+ "unit_price": Numeric(12, 2),
+ "revenue": Numeric(14, 2),
+ "cost": Numeric(14, 2),
+ "profit": Numeric(14, 2),
+ "currency_code": String(10),
+ "currency_symbol": String(10),
+ },
+ method="multi",
+ index=False,
+ )
+ logger.debug("Done loading international sales data!")
+
+
+def load_international_sales(only_metadata: bool = False, force: bool = False) -> None:
+ """Load international sales dataset for demonstrating dynamic currency formatting.
+
+ This dataset contains multi-currency transaction data with:
+ - Multiple currencies (USD, EUR, GBP, JPY, CAD, AUD)
+ - Case variations for normalization testing (usd, eur, Gbp, Cad)
+ - Word variations for normalization testing (euro, EURO)
+ - Symbol variations for normalization testing (€)
+ - NULL and empty string currency values for fallback testing
+ - Invalid currency code (XYZ) for fallback testing
+ - Multiple monetary columns (revenue, cost, profit, unit_price)
+ """
+ database = get_example_database()
+ tbl_name = "international_sales"
+
+ with database.get_sqla_engine() as engine:
+ schema = inspect(engine).default_schema_name
+ table_exists = database.has_table(Table(tbl_name, schema))
+
+ if not only_metadata and (not table_exists or force):
+ load_data(tbl_name, database)
+
+ table = get_table_connector_registry()
+ obj = db.session.query(table).filter_by(table_name=tbl_name, schema=schema).first()
+ if not obj:
+ logger.debug("Creating table [%s] reference", tbl_name)
+ obj = table(table_name=tbl_name, schema=schema)
+ db.session.add(obj)
+
+ _set_table_metadata(obj, database)
+
+
+def _set_table_metadata(datasource: SqlaTable, database: Database) -> None:
+ """Set metadata for the international sales dataset."""
+ datasource.main_dttm_col = "transaction_date"
+ datasource.database = database
+ datasource.filter_select_enabled = True
+ datasource.description = (
+ "International sales transactions across multiple currencies "
+ "for demonstrating dynamic currency formatting features."
+ )
+ # Set the currency code column for dynamic currency detection
+ datasource.currency_code_column = "currency_code"
+ datasource.fetch_metadata()
diff --git a/tests/unit_tests/datasets/schema_tests.py b/superset/migrations/versions/2025-11-18_14-00_9787190b3d89_add_currency_column_support.py
similarity index 51%
copy from tests/unit_tests/datasets/schema_tests.py
copy to superset/migrations/versions/2025-11-18_14-00_9787190b3d89_add_currency_column_support.py
index 8aa327f77a..6084f50a1d 100644
--- a/tests/unit_tests/datasets/schema_tests.py
+++ b/superset/migrations/versions/2025-11-18_14-00_9787190b3d89_add_currency_column_support.py
@@ -14,35 +14,35 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""add currency column support
-# pylint: disable=import-outside-toplevel, invalid-name, unused-argument, redefined-outer-name
-import pytest
-from marshmallow import ValidationError
-
-from superset.datasets.schemas import validate_python_date_format
-
-
-# pylint: disable=too-few-public-methods
-@pytest.mark.parametrize(
- "payload",
- [
- "epoch_ms",
- "epoch_s",
- "%Y-%m-%dT%H:%M:%S.%f",
- "%Y%m%d",
- ],
-)
-def test_validate_python_date_format(payload) -> None:
- assert validate_python_date_format(payload)
-
-
-@pytest.mark.parametrize(
- "payload",
- [
- "%d%m%Y",
- "%Y/%m/%dT%H:%M:%S.%f",
- ],
-)
-def test_validate_python_date_format_raises(payload) -> None:
- with pytest.raises(ValidationError):
- validate_python_date_format(payload)
+Revision ID: 9787190b3d89
+Revises: f5b5f88d8526
+Create Date: 2025-11-18 14:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "9787190b3d89"
+down_revision = "f5b5f88d8526"
+
+
+def upgrade():
+ """Add currency column support to datasets."""
+ # Add currency code column designation to tables (like main_dttm_col pattern)
+ add_columns(
+ "tables",
+ sa.Column("currency_code_column", sa.String(250), nullable=True),
+ )
+
+
+def downgrade():
+ """Remove currency column support."""
+ drop_columns(
+ "tables",
+ "currency_code_column",
+ )
diff --git a/superset/superset_typing.py b/superset/superset_typing.py
index 105a28d4cf..4d409398d1 100644
--- a/superset/superset_typing.py
+++ b/superset/superset_typing.py
@@ -243,6 +243,7 @@ class ExplorableData(TypedDict, total=False):
granularity_sqla: Available time granularities
time_grain_sqla: Available time grains
main_dttm_col: Main datetime column
+ currency_code_column: Column containing currency codes for dynamic formatting
fetch_values_predicate: Predicate for fetching filter values
template_params: Template parameters for Jinja
is_sqllab_view: Whether this is a SQL Lab view
@@ -287,6 +288,7 @@ class ExplorableData(TypedDict, total=False):
granularity_sqla: list[tuple[Any, Any]]
time_grain_sqla: list[tuple[Any, Any]]
main_dttm_col: str | None
+ currency_code_column: str | None
fetch_values_predicate: str | None
template_params: str | None
is_sqllab_view: bool
diff --git a/superset/utils/currency.py b/superset/utils/currency.py
new file mode 100644
index 0000000000..f274bf5db7
--- /dev/null
+++ b/superset/utils/currency.py
@@ -0,0 +1,160 @@
+# 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.
+"""Currency detection utilities for dynamic currency formatting."""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+from typing import Any, TYPE_CHECKING
+
+from superset.common.db_query_status import QueryStatus
+
+if TYPE_CHECKING:
+ from superset.explorables.base import Explorable
+ from superset.superset_typing import QueryObjectDict
+ from superset.utils.core import QueryObjectFilterClause
+
+logger = logging.getLogger(__name__)
+
+
+def has_auto_currency_in_column_config(form_data: dict[str, Any] | None) -> bool:
+ """
+ Check if any column in column_config has AUTO currency format.
+
+ Used by Table charts which configure currency per-column via column_config,
+ rather than using top-level currency_format like other chart types.
+
+ :param form_data: The form data containing column_config
+ :return: True if any column has AUTO currency format
+ """
+ if not form_data:
+ return False
+ column_config = form_data.get("column_config", {})
+ if not isinstance(column_config, dict):
+ return False
+ for config in column_config.values():
+ if not isinstance(config, dict):
+ continue
+ currency_format = config.get("currencyFormat", {})
+ if (
+ isinstance(currency_format, dict)
+ and currency_format.get("symbol") == "AUTO"
+ ):
+ return True
+ return False
+
+
+def detect_currency_from_df(
+ df: Any, # pd.DataFrame, but avoiding import for type checking
+ currency_column: str,
+) -> str | None:
+ """
+ Detect currency from an already-fetched dataframe.
+
+ Returns the currency code if all data contains a single currency,
+ or None if multiple currencies are present or column is missing.
+
+ :param df: The pandas DataFrame to analyze
+ :param currency_column: The name of the currency code column
+ :return: ISO 4217 currency code (e.g., "USD", "EUR") or None
+ """
+ if df is None or df.empty:
+ return None
+
+ if currency_column not in df.columns:
+ return None
+
+ unique_currencies = df[currency_column].dropna().astype(str).str.upper().unique()
+
+ if len(unique_currencies) == 1:
+ return str(unique_currencies[0])
+
+ return None
+
+
+def detect_currency(
+ datasource: Explorable,
+ filters: list[QueryObjectFilterClause] | None = None,
+ granularity: str | None = None,
+ from_dttm: datetime | None = None,
+ to_dttm: datetime | None = None,
+ extras: dict[str, Any] | None = None,
+) -> str | None:
+ """
+ Detect currency from filtered data for AUTO mode currency formatting.
+
+ Executes a lightweight query to get distinct currency values using the
+ provided filters. Returns the currency code if all filtered data contains
+ a single currency, or None if multiple currencies are present.
+
+ This utility is used by both the modern QueryContext API and the legacy
+ viz API to provide consistent currency detection behavior.
+
+ :param datasource: The datasource to query
+ :param filters: List of filter dicts with 'col', 'op', 'val' keys
+ :param granularity: Optional time granularity column
+ :param from_dttm: Optional start datetime for time filtering
+ :param to_dttm: Optional end datetime for time filtering
+ :param extras: Optional extra query parameters (having, where clauses)
+ :return: ISO 4217 currency code (e.g., "USD", "EUR") or None
+ """
+ currency_column = getattr(datasource, "currency_code_column", None)
+ if not currency_column:
+ return None
+
+ datasource_id = getattr(datasource, "id", 0)
+
+ query_method = getattr(datasource, "query", None)
+ if not callable(query_method):
+ return None
+
+ try:
+ query_obj: QueryObjectDict = {
+ "granularity": granularity,
+ "from_dttm": from_dttm,
+ "to_dttm": to_dttm,
+ "is_timeseries": False,
+ "groupby": [currency_column],
+ "metrics": [],
+ "filter": filters or [],
+ "extras": extras or {},
+ }
+
+ result = query_method(query_obj)
+
+ if result.status != QueryStatus.SUCCESS or result.df.empty:
+ return None
+ if currency_column not in result.df.columns:
+ return None
+
+ unique_currencies = (
+ result.df[currency_column].dropna().astype(str).str.upper().unique()
+ )
+
+ if len(unique_currencies) == 1:
+ return str(unique_currencies[0])
+
+ return None
+
+ except Exception: # pylint: disable=broad-except
+ logger.warning(
+ "Failed to detect currency for datasource %s",
+ datasource_id,
+ exc_info=True,
+ )
+ return None
diff --git a/superset/views/core.py b/superset/views/core.py
index ced2078b14..cbe722cc92 100755
--- a/superset/views/core.py
+++ b/superset/views/core.py
@@ -168,17 +168,16 @@ class Superset(BaseSupersetView):
payload = viz_obj.get_df_payload()
if viz_obj.has_error(payload):
return json_error_response(payload=payload, status=400)
- return self.json_response(
- {
- "data": payload["df"].to_dict("records")
- if payload["df"] is not None
- else [],
- "colnames": payload.get("colnames"),
- "coltypes": payload.get("coltypes"),
- "rowcount": payload.get("rowcount"),
- "sql_rowcount": payload.get("sql_rowcount"),
- },
- )
+ response = {
+ "data": payload["df"].to_dict("records")
+ if payload["df"] is not None
+ else [],
+ "colnames": payload.get("colnames"),
+ "coltypes": payload.get("coltypes"),
+ "rowcount": payload.get("rowcount"),
+ "sql_rowcount": payload.get("sql_rowcount"),
+ }
+ return self.json_response(response)
def get_samples(self, viz_obj: BaseViz) -> FlaskResponse:
return self.json_response(viz_obj.get_samples())
diff --git a/superset/viz.py b/superset/viz.py
index b641009602..c6c7cf699b 100644
--- a/superset/viz.py
+++ b/superset/viz.py
@@ -514,6 +514,7 @@ class BaseViz: # pylint: disable=too-many-public-methods
] + rejected_time_columns
if df is not None:
payload["colnames"] = list(df.columns)
+
return payload
@deprecated(deprecated_in="3.0")
diff --git a/tests/integration_tests/datasets/commands_tests.py b/tests/integration_tests/datasets/commands_tests.py
index 92a0e37179..58f947034e 100644
--- a/tests/integration_tests/datasets/commands_tests.py
+++ b/tests/integration_tests/datasets/commands_tests.py
@@ -98,6 +98,7 @@ class TestExportDatasetsCommand(SupersetTestCase):
assert metadata == {
"cache_timeout": None,
"catalog": None,
+ "currency_code_column": None,
"columns": [
{
"column_name": "source",
@@ -229,6 +230,7 @@ class TestExportDatasetsCommand(SupersetTestCase):
assert list(metadata.keys()) == [
"table_name",
"main_dttm_col",
+ "currency_code_column",
"description",
"default_endpoint",
"offset",
@@ -370,6 +372,7 @@ class TestImportDatasetsCommand(SupersetTestCase):
)
assert dataset.table_name == "imported_dataset"
assert dataset.main_dttm_col is None
+ assert dataset.currency_code_column == "currency"
assert dataset.description == "This is a dataset that was exported"
assert dataset.default_endpoint == ""
assert dataset.offset == 66
diff --git a/tests/integration_tests/fixtures/importexport.py b/tests/integration_tests/fixtures/importexport.py
index 40f1cef9e2..0cd63526e8 100644
--- a/tests/integration_tests/fixtures/importexport.py
+++ b/tests/integration_tests/fixtures/importexport.py
@@ -509,6 +509,7 @@ database_with_ssh_tunnel_config_private_pass_only: dict[str, Any] = {
dataset_config: dict[str, Any] = {
"table_name": "imported_dataset",
"main_dttm_col": None,
+ "currency_code_column": "currency",
"description": "This is a dataset that was exported",
"default_endpoint": "",
"offset": 66,
diff --git a/tests/unit_tests/common/test_query_actions_currency.py b/tests/unit_tests/common/test_query_actions_currency.py
new file mode 100644
index 0000000000..50ec9619c8
--- /dev/null
+++ b/tests/unit_tests/common/test_query_actions_currency.py
@@ -0,0 +1,290 @@
+# 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.
+from unittest.mock import MagicMock, patch
+
+import pandas as pd
+import pytest
+
+from superset.common.query_actions import _detect_currency
+
+
+@pytest.fixture
+def mock_query_context() -> MagicMock:
+ """Create a mock QueryContext with AUTO currency format."""
+ context = MagicMock()
+ context.form_data = {"currency_format": {"symbol": "AUTO"}}
+ return context
+
+
+@pytest.fixture
+def mock_query_obj() -> MagicMock:
+ """Create a mock QueryObject with filter attributes."""
+ obj = MagicMock()
+ obj.filter = []
+ obj.granularity = None
+ obj.from_dttm = None
+ obj.to_dttm = None
+ obj.extras = {}
+ return obj
+
+
+@pytest.fixture
+def mock_datasource() -> MagicMock:
+ """Create a mock datasource with currency column."""
+ ds = MagicMock()
+ ds.currency_code_column = "currency_code"
+ return ds
+
+
+def test_detect_currency_returns_none_when_form_data_is_none(
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Returns None when query context has no form_data."""
+ context = MagicMock()
+ context.form_data = None
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_returns_none_when_currency_format_not_dict(
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Returns None when currency_format is not a dict."""
+ context = MagicMock()
+ context.form_data = {"currency_format": "invalid"}
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_returns_none_when_symbol_not_auto(
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Returns None when currency_format.symbol is not AUTO."""
+ context = MagicMock()
+ context.form_data = {"currency_format": {"symbol": "USD"}}
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_returns_none_when_no_currency_column(
+ mock_query_context: MagicMock,
+ mock_query_obj: MagicMock,
+) -> None:
+ """Returns None when datasource has no currency_code_column."""
+ datasource = MagicMock()
+ datasource.currency_code_column = None
+
+ result = _detect_currency(mock_query_context, mock_query_obj, datasource)
+
+ assert result is None
+
+
+@patch("superset.common.query_actions.detect_currency_from_df")
+def test_detect_currency_uses_dataframe_when_column_present(
+ mock_detect_from_df: MagicMock,
+ mock_query_context: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Uses detect_currency_from_df when df contains currency column."""
+ df = pd.DataFrame({"currency_code": ["USD", "USD"]})
+ mock_detect_from_df.return_value = "USD"
+
+ result = _detect_currency(mock_query_context, mock_query_obj, mock_datasource, df)
+
+ assert result == "USD"
+ mock_detect_from_df.assert_called_once_with(df, "currency_code")
+
+
+@patch("superset.common.query_actions.detect_currency")
+def test_detect_currency_queries_datasource_when_no_df(
+ mock_detect: MagicMock,
+ mock_query_context: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Queries datasource when df is None."""
+ mock_detect.return_value = "EUR"
+
+ result = _detect_currency(mock_query_context, mock_query_obj, mock_datasource)
+
+ assert result == "EUR"
+ mock_detect.assert_called_once_with(
+ datasource=mock_datasource,
+ filters=mock_query_obj.filter,
+ granularity=mock_query_obj.granularity,
+ from_dttm=mock_query_obj.from_dttm,
+ to_dttm=mock_query_obj.to_dttm,
+ extras=mock_query_obj.extras,
+ )
+
+
+@patch("superset.common.query_actions.detect_currency")
+def test_detect_currency_queries_datasource_when_column_not_in_df(
+ mock_detect: MagicMock,
+ mock_query_context: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Falls back to query when df doesn't have currency column."""
+ df = pd.DataFrame({"other_column": ["value"]})
+ mock_detect.return_value = "GBP"
+
+ result = _detect_currency(mock_query_context, mock_query_obj, mock_datasource, df)
+
+ assert result == "GBP"
+ mock_detect.assert_called_once()
+
+
+# Tests for column_config AUTO detection (Table charts)
+
+
+@pytest.fixture
+def mock_query_context_with_column_config() -> MagicMock:
+ """Create a mock QueryContext with column_config AUTO currency (Table charts)."""
+ context = MagicMock()
+ context.form_data = {
+ "column_config": {
+ "cost": {"currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"}}
+ }
+ }
+ return context
+
+
+@patch("superset.common.query_actions.detect_currency")
+def test_detect_currency_checks_column_config_for_auto(
+ mock_detect: MagicMock,
+ mock_query_context_with_column_config: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Runs detection when column_config has AUTO currency (Table charts)."""
+ mock_detect.return_value = "USD"
+
+ result = _detect_currency(
+ mock_query_context_with_column_config,
+ mock_query_obj,
+ mock_datasource,
+ )
+
+ assert result == "USD"
+ mock_detect.assert_called_once()
+
+
+@patch("superset.common.query_actions.detect_currency_from_df")
+def test_detect_currency_column_config_uses_dataframe(
+ mock_detect_from_df: MagicMock,
+ mock_query_context_with_column_config: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Uses dataframe detection when column_config has AUTO and df has currency."""
+ df = pd.DataFrame({"currency_code": ["EUR", "EUR"]})
+ mock_detect_from_df.return_value = "EUR"
+
+ result = _detect_currency(
+ mock_query_context_with_column_config,
+ mock_query_obj,
+ mock_datasource,
+ df,
+ )
+
+ assert result == "EUR"
+ mock_detect_from_df.assert_called_once_with(df, "currency_code")
+
+
+def test_detect_currency_skips_when_no_auto_in_column_config(
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Returns None when column_config has explicit currency (not AUTO)."""
+ context = MagicMock()
+ context.form_data = {
+ "column_config": {"cost": {"currencyFormat": {"symbol": "USD"}}}
+ }
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result is None
+
+
+@patch("superset.common.query_actions.detect_currency")
+def test_detect_currency_works_with_both_top_level_and_column_config(
+ mock_detect: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Detects when both top-level and column_config have AUTO."""
+ context = MagicMock()
+ context.form_data = {
+ "currency_format": {"symbol": "AUTO"},
+ "column_config": {"cost": {"currencyFormat": {"symbol": "AUTO"}}},
+ }
+ mock_detect.return_value = "JPY"
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result == "JPY"
+ mock_detect.assert_called_once()
+
+
+@patch("superset.common.query_actions.detect_currency")
+def test_detect_currency_top_level_auto_triggers_detection(
+ mock_detect: MagicMock,
+ mock_query_obj: MagicMock,
+ mock_datasource: MagicMock,
+) -> None:
+ """Detects when only top-level currency_format has AUTO."""
+ context = MagicMock()
+ context.form_data = {
+ "currency_format": {"symbol": "AUTO"},
+ "column_config": {
+ "cost": {"currencyFormat": {"symbol": "USD"}} # explicit, not AUTO
+ },
+ }
+ mock_detect.return_value = "CAD"
+
+ result = _detect_currency(context, mock_query_obj, mock_datasource)
+
+ assert result == "CAD"
+ mock_detect.assert_called_once()
+
+
+def test_detect_currency_column_config_no_currency_column_returns_none(
+ mock_query_context_with_column_config: MagicMock,
+ mock_query_obj: MagicMock,
+) -> None:
+ """Returns None when column_config has AUTO but datasource lacks currency column."""
+ datasource = MagicMock()
+ datasource.currency_code_column = None
+
+ result = _detect_currency(
+ mock_query_context_with_column_config,
+ mock_query_obj,
+ datasource,
+ )
+
+ assert result is None
diff --git a/tests/unit_tests/common/test_query_context_factory.py b/tests/unit_tests/common/test_query_context_factory.py
index c334ee3e42..37a7b47460 100644
--- a/tests/unit_tests/common/test_query_context_factory.py
+++ b/tests/unit_tests/common/test_query_context_factory.py
@@ -436,3 +436,109 @@ class TestQueryContextFactory:
self.factory._apply_filters(query_object)
assert query_object.filter[0]["val"] == "value"
+
+ def test_add_currency_column_no_form_data(self):
+ """Test _add_currency_column when form_data is None."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ datasource = Mock()
+
+ self.factory._add_currency_column(query_object, None, datasource)
+
+ assert query_object.columns == ["col1"]
+
+ def test_add_currency_column_no_columns(self):
+ """Test _add_currency_column when query_object has no columns."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = []
+ form_data = {
+ "viz_type": "pivot_table_v2",
+ "currency_format": {"symbol": "AUTO"},
+ }
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == []
+
+ def test_add_currency_column_unsupported_viz_type(self):
+ """Test _add_currency_column with unsupported viz type."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ form_data = {"viz_type": "pie", "currency_format": {"symbol": "AUTO"}}
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1"]
+
+ def test_add_currency_column_symbol_not_auto(self):
+ """Test _add_currency_column when symbol is not AUTO."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ form_data = {"viz_type": "pivot_table_v2", "currency_format": {"symbol": "USD"}}
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1"]
+
+ def test_add_currency_column_no_currency_column_on_datasource(self):
+ """Test _add_currency_column when datasource has no currency column."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ form_data = {
+ "viz_type": "pivot_table_v2",
+ "currency_format": {"symbol": "AUTO"},
+ }
+ datasource = Mock()
+ datasource.currency_code_column = None
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1"]
+
+ def test_add_currency_column_already_in_query(self):
+ """Test _add_currency_column when currency column already exists."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1", "currency_code"]
+ form_data = {
+ "viz_type": "pivot_table_v2",
+ "currency_format": {"symbol": "AUTO"},
+ }
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1", "currency_code"]
+
+ def test_add_currency_column_adds_column_for_pivot_table(self):
+ """Test _add_currency_column adds column for pivot_table_v2 viz type"""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ form_data = {
+ "viz_type": "pivot_table_v2",
+ "currency_format": {"symbol": "AUTO"},
+ }
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1", "currency_code"]
+
+ def test_add_currency_column_skips_table_viz_type(self):
+ """Test _add_currency_column does not add column for table viz type."""
+ query_object = Mock(spec=QueryObject)
+ query_object.columns = ["col1"]
+ form_data = {"viz_type": "table", "currency_format": {"symbol": "AUTO"}}
+ datasource = Mock()
+ datasource.currency_code_column = "currency_code"
+
+ self.factory._add_currency_column(query_object, form_data, datasource)
+
+ assert query_object.columns == ["col1"]
diff --git a/tests/unit_tests/connectors/sqla/models_test.py b/tests/unit_tests/connectors/sqla/models_test.py
index 437ddf9151..f3079ca356 100644
--- a/tests/unit_tests/connectors/sqla/models_test.py
+++ b/tests/unit_tests/connectors/sqla/models_test.py
@@ -842,3 +842,67 @@ def test_quoted_name_prevents_double_quoting(mocker: MockerFixture) -> None:
# Should have each part quoted separately:
# GOOD: "MY_DB"."MY_SCHEMA"."MY_TABLE"
assert '"MY_DB"."MY_SCHEMA"."MY_TABLE"' in compiled
+
+
+def test_sqla_table_currency_code_column_property() -> None:
+ """
+ Test currency_code_column property on SqlaTable.
+ """
+ database = Database(database_name="my_db")
+ table = SqlaTable(
+ table_name="sales",
+ database=database,
+ currency_code_column="currency",
+ )
+ assert table.currency_code_column == "currency"
+
+
+def test_sqla_table_data_includes_currency_code_column(mocker: MockerFixture) -> None:
+ """
+ Test that data property includes currency_code_column.
+ """
+ database = mocker.MagicMock()
+ database.get_sqla_engine.return_value.__enter__ = mocker.MagicMock()
+ database.get_sqla_engine.return_value.__exit__ = mocker.MagicMock()
+
+ table = SqlaTable(
+ table_name="sales",
+ database=database,
+ currency_code_column="currency_code",
+ main_dttm_col="ds",
+ )
+ table.columns = []
+ table.metrics = []
+
+ # Mock the columns property to return empty list
+ mocker.patch.object(SqlaTable, "columns", [])
+ mocker.patch.object(SqlaTable, "metrics", [])
+
+ data = table.data
+ assert data["currency_code_column"] == "currency_code"
+ assert data["main_dttm_col"] == "ds"
+
+
+def test_sqla_table_link_escapes_url(mocker: MockerFixture) -> None:
+ """
+ Test that link property properly escapes URL to prevent XSS.
+ """
+ database = Database(database_name="my_db")
+ table = SqlaTable(
+ table_name='test<script>alert("xss")</script>',
+ database=database,
+ id=1,
+ )
+
+ # Mock explore_url to return a URL with special characters
+ mocker.patch.object(
+ SqlaTable,
+ "explore_url",
+ new_callable=mocker.PropertyMock,
+ return_value='/explore/?datasource_type=table&datasource_id=1&name=<script>alert("xss")</script>',
+ )
+
+ link = table.link
+ # Verify that special characters are escaped in both name and URL
+ assert "<script>" in str(link)
+ assert "<script>" not in str(link)
diff --git a/tests/unit_tests/datasets/commands/export_test.py b/tests/unit_tests/datasets/commands/export_test.py
index 13b114c99a..d2bb3a66cc 100644
--- a/tests/unit_tests/datasets/commands/export_test.py
+++ b/tests/unit_tests/datasets/commands/export_test.py
@@ -155,6 +155,7 @@ def test_export(session: Session) -> None:
f"datasets/my_database/my_table_{sqla_table.id}.yaml",
f"""table_name: my_table
main_dttm_col: ds
+currency_code_column: null
description: This is the description
default_endpoint: null
offset: -8
diff --git a/tests/unit_tests/datasets/schema_tests.py b/tests/unit_tests/datasets/schema_tests.py
index 8aa327f77a..280a2440c2 100644
--- a/tests/unit_tests/datasets/schema_tests.py
+++ b/tests/unit_tests/datasets/schema_tests.py
@@ -46,3 +46,32 @@ def test_validate_python_date_format(payload) -> None:
def test_validate_python_date_format_raises(payload) -> None:
with pytest.raises(ValidationError):
validate_python_date_format(payload)
+
+
+def test_dataset_put_schema_includes_currency_code_column() -> None:
+ """Test that DatasetPutSchema properly handles currency_code_column field."""
+ from superset.datasets.schemas import DatasetPutSchema
+
+ schema = DatasetPutSchema()
+
+ # Dataset with currency code column
+ data = {
+ "currency_code_column": "currency",
+ }
+ result = schema.load(data)
+ assert result["currency_code_column"] == "currency"
+
+
+def test_dataset_put_schema_currency_code_column_optional() -> None:
+ """Test that currency_code_column is optional in DatasetPutSchema."""
+ from superset.datasets.schemas import DatasetPutSchema
+
+ schema = DatasetPutSchema()
+
+ # Dataset without currency code column (should not fail)
+ data: dict[str, str | None] = {}
+ result = schema.load(data)
+ assert (
+ "currency_code_column" not in result
+ or result.get("currency_code_column") is None
+ )
diff --git a/tests/unit_tests/utils/currency_test.py b/tests/unit_tests/utils/currency_test.py
new file mode 100644
index 0000000000..763f99220d
--- /dev/null
+++ b/tests/unit_tests/utils/currency_test.py
@@ -0,0 +1,332 @@
+# 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.
+from unittest.mock import MagicMock
+
+import pandas as pd
+import pytest
+
+from superset.common.db_query_status import QueryStatus
+from superset.utils.currency import (
+ detect_currency,
+ detect_currency_from_df,
+ has_auto_currency_in_column_config,
+)
+
+
+@pytest.fixture
+def mock_datasource() -> MagicMock:
+ """Create a mock datasource with currency_code_column configured."""
+ datasource = MagicMock()
+ datasource.currency_code_column = "currency_code"
+ datasource.id = 1
+ return datasource
+
+
+@pytest.fixture
+def mock_query_result() -> MagicMock:
+ """Create a mock query result."""
+ result = MagicMock()
+ result.status = QueryStatus.SUCCESS
+ return result
+
+
+def test_detect_currency_returns_none_when_no_currency_column() -> None:
+ """Returns None when datasource has no currency_code_column configured."""
+ datasource = MagicMock()
+ datasource.currency_code_column = None
+
+ result = detect_currency(datasource)
+
+ assert result is None
+ datasource.query.assert_not_called()
+
+
+def test_detect_currency_returns_single_currency(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Returns currency code when all filtered data contains single currency."""
+ mock_query_result.df = pd.DataFrame({"currency_code": ["USD", "USD", "USD"]})
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result == "USD"
+
+
+def test_detect_currency_returns_none_for_multiple_currencies(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Returns None when filtered data contains multiple currencies."""
+ mock_query_result.df = pd.DataFrame({"currency_code": ["USD", "EUR", "GBP"]})
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_returns_none_for_empty_dataframe(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Returns None when query returns empty dataframe."""
+ mock_query_result.df = pd.DataFrame()
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_returns_none_on_query_failure(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Returns None when query fails."""
+ mock_query_result.status = QueryStatus.FAILED
+ mock_query_result.df = pd.DataFrame()
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_handles_exception_gracefully(
+ mock_datasource: MagicMock,
+) -> None:
+ """Returns None and logs warning when exception occurs."""
+ mock_datasource.query.side_effect = Exception("Database error")
+
+ result = detect_currency(mock_datasource)
+
+ assert result is None
+
+
+def test_detect_currency_normalizes_to_uppercase(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Normalizes currency codes to uppercase."""
+ mock_query_result.df = pd.DataFrame({"currency_code": ["usd", "Usd", "USD"]})
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result == "USD"
+
+
+def test_detect_currency_ignores_null_values(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Ignores null currency values when detecting single currency."""
+ mock_query_result.df = pd.DataFrame({"currency_code": ["USD", None, "USD", None]})
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result == "USD"
+
+
+def test_detect_currency_returns_none_when_column_missing_from_result(
+ mock_datasource: MagicMock,
+ mock_query_result: MagicMock,
+) -> None:
+ """Returns None when currency column is missing from query result."""
+ mock_query_result.df = pd.DataFrame({"other_column": ["value"]})
+ mock_datasource.query.return_value = mock_query_result
+
+ result = detect_currency(mock_datasource)
+
+ assert result is None
+
+
+# Tests for detect_currency_from_df
+
+
+def test_detect_currency_from_df_returns_single_currency() -> None:
+ """Returns currency code when all data contains single currency."""
+ df = pd.DataFrame({"currency_code": ["USD", "USD", "USD"]})
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result == "USD"
+
+
+def test_detect_currency_from_df_returns_none_for_multiple_currencies() -> None:
+ """Returns None when data contains multiple currencies."""
+ df = pd.DataFrame({"currency_code": ["USD", "EUR", "GBP"]})
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result is None
+
+
+def test_detect_currency_from_df_returns_none_for_empty_dataframe() -> None:
+ """Returns None when dataframe is empty."""
+ df = pd.DataFrame()
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result is None
+
+
+def test_detect_currency_from_df_returns_none_for_none_dataframe() -> None:
+ """Returns None when dataframe is None."""
+ result = detect_currency_from_df(None, "currency_code")
+
+ assert result is None
+
+
+def test_detect_currency_from_df_returns_none_when_column_missing() -> None:
+ """Returns None when currency column is missing from dataframe."""
+ df = pd.DataFrame({"other_column": ["value"]})
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result is None
+
+
+def test_detect_currency_from_df_normalizes_to_uppercase() -> None:
+ """Normalizes currency codes to uppercase."""
+ df = pd.DataFrame({"currency_code": ["usd", "Usd", "USD"]})
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result == "USD"
+
+
+def test_detect_currency_from_df_ignores_null_values() -> None:
+ """Ignores null currency values when detecting single currency."""
+ df = pd.DataFrame({"currency_code": ["USD", None, "USD", None]})
+
+ result = detect_currency_from_df(df, "currency_code")
+
+ assert result == "USD"
+
+
+def test_detect_currency_returns_none_when_query_not_callable() -> None:
+ """Returns None when datasource query attribute is not callable."""
+ datasource = MagicMock()
+ datasource.currency_code_column = "currency_code"
+ datasource.query = "not_a_callable" # Set to a string instead of a method
+
+ result = detect_currency(datasource)
+
+ assert result is None
+
+
+# Tests for has_auto_currency_in_column_config
+
+
+def test_has_auto_currency_in_column_config_returns_true_when_auto() -> None:
+ """Returns True when column_config has AUTO currency."""
+ form_data = {
+ "column_config": {
+ "cost": {"currencyFormat": {"symbol": "AUTO", "symbolPosition": "prefix"}}
+ }
+ }
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is True
+
+
+def test_has_auto_currency_in_column_config_returns_true_multiple_columns() -> None:
+ """Returns True when any column in column_config has AUTO currency."""
+ form_data = {
+ "column_config": {
+ "revenue": {"currencyFormat": {"symbol": "USD"}},
+ "cost": {"currencyFormat": {"symbol": "AUTO"}},
+ "profit": {"d3NumberFormat": ",.0f"},
+ }
+ }
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is True
+
+
+def test_has_auto_currency_in_column_config_returns_false_for_explicit() -> None:
+ """Returns False when column_config has explicit currency symbol."""
+ form_data = {"column_config": {"cost": {"currencyFormat": {"symbol": "USD"}}}}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_returns_false_for_none() -> None:
+ """Returns False when form_data is None."""
+ result = has_auto_currency_in_column_config(None)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_returns_false_for_empty() -> None:
+ """Returns False when form_data is empty."""
+ result = has_auto_currency_in_column_config({})
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_returns_false_no_column_config() -> None:
+ """Returns False when column_config is not present."""
+ form_data = {"other_key": "value"}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_handles_invalid_column_config() -> None:
+ """Returns False when column_config is not a dict."""
+ form_data = {"column_config": "invalid"}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_handles_invalid_config_entry() -> None:
+ """Returns False when column config entry is not a dict."""
+ form_data = {"column_config": {"cost": "invalid"}}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_handles_invalid_currency_format() -> None:
+ """Returns False when currencyFormat is not a dict."""
+ form_data = {"column_config": {"cost": {"currencyFormat": "invalid"}}}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False
+
+
+def test_has_auto_currency_in_column_config_handles_no_currency_format() -> None:
+ """Returns False when column has no currencyFormat."""
+ form_data = {"column_config": {"cost": {"d3NumberFormat": ",.0f"}}}
+
+ result = has_auto_currency_in_column_config(form_data)
+
+ assert result is False