villebro commented on code in PR #24517:
URL: https://github.com/apache/superset/pull/24517#discussion_r1244022658


##########
superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.test.ts:
##########
@@ -0,0 +1,158 @@
+/*
+ * 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,
+  getCurrencySymbol,
+  NumberFormats,
+} from '@superset-ui/core';
+
+it('getCurrencySymbol', () => {
+  expect(
+    getCurrencySymbol({ symbol: 'PLN', symbolPosition: 'prefix' }),
+  ).toEqual('PLN');
+  expect(
+    getCurrencySymbol({ symbol: 'USD', symbolPosition: 'prefix' }),
+  ).toEqual('$');
+
+  expect(() =>
+    getCurrencySymbol({ symbol: 'INVALID_CODE', symbolPosition: 'prefix' }),
+  ).toThrow(RangeError);
+});
+
+it('CurrencyFormatter object fields', () => {
+  const defaultCurrencyFormatter = new CurrencyFormatter({
+    currency: { symbol: 'USD', symbolPosition: 'prefix' },
+  });
+  
expect(defaultCurrencyFormatter.d3Format).toEqual(NumberFormats.SMART_NUMBER);
+  expect(defaultCurrencyFormatter.locale).toEqual('en-US');
+  expect(defaultCurrencyFormatter.currency).toEqual({
+    symbol: 'USD',
+    symbolPosition: 'prefix',
+  });
+
+  const currencyFormatter = new CurrencyFormatter({
+    currency: { symbol: 'PLN', symbolPosition: 'suffix' },
+    locale: 'pl-PL',
+    d3Format: ',.1f',
+  });
+  expect(currencyFormatter.d3Format).toEqual(',.1f');
+  expect(currencyFormatter.locale).toEqual('pl-PL');
+  expect(currencyFormatter.currency).toEqual({
+    symbol: 'PLN',
+    symbolPosition: 'suffix',
+  });
+});
+
+it('CurrencyFormatter:hasValidCurrency', () => {
+  const currencyFormatter = new CurrencyFormatter({
+    currency: { symbol: 'USD', symbolPosition: 'prefix' },
+  });
+  expect(currencyFormatter.hasValidCurrency()).toBeTruthy();
+
+  const currencyFormatterWithoutPosition = new CurrencyFormatter({
+    // @ts-ignore
+    currency: { symbol: 'USD' },
+  });
+  expect(currencyFormatterWithoutPosition.hasValidCurrency()).toBeTruthy();

Review Comment:
   ...and if we made that change up there, this would be
   ```suggestion
     expect(currencyFormatterWithoutPosition.hasValidCurrency()).toBe(true);
   ```



##########
superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts:
##########
@@ -0,0 +1,79 @@
+/**
+ * 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 { ExtensibleFunction } from '../models';
+import { getNumberFormatter, NumberFormats } from '../number-format';
+import { Currency } from '../query';
+
+interface CurrencyFormatterConfig {
+  d3Format?: string;
+  currency: Currency;
+  locale?: string;
+}
+
+interface CurrencyFormatter {
+  (value: number | null | undefined): string;
+}
+
+export const getCurrencySymbol = (currency: Currency) =>
+  new Intl.NumberFormat('en-US', {
+    style: 'currency',
+    currency: currency.symbol,
+  })
+    .formatToParts(1)
+    .find(x => x.type === 'currency')?.value;
+
+class CurrencyFormatter extends ExtensibleFunction {
+  d3Format: string;
+
+  locale: string;
+
+  currency: Currency;
+
+  constructor(config: CurrencyFormatterConfig) {
+    super((value: number) => this.format(value));
+    this.d3Format = config.d3Format || NumberFormats.SMART_NUMBER;
+    this.currency = config.currency;
+    this.locale = config.locale || 'en-US';
+  }
+
+  hasValidCurrency() {
+    return this.currency?.symbol;
+  }

Review Comment:
   I'm going on about return types again 😆 To be precise, shouldn't this be
   ```ts
     hasValidCurrency(): boolean {
       return Boolean(this.currency?.symbol);
     }
   ```
   



##########
superset-frontend/plugins/plugin-chart-echarts/src/utils/buildCustomFormatters.ts:
##########
@@ -0,0 +1,96 @@
+import {
+  Currency,
+  CurrencyFormatter,
+  ensureIsArray,
+  getNumberFormatter,
+  isDefined,
+  isSavedMetric,
+  QueryFormMetric,
+  ValueFormatter,
+} from '@superset-ui/core';
+
+export const buildCustomFormatters = (
+  metrics: QueryFormMetric | QueryFormMetric[] | undefined,
+  currencyFormats: Record<string, Currency>,
+  columnFormats: Record<string, string>,
+  d3Format: string | undefined,
+  labelMap: Record<string, string[]> = {},
+  seriesNames: string[] = [],
+) => {
+  const metricsArray = ensureIsArray(metrics);
+  if (metricsArray.length === 1) {
+    const metric = metricsArray[0];
+    if (isSavedMetric(metric)) {
+      return {
+        [metric]: currencyFormats[metric]
+          ? new CurrencyFormatter({
+              d3Format: columnFormats[metric] ?? d3Format,
+              currency: currencyFormats[metric],
+            })
+          : getNumberFormatter(columnFormats[metric] ?? d3Format),
+      };
+    }
+    return {};
+  }
+  return seriesNames.reduce((acc, name) => {
+    if (!isDefined(name)) {
+      return acc;
+    }
+
+    const metricName = labelMap[name]?.[0];
+    const isSaved =
+      metricName &&
+      // string equality checks if it is a saved metric
+      metricsArray?.some(metric => metric === metricName);
+    const actualD3Format = isSaved
+      ? columnFormats[metricName] ?? d3Format
+      : d3Format;
+    if (isSaved && currencyFormats[metricName]) {
+      return {
+        ...acc,
+        [name]: new CurrencyFormatter({
+          d3Format: actualD3Format,
+          currency: currencyFormats[metricName],
+        }),
+      };
+    }
+    return {
+      ...acc,
+      [name]: getNumberFormatter(actualD3Format),
+    };
+  }, {});
+};
+
+export const getCustomFormatter = (
+  customFormatters: Record<string, ValueFormatter>,
+  metrics: QueryFormMetric | QueryFormMetric[] | undefined,
+  key?: string,
+) => {
+  const metricsArray = ensureIsArray(metrics);
+  if (metricsArray.length === 1 && isSavedMetric(metricsArray[0])) {
+    return customFormatters[metricsArray[0]];
+  }
+  return key ? customFormatters[key] : undefined;
+};
+
+export const getFormatter = (

Review Comment:
   For the sake of consistency, should this be `getValueFormatter`?



##########
superset-frontend/src/explore/actions/hydrateExplore.ts:
##########
@@ -96,6 +96,8 @@ export const hydrateExplore =
     if (dashboardId) {
       initialFormData.dashboardId = dashboardId;
     }
+
+    // const initialDatasource = dataset;

Review Comment:
   I assume this is redundant
   ```suggestion
   
       // const initialDatasource = dataset;
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to